tickflare 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -2
  3. package/dist/client/buffered.d.ts +108 -0
  4. package/dist/client/buffered.js +252 -0
  5. package/dist/client/buffered.js.map +1 -0
  6. package/dist/client/clock.d.ts +36 -0
  7. package/dist/client/clock.js +83 -0
  8. package/dist/client/clock.js.map +1 -0
  9. package/dist/client/index.d.ts +83 -5
  10. package/dist/client/index.js +254 -15
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/interpolate.d.ts +6 -5
  13. package/dist/client/interpolate.js +6 -5
  14. package/dist/client/interpolate.js.map +1 -1
  15. package/dist/client/lockstep.d.ts +23 -4
  16. package/dist/client/lockstep.js +47 -4
  17. package/dist/client/lockstep.js.map +1 -1
  18. package/dist/client/predict.js +16 -3
  19. package/dist/client/predict.js.map +1 -1
  20. package/dist/lockstep.d.ts +43 -4
  21. package/dist/lockstep.js +33 -0
  22. package/dist/lockstep.js.map +1 -1
  23. package/dist/protocol.d.ts +131 -5
  24. package/dist/protocol.js +16 -3
  25. package/dist/protocol.js.map +1 -1
  26. package/dist/server/gateway.d.ts +5 -0
  27. package/dist/server/gateway.js +14 -0
  28. package/dist/server/gateway.js.map +1 -1
  29. package/dist/server/index.d.ts +4 -3
  30. package/dist/server/index.js +3 -2
  31. package/dist/server/index.js.map +1 -1
  32. package/dist/server/lockstep.d.ts +30 -4
  33. package/dist/server/lockstep.js +78 -6
  34. package/dist/server/lockstep.js.map +1 -1
  35. package/dist/server/room.d.ts +138 -2
  36. package/dist/server/room.js +701 -44
  37. package/dist/server/room.js.map +1 -1
  38. package/dist/server/schema.d.ts +67 -0
  39. package/dist/server/schema.js +44 -0
  40. package/dist/server/schema.js.map +1 -0
  41. package/dist/server/spectators.d.ts +74 -0
  42. package/dist/server/spectators.js +190 -0
  43. package/dist/server/spectators.js.map +1 -0
  44. package/dist/server/storage.d.ts +13 -1
  45. package/dist/server/storage.js +23 -5
  46. package/dist/server/storage.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/client/buffered.ts +294 -0
  49. package/src/client/clock.ts +86 -0
  50. package/src/client/index.ts +296 -15
  51. package/src/client/interpolate.ts +6 -5
  52. package/src/client/lockstep.ts +68 -7
  53. package/src/client/predict.ts +16 -3
  54. package/src/lockstep.ts +67 -4
  55. package/src/protocol.ts +134 -4
  56. package/src/server/gateway.ts +14 -0
  57. package/src/server/index.ts +7 -0
  58. package/src/server/lockstep.ts +77 -7
  59. package/src/server/room.ts +735 -45
  60. package/src/server/schema.ts +101 -0
  61. package/src/server/spectators.ts +221 -0
  62. package/src/server/storage.ts +33 -6
@@ -10,8 +10,9 @@ import {
10
10
  } from "../protocol.js";
11
11
  import { BINARY_PATCHES } from "../binary.js";
12
12
  import { DeltaSender, type SeatedSocket } from "./delta.js";
13
- import { MAX_CLOSE_REASON, readFrame, refuse } from "./frames.js";
14
- import { NAME_HEADER, PLAYER_HEADER, ROOM_HEADER, type RoomNamespace } from "./gateway.js";
13
+ import { SpectatorLine, SPECTATOR_ID_TAG, SPECTATOR_TAG } from "./spectators.js";
14
+ import { MAX_CLOSE_REASON, readFrame, refuse, type ClientFrame } from "./frames.js";
15
+ import { NAME_HEADER, PLAYER_HEADER, ROOM_HEADER, SPECTATOR_HEADER, type RoomNamespace } from "./gateway.js";
15
16
  import { RateLimiter } from "./limiter.js";
16
17
  import { SignalSender, type Signal } from "./signals.js";
17
18
  import { Tracker } from "./tracked.js";
@@ -70,8 +71,67 @@ const BINARY_TAG = "\u0001patches=b1";
70
71
  const V2_TAG = "\u0001v=2";
71
72
  /** Marks the socket of a client that speaks version 3: it is told who came and went, not the whole list of players. */
72
73
  const V3_TAG = "\u0001v=3";
74
+ /** Marks the socket of a client that speaks version 4: it is told the room's clock. */
75
+ const V4_TAG = "\u0001v=4";
76
+ /** Marks the socket of a client that speaks version 5: it can be told which of its commands were handled. */
77
+ const V5_TAG = "\u0001v=5";
78
+ /** Starts the tag that holds the name a client of version 5 gave itself. */
79
+ const CLIENT_TAG = "\u0001c=";
80
+ /** What a client may name itself: short, and nothing that needs escaping anywhere. */
81
+ const CLIENT_NAME = /^[\w-]{1,64}$/;
82
+ /** How many of a client's latest refused commands the room remembers the reasons of. */
83
+ const REFUSALS_KEPT = 8;
84
+ /** How much of each of those reasons it remembers, in characters. */
85
+ const REASON_KEPT = 120;
86
+ /**
87
+ * The most that is written to the room's row of which commands were handled,
88
+ * in characters: about fifteen hundred clients. The row holds the state and
89
+ * the seats too, and Cloudflare allows it 2 MB. Past this the clients that
90
+ * connected longest ago are left out, and are told nothing when they come
91
+ * back after the room has slept.
92
+ */
93
+ const HANDLED_CHARS = 100_000;
73
94
  const isMark = (tag: string) => tag.charCodeAt(0) === 1;
74
95
 
96
+ /**
97
+ * What the room remembers of the commands of one client, by the player it
98
+ * plays for. A client that names itself numbers its commands upwards for
99
+ * as long as it lives, so one number says how far the room has got with
100
+ * them, and a command that is sent again after a lost connection is known
101
+ * for what it is.
102
+ */
103
+ interface Handled {
104
+ /** The name the client gave itself: another client of the same player starts over. */
105
+ client: string;
106
+ /** The `id` of the latest command or leave of its that was handled, applied or refused. 0 for none. */
107
+ last: number;
108
+ /**
109
+ * The room can say what became of the commands after this one, up to
110
+ * `last`, and not of those up to it. 0 while it can say of every one. It
111
+ * moves when a command arrives that is not the next: the ones between were
112
+ * given up by the client, or were handled here without a write (refused,
113
+ * or applied and changing nothing) before the room slept, and are gone
114
+ * from what it remembers. And when a refusal is forgotten for a newer one.
115
+ */
116
+ from: number;
117
+ /** The latest of them that were refused, oldest first, each with its reason. */
118
+ refused: [id: number, reason: string][];
119
+ /** This record as it goes into the room's row, until it changes. */
120
+ json?: string;
121
+ }
122
+
123
+ /**
124
+ * What the room notes on a socket itself, where it outlasts this instance.
125
+ * `replaced`: a newer connection of the same player took over. `silent`: it
126
+ * was closed for its silence. `untracked`: the room came back from an older
127
+ * save under it, see `#load`.
128
+ */
129
+ interface SocketNote {
130
+ replaced?: boolean;
131
+ silent?: boolean;
132
+ untracked?: boolean;
133
+ }
134
+
75
135
  /** What a socket's tags say: whose it is, and what its client asked for. */
