<!-- https://tinyactors.dev/guides/missing-actors/ -->
# When the actor is not there

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> A send to a hibernated actor wakes it, and a send to no actor fails at once. Choose, for each kind of actor, how your application avoids or handles the failure.

A send to an actor asleep in your store wakes it, and a send to no actor fails at once. Your application chooses, per kind of actor, whether to avoid that failure or handle it.

<a id="three-cases"></a>

## Find out where the actor is

What a send does depends on where its actor is:

- **The actor is hibernated.**: The host keeps the event in its queue and wakes the actor, loading its blob itself when the host has a `store`. The event runs as if the actor had never left, and a send to a name finds a hibernated actor as it finds a resident one.
- **No actor has that name or session.**: It was never spawned, or it ended. The sender gets `error.communication` at once, in the same run, with the send's `sendid`; an `actor.send` or `host.send` from your program throws `StaleError` instead.
- **The address is another system's.**: The send goes to your `transport` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)), and whether it arrives is your transport's to say.

Unlike a virtual actor, a missing actor is never spawned by a send, and its events wait in no queue. Your application decides what happens instead.

<a id="which-way-for-which-actor"></a>

## Choose by how long the actor lives

Pick the way for each kind of actor in your application:

| The actor | The way | In the chat example |
|---|---|---|
| long-lived, a known set (a workspace, a room, an account) | it never ends and hibernates | workspaces and rooms |
| made on demand, or not an actor at all (a cart, a user who may be offline) | your I/O processor routes it | direct messages (`chat:inbox`), rooms made by their workspace |
| short-lived, ends on its own (a connection, a job) | the sender handles `error.communication` | a join of a room that does not exist |

The [chat example](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/examples/chat-rooms/README.md) uses each of them, and its README says where.

<a id="the-actor-never-ends-and-hibernates"></a>

## Keep long-lived actors and let them hibernate

An actor that stands for a room or an account has no top-level `<final>`, so it never ends. It is always there to send to by its name.

A host with a `store` and a `resident` bound keeps it in memory only while it works. An idle actor costs its blob in your store ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).

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

const compiled = compileCharts([
  { name: 'room.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="room" initial="open">
    <datamodel><data id="said" expr="0"/></datamodel>
    <state id="open">
      <transition event="post">
        <assign location="said" expr="said + 1"/>
        <log expr="'the room has had ' + said + ' messages'"/>
      </transition>
    </state>
  </scxml>` },
  { name: 'member.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="member" initial="s">
    <state id="s">
      <transition event="say"><send event="post" target="tinyactors://chat/@room.acme.general"/></transition>
    </state>
  </scxml>` },
]);
const store = new MemoryStore();
const host = new Host(compiled, { system: 'chat', store, resident: 1, log: (entry) => console.log(entry.text) });
compiled.close();

