tickflare 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +3 -2
  3. package/dist/client/buffered.d.ts +25 -5
  4. package/dist/client/buffered.js +30 -7
  5. package/dist/client/buffered.js.map +1 -1
  6. package/dist/client/index.d.ts +62 -5
  7. package/dist/client/index.js +193 -14
  8. package/dist/client/index.js.map +1 -1
  9. package/dist/client/interpolate.d.ts +6 -5
  10. package/dist/client/interpolate.js +6 -5
  11. package/dist/client/interpolate.js.map +1 -1
  12. package/dist/client/lockstep.d.ts +23 -4
  13. package/dist/client/lockstep.js +47 -4
  14. package/dist/client/lockstep.js.map +1 -1
  15. package/dist/client/predict.js +16 -3
  16. package/dist/client/predict.js.map +1 -1
  17. package/dist/lockstep.d.ts +43 -4
  18. package/dist/lockstep.js +33 -0
  19. package/dist/lockstep.js.map +1 -1
  20. package/dist/protocol.d.ts +93 -5
  21. package/dist/protocol.js +12 -3
  22. package/dist/protocol.js.map +1 -1
  23. package/dist/server/gateway.d.ts +5 -0
  24. package/dist/server/gateway.js +14 -0
  25. package/dist/server/gateway.js.map +1 -1
  26. package/dist/server/index.d.ts +4 -3
  27. package/dist/server/index.js +3 -2
  28. package/dist/server/index.js.map +1 -1
  29. package/dist/server/lockstep.d.ts +29 -4
  30. package/dist/server/lockstep.js +72 -5
  31. package/dist/server/lockstep.js.map +1 -1
  32. package/dist/server/room.d.ts +118 -1
  33. package/dist/server/room.js +557 -30
  34. package/dist/server/room.js.map +1 -1
  35. package/dist/server/schema.d.ts +67 -0
  36. package/dist/server/schema.js +44 -0
  37. package/dist/server/schema.js.map +1 -0
  38. package/dist/server/spectators.d.ts +74 -0
  39. package/dist/server/spectators.js +190 -0
  40. package/dist/server/spectators.js.map +1 -0
  41. package/dist/server/storage.d.ts +13 -1
  42. package/dist/server/storage.js +23 -5
  43. package/dist/server/storage.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/client/buffered.ts +43 -13
  46. package/src/client/index.ts +237 -14
  47. package/src/client/interpolate.ts +6 -5
  48. package/src/client/lockstep.ts +68 -7
  49. package/src/client/predict.ts +16 -3
  50. package/src/lockstep.ts +67 -4
  51. package/src/protocol.ts +94 -4
  52. package/src/server/gateway.ts +14 -0
  53. package/src/server/index.ts +6 -0
  54. package/src/server/lockstep.ts +70 -6
  55. package/src/server/room.ts +589 -31
  56. package/src/server/schema.ts +101 -0
  57. package/src/server/spectators.ts +221 -0
  58. 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";
@@ -72,8 +73,65 @@ const V2_TAG = "\u0001v=2";
72
73
  const V3_TAG = "\u0001v=3";
73
74
  /** Marks the socket of a client that speaks version 4: it is told the room's clock. */
74
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;
75
94
  const isMark = (tag: string) => tag.charCodeAt(0) === 1;
76
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
+
77
135
  /** What a socket's tags say: whose it is, and what its client asked for. */
