<!-- https://tinyactors.dev/guides/io-processors/ -->
# I/O processors

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Charts send events to I/O processors, objects of your own that do the I/O and send the answers back as events.

A chart asks for outside work by sending an event. An I/O processor in your code does the work and answers with another event, at once or later.

<a id="charts-send-events"></a>

## Ask for outside work with a send

A chart that needs the network, a file or a database sends an event with `<send type>`. The type names an I/O processor, an object in your program.

The processor does the work and sends any answer back as an event. The chart decides when to ask and what an answer changes.

<a id="declaring-a-processor"></a>

## Register a processor for each type

List your processors in the host's `ioProcessors` option, each under a type: any URI you choose. The host calls a processor's `receive(send)` for each send to its type.

To look up a price held in your program, this chart sends to a registered processor:

```javascript title="quote.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'quote.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="quote" initial="asking">
  <state id="asking">
    <onentry>
      <send type="urn:example:prices" event="lookup" target="tea" id="ask-1">
        <param name="currency" expr="'EUR'"/>
      </send>
    </onentry>
    <transition event="price" target="known">
      <log expr="'tea costs ' + _event.data.amount + ' ' + _event.data.currency + ' (answer to ' + _event.sendid + ')'"/>
    </transition>
  </state>
  <final id="known"/>
</scxml>` }]);

const prices = { tea: 4 };
const host = new Host(compiled, {
  system: 'shop',
  ioProcessors: {
    'urn:example:prices': {
      receive(send) {
        console.log(`${send.type}: ${send.event} ${send.target} for session ${send.session}`);
        send.answer('price', { amount: prices[send.target], currency: send.data.currency });
      },
    },
  },
  log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('quote');
await host.idle();
host.close();
```

```text title="output"
urn:example:prices: lookup tea for session 1
tea costs 4 EUR (answer to ask-1)
```

- **A class instance**: serves as well as a literal: `receive` is called as its method, so `this` is the processor.
- **`location`**: is optional, and is what the chart reads in `_ioprocessors[type].location`.
- **A type no processor serves**: gives the sending chart `error.execution`.
- **A plain function**: in place of the object is a `TypeError` at `new Host`, naming its type.

<a id="the-send"></a>

## Read what the chart sent

The `send` that `receive` gets holds the attributes of one `<send>` and its sender, each read on first access.

| Field | What it holds |
|---|---|
| `host` | the host the send came from |
| `session` | the sender's session, a `bigint` |
| `sender` | the sender, an `Actor` |
| `event` | the event's name (`<send event>`) |
| `target` | `<send target>` as a string, `undefined` when it has none |
| `sendid` | `<send id>`, or the id the host generated; `undefined` when it has none. A generated id is unique in the sender's session only (each session's first is `send.1`), so key what you keep by both: `` `${send.session}:${send.sendid}` `` |
| `data` | the `<param>`s as an object, or the `<content>`'s value |
| `type` | the processor's type |
| `origin` | the sender's address, an `Address` |
| `traceparent` | the sending step's trace as W3C text, `undefined` when untraced ([Telemetry](https://tinyactors.dev/guides/telemetry/index.md)) |
| `message` | the outgoing half, for a transport ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)) |

Copy what you keep for later. The send is valid while the handler runs, and a read after it returned throws `TA_ERROR_STALE`.

<a id="answer-or-fail"></a>

## Answer the sender, or fail the request

Your `receive` answers a send, fails it or does neither. Above, `send.answer('price', …)` sends the event `price` back to the actor, whose transition on `price` reads `_event.data` and `_event.sendid`.

- **`send.answer(event, data, options)`**: Sends `event` back to the sender, with this send's `sendid` as its `_event.sendid`. The options are `traceparent` (the answer continues the send's trace unless you give another, or `null` for a new one), `origin` (the answer's `_event.origin`) and `raw` (the message as you read it, for a chart that wants it).
- **`send.fail()`**: Gives the sender `error.communication` with this send's `sendid`, for a request that could not be done.
- **Neither**: suits a notification, or a chart that waits for a timeout of its own.

A second answer, or an answer after `fail()`, throws `TA_ERROR_STATE`.

A processor that carries sends out of the process, or speaks SCXML's BasicHTTP, uses the fields `origin` and `message` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)). They and the answer's `origin` and `raw` follow the [wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format).

<a id="answering-later"></a>

## Return a promise to answer later

When `receive` returns a promise, the host copies every field of its send first. Its `answer()` and `fail()` then work whenever the promise gets there, while the host is open.

The actor handles its other events meanwhile, and the answer reaches it as one more event. This processor awaits a stand-in for an SMTP client, then answers `delivered`:

```javascript title="mailer.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'mailer.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="mailer" initial="sending">
  <state id="sending">
    <onentry>
      <send type="urn:example:mail" event="deliver" target="ada@example.com"><content expr="'hello'"/></send>
      <send event="timeout" delay="5s"/>
    </onentry>
    <transition event="delivered" target="sent"><log expr="'delivered after ' + _event.data.ms + ' ms'"/></transition>
    <transition event="error.communication" target="failed"/>
    <transition event="timeout" target="failed"/>
  </state>
  <final id="sent"/>
  <final id="failed"><onentry><log expr="'not delivered'"/></onentry></final>
</scxml>` }]);

// A stand-in for an SMTP client.
const deliver = (to, body) => new Promise((resolve) => setTimeout(() => resolve(20), 20));

const host = new Host(compiled, {
  system: 'demo',
  ioProcessors: {
    'urn:example:mail': {
      async receive(send) {
        try {
          const ms = await deliver(send.target, send.data); // send is still readable here
          send.answer('delivered', { ms });
        } catch {
          send.fail();
        }
      },
    },
  },
  log: (entry) => console.log(entry.text),
});
compiled.close();

host.spawn('mailer');
await host.idle();
host.close();
```

```text title="output"
delivered after 20 ms
```

`await host.idle()` waits for the promise the handler returned, so it resolves after the answer. It waits only for a promise the handler returns, never for one it starts and drops.

The pending `timeout` keeps the process alive until `host.close()`.

- **`true`**: is what `answer()` and `fail()` return when the sender gets the event.
- **`false`**: means the sender ended meanwhile, and nothing was delivered.
- **An exception**: is any other refusal: a second answer or a closed host (`TA_ERROR_STATE`), or data outside the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values), such as a function.

<a id="when-the-sender-ends"></a>

## Settle open requests when an actor ends

An actor that reaches a top-level `<final>` ends at once, and SCXML drops the events still in its queue. A request sent with `actor.send` behind the event that ends it reaches no handler.

Have the `<final>`'s `<onentry>` send to your processor, and settle there what you still hold for that session.

Here each request waits for the actor's `response`. The one sent behind `logout` gets `401 logged out` from the `closed` handler:

```javascript title="login.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'login.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="login" initial="in">
  <state id="in">
    <transition event="request"><send type="urn:example:http" event="response"><content expr="'200 ' + _event.data"/></send></transition>
    <transition event="logout" target="out"/>
  </state>
  <final id="out"><onentry><send type="urn:example:http" event="closed"/></onentry></final>
</scxml>` }]);

