@tinyactors/node 0.1.0 → 0.3.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.
Files changed (43) hide show
  1. package/README.md +648 -154
  2. package/docs/guide/browser.md +494 -0
  3. package/docs/guide/capacity.md +202 -0
  4. package/docs/guide/charts.md +578 -0
  5. package/docs/guide/hibernation.md +201 -0
  6. package/docs/guide/inspection.md +381 -0
  7. package/docs/guide/io-processors.md +269 -0
  8. package/docs/guide/migration.md +323 -0
  9. package/docs/guide/other-systems.md +275 -0
  10. package/docs/guide/quickjs.md +135 -0
  11. package/docs/guide/services.md +317 -0
  12. package/docs/guide/snapshots.md +186 -0
  13. package/docs/guide/telemetry.md +265 -0
  14. package/docs/guide/testing.md +272 -0
  15. package/docs/values.md +107 -0
  16. package/index.d.ts +1166 -1820
  17. package/index.mjs +6 -0
  18. package/lib/convenience.mjs +162 -0
  19. package/lib/direct.mjs +65 -0
  20. package/package.json +29 -16
  21. package/index.js +0 -34
  22. package/lib/actor.js +0 -85
  23. package/lib/debug/breakpoints.js +0 -349
  24. package/lib/debug/console.js +0 -149
  25. package/lib/debug/expressions.js +0 -133
  26. package/lib/debug/frames.js +0 -119
  27. package/lib/debug/labels.js +0 -142
  28. package/lib/debug/macrosteps.js +0 -207
  29. package/lib/debug/protocol.js +0 -186
  30. package/lib/debug/sources.js +0 -218
  31. package/lib/debug/variables.js +0 -265
  32. package/lib/debug.js +0 -1434
  33. package/lib/definition.js +0 -139
  34. package/lib/errors.js +0 -24
  35. package/lib/events.js +0 -56
  36. package/lib/image.js +0 -90
  37. package/lib/loader.js +0 -68
  38. package/lib/metrics.js +0 -333
  39. package/lib/native.js +0 -8
  40. package/lib/otlp.js +0 -332
  41. package/lib/statechart.js +0 -768
  42. package/lib/system.js +0 -2183
  43. package/lib/tracing.js +0 -164
package/README.md CHANGED
@@ -1,169 +1,663 @@
1
1
  # @tinyactors/node
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
+ Run statecharts as actors in Node.js and Bun.
5
4
 
6
- ```text
7
- npm install @tinyactors/node
5
+ Much of a program's logic is a lifecycle: an order is open, then paying,
6
+ then paid or timed out; a connection is dialing, up, or backing off. Written
7
+ as flags and callbacks, a lifecycle spreads over a codebase, and the states
8
+ it may be in are nowhere written down. A **statechart** writes them down:
9
+ the states, the events that move between them, and what happens on the
10
+ way. This package runs statecharts written in
11
+ [SCXML](https://www.w3.org/TR/scxml/), the W3C's XML language for them,
12
+ with JavaScript for their data and expressions.
13
+
14
+ Each running statechart is an **actor**: it has its own data and a queue
15
+ of events, and it talks to the world only by sending and receiving events.
16
+ A **host** runs many of them, from a handful to millions, on your
17
+ program's event loop. The host does no I/O of its own. When an actor sends
18
+ something out (a payment request, a log line, an email), your handler gets
19
+ it, does the I/O, and answers with an event. So the logic stays in the
20
+ charts, testable on a simulated clock, and the I/O stays in your code.
21
+
22
+ Use it when your program keeps many long-lived things that each have a
23
+ lifecycle (orders, sessions, devices, workflows), when you want timeouts
24
+ and retries written as states rather than timers, or when the same logic
25
+ must run in tests without the network.
26
+
27
+ This README describes the package as it is built from `main`. The last
28
+ version on npm, 0.2.0, is an earlier binding with another API.
29
+
30
+ ## Install
31
+
32
+ ```sh
33
+ npm install @tinyactors/node # or: pnpm add, bun add
8
34
  ```
9
35
 
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).
36
+ It runs on Node.js 22.3 or later and on Bun (tested on 1.4), on macOS
37
+ (arm64, x64) and Linux (x64, arm64; glibc or musl). Nothing compiles on
38
+ install: the addon is prebuilt, one per platform, in
39
+ `@tinyactors/node-darwin-arm64`, `-darwin-x64`, `-linux-x64` and
40
+ `-linux-arm64`, which the main package lists as optional dependencies, so
41
+ the package manager installs only the one that matches. A Linux addon
42
+ links no C library, so one file serves glibc and musl. The macOS addons
43
+ are cross-built from Linux and checked by their symbols; no Mac has run
44
+ them yet. An install that left out optional dependencies
45
+ (`--no-optional`, `--omit=optional`) fails at import, naming the package
46
+ it needs.
47
+
48
+ For a browser, or a platform with no addon (Windows), the same API is
49
+ `@tinyactors/wasm`, core compiled to WebAssembly: see
50
+ [In the browser](docs/guide/browser.md), which says what differs.
51
+
52
+ Development builds of `main` are published under the `next` dist-tag
53
+ (`npm install @tinyactors/node@next`), versioned
54
+ `<next minor>-dev.<date>.<n>.g<commit>`. Releases, their tarballs and
55
+ `SHA256SUMS` are on
56
+ [tinyactors-dev/tinyactors-napi](https://github.com/tinyactors-dev/tinyactors-napi/releases).
57
+
58
+ ## A first program
59
+
60
+ An order collects items, then asks a payment service to charge the total,
61
+ and is paid when the service answers. Save this as `order.mjs` and run it
62
+ with `node order.mjs` or `bun order.mjs`:
14
63
 
15
64
  ```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
