<!-- https://tinyactors.dev/guides/services/ -->
# Invoked services

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

> Run a connection, a subprocess or a long computation for as long as a chart's state is active, with SCXML's invoke.

A chart's `<invoke>` starts a connection or a subprocess in your program when the chart enters a state, and stops it when the chart leaves. 200,000 actors with one each made a million round trips in 18 to 23 seconds.

<a id="invoke"></a>

## Choose invoke for work that outlives a request

An I/O processor answers one send at a time, while a connection or a subscription lives longer. SCXML's `<invoke>` starts it on entering a state and stops it on leaving.

While the state is active, the chart and what it invoked exchange events. When your program runs it, it is a service, the subject of this guide.

An invoked chart runs instead as a child actor of the host ([A chart that starts another](https://tinyactors.dev/guides/charts/index.md#a-chart-that-starts-another)).

<a id="a-service"></a>

## Start a service when the state is entered

Register a handler per `<invoke type>` in the host's `services: { [type]: handler }`. At each start the handler gets an invocation and returns the service, any object.

The host keeps the service until the invocation ends, and calls two methods on it if it has them:

- **`receive(send)`**: gets each `<send target="#_<invokeid>">` of the invoker, and each event it forwards with `autoforward="true"`;
- **`stop()`**: runs when the invoker leaves the state, which cancels the invocation.

The service answers through the invocation. `invocation.sendBack(event, data)` sends the invoker an event whose `_event.invokeid` is the invoke's id.

`invocation.done(data)` ends the service and gives the invoker `done.invoke.<invokeid>` with `data`.

This counter starts from the invoke's `start` param, 10, answers each `ping` with `pong`, and ends on `finish` with its total:

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

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="player" initial="playing">
  <state id="playing">
    <invoke id="counter" type="urn:example:counter" src="counter://local">
      <param name="start" expr="10"/>
    </invoke>
    <transition event="go"><send target="#_counter" event="ping"/></transition>
    <transition event="finish"><send target="#_counter" event="finish"/></transition>
    <transition event="pong"><log expr="'pong ' + _event.data.n + ' from ' + _event.invokeid"/></transition>
    <transition event="done.invoke.counter" target="finished">
      <log expr="'done, total ' + _event.data.total"/>
    </transition>
  </state>
  <final id="finished"/>
</scxml>`;

class Counter {
  constructor(invocation) {
    this.invocation = invocation;
    this.count = invocation.data.start;
    console.log(`started ${invocation.type} ${invocation.src} for session ${invocation.session}`);
  }
  receive(send) {
    this.count++;
    if (send.event === 'finish') this.invocation.done({ total: this.count });
    else this.invocation.sendBack('pong', { n: this.count });
  }
  stop() {
    console.log('stopped');
  }
}

const compiled = compileCharts([{ name: 'player.scxml', text: chart }]);
const host = new Host(compiled, {
  system: 'demo',
  services: { 'urn:example:counter': (invocation) => new Counter(invocation) },
  log: (entry) => console.log(entry.text),
});
compiled.close();

const player = host.spawn('player');
player.send('go');
player.send('go');
player.send('finish');
await host.idle();
host.close();
```

```text title="output"
started urn:example:counter counter://local for session 1
pong 11 from counter
pong 12 from counter
done, total 13
```

`stop` runs only for a cancel: the counter ended with `done`, so the output has no `stopped`.

<a id="when-it-starts"></a>

## Send to a service from a later event

A service starts after the step that entered its state, raised and eventless transitions included, as a child chart does.

A `<send target="#_counter">` from that step, such as the state's own `<onentry>`, gets `error.communication`. Send from a later event, as `go` does above.

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

## Answer from a timer or a promise

The invocation stays valid after the start: a service may keep it and call `sendBack` from a timer or a promise. It carries the invoker and the invoke:

- **`host`**: the host that started it;
- **`session`**: the invoker, a `bigint`;
- **`invokeid`, `type`, `src`**: the invoke's attributes;
- **`data`**: the `<param>`s as an object, or the `<content>`;
- **`traceparent`**: the invoke's trace;
- **`running`**: false once the invocation ended;
- **`restored`**: true when a restored host starts it again ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).

`sendBack` and `done` continue the invoke's trace unless their last argument is `{ traceparent }`. A `null` traceparent starts a new trace.

After `done`, a cancel or `host.close()`, `sendBack` and `done` throw a `TinyactorsError` with `TA_ERROR_STALE`.

Read the send `receive` gets during the call, as an I/O processor's. A `receive` that returns a promise has its send filled first, so it may read it after an `await`.

<a id="a-service-that-starts-asynchronously"></a>

## Queue sends until the service connects

A handler may return a promise of the service, while a connection opens or a process spawns. Until it settles the sends wait, and reach `receive` in order once it resolves.

This handler reports `connecting` with `sendBack` while it waits. Both queries reach the service once the connection opens:

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

// A stand-in for a client library: a connection that opens after 20 ms.
const connect = (url) => new Promise((resolve) => setTimeout(() => resolve({
  ask: async (question) => `${url} says yes to ${question}`,
}), 20));

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="client" initial="connected">
  <state id="connected">
    <invoke id="db" type="urn:example:db" src="db://primary"/>
    <transition event="query"><send target="#_db" event="query"><content expr="_event.data"/></send></transition>
    <transition event="status"><log expr="'status ' + _event.data"/></transition>
    <transition event="answer"><log expr="_event.data"/></transition>
  </state>
</scxml>`;

const compiled = compileCharts([{ name: 'client.scxml', text: chart }]);
const host = new Host(compiled, {
  system: 'demo',
  services: {
    'urn:example:db': async (invocation) => {
      invocation.sendBack('status', 'connecting');
      const connection = await connect(invocation.src);
      return {
        async receive(send) {
          invocation.sendBack('answer', await connection.ask(send.data));
        },
      };
    },
  },
  log: (entry) => console.log(entry.text),
});
compiled.close();

const client = host.spawn('client');
client.send('query', 'first');  // both reach the service once it is connected
client.send('query', 'second');
await new Promise((resolve) => setTimeout(resolve, 100));
await host.idle();
host.close();
```

```text title="output"
status connecting
db://primary says yes to first
db://primary says yes to second
```

- **A cancel before the promise settles**: stops the service as soon as it resolves. The sends that waited are dropped, since the invoker has left and nothing could answer them.
- **A rejection**: is a failed start: the invoker gets `error.communication`, once and once more for each send that waited. The rejection stays unhandled, as any handler's promise's does ([Before you use it](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#before-you-use-it)).
- **After `host.close()`**: a promise that settles is ignored.

<a id="return-at-once"></a>

## Accept sends before the connection is ready

A service returned at once takes sends before it is ready, and decides itself what a send does while it connects.

This one starts connecting in its constructor, and each `receive` awaits that start before it asks:

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

const connect = (url) => new Promise((resolve) => setTimeout(() => resolve({
  ask: async (question) => `${url} answers ${question}`,
}), 20));

class Connection {
  constructor(invocation) {
    this.invocation = invocation;
    this.ready = connect(invocation.src); // a promise, started now
    this.ready.catch(() => {});           // its failure is answered in receive
  }
  async receive(send) {             // send was filled before the host moved on
    const connection = await this.ready;
    this.invocation.sendBack('answer', await connection.ask(send.data));
  }
}

const compiled = compileCharts([{ name: 'client.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="client" initial="s">
  <state id="s">
    <invoke id="db" type="urn:example:db" src="db://replica"/>
    <transition event="query"><send target="#_db" event="query"><content expr="_event.data"/></send></transition>
    <transition event="answer"><log expr="_event.data"/></transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, {
  system: 'demo',
  services: { 'urn:example:db': (invocation) => new Connection(invocation) },
  log: (entry) => console.log(entry.text),
});
compiled.close();

host.spawn('client').send('query', 'ping');
await new Promise((resolve) => setTimeout(resolve, 100));
await host.idle();
host.close();
```

```text title="output"
db://replica answers ping
```

`await host.idle()` waits for the promises your handlers return, a service handler's or a `receive`'s. A promise a service starts on its own is yours to wait for.

Both examples open the connection in the background, so they wait on a timer before `idle()`.

<a id="failures"></a>

## Handle a service that fails

Each of these gives the invoker `error.communication`, and so does each later send until the invoker leaves the state:

- no handler for the type, or none for a restored invocation;
- a handler that throws or whose promise rejects;
- a `receive` that throws or whose promise rejects: the service crashed, and is dropped without `stop`.

The invoker gets none when it cancelled the invocation in the same step that started it.

A handler's error is reported at the end of that event-loop turn, to `onHandlerError(error, invocation)` or out of `idle()`.

A type with no handler throws nothing, since the chart chose it. An untrusted chart on quickjs cannot end your process by naming a type you do not serve.

Here the handler throws: `idle()` rejects with its error, then the chart handles `error.communication`.

```javascript title="mail.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">
    <invoke id="mail" type="urn:example:mail" src="smtp://localhost"/>
    <transition event="error.communication"><log expr="'the mail service failed'"/></transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, {
  system: 'demo',
  services: { 'urn:example:mail': () => { throw new Error('no SMTP server'); } },
  log: (entry) => console.log(entry.text),
});
compiled.close();

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

```text title="output"
idle() rejected: no SMTP server
the mail service failed
```

<a id="closing"></a>

## Close a host with services running

`host.close()` drops the running services and calls no `stop`. The host keeps them on its own object, so a dropped host whose services refer back to it is still collected.

<a id="at-scale"></a>

## Run 200,000 services in one host

[`tools/services.mjs`](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/tools/services.mjs) runs actors that each invoke a counter service, and sends pings and pongs to actors drawn at random. Then a third finish with done data, a third are cancelled, and the rest keep theirs.

It checks that every pong is counted once and every done datum is right. Every cancelled service must be stopped exactly once, no other stopped, and the ended services collected.

| runtime, datamodel | start 200,000 invocations | 1,000,000 round trips | end (done, cancel) | peak resident | core's region |
|---|---|---|---|---|---|
| node, native | 4.4 s (45,000 a second) | 23.0 s (43,000 a second) | 1.8 s | 516 MB (2578 B per actor and service) | 54.6 MB (273 B per actor) |
| node, quickjs | 3.7 s (54,000 a second) | 22.3 s (45,000 a second) | 2.1 s | 712 MB (3560 B per actor and service) | 66.1 MB (330 B per actor) |
| bun, native | 3.5 s (57,000 a second) | 19.0 s (53,000 a second) | 1.6 s | 767 MB (3834 B per actor and service) | 54.6 MB (273 B per actor) |
| bun, quickjs | 2.7 s (73,000 a second) | 18.2 s (55,000 a second) | 1.8 s | 807 MB (4036 B per actor and service) | 66.1 MB (330 B per actor) |

200,000 actors, each with a counter service, making 1,000,000 round trips (actor, service, actor); then a third finished and a third cancelled. Every check passed, and the host held only the 66,666 services still running. One run, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.

A round trip costs about what it costs with 10,000 actors: a run's work stays the same as invocations add up.

Each invocation takes one of the host's requests. `system.maxRequests` sets where the pool starts, and a segment grows it when it runs out ([Capacity and memory](https://tinyactors.dev/guides/capacity/index.md)).

In the repository, `mise run services` runs the program.