const room = host.spawn('room', { name: 'room.acme.general' });
const member = host.spawn('member');
await host.idle();
console.log('the room is in the store:', store.blobs.has(room.id));
member.send('say');
member.send('say');
await host.idle();
console.log('the room is in the store:', store.blobs.has(room.id));
host.close();
```

```text title="output"
the room is in the store: true
the room has had 1 messages
the room has had 2 messages
the room is in the store: true
```

The member never learns that the room was hibernated. The host loaded it for the first `post` and hibernated it again when the host went idle.

Use this way when the set of actors is known and each is worth keeping until it is deleted on purpose. Your program, or an actor that manages the set, spawns them.

<a id="the-application-routes-it"></a>

## Spawn the actor when a send finds none

Send to an actor made on demand, such as a cart, through an I/O processor of your own. It looks the actor up with `send.host.actor` and spawns it when it is missing.

It forwards the event with the sender's address as its `origin`, so the actor answers the sender directly:

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

const compiled = compileCharts([
  { name: 'cart.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="cart" initial="open">
    <datamodel><data id="items" expr="[]"/></datamodel>
    <state id="open">
      <transition event="add">
        <assign location="items" expr="[...items, _event.data.sku]"/>
        <send event="added" targetexpr="_event.origin"><content expr="items.length"/></send>
      </transition>
    </state>
  </scxml>` },
  { name: 'shopper.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="shopper" initial="s">
    <state id="s">
      <transition event="buy">
        <send type="carts" event="add" targetexpr="'cart.' + _event.data.customer"><content expr="_event.data"/></send>
      </transition>
      <transition event="added"><log expr="'the cart holds ' + _event.data"/></transition>
    </state>
  </scxml>` },
]);

/** The carts processor: the cart named by the send's target, made when it is not there. */
const carts = {
  receive(send) {
    let cart;
    try {
      cart = send.host.actor(send.target);
    } catch (error) {
      if (!(error instanceof StaleError)) throw error;
      cart = send.host.spawn('cart', { name: send.target });
      console.log(`made ${send.target}`);
    }
    cart.send(send.event, send.data, { origin: send.sender.address });
  },
};
const host = new Host(compiled, { system: 'shop', ioProcessors: { carts }, log: (entry) => console.log(entry.text) });
compiled.close();

const shopper = host.spawn('shopper');
shopper.send('buy', { customer: 'ada', sku: 'tea' });
shopper.send('buy', { customer: 'ada', sku: 'cake' });
await host.idle();
host.close();
```

```text title="output"
made cart.ada
the cart holds 1
the cart holds 2
```

The processor is your code, so the policy is yours. It may refuse instead of spawning, or read the actor's starting state from your database.

It may also queue the event while something else makes the actor.

When rules decide which actors may exist, keep the decision in a chart. A collection actor that never ends checks each request and makes the actors with the package's `Spawner`.

The processor then only forwards to the collection ([Spawning from a chart](https://tinyactors.dev/guides/io-processors/index.md#spawning-from-a-chart)).

The same way serves what is not an actor. A processor for direct messages forwards to each of the user's open connections, or stores the message when there are none.

<a id="the-sender-handles-errorcommunication"></a>

## Handle the failed send in the sending chart

An actor that ends, such as a connection or a job, may get a send after its end. Its sender gets `error.communication` at once, with the send's `sendid`.

A transition on that event, matched by `sendid`, decides what follows. This client tells its user the room does not exist:

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

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">
    <transition event="join">
      <send id="join" event="join" targetexpr="'tinyactors://chat/@room.acme.' + _event.data"/>
    </transition>
    <transition event="error.communication" cond="_event.sendid === 'join'">
      <log expr="'no such room'"/>
    </transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();

const client = host.spawn('client');
client.send('join', 'nowhere');
await host.idle();
host.close();
```

```text title="output"
no such room
```

A send to a session that ended, or to a name no actor has, fails this way. A send to another system's address reaches your transport instead.

The transport fails it, with `send.fail()` or with `host.fail` from the other side, when it learns the actor is not there.

<a id="names-that-need-no-encoding"></a>

## Name actors with letters, digits, dots and dashes

A name is written into addresses, as `tinyactors://chat/@<name>` in a chart's `target` and in your logs. An address's name holds only the characters RFC 3986 calls unreserved.

Those are `A`-`Z`, `a`-`z`, `0`-`9`, `-`, `.`, `_` and `~`, and any other byte is percent-encoded. The [address grammar](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/src/base/address.c) checks it.

`Address.fromName` encodes for you, but `room/general` is then `room%2Fgeneral` in every address. A chart that writes `room/general` unencoded reaches no actor and gets `error.communication`:

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

console.log(Address.fromName('chat', 'room/general').text);
console.log(Address.fromName('chat', 'room.acme.general').text);

const compiled = compileCharts([
  { name: 'room.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="room"><state id="s"/></scxml>` },
  { name: 'poster.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="poster" initial="s">
    <state id="s">
      <onentry><send id="raw" event="post" target="tinyactors://chat/@room/general"/></onentry>
      <transition event="error.communication"><log expr="'error.communication for ' + _event.sendid"/></transition>
    </state>
  </scxml>` },
]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('room', { name: 'room/general' });
host.spawn('poster');
await host.idle();
console.log(host.actor('room/general').address.text);
host.close();
```

```text title="output"
tinyactors://chat/@room%2Fgeneral
tinyactors://chat/@room.acme.general
error.communication for raw
tinyactors://chat/#_scxml_1
```

Name an actor by its kind and its ids joined by `.`, each id of lowercase letters, digits and `-`. Examples are `room.acme.general` and `cart.ada`.

Check an id that comes from a user before it becomes part of a name. The system's own id is stricter: lowercase letters, digits, `-` and `.`.

Names with parts also avoid two lookups by other keys. tinyactors finds an unnamed actor by its chart's name, and an invoked child by its invoke id.

So a name `room` would find any unnamed actor of the chart `room`, and `cart` the child of an `<invoke id="cart">`. `room.acme.general` equals neither.

A name has one owner, the collection actor that spawns it ([Spawning from a chart](https://tinyactors.dev/guides/io-processors/index.md#spawning-from-a-chart)).

<a id="keying-a-table-by-the-sender"></a>

## Keep one table entry per sender

A room's members or a workspace's pending requests are tables keyed by `_event.origin`, the sender's address. One sender's origin comes in two forms:

- **`#_scxml_2`, the fragment alone**: when the send stayed in the sender's segment of the host: a send to a session's address (`#_scxml_<n>`, or the full address of a session of the same system), to `#_parent`, to an invoked child, and a delayed send among them;
- **`tinyactors://chat/#_scxml_2`, the full address**: when the host routed the send: a send to a name (`@room.acme.general`), to a session in another segment, or from another system (whatever origin its transport passes, the full address when it passes the sender's `origin` on).

Both name the same sender, so key the table by the origin from `#` on. Here a helper in a chart-level `<script>` gives both forms one key:

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

const compiled = compileCharts([
  { name: 'room.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="room" initial="open">
    <script>
      /** The sender's key: its address from the "#" on, whichever form the origin has. */
      function sender(origin) { return origin.slice(origin.indexOf('#')); }
    </script>
    <datamodel><data id="members" expr="({})"/></datamodel>
    <state id="open">
      <transition event="join">
        <assign location="members" expr="({ ...members, [sender(_event.origin)]: _event.data })"/>
        <log expr="_event.origin + ' is ' + sender(_event.origin) + ': ' + Object.keys(members).length + ' member'"/>
      </transition>
    </state>
  </scxml>` },
  { name: 'member.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="member" initial="s">
    <state id="s">
      <transition event="join"><send event="join" targetexpr="_event.data"><content expr="'ada'"/></send></transition>
    </state>
  </scxml>` },
]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();

const room = host.spawn('room', { name: 'room.acme.general' });
const member = host.spawn('member');
member.send('join', room.address.text);                   // by its session
await host.idle();
member.send('join', 'tinyactors://chat/@room.acme.general'); // by its name
await host.idle();
host.close();
```

```text title="output"
#_scxml_2 is #_scxml_2: 1 member
tinyactors://chat/#_scxml_2 is #_scxml_2: 1 member
```

The fragment is a key and a target too: `<send targetexpr="key">` reaches the sender from any segment of the host.

<a id="full-address"></a>

## Keep the system when senders cross systems

A directory that answers several hosts holds senders of other systems, so its keys must keep the system. An origin from another system always names it.

There, complete a fragment with the actor's own system, from its own address in `_ioprocessors.scxml.location`:

```xml
<script>
  /** The sender's full address; `self` is _ioprocessors.scxml.location. */
  function senderAddress(origin, self) {
    return origin.startsWith('#_scxml_') ? self.slice(0, self.indexOf('#')) + origin : origin;
  }
</script>
<assign location="members" expr="({ ...members, [senderAddress(_event.origin, _ioprocessors.scxml.location)]: _event.data })"/>
```

An event from a service your program runs (`invocation.sendBack`) has the origin `#_<invokeid>`. It names that invocation in this actor only, and either helper leaves it as it is.
