<!-- https://tinyactors.dev/guides/other-systems/ -->
# Other systems

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Send events to actors in other processes and machines: a function you write carries each message, and the other host takes it unchanged.

An actor sends to an actor on another machine by its address. A function you write carries the message, and the other side's host takes it unchanged, a Python host included.

<a id="systems"></a>

## Give each host a system name

The `system` option names a host's system, and every address starts with it: `tinyactors://<system>/...`. Actors of one system reach actors of another, in this process or on another machine, by address.

The host delivers a send to its own system's address itself. A send to any other system goes to your `transport` option, a handler that carries it there.

You choose the wire and its encoding. The other side gives each message to its host with `host.send` ([Wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format)).

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

## Send to an actor by its address

`actor.address` gives an actor's address, and `host.actor(address)` finds the actor a local address names.

`host.send` takes an `Actor`, a session, an address string or an `Address`. On the host named `shop`, `tinyactors://shop/@teller` reaches the actor spawned with the name `teller`.

A message's `origin` is the sender's address as the other side gave it. The receiving actor reads it as `_event.origin`.

<a id="two-systems"></a>

## Carry each send to the other host

The `transport` handler gets each send to another system as a `Send`. The other side passes its `send.message` to `host.send(message)` as it is.

- **`send.message`**: The outgoing half: `target`, `event`, `data`, `sendid`, `origin` and `traceparent`, `null` for a field the send lacks. A Python host's `host.send` takes it too.
- **`send.target`, `send.origin`**: The receiver's and the sender's addresses, as `Address` values.
- **`encode`, `decode`**: Write the message as CBOR, its addresses as CBOR's tag 32, as a Python host's `encode` does, and read them back as `Address` values.

Here two hosts in one process pass encoded messages through a timer. The shop's checkout asks the bank's teller for a charge, and the teller approves it.

```javascript title="two-systems.mjs"
import { Address, compileCharts, decode, encode, Host } from '@tinyactors/node';

const shopChart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="checkout" initial="paying">
  <state id="paying">
    <onentry>
      <send event="charge" target="tinyactors://bank/@teller"><param name="amount" expr="12"/></send>
    </onentry>
    <transition event="approved" target="done"><log expr="'approved by ' + _event.origin"/></transition>
  </state>
  <final id="done"/>
</scxml>`;
const bankChart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="teller" initial="open">
  <state id="open">
    <transition event="charge">
      <log expr="'charging ' + _event.data.amount + ' for ' + _event.origin"/>
      <send event="approved" targetexpr="_event.origin"/>
    </transition>
  </state>
</scxml>`;

const image = (name, text) => {
  const compiled = compileCharts([{ name, text }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

// The wire: bytes in a queue, delivered on a later turn of the event loop.
const hosts = {};
const wire = (message) => {
  const bytes = encode(message);
  setTimeout(() => {
    const received = decode(bytes);
    hosts[received.target.system].send(received);
  });
};

const log = (entry) => console.log(entry.text);
const transport = (send) => wire(send.message);
hosts.shop = new Host(image('checkout.scxml', shopChart), { system: 'shop', log, transport });
hosts.bank = new Host(image('teller.scxml', bankChart), { system: 'bank', log, transport });

hosts.bank.spawn('teller', { name: 'teller' });
hosts.shop.spawn('checkout');
await new Promise((resolve) => setTimeout(resolve, 50));
await Promise.all([hosts.shop.idle(), hosts.bank.idle()]);
hosts.shop.close();
hosts.bank.close();
```

```text title="output"
charging 12 for tinyactors://shop/#_scxml_1
approved by tinyactors://bank/#_scxml_1
```

The teller answers to `_event.origin`, the checkout's full address, so the approval goes back through the bank's transport.

<a id="over-a-socket"></a>

## Connect two processes over TCP

Between processes, the transport writes each message as a frame on a connection: four bytes of length, then the message's CBOR.

Call `socket.setNoDelay(true)` on both ends. Node.js turns on Nagle's algorithm by default, which holds a second small write until the peer acknowledges the first.

That wait is about 40 ms on Linux's loopback, and an answer is often a second small frame. Python's asyncio turns the algorithm off by itself.

In this program the bank listens on a port and the shop connects. The charge and the approval cross the connection as one frame each.

