@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.
- package/CHANGELOG.md +26 -1
- package/README.md +134 -4
- package/dist/ask.d.ts +5 -1
- package/dist/ask.js +16 -0
- package/dist/backstage/index.d.ts +2 -1
- package/dist/backstage/index.js +1 -0
- package/dist/backstage/source.d.ts +1 -1
- package/dist/backstage/source.js +65 -2
- package/dist/backstage/types.d.ts +65 -4
- package/dist/backstage/types.js +2 -1
- package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
- package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
- package/dist/backstage-ui/index.html +2 -2
- package/dist/cell.d.ts +19 -16
- package/dist/cell.js +46 -20
- package/dist/checks.d.ts +10 -0
- package/dist/checks.js +34 -2
- package/dist/cluster/index.d.ts +6 -0
- package/dist/cluster/index.js +4 -0
- package/dist/cluster/leases.d.ts +37 -0
- package/dist/cluster/leases.js +132 -0
- package/dist/cluster/membership.d.ts +100 -0
- package/dist/cluster/membership.js +559 -0
- package/dist/cluster/memory.d.ts +31 -0
- package/dist/cluster/memory.js +187 -0
- package/dist/cluster/placement.d.ts +10 -0
- package/dist/cluster/placement.js +30 -0
- package/dist/cluster/postgres/index.d.ts +1 -0
- package/dist/cluster/postgres/index.js +3 -0
- package/dist/cluster/postgres/schema.d.ts +7 -0
- package/dist/cluster/postgres/schema.js +33 -0
- package/dist/cluster/postgres/schema.sql +18 -0
- package/dist/cluster/postgres/store.d.ts +28 -0
- package/dist/cluster/postgres/store.js +124 -0
- package/dist/cluster/region.d.ts +103 -0
- package/dist/cluster/region.js +843 -0
- package/dist/cluster/remoting.d.ts +79 -0
- package/dist/cluster/remoting.js +755 -0
- package/dist/cluster/shard-memory.d.ts +14 -0
- package/dist/cluster/shard-memory.js +92 -0
- package/dist/cluster/shard-store.d.ts +62 -0
- package/dist/cluster/shard-store.js +36 -0
- package/dist/cluster/shard.d.ts +54 -0
- package/dist/cluster/shard.js +278 -0
- package/dist/cluster/sharding.d.ts +116 -0
- package/dist/cluster/sharding.js +286 -0
- package/dist/cluster/table.d.ts +29 -0
- package/dist/cluster/table.js +74 -0
- package/dist/cluster/timed-store.d.ts +4 -0
- package/dist/cluster/timed-store.js +19 -0
- package/dist/cluster/transport.d.ts +29 -0
- package/dist/cluster/transport.js +4 -0
- package/dist/cluster/wire.d.ts +90 -0
- package/dist/cluster/wire.js +177 -0
- package/dist/hash.d.ts +7 -0
- package/dist/hash.js +25 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal.d.ts +139 -2
- package/dist/internal.js +12 -1
- package/dist/json.d.ts +44 -0
- package/dist/json.js +143 -0
- package/dist/node/cluster/frames.d.ts +31 -0
- package/dist/node/cluster/frames.js +73 -0
- package/dist/node/cluster/index.d.ts +1 -0
- package/dist/node/cluster/index.js +3 -0
- package/dist/node/cluster/tcp.d.ts +101 -0
- package/dist/node/cluster/tcp.js +416 -0
- package/dist/persistence/actor.d.ts +9 -0
- package/dist/persistence/actor.js +21 -10
- package/dist/persistence/backend.d.ts +1 -10
- package/dist/persistence/backend.js +4 -34
- package/dist/persistence/errors.d.ts +19 -0
- package/dist/persistence/errors.js +22 -0
- package/dist/persistence/index.d.ts +1 -1
- package/dist/persistence/index.js +1 -1
- package/dist/persistence/postgres/index.d.ts +2 -1
- package/dist/persistence/postgres/index.js +1 -1
- package/dist/persistence/postgres/pool.d.ts +44 -0
- package/dist/persistence/postgres/pool.js +65 -0
- package/dist/persistence/postgres/postgres.d.ts +1 -33
- package/dist/persistence/postgres/postgres.js +4 -63
- package/dist/persistence/projection.d.ts +6 -0
- package/dist/persistence/projection.js +21 -5
- package/dist/rehearsal/clock.d.ts +54 -0
- package/dist/rehearsal/clock.js +203 -0
- package/dist/rehearsal/database.d.ts +116 -0
- package/dist/rehearsal/database.js +349 -0
- package/dist/rehearsal/loop.d.ts +57 -0
- package/dist/rehearsal/loop.js +153 -0
- package/dist/rehearsal/network.d.ts +120 -0
- package/dist/rehearsal/network.js +524 -0
- package/dist/rehearsal/ranges.d.ts +8 -0
- package/dist/rehearsal/ranges.js +27 -0
- package/dist/rehearsal/yield.d.ts +9 -0
- package/dist/rehearsal/yield.js +24 -0
- package/dist/system.d.ts +13 -1
- package/dist/system.js +204 -25
- package/dist/timeout.d.ts +8 -0
- package/dist/timeout.js +26 -0
- package/dist/types.d.ts +86 -3
- package/package.json +21 -2
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
- package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
- package/dist/persistence/json.d.ts +0 -7
- package/dist/persistence/json.js +0 -75
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
// The simulated database (milestone 5, T3): a journal, snapshot store, offset store and shard store
|
|
2
|
+
// on one endpoint, as Postgres serves them all in a real cluster. Its data lives in the in-memory
|
|
3
|
+
// backends. What this adds is time and faults (decision 0033): a call's request travels to the
|
|
4
|
+
// database for a drawn latency, is applied there, and its reply travels back for another, each a
|
|
5
|
+
// timer of simulation time. The reply reaches the caller through its node's clock, so a paused
|
|
6
|
+
// node gets it only when it wakes.
|
|
7
|
+
//
|
|
8
|
+
// Calls are independent, as on a pool of connections: two from one node can overtake each other.
|
|
9
|
+
// A hang holds the calls that arrive, unapplied, and applies them in arrival order when it lets
|
|
10
|
+
// go. A node cut off from the database has its calls refused, and replies already on their way
|
|
11
|
+
// to it arrive as a lost connection, so an applied call can report failure: the outcome a caller
|
|
12
|
+
// can't know, which recovery settles (decision 0013).
|
|
13
|
+
import { checkId, checkInt, checkKeys, describe, wallClock } from '../checks.js';
|
|
14
|
+
import { inMemoryShardStore } from '../cluster/shard-memory.js';
|
|
15
|
+
import { checkAcquire, checkEntity, checkPrefix, checkRelease, checkRenewAll, } from '../cluster/shard-store.js';
|
|
16
|
+
import { checkAppend, checkOffsetSave, checkRead, checkReadByTag, serializeSnapshot, } from '../persistence/backend.js';
|
|
17
|
+
import { inMemoryPersistence } from '../persistence/memory.js';
|
|
18
|
+
import { checkRange, checkRate, draw } from './ranges.js';
|
|
19
|
+
const OPTIONS = new Set(['scheduler', 'random', 'latencyMs', 'clock']);
|
|
20
|
+
const SLOW_OPTIONS = new Set(['node', 'latencyMs']);
|
|
21
|
+
const HANG_OPTIONS = new Set(['node']);
|
|
22
|
+
const RATE_OPTIONS = new Set(['node', 'rate']);
|
|
23
|
+
/**
|
|
24
|
+
* Makes a simulated database on `scheduler`, empty, with no faults until they're injected.
|
|
25
|
+
* @throws TypeError for options that can't be used.
|
|
26
|
+
*/
|
|
27
|
+
export function simulatedDatabase(opts) {
|
|
28
|
+
checkKeys(opts, OPTIONS, 'simulatedDatabase');
|
|
29
|
+
const { scheduler, random, latencyMs = [1, 3] } = opts;
|
|
30
|
+
const given = scheduler;
|
|
31
|
+
if (typeof given?.setTimer !== 'function') {
|
|
32
|
+
throw new TypeError('simulatedDatabase: scheduler must be a Scheduler');
|
|
33
|
+
}
|
|
34
|
+
const givenRandom = random;
|
|
35
|
+
if (typeof givenRandom !== 'function') {
|
|
36
|
+
throw new TypeError(`simulatedDatabase: random must be a function, got ${describe(random)}`);
|
|
37
|
+
}
|
|
38
|
+
const latency = checkRange(latencyMs, 'simulatedDatabase: latencyMs');
|
|
39
|
+
const read = wallClock(opts.clock ?? (() => scheduler.now()), 'simulatedDatabase');
|
|
40
|
+
const db = new Db(scheduler, random, latency, read);
|
|
41
|
+
return {
|
|
42
|
+
connect: (node, clock = scheduler) => db.connect(node, clock),
|
|
43
|
+
now: () => db.now(),
|
|
44
|
+
slow(sopts) {
|
|
45
|
+
checkKeys(sopts, SLOW_OPTIONS, 'slow');
|
|
46
|
+
const node = checkNode(sopts.node, 'slow');
|
|
47
|
+
const range = checkRange(sopts.latencyMs, 'slow: latencyMs');
|
|
48
|
+
return db.add(db.slows, { node, range });
|
|
49
|
+
},
|
|
50
|
+
hang(hopts = {}) {
|
|
51
|
+
checkKeys(hopts, HANG_OPTIONS, 'hang');
|
|
52
|
+
const rule = { node: checkNode(hopts.node, 'hang') };
|
|
53
|
+
return db.add(db.hangs, rule, () => {
|
|
54
|
+
db.letGo();
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
fail(fopts = {}) {
|
|
58
|
+
checkKeys(fopts, RATE_OPTIONS, 'fail');
|
|
59
|
+
return db.add(db.failures, checkRateRule(fopts, 'fail'));
|
|
60
|
+
},
|
|
61
|
+
loseReplies(lopts = {}) {
|
|
62
|
+
checkKeys(lopts, RATE_OPTIONS, 'loseReplies');
|
|
63
|
+
return db.add(db.losses, checkRateRule(lopts, 'loseReplies'));
|
|
64
|
+
},
|
|
65
|
+
cutOff(node) {
|
|
66
|
+
checkId(node, 'cutOff: node');
|
|
67
|
+
return db.add(db.cuts, node);
|
|
68
|
+
},
|
|
69
|
+
jump(ms) {
|
|
70
|
+
checkInt(ms, 'jump: ms');
|
|
71
|
+
db.jumped += ms;
|
|
72
|
+
},
|
|
73
|
+
events: (persistenceId) => db.data.events(persistenceId),
|
|
74
|
+
counts: () => ({ ...db.counters }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const applies = (rule, node) => rule.node === undefined || rule.node === node;
|
|
78
|
+
class Db {
|
|
79
|
+
scheduler;
|
|
80
|
+
random;
|
|
81
|
+
latency;
|
|
82
|
+
wall;
|
|
83
|
+
jumped = 0;
|
|
84
|
+
slows = [];
|
|
85
|
+
hangs = [];
|
|
86
|
+
failures = [];
|
|
87
|
+
losses = [];
|
|
88
|
+
cuts = [];
|
|
89
|
+
// What hangs hold, in the order it arrived.
|
|
90
|
+
held = [];
|
|
91
|
+
counters = {
|
|
92
|
+
calls: 0,
|
|
93
|
+
applied: 0,
|
|
94
|
+
failed: 0,
|
|
95
|
+
refused: 0,
|
|
96
|
+
hung: 0,
|
|
97
|
+
lostReplies: 0,
|
|
98
|
+
disconnected: 0,
|
|
99
|
+
dropped: 0,
|
|
100
|
+
};
|
|
101
|
+
data;
|
|
102
|
+
leases;
|
|
103
|
+
constructor(scheduler, random, latency, wall) {
|
|
104
|
+
this.scheduler = scheduler;
|
|
105
|
+
this.random = random;
|
|
106
|
+
this.latency = latency;
|
|
107
|
+
this.wall = wall;
|
|
108
|
+
const clock = () => this.now();
|
|
109
|
+
this.data = inMemoryPersistence({ clock });
|
|
110
|
+
this.leases = inMemoryShardStore({ clock });
|
|
111
|
+
}
|
|
112
|
+
now() {
|
|
113
|
+
return this.wall() + this.jumped;
|
|
114
|
+
}
|
|
115
|
+
/** Adds `rule` to `rules` until the returned function takes it out again, and calls `then`. */
|
|
116
|
+
add(rules, rule, then) {
|
|
117
|
+
rules.push(rule);
|
|
118
|
+
let ended = false;
|
|
119
|
+
return () => {
|
|
120
|
+
if (ended)
|
|
121
|
+
return;
|
|
122
|
+
ended = true;
|
|
123
|
+
rules.splice(rules.indexOf(rule), 1);
|
|
124
|
+
then?.();
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
connect(node, clock) {
|
|
128
|
+
checkId(node, 'simulatedDatabase.connect: node');
|
|
129
|
+
const given = clock;
|
|
130
|
+
if (typeof given?.runSoon !== 'function') {
|
|
131
|
+
throw new TypeError('simulatedDatabase.connect: clock must be a Scheduler');
|
|
132
|
+
}
|
|
133
|
+
const client = { node, clock, closed: false, pending: new Set() };
|
|
134
|
+
return {
|
|
135
|
+
node,
|
|
136
|
+
persistence: this.#persistence(client),
|
|
137
|
+
shards: this.#shards(client),
|
|
138
|
+
close: () => {
|
|
139
|
+
if (client.closed)
|
|
140
|
+
return;
|
|
141
|
+
client.closed = true;
|
|
142
|
+
const error = new Error(`${node}'s database client has closed`);
|
|
143
|
+
for (const call of client.pending)
|
|
144
|
+
this.#hand(call, { ok: false, error });
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Makes a call: `check` runs now, and rejects the call at once if its arguments are bad, as a
|
|
150
|
+
* driver does before sending. `apply` runs once the request reaches the database.
|
|
151
|
+
*/
|
|
152
|
+
call(client, op, check) {
|
|
153
|
+
if (client.closed) {
|
|
154
|
+
return Promise.reject(new Error(`${client.node}'s database client has closed`));
|
|
155
|
+
}
|
|
156
|
+
let apply;
|
|
157
|
+
try {
|
|
158
|
+
apply = check();
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
// The argument checks only ever throw TypeError.
|
|
162
|
+
return Promise.reject(error instanceof Error ? error : new TypeError(String(error)));
|
|
163
|
+
}
|
|
164
|
+
this.counters.calls++;
|
|
165
|
+
return new Promise((resolve, reject) => {
|
|
166
|
+
const call = {
|
|
167
|
+
client,
|
|
168
|
+
op,
|
|
169
|
+
apply,
|
|
170
|
+
resolve: resolve,
|
|
171
|
+
reject,
|
|
172
|
+
};
|
|
173
|
+
client.pending.add(call);
|
|
174
|
+
this.scheduler.setTimer(() => {
|
|
175
|
+
this.arrive(call);
|
|
176
|
+
}, this.#latency(client.node));
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/** A request reaches the database: refused, held, failed, or applied. */
|
|
180
|
+
arrive(call) {
|
|
181
|
+
const { node } = call.client;
|
|
182
|
+
if (this.cuts.includes(node)) {
|
|
183
|
+
this.counters.refused++;
|
|
184
|
+
this.#hand(call, { ok: false, error: new Error(`${node} cannot reach the database`) });
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (this.hangs.some((rule) => applies(rule, node))) {
|
|
188
|
+
this.counters.hung++;
|
|
189
|
+
this.held.push(call);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (this.#chance(this.failures, node)) {
|
|
193
|
+
this.counters.failed++;
|
|
194
|
+
this.#reply(call, { ok: false, error: new Error(`the database failed ${call.op}`) });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.counters.applied++;
|
|
198
|
+
call.apply().then((value) => {
|
|
199
|
+
this.#reply(call, { ok: true, value });
|
|
200
|
+
}, (error) => {
|
|
201
|
+
this.#reply(call, { ok: false, error });
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
/** A hang ended: the calls no hang still holds go on, in the order they arrived. */
|
|
205
|
+
letGo() {
|
|
206
|
+
const calls = this.held.splice(0);
|
|
207
|
+
for (const call of calls) {
|
|
208
|
+
if (this.hangs.some((rule) => applies(rule, call.client.node)))
|
|
209
|
+
this.held.push(call);
|
|
210
|
+
else
|
|
211
|
+
this.arrive(call);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Sends the reply on its way, unless it's lost.
|
|
215
|
+
#reply(call, outcome) {
|
|
216
|
+
const { node } = call.client;
|
|
217
|
+
if (this.#chance(this.losses, node)) {
|
|
218
|
+
this.counters.lostReplies++;
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
this.scheduler.setTimer(() => {
|
|
222
|
+
if (this.cuts.includes(node)) {
|
|
223
|
+
this.counters.disconnected++;
|
|
224
|
+
this.#hand(call, {
|
|
225
|
+
ok: false,
|
|
226
|
+
error: new Error(`${node}'s connection to the database was lost`),
|
|
227
|
+
});
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this.#hand(call, outcome);
|
|
231
|
+
}, this.#latency(node));
|
|
232
|
+
}
|
|
233
|
+
// Hands the outcome to the caller, through its node's clock, unless it has had one already.
|
|
234
|
+
#hand(call, outcome) {
|
|
235
|
+
const { client } = call;
|
|
236
|
+
if (!client.pending.delete(call)) {
|
|
237
|
+
this.counters.dropped++;
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
client.clock.runSoon(() => {
|
|
241
|
+
if (outcome.ok)
|
|
242
|
+
call.resolve(outcome.value);
|
|
243
|
+
else
|
|
244
|
+
call.reject(outcome.error);
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
#latency(node) {
|
|
248
|
+
let ms = draw(this.random, this.latency);
|
|
249
|
+
for (const rule of this.slows) {
|
|
250
|
+
if (applies(rule, node))
|
|
251
|
+
ms = Math.max(ms, draw(this.random, rule.range));
|
|
252
|
+
}
|
|
253
|
+
return ms;
|
|
254
|
+
}
|
|
255
|
+
#chance(rules, node) {
|
|
256
|
+
let hit = false;
|
|
257
|
+
for (const rule of rules)
|
|
258
|
+
if (applies(rule, node) && this.random() < rule.rate)
|
|
259
|
+
hit = true;
|
|
260
|
+
return hit;
|
|
261
|
+
}
|
|
262
|
+
#persistence(client) {
|
|
263
|
+
const { journal, snapshots, offsets } = this.data;
|
|
264
|
+
const call = (op, check) => this.call(client, op, check);
|
|
265
|
+
const j = {
|
|
266
|
+
append: (persistenceId, expectedSeq, events) => call('journal.append', () => {
|
|
267
|
+
// Copied now, as a driver serializes before sending, so the caller can't change them.
|
|
268
|
+
const batch = checkAppend(persistenceId, expectedSeq, events).map(({ version, tags, json }) => ({ event: JSON.parse(json), version, tags }));
|
|
269
|
+
return () => journal.append(persistenceId, expectedSeq, batch);
|
|
270
|
+
}),
|
|
271
|
+
read: (persistenceId, fromSeq, limit) => call('journal.read', () => {
|
|
272
|
+
checkRead(persistenceId, fromSeq, limit);
|
|
273
|
+
return () => journal.read(persistenceId, fromSeq, limit);
|
|
274
|
+
}),
|
|
275
|
+
readByTag: (tag, afterOffset, limit) => call('journal.readByTag', () => {
|
|
276
|
+
checkReadByTag(tag, afterOffset, limit);
|
|
277
|
+
return () => journal.readByTag(tag, afterOffset, limit);
|
|
278
|
+
}),
|
|
279
|
+
};
|
|
280
|
+
const s = {
|
|
281
|
+
save: (persistenceId, snapshot) => call('snapshots.save', () => {
|
|
282
|
+
const { seq, version, json } = serializeSnapshot(persistenceId, snapshot);
|
|
283
|
+
const copy = { seq, version, state: JSON.parse(json) };
|
|
284
|
+
return () => snapshots.save(persistenceId, copy);
|
|
285
|
+
}),
|
|
286
|
+
load: (persistenceId) => call('snapshots.load', () => {
|
|
287
|
+
checkId(persistenceId, 'snapshots.load: persistenceId');
|
|
288
|
+
return () => snapshots.load(persistenceId);
|
|
289
|
+
}),
|
|
290
|
+
};
|
|
291
|
+
const o = {
|
|
292
|
+
load: (name) => call('offsets.load', () => {
|
|
293
|
+
checkId(name, 'offsets.load: name');
|
|
294
|
+
return () => offsets.load(name);
|
|
295
|
+
}),
|
|
296
|
+
save: (name, offset) => call('offsets.save', () => {
|
|
297
|
+
checkOffsetSave(name, offset);
|
|
298
|
+
return () => offsets.save(name, offset);
|
|
299
|
+
}),
|
|
300
|
+
};
|
|
301
|
+
return { journal: j, snapshots: s, offsets: o };
|
|
302
|
+
}
|
|
303
|
+
#shards(client) {
|
|
304
|
+
const store = this.leases;
|
|
305
|
+
const call = (op, check) => this.call(client, op, check);
|
|
306
|
+
return {
|
|
307
|
+
acquire: (lease, holder, ttlMs) => call('shards.acquire', () => {
|
|
308
|
+
checkAcquire(lease, holder, ttlMs);
|
|
309
|
+
return () => store.acquire(lease, holder, ttlMs);
|
|
310
|
+
}),
|
|
311
|
+
renewAll: (holder, ttlMs) => call('shards.renewAll', () => {
|
|
312
|
+
checkRenewAll(holder, ttlMs);
|
|
313
|
+
return () => store.renewAll(holder, ttlMs);
|
|
314
|
+
}),
|
|
315
|
+
release: (lease, holder, token) => call('shards.release', () => {
|
|
316
|
+
checkRelease(lease, holder, token);
|
|
317
|
+
return () => store.release(lease, holder, token);
|
|
318
|
+
}),
|
|
319
|
+
holders: (prefix) => call('shards.holders', () => {
|
|
320
|
+
checkPrefix(prefix);
|
|
321
|
+
return () => store.holders(prefix);
|
|
322
|
+
}),
|
|
323
|
+
remember: (shard, id) => call('shards.remember', () => {
|
|
324
|
+
checkEntity(shard, id, 'remember');
|
|
325
|
+
return () => store.remember(shard, id);
|
|
326
|
+
}),
|
|
327
|
+
forget: (shard, id) => call('shards.forget', () => {
|
|
328
|
+
checkEntity(shard, id, 'forget');
|
|
329
|
+
return () => store.forget(shard, id);
|
|
330
|
+
}),
|
|
331
|
+
remembered: (shard) => call('shards.remembered', () => {
|
|
332
|
+
checkId(shard, 'remembered: shard');
|
|
333
|
+
return () => store.remembered(shard);
|
|
334
|
+
}),
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function checkNode(node, where) {
|
|
339
|
+
if (node === undefined)
|
|
340
|
+
return undefined;
|
|
341
|
+
checkId(node, `${where}: node`);
|
|
342
|
+
return node;
|
|
343
|
+
}
|
|
344
|
+
function checkRateRule(opts, where) {
|
|
345
|
+
return {
|
|
346
|
+
node: checkNode(opts.node, where),
|
|
347
|
+
rate: opts.rate === undefined ? 1 : checkRate(opts.rate, where),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
@@ -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;
|