78
136
  interface SocketInfo {
79
137
  id: string | undefined;
@@ -85,6 +143,12 @@ interface SocketInfo {
85
143
  presence: boolean;
86
144
  /** Version 4: told the room's clock. */
87
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;
88
152
  }
89
153
  /**
90
154
  * In a room with more than `PRESENCE_CROWD` connections, the least time
@@ -186,6 +250,21 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
186
250
  */
187
251
  protected maxCommandsPerSecond = 30;
188
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
+
189
268
  /**
190
269
  * Where `finishMatch` announces a finished match. Set it to a Queue binding:
191
270
  * `protected override matchQueue = this.env.MATCHES;`
@@ -208,6 +287,78 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
208
287
  /** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
209
288
  protected tickRate = 0;
210
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
+
211
362
  /**
212
363
  * While the room is ticking, the most ticks it runs back to back to catch
213
364
  * up when it wakes late. The simulation keeps to a fixed clock: tick `n`
@@ -307,6 +458,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
307
458
  /** Timer name to the time it fires, in epoch milliseconds. */
308
459
  #timers = new Map<string, number>();
309
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>();
310
465
  /** Seats given up during this event. Their sockets are closed once the event is over. */
311
466
  #removed: { id: string; reason: string }[] = [];
312
467
  /** The timers changed, so the object's alarm has to be moved before the event ends. */
@@ -324,6 +479,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
324
479
  #signals: Signal[] = [];
325
480
  /** Messages for players, as frames, waiting for the end of the event. `to` null is everyone. */
326
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 }[] = [];
327
484
  /** While ticking: the commands each socket has had applied and not yet been told about. */
328
485
  #owed = new Map<WebSocket, number[]>();
329
486
  /** The command being handled, and who sent it. */
@@ -375,6 +532,12 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
375
532
 
376
533
  /** Holds each player to `maxCommandsPerSecond`. */
377
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>();
378
541
 
379
542
  /** Ticks run since the room was created. */
380
543
  #tick = 0;
@@ -499,6 +662,30 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
499
662
  return this.state;
500
663
  }
501
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
+
502
689
  /** Everyone with a seat, in join order. */
503
690
  protected get players(): Player[] {
504
691
  // One pass over the sockets, not one per player: a join tells everyone this list.
@@ -516,6 +703,28 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
516
703
  return this.#tick;
517
704
  }
518
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
+
519
728
  /** The id this room is reached under, once someone has connected through the gateway. */
520
729
  protected get roomId(): string | null {
521
730
  return this.#roomId;
@@ -645,7 +854,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
645
854
  this.#mail.push({ to: playerId, frame: messageFrame(message) });
646
855
  }
647
856
 
648
- /** `send` to every player who is connected. */
857
+ /** `send` to every player who is connected, and to those who watch: see `maxSpectators`. */
649
858
  protected broadcast(message: unknown): void {
650
859
  this.#mail.push({ to: null, frame: messageFrame(message) });
651
860
  }
@@ -819,7 +1028,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
819
1028
 
820
1029
  /** Durable Object entry point for connections and HTTP requests from the gateway. Tickflare's: override `onHttp` instead. */
821
1030
  override async fetch(request: Request): Promise<Response> {
822
- 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;
823
1034
  if (!playerId) {
824
1035
  return new Response("Missing player identity", { status: 401 });
825
1036
  }
@@ -843,11 +1054,22 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
843
1054
  }
844
1055
  }
845
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
+ }
846
1063
  const marks: string[] = [];
847
1064
  if (asked.get("patches") === BINARY_PATCHES) marks.push(BINARY_TAG);
848
1065
  if (Number(asked.get("v")) >= 2) marks.push(V2_TAG);
849
1066
  if (Number(asked.get("v")) >= 3) marks.push(V3_TAG);
850
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
+ }
851
1073
  const response = this.#connect(playerId, name, marks);
852
1074
  await this.#finish();
853
1075
  return response;
@@ -953,8 +1175,12 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
953
1175
  const server = pair[1];
954
1176
  const player: Player = { id: playerId, connected: true };
955
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);
956
1182
 
957
- if (!this.#roster.includes(playerId)) {
1183
+ if (!seated) {
958
1184
  const arrival = this.#store.arrival(playerId);
959
1185
  // A player handed over by another room is always let in.
960
1186
  if (arrival === undefined) {
@@ -979,6 +1205,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
979
1205
  return refuse(client, server, CloseCode.RoomFull, "room_full");
980
1206
  }
981
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: [] });
982
1212
  const joined = this.#apply(() => {
983
1213
  this.#roster.push(playerId);
