tickflare 0.0.0-stage → 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.
Files changed (125) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/buffered.d.ts +88 -0
  11. package/dist/client/buffered.js +229 -0
  12. package/dist/client/buffered.js.map +1 -0
  13. package/dist/client/clock.d.ts +36 -0
  14. package/dist/client/clock.js +83 -0
  15. package/dist/client/clock.js.map +1 -0
  16. package/dist/client/draft.d.ts +17 -0
  17. package/dist/client/draft.js +133 -0
  18. package/dist/client/draft.js.map +1 -0
  19. package/dist/client/index.d.ts +182 -0
  20. package/dist/client/index.js +496 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/interpolate.d.ts +31 -0
  23. package/dist/client/interpolate.js +59 -0
  24. package/dist/client/interpolate.js.map +1 -0
  25. package/dist/client/lockstep.d.ts +86 -0
  26. package/dist/client/lockstep.js +339 -0
  27. package/dist/client/lockstep.js.map +1 -0
  28. package/dist/client/matchmaking.d.ts +21 -0
  29. package/dist/client/matchmaking.js +55 -0
  30. package/dist/client/matchmaking.js.map +1 -0
  31. package/dist/client/pacer.d.ts +22 -0
  32. package/dist/client/pacer.js +65 -0
  33. package/dist/client/pacer.js.map +1 -0
  34. package/dist/client/predict.d.ts +75 -0
  35. package/dist/client/predict.js +203 -0
  36. package/dist/client/predict.js.map +1 -0
  37. package/dist/client/token.d.ts +10 -0
  38. package/dist/client/token.js +15 -0
  39. package/dist/client/token.js.map +1 -0
  40. package/dist/lockstep.d.ts +154 -0
  41. package/dist/lockstep.js +140 -0
  42. package/dist/lockstep.js.map +1 -0
  43. package/dist/patch.d.ts +54 -0
  44. package/dist/patch.js +186 -0
  45. package/dist/patch.js.map +1 -0
  46. package/dist/protocol.d.ts +268 -0
  47. package/dist/protocol.js +54 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/dist/server/accounts.d.ts +320 -0
  50. package/dist/server/accounts.js +1223 -0
  51. package/dist/server/accounts.js.map +1 -0
  52. package/dist/server/delta.d.ts +50 -0
  53. package/dist/server/delta.js +426 -0
  54. package/dist/server/delta.js.map +1 -0
  55. package/dist/server/frames.d.ts +15 -0
  56. package/dist/server/frames.js +23 -0
  57. package/dist/server/frames.js.map +1 -0
  58. package/dist/server/gateway.d.ts +80 -0
  59. package/dist/server/gateway.js +144 -0
  60. package/dist/server/gateway.js.map +1 -0
  61. package/dist/server/index.d.ts +21 -0
  62. package/dist/server/index.js +22 -0
  63. package/dist/server/index.js.map +1 -0
  64. package/dist/server/limiter.d.ts +12 -0
  65. package/dist/server/limiter.js +43 -0
  66. package/dist/server/limiter.js.map +1 -0
  67. package/dist/server/lockstep.d.ts +127 -0
  68. package/dist/server/lockstep.js +549 -0
  69. package/dist/server/lockstep.js.map +1 -0
  70. package/dist/server/matches.d.ts +31 -0
  71. package/dist/server/matches.js +69 -0
  72. package/dist/server/matches.js.map +1 -0
  73. package/dist/server/matchmaker.d.ts +121 -0
  74. package/dist/server/matchmaker.js +479 -0
  75. package/dist/server/matchmaker.js.map +1 -0
  76. package/dist/server/room.d.ts +402 -0
  77. package/dist/server/room.js +1896 -0
  78. package/dist/server/room.js.map +1 -0
  79. package/dist/server/signals.d.ts +18 -0
  80. package/dist/server/signals.js +37 -0
  81. package/dist/server/signals.js.map +1 -0
  82. package/dist/server/storage.d.ts +117 -0
  83. package/dist/server/storage.js +330 -0
  84. package/dist/server/storage.js.map +1 -0
  85. package/dist/server/tokens.d.ts +74 -0
  86. package/dist/server/tokens.js +117 -0
  87. package/dist/server/tokens.js.map +1 -0
  88. package/dist/server/tracked.d.ts +47 -0
  89. package/dist/server/tracked.js +270 -0
  90. package/dist/server/tracked.js.map +1 -0
  91. package/dist/world.d.ts +20 -0
  92. package/dist/world.js +21 -0
  93. package/dist/world.js.map +1 -0
  94. package/package.json +74 -4
  95. package/src/binary.ts +496 -0
  96. package/src/client/accounts.ts +423 -0
  97. package/src/client/buffered.ts +264 -0
  98. package/src/client/clock.ts +86 -0
  99. package/src/client/draft.ts +138 -0
  100. package/src/client/index.ts +631 -0
  101. package/src/client/interpolate.ts +60 -0
  102. package/src/client/lockstep.ts +398 -0
  103. package/src/client/matchmaking.ts +61 -0
  104. package/src/client/pacer.ts +67 -0
  105. package/src/client/predict.ts +239 -0
  106. package/src/client/token.ts +22 -0
  107. package/src/lockstep.ts +285 -0
  108. package/src/patch.ts +188 -0
  109. package/src/protocol.ts +300 -0
  110. package/src/server/accounts.ts +1474 -0
  111. package/src/server/delta.ts +467 -0
  112. package/src/server/frames.ts +23 -0
  113. package/src/server/gateway.ts +213 -0
  114. package/src/server/index.ts +86 -0
  115. package/src/server/limiter.ts +41 -0
  116. package/src/server/lockstep.ts +617 -0
  117. package/src/server/matches.ts +99 -0
  118. package/src/server/matchmaker.ts +537 -0
  119. package/src/server/room.ts +1999 -0
  120. package/src/server/signals.ts +46 -0
  121. package/src/server/storage.ts +392 -0
  122. package/src/server/tokens.ts +184 -0
  123. package/src/server/tracked.ts +260 -0
  124. package/src/world.ts +29 -0
  125. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,617 @@
