@tinyactors/node 0.2.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.
@@ -0,0 +1,494 @@
1
+ # In the browser: @tinyactors/wasm
2
+
3
+ `@tinyactors/wasm` is the same API as `@tinyactors/node`, built for the
4
+ web: core compiled to WebAssembly, with the package's JavaScript around
5
+ it. It runs in a page, in a Worker, and in Node.js and Bun too, where it
6
+ is the way on a platform with no addon (Windows). Everything in the other
7
+ guides holds for it, with the same names, shapes and errors; this guide
8
+ is what differs, and what a browser asks of you.
9
+
10
+ ```js
11
+ import { compileCharts, Host } from '@tinyactors/wasm';
12
+
13
+ const compiled = compileCharts([{ name: 'hello.scxml', text: `
14
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
15
+ datamodel="ecmascript" name="hello" initial="s">
16
+ <state id="s"><onentry><log expr="'hello from ' + _ioprocessors.scxml.location"/></onentry></state>
17
+ </scxml>` }]);
18
+ const host = new Host({ systemID: 'web' }, { log: (host, entry) => console.log(entry.text) });
19
+ host.addImage(compiled.image);
20
+ compiled.close();
21
+ host.spawn(host.chart('hello'));
22
+ await host.idle();
23
+ host.close();
24
+ ```
25
+
26
+ ```output
27
+ hello from tinyactors://web/#_scxml_1
28
+ ```
29
+
30
+ ## Contents
31
+
32
+ - [Loading: top-level await, or init()](#loading-top-level-await-or-init)
33
+ - [What a page needs: the floor and the CSP](#what-a-page-needs-the-floor-and-the-csp)
34
+ - [Bytes are Uint8Arrays](#bytes-are-uint8arrays)
35
+ - [The quickjs sandbox](#the-quickjs-sandbox)
36
+ - [Where charts run: declare your variables](#where-charts-run-declare-your-variables)
37
+ - [A dedicated Worker](#a-dedicated-worker)
38
+ - [The store: IndexedDB](#the-store-indexeddb)
39
+ - [Liveness: a page is not a process](#liveness-a-page-is-not-a-process)
40
+ - [Memory](#memory)
41
+ - [One store, two packages](#one-store-two-packages)
42
+
43
+ ## Loading: top-level await, or init()
44
+
45
+ `import { Host } from '@tinyactors/wasm'` is the line you write in
46
+ Node.js: the package's entry loads its module, `tinyactors.wasm` beside
47
+ its files, with top-level `await` (`fetch` and
48
+ `WebAssembly.compileStreaming` in a browser, the file in Node.js and
49
+ Bun), so every name works once the import settles.
50
+
51
+ Two places cannot take that. A Service Worker refuses a module graph with
52
+ top-level `await`, and some bundlers neither handle it nor place
53
+ `tinyactors.wasm` beside the bundle (esbuild does not follow
54
+ `new URL(..., import.meta.url)`). For them, **`@tinyactors/wasm/init`**
55
+ exports the same names and **`init(source?)`**, which loads the module
56
+ once; `source` is where it is (a URL, a `Response`, the bytes or a
57
+ compiled `WebAssembly.Module`), the package's own file when you pass
58
+ none. Until it settles, every call throws `TA_ERROR_STATE`:
59
+
60
+ ```js
61
+ import { Host, init } from '@tinyactors/wasm/init';
62
+
63
+ try {
64
+ new Host({ systemID: 'early' });
65
+ } catch (error) {
66
+ console.log('before init:', error.status);
67
+ }
68
+ await init(); // or init(new URL('/assets/tinyactors.wasm', location.href)), wherever your build put it
69
+ const host = new Host({ systemID: 'ready' });
70
+ console.log('after init: closed', host.closed);
71
+ host.close();
72
+ ```
73
+
74
+ ```output
75
+ before init: TA_ERROR_STATE
76
+ after init: closed false
77
+ ```
78
+
79
+ The package targets ES2022 and serves the module as
80
+ `@tinyactors/wasm/tinyactors.wasm`, so a bundler or a CDN can place it.
81
+
82
+ ## What a page needs: the floor and the CSP
83
+
84
+ **The browser floor** follows from what the module and the package use:
85
+ WebAssembly's `extended-const`, `multivalue`, `bulk-memory` and
86
+ `nontrapping-fptoint`, top-level `await` and
87
+ `String.prototype.isWellFormed`. By the engines' release notes that is
88
+ Chrome and Edge 114, Firefox 119 and Safari 16.4. Only Chromium (141) is
89
+ tested.
90
+
91
+ **The Content Security Policy.** The module needs `'wasm-unsafe-eval'` in
92
+ `script-src`. The native datamodel evaluates your charts' expressions and
93
+ scripts as JavaScript, so it needs `'unsafe-eval'` as well:
94
+
95
+ ```text
96
+ Content-Security-Policy: script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'
97
+ ```
98
+
99
+ Without `'unsafe-eval'`, under a `sandbox` policy without
100
+ `allow-same-origin`, or with Trusted Types enforced
101
+ (`require-trusted-types-for 'script'`, which guards string evaluation even
102
+ with `'unsafe-eval'`), `new Host(...)` throws `TinyactorsError` with
103
+ `TA_ERROR_UNSUPPORTED`, its message naming the directive, and
104
+ `compileCharts` skips its check of the charts' JavaScript syntax (it
105
+ parses with the same constructor). The quickjs sandbox is the datamodel
106
+ for such a page ([The quickjs sandbox](#the-quickjs-sandbox)).
107
+
108
+ ## Bytes are Uint8Arrays
109
+
110
+ What a host hands out as bytes (`compiled.image`, `host.hibernate()`,
111
+ `host.snapshot()`, `host.metrics()`, telemetry, `encode()`) is a
112
+ `Uint8Array`. `@tinyactors/node` gives `Buffer`s, a subclass of
113
+ `Uint8Array`, so code written against `Uint8Array` runs on both: use
114
+ `TextDecoder` for text, not `buf.toString()`, and compare or copy with the
115
+ typed array's own methods:
116
+
117
+ ```js
118
+ import { decode, encode } from '@tinyactors/wasm';
119
+
120
+ const bytes = encode({ sku: 'tea', qty: 2 });
121
+ console.log(bytes instanceof Uint8Array, bytes.length, 'bytes');
122
+ const copy = bytes.slice(); // a Uint8Array again, on both packages
123
+ console.log(decode(copy).sku, btoa(String.fromCharCode(...copy))); // base64, in a page as in Node.js
124
+ ```
125
+
126
+ ```output
127
+ true 14 bytes
128
+ tea omNza3VjdGVhY3F0eQI=
129
+ ```
130
+
131
+ `index.d.ts`, which both packages share, says `Uint8Array` everywhere.
132
+
133
+ ## The quickjs sandbox
134
+
135
+ `datamodel: 'quickjs'` works as it does in `@tinyactors/node`: the charts
136
+ run on quickjs-ng, inside the package's module, with the same limits,
137
+ realms, hibernation, migration and snapshots
138
+ ([the quickjs sandbox](quickjs.md)). It evaluates no chart text with
139
+ your engine, so it needs only `'wasm-unsafe-eval'`: it is the datamodel
140
+ for a page whose policy forbids `'unsafe-eval'`, and for charts you do
141
+ not trust.
142
+
143
+ ```js
144
+ import { Host } from '@tinyactors/wasm';
145
+
146
+ const host = new Host({ systemID: 'rules' }, { datamodel: 'quickjs', quickjs: { maxOps: 10000 } });
147
+ console.log(host.quickjsHeapBytes > 0);
148
+ host.close();
149
+ ```
150
+
151
+ ```output
152
+ true
153
+ ```
154
+
155
+ quickjs is in the one module every page downloads: 378 KiB with brotli
156
+ instead of 137 KiB without it (`mise run pack:wasm` reports the sizes).
157
+ Its engine's stack is the module's: at most 256 KiB, whatever
158
+ `quickjs.stackLimit` asks, so a recursion deeper than that is its
159
+ evaluation's `error.execution` (`RangeError: Maximum call stack size
160
+ exceeded`), as a deeper one is in `@tinyactors/node`. Its `Date` reads
161
+ the real clock, as in `@tinyactors/node`, whatever clock the host runs
162
+ on.
163
+
164
+ ## Where charts run: declare your variables
165
+
166
+ Chart code is trusted code here too: it runs in your engine, not in a
167
+ sandbox. Its realm is the host's own, made at its first chart:
168
+
169
+ | Where | A host's charts run in |
170
+ |---|---|
171
+ | a page | a hidden iframe of the page's origin, one per host, removed at `close()` |
172
+ | a Worker | the worker's own global (a Worker has no `document`) |
173
+ | Node.js, Bun | a `node:vm` context, as in `@tinyactors/node` |
174
+
175
+ A chart whose scripts declare nothing has a scope object per session in
176
+ that realm, as in `@tinyactors/node`. A chart whose scripts declare
177
+ (`var`, `function`, `let`, `const`, `class`) gets one function per chart,
178
+ which each session calls: its declarations are the session's own and its
179
+ functions close over them, for a few hundred bytes a session where
180
+ `@tinyactors/node` makes a `vm` context of 60 to 143 KB. Two things differ
181
+ from `@tinyactors/node`, and both are found, never silent:
182
+
183
+ - **An assignment to a name nobody declared**, in a chart-level
184
+ `<script>` (`visits = 0` with no `var`), puts the name on the host's
185
+ realm, shared by every session and chart of the host, where
186
+ `@tinyactors/node` gives it to the session. The host then refuses to
187
+ hibernate or snapshot the sessions of declaring charts, naming the
188
+ variable, rather than lose it. Declare every variable: a `<data>`, or
189
+ `var` in a chart-level script.
190
+ - **A function declared inside a block** of a transition's script (`if
191
+ (x) { function f() {} }`) is a variable of the session only once that
192
+ script ran, and hibernation does not keep it. Declare functions at the
193
+ top of a chart-level script.
194
+
195
+ ```js
196
+ import { compileCharts, Host } from '@tinyactors/wasm';
197
+
198
+ const chart = (name, script) => `
199
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
200
+ datamodel="ecmascript" name="${name}" initial="s">
201
+ <script>${script}</script>
202
+ <state id="s"><transition event="visit"><script>visit()</script><log expr="'${name}: ' + visits"/></transition></state>
203
+ </scxml>`;
204
+ const compiled = compileCharts([
205
+ { name: 'declared.scxml', text: chart('declared', 'var visits = 0; function visit() { visits += 1; }') },
206
+ { name: 'undeclared.scxml', text: chart('undeclared', 'visits = 0; function visit() { visits += 1; }') },
207
+ ]);
208
+ const host = new Host({ systemID: 'web' }, { log: (host, entry) => console.log(entry.text) });
209
+ host.addImage(compiled.image);
210
+ compiled.close();
211
+
212
+ const declared = host.spawn(host.chart('declared'));
213
+ host.send(declared, 'visit');
214
+ await host.idle();
215
+ host.wake(declared, host.hibernate(declared)); // out of memory and back, its visits with it
216
+ host.send(declared, 'visit');
217
+ await host.idle();
218
+
219
+ const undeclared = host.spawn(host.chart('undeclared'));
220
+ host.send(undeclared, 'visit');
221
+ await host.idle();
222
+ try {
223
+ host.hibernate(undeclared);
224
+ } catch (error) {
225
+ console.log('stays resident:', error.status, /'visits'.*declare it/.test(error.message));
226
+ }
227
+ host.close();
228
+ ```
229
+
230
+ ```output
231
+ declared: 1
232
+ declared: 2
233
+ undeclared: 1
234
+ stays resident: TA_ERROR_UNSUPPORTED true
235
+ ```
236
+
237
+ The rest of [Writing charts](charts.md#scripts) holds as it is: a chart
238
+ whose chart-level scripts declare with `let`, `const` or `class` keeps its
239
+ sessions resident, and a chart-level script that starts with
240
+ `'use strict'`, or a strict transition script that declares a `var`, is
241
+ refused when the image is added (one function cannot keep it). A
242
+ chart-level script that throws ends that session's chart-level scripts:
243
+ its `error.execution` says the later ones did not run.
244
+
245
+ ## A dedicated Worker
246
+
247
+ On a page the charts share the page's thread: a long macrostep is a
248
+ frame the page does not draw. Give tinyactors a Worker of its own and the
249
+ page stays responsive, and the charts' realm (the worker's global) holds
250
+ nothing of the page's own code. The page and the worker talk with
251
+ `postMessage`, and only values cross, as between any two systems:
252
+
253
+ ```js browser
254
+ const worker = new Worker(new URL('./counters-worker.mjs', import.meta.url), { type: 'module' });
255
+ // the worker says when it listens: a message sent before its module ran (it loads
256
+ // the package with top-level await) has no listener and is lost
257
+ await new Promise((resolve) => { worker.onmessage = resolve; });
258
+ const ask = (message) => new Promise((resolve) => {
259
+ worker.onmessage = (event) => resolve(event.data);
260
+ worker.postMessage(message);
261
+ });
262
+ console.log(await ask({ op: 'spawn', name: 'ada' }));
263
+ console.log(await ask({ op: 'visit', name: 'ada' }));
264
+ console.log(await ask({ op: 'visit', name: 'ada' }));
265
+ worker.terminate();
266
+ ```
267
+
268
+ ```output
269
+ spawned ada
270
+ ada: 1
271
+ ada: 2
272
+ ```
273
+
274
+ The worker's script, `counters-worker.mjs` beside the page's:
275
+
276
+ ```js browser
277
+ // file: counters-worker.mjs
278
+ import { compileCharts, Host } from '@tinyactors/wasm';
279
+
280
+ const compiled = compileCharts([{ name: 'counter.scxml', text: `
281
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
282
+ datamodel="ecmascript" name="counter" initial="s">
283
+ <datamodel><data id="visits" expr="0"/></datamodel>
284
+ <state id="s">
285
+ <transition event="visit">
286
+ <assign location="visits" expr="visits + 1"/>
287
+ <send event="counted" target="#_page" type="urn:page"><param name="visits" expr="visits"/></send>
288
+ </transition>
289
+ </state>
290
+ </scxml>` }]);
291
+ let answer = null; // the page's pending question
292
+ const host = new Host({ systemID: 'worker', ioProcessors: [{ type: 'urn:page' }] }, {
293
+ ioProcessors: { 'urn:page': (host, send) => answer?.(`${host.actorByName('ada') === send.session ? 'ada' : '?'}: ${send.data.visits}`) },
294
+ });
295
+ host.addImage(compiled.image);
296
+ compiled.close();
297
+
298
+ self.onmessage = async ({ data }) => {
299
+ const reply = new Promise((resolve) => { answer = resolve; });
300
+ if (data.op === 'spawn') {
301
+ host.spawn(host.chart('counter'), { name: data.name });
302
+ answer(`spawned ${data.name}`);
303
+ } else host.send(host.actorByName(data.name), 'visit');
304
+ await host.idle();
305
+ postMessage(await reply);
306
+ };
307
+ postMessage('ready');
308
+ ```
309
+
310
+ A module Worker has no import map: a bundler resolves
311
+ `@tinyactors/wasm` in its script as it does in the page's, or the script
312
+ imports the package's `index.mjs` by its URL.
313
+
314
+ ## The store: IndexedDB
315
+
316
+ The host does no I/O, in a browser as on a server: where hibernated
317
+ actors and snapshots live is yours. Node.js programs use a database or
318
+ files ([Hibernation](hibernation.md) uses SQLite); a page has IndexedDB,
319
+ which stores a `Uint8Array` as it is. Here a counter is hibernated into
320
+ it, and woken from it when an event comes:
321
+
322
+ ```js browser
323
+ import { compileCharts, Host } from '@tinyactors/wasm';
324
+
325
+ // IndexedDB, as promises: one object store of blobs, the session as the key
326
+ const done = (request) => new Promise((resolve, reject) => {
327
+ request.onsuccess = () => resolve(request.result);
328
+ request.onerror = () => reject(request.error);
329
+ });
330
+ const opening = indexedDB.open('tinyactors-blobs', 1);
331
+ opening.onupgradeneeded = () => opening.result.createObjectStore('blobs');
332
+ const db = await done(opening);
333
+ const blobs = (mode) => db.transaction('blobs', mode).objectStore('blobs');
334
+ const store = {
335
+ put: (session, blob) => done(blobs('readwrite').put(blob, String(session))),
336
+ take: async (session) => {
337
+ const blob = await done(blobs('readonly').get(String(session)));
338
+ await done(blobs('readwrite').delete(String(session)));
339
+ return blob;
340
+ },
341
+ };
342
+
343
+ const compiled = compileCharts([{ name: 'counter.scxml', text: `
344
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
345
+ datamodel="ecmascript" name="counter" initial="s">
346
+ <datamodel><data id="count" expr="0"/></datamodel>
347
+ <state id="s">
348
+ <transition event="inc"><assign location="count" expr="count + 1"/></transition>
349
+ <transition event="report"><log expr="'count ' + count"/></transition>
350
+ </state>
351
+ </scxml>` }]);
352
+ const host = new Host({ systemID: 'web' }, {
353
+ log: (host, entry) => console.log(entry.text),
354
+ wake: async (host, session) => host.wake(session, await store.take(session)), // idle() waits for it
355
+ });
356
+ host.addImage(compiled.image);
357
+ compiled.close();
358
+
359
+ const counter = host.spawn(host.chart('counter'));
360
+ host.send(counter, 'inc');
361
+ await host.idle();
362
+ host.sweep(100, 100); // a first sweep marks; the actor has not run since
363
+ for (const session of host.sweep(100, 100)) await store.put(session, host.hibernate(session));
364
+ console.log('stored:', await done(blobs('readonly').count()));
365
+
366
+ host.send(counter, 'inc'); // it is woken from the store first
367
+ host.send(counter, 'report');
368
+ await host.idle();
369
+ host.close();
370
+ db.close();
371
+ await done(indexedDB.deleteDatabase('tinyactors-blobs'));
372
+ ```
373
+
374
+ ```output
375
+ stored: 1
376
+ count 2
377
+ ```
378
+
379
+ ## Liveness: a page is not a process
380
+
381
+ In Node.js an open host with a pending deadline keeps the process alive.
382
+ A page has no such process: its hosts run while the page does. Two things
383
+ follow.
384
+
385
+ - **Timers are late in a hidden tab.** A host runs its turns as
386
+ `MessageChannel` messages and arms one `setTimeout` at its next
387
+ deadline. A browser throttles the timers of a hidden tab (Chromium to
388
+ about once a second, and to once a minute after a few minutes hidden),
389
+ so a delayed `<send>` or a timeout comes late there; it is never lost,
390
+ and runs when the timer fires. A dedicated Worker is throttled less, but
391
+ is not exempt.
392
+ - **A page that goes away takes its actors with it.** A tab can be
393
+ closed, discarded or frozen without notice. Keep what must survive in
394
+ your store: hibernate actors as they go cold, or snapshot the host when
395
+ the page is hidden (`visibilitychange`, the last event a page is sure to
396
+ get), and restore it when the page loads again:
397
+
398
+ ```js browser
399
+ import { compileCharts, Host, SimulatedClock } from '@tinyactors/wasm';
400
+
401
+ const done = (request) => new Promise((resolve, reject) => {
402
+ request.onsuccess = () => resolve(request.result);
403
+ request.onerror = () => reject(request.error);
404
+ });
405
+ const opening = indexedDB.open('tinyactors-host', 1);
406
+ opening.onupgradeneeded = () => opening.result.createObjectStore('hosts');
407
+ const db = await done(opening);
408
+ const hosts = (mode) => db.transaction('hosts', mode).objectStore('hosts');
409
+
410
+ const config = { systemID: 'web' };
411
+ const options = () => ({ clock: new SimulatedClock(), log: (host, entry) => console.log(entry.text) });
412
+ const compiled = compileCharts([{ name: 'cart.scxml', text: `
413
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
414
+ datamodel="ecmascript" name="cart" initial="open">
415
+ <datamodel><data id="items" expr="[]"/></datamodel>
416
+ <state id="open">
417
+ <transition event="add"><script>items.push(_event.data)</script></transition>
418
+ <transition event="show"><log expr="'cart: ' + items.join(', ')"/></transition>
419
+ </state>
420
+ </scxml>` }]);
421
+
422
+ // at load: the host as the page left it, else a new one
423
+ async function load() {
424
+ const saved = await done(hosts('readonly').get('host'));
425
+ if (saved !== undefined) return Host.restore(saved, config, options());
426
+ const host = new Host(config, options());
427
+ host.addImage(compiled.image);
428
+ host.spawn(host.chart('cart'), { name: 'cart' });
429
+ return host;
430
+ }
431
+ // when the page is hidden: a snapshot needs a quiescent host, so after idle()
432
+ async function save(host) {
433
+ await host.idle();
434
+ await done(hosts('readwrite').put(host.snapshot(), 'host'));
435
+ }
436
+
437
+ const host = await load();
438
+ document.addEventListener('visibilitychange', () => {
439
+ if (document.visibilityState === 'hidden') save(host);
440
+ });
441
+ host.send(host.actorByName('cart'), 'add', 'tea');
442
+ await save(host); // what the event would do, here at once
443
+ host.close();
444
+
445
+ const again = await load(); // the page loaded again
446
+ again.send(again.actorByName('cart'), 'add', 'cake');
447
+ again.send(again.actorByName('cart'), 'show');
448
+ await again.idle();
449
+ again.close();
450
+ compiled.close();
451
+ db.close();
452
+ await done(indexedDB.deleteDatabase('tinyactors-host'));
453
+ ```
454
+
455
+ ```output
456
+ cart: tea, cake
457
+ ```
458
+
459
+ [Snapshots](snapshots.md) says what a snapshot holds and what it does
460
+ not (the services your program runs, which a restore announces again).
461
+
462
+ ## Memory
463
+
464
+ - **WebAssembly memory never shrinks.** The host's memory is the module's
465
+ linear memory, which grows and is never given back: a page keeps its
466
+ peak. Hibernating actors makes room for others in it, not a smaller
467
+ page. A snapshot is packed in that memory before it is copied out, so a
468
+ 100 MB snapshot leaves the memory 100 MB larger.
469
+ - **4 GiB at most.** wasm32 addresses 4 GiB, and a region that grows is
470
+ copied before the old one is freed, so one host holds about two million
471
+ resident actors at most, where `@tinyactors/node` goes on.
472
+ - What the package hands out (bytes, values, views) is never a view of
473
+ that memory: it stays valid when the memory grows.
474
+
475
+ [Capacity and memory](capacity.md) has what an actor costs.
476
+
477
+ ## One store, two packages
478
+
479
+ A Node.js server on `@tinyactors/node` and a browser client on
480
+ `@tinyactors/wasm` can share a database, but not the bytes a host packs:
481
+
482
+ - **A snapshot does not cross.** It is the host's memory as the build that
483
+ made it lays it out, and the addon is a 64-bit build where the module
484
+ is a 32-bit one. Each package labels its snapshots with its own name and
485
+ refuses the other's with `TA_ERROR_INVALID`, the message naming the
486
+ package that made it.
487
+ - **A hibernation blob belongs to its host.** It wakes in the host that
488
+ hibernated it, or in one restored from that host's snapshot, which the
489
+ other package cannot restore; another host's blob throws
490
+ `TA_ERROR_INVALID`. Keep the server's blobs and the client's apart in
491
+ the store, by host.
492
+ - **Values cross.** `encode` and `decode` are one format in both packages
493
+ ([Other systems](other-systems.md)): move work between the server and
494
+ the client as events and their data, from one system to another.