@kylewillett/troupe 0.0.0-stage → 0.1.1

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -0
  3. package/README.md +380 -2
  4. package/dist/actor.d.ts +13 -0
  5. package/dist/actor.js +14 -0
  6. package/dist/ask.d.ts +39 -0
  7. package/dist/ask.js +135 -0
  8. package/dist/backstage/encode.d.ts +36 -0
  9. package/dist/backstage/encode.js +183 -0
  10. package/dist/backstage/index.d.ts +4 -0
  11. package/dist/backstage/index.js +4 -0
  12. package/dist/backstage/requests.d.ts +8 -0
  13. package/dist/backstage/requests.js +137 -0
  14. package/dist/backstage/source.d.ts +10 -0
  15. package/dist/backstage/source.js +143 -0
  16. package/dist/backstage/types.d.ts +135 -0
  17. package/dist/backstage/types.js +3 -0
  18. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
  19. package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
  20. package/dist/backstage-ui/index.html +13 -0
  21. package/dist/cell.d.ts +129 -0
  22. package/dist/cell.js +763 -0
  23. package/dist/checks.d.ts +9 -0
  24. package/dist/checks.js +25 -0
  25. package/dist/dispatcher.d.ts +36 -0
  26. package/dist/dispatcher.js +65 -0
  27. package/dist/errors.d.ts +37 -0
  28. package/dist/errors.js +41 -0
  29. package/dist/events.d.ts +37 -0
  30. package/dist/events.js +88 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.js +7 -0
  33. package/dist/internal.d.ts +81 -0
  34. package/dist/internal.js +36 -0
  35. package/dist/logger.d.ts +31 -0
  36. package/dist/logger.js +56 -0
  37. package/dist/names.d.ts +20 -0
  38. package/dist/names.js +50 -0
  39. package/dist/node/backstage/index.d.ts +1 -0
  40. package/dist/node/backstage/index.js +2 -0
  41. package/dist/node/backstage/server.d.ts +60 -0
  42. package/dist/node/backstage/server.js +342 -0
  43. package/dist/node/sqlite/index.d.ts +1 -0
  44. package/dist/node/sqlite/index.js +2 -0
  45. package/dist/node/sqlite/schema.d.ts +2 -0
  46. package/dist/node/sqlite/schema.js +36 -0
  47. package/dist/node/sqlite/schema.sql +32 -0
  48. package/dist/node/sqlite/sqlite.d.ts +24 -0
  49. package/dist/node/sqlite/sqlite.js +183 -0
  50. package/dist/persistence/actor.d.ts +158 -0
  51. package/dist/persistence/actor.js +454 -0
  52. package/dist/persistence/backend.d.ts +32 -0
  53. package/dist/persistence/backend.js +96 -0
  54. package/dist/persistence/errors.d.ts +60 -0
  55. package/dist/persistence/errors.js +82 -0
  56. package/dist/persistence/index.d.ts +6 -0
  57. package/dist/persistence/index.js +5 -0
  58. package/dist/persistence/json.d.ts +7 -0
  59. package/dist/persistence/json.js +75 -0
  60. package/dist/persistence/memory.d.ts +18 -0
  61. package/dist/persistence/memory.js +143 -0
  62. package/dist/persistence/postgres/index.d.ts +1 -0
  63. package/dist/persistence/postgres/index.js +3 -0
  64. package/dist/persistence/postgres/postgres.d.ts +66 -0
  65. package/dist/persistence/postgres/postgres.js +236 -0
  66. package/dist/persistence/postgres/schema.d.ts +12 -0
  67. package/dist/persistence/postgres/schema.js +57 -0
  68. package/dist/persistence/postgres/schema.sql +35 -0
  69. package/dist/persistence/projection.d.ts +48 -0
  70. package/dist/persistence/projection.js +102 -0
  71. package/dist/persistence/standard-schema.d.ts +63 -0
  72. package/dist/persistence/standard-schema.js +7 -0
  73. package/dist/persistence/types.d.ts +73 -0
  74. package/dist/persistence/types.js +3 -0
  75. package/dist/queue.d.ts +11 -0
  76. package/dist/queue.js +31 -0
  77. package/dist/scheduler.d.ts +24 -0
  78. package/dist/scheduler.js +23 -0
  79. package/dist/supervision.d.ts +91 -0
  80. package/dist/supervision.js +120 -0
  81. package/dist/system.d.ts +28 -0
  82. package/dist/system.js +216 -0
  83. package/dist/testkit/index.d.ts +4 -0
  84. package/dist/testkit/index.js +4 -0
  85. package/dist/testkit/kit.d.ts +63 -0
  86. package/dist/testkit/kit.js +93 -0
  87. package/dist/testkit/manual-scheduler.d.ts +58 -0
  88. package/dist/testkit/manual-scheduler.js +187 -0
  89. package/dist/testkit/probe.d.ts +50 -0
  90. package/dist/testkit/probe.js +124 -0
  91. package/dist/testkit/random.d.ts +11 -0
  92. package/dist/testkit/random.js +23 -0
  93. package/dist/timers.d.ts +37 -0
  94. package/dist/timers.js +110 -0
  95. package/dist/types.d.ts +364 -0
  96. package/dist/types.js +1 -0
  97. package/package.json +112 -4