const pending = new Map(); // String(session) -> the resolvers of its requests, in order
const host = new Host(compiled, {
  system: 'web',
  ioProcessors: {
    'urn:example:http': {
      receive(send) {
        const waiting = pending.get(String(send.session)) ?? [];
        if (send.event === 'response') waiting.shift()?.(send.data);
        if (send.event === 'closed') {
          for (const resolve of waiting.splice(0)) resolve('401 logged out');
          pending.delete(String(send.session));
        }
      },
    },
  },
});
compiled.close();

/** Sends `path` to the actor; resolves with its answer. */
const request = (actor, path) => new Promise((resolve) => {
  const key = String(actor.id);
  pending.set(key, [...(pending.get(key) ?? []), resolve]);
  actor.send('request', path);
});

const login = host.spawn('login');
const first = request(login, '/home');
login.send('logout');
const second = request(login, '/account'); // queued behind the logout: dropped
console.log(await first);
console.log(await second);
host.close();
```

```text title="output"
200 /home
401 logged out
```

<a id="when-a-handler-fails"></a>

## Catch what a processor throws

A handler that throws, or whose promise rejects, before it answers fails its send: the sender gets `error.communication`. After an answer, the answer stands.

Either way the host reports the error at the end of that event-loop turn, to the first of these:

1. the host's `onHandlerError(error, effect)`, when it has one, with the send as `effect`;
2. a waiting `host.idle()`, which rejects with it;
3. the runtime, as an uncaught exception, or as an unhandled rejection for a promise that rejected.

This processor always throws. The chart handles `error.communication`, then `idle()` rejects with the error:

```javascript title="flaky.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="c" initial="s">
  <state id="s">
    <onentry><send type="urn:example:flaky" event="go" id="g1"/></onentry>
    <transition event="error.communication"><log expr="'the chart got error.communication for ' + _event.sendid"/></transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, {
  system: 'demo',
  ioProcessors: { 'urn:example:flaky': { receive() { throw new Error('connection refused'); } } },
  log: (entry) => console.log(entry.text),
});
compiled.close();

