# Commands in depth

> Synchronous, async and binary commands, their errors and how much data they carry.

A command is a named Rust handler the page calls with `window.kurogane.invoke`. See [IPC](https://kurogane-rs.org/docs/concepts/ipc.md) for how commands sit next to events and streams.

## Take and return your own types

The request is any type serde can read. The reply is any type serde can write:

```rust
use kurogane::{App, AppHandle, IpcError};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct Search {
    query: String,
    limit: usize,
}

#[derive(Serialize)]
struct Hit {
    title: String,
}

fn search(request: Search, _: &AppHandle) -> Result<Vec<Hit>, IpcError> {
    let hits = (0..request.limit)
        .map(|n| Hit { title: format!("{} #{n}", request.query) })
        .collect();
    Ok(hits)
}

fn main() {
    App::new("content").command("search", search).run_or_exit();
}
```

```javascript
const hits = await window.kurogane.invoke("search", { query: "notes", limit: 3 });
```

A call without a payload sends JSON `null`. A handler that takes `()` or an `Option` accepts it:

```rust
App::new("content")
    .command("version", |_: (), _: &AppHandle| Ok(env!("CARGO_PKG_VERSION")))
    .run_or_exit();
```

```javascript
const version = await window.kurogane.invoke("version");
```

A request the handler's type can't read rejects with code `-2` before the handler runs.

## Answer later

[`App::command`](https://kurogane-rs.org/docs/api/app/app.md#method.command) runs on the UI thread. That thread also runs every window and receives every message from every page. For slow work use [`App::async_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_command). Its handler gets a [`Responder`](https://kurogane-rs.org/docs/api/ipc/responder.md) and resolves it from any thread:

```rust
use kurogane::{App, AppHandle, Responder};

fn main() {
    App::new("content")
        .async_command("sum", |numbers: Vec<i64>, responder: Responder<i64>, _: &AppHandle| {
            std::thread::spawn(move || responder.resolve(Ok(numbers.iter().sum())));
        })
        .run_or_exit();
}
```

The handler itself still runs on the UI thread. Return from it promptly and do the work elsewhere.

* A request is answered once. `resolve` takes the responder.
* A responder dropped unanswered rejects the call with code `-3`. Every call settles.
* A responder of a cancelled call sends nothing.

## Cancel a call

The promise `invoke` returns has a `cancel()`. It rejects the promise with code `0` and marks an async handler's responder cancelled:

```javascript
const call = window.kurogane.invoke("sum", numbers);
cancelButton.onclick = () => call.cancel();
```

A page that navigates away or closes cancels its open calls too. Check [`Responder::is_cancelled`](https://kurogane-rs.org/docs/api/ipc/responder.md#method.is_cancelled) to stop work nobody waits for:

```rust
use kurogane::{App, AppHandle, Responder};

fn main() {
    App::new("content")
        .async_command("count", |to: u64, responder: Responder<u64>, _: &AppHandle| {
            std::thread::spawn(move || {
                let mut total = 0;
                for n in 0..to {
                    if responder.is_cancelled() {
                        return;
                    }
                    total += n;
                }
                responder.resolve(Ok(total));
            });
        })
        .run_or_exit();
}
```

A page back from the back-forward cache finds the calls it left open rejected with code `-9`.

## Send bytes

[`App::binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.binary_command) takes and returns raw bytes without JSON:

```rust
use kurogane::{App, AppHandle};

fn main() {
    App::new("content")
        .binary_command("checksum", |data: &[u8], _: &AppHandle| {
            let sum: u32 = data.iter().map(|&byte| u32::from(byte)).sum();
            Ok(sum.to_le_bytes().to_vec())
        })
        .run_or_exit();
}
```

The page sends an `ArrayBuffer` or a typed array and gets an `ArrayBuffer` back:

```javascript
const reply = await window.kurogane.invoke("checksum", new TextEncoder().encode("hello"));
const sum = new DataView(reply).getUint32(0, true);
```

[`App::async_binary_command`](https://kurogane-rs.org/docs/api/app/app.md#method.async_binary_command) is its async form. Its handler owns the bytes and gets a [`BinaryResponder`](https://kurogane-rs.org/docs/api/ipc/binaryresponder.md).

## Report errors

A handler fails with an [`IpcError`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md). A string converts into one. The page's promise rejects with an `Error` whose `code` says what failed and whose `message` is yours:

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

fn main() {
    App::new("content")
        .command("open", |path: String, _: &AppHandle| -> Result<String, IpcError> {
            std::fs::read_to_string(&path).map_err(|e| format!("can't open {path}: {e}").into())
        })
        .run_or_exit();
}
```

```javascript
try {
  const text = await window.kurogane.invoke("open", "notes.txt");
} catch (error) {
  console.log(error.code, error.message);
}
```

Send a code of your own with [`IpcError::with_code`](https://kurogane-rs.org/docs/api/ipc/ipcerror.md#method.with_code) and [`ErrorCode::App`](https://kurogane-rs.org/docs/api/ipc/errorcode.md#variant.App). Your codes are positive:

```rust
use std::num::NonZeroU16;

use kurogane::{ErrorCode, IpcError};

const NOT_FOUND: NonZeroU16 = NonZeroU16::new(404).unwrap();

fn not_found(what: &str) -> IpcError {
    IpcError::with_code(format!("{what} not found"), ErrorCode::App(NOT_FOUND))
}
```

Kurogane's own codes are zero or negative:

| Code | Meaning |
|---|---|
| `0` | the handler reported a failure, or the page cancelled |
| `-1` | the handler panicked |
| `-2` | the request or reply couldn't be decoded or encoded |
| `-3` | an async handler dropped its responder unanswered |
| `-4` | the page's origin may not call the command |
| `-5` | no filesystem grant of the origin covers the operation |
| `-6` | the path is outside the granted roots, denied or a link |
| `-7` | the path is malformed |
| `-8` | a file or message exceeds its transfer limit |
| `-9` | the page left with the call open and came back from the back-forward cache |

A handler that panics rejects the call with `-1`. Your app keeps running.

## Large data

One message from a page has a size cap. A call over it rejects with `-8` before anything is sent. Send larger data as a [stream](https://kurogane-rs.org/docs/concepts/ipc.md#streams) in chunks. The page stays responsive between chunks.

## Test a handler

A handler is a function. Call it directly in a test. An async handler's logic can take its `Responder` and leave the `AppHandle` out. [`Responder::new`](https://kurogane-rs.org/docs/api/ipc/responder.md#method.new) makes one that hands its result to a closure:

```rust
use std::sync::mpsc;

use kurogane::Responder;

fn sum(numbers: Vec<i64>, responder: Responder<i64>) {
    responder.resolve(Ok(numbers.iter().sum()));
}

#[test]
fn sums_the_numbers() {
    let (tx, rx) = mpsc::channel();
    sum(vec![1, 2, 3], Responder::new(Box::new(move |result| tx.send(result).unwrap())));
    assert_eq!(rx.recv().unwrap(), Ok(6));
}
```

Register it with `.async_command("sum", |numbers, responder, _| sum(numbers, responder))`.

## Rules for commands

* A name registered twice is a configuration error. [`App::build`](https://kurogane-rs.org/docs/api/app/app.md#method.build) reports it before anything starts.
* Only your app's own origin calls a command by default. [`App::permit`](https://kurogane-rs.org/docs/api/app/app.md#method.permit) opens one to other origins. See [Who may call](https://kurogane-rs.org/docs/concepts/ipc.md#who-may-call).
* Every handler runs on the UI thread. Async responders and binary responders work from any thread.
