@tinyactors/node 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +388 -156
- package/node/index.d.ts +915 -0
- package/node/index.js +44 -0
- package/node/transports.js +60 -0
- package/node/ws.js +152 -0
- package/package.json +22 -17
- package/shared/core.mjs +2966 -0
- package/shared/ecmascript.mjs +670 -0
- package/index.d.ts +0 -1875
- package/index.js +0 -34
- package/lib/actor.js +0 -85
- package/lib/debug/breakpoints.js +0 -349
- package/lib/debug/console.js +0 -149
- package/lib/debug/expressions.js +0 -133
- package/lib/debug/frames.js +0 -119
- package/lib/debug/labels.js +0 -142
- package/lib/debug/macrosteps.js +0 -207
- package/lib/debug/protocol.js +0 -186
- package/lib/debug/sources.js +0 -218
- package/lib/debug/variables.js +0 -265
- package/lib/debug.js +0 -1434
- package/lib/definition.js +0 -139
- package/lib/errors.js +0 -24
- package/lib/events.js +0 -56
- package/lib/image.js +0 -90
- package/lib/loader.js +0 -68
- package/lib/metrics.js +0 -333
- package/lib/native.js +0 -8
- package/lib/otlp.js +0 -332
- package/lib/statechart.js +0 -768
- package/lib/system.js +0 -2183
- package/lib/tracing.js +0 -164
package/lib/system.js
DELETED
|
@@ -1,2183 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
// System facade over the native System (ADR 0012) and the generated core
|
|
4
|
-
// module (ADR 0013). Scheduling is native (ADR 0007): nothing here takes part
|
|
5
|
-
// in it; spawn() and destroy() only reach core, whose hooks tell the pump.
|
|
6
|
-
|
|
7
|
-
const v8 = require('node:v8');
|
|
8
|
-
|
|
9
|
-
const native = require('./native');
|
|
10
|
-
const { TinyactorsError } = require('./errors');
|
|
11
|
-
const { Definition, identityOf } = require('./definition');
|
|
12
|
-
const { DefinitionBuilder } = require('./statechart');
|
|
13
|
-
const { ActorID } = require('./actor');
|
|
14
|
-
const { EventNames } = require('./events');
|
|
15
|
-
const { SessionImage, handleOf } = require('./image');
|
|
16
|
-
const { traceConfig, TRACE_KINDS } = require('./tracing');
|
|
17
|
-
const { buildSnapshot } = require('./metrics');
|
|
18
|
-
|
|
19
|
-
const NO_STATE = 4294967295;
|
|
20
|
-
|
|
21
|
-
const { core } = native;
|
|
22
|
-
|
|
23
|
-
// Compiles a spec in the generated shape. A refused chart throws with core's
|
|
24
|
-
// compile error formatted into the message (ADR 0058), and the error itself,
|
|
25
|
-
// with a readable path, as `detail`.
|
|
26
|
-
/* Core's TA_MICROSTEP_LIMIT_NONE: this definition has no limit (ADR 0075). */
|
|
27
|
-
const MICROSTEP_LIMIT_NONE = 0xffffffff;
|
|
28
|
-
|
|
29
|
-
/* `options.microstepLimit`: undefined, or a count from 0 (none) up. */
|
|
30
|
-
function microstepLimitOption(options, where) {
|
|
31
|
-
if (options === null || typeof options !== 'object') {
|
|
32
|
-
throw new TinyactorsError(`${where}: options must be an object`, 'invalid');
|
|
33
|
-
}
|
|
34
|
-
const limit = options.microstepLimit;
|
|
35
|
-
if (limit !== undefined && !(Number.isInteger(limit) && limit >= 0 && limit < MICROSTEP_LIMIT_NONE)) {
|
|
36
|
-
throw new TinyactorsError(`${where}: microstepLimit must be a whole number from 0 (none)`, 'invalid');
|
|
37
|
-
}
|
|
38
|
-
return limit;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function compile(system, spec) {
|
|
42
|
-
try {
|
|
43
|
-
return core.definition_compile_spec(system, spec);
|
|
44
|
-
} catch (error) {
|
|
45
|
-
const refusal = error instanceof TinyactorsError ? error.detail?.error : undefined;
|
|
46
|
-
if (refusal === undefined) {
|
|
47
|
-
throw error;
|
|
48
|
-
}
|
|
49
|
-
let text;
|
|
50
|
-
try {
|
|
51
|
-
text = core.compile_error_format(spec, refusal);
|
|
52
|
-
} catch {
|
|
53
|
-
text = `${refusal.code}: ${refusal.message}`;
|
|
54
|
-
}
|
|
55
|
-
throw new TinyactorsError(`chart refused: ${text}`, error.code, {
|
|
56
|
-
error: refusal,
|
|
57
|
-
code: refusal.code,
|
|
58
|
-
path: pathText(refusal.path),
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// What a registered compiler returned, in the shape the built-in data model
|
|
64
|
-
// runs (ADR 0019): a function for a value, a condition or a script, and a
|
|
65
|
-
// { get, set } location for a location. A data name as a location reads and
|
|
66
|
-
// assigns that name, and assigning a name the data does not have fails as
|
|
67
|
-
// the built-in model's own data names do.
|
|
68
|
-
function normalizeCompiled(made, role) {
|
|
69
|
-
if (role !== 'location') {
|
|
70
|
-
if (typeof made !== 'function') {
|
|
71
|
-
throw new TypeError(`compile() must return a function for a ${role}`);
|
|
72
|
-
}
|
|
73
|
-
return made;
|
|
74
|
-
}
|
|
75
|
-
if (typeof made === 'string') {
|
|
76
|
-
const name = made;
|
|
77
|
-
return {
|
|
78
|
-
get() { return this[name]; },
|
|
79
|
-
set(value) {
|
|
80
|
-
if (!Object.hasOwn(this, name)) {
|
|
81
|
-
throw new TypeError(`assignment to an undeclared data name: ${name}`);
|
|
82
|
-
}
|
|
83
|
-
this[name] = value;
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
if (made === null || typeof made !== 'object' || typeof made.get !== 'function' || typeof made.set !== 'function') {
|
|
88
|
-
throw new TypeError('compile() must return a data name or { get, set } for a location');
|
|
89
|
-
}
|
|
90
|
-
return made;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// `states[0].transitions[1].condition`, from core's path elements.
|
|
94
|
-
function pathText(path) {
|
|
95
|
-
const noIndex = 4294967295;
|
|
96
|
-
return (path ?? [])
|
|
97
|
-
.map(({ member, index }, at) => `${at === 0 ? '' : '.'}${member}${index === noIndex ? '' : `[${index}]`}`)
|
|
98
|
-
.join('');
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// The native System behind a public one, for other lib/ modules and tests.
|
|
102
|
-
// index.js does not export it.
|
|
103
|
-
let nativeOf;
|
|
104
|
-
// handler(system, kind, payload): the pump hands every service effect to it
|
|
105
|
-
// (src/napi_services.h). It is one function for the environment, so no
|
|
106
|
-
// native reference keeps a System alive.
|
|
107
|
-
let effectHandler;
|
|
108
|
-
// observe(system, { traces, log, runaway, defined, deadLetter, dropped }):
|
|
109
|
-
// what lib/debug.js reads beside the application (ADR 0026).
|
|
110
|
-
// `traces(traces, logs)` gets every turn's OTLP bytes the application's
|
|
111
|
-
// trace sink gets, installing a sink of its own when the application has
|
|
112
|
-
// none; `log(record)` every <log> record; `runaway(actor)` each actor
|
|
113
|
-
// quarantined as a runaway (core ADR 0075); `defined(id)` each definition
|
|
114
|
-
// define() registered, a new one or one answered by identity (core ADR
|
|
115
|
-
// 0077), whose spans may have moved (core ADR 0085); `deadLetter(record)`
|
|
116
|
-
// every dead letter, as the application's deadLetter hook gets it, just
|
|
117
|
-
// before it does; `dropped({ source, sendID, event, type, target, error })`
|
|
118
|
-
// each <send> an I/O processor failed, as its sender gets
|
|
119
|
-
// error.communication for it. Observers never change what the application
|
|
120
|
-
// hears. Returns { stop() }. index.js does not export it.
|
|
121
|
-
let observe;
|
|
122
|
-
|
|
123
|
-
// The SCXML invoker type core normalizes "scxml" and its URI to (core
|
|
124
|
-
// ADR 0016); the in-system SCXML invoker is registered under it.
|
|
125
|
-
const SCXML_INVOKER = 'http://www.w3.org/TR/scxml/';
|
|
126
|
-
const SCXML_ALIASES = new Set(['scxml', 'http://www.w3.org/TR/scxml', SCXML_INVOKER]);
|
|
127
|
-
|
|
128
|
-
// Systems created in this process, to tell their metric streams apart.
|
|
129
|
-
let systemCount = 0;
|
|
130
|
-
|
|
131
|
-
// core's counters are uint64 (bigints across the binding); as numbers.
|
|
132
|
-
function numbers(counters) {
|
|
133
|
-
const out = {};
|
|
134
|
-
for (const [key, value] of Object.entries(counters)) {
|
|
135
|
-
out[key] = Number(value);
|
|
136
|
-
}
|
|
137
|
-
return out;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
class System {
|
|
141
|
-
#native;
|
|
142
|
-
#events;
|
|
143
|
-
// Definition ID -> true when it runs the JavaScript data model; read from
|
|
144
|
-
// core once per definition.
|
|
145
|
-
#javascript = new Map();
|
|
146
|
-
|
|
147
|
-
// Services (ROADMAP step 13): I/O processors by type, invokers by type,
|
|
148
|
-
// live JavaScript invocations by service handle, and the log sink.
|
|
149
|
-
#io = new Map();
|
|
150
|
-
#invokers = new Map();
|
|
151
|
-
#invocations = new Map();
|
|
152
|
-
#logSink;
|
|
153
|
-
#traceSink;
|
|
154
|
-
#traceConfig = {};
|
|
155
|
-
// observe() observers, and whether the native sink is installed for them
|
|
156
|
-
// alone (the application has none).
|
|
157
|
-
#observers = new Set();
|
|
158
|
-
#observerSink = false;
|
|
159
|
-
// Active watchTraces() handles, and every definition's identity, for the
|
|
160
|
-
// watches and for metrics().
|
|
161
|
-
#watches = new Set();
|
|
162
|
-
// Loaders by family (napi ADR 0020), and why the last load of an address
|
|
163
|
-
// failed, for the deadLetter hook's `detail`.
|
|
164
|
-
#loaders = new Map();
|
|
165
|
-
#loadDetails = new Map();
|
|
166
|
-
// Families whose actors unload() offloaded, with no loader of their own.
|
|
167
|
-
#offloadFamilies = new Set();
|
|
168
|
-
#startTime = Date.now();
|
|
169
|
-
#metricsName = String((systemCount += 1));
|
|
170
|
-
// Aborted on close(): the signal every EffectContext carries.
|
|
171
|
-
#lifetime = new AbortController();
|
|
172
|
-
#effectContext;
|
|
173
|
-
|
|
174
|
-
static {
|
|
175
|
-
nativeOf = (system) => system.#native;
|
|
176
|
-
effectHandler = (system, kind, payload) => system.#effect(kind, payload);
|
|
177
|
-
observe = (system, observer) => system.#observe(observer);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Options:
|
|
182
|
-
* - scheduling: { resumeBudget, actionBudget, resumesPerTurn } (ADR 0007);
|
|
183
|
-
* - finished: "destroy" (the default) or "retain" (ADR 0012);
|
|
184
|
-
* - scheduling.messageBudget: deliveries per turn, and dead letters
|
|
185
|
-
* reported per turn; scheduling.maxQueuedMessages: post() throws
|
|
186
|
-
* `queue-full` beyond it (ADR 0005);
|
|
187
|
-
* - done({ actor, finalState, data }), fault({ actor, operation, code,
|
|
188
|
-
* message }) and deadLetter({ target, event, reason, detail?, data?,
|
|
189
|
-
* traceparent? }): hooks the pump calls at the end of a turn (ADRs
|
|
190
|
-
* 0008, 0012). `detail` says why a load failed, for mail that waited
|
|
191
|
-
* for a loader (napi ADR 0020); `data` and `traceparent` are what
|
|
192
|
-
* posting the message again needs, absent when it had none.
|
|
193
|
-
*/
|
|
194
|
-
constructor(options) {
|
|
195
|
-
if (options !== undefined && (options === null || typeof options !== 'object')) {
|
|
196
|
-
throw new TinyactorsError('createSystem options must be an object', 'invalid');
|
|
197
|
-
}
|
|
198
|
-
// The native hook is always this system's, so observers hear dead
|
|
199
|
-
// letters too; the application's hook, when it has one, gets each as
|
|
200
|
-
// before. Anything else the application passed is the native side's to
|
|
201
|
-
// refuse. The native side holds its hooks strongly, so the hook reaches
|
|
202
|
-
// this system through a WeakRef: a system the application drops without
|
|
203
|
-
// close() is still finalized, as with the environment-wide effect handler.
|
|
204
|
-
const deadLetter = options?.deadLetter;
|
|
205
|
-
const self = new WeakRef(this);
|
|
206
|
-
const nativeOptions = deadLetter !== undefined && typeof deadLetter !== 'function' ? options
|
|
207
|
-
: { ...options, deadLetter: (letter) => self.deref()?.#deadLetter(letter, deadLetter) };
|
|
208
|
-
this.#native = new native.System(this, nativeOptions);
|
|
209
|
-
this.#events = new EventNames(this.#native);
|
|
210
|
-
const unloadValues = options?.unloadValues ?? 'serialize';
|
|
211
|
-
if (unloadValues !== 'serialize' && unloadValues !== 'handles') {
|
|
212
|
-
throw new TinyactorsError('createSystem(): unloadValues must be "serialize" or "handles"', 'invalid');
|
|
213
|
-
}
|
|
214
|
-
this.#native.setOffloadValues(v8.serialize, v8.deserialize, unloadValues === 'handles');
|
|
215
|
-
const { io, invokers, log } = options ?? {};
|
|
216
|
-
for (const [type, processor] of Object.entries(servicesOf(io, 'createSystem(): io'))) {
|
|
217
|
-
this.registerIO(type, processor, { location: processor?.location, origin: processor?.origin });
|
|
218
|
-
}
|
|
219
|
-
for (const [type, invoker] of Object.entries(servicesOf(invokers, 'createSystem(): invokers'))) {
|
|
220
|
-
this.registerInvoker(type, invoker);
|
|
221
|
-
}
|
|
222
|
-
if (log !== undefined) {
|
|
223
|
-
this.setLogSink(log);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Make `processor` the I/O processor for `<send type>` (core ADRs 0015,
|
|
229
|
-
* 0046). Core calls it while an actor runs, so the call is queued and
|
|
230
|
-
* processor.send(request, context) runs at the end of that pump turn,
|
|
231
|
-
* never inside core (ADR 0001 rule 3). `request` is { source, sendID,
|
|
232
|
-
* event, type, target, data } (and { content, contentType } for a literal
|
|
233
|
-
* <content>); `context` is { system, signal, post }, where `signal` aborts
|
|
234
|
-
* on close(). A reply is an event the processor posts, now or later. A
|
|
235
|
-
* processor that throws or whose promise rejects has failed the send: the
|
|
236
|
-
* sender gets an external `error.communication` event whose data is
|
|
237
|
-
* { sendID, type, error }.
|
|
238
|
-
*
|
|
239
|
-
* `options` says how core renders the processor's text without running
|
|
240
|
-
* JavaScript (core ADR 0068):
|
|
241
|
-
* - `location`: this session's address through the processor, listed in
|
|
242
|
-
* `_ioprocessors` (`context.ioProcessors`). `{session}` is the session
|
|
243
|
-
* ID, `{family}` and `{name}` its named address.
|
|
244
|
-
* - `origin`: the URI of a computed origin (post with `origin: { type,
|
|
245
|
-
* token }`); `{token}` is the token.
|
|
246
|
-
* A processor posts events with an origin so a chart can answer them
|
|
247
|
-
* with `send(...).via(({ event }) => event.originType).to(({ event }) => event.origin)`: see post().
|
|
248
|
-
*/
|
|
249
|
-
registerIO(type, processor, options = {}) {
|
|
250
|
-
if (typeof type !== 'string' || type === '') {
|
|
251
|
-
throw new TinyactorsError('registerIO(): expected a type string', 'invalid');
|
|
252
|
-
}
|
|
253
|
-
if (processor === null || typeof processor !== 'object' || typeof processor.send !== 'function') {
|
|
254
|
-
throw new TinyactorsError('registerIO(): expected an I/O processor with a send(request, context) method', 'invalid');
|
|
255
|
-
}
|
|
256
|
-
const { location, origin } = options ?? {};
|
|
257
|
-
for (const [name, value] of [['location', location], ['origin', origin]]) {
|
|
258
|
-
if (value !== undefined && typeof value !== 'string') {
|
|
259
|
-
throw new TinyactorsError(`registerIO(): options.${name} must be a string template`, 'invalid');
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
this.#native.registerIO(type, location, origin);
|
|
263
|
-
this.#io.set(type, processor);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
/**
|
|
267
|
-
* Open a scope for a connection or a session of processor `type`, storing
|
|
268
|
-
* `uri` once (core ADR 0068). Events posted with `origin: { type, scope }`
|
|
269
|
-
* name it; after closeScope() their origin is empty, so a late reply
|
|
270
|
-
* reaches the processor with no target.
|
|
271
|
-
*/
|
|
272
|
-
openScope(type, uri) {
|
|
273
|
-
if (typeof uri !== 'string' || uri === '') {
|
|
274
|
-
throw new TinyactorsError('openScope(): expected a URI string', 'invalid');
|
|
275
|
-
}
|
|
276
|
-
const { index, generation } = this.#native.openScope(type, uri);
|
|
277
|
-
return Object.freeze({ type, uri, index, generation });
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/** Close a scope from openScope(). Closing it again does nothing. */
|
|
281
|
-
closeScope(scope) {
|
|
282
|
-
if (scope === null || typeof scope !== 'object') {
|
|
283
|
-
throw new TinyactorsError('closeScope(): expected a scope from openScope()', 'invalid');
|
|
284
|
-
}
|
|
285
|
-
this.#native.closeScope(scope.index, scope.generation);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Make `invoker` the invoker for `<invoke type>` (core ADR 0016). Core
|
|
290
|
-
* starts, cancels and forwards to invocations while an actor runs, so each
|
|
291
|
-
* call is queued and runs at the end of that pump turn:
|
|
292
|
-
* invoker.start(request, reporter) returns the service, whose cancel() runs
|
|
293
|
-
* when the invoking state exits and whose optional forward(event) gets
|
|
294
|
-
* autoforwarded events. The reporter's event(name, data) and done(data)
|
|
295
|
-
* reach the parent as external events (done is done.invoke.<id>); its
|
|
296
|
-
* unavailable(error) retires the invocation, and the parent gets
|
|
297
|
-
* error.communication. Its signal aborts on cancel, done, unavailable and
|
|
298
|
-
* close(). "scxml" names the in-system SCXML invoker's type; registering
|
|
299
|
-
* it replaces that invoker.
|
|
300
|
-
*/
|
|
301
|
-
registerInvoker(type, invoker) {
|
|
302
|
-
if (typeof type !== 'string' || type === '') {
|
|
303
|
-
throw new TinyactorsError('registerInvoker(): expected a type string', 'invalid');
|
|
304
|
-
}
|
|
305
|
-
if (invoker === null || typeof invoker !== 'object' || typeof invoker.start !== 'function') {
|
|
306
|
-
throw new TinyactorsError('registerInvoker(): expected an invoker with a start(request, reporter) method', 'invalid');
|
|
307
|
-
}
|
|
308
|
-
const canonical = SCXML_ALIASES.has(type) ? SCXML_INVOKER : type;
|
|
309
|
-
this.#native.registerInvoker(canonical);
|
|
310
|
-
this.#invokers.set(canonical, invoker);
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* Send `<log>` records to `sink` ({ source, label, hasValue, value }), at
|
|
315
|
-
* the end of the pump turn that ran them (core ADR 0045). Without a sink a
|
|
316
|
-
* <log> only evaluates its expression.
|
|
317
|
-
*/
|
|
318
|
-
setLogSink(sink) {
|
|
319
|
-
if (sink !== undefined && typeof sink !== 'function') {
|
|
320
|
-
throw new TinyactorsError('setLogSink(): expected a function or undefined', 'invalid');
|
|
321
|
-
}
|
|
322
|
-
this.#logSink = sink;
|
|
323
|
-
this.#native.setLogSink(sink !== undefined || this.#observing('log'));
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Hand traces and logs to `sink(traces, logs)` as OTLP protobuf (napi
|
|
328
|
-
* ADRs 0016 and 0017): once per pump turn, `traces` is one Uint8Array
|
|
329
|
-
* holding one ExportTraceServiceRequest with the spans that ended in that
|
|
330
|
-
* turn (empty when none ended), and `logs` one ExportLogsServiceRequest
|
|
331
|
-
* with the turn's log records, or undefined. Post them to an OTLP/HTTP
|
|
332
|
-
* endpoint's `/v1/traces` and `/v1/logs` as they are (Content-Type:
|
|
333
|
-
* application/x-protobuf), or decode traces with decodeTraces(). Logs are
|
|
334
|
-
* failures (an action that failed, an error.* raised, a run stopped for
|
|
335
|
-
* lack of memory) and <log>, written whatever the sampling, at most
|
|
336
|
-
* `logLimit` (default 20) per definition and name per second; the next
|
|
337
|
-
* log that passes carries `tinyactors.suppressed`. `logs: false` writes
|
|
338
|
-
* none. Without a sink (undefined) core builds no record.
|
|
339
|
-
*
|
|
340
|
-
* options:
|
|
341
|
-
* - detail: "summary" (default: a span per macrostep, lifecycle, and
|
|
342
|
-
* failures), "decisions" (adds microsteps, conditions, raised events)
|
|
343
|
-
* or "full" (every kind); see TRACE_DETAIL. Watched actors
|
|
344
|
-
* (watchTraces) always get every kind;
|
|
345
|
-
* - kinds: the record kinds wanted (TRACE_KINDS names), overriding
|
|
346
|
-
* `detail`: core builds no other record;
|
|
347
|
-
* - sample: the ratio of the traces this system starts that are sampled,
|
|
348
|
-
* 0 to 1 (default 1), decided as OpenTelemetry's TraceIDRatioBased
|
|
349
|
-
* does (core ADR 0073); a traceparent keeps its caller's decision;
|
|
350
|
-
* - unsampled: also trace macrosteps whose traceparent is not sampled;
|
|
351
|
-
* - resource: resource attributes, { "service.name": "orders", ... },
|
|
352
|
-
* strings only;
|
|
353
|
-
* - values: put event data and assigned values in attributes, as JSON
|
|
354
|
-
* cut at `valueLimit` characters (default 256, at most 1023). Off by
|
|
355
|
-
* default: values may hold personal data;
|
|
356
|
-
* - parent: "cause" (default) parents a macrostep under the step that
|
|
357
|
-
* caused it; "link" makes it a root and links it to its cause;
|
|
358
|
-
* - seed: a bigint; trace IDs the system starts (for deliveries and
|
|
359
|
-
* spawns without a traceparent) become a fixed sequence, for tests.
|
|
360
|
-
*
|
|
361
|
-
* Replacing or removing a sink ends the spans still open, marked
|
|
362
|
-
* `scxml.incomplete`, and hands them to the previous sink first.
|
|
363
|
-
*/
|
|
364
|
-
setTraceSink(sink, options = {}) {
|
|
365
|
-
if (sink !== undefined && typeof sink !== 'function') {
|
|
366
|
-
throw new TinyactorsError('setTraceSink(): expected a function or undefined', 'invalid');
|
|
367
|
-
}
|
|
368
|
-
const { unsampled = false, resource = {}, values = false, valueLimit = 256, parent = 'cause', seed,
|
|
369
|
-
logs = true, logLimit = 20 } = options ?? {};
|
|
370
|
-
if (!Number.isInteger(logLimit) || logLimit < 1 || logLimit > 1e6) {
|
|
371
|
-
throw new TinyactorsError('setTraceSink(): options.logLimit must be an integer from 1 to 1000000', 'invalid');
|
|
372
|
-
}
|
|
373
|
-
const config = traceConfig(options ?? {}, 'setTraceSink()');
|
|
374
|
-
if (parent !== 'cause' && parent !== 'link') {
|
|
375
|
-
throw new TinyactorsError('setTraceSink(): options.parent must be "cause" or "link"', 'invalid');
|
|
376
|
-
}
|
|
377
|
-
if (!Number.isInteger(valueLimit) || valueLimit < 0 || valueLimit > 1023) {
|
|
378
|
-
throw new TinyactorsError('setTraceSink(): options.valueLimit must be an integer from 0 to 1023', 'invalid');
|
|
379
|
-
}
|
|
380
|
-
if (resource === null || typeof resource !== 'object') {
|
|
381
|
-
throw new TinyactorsError('setTraceSink(): options.resource must be an object of strings', 'invalid');
|
|
382
|
-
}
|
|
383
|
-
const pairs = [];
|
|
384
|
-
for (const [key, value] of Object.entries(resource)) {
|
|
385
|
-
if (typeof value !== 'string') {
|
|
386
|
-
throw new TinyactorsError(`setTraceSink(): resource attribute "${key}" must be a string`, 'invalid');
|
|
387
|
-
}
|
|
388
|
-
pairs.push(key, value);
|
|
389
|
-
}
|
|
390
|
-
const previous = this.#traceSink;
|
|
391
|
-
const observed = sink === undefined && this.#observing('traces');
|
|
392
|
-
const remaining = observed
|
|
393
|
-
? this.#installObserverSink()
|
|
394
|
-
: this.#native.setTraceSink(sink !== undefined, config.kinds, config.watchedKinds,
|
|
395
|
-
unsampled === true ? config.kinds : 0, config.sample,
|
|
396
|
-
values === true, valueLimit, parent === 'link', pairs, seed,
|
|
397
|
-
logs === false ? 0 : logLimit);
|
|
398
|
-
this.#traceSink = sink;
|
|
399
|
-
this.#observerSink = observed;
|
|
400
|
-
this.#traceConfig = { detail: options?.detail, kinds: options?.kinds, sample: options?.sample,
|
|
401
|
-
unsampled: unsampled === true };
|
|
402
|
-
if (remaining !== undefined) {
|
|
403
|
-
previous?.(remaining.traces, remaining.logs);
|
|
404
|
-
this.#notify('traces', remaining.traces, remaining.logs);
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
// The native sink observers get when the application has none: nothing
|
|
409
|
-
// but what is watched, every kind of it, with values (ADR 0026).
|
|
410
|
-
#installObserverSink() {
|
|
411
|
-
const all = 2 ** TRACE_KINDS.length - 1;
|
|
412
|
-
return this.#native.setTraceSink(true, 0, all, 0, 0, true, 256, false, [], undefined, 0);
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
#observing(what) {
|
|
416
|
-
for (const observer of this.#observers) {
|
|
417
|
-
if (typeof observer[what] === 'function') return true;
|
|
418
|
-
}
|
|
419
|
-
return false;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// Calls `what` of every observer that has it.
|
|
423
|
-
#notify(what, ...args) {
|
|
424
|
-
for (const observer of this.#observers) {
|
|
425
|
-
observer[what]?.(...args);
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
#observe(observer) {
|
|
430
|
-
this.#observers.add(observer);
|
|
431
|
-
this.#applyObservers();
|
|
432
|
-
return Object.freeze({
|
|
433
|
-
stop: () => {
|
|
434
|
-
if (this.#observers.delete(observer) && !this.closed) {
|
|
435
|
-
this.#applyObservers();
|
|
436
|
-
}
|
|
437
|
-
},
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
// Installs or removes the observers' own trace sink, and turns <log>
|
|
442
|
-
// records on or off, as the observers and the application need them.
|
|
443
|
-
#applyObservers() {
|
|
444
|
-
this.#native.setLogSink(this.#logSink !== undefined || this.#observing('log'));
|
|
445
|
-
if (this.#traceSink !== undefined) {
|
|
446
|
-
return;
|
|
447
|
-
}
|
|
448
|
-
const wanted = this.#observing('traces');
|
|
449
|
-
if (wanted === this.#observerSink) {
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
const all = 2 ** TRACE_KINDS.length - 1;
|
|
453
|
-
const remaining = wanted
|
|
454
|
-
? this.#installObserverSink()
|
|
455
|
-
: this.#native.setTraceSink(false, 0, all, 0, 0, false, 256, false, [], undefined, 0);
|
|
456
|
-
this.#observerSink = wanted;
|
|
457
|
-
if (remaining !== undefined) {
|
|
458
|
-
this.#notify('traces', remaining.traces, remaining.logs);
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/**
|
|
463
|
-
* Changes what the installed sink gets, without reinstalling it, so open
|
|
464
|
-
* spans are not ended (napi ADR 0017 section 3). `options` takes
|
|
465
|
-
* `detail`, `kinds` and `sample` as setTraceSink() does; what it leaves
|
|
466
|
-
* out keeps its current value.
|
|
467
|
-
*/
|
|
468
|
-
configureTraces(options = {}) {
|
|
469
|
-
if (options === null || typeof options !== 'object') {
|
|
470
|
-
throw new TinyactorsError('configureTraces(): expected an options object', 'invalid');
|
|
471
|
-
}
|
|
472
|
-
const merged = { ...this.#traceConfig };
|
|
473
|
-
for (const key of ['detail', 'kinds', 'sample']) {
|
|
474
|
-
if (key in options) {
|
|
475
|
-
merged[key] = options[key];
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
if ('detail' in options && !('kinds' in options)) {
|
|
479
|
-
merged.kinds = undefined;
|
|
480
|
-
}
|
|
481
|
-
const config = traceConfig(merged, 'configureTraces()');
|
|
482
|
-
if (!this.#observerSink) {
|
|
483
|
-
// An observers' own sink keeps its masks: they are not the application's.
|
|
484
|
-
this.#native.configureTraces(config.kinds, config.watchedKinds, merged.unsampled ? config.kinds : 0,
|
|
485
|
-
config.sample);
|
|
486
|
-
}
|
|
487
|
-
this.#traceConfig = merged;
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
/**
|
|
491
|
-
* Traces what matches in full, sampled whatever the ratio, until the
|
|
492
|
-
* returned handle's stop() (napi ADR 0017 section 3): deliveries to the
|
|
493
|
-
* actors of `sessions` (session IDs or ActorIDs), to the named actors of
|
|
494
|
-
* `addresses` ({ family, name }, resolved to their sessions now), and to
|
|
495
|
-
* the actors of the definitions of `families` (family names; spawns of
|
|
496
|
-
* those families are watched from their bootstrap). Everything a watched
|
|
497
|
-
* delivery causes in this system is watched too. It needs a sink.
|
|
498
|
-
*/
|
|
499
|
-
watchTraces({ sessions = [], families = [], addresses = [] } = {}) {
|
|
500
|
-
const watch = { sessions: new Set(), families: new Set(families.map(String)) };
|
|
501
|
-
for (const session of sessions) {
|
|
502
|
-
watch.sessions.add(session instanceof ActorID ? BigInt(this.inspect(session).sessionID) : BigInt(session));
|
|
503
|
-
}
|
|
504
|
-
for (const address of addresses) {
|
|
505
|
-
const actor = this.findActor(address);
|
|
506
|
-
if (actor === undefined) {
|
|
507
|
-
throw new TinyactorsError('watchTraces(): no resident actor has that address', 'not-found');
|
|
508
|
-
}
|
|
509
|
-
watch.sessions.add(BigInt(this.inspect(actor).sessionID));
|
|
510
|
-
}
|
|
511
|
-
this.#watches.add(watch);
|
|
512
|
-
this.#applyWatches();
|
|
513
|
-
return Object.freeze({
|
|
514
|
-
stop: () => {
|
|
515
|
-
if (this.#watches.delete(watch) && !this.closed) {
|
|
516
|
-
this.#applyWatches();
|
|
517
|
-
}
|
|
518
|
-
},
|
|
519
|
-
});
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
#watchedFamily(family) {
|
|
523
|
-
for (const watch of this.#watches) {
|
|
524
|
-
if (watch.families.has(family)) {
|
|
525
|
-
return true;
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
return false;
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
#applyWatches() {
|
|
532
|
-
const sessions = new Set();
|
|
533
|
-
const families = new Set();
|
|
534
|
-
for (const watch of this.#watches) {
|
|
535
|
-
watch.sessions.forEach((session) => sessions.add(session));
|
|
536
|
-
watch.families.forEach((family) => families.add(family));
|
|
537
|
-
}
|
|
538
|
-
// Families go to the addon as names: it resolves each definition the
|
|
539
|
-
// first time a delivery meets it, so definitions core registers later
|
|
540
|
-
// (nested and invoke-time children, core ADR 0078) are watched too.
|
|
541
|
-
this.#native.setTraceWatch([...sessions], [...families]);
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
// One service effect, in the order core made the calls (napi_services.h).
|
|
545
|
-
#effect(kind, payload) {
|
|
546
|
-
switch (kind) {
|
|
547
|
-
case 'loads':
|
|
548
|
-
// Loads the turn started (napi ADR 0020); each finishes itself.
|
|
549
|
-
for (const request of payload) {
|
|
550
|
-
this.#runLoad(request).catch(() => {});
|
|
551
|
-
}
|
|
552
|
-
return;
|
|
553
|
-
case 'log':
|
|
554
|
-
this.#logSink?.(payload);
|
|
555
|
-
this.#notify('log', payload);
|
|
556
|
-
return;
|
|
557
|
-
case 'trace':
|
|
558
|
-
this.#traceSink?.(payload.traces, payload.logs);
|
|
559
|
-
this.#notify('traces', payload.traces, payload.logs);
|
|
560
|
-
return;
|
|
561
|
-
case 'runaway':
|
|
562
|
-
this.#notify('runaway', payload);
|
|
563
|
-
return;
|
|
564
|
-
case 'io':
|
|
565
|
-
this.#runIO(payload);
|
|
566
|
-
return;
|
|
567
|
-
case 'invoke-start':
|
|
568
|
-
this.#startInvocation(payload);
|
|
569
|
-
return;
|
|
570
|
-
case 'invoke-cancel':
|
|
571
|
-
this.#cancelInvocation(payload.handle, undefined);
|
|
572
|
-
return;
|
|
573
|
-
case 'invoke-forward':
|
|
574
|
-
this.#forwardInvocation(payload);
|
|
575
|
-
return;
|
|
576
|
-
default:
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
// The context every I/O processor call gets; made once per system.
|
|
582
|
-
#context() {
|
|
583
|
-
this.#effectContext ??= Object.freeze({
|
|
584
|
-
system: this,
|
|
585
|
-
signal: this.#lifetime.signal,
|
|
586
|
-
post: (target, event, data, options) => this.post(target, event, data, options),
|
|
587
|
-
});
|
|
588
|
-
return this.#effectContext;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
#replyContext(traceparent) {
|
|
592
|
-
const base = this.#context();
|
|
593
|
-
return Object.freeze({
|
|
594
|
-
system: base.system,
|
|
595
|
-
signal: base.signal,
|
|
596
|
-
post: (target, event, data, options) =>
|
|
597
|
-
this.post(target, event, data, options?.traceparent === undefined ? { ...options, traceparent } : options),
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
#runIO(payload) {
|
|
602
|
-
// payload.traceparent names the sending step, for the processor to carry along (ADR 0015).
|
|
603
|
-
const request = payload;
|
|
604
|
-
const processor = this.#io.get(request.type);
|
|
605
|
-
if (processor === undefined) {
|
|
606
|
-
this.#communicationError(request, new TinyactorsError(`no I/O processor for "${request.type}"`, 'not-found'));
|
|
607
|
-
return;
|
|
608
|
-
}
|
|
609
|
-
// A reply the processor posts stays in the trace of the sending step
|
|
610
|
-
// unless it names another (napi ADR 0017 section 6).
|
|
611
|
-
const context = request.traceparent === undefined ? this.#context() : this.#replyContext(request.traceparent);
|
|
612
|
-
let outcome;
|
|
613
|
-
try {
|
|
614
|
-
outcome = processor.send(request, context);
|
|
615
|
-
} catch (error) {
|
|
616
|
-
this.#communicationError(request, error);
|
|
617
|
-
return;
|
|
618
|
-
}
|
|
619
|
-
if (outcome !== null && typeof outcome === 'object' && typeof outcome.then === 'function') {
|
|
620
|
-
outcome.then(undefined, (error) => this.#communicationError(request, error));
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
// A failed send reaches its sender as error.communication (ADR 0008:
|
|
625
|
-
// failures after the call reach JavaScript through events or hooks).
|
|
626
|
-
#communicationError(request, error) {
|
|
627
|
-
if (this.closed || request.source === undefined) {
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
|
-
if (this.#observers.size > 0) {
|
|
631
|
-
try {
|
|
632
|
-
this.#notify('dropped', { source: request.source, sendID: request.sendID, event: request.event,
|
|
633
|
-
type: request.type, target: request.target, error });
|
|
634
|
-
} catch {
|
|
635
|
-
// An observer's failure is its own.
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
try {
|
|
639
|
-
this.post(request.source, 'error.communication', { sendID: request.sendID, type: request.type, error });
|
|
640
|
-
} catch {
|
|
641
|
-
// The sender is gone or its mailbox is full: nobody is left to tell.
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
#startInvocation(payload) {
|
|
646
|
-
const { handle, parent, invocationID } = payload;
|
|
647
|
-
const controller = new AbortController();
|
|
648
|
-
const invocation = { controller, service: undefined, live: true };
|
|
649
|
-
this.#invocations.set(handle, invocation);
|
|
650
|
-
// done() and unavailable() end the invocation once core took the
|
|
651
|
-
// report, or answered that the parent or the invocation is gone. A
|
|
652
|
-
// report that throws (queue-full, out-of-memory) was not taken: the
|
|
653
|
-
// invocation stays alive, its signal unaborted, for the service to
|
|
654
|
-
// report again.
|
|
655
|
-
const report = (kind, name, data) => {
|
|
656
|
-
if (!invocation.live || this.closed) {
|
|
657
|
-
return false;
|
|
658
|
-
}
|
|
659
|
-
const taken = this.#native.reportInvoke(parent.slot, parent.generation, invocationID, kind, name, data,
|
|
660
|
-
payload.traceparent);
|
|
661
|
-
if (kind !== 'event') {
|
|
662
|
-
this.#endInvocation(handle, invocation);
|
|
663
|
-
}
|
|
664
|
-
return taken;
|
|
665
|
-
};
|
|
666
|
-
const reporter = Object.freeze({
|
|
667
|
-
signal: controller.signal,
|
|
668
|
-
event: (name, data) => report('event', this.#events.id(name), data),
|
|
669
|
-
done: (data) => report('done', 0, data),
|
|
670
|
-
unavailable: (error) => report('unavailable', 0, error),
|
|
671
|
-
});
|
|
672
|
-
const invoker = this.#invokers.get(payload.type);
|
|
673
|
-
// No service is left to retry these reports, and a throw would reach the
|
|
674
|
-
// pump's effect loop: a report core cannot take is dropped here.
|
|
675
|
-
const unavailable = (error) => {
|
|
676
|
-
try {
|
|
677
|
-
reporter.unavailable(error);
|
|
678
|
-
} catch {
|
|
679
|
-
// queue-full or out-of-memory: the parent does not hear of it, and
|
|
680
|
-
// the invocation, with no service, ends here.
|
|
681
|
-
if (invocation.live) {
|
|
682
|
-
this.#endInvocation(handle, invocation);
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
};
|
|
686
|
-
if (invoker === undefined) {
|
|
687
|
-
unavailable(new TinyactorsError(`no invoker for "${payload.type}"`, 'not-found'));
|
|
688
|
-
return;
|
|
689
|
-
}
|
|
690
|
-
const request = Object.freeze({
|
|
691
|
-
system: this,
|
|
692
|
-
parent,
|
|
693
|
-
invocationID,
|
|
694
|
-
invokeID: payload.invokeID,
|
|
695
|
-
type: payload.type,
|
|
696
|
-
source: payload.source,
|
|
697
|
-
content: payload.content,
|
|
698
|
-
contentType: payload.contentType,
|
|
699
|
-
params: payload.params,
|
|
700
|
-
autoforward: payload.autoforward,
|
|
701
|
-
// The invoking step, for a service that starts work elsewhere (ADR 0015).
|
|
702
|
-
traceparent: payload.traceparent,
|
|
703
|
-
});
|
|
704
|
-
try {
|
|
705
|
-
invocation.service = invoker.start(request, reporter);
|
|
706
|
-
} catch (error) {
|
|
707
|
-
unavailable(error);
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
#endInvocation(handle, invocation) {
|
|
712
|
-
invocation.live = false;
|
|
713
|
-
this.#invocations.delete(handle);
|
|
714
|
-
invocation.controller.abort();
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
#cancelInvocation(handle, reason) {
|
|
718
|
-
const invocation = this.#invocations.get(handle);
|
|
719
|
-
if (invocation === undefined) {
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
this.#endInvocation(handle, invocation);
|
|
723
|
-
try {
|
|
724
|
-
const outcome = invocation.service?.cancel?.(reason);
|
|
725
|
-
if (outcome !== null && typeof outcome === 'object' && typeof outcome.then === 'function') {
|
|
726
|
-
outcome.then(undefined, () => {});
|
|
727
|
-
}
|
|
728
|
-
} catch {
|
|
729
|
-
// A service that fails to cancel is gone as far as the actor is concerned.
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
#forwardInvocation({ handle, event }) {
|
|
734
|
-
const invocation = this.#invocations.get(handle);
|
|
735
|
-
if (invocation === undefined || typeof invocation.service?.forward !== 'function') {
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
try {
|
|
739
|
-
const outcome = invocation.service.forward(event);
|
|
740
|
-
if (outcome !== null && typeof outcome === 'object' && typeof outcome.then === 'function') {
|
|
741
|
-
outcome.then(undefined, () => {});
|
|
742
|
-
}
|
|
743
|
-
} catch {
|
|
744
|
-
// Forwarding is best effort (SCXML 6.4: autoforward has no error path).
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
/** True once close() has run. */
|
|
749
|
-
get closed() {
|
|
750
|
-
return this.#native.closed;
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
/** "realtime" (the default) or "manual" (ADR 0007 point 3). */
|
|
754
|
-
get clock() {
|
|
755
|
-
return this.#native.clock;
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* Core's logical time in milliseconds. With the realtime clock it follows
|
|
760
|
-
* a monotonic clock read natively, relative to system creation plus
|
|
761
|
-
* `initialTime`.
|
|
762
|
-
*/
|
|
763
|
-
get time() {
|
|
764
|
-
return this.#native.time;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* Manual clock only: move time to `time` (never backwards) and resolve once
|
|
769
|
-
* everything due has been dispatched and the system is quiet.
|
|
770
|
-
*/
|
|
771
|
-
advanceTo(time) {
|
|
772
|
-
return this.#native.advanceTo(time);
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
/** Manual clock only: advanceTo(time + milliseconds). */
|
|
776
|
-
advanceBy(milliseconds) {
|
|
777
|
-
if (typeof milliseconds !== 'number' || !(milliseconds >= 0)) {
|
|
778
|
-
throw new TinyactorsError('advanceBy(): expected a non-negative number of milliseconds', 'invalid');
|
|
779
|
-
}
|
|
780
|
-
return this.#native.advanceTo(this.#native.time + milliseconds);
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
/**
|
|
784
|
-
* Register a data model for imported documents (ADR 0019): `compile(source,
|
|
785
|
-
* role)` turns each source expression of a document whose `datamodel` is
|
|
786
|
-
* `name` into what a builder chart would pass. For the roles `value`,
|
|
787
|
-
* `condition` and `script` that is a function called with `this` = the
|
|
788
|
-
* data and one argument, the context; for `location` it is a data name or
|
|
789
|
-
* `{ get(context), set(value, context) }`. Throwing refuses the chart; an
|
|
790
|
-
* error with numeric `offset` and `length` points into the source. The
|
|
791
|
-
* built-in data model runs what it returns, so storage, <foreach>,
|
|
792
|
-
* <param>, <content> and wire JSON behave as for builder charts.
|
|
793
|
-
* `javascript` and `null` are napi's own names. Register before the first
|
|
794
|
-
* define() that uses it. lib/ ships no expression compiler: running
|
|
795
|
-
* expression text is the caller's choice (tools/ecmascript-datamodel.js is
|
|
796
|
-
* an example).
|
|
797
|
-
*/
|
|
798
|
-
registerDatamodel(name, { compile } = {}) {
|
|
799
|
-
if (typeof name !== 'string' || name === '') {
|
|
800
|
-
throw new TinyactorsError('registerDatamodel(): expected a data model name', 'invalid');
|
|
801
|
-
}
|
|
802
|
-
if (typeof compile !== 'function') {
|
|
803
|
-
throw new TinyactorsError('registerDatamodel(): expected { compile(source, role) }', 'invalid');
|
|
804
|
-
}
|
|
805
|
-
this.#native.registerDatamodel(name, (source, role) => normalizeCompiled(compile(source, role), role));
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
/**
|
|
809
|
-
* Compile and register a chart: a statechart() builder, or a spec in the
|
|
810
|
-
* generated shape (the shape core's definition export returns). It
|
|
811
|
-
* compiles against the JavaScript data model ("javascript", ADR 0011); a
|
|
812
|
-
* plain spec opts into core's null data model with `datamodel: "null"`.
|
|
813
|
-
*
|
|
814
|
-
* `options.microstepLimit` overrides the system's
|
|
815
|
-
* `scheduling.microstepLimit` for this definition's actors (core ADR
|
|
816
|
-
* 0075): the microsteps one macrostep may run before its actor is
|
|
817
|
-
* quarantined as a runaway; 0 for no limit.
|
|
818
|
-
*
|
|
819
|
-
* With `{ format: 'scxml' }`, `source` is an SCXML document (a string or
|
|
820
|
-
* a Uint8Array of UTF-8). Its `datamodel` attribute picks the data model:
|
|
821
|
-
* `javascript` (also for a document without one), one registerDatamodel()
|
|
822
|
-
* registered, or `null`, which a document opts into by naming it. A refusal says where in the document (ADR
|
|
823
|
-
* 0058): `detail` has `stage`, `line`, `column` and `offset`.
|
|
824
|
-
* `options.resolve(src)` fetches `<data src>` and `<script src>` while the
|
|
825
|
-
* document is defined: it returns the content as a string or a
|
|
826
|
-
* Uint8Array, or undefined for a src it does not know, which refuses the
|
|
827
|
-
* document. Without it, any `src` is refused. `options.name` is what the
|
|
828
|
-
* document is called, such as its path or a file:// URL: the source its
|
|
829
|
-
* spans name (core ADR 0085), which Definition.sourceOf() answers and a
|
|
830
|
-
* debugger opens.
|
|
831
|
-
* An `<invoke type="scxml">` whose child chart is inline in `<content>`,
|
|
832
|
-
* or a literal `src` that `resolve` fetches, is compiled now, as part of
|
|
833
|
-
* this definition (napi ADR 0024, core ADR 0077): a broken child refuses
|
|
834
|
-
* the document. The definition keeps `resolve` for children compiled at
|
|
835
|
-
* invoke time from `srcexpr`, and its children inherit it. A child
|
|
836
|
-
* fetched by `src` or `srcexpr` is named by that src; a child inline in
|
|
837
|
-
* `<content>` is unnamed, as its lines count from the start of its
|
|
838
|
-
* content, not of the document.
|
|
839
|
-
*/
|
|
840
|
-
define(source, options = {}) {
|
|
841
|
-
const limit = microstepLimitOption(options, 'define()');
|
|
842
|
-
const format = options?.format;
|
|
843
|
-
if (format !== undefined) {
|
|
844
|
-
if (format !== 'scxml') {
|
|
845
|
-
throw new TinyactorsError(`define(): unknown format ${JSON.stringify(format)}; expected "scxml"`, 'invalid');
|
|
846
|
-
}
|
|
847
|
-
const resolve = options?.resolve;
|
|
848
|
-
if (resolve !== undefined && typeof resolve !== 'function') {
|
|
849
|
-
throw new TinyactorsError('define(): resolve must be a function of src', 'invalid');
|
|
850
|
-
}
|
|
851
|
-
const name = options?.name;
|
|
852
|
-
if (name !== undefined && typeof name !== 'string') {
|
|
853
|
-
throw new TinyactorsError('define(): name must be a string, such as the document\'s path', 'invalid');
|
|
854
|
-
}
|
|
855
|
-
return this.#registered(this.#importSCXML(source, name, resolve), limit);
|
|
856
|
-
}
|
|
857
|
-
let spec = source;
|
|
858
|
-
if (source instanceof DefinitionBuilder) {
|
|
859
|
-
spec = source.build();
|
|
860
|
-
} else if (source === null || typeof source !== 'object') {
|
|
861
|
-
throw new TinyactorsError('define(): expected a statechart() builder or a spec object', 'invalid');
|
|
862
|
-
}
|
|
863
|
-
this.#native.selectDatamodel(spec.datamodel === 'null' ? 'null' : 'javascript');
|
|
864
|
-
const compiled = compile(this.#native, spec);
|
|
865
|
-
return this.#registered(core.system_register_definition(this.#native, compiled.out), limit);
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
// A registered definition's facade, with its microstep limit when one is
|
|
869
|
-
// given.
|
|
870
|
-
#registered(id, limit) {
|
|
871
|
-
if (limit !== undefined) {
|
|
872
|
-
core.definition_set_microstep_limit(this.#native, id, limit === 0 ? MICROSTEP_LIMIT_NONE : limit);
|
|
873
|
-
}
|
|
874
|
-
this.#notify('defined', id);
|
|
875
|
-
return new Definition(this, this.#native, id);
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
// Decodes, compiles and registers an SCXML document; a refusal throws with
|
|
879
|
-
// its position (core ADRs 0058 and 0076).
|
|
880
|
-
#importSCXML(source, name, resolve) {
|
|
881
|
-
let bytes = source;
|
|
882
|
-
if (typeof source === 'string') {
|
|
883
|
-
bytes = new TextEncoder().encode(source);
|
|
884
|
-
} else if (!(source instanceof Uint8Array)) {
|
|
885
|
-
throw new TinyactorsError('define(): an SCXML document is a string or a Uint8Array', 'invalid');
|
|
886
|
-
}
|
|
887
|
-
const result = this.#native.importDefinition(bytes, name, resolve);
|
|
888
|
-
if (typeof result === 'bigint') {
|
|
889
|
-
return result;
|
|
890
|
-
}
|
|
891
|
-
const where = result.line === undefined ? '' : ` at line ${result.line}, column ${result.column}`;
|
|
892
|
-
throw new TinyactorsError(`chart refused${where}: ${result.message}`, result.code, {
|
|
893
|
-
stage: result.stage,
|
|
894
|
-
message: result.message,
|
|
895
|
-
line: result.line,
|
|
896
|
-
column: result.column,
|
|
897
|
-
offset: result.offset,
|
|
898
|
-
});
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
/**
|
|
902
|
-
* The newest registered, unretired definition with this identity, or
|
|
903
|
-
* undefined.
|
|
904
|
-
*/
|
|
905
|
-
findDefinition(identity) {
|
|
906
|
-
if (identity === null || typeof identity !== 'object') {
|
|
907
|
-
throw new TinyactorsError('findDefinition(): expected { family, revision }', 'invalid');
|
|
908
|
-
}
|
|
909
|
-
try {
|
|
910
|
-
const id = core.system_find_definition(this.#native, {
|
|
911
|
-
family: { name: identity.family },
|
|
912
|
-
revision: identity.revision,
|
|
913
|
-
});
|
|
914
|
-
return new Definition(this, this.#native, id);
|
|
915
|
-
} catch (error) {
|
|
916
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
917
|
-
return undefined;
|
|
918
|
-
}
|
|
919
|
-
throw error;
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
/**
|
|
924
|
-
* Create an actor of `definition`. It is bootstrapped by a later pump turn,
|
|
925
|
-
* never inside this call (ADR 0007); `await system.flush()` to see it in its
|
|
926
|
-
* initial state.
|
|
927
|
-
*/
|
|
928
|
-
spawn(definition, options = {}) {
|
|
929
|
-
if (!(definition instanceof Definition) || definition.system !== this) {
|
|
930
|
-
throw new TinyactorsError('spawn(): expected a Definition of this system', 'invalid');
|
|
931
|
-
}
|
|
932
|
-
let address;
|
|
933
|
-
if (options.address !== undefined) {
|
|
934
|
-
address = { family: { name: options.address.family }, name: options.address.name };
|
|
935
|
-
} else if (options.name !== undefined) {
|
|
936
|
-
address = { family: { name: definition.identity.family }, name: options.name };
|
|
937
|
-
}
|
|
938
|
-
const watched = this.#watches.size !== 0 && this.#watchedFamily(definition.identity.family);
|
|
939
|
-
const trace = this.#native.spawnTrace(options.traceparent, watched);
|
|
940
|
-
const pending = options.pendingSends === undefined ? undefined : this.#pendingSends(options.pendingSends);
|
|
941
|
-
const id = core.actor_spawn(this.#native, definition.id, address, options.binding, undefined, trace, pending);
|
|
942
|
-
return new ActorID(this, id.slot, id.generation);
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
/**
|
|
946
|
-
* The resident actor the directory has at `address` ({ family, name }), or
|
|
947
|
-
* undefined (ADR 0006).
|
|
948
|
-
*/
|
|
949
|
-
findActor(address) {
|
|
950
|
-
const { family, name } = addressOf(address, 'findActor()');
|
|
951
|
-
try {
|
|
952
|
-
const id = core.actor_find(this.#native, { family: { name: family }, name });
|
|
953
|
-
return new ActorID(this, id.slot, id.generation);
|
|
954
|
-
} catch (error) {
|
|
955
|
-
if (error instanceof TinyactorsError && (error.code === 'not-found' || error.code === 'unloaded')) {
|
|
956
|
-
return undefined;
|
|
957
|
-
}
|
|
958
|
-
throw error;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
/** A snapshot of core's view of `actor` (ADR 0054: O(size of the actor)). */
|
|
963
|
-
inspect(actor) {
|
|
964
|
-
const { slot, generation } = actorOf(this, actor);
|
|
965
|
-
const view = core.actor_inspect(this.#native, slot, generation);
|
|
966
|
-
const stateName = (state) => core.definition_state(this.#native, view.definition_id, state).id;
|
|
967
|
-
const idOrNull = (id) => (id === NO_STATE ? null : id);
|
|
968
|
-
const inspection = {
|
|
969
|
-
actor: new ActorID(this, view.actor.slot, view.actor.generation),
|
|
970
|
-
sessionID: view.session_id,
|
|
971
|
-
definition: identityOf(view.definition),
|
|
972
|
-
// The definition's ID, which names its states, transitions and
|
|
973
|
-
// actions to core's lookups (core ADR 0071).
|
|
974
|
-
definitionID: view.definition_id,
|
|
975
|
-
residency: view.residency,
|
|
976
|
-
published: view.published,
|
|
977
|
-
activeStates: core.actor_active_states(this.#native, slot, generation).map(stateName),
|
|
978
|
-
macrostepInProgress: view.macrostep_in_progress,
|
|
979
|
-
microstepInProgress: view.microstep_in_progress,
|
|
980
|
-
// Where a paused macrostep stands (core ADR 0083): its step key, and
|
|
981
|
-
// the unit it runs next; outside a macrostep, (session, 0, 0) and
|
|
982
|
-
// `at: "none"`.
|
|
983
|
-
step: { session: view.step.session, macrostep: Number(view.step.macrostep), microstep: view.step.microstep },
|
|
984
|
-
position: {
|
|
985
|
-
at: view.position.at,
|
|
986
|
-
state: view.position.state === NO_STATE ? null : stateName(view.position.state),
|
|
987
|
-
transition: idOrNull(view.position.transition),
|
|
988
|
-
action: idOrNull(view.position.action),
|
|
989
|
-
iteration: view.position.iteration,
|
|
990
|
-
},
|
|
991
|
-
// The external event of the macrostep in progress, and the internal
|
|
992
|
-
// queue, as `context.event` shows events.
|
|
993
|
-
currentEvent: view.current_event === undefined ? null : this.#eventOf(view.current_event),
|
|
994
|
-
internalEvents: view.internal_events.map((queued) => this.#eventOf(queued.event)),
|
|
995
|
-
internalEventCount: view.internal_events.length,
|
|
996
|
-
invocations: view.invokes.map((invoke) => ({
|
|
997
|
-
id: invoke.id,
|
|
998
|
-
type: core.system_atom_text(this.#native, invoke.type),
|
|
999
|
-
active: invoke.active,
|
|
1000
|
-
autoforward: invoke.autoforward,
|
|
1001
|
-
serviceHandle: invoke.service_handle,
|
|
1002
|
-
})),
|
|
1003
|
-
delayedSendCount: view.delayed_sends.length,
|
|
1004
|
-
delayedSends: view.delayed_sends.map((send) => this.#delayedSend(view, send)),
|
|
1005
|
-
scheduling: this.#native.scheduling(slot, generation),
|
|
1006
|
-
// The top-level final it reached, or null (core ADR 0056).
|
|
1007
|
-
finalState: view.final_state === NO_STATE ? null : stateName(view.final_state),
|
|
1008
|
-
allocatedBytes: view.allocated_bytes,
|
|
1009
|
-
// The live data object (JavaScript data model), shared, not copied.
|
|
1010
|
-
data: this.#dataRoot(view.definition_id, slot, generation),
|
|
1011
|
-
// A finished actor's completion data (<donedata>).
|
|
1012
|
-
completion: view.has_completion && view.completion?.has_data ? view.completion.data : undefined,
|
|
1013
|
-
};
|
|
1014
|
-
return inspection;
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
// An event from core's inspection, as `context.event` shows one.
|
|
1018
|
-
#eventOf(event) {
|
|
1019
|
-
const out = { name: this.#events.name(event.name), type: event.type };
|
|
1020
|
-
if (event.send_id !== 0n) {
|
|
1021
|
-
try {
|
|
1022
|
-
out.sendID = core.send_id_format(this.#native, event.send_id);
|
|
1023
|
-
} catch (error) {
|
|
1024
|
-
if (!(error instanceof TinyactorsError && error.code === 'not-found')) throw error;
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
const origin = this.#originOf(event.origin);
|
|
1028
|
-
if (origin !== undefined) {
|
|
1029
|
-
out.origin = origin;
|
|
1030
|
-
}
|
|
1031
|
-
if (event.data !== undefined) {
|
|
1032
|
-
out.data = event.data;
|
|
1033
|
-
}
|
|
1034
|
-
return out;
|
|
1035
|
-
}
|
|
1036
|
-
|
|
1037
|
-
// An event's EventOrigin, from core's ta_origin; undefined for none.
|
|
1038
|
-
// `type` and `uri` are what the receiver sees as _event.origintype and
|
|
1039
|
-
// _event.origin; a closed scope has no URI (core ADR 0068).
|
|
1040
|
-
#originOf(origin) {
|
|
1041
|
-
let out;
|
|
1042
|
-
switch (origin?.kind) {
|
|
1043
|
-
case 'actor':
|
|
1044
|
-
out = { kind: 'actor', actor: this.#destination(origin.actor) };
|
|
1045
|
-
break;
|
|
1046
|
-
case 'invoke':
|
|
1047
|
-
out = { kind: 'invocation', invocation: origin.invoke };
|
|
1048
|
-
break;
|
|
1049
|
-
case 'io':
|
|
1050
|
-
out = origin.scope === undefined ? { kind: 'io' } : { kind: 'io', scope: origin.scope };
|
|
1051
|
-
break;
|
|
1052
|
-
default:
|
|
1053
|
-
return undefined;
|
|
1054
|
-
}
|
|
1055
|
-
out.type = origin.type ?? '';
|
|
1056
|
-
if (origin.uri !== undefined) {
|
|
1057
|
-
out.uri = origin.uri;
|
|
1058
|
-
}
|
|
1059
|
-
return out;
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
// The actor's data root, or undefined under the null data model.
|
|
1063
|
-
#dataRoot(definitionID, slot, generation) {
|
|
1064
|
-
return this.#usesJavaScript(definitionID) ? core.actor_datamodel_root(this.#native, slot, generation) : undefined;
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
// One pending delayed send of the actor `view` inspects, from core's
|
|
1068
|
-
// ta_delayed_send_info (core ADR 0054). A literal target is text in the
|
|
1069
|
-
// owner's definition, named by content ID. A destination naming the owner,
|
|
1070
|
-
// by its runtime ID or its session ID, is "self": stored and re-armed in
|
|
1071
|
-
// another session, those IDs would name another actor (core ADR 0074).
|
|
1072
|
-
#delayedSend(view, send) {
|
|
1073
|
-
const definitionID = view.definition_id;
|
|
1074
|
-
let id = null;
|
|
1075
|
-
try {
|
|
1076
|
-
id = core.send_id_format(this.#native, send.send_id);
|
|
1077
|
-
} catch (error) {
|
|
1078
|
-
if (!(error instanceof TinyactorsError && error.code === 'not-found')) {
|
|
1079
|
-
throw error;
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
return {
|
|
1083
|
-
id,
|
|
1084
|
-
due: send.due,
|
|
1085
|
-
event: this.#events.name(send.event),
|
|
1086
|
-
ioType: core.system_atom_text(this.#native, send.io_type),
|
|
1087
|
-
destination: isOwner(view, send.destination) ? 'self' : this.#destination(send.destination),
|
|
1088
|
-
target: send.has_target_text
|
|
1089
|
-
? new TextDecoder().decode(core.definition_content(this.#native, definitionID, send.target_text).bytes)
|
|
1090
|
-
: send.target,
|
|
1091
|
-
data: send.data,
|
|
1092
|
-
submitted: send.submitted,
|
|
1093
|
-
// What a re-arm needs (core ADR 0074 section 8): the literal target's
|
|
1094
|
-
// and <content>'s IDs in the definition, and the sending step's trace.
|
|
1095
|
-
targetContent: send.has_target_text ? send.target_text : null,
|
|
1096
|
-
content: send.has_content ? send.content : null,
|
|
1097
|
-
traceparent: traceparentOf(send.trace),
|
|
1098
|
-
};
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// Records core can re-arm from pendingSends, the shape inspect() returns
|
|
1102
|
-
// (core ADR 0074 section 8). Text becomes this system's IDs again.
|
|
1103
|
-
#pendingSends(sends) {
|
|
1104
|
-
if (!Array.isArray(sends)) {
|
|
1105
|
-
throw new TinyactorsError('spawn(): pendingSends must be an array of inspect().delayedSends entries', 'invalid');
|
|
1106
|
-
}
|
|
1107
|
-
return sends.map((send, index) => {
|
|
1108
|
-
if (send === null || typeof send !== 'object' || !Number.isSafeInteger(send.due) || typeof send.event !== 'string') {
|
|
1109
|
-
throw new TinyactorsError('spawn(): a pending send needs { due, event, ... } as inspect() gives it', 'invalid');
|
|
1110
|
-
}
|
|
1111
|
-
return {
|
|
1112
|
-
send_id: send.id === null || send.id === undefined ? 0 : core.send_id_parse(this.#native, send.id),
|
|
1113
|
-
due: send.due,
|
|
1114
|
-
event: this.#events.id(send.event),
|
|
1115
|
-
io_type: send.ioType ? core.system_intern_atom(this.#native, send.ioType) : 0,
|
|
1116
|
-
destination: this.#destinationRef(send.destination, index),
|
|
1117
|
-
target: send.targetContent === null || send.targetContent === undefined ? send.target : undefined,
|
|
1118
|
-
data: send.data,
|
|
1119
|
-
submitted: false,
|
|
1120
|
-
has_target_text: send.targetContent !== null && send.targetContent !== undefined,
|
|
1121
|
-
target_text: send.targetContent ?? 0,
|
|
1122
|
-
has_content: send.content !== null && send.content !== undefined,
|
|
1123
|
-
content: send.content ?? 0,
|
|
1124
|
-
trace: send.traceparent ? this.#native.spawnTrace(send.traceparent, false) : NO_TRACE,
|
|
1125
|
-
};
|
|
1126
|
-
});
|
|
1127
|
-
}
|
|
1128
|
-
|
|
1129
|
-
// A stored pending send's destination as core's actor ref (core ADR 0074
|
|
1130
|
-
// section 8). "self" and null (a custom I/O processor's send, which has
|
|
1131
|
-
// none) are runtime ID 0: core re-arms an SCXML send there to the new
|
|
1132
|
-
// session. An address is named. An unnamed other actor re-arms only as a
|
|
1133
|
-
// live ActorID of this system: a stored slot and generation would name
|
|
1134
|
-
// whichever actor holds that slot by now.
|
|
1135
|
-
#destinationRef(destination, index) {
|
|
1136
|
-
if (destination === 'self' || destination === null || destination === undefined) {
|
|
1137
|
-
return { kind: 'runtime', runtime: { slot: 0, generation: 0 } };
|
|
1138
|
-
}
|
|
1139
|
-
if (destination instanceof ActorID) {
|
|
1140
|
-
if (destination.system !== this) {
|
|
1141
|
-
throw new TinyactorsError(`spawn(): pendingSends[${index}] is a send to an unnamed actor of another system, ` +
|
|
1142
|
-
'which cannot be re-armed here', 'invalid');
|
|
1143
|
-
}
|
|
1144
|
-
return { kind: 'runtime', runtime: { slot: destination.slot, generation: destination.generation } };
|
|
1145
|
-
}
|
|
1146
|
-
if (typeof destination === 'object' && typeof destination.family === 'string' && typeof destination.name === 'string') {
|
|
1147
|
-
return { kind: 'named', named: { family: { name: destination.family }, name: destination.name } };
|
|
1148
|
-
}
|
|
1149
|
-
throw new TinyactorsError(`spawn(): pendingSends[${index}] is a send to an unnamed actor, which a stored entry ` +
|
|
1150
|
-
'cannot name again: send to an address, or to the actor itself', 'invalid');
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
// A resolved destination: an ActorID, an address, or null for a custom
|
|
1154
|
-
// I/O processor, whose destination core leaves as runtime ID 0.
|
|
1155
|
-
#destination(ref) {
|
|
1156
|
-
if (ref === undefined || ref === null) {
|
|
1157
|
-
return null;
|
|
1158
|
-
}
|
|
1159
|
-
if (ref.kind === 'named') {
|
|
1160
|
-
return ref.named === undefined ? null : { family: ref.named.family.name, name: ref.named.name };
|
|
1161
|
-
}
|
|
1162
|
-
const { slot, generation } = ref.runtime;
|
|
1163
|
-
return generation === 0 ? null : new ActorID(this, slot, generation);
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
/**
|
|
1167
|
-
* The resident actors as pages of IDs (ADR 0003): each page is a
|
|
1168
|
-
* Uint32Array of interleaved [slot, generation] pairs, with no object per
|
|
1169
|
-
* actor. Pages come from core's walk in slot order and continue from its
|
|
1170
|
-
* cursor, so a whole iteration is linear and holds one page at a time. A
|
|
1171
|
-
* page is a snapshot: an actor resident for the whole iteration appears
|
|
1172
|
-
* exactly once, one destroyed before the walk reaches it does not appear,
|
|
1173
|
-
* and one spawned meanwhile appears when its slot is ahead of the cursor
|
|
1174
|
-
* (core ADR 0062). Options: { pageSize } (default 1024, at most 65536).
|
|
1175
|
-
*/
|
|
1176
|
-
/**
|
|
1177
|
-
* Every definition the system holds, as inspections, one page of IDs at
|
|
1178
|
-
* a time (core ADR 0078): builder and imported charts, their nested inline
|
|
1179
|
-
* children, and children compiled when an <invoke> ran. Retired
|
|
1180
|
-
* definitions still in use are included (`retired` says so). A definition
|
|
1181
|
-
* freed after its page was taken, and before it was reached, is skipped.
|
|
1182
|
-
* Options: { pageSize } (default 1024, at most 65536).
|
|
1183
|
-
*/
|
|
1184
|
-
*definitions(options = {}) {
|
|
1185
|
-
const pageSize = pageSizeOf(options, 'definitions()');
|
|
1186
|
-
for (const id of this.#definitionIDs(pageSize)) {
|
|
1187
|
-
let inspection;
|
|
1188
|
-
try {
|
|
1189
|
-
inspection = new Definition(this, this.#native, id).inspect();
|
|
1190
|
-
} catch (error) {
|
|
1191
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1192
|
-
continue;
|
|
1193
|
-
}
|
|
1194
|
-
throw error;
|
|
1195
|
-
}
|
|
1196
|
-
yield inspection;
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
// The IDs of the definitions core holds, in slot order, `pageSize` at a
|
|
1201
|
-
// time; a page shorter than that is the last (core ADR 0078).
|
|
1202
|
-
*#definitionIDs(pageSize) {
|
|
1203
|
-
let from = 0;
|
|
1204
|
-
for (;;) {
|
|
1205
|
-
const ids = core.system_definitions(this.#native, from, pageSize);
|
|
1206
|
-
yield* ids;
|
|
1207
|
-
if (ids.length < pageSize) {
|
|
1208
|
-
return;
|
|
1209
|
-
}
|
|
1210
|
-
from = Number(BigInt.asUintN(32, BigInt(ids[ids.length - 1]))) + 1;
|
|
1211
|
-
}
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
*actorIDs(options = {}) {
|
|
1215
|
-
const pageSize = pageSizeOf(options, 'actorIDs()');
|
|
1216
|
-
let from = 0;
|
|
1217
|
-
while (from !== null) {
|
|
1218
|
-
const page = this.#native.idPage(from, pageSize);
|
|
1219
|
-
if (page.ids.length > 0) {
|
|
1220
|
-
yield page.ids;
|
|
1221
|
-
}
|
|
1222
|
-
from = page.next;
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
/**
|
|
1227
|
-
* The resident actors' inspections, one page of IDs at a time (ADR 0003).
|
|
1228
|
-
* Each actor is inspected when the iterator reaches it, with inspect(), so
|
|
1229
|
-
* at most one page of IDs and one inspection are held at a time. An actor
|
|
1230
|
-
* destroyed after its page was taken, and before it was reached, is
|
|
1231
|
-
* skipped. Options: { pageSize } (default 1024, at most 65536).
|
|
1232
|
-
*/
|
|
1233
|
-
*actors(options = {}) {
|
|
1234
|
-
for (const ids of this.actorIDs(options)) {
|
|
1235
|
-
for (let at = 0; at < ids.length; at += 2) {
|
|
1236
|
-
let inspection;
|
|
1237
|
-
try {
|
|
1238
|
-
inspection = this.inspect(new ActorID(this, ids[at], ids[at + 1]));
|
|
1239
|
-
} catch (error) {
|
|
1240
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1241
|
-
continue;
|
|
1242
|
-
}
|
|
1243
|
-
throw error;
|
|
1244
|
-
}
|
|
1245
|
-
yield inspection;
|
|
1246
|
-
}
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
/** True when a resident actor has this ID. */
|
|
1251
|
-
exists(actor) {
|
|
1252
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1253
|
-
try {
|
|
1254
|
-
core.actor_inspect(this.#native, slot, generation);
|
|
1255
|
-
return true;
|
|
1256
|
-
} catch (error) {
|
|
1257
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1258
|
-
return false;
|
|
1259
|
-
}
|
|
1260
|
-
throw error;
|
|
1261
|
-
}
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
/** Terminate `actor`. Throws `not-found` for an actor that is gone. */
|
|
1265
|
-
destroy(actor) {
|
|
1266
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1267
|
-
core.actor_destroy(this.#native, slot, generation);
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
/**
|
|
1271
|
-
* Queue `event` for `target` and return (ADR 0005). Nothing runs inside
|
|
1272
|
-
* this call: a later pump turn delivers it, in the order posts to that
|
|
1273
|
-
* target were accepted. Mail for an actor that is gone or finished is a
|
|
1274
|
-
* dead letter (the `deadLetter` hook), not an error. `target` is an
|
|
1275
|
-
* ActorID or an address { family, name }, resolved through the directory
|
|
1276
|
-
* when the post is accepted (ADR 0006); a name with no resident actor is a
|
|
1277
|
-
* dead letter too. `data` is any JavaScript value, shared with the
|
|
1278
|
-
* receiver, not copied (ADR 0011); it is `_event.data`
|
|
1279
|
-
* (`context.event.data`) in the receiver's expressions. Throws
|
|
1280
|
-
* `queue-full` when scheduling.maxQueuedMessages or maxRetainedBytes would
|
|
1281
|
-
* be passed: post() has no promise to report it through (ADR 0008).
|
|
1282
|
-
*/
|
|
1283
|
-
post(target, event, data, options) {
|
|
1284
|
-
if (options?.signal?.aborted) {
|
|
1285
|
-
throw new TinyactorsError('post(): the signal is already aborted', 'aborted');
|
|
1286
|
-
}
|
|
1287
|
-
this.#accept(target, event, data, options, false, 'post()');
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
/**
|
|
1291
|
-
* Queue `event` for `target` and return a promise (ADR 0005 point 11).
|
|
1292
|
-
* With `until: "completed"` (the default) it resolves with
|
|
1293
|
-
* { actor, status: "stable" | "done", completion } once the macrostep this
|
|
1294
|
-
* message starts has ended: the actor is stable again, or it finished
|
|
1295
|
-
* (`completion` is its done data). It rejects when the message becomes a
|
|
1296
|
-
* dead letter (`not-found`, `done`, `unloaded`, `invalid`), when the
|
|
1297
|
-
* macrostep faults (the fault's code; the actor is quarantined), on
|
|
1298
|
-
* `options.signal` (`aborted`), after `options.timeout` milliseconds
|
|
1299
|
-
* (`timeout`), and on close() (`closed`). Aborting or timing out withdraws
|
|
1300
|
-
* the message if it is still queued; a message the actor already took is
|
|
1301
|
-
* not undone. With `until: "accepted"` it resolves with
|
|
1302
|
-
* { actor, status: "accepted" } as soon as the message is queued.
|
|
1303
|
-
* A full queue rejects with `queue-full`; only misuse throws (ADR 0008).
|
|
1304
|
-
*/
|
|
1305
|
-
send(target, event, data, options = {}) {
|
|
1306
|
-
const until = options.until ?? 'completed';
|
|
1307
|
-
if (until !== 'completed' && until !== 'accepted') {
|
|
1308
|
-
throw new TinyactorsError('send(): options.until must be "completed" or "accepted"', 'invalid');
|
|
1309
|
-
}
|
|
1310
|
-
const timeout = options.timeout;
|
|
1311
|
-
if (timeout !== undefined && !(typeof timeout === 'number' && timeout >= 0 && Number.isFinite(timeout))) {
|
|
1312
|
-
throw new TinyactorsError('send(): options.timeout must be a non-negative number of milliseconds', 'invalid');
|
|
1313
|
-
}
|
|
1314
|
-
const signal = options.signal;
|
|
1315
|
-
if (signal?.aborted) {
|
|
1316
|
-
// Validate the call first: misuse throws even with an aborted signal.
|
|
1317
|
-
if (!(target instanceof ActorID)) addressOf(target, 'send()');
|
|
1318
|
-
else actorOf(this, target);
|
|
1319
|
-
return Promise.reject(new TinyactorsError('send(): the signal is already aborted', 'aborted'));
|
|
1320
|
-
}
|
|
1321
|
-
let promise;
|
|
1322
|
-
try {
|
|
1323
|
-
promise = this.#accept(target, event, data, options, until === 'completed', 'send()');
|
|
1324
|
-
} catch (error) {
|
|
1325
|
-
if (error instanceof TinyactorsError && (error.code === 'queue-full' || error.code === 'out-of-memory')) {
|
|
1326
|
-
return Promise.reject(error);
|
|
1327
|
-
}
|
|
1328
|
-
throw error;
|
|
1329
|
-
}
|
|
1330
|
-
if (until === 'accepted') {
|
|
1331
|
-
return Promise.resolve({ actor: target instanceof ActorID ? target : undefined, status: 'accepted' });
|
|
1332
|
-
}
|
|
1333
|
-
if (signal === undefined && timeout === undefined) {
|
|
1334
|
-
return promise;
|
|
1335
|
-
}
|
|
1336
|
-
const native = this.#native;
|
|
1337
|
-
const token = native.lastSendToken;
|
|
1338
|
-
const cancel = (code) => {
|
|
1339
|
-
try {
|
|
1340
|
-
if (!native.closed) native.cancelSend(token, code);
|
|
1341
|
-
} catch {
|
|
1342
|
-
// The system closed in the meantime; close() settled the promise.
|
|
1343
|
-
}
|
|
1344
|
-
};
|
|
1345
|
-
const onAbort = () => cancel('aborted');
|
|
1346
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1347
|
-
const timer = timeout === undefined ? undefined : setTimeout(() => cancel('timeout'), timeout);
|
|
1348
|
-
timer?.unref?.();
|
|
1349
|
-
const cleanup = () => {
|
|
1350
|
-
signal?.removeEventListener('abort', onAbort);
|
|
1351
|
-
if (timer !== undefined) clearTimeout(timer);
|
|
1352
|
-
};
|
|
1353
|
-
return promise.then(
|
|
1354
|
-
(result) => {
|
|
1355
|
-
cleanup();
|
|
1356
|
-
return result;
|
|
1357
|
-
},
|
|
1358
|
-
(error) => {
|
|
1359
|
-
cleanup();
|
|
1360
|
-
throw error;
|
|
1361
|
-
},
|
|
1362
|
-
);
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
// Accepts one message for post() or send(); returns send()'s native promise.
|
|
1366
|
-
#accept(target, event, data, options, completion, what) {
|
|
1367
|
-
const bytes = retainedBytes(data, options, what);
|
|
1368
|
-
const origin = originOf(options?.origin, what);
|
|
1369
|
-
const trace = options?.traceparent;
|
|
1370
|
-
if (!(target instanceof ActorID)) {
|
|
1371
|
-
if (options?.transition !== undefined) {
|
|
1372
|
-
throw new TinyactorsError(`${what}: options.transition needs an actor ID: it names that actor's states`, 'invalid');
|
|
1373
|
-
}
|
|
1374
|
-
if (target !== null && typeof target === 'object' && 'name' in target) {
|
|
1375
|
-
const { family, name } = addressOf(target, what);
|
|
1376
|
-
const id = this.#events.id(event);
|
|
1377
|
-
return completion
|
|
1378
|
-
? this.#native.sendNamed(family, name, id, data, bytes, origin, trace)
|
|
1379
|
-
: this.#native.postNamed(family, name, id, data, bytes, origin, trace);
|
|
1380
|
-
}
|
|
1381
|
-
throw new TinyactorsError(`${what}: expected an actor of this system or an address`, 'invalid');
|
|
1382
|
-
}
|
|
1383
|
-
const { slot, generation } = actorOf(this, target);
|
|
1384
|
-
const id = this.#events.id(event);
|
|
1385
|
-
const jump = options?.transition === undefined ? undefined : this.#jumpOf(target, options.transition, what);
|
|
1386
|
-
return completion
|
|
1387
|
-
? this.#native.send(slot, generation, id, data, bytes, origin, trace, jump)
|
|
1388
|
-
: this.#native.post(slot, generation, id, data, bytes, origin, trace, jump);
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
// An operator transition by state names, as the native post takes it: the
|
|
1392
|
-
// target's definition now and state IDs (core ADR 0082, ADR 0026).
|
|
1393
|
-
#jumpOf(actor, transition, what) {
|
|
1394
|
-
const { targets, source } = transition ?? {};
|
|
1395
|
-
if (!Array.isArray(targets) || targets.length === 0 || !targets.every((state) => typeof state === 'string') ||
|
|
1396
|
-
(source !== undefined && source !== null && typeof source !== 'string')) {
|
|
1397
|
-
throw new TinyactorsError(`${what}: options.transition must be { targets: [state, ...], source? }`, 'invalid');
|
|
1398
|
-
}
|
|
1399
|
-
const definition = core.actor_inspect(this.#native, actor.slot, actor.generation).definition_id;
|
|
1400
|
-
const state = (name) => {
|
|
1401
|
-
try {
|
|
1402
|
-
return core.definition_find_state(this.#native, definition, name);
|
|
1403
|
-
} catch (error) {
|
|
1404
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1405
|
-
throw new TinyactorsError(`${what}: "${name}" is not a state of the actor's chart`, 'invalid');
|
|
1406
|
-
}
|
|
1407
|
-
throw error;
|
|
1408
|
-
}
|
|
1409
|
-
};
|
|
1410
|
-
return {
|
|
1411
|
-
definition,
|
|
1412
|
-
source: source === undefined || source === null ? NO_STATE : state(source),
|
|
1413
|
-
targets: targets.map(state),
|
|
1414
|
-
};
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
/*
|
|
1418
|
-
* Persistence and replacement (ROADMAP step 14; core ADRs 0013, 0014,
|
|
1419
|
-
* 0043, 0051, 0052, 0066).
|
|
1420
|
-
*/
|
|
1421
|
-
|
|
1422
|
-
/**
|
|
1423
|
-
* Capture `actor` in memory: core's session image, plus the data-model
|
|
1424
|
-
* root it has now (core's image does not hold it). A macrostep in
|
|
1425
|
-
* progress is captured too; an unpublished (prepared) actor cannot be
|
|
1426
|
-
* captured (`busy`).
|
|
1427
|
-
*/
|
|
1428
|
-
capture(actor) {
|
|
1429
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1430
|
-
const view = core.actor_inspect(this.#native, slot, generation);
|
|
1431
|
-
const handle = core.actor_capture(this.#native, slot, generation);
|
|
1432
|
-
const self = this.#destination(view.self);
|
|
1433
|
-
return new SessionImage(this, handle, {
|
|
1434
|
-
actor: new ActorID(this, slot, generation),
|
|
1435
|
-
sessionID: view.session_id,
|
|
1436
|
-
definition: identityOf(view.definition),
|
|
1437
|
-
address: self instanceof ActorID || self === null ? undefined : self,
|
|
1438
|
-
data: this.#dataRoot(view.definition_id, slot, generation),
|
|
1439
|
-
});
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
/**
|
|
1443
|
-
* Evict a stable named actor from memory (core ADR 0074): it is offloaded
|
|
1444
|
-
* to bytes the system keeps, with its data (serialized with v8.serialize,
|
|
1445
|
-
* or kept by handle; see the `unloadValues` option of createSystem), its
|
|
1446
|
-
* history and its pending delayed sends. The directory keeps its address
|
|
1447
|
-
* as unloaded, and mail to the address, or its own next delayed send,
|
|
1448
|
-
* loads it back from those bytes first (napi ADR 0020), with no loader
|
|
1449
|
-
* needed; load() brings it back at once. Throws `busy` while the actor has
|
|
1450
|
-
* mail waiting, is inside a macrostep, or is quarantined, so unloading
|
|
1451
|
-
* never drops accepted mail, and `unsupported` when a value it holds can
|
|
1452
|
-
* be neither serialized nor kept. Its ActorID is stale afterwards. The
|
|
1453
|
-
* bytes are for this process only: to survive a restart, store the
|
|
1454
|
-
* actor's data and inspect().delayedSends, and spawn it again with
|
|
1455
|
-
* { binding, pendingSends }.
|
|
1456
|
-
*/
|
|
1457
|
-
unload(actor) {
|
|
1458
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1459
|
-
const scheduling = this.#native.scheduling(slot, generation);
|
|
1460
|
-
if (scheduling !== 'idle' && scheduling !== 'none') {
|
|
1461
|
-
throw new TinyactorsError(`unload(): the actor is ${scheduling}; unload it once it is idle`, 'busy');
|
|
1462
|
-
}
|
|
1463
|
-
const view = core.actor_inspect(this.#native, slot, generation);
|
|
1464
|
-
const self = this.#destination(view.self);
|
|
1465
|
-
if (self === null || self instanceof ActorID) {
|
|
1466
|
-
throw new TinyactorsError('unload(): only a named actor can be unloaded', 'invalid');
|
|
1467
|
-
}
|
|
1468
|
-
let due;
|
|
1469
|
-
for (const send of view.delayed_sends) {
|
|
1470
|
-
due = due === undefined || send.due < due ? send.due : due;
|
|
1471
|
-
}
|
|
1472
|
-
// Mail or a timer for an offloaded actor starts a load, loader or not.
|
|
1473
|
-
if (!this.#loaders.has(self.family)) {
|
|
1474
|
-
this.#offloadFamilies.add(self.family);
|
|
1475
|
-
this.#native.setLoaderFamily(self.family, DEFAULT_MAX_WAITING);
|
|
1476
|
-
}
|
|
1477
|
-
this.#native.offload(slot, generation);
|
|
1478
|
-
if (due !== undefined) {
|
|
1479
|
-
this.#native.wakeAt(self.family, self.name, due);
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
/**
|
|
1484
|
-
* Bring an unloaded named actor back (core ADRs 0051 and 0074): from the
|
|
1485
|
-
* bytes unload() kept for `target`, an address { family, name }, or from
|
|
1486
|
-
* a SessionImage. It keeps its session ID, gets a new runtime ID (core
|
|
1487
|
-
* ADR 0066), and its address is resident again. `binding`, when given,
|
|
1488
|
-
* replaces the data root outright (it is not merged): for an address,
|
|
1489
|
-
* the data the actor was unloaded with; from an image, the root the image
|
|
1490
|
-
* kept, which it defaults to. The image stays the caller's to destroy. An
|
|
1491
|
-
* invocation that was active when it was captured does not come back:
|
|
1492
|
-
* the actor gets `error.communication.invoke.<id>.unavailable` for it
|
|
1493
|
-
* (core ADR 0038).
|
|
1494
|
-
*/
|
|
1495
|
-
load(target, options = {}) {
|
|
1496
|
-
if (options === null || typeof options !== 'object') {
|
|
1497
|
-
throw new TinyactorsError('load(): expected options { binding }', 'invalid');
|
|
1498
|
-
}
|
|
1499
|
-
if (!(target instanceof SessionImage)) {
|
|
1500
|
-
const { family, name } = addressOf(target, 'load()');
|
|
1501
|
-
const id = this.#native.loadOffloaded(family, name, options.binding);
|
|
1502
|
-
return new ActorID(this, id.slot, id.generation);
|
|
1503
|
-
}
|
|
1504
|
-
const image = target;
|
|
1505
|
-
const handle = handleOf(image, this, 'load()');
|
|
1506
|
-
if (image.address !== undefined) {
|
|
1507
|
-
// The image replaces whatever unload() offloaded to its address.
|
|
1508
|
-
this.#native.dropOffloaded(image.address.family, image.address.name);
|
|
1509
|
-
}
|
|
1510
|
-
const id = core.actor_load(this.#native, handle, undefined, this.#bindingFor(image, options), undefined).out;
|
|
1511
|
-
return new ActorID(this, id.slot, id.generation);
|
|
1512
|
-
}
|
|
1513
|
-
|
|
1514
|
-
/**
|
|
1515
|
-
* Restore an image under a fresh runtime ID without touching the
|
|
1516
|
-
* directory (core ADR 0052). It keeps the session ID unless a resident
|
|
1517
|
-
* session holds it (core ADR 0066). `binding` defaults to the data root
|
|
1518
|
-
* the image kept, which is shared with the captured actor if that still
|
|
1519
|
-
* runs; pass one for an independent copy.
|
|
1520
|
-
*/
|
|
1521
|
-
reconstruct(image, options = {}) {
|
|
1522
|
-
const handle = handleOf(image, this, 'reconstruct()');
|
|
1523
|
-
const id = core.actor_reconstruct(this.#native, handle, this.#bindingFor(image, options));
|
|
1524
|
-
return new ActorID(this, id.slot, id.generation);
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
/** Release the address of an actor that stays unloaded; its image is the caller's to destroy. */
|
|
1528
|
-
removeUnloaded(address) {
|
|
1529
|
-
const { family, name } = addressOf(address, 'removeUnloaded()');
|
|
1530
|
-
this.#native.dropOffloaded(family, name);
|
|
1531
|
-
core.actor_remove_unloaded(this.#native, { family: { name: family }, name });
|
|
1532
|
-
this.#native.cancelWake(family, name);
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
/**
|
|
1536
|
-
* Bring actors of `family` back when mail arrives for them (napi ADR
|
|
1537
|
-
* 0020). Mail for a name in `family` that has no resident actor (it is
|
|
1538
|
-
* unloaded, or there has never been one here: the family is virtual)
|
|
1539
|
-
* waits while `loader(address, why, { offloaded })` runs; `why` is
|
|
1540
|
-
* "mail", or "timer" when an unloaded actor's own delayed send is due, and
|
|
1541
|
-
* `offloaded` is true when unload() kept the actor's bytes here (core ADR
|
|
1542
|
-
* 0074). The loader returns, or resolves to:
|
|
1543
|
-
* - "offloaded": the actor comes back from those bytes, and the waiting
|
|
1544
|
-
* mail is delivered first, in order. A family with no loader does this
|
|
1545
|
-
* for an offloaded actor on its own;
|
|
1546
|
-
* - a SessionImage of this system: it is loaded (as load() does), and
|
|
1547
|
-
* the waiting mail is delivered first, in order;
|
|
1548
|
-
* - { image, restore }: the image is loaded, and `await restore(actor)`
|
|
1549
|
-
* runs before the waiting mail is delivered (for replaying a log);
|
|
1550
|
-
* - { spawn: definition, binding?, pendingSends? }: a new actor of
|
|
1551
|
-
* `definition` (of this family) at the address, from data the
|
|
1552
|
-
* application stored, with the delayed sends it stored from
|
|
1553
|
-
* inspect().delayedSends re-armed (core ADR 0074 section 8); the waiting
|
|
1554
|
-
* mail is delivered first;
|
|
1555
|
-
* - "not-found": dead letters with reason `not-found`;
|
|
1556
|
-
* - "reject" or { reject: reason }: "not now", as during a shutdown: dead
|
|
1557
|
-
* letters with reason `rejected`.
|
|
1558
|
-
* A thrown error is `load-failed`; a loader that has not settled after
|
|
1559
|
-
* `timeout` ms (default 5000) is `load-timeout`, and a result that comes
|
|
1560
|
-
* later is discarded (an image in it is destroyed). One load runs per
|
|
1561
|
-
* address; at most `maxWaiting` messages (default 1000) wait, and the rest
|
|
1562
|
-
* are dead letters with reason `waiting-full`. Pass `null` as the loader
|
|
1563
|
-
* to remove it.
|
|
1564
|
-
*/
|
|
1565
|
-
setLoader(family, loader, options = {}) {
|
|
1566
|
-
if (typeof family !== 'string' || family === '') {
|
|
1567
|
-
throw new TinyactorsError('setLoader(): expected a family name', 'invalid');
|
|
1568
|
-
}
|
|
1569
|
-
if (loader === null || loader === undefined) {
|
|
1570
|
-
this.#loaders.delete(family);
|
|
1571
|
-
// Offloaded actors still load back from their bytes.
|
|
1572
|
-
this.#native.setLoaderFamily(family, this.#offloadFamilies.has(family) ? DEFAULT_MAX_WAITING : 0);
|
|
1573
|
-
return;
|
|
1574
|
-
}
|
|
1575
|
-
if (typeof loader !== 'function') {
|
|
1576
|
-
throw new TinyactorsError('setLoader(): expected a loader function or null', 'invalid');
|
|
1577
|
-
}
|
|
1578
|
-
if (options === null || typeof options !== 'object') {
|
|
1579
|
-
throw new TinyactorsError('setLoader(): expected options { timeout, maxWaiting }', 'invalid');
|
|
1580
|
-
}
|
|
1581
|
-
const { timeout = 5000, maxWaiting = 1000 } = options;
|
|
1582
|
-
for (const [what, value] of [['timeout', timeout], ['maxWaiting', maxWaiting]]) {
|
|
1583
|
-
if (!Number.isSafeInteger(value) || value < 1 || value > 0xffffffff) {
|
|
1584
|
-
throw new TinyactorsError(`setLoader(): ${what} must be a positive integer`, 'invalid');
|
|
1585
|
-
}
|
|
1586
|
-
}
|
|
1587
|
-
this.#loaders.set(family, { loader, timeout, maxWaiting });
|
|
1588
|
-
this.#native.setLoaderFamily(family, maxWaiting);
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
/**
|
|
1592
|
-
* Wake the unloaded actor at `address` ({ family, name }) at `time`
|
|
1593
|
-
* (core's clock) through its family's loader, with `why` "timer" (napi
|
|
1594
|
-
* ADR 0020). unload() does this for the image's next deadline.
|
|
1595
|
-
*/
|
|
1596
|
-
wakeAt(address, time) {
|
|
1597
|
-
const { family, name } = addressOf(address, 'wakeAt()');
|
|
1598
|
-
this.#native.wakeAt(family, name, time);
|
|
1599
|
-
}
|
|
1600
|
-
|
|
1601
|
-
// Runs one load the pump started (napi ADR 0020) and finishes it.
|
|
1602
|
-
async #runLoad({ index, generation, family, name, why }) {
|
|
1603
|
-
const key = `${family}\u0000${name}`;
|
|
1604
|
-
this.#loadDetails.delete(key);
|
|
1605
|
-
const offloaded = this.#native.hasOffloaded(family, name);
|
|
1606
|
-
const entry = this.#loaders.get(family);
|
|
1607
|
-
if (entry === undefined) {
|
|
1608
|
-
// With no loader, an actor unload() offloaded comes back from its bytes.
|
|
1609
|
-
if (offloaded) {
|
|
1610
|
-
this.#loadOffloaded({ index, generation, key, address: { family, name } });
|
|
1611
|
-
} else {
|
|
1612
|
-
this.#completeLoad(index, generation, 'not-found');
|
|
1613
|
-
}
|
|
1614
|
-
return;
|
|
1615
|
-
}
|
|
1616
|
-
const address = { family, name };
|
|
1617
|
-
let settled = false;
|
|
1618
|
-
const timer = setTimeout(() => {
|
|
1619
|
-
if (!settled) {
|
|
1620
|
-
settled = true;
|
|
1621
|
-
this.#failLoad(key, { index, generation }, 'timed-out', `the loader did not settle within ${entry.timeout} ms`);
|
|
1622
|
-
}
|
|
1623
|
-
}, entry.timeout);
|
|
1624
|
-
timer.unref?.();
|
|
1625
|
-
let result;
|
|
1626
|
-
try {
|
|
1627
|
-
result = await entry.loader(address, why, { offloaded });
|
|
1628
|
-
} catch (error) {
|
|
1629
|
-
if (!settled) {
|
|
1630
|
-
settled = true;
|
|
1631
|
-
clearTimeout(timer);
|
|
1632
|
-
this.#failLoad(key, { index, generation }, 'failed', describe(error));
|
|
1633
|
-
}
|
|
1634
|
-
return;
|
|
1635
|
-
}
|
|
1636
|
-
if (settled) {
|
|
1637
|
-
discardLoad(result); // the load timed out: nothing may use this result
|
|
1638
|
-
return;
|
|
1639
|
-
}
|
|
1640
|
-
settled = true;
|
|
1641
|
-
clearTimeout(timer);
|
|
1642
|
-
try {
|
|
1643
|
-
await this.#applyLoad({ index, generation, key, address }, result);
|
|
1644
|
-
} catch (error) {
|
|
1645
|
-
this.#failLoad(key, { index, generation }, 'failed', describe(error));
|
|
1646
|
-
}
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
// Acts on a loader's result (setLoader()).
|
|
1650
|
-
async #applyLoad(load, result) {
|
|
1651
|
-
if (this.closed) {
|
|
1652
|
-
discardLoad(result);
|
|
1653
|
-
return;
|
|
1654
|
-
}
|
|
1655
|
-
const { index, generation, key } = load;
|
|
1656
|
-
if (result === 'offloaded') {
|
|
1657
|
-
this.#loadOffloaded(load);
|
|
1658
|
-
} else if (result === 'not-found') {
|
|
1659
|
-
this.#completeLoad(index, generation, 'not-found');
|
|
1660
|
-
} else if (result === 'reject') {
|
|
1661
|
-
this.#failLoad(key, load, 'rejected', '');
|
|
1662
|
-
} else if (result !== null && typeof result === 'object' && 'reject' in result) {
|
|
1663
|
-
this.#failLoad(key, load, 'rejected', String(result.reject));
|
|
1664
|
-
} else if (result instanceof SessionImage) {
|
|
1665
|
-
this.#completeLoad(index, generation, 'loaded', this.#loadImage(result, load));
|
|
1666
|
-
} else if (result !== null && typeof result === 'object' && result.image instanceof SessionImage) {
|
|
1667
|
-
const actor = this.#loadImage(result.image, load);
|
|
1668
|
-
if (typeof result.restore === 'function') {
|
|
1669
|
-
await result.restore(actor);
|
|
1670
|
-
}
|
|
1671
|
-
if (!this.closed) {
|
|
1672
|
-
this.#completeLoad(index, generation, 'loaded', actor);
|
|
1673
|
-
}
|
|
1674
|
-
} else if (result !== null && typeof result === 'object' && result.spawn instanceof Definition) {
|
|
1675
|
-
this.#completeLoad(index, generation, 'spawned', this.#spawnAt(result, load));
|
|
1676
|
-
} else {
|
|
1677
|
-
this.#failLoad(key, load, 'failed', 'the loader returned something it cannot: expected "offloaded", ' +
|
|
1678
|
-
'a SessionImage, { image, restore }, { spawn, binding, pendingSends }, "not-found", "reject" or { reject }');
|
|
1679
|
-
}
|
|
1680
|
-
}
|
|
1681
|
-
|
|
1682
|
-
// Loads the actor unload() offloaded to the load's address (core ADR 0074).
|
|
1683
|
-
#loadOffloaded({ index, generation, key, address }) {
|
|
1684
|
-
try {
|
|
1685
|
-
const id = this.#native.loadOffloaded(address.family, address.name);
|
|
1686
|
-
this.#completeLoad(index, generation, 'loaded', new ActorID(this, id.slot, id.generation));
|
|
1687
|
-
} catch (error) {
|
|
1688
|
-
this.#failLoad(key, { index, generation }, 'failed', describe(error));
|
|
1689
|
-
}
|
|
1690
|
-
}
|
|
1691
|
-
|
|
1692
|
-
// Loads a loader's image under the trace of the mail that caused the load.
|
|
1693
|
-
#loadImage(image, { index, generation, address }) {
|
|
1694
|
-
const handle = handleOf(image, this, "setLoader(): the loader's image");
|
|
1695
|
-
if (image.address === undefined || image.address.family !== address.family ||
|
|
1696
|
-
image.address.name !== address.name) {
|
|
1697
|
-
throw new TinyactorsError(`the loader returned an image of another address than ${address.family}/${address.name}`,
|
|
1698
|
-
'invalid');
|
|
1699
|
-
}
|
|
1700
|
-
const id = core.actor_load(this.#native, handle, undefined, this.#bindingFor(image, {}),
|
|
1701
|
-
this.#native.loadTrace(index, generation)).out;
|
|
1702
|
-
// The image replaces whatever unload() offloaded to this address.
|
|
1703
|
-
this.#native.dropOffloaded(address.family, address.name);
|
|
1704
|
-
return new ActorID(this, id.slot, id.generation);
|
|
1705
|
-
}
|
|
1706
|
-
|
|
1707
|
-
// Spawns a loader's { spawn, binding, pendingSends } at the load's address.
|
|
1708
|
-
#spawnAt({ spawn: definition, binding, pendingSends }, { index, generation, address }) {
|
|
1709
|
-
if (definition.system !== this || definition.identity.family !== address.family) {
|
|
1710
|
-
throw new TinyactorsError(`{ spawn } needs a definition of family ${address.family} of this system`, 'invalid');
|
|
1711
|
-
}
|
|
1712
|
-
if (this.#unloadedAt(address)) {
|
|
1713
|
-
this.removeUnloaded(address); // the application's data replaces the image
|
|
1714
|
-
}
|
|
1715
|
-
const pending = pendingSends === undefined ? undefined : this.#pendingSends(pendingSends);
|
|
1716
|
-
const id = core.actor_spawn(this.#native, definition.id, { family: { name: address.family }, name: address.name },
|
|
1717
|
-
binding, undefined, this.#native.loadTrace(index, generation), pending);
|
|
1718
|
-
return new ActorID(this, id.slot, id.generation);
|
|
1719
|
-
}
|
|
1720
|
-
|
|
1721
|
-
// True when the directory keeps `address` as unloaded.
|
|
1722
|
-
#unloadedAt({ family, name }) {
|
|
1723
|
-
try {
|
|
1724
|
-
core.actor_find(this.#native, { family: { name: family }, name });
|
|
1725
|
-
return false;
|
|
1726
|
-
} catch (error) {
|
|
1727
|
-
if (error instanceof TinyactorsError && error.code === 'unloaded') {
|
|
1728
|
-
return true;
|
|
1729
|
-
}
|
|
1730
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1731
|
-
return false;
|
|
1732
|
-
}
|
|
1733
|
-
throw error;
|
|
1734
|
-
}
|
|
1735
|
-
}
|
|
1736
|
-
|
|
1737
|
-
#completeLoad(index, generation, outcome, actor) {
|
|
1738
|
-
if (!this.closed) {
|
|
1739
|
-
this.#native.completeLoad(index, generation, outcome, actor?.slot, actor?.generation);
|
|
1740
|
-
}
|
|
1741
|
-
}
|
|
1742
|
-
|
|
1743
|
-
#failLoad(key, { index, generation }, outcome, detail) {
|
|
1744
|
-
if (this.closed) {
|
|
1745
|
-
return;
|
|
1746
|
-
}
|
|
1747
|
-
if (detail !== '') {
|
|
1748
|
-
this.#loadDetails.set(key, detail);
|
|
1749
|
-
}
|
|
1750
|
-
this.#native.completeLoad(index, generation, outcome, undefined, undefined, detail);
|
|
1751
|
-
}
|
|
1752
|
-
|
|
1753
|
-
// A dead letter of mail that waited for a failed load carries why it failed.
|
|
1754
|
-
// One dead letter: observers first, never letting them fail the turn,
|
|
1755
|
-
// then the application's hook, whose exceptions are the application's.
|
|
1756
|
-
#deadLetter(letter, hook) {
|
|
1757
|
-
const record = this.#withLoadDetail(letter);
|
|
1758
|
-
if (this.#observers.size > 0) {
|
|
1759
|
-
try {
|
|
1760
|
-
this.#notify('deadLetter', record);
|
|
1761
|
-
} catch {
|
|
1762
|
-
// An observer's failure is its own.
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
hook?.(record);
|
|
1766
|
-
}
|
|
1767
|
-
|
|
1768
|
-
#withLoadDetail(letter) {
|
|
1769
|
-
if ((letter.reason === 'rejected' || letter.reason === 'load-failed' || letter.reason === 'load-timeout') &&
|
|
1770
|
-
!(letter.target instanceof ActorID)) {
|
|
1771
|
-
const detail = this.#loadDetails.get(`${letter.target.family}\u0000${letter.target.name}`);
|
|
1772
|
-
if (detail !== undefined) {
|
|
1773
|
-
return { ...letter, detail };
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
return letter;
|
|
1777
|
-
}
|
|
1778
|
-
|
|
1779
|
-
/**
|
|
1780
|
-
* Create a fresh, unpublished actor of `definition` to replace the named
|
|
1781
|
-
* actor `incumbent` in place (core ADR 0043; docs/design.md). It
|
|
1782
|
-
* bootstraps like a spawned actor, and core holds its visible bootstrap
|
|
1783
|
-
* effects until activate(). `binding` defaults to the incumbent's live
|
|
1784
|
-
* data root when the new definition uses the JavaScript data model.
|
|
1785
|
-
*/
|
|
1786
|
-
prepareReplacement(incumbent, definition, options = {}) {
|
|
1787
|
-
const { slot, generation } = actorOf(this, incumbent);
|
|
1788
|
-
if (!(definition instanceof Definition) || definition.system !== this) {
|
|
1789
|
-
throw new TinyactorsError('prepareReplacement(): expected a Definition of this system', 'invalid');
|
|
1790
|
-
}
|
|
1791
|
-
let binding = options.binding;
|
|
1792
|
-
if (binding === undefined && this.#usesJavaScript(definition.id)) {
|
|
1793
|
-
const view = core.actor_inspect(this.#native, slot, generation);
|
|
1794
|
-
binding = this.#dataRoot(view.definition_id, slot, generation);
|
|
1795
|
-
}
|
|
1796
|
-
const id = core.actor_prepare_replacement(this.#native, slot, generation, definition.id, binding);
|
|
1797
|
-
return new PreparedActor(this, id.slot, id.generation, incumbent);
|
|
1798
|
-
}
|
|
1799
|
-
|
|
1800
|
-
/**
|
|
1801
|
-
* Publish `prepared` at its incumbent's address, then destroy the
|
|
1802
|
-
* incumbent (docs/design.md). Mail still waiting for the incumbent moves,
|
|
1803
|
-
* in order, to the front of the replacement's mailbox, so nothing accepted
|
|
1804
|
-
* for the address is lost; the incumbent's delayed sends are discarded.
|
|
1805
|
-
* Throws `busy` while the incumbent is inside a macrostep. If activation
|
|
1806
|
-
* fails, the incumbent keeps the address and the prepared actor is left
|
|
1807
|
-
* for the caller to destroy.
|
|
1808
|
-
*/
|
|
1809
|
-
activate(prepared) {
|
|
1810
|
-
if (!(prepared instanceof PreparedActor) || prepared.system !== this) {
|
|
1811
|
-
throw new TinyactorsError('activate(): expected a prepared actor of this system', 'invalid');
|
|
1812
|
-
}
|
|
1813
|
-
const { incumbent } = prepared;
|
|
1814
|
-
if (this.#native.scheduling(incumbent.slot, incumbent.generation) === 'runnable') {
|
|
1815
|
-
throw new TinyactorsError('activate(): the incumbent is inside a macrostep; activate once it is idle', 'busy');
|
|
1816
|
-
}
|
|
1817
|
-
core.actor_activate_replacement(this.#native, incumbent.slot, incumbent.generation,
|
|
1818
|
-
prepared.slot, prepared.generation);
|
|
1819
|
-
core.actor_destroy(this.#native, incumbent.slot, incumbent.generation);
|
|
1820
|
-
return new ActorID(this, prepared.slot, prepared.generation);
|
|
1821
|
-
}
|
|
1822
|
-
|
|
1823
|
-
// The binding load() and reconstruct() pass: the option, or the image's root.
|
|
1824
|
-
#bindingFor(image, options) {
|
|
1825
|
-
if (options === null || typeof options !== 'object') {
|
|
1826
|
-
throw new TinyactorsError('expected options { binding }', 'invalid');
|
|
1827
|
-
}
|
|
1828
|
-
return options.binding !== undefined ? options.binding : image.data;
|
|
1829
|
-
}
|
|
1830
|
-
|
|
1831
|
-
// True when the definition runs the JavaScript data model, under its own
|
|
1832
|
-
// name or a registered one (ADR 0019): every data model napi offers but
|
|
1833
|
-
// core's null one is the built-in model. Cached.
|
|
1834
|
-
#usesJavaScript(definitionID) {
|
|
1835
|
-
let javascript = this.#javascript.get(definitionID);
|
|
1836
|
-
if (javascript === undefined) {
|
|
1837
|
-
javascript = core.definition_inspect(this.#native, definitionID).datamodel !== 'null';
|
|
1838
|
-
this.#javascript.set(definitionID, javascript);
|
|
1839
|
-
}
|
|
1840
|
-
return javascript;
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
/** Put an actor that faulted back into scheduling (ADR 0008). */
|
|
1844
|
-
release(actor) {
|
|
1845
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1846
|
-
this.#native.release(slot, generation);
|
|
1847
|
-
}
|
|
1848
|
-
|
|
1849
|
-
/*
|
|
1850
|
-
* Debugging and operating one actor (ADR 0026, core ADRs 0082 and 0084).
|
|
1851
|
-
*/
|
|
1852
|
-
|
|
1853
|
-
/**
|
|
1854
|
-
* The messages waiting in `actor`'s mailbox, oldest first, at most
|
|
1855
|
-
* `limit` (default 100): { event, data, awaited, scope, transition }.
|
|
1856
|
-
* `awaited` is true when a send() waits for the message; `scope` is
|
|
1857
|
-
* { index, generation } when its origin is an openScope() scope;
|
|
1858
|
-
* `transition` is { source, targets } (state IDs, source null for the
|
|
1859
|
-
* root) when it carries an operator transition. O(limit).
|
|
1860
|
-
*/
|
|
1861
|
-
mailbox(actor, options = {}) {
|
|
1862
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1863
|
-
const { limit = 100 } = options ?? {};
|
|
1864
|
-
if (!Number.isInteger(limit) || limit < 0 || limit > 4294967295) {
|
|
1865
|
-
throw new TinyactorsError('mailbox(): limit must be a non-negative integer', 'invalid');
|
|
1866
|
-
}
|
|
1867
|
-
const messages = this.#native.mailbox(slot, generation, limit);
|
|
1868
|
-
const definition = messages.some((message) => message.transition !== undefined)
|
|
1869
|
-
? core.actor_inspect(this.#native, slot, generation).definition_id
|
|
1870
|
-
: undefined;
|
|
1871
|
-
const stateName = (state) => (state === NO_STATE ? null : core.definition_state(this.#native, definition, state).id);
|
|
1872
|
-
return messages.map((message) => (message.transition === undefined ? message : {
|
|
1873
|
-
...message,
|
|
1874
|
-
transition: { source: stateName(message.transition.source), targets: message.transition.targets.map(stateName) },
|
|
1875
|
-
}));
|
|
1876
|
-
}
|
|
1877
|
-
|
|
1878
|
-
/**
|
|
1879
|
-
* Abandon `actor`'s macrostep (core ADR 0082): one that never ends, or an
|
|
1880
|
-
* event delivered and not yet taken. The actor keeps the configuration
|
|
1881
|
-
* after its last completed microstep; what the macrostep did so far stays
|
|
1882
|
-
* done. The send() that follows it rejects with `abandoned`. Throws `busy`
|
|
1883
|
-
* while it is paused inside a microstep (the pump finishes that microstep
|
|
1884
|
-
* in its next turns, and it can be abandoned between two) or has not
|
|
1885
|
-
* finished its bootstrap, `invalid` when no macrostep is in progress,
|
|
1886
|
-
* `done` and `not-found` as delivery does.
|
|
1887
|
-
*/
|
|
1888
|
-
abandon(actor) {
|
|
1889
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1890
|
-
core.actor_abandon(this.#native, slot, generation);
|
|
1891
|
-
}
|
|
1892
|
-
|
|
1893
|
-
/**
|
|
1894
|
-
* Withdraw `actor`'s pending delayed send `sendID` (core ADR 0084): the
|
|
1895
|
-
* `id` inspect() shows in `delayedSends`, such as "#_send.3" or a chart's
|
|
1896
|
-
* literal ID. Every pending send of this actor with that ID goes, as a
|
|
1897
|
-
* <cancel> of it would. Throws `not-found` when the actor has none, `done`
|
|
1898
|
-
* when its only ones were refused once and now belong to their receiver.
|
|
1899
|
-
*/
|
|
1900
|
-
withdrawSend(actor, sendID) {
|
|
1901
|
-
const { slot, generation } = actorOf(this, actor);
|
|
1902
|
-
if (typeof sendID !== 'string' || sendID === '') {
|
|
1903
|
-
throw new TinyactorsError('withdrawSend(): expected a send ID string', 'invalid');
|
|
1904
|
-
}
|
|
1905
|
-
let id;
|
|
1906
|
-
try {
|
|
1907
|
-
id = core.send_id_parse(this.#native, sendID);
|
|
1908
|
-
} catch (error) {
|
|
1909
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1910
|
-
throw new TinyactorsError(`withdrawSend(): no pending send has the ID ${sendID}`, 'not-found');
|
|
1911
|
-
}
|
|
1912
|
-
throw error;
|
|
1913
|
-
}
|
|
1914
|
-
try {
|
|
1915
|
-
core.actor_withdraw_send(this.#native, slot, generation, id);
|
|
1916
|
-
} catch (error) {
|
|
1917
|
-
if (error instanceof TinyactorsError && error.code === 'not-found') {
|
|
1918
|
-
throw new TinyactorsError(`withdrawSend(): the actor has no pending send ${sendID}`, 'not-found');
|
|
1919
|
-
}
|
|
1920
|
-
if (error instanceof TinyactorsError && error.code === 'done') {
|
|
1921
|
-
throw new TinyactorsError(`withdrawSend(): send ${sendID} was refused once and belongs to its receiver now`, 'done');
|
|
1922
|
-
}
|
|
1923
|
-
throw error;
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
|
|
1927
|
-
/**
|
|
1928
|
-
* Resolves once the system is quiet: nothing runnable, nothing ready, no
|
|
1929
|
-
* dead letters to report, and nothing due at the current time (ADR 0007
|
|
1930
|
-
* point 4). A delayed send due later does not hold it. It spans as many
|
|
1931
|
-
* pump turns as needed and yields to the event loop between them. close()
|
|
1932
|
-
* rejects it with `closed`.
|
|
1933
|
-
*/
|
|
1934
|
-
flush() {
|
|
1935
|
-
return this.#native.flush();
|
|
1936
|
-
}
|
|
1937
|
-
|
|
1938
|
-
/**
|
|
1939
|
-
* Memory counters by category and the number of allocator calls
|
|
1940
|
-
* (ADRs 0009 and 0014). Throws `closed` after close().
|
|
1941
|
-
*/
|
|
1942
|
-
stats() {
|
|
1943
|
-
return this.#native.stats();
|
|
1944
|
-
}
|
|
1945
|
-
|
|
1946
|
-
/**
|
|
1947
|
-
* A metrics snapshot as plain data (napi ADR 0017 section 7, core ADR
|
|
1948
|
-
* 0072): core's counters per definition, state occupancy, and napi's
|
|
1949
|
-
* messages and memory, as { startTime, time, system, metrics }, where
|
|
1950
|
-
* each metric is { name, unit, kind: "sum" | "gauge", points:
|
|
1951
|
-
* [{ attributes, value }] }. Read it from an OpenTelemetry observable
|
|
1952
|
-
* instrument, or encode it with metricsToOTLP(). Cheap enough to call at
|
|
1953
|
-
* every export interval: it walks definitions, not actors.
|
|
1954
|
-
*/
|
|
1955
|
-
metrics() {
|
|
1956
|
-
const native = this.#native;
|
|
1957
|
-
const definitions = [];
|
|
1958
|
-
// Every definition core holds, nested and invoke-time children included
|
|
1959
|
-
// (core ADR 0078); a freed one's counts live on in the system's totals.
|
|
1960
|
-
for (const id of this.#definitionIDs(DEFAULT_PAGE_SIZE)) {
|
|
1961
|
-
const identity = identityOf(core.definition_inspect(native, id).identity);
|
|
1962
|
-
const counters = core.definition_counters(native, id);
|
|
1963
|
-
const occupancy = [];
|
|
1964
|
-
core.definition_occupancy(native, id).forEach((actors, state) => {
|
|
1965
|
-
if (actors !== 0) {
|
|
1966
|
-
occupancy.push({ state: core.definition_state(native, id, state).id, actors });
|
|
1967
|
-
}
|
|
1968
|
-
});
|
|
1969
|
-
definitions.push({
|
|
1970
|
-
attributes: { 'tinyactors.definition.family': identity.family,
|
|
1971
|
-
'tinyactors.definition.revision': identity.revision },
|
|
1972
|
-
counters: numbers(counters),
|
|
1973
|
-
occupancy,
|
|
1974
|
-
});
|
|
1975
|
-
}
|
|
1976
|
-
const stats = native.stats();
|
|
1977
|
-
const memory = {};
|
|
1978
|
-
for (const [category, counters] of Object.entries(stats.memory)) {
|
|
1979
|
-
if (category !== 'total') {
|
|
1980
|
-
memory[category] = counters.bytesInUse;
|
|
1981
|
-
}
|
|
1982
|
-
}
|
|
1983
|
-
return buildSnapshot({
|
|
1984
|
-
startTime: this.#startTime,
|
|
1985
|
-
time: Date.now(),
|
|
1986
|
-
systemName: this.#metricsName,
|
|
1987
|
-
system: numbers(core.system_counters(native)),
|
|
1988
|
-
definitions,
|
|
1989
|
-
host: { queued: stats.messages.queued, delivered: stats.messages.delivered, memory,
|
|
1990
|
-
native: native.hostMetrics() },
|
|
1991
|
-
});
|
|
1992
|
-
}
|
|
1993
|
-
|
|
1994
|
-
/**
|
|
1995
|
-
* Destroy the native system and everything it holds. Idempotent and
|
|
1996
|
-
* authoritative: afterwards every method except close() throws `closed`.
|
|
1997
|
-
*/
|
|
1998
|
-
close() {
|
|
1999
|
-
if (!this.#native.closed) {
|
|
2000
|
-
// Services first: their signals abort and live invocations are
|
|
2001
|
-
// cancelled; what core's teardown asks of them afterwards is dropped.
|
|
2002
|
-
this.#lifetime.abort();
|
|
2003
|
-
for (const handle of [...this.#invocations.keys()]) {
|
|
2004
|
-
this.#cancelInvocation(handle, 'closed');
|
|
2005
|
-
}
|
|
2006
|
-
}
|
|
2007
|
-
this.#native.close();
|
|
2008
|
-
}
|
|
2009
|
-
|
|
2010
|
-
[Symbol.dispose]() {
|
|
2011
|
-
this.close();
|
|
2012
|
-
}
|
|
2013
|
-
}
|
|
2014
|
-
|
|
2015
|
-
/*
|
|
2016
|
-
* The retained-bytes estimate of a message's data (ADR 0005 point 9):
|
|
2017
|
-
* `options.bytes` when given; otherwise 0 for no data and for numbers,
|
|
2018
|
-
* booleans, null and the like (they ride inline, ADR 0011), 2 bytes per
|
|
2019
|
-
* UTF-16 code unit for a string, byteLength for an ArrayBuffer or a view of
|
|
2020
|
-
* one, and a flat 64 bytes for any other object. Objects are not walked:
|
|
2021
|
-
* the estimate must stay O(1), so pass `bytes` for large objects.
|
|
2022
|
-
*/
|
|
2023
|
-
const OBJECT_BYTES = 64;
|
|
2024
|
-
/*
|
|
2025
|
-
* The origin option of post() and send() (core ADR 0068): who a chart
|
|
2026
|
-
* answers with `_event.origin`. { type, uri } is one request's reply URI,
|
|
2027
|
-
* { type, scope } names a scope from openScope(), { type, token } a
|
|
2028
|
-
* computed origin rendered from the processor's origin template.
|
|
2029
|
-
*/
|
|
2030
|
-
function originOf(origin, what) {
|
|
2031
|
-
if (origin === undefined) return undefined;
|
|
2032
|
-
if (origin === null || typeof origin !== 'object' || typeof origin.type !== 'string') {
|
|
2033
|
-
throw new TinyactorsError(`${what}: options.origin must be { type, uri }, { type, scope } or { type, token }`, 'invalid');
|
|
2034
|
-
}
|
|
2035
|
-
if (origin.scope !== undefined) {
|
|
2036
|
-
return { type: origin.type, scope: { index: origin.scope.index, generation: origin.scope.generation } };
|
|
2037
|
-
}
|
|
2038
|
-
return origin;
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
|
-
function retainedBytes(data, options, what) {
|
|
2042
|
-
const hint = options?.bytes;
|
|
2043
|
-
if (hint !== undefined) {
|
|
2044
|
-
if (!(typeof hint === 'number' && hint >= 0 && Number.isFinite(hint))) {
|
|
2045
|
-
throw new TinyactorsError(`${what}: options.bytes must be a non-negative number`, 'invalid');
|
|
2046
|
-
}
|
|
2047
|
-
return Math.ceil(hint);
|
|
2048
|
-
}
|
|
2049
|
-
switch (typeof data) {
|
|
2050
|
-
case 'string':
|
|
2051
|
-
return data.length * 2;
|
|
2052
|
-
case 'object':
|
|
2053
|
-
if (data === null) return 0;
|
|
2054
|
-
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
|
|
2055
|
-
return OBJECT_BYTES;
|
|
2056
|
-
case 'function':
|
|
2057
|
-
return OBJECT_BYTES;
|
|
2058
|
-
case 'bigint':
|
|
2059
|
-
return 16;
|
|
2060
|
-
default:
|
|
2061
|
-
return 0;
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2064
|
-
|
|
2065
|
-
const DEFAULT_PAGE_SIZE = 1024;
|
|
2066
|
-
const MAX_PAGE_SIZE = 65536;
|
|
2067
|
-
|
|
2068
|
-
// The page size of actors() and actorIDs().
|
|
2069
|
-
function pageSizeOf(options, method) {
|
|
2070
|
-
if (options === null || typeof options !== 'object') {
|
|
2071
|
-
throw new TinyactorsError(`${method}: options must be an object`, 'invalid');
|
|
2072
|
-
}
|
|
2073
|
-
const { pageSize = DEFAULT_PAGE_SIZE } = options;
|
|
2074
|
-
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
|
|
2075
|
-
throw new TinyactorsError(`${method}: pageSize must be an integer from 1 to ${MAX_PAGE_SIZE}`, 'invalid');
|
|
2076
|
-
}
|
|
2077
|
-
return pageSize;
|
|
2078
|
-
}
|
|
2079
|
-
|
|
2080
|
-
// The (slot, generation) of an ActorID of `system` (ADR 0002).
|
|
2081
|
-
function actorOf(system, actor) {
|
|
2082
|
-
if (!(actor instanceof ActorID) || actor.system !== system) {
|
|
2083
|
-
throw new TinyactorsError('expected an actor of this system', 'invalid');
|
|
2084
|
-
}
|
|
2085
|
-
return actor;
|
|
2086
|
-
}
|
|
2087
|
-
|
|
2088
|
-
// How many messages wait for an offloaded actor's load with no loader
|
|
2089
|
-
// (setLoader's maxWaiting default, napi ADR 0020).
|
|
2090
|
-
const DEFAULT_MAX_WAITING = 1000;
|
|
2091
|
-
|
|
2092
|
-
// A trace parent that names no trace (core ADR 0067).
|
|
2093
|
-
const NO_TRACE = Object.freeze({
|
|
2094
|
-
context: Object.freeze({ trace_id_high: 0, trace_id_low: 0, flags: 0, detail: 0 }),
|
|
2095
|
-
cause: Object.freeze({ session: 0, macrostep: 0, microstep: 0 }),
|
|
2096
|
-
});
|
|
2097
|
-
|
|
2098
|
-
// A delayed send's trace parent as traceparent text, or null for none.
|
|
2099
|
-
function traceparentOf(trace) {
|
|
2100
|
-
if (trace === undefined || trace === null || (!trace.context?.trace_id_high && !trace.context?.trace_id_low)) {
|
|
2101
|
-
return null;
|
|
2102
|
-
}
|
|
2103
|
-
try {
|
|
2104
|
-
return core.traceparent_format(trace);
|
|
2105
|
-
} catch (error) {
|
|
2106
|
-
if (error instanceof TinyactorsError) {
|
|
2107
|
-
return null;
|
|
2108
|
-
}
|
|
2109
|
-
throw error;
|
|
2110
|
-
}
|
|
2111
|
-
}
|
|
2112
|
-
|
|
2113
|
-
// True when core's actor ref names the inspected actor: its runtime ID, or
|
|
2114
|
-
// its session ID, which a send to `#_scxml_<session>` keeps after a reload.
|
|
2115
|
-
function isOwner(view, ref) {
|
|
2116
|
-
if (ref?.kind !== 'runtime' || ref.runtime.generation === 0) {
|
|
2117
|
-
return false;
|
|
2118
|
-
}
|
|
2119
|
-
const { slot, generation } = ref.runtime;
|
|
2120
|
-
return (slot === view.actor.slot && generation === view.actor.generation) ||
|
|
2121
|
-
((BigInt(generation) << 32n) | BigInt(slot)) === BigInt(view.session_id);
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
// A named address { family, name } with non-empty text (ADR 0006).
|
|
2125
|
-
function addressOf(address, caller) {
|
|
2126
|
-
if (address === null || typeof address !== 'object' ||
|
|
2127
|
-
typeof address.family !== 'string' || address.family === '' ||
|
|
2128
|
-
typeof address.name !== 'string' || address.name === '') {
|
|
2129
|
-
throw new TinyactorsError(`${caller}: expected an address { family, name } of non-empty strings`, 'invalid');
|
|
2130
|
-
}
|
|
2131
|
-
return address;
|
|
2132
|
-
}
|
|
2133
|
-
|
|
2134
|
-
// The io or invokers option: undefined or an object of services by type.
|
|
2135
|
-
function servicesOf(value, what) {
|
|
2136
|
-
if (value === undefined) {
|
|
2137
|
-
return {};
|
|
2138
|
-
}
|
|
2139
|
-
if (value === null || typeof value !== 'object') {
|
|
2140
|
-
throw new TinyactorsError(`${what} must be an object of services by type`, 'invalid');
|
|
2141
|
-
}
|
|
2142
|
-
return value;
|
|
2143
|
-
}
|
|
2144
|
-
|
|
2145
|
-
native.setupEffects(effectHandler);
|
|
2146
|
-
|
|
2147
|
-
// A fresh unpublished actor that replaces `incumbent` once activated (step 14).
|
|
2148
|
-
class PreparedActor extends ActorID {
|
|
2149
|
-
constructor(system, slot, generation, incumbent) {
|
|
2150
|
-
super(system, slot, generation);
|
|
2151
|
-
this.incumbent = incumbent;
|
|
2152
|
-
}
|
|
2153
|
-
|
|
2154
|
-
/** False until activate() publishes it at the incumbent's address. */
|
|
2155
|
-
get published() {
|
|
2156
|
-
return this.system.inspect(this).published;
|
|
2157
|
-
}
|
|
2158
|
-
|
|
2159
|
-
/** Publish at the incumbent's address and destroy the incumbent (System.activate). */
|
|
2160
|
-
activate() {
|
|
2161
|
-
return this.system.activate(this);
|
|
2162
|
-
}
|
|
2163
|
-
}
|
|
2164
|
-
|
|
2165
|
-
function createSystem(options) {
|
|
2166
|
-
return new System(options);
|
|
2167
|
-
}
|
|
2168
|
-
|
|
2169
|
-
// The text of what a loader threw, for a log and a dead letter's `detail`.
|
|
2170
|
-
function describe(error) {
|
|
2171
|
-
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
2172
|
-
}
|
|
2173
|
-
|
|
2174
|
-
// A loader's result that came too late or cannot be used: its image goes.
|
|
2175
|
-
function discardLoad(result) {
|
|
2176
|
-
if (result instanceof SessionImage) {
|
|
2177
|
-
result.destroy();
|
|
2178
|
-
} else if (result !== null && typeof result === 'object' && result.image instanceof SessionImage) {
|
|
2179
|
-
result.image.destroy();
|
|
2180
|
-
}
|
|
2181
|
-
}
|
|
2182
|
-
|
|
2183
|
-
module.exports = { System, createSystem, nativeOf, observe, ActorID, PreparedActor, SessionImage };
|