Do a chart's I/O in your own code

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.

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.

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:

quote.mjsjavascript
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();
output
urn:example:prices: lookup tea for session 1
tea costs 4 EUR (answer to ask-1)
  • A class instanceserves as well as a literal: receive is called as its method, so this is the processor.
  • locationis optional, and is what the chart reads in _ioprocessors[type].location.
  • A type no processor servesgives the sending chart error.execution.
  • A plain functionin place of the object is a TypeError at new Host, naming its type.

Read what the chart sent

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

FieldWhat it holds
hostthe host the send came from
sessionthe sender's session, a bigint
senderthe sender, an Actor
eventthe 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}`
datathe <param>s as an object, or the <content>'s value
typethe processor's type
originthe sender's address, an Address
traceparentthe sending step's trace as W3C text, undefined when untraced (Telemetry)
messagethe outgoing half, for a transport (Other systems)

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

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.
  • Neithersuits 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). They and the answer's origin and raw follow the wire format.

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:

mailer.mjsjavascript
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();
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().

  • trueis what answer() and fail() return when the sender gets the event.
  • falsemeans the sender ended meanwhile, and nothing was delivered.
  • An exceptionis any other refusal: a second answer or a closed host (TA_ERROR_STATE), or data outside the value table, such as a function.

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:

login.mjsjavascript
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();
output
200 /home
401 logged out

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:

flaky.mjsjavascript
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();
output
the chart got error.communication for g1
idle() rejected: connection refused

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.

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:

spawner.mjsjavascript
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();
output
room about tea got hello
1 room

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). It handles one request at a time and records each, so it never asks twice for a name.

The chat-rooms example'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.

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). 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:

names.mjsjavascript
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();
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).