76
136
  interface SocketInfo {
77
137
  id: string | undefined;
@@ -81,6 +141,14 @@ interface SocketInfo {
81
141
  arrays: boolean;
82
142
  /** Version 3: presence as changes. */
83
143
  presence: boolean;
144
+ /** Version 4: told the room's clock. */
145
+ clock: boolean;
146
+ /** Version 5: can be told which of its commands were handled. */
147
+ resumes: boolean;
148
+ /** The name its client gave itself, if it gave one. */
149
+ client: string | undefined;
150
+ /** It is a spectator's: `id` is then undefined, since nobody's seat is behind it. */
151
+ spectator: boolean;
84
152
  }
85
153
  /**
86
154
  * In a room with more than `PRESENCE_CROWD` connections, the least time
@@ -105,7 +173,7 @@ const DELETE_RETRY_MS = 30_000;
105
173
  *
106
174
  * Cloudflare takes an object that has had no incoming event for 70 to 140
107
175
  * seconds out of memory, simulation and all. A keepalive does not count:
108
- * Cloudflare answers it without waking the room. A pending `setInterval`
176
+ * Cloudflare answers it without waking the room. A pending timer
109
177
  * holds the object for at most 15 minutes. So without this, a match in which
110
178
  * nobody sends a command would stop, and stay stopped until someone did. An
111
179
  * alarm is an event, and when Cloudflare restarts the room for any other
@@ -127,6 +195,19 @@ const DELETE_PATIENCE_MS = 10_000;
127
195
  const FORWARD_GRACE_MS = 30_000;
128
196
  /** Consecutive failed ticks after which the simulation pauses until the next event. */
129
197
  const MAX_FAILED_TICKS = 5;
198
+ /**
199
+ * Rooms that send a patch for every tick, even when they catch up several at
200
+ * once: a lockstep room's view is one turn, and a client must see each.
201
+ */
202
+ const patchesEachTick = new WeakSet<object>();
203
+
204
+ /** Has `room` send a patch for every tick it runs, also when catching up. @internal */
205
+ export function patchEachTick(room: object): void {
206
+ patchesEachTick.add(room);
207
+ }
208
+
209
+ /** While the simulation runs, how often clients of version 4 are told the room's clock, in milliseconds. */
210
+ const CLOCK_EVERY_MS = 5_000;
130
211
 
131
212
  /**
132
213
  * An authoritative game room: one Durable Object per room.
@@ -169,6 +250,21 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
169
250
  */
170
251
  protected maxCommandsPerSecond = 30;
171
252
 
253
+ /**
254
+ * Whether the room remembers which commands of each client it has handled,
255
+ * so that a client whose connection dropped can be told when it is back,
256
+ * send again the ones that never arrived, and have none applied twice.
257
+ * `RoomClient` does this by itself. On by default.
258
+ *
259
+ * What was handled is saved with the state, in the same row, so the two
260
+ * are always of the same moment. A ticking room that also records commands
261
+ * somewhere of its own as they arrive should call `saveNow()` in the same
262
+ * hook, as for anything else it writes itself, or turn this off: after a
263
+ * restart the room would otherwise take a command that is sent again for
264
+ * new, though its own record has it.
265
+ */
266
+ protected rememberCommands = true;
267
+
172
268
  /**
173
269
  * Where `finishMatch` announces a finished match. Set it to a Queue binding:
174
270
  * `protected override matchQueue = this.env.MATCHES;`
@@ -191,6 +287,94 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
191
287
  /** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
192
288
  protected tickRate = 0;
193
289
 
290
+ /**
291
+ * How many times a second a ticking room sends what changed, when that is
292
+ * to be less often than it simulates. 0, the default, sends after every
293
+ * tick, and so does any rate that is not below `tickRate`.
294
+ *
295
+ * With `tickRate = 60` and `patchRate = 20` the room moves things sixty
296
+ * times a second and sends every third tick, in one patch that takes each
297
+ * player's view from the last one sent to now. What a patch costs, the
298
+ * comparison of every player's view and the bytes, is then paid a third
299
+ * as often; a tick costs what it did. With a rate that does not divide
300
+ * `tickRate` the gaps between patches differ by a tick, and average out.
301
+ *
302
+ * What waits for the patch: the `ack` of a command, since it says that
303
+ * the view shows the command, and messages sent with `send()` and
304
+ * `broadcast()` from `onTick`, so that they still arrive after the patch
305
+ * that shows their tick. Whatever is waiting goes out at once when the
306
+ * simulation stops, and in a tick that removes a player. A lockstep room
307
+ * sends every turn, whatever this says.
308
+ *
309
+ * `RoomClient.patchRate` tells the client, and `BufferedInterpolator`
310
+ * keeps as much more of a delay as it takes to always have two patches to
311
+ * draw between.
312
+ */
313
+ protected patchRate = 0;
314
+
315
+ /**
316
+ * How many connections may watch the room without a seat in it. 0, the
317
+ * default, lets nobody watch.
318
+ *
319
+ * A spectator connects with `?spectate=1` (`new RoomClient(url, {
320
+ * spectate: true })`) and is sent `spectatorView()`, kept up to date as a
321
+ * player's view is. They take no seat: they are not among `players`, no
322
+ * hook but `onSpectate` hears of them, what they send is refused, and a
323
+ * room with nobody but spectators connected is empty. They also hear what
324
+ * the room sends with `broadcast()`, and who is here.
325
+ *
326
+ * Not for lockstep rooms, whose state is on the clients.
327
+ */
328
+ protected maxSpectators = 0;
329
+
330
+ /**
331
+ * How far behind the room its spectators are, in milliseconds. 0, the
332
+ * default, sends them every change as the players are sent it.
333
+ *
334
+ * With a delay, nothing reaches a spectator sooner than that after the
335
+ * players: not the view, not who is here, not a broadcast. It is what
336
+ * keeps someone who watches from telling someone who plays what they
337
+ * cannot see yet. A spectator who connects waits this long for their first
338
+ * view, unless others are watching already.
339
+ *
340
+ * What it costs: the changes of that long are held in memory, and a room
341
+ * that would be asleep stays awake for as long after each change, while
342
+ * someone watches.
343
+ */
344
+ protected spectatorDelayMs = 0;
345
+
346
+ /**
347
+ * How many ticks of the state a ticking room keeps to look back at with
348
+ * `stateAt`. 0, the default, keeps none.
349
+ *
350
+ * It is for judging a command by what its player was looking at when they
351
+ * sent it, which is a moment ago: a shot at a runner drawn where they were
352
+ * a tenth of a second back. Set it to as many ticks as the lag you mean to
353
+ * forgive: 12 at 60 ticks a second is 200 ms. It is also as far as a client
354
+ * that lies about what it saw can reach back, so no more than that.
355
+ *
356
+ * Kept in memory, as the JSON the room has of each tick anyway: it costs no
357
+ * work in a tick, and as many states of memory as it is long. A room that
358
+ * restarts, or whose simulation stops, has none until it has ticked again.
359
+ */
360
+ protected historyTicks = 0;
361
+
362
+ /**
363
+ * While the room is ticking, the most ticks it runs back to back to catch
364
+ * up when it wakes late. The simulation keeps to a fixed clock: tick `n`
365
+ * is due `n / tickRate` seconds after the clock started, and a room that
366
+ * wakes late, because a tick or an event took long or the machine was
367
+ * busy, runs every tick that has come due since, each with the same `dt`,
368
+ * and sends one patch for all of them.
369
+ *
370
+ * When more than this many are due, after a stall of a fraction of a
371
+ * second, the room runs this many and lets the rest go: the clock moves on,
372
+ * and the game is that much behind the wall clock for good, instead of
373
+ * fast-forwarding through a burst of ticks. 1 never catches up, which is
374
+ * how rooms ran before 0.2.
375
+ */
376
+ protected maxCatchUpTicks = 5;
377
+
194
378
  /**
195
379
  * While the room is ticking, how often the state is written to storage, in
196
380
  * milliseconds. It is also written whenever the simulation stops. A room
@@ -274,6 +458,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
274
458
  /** Timer name to the time it fires, in epoch milliseconds. */
275
459
  #timers = new Map<string, number>();
276
460
  #committed: Committed = { state: "", roster: "[]", timers: "[]" };
461
+ /** What the spectators are sent, and when: see `SpectatorLine`. */
462
+ #line = new SpectatorLine(() => this.#watching());
463
+ /** The state after each of the last `historyTicks` ticks, by tick: see `stateAt`. In order of tick. */
464
+ #history = new Map<number, string>();
277
465
  /** Seats given up during this event. Their sockets are closed once the event is over. */
278
466
  #removed: { id: string; reason: string }[] = [];
279
467
  /** The timers changed, so the object's alarm has to be moved before the event ends. */
@@ -291,6 +479,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
291
479
  #signals: Signal[] = [];
292
480
  /** Messages for players, as frames, waiting for the end of the event. `to` null is everyone. */
293
481
  #mail: { to: string | null; frame: string }[] = [];
482
+ /** Messages sent from ticks that no patch has followed yet: see `patchRate`. */
483
+ #heldMail: { to: string | null; frame: string }[] = [];
294
484
  /** While ticking: the commands each socket has had applied and not yet been told about. */
295
485
  #owed = new Map<WebSocket, number[]>();
296
486
  /** The command being handled, and who sent it. */
@@ -342,11 +532,28 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
342
532
 
343
533
  /** Holds each player to `maxCommandsPerSecond`. */
344
534
  #limiter = new RateLimiter();
535
+ /**
536
+ * Which commands of each seated player's client have been handled: see
537
+ * `Handled`. Saved in the room's row whenever the state is, so that what
538
+ * storage says was handled is what the saved state shows.
539
+ */
540
+ #handled = new Map<string, Handled>();
345
541
 
346
542
  /** Ticks run since the room was created. */
347
543
  #tick = 0;
348
- /** Set while the simulation is running. */
349
- #loop: ReturnType<typeof setInterval> | undefined;
544
+ /** Set while the simulation is running: the timer for the next wake-up. */
545
+ #loop: ReturnType<typeof setTimeout> | undefined;
546
+ /**
547
+ * The simulation's clock: tick `#clockTick` was due at `#clockAt`, in epoch
548
+ * milliseconds, and each tick after it `1000 / tickRate` later. Set when
549
+ * the simulation starts, and moved on when ticks are let go.
550
+ */
551
+ #clockTick = 0;
552
+ #clockAt = 0;
553
+ /** Goes up each time the clock starts over or moves on: a client keeps a clock per epoch. */
554
+ #epoch = 0;
555
+ /** When clients were last told the clock, in epoch milliseconds. */
556
+ #clockToldAt = 0;
350
557
  /** The committed state is newer than what is in storage. Only happens while ticking. */
351
558
  #unsaved = false;
352
559
  #ticksSinceSave = 0;
@@ -408,7 +615,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
408
615
 
409
616
  /**
410
617
  * Advance the simulation by one step of `dt` seconds (always `1 / tickRate`).
411
- * Runs `tickRate` times a second while the room is ticking.
618
+ * Runs `tickRate` times a second while the room is ticking, on a fixed
619
+ * clock: a room that wakes late runs the ticks it owes back to back. See
620
+ * `maxCatchUpTicks`.
412
621
  */
413
622
  protected onTick(_dt: number): void {}
414
623
 
@@ -453,6 +662,30 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
453
662
  return this.state;
454
663
  }