```javascript title="socket.mjs"
import { connect, createServer } from 'node:net';
import { compileCharts, decode, encode, Host } from '@tinyactors/node';

/** Calls `receive` with each message the frames on `socket` hold. */
function frames(socket, receive) {
  let buffered = Buffer.alloc(0);
  socket.on('data', (chunk) => {
    buffered = Buffer.concat([buffered, chunk]);
    while (buffered.length >= 4 && buffered.length >= 4 + buffered.readUInt32BE(0)) {
      const length = buffered.readUInt32BE(0);
      receive(decode(buffered.subarray(4, 4 + length)));
      buffered = buffered.subarray(4 + length);
    }
  });
}
const frame = (message) => {
  const body = encode(message);
  const head = Buffer.alloc(4);
  head.writeUInt32BE(body.length);
  return Buffer.concat([head, body]);
};

let toBank;
let toShop;
const log = (entry) => console.log(entry.text);
const compiled = compileCharts([
  { name: 'checkout.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="checkout">
  <state id="paying">
    <onentry><send event="charge" target="tinyactors://bank/@teller"/></onentry>
    <transition event="approved" target="done"><log expr="'approved'"/></transition>
  </state>
  <final id="done"/>
</scxml>` },
  { name: 'teller.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="teller">
  <state id="s"><transition event="charge"><log expr="'charging ' + _event.origin"/><send event="approved" targetexpr="_event.origin"/></transition></state>
</scxml>` },
]);
const shop = new Host(compiled, { system: 'shop', log, transport: (send) => toBank.write(frame(send.message)) });
const bank = new Host(compiled, { system: 'bank', log, transport: (send) => toShop.write(frame(send.message)) });
compiled.close();

// The bank listens on a port of the system's choosing; the shop connects.
const server = createServer((socket) => {
  socket.setNoDelay(true);
  toShop = socket;
  frames(socket, (message) => bank.send(message));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
toBank = connect(server.address().port, '127.0.0.1');
toBank.setNoDelay(true);
frames(toBank, (message) => shop.send(message));
await new Promise((resolve) => toBank.once('connect', resolve));
await new Promise((resolve) => setImmediate(resolve)); // the server's side of the connection

bank.spawn('teller', { name: 'teller' });
const order = shop.spawn('checkout');
await order.done;
console.log('order', order.id, 'ended');
toBank.end();
server.close();
shop.close();
bank.close();
```

```text title="output"
charging tinyactors://shop/#_scxml_1
approved
order 1n ended
```

<a id="failed-delivery"></a>

## Tell the sender when delivery fails

When the transport cannot write a frame, or the peer is gone, it calls `send.fail()` while its handler runs. After the handler has returned, call `host.fail(sender, sendid)` on the sending host.

There `sender` is the message's `origin`, the actor that sent it, not the target it was for. That actor gets `error.communication` with that `sendid`.

Only a failure needs a call: a delivered send needs nothing more. A host without a `transport` handler fails every send to another system.

<a id="addresses"></a>

## Read an address into its parts

`new Address(text)` reads an address into its `system`, `session` (a `bigint`) and `name`, each `undefined` when the text lacks it.

`Address.fromSession(system, session)` and `Address.fromName(system, name)` make one, and `toString()` gives its text. This program makes both kinds and reads text that is no address.

```javascript title="address.mjs"
import { Address } from '@tinyactors/node';

const bySession = Address.fromSession('shop', 42n);
const byName = Address.fromName('shop', 'front desk');
console.log(bySession.text, bySession.system, bySession.session);
console.log(byName.text, byName.name);
console.log(new Address('not an address').system);
```

```text title="output"
tinyactors://shop/#_scxml_42 shop 42n
tinyactors://shop/@front%20desk front desk
undefined
```

<a id="json"></a>

## Write messages as JSON

`JSON.stringify` writes each address of a `send.message` as its text (`address.toJSON()`). The other side's `host.send` takes the parsed message, its addresses as strings, and `new Address(text)` reads one back.

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

let wire;
const compiled = compileCharts([
  { name: 'checkout.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="checkout">
  <state id="s"><onentry><send event="charge" target="tinyactors://bank/@teller"><param name="amount" expr="12"/></send></onentry></state>
</scxml>` },
  { name: 'teller.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="teller">
  <state id="s"><transition event="charge"><log expr="'charge ' + _event.data.amount + ' from ' + _event.origin"/></transition></state>
</scxml>` },
]);
const shop = new Host(compiled, { system: 'shop', transport: (send) => { wire = JSON.stringify(send.message); } });
const bank = new Host(compiled, { system: 'bank', log: (entry) => console.log(entry.text) });
compiled.close();
bank.spawn('teller', { name: 'teller' });
shop.spawn('checkout');
await shop.idle();

const message = JSON.parse(wire); // its addresses are strings
console.log(typeof message.target, message.target);
bank.send(message);
await bank.idle();
console.log(new Address(message.origin).session);
shop.close();
bank.close();
```

```text title="output"
string tinyactors://bank/@teller
charge 12 from tinyactors://shop/#_scxml_1
1n
```

Inside event data an address is plain text: values have no address type.

<a id="scxmls-basichttp"></a>

## Read and write BasicHTTP requests

SCXML defines BasicHTTP, a way to send events as HTTP form posts. The package writes and reads those requests, for an I/O processor or a server of your own.

- **`encodeHTTPPost({ url, event, fields, body })`**: Writes the request a send makes, as bytes for a socket.
- **`parseHTTPRequest(bytes)`**: Reads an incoming request's form fields and its event: the `_scxmleventname` field, or `HTTP.<METHOD>`.

```javascript title="basichttp.mjs"
import { encodeHTTPPost, parseHTTPRequest } from '@tinyactors/node';

const request = encodeHTTPPost({
  url: 'http://localhost:8080/scxml',
  event: 'order.placed',
  fields: [{ name: 'sku', value: 'tea' }, { name: 'qty', value: '2' }],
});
console.log(new TextDecoder().decode(request).split('\r\n')[0]);

const incoming = parseHTTPRequest(request);
console.log(incoming.method, incoming.target, incoming.event);
console.log(incoming.fields.map(({ name, value }) => `${name}=${value}`).join(' '));
```

```text title="output"
POST /scxml HTTP/1.1
POST /scxml order.placed
sku=tea qty=2
```

The host hands each send to your I/O processor, and your program writes the bytes and serves the port.
