@kylewillett/troupe 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +134 -4
  3. package/dist/ask.d.ts +5 -1
  4. package/dist/ask.js +16 -0
  5. package/dist/backstage/index.d.ts +2 -1
  6. package/dist/backstage/index.js +1 -0
  7. package/dist/backstage/source.d.ts +1 -1
  8. package/dist/backstage/source.js +65 -2
  9. package/dist/backstage/types.d.ts +65 -4
  10. package/dist/backstage/types.js +2 -1
  11. package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
  12. package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
  13. package/dist/backstage-ui/index.html +2 -2
  14. package/dist/cell.d.ts +19 -16
  15. package/dist/cell.js +46 -20
  16. package/dist/checks.d.ts +10 -0
  17. package/dist/checks.js +34 -2
  18. package/dist/cluster/index.d.ts +6 -0
  19. package/dist/cluster/index.js +4 -0
  20. package/dist/cluster/leases.d.ts +37 -0
  21. package/dist/cluster/leases.js +132 -0
  22. package/dist/cluster/membership.d.ts +100 -0
  23. package/dist/cluster/membership.js +559 -0
  24. package/dist/cluster/memory.d.ts +31 -0
  25. package/dist/cluster/memory.js +187 -0
  26. package/dist/cluster/placement.d.ts +10 -0
  27. package/dist/cluster/placement.js +30 -0
  28. package/dist/cluster/postgres/index.d.ts +1 -0
  29. package/dist/cluster/postgres/index.js +3 -0
  30. package/dist/cluster/postgres/schema.d.ts +7 -0
  31. package/dist/cluster/postgres/schema.js +33 -0
  32. package/dist/cluster/postgres/schema.sql +18 -0
  33. package/dist/cluster/postgres/store.d.ts +28 -0
  34. package/dist/cluster/postgres/store.js +124 -0
  35. package/dist/cluster/region.d.ts +103 -0
  36. package/dist/cluster/region.js +843 -0
  37. package/dist/cluster/remoting.d.ts +79 -0
  38. package/dist/cluster/remoting.js +755 -0
  39. package/dist/cluster/shard-memory.d.ts +14 -0
  40. package/dist/cluster/shard-memory.js +92 -0
  41. package/dist/cluster/shard-store.d.ts +62 -0
  42. package/dist/cluster/shard-store.js +36 -0
  43. package/dist/cluster/shard.d.ts +54 -0
  44. package/dist/cluster/shard.js +278 -0
  45. package/dist/cluster/sharding.d.ts +116 -0
  46. package/dist/cluster/sharding.js +286 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/timed-store.d.ts +4 -0
  50. package/dist/cluster/timed-store.js +19 -0
  51. package/dist/cluster/transport.d.ts +29 -0
  52. package/dist/cluster/transport.js +4 -0
  53. package/dist/cluster/wire.d.ts +90 -0
  54. package/dist/cluster/wire.js +177 -0
  55. package/dist/hash.d.ts +7 -0
  56. package/dist/hash.js +25 -0
  57. package/dist/index.d.ts +1 -0
  58. package/dist/index.js +1 -0
  59. package/dist/internal.d.ts +139 -2
  60. package/dist/internal.js +12 -1
  61. package/dist/json.d.ts +44 -0
  62. package/dist/json.js +143 -0
  63. package/dist/node/cluster/frames.d.ts +31 -0
  64. package/dist/node/cluster/frames.js +73 -0
  65. package/dist/node/cluster/index.d.ts +1 -0
  66. package/dist/node/cluster/index.js +3 -0
  67. package/dist/node/cluster/tcp.d.ts +101 -0
  68. package/dist/node/cluster/tcp.js +416 -0
  69. package/dist/persistence/actor.d.ts +9 -0
  70. package/dist/persistence/actor.js +21 -10
  71. package/dist/persistence/backend.d.ts +1 -10
  72. package/dist/persistence/backend.js +4 -34
  73. package/dist/persistence/errors.d.ts +19 -0
  74. package/dist/persistence/errors.js +22 -0
  75. package/dist/persistence/index.d.ts +1 -1
  76. package/dist/persistence/index.js +1 -1
  77. package/dist/persistence/postgres/index.d.ts +2 -1
  78. package/dist/persistence/postgres/index.js +1 -1
  79. package/dist/persistence/postgres/pool.d.ts +44 -0
  80. package/dist/persistence/postgres/pool.js +65 -0
  81. package/dist/persistence/postgres/postgres.d.ts +1 -33
  82. package/dist/persistence/postgres/postgres.js +4 -63
  83. package/dist/persistence/projection.d.ts +6 -0
  84. package/dist/persistence/projection.js +21 -5
  85. package/dist/rehearsal/clock.d.ts +54 -0
  86. package/dist/rehearsal/clock.js +203 -0
  87. package/dist/rehearsal/database.d.ts +116 -0
  88. package/dist/rehearsal/database.js +349 -0
  89. package/dist/rehearsal/loop.d.ts +57 -0
  90. package/dist/rehearsal/loop.js +153 -0
  91. package/dist/rehearsal/network.d.ts +120 -0
  92. package/dist/rehearsal/network.js +524 -0
  93. package/dist/rehearsal/ranges.d.ts +8 -0
  94. package/dist/rehearsal/ranges.js +27 -0
  95. package/dist/rehearsal/yield.d.ts +9 -0
  96. package/dist/rehearsal/yield.js +24 -0
  97. package/dist/system.d.ts +13 -1
  98. package/dist/system.js +204 -25
  99. package/dist/timeout.d.ts +8 -0
  100. package/dist/timeout.js +26 -0
  101. package/dist/types.d.ts +86 -3
  102. package/package.json +21 -2
  103. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  104. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  105. package/dist/persistence/json.d.ts +0 -7
  106. package/dist/persistence/json.js +0 -75