455
664
 
665
+ /**
666
+ * What spectators see: one view for all of them. Defaults to the whole
667
+ * state, in a room where that is what players see too. A room with a
668
+ * `view()` of its own hides something from its players, and has to say
669
+ * here what someone who watches may see: until it does, it takes no
670
+ * spectators.
671
+ */
672
+ protected spectatorView(): unknown {
673
+ return this.state;
674
+ }
675
+
676
+ /**
677
+ * Someone asks to watch, in a room with `maxSpectators`. Throw
678
+ * `reject("reason")` to turn them away. `player.connected` says whether
679
+ * they also hold a seat and are connected to it. A hook like the others:
680
+ * what it changes is kept.
681
+ */
682
+ protected onSpectate(_player: Player): void {}
683
+
684
+ /** How many spectators are connected. */
685
+ protected get spectators(): number {
686
+ return this.#watching().length;
687
+ }
688
+
456
689
  /** Everyone with a seat, in join order. */
457
690
  protected get players(): Player[] {
458
691
  // One pass over the sockets, not one per player: a join tells everyone this list.
@@ -470,6 +703,28 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
470
703
  return this.#tick;
471
704
  }
472
705
 
706
+ /**
707
+ * The state as it was after tick `tick`, which is what the patch of that
708
+ * tick showed, or undefined if the room does not have it: `historyTicks`
709
+ * is 0, the tick is older than that many ticks or has not run yet, or the
710
+ * simulation has stopped or the room restarted since. The latest it has is
711
+ * `stateAt(this.tick)`, the state as the last tick left it, without what
712
+ * commands did since. Where there is none, judge by `this.state`.
713
+ *
714
+ * A tick with a fraction, as `BufferedInterpolator.drawnTick()` gives it,
715
+ * is taken as the nearest whole one. Where half a tick matters, take the
716
+ * ticks on either side and blend what you need from them.
717
+ *
718
+ * It is the whole state, not a player's view of it, and a copy of your
719
+ * own, made from that tick's JSON on every call: it costs what the state
720
+ * weighs to parse, so call it once for a command and keep what it gave.
721
+ * Changing the copy changes nothing in the room.
722
+ */
723
+ protected stateAt(tick: number): State | undefined {
724
+ const kept = this.#history.get(Math.round(tick));
725
+ return kept === undefined ? undefined : (JSON.parse(kept) as State);
726
+ }
727
+
473
728
  /** The id this room is reached under, once someone has connected through the gateway. */
474
729
  protected get roomId(): string | null {
475
730
  return this.#roomId;
@@ -599,7 +854,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
599
854
  this.#mail.push({ to: playerId, frame: messageFrame(message) });
600
855
  }
601
856
 
602
- /** `send` to every player who is connected. */
857
+ /** `send` to every player who is connected, and to those who watch: see `maxSpectators`. */
603
858
  protected broadcast(message: unknown): void {
604
859
  this.#mail.push({ to: null, frame: messageFrame(message) });
605
860
  }
@@ -773,7 +1028,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
773
1028
 
774
1029
  /** Durable Object entry point for connections and HTTP requests from the gateway. Tickflare's: override `onHttp` instead. */
775
1030
  override async fetch(request: Request): Promise<Response> {
776
- const playerId = request.headers.get(PLAYER_HEADER);
1031
+ // Someone who asks to watch comes under a header of their own: see `routeToRoom`.
1032
+ const watcherId = request.headers.get(SPECTATOR_HEADER);
1033
+ const playerId = request.headers.get(PLAYER_HEADER) ?? watcherId;
777
1034
  if (!playerId) {
778
1035
  return new Response("Missing player identity", { status: 401 });
779
1036
  }
@@ -797,10 +1054,22 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
797
1054
  }
