@kylewillett/troupe 0.1.0 → 0.2.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 +21 -2
- package/README.md +132 -2
- 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 +16 -14
- package/dist/cell.js +38 -13
- 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 +109 -0
- package/dist/cluster/sharding.js +278 -0
- package/dist/cluster/table.d.ts +29 -0
- package/dist/cluster/table.js +74 -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/internal.d.ts +134 -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.js +1 -1
- package/dist/persistence/backend.d.ts +1 -10
- package/dist/persistence/backend.js +4 -34
- 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/system.d.ts +1 -1
- package/dist/system.js +190 -24
- package/dist/types.d.ts +86 -3
- package/package.json +25 -4
- 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,559 @@
|
|
|
1
|
+
// Membership (decision 0028): who is in the cluster, gossiped with no leader. It answers where to
|
|
2
|
+
// send a message and, from T6, where a shard should live. It never decides who owns a shard:
|
|
3
|
+
// that's the lease's job, so downing a node that's still running can't make a second owner.
|
|
4
|
+
//
|
|
5
|
+
// Every node heartbeats every other member each `heartbeatMs`, and on the same tick sends its
|
|
6
|
+
// whole table to one member chosen by the system's random. A member this node hasn't heard for
|
|
7
|
+
// `unreachableAfterMs` is unreachable, in this node's view only, and one that stays unreachable
|
|
8
|
+
// for `downAfterMs` is downed, which is gossiped. Membership's frames are remoting's control
|
|
9
|
+
// frames, sent only on an open connection, so none waits in a buffer to arrive stale.
|
|
10
|
+
import { checkInt, checkKeys, describe } from '../checks.js';
|
|
11
|
+
import { hooksOf } from '../internal.js';
|
|
12
|
+
import { isTransport, startRemoting } from './remoting.js';
|
|
13
|
+
import { checkLeases, isShardStore, startSharding, } from './sharding.js';
|
|
14
|
+
import { advance, decodeTable, encodeTable, isAfter, keyOf, merge, sameTable, } from './table.js';
|
|
15
|
+
import { ADDRESS, CLUSTER_NAME } from './wire.js';
|
|
16
|
+
const OPTIONS = new Set([
|
|
17
|
+
'name',
|
|
18
|
+
'transport',
|
|
19
|
+
'seeds',
|
|
20
|
+
'heartbeatMs',
|
|
21
|
+
'unreachableAfterMs',
|
|
22
|
+
'downAfterMs',
|
|
23
|
+
'seedTimeoutMs',
|
|
24
|
+
'bufferSize',
|
|
25
|
+
'maxFrameBytes',
|
|
26
|
+
'shards',
|
|
27
|
+
'leases',
|
|
28
|
+
]);
|
|
29
|
+
const DAY_MS = 86_400_000;
|
|
30
|
+
const joined = new WeakSet();
|
|
31
|
+
/**
|
|
32
|
+
* Joins `system` to a cluster: listens on the transport, joins through a seed, and keeps the
|
|
33
|
+
* member table from then on. Returns at once: `whenUp` says when the node is in.
|
|
34
|
+
* @throws TypeError for options that can't be used, unknown ones included, or a system that
|
|
35
|
+
* wasn't made by `createActorSystem`.
|
|
36
|
+
* @throws Error if the system is already in a cluster.
|
|
37
|
+
*/
|
|
38
|
+
export function joinCluster(system, opts) {
|
|
39
|
+
return startCluster(system, opts).cluster;
|
|
40
|
+
}
|
|
41
|
+
/** {@link joinCluster}, with the remoting underneath and the options only tests set. */
|
|
42
|
+
export function startCluster(system, opts, internals = {}) {
|
|
43
|
+
const checked = checkOptions(opts);
|
|
44
|
+
const hooks = hooksOf(system);
|
|
45
|
+
if (joined.has(system))
|
|
46
|
+
throw new Error('joinCluster: this system is already in a cluster');
|
|
47
|
+
const { pruneAfterMs = DAY_MS } = internals;
|
|
48
|
+
checkInt(pruneAfterMs, 'joinCluster: pruneAfterMs');
|
|
49
|
+
const remoting = startRemoting(system, {
|
|
50
|
+
cluster: checked.name,
|
|
51
|
+
transport: checked.transport,
|
|
52
|
+
bufferSize: checked.bufferSize,
|
|
53
|
+
maxFrameBytes: checked.maxFrameBytes,
|
|
54
|
+
closeWithSystem: false,
|
|
55
|
+
});
|
|
56
|
+
joined.add(system);
|
|
57
|
+
const membership = new Membership(system, hooks, remoting, checked, pruneAfterMs);
|
|
58
|
+
return { cluster: membership.api, remoting };
|
|
59
|
+
}
|
|
60
|
+
function checkOptions(opts) {
|
|
61
|
+
checkKeys(opts, OPTIONS, 'joinCluster');
|
|
62
|
+
const { name, transport, seeds, heartbeatMs = 1_000, unreachableAfterMs = 5_000, downAfterMs = 10_000, seedTimeoutMs = 5_000, bufferSize = 10_000, maxFrameBytes = 1_048_576, shards, leases, } = opts;
|
|
63
|
+
if (typeof name !== 'string' || !CLUSTER_NAME.test(name)) {
|
|
64
|
+
throw new TypeError(`joinCluster: name must be lower-case letters, digits and "-", got ${describe(name)}`);
|
|
65
|
+
}
|
|
66
|
+
if (!isTransport(transport))
|
|
67
|
+
throw new TypeError('joinCluster: transport must be a Transport');
|
|
68
|
+
if (!Array.isArray(seeds) || seeds.length === 0) {
|
|
69
|
+
throw new TypeError('joinCluster: seeds must be a non-empty array of addresses');
|
|
70
|
+
}
|
|
71
|
+
const seen = new Set();
|
|
72
|
+
for (const seed of seeds) {
|
|
73
|
+
if (typeof seed !== 'string' || !ADDRESS.test(seed)) {
|
|
74
|
+
throw new TypeError(`joinCluster: a seed must be an address, without "@", "#", "/" or spaces, got ${describe(seed)}`);
|
|
75
|
+
}
|
|
76
|
+
if (seen.has(seed))
|
|
77
|
+
throw new TypeError(`joinCluster: seed "${seed}" is listed twice`);
|
|
78
|
+
seen.add(seed);
|
|
79
|
+
}
|
|
80
|
+
checkInt(heartbeatMs, 'joinCluster: heartbeatMs');
|
|
81
|
+
checkInt(unreachableAfterMs, 'joinCluster: unreachableAfterMs');
|
|
82
|
+
if (unreachableAfterMs <= heartbeatMs) {
|
|
83
|
+
throw new TypeError(`joinCluster: unreachableAfterMs (${String(unreachableAfterMs)}) must be more than heartbeatMs (${String(heartbeatMs)})`);
|
|
84
|
+
}
|
|
85
|
+
checkInt(downAfterMs, 'joinCluster: downAfterMs', { min: 0 });
|
|
86
|
+
checkInt(seedTimeoutMs, 'joinCluster: seedTimeoutMs', { min: 0 });
|
|
87
|
+
checkInt(bufferSize, 'joinCluster: bufferSize', { min: 0 });
|
|
88
|
+
checkInt(maxFrameBytes, 'joinCluster: maxFrameBytes');
|
|
89
|
+
if (shards !== undefined && !isShardStore(shards)) {
|
|
90
|
+
throw new TypeError('joinCluster: shards must be a ShardStore');
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
name,
|
|
94
|
+
transport,
|
|
95
|
+
seeds: Object.freeze([...seeds]),
|
|
96
|
+
heartbeatMs,
|
|
97
|
+
unreachableAfterMs,
|
|
98
|
+
downAfterMs,
|
|
99
|
+
seedTimeoutMs,
|
|
100
|
+
bufferSize,
|
|
101
|
+
maxFrameBytes,
|
|
102
|
+
shards,
|
|
103
|
+
leases: checkLeases(leases),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const EVENT = {
|
|
107
|
+
up: 'memberUp',
|
|
108
|
+
leaving: 'memberLeaving',
|
|
109
|
+
down: 'memberDown',
|
|
110
|
+
removed: undefined,
|
|
111
|
+
};
|
|
112
|
+
/** Membership's state for one node. */
|
|
113
|
+
class Membership {
|
|
114
|
+
api;
|
|
115
|
+
#hooks;
|
|
116
|
+
#remoting;
|
|
117
|
+
#opts;
|
|
118
|
+
#pruneAfterMs;
|
|
119
|
+
#selfKey;
|
|
120
|
+
#table = new Map();
|
|
121
|
+
#local = new Map();
|
|
122
|
+
// Keys pruned, and when. Others prune a little later than this node, since they learned of the
|
|
123
|
+
// tombstone later, so their gossip would bring it back. Kept for another pruneAfterMs.
|
|
124
|
+
#pruned = new Map();
|
|
125
|
+
#phase = 'joining';
|
|
126
|
+
#cancelTick;
|
|
127
|
+
#cancelSeedTimeout;
|
|
128
|
+
#resolveUp;
|
|
129
|
+
#rejectUp;
|
|
130
|
+
#left;
|
|
131
|
+
#sharding;
|
|
132
|
+
#closing;
|
|
133
|
+
// Tells inspectors, such as Backstage, that this node's view of the cluster may have changed.
|
|
134
|
+
#changed;
|
|
135
|
+
constructor(system, hooks, remoting, opts, pruneAfterMs) {
|
|
136
|
+
this.#hooks = hooks;
|
|
137
|
+
this.#remoting = remoting;
|
|
138
|
+
this.#opts = opts;
|
|
139
|
+
this.#pruneAfterMs = pruneAfterMs;
|
|
140
|
+
const { address, uid } = remoting.self;
|
|
141
|
+
this.#selfKey = keyOf(address, uid);
|
|
142
|
+
const whenUp = new Promise((resolve, reject) => {
|
|
143
|
+
this.#resolveUp = resolve;
|
|
144
|
+
this.#rejectUp = reject;
|
|
145
|
+
});
|
|
146
|
+
// Handled here, so a node nobody awaits doesn't raise an unhandled rejection when it leaves.
|
|
147
|
+
whenUp.catch(() => { });
|
|
148
|
+
remoting.onControl((from, frame) => {
|
|
149
|
+
this.#onControl(from, frame);
|
|
150
|
+
});
|
|
151
|
+
remoting.onPeer((peer) => {
|
|
152
|
+
this.#onPeer(peer);
|
|
153
|
+
});
|
|
154
|
+
remoting.whenListening.then(() => {
|
|
155
|
+
this.#start();
|
|
156
|
+
}, (error) => {
|
|
157
|
+
void this.#shutdown(error instanceof Error ? error : new Error(String(error)));
|
|
158
|
+
});
|
|
159
|
+
// terminate() leaves gracefully once /user has stopped, handing shards off before /system
|
|
160
|
+
// stops. The cluster closes remoting itself, after saying goodbye.
|
|
161
|
+
hooks.onTerminate(() => this.#leave());
|
|
162
|
+
const members = () => this.#members();
|
|
163
|
+
this.#sharding = startSharding({
|
|
164
|
+
system,
|
|
165
|
+
hooks,
|
|
166
|
+
remoting,
|
|
167
|
+
store: opts.shards,
|
|
168
|
+
leases: opts.leases,
|
|
169
|
+
maxFrameBytes: opts.maxFrameBytes,
|
|
170
|
+
members,
|
|
171
|
+
changed: () => {
|
|
172
|
+
this.#changed();
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
this.#changed = hooks.setCluster(Object.freeze({
|
|
176
|
+
address,
|
|
177
|
+
uid,
|
|
178
|
+
members,
|
|
179
|
+
entityTypes: () => this.#sharding.entityTypes(),
|
|
180
|
+
}));
|
|
181
|
+
this.api = Object.freeze({
|
|
182
|
+
self: Object.freeze({ address, uid }),
|
|
183
|
+
members,
|
|
184
|
+
whenUp,
|
|
185
|
+
sharding: this.#sharding.api,
|
|
186
|
+
leave: () => this.#leave(),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
// ---- the node's own life ----
|
|
190
|
+
#start() {
|
|
191
|
+
if (this.#phase !== 'joining')
|
|
192
|
+
return;
|
|
193
|
+
const { seeds, seedTimeoutMs, heartbeatMs } = this.#opts;
|
|
194
|
+
const address = this.#remoting.self.address;
|
|
195
|
+
this.#cancelTick = this.#every(heartbeatMs, () => {
|
|
196
|
+
this.#tick();
|
|
197
|
+
});
|
|
198
|
+
if (seeds[0] === address) {
|
|
199
|
+
if (seeds.length === 1) {
|
|
200
|
+
this.#formAlone();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
this.#cancelSeedTimeout = this.#hooks.scheduler.setTimer(() => {
|
|
204
|
+
this.#cancelSeedTimeout = undefined;
|
|
205
|
+
this.#formAlone();
|
|
206
|
+
}, seedTimeoutMs);
|
|
207
|
+
}
|
|
208
|
+
this.#sendJoins();
|
|
209
|
+
}
|
|
210
|
+
/** A timer that runs `task` every `ms` until it's cancelled. */
|
|
211
|
+
#every(ms, task) {
|
|
212
|
+
let cancel = () => { };
|
|
213
|
+
let stopped = false;
|
|
214
|
+
const arm = () => {
|
|
215
|
+
cancel = this.#hooks.scheduler.setTimer(() => {
|
|
216
|
+
if (stopped)
|
|
217
|
+
return;
|
|
218
|
+
arm();
|
|
219
|
+
task();
|
|
220
|
+
}, ms);
|
|
221
|
+
};
|
|
222
|
+
arm();
|
|
223
|
+
return () => {
|
|
224
|
+
stopped = true;
|
|
225
|
+
cancel();
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
#formAlone() {
|
|
229
|
+
if (this.#phase !== 'joining')
|
|
230
|
+
return;
|
|
231
|
+
this.#hooks.log.info(`cluster: ${this.#remoting.self.address} formed the cluster alone`, {
|
|
232
|
+
address: this.#remoting.self.address,
|
|
233
|
+
});
|
|
234
|
+
this.#becomeUp(new Map());
|
|
235
|
+
}
|
|
236
|
+
/** This node is in: `table` is what let it in, which this node's own entry joins. */
|
|
237
|
+
#becomeUp(table) {
|
|
238
|
+
this.#phase = 'up';
|
|
239
|
+
this.#cancelSeedTimeout?.();
|
|
240
|
+
this.#cancelSeedTimeout = undefined;
|
|
241
|
+
const { address, uid } = this.#remoting.self;
|
|
242
|
+
this.#apply(advance(table, { address, uid, status: 'up' }));
|
|
243
|
+
this.#resolveUp();
|
|
244
|
+
}
|
|
245
|
+
#leave() {
|
|
246
|
+
if (this.#left !== undefined)
|
|
247
|
+
return this.#left;
|
|
248
|
+
if (this.#phase === 'joining') {
|
|
249
|
+
this.#left = this.#shutdown(new Error('the node left before it was in the cluster'));
|
|
250
|
+
return this.#left;
|
|
251
|
+
}
|
|
252
|
+
const { address, uid } = this.#remoting.self;
|
|
253
|
+
this.#phase = 'leaving';
|
|
254
|
+
// Publishing `leaving` tells the regions to hand their shards off, and the others to stop
|
|
255
|
+
// placing shards here. Once the regions have stopped, the others hear this node has gone.
|
|
256
|
+
this.#apply(advance(this.#table, { address, uid, status: 'leaving' }));
|
|
257
|
+
this.#gossipToAll();
|
|
258
|
+
this.#left = this.#sharding.whenStopped().then(() => {
|
|
259
|
+
if (this.#phase === 'leaving') {
|
|
260
|
+
this.#apply(advance(this.#table, { address, uid, status: 'removed' }));
|
|
261
|
+
this.#gossipToAll();
|
|
262
|
+
}
|
|
263
|
+
return this.#shutdown(undefined);
|
|
264
|
+
});
|
|
265
|
+
return this.#left;
|
|
266
|
+
}
|
|
267
|
+
/** A trusted member says this node is down: it leaves, and can come back only as a new uid. */
|
|
268
|
+
#downed(by) {
|
|
269
|
+
if (this.#phase !== 'up' && this.#phase !== 'leaving')
|
|
270
|
+
return;
|
|
271
|
+
const { address, uid } = this.#remoting.self;
|
|
272
|
+
this.#hooks.log.warn(`cluster: ${by} downed this node, so it has left the cluster`, {
|
|
273
|
+
address,
|
|
274
|
+
by,
|
|
275
|
+
});
|
|
276
|
+
this.#apply(advance(this.#table, { address, uid, status: 'down' }));
|
|
277
|
+
}
|
|
278
|
+
#shutdown(error) {
|
|
279
|
+
if (this.#phase === 'left' && this.#closing !== undefined)
|
|
280
|
+
return this.#closing;
|
|
281
|
+
this.#phase = 'left';
|
|
282
|
+
this.#cancelTick?.();
|
|
283
|
+
this.#cancelTick = undefined;
|
|
284
|
+
this.#cancelSeedTimeout?.();
|
|
285
|
+
this.#cancelSeedTimeout = undefined;
|
|
286
|
+
this.#rejectUp(error ?? new Error('the node left the cluster before it was up'));
|
|
287
|
+
const closing = this.#remoting.close();
|
|
288
|
+
this.#closing = closing;
|
|
289
|
+
this.#left ??= closing;
|
|
290
|
+
return closing;
|
|
291
|
+
}
|
|
292
|
+
// ---- the table ----
|
|
293
|
+
/**
|
|
294
|
+
* Makes `next` this node's table, and publishes what changed: an event for each entry that
|
|
295
|
+
* moved, in table order. Another incarnation at this node's own address is an old one of this
|
|
296
|
+
* node, so it's retired first.
|
|
297
|
+
*/
|
|
298
|
+
#apply(next) {
|
|
299
|
+
const self = this.#remoting.self;
|
|
300
|
+
next = this.#retire(next, { address: self.address, uid: self.uid });
|
|
301
|
+
const previous = this.#table;
|
|
302
|
+
this.#table = next;
|
|
303
|
+
const now = this.#hooks.scheduler.now();
|
|
304
|
+
for (const [key, entry] of next) {
|
|
305
|
+
const before = previous.get(key);
|
|
306
|
+
if (before?.status === entry.status)
|
|
307
|
+
continue;
|
|
308
|
+
let local = this.#local.get(key);
|
|
309
|
+
if (local === undefined) {
|
|
310
|
+
local = { heardAt: now, reachable: true, unreachableAt: 0, tombstoneAt: undefined };
|
|
311
|
+
this.#local.set(key, local);
|
|
312
|
+
}
|
|
313
|
+
if (local.tombstoneAt === undefined && isAfter(entry.status, 'leaving')) {
|
|
314
|
+
local.tombstoneAt = now;
|
|
315
|
+
}
|
|
316
|
+
const type = EVENT[entry.status];
|
|
317
|
+
if (type !== undefined) {
|
|
318
|
+
this.#publish({ type, address: entry.address, uid: entry.uid });
|
|
319
|
+
}
|
|
320
|
+
else if (before !== undefined) {
|
|
321
|
+
this.#publish({ type: 'memberRemoved', address: entry.address, uid: entry.uid });
|
|
322
|
+
}
|
|
323
|
+
if (key !== this.#selfKey && isAfter(entry.status, 'leaving')) {
|
|
324
|
+
this.#remoting.nodeDown(entry.address, entry.uid);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const own = next.get(this.#selfKey);
|
|
328
|
+
if (own?.status === 'down' && this.#phase !== 'left')
|
|
329
|
+
void this.#shutdown(undefined);
|
|
330
|
+
}
|
|
331
|
+
/** `table` with every other incarnation at `current`'s address removed. */
|
|
332
|
+
#retire(table, current) {
|
|
333
|
+
let next = table;
|
|
334
|
+
for (const entry of table.values()) {
|
|
335
|
+
if (entry.address === current.address &&
|
|
336
|
+
entry.uid !== current.uid &&
|
|
337
|
+
entry.status !== 'removed') {
|
|
338
|
+
next = advance(next, { ...entry, status: 'removed' });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return next;
|
|
342
|
+
}
|
|
343
|
+
/** Publishes a member event, and tells inspectors the view has changed. */
|
|
344
|
+
#publish(body) {
|
|
345
|
+
this.#hooks.publish(body);
|
|
346
|
+
this.#changed();
|
|
347
|
+
}
|
|
348
|
+
#members() {
|
|
349
|
+
const members = [];
|
|
350
|
+
for (const [key, entry] of this.#table) {
|
|
351
|
+
if (entry.status === 'removed')
|
|
352
|
+
continue;
|
|
353
|
+
const reachable = key === this.#selfKey || (this.#local.get(key)?.reachable ?? true);
|
|
354
|
+
members.push(Object.freeze({
|
|
355
|
+
address: entry.address,
|
|
356
|
+
uid: entry.uid,
|
|
357
|
+
status: entry.status,
|
|
358
|
+
reachable,
|
|
359
|
+
}));
|
|
360
|
+
}
|
|
361
|
+
return members;
|
|
362
|
+
}
|
|
363
|
+
/** The other members this node talks to: up or leaving, not itself. */
|
|
364
|
+
#peers() {
|
|
365
|
+
return [...this.#table.entries()]
|
|
366
|
+
.filter(([key, e]) => key !== this.#selfKey && !isAfter(e.status, 'leaving'))
|
|
367
|
+
.map(([, e]) => e);
|
|
368
|
+
}
|
|
369
|
+
/** Whether a member is one this node still listens to: up or leaving. */
|
|
370
|
+
#trusts(from) {
|
|
371
|
+
const entry = this.#table.get(keyOf(from.address, from.uid));
|
|
372
|
+
return entry !== undefined && !isAfter(entry.status, 'leaving');
|
|
373
|
+
}
|
|
374
|
+
/** Whether this node has downed or removed `from`, so it no longer listens to it. */
|
|
375
|
+
#distrusts(from) {
|
|
376
|
+
const entry = this.#table.get(keyOf(from.address, from.uid));
|
|
377
|
+
return entry !== undefined && isAfter(entry.status, 'leaving');
|
|
378
|
+
}
|
|
379
|
+
// ---- the tick ----
|
|
380
|
+
#tick() {
|
|
381
|
+
if (this.#phase === 'joining') {
|
|
382
|
+
this.#sendJoins();
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (this.#phase !== 'up')
|
|
386
|
+
return;
|
|
387
|
+
const peers = this.#peers();
|
|
388
|
+
for (const peer of peers)
|
|
389
|
+
this.#remoting.signal(peer.address, { t: 'hb' });
|
|
390
|
+
this.#checkReachability(peers);
|
|
391
|
+
this.#gossipToOne();
|
|
392
|
+
this.#prune();
|
|
393
|
+
}
|
|
394
|
+
#sendJoins() {
|
|
395
|
+
const address = this.#remoting.self.address;
|
|
396
|
+
for (const seed of this.#opts.seeds) {
|
|
397
|
+
if (seed !== address)
|
|
398
|
+
this.#remoting.signal(seed, { t: 'join' });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
#checkReachability(peers) {
|
|
402
|
+
const now = this.#hooks.scheduler.now();
|
|
403
|
+
const { unreachableAfterMs, downAfterMs } = this.#opts;
|
|
404
|
+
for (const peer of peers) {
|
|
405
|
+
const local = this.#local.get(keyOf(peer.address, peer.uid));
|
|
406
|
+
if (local === undefined)
|
|
407
|
+
continue;
|
|
408
|
+
if (local.reachable && now - local.heardAt >= unreachableAfterMs) {
|
|
409
|
+
local.reachable = false;
|
|
410
|
+
local.unreachableAt = now;
|
|
411
|
+
this.#hooks.log.info(`cluster: ${peer.address} is unreachable`, { address: peer.address });
|
|
412
|
+
this.#publish({
|
|
413
|
+
type: 'reachability',
|
|
414
|
+
address: peer.address,
|
|
415
|
+
uid: peer.uid,
|
|
416
|
+
reachable: false,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
if (!local.reachable && now - local.unreachableAt >= downAfterMs) {
|
|
420
|
+
this.#hooks.log.warn(`cluster: downed ${peer.address}, unreachable for ${String(now - local.unreachableAt)} ms`, { address: peer.address });
|
|
421
|
+
this.#apply(advance(this.#table, { ...peer, status: 'down' }));
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
#gossipToOne() {
|
|
426
|
+
const peers = this.#peers();
|
|
427
|
+
const reachable = peers.filter((p) => this.#local.get(keyOf(p.address, p.uid))?.reachable === true);
|
|
428
|
+
const pool = reachable.length > 0 ? reachable : peers;
|
|
429
|
+
if (pool.length === 0)
|
|
430
|
+
return;
|
|
431
|
+
const target = pool[Math.floor(this.#hooks.random() * pool.length)];
|
|
432
|
+
if (target !== undefined)
|
|
433
|
+
this.#gossip(target.address, false);
|
|
434
|
+
}
|
|
435
|
+
#gossipToAll() {
|
|
436
|
+
for (const peer of this.#peers())
|
|
437
|
+
this.#gossip(peer.address, false);
|
|
438
|
+
}
|
|
439
|
+
#gossip(address, reply) {
|
|
440
|
+
const frame = { t: 'gossip', members: encodeTable(this.#table) };
|
|
441
|
+
if (reply)
|
|
442
|
+
frame.reply = true;
|
|
443
|
+
this.#remoting.signal(address, frame);
|
|
444
|
+
}
|
|
445
|
+
#prune() {
|
|
446
|
+
const now = this.#hooks.scheduler.now();
|
|
447
|
+
let next;
|
|
448
|
+
for (const [key, entry] of this.#table) {
|
|
449
|
+
const local = this.#local.get(key);
|
|
450
|
+
if (local?.tombstoneAt === undefined || now - local.tombstoneAt < this.#pruneAfterMs) {
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (key === this.#selfKey)
|
|
454
|
+
continue;
|
|
455
|
+
next ??= new Map(this.#table);
|
|
456
|
+
next.delete(key);
|
|
457
|
+
this.#local.delete(key);
|
|
458
|
+
this.#pruned.set(key, now);
|
|
459
|
+
if (entry.status === 'down') {
|
|
460
|
+
this.#publish({ type: 'memberRemoved', address: entry.address, uid: entry.uid });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (next !== undefined)
|
|
464
|
+
this.#table = next;
|
|
465
|
+
for (const [key, at] of this.#pruned) {
|
|
466
|
+
if (now - at >= this.#pruneAfterMs)
|
|
467
|
+
this.#pruned.delete(key);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// ---- frames ----
|
|
471
|
+
#onPeer(peer) {
|
|
472
|
+
// A join goes out as soon as a seed can hear it, not on the next tick. A new incarnation at
|
|
473
|
+
// a known address is retired by the join that brings it, and by its own gossip.
|
|
474
|
+
if (this.#phase === 'joining' && this.#opts.seeds.includes(peer.address)) {
|
|
475
|
+
this.#remoting.signal(peer.address, { t: 'join' });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
#onControl(from, frame) {
|
|
479
|
+
if (this.#phase === 'left')
|
|
480
|
+
return;
|
|
481
|
+
switch (frame.t) {
|
|
482
|
+
case 'hb':
|
|
483
|
+
this.#onHeartbeat(from);
|
|
484
|
+
return;
|
|
485
|
+
case 'join':
|
|
486
|
+
this.#onJoin(from);
|
|
487
|
+
return;
|
|
488
|
+
case 'gossip':
|
|
489
|
+
this.#onGossip(from, frame);
|
|
490
|
+
return;
|
|
491
|
+
case 'downed':
|
|
492
|
+
// Only from a member this node still trusts: a node this one has downed can't make it
|
|
493
|
+
// leave, so two sides of a partition that down each other leave two clusters, not none.
|
|
494
|
+
if (this.#trusts(from))
|
|
495
|
+
this.#downed(from.address);
|
|
496
|
+
return;
|
|
497
|
+
default:
|
|
498
|
+
this.#hooks.log.warn(`cluster: ignored a "${String(frame.t)}" frame from ${from.address}`, {
|
|
499
|
+
address: from.address,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
#onHeartbeat(from) {
|
|
504
|
+
const local = this.#local.get(keyOf(from.address, from.uid));
|
|
505
|
+
if (local === undefined)
|
|
506
|
+
return;
|
|
507
|
+
local.heardAt = this.#hooks.scheduler.now();
|
|
508
|
+
if (local.reachable)
|
|
509
|
+
return;
|
|
510
|
+
local.reachable = true;
|
|
511
|
+
this.#hooks.log.info(`cluster: ${from.address} is reachable again`, { address: from.address });
|
|
512
|
+
this.#publish({
|
|
513
|
+
type: 'reachability',
|
|
514
|
+
address: from.address,
|
|
515
|
+
uid: from.uid,
|
|
516
|
+
reachable: true,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
#onJoin(from) {
|
|
520
|
+
// Only a member lets another in, so a node that isn't in a cluster can't start one.
|
|
521
|
+
if (this.#phase !== 'up')
|
|
522
|
+
return;
|
|
523
|
+
const key = keyOf(from.address, from.uid);
|
|
524
|
+
const known = this.#table.get(key);
|
|
525
|
+
if (known !== undefined && isAfter(known.status, 'leaving'))
|
|
526
|
+
return;
|
|
527
|
+
if (known === undefined) {
|
|
528
|
+
this.#apply(this.#retire(advance(this.#table, { ...from, status: 'up' }), from));
|
|
529
|
+
}
|
|
530
|
+
this.#gossip(from.address, true);
|
|
531
|
+
}
|
|
532
|
+
#onGossip(from, frame) {
|
|
533
|
+
const decoded = decodeTable(frame.members, (a) => ADDRESS.test(a));
|
|
534
|
+
const received = decoded === undefined || this.#pruned.size === 0
|
|
535
|
+
? decoded
|
|
536
|
+
: new Map([...decoded].filter(([key]) => !this.#pruned.has(key)));
|
|
537
|
+
if (received === undefined) {
|
|
538
|
+
this.#hooks.log.warn(`cluster: ignored gossip from ${from.address} that isn’t a table`, {
|
|
539
|
+
address: from.address,
|
|
540
|
+
});
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (this.#phase === 'joining') {
|
|
544
|
+
// The welcome: a member's table with this node in it.
|
|
545
|
+
if (received.get(this.#selfKey)?.status === 'up')
|
|
546
|
+
this.#becomeUp(received);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
// Gossip from a member this node hasn't heard of yet is welcome: it was let in elsewhere.
|
|
550
|
+
if (this.#distrusts(from))
|
|
551
|
+
return;
|
|
552
|
+
const next = merge(this.#table, received);
|
|
553
|
+
if (!sameTable(next, this.#table))
|
|
554
|
+
this.#apply(next);
|
|
555
|
+
// Push-pull: a node that knew more answers, once, so two nodes agree after one exchange.
|
|
556
|
+
if (frame.reply !== true && !sameTable(this.#table, received))
|
|
557
|
+
this.#gossip(from.address, true);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Scheduler } from '../scheduler.js';
|
|
2
|
+
import type { Transport } from './transport.js';
|
|
3
|
+
/** Options for {@link inMemoryNetwork}. */
|
|
4
|
+
export interface InMemoryNetworkOptions {
|
|
5
|
+
/** The scheduler every delivery goes through: one per network. */
|
|
6
|
+
scheduler: Scheduler;
|
|
7
|
+
/** How long a frame, an open or a close takes to arrive, in ms. Default 1. */
|
|
8
|
+
latencyMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Nodes in one process, joined by connections that deliver after a fixed latency. */
|
|
11
|
+
export interface InMemoryNetwork {
|
|
12
|
+
/**
|
|
13
|
+
* A transport for the node at `address`. An address is free again once its transport has
|
|
14
|
+
* closed or its node has been killed.
|
|
15
|
+
* @throws Error if a live transport already has `address`.
|
|
16
|
+
* @throws TypeError unless `address` is a non-empty string.
|
|
17
|
+
*/
|
|
18
|
+
transport(address: string): Transport;
|
|
19
|
+
/**
|
|
20
|
+
* Kills the node at `address`, as `kill -9` would: its connections drop with no goodbye, frames
|
|
21
|
+
* on their way to or from it are lost, and the other ends see their connections close with an
|
|
22
|
+
* error, one latency later. Killing an address with no live node does nothing.
|
|
23
|
+
*/
|
|
24
|
+
kill(address: string): void;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Makes an in-memory network on `scheduler`. Every frame is delivered `latencyMs` after it's sent,
|
|
28
|
+
* in order per connection.
|
|
29
|
+
* @throws TypeError for options that can't be used.
|
|
30
|
+
*/
|
|
31
|
+
export declare function inMemoryNetwork(opts: InMemoryNetworkOptions): InMemoryNetwork;
|