@pocketrts/lockstep 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +239 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/lockstep.d.ts +328 -0
- package/dist/lockstep.js +779 -0
- package/dist/queue.d.ts +19 -0
- package/dist/queue.js +25 -0
- package/dist/text.d.ts +8 -0
- package/dist/text.js +26 -0
- package/package.json +41 -3
package/dist/lockstep.js
ADDED
|
@@ -0,0 +1,779 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic lockstep turn scheduling: the host orders commands and broadcasts turns on a fixed beat; every peer
|
|
3
|
+
* simulates up to the end of a turn only after it has received that turn. Pure logic, no DOM and no connections:
|
|
4
|
+
* inputs are "a message arrived", "what time is it" (`update`), "the host changed" and "a member was lost"; outputs go
|
|
5
|
+
* through `LockstepHooks` (send messages, report events). The game wires it to its room session and main loop.
|
|
6
|
+
*
|
|
7
|
+
* - Turns: each turn has `turnTicks` slots (a slot is one simulation step; a paused world still consumes slots, so
|
|
8
|
+
* turn numbers are not world tick numbers). Turn n's commands run in its first slot. At the start the host sends
|
|
9
|
+
* turns 0..lead, then turn k + lead on beat k, so every peer usually holds `lead` turns of margin.
|
|
10
|
+
* - Commands: members send commands to the host at any time; the host puts them in the next broadcast turn (they run
|
|
11
|
+
* about `lead` turns after being issued). Members keep the commands they have not yet seen in a turn and resend them
|
|
12
|
+
* after a host migration; the host deduplicates by the highest sequence number already seen from each member.
|
|
13
|
+
* - Catch-up and waiting: every peer reports each finished turn to the host. When someone lags more than `lagTurns`,
|
|
14
|
+
* the host stops sending new turns (the match runs at the slowest peer's pace); after `waitShowMs` of halting it
|
|
15
|
+
* broadcasts whom it waits for (doubling as the host heartbeat). A blocking member with no progress for `stallMs` is
|
|
16
|
+
* dropped.
|
|
17
|
+
* - Membership: the host's verdict rules. Members the host drops are listed in a turn's `drop`; every peer closes its
|
|
18
|
+
* link to them, and the game's `dropCommands` hook can insert system commands into the same turn.
|
|
19
|
+
* - Host migration: after the connection layer names a new host, the new host asks everyone for the last turn they
|
|
20
|
+
* received, sends missing turns to the peers that lack them, and continues ordering from the next turn; the old
|
|
21
|
+
* host's drop (and its `dropCommands`) goes into the first new turn. If a peer claims to be the new host while the
|
|
22
|
+
* old host is still alive for others (only the claimant lost the old host), they answer `stale` and the claimant
|
|
23
|
+
* drops itself.
|
|
24
|
+
*/
|
|
25
|
+
export const DEFAULT_LOCKSTEP_OPTIONS = Object.freeze({
|
|
26
|
+
turnTicks: 3,
|
|
27
|
+
turnMs: 100,
|
|
28
|
+
lead: 2,
|
|
29
|
+
keepTurns: 600,
|
|
30
|
+
lagTurns: 8,
|
|
31
|
+
waitShowMs: 600,
|
|
32
|
+
waitKeepMs: 1500,
|
|
33
|
+
waitBeatMs: 500,
|
|
34
|
+
stallMs: 10_000,
|
|
35
|
+
silentMs: 10_000,
|
|
36
|
+
staleMs: 1500,
|
|
37
|
+
migrateMs: 5000,
|
|
38
|
+
checkTurns: 10,
|
|
39
|
+
frozenMs: 2000,
|
|
40
|
+
loadMs: 60_000,
|
|
41
|
+
loadBeatMs: 500,
|
|
42
|
+
turnBytes: 40_000,
|
|
43
|
+
entryBytes: 32,
|
|
44
|
+
maxFrameSteps: 24,
|
|
45
|
+
});
|
|
46
|
+
/** Options that count turns, slots or bytes, or set the beat: positive integers (a `turnMs` of 0 would never end a beat). */
|
|
47
|
+
const POSITIVE_INTEGER_OPTIONS = new Set([
|
|
48
|
+
'turnTicks', 'turnMs', 'lead', 'keepTurns', 'lagTurns', 'checkTurns', 'maxFrameSteps', 'turnBytes',
|
|
49
|
+
]);
|
|
50
|
+
/**
|
|
51
|
+
* Fill in defaults; `undefined` fields keep the default. Throws `RangeError` when a turn, slot or byte count or
|
|
52
|
+
* `turnMs` is not a positive finite integer, another field is not a non-negative finite number, or `keepTurns` is not
|
|
53
|
+
* greater than `lead`.
|
|
54
|
+
*/
|
|
55
|
+
export function lockstepOptions(options = {}) {
|
|
56
|
+
const out = { ...DEFAULT_LOCKSTEP_OPTIONS };
|
|
57
|
+
for (const k of Object.keys(out)) {
|
|
58
|
+
const v = options[k];
|
|
59
|
+
if (v === undefined)
|
|
60
|
+
continue;
|
|
61
|
+
if (POSITIVE_INTEGER_OPTIONS.has(k)) {
|
|
62
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
|
|
63
|
+
throw new RangeError(`lockstep option ${k} must be a positive finite integer, got ${String(v)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
else if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
|
|
67
|
+
throw new RangeError(`lockstep option ${k} must be a non-negative finite number, got ${String(v)}`);
|
|
68
|
+
}
|
|
69
|
+
out[k] = v;
|
|
70
|
+
}
|
|
71
|
+
if (out.keepTurns <= out.lead) {
|
|
72
|
+
throw new RangeError(`lockstep option keepTurns (${out.keepTurns}) must be greater than lead (${out.lead})`);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
export const DROP_REASONS = ['left', 'desync', 'stall', 'load'];
|
|
77
|
+
/** Unknown reasons from the wire count as `left`. */
|
|
78
|
+
const dropReason = (r) => (DROP_REASONS.includes(r) ? r : 'left');
|
|
79
|
+
export class Lockstep {
|
|
80
|
+
cfg;
|
|
81
|
+
hooks;
|
|
82
|
+
options;
|
|
83
|
+
self;
|
|
84
|
+
host;
|
|
85
|
+
phase = 'loading';
|
|
86
|
+
/** Members still in the match (including self), changed by the host's verdicts. */
|
|
87
|
+
members = new Set();
|
|
88
|
+
/** Members the host halted for (UI: "waiting for ..."). */
|
|
89
|
+
waiting = [];
|
|
90
|
+
/** Host migration in progress (UI: "host left, switching"). */
|
|
91
|
+
migrating = false;
|
|
92
|
+
/** Loading: members that are ready. */
|
|
93
|
+
loaded = new Set();
|
|
94
|
+
/** Slots consumed. */
|
|
95
|
+
slot = 0;
|
|
96
|
+
/** Last turn received in sequence. */
|
|
97
|
+
recv = -1;
|
|
98
|
+
turns = new Map();
|
|
99
|
+
/** Highest sequence number seen in a turn per member. */
|
|
100
|
+
seen = new Map();
|
|
101
|
+
/** Own commands not yet seen in a turn. */
|
|
102
|
+
pending = [];
|
|
103
|
+
seq = 0;
|
|
104
|
+
lastHost;
|
|
105
|
+
/** During migration: already reported to the new host (new commands may go to it directly). */
|
|
106
|
+
reported = false;
|
|
107
|
+
/** This peer has loaded. */
|
|
108
|
+
selfReady = false;
|
|
109
|
+
closed = false;
|
|
110
|
+
hiddenAt = -1;
|
|
111
|
+
lastUpdate = -1;
|
|
112
|
+
// ---- host ----
|
|
113
|
+
nextTurn = 0;
|
|
114
|
+
inbox = [];
|
|
115
|
+
/** Highest sequence number accepted (into the inbox or a turn) per member. */
|
|
116
|
+
accepted = new Map();
|
|
117
|
+
drops = [];
|
|
118
|
+
beatAt = 0;
|
|
119
|
+
/** Halted, waiting for someone. */
|
|
120
|
+
halted = false;
|
|
121
|
+
/** Accumulated halt time (ms; decays while not halted). */
|
|
122
|
+
haltMs = 0;
|
|
123
|
+
/** When each member last blocked. */
|
|
124
|
+
blockedAt = new Map();
|
|
125
|
+
lastCheck = -1;
|
|
126
|
+
waitSent = 0;
|
|
127
|
+
/** Each member's last finished turn and when it last changed. */
|
|
128
|
+
progress = new Map();
|
|
129
|
+
/** Checksums: turn → member → value. */
|
|
130
|
+
sums = new Map();
|
|
131
|
+
loadUntil = 0;
|
|
132
|
+
loadBeat = 0;
|
|
133
|
+
/** New host during migration: members yet to report and the deadline, reported last turns, commands held meanwhile. */
|
|
134
|
+
mig = null;
|
|
135
|
+
/** New host: when it became host through migration (-1 when host from the start); `stale` is honoured only within silentMs. */
|
|
136
|
+
hostSince = -1;
|
|
137
|
+
/** New host: next heartbeat during migration. */
|
|
138
|
+
migBeat = 0;
|
|
139
|
+
/** New host: members that reported in this migration (their `stale` is honoured too). */
|
|
140
|
+
reportedBy = new Set();
|
|
141
|
+
/** Members that left but whose drop has not appeared in a turn (old hosts etc.): announced by whoever becomes host. */
|
|
142
|
+
unannounced = new Set();
|
|
143
|
+
// ---- member ----
|
|
144
|
+
/** Someone claims to be the new host while ours is still here: hold its messages until ours speaks or stays silent. */
|
|
145
|
+
claim = null;
|
|
146
|
+
constructor(cfg, hooks) {
|
|
147
|
+
this.cfg = cfg;
|
|
148
|
+
this.hooks = hooks;
|
|
149
|
+
this.options = Object.freeze(lockstepOptions(cfg.options));
|
|
150
|
+
this.self = cfg.self;
|
|
151
|
+
this.host = cfg.host;
|
|
152
|
+
for (const m of cfg.members)
|
|
153
|
+
this.members.add(m);
|
|
154
|
+
const now = cfg.now();
|
|
155
|
+
this.lastHost = now;
|
|
156
|
+
this.loadUntil = now + this.options.loadMs;
|
|
157
|
+
}
|
|
158
|
+
get isHost() {
|
|
159
|
+
return this.self === this.host;
|
|
160
|
+
}
|
|
161
|
+
/** Turns completed (= the next turn to simulate). */
|
|
162
|
+
get turn() {
|
|
163
|
+
return Math.floor(this.slot / this.options.turnTicks);
|
|
164
|
+
}
|
|
165
|
+
/** Time (ms) since the last message from the host. */
|
|
166
|
+
hostSilentFor() {
|
|
167
|
+
return this.cfg.now() - this.lastHost;
|
|
168
|
+
}
|
|
169
|
+
/** Slots that can be advanced right now. */
|
|
170
|
+
available() {
|
|
171
|
+
if (this.phase !== 'running' || this.closed)
|
|
172
|
+
return 0;
|
|
173
|
+
return Math.max(0, (this.recv + 1) * this.options.turnTicks - this.slot);
|
|
174
|
+
}
|
|
175
|
+
// ------------------------------------------------------------------ command queue side
|
|
176
|
+
/** A local command: the host puts it in the next turn; a member sends it to the host and keeps a copy. */
|
|
177
|
+
submit(d) {
|
|
178
|
+
if (this.closed || this.phase === 'over')
|
|
179
|
+
return;
|
|
180
|
+
const s = ++this.seq;
|
|
181
|
+
this.pending.push({ s, d });
|
|
182
|
+
if (this.isHost && !this.mig)
|
|
183
|
+
this.accept(this.self, s, d);
|
|
184
|
+
else if (!this.isHost && (!this.migrating || this.reported))
|
|
185
|
+
this.hooks.send(this.host, { k: 'cmd', s, d });
|
|
186
|
+
}
|
|
187
|
+
/** Commands for the next slot; null when its turn has not arrived (no slot consumed). */
|
|
188
|
+
take() {
|
|
189
|
+
if (!this.available())
|
|
190
|
+
return null;
|
|
191
|
+
const n = this.turn;
|
|
192
|
+
const first = this.slot % this.options.turnTicks === 0;
|
|
193
|
+
this.slot++;
|
|
194
|
+
return first ? this.turns.get(n).c.map(e => e[2]) : [];
|
|
195
|
+
}
|
|
196
|
+
/** Call after advancing a slot: returns the turn number when a turn was just completed (then pass a checksum if `isCheckTurn`). */
|
|
197
|
+
stepped() {
|
|
198
|
+
const tt = this.options.turnTicks;
|
|
199
|
+
if (this.slot % tt !== 0)
|
|
200
|
+
return null;
|
|
201
|
+
const n = this.slot / tt - 1;
|
|
202
|
+
if (this.isHost)
|
|
203
|
+
this.setProgress(this.self, n);
|
|
204
|
+
else
|
|
205
|
+
this.hooks.send(this.host, { k: 'at', n });
|
|
206
|
+
return n;
|
|
207
|
+
}
|
|
208
|
+
/** Whether to compare checksums at the end of turn n (with the default `checkTurns` unless given). */
|
|
209
|
+
static isCheckTurn(n, checkTurns = DEFAULT_LOCKSTEP_OPTIONS.checkTurns) {
|
|
210
|
+
return (n + 1) % checkTurns === 0;
|
|
211
|
+
}
|
|
212
|
+
/** Whether to compare checksums at the end of turn n, with this scheduler's `checkTurns`. */
|
|
213
|
+
isCheckTurn(n) {
|
|
214
|
+
return Lockstep.isCheckTurn(n, this.options.checkTurns);
|
|
215
|
+
}
|
|
216
|
+
/** The game's checksum of its world at the end of turn n (an integer). */
|
|
217
|
+
checksum(n, v) {
|
|
218
|
+
if (this.isHost)
|
|
219
|
+
this.addSum(n, this.self, v);
|
|
220
|
+
else
|
|
221
|
+
this.hooks.send(this.host, { k: 'sum', n, v });
|
|
222
|
+
}
|
|
223
|
+
// ------------------------------------------------------------------ loading
|
|
224
|
+
/** This peer has loaded its world. */
|
|
225
|
+
ready() {
|
|
226
|
+
this.selfReady = true;
|
|
227
|
+
this.lastHost = this.cfg.now();
|
|
228
|
+
if (this.isHost) {
|
|
229
|
+
this.loaded.add(this.self);
|
|
230
|
+
this.hooks.status();
|
|
231
|
+
}
|
|
232
|
+
else
|
|
233
|
+
this.hooks.send(this.host, { k: 'loaded' });
|
|
234
|
+
}
|
|
235
|
+
startRunning(now) {
|
|
236
|
+
this.phase = 'running';
|
|
237
|
+
this.lastHost = now;
|
|
238
|
+
this.hooks.status();
|
|
239
|
+
}
|
|
240
|
+
/** Host: everyone ready (or timed out), start. */
|
|
241
|
+
go(now) {
|
|
242
|
+
for (const m of this.members)
|
|
243
|
+
if (!this.loaded.has(m))
|
|
244
|
+
this.drop(m, 'load');
|
|
245
|
+
this.hooks.send('all', { k: 'go' });
|
|
246
|
+
this.startRunning(now);
|
|
247
|
+
for (const m of this.members)
|
|
248
|
+
this.progress.set(m, { n: -1, at: now });
|
|
249
|
+
for (let n = 0; n <= this.options.lead; n++)
|
|
250
|
+
this.broadcast();
|
|
251
|
+
this.beatAt = now + this.options.turnMs;
|
|
252
|
+
}
|
|
253
|
+
// ------------------------------------------------------------------ clock
|
|
254
|
+
/** Call every frame (or on a timer). */
|
|
255
|
+
update() {
|
|
256
|
+
if (this.closed)
|
|
257
|
+
return;
|
|
258
|
+
const o = this.options;
|
|
259
|
+
const now = this.cfg.now();
|
|
260
|
+
// This peer was frozen (loading, background page, a long frame): take the backlog first, and do not count the
|
|
261
|
+
// frozen time against others' silence or progress
|
|
262
|
+
if (this.lastUpdate >= 0 && now - this.lastUpdate > o.frozenMs)
|
|
263
|
+
this.thaw(now);
|
|
264
|
+
this.lastUpdate = now;
|
|
265
|
+
if (this.claim && now - this.claim.at >= o.staleMs && now - this.lastHost >= o.staleMs) {
|
|
266
|
+
// Our host has said nothing since someone else claimed to be host: treat it as gone
|
|
267
|
+
this.hooks.dropHost();
|
|
268
|
+
if (this.closed)
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (this.phase === 'over')
|
|
272
|
+
return;
|
|
273
|
+
if (this.isHost)
|
|
274
|
+
this.hostUpdate(now);
|
|
275
|
+
else if (now - this.lastHost >= o.silentMs) {
|
|
276
|
+
// The new host stays silent during migration: most likely only we lost the old host, which others still have
|
|
277
|
+
if (this.migrating)
|
|
278
|
+
return this.die('left');
|
|
279
|
+
this.lastHost = now;
|
|
280
|
+
this.hooks.dropHost();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
hostUpdate(now) {
|
|
284
|
+
const o = this.options;
|
|
285
|
+
if (this.mig) {
|
|
286
|
+
// Heartbeat during migration too (while loading it may wait until the load deadline, about a minute): reported
|
|
287
|
+
// members know the new host is alive, and the UI shows whom it waits for
|
|
288
|
+
if (now >= this.migBeat) {
|
|
289
|
+
this.migBeat = now + o.loadBeatMs;
|
|
290
|
+
if (this.phase === 'loading')
|
|
291
|
+
this.hooks.send('all', { k: 'load', done: [...this.loaded] });
|
|
292
|
+
else
|
|
293
|
+
this.hooks.send('all', { k: 'wait', ids: [...this.mig.left] });
|
|
294
|
+
}
|
|
295
|
+
if (now >= this.mig.until) {
|
|
296
|
+
// Not a single report: from here "everyone else dropped at once" and "we lost the network / froze and were
|
|
297
|
+
// dropped" look the same. Dropping ourselves is safer (cost: with 3+ peers, if all others really dropped at
|
|
298
|
+
// once, the last one leaves instead of continuing). A two-peer match asks nobody (asked is 0) and continues
|
|
299
|
+
if (this.mig.asked > 0 && this.mig.last.size === 0)
|
|
300
|
+
return this.die('isolated');
|
|
301
|
+
for (const id of [...this.mig.left])
|
|
302
|
+
this.drop(id, 'left');
|
|
303
|
+
}
|
|
304
|
+
this.finishMigration();
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (this.phase === 'loading') {
|
|
308
|
+
const gone = new Set(this.drops.map(d => d[0]));
|
|
309
|
+
if ([...this.members].every(m => this.loaded.has(m) || gone.has(m)) || now >= this.loadUntil)
|
|
310
|
+
return this.go(now);
|
|
311
|
+
if (now >= this.loadBeat) {
|
|
312
|
+
this.loadBeat = now + o.loadBeatMs;
|
|
313
|
+
this.hooks.send('all', { k: 'load', done: [...this.loaded] });
|
|
314
|
+
}
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const dt = this.lastCheck >= 0 ? Math.min(500, now - this.lastCheck) : 0;
|
|
318
|
+
this.lastCheck = now;
|
|
319
|
+
const blockers = [...this.members].filter(m => (this.progress.get(m)?.n ?? -1) < this.nextTurn - o.lagTurns);
|
|
320
|
+
// Accumulate halt time (decaying at half speed when not halted): intermittent persistent lag counts, a single hiccup does not
|
|
321
|
+
if (blockers.length) {
|
|
322
|
+
this.haltMs += dt;
|
|
323
|
+
for (const b of blockers)
|
|
324
|
+
this.blockedAt.set(b, now);
|
|
325
|
+
}
|
|
326
|
+
else
|
|
327
|
+
this.haltMs = Math.max(0, this.haltMs - dt / 2);
|
|
328
|
+
const show = this.haltMs >= o.waitShowMs ? [...this.members].filter(m => now - (this.blockedAt.get(m) ?? -Infinity) < o.waitKeepMs) : [];
|
|
329
|
+
const changed = show.length !== this.waiting.length || show.some((v, i) => v !== this.waiting[i]);
|
|
330
|
+
// The wait list doubles as the heartbeat while halted: resend it periodically while it is not empty
|
|
331
|
+
if (changed || (show.length && now - this.waitSent >= o.waitBeatMs)) {
|
|
332
|
+
this.waitSent = now;
|
|
333
|
+
this.setWaiting(show);
|
|
334
|
+
this.hooks.send('all', { k: 'wait', ids: show });
|
|
335
|
+
}
|
|
336
|
+
if (blockers.length) {
|
|
337
|
+
this.halted = true;
|
|
338
|
+
for (const b of blockers) {
|
|
339
|
+
if (b !== this.self && now - (this.progress.get(b)?.at ?? now) >= o.stallMs)
|
|
340
|
+
this.drop(b, 'stall');
|
|
341
|
+
}
|
|
342
|
+
// Drops travel in turns: send one turn when drops are pending (laggards just hold one more turn)
|
|
343
|
+
if (this.drops.length)
|
|
344
|
+
this.broadcast();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (this.halted) {
|
|
348
|
+
this.halted = false;
|
|
349
|
+
this.beatAt = now;
|
|
350
|
+
}
|
|
351
|
+
// Too many beats behind (the page froze): do not send a burst, restart the beat from now
|
|
352
|
+
if (now - this.beatAt > o.turnMs * 3)
|
|
353
|
+
this.beatAt = now;
|
|
354
|
+
while (now >= this.beatAt) {
|
|
355
|
+
this.broadcast();
|
|
356
|
+
this.beatAt += o.turnMs;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
thaw(now) {
|
|
360
|
+
this.lastHost = Math.max(this.lastHost, now);
|
|
361
|
+
for (const p of this.progress.values())
|
|
362
|
+
p.at = Math.max(p.at, now);
|
|
363
|
+
if (this.claim)
|
|
364
|
+
this.claim.at = now;
|
|
365
|
+
if (this.mig)
|
|
366
|
+
this.mig.until = Math.max(this.mig.until, now + this.options.migrateMs);
|
|
367
|
+
this.lastCheck = now;
|
|
368
|
+
}
|
|
369
|
+
/** The page went to the background / came back: away longer than `silentMs` drops this peer (`hidden`). */
|
|
370
|
+
visibility(hidden) {
|
|
371
|
+
const now = this.cfg.now();
|
|
372
|
+
if (hidden) {
|
|
373
|
+
this.hiddenAt = now;
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const away = this.hiddenAt >= 0 ? now - this.hiddenAt : 0;
|
|
377
|
+
this.hiddenAt = -1;
|
|
378
|
+
if (away >= this.options.silentMs && this.phase === 'running' && this.members.size > 1)
|
|
379
|
+
this.die('hidden');
|
|
380
|
+
}
|
|
381
|
+
/** This peer's match is over (results screen): stop ordering and stop checking the host's silence. */
|
|
382
|
+
finish() {
|
|
383
|
+
this.phase = 'over';
|
|
384
|
+
this.claim = null;
|
|
385
|
+
}
|
|
386
|
+
close() {
|
|
387
|
+
this.closed = true;
|
|
388
|
+
}
|
|
389
|
+
// ------------------------------------------------------------------ host: ordering
|
|
390
|
+
/** Host accepts a command: deduplicate a member's by sequence number (resends are not taken twice) and authorize; own ones are not checked. */
|
|
391
|
+
accept(from, s, d) {
|
|
392
|
+
if (from !== this.self) {
|
|
393
|
+
if ((this.accepted.get(from) ?? 0) >= s)
|
|
394
|
+
return;
|
|
395
|
+
this.accepted.set(from, s);
|
|
396
|
+
if (!this.cfg.authorize(from, d))
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
this.inbox.push([from, s, d]);
|
|
400
|
+
}
|
|
401
|
+
/** Send the next turn (command data beyond `turnBytes` waits for later turns). */
|
|
402
|
+
broadcast() {
|
|
403
|
+
const { turnBytes, entryBytes } = this.options;
|
|
404
|
+
let bytes = 0, k = 0;
|
|
405
|
+
const size = (e) => e[2].length + entryBytes;
|
|
406
|
+
while (k < this.inbox.length && (k === 0 || bytes + size(this.inbox[k]) <= turnBytes))
|
|
407
|
+
bytes += size(this.inbox[k++]);
|
|
408
|
+
const t = { n: this.nextTurn++, c: this.inbox.splice(0, k) };
|
|
409
|
+
if (this.drops.length)
|
|
410
|
+
t.drop = this.drops.splice(0);
|
|
411
|
+
try {
|
|
412
|
+
this.hooks.send('all', { k: 'turn', t });
|
|
413
|
+
}
|
|
414
|
+
catch (e) {
|
|
415
|
+
// A failed send (for example over the connection layer's message limit) must not throw into the main loop;
|
|
416
|
+
// the turn is still recorded, members that missed it fall behind and are eventually dropped
|
|
417
|
+
console.error('[lockstep] failed to send turn', e);
|
|
418
|
+
}
|
|
419
|
+
this.addTurn(t);
|
|
420
|
+
}
|
|
421
|
+
/** The game's system commands for a drop, sequenced as the host's own. */
|
|
422
|
+
dropCommands(id, reason) {
|
|
423
|
+
const cmds = this.cfg.dropCommands?.(id, reason) ?? [];
|
|
424
|
+
return cmds.map(d => [this.self, ++this.seq, d]);
|
|
425
|
+
}
|
|
426
|
+
/** Host: announce that `id` is dropped (in the next turn), with the game's drop commands in the same turn. */
|
|
427
|
+
drop(id, reason) {
|
|
428
|
+
if (!this.isHost || id === this.self || !this.members.has(id) || this.drops.some(d => d[0] === id))
|
|
429
|
+
return;
|
|
430
|
+
this.drops.push([id, reason]);
|
|
431
|
+
this.inbox.push(...this.dropCommands(id, reason));
|
|
432
|
+
this.hooks.send(id, { k: 'kicked', reason });
|
|
433
|
+
this.mig?.left.delete(id);
|
|
434
|
+
}
|
|
435
|
+
setProgress(id, n) {
|
|
436
|
+
const p = this.progress.get(id);
|
|
437
|
+
if (!p || n > p.n)
|
|
438
|
+
this.progress.set(id, { n, at: this.cfg.now() });
|
|
439
|
+
}
|
|
440
|
+
addSum(n, id, v) {
|
|
441
|
+
if (!this.members.has(id))
|
|
442
|
+
return;
|
|
443
|
+
let m = this.sums.get(n);
|
|
444
|
+
if (!m)
|
|
445
|
+
this.sums.set(n, (m = new Map()));
|
|
446
|
+
m.set(id, v);
|
|
447
|
+
const mine = m.get(this.self);
|
|
448
|
+
if (mine !== undefined) {
|
|
449
|
+
for (const [who, val] of m) {
|
|
450
|
+
if (who === this.self)
|
|
451
|
+
continue;
|
|
452
|
+
if (val !== mine)
|
|
453
|
+
this.drop(who, 'desync');
|
|
454
|
+
m.delete(who);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
// Keep only recent ones
|
|
458
|
+
for (const k of this.sums.keys())
|
|
459
|
+
if (k < n - this.options.checkTurns * 20)
|
|
460
|
+
this.sums.delete(k);
|
|
461
|
+
}
|
|
462
|
+
// ------------------------------------------------------------------ receiving turns
|
|
463
|
+
/** Take a turn (in order only: with a gap it is not taken; the new host fills gaps during migration). */
|
|
464
|
+
addTurn(t) {
|
|
465
|
+
if (t.n !== this.recv + 1)
|
|
466
|
+
return;
|
|
467
|
+
this.turns.set(t.n, t);
|
|
468
|
+
this.recv = t.n;
|
|
469
|
+
// Keep turns not yet simulated
|
|
470
|
+
const keep = this.options.keepTurns;
|
|
471
|
+
if (t.n - keep < this.turn)
|
|
472
|
+
this.turns.delete(t.n - keep);
|
|
473
|
+
for (const [from, s] of t.c)
|
|
474
|
+
if ((this.seen.get(from) ?? 0) < s)
|
|
475
|
+
this.seen.set(from, s);
|
|
476
|
+
const mine = this.seen.get(this.self) ?? 0;
|
|
477
|
+
if (this.pending.length && this.pending[0].s <= mine)
|
|
478
|
+
this.pending = this.pending.filter(p => p.s > mine);
|
|
479
|
+
for (const [id, raw] of t.drop ?? []) {
|
|
480
|
+
const reason = dropReason(raw);
|
|
481
|
+
// Members already gone and awaiting announcement (old hosts removed earlier) are reported once too; members in
|
|
482
|
+
// neither set were reported already
|
|
483
|
+
const pending = this.unannounced.delete(id);
|
|
484
|
+
if (id === this.self) {
|
|
485
|
+
this.die(reason);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
const member = this.members.delete(id);
|
|
489
|
+
if (!member && !pending)
|
|
490
|
+
continue;
|
|
491
|
+
this.progress.delete(id);
|
|
492
|
+
this.waiting = this.waiting.filter(w => w !== id);
|
|
493
|
+
this.hooks.dropped(id, reason);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// ------------------------------------------------------------------ messages
|
|
497
|
+
/** A lockstep message from member `from` (validated here; malformed messages are ignored). */
|
|
498
|
+
receive(from, m) {
|
|
499
|
+
if (this.closed || typeof m !== 'object' || m === null)
|
|
500
|
+
return;
|
|
501
|
+
if (from === this.host)
|
|
502
|
+
this.lastHost = this.cfg.now();
|
|
503
|
+
if (this.claim && from === this.host && !this.isHost) {
|
|
504
|
+
// Our host still talks: the claimant is the one that lost the old host
|
|
505
|
+
this.hooks.send(this.claim.from, { k: 'stale' });
|
|
506
|
+
this.claim = null;
|
|
507
|
+
}
|
|
508
|
+
switch (m.k) {
|
|
509
|
+
case 'stale':
|
|
510
|
+
// Honoured only shortly after becoming host through migration, and only from members this migration waits
|
|
511
|
+
// for or heard from: a host from the start ignores it, so no member can make the host quit with one message
|
|
512
|
+
if (this.isHost && this.hostSince >= 0 && this.cfg.now() - this.hostSince < this.options.silentMs
|
|
513
|
+
&& (this.mig?.left.has(from) || this.reportedBy.has(from)))
|
|
514
|
+
this.die('left');
|
|
515
|
+
return;
|
|
516
|
+
case 'kicked':
|
|
517
|
+
if (from === this.host)
|
|
518
|
+
this.die(dropReason(m.reason));
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
if (this.isHost)
|
|
522
|
+
return this.hostReceive(from, m);
|
|
523
|
+
// Below: received as a member
|
|
524
|
+
const hostOnly = m.k === 'turn' || m.k === 'wait' || m.k === 'mig' || m.k === 'load' || m.k === 'go';
|
|
525
|
+
if (hostOnly && from !== this.host) {
|
|
526
|
+
if (!this.members.has(from))
|
|
527
|
+
return;
|
|
528
|
+
if (!this.claim || this.claim.from !== from)
|
|
529
|
+
this.claim = { from, at: this.cfg.now(), msgs: [] };
|
|
530
|
+
this.claim.msgs.push(m);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
switch (m.k) {
|
|
534
|
+
case 'turn':
|
|
535
|
+
if (m.t && Array.isArray(m.t.c) && Number.isInteger(m.t.n)) {
|
|
536
|
+
// A turn while loading: the host has started (go was missed, or the old host left right after sending it)
|
|
537
|
+
if (this.phase === 'loading')
|
|
538
|
+
this.startRunning(this.cfg.now());
|
|
539
|
+
this.addTurn(m.t);
|
|
540
|
+
if (this.migrating) {
|
|
541
|
+
this.migrating = false;
|
|
542
|
+
// The wait list from migration heartbeats (members yet to report) is stale now
|
|
543
|
+
this.waiting = [];
|
|
544
|
+
this.hooks.status();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
break;
|
|
548
|
+
case 'wait':
|
|
549
|
+
if (Array.isArray(m.ids))
|
|
550
|
+
this.setWaiting(m.ids.filter(id => this.members.has(id)));
|
|
551
|
+
break;
|
|
552
|
+
case 'mig':
|
|
553
|
+
this.reportTo(from, m.last);
|
|
554
|
+
break;
|
|
555
|
+
case 'load':
|
|
556
|
+
if (Array.isArray(m.done)) {
|
|
557
|
+
this.loaded = new Set(m.done);
|
|
558
|
+
this.hooks.status();
|
|
559
|
+
}
|
|
560
|
+
break;
|
|
561
|
+
case 'go':
|
|
562
|
+
if (this.phase === 'loading')
|
|
563
|
+
this.startRunning(this.cfg.now());
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
hostReceive(from, m) {
|
|
568
|
+
if (!this.members.has(from))
|
|
569
|
+
return;
|
|
570
|
+
switch (m.k) {
|
|
571
|
+
case 'cmd':
|
|
572
|
+
if (!Number.isInteger(m.s) || typeof m.d !== 'string')
|
|
573
|
+
return;
|
|
574
|
+
if (this.mig)
|
|
575
|
+
this.mig.held.push([from, m.s, m.d]);
|
|
576
|
+
else
|
|
577
|
+
this.accept(from, m.s, m.d);
|
|
578
|
+
break;
|
|
579
|
+
case 'at':
|
|
580
|
+
if (Number.isInteger(m.n))
|
|
581
|
+
this.setProgress(from, m.n);
|
|
582
|
+
break;
|
|
583
|
+
case 'sum':
|
|
584
|
+
if (Number.isInteger(m.n) && Number.isInteger(m.v))
|
|
585
|
+
this.addSum(m.n, from, m.v);
|
|
586
|
+
break;
|
|
587
|
+
case 'loaded':
|
|
588
|
+
if (this.phase === 'loading') {
|
|
589
|
+
this.loaded.add(from);
|
|
590
|
+
this.hooks.status();
|
|
591
|
+
}
|
|
592
|
+
break;
|
|
593
|
+
case 'old':
|
|
594
|
+
if (this.mig && m.t && Number.isInteger(m.t.n))
|
|
595
|
+
this.addTurn(m.t);
|
|
596
|
+
break;
|
|
597
|
+
case 'rep':
|
|
598
|
+
if (this.mig && this.mig.left.delete(from)) {
|
|
599
|
+
this.reportedBy.add(from);
|
|
600
|
+
this.mig.last.set(from, Number.isInteger(m.last) ? m.last : -1);
|
|
601
|
+
this.setProgress(from, Number.isInteger(m.done) ? m.done : -1);
|
|
602
|
+
// New host still loading while this member runs: the old host sent go, start from its progress (no more
|
|
603
|
+
// waiting for everyone, no resend of the opening turns)
|
|
604
|
+
if (m.run && this.phase === 'loading') {
|
|
605
|
+
this.loaded.add(from);
|
|
606
|
+
this.startRunning(this.cfg.now());
|
|
607
|
+
for (const id of this.members)
|
|
608
|
+
if (!this.progress.has(id))
|
|
609
|
+
this.progress.set(id, { n: -1, at: this.cfg.now() });
|
|
610
|
+
}
|
|
611
|
+
this.finishMigration();
|
|
612
|
+
}
|
|
613
|
+
break;
|
|
614
|
+
case 'turn':
|
|
615
|
+
case 'mig':
|
|
616
|
+
case 'wait':
|
|
617
|
+
// Someone else speaks as host: the migration came from our link to the old host breaking; theirs is alive
|
|
618
|
+
this.hooks.send(from, { k: 'stale' });
|
|
619
|
+
break;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/** The connection layer lost a member (host changes go through `hostChanged`): the host drops it, members await the verdict. */
|
|
623
|
+
memberLost(id) {
|
|
624
|
+
if (this.isHost) {
|
|
625
|
+
this.drop(id, 'left');
|
|
626
|
+
if (this.mig)
|
|
627
|
+
this.finishMigration();
|
|
628
|
+
}
|
|
629
|
+
else if (this.members.has(id)) {
|
|
630
|
+
// Wait for the host's announcement; if the host leaves before announcing, the new host announces it
|
|
631
|
+
this.unannounced.add(id);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
// ------------------------------------------------------------------ host migration
|
|
635
|
+
/** The connection layer's host changed (the old host is already removed from its member list). */
|
|
636
|
+
hostChanged(id) {
|
|
637
|
+
if (this.closed || id === this.host)
|
|
638
|
+
return;
|
|
639
|
+
const old = this.host;
|
|
640
|
+
this.host = id;
|
|
641
|
+
// The old host left but its drop is not in a turn yet: remember it, whoever becomes host announces it (none is
|
|
642
|
+
// missed when several hosts drop in a row)
|
|
643
|
+
if (this.members.has(old))
|
|
644
|
+
this.unannounced.add(old);
|
|
645
|
+
this.members.delete(old);
|
|
646
|
+
this.progress.delete(old);
|
|
647
|
+
this.waiting = this.waiting.filter(w => w !== old);
|
|
648
|
+
this.lastHost = this.cfg.now();
|
|
649
|
+
if (this.phase === 'over')
|
|
650
|
+
return;
|
|
651
|
+
this.migrating = true;
|
|
652
|
+
this.reported = false;
|
|
653
|
+
const claim = this.claim;
|
|
654
|
+
this.claim = null;
|
|
655
|
+
if (id === this.self) {
|
|
656
|
+
const now = this.cfg.now();
|
|
657
|
+
const o = this.options;
|
|
658
|
+
const left = new Set([...this.members].filter(m => m !== this.self && !this.unannounced.has(m)));
|
|
659
|
+
// Migration while loading: members may still be building their world (a phone can freeze for many seconds)
|
|
660
|
+
// and cannot report; wait until the load deadline
|
|
661
|
+
const wait = this.phase === 'loading' ? Math.max(o.migrateMs, this.loadUntil - now) : o.migrateMs;
|
|
662
|
+
this.mig = { left, asked: left.size, until: now + wait, last: new Map(), held: [], gone: new Map() };
|
|
663
|
+
this.hostSince = now;
|
|
664
|
+
this.reportedBy.clear();
|
|
665
|
+
// Migration while loading: members say again whether they are ready when they report
|
|
666
|
+
this.loaded = new Set(this.selfReady ? [this.self] : []);
|
|
667
|
+
this.nextTurn = this.recv + 1;
|
|
668
|
+
this.hooks.send('all', { k: 'mig', last: this.recv });
|
|
669
|
+
// Members gone but unannounced (the old host and earlier hosts that dropped together): announce them with
|
|
670
|
+
// their drop commands in the first new turn (sent after migration completes)
|
|
671
|
+
for (const gone of this.unannounced) {
|
|
672
|
+
if (this.drops.some(d => d[0] === gone))
|
|
673
|
+
continue;
|
|
674
|
+
this.drops.push([gone, 'left']);
|
|
675
|
+
const cmds = this.dropCommands(gone, 'left');
|
|
676
|
+
this.mig.held.push(...cmds);
|
|
677
|
+
this.mig.gone.set(gone, cmds.map(e => e[1]));
|
|
678
|
+
}
|
|
679
|
+
this.setProgress(this.self, this.turn - 1);
|
|
680
|
+
this.finishMigration();
|
|
681
|
+
}
|
|
682
|
+
else if (claim && claim.from === id) {
|
|
683
|
+
for (const m of claim.msgs)
|
|
684
|
+
this.receive(id, m);
|
|
685
|
+
}
|
|
686
|
+
this.hooks.status();
|
|
687
|
+
}
|
|
688
|
+
/** Member: report to the new host, send it the turns it lacks, and resend commands not yet seen in a turn. */
|
|
689
|
+
reportTo(host, last) {
|
|
690
|
+
for (let n = Math.max(last + 1, this.recv - this.options.keepTurns + 1); n <= this.recv; n++) {
|
|
691
|
+
const t = this.turns.get(n);
|
|
692
|
+
if (t)
|
|
693
|
+
this.hooks.send(host, { k: 'old', t });
|
|
694
|
+
}
|
|
695
|
+
this.hooks.send(host, { k: 'rep', last: this.recv, done: this.turn - 1, run: this.phase === 'running' });
|
|
696
|
+
if (this.phase === 'loading' && this.selfReady)
|
|
697
|
+
this.hooks.send(host, { k: 'loaded' });
|
|
698
|
+
for (const p of this.pending)
|
|
699
|
+
this.hooks.send(host, { k: 'cmd', s: p.s, d: p.d });
|
|
700
|
+
this.reported = true;
|
|
701
|
+
}
|
|
702
|
+
/** New host: once all reports are in (or timed out), resend turns and continue ordering. */
|
|
703
|
+
finishMigration() {
|
|
704
|
+
const mg = this.mig;
|
|
705
|
+
if (!mg || mg.left.size)
|
|
706
|
+
return;
|
|
707
|
+
this.mig = null;
|
|
708
|
+
// Drops already announced in old turns received during migration (no longer unannounced): withdraw the prepared
|
|
709
|
+
// drop and its commands to avoid duplicates
|
|
710
|
+
for (const [id, seqs] of mg.gone) {
|
|
711
|
+
if (this.unannounced.has(id))
|
|
712
|
+
continue;
|
|
713
|
+
this.drops = this.drops.filter(d => d[0] !== id);
|
|
714
|
+
if (seqs.length)
|
|
715
|
+
mg.held = mg.held.filter(e => !(e[0] === this.self && seqs.includes(e[1])));
|
|
716
|
+
}
|
|
717
|
+
const keep = this.options.keepTurns;
|
|
718
|
+
for (const [id, last] of mg.last) {
|
|
719
|
+
if (!this.members.has(id))
|
|
720
|
+
continue;
|
|
721
|
+
for (let n = Math.max(last + 1, this.recv - keep + 1); n <= this.recv; n++) {
|
|
722
|
+
const t = this.turns.get(n);
|
|
723
|
+
if (t)
|
|
724
|
+
this.hooks.send(id, { k: 'turn', t });
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
this.nextTurn = this.recv + 1;
|
|
728
|
+
// Sequence numbers up to those already seen are not taken again (resends are deduplicated)
|
|
729
|
+
for (const [from, s] of this.seen)
|
|
730
|
+
this.accepted.set(from, Math.max(this.accepted.get(from) ?? 0, s));
|
|
731
|
+
// Own commands not yet seen in a turn (sent to the old host as a member before migration)
|
|
732
|
+
for (const p of this.pending)
|
|
733
|
+
this.accept(this.self, p.s, p.d);
|
|
734
|
+
for (const [from, s, d] of mg.held)
|
|
735
|
+
this.accept(from, s, d);
|
|
736
|
+
if (this.phase !== 'loading') {
|
|
737
|
+
// Continue ordering: send a turn at once, announcing the old host's drop and its drop commands
|
|
738
|
+
this.broadcast();
|
|
739
|
+
this.beatAt = this.cfg.now() + this.options.turnMs;
|
|
740
|
+
}
|
|
741
|
+
this.migrating = false;
|
|
742
|
+
// Migration heartbeats carried a wait list (members yet to report): clear it explicitly so members stop showing it
|
|
743
|
+
this.waiting = [];
|
|
744
|
+
this.hooks.send('all', { k: 'wait', ids: [] });
|
|
745
|
+
this.hooks.status();
|
|
746
|
+
}
|
|
747
|
+
// ------------------------------------------------------------------ misc
|
|
748
|
+
setWaiting(ids) {
|
|
749
|
+
if (ids.length === this.waiting.length && ids.every((v, i) => v === this.waiting[i]))
|
|
750
|
+
return;
|
|
751
|
+
this.waiting = ids;
|
|
752
|
+
this.hooks.status();
|
|
753
|
+
}
|
|
754
|
+
die(reason) {
|
|
755
|
+
if (this.closed)
|
|
756
|
+
return;
|
|
757
|
+
this.closed = true;
|
|
758
|
+
this.hooks.selfDropped(reason);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/** Margin (slots) above which `frameSteps` speeds up to catch up: (lead + 1) × turnTicks. */
|
|
762
|
+
export function catchupSlots(options = {}) {
|
|
763
|
+
const d = DEFAULT_LOCKSTEP_OPTIONS;
|
|
764
|
+
return ((options.lead ?? d.lead) + 1) * (options.turnTicks ?? d.turnTicks);
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* How many slots to advance this frame: `acc` is accumulated simulation time (s), `dt` the step length (s), `avail`
|
|
768
|
+
* the slots in hand (`Lockstep.available()`). Pass `lockstep.options` when the scheduler uses non-default options.
|
|
769
|
+
* Returns the steps and the remaining accumulated time.
|
|
770
|
+
*/
|
|
771
|
+
export function frameSteps(acc, dt, avail, options = {}) {
|
|
772
|
+
const catchup = catchupSlots(options);
|
|
773
|
+
const normal = Math.floor(acc / dt);
|
|
774
|
+
const extra = avail > catchup ? Math.ceil((avail - catchup) / 2) : 0;
|
|
775
|
+
const steps = Math.min(avail, normal + extra, options.maxFrameSteps ?? DEFAULT_LOCKSTEP_OPTIONS.maxFrameSteps);
|
|
776
|
+
// Starved (turn not here yet): do not build up debt, keep at most one step; catch-up makes up the rest later
|
|
777
|
+
const left = Math.min(acc - Math.min(steps, normal) * dt, dt);
|
|
778
|
+
return { steps, acc: Math.max(0, left) };
|
|
779
|
+
}
|