- }
65
+ import { compileCharts, Host } from '@tinyactors/node';
66
+
67
+ // 1. The chart: the order's states and what moves between them.
68
+ const chart = `
69
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
70
+ datamodel="ecmascript" name="order" initial="open">
71
+ <datamodel>
72
+ <data id="total" expr="0"/>
73
+ </datamodel>
74
+ <state id="open">
75
+ <transition event="add">
76
+ <assign location="total" expr="total + _event.data.price"/>
77
+ </transition>
78
+ <transition event="checkout" target="paying"/>
79
+ </state>
80
+ <state id="paying">
81
+ <onentry>
82
+ <send type="urn:payments" event="charge" target="card">
83
+ <param name="amount" expr="total"/>
84
+ </send>
85
+ </onentry>
86
+ <transition event="charged" target="paid"/>
87
+ </state>
88
+ <final id="paid">
89
+ <onentry><log label="order" expr="'paid ' + total"/></onentry>
90
+ </final>
91
+ </scxml>`;
92
+
93
+ // 2. Compile it into an image the host can load.
94
+ const compiled = compileCharts([{ name: 'order.scxml', text: chart }]);
95
+
96
+ // 3. A host, with a handler for what the chart sends to urn:payments.
97
+ const host = new Host(
98
+ { systemID: 'shop', ioProcessors: [{ type: 'urn:payments' }] },
99
+ {
100
+ ioProcessors: {
101
+ 'urn:payments': (host, send) => {
102
+ console.log(`charging ${send.data.amount} to ${send.target}`);
103
+ send.answer('charged');
104
+ },
105
+ },
106
+ log: (host, entry) => console.log(`${entry.label}: ${entry.text}`),
107
+ },
108
+ );
109
+ host.addImage(compiled.image);
110
+ compiled.close();
30
111
 