host.spawn('c');
await host.idle().catch((error) => console.log('idle() rejected:', error.message));
await host.idle();
host.close();
```

```text title="output"
the chart got error.communication for g1
idle() rejected: connection refused
```

<a id="inputs-from-a-handler"></a>

## Send to other actors from a processor

Through `send.host` a handler can send an event to any actor, spawn one or terminate one. `send.sender.send(...)` sends a new event to the sender.

Each call applies at once, and the actors it reaches run after the handler returns.

<a id="spawning-from-a-chart"></a>

## Let a chart start lasting actors

`<invoke>` looks like the way, but it stops its child when the state is left. The package's `Spawner` is a processor that starts an actor which stays.

Register it under a type you choose, and a chart sends it `{ chart, name, params }`. The host spawns the chart's current version under the name.

The sender gets `spawned` with `{ name, address }` and the send's `sendid`, and sends to the `address` from then on. An unknown chart, or data of another shape, gives it `error.communication`.

Here a lobby spawns a room about tea and says hello at its address:

```javascript title="spawner.mjs"
import { compileCharts, Host, Spawner } from '@tinyactors/node';

const compiled = compileCharts([
  { name: 'lobby.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="lobby" initial="s">
    <state id="s">
      <onentry>
        <send type="spawn" event="spawn">
          <param name="chart" expr="'room'"/>
          <param name="params" expr="({ topic: 'tea' })"/>
        </send>
      </onentry>
      <transition event="spawned"><send event="hello" targetexpr="_event.data.address"/></transition>
    </state>
  </scxml>` },
  { name: 'room.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="room" initial="s">
    <datamodel><data id="topic"/></datamodel>
    <state id="s"><transition event="hello"><log expr="'room about ' + topic + ' got hello'"/></transition></state>
  </scxml>` },
]);
const host = new Host(compiled, {
  system: 'demo',
  ioProcessors: { spawn: new Spawner() },
  log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('lobby');
await host.idle();
console.log((await host.actors({ chart: 'room' })).length, 'room');
host.close();
```

```text title="output"
room about tea got hello
1 room
```

<a id="one-owner-per-name"></a>

## Give each name one owner

The `Spawner` spawns each time it is asked, without looking the name up first. So let one collection actor decide which actors of a kind exist, and spawn only from it.

A workspace spawns its rooms, for one ([the application routes it](https://tinyactors.dev/guides/missing-actors/index.md#the-application-routes-it)). It handles one request at a time and records each, so it never asks twice for a name.

The [chat-rooms example](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/examples/chat-rooms/README.md)'s workspace keeps a `creating` table keyed by the spawn's `sendid`. An entry stays until `spawned` or `error.communication` answers it.

Two actors spawning one name is a design error in the application. Within one version the oldest holder keeps the name, and a newer version's holder wins.

That rule is `ta_host_actor_by_name`'s, in [the core's host.h](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/include/tinyactors/host.h).

<a id="updating-through-names"></a>

## Deploy a new version of a named actor

To deploy, compile the new chart and pass its `image` to `host.addImage`. New actors start in the newest version, and running ones stay on theirs until they end or you migrate them.

The versions need not be compatible ([versions and segments](https://tinyactors.dev/guides/migration/index.md#versions-and-segments)). For a named actor, its owner then spawns the new version under the same name.

Names are looked up newest version first, so the name finds the new actor: `@room.acme.general`, `host.actor('room.acme.general')`. The old actor runs its version at its session address until it ends.

Here the lobby opens room version 1, the deploy adds version 2, and the old room still answers at its address:

```javascript title="names.mjs"
import { compileCharts, Host, Spawner } from '@tinyactors/node';

const room = (version) => `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
    datamodel="ecmascript" name="room" initial="s">
  <state id="s"><transition event="hello"><log expr="_name + ' runs version ${version}'"/></transition></state>
</scxml>`;
const image = (documents) => {
  const compiled = compileCharts(documents);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};
const host = new Host(image([
  { name: 'lobby.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="lobby" initial="s">
    <state id="s">
      <transition event="open">
        <send type="spawn" event="spawn">
          <param name="chart" expr="'room'"/>
          <param name="name" expr="'room.acme.general'"/>
        </send>
      </transition>
      <transition event="spawned"><send event="hello" targetexpr="_event.data.address"/></transition>
    </state>
  </scxml>` },
  { name: 'room.scxml', text: room(1) },
]), { system: 'demo', ioProcessors: { spawn: new Spawner() }, log: (entry) => console.log(entry.text) });
const lobby = host.spawn('lobby');                    // the room's one owner
lobby.send('open');
await host.idle();
const old = host.actor('room.acme.general');
host.addImage(image([{ name: 'room.scxml', text: room(2) }]));   // the deploy
lobby.send('open');                                   // version 2 starts under the name
await host.idle();
old.send('hello');                                    // the old room, at its session address
await host.idle();
host.close();
```

```text title="output"
room.acme.general runs version 1
room.acme.general runs version 2
room.acme.general runs version 1
```

A long-lived actor such as a workspace should change before it ends. Move it with `host.migrate({ chart: 'workspace' })` ([Migration](https://tinyactors.dev/guides/migration/index.md)).