984
1214
  this.#connecting = playerId;
@@ -990,6 +1220,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
990
1220
  }
991
1221
  });
992
1222
  if (!joined.ok) {
1223
+ this.#handled.delete(playerId);
993
1224
  return refuse(client, server, CloseCode.JoinRejected, joined.reason);
994
1225
  }
995
1226
  } else if (!this.#isConnected(playerId)) {
@@ -1010,14 +1241,117 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1010
1241
  // What the client asked for is kept with the socket, where it outlasts the room's sleep.
1011
1242
  this.ctx.acceptWebSocket(server, [playerId, ...marks]);
1012
1243
  this.#heard.set(server, Date.now());
1013
- 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);
1014
1260
  this.#broadcastPresence(server);
1015
1261
 
1016
1262
  return new Response(null, { status: 101, webSocket: client });
1017
1263
  }
1018
1264
 
1019
- /** Sends a socket everything from the start: who they are, the players and their whole view. */
1020
- #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 {
1021
1355
  const welcome = JSON.stringify({
1022
1356
  t: "welcome",
1023
1357
  v: this.#versionOf(ws),
@@ -1026,6 +1360,10 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1026
1360
  tick: this.#tick,
1027
1361
  tickRate: this.tickRate,
1028
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 } : {}),
1029
1367
  state: this.view(player),
1030
1368
  players: this.players,
1031
1369
  } satisfies ServerMessage);
@@ -1044,7 +1382,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1044
1382
  this.#owed.delete(old);
1045
1383
  try {
1046
1384
  // Marked, so that its close is not taken for the player dropping.
1047
- old.serializeAttachment({ replaced: true });
1385
+ this.#note(old, { replaced: true });
1048
1386
  old.close(CloseCode.Replaced, "replaced");
1049
1387
  } catch {
1050
1388
  // Already closed.
@@ -1054,8 +1392,33 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1054
1392
 
1055
1393
  #receive(ws: WebSocket, message: string | ArrayBuffer): void {
1056
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
+ }
1057
1407
  // A socket whose seat is gone is about to be closed; ignore what it still sends.
1058
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;
1059
1422
 
1060
1423
  // Every frame counts against the limit, including the ones refused below.
1061
1424
  const allowed = this.#limiter.spend(playerId, this.maxCommandsPerSecond);
@@ -1076,15 +1439,50 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1076
1439
  if (!frame) {
1077
1440
  return this.#send(ws, { t: "error", reason: allowed ? "invalid_message" : "rate_limited" });
1078
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
+ };
1079
1479
  if (!allowed) {
1080
1480
  // Answered by id, so the client's pending command settles instead of hanging.
1081
- return this.#send(ws, { t: "reject", id: frame.id, reason: "rate_limited" });
1481
+ return refuse("rate_limited");
1082
1482
  }
1083
1483
 
1084
1484
  const player: Player = { id: playerId, connected: true };
1085
1485
  let outcome: Outcome;
1086
- // While the simulation runs, what a command changed is sent with the next tick.
1087
- const ticking = this.#loop !== undefined;
1088
1486
  if (frame.t === "leave") {
1089
1487
  outcome = this.#apply(() => {
1090
1488
  this.onLeave(player);
@@ -1097,8 +1495,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1097
1495
  try {
1098
1496
  command = this.parseCommand(frame.data);
1099
1497
  } catch (err) {
1100
- const reason = err instanceof Rejection ? err.reason : "invalid_command";
1101
- return this.#send(ws, { t: "reject", id: frame.id, reason });
1498
+ return refuse(err instanceof Rejection ? err.reason : "invalid_command");
1102
1499
  }
1103
1500
  // If this changes what the player sees, the frame that says so says whose command it shows.
1104
1501
  this.#answering = { ws, id: frame.id };
@@ -1109,18 +1506,46 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1109
1506
  }
1110
1507
  }
1111
1508
 
