@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.
- package/README.md +648 -154
- package/docs/guide/browser.md +494 -0
- package/docs/guide/capacity.md +202 -0
- package/docs/guide/charts.md +578 -0
- package/docs/guide/hibernation.md +201 -0
- package/docs/guide/inspection.md +381 -0
- package/docs/guide/io-processors.md +269 -0
- package/docs/guide/migration.md +323 -0
- package/docs/guide/other-systems.md +275 -0
- package/docs/guide/quickjs.md +135 -0
- package/docs/guide/services.md +317 -0
- package/docs/guide/snapshots.md +186 -0
- package/docs/guide/telemetry.md +265 -0
- package/docs/guide/testing.md +272 -0
- package/docs/values.md +107 -0
- package/index.d.ts +1166 -1820
- package/index.mjs +6 -0
- package/lib/convenience.mjs +162 -0
- package/lib/direct.mjs +65 -0
- package/package.json +29 -16
- 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
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Hibernation
|
|
2
|
+
|
|
3
|
+
Most actors spend most of their time waiting: an order waits for a
|
|
4
|
+
payment, a session for its user, a device for its next reading. Kept in
|
|
5
|
+
memory, a million waiting actors cost a million actors' memory.
|
|
6
|
+
Hibernation takes the cold ones out: each becomes a **blob**, a `Buffer`
|
|
7
|
+
you keep in your store, and the host asks for it back when the actor has
|
|
8
|
+
work. The host does no I/O, so where the blobs live (a database, files, a
|
|
9
|
+
cache) is your choice and your code.
|
|
10
|
+
|
|
11
|
+
Three calls and one handler do it:
|
|
12
|
+
|
|
13
|
+
- **`host.sweep(maxScan, limit)`** returns at most `limit` sessions that
|
|
14
|
+
have not run since the previous sweep and can be hibernated now,
|
|
15
|
+
looking at no more than `maxScan` actors. Calling it regularly is what
|
|
16
|
+
makes "not run since the previous sweep" mean cold: the first sweep
|
|
17
|
+
after an actor ran skips it.
|
|
18
|
+
- **`host.hibernate(session)`** takes the actor out of memory and returns
|
|
19
|
+
its blob, for you to store.
|
|
20
|
+
- **`wake: (host, session, migration) => ...`**, a handler in the host's
|
|
21
|
+
options, is called when a hibernated actor has work: an event came for
|
|
22
|
+
it, or one of its delayed sends fell due (`migration` is `undefined`
|
|
23
|
+
then; a [migration](migration.md) may ask too). Load the blob and call
|
|
24
|
+
- **`host.wake(session, blob)`**, then or later. Its events have waited
|
|
25
|
+
in its queue, and run at the next turn.
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { compileCharts, Host, TinyactorsError } from '@tinyactors/node';
|
|
29
|
+
|
|
30
|
+
const compiled = compileCharts([{ name: 'counter.scxml', text: `
|
|
31
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
32
|
+
datamodel="ecmascript" name="counter" initial="counting">
|
|
33
|
+
<datamodel><data id="n" expr="0"/></datamodel>
|
|
34
|
+
<state id="counting">
|
|
35
|
+
<transition event="add">
|
|
36
|
+
<assign location="n" expr="n + _event.data"/>
|
|
37
|
+
<log expr="'counter ' + _sessionid + ' is at ' + n"/>
|
|
38
|
+
</transition>
|
|
39
|
+
</state>
|
|
40
|
+
</scxml>` }]);
|
|
41
|
+
|
|
42
|
+
const store = new Map(); // your database: session -> blob
|
|
43
|
+
|
|
44
|
+
const host = new Host({ systemID: 'demo' }, {
|
|
45
|
+
wake: (host, session) => {
|
|
46
|
+
console.log(`waking ${session}`);
|
|
47
|
+
host.wake(session, store.get(session));
|
|
48
|
+
store.delete(session);
|
|
49
|
+
},
|
|
50
|
+
log: (host, entry) => console.log(entry.text),
|
|
51
|
+
});
|
|
52
|
+
host.addImage(compiled.image);
|
|
53
|
+
compiled.close();
|
|
54
|
+
|
|
55
|
+
function evict(host) {
|
|
56
|
+
for (const session of host.sweep(1 << 20, 1024)) {
|
|
57
|
+
try {
|
|
58
|
+
store.set(session, host.hibernate(session));
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (!(error instanceof TinyactorsError)) throw error; // not at rest: it stays
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const counters = [1, 2, 3].map(() => host.spawn(host.chart('counter')));
|
|
66
|
+
await host.idle();
|
|
67
|
+
evict(host); // every counter ran at its start: none is cold yet
|
|
68
|
+
evict(host); // none ran since the last sweep: all three go
|
|
69
|
+
console.log(`${store.size} in the store`);
|
|
70
|
+
|
|
71
|
+
host.send(counters[1], 'add', 5);
|
|
72
|
+
host.send(counters[1], 'add', 5); // one wake for both
|
|
73
|
+
await host.idle();
|
|
74
|
+
console.log(`${store.size} in the store`);
|
|
75
|
+
host.close();
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```output
|
|
79
|
+
3 in the store
|
|
80
|
+
waking 2
|
|
81
|
+
counter 2 is at 5
|
|
82
|
+
counter 2 is at 10
|
|
83
|
+
2 in the store
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
In a server, run the sweep on a timer, or after a burst of work, and size
|
|
87
|
+
`limit` so that one sweep does not hold the event loop for long.
|
|
88
|
+
|
|
89
|
+
## What a blob holds
|
|
90
|
+
|
|
91
|
+
A blob is the actor's whole state: its active states, its variables, its
|
|
92
|
+
`_event`, its place in the host. Wake it in the host that
|
|
93
|
+
hibernated it, or in one [restored](snapshots.md) from that host's
|
|
94
|
+
snapshot. Another host's blob throws `TA_ERROR_INVALID`, even for a
|
|
95
|
+
session of the same number running the same chart: each host draws a
|
|
96
|
+
random identity when it is created, and every blob carries it. It lives in your store until the wake; the host keeps nothing
|
|
97
|
+
of it but which hibernation it was. A wake takes the session's latest blob
|
|
98
|
+
only: a blob of an earlier hibernation, which a store that fell behind
|
|
99
|
+
hands back (an overwrite that failed, a replica, a cache), throws
|
|
100
|
+
`TA_ERROR_STALE` and the actor stays hibernated, so no state is lost
|
|
101
|
+
without an error. On a host [restored](snapshots.md) from a snapshot, a
|
|
102
|
+
blob of a hibernation made after the snapshot was taken is accepted too,
|
|
103
|
+
so a store that keeps one blob per session goes on working there.
|
|
104
|
+
|
|
105
|
+
On the native datamodel the variables are written as values of the
|
|
106
|
+
value table ([README](../../README.md#values)): numbers, `bigint`s,
|
|
107
|
+
strings, `Uint8Array`s, arrays, plain objects, `true`, `false`, `null`
|
|
108
|
+
and `undefined`. A variable holding something else (a function, a `Map`,
|
|
109
|
+
a `Date`, a class's instance, an XML document) keeps the actor in memory.
|
|
110
|
+
A chart whose scripts declare top-level names gets a new context at the
|
|
111
|
+
wake: its `var`s come back from the blob and its `function` declarations
|
|
112
|
+
are made again from its scripts. One that declares with `let`, `const`
|
|
113
|
+
or `class` keeps its actors in memory. On quickjs the engine writes its
|
|
114
|
+
own values, so a `Date`, a `Map`, a `Set` or a typed array is stored too
|
|
115
|
+
([The quickjs sandbox](quickjs.md#what-differs-from-the-native-datamodel)).
|
|
116
|
+
|
|
117
|
+
What stays in the host: a hibernated actor keeps its slot and a small
|
|
118
|
+
record (about 60 bytes), and the data of its pending delayed sends and of
|
|
119
|
+
the events waiting in its queue stays too. A pending delayed send wakes
|
|
120
|
+
the actor when it falls due.
|
|
121
|
+
|
|
122
|
+
## When an actor cannot hibernate
|
|
123
|
+
|
|
124
|
+
`hibernate` throws a `TinyactorsError` and the actor stays where it is:
|
|
125
|
+
|
|
126
|
+
- **`TA_ERROR_STATE`:** not now. Every one of these gives the same
|
|
127
|
+
status (only the message, which is for people, lists them):
|
|
128
|
+
- it has events waiting in its queue (an input you gave since its last
|
|
129
|
+
turn, an event another actor sent, a delayed send that fell due);
|
|
130
|
+
- its step is not over: called, for example, from the handler of a
|
|
131
|
+
send it made in this turn;
|
|
132
|
+
- it runs an invoked child chart or a service;
|
|
133
|
+
- it is not resident: already hibernated, including one whose wake the
|
|
134
|
+
host has asked your `wake` handler for and that you have not given
|
|
135
|
+
back yet.
|
|
136
|
+
- **`TA_ERROR_STALE`:** the session ended, or never was.
|
|
137
|
+
- **`TA_ERROR_UNSUPPORTED`:** a variable holds what its datamodel cannot
|
|
138
|
+
store. The message names the variable.
|
|
139
|
+
|
|
140
|
+
The first three cases of `TA_ERROR_STATE` pass (try again after a turn);
|
|
141
|
+
the last does not, and the status cannot tell them apart. An eviction
|
|
142
|
+
loop therefore knows which actors are resident itself, as the one above
|
|
143
|
+
does: what `sweep` returns is resident, and a session whose blob is in
|
|
144
|
+
your store, or whose wake you were asked for, is not.
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
148
|
+
|
|
149
|
+
const compiled = compileCharts([{ name: 'c.scxml', text: `
|
|
150
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
151
|
+
datamodel="ecmascript" name="c" initial="s">
|
|
152
|
+
<datamodel><data id="seen" expr="new Map()"/></datamodel>
|
|
153
|
+
<state id="s"/>
|
|
154
|
+
</scxml>` }]);
|
|
155
|
+
const host = new Host({ systemID: 'demo' });
|
|
156
|
+
host.addImage(compiled.image);
|
|
157
|
+
compiled.close();
|
|
158
|
+
|
|
159
|
+
const session = host.spawn(host.chart('c'));
|
|
160
|
+
await host.idle();
|
|
161
|
+
try {
|
|
162
|
+
host.hibernate(session);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
console.log(error.status);
|
|
165
|
+
console.log(error.message);
|
|
166
|
+
}
|
|
167
|
+
host.close();
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
```output
|
|
171
|
+
TA_ERROR_UNSUPPORTED
|
|
172
|
+
variable 'seen' cannot be stored: only plain objects, arrays and Uint8Arrays are values (docs/values.md)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Without a `wake` handler the host does not ask: a hibernated actor stays
|
|
176
|
+
hibernated, and its events wait, until you call `host.wake` yourself.
|
|
177
|
+
|
|
178
|
+
## At scale
|
|
179
|
+
|
|
180
|
+
How many actors a host holds and how much memory it needs is in
|
|
181
|
+
[Capacity and memory](capacity.md): a hibernated actor still counts
|
|
182
|
+
toward `system.maxActors`.
|
|
183
|
+
|
|
184
|
+
`tools/stress.mjs` (`mise run stress` in the repository) is the pattern
|
|
185
|
+
of this guide at scale: two million actors, at most 1000 resident, the
|
|
186
|
+
rest in SQLite (`node:sqlite` under Node.js, `bun:sqlite` under Bun).
|
|
187
|
+
|
|
188
|
+
One run of it (2026-10-16, x86_64 Linux 6.18, Intel Xeon @ 2.10GHz, 4
|
|
189
|
+
CPUs, 16 GiB; node 22.23.3, bun 1.4.1): two million actors of a counter
|
|
190
|
+
chart, at most 1000 resident, 200,000 events to actors drawn at random,
|
|
191
|
+
so nearly every event wakes one from the store and the sweep sends
|
|
192
|
+
another back (199,860 wakes in each run). Every sampled actor's count
|
|
193
|
+
matched the events it was sent, and after every eviction at most 1000
|
|
194
|
+
actors were resident.
|
|
195
|
+
|
|
196
|
+
| runtime, datamodel | populate (spawn and hibernate 2,000,000) | 200,000 events (woken, swept back) | peak resident | core's region | SQLite file |
|
|
197
|
+
|---|---|---|---|---|---|
|
|
198
|
+
| node, native | 26.1 s (76,700 a second) | 14.6 s (13,700 a second) | 253 MB (126 B per actor) | 115 MB (58 B per actor) | 378 MB |
|
|
199
|
+
| node, quickjs | 17.1 s (116,900 a second) | 11.9 s (16,900 a second) | 262 MB (131 B per actor) | 115 MB (58 B per actor) | 409 MB |
|
|
200
|
+
| bun, native | 19.5 s (102,600 a second) | 12.9 s (15,500 a second) | 236 MB (118 B per actor) | 115 MB (58 B per actor) | 378 MB |
|
|
201
|
+
| bun, quickjs | 14.0 s (143,000 a second) | 11.9 s (16,900 a second) | 221 MB (111 B per actor) | 115 MB (58 B per actor) | 409 MB |
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
# Inspecting a host
|
|
2
|
+
|
|
3
|
+
A running host answers questions about itself: which state an actor is
|
|
4
|
+
in, what its variables hold, which actors exist, what the host has done
|
|
5
|
+
so far. These are the **typed methods**, one per question. Each reads
|
|
6
|
+
the host as it is when you call it and answers in a later turn, so each
|
|
7
|
+
returns a promise: `await host.actorState({ session })`.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
11
|
+
|
|
12
|
+
const compiled = compileCharts([{ name: 'order.scxml', text: `
|
|
13
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
14
|
+
datamodel="ecmascript" name="order" initial="open">
|
|
15
|
+
<datamodel>
|
|
16
|
+
<data id="items" expr="[]"/>
|
|
17
|
+
</datamodel>
|
|
18
|
+
<state id="open" initial="browsing">
|
|
19
|
+
<state id="browsing">
|
|
20
|
+
<transition event="add"><script>items.push(_event.data)</script></transition>
|
|
21
|
+
</state>
|
|
22
|
+
</state>
|
|
23
|
+
</scxml>` }]);
|
|
24
|
+
const host = new Host({ systemID: 'shop' });
|
|
25
|
+
host.addImage(compiled.image);
|
|
26
|
+
compiled.close();
|
|
27
|
+
|
|
28
|
+
const order = host.spawn(host.chart('order'), { name: 'first' });
|
|
29
|
+
host.send(order, 'add', 'tea');
|
|
30
|
+
await host.idle(); // the actor has started and handled 'add'
|
|
31
|
+
|
|
32
|
+
const { value } = await host.actorState({ session: order });
|
|
33
|
+
console.log('state:', JSON.stringify(value));
|
|
34
|
+
const { variables } = await host.actorContext({ session: order });
|
|
35
|
+
console.log('variables:', JSON.stringify(variables));
|
|
36
|
+
const actor = await host.actorGet({ session: order });
|
|
37
|
+
console.log('actor:', actor.chart, 'mailbox', actor.mailbox);
|
|
38
|
+
host.close();
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```output
|
|
42
|
+
state: {"open":"browsing"}
|
|
43
|
+
variables: {"items":["tea"]}
|
|
44
|
+
actor: order mailbox 0
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Asked before the `await host.idle()`, the same methods would have found
|
|
48
|
+
an actor that had not started yet: no active state, and every variable
|
|
49
|
+
`undefined`, the spawn's `params` included. An actor's `<data>` are
|
|
50
|
+
given their values, from `expr` or from `params`, when it first runs, in
|
|
51
|
+
the host's next turn after the spawn. A variable that holds `undefined`
|
|
52
|
+
reads `undefined` and one that holds `null` reads `null`, on both
|
|
53
|
+
datamodels. An actor's state reads as nested objects, one key per
|
|
54
|
+
compound state: `{"open": "browsing"}` is the state `browsing` inside
|
|
55
|
+
`open`, and a parallel state is `{"p": {"r1": ..., "r2": ...}}`, one
|
|
56
|
+
key per region.
|
|
57
|
+
|
|
58
|
+
## The methods
|
|
59
|
+
|
|
60
|
+
| Method | Params | Result |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `actorState` | `{ session }` | `{ value, history }`: the active states, as above, and where each history state would return ([below](#delayed-sends-and-history)) |
|
|
63
|
+
| `actorContext` | `{ session }` | `{ variables }`: each `<data>` and its value |
|
|
64
|
+
| `actorGet` | `{ session }` | `{ session, segment, chart, parent, mailbox, invocations, timers, timersPending }`: `timers` its pending delayed sends ([below](#delayed-sends-and-history)) |
|
|
65
|
+
| `actorList` | `{ cursor, limit }`, both optional | `{ sessions, cursor }`: a page of sessions; `cursor` is `null` after the last page |
|
|
66
|
+
| `hostStats` | none | `{ host, pools, charts }`: counters ([below](#the-hosts-counters)) |
|
|
67
|
+
| `hostConfig` | none | the config the host runs with, every default filled in |
|
|
68
|
+
| `traceConfigure`, `traceWatch`, `traceUnwatch`, `traceEnd`, `traceSpansDecode` | | [Telemetry](telemetry.md) |
|
|
69
|
+
|
|
70
|
+
A method without params is called with none: `await
|
|
71
|
+
host.hostStats()`. The host checks the params: one the method does
|
|
72
|
+
not take, of the wrong type or out of range is an error, as is a session
|
|
73
|
+
that names no actor (it ended, or never was). **Sessions in a result are
|
|
74
|
+
numbers**, while `spawn`, `actorByName` and the views give `bigint`s, so
|
|
75
|
+
`result.sessions.includes(session)` is false for a `bigint` session and
|
|
76
|
+
a `Map` keyed by one misses the other: compare with `Number(session) ===
|
|
77
|
+
listed`, or key by `String(session)`
|
|
78
|
+
([README](../../README.md#actors-sessions-and-addresses)). The inputs take
|
|
79
|
+
either back as it is (`host.send(result.sessions[0], ...)`).
|
|
80
|
+
|
|
81
|
+
Each method's params and result are typed in the package's `index.d.ts`
|
|
82
|
+
(`SessionParams`, `ActorStateResult`, `ActorListResult`,
|
|
83
|
+
`HostStatsResult`, `EffectiveHostConfig`, ...), for the promise forms and
|
|
84
|
+
the handlers' `result` alike, and so is the host's config (`HostConfig`).
|
|
85
|
+
An editor completes `stats.pools[0].actors.highWater`, and TypeScript, or
|
|
86
|
+
`tsc` checking JavaScript, refuses a field a result does not have or
|
|
87
|
+
a param a method does not take. Every example of these guides is checked
|
|
88
|
+
that way against the package's types, the one below included.
|
|
89
|
+
|
|
90
|
+
`actorContext` and `actorState` are refused for a hibernated
|
|
91
|
+
actor (`reason` `'state'`): wake it first ([Hibernation](hibernation.md)).
|
|
92
|
+
|
|
93
|
+
## Delayed sends and history
|
|
94
|
+
|
|
95
|
+
What an operator asks first about a waiting actor is when it will act
|
|
96
|
+
next and where it will go back to. `actorGet` answers the first:
|
|
97
|
+
`timers` lists the actor's pending delayed sends (each `<send delay>`
|
|
98
|
+
not yet due and not cancelled), earliest first, each `{ sendid, event,
|
|
99
|
+
due }`, with `due` in milliseconds on the clock `host.now()` reads. The
|
|
100
|
+
list holds at most 32; `timersPending` is how many there are, so a
|
|
101
|
+
longer `timersPending` says the list was cut. A send without an `id` has
|
|
102
|
+
a `sendid` of `null`. `actorState` answers the second: `history`
|
|
103
|
+
holds, for each history state the actor has recorded, its parent state as
|
|
104
|
+
it would be entered again, in the shape of `value`. A history state
|
|
105
|
+
records when its parent is exited, so before the first exit it is absent
|
|
106
|
+
and `history` is `{}`.
|
|
107
|
+
|
|
108
|
+
```js
|
|
109
|
+
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
|
|
110
|
+
|
|
111
|
+
const compiled = compileCharts([{ name: 'review.scxml', text: `
|
|
112
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
113
|
+
datamodel="ecmascript" name="review" initial="reviewing">
|
|
114
|
+
<state id="reviewing" initial="draft">
|
|
115
|
+
<onentry><send id="sla" event="breach" delay="7200s"/></onentry>
|
|
116
|
+
<history id="back" type="deep"><transition target="draft"/></history>
|
|
117
|
+
<state id="draft"><transition event="submit" target="legal"/></state>
|
|
118
|
+
<state id="legal"/>
|
|
119
|
+
<transition event="hold" target="held"/>
|
|
120
|
+
</state>
|
|
121
|
+
<state id="held"><transition event="release" target="back"/></state>
|
|
122
|
+
</scxml>` }]);
|
|
123
|
+
const clock = new SimulatedClock();
|
|
124
|
+
const host = new Host({ systemID: 'docs' }, { clock });
|
|
125
|
+
host.addImage(compiled.image);
|
|
126
|
+
compiled.close();
|
|
127
|
+
|
|
128
|
+
const doc = host.spawn(host.chart('review'));
|
|
129
|
+
host.send(doc, 'submit');
|
|
130
|
+
host.send(doc, 'hold');
|
|
131
|
+
await host.idle();
|
|
132
|
+
clock.increment(60_000); // a minute later
|
|
133
|
+
|
|
134
|
+
const { timers, timersPending } = await host.actorGet({ session: doc });
|
|
135
|
+
for (const { sendid, event, due } of timers) console.log(sendid, event, 'in', (due - host.now()) / 1000, 's');
|
|
136
|
+
console.log('pending:', timersPending);
|
|
137
|
+
const { value, history } = await host.actorState({ session: doc });
|
|
138
|
+
console.log('state:', JSON.stringify(value), 'history:', JSON.stringify(history));
|
|
139
|
+
host.close();
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
```output
|
|
143
|
+
sla breach in 7140 s
|
|
144
|
+
pending: 1
|
|
145
|
+
state: "held" history: {"back":{"reviewing":"legal"}}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
A deep history (`type="deep"`) returns to the atomic states it recorded,
|
|
149
|
+
so its value goes down to them; a shallow one returns to the child of
|
|
150
|
+
its parent it recorded, which enters its own initial state, and its
|
|
151
|
+
value names that child alone. Neither costs anything per event: the
|
|
152
|
+
host reads them only when asked.
|
|
153
|
+
|
|
154
|
+
A page at a time, `actorList` lists every actor:
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
158
|
+
|
|
159
|
+
const compiled = compileCharts([{ name: 'idle.scxml', text: `
|
|
160
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
161
|
+
datamodel="ecmascript" name="idle"><state id="waiting"/></scxml>` }]);
|
|
162
|
+
const host = new Host({ systemID: 'shop' });
|
|
163
|
+
host.addImage(compiled.image);
|
|
164
|
+
compiled.close();
|
|
165
|
+
for (let i = 0; i < 5; i++) host.spawn(host.chart('idle'));
|
|
166
|
+
|
|
167
|
+
const sessions = [];
|
|
168
|
+
let cursor = 0;
|
|
169
|
+
do {
|
|
170
|
+
const page = await host.actorList({ cursor, limit: 2 });
|
|
171
|
+
sessions.push(...page.sessions);
|
|
172
|
+
cursor = page.cursor;
|
|
173
|
+
} while (cursor !== null);
|
|
174
|
+
console.log('sessions:', sessions.join(' '));
|
|
175
|
+
host.close();
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```output
|
|
179
|
+
sessions: 1 2 3 4 5
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Errors
|
|
183
|
+
|
|
184
|
+
An error rejects the promise with a `TinyactorsError` with `code`
|
|
185
|
+
(JSON-RPC's number), `reason` (a word such as `stale`, `type`,
|
|
186
|
+
`unknown`) and `path` (the param it is about), and a message for people.
|
|
187
|
+
A call the host refuses at once (a closed host) rejects too.
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
import { Host } from '@tinyactors/node';
|
|
191
|
+
|
|
192
|
+
const host = new Host({ systemID: 'shop' });
|
|
193
|
+
try {
|
|
194
|
+
await host.actorState({ session: 99 });
|
|
195
|
+
} catch (error) {
|
|
196
|
+
console.log(error.reason, error.path, error.code);
|
|
197
|
+
}
|
|
198
|
+
// @ts-expect-error: a param actorGet does not take, which the types refuse too
|
|
199
|
+
await host.actorGet({ name: 'first' }).catch((error) => console.log(error.reason, error.path));
|
|
200
|
+
host.close();
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
```output
|
|
204
|
+
stale params.session -32001
|
|
205
|
+
unknown params.name
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
The rejection is yours to handle: `host.idle()` does not see it, and one
|
|
209
|
+
you do not catch is an unhandled rejection, which ends a Node.js or Bun
|
|
210
|
+
process by default. `host.close()` drops the methods still waiting:
|
|
211
|
+
their promises never settle.
|
|
212
|
+
|
|
213
|
+
## With handlers
|
|
214
|
+
|
|
215
|
+
Each method also takes handlers instead of returning a promise:
|
|
216
|
+
`host.actorState(params, onResult, onError)`, and so on. Given handlers
|
|
217
|
+
it returns nothing; `onResult(host, result)` is called in a
|
|
218
|
+
later turn, or `onError(host, error)` with the same `TinyactorsError`.
|
|
219
|
+
The promise is made only when no handler is given, so a caller that
|
|
220
|
+
passes handlers pays for no promise. A method without params takes `undefined`:
|
|
221
|
+
`host.hostStats(undefined, onResult)`.
|
|
222
|
+
|
|
223
|
+
```js
|
|
224
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
225
|
+
|
|
226
|
+
const compiled = compileCharts([{ name: 'idle.scxml', text: `
|
|
227
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
228
|
+
datamodel="ecmascript" name="idle"><state id="waiting"/></scxml>` }]);
|
|
229
|
+
const host = new Host({ systemID: 'shop' });
|
|
230
|
+
host.addImage(compiled.image);
|
|
231
|
+
compiled.close();
|
|
232
|
+
const session = host.spawn(host.chart('idle'));
|
|
233
|
+
await host.idle();
|
|
234
|
+
|
|
235
|
+
host.actorState({ session }, (host, result) => console.log('state:', JSON.stringify(result.value)));
|
|
236
|
+
host.hostStats(undefined, (host, stats) => console.log('actors:', stats.host.actors));
|
|
237
|
+
host.actorGet({ session: 99 }, () => {}, (host, error) => console.log('error:', error.reason));
|
|
238
|
+
console.log('asked');
|
|
239
|
+
await host.idle();
|
|
240
|
+
host.close();
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
```output
|
|
244
|
+
asked
|
|
245
|
+
state: "waiting"
|
|
246
|
+
actors: 1
|
|
247
|
+
error: stale
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The handlers ran after `asked`, in a later turn. Without an `onError`,
|
|
251
|
+
an error rejects a waiting `host.idle()`, or else is thrown as an
|
|
252
|
+
uncaught exception, as a handler's error is.
|
|
253
|
+
|
|
254
|
+
## The host's counters
|
|
255
|
+
|
|
256
|
+
`hostStats` answers three parts:
|
|
257
|
+
|
|
258
|
+
- `host`: `segments` (live), `actors` and `hibernated` (now),
|
|
259
|
+
`runnable` (actors with work waiting), `migrations` (running),
|
|
260
|
+
`regionBytes` (the memory of the live segments), `delivered` (events
|
|
261
|
+
put in queues), `routed` (sends between the host's segments),
|
|
262
|
+
`migrated` (actors moved), `retired` (segments freed after a
|
|
263
|
+
migration), and `fuelClock` (the work the host has done, the clock its
|
|
264
|
+
trace records are stamped with).
|
|
265
|
+
- `pools`: an array with one entry per live segment, in segment order.
|
|
266
|
+
Each entry has its `segment` number and one object per pool, `actors`,
|
|
267
|
+
`events`, `timers`, `workspaces`, `requests` and `slabBytes`, each
|
|
268
|
+
`{ capacity, used, highWater }`: `stats.pools[0].actors.used`
|
|
269
|
+
([Capacity and memory](capacity.md)).
|
|
270
|
+
- `charts`: one entry per chart name, summed over its versions: `name`,
|
|
271
|
+
`actors`, `hibernated`, `spawned`, `ended`, `turns`, `macrosteps`,
|
|
272
|
+
`fuel`, `errorsExecution`, `errorsCommunication`, `errorsPlatform`,
|
|
273
|
+
`faults`.
|
|
274
|
+
|
|
275
|
+
The words, as the counters use them:
|
|
276
|
+
|
|
277
|
+
- A **macrostep** is everything one event does to an actor: its
|
|
278
|
+
transitions and those that follow on their own, until the actor waits
|
|
279
|
+
for the next event. A **microstep** is one set of transitions taken
|
|
280
|
+
together. Spans are named after both ([Telemetry](telemetry.md)).
|
|
281
|
+
- **Fuel** is the host's unit of work: an action, a transition, and a
|
|
282
|
+
share of the JavaScript an expression runs. A **turn** is one time an
|
|
283
|
+
actor is given the processor; it runs until it waits or has spent its
|
|
284
|
+
fuel for the turn (`system.quantum`), so a busy actor cannot starve the
|
|
285
|
+
others.
|
|
286
|
+
- A **workspace** is the room an actor needs while it runs; the host has
|
|
287
|
+
a few and an actor waits for one.
|
|
288
|
+
- `errorsPlatform` counts `error.platform` events raised in the chart's
|
|
289
|
+
actors; `faults` counts actors the host
|
|
290
|
+
had to end because their run failed inside the host.
|
|
291
|
+
|
|
292
|
+
```js
|
|
293
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
294
|
+
|
|
295
|
+
const compiled = compileCharts([{ name: 'job.scxml', text: `
|
|
296
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
297
|
+
datamodel="ecmascript" name="job" initial="running">
|
|
298
|
+
<state id="running">
|
|
299
|
+
<transition event="finish" target="done"/>
|
|
300
|
+
<transition event="break"><assign location="undeclared" expr="1"/></transition>
|
|
301
|
+
</state>
|
|
302
|
+
<final id="done"/>
|
|
303
|
+
</scxml>` }]);
|
|
304
|
+
const host = new Host({ systemID: 'shop' });
|
|
305
|
+
host.addImage(compiled.image);
|
|
306
|
+
compiled.close();
|
|
307
|
+
|
|
308
|
+
const jobs = [1, 2, 3].map(() => host.spawn(host.chart('job')));
|
|
309
|
+
host.send(jobs[0], 'finish');
|
|
310
|
+
host.send(jobs[1], 'break');
|
|
311
|
+
await host.idle();
|
|
312
|
+
const stats = await host.hostStats();
|
|
313
|
+
const [job] = stats.charts;
|
|
314
|
+
console.log(`${job.name}: ${job.spawned} spawned, ${job.ended} ended, ${job.actors} running, ${job.errorsExecution} execution error`);
|
|
315
|
+
console.log(`${stats.host.segments} segment, ${stats.pools[0].actors.used} actors in its pool`);
|
|
316
|
+
host.close();
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
```output
|
|
320
|
+
job: 3 spawned, 1 ended, 2 running, 1 execution error
|
|
321
|
+
1 segment, 2 actors in its pool
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
## Two actors that never rest
|
|
325
|
+
|
|
326
|
+
Actors that answer each other for ever keep the host busy: each turn
|
|
327
|
+
runs them, `await host.idle()` never resolves, and nothing is logged or
|
|
328
|
+
thrown, since every step is legal. The usual cause is SCXML's prefix
|
|
329
|
+
match ([README](../../README.md#charts)): a transition on `join` also
|
|
330
|
+
takes the answer `join.refused`, and asks again. The counters show it.
|
|
331
|
+
Between two readings while you gave no input, a loop's charts gain
|
|
332
|
+
`macrosteps` and `fuel` without end, `host.delivered` grows, and
|
|
333
|
+
`host.runnable` stays above zero; a host that is only slow drains its
|
|
334
|
+
queue instead.
|
|
335
|
+
|
|
336
|
+
```js
|
|
337
|
+
import { Host } from '@tinyactors/node';
|
|
338
|
+
|
|
339
|
+
const host = new Host({ systemID: 'chat' });
|
|
340
|
+
host.addCharts({
|
|
341
|
+
'user.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="user">
|
|
342
|
+
<state id="s">
|
|
343
|
+
<onentry><send event="join" target="tinyactors://chat/@room"/></onentry>
|
|
344
|
+
<transition event="join"><send event="join" target="tinyactors://chat/@room"/></transition>
|
|
345
|
+
</state>
|
|
346
|
+
</scxml>`,
|
|
347
|
+
'room.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="room">
|
|
348
|
+
<state id="s"><transition event="join"><send event="join.refused" targetexpr="_event.origin"/></transition></state>
|
|
349
|
+
</scxml>`,
|
|
350
|
+
});
|
|
351
|
+
host.spawnChart('room', { name: 'room' });
|
|
352
|
+
const user = host.spawnChart('user');
|
|
353
|
+
|
|
354
|
+
/** The charts whose actors kept working for `ms` with no input given. */
|
|
355
|
+
async function busy(host, ms) {
|
|
356
|
+
const before = await host.hostStats();
|
|
357
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
358
|
+
const after = await host.hostStats();
|
|
359
|
+
if (after.host.runnable === 0) return [];
|
|
360
|
+
return after.charts
|
|
361
|
+
.filter((chart) => chart.macrosteps - (before.charts.find((c) => c.name === chart.name)?.macrosteps ?? 0) > 1000)
|
|
362
|
+
.map((chart) => chart.name)
|
|
363
|
+
.sort();
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
console.log('busy:', (await busy(host, 200)).join(', '));
|
|
367
|
+
host.terminate(user); // in production: alert, and fix the chart
|
|
368
|
+
await host.idle();
|
|
369
|
+
console.log('idle again; busy:', (await busy(host, 50)).length);
|
|
370
|
+
host.close();
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
```output
|
|
374
|
+
busy: room, user
|
|
375
|
+
idle again; busy: 0
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
A watchdog that runs this on a timer, and alerts when a chart stays busy
|
|
379
|
+
over several readings, finds such a loop. The fix is in the chart: name
|
|
380
|
+
the answer so that it does not extend the request (`refused.join`), or
|
|
381
|
+
make the `join` transition's `cond` refuse what is not a request.
|