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