798
1055
  }
799
1056
  const asked = new URL(request.url).searchParams;
1057
+ // By the header, or by the query alone when the gateway in front is not `routeToRoom`.
1058
+ if (watcherId !== null || asked.get("spectate") === "1") {
1059
+ const response = this.#spectate(playerId, name);
1060
+ await this.#finish();
1061
+ return response;
1062
+ }
800
1063
  const marks: string[] = [];
801
1064
  if (asked.get("patches") === BINARY_PATCHES) marks.push(BINARY_TAG);
802
1065
  if (Number(asked.get("v")) >= 2) marks.push(V2_TAG);
803
1066
  if (Number(asked.get("v")) >= 3) marks.push(V3_TAG);
1067
+ if (Number(asked.get("v")) >= 4) marks.push(V4_TAG);
1068
+ if (Number(asked.get("v")) >= 5) {
1069
+ marks.push(V5_TAG);
1070
+ const client = asked.get("client");
1071
+ if (this.rememberCommands && client !== null && CLIENT_NAME.test(client)) marks.push(CLIENT_TAG + client);
1072
+ }
804
1073
  const response = this.#connect(playerId, name, marks);
805
1074
  await this.#finish();
806
1075
  return response;
@@ -906,8 +1175,12 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
906
1175
  const server = pair[1];
907
1176
  const player: Player = { id: playerId, connected: true };
908
1177
  if (name !== undefined) player.name = name;
1178
+ /** The player had their seat before this connection: what their client sent before was sent to this seat. */
1179
+ const seated = this.#roster.includes(playerId);
1180
+ /** The name the client gave itself, if the room remembers commands and it gave one. */
1181
+ const named = marks.find((mark) => mark.startsWith(CLIENT_TAG))?.slice(CLIENT_TAG.length);
909
1182
 
910
- if (!this.#roster.includes(playerId)) {
1183
+ if (!seated) {
911
1184
  const arrival = this.#store.arrival(playerId);
912
1185
  // A player handed over by another room is always let in.
913
1186
  if (arrival === undefined) {
@@ -932,6 +1205,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
932
1205
  return refuse(client, server, CloseCode.RoomFull, "room_full");
933
1206
  }
934
1207
  }
1208
+ // A new seat starts over: nothing sent to an earlier one counts. Noted before the join is
1209
+ // saved, so that the same write holds it.
1210
+ this.#handled.delete(playerId);
1211
+ if (named !== undefined) this.#handled.set(playerId, { client: named, last: 0, from: 0, refused: [] });
935
1212
  const joined = this.#apply(() => {
936
1213
  this.#roster.push(playerId);
937
1214
  this.#connecting = playerId;
@@ -943,6 +1220,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
943
1220
  }
944
1221
  });
945
1222
  if (!joined.ok) {
1223
+ this.#handled.delete(playerId);
946
1224
  return refuse(client, server, CloseCode.JoinRejected, joined.reason);
947
1225
  }
948
1226
  } else if (!this.#isConnected(playerId)) {
@@ -963,14 +1241,117 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
963
1241
  // What the client asked for is kept with the socket, where it outlasts the room's sleep.
964
1242
  this.ctx.acceptWebSocket(server, [playerId, ...marks]);
965
1243
  this.#heard.set(server, Date.now());
966
- this.#welcome(server, player, this.#loop !== undefined);
1244
+ let resumed: Handled | undefined;
1245
+ if (named !== undefined && seated) {
1246
+ const known = this.#handled.get(playerId);
1247
+ if (known?.client === named) {
1248
+ // The client the seat last heard from, on a new connection: it is told how far the room
1249
+ // got with its commands.
1250
+ resumed = known;
1251
+ } else {
1252
+ // Another client than the one the room remembers: a page that was loaded again, or a
1253
+ // second device. Whether the room ever heard from it is not known, so it is told nothing,
1254
+ // and counts from here. Written now: a client the room knows is one in storage.
1255
+ this.#handled.set(playerId, { client: named, last: 0, from: 0, refused: [] });
1256
+ this.#saveHandled();
1257
+ }
1258
+ }
1259
+ this.#welcome(server, player, this.#loop !== undefined, resumed);
967
1260
  this.#broadcastPresence(server);
968
1261
 
969
1262
  return new Response(null, { status: 101, webSocket: client });
970
1263
  }
971
1264
 
