@tinyactors/node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,169 +1,401 @@
1
- # @tinyactors/node
1
+ # tinyactors for Node.js
2
2
 
3
- Tinyactors for Node.js (22.14 or newer) and Bun: SCXML statecharts run as
4
- actors on a native runtime, through Node-API.
3
+ xstate-style machines and actors running on the tinyactors SCXML runtime.
4
+ The addon is written against the **Node-API C API** (`node_api.h`, no C++
5
+ wrapper) and links the tinyactors static libraries. The JavaScript API lives
6
+ in `bindings/shared/core.mjs` and is shared with the
7
+ [web binding](../web) (same `index.d.ts`), so the same code runs in Node.js and
8
+ in browsers. Node.js ≥ 22.12 (`require()` of the ES-module core).
5
9
 
6
- ```text
7
- npm install @tinyactors/node
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @tinyactors/node # or: pnpm add, bun add
8
14
  ```
9
15
 
10
- The install brings a prebuilt addon for your platform: no compiler, no
11
- `node-gyp` and no postinstall script. There are addons for macOS on Apple
12
- silicon and Intel (11.0 or newer) and for Linux on x64 and arm64; the Linux
13
- addon links no C library, so one build serves glibc and musl (Alpine).
16
+ The package carries no compiler step: each supported platform has a
17
+ prebuilt addon in its own package (`@tinyactors/node-darwin-arm64`,
18
+ `-darwin-x64`, `-linux-x64`, `-linux-arm64`), an optional dependency that
19
+ npm, pnpm and Bun install only where it matches. The Linux addon serves
20
+ glibc and musl alike. Development builds are under the `next` dist-tag
21
+ (`npm install @tinyactors/node@next`).
22
+
23
+ In this repository, `mise run node:build` (in `tinyactors-core`) builds the
24
+ addon into `bindings/node/build/tinyactors.node`, which `index.js` loads
25
+ before any installed platform package. Packaging and releasing are in
26
+ [distribution](../../docs/distribution.md).
27
+
28
+ ```js
29
+ const { createMachine, createActor, assign } = require('@tinyactors/node');
30
+
31
+ const toggle = createMachine({
32
+ id: 'toggle',
33
+ initial: 'inactive',
34
+ context: { count: 0 },
35
+ states: {
36
+ inactive: { on: { TOGGLE: { target: 'active', actions: assign({ count: ({ context }) => context.count + 1 }) } } },
37
+ active: { on: { TOGGLE: 'inactive' }, after: { 1000: 'inactive' } },
38
+ },
39
+ });
40
+
41
+ const actor = createActor(toggle).start();
42
+ actor.subscribe((s) => console.log(s.value, s.context));
43
+ actor.send({ type: 'TOGGLE' });
44
+ ```
45
+
46
+ ## How it works
47
+
48
+ - `createMachine(config)` compiles the config to SCXML that reads like
49
+ hand-written SCXML (`machine.toSCXML()`): named guards and actions appear by
50
+ name (`cond="isAdult"`, `<script>track({"tag":"t"})</script>`), inline
51
+ functions by their source, literals as JSON, `stateIn` as `In('a.b')`,
52
+ combinators as `and(isAdult, not(above({"min":30})))`, assigns as
53
+ `<assign location="count" expr="..."/>`, raises as `<raise event="X"/>`.
54
+ - The context is SCXML data: one `<data id="prop">` per property, for object
55
+ literals and for factories `({ input }) => ({ a: input.a, b: [] })` alike
56
+ (each `<data>` shows its property's source; the factory still runs once per
57
+ actor). `assign()` becomes one `<assign location="prop">` per property; the
58
+ computed properties are evaluated together against the previous context
59
+ (xstate semantics), constants follow. Sequential steps read best as
60
+ sequential assigns: `[assign({ pos: ... }), assign({ status: ({ context })
61
+ => status(context.pos) })]`. Only a function the compiler cannot split (a
62
+ block body, spreads, computed keys) falls back to a single
63
+ `<data id="context">` / `<assign location="context">`.
64
+ - Each machine keeps a registry from that text to the JavaScript function
65
+ implementing it. When a chart is attached to a native system, the datamodel
66
+ resolves every expression of the chart once and stores the functions in a
67
+ table indexed by the image's expression ids — evaluation is an indexed
68
+ call, and the index never appears in the chart. Two different functions
69
+ with the same source text are told apart by a trailing comment
70
+ (`... /* 2 */`).
71
+ - **One native system per `System`, not per actor.** Actors started with
72
+ `createActor()` live in the process-wide default system (or the one given
73
+ as `createActor(machine, { system: createSystem() })`). The machines known
74
+ when the system starts are linked into one image; a machine defined later
75
+ is linked into an additional *segment* (as is each reloaded version). All
76
+ segments share one base URI, `tinyactors://<system id>/`, and each creates
77
+ sessions from its own range; a send to a session in another segment goes
78
+ through the runtime's remote I/O processor (`TA_IO_PROCESSOR_SCXML_SHARED`), so
79
+ `sendTo(actor, ...)` and
80
+ `sendTo(({ system }) => system.get('id'), ...)` work across them. The
81
+ native region grows by relocation (thousands of actors per system).
82
+ - Context, events and payloads are napi references owned by the system's
83
+ datamodel host; they live as long as the system (payloads are refcounted
84
+ and recycled).
85
+ - Events are processed synchronously on `send()`; long-running work yields
86
+ cooperatively (`setImmediate`) so even a runaway eventless loop cannot block
87
+ the event loop or starve other actors. Delayed events use the host clock via
88
+ `setTimeout`. Calls made from inside actions (e.g. `actor.send()`) are
89
+ queued until the current run returns. A system runs on the JavaScript
90
+ thread; for more cores, run systems in worker threads and link them —
91
+ [docs/concurrency.md](../../docs/concurrency.md) explains what runs when.
92
+
93
+ ## Hibernation
94
+
95
+ Idle actors can be unloaded and brought back on demand. The system never does
96
+ I/O itself: you hand it a store.
14
97
 
