@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,265 @@
|
|
|
1
|
+
# Telemetry
|
|
2
|
+
|
|
3
|
+
Telemetry is optional: a host without it runs the same. Turn it on to see
|
|
4
|
+
what your actors did in an OpenTelemetry backend.
|
|
5
|
+
|
|
6
|
+
A host can describe what its actors did as OpenTelemetry data: a span
|
|
7
|
+
for each step an actor takes (the event, the transitions, the states left
|
|
8
|
+
and entered), a log record for each `<log>` and each failed action, and
|
|
9
|
+
metrics of the host's counters. It writes them as OTLP requests, the
|
|
10
|
+
protobuf bytes an OpenTelemetry collector takes at `/v1/traces`,
|
|
11
|
+
`/v1/logs` and `/v1/metrics`. Sending them is your code's job, so you
|
|
12
|
+
choose the transport, the retries and the collector.
|
|
13
|
+
|
|
14
|
+
## Turning it on
|
|
15
|
+
|
|
16
|
+
Two things: a `telemetry` map in the config, which gives the host its
|
|
17
|
+
encoder, and a `telemetry` handler in the options, which gets each request
|
|
18
|
+
the encoder wrote, as a `Buffer`, with its signal (`'traces'` or
|
|
19
|
+
`'logs'`).
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
|
|
23
|
+
|
|
24
|
+
const compiled = compileCharts([{ name: 'order.scxml', text: `
|
|
25
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
26
|
+
datamodel="ecmascript" name="order" initial="open">
|
|
27
|
+
<state id="open">
|
|
28
|
+
<transition event="pay" target="paid"><log label="order" expr="'paid'"/></transition>
|
|
29
|
+
</state>
|
|
30
|
+
<final id="paid"/>
|
|
31
|
+
</scxml>` }]);
|
|
32
|
+
|
|
33
|
+
const requests = [];
|
|
34
|
+
const clock = new SimulatedClock();
|
|
35
|
+
const host = new Host({
|
|
36
|
+
systemID: 'shop',
|
|
37
|
+
system: { ticksPerSecond: 1000 }, // the host's clock in milliseconds
|
|
38
|
+
telemetry: { flushInterval: 1000, resource: { 'service.name': 'shop' } }, // a request at most a second after its first record
|
|
39
|
+
}, {
|
|
40
|
+
clock,
|
|
41
|
+
telemetry: (host, signal, data) => {
|
|
42
|
+
// A real exporter posts the bytes, from a promise so the host goes on:
|
|
43
|
+
// fetch(`${collector}/v1/${signal}`, { method: 'POST', headers: { 'content-type': 'application/x-protobuf' }, body: data })
|
|
44
|
+
requests.push([signal, data]);
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
host.addImage(compiled.image);
|
|
48
|
+
compiled.close();
|
|
49
|
+
|
|
50
|
+
const caller = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'; // a W3C traceparent, from an HTTP header
|
|
51
|
+
host.send(host.spawn(host.chart('order')), 'pay', undefined, { traceparent: caller });
|
|
52
|
+
await host.idle();
|
|
53
|
+
console.log('requests before the flush interval:', requests.length);
|
|
54
|
+
clock.increment(1000);
|
|
55
|
+
await host.idle();
|
|
56
|
+
console.log('signals:', requests.map(([signal]) => signal).sort().join(', '));
|
|
57
|
+
|
|
58
|
+
// Read the spans back (for a test; a collector does this for you).
|
|
59
|
+
for (const [signal, data] of requests) {
|
|
60
|
+
if (signal !== 'traces') continue;
|
|
61
|
+
const { spans } = await host.traceSpansDecode({ traces: data });
|
|
62
|
+
const ours = spans.filter((span) => span.trace === '0af7651916cd43dd8448eb211c80319c');
|
|
63
|
+
console.log('spans in the caller\'s trace:', ours.map((span) => span.name).sort().join(', '));
|
|
64
|
+
const step = ours.find((span) => span.name === 'scxml.macrostep pay');
|
|
65
|
+
console.log('the step\'s parent is the caller\'s span:', step.parent === 'b7ad6b7169203331');
|
|
66
|
+
}
|
|
67
|
+
host.close();
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```output
|
|
71
|
+
requests before the flush interval: 0
|
|
72
|
+
signals: logs, traces
|
|
73
|
+
spans in the caller's trace: scxml.destroyed, scxml.finished, scxml.macrostep pay, scxml.microstep pay
|
|
74
|
+
the step's parent is the caller's span: true
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The handler runs in the host's turn: start the post there, and do not
|
|
78
|
+
wait for the collector before returning. A handler's error is the turn's
|
|
79
|
+
([README](../../README.md#errors)); the request it failed to send is not
|
|
80
|
+
offered again, so retrying is the exporter's to do.
|
|
81
|
+
|
|
82
|
+
**`host.metrics()`** returns the metrics request for the host's counters
|
|
83
|
+
now, a `Buffer` for `/v1/metrics`. Call it on your own schedule. It throws
|
|
84
|
+
`TA_ERROR_STATE` on a host without `telemetry` in its config.
|
|
85
|
+
|
|
86
|
+
**At `host.close()`** every span still open ends, marked incomplete, and
|
|
87
|
+
the handler gets the last requests before the host is freed. A promise the
|
|
88
|
+
handler returns there is awaited by `await host[Symbol.asyncDispose]()`.
|
|
89
|
+
A host the garbage collector frees without `close()` skips this: close
|
|
90
|
+
the hosts whose telemetry you want.
|
|
91
|
+
|
|
92
|
+
## The encoder's options
|
|
93
|
+
|
|
94
|
+
The config's `telemetry` map, every key optional:
|
|
95
|
+
|
|
96
|
+
| Key | Default | What it does |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `flushInterval` | 0 | a request is ready this long after its first record, in the host's clock ticks (`system.ticksPerSecond`); 0 means only when the staging is full, or at close |
|
|
99
|
+
| `resource` | none | attributes on every request, such as `service.name` (at most 32, text to text) |
|
|
100
|
+
| `logs` | `true` | `<log>` lines and failed actions as log records |
|
|
101
|
+
| `values` | `false` | event data and assigned values in the spans; they may hold personal data, so turn this on knowingly |
|
|
102
|
+
| `linkParents` | `false` | an actor's step is a root span linked to its cause, instead of its child |
|
|
103
|
+
| `stagingBytes` | 1048576 | the encoder's staging memory |
|
|
104
|
+
|
|
105
|
+
The host's clock runs at `system.ticksPerSecond`, a billion by default
|
|
106
|
+
(nanoseconds), so a `flushInterval` of 5000 is five microseconds unless the
|
|
107
|
+
config sets the rate. Most programs that export set `ticksPerSecond:
|
|
108
|
+
1000` and give the interval in milliseconds.
|
|
109
|
+
|
|
110
|
+
A pending flush is one of the host's deadlines: once records are staged,
|
|
111
|
+
`host.nextDeadline` reads the time to the flush even when no actor has a
|
|
112
|
+
delayed send left, the host's timer is armed for it (keeping the process
|
|
113
|
+
alive until then), and a test that asserts "no timer is left" first steps
|
|
114
|
+
its clock past the flush:
|
|
115
|
+
|
|
116
|
+
```js
|
|
117
|
+
import { Host, SimulatedClock } from '@tinyactors/node';
|
|
118
|
+
|
|
119
|
+
const clock = new SimulatedClock();
|
|
120
|
+
const host = new Host({ systemID: 'shop', system: { ticksPerSecond: 1000 }, telemetry: { flushInterval: 1000 } }, {
|
|
121
|
+
clock,
|
|
122
|
+
telemetry: (host, signal) => console.log(signal, 'at', clock.now),
|
|
123
|
+
});
|
|
124
|
+
host.addCharts({ 'job.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="job">
|
|
125
|
+
<final id="done"/>
|
|
126
|
+
</scxml>` });
|
|
127
|
+
host.spawnChart('job');
|
|
128
|
+
await host.idle();
|
|
129
|
+
console.log('the job ended; nextDeadline', host.nextDeadline);
|
|
130
|
+
clock.increment(host.nextDeadline ?? 0);
|
|
131
|
+
await host.idle();
|
|
132
|
+
console.log('flushed; nextDeadline', host.nextDeadline);
|
|
133
|
+
host.close();
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```output
|
|
137
|
+
the job ended; nextDeadline 1000
|
|
138
|
+
traces at 1000
|
|
139
|
+
logs at 1000
|
|
140
|
+
flushed; nextDeadline undefined
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Trace context
|
|
144
|
+
|
|
145
|
+
The host carries W3C trace context through every step. An input may name
|
|
146
|
+
the trace it continues: `host.send(session, event, data, { traceparent
|
|
147
|
+
})` and `host.spawn(ref, { traceparent })` take a `traceparent` header's
|
|
148
|
+
text, and text that does not parse starts a new trace. Toward the
|
|
149
|
+
outside, a send's `traceparent` is the sending step's context, for the
|
|
150
|
+
header of the request your I/O processor makes, and `send.answer()`
|
|
151
|
+
continues it unless you pass another (`null` for a new trace):
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
155
|
+
|
|
156
|
+
const compiled = compileCharts([{ name: 'c.scxml', text: `
|
|
157
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
158
|
+
datamodel="ecmascript" name="c" initial="s">
|
|
159
|
+
<state id="s">
|
|
160
|
+
<transition event="go"><send type="urn:example:api" event="call"/></transition>
|
|
161
|
+
</state>
|
|
162
|
+
</scxml>` }]);
|
|
163
|
+
const host = new Host({ systemID: 'demo', ioProcessors: [{ type: 'urn:example:api' }] }, {
|
|
164
|
+
ioProcessors: {
|
|
165
|
+
'urn:example:api': (host, send) => {
|
|
166
|
+
const [, trace] = send.traceparent.split('-');
|
|
167
|
+
console.log('the outgoing request continues trace', trace);
|
|
168
|
+
// fetch(url, { headers: { traceparent: send.traceparent } })
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
host.addImage(compiled.image);
|
|
173
|
+
compiled.close();
|
|
174
|
+
host.send(host.spawn(host.chart('c')), 'go', undefined, {
|
|
175
|
+
traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
|
|
176
|
+
});
|
|
177
|
+
await host.idle();
|
|
178
|
+
host.close();
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
```output
|
|
182
|
+
the outgoing request continues trace 4bf92f3577b34da6a3ce929d0e0e4736
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Tracing is on by default (`system.tracing`), with or without an encoder,
|
|
186
|
+
so trace context flows even when nothing is exported.
|
|
187
|
+
|
|
188
|
+
**Each host starts its own trace IDs.** A trace the host starts itself
|
|
189
|
+
takes its ID from a generator seeded by `system.traceSeed`. When the
|
|
190
|
+
config gives none, the package draws a random seed for each new host
|
|
191
|
+
(`crypto.getRandomValues`), so two processes, or one process and its
|
|
192
|
+
restart, do not collide at the collector. To reproduce a test's traces,
|
|
193
|
+
set the seed: the same seed gives the same IDs. `Host.restore` keeps the
|
|
194
|
+
generators of the snapshot.
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
198
|
+
|
|
199
|
+
const compiled = compileCharts([{ name: 'c.scxml', text: `
|
|
200
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
201
|
+
datamodel="ecmascript" name="c" initial="s">
|
|
202
|
+
<state id="s"><onentry><send type="urn:example:api" event="call"/></onentry></state>
|
|
203
|
+
</scxml>` }]);
|
|
204
|
+
const image = compiled.image;
|
|
205
|
+
compiled.close();
|
|
206
|
+
|
|
207
|
+
const firstTrace = async (system) => {
|
|
208
|
+
let trace;
|
|
209
|
+
const host = new Host({ systemID: 'demo', ioProcessors: [{ type: 'urn:example:api' }], system }, {
|
|
210
|
+
ioProcessors: { 'urn:example:api': (host, send) => { trace = send.traceparent.split('-')[1]; } },
|
|
211
|
+
});
|
|
212
|
+
host.addImage(image);
|
|
213
|
+
host.spawn(host.chart('c'));
|
|
214
|
+
await host.idle();
|
|
215
|
+
host.close();
|
|
216
|
+
return trace;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
console.log('no seed, twice:', (await firstTrace({})) === (await firstTrace({})));
|
|
220
|
+
console.log('seed 7, twice:', (await firstTrace({ traceSeed: 7 })) === (await firstTrace({ traceSeed: 7 })));
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
```output
|
|
224
|
+
no seed, twice: false
|
|
225
|
+
seed 7, twice: true
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Choosing what is traced
|
|
229
|
+
|
|
230
|
+
Typed methods ([Inspecting a host](inspection.md)) set what the host
|
|
231
|
+
records:
|
|
232
|
+
|
|
233
|
+
- **`traceConfigure(params)`** sets what every actor traces: `detail`
|
|
234
|
+
(`'summary'`, `'decisions'`, `'full'` or `'off'`), `values`, `sample`
|
|
235
|
+
(the share of new traces sampled, 0 to 1) and `rules`. It replaces the
|
|
236
|
+
previous configuration.
|
|
237
|
+
- **`traceWatch({ rules, seconds })`** adds rules in front of the
|
|
238
|
+
configured ones for a while (900 seconds by default), and answers `{ id
|
|
239
|
+
}`; **`traceUnwatch({ id })`** ends a watch early. A watch is how an
|
|
240
|
+
operator looks closely at one chart or one actor without tracing
|
|
241
|
+
everything.
|
|
242
|
+
- **`traceEnd()`** ends every open span now, as `close()` does.
|
|
243
|
+
- **`traceSpansDecode({ traces })`** reads the spans of a traces request
|
|
244
|
+
back, as above.
|
|
245
|
+
|
|
246
|
+
A rule matches by `chart`, `actor` (a trailing `*` makes it a prefix),
|
|
247
|
+
`event` (SCXML's prefix rule), `session` or `from` (`'host'`, `'actor'`,
|
|
248
|
+
`'timer'`, `'spawn'`, ...), and decides `sample` (`'keep'`, `'sample'`,
|
|
249
|
+
`'drop'` or a share) and `detail`, at most `perSecond` with a `burst`.
|
|
250
|
+
|
|
251
|
+
```js
|
|
252
|
+
import { Host } from '@tinyactors/node';
|
|
253
|
+
|
|
254
|
+
const host = new Host({ systemID: 'shop', telemetry: {} });
|
|
255
|
+
await host.traceConfigure({ detail: 'summary', sample: 0.01 });
|
|
256
|
+
console.log('1 trace in 100, summarized');
|
|
257
|
+
const watch = await host.traceWatch({ rules: [{ chart: 'checkout', sample: 'keep', detail: 'full' }], seconds: 60 });
|
|
258
|
+
console.log(`watch ${watch.id}: every checkout in full for a minute`);
|
|
259
|
+
host.close();
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
```output
|
|
263
|
+
1 trace in 100, summarized
|
|
264
|
+
watch 1: every checkout in full for a minute
|
|
265
|
+
```
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
# Testing your charts
|
|
2
|
+
|
|
3
|
+
A chart's logic can be tested without its I/O and without waiting for its
|
|
4
|
+
timeouts. Three things make that work:
|
|
5
|
+
|
|
6
|
+
- **I/O processors are your handlers**, so a test gives the host handlers
|
|
7
|
+
that record what the chart sent and answer as the test decides: now,
|
|
8
|
+
later, with an error, or never.
|
|
9
|
+
- **A `SimulatedClock`** moves only when the test moves it, so a timeout
|
|
10
|
+
of an hour takes no time.
|
|
11
|
+
- **`await host.idle()`** returns when the host has nothing left to do,
|
|
12
|
+
so the test then looks at a settled host.
|
|
13
|
+
|
|
14
|
+
## A test
|
|
15
|
+
|
|
16
|
+
The chart below asks a payment service to charge a card, retries twice
|
|
17
|
+
when no answer comes within 30 seconds, and gives up after the third
|
|
18
|
+
attempt. The test checks each step: the sends the chart made, its state
|
|
19
|
+
between them, and the end.
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import assert from 'node:assert/strict';
|
|
23
|
+
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
|
|
24
|
+
|
|
25
|
+
const chart = `
|
|
26
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
27
|
+
datamodel="ecmascript" name="payment" initial="charging">
|
|
28
|
+
<datamodel><data id="attempts" expr="0"/></datamodel>
|
|
29
|
+
<state id="charging">
|
|
30
|
+
<onentry>
|
|
31
|
+
<assign location="attempts" expr="attempts + 1"/>
|
|
32
|
+
<send type="urn:example:payments" event="charge" target="card"/>
|
|
33
|
+
<send event="timeout" delay="30s" id="timer"/>
|
|
34
|
+
</onentry>
|
|
35
|
+
<transition event="charged" target="paid"><cancel sendid="timer"/></transition>
|
|
36
|
+
<transition event="timeout" cond="attempts < 3" target="charging"/>
|
|
37
|
+
<transition event="timeout" target="failed"/>
|
|
38
|
+
</state>
|
|
39
|
+
<final id="paid"/>
|
|
40
|
+
<final id="failed"><onentry><log label="payment" expr="'gave up after ' + attempts"/></onentry></final>
|
|
41
|
+
</scxml>`;
|
|
42
|
+
|
|
43
|
+
/** A host running the chart on a simulated clock, recording its charges. */
|
|
44
|
+
function setup() {
|
|
45
|
+
const compiled = compileCharts([{ name: 'payment.scxml', text: chart }]);
|
|
46
|
+
const clock = new SimulatedClock();
|
|
47
|
+
const charges = [];
|
|
48
|
+
const logs = [];
|
|
49
|
+
const host = new Host({ systemID: 'test', ioProcessors: [{ type: 'urn:example:payments' }] }, {
|
|
50
|
+
clock,
|
|
51
|
+
ioProcessors: { 'urn:example:payments': (host, send) => charges.push({ at: clock.now, target: send.target }) },
|
|
52
|
+
log: (host, entry) => logs.push(entry.text),
|
|
53
|
+
});
|
|
54
|
+
host.addImage(compiled.image);
|
|
55
|
+
compiled.close();
|
|
56
|
+
return { host, clock, charges, logs };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The actor's state value, read with a typed method. */
|
|
60
|
+
const state = async (host, session) => (await host.actorState({ session })).value;
|
|
61
|
+
|
|
62
|
+
// It retries every 30 seconds and gives up after three attempts.
|
|
63
|
+
{
|
|
64
|
+
const { host, clock, charges, logs } = setup();
|
|
65
|
+
const payment = host.spawn(host.chart('payment'), { name: 'payment' });
|
|
66
|
+
await host.idle();
|
|
67
|
+
assert.deepEqual(charges, [{ at: 0, target: 'card' }]);
|
|
68
|
+
assert.equal(await state(host, payment), 'charging');
|
|
69
|
+
|
|
70
|
+
clock.increment(30_000);
|
|
71
|
+
await host.idle();
|
|
72
|
+
clock.increment(30_000);
|
|
73
|
+
await host.idle();
|
|
74
|
+
assert.deepEqual(charges.map((charge) => charge.at), [0, 30_000, 60_000]);
|
|
75
|
+
|
|
76
|
+
clock.increment(30_000);
|
|
77
|
+
await host.idle();
|
|
78
|
+
assert.deepEqual(logs, ['gave up after 3']);
|
|
79
|
+
assert.equal(host.actorByName('payment'), undefined, 'a final state ends the actor');
|
|
80
|
+
host.close();
|
|
81
|
+
console.log('ok: retries, then gives up');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// An answer before the timeout ends it, and no timer is left.
|
|
85
|
+
{
|
|
86
|
+
const { host, clock, charges } = setup();
|
|
87
|
+
const payment = host.spawn(host.chart('payment'), { name: 'payment' });
|
|
88
|
+
await host.idle();
|
|
89
|
+
host.send(payment, 'charged');
|
|
90
|
+
await host.idle();
|
|
91
|
+
assert.equal(host.actorByName('payment'), undefined);
|
|
92
|
+
assert.equal(host.nextDeadline, undefined, 'the timer was cancelled');
|
|
93
|
+
clock.increment(60_000);
|
|
94
|
+
await host.idle();
|
|
95
|
+
assert.equal(charges.length, 1);
|
|
96
|
+
host.close();
|
|
97
|
+
console.log('ok: an answer ends it');
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```output
|
|
102
|
+
ok: retries, then gives up
|
|
103
|
+
ok: an answer ends it
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The test answered by sending `charged` itself with `host.send`, which is
|
|
107
|
+
what the I/O processor's `send.answer('charged')` would do, without the
|
|
108
|
+
`sendid`. A test may equally answer from the handler.
|
|
109
|
+
|
|
110
|
+
## Stepping the clock
|
|
111
|
+
|
|
112
|
+
`clock.increment(ms)` moves the clock once. What is due by then runs once,
|
|
113
|
+
at the new time, and a delay it starts counts from the new time. So a
|
|
114
|
+
chart that ticks every second ticks once for an `increment(3500)`, and
|
|
115
|
+
its next tick is due a second later. To see every tick, step to each
|
|
116
|
+
deadline; `host.nextDeadline` says how far the next one is:
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
|
|
120
|
+
|
|
121
|
+
const compiled = compileCharts([{ name: 'ticker.scxml', text: `
|
|
122
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
123
|
+
datamodel="ecmascript" name="ticker" initial="ticking">
|
|
124
|
+
<datamodel><data id="n" expr="0"/></datamodel>
|
|
125
|
+
<state id="ticking">
|
|
126
|
+
<onentry><send event="tick" delay="1s"/></onentry>
|
|
127
|
+
<transition event="tick" target="ticking"><assign location="n" expr="n + 1"/><log expr="'tick ' + n"/></transition>
|
|
128
|
+
</state>
|
|
129
|
+
</scxml>` }]);
|
|
130
|
+
const clock = new SimulatedClock();
|
|
131
|
+
const host = new Host({ systemID: 'test' }, { clock, log: (host, entry) => console.log(entry.text, 'at', clock.now) });
|
|
132
|
+
host.addImage(compiled.image);
|
|
133
|
+
compiled.close();
|
|
134
|
+
host.spawn(host.chart('ticker'));
|
|
135
|
+
await host.idle();
|
|
136
|
+
|
|
137
|
+
clock.increment(3500); // one jump: one tick
|
|
138
|
+
await host.idle();
|
|
139
|
+
while (clock.now < 6500) { // step deadline by deadline
|
|
140
|
+
clock.increment(host.nextDeadline);
|
|
141
|
+
await host.idle();
|
|
142
|
+
}
|
|
143
|
+
host.close();
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```output
|
|
147
|
+
tick 1 at 3500
|
|
148
|
+
tick 2 at 4500
|
|
149
|
+
tick 3 at 5500
|
|
150
|
+
tick 4 at 6500
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**An input runs at the next turn's time.** `host.send` puts the event in
|
|
154
|
+
the queue at once, but the actor handles it in the host's next turn, at
|
|
155
|
+
the clock's time then, and `host.nextDeadline` still reads the last idle
|
|
156
|
+
turn's. So an input followed by an `increment` in the same tick is
|
|
157
|
+
handled after the clock moved, and a delay it starts counts from the new
|
|
158
|
+
time. Await `idle()` between the two when the input belongs before the
|
|
159
|
+
step:
|
|
160
|
+
|
|
161
|
+
```js
|
|
162
|
+
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
|
|
163
|
+
|
|
164
|
+
const compiled = compileCharts([{ name: 'hold.scxml', text: `
|
|
165
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
166
|
+
datamodel="ecmascript" name="hold" initial="s">
|
|
167
|
+
<state id="s">
|
|
168
|
+
<transition event="reserve"><log expr="'reserved'"/><send event="expire" delay="60s"/></transition>
|
|
169
|
+
<transition event="expire"><log expr="'expired'"/></transition>
|
|
170
|
+
</state>
|
|
171
|
+
</scxml>` }]);
|
|
172
|
+
const clock = new SimulatedClock();
|
|
173
|
+
const host = new Host({ systemID: 'test' }, { clock, log: (host, entry) => console.log(entry.text, 'at', clock.now) });
|
|
174
|
+
host.addImage(compiled.image);
|
|
175
|
+
compiled.close();
|
|
176
|
+
const actor = host.spawn(host.chart('hold'));
|
|
177
|
+
await host.idle();
|
|
178
|
+
|
|
179
|
+
host.send(actor, 'reserve');
|
|
180
|
+
console.log('nextDeadline right after the input:', host.nextDeadline);
|
|
181
|
+
clock.increment(59_000); // the input runs now, at 59000: the hold is due at 119000
|
|
182
|
+
await host.idle();
|
|
183
|
+
|
|
184
|
+
host.send(actor, 'reserve');
|
|
185
|
+
await host.idle(); // the input runs at 59000, before the step
|
|
186
|
+
clock.increment(60_000);
|
|
187
|
+
await host.idle();
|
|
188
|
+
host.close();
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
```output
|
|
192
|
+
nextDeadline right after the input: undefined
|
|
193
|
+
reserved at 59000
|
|
194
|
+
reserved at 59000
|
|
195
|
+
expired at 119000
|
|
196
|
+
expired at 119000
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Both holds came due at 119000, though the first was given at 0.
|
|
200
|
+
|
|
201
|
+
## Waiting for something to happen
|
|
202
|
+
|
|
203
|
+
`await host.idle()` waits until the host has nothing to do now and no
|
|
204
|
+
promise your handlers returned is pending. It does not wait for a
|
|
205
|
+
deadline on the runtime's clock, nor for a promise a handler starts and
|
|
206
|
+
does not return, and no call tells you when one actor ends. When a test runs on
|
|
207
|
+
the real clock, wait for the condition itself:
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
import { compileCharts, Host } from '@tinyactors/node';
|
|
211
|
+
|
|
212
|
+
/** Turns the host until `condition()` holds, checking every 10 ms. */
|
|
213
|
+
async function until(host, condition, ms = 5000) {
|
|
214
|
+
for (const end = Date.now() + ms; !condition(); ) {
|
|
215
|
+
if (Date.now() > end) throw new Error('timed out');
|
|
216
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
217
|
+
await host.idle();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const compiled = compileCharts([{ name: 'job.scxml', text: `
|
|
222
|
+
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
|
|
223
|
+
datamodel="ecmascript" name="job" initial="working">
|
|
224
|
+
<state id="working"><onentry><send event="finish" delay="50ms"/></onentry>
|
|
225
|
+
<transition event="finish" target="done"/>
|
|
226
|
+
</state>
|
|
227
|
+
<final id="done"/>
|
|
228
|
+
</scxml>` }]);
|
|
229
|
+
const host = new Host({ systemID: 'test' });
|
|
230
|
+
host.addImage(compiled.image);
|
|
231
|
+
compiled.close();
|
|
232
|
+
|
|
233
|
+
host.spawn(host.chart('job'), { name: 'job' });
|
|
234
|
+
await host.idle();
|
|
235
|
+
console.log('after idle():', host.actorByName('job') === undefined ? 'ended' : 'still running');
|
|
236
|
+
await until(host, () => host.actorByName('job') === undefined);
|
|
237
|
+
console.log('after until():', 'ended');
|
|
238
|
+
host.close();
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
```output
|
|
242
|
+
after idle(): still running
|
|
243
|
+
after until(): ended
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
A chart can also say it is done: a `<send type="urn:test:done">` in its
|
|
247
|
+
final state's `<onentry>`, to an I/O processor the test serves, resolves
|
|
248
|
+
whatever promise the test waits on.
|
|
249
|
+
|
|
250
|
+
## Habits that help
|
|
251
|
+
|
|
252
|
+
- **Await `idle()` after each input** that should have an effect before
|
|
253
|
+
the next assertion. A host runs on the event loop, so nothing has run
|
|
254
|
+
right after `host.send` returns.
|
|
255
|
+
- **Read state with the typed methods** (`actorState`, `actorContext`)
|
|
256
|
+
after an `idle()`: they read the host as it is when called
|
|
257
|
+
([Inspecting a host](inspection.md)).
|
|
258
|
+
- **Give actors names** to find them with `actorByName`, and to see that
|
|
259
|
+
one ended: a final state ends the actor and frees its name.
|
|
260
|
+
- **Close every host**, in a `finally` or the test framework's teardown.
|
|
261
|
+
A host on a `SimulatedClock` arms no timer, so a forgotten one does not
|
|
262
|
+
keep the test process alive, but it holds its memory until collected.
|
|
263
|
+
- **Test against both datamodels** if the charts will run on quickjs in
|
|
264
|
+
production: give the host `datamodel: 'quickjs'` in a second run
|
|
265
|
+
([The quickjs sandbox](quickjs.md)).
|
|
266
|
+
- **Start from a prepared world** with a [snapshot](snapshots.md): set a
|
|
267
|
+
host up once, take `host.snapshot()`, and `Host.restore` it at the
|
|
268
|
+
start of each test.
|
|
269
|
+
- **Make an unhandled error fail the test.** A handler that throws is
|
|
270
|
+
reported by the next `await host.idle()`, which rejects
|
|
271
|
+
([README](../../README.md#errors)), so a test that awaits `idle()`
|
|
272
|
+
sees it.
|
package/docs/values.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# JavaScript values
|
|
2
|
+
|
|
3
|
+
`@tinyactors/node` exports `encode(value)` and `decode(bytes)`, the one
|
|
4
|
+
conversion between JavaScript values and the value table's CBOR
|
|
5
|
+
(`tinyactors-core/docs/protocol.md`, "Values"). The addon writes with
|
|
6
|
+
core's streaming CBOR writer and reads with its streaming reader
|
|
7
|
+
(`src/values.c`); nothing is converted in JavaScript.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { decode, encode } from '@tinyactors/node';
|
|
11
|
+
|
|
12
|
+
const bytes = encode({ name: 'ada', score: 2n ** 60n, tags: ['a'], blob: new Uint8Array([1, 2]) });
|
|
13
|
+
const value = decode(bytes); // { name: 'ada', score: 1152921504606846976n, tags: ['a'], blob: Uint8Array [1, 2] }
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## The table
|
|
17
|
+
|
|
18
|
+
| JavaScript | CBOR | Back |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| `undefined` | undefined (`f7`) | `undefined` |
|
|
21
|
+
| `null` | null (`f6`) | `null` |
|
|
22
|
+
| `true`, `false` | true, false | `true`, `false` |
|
|
23
|
+
| a number for which `Number.isSafeInteger` holds, not `-0` | an integer | a number |
|
|
24
|
+
| any other number: a fraction, `-0`, `NaN`, the infinities, an integer past 2^53 | a float, in its shortest exact width | a number |
|
|
25
|
+
| a `bigint` from -2^64 to 2^64-1 | an integer | a number within ±(2^53-1), else a `bigint` |
|
|
26
|
+
| a string | text, valid UTF-8 | a string |
|
|
27
|
+
| a `Uint8Array` (a `Buffer` too; a view's own bytes) | bytes | a `Uint8Array` |
|
|
28
|
+
| an array | an array, a hole as undefined | an array |
|
|
29
|
+
| a plain object (its prototype `Object.prototype` or `null`) | a map of its own enumerable string keys, in `Object.keys` order | a plain object |
|
|
30
|
+
| an `Address` | tag 32 on its text (an actor reference) | an `Address` |
|
|
31
|
+
|
|
32
|
+
`undefined` and `null` stay distinct at every position: a key holding
|
|
33
|
+
`undefined` is kept, and an array's `undefined` is not `null`. Every
|
|
34
|
+
integer comes back as itself, as a number or a `bigint`; a float holding
|
|
35
|
+
an integer (`1.0` in CBOR) comes back as the number `1`, and goes out
|
|
36
|
+
again as an integer.
|
|
37
|
+
|
|
38
|
+
`encode` and `decode` keep an actor reference: an `Address` is tag 32 on
|
|
39
|
+
its text and comes back an `Address`, as in a Python host, so a
|
|
40
|
+
transport's `send.message` crosses a wire as it is. A chart has no
|
|
41
|
+
reference type: inside a value a chart reads (event data, params) an
|
|
42
|
+
`Address` is its text, and an actor reference a chart sends reaches you
|
|
43
|
+
as its address string.
|
|
44
|
+
|
|
45
|
+
## Refusals
|
|
46
|
+
|
|
47
|
+
What `encode` cannot write and `decode` cannot read throws a
|
|
48
|
+
`TinyactorsError`, never a value made up for it. Its `status` is core's
|
|
49
|
+
name for the reason:
|
|
50
|
+
|
|
51
|
+
- `TA_ERROR_UNSUPPORTED`: a value outside the table: a function, a
|
|
52
|
+
symbol, a `Date`, a `Map`, an instance of a class, an `ArrayBuffer`, a
|
|
53
|
+
`DataView` or a typed array other than `Uint8Array`;
|
|
54
|
+
- `TA_ERROR_INVALID`: a value the table cannot hold: a `bigint` past 64
|
|
55
|
+
bits, a string with a lone surrogate (refused, never replaced by
|
|
56
|
+
U+FFFD), nesting deeper than 64 (which a cycle reaches); and CBOR that
|
|
57
|
+
is malformed, truncated, followed by more bytes, a map key that is not
|
|
58
|
+
text, a tag other than 32, tag 32 on something but text, or a simple
|
|
59
|
+
value other than false, true, null and undefined.
|
|
60
|
+
|
|
61
|
+
A getter that throws while `encode` reads an object passes its own
|
|
62
|
+
exception through. `decode` takes a `Uint8Array` (a `Buffer` too) or an
|
|
63
|
+
`ArrayBuffer`, holding exactly one CBOR item; any other argument is a
|
|
64
|
+
`TypeError`.
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import { encode, TinyactorsError } from '@tinyactors/node';
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
encode({ at: new Date() });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof TinyactorsError) console.log(error.status); // "TA_ERROR_UNSUPPORTED"
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
A map key given twice keeps its last value. A key `"__proto__"` is an
|
|
77
|
+
own key of the object `decode` makes; no prototype is set and no setter
|
|
78
|
+
runs.
|
|
79
|
+
|
|
80
|
+
## Ownership and use
|
|
81
|
+
|
|
82
|
+
| What | Owner | Lifetime |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| the bytes given to `decode` | the caller | read during the call only; never held |
|
|
85
|
+
| the writer and the call's text | the environment's instance | an arena with a mark per call, released when the call returns; a getter that calls `encode` again allocates above the outer call and releases to its own mark |
|
|
86
|
+
| the `Uint8Array` `encode` returns, the value `decode` returns | the caller | independent of the input and of the addon |
|
|
87
|
+
|
|
88
|
+
Strings are copied once as UTF-8 for the writer (the copy Node-API
|
|
89
|
+
forces); only a string whose UTF-8 holds U+FFFD is read again as UTF-16,
|
|
90
|
+
to tell a lone surrogate from a real U+FFFD. Each array and object is
|
|
91
|
+
read as `encode` reaches it: do not change a value from a getter while it
|
|
92
|
+
is being encoded if you need a consistent whole. A subtree shared by two
|
|
93
|
+
keys is written twice. The module is initialized once per environment,
|
|
94
|
+
the main thread and each worker, each with its own instance.
|
|
95
|
+
|
|
96
|
+
## `encode` and a datamodel's `to_wire`
|
|
97
|
+
|
|
98
|
+
`encode` is the API's codec, for values the application holds. A chart's
|
|
99
|
+
data leaves an ECMAScript datamodel by its `to_wire`, whose rules are
|
|
100
|
+
JavaScript's for a value sent elsewhere: `undefined` at the top and in an
|
|
101
|
+
array is null, a key holding `undefined` is dropped, a `Date` is its JSON
|
|
102
|
+
form, a function is dropped, an `ArrayBuffer` or any view is its bytes
|
|
103
|
+
(the suite's `values.txt`, the `encode` cases). `encode` keeps
|
|
104
|
+
`undefined` apart from `null` and refuses the others instead, so a value
|
|
105
|
+
read back is the value written. `test/values.test.mjs` runs `values.txt`'s
|
|
106
|
+
`ecmascript` lines against `encode` and `decode`, with the cases where the
|
|
107
|
+
two differ listed and checked for what `encode` gives.
|