@kylewillett/troupe 0.2.0 → 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.
@@ -0,0 +1,57 @@
1
+ import type { Scheduler } from '../scheduler.js';
2
+ import type { SystemHandle } from '../system.js';
3
+ import type { ManualScheduler } from '../testkit/manual-scheduler.js';
4
+ /** Options for a {@link RunLoop}. */
5
+ export interface RunLoopOptions {
6
+ /**
7
+ * How long one actor may stay busy on one message, in ms of its own clock, before the run counts
8
+ * as stalled. Default 30,000, which is longer than any simulated call should take.
9
+ */
10
+ stallAfterMs?: number;
11
+ }
12
+ /** Thrown when a run can't go on: an actor is waiting on something outside the simulation. */
13
+ export declare class StallError extends Error {
14
+ /** Always `"StallError"`, so the error can be recognized without `instanceof`. */
15
+ readonly name = "StallError";
16
+ /** The busy actors, each as its system's label, if it has one, and its path. */
17
+ readonly actors: readonly string[];
18
+ constructor(message: string, actors: readonly string[]);
19
+ }
20
+ /**
21
+ * Drives one simulation: the simulation's {@link ManualScheduler}, with every node's clock on it,
22
+ * and the actor systems it watches for stalls.
23
+ */
24
+ export declare class RunLoop {
25
+ #private;
26
+ /**
27
+ * Makes a loop for `sim`.
28
+ * @throws TypeError for options that can't be used.
29
+ */
30
+ constructor(sim: ManualScheduler, opts?: RunLoopOptions);
31
+ /** The simulation's time, in ms. */
32
+ now(): number;
33
+ /**
34
+ * Watches a system for stalls. `clock` is its scheduler, which its busy times are on, and
35
+ * `label`, such as its node's name, goes before its actors' paths in a {@link StallError}.
36
+ */
37
+ watch(handle: SystemHandle, clock: Scheduler, label?: string): void;
38
+ /**
39
+ * Runs everything that needs no simulation time to pass, and the promise continuations it
40
+ * starts, until nothing more is ready.
41
+ * @throws StallError if an actor is busy and nothing could ever finish it, or has been busy on
42
+ * one message for longer than `stallAfterMs`.
43
+ */
44
+ settle(): Promise<void>;
45
+ /**
46
+ * Moves simulation time `ms` on, settling at every timer's due time on the way, and ends
47
+ * settled at exactly `ms` later.
48
+ * @throws TypeError unless `ms` is a non-negative integer.
49
+ * @throws StallError as `settle` does.
50
+ */
51
+ advance(ms: number): Promise<void>;
52
+ /**
53
+ * Moves simulation time on to `time`, as `advance` does.
54
+ * @throws RangeError if `time` is earlier than now.
55
+ */
56
+ runUntil(time: number): Promise<void>;
57
+ }
@@ -0,0 +1,153 @@
1
+ // The run loop (decision 0033), which closes virtual time. 0003 left a gap: an async receive awaits
2
+ // real promises, so the testkit's settle waits real event-loop turns while actors are busy. Here
3
+ // every call a run makes resolves on a timer of simulation time, so the loop never waits for a
4
+ // busy actor. It runs everything that's ready, yields one macrotask so the continuations that work
5
+ // started can finish, and repeats until nothing more is ready. Then it moves time to the next
6
+ // timer: an actor awaiting a simulated call is waiting on a timer, and time will reach it.
7
+ import { checkInt, checkKeys } from '../checks.js';
8
+ import { openYielder } from './yield.js';
9
+ /** Thrown when a run can't go on: an actor is waiting on something outside the simulation. */
10
+ export class StallError extends Error {
11
+ /** Always `"StallError"`, so the error can be recognized without `instanceof`. */
12
+ name = 'StallError';
13
+ /** The busy actors, each as its system's label, if it has one, and its path. */
14
+ actors;
15
+ constructor(message, actors) {
16
+ super(message);
17
+ this.actors = actors;
18
+ }
19
+ }
20
+ const OPTIONS = new Set(['stallAfterMs']);
21
+ /**
22
+ * Drives one simulation: the simulation's {@link ManualScheduler}, with every node's clock on it,
23
+ * and the actor systems it watches for stalls.
24
+ */
25
+ export class RunLoop {
26
+ #sim;
27
+ #stallAfterMs;
28
+ #watched = [];
29
+ #yielder;
30
+ #users = 0;
31
+ /**
32
+ * Makes a loop for `sim`.
33
+ * @throws TypeError for options that can't be used.
34
+ */
35
+ constructor(sim, opts = {}) {
36
+ checkKeys(opts, OPTIONS, 'RunLoop');
37
+ const { stallAfterMs = 30_000 } = opts;
38
+ checkInt(stallAfterMs, 'RunLoop: stallAfterMs');
39
+ this.#sim = sim;
40
+ this.#stallAfterMs = stallAfterMs;
41
+ }
42
+ /** The simulation's time, in ms. */
43
+ now() {
44
+ return this.#sim.now();
45
+ }
46
+ /**
47
+ * Watches a system for stalls. `clock` is its scheduler, which its busy times are on, and
48
+ * `label`, such as its node's name, goes before its actors' paths in a {@link StallError}.
49
+ */
50
+ watch(handle, clock, label) {
51
+ this.#watched.push({ handle, clock, label });
52
+ }
53
+ /**
54
+ * Runs everything that needs no simulation time to pass, and the promise continuations it
55
+ * starts, until nothing more is ready.
56
+ * @throws StallError if an actor is busy and nothing could ever finish it, or has been busy on
57
+ * one message for longer than `stallAfterMs`.
58
+ */
59
+ async settle() {
60
+ await this.#using(async (yielder) => {
61
+ await this.#settle(yielder);
62
+ });
63
+ }
64
+ /**
65
+ * Moves simulation time `ms` on, settling at every timer's due time on the way, and ends
66
+ * settled at exactly `ms` later.
67
+ * @throws TypeError unless `ms` is a non-negative integer.
68
+ * @throws StallError as `settle` does.
69
+ */
70
+ async advance(ms) {
71
+ checkInt(ms, 'RunLoop.advance: ms', { min: 0 });
72
+ await this.#using(async (yielder) => {
73
+ const target = this.#sim.now() + ms;
74
+ await this.#settle(yielder);
75
+ for (;;) {
76
+ const next = this.#sim.nextTimerAt();
77
+ if (next === undefined || next > target)
78
+ break;
79
+ this.#sim.advanceTo(next);
80
+ await this.#settle(yielder);
81
+ }
82
+ this.#sim.advanceTo(target);
83
+ });
84
+ }
85
+ /**
86
+ * Moves simulation time on to `time`, as `advance` does.
87
+ * @throws RangeError if `time` is earlier than now.
88
+ */
89
+ async runUntil(time) {
90
+ const now = this.#sim.now();
91
+ if (!(time >= now)) {
92
+ throw new RangeError(`RunLoop.runUntil: can't move time back from ${String(now)} to ${String(time)}`);
93
+ }
94
+ await this.advance(time - now);
95
+ }
96
+ // One channel for every yield while any call is running, closed once none is, so the loop never
97
+ // keeps a Node process alive.
98
+ async #using(body) {
99
+ this.#yielder ??= openYielder();
100
+ const yielder = this.#yielder;
101
+ this.#users++;
102
+ try {
103
+ await body(yielder);
104
+ }
105
+ finally {
106
+ this.#users--;
107
+ if (this.#users === 0) {
108
+ yielder.close();
109
+ this.#yielder = undefined;
110
+ }
111
+ }
112
+ }
113
+ async #settle(yielder) {
114
+ this.#sim.runReady();
115
+ // A round that started nothing new leaves only timers in the future.
116
+ do
117
+ await yielder.next();
118
+ while (this.#sim.runReady() > 0);
119
+ this.#checkStalls();
120
+ }
121
+ #checkStalls() {
122
+ let busy = 0;
123
+ for (const w of this.#watched)
124
+ busy += w.handle.busy();
125
+ if (busy === 0)
126
+ return;
127
+ const at = `at ${String(this.#sim.now())} ms of simulation time`;
128
+ if (this.#sim.nextTimerAt() === undefined) {
129
+ const actors = this.#busy(() => true);
130
+ throw new StallError(`the run stalled ${at}: nothing is ready and no timer is set, but ${actors.join(', ')} ` +
131
+ 'is still busy. Is it awaiting a promise outside the simulation?', actors);
132
+ }
133
+ const limit = this.#stallAfterMs;
134
+ const actors = this.#busy((since, clock) => clock.now() - since >= limit);
135
+ if (actors.length > 0) {
136
+ throw new StallError(`the run stalled ${at}: ${actors.join(', ')} has been busy on one message for ` +
137
+ `${String(limit)} ms or more. Is it awaiting a promise outside the simulation, or a ` +
138
+ 'call that never answers?', actors);
139
+ }
140
+ }
141
+ #busy(stuck) {
142
+ const actors = [];
143
+ for (const { handle, clock, label } of this.#watched) {
144
+ if (handle.busy() === 0)
145
+ continue;
146
+ for (const { path, since } of handle.busyActors()) {
147
+ if (stuck(since, clock))
148
+ actors.push(label === undefined ? path : `${label} ${path}`);
149
+ }
150
+ }
151
+ return actors;
152
+ }
153
+ }
@@ -0,0 +1,120 @@
1
+ import type { Transport } from '../cluster/transport.js';
2
+ import type { Scheduler } from '../scheduler.js';
3
+ /** `contract` keeps the `Transport` contract. `chaos` breaks it: loss, reordering and repeats. */
4
+ export type NetworkMode = 'contract' | 'chaos';
5
+ /** Options for {@link simulatedNetwork}. */
6
+ export interface SimulatedNetworkOptions {
7
+ /** The simulation's scheduler, which every open, frame and close goes through. */
8
+ scheduler: Scheduler;
9
+ /** The network's own random stream, which draws every latency, loss and repeat. */
10
+ random: () => number;
11
+ /** Default `contract`. */
12
+ mode?: NetworkMode;
13
+ /**
14
+ * The range each open, frame and close's latency is drawn from, in whole ms, both ends
15
+ * included. Default `[1, 3]`.
16
+ */
17
+ latencyMs?: readonly [number, number];
18
+ /**
19
+ * How long a connection can hold frames a partition stops before it resets, in ms, as TCP gives
20
+ * up retransmitting. A dial across a partition fails after it too. Default 10,000.
21
+ */
22
+ resetAfterMs?: number;
23
+ }
24
+ /**
25
+ * The links a fault applies to: every frame to or from `node`, or only those between `node` and
26
+ * `peer`.
27
+ */
28
+ export interface LinkSelector {
29
+ readonly node: string;
30
+ readonly peer?: string;
31
+ }
32
+ /** What a simulated network has done with frames so far. */
33
+ export interface NetworkCounts {
34
+ /** Frames sent on a connection that was open at the sender's end. */
35
+ readonly sent: number;
36
+ /** Frames handed to the other end's listeners. */
37
+ readonly delivered: number;
38
+ /** Frames chaos mode lost: dropped at random, or cut by a partition. */
39
+ readonly lost: number;
40
+ /** Extra copies chaos mode sent. */
41
+ readonly duplicated: number;
42
+ /** Frames chaos mode scheduled to arrive before one sent earlier on the same connection. */
43
+ readonly overtaken: number;
44
+ /** Opens, frames and closes a partition held. */
45
+ readonly held: number;
46
+ /** Connections that reset because a partition held their frames for `resetAfterMs`. */
47
+ readonly timedOut: number;
48
+ /** Connections reset by {@link SimulatedNetwork.reset}. */
49
+ readonly resets: number;
50
+ }
51
+ /** Nodes in one simulation, joined by a network that faults can be injected into. */
52
+ export interface SimulatedNetwork {
53
+ readonly mode: NetworkMode;
54
+ /**
55
+ * A transport for the node at `address`. An address is free again once its transport has
56
+ * closed or its node has been killed.
57
+ * @throws Error if a live transport already has `address`.
58
+ * @throws TypeError unless `address` is a non-empty string.
59
+ */
60
+ transport(address: string): Transport;
61
+ /**
62
+ * Kills the node at `address`, as `kill -9` would: frames on their way from it are lost, and
63
+ * the other ends of its connections see an error once its reset reaches them.
64
+ */
65
+ kill(address: string): void;
66
+ /**
67
+ * Cuts `side` off from `other`, both ways, or with `oneWay` only from `side` to `other`, until
68
+ * the returned function heals it. Connections see nothing. In contract mode their frames wait,
69
+ * and in chaos mode they're lost.
70
+ * @throws TypeError unless both sides are non-empty lists of addresses, with none on both.
71
+ */
72
+ partition(side: readonly string[], other: readonly string[], opts?: {
73
+ readonly oneWay?: boolean;
74
+ }): () => void;
75
+ /**
76
+ * Resets every connection between `a` and `b`, as a TCP reset does: both ends close with an
77
+ * error, and the frames on their way are lost.
78
+ */
79
+ reset(a: string, b: string): void;
80
+ /**
81
+ * Draws the latency of every open, frame and close on the selected links from `latencyMs`
82
+ * instead, if that's longer, until the returned function ends it. Frames stay in order.
83
+ */
84
+ delay(opts: LinkSelector & {
85
+ readonly latencyMs: readonly [number, number];
86
+ }): () => void;
87
+ /**
88
+ * Adds up to `windowMs` to the latency of everything on the selected links, drawn each time,
89
+ * until the returned function ends it. Frames on different connections overtake each other.
90
+ * With `within`, in chaos mode only, frames on one connection do too.
91
+ * @throws TypeError for `within` in contract mode.
92
+ */
93
+ reorder(opts: LinkSelector & {
94
+ readonly windowMs: number;
95
+ readonly within?: boolean;
96
+ }): () => void;
97
+ /**
98
+ * Loses each frame on the selected links with chance `rate`, leaving its connection open, until
99
+ * the returned function ends it. Chaos mode only.
100
+ * @throws TypeError in contract mode.
101
+ */
102
+ lose(opts: LinkSelector & {
103
+ readonly rate: number;
104
+ }): () => void;
105
+ /**
106
+ * Sends each frame on the selected links twice with chance `rate`, the copy with a latency of
107
+ * its own, until the returned function ends it. Chaos mode only.
108
+ * @throws TypeError in contract mode.
109
+ */
110
+ duplicate(opts: LinkSelector & {
111
+ readonly rate: number;
112
+ }): () => void;
113
+ /** What the network has done with frames so far. */
114
+ counts(): NetworkCounts;
115
+ }
116
+ /**
117
+ * Makes a simulated network on `scheduler`, with no faults until they're injected.
118
+ * @throws TypeError for options that can't be used.
119
+ */
120
+ export declare function simulatedNetwork(opts: SimulatedNetworkOptions): SimulatedNetwork;