# Streams

> Move chunks both ways between a page and a Rust handler until one side ends.

A stream carries chunks in both directions between one page and one [`StreamHandler`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md). Use one for data larger than a command carries, for progress as data arrives or for a long exchange that a single reply can't hold.

## Receive an upload

Register a factory with [`App::stream`](https://kurogane-rs.org/docs/api/app/app.md#method.stream). It makes a handler for each stream a page opens:

```rust
use kurogane::{App, IpcError, StreamHandler, StreamResponder};

struct Upload {
    received: usize,
}

impl StreamHandler for Upload {
    // Accept or refuse before the page holds the stream
    fn on_open(&mut self, metadata: &str) -> Result<(), IpcError> {
        if metadata.is_empty() {
            return Err("name the upload".into());
        }
        Ok(())
    }

    fn on_chunk(&mut self, data: &[u8], _: &StreamResponder) -> Result<(), IpcError> {
        self.received += data.len();
        Ok(())
    }

    fn on_end(&mut self, _: &str, responder: StreamResponder) -> Result<(), IpcError> {
        responder.end(&self.received.to_string())
    }
}

fn main() {
    App::new("content")
        .stream("upload", || Upload { received: 0 })
        .run_or_exit();
}
```

The page opens the stream, writes chunks and ends it:

```javascript
const stream = await window.kurogane.openStream("upload", "notes.txt");
stream.onEnd((result) => console.log(`${result} bytes received`));
stream.onError((message) => console.error(message));

const bytes = new Uint8Array(await file.arrayBuffer());
const chunk = 1 << 20;
for (let offset = 0; offset < bytes.length; offset += chunk) {
  stream.write(bytes.subarray(offset, offset + chunk));
}
stream.end();
```

## Send data to the page from a thread

[`StreamHandler::on_opened`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened) runs once the page holds the stream. Hand a clone of the [`StreamResponder`](https://kurogane-rs.org/docs/api/ipc/streamresponder.md) to a thread that produces the data:

```rust
use std::io::Read;

use kurogane::{App, IpcError, StreamHandler, StreamResponder};

struct Download;

impl StreamHandler for Download {
    fn on_opened(&mut self, responder: &StreamResponder) -> Result<(), IpcError> {
        let responder = responder.clone();
        std::thread::spawn(move || {
            let path = std::env::temp_dir().join("export.bin");
            let Ok(mut file) = std::fs::File::open(path) else {
                let _ = responder.error("no export yet");
                return;
            };
            let mut buffer = vec![0; 1 << 20];
            loop {
                match file.read(&mut buffer) {
                    Ok(0) => break,
                    Ok(n) => {
                        if responder.send_data(&buffer[..n]).is_err() {
                            // The page left or the stream closed
                            return;
                        }
                    }
                    Err(e) => {
                        let _ = responder.error(e.to_string());
                        return;
                    }
                }
            }
            let _ = responder.end("done");
        });
        Ok(())
    }

    fn on_chunk(&mut self, _: &[u8], _: &StreamResponder) -> Result<(), IpcError> {
        Err("this stream only sends".into())
    }
}

fn main() {
    App::new("content").stream("download", || Download).run_or_exit();
}
```

```javascript
const stream = await window.kurogane.openStream("download");
const parts = [];
stream.onData((buffer) => parts.push(buffer));
stream.onEnd(() => save(new Blob(parts)));
stream.onError((message) => console.error(message));
```

Chunks that arrive before `onData` is registered are kept and handed over when it is.

## A stream's life

1. [`on_open`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_open) accepts or refuses the stream. Nothing can be sent yet since the page doesn't hold the stream. An `Err` rejects the page's `openStream` with its message and code.
2. The page's `openStream` resolves. Then [`on_opened`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_opened) runs.
3. [`on_chunk`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#tymethod.on_chunk) runs for each chunk the page writes.
4. [`on_end`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_end) runs when the page ends the stream with its result. When it sends neither an end nor an error the runtime ends the stream with an empty result. The page always hears back.

[`on_error`](https://kurogane-rs.org/docs/api/ipc/streamhandler.md#method.on_error) runs when the page's side reports a failure. `on_chunk` is the one callback without a default.

The first `end` or `error` sent closes the stream, whichever clone of the responder sends it. Later sends fail with `stream closed`. An `Err` from `on_opened`, `on_chunk` or `on_end` fails the stream unless it's already closed. A panic in any callback counts as an `Err` with the message `handler panicked`.

The runtime drops the handler once the stream is closed.

## The page's side

`openStream(name, metadata)` resolves with a stream once the handler accepts it:

| Method | What it does |
|---|---|
| `onData(callback)` | receives each chunk as an `ArrayBuffer` |
| `onEnd(callback)` | receives the result the stream ended with, once |
| `onError(callback)` | receives the failure's message, once |
| `write(data)` | sends an `ArrayBuffer` or typed array to `on_chunk` |
| `end(result)` | ends the stream; `on_end` receives `result` |

A refused open rejects with an `Error` whose `code` is `0` when the handler refused it and `-4` when the page's origin may not open it. A chunk over the size cap makes `write` throw. It sends nothing and the stream stays open.

## Reach the app from a handler

[`App::stream_h`](https://kurogane-rs.org/docs/api/app/app.md#method.stream_h) gives the factory the [`AppHandle`](https://kurogane-rs.org/docs/api/app/apphandle.md) too. Keep a clone in the handler to send events or query what is open:

```rust
use kurogane::{App, AppHandle, IpcError, StreamHandler, StreamResponder};

struct Logged {
    app: AppHandle,
}

impl StreamHandler for Logged {
    fn on_chunk(&mut self, data: &[u8], _: &StreamResponder) -> Result<(), IpcError> {
        self.app.broadcast_json("received", &data.len());
        Ok(())
    }

    fn on_end(&mut self, _: &str, _: StreamResponder) -> Result<(), IpcError> {
        Ok(())
    }
}

fn main() {
    App::new("content")
        .stream_h("logged", |app| Logged { app: app.clone() })
        .run_or_exit();
}
```

## Rules for streams

* The factory and every callback run on the UI thread. Return promptly. A `StreamResponder` works from any thread.
* Streams follow the same access rule as commands. [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) opens one to other origins.
* A responder's sends fail once its page's document goes, when the frame navigates or closes.
* A page back from the back-forward cache finds the streams it left open failed with `The page left`.
* A name registered twice is a configuration error.