31
- main();
112
+ // 4. An actor of the chart, and three events for it.
113
+ const order = host.spawn(host.chart('order'));
114
+ host.send(order, 'add', { price: 4 });
115
+ host.send(order, 'add', { price: 7 });
116
+ host.send(order, 'checkout');
117
+
118
+ // 5. Let it run, then stop.
119
+ await host.idle();
120
+ host.close();
121
+ ```
122
+
123
+ It prints:
124
+
125
+ ```output
126
+ charging 11 to card
127
+ order: paid 11
32
128
  ```
33
129
 
34
- `index.d.ts` describes the whole API. The package is 0.x: its API changes
35
- in minor versions.
130
+ What happened, step by step:
131
+
132
+ 1. **The chart** has three states. In `open`, each `add` event adds its
133
+ price to the variable `total`; `checkout` moves to `paying`. Entering
134
+ `paying` sends a `charge` event to `urn:payments`, which is not
135
+ another actor but something outside the host. The answer `charged`
136
+ moves to `paid`, a final state, which logs the total.
137
+ 2. **`compileCharts`** checks the chart and compiles it. A mistake in the
138
+ XML, an unknown state id or a malformed attribute throws a
139
+ `CompileError` here, before anything runs. JavaScript that does not
140
+ parse is a warning in `compiled.diagnostics` (SCXML makes it an
141
+ `error.execution` when it runs), and an error with
142
+ `compileCharts(sources, undefined, { warningsAsErrors: true })`.
143
+ 3. **`new Host(config, options)`** makes a host. The config names this
144
+ system (`systemID`) and the I/O processors its charts may send to; the
145
+ options hold your handlers. The `urn:payments` handler gets each send
146
+ to that type: its data, its target, and `answer()`, which sends an
147
+ event back to the actor that sent it.
148
+ 4. **`host.spawn`** starts an actor of the chart and returns its session
149
+ id, a `bigint`. `host.send` puts an event in its queue.
150
+ 5. **`await host.idle()`** waits until the host has nothing left to do.
151
+ The actor runs on the event loop on its own; `idle()` only watches.
152
+ `host.close()` frees the host.
153
+
154
+ ## Concepts
155
+
156
+ Read these in order the first time. Each builds on the one before.
157
+
158
+ ### Charts
159
+
160
+ A chart is an SCXML document. Its parts, from the outside in:
161
+
162
+ - **`<scxml>`** names the chart (`name`), its first state (`initial`) and
163
+ its language for data and expressions. Write `datamodel="ecmascript"`,
164
+ JavaScript, on every chart. A chart without the attribute gets SCXML's
165
+ null datamodel, which evaluates no expression and says nothing about it:
166
+ its `<log>`s and `<data>` do nothing. Another value is refused when the
167
+ image is added (`host.addImage` throws `TA_ERROR_INVALID`).
168
+ - **`<state id>`** is a state the actor can be in. States nest (a
169
+ compound state has children, one of them active), and `<parallel>`
170
+ holds regions that are all active at once. **`<final>`** ends the
171
+ actor.
172
+ - **`<transition event cond target>`** leaves the state when an event
173
+ whose name matches `event` arrives and the expression `cond` is true.
174
+ Without `target` it runs its actions and stays.
175
+ - **Actions** run on a transition and in `<onentry>` and `<onexit>`:
176
+ `<assign>`, `<script>`, `<log>`, `<send>`, `<raise>`, `<cancel>`,
177
+ `<if>` and `<foreach>`.
178
+ - **`<datamodel>`** declares the actor's variables, one `<data id expr>`
179
+ each. Every expression in the chart sees them as plain variables, and
180
+ sees the event being handled as `_event` (`_event.name`, `_event.data`).
181
+
182
+ An event's name is matched by prefix, word by word: `event="error"` and
183
+ `event="error.*"` match `error.execution` and `error.communication`;
184
+ `event="a b"` matches either name; `event="*"` matches any event. An
185
+ event no transition matches is dropped.
186
+
187
+ The prefix rule also matches an answer whose name starts with the
188
+ request's: `event="join"` takes `join.refused` too. A chart that asks a
189
+ peer again on `join`, and a peer that answers with `join.refused`, then
190
+ answer each other for ever, and `await host.idle()` never resolves. Name
191
+ an answer so that it does not extend the request (`refused.join`), and
192
+ see [Inspecting a host](docs/guide/inspection.md#two-actors-that-never-rest)
193
+ for how such a loop shows in the host's counters.
194
+
195
+ [Writing charts](docs/guide/charts.md) covers the JavaScript a chart may
196
+ hold, `<script>`, XML data, several charts in one image (and
197
+ `host.addCharts`, `host.spawnChart` and `directoryResolver`, which save
198
+ the steps), and `<invoke>`.
36
199
 
37
- ## Working on it in the repository
200
+ ### Starting an actor with data
38
201
 
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:
202
+ `spawn`'s `params` set the new actor's variables: each key that names a
203
+ top-level `<data>` replaces that variable's initial value, keys that name
204
+ no `<data>` are left out, and the variables you do not name keep the
205
+ chart's `expr`.
41
206
 
42
- ```text
43
- mise run build
44
- mise run test
207
+ ```js
208
+ import { compileCharts, Host } from '@tinyactors/node';
209
+
210
+ const compiled = compileCharts([{ name: 'greeter.scxml', text: `
211
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
212
+ datamodel="ecmascript" name="greeter" initial="ready">
213
+ <datamodel>
214
+ <data id="greeting" expr="'Hello'"/>
215
+ <data id="who" expr="'world'"/>
216
+ </datamodel>
217
+ <state id="ready">
218
+ <onentry><log expr="greeting + ', ' + who + '!'"/></onentry>
219
+ </state>
220
+ </scxml>` }]);
221
+
222
+ const host = new Host({ systemID: 'demo' }, { log: (host, entry) => console.log(entry.text) });
223
+ host.addImage(compiled.image);
224
+ compiled.close();
225
+
226
+ host.spawn(host.chart('greeter'));
227
+ host.spawn(host.chart('greeter'), { params: { who: 'Ada' } });
228
+ host.spawn(host.chart('greeter'), { params: { greeting: 'Hi', who: 'Bob', mood: 'ignored' } });
229
+ await host.idle();
230
+ host.close();
45
231
  ```