package/dist/cell.js ADDED
@@ -0,0 +1,763 @@
1
+ import { ActorStoppedError, NotAChildError } from './errors.js';
2
+ import { INTERNALS, persistentHookOf, START, } from './internal.js';
3
+ import { safeLogger } from './logger.js';
4
+ import { Names } from './names.js';
5
+ import { Queue } from './queue.js';
6
+ import { decide, NO_FAILURES, } from './supervision.js';
7
+ import { TimerEnvelope, TimerTable, timersFor } from './timers.js';
8
+ /** A settled `pipeToSelf` promise in the mailbox. Its mapper runs when it's dequeued. */
9
+ class PipeEnvelope {
10
+ result;
11
+ map;
12
+ constructor(result, map) {
13
+ this.result = result;
14
+ this.map = map;
15
+ }
16
+ }
17
+ /** A mailbox item with the id of its `delivered`, wrapped only while message events are on. */
18
+ class Tracked {
19
+ id;
20
+ item;
21
+ constructor(id, item) {
22
+ this.id = id;
23
+ this.item = item;
24
+ }
25
+ }
26
+ /**
27
+ * One actor: its state, mailbox and lifecycle. The dispatcher gives it turns, and it runs one
28
+ * message at a time, holding its mailbox while an async `receive` or `onSignal` is pending
29
+ * (decision 0002).
30
+ *
31
+ * It has two queues. The system queue holds stop requests, `terminated` notices and restart
32
+ * steps, and is always read before the user queue, so a stop jumps ahead of queued messages.
33
+ *
34
+ * The user queue holds messages, plus timer and `pipeToSelf` messages in envelopes that are
35
+ * unwrapped when they're dequeued. A timer's envelope is checked against its timer's current
36
+ * generation then, so a cancelled timer's message is never received.
37
+ *
38
+ * While a subscriber wants message events (decision 0020), each message is wrapped with an id as
39
+ * it goes in, publishing `delivered`, and ends with exactly one `processed` or dead letter with
40
+ * that id. While none does, nothing is wrapped or built. The cell names itself as the sender of
41
+ * every `tell` during its turn, and around code it runs once an awaited handler settles.
42
+ *
43
+ * A definition may carry an internal start hook (`src/internal.ts`), which runs after `initial` and
44
+ * holds the mailbox until it settles. Persistent actors recover there (decision 0011).
45
+ *
46
+ * Stopping goes: cancel the timers, dead-letter the user queue, stop every child and wait for them, run `postStop`,
47
+ * then terminate, which frees the name, notifies watchers and publishes `stopped`.
48
+ *
49
+ * A failure goes to the strategy the parent chose (decision 0006). A restart makes a new
50
+ * incarnation behind the same ref (decision 0008): run `preRestart`, drop the actor's own watches,
51
+ * stop the children and wait for them and for any backoff delay, then run `initial` with a new
52
+ * `ctx`. The mailbox, the ref and the watchers carry over.
53
+ */
54
+ export class Cell {
55
+ ref;
56
+ name;
57
+ path;
58
+ parent;
59
+ names = new Names();
60
+ childCells = new Map();
61
+ watchers = new Set();
62
+ #watching = new Set();
63
+ #def;
64
+ #host;
65
+ #capacity;
66
+ #strategy;
67
+ #mailbox = new Queue();
68
+ #timers;
69
+ #system = new Queue();
70
+ #log;
71
+ #internals;
72
+ #ctx;
73
+ // Bumped when an incarnation ends, so its ctx can tell it's stale.
74
+ #incarnation = 0;
75
+ #state;
76
+ #started = false;
77
+ // True once initial has returned, so there's a state to pass to preRestart and postStop.
78
+ #hasState = false;
79
+ // When this incarnation ran initial, for the backoff reset.
80
+ #startedAt = 0;
81
+ #history = NO_FAILURES;
82
+ #restart;
83
+ // Waiting for every child to terminate, for a stop or a restart.
84
+ #awaitingChildren = false;
85
+ #phase = 'running';
86
+ #failure;
87
+ // In the dispatcher's ready queue.
88
+ #scheduled = false;
89
+ // Inside run(), so a tell to self doesn't schedule the cell a second time.
90
+ #running = false;
91
+ // Waiting for an async receive or onSignal to settle.
92
+ #busy = false;
93
+ // How many mailbox items are Tracked, so an untracked mailbox skips the instanceof check.
94
+ #tracked = 0;
95
+ constructor(name, path, def, host, opts, parent) {
96
+ this.name = name;
97
+ this.path = path;
98
+ this.#def = def;
99
+ this.#host = host;
100
+ this.#capacity = opts.capacity;
101
+ this.#strategy = opts.supervision;
102
+ this.parent = parent;
103
+ this.#log = safeLogger(host.log, { path });
104
+ this.#internals = {
105
+ publish: (body) => {
106
+ host.events.publish(body);
107
+ },
108
+ track: (promise) => {
109
+ host.trackBusy(1);
110
+ const done = () => {
111
+ host.trackBusy(-1);
112
+ };
113
+ Promise.resolve(promise).then(done, done);
114
+ },
115
+ asSender: (fn) => this.#asSender(fn),
116
+ };
117
+ this.ref = host.makeRef(path, (msg) => {
118
+ this.#enqueue(msg);
119
+ });
120
+ this.#timers = new TimerTable({
121
+ setTimer: (task, delayMs) => host.setTimer(task, delayMs),
122
+ enqueue: (envelope) => this.#enqueue(envelope),
123
+ });
124
+ this.#ctx = this.#makeContext();
125
+ }
126
+ get terminated() {
127
+ return this.#phase === 'terminated';
128
+ }
129
+ get failure() {
130
+ return this.#failure;
131
+ }
132
+ inspect() {
133
+ return {
134
+ path: this.path,
135
+ status: this.#phase === 'restarting' || this.#phase === 'stopping'
136
+ ? this.#phase
137
+ : this.#started && this.#hasState
138
+ ? 'running'
139
+ : 'starting',
140
+ depth: this.#mailbox.size,
141
+ state: this.#hasState ? this.#state : undefined,
142
+ persistent: persistentHookOf(this.#def),
143
+ };
144
+ }
145
+ /** Queues the actor's first step, which runs `initial`. */
146
+ start() {
147
+ this.#schedule();
148
+ }
149
+ requestStop() {
150
+ if (this.#stopping())
151
+ return;
152
+ this.#system.push({ type: 'stop' });
153
+ this.#scheduleIfReady();
154
+ }
155
+ notifyTerminated(target) {
156
+ if (this.#phase !== 'running' || !this.#watching.has(target))
157
+ return;
158
+ this.#system.push({ type: 'terminated', target });
159
+ this.#scheduleIfReady();
160
+ }
161
+ removeChild(child) {
162
+ this.childCells.delete(child.name);
163
+ this.names.release(child.name);
164
+ if (this.#awaitingChildren && this.childCells.size === 0) {
165
+ this.#system.push({ type: 'childrenDone' });
166
+ this.#scheduleIfReady();
167
+ }
168
+ }
169
+ run(max) {
170
+ this.#scheduled = false;
171
+ this.#running = true;
172
+ let steps = 0;
173
+ try {
174
+ while (steps < max && !this.#busy && this.#phase !== 'terminated') {
175
+ if (!this.#started) {
176
+ steps++;
177
+ this.#init();
178
+ continue;
179
+ }
180
+ const sys = this.#system.shift();
181
+ if (sys !== undefined) {
182
+ steps++;
183
+ this.#handleSystem(sys);
184
+ continue;
185
+ }
186
+ if (this.#phase !== 'running' || this.#mailbox.size === 0)
187
+ break;
188
+ // Size checked above, so shift() returns an item. M itself may include undefined.
189
+ const item = this.#mailbox.shift();
190
+ steps++;
191
+ this.#receive(item);
192
+ }
193
+ }
194
+ finally {
195
+ this.#running = false;
196
+ }
197
+ this.#scheduleIfReady();
198
+ return steps;
199
+ }
200
+ /** Runs `fn` with this actor as the sender, for code that runs outside its turn. */
201
+ #asSender(fn) {
202
+ const host = this.#host;
203
+ const outer = host.senderOverride;
204
+ host.senderOverride = this.path;
205
+ try {
206
+ return fn();
207
+ }
208
+ finally {
209
+ host.senderOverride = outer;
210
+ }
211
+ }
212
+ /** Builds the ctx for the current incarnation. It goes stale once that incarnation ends. */
213
+ #makeContext() {
214
+ const incarnation = this.#incarnation;
215
+ const current = () => this.#incarnation === incarnation;
216
+ const host = this.#host;
217
+ const ctx = {
218
+ self: this.ref,
219
+ log: this.#log,
220
+ now: () => host.now(),
221
+ spawn: (def, childName, opts) => {
222
+ if (!current() || this.#phase !== 'running') {
223
+ throw new ActorStoppedError(`${this.path}: this incarnation has stopped or restarted, so it can't spawn`);
224
+ }
225
+ return host.spawn(this, def, childName, opts);
226
+ },
227
+ stop: (ref) => {
228
+ this.#stop(ref);
229
+ },
230
+ watch: (ref) => {
231
+ if (current())
232
+ this.#watch(ref);
233
+ },
234
+ unwatch: (ref) => {
235
+ this.#unwatch(ref);
236
+ },
237
+ child: (childName) => this.childCells.get(childName)?.ref,
238
+ children: () => [...this.childCells.values()].map((c) => c.ref),
239
+ timers: timersFor(this.#timers, () => current() && this.#phase === 'running'),
240
+ pipeToSelf: (promise, map) => {
241
+ if (typeof map !== 'function') {
242
+ throw new TypeError('pipeToSelf: map must be a function');
243
+ }
244
+ this.#pipe(promise, map);
245
+ },
246
+ };
247
+ // Not enumerable, so spreading or logging a ctx doesn't show it.
248
+ Object.defineProperty(ctx, INTERNALS, { value: this.#internals });
249
+ return Object.freeze(ctx);
250
+ }
251
+ /** Unwraps one mailbox item and hands it to `receive`. */
252
+ #receive(envelope) {
253
+ let item;
254
+ let tracking;
255
+ if (this.#tracked > 0 && envelope instanceof Tracked) {
256
+ item = envelope.item;
257
+ tracking = this.#take(envelope);
258
+ }
259
+ else {
260
+ // With no Tracked items in the mailbox, this one isn't.
261
+ item = envelope;
262
+ }
263
+ let msg;
264
+ if (item instanceof TimerEnvelope) {
265
+ // A cancelled or replaced timer's message is dropped here, even if it was already queued.
266
+ if (!this.#timers.accept(item)) {
267
+ if (tracking !== undefined)
268
+ this.#processed(tracking, false, true);
269
+ return;
270
+ }
271
+ msg = item.msg;
272
+ }
273
+ else if (item instanceof PipeEnvelope) {
274
+ try {
275
+ msg = item.map(item.result);
276
+ }
277
+ catch (error) {
278
+ if (tracking !== undefined)
279
+ this.#processed(tracking, false);
280
+ this.#fail(error, { pipeToSelf: item.result.ok ? 'ok' : 'error' });
281
+ return;
282
+ }
283
+ }
284
+ else {
285
+ msg = item;
286
+ }
287
+ const handler = () => this.#def.receive(this.#state, msg, this.#ctx);
288
+ if (tracking === undefined)
289
+ this.#invoke(handler, { message: msg });
290
+ else
291
+ this.#invokeTracked(handler, { message: msg }, tracking);
292
+ }
293
+ /** Starts tracking a message as it's taken from the mailbox. */
294
+ #take(envelope) {
295
+ this.#tracked--;
296
+ return { id: envelope.id, takenAt: this.#host.now(), depth: this.#mailbox.size };
297
+ }
298
+ /** Publishes the `processed` that ends a tracked message, if anyone still wants it. */
299
+ #processed(tracking, stateChanged, skipped = false) {
300
+ const { events } = this.#host;
301
+ if (!events.messages)
302
+ return;
303
+ const body = {
304
+ type: 'processed',
305
+ path: this.path,
306
+ id: tracking.id,
307
+ durationMs: this.#host.now() - tracking.takenAt,
308
+ depth: tracking.depth,
309
+ stateChanged,
310
+ };
311
+ events.publishMessage(skipped ? { ...body, skipped: true } : body);
312
+ }
313
+ /**
314
+ * Waits for `promise` without making the cell busy, so the mailbox stays open (decision 0002),
315
+ * then queues the result for its mapper.
316
+ *
317
+ * An ask's result is queued the moment the ask settles, with no promise hop, so piping an ask
318
+ * runs entirely on the scheduler and isn't busy work for `settle` (decision 0010).
319
+ */
320
+ #pipe(promise, map) {
321
+ const host = this.#host;
322
+ // The envelope only ever passes this result to this mapper, so widening T is safe.
323
+ const widened = map;
324
+ const enqueue = (result) => {
325
+ this.#enqueue(new PipeEnvelope(result, widened));
326
+ };
327
+ if (host.onAskSettled(promise, enqueue)) {
328
+ // The result arrives through the listener. Handle the rejection here too, or a timed-out
329
+ // ask would be an unhandled rejection.
330
+ Promise.resolve(promise).then(undefined, () => { });
331
+ return;
332
+ }
333
+ host.trackBusy(1);
334
+ const deliver = (result) => {
335
+ host.trackBusy(-1);
336
+ enqueue(result);
337
+ };
338
+ Promise.resolve(promise).then((value) => {
339
+ deliver({ ok: true, value });
340
+ }, (error) => {
341
+ deliver({ ok: false, error });
342
+ });
343
+ }
344
+ #stopping() {
345
+ return this.#phase === 'stopping' || this.#phase === 'terminated';
346
+ }
347
+ /** Queues a message, or makes it a dead letter. Returns false for a dead letter. */
348
+ #enqueue(item) {
349
+ const reason = this.#host.terminating()
350
+ ? 'terminated'
351
+ : this.#stopping()
352
+ ? 'stopped'
353
+ : this.#mailbox.size >= this.#capacity
354
+ ? 'mailboxFull'
355
+ : undefined;
356
+ if (reason !== undefined) {
357
+ this.#deadLetter(item, reason, undefined);
358
+ return false;
359
+ }
360
+ // While restarting, messages queue up and wait for the new incarnation.
361
+ if (this.#host.events.messages)
362
+ this.#pushTracked(item);
363
+ else
364
+ this.#mailbox.push(item);
365
+ this.#scheduleIfReady();
366
+ return true;
367
+ }
368
+ /** Queues a message with an id, and publishes its `delivered`. */
369
+ #pushTracked(item) {
370
+ const host = this.#host;
371
+ const id = host.events.nextMessageId();
372
+ this.#mailbox.push(new Tracked(id, item));
373
+ this.#tracked++;
374
+ const sender = host.senderOverride ?? host.dispatcher.current?.path;
375
+ const body = {
376
+ type: 'delivered',
377
+ path: this.path,
378
+ id,
379
+ message: sent(item),
380
+ depth: this.#mailbox.size,
381
+ };
382
+ host.events.publishMessage(sender === undefined ? body : { ...body, from: sender });
383
+ }
384
+ #deadLetter(item, reason, id) {
385
+ const body = { type: 'deadLetter', recipient: this.path, message: sent(item), reason };
386
+ this.#host.events.publish(id === undefined ? body : { ...body, id });
387
+ }
388
+ #scheduleIfReady() {
389
+ if (this.#scheduled || this.#running || this.#busy || this.#phase === 'terminated')
390
+ return;
391
+ // The mailbox only counts while running: a restarting cell with queued messages but nothing
392
+ // else to do would otherwise be scheduled, run no steps, and be scheduled again forever.
393
+ const hasWork = !this.#started ||
394
+ this.#system.size > 0 ||
395
+ (this.#phase === 'running' && this.#mailbox.size > 0);
396
+ if (hasWork)
397
+ this.#schedule();
398
+ }
399
+ #schedule() {
400
+ this.#scheduled = true;
401
+ this.#host.dispatcher.schedule(this);
402
+ }
403
+ #init() {
404
+ this.#started = true;
405
+ this.#hasState = false;
406
+ this.#state = undefined;
407
+ this.#startedAt = this.#host.now();
408
+ const { initial } = this.#def;
409
+ let state;
410
+ try {
411
+ state =
412
+ typeof initial === 'function'
413
+ ? initial(this.#ctx)
414
+ : initial;
415
+ }
416
+ catch (error) {
417
+ this.#fail(error, {}, true);
418
+ return;
419
+ }
420
+ const start = this.#def[START];
421
+ if (start === undefined) {
422
+ this.#state = state;
423
+ this.#hasState = true;
424
+ return;
425
+ }
426
+ // A persistent actor's recovery: the mailbox is held until it settles, so no message runs
427
+ // first, and its failure is a failure in the start, like a throw in initial.
428
+ this.#state = state;
429
+ let started;
430
+ try {
431
+ started = start(state, this.#ctx);
432
+ }
433
+ catch (error) {
434
+ this.#fail(error, {}, true);
435
+ return;
436
+ }
437
+ this.#awaitBusy(started, (next) => {
438
+ this.#state = next;
439
+ this.#hasState = true;
440
+ }, (error) => {
441
+ this.#fail(error, {}, true);
442
+ });
443
+ }
444
+ #handleSystem(sys) {
445
+ switch (sys.type) {
446
+ case 'stop':
447
+ this.#beginStop(undefined);
448
+ return;
449
+ case 'childrenDone':
450
+ this.#awaitingChildren = false;
451
+ if (this.#restart === undefined) {
452
+ this.#postStop();
453
+ return;
454
+ }
455
+ this.#restart.childrenPending = false;
456
+ this.#finishRestart();
457
+ return;
458
+ case 'restartDue':
459
+ // A stop since the timer fired cancels the restart, and this with it.
460
+ if (this.#restart === undefined)
461
+ return;
462
+ this.#restart.delayPending = false;
463
+ this.#finishRestart();
464
+ return;
465
+ case 'terminated': {
466
+ // Dropped while stopping, and after unwatch, even if it was already queued.
467
+ if (this.#phase !== 'running' || !this.#watching.delete(sys.target))
468
+ return;
469
+ const onSignal = this.#def.onSignal?.bind(this.#def);
470
+ if (onSignal === undefined)
471
+ return;
472
+ const failure = sys.target.failure;
473
+ const signal = failure === undefined
474
+ ? { type: 'terminated', ref: sys.target.ref }
475
+ : { type: 'terminated', ref: sys.target.ref, failure: failure.error };
476
+ this.#invoke(() => onSignal(this.#state, signal, this.#ctx), {
477
+ signal: 'terminated',
478
+ target: sys.target.ref.path,
479
+ });
480
+ return;
481
+ }
482
+ }
483
+ }
484
+ /**
485
+ * Runs a handler that returns the next state, directly or as a promise. A promise makes the
486
+ * cell busy until it settles. A throw or rejection is a failure, for supervision.
487
+ */
488
+ #invoke(handler, context) {
489
+ let result;
490
+ try {
491
+ result = handler();
492
+ }
493
+ catch (error) {
494
+ this.#fail(error, context);
495
+ return;
496
+ }
497
+ if (!isThenable(result)) {
498
+ this.#state = result;
499
+ return;
500
+ }
501
+ this.#awaitBusy(result, (next) => {
502
+ this.#state = next;
503
+ }, (error) => {
504
+ this.#fail(error, context);
505
+ });
506
+ }
507
+ /**
508
+ * {@link Cell.#invoke} for a tracked message: its `processed` comes when the handler settles,
509
+ * before any `failed`. A copy rather than a flag, so the untracked path every message takes
510
+ * while nobody watches stays as small as it was, and V8 keeps inlining it (decision 0020).
511
+ */
512
+ #invokeTracked(handler, context, tracking) {
513
+ const before = this.#state;
514
+ let result;
515
+ try {
516
+ result = handler();
517
+ }
518
+ catch (error) {
519
+ this.#processed(tracking, false);
520
+ this.#fail(error, context);
521
+ return;
522
+ }
523
+ if (!isThenable(result)) {
524
+ this.#state = result;
525
+ this.#processed(tracking, result !== before);
526
+ return;
527
+ }
528
+ this.#awaitBusy(result, (next) => {
529
+ this.#state = next;
530
+ this.#processed(tracking, next !== before);
531
+ }, (error) => {
532
+ this.#processed(tracking, false);
533
+ this.#fail(error, context);
534
+ });
535
+ }
536
+ /**
537
+ * Holds the mailbox until `promise` settles. The callbacks run as this actor's code, so a
538
+ * `preRestart` or `postStop` they lead to has a sender, as it would inside a turn.
539
+ */
540
+ #awaitBusy(promise, ok, failed) {
541
+ this.#busy = true;
542
+ this.#host.trackBusy(1);
543
+ Promise.resolve(promise).then((value) => {
544
+ this.#busy = false;
545
+ this.#host.trackBusy(-1);
546
+ this.#asSender(() => {
547
+ ok(value);
548
+ });
549
+ this.#scheduleIfReady();
550
+ }, (error) => {
551
+ this.#busy = false;
552
+ this.#host.trackBusy(-1);
553
+ this.#asSender(() => {
554
+ failed(error);
555
+ });
556
+ this.#scheduleIfReady();
557
+ });
558
+ }
559
+ /** Hands a failure to the strategy, then publishes and logs what it decided. */
560
+ #fail(error, context, inInitial = false) {
561
+ const { decision, history } = decide(this.#strategy, this.#history, {
562
+ now: this.#host.now(),
563
+ startedAt: this.#startedAt,
564
+ inInitial,
565
+ random: () => this.#host.random(),
566
+ });
567
+ this.#history = history;
568
+ const { directive } = decision;
569
+ this.#host.events.publish({ type: 'failed', path: this.path, error, directive });
570
+ this.#log.error('actor failed', { ...context, error, directive });
571
+ switch (decision.directive) {
572
+ case 'stop':
573
+ this.#beginStop({ error });
574
+ return;
575
+ case 'resume':
576
+ return;
577
+ case 'restart':
578
+ this.#beginRestart(error, decision.attempt, decision.delayMs);
579
+ return;
580
+ }
581
+ }
582
+ #beginRestart(error, attempt, delayMs) {
583
+ this.#phase = 'restarting';
584
+ this.#incarnation++;
585
+ this.#unwatchAll();
586
+ this.#timers.cancelAll();
587
+ const restart = {
588
+ attempt,
589
+ delayMs,
590
+ childrenPending: true,
591
+ delayPending: delayMs > 0,
592
+ cancelDelay: undefined,
593
+ };
594
+ this.#restart = restart;
595
+ // The delay runs from the failure, alongside preRestart and the children stopping.
596
+ if (delayMs > 0) {
597
+ restart.cancelDelay = this.#host.setTimer(() => {
598
+ this.#system.push({ type: 'restartDue' });
599
+ this.#scheduleIfReady();
600
+ }, delayMs);
601
+ }
602
+ this.#signal({ type: 'preRestart', error }, 'restarting anyway', () => {
603
+ if (this.#stopChildren())
604
+ return;
605
+ restart.childrenPending = false;
606
+ this.#finishRestart();
607
+ });
608
+ }
609
+ /** Starts the new incarnation, once the children are gone and the delay is over. */
610
+ #finishRestart() {
611
+ const restart = this.#restart;
612
+ if (restart === undefined || restart.childrenPending || restart.delayPending)
613
+ return;
614
+ this.#restart = undefined;
615
+ this.#phase = 'running';
616
+ this.#ctx = this.#makeContext();
617
+ // The next step runs initial again, ahead of the queued messages.
618
+ this.#started = false;
619
+ this.#host.events.publish({
620
+ type: 'restarted',
621
+ path: this.path,
622
+ attempt: restart.attempt,
623
+ delayMs: restart.delayMs,
624
+ });
625
+ }
626
+ #stop(ref) {
627
+ if (ref === undefined || ref === this.ref) {
628
+ this.requestStop();
629
+ return;
630
+ }
631
+ const cell = this.#host.cellOf(ref);
632
+ if (cell?.parent !== this) {
633
+ throw new NotAChildError(`${ref.path} is not a child of ${this.path}`);
634
+ }
635
+ // A child that has already terminated: nothing to do.
636
+ cell.requestStop();
637
+ }
638
+ #watch(ref) {
639
+ const target = this.#cellOrThrow(ref, 'watch');
640
+ if (this.#phase !== 'running' || target === this || this.#watching.has(target))
641
+ return;
642
+ this.#watching.add(target);
643
+ if (target.terminated) {
644
+ this.notifyTerminated(target);
645
+ }
646
+ else {
647
+ target.watchers.add(this);
648
+ }
649
+ }
650
+ #unwatch(ref) {
651
+ const target = this.#cellOrThrow(ref, 'unwatch');
652
+ this.#watching.delete(target);
653
+ target.watchers.delete(this);
654
+ }
655
+ #unwatchAll() {
656
+ for (const target of this.#watching)
657
+ target.watchers.delete(this);
658
+ this.#watching.clear();
659
+ }
660
+ #cellOrThrow(ref, what) {
661
+ const cell = this.#host.cellOf(ref);
662
+ if (cell === undefined) {
663
+ throw new TypeError(`${what}: the ref is not an actor of this system`);
664
+ }
665
+ return cell;
666
+ }
667
+ #beginStop(failure) {
668
+ if (this.#stopping())
669
+ return;
670
+ // A stop during a restart cancels it. postStop then runs with the last state.
671
+ this.#restart?.cancelDelay?.();
672
+ this.#restart = undefined;
673
+ this.#phase = 'stopping';
674
+ this.#failure = failure;
675
+ this.#timers.cancelAll();
676
+ while (this.#mailbox.size > 0) {
677
+ const envelope = this.#mailbox.shift();
678
+ const tracked = this.#tracked > 0 && envelope instanceof Tracked;
679
+ if (tracked)
680
+ this.#tracked--;
681
+ const item = tracked ? envelope.item : envelope;
682
+ if (!(item instanceof TimerEnvelope)) {
683
+ this.#deadLetter(item, 'stopped', tracked ? envelope.id : undefined);
684
+ }
685
+ else if (tracked) {
686
+ // Its timer was cancelled just above, so its message is never received, not even as a
687
+ // dead letter. A tracked one still owes its `processed`.
688
+ const now = this.#host.now();
689
+ this.#processed({ id: envelope.id, takenAt: now, depth: this.#mailbox.size }, false, true);
690
+ }
691
+ }
692
+ // A restart may already be waiting for the children, and childrenDone will still come.
693
+ if (this.#awaitingChildren || this.#stopChildren())
694
+ return;
695
+ this.#postStop();
696
+ }
697
+ /** Asks every child to stop. Returns false when there are none, so there's nothing to wait for. */
698
+ #stopChildren() {
699
+ if (this.childCells.size === 0)
700
+ return false;
701
+ this.#awaitingChildren = true;
702
+ for (const child of [...this.childCells.values()])
703
+ child.requestStop();
704
+ return true;
705
+ }
706
+ #postStop() {
707
+ this.#signal({ type: 'postStop' }, 'stopping anyway', () => {
708
+ this.#terminate();
709
+ });
710
+ }
711
+ /**
712
+ * Runs `preRestart` or `postStop`, awaiting it if it's async, then `next`. These can't fail the
713
+ * actor: a throw or rejection is logged, and `next` runs anyway. Skipped when there's no state.
714
+ */
715
+ #signal(signal, anyway, next) {
716
+ const onSignal = this.#def.onSignal?.bind(this.#def);
717
+ if (onSignal === undefined || !this.#hasState) {
718
+ next();
719
+ return;
720
+ }
721
+ let result;
722
+ try {
723
+ result = onSignal(this.#state, signal, this.#ctx);
724
+ }
725
+ catch (error) {
726
+ this.#log.error(`${signal.type} threw; ${anyway}`, { error });
727
+ next();
728
+ return;
729
+ }
730
+ if (!isThenable(result)) {
731
+ next();
732
+ return;
733
+ }
734
+ this.#awaitBusy(result, next, (error) => {
735
+ this.#log.error(`${signal.type} rejected; ${anyway}`, { error });
736
+ next();
737
+ });
738
+ }
739
+ #terminate() {
740
+ this.#phase = 'terminated';
741
+ this.#unwatchAll();
742
+ this.parent.removeChild(this);
743
+ for (const watcher of this.watchers)
744
+ watcher.notifyTerminated(this);
745
+ this.watchers.clear();
746
+ this.#host.events.publish(this.#failure === undefined
747
+ ? { type: 'stopped', path: this.path }
748
+ : { type: 'stopped', path: this.path, failure: this.#failure.error });
749
+ }
750
+ }
751
+ /** What was sent, never the cell's wrapper: a pipe's raw `Result`, a timer's message. */
752
+ function sent(item) {
753
+ return item instanceof PipeEnvelope
754
+ ? item.result
755
+ : item instanceof TimerEnvelope
756
+ ? item.msg
757
+ : item;
758
+ }
759
+ function isThenable(value) {
760
+ return (typeof value === 'object' &&
761
+ value !== null &&
762
+ typeof value.then === 'function');
763
+ }