@@ -0,0 +1,524 @@
1
+ // The simulated network (decision 0035): a Transport on simulation time, as the in-memory network
2
+ // is, that a run can partition, reset, slow down and reorder, all drawn from its own random stream.
3
+ //
4
+ // Contract mode does only what TCP can. Frames on one connection arrive in order, at most once,
5
+ // and the only frames lost are the ones still on a connection when it closes. A partition holds
6
+ // frames, as TCP retransmits across a dropped cable: they arrive in order once it heals, or the
7
+ // connection times out and resets with them on it. Chaos mode breaks the contract on purpose: it
8
+ // loses frames from the middle of a connection, reorders them within one, and repeats them, and a
9
+ // partition loses the frames it cuts. Opens, closes and resets are never lost or repeated in
10
+ // either mode, since they stand for TCP's own handshakes, which it retransmits.
11
+ import { checkInt, checkKeys, describe } from '../checks.js';
12
+ import { checkRange, checkRate, draw } from './ranges.js';
13
+ const OPTIONS = new Set(['scheduler', 'random', 'mode', 'latencyMs', 'resetAfterMs']);
14
+ const PARTITION_OPTIONS = new Set(['oneWay']);
15
+ const DELAY_OPTIONS = new Set(['node', 'peer', 'latencyMs']);
16
+ const REORDER_OPTIONS = new Set(['node', 'peer', 'windowMs', 'within']);
17
+ const RATE_OPTIONS = new Set(['node', 'peer', 'rate']);
18
+ /**
19
+ * Makes a simulated network on `scheduler`, with no faults until they're injected.
20
+ * @throws TypeError for options that can't be used.
21
+ */
22
+ export function simulatedNetwork(opts) {
23
+ checkKeys(opts, OPTIONS, 'simulatedNetwork');
24
+ const { scheduler, random, mode = 'contract', latencyMs = [1, 3], resetAfterMs = 10_000 } = opts;
25
+ const given = scheduler;
26
+ if (typeof given?.setTimer !== 'function') {
27
+ throw new TypeError('simulatedNetwork: scheduler must be a Scheduler');
28
+ }
29
+ const givenRandom = random;
30
+ if (typeof givenRandom !== 'function') {
31
+ throw new TypeError(`simulatedNetwork: random must be a function, got ${describe(random)}`);
32
+ }
33
+ const givenMode = mode;
34
+ if (givenMode !== 'contract' && givenMode !== 'chaos') {
35
+ throw new TypeError(`simulatedNetwork: mode must be "contract" or "chaos", got ${describe(mode)}`);
36
+ }
37
+ const latency = checkRange(latencyMs, 'simulatedNetwork: latencyMs');
38
+ checkInt(resetAfterMs, 'simulatedNetwork: resetAfterMs');
39
+ const net = new Net(scheduler, random, mode, latency, resetAfterMs);
40
+ const chaosOnly = (what) => {
41
+ if (mode !== 'chaos') {
42
+ throw new TypeError(`simulatedNetwork: ${what} breaks the Transport contract: chaos mode only`);
43
+ }
44
+ };
45
+ return {
46
+ mode,
47
+ transport: (address) => net.transport(address),
48
+ kill: (address) => {
49
+ net.kill(address);
50
+ },
51
+ partition(side, other, popts = {}) {
52
+ checkKeys(popts, PARTITION_OPTIONS, 'partition');
53
+ const a = checkSide(side, 'partition: side');
54
+ const b = checkSide(other, 'partition: other');
55
+ for (const address of a) {
56
+ if (b.has(address))
57
+ throw new TypeError(`partition: ${address} is on both sides`);
58
+ }
59
+ const oneWay = popts.oneWay ?? false;
60
+ if (typeof oneWay !== 'boolean') {
61
+ throw new TypeError(`partition: oneWay must be a boolean, got ${describe(oneWay)}`);
62
+ }
63
+ const cuts = oneWay
64
+ ? [{ from: a, to: b }]
65
+ : [
66
+ { from: a, to: b },
67
+ { from: b, to: a },
68
+ ];
69
+ return net.add(net.cuts, cuts, () => {
70
+ net.flush();
71
+ });
72
+ },
73
+ reset(a, b) {
74
+ checkAddress(a, 'reset: a');
75
+ checkAddress(b, 'reset: b');
76
+ net.reset(a, b);
77
+ },
78
+ delay(dopts) {
79
+ checkKeys(dopts, DELAY_OPTIONS, 'delay');
80
+ const selector = checkSelector(dopts, 'delay');
81
+ const range = checkRange(dopts.latencyMs, 'delay: latencyMs');
82
+ return net.add(net.delays, [{ ...selector, range }]);
83
+ },
84
+ reorder(ropts) {
85
+ checkKeys(ropts, REORDER_OPTIONS, 'reorder');
86
+ const selector = checkSelector(ropts, 'reorder');
87
+ checkInt(ropts.windowMs, 'reorder: windowMs');
88
+ const within = ropts.within ?? false;
89
+ if (typeof within !== 'boolean') {
90
+ throw new TypeError(`reorder: within must be a boolean, got ${describe(within)}`);
91
+ }
92
+ if (within)
93
+ chaosOnly('reordering within a connection');
94
+ return net.add(net.reorders, [{ ...selector, windowMs: ropts.windowMs, within }]);
95
+ },
96
+ lose(lopts) {
97
+ checkKeys(lopts, RATE_OPTIONS, 'lose');
98
+ const rule = { ...checkSelector(lopts, 'lose'), rate: checkRate(lopts.rate, 'lose') };
99
+ chaosOnly('losing a frame from an open connection');
100
+ return net.add(net.losses, [rule]);
101
+ },
102
+ duplicate(dopts) {
103
+ checkKeys(dopts, RATE_OPTIONS, 'duplicate');
104
+ const rule = {
105
+ ...checkSelector(dopts, 'duplicate'),
106
+ rate: checkRate(dopts.rate, 'duplicate'),
107
+ };
108
+ chaosOnly('repeating a frame');
109
+ return net.add(net.duplicates, [rule]);
110
+ },
111
+ counts: () => ({ ...net.counts }),
112
+ };
113
+ }
114
+ /** One direction of a connection. */
115
+ class Pipe {
116
+ /** When the latest thing sent this way arrives, so nothing sent after it arrives before it. */
117
+ lastArrival = 0;
118
+ /** What a partition is holding, in the order it was sent. */
119
+ held = [];
120
+ cancelTimeout;
121
+ }
122
+ /** One connection: the end that dialed, and the end that accepted once the open arrives. */
123
+ class Link {
124
+ target;
125
+ a;
126
+ b;
127
+ broken = false;
128
+ ab = new Pipe();
129
+ ba = new Pipe();
130
+ dialer;
131
+ constructor(net, host, target) {
132
+ this.target = target;
133
+ this.dialer = host.address;
134
+ this.a = new End(net, host, this, 'a');
135
+ }
136
+ pipe(side) {
137
+ return side === 'a' ? this.ab : this.ba;
138
+ }
139
+ /** The addresses frames sent from `side` go from and to. */
140
+ route(side) {
141
+ return side === 'a' ? [this.dialer, this.target] : [this.target, this.dialer];
142
+ }
143
+ }
144
+ function matches(rule, from, to) {
145
+ return ((rule.node === from && (rule.peer === undefined || rule.peer === to)) ||
146
+ (rule.node === to && (rule.peer === undefined || rule.peer === from)));
147
+ }
148
+ class Net {
149
+ scheduler;
150
+ random;
151
+ mode;
152
+ latency;
153
+ resetAfterMs;
154
+ hosts = new Map();
155
+ // Insertion order, so a heal flushes connections in an order a run repeats.
156
+ links = new Set();
157
+ cuts = [];
158
+ delays = [];
159
+ reorders = [];
160
+ losses = [];
161
+ duplicates = [];
162
+ counts = {
163
+ sent: 0,
164
+ delivered: 0,
165
+ lost: 0,
166
+ duplicated: 0,
167
+ overtaken: 0,
168
+ held: 0,
169
+ timedOut: 0,
170
+ resets: 0,
171
+ };
172
+ constructor(scheduler, random, mode, latency, resetAfterMs) {
173
+ this.scheduler = scheduler;
174
+ this.random = random;
175
+ this.mode = mode;
176
+ this.latency = latency;
177
+ this.resetAfterMs = resetAfterMs;
178
+ }
179
+ /** Adds `items` to `rules` until the returned function takes them out again, and calls `then`. */
180
+ add(rules, items, then) {
181
+ rules.push(...items);
182
+ let ended = false;
183
+ return () => {
184
+ if (ended)
185
+ return;
186
+ ended = true;
187
+ for (const item of items)
188
+ rules.splice(rules.indexOf(item), 1);
189
+ then?.();
190
+ };
191
+ }
192
+ transport(address) {
193
+ checkAddress(address, 'simulatedNetwork: address');
194
+ if (this.hosts.has(address)) {
195
+ throw new Error(`simulatedNetwork: ${address} already has a live transport`);
196
+ }
197
+ const host = { address, onConnection: undefined, ends: new Set(), gone: false };
198
+ this.hosts.set(address, host);
199
+ return {
200
+ address,
201
+ listen: (onConnection) => {
202
+ if (host.gone)
203
+ return Promise.reject(new Error(`${address} has closed`));
204
+ if (host.onConnection !== undefined) {
205
+ return Promise.reject(new Error(`${address} is already listening`));
206
+ }
207
+ host.onConnection = onConnection;
208
+ return Promise.resolve();
209
+ },
210
+ connect: (to) => {
211
+ if (host.gone) {
212
+ const dead = new Link(this, host, to).a;
213
+ dead.drop(new Error(`${address} has closed`));
214
+ return dead;
215
+ }
216
+ return this.connect(host, to);
217
+ },
218
+ close: () => {
219
+ if (!host.gone) {
220
+ host.gone = true;
221
+ host.onConnection = undefined;
222
+ this.hosts.delete(address);
223
+ for (const end of [...host.ends])
224
+ end.close();
225
+ }
226
+ return Promise.resolve();
227
+ },
228
+ };
229
+ }
230
+ connect(from, to) {
231
+ const link = new Link(this, from, to);
232
+ const local = link.a;
233
+ from.ends.add(local);
234
+ this.links.add(link);
235
+ this.send(link, 'a', { kind: 'open' });
236
+ return local;
237
+ }
238
+ kill(address) {
239
+ const host = this.hosts.get(address);
240
+ if (host === undefined)
241
+ return;
242
+ host.gone = true;
243
+ host.onConnection = undefined;
244
+ this.hosts.delete(address);
245
+ for (const end of [...host.ends])
246
+ end.vanish();
247
+ }
248
+ reset(a, b) {
249
+ for (const link of [...this.links]) {
250
+ const between = (link.dialer === a && link.target === b) || (link.dialer === b && link.target === a);
251
+ if (!between || link.broken)
252
+ continue;
253
+ this.counts.resets++;
254
+ this.break(link, (peer) => new Error(`the connection to ${peer} was reset`));
255
+ }
256
+ }
257
+ /** Sends `packet` from `side` of `link`: held if a partition stops it, otherwise on its way. */
258
+ send(link, side, packet) {
259
+ if (link.broken)
260
+ return;
261
+ if (packet.kind === 'frame')
262
+ this.counts.sent++;
263
+ const pipe = link.pipe(side);
264
+ const [from, to] = link.route(side);
265
+ const cut = this.cut(from, to);
266
+ if (cut && packet.kind === 'frame' && this.mode === 'chaos') {
267
+ this.counts.lost++;
268
+ return;
269
+ }
270
+ // Whatever is held goes first, so nothing overtakes it.
271
+ if (cut || pipe.held.length > 0) {
272
+ this.counts.held++;
273
+ pipe.held.push(packet);
274
+ pipe.cancelTimeout ??= this.scheduler.setTimer(() => {
275
+ this.timeOut(link);
276
+ }, this.resetAfterMs);
277
+ return;
278
+ }
279
+ this.transmit(link, side, packet);
280
+ }
281
+ /** Sends what each healed partition held, in the order it was sent. */
282
+ flush() {
283
+ for (const link of [...this.links]) {
284
+ for (const side of ['a', 'b']) {
285
+ const pipe = link.pipe(side);
286
+ if (pipe.held.length === 0)
287
+ continue;
288
+ const [from, to] = link.route(side);
289
+ if (this.cut(from, to))
290
+ continue;
291
+ pipe.cancelTimeout?.();
292
+ pipe.cancelTimeout = undefined;
293
+ for (const packet of pipe.held.splice(0))
294
+ this.transmit(link, side, packet);
295
+ }
296
+ this.retire(link);
297
+ }
298
+ }
299
+ /** Removes a connection once both ends have closed and nothing is held on it. */
300
+ retire(link) {
301
+ if (!link.a.closed || link.b?.closed === false)
302
+ return;
303
+ if (link.ab.held.length > 0 || link.ba.held.length > 0)
304
+ return;
305
+ this.links.delete(link);
306
+ }
307
+ /** Whether a partition stops frames from `from` to `to`. */
308
+ cut(from, to) {
309
+ for (const cut of this.cuts)
310
+ if (cut.from.has(from) && cut.to.has(to))
311
+ return true;
312
+ return false;
313
+ }
314
+ // A partition held frames too long: TCP gives up, and both ends see the connection reset.
315
+ timeOut(link) {
316
+ this.counts.timedOut++;
317
+ this.break(link, (peer) => new Error(`the connection to ${peer} timed out`));
318
+ }
319
+ break(link, error) {
320
+ link.broken = true;
321
+ for (const pipe of [link.ab, link.ba]) {
322
+ pipe.held = [];
323
+ pipe.cancelTimeout?.();
324
+ pipe.cancelTimeout = undefined;
325
+ }
326
+ link.a.finish({ error: error(link.target) });
327
+ link.b?.finish({ error: error(link.dialer) });
328
+ this.retire(link);
329
+ }
330
+ // Draws a frame's fate in chaos mode, then puts it, and any copy, on its way.
331
+ transmit(link, side, packet) {
332
+ if (packet.kind === 'frame') {
333
+ const [from, to] = link.route(side);
334
+ if (this.#chance(this.losses, from, to)) {
335
+ this.counts.lost++;
336
+ return;
337
+ }
338
+ this.#schedule(link, side, packet);
339
+ if (this.#chance(this.duplicates, from, to)) {
340
+ this.counts.duplicated++;
341
+ this.#schedule(link, side, packet);
342
+ }
343
+ return;
344
+ }
345
+ this.#schedule(link, side, packet);
346
+ }
347
+ #chance(rules, from, to) {
348
+ let hit = false;
349
+ for (const rule of rules)
350
+ if (matches(rule, from, to) && this.random() < rule.rate)
351
+ hit = true;
352
+ return hit;
353
+ }
354
+ #schedule(link, side, packet) {
355
+ const [from, to] = link.route(side);
356
+ const pipe = link.pipe(side);
357
+ let latency = draw(this.random, this.latency);
358
+ for (const rule of this.delays) {
359
+ if (matches(rule, from, to))
360
+ latency = Math.max(latency, draw(this.random, rule.range));
361
+ }
362
+ let within = false;
363
+ for (const rule of this.reorders) {
364
+ if (!matches(rule, from, to))
365
+ continue;
366
+ latency += draw(this.random, [0, rule.windowMs]);
367
+ if (rule.within)
368
+ within = true;
369
+ }
370
+ const now = this.scheduler.now();
371
+ let at = now + latency;
372
+ // Only frames overtake: TCP's own handshakes keep their place.
373
+ if (within && packet.kind === 'frame') {
374
+ if (at < pipe.lastArrival)
375
+ this.counts.overtaken++;
376
+ }
377
+ else {
378
+ at = Math.max(at, pipe.lastArrival);
379
+ }
380
+ pipe.lastArrival = Math.max(pipe.lastArrival, at);
381
+ this.scheduler.setTimer(() => {
382
+ this.#arrive(link, side, packet);
383
+ }, at - now);
384
+ }
385
+ #arrive(link, side, packet) {
386
+ // A reset loses everything on its way: both ends have closed, so nothing below delivers it.
387
+ const source = side === 'a' ? link.a : link.b;
388
+ const dest = side === 'a' ? link.b : link.a;
389
+ switch (packet.kind) {
390
+ case 'open': {
391
+ const local = link.a;
392
+ if (local.closed)
393
+ return;
394
+ const target = this.hosts.get(link.target);
395
+ if (target?.onConnection === undefined) {
396
+ local.drop(new Error(`nothing listens at ${link.target}`));
397
+ return;
398
+ }
399
+ const remote = new End(this, target, link, 'b');
400
+ target.ends.add(remote);
401
+ link.b = remote;
402
+ link.ba.lastArrival = this.scheduler.now();
403
+ target.onConnection(remote);
404
+ return;
405
+ }
406
+ case 'frame':
407
+ // Lost if its node was killed since, or the other end has closed, or never opened.
408
+ if (source?.vanished !== false || dest === undefined || dest.closed)
409
+ return;
410
+ this.counts.delivered++;
411
+ dest.emit(packet.frame);
412
+ return;
413
+ case 'close':
414
+ dest?.finish({});
415
+ return;
416
+ case 'reset': {
417
+ const [from] = link.route(side);
418
+ dest?.finish({ error: new Error(`the connection to ${from} was reset`) });
419
+ }
420
+ }
421
+ }
422
+ }
423
+ /** One end of a connection. */
424
+ class End {
425
+ closed = false;
426
+ // Its node was killed, so even frames it sent before are lost.
427
+ vanished = false;
428
+ #net;
429
+ #host;
430
+ #link;
431
+ #side;
432
+ #frameListeners = [];
433
+ #closeListeners = [];
434
+ #closeError;
435
+ constructor(net, host, link, side) {
436
+ this.#net = net;
437
+ this.#host = host;
438
+ this.#link = link;
439
+ this.#side = side;
440
+ }
441
+ send(frame) {
442
+ if (this.closed)
443
+ return;
444
+ this.#net.send(this.#link, this.#side, { kind: 'frame', frame });
445
+ }
446
+ onFrame(listener) {
447
+ this.#frameListeners.push(listener);
448
+ }
449
+ onClose(listener) {
450
+ const closed = this.#closeError;
451
+ if (closed === undefined) {
452
+ this.#closeListeners.push(listener);
453
+ return;
454
+ }
455
+ this.#net.scheduler.runSoon(() => {
456
+ listener(...closeArgs(closed));
457
+ });
458
+ }
459
+ close() {
460
+ if (this.closed)
461
+ return;
462
+ // Sent before this end closes, so it's held behind the frames already sent if it must be.
463
+ this.#net.send(this.#link, this.#side, { kind: 'close' });
464
+ this.finish({});
465
+ }
466
+ /** Closes this end because it never opened, telling its listeners why. */
467
+ drop(error) {
468
+ this.finish({ error });
469
+ }
470
+ /** This end's node was killed: nothing is told here, and the other end hears of it as an error. */
471
+ vanish() {
472
+ this.vanished = true;
473
+ if (this.closed)
474
+ return;
475
+ this.#net.send(this.#link, this.#side, { kind: 'reset' });
476
+ this.closed = true;
477
+ this.#closeError = {};
478
+ this.#host.ends.delete(this);
479
+ this.#frameListeners.length = 0;
480
+ this.#closeListeners.length = 0;
481
+ this.#net.retire(this.#link);
482
+ }
483
+ emit(frame) {
484
+ for (const listener of this.#frameListeners)
485
+ listener(frame);
486
+ }
487
+ /** Closes this end, telling its listeners on the scheduler. */
488
+ finish(how) {
489
+ if (this.closed)
490
+ return;
491
+ this.closed = true;
492
+ this.#closeError = how;
493
+ this.#host.ends.delete(this);
494
+ const listeners = this.#closeListeners.splice(0);
495
+ // Told on the scheduler, never inside the call that closed it, so a listener can't re-enter.
496
+ this.#net.scheduler.runSoon(() => {
497
+ for (const listener of listeners)
498
+ listener(...closeArgs(how));
499
+ });
500
+ this.#net.retire(this.#link);
501
+ }
502
+ }
503
+ function closeArgs(how) {
504
+ return 'error' in how ? [how.error] : [];
505
+ }
506
+ function checkAddress(address, what) {
507
+ if (typeof address !== 'string' || address === '') {
508
+ throw new TypeError(`${what} must be a non-empty string, got ${describe(address)}`);
509
+ }
510
+ }
511
+ function checkSide(side, what) {
512
+ if (!Array.isArray(side) || side.length === 0) {
513
+ throw new TypeError(`${what} must be a non-empty list of addresses`);
514
+ }
515
+ for (const address of side)
516
+ checkAddress(address, `${what}'s address`);
517
+ return new Set(side);
518
+ }
519
+ function checkSelector(opts, where) {
520
+ checkAddress(opts.node, `${where}: node`);
521
+ if (opts.peer !== undefined)
522
+ checkAddress(opts.peer, `${where}: peer`);
523
+ return { node: opts.node, peer: opts.peer };
524
+ }
@@ -0,0 +1,8 @@
1
+ /** A range of whole ms, both ends included. */
2
+ export type Range = readonly [number, number];
3
+ /** Checks a `[min, max]` range of non-negative integers, with `min` at most `max`. */
4
+ export declare function checkRange(range: unknown, what: string): Range;
5
+ /** Checks a chance: a number above 0 and at most 1. */
6
+ export declare function checkRate(rate: unknown, what: string): number;
7
+ /** Draws a whole number from `range`, both ends included. */
8
+ export declare function draw(random: () => number, [min, max]: Range): number;
@@ -0,0 +1,27 @@
1
+ // The checks Rehearsal's simulated pieces share for the ranges and chances their faults take, so
2
+ // the network and the database reject exactly the same values.
3
+ import { checkInt, describe } from '../checks.js';
4
+ /** Checks a `[min, max]` range of non-negative integers, with `min` at most `max`. */
5
+ export function checkRange(range, what) {
6
+ if (!Array.isArray(range) || range.length !== 2) {
7
+ throw new TypeError(`${what} must be [min, max], got ${describe(range)}`);
8
+ }
9
+ const [min, max] = range;
10
+ checkInt(min, `${what}[0]`, { min: 0 });
11
+ checkInt(max, `${what}[1]`, { min: 0 });
12
+ if (max < min) {
13
+ throw new TypeError(`${what} must have min at most max, got [${String(min)}, ${String(max)}]`);
14
+ }
15
+ return [min, max];
16
+ }
17
+ /** Checks a chance: a number above 0 and at most 1. */
18
+ export function checkRate(rate, what) {
19
+ if (typeof rate !== 'number' || !(rate > 0 && rate <= 1)) {
20
+ throw new TypeError(`${what}: rate must be a number above 0 and at most 1, got ${describe(rate)}`);
21
+ }
22
+ return rate;
23
+ }
24
+ /** Draws a whole number from `range`, both ends included. */
25
+ export function draw(random, [min, max]) {
26
+ return min + Math.floor(random() * (max - min + 1));
27
+ }
@@ -0,0 +1,9 @@
1
+ /** Yields one macrotask at a time, on one channel, until it's closed. */
2
+ export interface Yielder {
3
+ /** Resolves on the next macrotask, once every microtask queued before it has run. */
4
+ next(): Promise<void>;
5
+ /** Closes the channel. An open port would keep a Node process alive. */
6
+ close(): void;
7
+ }
8
+ /** Opens a channel to yield on. One channel serves every yield, which is eight times cheaper. */
9
+ export declare function openYielder(): Yielder;
@@ -0,0 +1,24 @@
1
+ // One macrotask, cheaply (decision 0033). Rehearsal's run loop yields after each round of ready
2
+ // work, so the promise continuations that work started finish before simulation time moves: every
3
+ // microtask runs before the next macrotask. setTimeout(0) waits at least a millisecond in Node and
4
+ // four in nested browser calls, and setImmediate is Node-only (0004). A MessageChannel's message
5
+ // is unclamped everywhere: 0.4 µs a yield in Node and 1.3 µs in Chromium, against 1.1 and 4.5 ms.
6
+ /** Opens a channel to yield on. One channel serves every yield, which is eight times cheaper. */
7
+ export function openYielder() {
8
+ const channel = new MessageChannel();
9
+ const waiting = [];
10
+ channel.port1.addEventListener('message', () => {
11
+ waiting.shift()?.();
12
+ });
13
+ channel.port1.start();
14
+ return {
15
+ next: () => new Promise((resolve) => {
16
+ waiting.push(resolve);
17
+ channel.port2.postMessage(null);
18
+ }),
19
+ close: () => {
20
+ channel.port1.close();
21
+ channel.port2.close();
22
+ },
23
+ };
24
+ }
package/dist/system.d.ts CHANGED
@@ -1,5 +1,11 @@
1
- import { type Watcher } from './cell.js';
1
+ import { type Watcher } from './internal.js';
2
2
  import type { ActorRef, ActorSystem, ActorSystemOptions, AnyRef } from './types.js';
3
+ /** An actor waiting on a promise, from an async handler or `pipeToSelf`. */
4
+ export interface BusyActor {
5
+ readonly path: string;
6
+ /** When it became busy, on the system's scheduler. */
7
+ readonly since: number;
8
+ }
3
9
  /** The parts of a system that the testkit needs and the public API hides. */
4
10
  export interface SystemHandle {
5
11
  readonly system: ActorSystem;
@@ -8,6 +14,12 @@ export interface SystemHandle {
8
14
  * isn't counted, because the scheduler completes it (decision 0010).
9
15
  */
10
16
  busy(): number;
17
+ /**
18
+ * The actors that are busy now, each with the time on this system's scheduler when it became
19
+ * busy, for Rehearsal's stall check. An actor that's busy again straight after settling counts
20
+ * from the second time.
21
+ */
22
+ busyActors(): readonly BusyActor[];
11
23
  /** How many asks are waiting for a reply or their timeout. */
12
24
  pendingAsks(): number;
13
25
  /** Makes a ref whose `ask` works like any actor's, for probes. */