@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.
- package/CHANGELOG.md +10 -0
- package/README.md +6 -2
- package/dist/cell.d.ts +3 -2
- package/dist/cell.js +8 -7
- package/dist/cluster/sharding.d.ts +7 -0
- package/dist/cluster/sharding.js +14 -6
- package/dist/cluster/timed-store.d.ts +4 -0
- package/dist/cluster/timed-store.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal.d.ts +5 -0
- package/dist/persistence/actor.d.ts +9 -0
- package/dist/persistence/actor.js +20 -9
- 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/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 +12 -0
- package/dist/system.js +14 -1
- package/dist/timeout.d.ts +8 -0
- package/dist/timeout.js +26 -0
- package/package.json +1 -1
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// A node's clock in a simulation (decision 0033). Every node of a run shares one simulation clock,
|
|
2
|
+
// a ManualScheduler that nothing in the cluster reads. Each node gets a view onto it, with its own
|
|
3
|
+
// rate and its own reading, so a lease timed on a holder's clock can disagree with the store's.
|
|
4
|
+
//
|
|
5
|
+
// A node clock keeps no timer queue of its own: every task and timer goes onto the simulation's
|
|
6
|
+
// heap, converted to simulation time. One heap orders everything every node does, by due time and
|
|
7
|
+
// then creation, which is what makes a run repeat exactly.
|
|
8
|
+
import { checkInt, checkKeys } from '../checks.js';
|
|
9
|
+
const OPTIONS = new Set(['driftPpm', 'startAt']);
|
|
10
|
+
const MAX_DRIFT_PPM = 100_000;
|
|
11
|
+
/**
|
|
12
|
+
* One node's scheduler in a simulation: a view onto the simulation's {@link ManualScheduler} at its
|
|
13
|
+
* own rate. Its `now()` is whole milliseconds and never goes backwards, and its timers fire when
|
|
14
|
+
* its own clock reaches them.
|
|
15
|
+
*
|
|
16
|
+
* {@link NodeClock.pause} stops the node's process, as a long GC or a suspended VM does: none of its
|
|
17
|
+
* tasks or timers run, though its clock keeps going. {@link NodeClock.resume} then runs everything
|
|
18
|
+
* that fell due meanwhile, in the order it fell due, before anything new.
|
|
19
|
+
*/
|
|
20
|
+
export class NodeClock {
|
|
21
|
+
#sim;
|
|
22
|
+
#simStart;
|
|
23
|
+
#nodeStart;
|
|
24
|
+
#rate;
|
|
25
|
+
#paused = false;
|
|
26
|
+
// What fell due while paused, and, until it has all run, what fell due after.
|
|
27
|
+
#backlog = [];
|
|
28
|
+
#flushQueued = false;
|
|
29
|
+
/**
|
|
30
|
+
* Makes a clock for one node on `sim`.
|
|
31
|
+
* @throws TypeError for options that can't be used.
|
|
32
|
+
*/
|
|
33
|
+
constructor(sim, opts = {}) {
|
|
34
|
+
checkKeys(opts, OPTIONS, 'NodeClock');
|
|
35
|
+
const { driftPpm = 0, startAt = sim.now() } = opts;
|
|
36
|
+
checkInt(driftPpm, 'NodeClock: driftPpm', { min: -MAX_DRIFT_PPM });
|
|
37
|
+
if (driftPpm > MAX_DRIFT_PPM) {
|
|
38
|
+
throw new TypeError(`NodeClock: driftPpm must be at most ${String(MAX_DRIFT_PPM)}, got ${String(driftPpm)}`);
|
|
39
|
+
}
|
|
40
|
+
checkInt(startAt, 'NodeClock: startAt', { min: 0 });
|
|
41
|
+
this.#sim = sim;
|
|
42
|
+
this.#simStart = sim.now();
|
|
43
|
+
this.#nodeStart = startAt;
|
|
44
|
+
this.#rate = 1 + driftPpm / 1_000_000;
|
|
45
|
+
}
|
|
46
|
+
/** The node's own time, in whole ms. */
|
|
47
|
+
now() {
|
|
48
|
+
return this.#at(this.#sim.now());
|
|
49
|
+
}
|
|
50
|
+
/** Whether the node is paused. */
|
|
51
|
+
get paused() {
|
|
52
|
+
return this.#paused;
|
|
53
|
+
}
|
|
54
|
+
/** Queues `task` on the simulation, to run as this node's. */
|
|
55
|
+
runSoon(task) {
|
|
56
|
+
const item = { task, cancelled: false };
|
|
57
|
+
this.#sim.runSoon(() => {
|
|
58
|
+
this.#fire(item);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Runs `task` once this node's clock has moved `delayMs` on: at the first whole millisecond of
|
|
63
|
+
* simulation time when `now()` reads at least that. A negative or `NaN` delay counts as 0.
|
|
64
|
+
*/
|
|
65
|
+
setTimer(task, delayMs) {
|
|
66
|
+
const delay = Number.isNaN(delayMs) ? 0 : Math.max(0, delayMs);
|
|
67
|
+
const item = { task, cancelled: false };
|
|
68
|
+
const cancel = this.#sim.setTimer(() => {
|
|
69
|
+
this.#fire(item);
|
|
70
|
+
}, this.#simDelay(this.now() + delay));
|
|
71
|
+
return () => {
|
|
72
|
+
item.cancelled = true;
|
|
73
|
+
cancel();
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Stops the node's process. Its clock keeps going. Pausing a paused node does nothing. */
|
|
77
|
+
pause() {
|
|
78
|
+
this.#paused = true;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Lets the node run again: what fell due while it was paused runs on the simulation's next turn,
|
|
82
|
+
* in order, before anything that falls due later. Resuming a running node does nothing.
|
|
83
|
+
*/
|
|
84
|
+
resume() {
|
|
85
|
+
if (!this.#paused)
|
|
86
|
+
return;
|
|
87
|
+
this.#paused = false;
|
|
88
|
+
this.#queueFlush();
|
|
89
|
+
}
|
|
90
|
+
// Runs an item now, unless the node is paused or still has a backlog to run first.
|
|
91
|
+
#fire(item) {
|
|
92
|
+
if (item.cancelled)
|
|
93
|
+
return;
|
|
94
|
+
if (this.#paused || this.#backlog.length > 0) {
|
|
95
|
+
this.#backlog.push(item);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
item.task();
|
|
99
|
+
}
|
|
100
|
+
#queueFlush() {
|
|
101
|
+
if (this.#flushQueued || this.#backlog.length === 0)
|
|
102
|
+
return;
|
|
103
|
+
this.#flushQueued = true;
|
|
104
|
+
this.#sim.runSoon(this.#flush);
|
|
105
|
+
}
|
|
106
|
+
#flush = () => {
|
|
107
|
+
this.#flushQueued = false;
|
|
108
|
+
// One at a time, so a task that throws leaves the rest queued for the next turn.
|
|
109
|
+
while (!this.#paused) {
|
|
110
|
+
const item = this.#backlog.shift();
|
|
111
|
+
if (item === undefined)
|
|
112
|
+
return;
|
|
113
|
+
if (item.cancelled)
|
|
114
|
+
continue;
|
|
115
|
+
try {
|
|
116
|
+
item.task();
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
this.#queueFlush();
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
// The node's reading at simulation time `sim`.
|
|
125
|
+
#at(sim) {
|
|
126
|
+
return this.#nodeStart + Math.floor((sim - this.#simStart) * this.#rate);
|
|
127
|
+
}
|
|
128
|
+
// How long from now in simulation time, in whole ms, until this node's clock reads `target`.
|
|
129
|
+
#simDelay(target) {
|
|
130
|
+
const now = this.#sim.now();
|
|
131
|
+
let delay = Math.max(0, Math.ceil((target - this.#nodeStart) / this.#rate + this.#simStart - now));
|
|
132
|
+
// The division can land a millisecond either side of the first one that reaches `target`.
|
|
133
|
+
while (this.#at(now + delay) < target)
|
|
134
|
+
delay++;
|
|
135
|
+
while (delay > 0 && this.#at(now + delay - 1) >= target)
|
|
136
|
+
delay--;
|
|
137
|
+
return delay;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Wraps `transport` so that everything it hands its node, from new connections and frames to
|
|
142
|
+
* closes and refusals, arrives through the node's `clock`. While the node is paused, its frames
|
|
143
|
+
* wait at its sockets and it can't answer anyone, and when it resumes they arrive in order.
|
|
144
|
+
*/
|
|
145
|
+
export function throughClock(transport, clock) {
|
|
146
|
+
// Listens on the real connection at once, as a socket buffers what arrives before anyone reads,
|
|
147
|
+
// so frames that come while a new connection waits for a paused node aren't lost.
|
|
148
|
+
const wrap = (connection) => {
|
|
149
|
+
const frameListeners = [];
|
|
150
|
+
const closeListeners = [];
|
|
151
|
+
let closed;
|
|
152
|
+
connection.onFrame((frame) => {
|
|
153
|
+
clock.runSoon(() => {
|
|
154
|
+
for (const listener of frameListeners)
|
|
155
|
+
listener(frame);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
connection.onClose((...args) => {
|
|
159
|
+
clock.runSoon(() => {
|
|
160
|
+
closed = args;
|
|
161
|
+
for (const listener of closeListeners.splice(0))
|
|
162
|
+
listener(...args);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
return {
|
|
166
|
+
send: (frame) => {
|
|
167
|
+
connection.send(frame);
|
|
168
|
+
},
|
|
169
|
+
onFrame: (listener) => {
|
|
170
|
+
frameListeners.push(listener);
|
|
171
|
+
},
|
|
172
|
+
onClose: (listener) => {
|
|
173
|
+
const args = closed;
|
|
174
|
+
if (args === undefined)
|
|
175
|
+
closeListeners.push(listener);
|
|
176
|
+
else
|
|
177
|
+
clock.runSoon(() => {
|
|
178
|
+
listener(...args);
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
close: () => {
|
|
182
|
+
connection.close();
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
return {
|
|
187
|
+
address: transport.address,
|
|
188
|
+
listen: (onConnection, onRefused) => transport.listen((connection) => {
|
|
189
|
+
const wrapped = wrap(connection);
|
|
190
|
+
clock.runSoon(() => {
|
|
191
|
+
onConnection(wrapped);
|
|
192
|
+
});
|
|
193
|
+
}, onRefused === undefined
|
|
194
|
+
? undefined
|
|
195
|
+
: (reason) => {
|
|
196
|
+
clock.runSoon(() => {
|
|
197
|
+
onRefused(reason);
|
|
198
|
+
});
|
|
199
|
+
}),
|
|
200
|
+
connect: (address) => wrap(transport.connect(address)),
|
|
201
|
+
close: () => transport.close(),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { type ShardStore } from '../cluster/shard-store.js';
|
|
2
|
+
import type { Persistence, StoredEvent } from '../persistence/types.js';
|
|
3
|
+
import type { Scheduler } from '../scheduler.js';
|
|
4
|
+
/** Options for {@link simulatedDatabase}. */
|
|
5
|
+
export interface SimulatedDatabaseOptions {
|
|
6
|
+
/** The simulation's scheduler, which every request and reply travels on. */
|
|
7
|
+
scheduler: Scheduler;
|
|
8
|
+
/** The database's own random stream, which draws every latency, error and lost reply. */
|
|
9
|
+
random: () => number;
|
|
10
|
+
/**
|
|
11
|
+
* The range each request's and each reply's latency is drawn from, in whole ms, both ends
|
|
12
|
+
* included. Default `[1, 3]`.
|
|
13
|
+
*/
|
|
14
|
+
latencyMs?: readonly [number, number];
|
|
15
|
+
/**
|
|
16
|
+
* The database's wall clock, in integer ms, which the shard store judges lease expiry by and
|
|
17
|
+
* the journal stamps events with. {@link SimulatedDatabase.jump} adds to it. Default the
|
|
18
|
+
* scheduler's `now`.
|
|
19
|
+
*/
|
|
20
|
+
clock?: () => number;
|
|
21
|
+
}
|
|
22
|
+
/** The database as one node incarnation reaches it. */
|
|
23
|
+
export interface DatabaseClient {
|
|
24
|
+
/** The node the calls come from. */
|
|
25
|
+
readonly node: string;
|
|
26
|
+
/** The journal, snapshot store and offset store. */
|
|
27
|
+
readonly persistence: Required<Persistence>;
|
|
28
|
+
/** The shard store, on the same endpoint. */
|
|
29
|
+
readonly shards: ShardStore;
|
|
30
|
+
/**
|
|
31
|
+
* Ends the client, as its process dying does. Requests already sent are still applied, but
|
|
32
|
+
* every call still waiting fails at once, and so does every later one, so an actor system left
|
|
33
|
+
* running in the same process can still wind down.
|
|
34
|
+
*/
|
|
35
|
+
close(): void;
|
|
36
|
+
}
|
|
37
|
+
/** What a simulated database has done with calls so far. */
|
|
38
|
+
export interface DatabaseCounts {
|
|
39
|
+
/** Calls made with valid arguments. */
|
|
40
|
+
readonly calls: number;
|
|
41
|
+
/** Calls applied to the data. */
|
|
42
|
+
readonly applied: number;
|
|
43
|
+
/** Calls that failed with an error from {@link SimulatedDatabase.fail}, unapplied. */
|
|
44
|
+
readonly failed: number;
|
|
45
|
+
/** Calls refused because their node was cut off. */
|
|
46
|
+
readonly refused: number;
|
|
47
|
+
/** Calls a hang held when they arrived. */
|
|
48
|
+
readonly hung: number;
|
|
49
|
+
/** Replies {@link SimulatedDatabase.loseReplies} lost. */
|
|
50
|
+
readonly lostReplies: number;
|
|
51
|
+
/** Replies that arrived as a lost connection, because their node was cut off meanwhile. */
|
|
52
|
+
readonly disconnected: number;
|
|
53
|
+
/** Replies that came after their client closed, which had failed the call already. */
|
|
54
|
+
readonly dropped: number;
|
|
55
|
+
}
|
|
56
|
+
/** The calls a fault applies to: every node's, or only `node`'s. */
|
|
57
|
+
export interface CallSelector {
|
|
58
|
+
readonly node?: string;
|
|
59
|
+
}
|
|
60
|
+
/** One endpoint for a whole simulated cluster's persistence and shard leases, with faults. */
|
|
61
|
+
export interface SimulatedDatabase {
|
|
62
|
+
/**
|
|
63
|
+
* A client for one node incarnation. Its replies are handed back on `clock`, the node's own,
|
|
64
|
+
* so they wait while it's paused. Default the database's scheduler.
|
|
65
|
+
* @throws TypeError unless `node` is a non-empty string.
|
|
66
|
+
*/
|
|
67
|
+
connect(node: string, clock?: Scheduler): DatabaseClient;
|
|
68
|
+
/** The database's wall clock, jumps included. */
|
|
69
|
+
now(): number;
|
|
70
|
+
/**
|
|
71
|
+
* Draws the latency of every request and reply of the selected calls from `latencyMs` instead,
|
|
72
|
+
* if that's longer, until the returned function ends it.
|
|
73
|
+
*/
|
|
74
|
+
slow(opts: CallSelector & {
|
|
75
|
+
readonly latencyMs: readonly [number, number];
|
|
76
|
+
}): () => void;
|
|
77
|
+
/**
|
|
78
|
+
* Holds the selected calls that arrive, unapplied and unanswered, until the returned function
|
|
79
|
+
* lets go. Then they're applied, in the order they arrived. Never calling it hangs them for good.
|
|
80
|
+
*/
|
|
81
|
+
hang(opts?: CallSelector): () => void;
|
|
82
|
+
/**
|
|
83
|
+
* Fails each selected call with chance `rate` (default 1), without applying it, until the
|
|
84
|
+
* returned function ends it.
|
|
85
|
+
*/
|
|
86
|
+
fail(opts?: CallSelector & {
|
|
87
|
+
readonly rate?: number;
|
|
88
|
+
}): () => void;
|
|
89
|
+
/**
|
|
90
|
+
* Applies each selected call and loses its reply, with chance `rate` (default 1), until the
|
|
91
|
+
* returned function ends it. Its caller never hears.
|
|
92
|
+
*/
|
|
93
|
+
loseReplies(opts?: CallSelector & {
|
|
94
|
+
readonly rate?: number;
|
|
95
|
+
}): () => void;
|
|
96
|
+
/**
|
|
97
|
+
* Cuts `node` off, every incarnation of it, until the returned function heals it: its calls
|
|
98
|
+
* are refused, and replies on their way to it arrive as a lost connection.
|
|
99
|
+
* @throws TypeError unless `node` is a non-empty string.
|
|
100
|
+
*/
|
|
101
|
+
cutOff(node: string): () => void;
|
|
102
|
+
/**
|
|
103
|
+
* Jumps the database's wall clock `ms` forward, for good.
|
|
104
|
+
* @throws TypeError unless `ms` is a positive integer.
|
|
105
|
+
*/
|
|
106
|
+
jump(ms: number): void;
|
|
107
|
+
/** Every stored event, in offset order, or only `persistenceId`'s, read with no time passing. */
|
|
108
|
+
events(persistenceId?: string): readonly StoredEvent[];
|
|
109
|
+
/** What the database has done with calls so far. */
|
|
110
|
+
counts(): DatabaseCounts;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Makes a simulated database on `scheduler`, empty, with no faults until they're injected.
|
|
114
|
+
* @throws TypeError for options that can't be used.
|
|
115
|
+
*/
|
|
116
|
+
export declare function simulatedDatabase(opts: SimulatedDatabaseOptions): SimulatedDatabase;
|
|
@@ -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
|
+
}
|