Send events to actors in other processes
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.
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).
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.
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.messageThe outgoing half:target,event,data,sendid,originandtraceparent,nullfor a field the send lacks. A Python host'shost.sendtakes it too.send.target,send.originThe receiver's and the sender's addresses, asAddressvalues.encode,decodeWrite the message as CBOR, its addresses as CBOR's tag 32, as a Python host'sencodedoes, and read them back asAddressvalues.
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.
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();charging 12 for tinyactors://shop/#_scxml_1
approved by tinyactors://bank/#_scxml_1The teller answers to _event.origin, the checkout's full address, so the approval goes back through the bank's transport.
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.
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();charging tinyactors://shop/#_scxml_1
approved
order 1n endedTell 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.
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.
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);tinyactors://shop/#_scxml_42 shop 42n
tinyactors://shop/@front%20desk front desk
undefinedWrite 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.
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();string tinyactors://bank/@teller
charge 12 from tinyactors://shop/#_scxml_1
1nInside event data an address is plain text: values have no address type.
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_scxmleventnamefield, orHTTP.<METHOD>.
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(' '));POST /scxml HTTP/1.1
POST /scxml order.placed
sku=tea qty=2The host hands each send to your I/O processor, and your program writes the bytes and serves the port.