15
98
  ```js
16
- const { createSystem, statechart } = require('@tinyactors/node');
17
-
18
- const light = statechart({ family: 'light', revision: 'v1' })
19
- .data('switches', 0)
20
- .state('off', (s) => s.on('toggle', (t) => t.target('on').assign('switches', function () { return this.switches + 1; })))
21
- .state('on', (s) => s.on('toggle', (t) => t.target('off')));
22
-
23
- async function main() {
24
- const system = createSystem();
25
- const lamp = system.spawn(system.define(light), { name: 'lamp' });
26
- await lamp.send('toggle'); // resolves once the macrostep it started ends
27
- console.log(lamp.inspect().activeStates, lamp.data().switches); // [ 'on' ] 1
28
- system.close();
29
- }
30
-
31
- main();
99
+ const system = createSystem({
100
+ hibernation: {
101
+ store: { get: (k) => db.get(k), set: (k, blob) => db.put(k, blob), delete: (k) => db.del(k) }, // may be async
102
+ sweepMs: 30_000, // unload actors idle for a whole sweep period (0 = only system.hibernate())
103
+ },
104
+ });
105
+ system.hibernate(actor); // or system.hibernate() for every idle actor
106
+ actor.hibernated; // true; getSnapshot() is answered from cache
107
+ actor.send({ type: 'X' }); // the event waits, the blob is loaded, the actor carries on
32
108
  ```
33
109
 
34
- `index.d.ts` describes the whole API. The package is 0.x: its API changes
35
- in minor versions.
110
+ Context, events and input travel through a tagged-JSON codec (`encodeValue` /
111
+ `decodeValue`). It keeps `undefined`, `Date`, `Map`, `Set`, `BigInt`, shared
112
+ references and cycles, and encodes actors as their addresses. Actors whose
113
+ context holds functions stay resident (the sweep skips them;
114
+ `system.hibernate(actor)` throws, naming what cannot be stored). Pending
115
+ delayed events wake the actor when they fire. `createMemoryStore()` is a
116
+ store in memory.
36
117
 