1112
- if (!outcome.ok) {
1113
- return this.#send(ws, { t: "reject", id: frame.id, reason: outcome.reason });
1114
- }
1115
- if (ticking && frame.t === "cmd") {
1116
- // An ack means "you have seen the result", and the result goes out with the tick.
1117
- const owed = this.#owed.get(ws);
1118
- if (owed) owed.push(frame.id);
1119
- else this.#owed.set(ws, [frame.id]);
1120
- return;
1121
- }
1509
+ if (!outcome.ok) return refuse(outcome.reason);
1122
1510
  // The state frame, if any, has already gone out.
1123
- 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();
1124
1549
  }
1125
1550
 
1126
1551
  /** Acks the commands `ws` is still owed an answer to, or everyone's. */
@@ -1140,7 +1565,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1140
1565
  if (!playerId || !this.#roster.includes(playerId)) return;
1141
1566
  // A newer connection for the same player took over: nothing to announce, now or
1142
1567
  // when this close arrives after the newer connection has itself gone.
1143
- const mark = ws.deserializeAttachment() as { replaced?: boolean; silent?: boolean } | null;
1568
+ const mark = ws.deserializeAttachment() as SocketNote | null;
1144
1569
  // Or it was closed for its silence, and the player's going was dealt with then.
1145
1570
  if (mark?.replaced || (mark?.silent && !silent)) return;
1146
1571
  if (this.#isConnected(playerId, ws)) return;
@@ -1175,6 +1600,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1175
1600
  if (this.#removed.length > 0 || this.#presenceStale) {
1176
1601
  this.#presenceStale = false;
1177
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);
1178
1605
  for (const ws of this.ctx.getWebSockets(id)) {
1179
1606
  try {
1180
1607
  ws.close(CloseCode.Removed, reason.slice(0, MAX_CLOSE_REASON));
@@ -1314,9 +1741,16 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1314
1741
  } else if (!wanted && this.#loop !== undefined) {
1315
1742
  clearTimeout(this.#loop);
1316
1743
  this.#loop = undefined;
1317
- // 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.
1318
1745
  this.#broadcastTick();
1746
+ if (this.#heldMail.length > 0) {
1747
+ this.#mail.unshift(...this.#heldMail.splice(0));
1748
+ this.#deliverMail();
1749
+ }
1319
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();
1320
1754
  this.#tellClock(Date.now());
1321
1755
  }
1322
1756
  }
@@ -1351,6 +1785,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1351
1785
  }
1352
1786
  const until = Math.min(due, this.#tick + cap);
1353
1787
  const eachTick = patchesEachTick.has(this);
1788
+ const before = this.#tick;
1354
1789
  let ran = 0;
1355
1790
  let halted = false;
1356
1791
  while (this.#tick < until) {
@@ -1381,11 +1816,38 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1381
1816
  this.#ticksSinceSave = 0;
1382
1817
  if (this.#unsaved) this.#writeRoom();
1383
1818
  }
1384
- this.#broadcastTick();
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
+ }
1385
1829
  if (moved || now - this.#clockToldAt >= CLOCK_EVERY_MS) this.#tellClock(now);
1386
1830
  this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1387
1831
  }
1388
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);
1849
+ }
1850
+
1389
1851
  #runTick(): void {
1390
1852
  this.#tick += 1;
1391
1853
  const ticked = this.#apply(() => this.onTick(1 / this.tickRate), false, true);
@@ -1396,6 +1858,26 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1396
1858
  this.#failedTicks = 0;
1397
1859
  this.#stalled = true;
1398
1860
  }
1861
+ this.#remember();
1862
+ }
1863
+
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;
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
+ }
1399
1881
  }
1400
1882
 
1401
1883
  /** Where the clock is at `now`, for a client of version 4: see `ClockFrame`. */
