@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
@@ -0,0 +1,187 @@
1
+ const OPTION_KEYS = new Set(['startTime', 'maxSteps']);
2
+ /**
3
+ * A scheduler on virtual time, for tests and simulation (decision 0003). Nothing runs on its
4
+ * own: queued tasks and due timers run only when you call {@link ManualScheduler.runReady} or
5
+ * {@link ManualScheduler.advanceTo}, and time moves only through `advanceTo`.
6
+ *
7
+ * Queued tasks always run before timers, and timers run in order of due time, then of creation.
8
+ * An error thrown by a task comes out of the call that ran it. The task has already left the
9
+ * queue, so the scheduler stays usable.
10
+ */
11
+ export class ManualScheduler {
12
+ #now;
13
+ #maxSteps;
14
+ #tasks = [];
15
+ #taskHead = 0;
16
+ #heap = [];
17
+ #seq = 0;
18
+ #live = 0;
19
+ constructor(opts = {}) {
20
+ for (const key of Object.keys(opts)) {
21
+ if (!OPTION_KEYS.has(key))
22
+ throw new TypeError(`ManualScheduler: unknown option "${key}"`);
23
+ }
24
+ const { startTime = 0, maxSteps = 100_000 } = opts;
25
+ if (!Number.isFinite(startTime)) {
26
+ throw new TypeError(`ManualScheduler: startTime must be a finite number, got ${String(startTime)}`);
27
+ }
28
+ if (!Number.isSafeInteger(maxSteps) || maxSteps < 1) {
29
+ throw new TypeError(`ManualScheduler: maxSteps must be a positive integer, got ${String(maxSteps)}`);
30
+ }
31
+ this.#now = startTime;
32
+ this.#maxSteps = maxSteps;
33
+ }
34
+ /** The current virtual time, in ms. While a timer runs, this is its due time. */
35
+ now() {
36
+ return this.#now;
37
+ }
38
+ /** Queues `task`. It runs at the next {@link ManualScheduler.runReady} or `advanceTo`. */
39
+ runSoon(task) {
40
+ this.#tasks.push(task);
41
+ }
42
+ /**
43
+ * Schedules `task` at `now() + delayMs` of virtual time. A negative or `NaN` delay counts as 0,
44
+ * as `setTimeout` treats it.
45
+ * @returns A function that cancels the timer. It stops a timer that's already due as long as it
46
+ * hasn't run yet.
47
+ */
48
+ setTimer(task, delayMs) {
49
+ const delay = Number.isNaN(delayMs) ? 0 : Math.max(0, delayMs);
50
+ const timer = { due: this.#now + delay, seq: this.#seq++, task, cancelled: false };
51
+ this.#push(timer);
52
+ this.#live++;
53
+ return () => {
54
+ if (timer.cancelled)
55
+ return;
56
+ timer.cancelled = true;
57
+ this.#live--;
58
+ };
59
+ }
60
+ /**
61
+ * Runs queued tasks and due timers, without moving time, until none are left. Tasks go first,
62
+ * so the tasks a timer queues run before the next timer.
63
+ * @returns How many tasks and timers ran.
64
+ * @throws RangeError after `maxSteps` in one call, which means something re-queues itself
65
+ * without end.
66
+ */
67
+ runReady() {
68
+ let ran = 0;
69
+ for (;;) {
70
+ const task = this.#takeTask();
71
+ if (task !== undefined) {
72
+ ran = this.#step(ran);
73
+ task();
74
+ continue;
75
+ }
76
+ const timer = this.#peekLive();
77
+ if (timer === undefined || timer.due > this.#now)
78
+ return ran;
79
+ this.#pop();
80
+ timer.cancelled = true;
81
+ this.#live--;
82
+ ran = this.#step(ran);
83
+ timer.task();
84
+ }
85
+ }
86
+ /**
87
+ * Moves virtual time forward to `time`, running everything that falls due on the way. Before
88
+ * each timer runs, `now()` is set to its due time. Timers scheduled along the way also run if
89
+ * they fall due by `time`. Ends with `now() === time`.
90
+ * @throws RangeError if `time` is earlier than `now()`, because virtual time never goes back.
91
+ */
92
+ advanceTo(time) {
93
+ if (Number.isNaN(time) || time < this.#now) {
94
+ throw new RangeError(`ManualScheduler: can't move time back from ${String(this.#now)} to ${String(time)}`);
95
+ }
96
+ for (;;) {
97
+ this.runReady();
98
+ const next = this.#peekLive();
99
+ if (next === undefined || next.due > time)
100
+ break;
101
+ this.#now = next.due;
102
+ }
103
+ this.#now = time;
104
+ }
105
+ /**
106
+ * The due time of the earliest timer that hasn't run or been cancelled, or `undefined` when none
107
+ * is scheduled. It can be earlier than `now()` for a timer that's due but hasn't run yet.
108
+ */
109
+ nextTimerAt() {
110
+ return this.#peekLive()?.due;
111
+ }
112
+ /** How many timers are scheduled and not yet run or cancelled. */
113
+ pendingTimers() {
114
+ return this.#live;
115
+ }
116
+ // Counts one more step of a runReady call, and stops a call that will never finish.
117
+ #step(ran) {
118
+ if (ran >= this.#maxSteps) {
119
+ throw new RangeError(`ManualScheduler: more than ${String(this.#maxSteps)} tasks and timers ran at time ` +
120
+ `${String(this.#now)}; something is re-queuing itself without end`);
121
+ }
122
+ return ran + 1;
123
+ }
124
+ #takeTask() {
125
+ if (this.#taskHead === this.#tasks.length)
126
+ return undefined;
127
+ const task = this.#tasks[this.#taskHead];
128
+ this.#taskHead++;
129
+ // Reclaim the consumed prefix once it dominates the array, so the queue can't grow forever.
130
+ if (this.#taskHead > 1024 && this.#taskHead * 2 > this.#tasks.length) {
131
+ this.#tasks.splice(0, this.#taskHead);
132
+ this.#taskHead = 0;
133
+ }
134
+ return task;
135
+ }
136
+ // The earliest timer that's still live, dropping cancelled ones from the top of the heap.
137
+ #peekLive() {
138
+ for (;;) {
139
+ const top = this.#heap[0];
140
+ if (top === undefined || !top.cancelled)
141
+ return top;
142
+ this.#pop();
143
+ }
144
+ }
145
+ #push(timer) {
146
+ const heap = this.#heap;
147
+ heap.push(timer);
148
+ let i = heap.length - 1;
149
+ while (i > 0) {
150
+ const parent = (i - 1) >> 1;
151
+ if (!earlier(timer, at(heap, parent)))
152
+ break;
153
+ heap[i] = at(heap, parent);
154
+ i = parent;
155
+ }
156
+ heap[i] = timer;
157
+ }
158
+ #pop() {
159
+ const heap = this.#heap;
160
+ const last = heap.pop();
161
+ if (last === undefined || heap.length === 0)
162
+ return;
163
+ let i = 0;
164
+ for (;;) {
165
+ const left = 2 * i + 1;
166
+ if (left >= heap.length)
167
+ break;
168
+ const right = left + 1;
169
+ const child = right < heap.length && earlier(at(heap, right), at(heap, left)) ? right : left;
170
+ if (!earlier(at(heap, child), last))
171
+ break;
172
+ heap[i] = at(heap, child);
173
+ i = child;
174
+ }
175
+ heap[i] = last;
176
+ }
177
+ }
178
+ function earlier(a, b) {
179
+ return a.due < b.due || (a.due === b.due && a.seq < b.seq);
180
+ }
181
+ function at(heap, i) {
182
+ const timer = heap[i];
183
+ // Callers only pass indexes below heap.length.
184
+ if (timer === undefined)
185
+ throw new Error(`ManualScheduler: heap index ${String(i)} out of range`);
186
+ return timer;
187
+ }
@@ -0,0 +1,50 @@
1
+ import type { Watcher } from '../cell.js';
2
+ import type { ActorRef, AnyRef } from '../types.js';
3
+ /** What a probe needs from its system. */
4
+ export interface ProbeHost {
5
+ /** The system's ref factory, which gives the probe's ref its `ask`. */
6
+ makeRef<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
7
+ /** Watches `ref` on the probe's behalf, as `ctx.watch` does. */
8
+ watch(ref: AnyRef, watcher: Watcher): void;
9
+ }
10
+ /**
11
+ * A ref that records what it's sent, for assertions. Its assertions are synchronous, because the
12
+ * test controls time: `await kit.settle()` (or `advance`), then assert.
13
+ *
14
+ * Exported as a type only: create probes with `kit.probe()`.
15
+ */
16
+ export declare class TestProbe<M> {
17
+ #private;
18
+ /** Send this to the actor under test, as a `replyTo` or a subscriber. */
19
+ readonly ref: ActorRef<M>;
20
+ /** @internal Create probes with `kit.probe()`. */
21
+ constructor(path: string, name: string, host: ProbeHost);
22
+ /**
23
+ * Takes the next message and checks it.
24
+ * @param match Optional. A value it must deeply equal, or a predicate it must pass.
25
+ * @returns The message.
26
+ * @throws Error naming the probe and what it got, if no message is queued or it doesn't match.
27
+ */
28
+ expectMessage(match?: M | ((msg: M) => boolean)): M;
29
+ /**
30
+ * Checks that no message is queued.
31
+ * @throws Error naming the probe and the first message waiting.
32
+ */
33
+ expectNoMessage(): void;
34
+ /** Takes every queued message, oldest first. */
35
+ messages(): M[];
36
+ /**
37
+ * Watches an actor, for {@link TestProbe.expectTerminated}. Watching twice is the same as once,
38
+ * and watching an actor that has already terminated records its termination at once.
39
+ * @throws TypeError if `ref` isn't an actor of this system.
40
+ */
41
+ watch(ref: AnyRef): void;
42
+ /**
43
+ * Checks that a watched actor has terminated, and takes its notice, so the probe stops watching
44
+ * it.
45
+ * @throws Error naming the probe and the actor, if it hasn't terminated or isn't watched.
46
+ */
47
+ expectTerminated(ref: AnyRef): void;
48
+ }
49
+ /** Structural equality for plain data: primitives by `Object.is`, arrays and objects by content. */
50
+ export declare function deepEqual(a: unknown, b: unknown): boolean;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * A ref that records what it's sent, for assertions. Its assertions are synchronous, because the
3
+ * test controls time: `await kit.settle()` (or `advance`), then assert.
4
+ *
5
+ * Exported as a type only: create probes with `kit.probe()`.
6
+ */
7
+ export class TestProbe {
8
+ /** Send this to the actor under test, as a `replyTo` or a subscriber. */
9
+ ref;
10
+ #name;
11
+ #received = [];
12
+ #host;
13
+ // Refs being watched whose terminated notice hasn't arrived, and notices not yet expected.
14
+ #watching = new Set();
15
+ #terminated = new Set();
16
+ #watcher = {
17
+ notifyTerminated: (target) => {
18
+ if (this.#watching.delete(target.ref))
19
+ this.#terminated.add(target.ref);
20
+ },
21
+ };
22
+ /** @internal Create probes with `kit.probe()`. */
23
+ constructor(path, name, host) {
24
+ this.#name = name;
25
+ this.#host = host;
26
+ this.ref = host.makeRef(path, (msg) => {
27
+ this.#received.push(msg);
28
+ });
29
+ }
30
+ /**
31
+ * Takes the next message and checks it.
32
+ * @param match Optional. A value it must deeply equal, or a predicate it must pass.
33
+ * @returns The message.
34
+ * @throws Error naming the probe and what it got, if no message is queued or it doesn't match.
35
+ */
36
+ expectMessage(match) {
37
+ if (this.#received.length === 0) {
38
+ throw new Error(`${this.#name}: expected a message, but none arrived`);
39
+ }
40
+ const msg = this.#received.shift();
41
+ if (match === undefined)
42
+ return msg;
43
+ if (typeof match === 'function') {
44
+ if (!match(msg)) {
45
+ throw new Error(`${this.#name}: got ${show(msg)}, which doesn't match the predicate`);
46
+ }
47
+ }
48
+ else if (!deepEqual(msg, match)) {
49
+ throw new Error(`${this.#name}: expected ${show(match)}, got ${show(msg)}`);
50
+ }
51
+ return msg;
52
+ }
53
+ /**
54
+ * Checks that no message is queued.
55
+ * @throws Error naming the probe and the first message waiting.
56
+ */
57
+ expectNoMessage() {
58
+ if (this.#received.length > 0) {
59
+ const extra = this.#received.length > 1 ? ` and ${String(this.#received.length - 1)} more` : '';
60
+ throw new Error(`${this.#name}: expected no message, got ${show(this.#received[0])}${extra}`);
61
+ }
62
+ }
63
+ /** Takes every queued message, oldest first. */
64
+ messages() {
65
+ return this.#received.splice(0);
66
+ }
67
+ /**
68
+ * Watches an actor, for {@link TestProbe.expectTerminated}. Watching twice is the same as once,
69
+ * and watching an actor that has already terminated records its termination at once.
70
+ * @throws TypeError if `ref` isn't an actor of this system.
71
+ */
72
+ watch(ref) {
73
+ if (this.#watching.has(ref) || this.#terminated.has(ref))
74
+ return;
75
+ // Added first, because an actor that has already terminated is reported during the call.
76
+ this.#watching.add(ref);
77
+ try {
78
+ this.#host.watch(ref, this.#watcher);
79
+ }
80
+ catch (error) {
81
+ this.#watching.delete(ref);
82
+ throw error;
83
+ }
84
+ }
85
+ /**
86
+ * Checks that a watched actor has terminated, and takes its notice, so the probe stops watching
87
+ * it.
88
+ * @throws Error naming the probe and the actor, if it hasn't terminated or isn't watched.
89
+ */
90
+ expectTerminated(ref) {
91
+ if (this.#terminated.delete(ref))
92
+ return;
93
+ const why = this.#watching.has(ref) ? "it hasn't" : "the probe isn't watching it";
94
+ throw new Error(`${this.#name}: expected ${ref.path} to terminate, but ${why}`);
95
+ }
96
+ }
97
+ /** Structural equality for plain data: primitives by `Object.is`, arrays and objects by content. */
98
+ export function deepEqual(a, b) {
99
+ if (Object.is(a, b))
100
+ return true;
101
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
102
+ return false;
103
+ if (Array.isArray(a) !== Array.isArray(b))
104
+ return false;
105
+ if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
106
+ return false;
107
+ const keysA = Object.keys(a);
108
+ const keysB = Object.keys(b);
109
+ if (keysA.length !== keysB.length)
110
+ return false;
111
+ const recA = a;
112
+ const recB = b;
113
+ return keysA.every((key) => Object.hasOwn(recB, key) && deepEqual(recA[key], recB[key]));
114
+ }
115
+ function show(value) {
116
+ try {
117
+ // Typed as string, but JSON.stringify returns undefined for undefined and symbols.
118
+ const json = JSON.stringify(value, (_key, v) => typeof v === 'function' ? '[function]' : typeof v === 'bigint' ? `${v.toString()}n` : v);
119
+ return json ?? String(value);
120
+ }
121
+ catch {
122
+ return String(value);
123
+ }
124
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A seeded pseudo-random source in `[0, 1)`, for the system's `random` option. The same seed
3
+ * always gives the same sequence, so a test that uses one is repeatable (decision 0003).
4
+ *
5
+ * It uses mulberry32: fast, small, with a 32-bit state. It's good enough for jitter and
6
+ * simulation, and not for anything cryptographic.
7
+ *
8
+ * @param seed Any safe integer. Only its low 32 bits are used.
9
+ * @throws TypeError if `seed` isn't a safe integer.
10
+ */
11
+ export declare function seededRandom(seed: number): () => number;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A seeded pseudo-random source in `[0, 1)`, for the system's `random` option. The same seed
3
+ * always gives the same sequence, so a test that uses one is repeatable (decision 0003).
4
+ *
5
+ * It uses mulberry32: fast, small, with a 32-bit state. It's good enough for jitter and
6
+ * simulation, and not for anything cryptographic.
7
+ *
8
+ * @param seed Any safe integer. Only its low 32 bits are used.
9
+ * @throws TypeError if `seed` isn't a safe integer.
10
+ */
11
+ export function seededRandom(seed) {
12
+ if (!Number.isSafeInteger(seed)) {
13
+ throw new TypeError(`seededRandom: seed must be a safe integer, got ${String(seed)}`);
14
+ }
15
+ let state = seed >>> 0;
16
+ return () => {
17
+ state = (state + 0x6d2b79f5) >>> 0;
18
+ let t = state;
19
+ t = Math.imul(t ^ (t >>> 15), t | 1);
20
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
21
+ return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
22
+ };
23
+ }
@@ -0,0 +1,37 @@
1
+ import type { Timers } from './types.js';
2
+ /**
3
+ * A timer's message in the mailbox. It carries its timer's generation, which is checked when it's
4
+ * dequeued, so a cancelled or replaced timer's message is never received, even if it was already
5
+ * queued.
6
+ */
7
+ export declare class TimerEnvelope<M> {
8
+ readonly key: string;
9
+ readonly generation: number;
10
+ readonly msg: M;
11
+ constructor(key: string, generation: number, msg: M);
12
+ }
13
+ /** What a {@link TimerTable} needs from its cell. */
14
+ export interface TimerHost<M> {
15
+ setTimer(task: () => void, delayMs: number): () => void;
16
+ /** Queues a fired timer's message. Returns false if it became a dead letter instead. */
17
+ enqueue(envelope: TimerEnvelope<M>): boolean;
18
+ }
19
+ /** One cell's keyed timers. The cell cancels them all on stop and on restart. */
20
+ export declare class TimerTable<M> {
21
+ #private;
22
+ constructor(host: TimerHost<M>);
23
+ start(key: string, msg: M, delayMs: number, periodic: boolean): void;
24
+ cancel(key: string): void;
25
+ cancelAll(): void;
26
+ isActive(key: string): boolean;
27
+ /**
28
+ * Called when an envelope is dequeued. Returns true if its timer is still current, so its
29
+ * message should be received. A single timer is done once its message has been received.
30
+ */
31
+ accept(envelope: TimerEnvelope<M>): boolean;
32
+ }
33
+ /**
34
+ * The `ctx.timers` of one incarnation. Arguments are checked first, so a bad one always throws.
35
+ * Once `live()` is false, every method does nothing.
36
+ */
37
+ export declare function timersFor<M>(table: TimerTable<M>, live: () => boolean): Timers<M>;
package/dist/timers.js ADDED
@@ -0,0 +1,110 @@
1
+ import { checkInt, describe } from './checks.js';
2
+ /**
3
+ * A timer's message in the mailbox. It carries its timer's generation, which is checked when it's
4
+ * dequeued, so a cancelled or replaced timer's message is never received, even if it was already
5
+ * queued.
6
+ */
7
+ export class TimerEnvelope {
8
+ key;
9
+ generation;
10
+ msg;
11
+ constructor(key, generation, msg) {
12
+ this.key = key;
13
+ this.generation = generation;
14
+ this.msg = msg;
15
+ }
16
+ }
17
+ /** One cell's keyed timers. The cell cancels them all on stop and on restart. */
18
+ export class TimerTable {
19
+ #host;
20
+ #entries = new Map();
21
+ // Counts across incarnations, so a key that's started again after a restart never matches an
22
+ // old envelope.
23
+ #generation = 0;
24
+ constructor(host) {
25
+ this.#host = host;
26
+ }
27
+ start(key, msg, delayMs, periodic) {
28
+ this.cancel(key);
29
+ const entry = { generation: ++this.#generation, periodic, cancel: () => { } };
30
+ const arm = () => {
31
+ entry.cancel = this.#host.setTimer(fire, delayMs);
32
+ };
33
+ const fire = () => {
34
+ // Fixed delay: the next firing is measured from this one, not from when it's received.
35
+ if (periodic)
36
+ arm();
37
+ const queued = this.#host.enqueue(new TimerEnvelope(key, entry.generation, msg));
38
+ // A single timer whose message became a dead letter will never be received.
39
+ if (!queued && !periodic)
40
+ this.#entries.delete(key);
41
+ };
42
+ this.#entries.set(key, entry);
43
+ arm();
44
+ }
45
+ cancel(key) {
46
+ const entry = this.#entries.get(key);
47
+ if (entry === undefined)
48
+ return;
49
+ entry.cancel();
50
+ this.#entries.delete(key);
51
+ }
52
+ cancelAll() {
53
+ for (const entry of this.#entries.values())
54
+ entry.cancel();
55
+ this.#entries.clear();
56
+ }
57
+ isActive(key) {
58
+ return this.#entries.has(key);
59
+ }
60
+ /**
61
+ * Called when an envelope is dequeued. Returns true if its timer is still current, so its
62
+ * message should be received. A single timer is done once its message has been received.
63
+ */
64
+ accept(envelope) {
65
+ const entry = this.#entries.get(envelope.key);
66
+ if (entry?.generation !== envelope.generation)
67
+ return false;
68
+ if (!entry.periodic)
69
+ this.#entries.delete(envelope.key);
70
+ return true;
71
+ }
72
+ }
73
+ /**
74
+ * The `ctx.timers` of one incarnation. Arguments are checked first, so a bad one always throws.
75
+ * Once `live()` is false, every method does nothing.
76
+ */
77
+ export function timersFor(table, live) {
78
+ return Object.freeze({
79
+ startSingle(key, msg, delayMs) {
80
+ checkKey(key, 'timers.startSingle');
81
+ checkInt(delayMs, 'timers.startSingle: delayMs', { min: 0 });
82
+ if (live())
83
+ table.start(key, msg, delayMs, false);
84
+ },
85
+ startPeriodic(key, msg, intervalMs) {
86
+ checkKey(key, 'timers.startPeriodic');
87
+ checkInt(intervalMs, 'timers.startPeriodic: intervalMs');
88
+ if (live())
89
+ table.start(key, msg, intervalMs, true);
90
+ },
91
+ cancel(key) {
92
+ checkKey(key, 'timers.cancel');
93
+ if (live())
94
+ table.cancel(key);
95
+ },
96
+ cancelAll() {
97
+ if (live())
98
+ table.cancelAll();
99
+ },
100
+ isActive(key) {
101
+ checkKey(key, 'timers.isActive');
102
+ return live() && table.isActive(key);
103
+ },
104
+ });
105
+ }
106
+ function checkKey(key, where) {
107
+ if (typeof key !== 'string') {
108
+ throw new TypeError(`${where}: key must be a string, got ${describe(key)}`);
109
+ }
110
+ }