@tinyactors/wasm 0.0.0-stage → 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/lib/host.mjs ADDED
@@ -0,0 +1,2049 @@
1
+ // The Host over the module (docs/browser.md; the addon's src/host.c,
2
+ // loop.c, effects.c and methods.c, translated): the class, its inputs, the
3
+ // loop on the event loop, the effects as thin views, the typed methods,
4
+ // the invoked services, hibernation, migration and snapshots. What reads
5
+ // or writes core's structs is the C layer's (wasm/src/); this file makes
6
+ // and calls JavaScript objects and schedules.
7
+ //
8
+ // Who holds what:
9
+ // - a Host holds its state (HostState, the owner the module's imports
10
+ // name, held by the module weakly) and, under a symbol, its handlers
11
+ // object (the handlers, the pending typed methods' handlers, the
12
+ // running services): a handler that closes over its host makes a cycle
13
+ // the collector sees through;
14
+ // - the state holds the Host only weakly (a WeakRef), so a FinalizationRegistry
15
+ // whose token is the state frees a host nobody closed;
16
+ // - a pending turn (setImmediate, or a MessageChannel message) and the
17
+ // deadline's timer hold the Host, as the addon's do.
18
+ import { Address, addressText, isAddress } from './address.mjs';
19
+ import * as cbor from './cbor.mjs';
20
+ import { bytesOf, countOf, inputOptions, onlyKnown, optionalText, sessionOf, textOf } from './checks.mjs';
21
+ import { TinyactorsError, coreError, refusal } from './errors.mjs';
22
+ import { NativeDatamodel } from './datamodel.mjs';
23
+ import { QuickJSDatamodel } from './quickjs.mjs';
24
+ import { policyRefusal } from './realms.mjs';
25
+ import { instance } from './state.mjs';
26
+
27
+ // ---- core's constants (tinyactors/host.h, system.h) ---------------------------------
28
+
29
+ const FIELD = {
30
+ KIND: 1, SEGMENT: 2, SESSION: 4, TOKEN: 6, IO_PROCESSOR: 7, FLAGS: 8, MIGRATION: 9, PAYLOAD: 10, DATAMODEL: 11,
31
+ CHART: 13, MIGRATED: 14, FAILED: 15, PENDING: 16,
32
+ TARGET: 32, EVENT: 33, SENDID: 34, AUXILIARY: 35, TRACEPARENT: 36, ORIGIN: 37, WIRE: 64,
33
+ };
34
+ const EFFECT = {
35
+ SEND: 1, INVOKE: 3, UNINVOKE: 4, LOG: 5, WAKE: 8,
36
+ MIGRATED: 16, MIGRATION_DONE: 17, REPLY: 23,
37
+ };
38
+ const FLAG_RESTORED = 2;
39
+ const EVENT_FROM_INVOKE = 1, EVENT_INVOKE_DONE = 2, EVENT_ERROR_COMMUNICATION = 4;
40
+ const INVOCATION_FAILURE = EVENT_ERROR_COMMUNICATION | EVENT_FROM_INVOKE;
41
+ const NIL = 0xFFFFFFFF;
42
+ const TA_OK = 0, TA_ERROR_INVALID = -3, TA_ERROR_STALE = -5, TA_ERROR_UNSUPPORTED = -7;
43
+ const MIGRATE_WAKE = 1;
44
+
45
+ // The layer's own (wasm/src/web.h, loop.c).
46
+ const NEXT = { YIELD: 0, IDLE: 1, EXHAUSTED: 2, FAULT: 3, REFUSED: 4 };
47
+ const OUTPUT = { METRICS: 1, BLOB: 2, SNAPSHOT: 3, CONFIG: 4, TRACES: 5, LOGS: 6 };
48
+ const TAKE_REFUSED = 0xFFFFFFFF;
49
+ const DATAMODEL_NATIVE = 1, DATAMODEL_QUICKJS = 2;
50
+ const EVENT_WORDS = 19;
51
+ const SLICE = 256;
52
+ const CONFIG_ERROR = 8192;
53
+ // The longest delay setTimeout keeps (2^31 - 1 ms); a deadline further away
54
+ // is armed at this, and the idle turn it wakes arms the rest.
55
+ const TIMEOUT_MAX = 2147483647;
56
+ const LABEL = 'tinyactors-wasm';
57
+
58
+ const POOLS = [
59
+ 'the host\'s allocator refused memory for the host\'s own (TA_POOL_NONE)',
60
+ 'the host\'s allocator refused memory for the pool of events (TA_POOL_EVENTS)',
61
+ 'the host\'s allocator refused memory for the pool of instances and strings (TA_POOL_SLAB)',
62
+ 'the host\'s allocator refused memory for the pool of timers (TA_POOL_TIMERS)',
63
+ 'the host\'s allocator refused memory for the pool of actors (TA_POOL_ACTORS)',
64
+ 'the host\'s allocator refused memory for the pool of requests (TA_POOL_REQUESTS)',
65
+ ];
66
+
67
+ const KNOWN_OPTIONS = ['ioProcessors', 'transport', 'log', 'clock', 'telemetry', 'wake', 'migrated', 'migrationDone',
68
+ 'services', 'datamodel', 'quickjs'];
69
+ const HANDLER_FUNCTIONS = ['log', 'transport', 'telemetry', 'wake', 'migrated', 'migrationDone'];
70
+ const HANDLER_MAPS = ['ioProcessors', 'services'];
71
+
72
+ // The handlers' key on a Host: not enumerable, not configurable; writable,
73
+ // so close() drops it.
74
+ const HANDLERS = Symbol('tinyactors.handlers');
75
+ // What only the layer passes the constructors of views and records.
76
+ const MAKING = Symbol('making');
77
+
78
+ // ---- the event loop's macrotasks ---------------------------------------------------------
79
+
80
+ // A turn after the event loop ran: setImmediate where it exists (node,
81
+ // bun: the addon's, so liveness is the same), else a MessageChannel
82
+ // message (a page, a Worker: a chained setTimeout(0) waits 4 ms).
83
+ const macrotask = (() => {
84
+ if (typeof globalThis.setImmediate === 'function') {
85
+ return { arm: (fn, host) => globalThis.setImmediate(fn, host), clear: (handle) => globalThis.clearImmediate(handle) };
86
+ }
87
+ const queue = [];
88
+ let channel = null;
89
+ const run = () => {
90
+ const entry = queue.shift();
91
+ if (entry !== undefined && !entry.cancelled) entry.fn(entry.host);
92
+ };
93
+ return {
94
+ arm(fn, host) {
95
+ if (channel === null) {
96
+ channel = new MessageChannel();
97
+ channel.port1.onmessage = run;
98
+ }
99
+ const entry = { fn, host, cancelled: false };
100
+ queue.push(entry);
101
+ channel.port2.postMessage(null);
102
+ return entry;
103
+ },
104
+ clear(entry) { entry.cancelled = true; },
105
+ };
106
+ })();
107
+
108
+ // ---- the hosts nobody closed ------------------------------------------------------------------
109
+
110
+ const unclosed = new FinalizationRegistry((state) => {
111
+ try {
112
+ state.release();
113
+ } catch {
114
+ // a poisoned module frees nothing more
115
+ }
116
+ });
117
+
118
+ // What Host.restore passes the constructor: taken at its entry.
119
+ let restoring = null;
120
+
121
+ // The state of a Host's views and records, by the private brand of each class.
122
+ let stateOf;
123
+
124
+ // ---- the host's state: the owner of its imports ---------------------------------------------
125
+
126
+ class HostState {
127
+ constructor(module, self) {
128
+ this.module = module;
129
+ this.fn = module.fn;
130
+ this.self = new WeakRef(self);
131
+ this.pointer = 0;
132
+ this.id = 0;
133
+ this.scratch = 0;
134
+ this.open = false;
135
+ this.depth = 0;
136
+ this.turning = false;
137
+ this.closing = false;
138
+ this.immediate = null;
139
+ this.timer = null;
140
+ this.idle = null; // {promise, resolve, reject}
141
+ this.promises = 0;
142
+ this.error = null; // [the first error kept]
143
+ this.ticksPerSecond = 0;
144
+ this.encoder = false;
145
+ this.telemetry = false;
146
+ this.simulated = null; // a SimulatedClock's state
147
+ this.processors = 0;
148
+ this.datamodelName = 'native';
149
+ this.native = null; // the native datamodel (datamodel.mjs)
150
+ this.quickjs = null; // or quickjs's (quickjs.mjs)
151
+ this.effective = null;
152
+ this.taken = null;
153
+ this.endings = null;
154
+ this.reason = '';
155
+ }
156
+
157
+ host() { return this.self.deref(); }
158
+ handlers() { return this.host()?.[HANDLERS]; }
159
+
160
+ // ---- errors ----
161
+
162
+ keep(error) {
163
+ if (this.error === null) this.error = [error];
164
+ }
165
+
166
+ takeKept() {
167
+ const kept = this.error;
168
+ this.error = null;
169
+ return kept;
170
+ }
171
+
172
+ // The import guard's: what an import's work threw.
173
+ raised(error) { this.keep(error); }
174
+
175
+ // ---- a call -----
176
+
177
+ // Runs `body` as one call of the host: refused once closed, its arena
178
+ // memory above a mark released on every path, a close() a handler asked
179
+ // for done when the outermost call returns.
180
+ call(body) {
181
+ if (!this.open) throw refusal('TA_ERROR_STATE', 'the Host is closed');
182
+ this.depth++;
183
+ try {
184
+ return this.module.scoped(this.scratch, body);
185
+ } finally {
186
+ this.leave();
187
+ }
188
+ }
189
+
190
+ leave() {
191
+ this.depth--;
192
+ if (this.depth === 0 && !this.turning && this.closing) this.closeNow();
193
+ }
194
+
195
+ advance() { this.fn.ta_web_host_advance(this.pointer); }
196
+
197
+ // An input came: a turn, one pending at a time.
198
+ schedule() {
199
+ if (!this.open || this.turning || this.immediate !== null) return;
200
+ const host = this.host();
201
+ if (host !== undefined) this.immediate = macrotask.arm(turnOf, host);
202
+ }
203
+
204
+ // ---- the imports ----
205
+
206
+ effect(index, extra) {
207
+ switch (this.word(index, FIELD.KIND)) {
208
+ case EFFECT.SEND: this.dispatchSend(index); break;
209
+ case EFFECT.LOG: this.dispatchLog(index); break;
210
+ case EFFECT.WAKE: this.dispatchWake(index); break;
211
+ case EFFECT.MIGRATED: this.dispatchMigrated(index); break;
212
+ case EFFECT.MIGRATION_DONE: this.dispatchMigrationDone(index); break;
213
+ case EFFECT.INVOKE: this.dispatchInvoke(index); break;
214
+ case EFFECT.UNINVOKE: this.dispatchUninvoke(index); break;
215
+ case EFFECT.REPLY: this.dispatchReply(index, extra); break;
216
+ default: break;
217
+ }
218
+ return TA_OK;
219
+ }
220
+
221
+ output(kind, length) {
222
+ const module = this.module;
223
+ if (kind === OUTPUT.TRACES || kind === OUTPUT.LOGS) {
224
+ const signal = kind === OUTPUT.TRACES ? 'traces' : 'logs';
225
+ if (length === TAKE_REFUSED) {
226
+ this.keep(refusal('TA_ERROR_NO_MEMORY', `the take of ${signal} was refused`));
227
+ return TA_OK;
228
+ }
229
+ this.export(signal, module.copyOut(module.word(0), length));
230
+ return TA_OK;
231
+ }
232
+ const bytes = module.copyOut(module.word(0), module.word(1));
233
+ if (kind === OUTPUT.CONFIG) {
234
+ this.effective = module.scoped(module.scratch, () => {
235
+ const [at, n] = module.copyIn(module.scratch, bytes);
236
+ return cbor.read(module, module.scratch, at, n);
237
+ });
238
+ } else this.taken = bytes;
239
+ return TA_OK;
240
+ }
241
+
242
+ clock(which) {
243
+ if (which === 2) return Date.now() * 1e6; // quickjs's Date: the real wall clock
244
+ if (this.simulated !== null) return Number(this.simulated.ns);
245
+ return which === 0 ? performance.now() * 1e6 : Date.now() * 1e6;
246
+ }
247
+
248
+ // The native datamodel's entries (wasm/src/datamodel.c, datamodel.mjs).
249
+ datamodel(entry, slot) { return this.native === null ? TA_ERROR_UNSUPPORTED : this.native.entry(entry, slot); }
250
+
251
+ // ---- effect fields ----
252
+
253
+ number(index, field) { return BigInt.asUintN(64, this.fn.ta_web_effect_number(this.pointer, index, field)); }
254
+ // u32 answers read as i32 by JavaScript: TA_NIL is 0xFFFFFFFF, not -1
255
+ word(index, field) { return this.fn.ta_web_effect_word(this.pointer, index, field) >>> 0; }
256
+
257
+ text(index, field) {
258
+ const at = this.fn.ta_web_effect_text(this.pointer, index, field) >>> 0;
259
+ return this.module.string(at, this.module.word(0));
260
+ }
261
+
262
+ acks() { return this.fn.ta_web_host_acks(this.pointer); }
263
+
264
+ // The data of effect `index`: its payload's value, copied into the
265
+ // application's realm.
266
+ data(index) {
267
+ const payload = this.number(index, FIELD.PAYLOAD);
268
+ if (payload === 0n || this.word(index, FIELD.DATAMODEL) === NIL) return undefined;
269
+ return this.exported(payload);
270
+ }
271
+
272
+ exported(payload) {
273
+ if (this.quickjs !== null) return this.quickjs.exported(payload);
274
+ return this.native === null ? undefined : this.native.exported(payload);
275
+ }
276
+
277
+ // The payload a value is for the target's datamodel: 0n for none
278
+ // (undefined), a TypeError for a chart whose datamodel takes no data.
279
+ // `target` is {session} or {segment, chart}.
280
+ payload(value, target) {
281
+ if (value === undefined) return 0n;
282
+ const module = this.module;
283
+ module.setWord64(0, target.session ?? 0n);
284
+ module.setWord(2, target.segment ?? 0);
285
+ module.setWord(3, target.chart ?? 0);
286
+ const takes = this.fn.ta_web_host_takes_data(this.pointer);
287
+ if (takes === TA_ERROR_STALE) throw refusal('TA_ERROR_STALE', 'no live session takes this data');
288
+ if (takes !== 1) throw new TypeError('the chart\'s datamodel takes no data');
289
+ return (this.quickjs ?? this.native).payload(value);
290
+ }
291
+
292
+ release(payload) {
293
+ if (payload !== 0n && this.open) this.fn.ta_web_payload_drop(this.pointer, Number(payload & 0xFFFFFFFFn), Number(payload >> 32n));
294
+ }
295
+
296
+ // ---- promises a handler returned ----
297
+
298
+ // Followed with `then`, counted, so idle() waits for them.
299
+ follow(result) {
300
+ if (result === null || (typeof result !== 'object' && typeof result !== 'function')) return;
301
+ let then;
302
+ try {
303
+ then = result.then;
304
+ if (typeof then !== 'function') return;
305
+ then.call(result, () => this.settled(), (reason) => {
306
+ this.settled();
307
+ throw reason;
308
+ });
309
+ } catch {
310
+ return; // not followed: idle() does not wait for it
311
+ }
312
+ this.promises++;
313
+ }
314
+
315
+ settled() {
316
+ if (this.promises > 0 && --this.promises === 0 && this.open && this.idle !== null) {
317
+ this.schedule();
318
+ if (this.error !== null && this.depth === 0 && !this.turning) throw this.takeKept()[0];
319
+ }
320
+ }
321
+
322
+ // ---- the loop -----
323
+
324
+ turn() {
325
+ this.turning = true;
326
+ let next;
327
+ try {
328
+ next = this.fn.ta_web_turn(this.pointer);
329
+ } finally {
330
+ this.turning = false;
331
+ }
332
+ return next;
333
+ }
334
+
335
+ turnError(next) {
336
+ const kept = this.takeKept();
337
+ if (kept !== null) return kept;
338
+ if (next === NEXT.EXHAUSTED) {
339
+ const pool = this.fn.ta_web_host_detail(this.pointer, 0);
340
+ return [refusal('TA_ERROR_NO_MEMORY', POOLS[pool] ?? 'the host\'s allocator refused memory for a pool (TA_POOL_*)')];
341
+ }
342
+ if (next === NEXT.FAULT) {
343
+ return [refusal(this.module.statusName(this.fn.ta_web_host_detail(this.pointer, 1)), 'the host\'s run faulted')];
344
+ }
345
+ return null;
346
+ }
347
+
348
+ clearTimer() {
349
+ if (this.timer !== null) clearTimeout(this.timer);
350
+ this.timer = null;
351
+ }
352
+
353
+ settle(error) {
354
+ const idle = this.idle;
355
+ if (idle === null) return;
356
+ this.idle = null;
357
+ if (error !== null) idle.reject(error[0]);
358
+ else idle.resolve(undefined);
359
+ }
360
+
361
+ // One turn, from a macrotask or the timer: the turn's first error
362
+ // rejects a waiting idle(); with none waiting it is thrown from here,
363
+ // after the next turn is scheduled or the timer armed.
364
+ run(byTimer) {
365
+ if (byTimer) this.timer = null;
366
+ else this.immediate = null;
367
+ if (!this.open || this.turning || this.depth > 0) return;
368
+ this.depth++;
369
+ let next, error;
370
+ try {
371
+ next = this.turn();
372
+ } catch (thrown) {
373
+ next = NEXT.FAULT;
374
+ this.keep(thrown); // the module stopped (a trap): its error
375
+ }
376
+ error = this.turnError(next);
377
+ let settle = false;
378
+ if (next === NEXT.YIELD && !this.closing) {
379
+ this.schedule();
380
+ } else {
381
+ this.clearTimer();
382
+ if (next === NEXT.IDLE && this.simulated === null && !this.closing && this.open) {
383
+ const delay = this.fn.ta_web_host_delay(this.pointer);
384
+ const host = this.host();
385
+ if (delay >= 0 && host !== undefined) this.timer = setTimeout(timerOf, Math.min(delay, TIMEOUT_MAX), host);
386
+ }
387
+ settle = next !== NEXT.IDLE || this.promises === 0;
388
+ }
389
+ if (error === null) error = this.takeKept();
390
+ // a close a handler asked for runs at the leave: the waiter is kept
391
+ // from it (it would reject it as closed before idle) and settles after
392
+ const closing = this.closing && this.depth === 1;
393
+ const waiter = closing ? this.idle : null;
394
+ if (closing) this.idle = null;
395
+ this.leave();
396
+ if (closing) {
397
+ if (error === null) error = this.takeKept(); // the last take's
398
+ this.idle = waiter;
399
+ settle = true;
400
+ }
401
+ if (error !== null && this.idle !== null) {
402
+ this.settle(error);
403
+ error = null;
404
+ } else if (settle) this.settle(null);
405
+ if (error !== null) throw error[0];
406
+ }
407
+
408
+ // ---- the stop ----
409
+
410
+ quiet() {
411
+ this.clearTimer();
412
+ if (this.immediate !== null) macrotask.clear(this.immediate);
413
+ this.immediate = null;
414
+ if (this.idle !== null) this.settle([refusal('TA_ERROR_STATE', 'the Host was closed before it was idle')]);
415
+ }
416
+
417
+ closeNow() {
418
+ this.closing = false;
419
+ this.endings = null;
420
+ this.quiet();
421
+ if (this.encoder && this.telemetry) {
422
+ this.endings = [];
423
+ this.depth++;
424
+ try {
425
+ this.fn.ta_web_host_end(this.pointer);
426
+ } catch (error) {
427
+ this.keep(error);
428
+ }
429
+ this.depth--;
430
+ this.closing = false; // a close asked by a handler there: this one
431
+ this.quiet();
432
+ }
433
+ this.release();
434
+ const host = this.host();
435
+ if (host !== undefined) host[HANDLERS] = undefined;
436
+ }
437
+
438
+ // The host freed in the module: by close(), or by the registry.
439
+ release() {
440
+ if (this.pointer === 0) return;
441
+ const pointer = this.pointer;
442
+ this.pointer = 0;
443
+ this.open = false;
444
+ unclosed.unregister(this);
445
+ this.module.unregister(this.id);
446
+ try {
447
+ if (!this.module.poisoned) this.module.call('ta_web_host_free', pointer);
448
+ } finally {
449
+ this.native?.free(); // its realm: a page's iframe is removed
450
+ }
451
+ }
452
+
453
+ // ---- dispatch ----
454
+
455
+ // A handler's call: its error kept for the turn, its promise followed.
456
+ invoke(handler, args) {
457
+ let result;
458
+ try {
459
+ result = handler(...args);
460
+ } catch (error) {
461
+ this.keep(error);
462
+ return;
463
+ }
464
+ this.follow(result);
465
+ }
466
+
467
+ dispatchSend(index) {
468
+ const processor = this.word(index, FIELD.IO_PROCESSOR);
469
+ if (processor === NIL) {
470
+ this.dispatchServiceSend(index);
471
+ return;
472
+ }
473
+ if (processor > this.processors) return;
474
+ const host = this.host();
475
+ const handlers = this.handlers();
476
+ if (host === undefined || handlers === undefined) return;
477
+ const view = new Send(MAKING, this, index, processor);
478
+ const handler = handlers.processors?.[processor];
479
+ if (typeof handler !== 'function') { // no handler: a failed completion
480
+ try {
481
+ replyTo(view, FAILURE);
482
+ } catch (error) {
483
+ this.keep(error);
484
+ }
485
+ return;
486
+ }
487
+ try {
488
+ const result = handler(host, view);
489
+ followSend(this, view, result);
490
+ } catch (error) {
491
+ failUnanswered(view);
492
+ this.keep(error);
493
+ }
494
+ }
495
+
496
+ dispatchLog(index) {
497
+ const handler = this.handlers()?.log;
498
+ if (typeof handler !== 'function') return;
499
+ this.invoke(handler, [this.host(), new LogEntry(MAKING, this, index)]);
500
+ }
501
+
502
+ dispatchMigrated(index) {
503
+ const handler = this.handlers()?.migrated;
504
+ if (typeof handler !== 'function') return;
505
+ this.invoke(handler, [this.host(), new Migrated(MAKING, this, index)]);
506
+ }
507
+
508
+ dispatchWake(index) {
509
+ const handler = this.handlers()?.wake;
510
+ if (typeof handler !== 'function') return;
511
+ const migration = this.number(index, FIELD.MIGRATION);
512
+ this.invoke(handler, [this.host(), this.number(index, FIELD.SESSION), migration === 0n ? undefined : Number(migration)]);
513
+ }
514
+
515
+ // {migration, migrated, failed, pending}, read now (valid until the
516
+ // next run) into the host's arena.
517
+ migrationResult(index) {
518
+ const module = this.module;
519
+ const id = this.word(index, FIELD.MIGRATION);
520
+ const count = this.word(index, FIELD.PENDING), failedCount = this.word(index, FIELD.FAILED);
521
+ const result = { migration: id, migrated: this.word(index, FIELD.MIGRATED) };
522
+ module.scoped(this.scratch, () => {
523
+ const pending = count ? module.room(this.scratch, 8 * count) : 0;
524
+ const failures = failedCount ? module.room(this.scratch, 12 * failedCount) : 0;
525
+ module.words().set([id, pending, count, failures, failedCount], module.record);
526
+ this.fn.ta_web_host_migration_result(this.pointer);
527
+ const got = module.word(0), lost = module.word(1);
528
+ const words = module.words();
529
+ const left = [];
530
+ for (let i = 0; i < got; i++) left.push(BigInt(words[(pending >>> 2) + 2 * i]) | (BigInt(words[(pending >>> 2) + 2 * i + 1]) << 32n));
531
+ const failed = [];
532
+ for (let i = 0; i < lost; i++) {
533
+ const at = (failures >>> 2) + 3 * i;
534
+ const session = BigInt(words[at]) | (BigInt(words[at + 1]) << 32n);
535
+ failed.push(Object.freeze({ session, reason: module.statusName(words[at + 2] | 0) }));
536
+ }
537
+ result.failed = Object.freeze(failed);
538
+ result.pending = Object.freeze(left);
539
+ });
540
+ return result;
541
+ }
542
+
543
+ dispatchMigrationDone(index) {
544
+ const handler = this.handlers()?.migrationDone;
545
+ if (typeof handler !== 'function') return;
546
+ let result;
547
+ try {
548
+ result = this.migrationResult(index);
549
+ } catch (error) {
550
+ this.keep(error);
551
+ return;
552
+ }
553
+ this.invoke(handler, [this.host(), result]);
554
+ }
555
+
556
+ // The telemetry handler gets the request as a Uint8Array it keeps; in
557
+ // the last take what it returns is kept for [Symbol.asyncDispose].
558
+ export(signal, bytes) {
559
+ const handler = this.handlers()?.telemetry;
560
+ if (typeof handler !== 'function') return;
561
+ let result;
562
+ try {
563
+ result = handler(this.host(), signal, bytes);
564
+ } catch (error) {
565
+ this.keep(error);
566
+ return;
567
+ }
568
+ if (this.endings === null) this.follow(result);
569
+ else if (result !== null && (typeof result === 'object' || typeof result === 'function')) this.endings.push(result);
570
+ }
571
+
572
+ // actor.get's result with each timer's due, the host's ticks, as
573
+ // milliseconds on the clock now() reads (ta_web_host_milliseconds).
574
+ timesInMilliseconds(result) {
575
+ for (const timer of result?.timers ?? []) {
576
+ const ticks = BigInt(timer.due);
577
+ timer.due = this.fn.ta_web_host_milliseconds(this.pointer, Number(ticks & 0xFFFFFFFFn), Number(ticks >> 32n));
578
+ }
579
+ return result;
580
+ }
581
+
582
+ // A typed method's REPLY: its pending row's handlers at `slot` (the row
583
+ // found and removed in C), the reply read once.
584
+ dispatchReply(index, slot) {
585
+ const handlers = this.handlers();
586
+ if (handlers === undefined || !Array.isArray(handlers.pending)) return;
587
+ const at = 2 * (slot - 1);
588
+ const onResult = handlers.pending[at], onError = handlers.pending[at + 1];
589
+ handlers.pending[at] = undefined;
590
+ handlers.pending[at + 1] = undefined;
591
+ let reply;
592
+ try {
593
+ const module = this.module;
594
+ const pointer = this.fn.ta_web_effect_bytes(this.pointer, index, FIELD.WIRE) >>> 0;
595
+ const length = module.word(0);
596
+ reply = module.scoped(this.scratch, () => cbor.read(module, this.scratch, pointer, length));
597
+ } catch (error) {
598
+ this.keep(error);
599
+ return;
600
+ }
601
+ if (reply === null || typeof reply !== 'object') return;
602
+ if (Object.hasOwn(reply, 'error')) {
603
+ const error = coreError(reply.error);
604
+ if (typeof onError !== 'function') {
605
+ this.keep(error);
606
+ return;
607
+ }
608
+ this.invoke(onError, [this.host(), error]);
609
+ return;
610
+ }
611
+ if (typeof onResult === 'function') this.invoke(onResult, [this.host(), reply.result]);
612
+ }
613
+
614
+ // ---- invoked services ----
615
+
616
+ invocations() { return this.handlers()?.invocations; }
617
+
618
+ dispatchInvoke(index) {
619
+ const handlers = this.handlers();
620
+ if (handlers === undefined) return;
621
+ let record;
622
+ try {
623
+ record = new Invocation(MAKING, this, index);
624
+ } catch (error) {
625
+ this.keep(error);
626
+ return;
627
+ }
628
+ const state = invocationState(record);
629
+ const services = handlers.services;
630
+ const handler = services !== null && typeof services === 'object' && Object.hasOwn(services, state.type) ? services[state.type] : undefined;
631
+ let started = false, result, thrown = null;
632
+ if (typeof handler === 'function') {
633
+ try {
634
+ result = handler(this.host(), record);
635
+ const then = result !== null && (typeof result === 'object' || typeof result === 'function') ? result.then : undefined;
636
+ if (typeof then === 'function') {
637
+ startInvocation(state, result);
638
+ return;
639
+ }
640
+ started = true;
641
+ } catch (error) {
642
+ thrown = [error];
643
+ }
644
+ }
645
+ if (!started) { // it does not run: kept as failed, so sends to it fail too, until the UNINVOKE
646
+ failInvocation(state, { sendid: undefined, tell: !this.uninvokedInBatch(index) });
647
+ if (thrown !== null) this.keep(thrown[0]);
648
+ return;
649
+ }
650
+ if (state.flags & INVOCATION.ENDED) return; // done() in the handler: nothing to keep
651
+ this.invocations()?.set(state.key, [record, result]);
652
+ }
653
+
654
+ // An UNINVOKE of the same (segment, token) later in the open batch: the
655
+ // invoker cancelled it in the run that started it.
656
+ uninvokedInBatch(index) {
657
+ const segment = this.word(index, FIELD.SEGMENT), token = this.word(index, FIELD.TOKEN);
658
+ for (let i = index + 1; ; i++) {
659
+ const kind = this.word(i, FIELD.KIND);
660
+ if (kind === 0) return false; // past the batch
661
+ if (kind === EFFECT.UNINVOKE && this.word(i, FIELD.SEGMENT) === segment && this.word(i, FIELD.TOKEN) === token) return true;
662
+ }
663
+ }
664
+
665
+ entryOf(index) {
666
+ const key = invocationKey(this.word(index, FIELD.SEGMENT), this.word(index, FIELD.TOKEN));
667
+ return this.invocations()?.get(key);
668
+ }
669
+
670
+ dispatchServiceSend(index) {
671
+ const entry = this.entryOf(index);
672
+ if (entry === undefined) return;
673
+ const [record, service] = entry;
674
+ const state = invocationState(record);
675
+ if (state.flags & INVOCATION.FAILED) { // a service that never ran: the send fails, as core's do
676
+ const sendid = this.text(index, FIELD.SENDID);
677
+ try {
678
+ postInvocation(state, { flags: INVOCATION_FAILURE, sendid: sendid === '' ? undefined : sendid });
679
+ } catch (error) {
680
+ this.keep(error);
681
+ }
682
+ return;
683
+ }
684
+ const starting = (state.flags & INVOCATION.STARTING) !== 0;
685
+ let receive = null;
686
+ if (!starting) {
687
+ try {
688
+ receive = serviceMethod(service, 'receive');
689
+ } catch (error) {
690
+ this.keep(error);
691
+ return;
692
+ }
693
+ if (receive === null) return;
694
+ }
695
+ const view = new Send(MAKING, this, index, NIL);
696
+ if (starting) { // a record now, for the service once it started
697
+ try {
698
+ materialize(view);
699
+ state.queue.push(view);
700
+ } catch (error) {
701
+ this.keep(error);
702
+ }
703
+ return;
704
+ }
705
+ try {
706
+ serviceReceive(state, service, receive, view);
707
+ } catch (error) {
708
+ this.keep(error);
709
+ }
710
+ }
711
+
712
+ dispatchUninvoke(index) {
713
+ const entry = this.entryOf(index);
714
+ if (entry === undefined) return; // done already, or never kept
715
+ const [record, service] = entry;
716
+ const state = invocationState(record);
717
+ const failed = (state.flags & INVOCATION.FAILED) !== 0, starting = (state.flags & INVOCATION.STARTING) !== 0;
718
+ if (starting) state.flags |= INVOCATION.UNINVOKED;
719
+ endInvocation(state);
720
+ if (failed || starting) return;
721
+ try {
722
+ const stop = serviceMethod(service, 'stop');
723
+ if (stop !== null) stop.call(service, this.host());
724
+ } catch (error) {
725
+ this.keep(error);
726
+ }
727
+ }
728
+ }
729
+
730
+ // The macrotask's and the timer's callbacks: the Host is their argument.
731
+ function turnOf(host) { stateOf(host)?.run(false); }
732
+ function timerOf(host) { stateOf(host)?.run(true); }
733
+
734
+ // ---- an event's words (wasm/src/host.c, ta_web_event_at) -------------------------------------
735
+
736
+ // Writes an event's words at word index `at`; texts are [pointer, length].
737
+ function eventWords(words, at, event) {
738
+ const session = event.session ?? 0n, data = event.data ?? 0n;
739
+ const none = [0, 0];
740
+ const [name, sendid, origin, origintype, raw, traceparent] =
741
+ [event.name, event.sendid, event.origin, event.origintype, event.raw, event.traceparent].map((t) => t ?? none);
742
+ words[at] = Number(session & 0xFFFFFFFFn);
743
+ words[at + 1] = Number(session >> 32n);
744
+ words[at + 2] = event.flags ?? 0;
745
+ words[at + 3] = event.token ?? 0;
746
+ words[at + 4] = name[0]; words[at + 5] = name[1];
747
+ words[at + 6] = sendid[0]; words[at + 7] = sendid[1];
748
+ words[at + 8] = origin[0]; words[at + 9] = origin[1];
749
+ words[at + 10] = origintype[0]; words[at + 11] = origintype[1];
750
+ words[at + 12] = Number(data & 0xFFFFFFFFn);
751
+ words[at + 13] = Number(data >> 32n);
752
+ words[at + 14] = raw[0]; words[at + 15] = raw[1];
753
+ words[at + 16] = traceparent[0]; words[at + 17] = traceparent[1];
754
+ words[at + 18] = 0;
755
+ }
756
+
757
+ // ---- thin views ------------------------------------------------------------------------------
758
+
759
+ const SEND_FIELDS = ['session', 'event', 'target', 'sendid', 'data', 'type', 'origin', 'traceparent'];
760
+ const VIEW_RECORD = 1, VIEW_ANSWERED = 2, VIEW_FAILED = 4;
761
+ // What answer() and fail() send: an answer, or the failure (`name` absent).
762
+ const FAILURE = Object.freeze({ data: undefined });
763
+
764
+ let viewOf;
765
+
766
+ function stale() {
767
+ return refusal('TA_ERROR_STALE', 'the effect\'s batch was acknowledged: read its fields in the handler, or return a promise from it');
768
+ }
769
+
770
+ // A send's thin view: the host's state, the ack count of its batch, the
771
+ // effect's index, its I/O processor and flags, then one slot per field,
772
+ // converted on first read and cached; a read with another ack count throws
773
+ // TA_ERROR_STALE. A record (a handler returned a promise) has every field
774
+ // filled before the ack and never goes stale.
775
+ class Send {
776
+ #view;
777
+
778
+ constructor(making, state, index, processor) {
779
+ if (making !== MAKING) throw new TypeError('a view of an effect is made by the host and given to its handler');
780
+ this.#view = { state, acks: state.acks(), index, processor, flags: 0, fields: new Map() };
781
+ }
782
+
783
+ static {
784
+ viewOf = (self) => {
785
+ if (self === null || typeof self !== 'object' || !(#view in self)) throw new TypeError('not a view of an effect');
786
+ return self.#view;
787
+ };
788
+ }
789
+
790
+ get session() { return sendField(viewOf(this), 'session'); }
791
+ get event() { return sendField(viewOf(this), 'event'); }
792
+ get target() { return sendField(viewOf(this), 'target'); }
793
+ get sendid() { return sendField(viewOf(this), 'sendid'); }
794
+ get data() { return sendField(viewOf(this), 'data'); }
795
+ get type() { return sendField(viewOf(this), 'type'); }
796
+ get origin() { return sendField(viewOf(this), 'origin'); }
797
+ get traceparent() { return sendField(viewOf(this), 'traceparent'); }
798
+
799
+ // The send's outgoing half, the object host.send(message) takes: a text
800
+ // field the send lacks is null.
801
+ get message() {
802
+ const view = viewOf(this);
803
+ const message = {};
804
+ for (const key of ['target', 'event', 'data', 'sendid', 'origin', 'traceparent']) {
805
+ const value = sendField(view, key);
806
+ message[key] = value === undefined && (key === 'sendid' || key === 'origin' || key === 'traceparent') ? null : value;
807
+ }
808
+ return message;
809
+ }
810
+
811
+ // answer(event, data?, {traceparent, origin, raw}?): true when
812
+ // delivered, false when the sender ended meanwhile.
813
+ answer(event, data, options) {
814
+ const view = viewOf(this);
815
+ const answer = { name: event, data, traceparent: undefined, origin: undefined, raw: undefined, given: false };
816
+ if (options !== undefined) {
817
+ if (options === null || typeof options !== 'object') throw new TypeError('an answer\'s options are an object of traceparent, origin, raw');
818
+ for (const key of Object.keys(options)) {
819
+ if (key !== 'traceparent' && key !== 'origin' && key !== 'raw') throw new TypeError('an answer\'s options are traceparent, origin and raw');
820
+ }
821
+ if (options.traceparent !== undefined) {
822
+ answer.traceparent = options.traceparent; // null: a new trace
823
+ answer.given = true;
824
+ }
825
+ answer.origin = options.origin;
826
+ answer.raw = options.raw;
827
+ }
828
+ if (typeof answer.name !== 'string') throw new TypeError('answer(event, data?, options?): the event is a string');
829
+ return replyTo(this, answer, view);
830
+ }
831
+
832
+ // fail(): error.communication for the sender, with the send's sendid and
833
+ // trace; false when the sender ended, as answer().
834
+ fail() {
835
+ return replyTo(this, FAILURE, viewOf(this));
836
+ }
837
+ }
838
+
839
+ function live(view) {
840
+ if (view.flags & VIEW_RECORD) return;
841
+ if (!view.state.open || view.state.acks() !== view.acks) throw stale();
842
+ }
843
+
844
+ function sendField(view, name) {
845
+ if (view.fields.has(name)) return view.fields.get(name);
846
+ live(view);
847
+ const { state, index, processor } = view;
848
+ let value;
849
+ switch (name) {
850
+ case 'session': value = state.number(index, FIELD.SESSION); break;
851
+ case 'event': value = state.text(index, FIELD.EVENT); break;
852
+ case 'target': {
853
+ const text = state.text(index, FIELD.TARGET);
854
+ value = text === '' ? undefined : processor === 0 ? new Address(text) : text;
855
+ break;
856
+ }
857
+ case 'sendid': value = state.text(index, FIELD.SENDID) || undefined; break;
858
+ case 'data': value = state.data(index); break;
859
+ case 'type': value = processor === NIL ? undefined : state.handlers()?.types?.[processor]; break;
860
+ case 'origin': {
861
+ const text = state.text(index, FIELD.ORIGIN);
862
+ value = text === '' ? undefined : new Address(text);
863
+ break;
864
+ }
865
+ default: value = state.text(index, FIELD.TRACEPARENT) || undefined;
866
+ }
867
+ view.fields.set(name, value);
868
+ return value;
869
+ }
870
+
871
+ // Every field read now, the view marked a record.
872
+ function materialize(send) {
873
+ const view = viewOf(send);
874
+ for (const name of SEND_FIELDS) sendField(view, name);
875
+ view.flags |= VIEW_RECORD;
876
+ }
877
+
878
+ // A handler returned a thenable: its view filled before the ack, and its
879
+ // rejection followed (the send failed if nobody answered it, the rejection
880
+ // thrown on, so the promise `then` made rejects unhandled).
881
+ function followSend(state, send, result) {
882
+ if (result === null || (typeof result !== 'object' && typeof result !== 'function')) return;
883
+ const then = result.then;
884
+ if (typeof then !== 'function') return;
885
+ materialize(send);
886
+ const chained = then.call(result, undefined, (reason) => {
887
+ failUnanswered(send);
888
+ throw reason;
889
+ });
890
+ state.follow(chained);
891
+ }
892
+
893
+ // An answer or the failure of a send: ta_host_send to its session with its
894
+ // sendid. true delivered, false the sender ended; a refusal throws.
895
+ function replyTo(send, answer, view = viewOf(send)) {
896
+ live(view);
897
+ if (view.flags & (VIEW_ANSWERED | VIEW_FAILED)) {
898
+ throw refusal('TA_ERROR_STATE', view.flags & VIEW_FAILED ? 'the send was failed already' : 'the send was answered already');
899
+ }
900
+ const session = sendField(view, 'session');
901
+ const sendid = sendField(view, 'sendid');
902
+ const type = sendField(view, 'type');
903
+ const failure = answer === FAILURE;
904
+ const traceparent = failure || !answer.given ? sendField(view, 'traceparent') : answer.traceparent;
905
+ const state = view.state;
906
+ return state.call(() => {
907
+ const module = state.module, scratch = state.scratch;
908
+ if (state.fn.ta_web_host_locate(state.pointer, Number(session & 0xFFFFFFFFn), Number(session >> 32n)) !== TA_OK) return false;
909
+ const event = {
910
+ session,
911
+ sendid: module.text(scratch, optionalText(sendid, 'a sendid is a string')),
912
+ traceparent: module.text(scratch, optionalText(traceparent, 'a traceparent is W3C text, a string, or null for a new trace')),
913
+ };
914
+ if (failure) event.flags = EVENT_ERROR_COMMUNICATION; // the name is not repeated
915
+ else {
916
+ event.name = module.text(scratch, textOf(answer.name, 'an answer\'s event is a string'));
917
+ event.origintype = module.text(scratch, optionalText(type, 'a processor\'s type is a string'));
918
+ event.origin = module.text(scratch, optionalText(addressText(answer.origin), 'an origin is an address, a string or an Address'));
919
+ event.raw = module.text(scratch, optionalText(answer.raw, 'raw is the message as read, a string'));
920
+ event.data = state.payload(answer.data, { session });
921
+ }
922
+ eventWords(module.words(), module.record, event);
923
+ const status = state.fn.ta_web_host_send(state.pointer);
924
+ if (status === TA_ERROR_STALE) return false; // the sender ended: nobody to tell (C released the data)
925
+ if (status !== TA_OK) throw refusal(module.statusName(status), failure ? 'the failure was refused' : 'the answer was refused');
926
+ view.flags |= failure ? VIEW_FAILED : VIEW_ANSWERED;
927
+ state.schedule();
928
+ return true;
929
+ });
930
+ }
931
+
932
+ // Fails a send nobody answered, for a handler that could not; what that
933
+ // throws is dropped.
934
+ function failUnanswered(send) {
935
+ const view = viewOf(send);
936
+ if (view.flags & (VIEW_ANSWERED | VIEW_FAILED) || !view.state.open) return;
937
+ try {
938
+ replyTo(send, FAILURE, view);
939
+ } catch {
940
+ // nobody's news
941
+ }
942
+ }
943
+
944
+ let entryOf;
945
+
946
+ // A <log> line: (session, label, text), a thin view until the ack.
947
+ class LogEntry {
948
+ #view;
949
+
950
+ constructor(making, state, index) {
951
+ if (making !== MAKING) throw new TypeError('a view of an effect is made by the host and given to its handler');
952
+ this.#view = { state, acks: state.acks(), index, flags: 0, fields: new Map() };
953
+ }
954
+
955
+ static {
956
+ entryOf = (self, name, read) => {
957
+ if (self === null || typeof self !== 'object' || !(#view in self)) throw new TypeError('not a view of an effect');
958
+ return cachedField(self.#view, name, read);
959
+ };
960
+ }
961
+
962
+ get session() { return entryOf(this, 'session', (s, i) => s.number(i, FIELD.SESSION)); }
963
+ get label() { return entryOf(this, 'label', (s, i) => s.text(i, FIELD.AUXILIARY)); }
964
+ get text() { return entryOf(this, 'text', (s, i) => s.text(i, FIELD.EVENT)); }
965
+ }
966
+
967
+ function cachedField(view, name, read) {
968
+ if (view.fields.has(name)) return view.fields.get(name);
969
+ live(view);
970
+ const value = read(view.state, view.index);
971
+ view.fields.set(name, value);
972
+ return value;
973
+ }
974
+
975
+ let migratedOf;
976
+
977
+ // An actor moved by a migration: a thin view until the ack.
978
+ class Migrated {
979
+ #view;
980
+
981
+ constructor(making, state, index) {
982
+ if (making !== MAKING) throw new TypeError('a view of an effect is made by the host and given to its handler');
983
+ this.#view = { state, acks: state.acks(), index, flags: 0, fields: new Map() };
984
+ }
985
+
986
+ static {
987
+ migratedOf = (self, name, read) => {
988
+ if (self === null || typeof self !== 'object' || !(#view in self)) throw new TypeError('not a view of an effect');
989
+ return cachedField(self.#view, name, read);
990
+ };
991
+ }
992
+
993
+ get session() { return migratedOf(this, 'session', (s, i) => s.number(i, FIELD.SESSION)); }
994
+ get segment() { return migratedOf(this, 'segment', (s, i) => s.word(i, FIELD.SEGMENT)); }
995
+ get chart() { return migratedOf(this, 'chart', (s, i) => s.text(i, FIELD.EVENT)); }
996
+ get migration() { return migratedOf(this, 'migration', (s, i) => s.word(i, FIELD.MIGRATION)); }
997
+ }
998
+
999
+ // ---- invoked services --------------------------------------------------------------------------
1000
+
1001
+ const INVOCATION = { ENDED: 1, FAILED: 2, RESTORED: 4, STARTING: 8, UNINVOKED: 16 };
1002
+
1003
+ let invocationState;
1004
+
1005
+ const invocationKey = (segment, token) => (BigInt(segment) << 32n) | BigInt(token);
1006
+
1007
+ // A text field of the INVOKE shared with the last invocation's when the
1008
+ // text is the same, so a population holds one string of its type, src
1009
+ // and invokeid.
1010
+ function sharedText(state, index, slot, field) {
1011
+ const text = state.text(index, field);
1012
+ const last = state.handlers()?.last;
1013
+ if (last === undefined) return text;
1014
+ if (last[slot] === text) return last[slot];
1015
+ last[slot] = text;
1016
+ return text;
1017
+ }
1018
+
1019
+ // What an INVOKE said, read once before the ack (the service runs until
1020
+ // done or cancelled), and how to answer the invoker.
1021
+ class Invocation {
1022
+ #state;
1023
+
1024
+ constructor(making, state, index) {
1025
+ if (making !== MAKING) throw new TypeError('an Invocation is made by the host and given to its service handler');
1026
+ const segment = state.word(index, FIELD.SEGMENT), token = state.word(index, FIELD.TOKEN);
1027
+ this.#state = {
1028
+ self: this,
1029
+ host: state,
1030
+ segment,
1031
+ token,
1032
+ key: invocationKey(segment, token),
1033
+ flags: state.word(index, FIELD.FLAGS) & FLAG_RESTORED ? INVOCATION.RESTORED : 0,
1034
+ session: state.number(index, FIELD.SESSION),
1035
+ invokeid: sharedText(state, index, 0, FIELD.SENDID),
1036
+ type: sharedText(state, index, 1, FIELD.EVENT),
1037
+ src: sharedText(state, index, 2, FIELD.TARGET),
1038
+ data: state.data(index),
1039
+ traceparent: state.text(index, FIELD.TRACEPARENT) || undefined,
1040
+ queue: undefined,
1041
+ };
1042
+ }
1043
+
1044
+ static {
1045
+ invocationState = (self) => {
1046
+ if (self === null || typeof self !== 'object' || !(#state in self)) throw new TypeError('not an Invocation');
1047
+ return self.#state;
1048
+ };
1049
+ }
1050
+
1051
+ get session() { return invocationState(this).session; }
1052
+ get invokeid() { return invocationState(this).invokeid; }
1053
+ get type() { return invocationState(this).type; }
1054
+ get src() { return invocationState(this).src; }
1055
+ get data() { return invocationState(this).data; }
1056
+ get traceparent() { return invocationState(this).traceparent; }
1057
+ get restored() { return (invocationState(this).flags & INVOCATION.RESTORED) !== 0; }
1058
+
1059
+ get running() {
1060
+ const state = invocationState(this);
1061
+ return !(state.flags & INVOCATION.ENDED) && state.host.open;
1062
+ }
1063
+
1064
+ // sendBack(event, data?, {traceparent}?)
1065
+ sendBack(event, data, options) {
1066
+ const state = invocationState(this);
1067
+ if (typeof event !== 'string') throw new TypeError('sendBack(event, data?, options?): the event is a string');
1068
+ const traceparent = invocationOptions(options);
1069
+ postInvocation(state, { flags: EVENT_FROM_INVOKE, name: event, data, traceparent });
1070
+ }
1071
+
1072
+ // done(data?, {traceparent}?): done.invoke.<invokeid> for the invoker;
1073
+ // the service is dropped.
1074
+ done(data, options) {
1075
+ const state = invocationState(this);
1076
+ const traceparent = invocationOptions(options);
1077
+ postInvocation(state, { flags: EVENT_INVOKE_DONE, data, traceparent });
1078
+ endInvocation(state);
1079
+ }
1080
+ }
1081
+
1082
+ // sendBack's and done's options: {traceparent}; undefined when absent (the
1083
+ // invocation's trace), null a new trace.
1084
+ function invocationOptions(options) {
1085
+ if (options === undefined) return undefined;
1086
+ if (options === null || typeof options !== 'object') throw new TypeError('an invocation\'s options are an object of traceparent');
1087
+ for (const key of Object.keys(options)) {
1088
+ if (key !== 'traceparent') throw new TypeError('an invocation\'s options are traceparent only');
1089
+ }
1090
+ return options.traceparent;
1091
+ }
1092
+
1093
+ // An event from the service to its invoker (TA_EVENT_IN_FROM_INVOKE), its
1094
+ // done (TA_EVENT_IN_INVOKE_DONE), or its failure (with the failed send's
1095
+ // sendid when there is one).
1096
+ function postInvocation(state, what) {
1097
+ const host = state.host;
1098
+ const failure = (what.flags & EVENT_ERROR_COMMUNICATION) !== 0;
1099
+ if (((state.flags & INVOCATION.ENDED) && !failure) || !host.open) {
1100
+ throw refusal('TA_ERROR_STALE', !host.open ? 'the Host is closed' : 'the invocation ended: done, cancelled or failed');
1101
+ }
1102
+ const traceparent = what.traceparent === undefined ? state.traceparent : what.traceparent;
1103
+ host.call(() => {
1104
+ const module = host.module, scratch = host.scratch;
1105
+ const event = {
1106
+ session: state.session,
1107
+ flags: what.flags,
1108
+ token: state.token,
1109
+ name: what.name === undefined ? undefined : module.text(scratch, textOf(what.name, 'a service\'s event is a string')),
1110
+ traceparent: module.text(scratch, optionalText(traceparent, 'a traceparent is W3C text, a string, or null for a new trace')),
1111
+ sendid: what.sendid === undefined ? undefined : module.text(scratch, optionalText(what.sendid, 'a sendid is a string')),
1112
+ };
1113
+ if (!failure) event.data = host.payload(what.data, { session: state.session });
1114
+ eventWords(module.words(), module.record, event);
1115
+ const status = host.fn.ta_web_host_send(host.pointer);
1116
+ if (status !== TA_OK) {
1117
+ throw refusal(module.statusName(status), what.flags & EVENT_INVOKE_DONE ? 'the done was refused' : failure ? 'the failure was refused' : 'the event was refused');
1118
+ }
1119
+ host.schedule();
1120
+ });
1121
+ }
1122
+
1123
+ // The invocation ended (done, cancelled): its entry goes, and with it the
1124
+ // host's hold on the service.
1125
+ function endInvocation(state) {
1126
+ state.flags |= INVOCATION.ENDED;
1127
+ state.host.invocations()?.delete(state.key);
1128
+ }
1129
+
1130
+ // The invocation failed (its start, or its service crashed): unless it
1131
+ // ended already it is marked failed, kept without its service, and the
1132
+ // invoker told (with `sendid` when a send failed).
1133
+ function failInvocation(state, { sendid, tell }) {
1134
+ if (state.flags & INVOCATION.ENDED) return;
1135
+ state.flags |= INVOCATION.ENDED | INVOCATION.FAILED;
1136
+ state.host.invocations()?.set(state.key, [state.self, undefined]);
1137
+ if (!tell) return;
1138
+ try {
1139
+ postInvocation(state, { flags: INVOCATION_FAILURE, sendid });
1140
+ } catch {
1141
+ // what the failure's post threw is nobody's news
1142
+ }
1143
+ }
1144
+
1145
+ // A method of a service (receive, stop), or null when it has none.
1146
+ function serviceMethod(service, name) {
1147
+ if (service === null || (typeof service !== 'object' && typeof service !== 'function')) return null;
1148
+ const method = service[name];
1149
+ return typeof method === 'function' ? method : null;
1150
+ }
1151
+
1152
+ // A send for a running service's receive, called on the service. A receive
1153
+ // that returns a promise has its view filled now, before the ack, and a
1154
+ // rejection is a crash; one that throws is a crash too (the error thrown
1155
+ // on).
1156
+ function serviceReceive(state, service, receive, send) {
1157
+ let result;
1158
+ try {
1159
+ result = receive.call(service, state.host.host(), send);
1160
+ const then = result !== null && (typeof result === 'object' || typeof result === 'function') ? result.then : undefined;
1161
+ if (typeof then === 'function') {
1162
+ materialize(send);
1163
+ const chained = then.call(result, undefined, (reason) => {
1164
+ failInvocation(state, { sendid: sendidOf(send), tell: true });
1165
+ throw reason;
1166
+ });
1167
+ state.host.follow(chained);
1168
+ }
1169
+ } catch (error) {
1170
+ failInvocation(state, { sendid: sendidOf(send), tell: true });
1171
+ throw error;
1172
+ }
1173
+ }
1174
+
1175
+ function sendidOf(send) {
1176
+ try {
1177
+ return send.sendid;
1178
+ } catch {
1179
+ return undefined;
1180
+ }
1181
+ }
1182
+
1183
+ // A service handler returned a thenable: the invocation is starting until
1184
+ // it settles; what comes meanwhile is queued.
1185
+ function startInvocation(state, thenable) {
1186
+ state.queue = [];
1187
+ state.flags |= INVOCATION.STARTING;
1188
+ const chained = thenable.then((service) => startedInvocation(state, service), (reason) => startFailed(state, reason));
1189
+ state.host.follow(chained);
1190
+ if (state.flags & INVOCATION.ENDED) return; // done() in the handler: nothing to keep
1191
+ state.host.invocations()?.set(state.key, [state.self, undefined]);
1192
+ }
1193
+
1194
+ function settleQueue(state) {
1195
+ const queue = state.queue ?? [];
1196
+ state.queue = undefined;
1197
+ state.flags &= ~INVOCATION.STARTING;
1198
+ return queue;
1199
+ }
1200
+
1201
+ // The handler's promise resolved with the service (between turns, never
1202
+ // inside a run).
1203
+ function startedInvocation(state, service) {
1204
+ const queue = settleQueue(state);
1205
+ const host = state.host;
1206
+ if (!host.open) return; // closed: dropped, not started
1207
+ if (state.flags & INVOCATION.UNINVOKED) { // cancelled while it started: stopped now
1208
+ const stop = serviceMethod(service, 'stop');
1209
+ if (stop !== null) stop.call(service, host.host());
1210
+ return;
1211
+ }
1212
+ if (state.flags & INVOCATION.ENDED) return; // done in its start
1213
+ host.invocations()?.set(state.key, [state.self, service]);
1214
+ let raised = null;
1215
+ for (const send of queue) {
1216
+ if (!host.open) break;
1217
+ try {
1218
+ if (state.flags & INVOCATION.FAILED) { // crashed on an earlier send: this one fails
1219
+ postInvocation(state, { flags: INVOCATION_FAILURE, sendid: sendidOf(send) });
1220
+ } else if (!(state.flags & INVOCATION.ENDED)) {
1221
+ const receive = serviceMethod(service, 'receive');
1222
+ if (receive !== null) serviceReceive(state, service, receive, send);
1223
+ }
1224
+ } catch (error) {
1225
+ if (raised === null) raised = [error];
1226
+ }
1227
+ }
1228
+ if (raised !== null) throw raised[0];
1229
+ }
1230
+
1231
+ // The handler's promise rejected: a failed start, unless it ended
1232
+ // meanwhile; the invoker told, then each queued send with its sendid.
1233
+ function startFailed(state, reason) {
1234
+ const queue = settleQueue(state);
1235
+ const host = state.host;
1236
+ if (host.open && !(state.flags & INVOCATION.ENDED)) {
1237
+ failInvocation(state, { sendid: undefined, tell: true });
1238
+ for (const send of queue) {
1239
+ if (!host.open) break;
1240
+ try {
1241
+ postInvocation(state, { flags: INVOCATION_FAILURE, sendid: sendidOf(send) });
1242
+ } catch {
1243
+ // a failure core refuses is nobody's news
1244
+ }
1245
+ }
1246
+ }
1247
+ throw reason;
1248
+ }
1249
+
1250
+ // ---- SimulatedClock ---------------------------------------------------------------------------
1251
+
1252
+ let clockOf;
1253
+
1254
+ // A clock in milliseconds (nanoseconds inside, exact) that moves only with
1255
+ // increment(ms), which schedules a turn on each host made with it; such a
1256
+ // host arms no timer. It holds the hosts weakly.
1257
+ export class SimulatedClock {
1258
+ #clock = { ns: 0n, hosts: [] };
1259
+
1260
+ constructor() {
1261
+ if (new.target === undefined) throw new TypeError('SimulatedClock is a class: new SimulatedClock()');
1262
+ }
1263
+
1264
+ static {
1265
+ clockOf = (self) => {
1266
+ if (self === null || typeof self !== 'object' || !(#clock in self)) throw new TypeError('not a SimulatedClock');
1267
+ return self.#clock;
1268
+ };
1269
+ }
1270
+
1271
+ get now() { return Number(clockOf(this).ns) / 1e6; }
1272
+
1273
+ increment(ms) {
1274
+ const clock = clockOf(this);
1275
+ if (typeof ms !== 'number') throw new TypeError('increment(ms): a number of milliseconds');
1276
+ if (!(ms >= 0)) throw new RangeError('increment(ms): not negative, not NaN');
1277
+ const step = ms * 1e6 + 0.5;
1278
+ if (step >= 18446744073709551616 - Number(clock.ns)) throw new RangeError('increment(ms): the clock would pass 2^64 nanoseconds');
1279
+ clock.ns += BigInt(Math.trunc(step));
1280
+ const live = [];
1281
+ for (const reference of clock.hosts) {
1282
+ const host = reference.deref();
1283
+ const state = host === undefined ? undefined : stateOf(host);
1284
+ if (state === undefined || !state.open) continue;
1285
+ live.push(reference);
1286
+ state.schedule();
1287
+ }
1288
+ clock.hosts = live;
1289
+ }
1290
+ }
1291
+
1292
+ // ---- the Host ----------------------------------------------------------------------------------
1293
+
1294
+ // The options' handlers, checked, into the handlers object the Host holds.
1295
+ function readHandlers(options) {
1296
+ const handlers = {};
1297
+ for (const name of HANDLER_FUNCTIONS) {
1298
+ const value = options?.[name];
1299
+ if (value === undefined) continue;
1300
+ if (typeof value !== 'function') throw new TypeError('a Host\'s handler is a function');
1301
+ handlers[name] = value;
1302
+ }
1303
+ for (const name of HANDLER_MAPS) {
1304
+ const value = options?.[name];
1305
+ if (value === undefined) continue;
1306
+ if (value === null || typeof value !== 'object') throw new TypeError('ioProcessors and services are objects of a type -> its handler');
1307
+ for (const key of Object.keys(value)) {
1308
+ if (typeof value[key] !== 'function') throw new TypeError('ioProcessors and services are objects of a type -> its handler');
1309
+ }
1310
+ handlers[name] = value;
1311
+ }
1312
+ handlers.invocations = new Map();
1313
+ handlers.last = new Array(3);
1314
+ return handlers;
1315
+ }
1316
+
1317
+ // The quickjs option's limits, checked as the addon checks them, as the
1318
+ // record's words 10-15 of ta_web_host_new (wasm/src/host.c,
1319
+ // ta_web_quickjs_config): maxOps, memoryLimit, stackLimit, realm.
1320
+ function checkQuickjs(given) {
1321
+ if (given === undefined) return;
1322
+ if (given === null || typeof given !== 'object') throw new TypeError('quickjs is an object of the sandbox\'s limits');
1323
+ onlyKnown(given, ['maxOps', 'memoryLimit', 'stackLimit', 'realm'], 'quickjs option');
1324
+ if (given.maxOps !== undefined) countOf(given.maxOps, 'quickjs.maxOps is an integer from 0 to 2^32-1');
1325
+ if (given.memoryLimit !== undefined) countOf(given.memoryLimit, 'quickjs.memoryLimit is a safe integer of bytes, 0 or more', Number.MAX_SAFE_INTEGER);
1326
+ if (given.stackLimit !== undefined) countOf(given.stackLimit, 'quickjs.stackLimit is a safe integer of bytes, 0 or more', Number.MAX_SAFE_INTEGER);
1327
+ if (given.realm !== undefined && given.realm !== 'auto' && given.realm !== 'isolated') throw new TypeError('quickjs.realm is "auto" or "isolated"');
1328
+ }
1329
+
1330
+ function quickjsWords(given) {
1331
+ const words = new Uint32Array(6);
1332
+ const wide = (at, n) => {
1333
+ words[at] = n % 0x100000000;
1334
+ words[at + 1] = Math.floor(n / 0x100000000);
1335
+ };
1336
+ words[0] = given?.maxOps ?? 0;
1337
+ wide(1, given?.memoryLimit ?? 0);
1338
+ wide(3, given?.stackLimit ?? 0);
1339
+ words[5] = given?.realm === 'isolated' ? 1 : 0;
1340
+ return words;
1341
+ }
1342
+
1343
+ // The effective config read once: the tick rate, whether an encoder runs,
1344
+ // the I/O processors (each type's handler at its number, processors[i + 1]
1345
+ // for ioProcessors[i], 0 the transport; types likewise).
1346
+ function readEffective(state, handlers) {
1347
+ const reply = state.effective;
1348
+ const config = reply?.result;
1349
+ const rate = config?.system?.ticksPerSecond;
1350
+ if (config === null || typeof config !== 'object' || typeof rate !== 'number' || rate < 1) {
1351
+ throw refusal('TA_ERROR_STATE', 'host.config gave no system.ticksPerSecond');
1352
+ }
1353
+ state.ticksPerSecond = rate;
1354
+ state.encoder = Object.hasOwn(config, 'telemetry');
1355
+ const entries = Array.isArray(config.ioProcessors) ? config.ioProcessors : [];
1356
+ const given = handlers.ioProcessors;
1357
+ const processors = [handlers.transport], types = [undefined];
1358
+ let found = 0;
1359
+ for (const entry of entries) {
1360
+ const type = entry !== null && typeof entry === 'object' && typeof entry.type === 'string' ? entry.type : undefined;
1361
+ types.push(type);
1362
+ let handler;
1363
+ if (given !== undefined && type !== undefined && Object.hasOwn(given, type)) {
1364
+ handler = given[type];
1365
+ found++;
1366
+ }
1367
+ processors.push(handler);
1368
+ }
1369
+ if (given !== undefined && Object.keys(given).length !== found) {
1370
+ throw new TypeError('ioProcessors names a type the config\'s ioProcessors does not have');
1371
+ }
1372
+ state.processors = entries.length;
1373
+ handlers.processors = processors;
1374
+ handlers.types = types;
1375
+ }
1376
+
1377
+ // The config a new host is made with: the caller's, or, when it gives no
1378
+ // system.traceSeed, a copy with a random one (the language layer picks the
1379
+ // seed, the maintainer, 2026-11-18), so hosts start different trace ids; a
1380
+ // seed the caller sets is kept, and so reproduces. A config core will refuse
1381
+ // anyway (not an object, a `system` that is not one) and a runtime without
1382
+ // crypto.getRandomValues keep the config as it is. As the addon's
1383
+ // ta_napi_config_seeded (src/host.c).
1384
+ function seeded(config) {
1385
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) return config;
1386
+ const system = config.system;
1387
+ if (system !== undefined) {
1388
+ if (system === null || typeof system !== 'object' || Array.isArray(system)) return config;
1389
+ if (system.traceSeed !== undefined) return config; // the caller's
1390
+ }
1391
+ if (typeof globalThis.crypto?.getRandomValues !== 'function') return config;
1392
+ const [low, high] = globalThis.crypto.getRandomValues(new Uint32Array(2));
1393
+ return Object.assign({}, config, { system: Object.assign({}, system, { traceSeed: (BigInt(high) << 32n) | BigInt(low) }) });
1394
+ }
1395
+
1396
+ // ta_web_host_new or ta_web_host_restore, with the config written into the
1397
+ // environment's arena and room for a refused config's error; then the
1398
+ // checks of a restore. Answers the host's pointer and, for a restore, the
1399
+ // snapshot's time.
1400
+ function makeHost(state, config, pack, limits) {
1401
+ const module = state.module;
1402
+ const scratch = module.scratch;
1403
+ return module.scoped(scratch, () => {
1404
+ // a restore keeps its config as given: its segments keep the snapshot's generators
1405
+ const [at, length] = cbor.write(module, scratch, pack === null ? seeded(config) : config);
1406
+ const room = module.room(scratch, CONFIG_ERROR);
1407
+ // a new host: random bits for its identity, so its hibernation blobs wake
1408
+ // in no other host (a restore keeps its snapshot's)
1409
+ let packed = pack === null ? globalThis.crypto.getRandomValues(new Uint32Array(2)) : [0, 0];
1410
+ if (pack !== null) packed = module.copyIn(scratch, pack); // 8-aligned, as a pack's parts need
1411
+ const datamodel = state.quickjs !== null ? DATAMODEL_QUICKJS : DATAMODEL_NATIVE;
1412
+ module.words().set([at, length, state.id, datamodel, room, CONFIG_ERROR, packed[0], packed[1], 0, 0, ...quickjsWords(limits)], module.record);
1413
+ const pointer = module.call(pack === null ? 'ta_web_host_new' : 'ta_web_host_restore', module.env) >>> 0;
1414
+ const w = module.words().slice(module.record, module.record + 9);
1415
+ const status = w[0] | 0;
1416
+ if (pointer === 0) {
1417
+ if (state.error !== null) throw state.takeKept()[0];
1418
+ if (pack !== null && w[2] === 2) {
1419
+ throw refusal('TA_ERROR_INVALID', 'a snapshot of @tinyactors/node: a snapshot restores only in the package that made it, ' +
1420
+ 'of the same version (it is the host\'s memory); move actors between the packages as hibernation blobs');
1421
+ }
1422
+ if (pack !== null && (w[2] === 1 || (status === TA_ERROR_INVALID && w[1] === 0))) {
1423
+ throw refusal('TA_ERROR_INVALID', 'not a snapshot of a Host of @tinyactors/wasm');
1424
+ }
1425
+ let error = null;
1426
+ if (w[1] > 0 && w[1] <= CONFIG_ERROR) {
1427
+ try {
1428
+ error = cbor.read(module, scratch, room, w[1])?.error ?? null;
1429
+ } catch {
1430
+ error = null;
1431
+ }
1432
+ }
1433
+ throw coreError(error, module.statusName(status));
1434
+ }
1435
+ if (pack === null) return { pointer };
1436
+ // what is checked once the host is made: views of the pack in the arena
1437
+ const time = BigInt(w[3]) | (BigInt(w[4]) << 32n);
1438
+ const systemID = module.string(w[5], w[6]);
1439
+ let datamodels = null;
1440
+ try {
1441
+ datamodels = cbor.read(module, scratch, w[7], w[8]);
1442
+ } catch {
1443
+ datamodels = null;
1444
+ }
1445
+ return { pointer, time, systemID, datamodels };
1446
+ });
1447
+ }
1448
+
1449
+ const STATE_KEYS = ['native', 'quickjs'];
1450
+
1451
+ // The datamodel's state back: {"native": ...} or {"quickjs": bytes}, the
1452
+ // key the host's datamodel: the native tables' namespaces and rows
1453
+ // (datamodel.mjs, restore), or quickjs's state (quickjs.mjs).
1454
+ function restoreDatamodel(state, datamodels) {
1455
+ if (datamodels === null || typeof datamodels !== 'object' || Array.isArray(datamodels) || Object.keys(datamodels).length !== 1) {
1456
+ throw refusal('TA_ERROR_INVALID', 'not a snapshot of a Host');
1457
+ }
1458
+ const [key] = Object.keys(datamodels);
1459
+ if (key !== state.datamodelName) {
1460
+ throw refusal('TA_ERROR_INVALID', state.datamodelName === 'native'
1461
+ ? 'the snapshot is of a host on quickjs: restore it with datamodel "quickjs"'
1462
+ : 'the snapshot is of a host on the native datamodel: restore it with datamodel "native"');
1463
+ }
1464
+ (state.quickjs ?? state.native).restore(datamodels[key]);
1465
+ }
1466
+
1467
+ let checked;
1468
+
1469
+ export class Host {
1470
+ #s;
1471
+
1472
+ static {
1473
+ stateOf = (host) => (host !== null && typeof host === 'object' && #s in host ? host.#s : undefined);
1474
+ checked = (host, open) => {
1475
+ if (host === null || typeof host !== 'object' || !(#s in host)) throw new TypeError('not a Host');
1476
+ const state = host.#s;
1477
+ if (open && !state.open) throw refusal('TA_ERROR_STATE', 'the Host is closed');
1478
+ return state;
1479
+ };
1480
+ }
1481
+
1482
+ constructor(config, options) {
1483
+ const restore = restoring;
1484
+ restoring = null;
1485
+ if (new.target === undefined) throw new TypeError('Host is a class: new Host(config, options)');
1486
+ if (options !== undefined) {
1487
+ if (options === null || typeof options !== 'object') throw new TypeError('a Host\'s options are an object');
1488
+ onlyKnown(options, KNOWN_OPTIONS, 'Host option');
1489
+ }
1490
+ const handlers = readHandlers(options);
1491
+ const datamodel = options?.datamodel;
1492
+ if (datamodel !== undefined && datamodel !== 'native' && datamodel !== 'quickjs') throw new TypeError('datamodel is "native" or "quickjs"');
1493
+ if (datamodel !== 'quickjs' && options?.quickjs !== undefined) {
1494
+ throw new TypeError('quickjs\'s limits are for a host with datamodel "quickjs"');
1495
+ }
1496
+ if (datamodel === 'quickjs') checkQuickjs(options.quickjs);
1497
+ else {
1498
+ const policy = policyRefusal(); // the native datamodel evaluates chart text; quickjs evaluates none
1499
+ if (policy !== null) throw refusal('TA_ERROR_UNSUPPORTED', policy);
1500
+ }
1501
+ const clock = options?.clock;
1502
+ let clockState = null;
1503
+ if (clock !== undefined) {
1504
+ try {
1505
+ clockState = clockOf(clock);
1506
+ } catch {
1507
+ throw new TypeError('clock is a SimulatedClock');
1508
+ }
1509
+ }
1510
+ const module = instance();
1511
+ const state = new HostState(module, this);
1512
+ state.telemetry = options?.telemetry !== undefined;
1513
+ if (datamodel === 'quickjs') {
1514
+ state.datamodelName = 'quickjs';
1515
+ state.quickjs = new QuickJSDatamodel(state);
1516
+ } else {
1517
+ state.datamodelName = 'native';
1518
+ state.native = new NativeDatamodel(state);
1519
+ }
1520
+ state.id = module.register(state);
1521
+ let made;
1522
+ try {
1523
+ made = makeHost(state, config, restore === null ? null : bytesOf(restore.snapshot, 'restore takes the snapshot\'s bytes: a Uint8Array or an ArrayBuffer'), options?.quickjs);
1524
+ } catch (error) {
1525
+ module.unregister(state.id);
1526
+ throw error;
1527
+ }
1528
+ state.pointer = made.pointer;
1529
+ state.scratch = module.call('ta_web_host_scratch', made.pointer) >>> 0;
1530
+ state.open = true;
1531
+ unclosed.register(this, state, state);
1532
+ try {
1533
+ readEffective(state, handlers);
1534
+ if (restore !== null) {
1535
+ restoreDatamodel(state, made.datamodels);
1536
+ if (state.effective.result.systemID !== made.systemID) {
1537
+ throw refusal('TA_ERROR_INVALID', `the snapshot is of system ${made.systemID}: restore it with the config it was taken with`);
1538
+ }
1539
+ }
1540
+ } catch (error) {
1541
+ state.release();
1542
+ throw error;
1543
+ }
1544
+ state.effective = null;
1545
+ Object.defineProperty(this, HANDLERS, { value: handlers, writable: true, enumerable: false, configurable: false });
1546
+ this.#s = state;
1547
+ if (clockState !== null) {
1548
+ state.simulated = clockState;
1549
+ clockState.hosts.push(new WeakRef(this));
1550
+ }
1551
+ if (restore !== null) { // on from the snapshot's time
1552
+ module.setWord64(0, made.time);
1553
+ module.call('ta_web_host_clock_resume', state.pointer);
1554
+ }
1555
+ state.advance(); // the host's clock starts now, not at 0
1556
+ }
1557
+
1558
+ // Host.restore(snapshot, config, options) -> Host: a new Host running the
1559
+ // snapshot, made by the constructor with `config` and `options`.
1560
+ static restore(snapshot, config, options) {
1561
+ bytesOf(snapshot, 'restore takes the snapshot\'s bytes first: a Uint8Array or an ArrayBuffer');
1562
+ if (typeof this !== 'function') throw new TypeError('restore is called on Host: Host.restore(snapshot, config, options)');
1563
+ const outer = restoring;
1564
+ restoring = { snapshot };
1565
+ try {
1566
+ return new this(config, options);
1567
+ } finally {
1568
+ restoring = outer;
1569
+ }
1570
+ }
1571
+
1572
+ get closed() { return !checked(this, false).open; }
1573
+ get ticksPerSecond() { return checked(this, false).ticksPerSecond; }
1574
+ // the quickjs engine's heap in bytes (O(1)); undefined on a native host
1575
+ // and on a closed one
1576
+ get quickjsHeapBytes() {
1577
+ const state = checked(this, false);
1578
+ return state.quickjs !== null && state.open ? state.quickjs.heapBytes() : undefined;
1579
+ }
1580
+
1581
+ get nextDeadline() {
1582
+ const state = checked(this, false);
1583
+ if (!state.open) return undefined;
1584
+ const delay = state.fn.ta_web_host_delay(state.pointer);
1585
+ return delay < 0 ? undefined : delay;
1586
+ }
1587
+
1588
+ now() {
1589
+ const state = checked(this, true);
1590
+ return state.fn.ta_web_host_now(state.pointer);
1591
+ }
1592
+
1593
+ // The promise of the next idle turn, the same to every caller until it
1594
+ // settles; it schedules a turn when none is pending.
1595
+ idle() {
1596
+ const state = checked(this, false);
1597
+ if (!state.open) return Promise.reject(refusal('TA_ERROR_STATE', 'the Host is closed'));
1598
+ if (state.idle !== null) return state.idle.promise;
1599
+ const idle = {};
1600
+ idle.promise = new Promise((resolve, reject) => {
1601
+ idle.resolve = resolve;
1602
+ idle.reject = reject;
1603
+ });
1604
+ state.idle = idle;
1605
+ if (state.immediate === null) state.schedule(); // a turn inside this one settles it at its end
1606
+ return idle.promise;
1607
+ }
1608
+
1609
+ close() {
1610
+ const state = checked(this, false);
1611
+ closeSelf(state);
1612
+ state.endings = null;
1613
+ }
1614
+
1615
+ [Symbol.dispose]() { this.close(); }
1616
+
1617
+ [Symbol.asyncDispose]() {
1618
+ let state;
1619
+ try {
1620
+ state = checked(this, false);
1621
+ closeSelf(state);
1622
+ } catch (error) {
1623
+ return Promise.reject(error);
1624
+ }
1625
+ const endings = state.endings;
1626
+ state.endings = null;
1627
+ if (endings !== null && endings.length > 0) return Promise.all(endings).then(() => undefined);
1628
+ return Promise.resolve(undefined);
1629
+ }
1630
+
1631
+ // ---- images and charts ----
1632
+
1633
+ addImage(image) {
1634
+ const state = checked(this, true);
1635
+ return state.call(() => {
1636
+ const bytes = bytesOf(image, 'addImage takes the image\'s bytes: a Uint8Array or an ArrayBuffer');
1637
+ const module = state.module;
1638
+ const [at, length] = module.copyIn(state.scratch, bytes);
1639
+ module.setWord(0, at);
1640
+ module.setWord(1, length);
1641
+ const status = state.fn.ta_web_host_add_image(state.pointer);
1642
+ const why = state.native?.attachError;
1643
+ if (state.native !== null) state.native.attachError = null;
1644
+ if (status === TA_ERROR_UNSUPPORTED && why == null) {
1645
+ throw refusal('TA_ERROR_UNSUPPORTED', 'the image was refused: a chart\'s datamodel is not in this host');
1646
+ }
1647
+ if (status !== TA_OK) throw refusal(module.statusName(status), why == null ? 'the image was refused' : `the image was refused: ${why}`);
1648
+ return module.word(1);
1649
+ });
1650
+ }
1651
+
1652
+ chart(name) {
1653
+ const state = checked(this, true);
1654
+ return state.call(() => {
1655
+ const module = state.module;
1656
+ const [at, length] = module.text(state.scratch, textOf(name, 'chart takes the chart\'s name, a string'));
1657
+ module.setWord(0, at);
1658
+ module.setWord(1, length);
1659
+ const status = state.fn.ta_web_host_chart(state.pointer);
1660
+ if (status !== TA_OK) throw refusal(module.statusName(status), 'the host has no chart of that name');
1661
+ return Object.freeze({ segment: module.word(1), chart: module.word(2) });
1662
+ });
1663
+ }
1664
+
1665
+ boot(segment) {
1666
+ const state = checked(this, true);
1667
+ return state.call(() => {
1668
+ const index = countOf(segment, 'boot takes a segment, the number addImage returned');
1669
+ state.advance();
1670
+ const status = state.fn.ta_web_host_boot(state.pointer, index);
1671
+ if (status !== TA_OK) throw refusal(state.module.statusName(status), 'the segment\'s boot was refused');
1672
+ state.schedule();
1673
+ });
1674
+ }
1675
+
1676
+ actorByName(name) {
1677
+ const state = checked(this, true);
1678
+ return state.call(() => {
1679
+ const module = state.module;
1680
+ const [at, length] = module.text(state.scratch, textOf(name, 'actorByName takes the actor\'s name, a string'));
1681
+ module.setWord(0, at);
1682
+ module.setWord(1, length);
1683
+ state.fn.ta_web_host_actor_by_name(state.pointer);
1684
+ const session = module.word64(0);
1685
+ return session === 0n ? undefined : session;
1686
+ });
1687
+ }
1688
+
1689
+ // ---- actors ----
1690
+
1691
+ spawn(ref, options) {
1692
+ const state = checked(this, true);
1693
+ return state.call(() => {
1694
+ const module = state.module, scratch = state.scratch;
1695
+ inputOptions(options, ['name', 'params', 'traceparent'], 'spawn option');
1696
+ const usage = 'spawn takes a chart reference, {segment, chart}, from host.chart';
1697
+ if (ref === null || typeof ref !== 'object') throw new TypeError(usage);
1698
+ const segment = countOf(ref.segment, usage), chart = countOf(ref.chart, usage);
1699
+ const name = module.text(scratch, optionalText(options?.name, 'spawn\'s name is a string'));
1700
+ const traceparent = module.text(scratch, optionalText(options?.traceparent, 'a traceparent is W3C text, a string'));
1701
+ const params = state.payload(options?.params, { segment, chart }); // moved to core on success
1702
+ state.advance();
1703
+ const w = module.words(), r = module.record;
1704
+ w[r] = segment;
1705
+ w[r + 1] = chart;
1706
+ w[r + 2] = name[0]; w[r + 3] = name[1];
1707
+ w[r + 4] = Number(params & 0xFFFFFFFFn); w[r + 5] = Number(params >> 32n);
1708
+ w[r + 6] = traceparent[0]; w[r + 7] = traceparent[1];
1709
+ const status = state.fn.ta_web_host_spawn(state.pointer);
1710
+ if (status !== TA_OK) throw refusal(module.statusName(status), 'the spawn was refused');
1711
+ state.schedule();
1712
+ return module.word64(1);
1713
+ });
1714
+ }
1715
+
1716
+ // send(target, event, data?, options?) or send(message): its length is 4
1717
+ send(target, event, data, options) { // eslint-disable-line no-unused-vars
1718
+ const args = [...arguments];
1719
+ const state = checked(this, true);
1720
+ return state.call(() => {
1721
+ let message;
1722
+ if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') message = messageOf(args[0]);
1723
+ else {
1724
+ const options = inputOptions(args[3], ['sendid', 'traceparent', 'origin'], 'send option');
1725
+ message = { target: args[0], event: args[1], data: args[2], sendid: options?.sendid, origin: options?.origin, traceparent: options?.traceparent };
1726
+ }
1727
+ const event = eventOf(state, message);
1728
+ eventWords(state.module.words(), state.module.record, event);
1729
+ const status = state.fn.ta_web_host_send(state.pointer);
1730
+ if (status !== TA_OK) throw refusal(state.module.statusName(status), 'the send was refused');
1731
+ state.schedule();
1732
+ });
1733
+ }
1734
+
1735
+ fail(target, sendid) {
1736
+ const state = checked(this, true);
1737
+ return state.call(() => {
1738
+ const event = eventOf(state, { target, sendid, name: null });
1739
+ event.flags = EVENT_ERROR_COMMUNICATION;
1740
+ eventWords(state.module.words(), state.module.record, event);
1741
+ const status = state.fn.ta_web_host_send(state.pointer);
1742
+ if (status !== TA_OK) throw refusal(state.module.statusName(status), 'the failure was refused');
1743
+ state.schedule();
1744
+ });
1745
+ }
1746
+
1747
+ sendMany(items) {
1748
+ const state = checked(this, true);
1749
+ return state.call(() => {
1750
+ if (!Array.isArray(items)) throw new TypeError('sendMany takes an array of messages');
1751
+ const module = state.module;
1752
+ let accepted = 0;
1753
+ try {
1754
+ for (let first = 0; first < items.length; first += SLICE) {
1755
+ const count = Math.min(SLICE, items.length - first);
1756
+ const taken = module.scoped(state.scratch, () => {
1757
+ const room = module.room(state.scratch, 4 * EVENT_WORDS * count) >>> 2;
1758
+ const payloads = [];
1759
+ try {
1760
+ for (let i = 0; i < count; i++) {
1761
+ const event = eventOf(state, messageOf(items[first + i]));
1762
+ if (event.data !== undefined && event.data !== 0n) payloads.push(event.data);
1763
+ eventWords(module.words(), room + i * EVENT_WORDS, event);
1764
+ }
1765
+ } catch (error) {
1766
+ for (const payload of payloads) state.release(payload); // still ours
1767
+ throw error;
1768
+ }
1769
+ module.setWord(0, room << 2);
1770
+ module.setWord(1, count);
1771
+ return state.fn.ta_web_host_send_many(state.pointer);
1772
+ });
1773
+ accepted += taken;
1774
+ if (taken !== count) break; // refused at an event: the rest is not sent
1775
+ }
1776
+ } finally {
1777
+ if (accepted) state.schedule();
1778
+ }
1779
+ return accepted;
1780
+ });
1781
+ }
1782
+
1783
+ terminate(session) {
1784
+ const state = checked(this, true);
1785
+ return state.call(() => {
1786
+ const id = sessionOf(session);
1787
+ const status = state.fn.ta_web_host_terminate(state.pointer, Number(id & 0xFFFFFFFFn), Number(id >> 32n));
1788
+ if (status !== TA_OK) throw refusal(state.module.statusName(status), 'the terminate was refused');
1789
+ state.schedule();
1790
+ });
1791
+ }
1792
+
1793
+ // ---- outputs ----
1794
+
1795
+ metrics() {
1796
+ const state = checked(this, true);
1797
+ return state.call(() => {
1798
+ state.taken = null;
1799
+ const status = state.fn.ta_web_host_metrics(state.pointer);
1800
+ if (status !== TA_OK) throw refusal(state.module.statusName(status), 'metrics were refused (TA_ERROR_STATE: the config has no telemetry)');
1801
+ const taken = state.taken;
1802
+ state.taken = null;
1803
+ return taken;
1804
+ });
1805
+ }
1806
+
1807
+ // ---- hibernation ----
1808
+
1809
+ sweep(maxScan, limit) {
1810
+ const state = checked(this, true);
1811
+ return state.call(() => {
1812
+ const scan = countOf(maxScan, 'sweep\'s maxScan is an integer from 0 to 2^32-1');
1813
+ const most = countOf(limit, 'sweep\'s limit is an integer from 0 to 2^32-1');
1814
+ const module = state.module;
1815
+ const room = Math.min(scan, most); // it answers at most one session a slot scanned
1816
+ const at = room ? module.room(state.scratch, 8 * room) : 0;
1817
+ module.words().set([scan, at, room], module.record);
1818
+ const found = state.fn.ta_web_host_sweep(state.pointer);
1819
+ const words = module.words(), base = at >>> 2;
1820
+ const sessions = new Array(found);
1821
+ for (let i = 0; i < found; i++) sessions[i] = BigInt(words[base + 2 * i]) | (BigInt(words[base + 2 * i + 1]) << 32n);
1822
+ return sessions;
1823
+ });
1824
+ }
1825
+
1826
+ hibernate(session) {
1827
+ const state = checked(this, true);
1828
+ return state.call(() => {
1829
+ const id = sessionOf(session);
1830
+ state.taken = null;
1831
+ const status = state.fn.ta_web_host_hibernate(state.pointer, Number(id & 0xFFFFFFFFn), Number(id >> 32n));
1832
+ if (status !== TA_OK) {
1833
+ let message = status === -6
1834
+ ? 'the actor is not at a stable point now (events waiting, in a macrostep, an invoked child), or not resident'
1835
+ : 'the hibernation was refused';
1836
+ const reason = state.quickjs !== null ? state.quickjs.reason() : state.reason;
1837
+ if (status === TA_ERROR_UNSUPPORTED && reason) message = reason;
1838
+ throw refusal(state.module.statusName(status), message);
1839
+ }
1840
+ const taken = state.taken;
1841
+ state.taken = null;
1842
+ return taken;
1843
+ });
1844
+ }
1845
+
1846
+ wake(session, blob) {
1847
+ const state = checked(this, true);
1848
+ return state.call(() => {
1849
+ const id = sessionOf(session);
1850
+ const bytes = bytesOf(blob, 'wake takes the blob hibernate gave: a Uint8Array or an ArrayBuffer');
1851
+ const module = state.module;
1852
+ const [at, length] = module.copyIn(state.scratch, bytes);
1853
+ module.setWord64(0, id);
1854
+ module.setWord(2, at);
1855
+ module.setWord(3, length);
1856
+ const status = state.fn.ta_web_host_wake(state.pointer);
1857
+ if (status !== TA_OK) {
1858
+ throw refusal(module.statusName(status), 'the wake was refused (TA_ERROR_STATE: the session is not hibernated; TA_ERROR_INVALID: not its blob; TA_ERROR_STALE: not its latest blob)');
1859
+ }
1860
+ state.schedule(); // its mailbox runs at the next turn
1861
+ });
1862
+ }
1863
+
1864
+ // ---- migration ----
1865
+
1866
+ migrate(options) {
1867
+ const state = checked(this, true);
1868
+ return state.call(() => {
1869
+ const module = state.module;
1870
+ let name = [0, 0], session = 0n, flags = 0, timeout = 0n;
1871
+ if (options !== undefined) {
1872
+ if (options === null || typeof options !== 'object') throw new TypeError('migrate takes an object of chart, session, wake, timeout, or nothing');
1873
+ onlyKnown(options, ['chart', 'session', 'wake', 'timeout'], 'migrate option');
1874
+ const { chart, session: given, wake, timeout: ms } = options;
1875
+ if (chart !== undefined) {
1876
+ textOf(chart, 'migrate\'s chart is a chart\'s name, a string');
1877
+ if (chart.length === 0) throw new RangeError('migrate\'s chart is a chart\'s name; leave it out for every chart');
1878
+ name = module.text(state.scratch, chart);
1879
+ }
1880
+ if (given !== undefined) session = sessionOf(given);
1881
+ if (wake !== undefined) {
1882
+ if (typeof wake !== 'boolean') throw new TypeError('migrate\'s wake is a boolean');
1883
+ flags = wake ? MIGRATE_WAKE : 0;
1884
+ }
1885
+ if (ms !== undefined) {
1886
+ if (typeof ms !== 'number') throw new TypeError('migrate\'s timeout is a number of milliseconds');
1887
+ const ns = ms * 1e6 + 0.5;
1888
+ if (!(ms >= 0) || !(ns < 18446744073709551616)) {
1889
+ throw new RangeError('migrate\'s timeout is milliseconds, not negative, below 2^64 nanoseconds');
1890
+ }
1891
+ timeout = ticksAfter(state, BigInt(Math.trunc(ns)));
1892
+ }
1893
+ }
1894
+ state.advance(); // the timeout counts from the host's clock now
1895
+ const w = module.words(), r = module.record;
1896
+ w[r] = name[0]; w[r + 1] = name[1];
1897
+ w[r + 2] = Number(session & 0xFFFFFFFFn); w[r + 3] = Number(session >> 32n);
1898
+ w[r + 4] = flags;
1899
+ w[r + 5] = Number(timeout & 0xFFFFFFFFn); w[r + 6] = Number(timeout >> 32n);
1900
+ const status = state.fn.ta_web_host_migrate(state.pointer);
1901
+ if (status !== TA_OK) throw refusal(module.statusName(status), 'the migration was refused');
1902
+ state.schedule(); // the migration moves actors in the next runs
1903
+ return module.word(1);
1904
+ });
1905
+ }
1906
+
1907
+ // ---- snapshots ----
1908
+
1909
+ snapshot() {
1910
+ const state = checked(this, true);
1911
+ return state.call(() => {
1912
+ const module = state.module;
1913
+ const ready = state.fn.ta_web_host_quiescent(state.pointer);
1914
+ if (ready !== TA_OK) {
1915
+ throw refusal(module.statusName(ready), 'a snapshot needs a quiescent host (TA_ERROR_STATE: from a handler, with an effect or a reply pending, or during a migration)');
1916
+ }
1917
+ state.advance(); // the snapshot's time is now, not the last turn's
1918
+ const [stateAt, stateLength] = cbor.write(module, state.scratch, { [state.datamodelName]: (state.quickjs ?? state.native).snapshot() });
1919
+ const [labelAt, labelLength] = module.text(state.scratch, LABEL);
1920
+ module.words().set([labelAt, labelLength, stateAt, stateLength], module.record);
1921
+ state.taken = null;
1922
+ const status = state.fn.ta_web_host_snapshot(state.pointer);
1923
+ if (status !== TA_OK) throw refusal(module.statusName(status), 'the snapshot was refused');
1924
+ const taken = state.taken;
1925
+ state.taken = null;
1926
+ return taken;
1927
+ });
1928
+ }
1929
+ }
1930
+
1931
+ // Nanoseconds as ticks at the host's rate, rounded up.
1932
+ function ticksAfter(state, ns) {
1933
+ const rate = BigInt(state.ticksPerSecond), billion = 1000000000n;
1934
+ const ticks = (ns / billion) * rate + ((ns % billion) * rate) / billion;
1935
+ const back = (ticks / rate) * billion + ((ticks % rate) * billion) / rate;
1936
+ return back < ns ? ticks + 1n : ticks;
1937
+ }
1938
+
1939
+ // close()'s work: from a handler (a call or a turn on the stack) it is done
1940
+ // when the outermost one returns; a kept error of the last take is thrown
1941
+ // once the host is freed.
1942
+ function closeSelf(state) {
1943
+ state.endings = null;
1944
+ if (!state.open) return;
1945
+ if (state.depth > 0 || state.turning) state.closing = true;
1946
+ else state.closeNow();
1947
+ if (!state.open) {
1948
+ const kept = state.takeKept();
1949
+ if (kept !== null) throw kept[0];
1950
+ }
1951
+ }
1952
+
1953
+ // A message, the object send.message gives: its known keys, the others
1954
+ // ignored, so a newer sender's keys do not break an older host.
1955
+ function messageOf(value) {
1956
+ if (value === null || typeof value !== 'object') {
1957
+ throw new TypeError('a message is an object of target, event, data, sendid, origin, traceparent');
1958
+ }
1959
+ const { target, event, data, sendid, origin, traceparent } = value;
1960
+ if (target === undefined || event === undefined) throw new TypeError('a message has a target and an event');
1961
+ return { target, event, data, sendid, origin, traceparent };
1962
+ }
1963
+
1964
+ // An event of send, sendMany and fail as words for core (texts in the
1965
+ // host's arena, the data a payload of the target session's datamodel, made
1966
+ // last, so nothing needs releasing when an earlier field is refused).
1967
+ function eventOf(state, message) {
1968
+ const module = state.module, scratch = state.scratch;
1969
+ const session = targetOf(state, message.target);
1970
+ const event = { session };
1971
+ if (message.name !== null) event.name = module.text(scratch, textOf(message.event, 'an event\'s name is a string'));
1972
+ event.sendid = module.text(scratch, optionalText(message.sendid, 'a sendid is a string'));
1973
+ event.origin = module.text(scratch, optionalText(addressText(message.origin), 'an origin is an address, a string or an Address'));
1974
+ event.traceparent = module.text(scratch, optionalText(message.traceparent, 'a traceparent is W3C text, a string'));
1975
+ event.data = state.payload(message.data, { session });
1976
+ return event;
1977
+ }
1978
+
1979
+ // An event's target: a session, or a local address core resolves.
1980
+ function targetOf(state, target) {
1981
+ const value = isAddress(target) ? target.text : target;
1982
+ if (typeof value !== 'string') {
1983
+ if (typeof value === 'bigint' || typeof value === 'number') return sessionOf(value);
1984
+ throw new TypeError('a target is a session (a bigint or a safe integer) or a local address (a string or an Address)');
1985
+ }
1986
+ const module = state.module;
1987
+ const [at, length] = module.text(state.scratch, value);
1988
+ module.setWord(0, at);
1989
+ module.setWord(1, length);
1990
+ const status = state.fn.ta_web_host_resolve(state.pointer);
1991
+ if (status !== TA_OK) throw refusal(module.statusName(status), 'the address names no local session');
1992
+ return module.word64(1);
1993
+ }
1994
+
1995
+ // ---- typed methods (methods.c) ------------------------------------------------------------------
1996
+
1997
+ const METHODS = [
1998
+ ['actorState', 'actor.state'], ['actorContext', 'actor.context'], ['actorList', 'actor.list'],
1999
+ ['actorGet', 'actor.get'], ['hostStats', 'host.stats'], ['hostConfig', 'host.config'],
2000
+ ['traceConfigure', 'trace.configure'], ['traceWatch', 'trace.watch'], ['traceUnwatch', 'trace.unwatch'],
2001
+ ['traceEnd', 'trace.end'], ['traceSpansDecode', 'trace.spans.decode'],
2002
+ ];
2003
+
2004
+ for (const [js, core] of METHODS) {
2005
+ const method = {
2006
+ [js](params, onResult, onError) {
2007
+ const state = checked(this, true);
2008
+ return state.call(() => {
2009
+ const failed = onError === null ? undefined : onError;
2010
+ if (typeof onResult !== 'function' || (typeof failed !== 'function' && failed !== undefined)) {
2011
+ throw new TypeError('a typed method takes (params, onResult(host, result), onError?(host, error))');
2012
+ }
2013
+ const handlers = state.handlers();
2014
+ if (handlers === undefined) throw refusal('TA_ERROR_STATE', 'the Host\'s handlers are gone');
2015
+ handlers.pending ??= [];
2016
+ const module = state.module;
2017
+ const slot = state.fn.ta_web_pending_add(state.pointer);
2018
+ if (slot === 0) throw refusal('TA_ERROR_NO_MEMORY', 'no memory for a pending method');
2019
+ const id = module.word64(0);
2020
+ const at = 2 * (slot - 1);
2021
+ // actor.get's timers[].due: the host's ticks as milliseconds on now()'s clock
2022
+ handlers.pending[at] = core === 'actor.get' ? (host, result) => onResult(host, state.timesInMilliseconds(result)) : onResult;
2023
+ handlers.pending[at + 1] = failed;
2024
+ let posted = false;
2025
+ try {
2026
+ state.advance(); // trace.watch's end is a time of the host's clock
2027
+ const message = params === undefined ? { method: core, id } : { method: core, params, id };
2028
+ const [bytesAt, length] = cbor.write(module, state.scratch, message);
2029
+ module.words().set([bytesAt, length, Number(id & 0xFFFFFFFFn), Number(id >> 32n)], module.record);
2030
+ const status = state.fn.ta_web_host_post(state.pointer);
2031
+ if (status !== TA_OK) {
2032
+ posted = true; // the row went with the refusal
2033
+ throw refusal(module.statusName(status), 'the method\'s post was refused');
2034
+ }
2035
+ posted = true;
2036
+ } catch (error) {
2037
+ handlers.pending[at] = undefined;
2038
+ handlers.pending[at + 1] = undefined;
2039
+ if (!posted && state.open) state.fn.ta_web_pending_remove(state.pointer, Number(id & 0xFFFFFFFFn), Number(id >> 32n));
2040
+ throw error;
2041
+ }
2042
+ state.schedule();
2043
+ });
2044
+ },
2045
+ }[js];
2046
+ Object.defineProperty(Host.prototype, js, { value: method, writable: true, configurable: true, enumerable: false });
2047
+ }
2048
+
2049
+ export { TinyactorsError };