@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 +388 -156
- package/node/index.d.ts +915 -0
- package/node/index.js +44 -0
- package/node/transports.js +60 -0
- package/node/ws.js +152 -0
- package/package.json +22 -17
- package/shared/core.mjs +2966 -0
- package/shared/ecmascript.mjs +670 -0
- package/index.d.ts +0 -1875
- package/index.js +0 -34
- package/lib/actor.js +0 -85
- package/lib/debug/breakpoints.js +0 -349
- package/lib/debug/console.js +0 -149
- package/lib/debug/expressions.js +0 -133
- package/lib/debug/frames.js +0 -119
- package/lib/debug/labels.js +0 -142
- package/lib/debug/macrosteps.js +0 -207
- package/lib/debug/protocol.js +0 -186
- package/lib/debug/sources.js +0 -218
- package/lib/debug/variables.js +0 -265
- package/lib/debug.js +0 -1434
- package/lib/definition.js +0 -139
- package/lib/errors.js +0 -24
- package/lib/events.js +0 -56
- package/lib/image.js +0 -90
- package/lib/loader.js +0 -68
- package/lib/metrics.js +0 -333
- package/lib/native.js +0 -8
- package/lib/otlp.js +0 -332
- package/lib/statechart.js +0 -768
- package/lib/system.js +0 -2183
- package/lib/tracing.js +0 -164
package/README.md
CHANGED
|
@@ -1,169 +1,401 @@
|
|
|
1
|
-
#
|
|
1
|
+
# tinyactors for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
|
|
7
|
-
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @tinyactors/node # or: pnpm add, bun add
|
|
8
14
|
```
|
|
9
15
|
|
|
10
|
-
The
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
35
|
-
|
|
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
|
-
|
|
118
|
+
### Moving an actor to another system
|
|
38
119
|
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
```
|
|
43
|
-
|
|
44
|
-
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
`
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
`
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
`
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
`
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
+
```
|