37
- ## Working on it in the repository
118
+ ### Moving an actor to another system
38
119
 
39
- In this repository the package is built and tested through the task
40
- interface; the addon it loads is the one `mise run build` writes:
120
+ `system.export(actor)` takes an actor out of its system as bytes — states,
121
+ context or variables, delayed events with their data, the actors it invoked,
122
+ and what it runs. `system.adopt(bytes)` takes it in anywhere: another system
123
+ in this process, another process, Node or web. It keeps its session (its
124
+ address under the new system's id), and its delayed events keep the time
125
+ they had left.
41
126
 
42
- ```text
43
- mise run build
44
- mise run test
127
+ ```js
128
+ const bytes = here.export(actor); // it stops here (no done event)
129
+ // ... another process ...
130
+ const actor = there.adopt(bytes); // machines are found as for restore
45
131
  ```
46
132
 
47
- The tests load the same native addon with Node.js and Bun. See
48
- [`docs/design.md`](docs/design.md) for the binding architecture, and
49
- [ADR 0001](../docs/adr/0001-packaging-and-releases.md) for how the packages
50
- are built and released: `mise run build --target <t>` builds a release
51
- target's addon with zig, `mise run symbols` checks what it imports, and
52
- `mise run package` stages and packs the npm packages into
53
- `build/npm/tarballs/`.
54
-
55
- ## `index.d.ts` is the desired API
56
-
57
- `index.d.ts` is the design target, not a description of what `lib/`
58
- implements. A declaration that is not implemented yet carries
59
- `// status: unimplemented`, or `// status: partial: <what is missing>`, on
60
- the line directly above it. Don't delete a declaration because `lib/` lacks
61
- it: implement it, or leave it marked. `grep -n "^ *// status:" index.d.ts`
62
- lists what is outstanding, and `mise run check-api-status` (part of
63
- `mise run test`) fails when a marker is stale or a missing declaration is
64
- unmarked, for the exports and for the objects it can probe at runtime.
65
-
66
- ## Benchmarks
67
-
68
- `mise run bench [population ...]` runs the tracing bench on Node and Bun and
69
- prints throughput and memory side by side; `mise run bench-compare <commit>`
70
- builds another commit beside the working tree and runs both alternately on
71
- this machine, flagging changes past 5%. Results are stored under
72
- `bench/results/<machine signature>/` (see its README).
73
-
74
- **Reporting convention.** A benchmark report always gives throughput and
75
- memory together, names the machine signature it ran under, and compares
76
- builds side by side with `bench-compare`, never against numbers from another
77
- day or another machine: the same build measured 30% apart on two days on
78
- one machine.
79
-
80
- ## Loading actors on demand
81
-
82
- `System.setLoader(family, loader)` brings actors of a family back when mail
83
- arrives for them. Mail for a name with no resident actor waits while the
84
- loader runs, then is delivered first, in order. The loader returns a
85
- `SessionImage` (process-local: for actors offloaded from memory in this
86
- process), `{ spawn: definition, binding }` to rebuild an actor from data
87
- the application stored (after a restart, for example), `"not-found"`, or
88
- `"reject"` for "not now". An unloaded actor's own timers wake it through
89
- its loader. See [ADR 0020](docs/adr/0020-mail-for-an-unloaded-actor-waits-while-a-loader-brings-it-back.md).
90
-
91
- ## Tracing
92
-
93
- `System.setTraceSink()` hands a function you register the spans of each
94
- pump turn as OTLP protobuf bytes, which any OTLP/HTTP collector takes as
95
- they are; `decodeTraces()` reads them back into objects. There is no
96
- telemetry dependency. See
97
- [`docs/tracing.md`](docs/tracing.md), and `mise run otel-demo` to look at
98
- a trace in otel-tui.
99
-
100
- SCXML documents import with `define(xml, { format: 'scxml' })`, and
101
- `registerDatamodel()` plugs in a compiler for their expression text. See
102
- [`docs/scxml.md`](docs/scxml.md).
103
-
104
- ## Debugging an actor
105
-
106
- `createDebugSession(system, { allow, audit, send })` is a Debug Adapter
107
- Protocol session over one actor of a running system: give it each incoming
108
- message with `receive()`, and it hands each outgoing one to `send`. It
109
- opens no socket and checks no credentials; put it behind your own
110
- transport and authentication, and decide each user's permissions before
111
- you create it. `DAPReader` and `encodeDAPMessage` frame messages on a byte
112
- stream (stdio, a TCP socket); a WebSocket needs neither.
113
-
114
- A client attaches with `{ "address": "family/name" }` (or `"sessionID"`),
115
- and may ask for fewer permissions with `"allow"`. The session watches the
116
- actor live and never stops it: a production actor is never held by a
117
- debugger. The client hears the actor stopped on entry, so it shows the
118
- stack and the variables, and after each macrostep the summary in the
119
- console and a refresh of both that leaves the keyboard focus where it is,
120
- so typing in the Debug Console is never interrupted. `pause` and the
121
- steps are refused, and `continue` changes nothing. Breakpoints are
122
- tracepoints: the console says where one would have stopped, and a logpoint
123
- writes its message.
124
-
125
- What `allow` grants are pokes, each a transition the watcher sees as a new
126
- macrostep: `send` an event through the mailbox, `set` a data-model
127
- location, `goto` (an operator transition, with `abandon`, `cancel` and
128
- `replace`), and `evaluate`. With none, the session only watches.
129
-
130
- **`evaluate` runs arbitrary code.** Watch, hover and console expressions,
131
- breakpoint conditions and logpoint `{expression}` parts run JavaScript in
132
- your process. They need the `evaluate` permission, which is off unless
133
- granted, and each is checked against the attach it runs under: a
134
- condition set before a watch-only attach never runs. Without it the
135
- Variables pane and the console commands still work. Grant it only to
136
- someone who may run code on the host.
137
-
138
- Frames and line breakpoints are on the lines a chart was written on:
139
- the builder calls of statechart(), or the lines of an SCXML document you
140
- name with `define(text, { format: 'scxml', name: path })`. A document
141
- defined without a name, or a child chart inline in `<content>`, is shown
142
- as SCXML the session writes from the definition, which the client asks
143
- for by `sourceReference` and sets breakpoints in.
144
-
145
- `audit(entry)` hears every attach, detach, breakpoint change, console
146
- command, evaluation and mutation before it happens; a hook that throws
147
- refuses it. That includes each breakpoint condition and logpoint part at
148
- each hit: a refused condition does not fire, and a refused part is
149
- written as `<refused>`. Only a detach is heard after it happens.
150
-
151
- `mise run dap-server` serves sessions for a small example system over
152
- stdio, or on a local port with `-- --port 4711`, to try a DAP client
153
- against. It grants every permission; it is a development tool, not part
154
- of the package. In VS Code, install
155
- [tinyactors-vscode](../tinyactors-vscode/README.md): an `attach`
156
- configuration with the `port` and the actor's `address` connects to such a
157
- server. See
158
- [ADR 0026](docs/adr/0026-a-debugger-watches-and-pokes-one-live-actor.md)
159
- and [the status of every DAP message](../docs/debug-adapter.md).
160
-
161
- `test/dap-transcripts.js` plays the DAP transcripts napi shares with the
162
- test host's adapter (`../tinyactors-test/dap/transcripts/`), under Node
163
- and Bun, so the two adapters stay in step. To add one, write the
164
- transcript, and the chart in both forms (`dap/charts/<chart>.js` and
165
- `.rb`) if it needs a new one, then play it in both hosts: `node
166
- test/dap-transcripts.js <name>` here (`DAP_TRACE=1` prints every message)
167
- and `ruby ruby/dap_transcripts.rb <name>` in tinyactors-test. The format
168
- and where the adapters differ are in
169
- [its README](../tinyactors-test/dap/README.md).
133
+ ## Hot reload and live migration
134
+
135
+ ```js
136
+ system.reload(counterV2); // CGI style: returns 2; new actors run it, running ones keep theirs
137
+ const { done } = system.migrate(); // move running actors (a job in time slices)
138
+ const { migrated, failed, pending } = await done; // pending: left behind (timeout)
139
+ system.migrate(counter, { wake: false, timeoutMs: 5000 }); // options
140
+ // in counterV2: on: { 'error.platform.upgrade': { actions: assign({ total: ({ event }) => event.data.count }) } }
141
+ ```
142
+
143
+ `reload(machine)` makes `machine` the current version of the machines with its
144
+ id (compiled right away, so errors throw there). A version whose actors are
145
+ all gone is freed. Addresses stay valid: all actors of a system share one base
146
+ URI and sessions are found wherever they live. `migrate(target?)` moves actors
147
+ of older versions (one actor, a machine's actors, or all) at a stable point:
148
+ states are matched by id, the context is kept (properties the new machine does
149
+ not declare are dropped, new ones initialized), timers keep running, and the
150
+ actor receives `{ type: 'error.platform.upgrade', data: previousContext }`.
151
+ Migration is a job advanced in time slices of a few ms, walking the actors
152
+ lazily, so the event loop stays responsive with any number of actors (100,000
153
+ actors: the call takes ~5 ms, each slice ~5 ms). Busy actors move at their next
154
+ stable point. Hibernated actors are loaded from the store first (`wake`, on by
155
+ default when the system has a hibernation store), or move once they wake.
156
+ `timeoutMs` ends the job and reports who was left behind. `done` resolves once
157
+ the moved actors have processed their upgrade event. There is deliberately no
158
+ "force": an actor mid-macrostep or with a pending request cannot move without
159
+ changing SCXML semantics, and an actor with running invocations waits until
160
+ they finish (its invoked sessions run charts of its old version, which are not
161
+ translated). Sends to an address
162
+ nobody has raise `error.communication` in the sender.
163
+
164
+ ## SCXML documents
165
+
166
+ `fromSCXML(xml, { documents })` runs a W3C SCXML document as actor logic, in
167
+ the same system as your machines (they message each other directly). The
168
+ `ecmascript` datamodel (SCXML Appendix B.2) runs in JavaScript with the same
169
+ semantics as the C datamodel; `null` works too. The W3C IRP suite passes
170
+ through this binding (158/158 mandatory; `mise run w3c:js`).
171
+
172
+ ```js
173
+ const { fromSCXML, createActor } = require('@tinyactors/node');
174
+
175
+ const counter = fromSCXML(`
176
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" initial="idle">
177
+ <datamodel><data id="count" expr="0"/></datamodel>
178
+ <state id="idle">
179
+ <transition event="inc"><assign location="count" expr="count + (_event.data.by || 1)"/></transition>
180
+ <transition event="done" target="end"/>
181
+ </state>
182
+ <final id="end"><donedata><param name="total" expr="count"/></donedata></final>
183
+ </scxml>`);
184
+
185
+ const a = createActor(counter, { input: { count: 10 } }).start(); // input overrides <data>
186
+ a.send({ type: 'inc', by: 2 }); // _event.name = 'inc', _event.data = { by: 2 }
187
+ a.getSnapshot().context; // { count: 12 } — the datamodel's variables
188
+ ```
189
+
190
+ - Events: `type` becomes `_event.name`; `data` (or, without it, the event's
191
+ other properties) becomes `_event.data`.
192
+ - The snapshot's `value` is the active states (by id) as a nested state value;
193
+ `context` the datamodel variables; `output` the `<donedata>`.
194
+ - `documents` maps names to further documents: `<invoke src="child.scxml">`
195
+ children and anything a `src="..."` names (`<data src>`).
196
+ - Expressions are compiled with `new Function` (a browser CSP must allow
197
+ `'unsafe-eval'` for SCXML documents; machines do not need it).
198
+ - `<script>`s that declare top-level names (`var`, `let`, `const`,
199
+ `function`, `class` — as the JS engine sees them: names in blocks or nested
200
+ functions do not count) make those names the session's, as in the C
201
+ datamodel. Such actors hibernate, snapshot, export and migrate: variables
202
+ and `let`/`const` bindings keep their values (`const` stays constant),
203
+ top-level function declarations are re-created. Anything else that cannot
204
+ be stored is refused naming the variable and line, e.g. `variable 'helper'
205
+ cannot be stored: it holds a function (line 12); only top-level function
206
+ declarations are stored ...`.
207
+
208
+ ## System images
209
+
210
+ A `<system>` manifest names charts and the actors to start; compiled, it is
211
+ one immutable image you can ship as bytes (also produced by the C `tac`
212
+ compiler) and boot anywhere — Node, a browser, a C host.
213
+
214
+ ```js
215
+ const { compileSystem, loadImage, createSystem } = require('@tinyactors/node');
216
+
217
+ const image = compileSystem(`
218
+ <system>
219
+ <chart name="pinger" src="ping.scxml"/>
220
+ <actor name="server" chart="pinger"/>
221
+ </system>`, { files: { 'ping.scxml': pingXML } });
222
+
223
+ fs.writeFileSync('app.tai', image.bytes);
224
+ const { server } = createSystem().boot(loadImage(fs.readFileSync('app.tai')));
225
+ createActor(image.chart('pinger')).start(); // more actors of an image's chart
226
+ ```
227
+
228
+ ## Snapshots and deterministic time
229
+
230
+ `system.snapshot()` returns the whole system as bytes: every actor's
231
+ configuration, context or datamodel variables, queued events and pending
232
+ timers, plus what it runs (the SCXML of each machine, documents, images).
233
+ `createSystem({ restore: bytes })` brings it back — same system id, so
234
+ addresses stay valid; find actors with `system.get(systemID)`. Machines are
235
+ matched by id and the SCXML they compile to (ones defined in the process are
236
+ found automatically; pass more in `machines`). Contexts must be encodable (no
237
+ functions); hibernated actors stay in the hibernation store, so restore with
238
+ the same store.
239
+
240
+ ```js
241
+ const bytes = system.snapshot(); // e.g. on shutdown
242
+ // ... a new process ...
243
+ const system = createSystem({ restore: bytes, hibernation: { store } });
244
+ system.get('lobby').send({ type: 'PING' });
245
+ ```
246
+
247
+ `createSystem({ clock })` makes the system run on your clock instead of wall
248
+ time: it arms no timers itself; advance the clock and call
249
+ `system.flush()`, which runs everything that is due until the system is
250
+ idle — for deterministic tests, simulations and replays.
251
+
252
+ ```js
253
+ let now = 0;
254
+ const system = createSystem({ clock: () => now });
255
+ createActor(machineWithAfter1000, { system }).start();
256
+ now += 1000;
257
+ system.flush(); // the `after: 1000` transition has been taken
258
+ ```
259
+
260
+ ## Links: actors across systems
261
+
262
+ `createLink(system, { url })` connects to another system (`serveLinks` on the
263
+ other side). The link is itself an actor: its snapshot value is the
264
+ connection status (`connecting`, `open`, `reconnecting`, `closed`); its context
265
+ holds `rtt`, `attempts`, `queued` and `peer`. Subscribe to it to show the status.
266
+
267
+ ```js
268
+ // server
269
+ const system = createSystem({ id: 'chess' });
270
+ createActor(lobby, { system, systemID: 'lobby' }).start();
271
+ // browsers are untrusted peers: they may send only what is exported
272
+ serveLinks(system, { server: httpServer, path: '/link', exports: { lobby: 'JOIN LEAVE' } }); // or { port }, { tcp }, or { accept }
273
+
274
+ // client (Node or the web binding); name: the server's system id
275
+ const link = createLink(createSystem(), { url: 'ws://localhost:8080/link', name: 'chess' });
276
+ createActor(player, { input: { lobby: link.get('lobby') } }); // an ActorRef to the remote lobby
277
+ // in the player: sendTo(({ context }) => context.lobby, ({ self }) => ({ type: 'JOIN', player: self }))
278
+ // in the lobby: sendTo(({ event }) => event.player, { type: 'WELCOME' }) — the reply crosses back
279
+ ```
280
+
281
+ Every actor has an `address` (`tinyactors://<system id>/#_scxml_<session>`)
282
+ and `self` in action arguments. An actor reference sent in an event arrives as
283
+ an `ActorRef` (with `send()`) that works as a `sendTo` target. `system.ref(address)`
284
+ creates one. `system.stop()` stops all actors, closes the system's links and
285
+ frees its native memory.
286
+
287
+ Routing is done by the native router (`ta_host`, docs/protocol.md), not in
288
+ JS: every link connection is one router *peer*, and the binding only moves
289
+ frames (link protocol v1: `hello`, `ev`, `err`, `ping`/`pong`). What that
290
+ gives you:
291
+
292
+ - **Policy.** A served peer is untrusted unless `trusted: true` or
293
+ `trust(hello)` says so: it may send only to the `exports` (`['lobby']`,
294
+ `{ lobby: 'JOIN LEAVE' }`, `'*'` for every name and session). Everything
295
+ else, and every forged `origin`, is refused.
296
+ - **No silent drops.** A refused or undeliverable send — unknown name, ended
297
+ session, no route, denied, queue full, expired — raises
298
+ `error.communication` (with the `sendid`) in the sending actor, across any
299
+ number of hops.
300
+ - **Queues and resumption.** While a link is down the router queues for it
301
+ (`maxQueue`, default 1000; `queueTTLMs` to expire them; `maxQueue: 0` to fail
302
+ fast). On the server, a peer that reconnects with the same system id within
303
+ `resumeMs` (default 30 s, on the system's clock: with a `clock` option,
304
+ simulated time) gets what was queued for it, in order.
305
+ - **Relaying.** With `announce: true` a system tells its peers which other
306
+ systems it reaches, and forwards their envelopes (for trusted peers): a
307
+ browser can reach a backend behind its server.
308
+ - **Values.** Between two JS systems values keep their types (`js` profile:
309
+ `Date`, `Map`, `Set`, `BigInt`, cycles, actor refs). With a peer in another
310
+ language they travel as neutral values (JSON plus `{"$ref"}` and
311
+ `{"$bytes"}`; `encodeWire` / `decodeWire`); `profile: 'neutral'` forces that.
312
+ - **Status.** `link.status()` and `server.status(systemID)` report the route:
313
+ state, queued, lag, rtt, sent/received/errors/duplicates.
314
+ - `system.deliver(envelope)` hands an envelope to the router from host code
315
+ (any transport you write yourself starts there).
316
+
317
+ ### Byte streams: TCP, stdio, serial
318
+
319
+ On byte streams the link protocol travels in length-prefixed frames (a 4-byte
320
+ big-endian length, then UTF-8 JSON; docs/protocol.md, "Framing"):
321
+
322
+ ```js
323
+ // TCP
324
+ const served = serveLinks(server, { tcp: { port: 7000 }, exports: ['echo'] }); // served.port
325
+ const link = createLink(client, { tcp: { host: 'db-1', port: 7000 }, name: 'srv' });
326
+
327
+ // any duplex stream: `transport` and `accept` take byte streams as well as WebSocket-like objects
328
+ const child = spawn('node', ['worker.js'], { stdio: ['pipe', 'pipe', 'inherit'] });
329
+ serveLinks(system, { trusted: true, accept: (on) => on({ readable: child.stdout, writable: child.stdin }) });
330
+ // in worker.js (stdout carries the link: log with createSystem({ logger }) to stderr)
331
+ createLink(system, { name: 'parent', transport: () => ({ readable: process.stdin, writable: process.stdout }) });
332
+ ```
333
+
334
+ A byte stream is a Node-style duplex (a `net.Socket`) or a `{ readable,
335
+ writable }` pair. `maxFrame` (default 1 MiB, both functions) is the largest
336
+ frame this side accepts and is announced in its hello. Frames above it are
337
+ skipped unread. An envelope that does not fit the other side's `maxFrame` is
338
+ not sent: its sender gets `error.communication`. `encodeFrame(text)` and
339
+ `new FrameDecoder({ maxFrame }).push(chunk)` (frames out; a refused one as
340
+ `{ reason: 'malformed', length }`) frame streams of your own. C hosts use
341
+ `ta_frame_header` / `ta_frame_read` (`include/tinyactors/frame.h`).
342
+
343
+ ### Store links: actors in PostgreSQL
344
+
345
+ `createStoreLink(system, { query, listen })` connects the system to a
346
+ database of actors (the PostgreSQL extension, bindings/postgres) through any
347
+ PostgreSQL client. The database becomes a peer: actors here and there send to
348
+ each other by address, replies included, and the database can reach the
349
+ browsers on your links (the link tells it which ones).
350
+
351
+ ```js
352
+ const pool = new pg.Pool();
353
+ const client = await pool.connect(); // a connection for LISTEN
354
+ const store = createStoreLink(system, {
355
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
356
+ listen: async (channel, fn) => { client.on('notification', (n) => n.channel === channel && fn(n.payload));
357
+ await client.query(`LISTEN ${channel}`); return () => client.query(`UNLISTEN ${channel}`); },
358
+ });
359
+ await store.ready; // store.id: the database's system id
360
+ sendTo(system.ref(`tinyactors://${store.id}/@ledger`), { type: 'add', amount: 5 });
361
+ ```
362
+
363
+ Envelopes go in with `tinyactors.deliver` (in order, retried until taken;
364
+ the database drops repeats), come out of the outbox with `claim_for` on
365
+ NOTIFY (and every `pollMs`), and errors travel both ways as
366
+ `error.communication`. Values travel as neutral values. `store.flush()`
367
+ waits until everything was handed over; `store.status()` is the route's
368
+ status.
369
+
370
+ ## Supported (xstate v5 subset)
371
+
372
+ `createMachine`, `setup({ actions, guards, delays, actors })`, `createActor`
373
+ (`start`, `stop`, `send`, `getSnapshot`, `subscribe`, `address`, `hibernated`,
374
+ options `input`, `systemID`, `system`, `logger`),
375
+ `createSystem({ id, hibernation, clock, logger, restore, machines })`,
376
+ `system.get()`, `system.ref()`, `system.sendMany()`, `system.hibernate()`,
377
+ `system.reload()`, `system.migrate()`, `system.snapshot()`, `system.boot()`,
378
+ `system.export()`, `system.adopt()`,
379
+ `system.flush()`, `system.stop()`, `fromSCXML`, `compileSystem`, `loadImage`,
380
+ `machine.provide()`, `createLink`, `serveLinks`, `encodeFrame`, `FrameDecoder`, `createMemoryStore`;
381
+ states (`initial`, nested, `parallel`, `final` with `output`, `history`),
382
+ `on` (including `'*'`), `always`, `after`, `entry`/`exit`, `invoke` of child
383
+ machines (`input`, `onDone`), `tags`; actions: functions, named actions with
384
+ `params`, `assign`, `raise` (optionally delayed), `sendTo`, `sendParent`,
385
+ `log`, `cancel`; guards: functions, named guards with `params`, `and`, `or`,
386
+ `not`, `stateIn`. Snapshots: `value`, `context`, `status`, `output`,
387
+ `error`, `matches()`, `hasTag()`.
388
+
389
+ Not supported: promise/callback/observable actors, `spawn`, `emit`,
390
+ `enqueueActions`, `onError`, `can()`, inspection API.
391
+
392
+ Semantics follow SCXML where they differ from xstate: an exception in user
393
+ code raises `error.execution` (the actor keeps running; see
394
+ `snapshot.error`), and external events wait while a macrostep is still
395
+ running.
396
+
397
+ ## Build & test
398
+
399
+ ```sh
400
+ mise run node:test # npm ci, build the addon, node --test, bun test, tsc
401
+ ```