@@ -1439,7 +1921,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1439
1921
  try {
1440
1922
  // Marked: the player drops now, once. If the other end is there after all and answers
1441
1923
  // the close, that is not a second drop.
1442
- ws.serializeAttachment({ silent: true });
1924
+ this.#note(ws, { silent: true });
1443
1925
  ws.close(CloseCode.Silent, "silent");
1444
1926
  } catch {
1445
1927
  // Already closed.
@@ -1475,6 +1957,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1475
1957
  this.#teams = meta.has("teams") ? (JSON.parse(meta.get("teams")!) as string[][]) : null;
1476
1958
  this.#outboxPending = this.#store.hasOutbox();
1477
1959
  this.#seq = room?.seq ?? 0;
1960
+ this.#handled = readHandled(room?.handled);
1478
1961
  let timers = this.#store.timers();
1479
1962
  if (timers.some(([name]) => name === AWAKE_TIMER)) {
1480
1963
  // The deadline lives in memory now. Left with the timers, it would fire for ever.
@@ -1499,6 +1982,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1499
1982
  if (sockets.length > 0 && this.#wantsTicks(true)) {
1500
1983
  for (const { ws, id } of sockets) {
1501
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 });
1502
1988
  this.#welcome(ws, { id, connected: true }, true);
1503
1989
  } catch (err) {
1504
1990
  console.error(`[tickflare] could not send the state to ${id}:`, err);
@@ -1507,6 +1993,21 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1507
1993
  }
1508
1994
  }
1509
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
+
1510
2011
  // Seats left by players who dropped while no timeout was running for them (the option was
1511
2012
  // added or shortened since, or the room was torn down mid-event) get one now.
1512
2013
  const connected = this.#connectedIds();
@@ -1583,7 +2084,40 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1583
2084
  }
1584
2085
 
1585
2086
  #persist(seq: number, committed: Committed): void {
1586
- 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(",")}}`;
1587
2121
  }
1588
2122
 
1589
2123
  /** Remembers the id this room is reached under, the first time it hears it. */
@@ -1744,6 +2278,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1744
2278
  * one that nothing is known about gets its whole view.
1745
2279
  */
1746
2280
  #broadcastState(before: string): void {
2281
+ this.#show();
1747
2282
  const sockets = this.#seatedSockets();
1748
2283
  if (sockets.length === 0) return;
1749
2284
  const custom = this.view !== Room.prototype.view;
@@ -1783,12 +2318,13 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1783
2318
  shows,
1784
2319
  );
1785
2320
  this.#answer();
2321
+ this.#show();
1786
2322
  }
1787
2323
 
1788
2324
  /** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
1789
2325
  #versionOf(ws: WebSocket): number {
1790
2326
  const info = this.#socketInfo(ws);
1791
- return info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
2327
+ return info.resumes ? 5 : info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
1792
2328
  }
1793
2329
 
1794
2330
  /**
@@ -1825,6 +2361,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1825
2361
 
1826
2362
  const players = this.players;
1827
2363
  const change = this.#presenceChange(players);
2364
+ if (change && this.#line.running) this.#line.tell(players, Math.max(0, this.spectatorDelayMs));
1828
2365
  let whole: string | undefined;
1829
2366
  let brief: string | undefined;
1830
2367
  for (const { ws } of sockets) {
@@ -1878,6 +2415,8 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1878
2415
  const mail = this.#mail.splice(0);
1879
2416
  let everyone: { ws: WebSocket; id: string }[] | undefined;
1880
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));
1881
2420
  const sockets =
1882
2421
  to === null
1883
2422
  ? (everyone ??= this.#seatedSockets()).map(({ ws }) => ws)
@@ -1938,6 +2477,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
1938
2477
  arrays: tags.includes(V2_TAG),
1939
2478
  presence: tags.includes(V3_TAG),
1940
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),
1941
2483
  };
1942
2484
  this.#infos.set(ws, info);
1943
2485
  }
@@ -1983,6 +2525,22 @@ function messageFrame(message: unknown): string {
1983
2525
  return frame;
1984
2526
  }
1985
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
+
1986
2544
  function isThenable(value: unknown): value is PromiseLike<unknown> {
1987
2545
  return typeof (value as { then?: unknown } | null | undefined)?.then === "function";
1988
2546
  }