972
- /** Sends a socket everything from the start: who they are, the players and their whole view. */
973
- #welcome(ws: WebSocket, player: Player, ticking: boolean): void {
1265
+ /** Someone asks to watch: see `maxSpectators`. */
1266
+ #spectate(playerId: string, name: string | undefined): Response {
1267
+ const pair = new WebSocketPair();
1268
+ const client = pair[0];
1269
+ const server = pair[1];
1270
+ const tag = SPECTATOR_ID_TAG + playerId;
1271
+ // Cloudflare takes no tag longer than this.
1272
+ if (!(this.maxSpectators > 0) || patchesEachTick.has(this) || tag.length > 256) {
1273
+ return refuse(client, server, CloseCode.JoinRejected, "no_spectators");
1274
+ }
1275
+ if (this.view !== Room.prototype.view && this.spectatorView === Room.prototype.spectatorView) {
1276
+ console.error(
1277
+ "[tickflare] this room has a view() of its own and no spectatorView(): it has to say what a spectator may see before it takes any.",
1278
+ );
1279
+ return refuse(client, server, CloseCode.JoinRejected, "no_spectators");
1280
+ }
1281
+ const others = this.#watching().filter((ws) => !this.ctx.getTags(ws).includes(tag));
1282
+ if (others.length >= this.maxSpectators) {
1283
+ return refuse(client, server, CloseCode.RoomFull, "spectators_full");
1284
+ }
1285
+ const player: Player = { id: playerId, connected: this.#isConnected(playerId) };
1286
+ if (name !== undefined) player.name = name;
1287
+ const asked = this.#apply(() => this.onSpectate(player));
1288
+ if (!asked.ok) return refuse(client, server, CloseCode.JoinRejected, asked.reason);
1289
+
1290
+ // One connection per spectator: the newest wins.
1291
+ for (const old of this.ctx.getWebSockets(tag)) {
1292
+ try {
1293
+ old.close(CloseCode.Replaced, "replaced");
1294
+ } catch {
1295
+ // Already closed.
1296
+ }
1297
+ }
1298
+ // Before this socket is among those the line sends to: what a line without a delay lets out
1299
+ // at once is in the welcome.
1300
+ if (!this.#line.running) this.#show(true);
1301
+ this.ctx.acceptWebSocket(server, [SPECTATOR_TAG, tag]);
1302
+ this.#heard.set(server, Date.now());
1303
+ // Nothing of the room as it is now: who they are, then what the others have been shown. For
1304
+ // the first to watch there is no such view yet, and it follows when its time has come.
1305
+ this.#send(server, {
1306
+ t: "spectating",
1307
+ v: 5,
1308
+ you: playerId,
1309
+ tickRate: this.tickRate,
1310
+ ...(this.#patchRate() > 0 ? { patchRate: this.#patchRate() } : {}),
1311
+ delay: Math.max(0, this.spectatorDelayMs),
1312
+ players: this.#line.players ?? [],
1313
+ });
1314
+ const shown = this.#line.shown;
1315
+ if (shown) this.#send(server, { t: "state", seq: shown.seq, tick: shown.tick, state: shown.view });
1316
+ return new Response(null, { status: 101, webSocket: client });
1317
+ }
1318
+
1319
+ /** The open sockets of the spectators. */
1320
+ #watching(): WebSocket[] {
1321
+ return this.ctx.getWebSockets(SPECTATOR_TAG).filter((ws) => ws.readyState === SOCKET_OPEN);
1322
+ }
1323
+
1324
+ /**
1325
+ * The players have just been sent the state as it is now: the spectators'
1326
+ * line takes their view of it. `starting` when it is to start whoever is
1327
+ * watching, for a spectator who is about to be.
1328
+ */
1329
+ #show(starting = false): void {
1330
+ if (!this.#line.running && !starting) {
1331
+ // Stopped while someone watches: it held too much, and starts over.
1332
+ if (!(this.maxSpectators > 0) || this.#watching().length === 0) return;
1333
+ starting = true;
1334
+ }
1335
+ if (!starting && !this.#line.keep(this.#watching().length > 0)) return;
1336
+ let view: unknown;
1337
+ try {
1338
+ view = this.spectatorView();
1339
+ } catch (err) {
1340
+ console.error("[tickflare] spectatorView() failed; the spectators keep the view they have:", err);
1341
+ return;
1342
+ }
1343
+ const delay = Math.max(0, this.spectatorDelayMs);
1344
+ const begins = !this.#line.running;
1345
+ this.#line.take(view, this.#seq, this.#tick, delay);
1346
+ if (begins) this.#line.tell(this.players, delay);
1347
+ }
1348
+
1349
+ /**
1350
+ * Sends a socket everything from the start: who they are, the players and
1351
+ * their whole view. `resumed`, on a new connection of a client that held
1352
+ * the seat before, also tells it which of its commands were handled.
1353
+ */
1354
+ #welcome(ws: WebSocket, player: Player, ticking: boolean, resumed?: Handled): void {
974
1355
  const welcome = JSON.stringify({
975
1356
  t: "welcome",
976
1357
  v: this.#versionOf(ws),
@@ -978,6 +1359,11 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
978
1359
  seq: this.#seq,
979
1360
  tick: this.#tick,
980
1361
  tickRate: this.tickRate,
1362
+ ...(this.#loop !== undefined && this.#socketInfo(ws).clock ? this.#clockReading(Date.now()) : {}),
1363
+ ...(this.#patchRate() > 0 ? { patchRate: this.#patchRate() } : {}),
1364
+ ...(resumed ? { c: resumed.last } : {}),
1365
+ ...(resumed && resumed.from > 0 ? { from: resumed.from } : {}),
1366
+ ...(resumed && resumed.refused.length > 0 ? { refused: resumed.refused } : {}),
981
1367
  state: this.view(player),
982
1368
  players: this.players,
983
1369
  } satisfies ServerMessage);
@@ -996,7 +1382,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
996
1382
  this.#owed.delete(old);
997
1383
  try {
998
1384
  // Marked, so that its close is not taken for the player dropping.
999
- old.serializeAttachment({ replaced: true });
1385
+ this.#note(old, { replaced: true });
1000
1386
  old.close(CloseCode.Replaced, "replaced");
1001
1387
  } catch {
1002
1388
  // Already closed.
@@ -1006,8 +1392,33 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1006
1392
 
1007
1393
  #receive(ws: WebSocket, message: string | ArrayBuffer): void {
1008
1394
  const playerId = this.#playerOf(ws);
1395
+ if (!playerId && this.#socketInfo(ws).spectator) {
1396
+ // Watching is all a spectator does. Answered by id, so that a client's promise settles.
1397
+ if (typeof message !== "string" || message.length > this.maxMessageLength) return;
1398
+ let frame: ClientFrame | undefined;
1399
+ try {
1400
+ frame = readFrame(JSON.parse(message));
1401
+ } catch {
1402
+ return;
1403
+ }
1404
+ if (frame) this.#send(ws, { t: "reject", id: frame.id, reason: "spectator" });
1405
+ return;
1406
+ }
1009
1407
  // A socket whose seat is gone is about to be closed; ignore what it still sends.
1010
1408
  if (!playerId || !this.#roster.includes(playerId)) return;
1409
+ // What the room notes on the socket of a client that named itself decides what its commands
1410
+ // count for: see `#handledFor`.
1411
+ const client = this.#socketInfo(ws).client;
1412
+ const note = client === undefined ? null : (ws.deserializeAttachment() as SocketNote | null);
1413
+ // A newer connection took over. If it is the same client's, it sends again whatever was not
1414
+ // handled when it was welcomed, and what still arrives here would be handled twice. If it is
1415
+ // another's, this one has been told to stop.
1416
+ if (note?.replaced) return;
1417
+ // The same, where the mark is missing: a connection that was closing already when the newer
1418
+ // one came is not among the room's sockets any more, and what it sent before it closed can
1419
+ // still arrive. The room keeps count for the client that connected last, so a socket of
1420
+ // another client is an older one. Its commands would be applied as they come, repeats too.
1421
+ if (client !== undefined && (this.#handled.get(playerId)?.client ?? client) !== client) return;
1011
1422
 
1012
1423
  // Every frame counts against the limit, including the ones refused below.
1013
1424
  const allowed = this.#limiter.spend(playerId, this.maxCommandsPerSecond);
@@ -1028,15 +1439,50 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1028
1439
  if (!frame) {
1029
1440
  return this.#send(ws, { t: "error", reason: allowed ? "invalid_message" : "rate_limited" });
1030
1441
  }
1442
+ // While the simulation runs, what a command changed is sent with the next tick.
1443
+ const ticking = this.#loop !== undefined;
1444
+ /** An ack means "you have seen the result": at once, or with the tick that sends the result. */
1445
+ const ack = () => {
1446
+ if (!ticking || frame.t !== "cmd") return this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1447
+ const owed = this.#owed.get(ws);
1448
+ if (owed) owed.push(frame.id);
1449
+ else this.#owed.set(ws, [frame.id]);
1450
+ };
1451
+
1452
+ const handled = this.#handledFor(ws, playerId, note);
1453
+ if (handled && frame.id <= handled.last) {
1454
+ // Sent before, on a connection that was lost before its answer arrived, and handled
1455
+ // then: answered as it was, and not applied again.
1456
+ const refusal = handled.refused.find(([id]) => id === frame.id);
1457
+ return refusal ? this.#send(ws, { t: "reject", id: frame.id, reason: refusal[1] }) : ack();
1458
+ }
1459
+ // From here on the command is handled, whatever becomes of it. If it changes the state, the
1460
+ // save that holds the change says so too: they are written together.
1461
+ if (handled) {
1462
+ // Not the one after the last: of those between, the room cannot say what became. The client
1463
+ // gave them up, or they were handled without a write before the room slept: a refusal, or a
1464
+ // command that changed nothing. Taking them for applied, as the count alone would have it,
1465
+ // could tell a client that a command it was refused went through.
1466
+ if (frame.id > handled.last + 1) handled.from = frame.id - 1;
1467
+ handled.last = frame.id;
1468
+ handled.json = undefined;
1469
+ }
1470
+ const refuse = (reason: string) => {
1471
+ if (handled) {
1472
+ handled.refused.push([frame.id, reason.slice(0, REASON_KEPT)]);
1473
+ // A refusal the room forgets is one it can no longer tell from a command it applied.
1474
+ if (handled.refused.length > REFUSALS_KEPT) handled.from = Math.max(handled.from, handled.refused.shift()![0]);
1475
+ handled.json = undefined;
1476
+ }
1477
+ this.#send(ws, { t: "reject", id: frame.id, reason });
1478
+ };
1031
1479
  if (!allowed) {
1032
1480
  // Answered by id, so the client's pending command settles instead of hanging.
1033
- return this.#send(ws, { t: "reject", id: frame.id, reason: "rate_limited" });
1481
+ return refuse("rate_limited");
1034
1482
  }
1035
1483
 
1036
1484
  const player: Player = { id: playerId, connected: true };
1037
1485
  let outcome: Outcome;
1038
- // While the simulation runs, what a command changed is sent with the next tick.
1039
- const ticking = this.#loop !== undefined;
1040
1486
  if (frame.t === "leave") {
1041
1487
  outcome = this.#apply(() => {
1042
1488
  this.onLeave(player);
@@ -1049,8 +1495,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1049
1495
  try {
1050
1496
  command = this.parseCommand(frame.data);
1051
1497
  } catch (err) {
1052
- const reason = err instanceof Rejection ? err.reason : "invalid_command";
1053
- return this.#send(ws, { t: "reject", id: frame.id, reason });
1498
+ return refuse(err instanceof Rejection ? err.reason : "invalid_command");
1054
1499
  }
1055
1500
  // If this changes what the player sees, the frame that says so says whose command it shows.
1056
1501
  this.#answering = { ws, id: frame.id };
@@ -1061,18 +1506,46 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1061
1506
  }
1062
1507
  }
1063
1508
 
1064
- if (!outcome.ok) {
1065
- return this.#send(ws, { t: "reject", id: frame.id, reason: outcome.reason });
1066
- }
1067
- if (ticking && frame.t === "cmd") {
1068
- // An ack means "you have seen the result", and the result goes out with the tick.
1069
- const owed = this.#owed.get(ws);
1070
- if (owed) owed.push(frame.id);
1071
- else this.#owed.set(ws, [frame.id]);
1072
- return;
1073
- }
1509
+ if (!outcome.ok) return refuse(outcome.reason);
1074
1510
  // The state frame, if any, has already gone out.
1075
- this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1511
+ ack();
1512
+ }
1513
+
1514
+ /**
1515
+ * What the room remembers of the commands of the client on `ws`, to tell
1516
+ * a command that is sent again from a new one. Undefined for a client
1517
+ * that did not name itself, and for one the room has no record of: its
1518
+ * commands are applied as they come.
1519
+ */
1520
+ #handledFor(ws: WebSocket, playerId: string, note: SocketNote | null): Handled | undefined {
1521
+ const client = this.#socketInfo(ws).client;
1522
+ if (client === undefined) return undefined;
1523
+ const handled = this.#handled.get(playerId);
1524
+ if (handled?.client !== client) return undefined;
1525
+ if (note?.untracked) {
1526
+ // The room came back from an older save under this connection. Commands the save does not
1527
+ // hold may be followed here by later ones, so their numbers no longer say which the room
1528
+ // has. From the first that arrives, the record is not to be trusted: it goes, and this
1529
+ // client is told nothing when it next connects.
1530
+ this.#handled.delete(playerId);
1531
+ return undefined;
1532
+ }
1533
+ return handled;
1534
+ }
1535
+
1536
+ /** Adds to what is noted on a socket itself: see `SocketNote`. */
1537
+ #note(ws: WebSocket, note: SocketNote): void {
1538
+ ws.serializeAttachment({ ...(ws.deserializeAttachment() as SocketNote | null), ...note });
1539
+ }
1540
+
1541
+ /**
1542
+ * Writes which commands were handled, now. Outside the simulation the
1543
+ * state in storage is the state as it is, and the one column is all that
1544
+ * differs. In it, the state goes along, so that the two stay of one moment.
1545
+ */
1546
+ #saveHandled(): void {
1547
+ if (this.#loop === undefined && !this.#unsaved && this.#store.writeHandled(this.#handledJson())) return;
1548
+ this.#writeRoom();
1076
1549
  }
1077
1550
 
1078
1551
  /** Acks the commands `ws` is still owed an answer to, or everyone's. */
@@ -1092,7 +1565,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1092
1565
  if (!playerId || !this.#roster.includes(playerId)) return;
1093
1566
  // A newer connection for the same player took over: nothing to announce, now or
1094
1567
  // when this close arrives after the newer connection has itself gone.
1095
- const mark = ws.deserializeAttachment() as { replaced?: boolean; silent?: boolean } | null;
1568
+ const mark = ws.deserializeAttachment() as SocketNote | null;
1096
1569
  // Or it was closed for its silence, and the player's going was dealt with then.
1097
1570
  if (mark?.replaced || (mark?.silent && !silent)) return;
1098
1571
  if (this.#isConnected(playerId, ws)) return;
@@ -1127,6 +1600,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1127
1600
  if (this.#removed.length > 0 || this.#presenceStale) {
1128
1601
  this.#presenceStale = false;
1129
1602
  for (const { id, reason } of this.#removed.splice(0)) {
1603
+ // A seat taken again starts over.
1604
+ if (!this.#roster.includes(id)) this.#handled.delete(id);
1130
1605
  for (const ws of this.ctx.getWebSockets(id)) {
1131
1606
  try {
1132
1607
  ws.close(CloseCode.Removed, reason.slice(0, MAX_CLOSE_REASON));
@@ -1256,14 +1731,121 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1256
1731
  #syncLoop(): void {
1257
1732
  const wanted = this.#wantsTicks(this.#anySeated());
1258
1733
  if (wanted && this.#loop === undefined) {
1259
- this.#loop = setInterval(() => this.#runTick(), 1000 / this.tickRate);
1734
+ // A clock of its own for every run: the time the simulation spent stopped is not owed back.
1735
+ const now = Date.now();
1736
+ this.#clockTick = this.#tick;
1737
+ this.#clockAt = now;
1738
+ this.#epoch += 1;
1739
+ this.#schedule(now);
1740
+ this.#tellClock(now);
1260
1741
  } else if (!wanted && this.#loop !== undefined) {
1261
- clearInterval(this.#loop);
1742
+ clearTimeout(this.#loop);
1262
1743
  this.#loop = undefined;
1263
- // Send what changed since the last tick, or it would never go out.
1744
+ // Send what changed since the last patch, or it would never go out.
1264
1745
  this.#broadcastTick();
1746
+ if (this.#heldMail.length > 0) {
1747
+ this.#mail.unshift(...this.#heldMail.splice(0));
1748
+ this.#deliverMail();
1749
+ }
1750
+ if (this.#unsaved) this.#writeRoom();
1751
+ // From here on the players are shown every change as it is made: no tick stands for what
1752
+ // they see, so there is none to look back at.
1753
+ this.#history.clear();
1754
+ this.#tellClock(Date.now());
1755
+ }
1756
+ }
1757
+
1758
+ /** When tick `tick` is due by the simulation's clock, in epoch milliseconds. */
1759
+ #dueAt(tick: number): number {
1760
+ return this.#clockAt + ((tick - this.#clockTick) * 1000) / this.tickRate;
1761
+ }
1762
+
1763
+ /** Sets the timer for the moment the next tick is due. */
1764
+ #schedule(now: number): void {
1765
+ const wait = Math.max(0, Math.ceil(this.#dueAt(this.#tick + 1) - now));
1766
+ this.#loop = setTimeout(() => this.#wake(), wait);
1767
+ }
1768
+
1769
+ /**
1770
+ * The simulation's timer fired: run every tick that has come due since the
1771
+ * last wake-up, up to `maxCatchUpTicks`, then send one patch for them all.
1772
+ */
1773
+ #wake(): void {
1774
+ const now = Date.now();
1775
+ const elapsed = ((now - this.#clockAt) * this.tickRate) / 1000;
1776
+ // A hair of slack, so that floating point does not put a tick that is due a moment later.
1777
+ const due = this.#clockTick + Math.floor(elapsed + 1e-6);
1778
+ const cap = Math.max(1, Math.floor(this.maxCatchUpTicks) || 1);
1779
+ let moved = false;
1780
+ if (due - this.#tick > cap) {
1781
+ // Too far behind to catch up: let the rest go, and move the clock on by as many ticks.
1782
+ this.#clockTick -= due - this.#tick - cap;
1783
+ this.#epoch += 1;
1784
+ moved = true;
1785
+ }
1786
+ const until = Math.min(due, this.#tick + cap);
1787
+ const eachTick = patchesEachTick.has(this);
1788
+ const before = this.#tick;
1789
+ let ran = 0;
1790
+ let halted = false;
1791
+ while (this.#tick < until) {
1792
+ // What the last tick did may have stopped the simulation: checked after every tick, as ever.
1793
+ if (ran > 0 && !this.#wantsTicks(this.#anySeated())) {
1794
+ halted = true;
1795
+ break;
1796
+ }
1797
+ if (ran > 0 && eachTick) this.#broadcastTick();
1798
+ this.#runTick();
1799
+ ran += 1;
1800
+ }
1801
+ if (halted) {
1802
+ // `#finish` stops the simulation in a moment. Until it does, no tick is due at once.
1803
+ this.#loop = setTimeout(() => this.#wake(), 1000 / this.tickRate);
1804
+ } else {
1805
+ this.#schedule(now);
1806
+ }
1807
+ if (ran === 0) return; // Woke a little early: nothing is due yet.
1808
+
1809
+ if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
1810
+ this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
1811
+ this.#closeSilent(now);
1812
+ }
1813
+ // Counted in ticks, as ever: catching up does not change when saves happen.
1814
+ this.#ticksSinceSave += ran;
1815
+ if (this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
1816
+ this.#ticksSinceSave = 0;
1265
1817
  if (this.#unsaved) this.#writeRoom();
1266
1818
  }
1819
+ if (this.#patchDue(before) || this.#removed.length > 0) {
1820
+ // Before what these ticks sent, which `#finish` delivers: messages follow the patch.
1821
+ if (this.#heldMail.length > 0) this.#mail.unshift(...this.#heldMail.splice(0));
1822
+ this.#broadcastTick();
1823
+ } else if (this.#mail.length > 0) {
1824
+ // No patch for these ticks yet. What they sent waits for it, so that a message never
1825
+ // arrives before the state it is about. A player who is being removed has to hear why
1826
+ // before the connection closes, which is why such a tick sends.
1827
+ this.#heldMail.push(...this.#mail.splice(0));
1828
+ }
1829
+ if (moved || now - this.#clockToldAt >= CLOCK_EVERY_MS) this.#tellClock(now);
1830
+ this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1831
+ }
1832
+
1833
+ /** `patchRate` where it holds anything back, and 0 where the room sends after every tick. */
1834
+ #patchRate(): number {
1835
+ const rate = this.patchRate;
1836
+ return rate > 0 && rate < this.tickRate && !patchesEachTick.has(this) ? rate : 0;
1837
+ }
1838
+
1839
+ /**
1840
+ * Whether a patch is due now that the ticks after `before` have run. With
1841
+ * a `patchRate`, patches fall due that many times a second by the count of
1842
+ * ticks, so a room that catches up sends no more often than one that
1843
+ * keeps time.
1844
+ */
1845
+ #patchDue(before: number): boolean {
1846
+ const rate = this.#patchRate();
1847
+ if (rate === 0) return true;
1848
+ return Math.floor((this.#tick * rate) / this.tickRate) > Math.floor((before * rate) / this.tickRate);
1267
1849
  }
1268
1850
 
1269
1851
  #runTick(): void {
@@ -1276,19 +1858,50 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1276
1858
  this.#failedTicks = 0;
1277
1859
  this.#stalled = true;
1278
1860
  }
1861
+ this.#remember();
1862
+ }
1279
1863
 
1280
- const now = Date.now();
1281
- if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
1282
- this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
1283
- this.#closeSilent(now);
1864
+ /** Keeps the state the tick that just ran left, and lets go of those older than `historyTicks`. */
1865
+ #remember(): void {
1866
+ const keep = Math.floor(this.historyTicks) || 0;
1867
+ if (keep <= 0) {
1868
+ if (this.#history.size > 0) this.#history.clear();
1869
+ return;
1284
1870
  }
1871
+ // `onEmpty` may have run after the tick, and what it wrote is not in the JSON yet.
1872
+ this.#freshen();
1873
+ const json = this.#committed.state;
1874
+ const last = this.#history.get(this.#tick - 1);
1875
+ // A tick that changed nothing keeps the string the one before it keeps, not one more like it.
1876
+ this.#history.set(this.#tick, last === json ? last : json);
1877
+ for (const tick of this.#history.keys()) {
1878
+ if (tick > this.#tick - keep) break;
1879
+ this.#history.delete(tick);
1880
+ }
1881
+ }
1285
1882
 
1286
- if (++this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
1287
- this.#ticksSinceSave = 0;
1288
- if (this.#unsaved) this.#writeRoom();
1883
+ /** Where the clock is at `now`, for a client of version 4: see `ClockFrame`. */
1884
+ #clockReading(now: number): { ms: number; epoch: number } {
1885
+ return { ms: Math.max(0, Math.round(now - this.#dueAt(this.#tick))), epoch: this.#epoch };
1886
+ }
1887
+
1888
+ /** Tells every client of version 4 where the clock is, or that it stopped. */
1889
+ #tellClock(now: number): void {
1890
+ this.#clockToldAt = now;
1891
+ let frame: string | undefined;
1892
+ for (const ws of this.ctx.getWebSockets()) {
1893
+ if (ws.readyState !== SOCKET_OPEN || !this.#socketInfo(ws).clock) continue;
1894
+ frame ??= JSON.stringify({
1895
+ t: "clock",
1896
+ tick: this.#tick,
1897
+ ...(this.#loop !== undefined ? this.#clockReading(now) : {}),
1898
+ } satisfies ServerMessage);
1899
+ try {
1900
+ ws.send(frame);
1901
+ } catch {
1902
+ // Socket is closing.
1903
+ }
1289
1904
  }
1290
- this.#broadcastTick();
1291
- this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1292
1905
  }
1293
1906
 
1294
1907
  /**
@@ -1308,7 +1921,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1308
1921
  try {
1309
1922
  // Marked: the player drops now, once. If the other end is there after all and answers
1310
1923
  // the close, that is not a second drop.
1311
- ws.serializeAttachment({ silent: true });
1924
+ this.#note(ws, { silent: true });
1312
1925
  ws.close(CloseCode.Silent, "silent");
1313
1926
  } catch {
1314
1927
  // Already closed.
@@ -1344,6 +1957,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1344
1957
  this.#teams = meta.has("teams") ? (JSON.parse(meta.get("teams")!) as string[][]) : null;
1345
1958
  this.#outboxPending = this.#store.hasOutbox();
1346
1959
  this.#seq = room?.seq ?? 0;
1960
+ this.#handled = readHandled(room?.handled);
1347
1961
  let timers = this.#store.timers();
1348
1962
  if (timers.some(([name]) => name === AWAKE_TIMER)) {
1349
1963
  // The deadline lives in memory now. Left with the timers, it would fire for ever.
@@ -1368,6 +1982,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1368
1982
  if (sockets.length > 0 && this.#wantsTicks(true)) {
1369
1983
  for (const { ws, id } of sockets) {
1370
1984
  try {
1985
+ // Commands this client sent since the save are gone with the old instance, and later
1986
+ // ones may still be on their way here: see `#handledFor`.
1987
+ if (this.#socketInfo(ws).client !== undefined) this.#note(ws, { untracked: true });
1371
1988
  this.#welcome(ws, { id, connected: true }, true);
1372
1989
  } catch (err) {
1373
1990
  console.error(`[tickflare] could not send the state to ${id}:`, err);
@@ -1376,6 +1993,21 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1376
1993
  }
1377
1994
  }
1378
1995
 
1996
+ // Spectators whose connections outlasted the instance: what was on its way to them went with
1997
+ // it, so their view starts over. A room that no longer takes any lets them go.
1998
+ const watching = this.#watching();
1999
+ if (watching.length > 0 && this.maxSpectators > 0) {
2000
+ this.#show(true);
2001
+ } else {
2002
+ for (const ws of watching) {
2003
+ try {
2004
+ ws.close(CloseCode.JoinRejected, "no_spectators");
2005
+ } catch {
2006
+ // Already closed.
2007
+ }
2008
+ }
2009
+ }
2010
+
1379
2011
  // Seats left by players who dropped while no timeout was running for them (the option was
1380
2012
  // added or shortened since, or the room was torn down mid-event) get one now.
1381
2013
  const connected = this.#connectedIds();
@@ -1452,7 +2084,40 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1452
2084
  }
1453
2085
 
1454
2086
  #persist(seq: number, committed: Committed): void {
1455
- this.#store.writeRoom({ seq, state: committed.state, roster: committed.roster, tick: this.#tick });
2087
+ this.#store.writeRoom({
2088
+ seq,
2089
+ state: committed.state,
2090
+ roster: committed.roster,
2091
+ tick: this.#tick,
2092
+ handled: this.#handledJson(),
2093
+ });
2094
+ }
2095
+
2096
+ /**
2097
+ * Which commands were handled, for the room's row: by player, the client's
2098
+ * name, its latest `id` and, if any, the refusals. "" when no client named
2099
+ * itself, as in every room whose clients are older than version 5.
2100
+ */
2101
+ #handledJson(): string {
2102
+ if (this.#handled.size === 0) return "";
2103
+ const seated = new Set(this.#roster);
2104
+ const records: string[] = [];
2105
+ let length = 1;
2106
+ for (const [id, handled] of this.#handled) {
2107
+ if (!seated.has(id)) {
2108
+ // A seat that was given up: a seat taken again starts over.
2109
+ this.#handled.delete(id);
2110
+ continue;
2111
+ }
2112
+ const { client, last, from, refused } = handled;
2113
+ handled.json ??= `${JSON.stringify(id)}:${JSON.stringify(from > 0 ? [client, last, refused, from] : refused.length > 0 ? [client, last, refused] : [client, last])}`;
2114
+ records.push(handled.json);
2115
+ length += handled.json.length + 1;
2116
+ }
2117
+ // See `HANDLED_CHARS`. The oldest are first.
2118
+ let skip = 0;
2119
+ while (length > HANDLED_CHARS) length -= records[skip++]!.length + 1;
2120
+ return skip >= records.length ? "" : `{${(skip > 0 ? records.slice(skip) : records).join(",")}}`;
1456
2121
  }
1457
2122
 
1458
2123
  /** Remembers the id this room is reached under, the first time it hears it. */
@@ -1613,6 +2278,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1613
2278
  * one that nothing is known about gets its whole view.
1614
2279
  */
1615
2280
  #broadcastState(before: string): void {
2281
+ this.#show();
1616
2282
  const sockets = this.#seatedSockets();
1617
2283
  if (sockets.length === 0) return;
1618
2284
  const custom = this.view !== Room.prototype.view;
@@ -1652,12 +2318,13 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1652
2318
  shows,
1653
2319
  );
1654
2320
  this.#answer();
2321
+ this.#show();
1655
2322
  }
1656
2323
 
1657
2324
  /** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
1658
2325
  #versionOf(ws: WebSocket): number {
1659
2326
  const info = this.#socketInfo(ws);
1660
- return info.presence ? PROTOCOL_VERSION : info.arrays ? 2 : 1;
2327
+ return info.resumes ? 5 : info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
1661
2328
  }
1662
2329
 
1663
2330
  /**
@@ -1694,6 +2361,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1694
2361
 
1695
2362
  const players = this.players;
1696
2363
  const change = this.#presenceChange(players);
2364
+ if (change && this.#line.running) this.#line.tell(players, Math.max(0, this.spectatorDelayMs));
1697
2365
  let whole: string | undefined;
1698
2366
  let brief: string | undefined;
1699
2367
  for (const { ws } of sockets) {
@@ -1747,6 +2415,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1747
2415
  const mail = this.#mail.splice(0);
1748
2416
  let everyone: { ws: WebSocket; id: string }[] | undefined;
1749
2417
  for (const { to, frame } of mail) {
2418
+ // What is said to everyone is said to those who watch as well, when their time comes.
2419
+ if (to === null && this.#line.running) this.#line.say(frame, Math.max(0, this.spectatorDelayMs));
1750
2420
  const sockets =
1751
2421
  to === null
1752
2422
  ? (everyone ??= this.#seatedSockets()).map(({ ws }) => ws)
@@ -1806,6 +2476,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1806
2476
  binary: tags.includes(BINARY_TAG),
1807
2477
  arrays: tags.includes(V2_TAG),
1808
2478
  presence: tags.includes(V3_TAG),
2479
+ clock: tags.includes(V4_TAG),
2480
+ resumes: tags.includes(V5_TAG),
2481
+ client: this.rememberCommands ? tags.find((tag) => tag.startsWith(CLIENT_TAG))?.slice(CLIENT_TAG.length) : undefined,
2482
+ spectator: tags.includes(SPECTATOR_TAG),
1809
2483
  };
1810
2484
  this.#infos.set(ws, info);
1811
2485
  }
@@ -1851,6 +2525,22 @@ function messageFrame(message: unknown): string {
1851
2525
  return frame;
1852
2526
  }
1853
2527
 
2528
+ /** Reads what `#handledJson` wrote. Anything it cannot read is taken for nothing handled. */
2529
+ function readHandled(json: string | undefined): Map<string, Handled> {
2530
+ const handled = new Map<string, Handled>();
2531
+ if (!json) return handled;
2532
+ try {
2533
+ const stored = JSON.parse(json) as Record<string, [string, number, [number, string][]?, number?]>;
2534
+ for (const [id, [client, last, refused, from]] of Object.entries(stored)) {
2535
+ handled.set(id, { client, last, from: from ?? 0, refused: refused ?? [] });
2536
+ }
2537
+ } catch (err) {
2538
+ console.error("[tickflare] could not read which commands were handled; taking it for none:", err);
2539
+ handled.clear();
2540
+ }
2541
+ return handled;
2542
+ }
2543
+
1854
2544
  function isThenable(value: unknown): value is PromiseLike<unknown> {
1855
2545
  return typeof (value as { then?: unknown } | null | undefined)?.then === "function";
1856
2546
  }