46
232
 
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).
233
+ ```output
234
+ Hello, world!
235
+ Hello, Ada!
236
+ Hi, Bob!
237
+ ```
238
+
239
+ ### The host and its event loop
240
+
241
+ A host holds actors and runs them on your program's event loop. There is
242
+ no `run()` to call. An input (`spawn`, `send`, `terminate`) is taken at
243
+ once (the event is in the actor's queue when `send` returns, or the call
244
+ throws), but nothing runs yet: it schedules a turn with `setImmediate`,
245
+ and in its turns the host runs
246
+ every actor that has an event, calls your handlers with what the actors
247
+ sent out, and runs again until nothing is left. A turn does a bounded
248
+ amount of work and then yields, so a busy host never starves your I/O.
249
+
250
+ `await host.idle()` resolves at the next turn that finds nothing to do
251
+ while no promise one of your handlers returned is pending (a promise a
252
+ handler starts and does not return is not waited for). It is for tests, scripts and an orderly shutdown; a server never needs to
253
+ call it. A handler may call the host (send an event, spawn an actor): the
254
+ input applies at once, and the actors run in the same or a later turn.
255
+
256
+ Each `addImage` makes a **segment**: the host's memory for that image's
257
+ actors, numbered from 0, which `addImage` returns. A host runs many
258
+ segments as one; you need the number for `boot` and see it in the host's
259
+ statistics.
260
+
261
+ A host also keeps time. A delayed `<send>` or a timeout is a deadline,
262
+ and an idle host arms one `setTimeout` for its next one. That timer keeps
263
+ the process alive while the host is open, as any `setTimeout` does, and
264
+ it is the only thing the host keeps the process alive with: an open host
265
+ with no deadline lets the process exit, even with actors that wait for an
266
+ answer (below, "Before you use it"). `host.close()` clears the timer,
267
+ frees the host, and drops every handler that was still waiting.
268
+
269
+ ### Actors, sessions and addresses
270
+
271
+ `spawn` returns the actor's **session**, a `bigint` unique in its host.
272
+ Inputs take it back: `host.send(session, event, data)`,
273
+ `host.terminate(session)`. They also take a number that is a safe
274
+ integer, since that is what a database or JSON gives back. The calls and
275
+ views return sessions as `bigint`s (`console.log` prints `1n`, and
276
+ `JSON.stringify` refuses one: convert with `String()` or `Number()`
277
+ yourself), while the results of the typed methods
278
+ ([Inspecting a host](docs/guide/inspection.md)) hold them as numbers. So
279
+ compare with `Number(session) === listed`, never `===` across the two;
280
+ either kind may be passed back to an input.
281
+
282
+ ```js
283
+ import { Host } from '@tinyactors/node';
284
+
285
+ const host = new Host({ systemID: 'demo' });
286
+ host.addCharts({ 'idle.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
287
+ datamodel="ecmascript" name="idle"><state id="s"/></scxml>` });
288
+ const session = host.spawnChart('idle', { name: 'first' });
289
+ const { sessions } = await host.actorList();
290
+ console.log(typeof session, typeof sessions[0]);
291
+ console.log(sessions.includes(Number(session)), sessions.map(BigInt).includes(session));
292
+ const byKey = new Map([[String(session), 'kept under its text']]);
293
+ console.log(byKey.get(String(sessions[0])), host.actorByName('first') === session);
294
+ host.close();
295
+ ```
296
+
297
+ ```output
298
+ bigint number
299
+ true true
300
+ kept under its text true
301
+ ```
302
+
303
+ `sessions.includes(session)` would be `false` (TypeScript refuses it),
304
+ and a `Map` keyed by the `bigint` misses the number: key it by
305
+ `String(session)`, which is the same for both kinds.
306
+
307
+ An actor may also have a **name**, given at spawn, and
308
+ `host.actorByName(name)` finds it. An actor that reaches a `<final>`
309
+ state, or is terminated, ends: its session is refused from then on with
310
+ `TA_ERROR_STALE`, and its name finds nothing. The events still in its
311
+ queue when it ends are dropped, as SCXML ends a session at its top-level
312
+ `<final>`: a `host.send` that returned before the end is never handled,
313
+ and nothing tells the application. A chart whose events stand for
314
+ requests your program holds (an HTTP response, a promise) tells your
315
+ program from its `<final>` first:
316
+ [I/O processors](docs/guide/io-processors.md#when-the-sender-ends) has the
317
+ pattern.
318
+
319
+ Actors find each other by **address**. Every system has its `systemID`,
320
+ and an actor's address is `tinyactors://<systemID>/#_scxml_<session>`, or
321
+ `tinyactors://<systemID>/@<name>` for a named one. A chart sends to
322
+ another actor with `<send target="tinyactors://shop/@pong" event="ping"/>`,
323
+ and the receiver answers to `_event.origin`. The `Address` class reads
324
+ and makes them:
325
+
326
+ ```js
327
+ import { compileCharts, Host, Address } from '@tinyactors/node';
328
+
329
+ const pong = `
330
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
331
+ datamodel="ecmascript" name="pong" initial="waiting">
332
+ <state id="waiting">
333
+ <transition event="ping">
334
+ <log expr="'pong got ' + _event.name"/>
335
+ <send event="pong" targetexpr="_event.origin"/>
336
+ </transition>
337
+ </state>
338
+ </scxml>`;
339
+ const ping = `
340
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
341
+ datamodel="ecmascript" name="ping" initial="asking">
342
+ <state id="asking">
343
+ <onentry><send event="ping" target="tinyactors://demo/@pong"/></onentry>
344
+ <transition event="pong" target="done"><log expr="'ping got ' + _event.name"/></transition>
345
+ </state>
346
+ <final id="done"/>
347
+ </scxml>`;
348
+
349
+ const compiled = compileCharts([{ name: 'ping.scxml', text: ping }, { name: 'pong.scxml', text: pong }]);
350
+ const host = new Host({ systemID: 'demo' }, { log: (host, entry) => console.log(entry.text) });
351
+ host.addImage(compiled.image);
352
+ compiled.close();
353
+
354
+ const pongSession = host.spawn(host.chart('pong'), { name: 'pong' });
355
+ const pingSession = host.spawn(host.chart('ping'));
356
+ await host.idle();
357
+
358
+ console.log(Address.fromSession('demo', pongSession).text);
359
+ console.log(new Address('tinyactors://demo/@pong').name);
360
+ console.log(host.actorByName('pong') === pongSession);
361
+ host.terminate(pongSession);
362
+ await host.idle();
363
+ console.log(host.actorByName('pong'), pingSession);
364
+ host.close();
365
+ ```
366
+
367
+ ```output
368
+ pong got ping
369
+ ping got pong
370
+ tinyactors://demo/#_scxml_1
371
+ pong
372
+ true
373
+ undefined 2n
374
+ ```
375
+
376
+ ### Effects and handlers
377
+
378
+ What an actor does toward the outside is an **effect**, and each kind has
379
+ a handler you give the host in its options:
380
+
381
+ | The chart does | Your handler | Guide |
382
+ |---|---|---|
383
+ | `<send type="urn:x">` to an I/O processor the config lists | `ioProcessors: { 'urn:x': (host, send) => ... }` | [I/O processors](docs/guide/io-processors.md) |
384
+ | `<send>` to an actor of another system | `transport: (host, send) => ...` | [Other systems](docs/guide/other-systems.md) |
385
+ | `<invoke type="urn:y">` of a service you run | `services: { 'urn:y': (host, invocation) => service }` | [Invoked services](docs/guide/services.md) |
386
+ | `<log>` | `log: (host, entry) => ...` | this README |
387
+ | spans, logs and metrics as OpenTelemetry (OTLP) | `telemetry: (host, signal, data) => ...` | [Telemetry](docs/guide/telemetry.md) |
388
+ | an event for an actor you took out of memory | `wake: (host, session, migration) => ...` | [Hibernation](docs/guide/hibernation.md) |
389
+
390
+ A send to an I/O processor the config lists but no handler serves is
391
+ failed: the sender gets the event `error.communication`, so a chart can
392
+ always react. A send to a type the config does not list at all raises
393
+ `error.execution` in the chart. `<log>` lines without
394
+ a `log` handler are dropped.
395
+
396
+ **A handler's argument is a view, valid while the handler runs.** The
397
+ `send` an I/O processor gets reads each field from the host's memory when
398
+ you first read it. After the handler returns, the host moves on and the
399
+ view is stale: reading it then throws `TA_ERROR_STALE`. Copy out what you
400
+ keep (`const { data } = send`). A handler that returns a promise (an
401
+ `async` function) is the exception: the host fills its view with every
402
+ field before moving on, so it may `await` and answer later.
403
+
404
+ ### Values
405
+
406
+ What crosses between your program and a chart (event data, spawn params,
407
+ results) is a value of one table: `undefined`, `null`, booleans, numbers,
408
+ `bigint`s up to 64 bits, strings, `Uint8Array`s, arrays and plain
409
+ objects. A function, a `Map`, a `Date` or a class's instance is refused
410
+ with `TA_ERROR_UNSUPPORTED`, and a value is copied when it crosses, so a
411
+ chart never holds your object, and what a chart hands you (`send.data`,
412
+ `invocation.data`) is made with your realm's constructors: its arrays are
413
+ `instanceof Array`, and `assert.deepStrictEqual` compares it with a
414
+ literal. `undefined` and `null` stay apart; a
415
+ whole number past 2^53 comes back as a `bigint`.
416
+
417
+ `encode(value)` and `decode(bytes)` give that table as CBOR bytes, the
418
+ form a value takes when you store or send it:
419
+
420
+ ```js
421
+ import { encode, decode } from '@tinyactors/node';
422
+
423
+ const bytes = encode({ sku: 'tea', qty: 2, big: 2n ** 60n, gone: undefined });
424
+ const value = decode(bytes);
425
+ console.log(bytes.length, 'bytes');
426
+ console.log(value.sku, value.qty, value.big, 'gone' in value, value.gone);
427
+ ```
428
+
429
+ ```output
430
+ 33 bytes
431
+ tea 2 1152921504606846976n true undefined
432
+ ```
433
+
434
+ `encode` also writes an `Address` (from "Actors, sessions and
435
+ addresses"), as CBOR's tag 32, and `decode` reads one back as an
436
+ `Address`: that is how a transport's message keeps its addresses
437
+ ([Other systems](docs/guide/other-systems.md)).
438
+ [docs/values.md](docs/values.md) has every row of the table and every
439
+ refusal.
440
+
441
+ ### Time and the SimulatedClock
442
+
443
+ Time in this API is milliseconds, with two exceptions that the host's
444
+ config and the trace methods inherit from core: `telemetry.flushInterval`
445
+ counts the host's clock ticks, and `traceWatch` takes `seconds`. In a
446
+ chart, `<send event="timeout" delay="30s"/>` sends an event to the actor
447
+ itself 30 seconds later, and `<cancel sendid>` takes it back. A delay is
448
+ written in seconds or milliseconds (`30s`, `1.5s`, `500ms`), and any
449
+ other form (`10`, `1m`) is a compile error. `delayexpr` computes one, and
450
+ must give such a string: `delayexpr="timeoutMs + 'ms'"`, not
451
+ `delayexpr="timeoutMs"`. A number, or a string without its unit, raises
452
+ `error.execution` with no `_event.data` (the delay is the host's check,
453
+ not code that threw, so there is no reason to give), and nothing is sent.
454
+ By default the host reads the runtime's
455
+ clock. A test gives it a `SimulatedClock` instead, which moves only when
456
+ you move it, so a test of a 30-second timeout takes no time:
457
+
458
+ ```js
459
+ import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
460
+
461
+ const compiled = compileCharts([{ name: 'door.scxml', text: `
462
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
463
+ datamodel="ecmascript" name="door" initial="open">
464
+ <state id="open">
465
+ <onentry><send event="close" delay="30s"/></onentry>
466
+ <transition event="close" target="closed"/>
467
+ </state>
468
+ <final id="closed"><onentry><log expr="'closed'"/></onentry></final>
469
+ </scxml>` }]);
470
+
471
+ const clock = new SimulatedClock();
472
+ const host = new Host({ systemID: 'demo' }, { clock, log: (host, entry) => console.log(entry.text, 'at', clock.now) });
473
+ host.addImage(compiled.image);
474
+ compiled.close();
475
+
476
+ host.spawn(host.chart('door'));
477
+ await host.idle();
478
+ console.log('next deadline in', host.nextDeadline, 'ms');
479
+ clock.increment(29_999);
480
+ await host.idle();
481
+ clock.increment(1);
482
+ await host.idle();
483
+ host.close();
484
+ ```
485
+
486
+ ```output
487
+ next deadline in 30000 ms
488
+ closed at 30000
489
+ ```
490
+
491
+ `host.now()` reads the host's clock in milliseconds (the simulated
492
+ clock's time, or the runtime's), the clock its deadlines and snapshots
493
+ use. `clock.increment(ms)` moves the clock and schedules a turn on every host
494
+ made with it; `await host.idle()` then sees what ran. One increment past
495
+ several deadlines does not replay each of them: what is due runs once, at
496
+ the new time, and a delay it starts counts from there. Step the clock one
497
+ deadline at a time to see each. An input runs at the host's next turn, so
498
+ one given just before an `increment` is handled at the new time: `await
499
+ host.idle()` between them when it should run first. A host on a
500
+ `SimulatedClock` arms no timer.
501
+
502
+ On the runtime's clock a delay counts from the step that armed it, which
503
+ runs a little after its timer fired (the timer's and the turn's latency).
504
+ So a chart that re-arms `<send event="tick" delay="20ms"/>` at each tick
505
+ falls behind by that latency every tick: 24 ms after 40 ticks alone, 136
506
+ ms beside a CPU-bound job, in the repository's job-scheduler example. A
507
+ chart cannot read the host's clock, so a job that must keep its cadence
508
+ is given its schedule as absolute times by your program, and asks your
509
+ program for the time (an I/O processor) before it arms each delay. [Testing your charts](docs/guide/testing.md)
510
+ has more.
511
+
512
+ ### Errors
513
+
514
+ Errors surface in four places:
515
+
516
+ - **At compile time,** `compileCharts` throws a `CompileError` whose
517
+ message is the first error as `file:line:column: error: message`, and
518
+ whose `diagnostics` holds them all.
519
+ - **At a call,** the host throws a `TinyactorsError` for what it refuses
520
+ at once: a chart it does not have, a session that ended or never was, a
521
+ config it does not take. Branch on `error.status` (`'TA_ERROR_STALE'`,
522
+ `'TA_ERROR_INVALID'`, ...); the message is for people. A refused config
523
+ also has `error.path`, the key it is about (`system.maxActors`), and
524
+ `error.reason`. Arguments of the
525
+ wrong JavaScript type throw a `TypeError`.
526
+ - **In a chart,** an expression that throws, or an `<assign>` to a
527
+ variable the chart does not declare, raises the event `error.execution`
528
+ for that actor, and a send that cannot be delivered raises
529
+ `error.communication`. These are events, not exceptions. A failed action
530
+ also stops the rest of its block: the actions after it in the same
531
+ `<onentry>`, `<onexit>` or transition do not run. The actor goes on,
532
+ and a transition on `error` handles both; without one the error event
533
+ is dropped like any event no transition matches. When the chart's code
534
+ failed, `_event.data` says why: `{ reason, message }`, `reason`
535
+ `'exception'` (code that threw; `message` is its text, as `String(e)`
536
+ gives it, such as `'Error: boom'`), `'fuel'` (it ran past QuickJS's
537
+ `maxOps`) or `'memory'` (past QuickJS's `memoryLimit`); a failure the
538
+ host decides (an unknown `<send>` type) has no data. To learn which
539
+ action failed, turn on [telemetry](docs/guide/telemetry.md), whose spans
540
+ and log records mark the failed action.
541
+ - **In your handlers,** an error a handler throws is reported after its
542
+ turn: it rejects a waiting `host.idle()`, or, with none waiting, is
543
+ thrown as an uncaught exception (below).
544
+
545
+ ```js
546
+ import { compileCharts, CompileError, Host, TinyactorsError } from '@tinyactors/node';
547
+
548
+ try {
549
+ compileCharts([{ name: 'bad.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="bad">
550
+ <state id="s"><transition event="go" target="nowhere"/></state>
551
+ </scxml>` }]);
552
+ } catch (error) {
553
+ if (!(error instanceof CompileError)) throw error;
554
+ console.log(error.message);
555
+ }
556
+
557
+ const host = new Host({ systemID: 'demo' });
558
+ try {
559
+ host.chart('missing');
560
+ } catch (error) {
561
+ if (!(error instanceof TinyactorsError)) throw error;
562
+ console.log(error.status, '-', error.message);
563
+ }
564
+ host.close();
565
+ ```
566
+
567
+ ```output
568
+ bad.scxml:2:17: error: unknown state id 'nowhere'
569
+ TA_ERROR_INVALID - the host has no chart of that name
570
+ ```
571
+
572
+ ## Before you use it
573
+
574
+ - **Chart code is trusted code.** On the native datamodel (the default)
575
+ a chart's expressions and scripts run in `node:vm` contexts of your own
576
+ engine, and a `vm` context is not a security boundary. Run charts you do
577
+ not trust on quickjs, the sandbox: `new Host(config, { datamodel:
578
+ 'quickjs', quickjs: { maxOps, memoryLimit } })`
579
+ ([the quickjs sandbox](docs/guide/quickjs.md)).
580
+ - **An open host with a pending deadline keeps the process alive, and
581
+ only then** (a delayed `<send>`, a timeout, the telemetry flush): the host arms one
582
+ timer at its next deadline, as `setTimeout` does, and `host.close()`
583
+ clears it. Nothing else holds the event loop: an open host with no
584
+ deadline lets the process exit, its actors still waiting, and so does an
585
+ actor that waits for an answer from a handler whose promise has no I/O
586
+ behind it. Give a chart that waits for an answer a timeout of its own,
587
+ and keep the process alive with your server, socket or timer.
588
+ - **A handler's error ends the process by default.** An error thrown by
589
+ a handler (an I/O processor's, the log handler, the result handler of
590
+ a typed method, one of the host's queries in
591
+ [Inspecting a host](docs/guide/inspection.md))
592
+ rejects a waiting `host.idle()`; with none waiting it is thrown from the
593
+ host's turn as an uncaught exception, and a handler's promise that
594
+ rejects is an unhandled rejection, as is a typed method's promise
595
+ (`await host.actorState(...)`) that rejects with no `catch`. Either
596
+ ends a Node.js or Bun process unless the application handles
597
+ `uncaughtException` and `unhandledRejection`. Only a turn's first error is reported; the others
598
+ of that turn are lost.
599
+ - **`using host = new Host(...)` needs a runtime that parses `using`:**
600
+ Bun 1.4 does, Node.js 22 does not. `Symbol.dispose` and
601
+ `Symbol.asyncDispose` call `close()`, which works everywhere.
602
+ - **A `<script>` that declares top-level names gives each session a
603
+ context of its own.** A chart whose scripts declare `var` or `function`,
604
+ or whose chart-level scripts declare `let`, `const` or `class`, at their
605
+ top level runs each of its sessions
606
+ in a `vm` context of its own (about 143 KB a session on Node.js, 60 KB
607
+ on Bun), so the script's functions close over its own variables. A
608
+ chart that declares nothing shares one context per host: declare the
609
+ function as a `<data>` and assign it in the script
610
+ (`<data id="price"/>`, `price = (sku) => ...`)
611
+ ([Writing charts](docs/guide/charts.md#scripts)).
612
+ - **A chart whose chart-level scripts declare with `let`, `const` or
613
+ `class` keeps its sessions resident** (in a transition's script they
614
+ are the script's own, each run). Hibernation, migration and snapshots refuse its
615
+ sessions (`TA_ERROR_UNSUPPORTED`): a new context cannot be given those
616
+ bindings back. Declare with `var` and `function`, or hold the values in
617
+ `<data>`, for a chart whose sessions should hibernate.
618
+ - **The charts of a host share the builtins of its shared context.** On
619
+ the native datamodel the charts that declare nothing run in one `vm`
620
+ context per host, so a chart that changes a builtin (`Math.random = ...`,
621
+ `Array.prototype.sum = ...`) changes it for the host's other charts
622
+ there; its sessions' own variables stay apart. On quickjs the same holds,
623
+ unless `quickjs: { realm: 'isolated' }` gives each session a context of
624
+ its own ([the quickjs sandbox](docs/guide/quickjs.md#realms)).
625
+
626
+ ## Guides
627
+
628
+ One per feature, each with complete examples that run as written. They
629
+ are in the package too, under `docs/guide/` in
630
+ `node_modules/@tinyactors/node`, so these links work after an install:
631
+
632
+ - [Writing charts](docs/guide/charts.md): JavaScript in charts, scripts,
633
+ XML data, several charts, `<invoke>` of a chart, systems and `boot`.
634
+ - [I/O processors](docs/guide/io-processors.md): your code as a chart's
635
+ output: answering, failing, answering later.
636
+ - [Invoked services](docs/guide/services.md): long-running things a chart
637
+ starts and stops, such as a connection or a subprocess.
638
+ - [Inspecting a host](docs/guide/inspection.md): an actor's state and
639
+ variables, listing actors, the host's counters.
640
+ - [Telemetry](docs/guide/telemetry.md): traces, logs and metrics as
641
+ OpenTelemetry, and trace context across your services.
642
+ - [Hibernation](docs/guide/hibernation.md): millions of actors, most of
643
+ them in your database.
644
+ - [Migration](docs/guide/migration.md): moving running actors to a new
645
+ version of their chart.
646
+ - [Snapshots](docs/guide/snapshots.md): the whole host as one blob, and a
647
+ host restored from it.
648
+ - [Other systems](docs/guide/other-systems.md): actors of two hosts
649
+ talking through your transport, and SCXML's BasicHTTP.
650
+ - [The quickjs sandbox](docs/guide/quickjs.md): charts you do not trust.
651
+ - [Capacity and memory](docs/guide/capacity.md): sizing a host, how it
652
+ grows, and what an actor costs.
653
+ - [Testing your charts](docs/guide/testing.md): a simulated clock,
654
+ `idle()`, and asserting on an actor's state.
655
+ - [In the browser](docs/guide/browser.md): `@tinyactors/wasm`, the same
656
+ API in a page or a Worker: loading, the CSP, IndexedDB as the store,
657
+ liveness, memory, and what differs.
658
+
659
+ The reference is the doc comment of each export in
660
+ [index.d.ts](index.d.ts), which an editor shows on hover. In TypeScript
661
+ the types need the `es2022` lib and a `URL` (the `dom` lib or
662
+ @types/node); they declare `Symbol.dispose` and `Disposable` themselves,
663
+ so no `esnext` lib is needed.