1
+ import type { CatchUp, LockstepView, Replay, Snapshot, TurnEntry, TurnsMessage } from "../lockstep.js";
2
+ import type { Player } from "../protocol.js";
3
+ import { Room, patchEachTick, reject } from "./room.js";
4
+ import { pieces } from "./storage.js";
5
+
6
+ /** What a lockstep room keeps: what clients see, and the inputs waiting for the next turn. */
7
+ export interface LockstepState<Input> extends LockstepView<Input> {
8
+ /** Inputs and events waiting for the next turn. Not sent to clients. */
9
+ pending: TurnEntry<Input>[];
10
+ }
11
+
12
+ /**
13
+ * What a `LockstepClient` sends: an input (`i`), its simulation's hash after
14
+ * turn `n` (`h`), or, to a room whose `turnClock` is `"players"`, a request
15
+ * to close the turns that are due (`t`).
16
+ */
17
+ export type LockstepCommand<Input> =
18
+ | {
19
+ /** A request to close the turns that are due. */
20
+ k: "t";
21
+ }
22
+ | {
23
+ /** An input. */
24
+ k: "i";
25
+ /** The input, before `parseInput`. */
26
+ d: Input;
27
+ }
28
+ | {
29
+ /** A hash of the client's simulation. */
30
+ k: "h";
31
+ /** The turn the simulation was at. */
32
+ n: number;
33
+ /** The hash. */
34
+ h: string;
35
+ };
36
+
37
+ /** How many turns' worth of reported hashes are kept for comparison. */
38
+ const HASHES_KEPT = 128;
39
+
40
+ /** How many snapshot turns' hashes are kept, for a snapshot that takes a while to arrive. */
41
+ const SNAPSHOT_TURNS_KEPT = 4;
42
+
43
+ /**
44
+ * With players asking for the turns: the most one request may close. If
45
+ * nobody asked for longer than this many turns, the game stood still for the
46
+ * rest of that time.
47
+ */
48
+ const MOST_TURNS_AT_ONCE = 30;
49
+
50
+ /**
51
+ * A lockstep room. It never runs the game: it validates inputs, orders them
52
+ * into turns at `tickRate` turns a second, records every turn in which
53
+ * something happened, and sends all players the same stream. Players coming
54
+ * and going are part of that stream, so every simulation sees them at the
55
+ * same turn.
56
+ *
57
+ * The recording is served at `{prefix}/{roomId}/replay`. Clients read it when
58
+ * they (re)connect, to catch up, and it doubles as the match replay.
59
+ *
60
+ * By default the room closes the turns itself, on a timer, and so is awake
61
+ * and billed for as long as the match lasts. Set `turnClock = "players"` and
62
+ * it sleeps between turns instead: see `turnClock`.
63
+ *
64
+ * If you override `onJoin`, `onDisconnect` or `onReconnect`, call `super` so
65
+ * the event still reaches the turn stream. A seat that is given up, whether
66
+ * the player left, timed out or was removed with `removePlayer`, is
67
+ * announced to the stream for you.
68
+ */
69
+ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
70
+ LockstepState<Input>,
71
+ LockstepCommand<Input>,
72
+ Env
73
+ > {
74
+ /** Turns per second. */
75
+ protected override tickRate = 10;
76
+
77
+ /** Inputs one player may send within a single turn. More are refused. */
78
+ protected maxInputsPerTurn = 32;
79
+
80
+ /**
81
+ * Who keeps time.
82
+ *
83
+ * `"room"`: the room closes a turn every `1 / tickRate` seconds on a timer
84
+ * of its own. It is awake for the whole match.
85
+ *
86
+ * `"players"`: the room has no timer. `LockstepClient` asks it for each
87
+ * turn as it falls due, one player's client at a time, and the room closes
88
+ * as many turns as its own clock says have passed, never more: a player
89
+ * can neither speed the game up nor hold it back while anyone else is
90
+ * connected. Between requests the room is asleep, which is most of the
91
+ * time. Orders take effect as soon as they do with `"room"`. Two things
92
+ * differ: the game stands still while nobody is connected to ask, and after
93
+ * a restart it skips ahead by up to `saveIntervalMs` of empty turns instead
94
+ * of going back by as much.
95
+ */
96
+ protected turnClock: "room" | "players" = "room";
97
+
98
+ /**
99
+ * How often the room takes a snapshot of the simulation from its players,
100
+ * so that someone who joins, reloads or reconnects late starts from it and
101
+ * not from turn 1. 0 keeps none.
102
+ *
103
+ * The room has no simulation of its own. A snapshot is what one player's
104
+ * client saved, with `save`, at a turn every client agrees on, and it is
105
+ * kept once the hash it came with is the one another connected player
106
+ * reported for that turn; a player who is alone is taken at their word.
107
+ * The client that loads it hashes the result again before trusting it.
108
+ * Clients whose simulation has no `save`, `load` and `hash` send none and
109
+ * load none, and catch up from the recording as before.
110
+ *
111
+ * Only the latest is kept. The recording is not shortened: it is still the
112
+ * whole match.
113
+ */
114
+ protected snapshotIntervalMs = 60_000;
115
+
116
+ /** The longest snapshot the room keeps, in characters of JSON. A longer one is refused. */
117
+ protected maxSnapshotLength = 8_000_000;
118
+
119
+ #resumed = false;
120
+ // With players asking for the turns, none of this is in `state`: a change to the state is a
121
+ // row written and a frame to everyone, and here turns change ten times a second.
122
+ /** The latest turn. `state.turn` is a checkpoint of it, written every `saveIntervalMs`. */
123
+ #turn = 0;
124
+ /** What happened in the latest turn. */
125
+ #entries: TurnEntry<Input>[] = [];
126
+ /** Inputs and events waiting for the next turn. */
127
+ #waiting: TurnEntry<Input>[] = [];
128
+ /** A moment and the turn that was current then: what "due" is counted from. */
129
+ #since: { at: number; turn: number } | undefined;
130
+ /** Turns to pass over at the next close, so that no number a player may have seen is used again. */
131
+ #skip = 0;
132
+ /** The first hash reported for each recent turn, and who reported it. */
133
+ #hashes = new Map<number, { hash: string; by: string }>();
134
+ /** For the latest turns a snapshot could be of: the first hash reported, and everyone who reported that one. */
135
+ #vouched = new Map<number, { hash: string; by: Set<string> }>();
136
+ /** A snapshot that has arrived and waits for the other players to report its hash, and who sent it. */
137
+ #candidate: (Snapshot & { by: string }) | undefined;
138
+ /** Names this run of the room: see `CatchUp.epoch`. */
139
+ #epoch: string | undefined;
140
+
141
+ constructor(ctx: DurableObjectState, env: Env) {
142
+ super(ctx, env);
143
+ // The view is one turn: when the room catches up on several, each still needs a frame of its own.
144
+ patchEachTick(this);
145
+ }
146
+
147
+ /**
148
+ * Turn an untrusted client payload into an input. Every client will feed
149
+ * what this returns to its simulation, so reject anything malformed here.
150
+ */
151
+ protected abstract parseInput(raw: unknown): Input;
152
+
153
+ /** Two players reported different hashes for `turn`: their simulations have diverged. */
154
+ protected onDesync(_turn: number): void {}
155
+
156
+ protected initialState(): LockstepState<Input> {
157
+ const seed = crypto.getRandomValues(new Uint32Array(1))[0]!;
158
+ return { seed, turn: 0, entries: [], pending: [], desync: null };
159
+ }
160
+
161
+ protected parseCommand(raw: unknown): LockstepCommand<Input> {
162
+ const frame = raw as { k?: unknown; d?: unknown; n?: unknown; h?: unknown } | null;
163
+ if (frame?.k === "t") return { k: "t" };
164
+ if (frame?.k === "i") return { k: "i", d: this.parseInput(frame.d) };
165
+ if (
166
+ frame?.k === "h" &&
167
+ Number.isSafeInteger(frame.n) &&
168
+ typeof frame.h === "string" &&
169
+ frame.h.length <= 64
170
+ ) {
171
+ return { k: "h", n: frame.n as number, h: frame.h };
172
+ }
173
+ return reject("invalid_command");
174
+ }
175
+
176
+ /**
177
+ * Squares the saved state with the recording, once, before this instance
178
+ * adds anything to `pending`.
179
+ *
180
+ * A turn is written to the recording as it closes; the room itself is
181
+ * saved less often. So after a restart the recording can be ahead of the
182
+ * saved state. Whatever was waiting when that state was saved went into
183
+ * the first turn that closed after it: if the recording has a later turn,
184
+ * those entries are in it already, and are dropped here instead of being
185
+ * recorded twice.
186
+ */
187
+ #resume(): void {
188
+ if (this.#resumed) return;
189
+ this.#resumed = true;
190
+ const last = this.#recorded()
191
+ ? this.ctx.storage.sql
192
+ .exec<{ n: number; entries: string }>("SELECT n, entries FROM tickflare_turns ORDER BY n DESC LIMIT 1")
193
+ .toArray()[0]
194
+ : undefined;
195
+ if (last && last.n > this.state.turn) {
196
+ this.state.turn = last.n; // Never reuse a number.
197
+ this.state.entries = JSON.parse(last.entries) as TurnEntry<Input>[];
198
+ this.state.pending = [];
199
+ }
200
+ // A snapshot is of a turn that has happened. If the saved counter is behind it, every turn in
201
+ // between was empty, or the recording would have it: carry on from the snapshot's.
202
+ const kept = this.#kept();
203
+ if (kept && kept.turn > this.state.turn) {
204
+ this.state.turn = kept.turn;
205
+ this.state.entries = [];
206
+ }
207
+ if (this.turnClock === "players") {
208
+ this.#turn = this.state.turn;
209
+ this.#entries = last?.n === this.#turn ? (JSON.parse(last.entries) as TurnEntry<Input>[]) : [];
210
+ this.state.entries = [];
211
+ // Turns closed since the checkpoint were only in memory, and players still connected have
212
+ // seen them. There were fewer than a checkpoint's worth: pass over that many.
213
+ if (this.#turn > 0) this.#skip = this.#checkpointEvery();
214
+ }
215
+ }
216
+
217
+ /** With players asking for the turns: how many turns go by between checkpoints of the counter. */
218
+ #checkpointEvery(): number {
219
+ return Math.max(1, Math.round((this.saveIntervalMs * this.tickRate) / 1000));
220
+ }
221
+
222
+ /** Queues an input or an event for the next turn. */
223
+ #add(entry: TurnEntry<Input>): void {
224
+ this.#resume();
225
+ if (this.turnClock === "players") this.#waiting.push(entry);
226
+ else this.state.pending.push(entry);
227
+ }
228
+
229
+ /**
230
+ * With players asking for the turns: closes the turns that are due by this
231
+ * room's clock, and puts what was waiting into the last of them. `now`
232
+ * closes one even if none is due, for something that must not wait in
233
+ * memory: a player coming or going is recorded in the same breath as the
234
+ * change of seats.
235
+ */
236
+ #close(now: boolean, by?: string): void {
237
+ this.#resume();
238
+ const time = Date.now();
239
+ const turnMs = 1000 / this.tickRate;
240
+ // The first request after a (re)start finds one turn due.
241
+ this.#since ??= { at: time - turnMs, turn: this.#turn };
242
+ // Half a turn early is on time: requests arrive a little before and a little after the beat.
243
+ let count = Math.floor(this.#since.turn + (time - this.#since.at) / turnMs - this.#turn + 0.5);
244
+ const stoodStill = count > MOST_TURNS_AT_ONCE;
245
+ if (stoodStill) count = MOST_TURNS_AT_ONCE;
246
+ if (count < 1) {
247
+ if (!now) return;
248
+ count = 1;
249
+ }
250
+ // Turns passed over after a restart are not turns the clock is owed back.
251
+ count += this.#skip;
252
+ this.#since.turn += this.#skip;
253
+ this.#skip = 0;
254
+
255
+ const first = this.#turn + 1;
256
+ const last = this.#turn + count;
257
+ const entries = this.#waiting;
258
+ if (entries.length > 0) {
259
+ this.#turns().exec("INSERT OR REPLACE INTO tickflare_turns (n, entries) VALUES (?, ?)", last, JSON.stringify(entries));
260
+ }
261
+ this.#waiting = [];
262
+ this.#entries = entries;
263
+ this.#turn = last;
264
+ if (stoodStill) this.#since = { at: time, turn: last };
265
+ if (last - this.state.turn >= this.#checkpointEvery()) this.state.turn = last;
266
+ this.broadcast({ tickflare: "turns", n: first, c: count, e: entries, ...(by === undefined ? {} : { b: by }) } satisfies TurnsMessage<Input>);
267
+ }
268
+
269
+ /** The room keeps time only when it is asked to: with players asking, it has no simulation to wake for. */
270
+ protected override shouldTick(): boolean {
271
+ return this.turnClock === "room";
272
+ }
273
+
274
+ protected onCommand(player: Player, command: LockstepCommand<Input>): void {
275
+ this.#resume();
276
+ const clocked = this.turnClock === "players";
277
+ if (command.k === "t") {
278
+ // A room that keeps its own time has nothing to be asked for.
279
+ if (clocked) this.#close(false, player.id);
280
+ return;
281
+ }
282
+ if (command.k === "i") {
283
+ const queue = clocked ? this.#waiting : this.state.pending;
284
+ const waiting = queue.filter((entry) => entry.player === player.id && entry.input !== undefined);
285
+ if (waiting.length >= this.maxInputsPerTurn) reject("too_many_inputs");
286
+ this.#add({ player: player.id, input: command.d });
287
+ return;
288
+ }
289
+
290
+ // Only turns that have happened, and recently enough to still be compared.
291
+ const turn = clocked ? this.#turn : this.state.turn;
292
+ if (command.n > turn) return;
293
+ this.#vouch(player.id, command.n, command.h, turn);
294
+ if (command.n <= turn - HASHES_KEPT) return;
295
+ const first = this.#hashes.get(command.n);
296
+ if (first === undefined) {
297
+ this.#hashes.set(command.n, { hash: command.h, by: player.id });
298
+ if (this.#hashes.size > HASHES_KEPT) {
299
+ for (const n of this.#hashes.keys()) {
300
+ if (n <= turn - HASHES_KEPT) this.#hashes.delete(n);
301
+ }
302
+ }
303
+ } else if (first.by !== player.id && first.hash !== command.h && !this.state.desync) {
304
+ // It takes two players to disagree: one changing their mind proves nothing.
305
+ this.state.desync = { turn: command.n };
306
+ this.#candidate = undefined; // Nobody can say which simulation a snapshot should be of.
307
+ this.onDesync(command.n);
308
+ }
309
+ }
310
+
311
+ /** Turns between snapshots, or 0 when the room keeps none. */
312
+ #snapshotEvery(): number {
313
+ const turns = (this.snapshotIntervalMs * this.tickRate) / 1000;
314
+ return turns > 0 && Number.isFinite(turns) ? Math.max(1, Math.round(turns)) : 0;
315
+ }
316
+
317
+ /**
318
+ * Notes that `playerId` reported `hash` for `turn`, if a snapshot could be
319
+ * of that turn, and keeps the snapshot that was waiting for it.
320
+ */
321
+ #vouch(playerId: string, turn: number, hash: string, latest: number): void {
322
+ const every = this.#snapshotEvery();
323
+ if (every === 0 || turn <= 0 || turn % every !== 0 || turn <= latest - every * SNAPSHOT_TURNS_KEPT) return;
324
+ let seen = this.#vouched.get(turn);
325
+ if (seen === undefined) {
326
+ seen = { hash, by: new Set() };
327
+ this.#vouched.set(turn, seen);
328
+ for (const n of this.#vouched.keys()) {
329
+ if (n <= latest - every * SNAPSHOT_TURNS_KEPT) this.#vouched.delete(n);
330
+ }
331
+ }
332
+ if (seen.hash === hash) seen.by.add(playerId);
333
+ const candidate = this.#candidate;
334
+ if (candidate?.turn === turn && this.#agreed(candidate, candidate.by)) {
335
+ this.#candidate = undefined;
336
+ this.#keep(candidate);
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Whether a snapshot sent by `by` is one to keep: every other player who
342
+ * is connected has reported the hash it came with. A player with the room
343
+ * to themselves has nobody to be wrong about it.
344
+ */
345
+ #agreed(snapshot: Snapshot, by: string): boolean {
346
+ const seen = this.#vouched.get(snapshot.turn);
347
+ if (seen === undefined || seen.hash !== snapshot.hash) return false;
348
+ const others = this.players.filter((player) => player.id !== by);
349
+ if (others.length === 0) return true;
350
+ const connected = others.filter((player) => player.connected);
351
+ return connected.length > 0 && connected.every((player) => seen.by.has(player.id));
352
+ }
353
+
354
+ /** Stores a snapshot in place of the one before it. One row, or several for a long one. */
355
+ #keep(snapshot: Snapshot): void {
356
+ this.ctx.storage.transactionSync(() => {
357
+ const sql = this.ctx.storage.sql;
358
+ sql.exec(
359
+ "CREATE TABLE IF NOT EXISTS tickflare_snapshot (part INTEGER PRIMARY KEY, turn INTEGER NOT NULL, hash TEXT NOT NULL, data TEXT NOT NULL)",
360
+ );
361
+ const parts = pieces(snapshot.data);
362
+ parts.forEach((piece, part) => {
363
+ sql.exec(
364
+ "INSERT OR REPLACE INTO tickflare_snapshot (part, turn, hash, data) VALUES (?, ?, ?, ?)",
365
+ part,
366
+ snapshot.turn,
367
+ snapshot.hash,
368
+ piece,
369
+ );
370
+ });
371
+ sql.exec("DELETE FROM tickflare_snapshot WHERE part >= ?", parts.length);
372
+ });
373
+ }
374
+
375
+ /** The turn and hash of the snapshot the room has, if it has one. */
376
+ #kept(): { turn: number; hash: string } | undefined {
377
+ const sql = this.ctx.storage.sql;
378
+ if (sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tickflare_snapshot'").toArray().length === 0) {
379
+ return undefined;
380
+ }
381
+ return sql.exec<{ turn: number; hash: string }>("SELECT turn, hash FROM tickflare_snapshot WHERE part = 0").toArray()[0];
382
+ }
383
+
384
+ /**
385
+ * A player's client sends the simulation it saved at `turn`. Kept at once
386
+ * if the other players have reported the same hash already, and held until
387
+ * they do otherwise.
388
+ */
389
+ async #offered(request: Request, params: URLSearchParams, player: Player): Promise<Response> {
390
+ const every = this.#snapshotEvery();
391
+ if (every === 0) return new Response("Not found", { status: 404 });
392
+ if (!this.players.some((seated) => seated.id === player.id && seated.connected)) {
393
+ return new Response("Only a connected player can send a snapshot", { status: 403 });
394
+ }
395
+ const turn = Number(params.get("turn"));
396
+ const hash = params.get("hash") ?? "";
397
+ if (!Number.isSafeInteger(turn) || turn <= 0 || turn % every !== 0 || hash === "" || hash.length > 64) {
398
+ return new Response("Not a snapshot turn, or no hash", { status: 400 });
399
+ }
400
+ // Checked before the body is read, so that one of no use costs nothing, and again after:
401
+ // the room moves on while it waits.
402
+ const useless = (): boolean => {
403
+ const latest = Math.max(this.state.turn, this.#turn);
404
+ const seen = this.#vouched.get(turn);
405
+ return (
406
+ !this.#resumed || // This run of the room has closed no turn yet: it cannot tell what has happened.
407
+ this.state.desync !== null ||
408
+ turn > latest ||
409
+ turn <= latest - every * SNAPSHOT_TURNS_KEPT ||
410
+ turn <= (this.#kept()?.turn ?? 0) ||
411
+ (this.#candidate !== undefined && turn <= this.#candidate.turn) ||
412
+ (seen !== undefined && seen.hash !== hash)
413
+ );
414
+ };
415
+ if (useless()) return new Response("Not a snapshot this room can use", { status: 409 });
416
+ // A character of JSON is at most three bytes on the wire.
417
+ const data = await textUpTo(request, this.maxSnapshotLength * 3);
418
+ if (data === undefined || data.length > this.maxSnapshotLength) return new Response("Snapshot too long", { status: 413 });
419
+ if (data.length === 0) return new Response("Empty snapshot", { status: 400 });
420
+ if (useless()) return new Response("Not a snapshot this room can use", { status: 409 });
421
+ const latest = Math.max(this.state.turn, this.#turn);
422
+ this.#candidate = { turn, hash, data, by: player.id };
423
+ this.#vouch(player.id, turn, hash, latest);
424
+ return this.#candidate === undefined
425
+ ? new Response("Kept", { status: 201 })
426
+ : new Response("Held until the other players report the same hash", { status: 202 });
427
+ }
428
+
429
+ /**
430
+ * What a client that is catching up is sent. One that says which turn its
431
+ * simulation is at, and got there in this run of the room, is sent the
432
+ * turns after it; one that has fallen a snapshot or more behind, or has no
433
+ * simulation, is sent the snapshot and the turns after that.
434
+ */
435
+ #catchUp(params: URLSearchParams): Replay<Input> | CatchUp<Input> {
436
+ if (!params.has("since")) return this.replay();
437
+ const epoch = (this.#epoch ??= crypto.randomUUID().slice(0, 8));
438
+ const since = Number(params.get("since"));
439
+ const latest = Math.max(this.state.turn, this.#turn);
440
+ let from = params.get("epoch") === epoch && Number.isSafeInteger(since) && since > 0 && since <= latest ? since : 0;
441
+
442
+ // `snapshot=N`: the client can load one, and has no use for any of turn N or before.
443
+ const newerThan = params.has("snapshot") ? Number(params.get("snapshot")) : Number.POSITIVE_INFINITY;
444
+ const kept = this.#kept();
445
+ let snapshot: Snapshot | undefined;
446
+ if (kept && kept.turn > newerThan && (from === 0 || kept.turn - from > this.#snapshotEvery())) {
447
+ const data = this.ctx.storage.sql
448
+ .exec<{ data: string }>("SELECT data FROM tickflare_snapshot ORDER BY part")
449
+ .toArray()
450
+ .map((row) => row.data)
451
+ .join("");
452
+ snapshot = { ...kept, data };
453
+ from = kept.turn;
454
+ }
455
+ const recording = this.#recording(from);
456
+ return {
457
+ ...recording,
458
+ // Before this run of the room has closed a turn, a snapshot can be ahead of the saved counter.
459
+ turn: Math.max(recording.turn, from, kept?.turn ?? 0),
460
+ epoch,
461
+ ...(from > 0 ? { from } : {}),
462
+ ...(snapshot ? { snapshot } : {}),
463
+ };
464
+ }
465
+
466
+ protected override onJoin(player: Player): void {
467
+ this.#event({ player: player.id, event: "join" });
468
+ }
469
+
470
+ /** A player came or went. With players asking for the turns, it is in a turn before this hook returns. */
471
+ #event(entry: TurnEntry<Input>): void {
472
+ this.#add(entry);
473
+ if (this.turnClock === "players") this.#close(true);
474
+ }
475
+
476
+ /** Every way of losing a seat ends here, so every simulation hears about it. */
477
+ protected override removePlayer(playerId: string, reason?: string): void {
478
+ if (this.players.some((player) => player.id === playerId)) {
479
+ this.#event({ player: playerId, event: "leave" });
480
+ }
481
+ super.removePlayer(playerId, reason);
482
+ }
483
+
484
+ protected override onDisconnect(player: Player): void {
485
+ this.#event({ player: player.id, event: "disconnect" });
486
+ }
487
+
488
+ protected override onReconnect(player: Player): void {
489
+ this.#event({ player: player.id, event: "reconnect" });
490
+ }
491
+
492
+ /**
493
+ * Closes the turn: whatever arrived since the last one becomes this turn's
494
+ * entries. A turn with something in it is one row in the recording, written
495
+ * before any player is sent it; `#resume` is what lets the room itself be
496
+ * saved on its usual schedule instead of with every turn.
497
+ */
498
+ protected override onTick(): void {
499
+ if (this.turnClock === "players") return; // Only if a subclass turned the timer back on.
500
+ this.#resume();
501
+ const state = this.state;
502
+ state.turn += 1;
503
+ state.entries = state.pending;
504
+ state.pending = [];
505
+ if (state.entries.length > 0) {
506
+ this.#turns().exec(
507
+ "INSERT OR REPLACE INTO tickflare_turns (n, entries) VALUES (?, ?)",
508
+ state.turn,
509
+ JSON.stringify(state.entries),
510
+ );
511
+ }
512
+ }
513
+
514
+ protected override view(): LockstepView<Input> {
515
+ const { seed, turn, entries, desync } = this.state;
516
+ const every = this.#snapshotEvery();
517
+ const snapshots = every > 0 ? { snapshotEvery: every } : {};
518
+ if (this.turnClock !== "players") return { seed, turn, entries, desync, ...snapshots };
519
+ // Before anything has woken this instance up, the checkpoint is all it knows.
520
+ const latest = Math.max(turn, this.#turn);
521
+ return {
522
+ seed,
523
+ turn: latest,
524
+ entries: latest === this.#turn ? this.#entries : [],
525
+ desync,
526
+ clock: "players",
527
+ ...snapshots,
528
+ };
529
+ }
530
+
531
+ /**
532
+ * `GET …/replay` is the recording, or the end of it for a client that is
533
+ * catching up. `POST …/snapshot` is a player's client sending a snapshot.
534
+ * If you override this, pass on what is not yours with `super.onHttp`.
535
+ */
536
+ protected override onHttp(request: Request, player: Player): Response | Promise<Response> {
537
+ const url = new URL(request.url);
538
+ if (request.method === "GET" && url.pathname.endsWith("/replay")) {
539
+ return Response.json(this.#catchUp(url.searchParams));
540
+ }
541
+ if (request.method === "POST" && url.pathname.endsWith("/snapshot")) {
542
+ return this.#offered(request, url.searchParams, player);
543
+ }
544
+ return new Response("Not found", { status: 404 });
545
+ }
546
+
547
+ /** Announces the end of the match and, if `matchBucket` is set, stores the recording as its replay. */
548
+ protected override finishMatch(result: Record<string, unknown> = {}): void {
549
+ super.finishMatch(result, this.replay());
550
+ }
551
+
552
+ /** The recording so far. */
553
+ protected replay(): Replay<Input> {
554
+ return this.#recording(0);
555
+ }
556
+
557
+ /** The recording so far, without the turns up to `after`. */
558
+ #recording(after: number): Replay<Input> {
559
+ const rows = this.#recorded()
560
+ ? this.ctx.storage.sql
561
+ .exec<{ n: number; entries: string }>("SELECT n, entries FROM tickflare_turns WHERE n > ? ORDER BY n", after)
562
+ .toArray()
563
+ : [];
564
+ const turns = rows.map((row): [number, TurnEntry<Input>[]] => [row.n, JSON.parse(row.entries) as TurnEntry<Input>[]]);
565
+ const last = turns[turns.length - 1]?.[0] ?? 0;
566
+ return {
567
+ v: 2,
568
+ seed: this.state.seed,
569
+ turnRate: this.tickRate,
570
+ turn: Math.max(this.state.turn, this.#turn, last),
571
+ turns,
572
+ };
573
+ }
574
+
575
+ /**
576
+ * The recording, to write to. The table is made with the first turn that
577
+ * has something in it, not before: a room that has recorded nothing stores
578
+ * nothing. Asked for each time, because a hook that fails takes back
579
+ * everything it wrote, a new table included.
580
+ */
581
+ #turns(): SqlStorage {
582
+ const sql = this.ctx.storage.sql;
583
+ sql.exec("CREATE TABLE IF NOT EXISTS tickflare_turns (n INTEGER PRIMARY KEY, entries TEXT NOT NULL)");
584
+ return sql;
585
+ }
586
+
587
+ /** Whether there is a recording to read. */
588
+ #recorded(): boolean {
589
+ return this.ctx.storage.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tickflare_turns'").toArray().length > 0;
590
+ }
591
+ }
592
+
593
+ /** The request's body as text, or undefined if it is longer than `bytes`: no more than that is read. */
594
+ async function textUpTo(request: Request, bytes: number): Promise<string | undefined> {
595
+ if (Number(request.headers.get("Content-Length") ?? 0) > bytes) return undefined;
596
+ const reader = request.body?.getReader();
597
+ if (!reader) return "";
598
+ const chunks: Uint8Array[] = [];
599
+ let length = 0;
600
+ for (;;) {
601
+ const { done, value } = await reader.read();
602
+ if (done) break;
603
+ length += value.byteLength;
604
+ if (length > bytes) {
605
+ await reader.cancel();
606
+ return undefined;
607
+ }
608
+ chunks.push(value);
609
+ }
610
+ const all = new Uint8Array(length);
611
+ let at = 0;
612
+ for (const chunk of chunks) {
613
+ all.set(chunk, at);
614
+ at += chunk.byteLength;
615
+ }
616
+ return new TextDecoder().decode(all);
617
+ }