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
@@ -3,8 +3,9 @@ import { DurableObject } from "cloudflare:workers";
3
3
  import { CloseCode, PING, PONG, PROTOCOL_VERSION, } from "../protocol.js";
4
4
  import { BINARY_PATCHES } from "../binary.js";
5
5
  import { DeltaSender } from "./delta.js";
6
+ import { SpectatorLine, SPECTATOR_ID_TAG, SPECTATOR_TAG } from "./spectators.js";
6
7
  import { MAX_CLOSE_REASON, readFrame, refuse } from "./frames.js";
7
- import { NAME_HEADER, PLAYER_HEADER, ROOM_HEADER } from "./gateway.js";
8
+ import { NAME_HEADER, PLAYER_HEADER, ROOM_HEADER, SPECTATOR_HEADER } from "./gateway.js";
8
9
  import { RateLimiter } from "./limiter.js";
9
10
  import { SignalSender } from "./signals.js";
10
11
  import { Tracker } from "./tracked.js";
@@ -30,6 +31,26 @@ const BINARY_TAG = "\u0001patches=b1";
30
31
  const V2_TAG = "\u0001v=2";
31
32
  /** Marks the socket of a client that speaks version 3: it is told who came and went, not the whole list of players. */
32
33
  const V3_TAG = "\u0001v=3";
34
+ /** Marks the socket of a client that speaks version 4: it is told the room's clock. */
35
+ const V4_TAG = "\u0001v=4";
36
+ /** Marks the socket of a client that speaks version 5: it can be told which of its commands were handled. */
37
+ const V5_TAG = "\u0001v=5";
38
+ /** Starts the tag that holds the name a client of version 5 gave itself. */
39
+ const CLIENT_TAG = "\u0001c=";
40
+ /** What a client may name itself: short, and nothing that needs escaping anywhere. */
41
+ const CLIENT_NAME = /^[\w-]{1,64}$/;
42
+ /** How many of a client's latest refused commands the room remembers the reasons of. */
43
+ const REFUSALS_KEPT = 8;
44
+ /** How much of each of those reasons it remembers, in characters. */
45
+ const REASON_KEPT = 120;
46
+ /**
47
+ * The most that is written to the room's row of which commands were handled,
48
+ * in characters: about fifteen hundred clients. The row holds the state and
49
+ * the seats too, and Cloudflare allows it 2 MB. Past this the clients that
50
+ * connected longest ago are left out, and are told nothing when they come
51
+ * back after the room has slept.
52
+ */
53
+ const HANDLED_CHARS = 100_000;
33
54
  const isMark = (tag) => tag.charCodeAt(0) === 1;
34
55
  /**
35
56
  * In a room with more than `PRESENCE_CROWD` connections, the least time
@@ -54,7 +75,7 @@ const DELETE_RETRY_MS = 30_000;
54
75
  *
55
76
  * Cloudflare takes an object that has had no incoming event for 70 to 140
56
77
  * seconds out of memory, simulation and all. A keepalive does not count:
57
- * Cloudflare answers it without waking the room. A pending `setInterval`
78
+ * Cloudflare answers it without waking the room. A pending timer
58
79
  * holds the object for at most 15 minutes. So without this, a match in which
59
80
  * nobody sends a command would stop, and stay stopped until someone did. An
60
81
  * alarm is an event, and when Cloudflare restarts the room for any other
@@ -76,6 +97,17 @@ const DELETE_PATIENCE_MS = 10_000;
76
97
  const FORWARD_GRACE_MS = 30_000;
77
98
  /** Consecutive failed ticks after which the simulation pauses until the next event. */
78
99
  const MAX_FAILED_TICKS = 5;
100
+ /**
101
+ * Rooms that send a patch for every tick, even when they catch up several at
102
+ * once: a lockstep room's view is one turn, and a client must see each.
103
+ */
104
+ const patchesEachTick = new WeakSet();
105
+ /** Has `room` send a patch for every tick it runs, also when catching up. @internal */
106
+ export function patchEachTick(room) {
107
+ patchesEachTick.add(room);
108
+ }
109
+ /** While the simulation runs, how often clients of version 4 are told the room's clock, in milliseconds. */
110
+ const CLOCK_EVERY_MS = 5_000;
79
111
  /**
80
112
  * An authoritative game room: one Durable Object per room.
81
113
  *
@@ -113,6 +145,20 @@ export class Room extends DurableObject {
113
145
  * `rate_limited` and never reach `parseCommand`. `Infinity` turns it off.
114
146
  */
115
147
  maxCommandsPerSecond = 30;
148
+ /**
149
+ * Whether the room remembers which commands of each client it has handled,
150
+ * so that a client whose connection dropped can be told when it is back,
151
+ * send again the ones that never arrived, and have none applied twice.
152
+ * `RoomClient` does this by itself. On by default.
153
+ *
154
+ * What was handled is saved with the state, in the same row, so the two
155
+ * are always of the same moment. A ticking room that also records commands
156
+ * somewhere of its own as they arrive should call `saveNow()` in the same
157
+ * hook, as for anything else it writes itself, or turn this off: after a
158
+ * restart the room would otherwise take a command that is sent again for
159
+ * new, though its own record has it.
160
+ */
161
+ rememberCommands = true;
116
162
  /**
117
163
  * Where `finishMatch` announces a finished match. Set it to a Queue binding:
118
164
  * `protected override matchQueue = this.env.MATCHES;`
@@ -131,6 +177,89 @@ export class Room extends DurableObject {
131
177
  rooms;
132
178
  /** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
133
179
  tickRate = 0;
180
+ /**
181
+ * How many times a second a ticking room sends what changed, when that is
182
+ * to be less often than it simulates. 0, the default, sends after every
183
+ * tick, and so does any rate that is not below `tickRate`.
184
+ *
185
+ * With `tickRate = 60` and `patchRate = 20` the room moves things sixty
186
+ * times a second and sends every third tick, in one patch that takes each
187
+ * player's view from the last one sent to now. What a patch costs, the
188
+ * comparison of every player's view and the bytes, is then paid a third
189
+ * as often; a tick costs what it did. With a rate that does not divide
190
+ * `tickRate` the gaps between patches differ by a tick, and average out.
191
+ *
192
+ * What waits for the patch: the `ack` of a command, since it says that
193
+ * the view shows the command, and messages sent with `send()` and
194
+ * `broadcast()` from `onTick`, so that they still arrive after the patch
195
+ * that shows their tick. Whatever is waiting goes out at once when the
196
+ * simulation stops, and in a tick that removes a player. A lockstep room
197
+ * sends every turn, whatever this says.
198
+ *
199
+ * `RoomClient.patchRate` tells the client, and `BufferedInterpolator`
200
+ * keeps as much more of a delay as it takes to always have two patches to
201
+ * draw between.
202
+ */
203
+ patchRate = 0;
204
+ /**
205
+ * How many connections may watch the room without a seat in it. 0, the
206
+ * default, lets nobody watch.
207
+ *
208
+ * A spectator connects with `?spectate=1` (`new RoomClient(url, {
209
+ * spectate: true })`) and is sent `spectatorView()`, kept up to date as a
210
+ * player's view is. They take no seat: they are not among `players`, no
211
+ * hook but `onSpectate` hears of them, what they send is refused, and a
212
+ * room with nobody but spectators connected is empty. They also hear what
213
+ * the room sends with `broadcast()`, and who is here.
214
+ *
215
+ * Not for lockstep rooms, whose state is on the clients.
216
+ */
217
+ maxSpectators = 0;
218
+ /**
219
+ * How far behind the room its spectators are, in milliseconds. 0, the
220
+ * default, sends them every change as the players are sent it.
221
+ *
222
+ * With a delay, nothing reaches a spectator sooner than that after the
223
+ * players: not the view, not who is here, not a broadcast. It is what
224
+ * keeps someone who watches from telling someone who plays what they
225
+ * cannot see yet. A spectator who connects waits this long for their first
226
+ * view, unless others are watching already.
227
+ *
228
+ * What it costs: the changes of that long are held in memory, and a room
229
+ * that would be asleep stays awake for as long after each change, while
230
+ * someone watches.
231
+ */
232
+ spectatorDelayMs = 0;
233
+ /**
234
+ * How many ticks of the state a ticking room keeps to look back at with
235
+ * `stateAt`. 0, the default, keeps none.
236
+ *
237
+ * It is for judging a command by what its player was looking at when they
238
+ * sent it, which is a moment ago: a shot at a runner drawn where they were
239
+ * a tenth of a second back. Set it to as many ticks as the lag you mean to
240
+ * forgive: 12 at 60 ticks a second is 200 ms. It is also as far as a client
241
+ * that lies about what it saw can reach back, so no more than that.
242
+ *
243
+ * Kept in memory, as the JSON the room has of each tick anyway: it costs no
244
+ * work in a tick, and as many states of memory as it is long. A room that
245
+ * restarts, or whose simulation stops, has none until it has ticked again.
246
+ */
247
+ historyTicks = 0;
248
+ /**
249
+ * While the room is ticking, the most ticks it runs back to back to catch
250
+ * up when it wakes late. The simulation keeps to a fixed clock: tick `n`
251
+ * is due `n / tickRate` seconds after the clock started, and a room that
252
+ * wakes late, because a tick or an event took long or the machine was
253
+ * busy, runs every tick that has come due since, each with the same `dt`,
254
+ * and sends one patch for all of them.
255
+ *
256
+ * When more than this many are due, after a stall of a fraction of a
257
+ * second, the room runs this many and lets the rest go: the clock moves on,
258
+ * and the game is that much behind the wall clock for good, instead of
259
+ * fast-forwarding through a burst of ticks. 1 never catches up, which is
260
+ * how rooms ran before 0.2.
261
+ */
262
+ maxCatchUpTicks = 5;
134
263
  /**
135
264
  * While the room is ticking, how often the state is written to storage, in
136
265
  * milliseconds. It is also written whenever the simulation stops. A room
@@ -208,6 +337,10 @@ export class Room extends DurableObject {
208
337
  /** Timer name to the time it fires, in epoch milliseconds. */
209
338
  #timers = new Map();
210
339
  #committed = { state: "", roster: "[]", timers: "[]" };
340
+ /** What the spectators are sent, and when: see `SpectatorLine`. */
341
+ #line = new SpectatorLine(() => this.#watching());
342
+ /** The state after each of the last `historyTicks` ticks, by tick: see `stateAt`. In order of tick. */
343
+ #history = new Map();
211
344
  /** Seats given up during this event. Their sockets are closed once the event is over. */
212
345
  #removed = [];
213
346
  /** The timers changed, so the object's alarm has to be moved before the event ends. */
@@ -224,6 +357,8 @@ export class Room extends DurableObject {
224
357
  #signals = [];
225
358
  /** Messages for players, as frames, waiting for the end of the event. `to` null is everyone. */
226
359
  #mail = [];
360
+ /** Messages sent from ticks that no patch has followed yet: see `patchRate`. */
361
+ #heldMail = [];
227
362
  /** While ticking: the commands each socket has had applied and not yet been told about. */
228
363
  #owed = new Map();
229
364
  /** The command being handled, and who sent it. */
@@ -274,10 +409,27 @@ export class Room extends DurableObject {
274
409
  #reading = 0;
275
410
  /** Holds each player to `maxCommandsPerSecond`. */
276
411
  #limiter = new RateLimiter();
412
+ /**
413
+ * Which commands of each seated player's client have been handled: see
414
+ * `Handled`. Saved in the room's row whenever the state is, so that what
415
+ * storage says was handled is what the saved state shows.
416
+ */
417
+ #handled = new Map();
277
418
  /** Ticks run since the room was created. */
278
419
  #tick = 0;
279
- /** Set while the simulation is running. */
420
+ /** Set while the simulation is running: the timer for the next wake-up. */
280
421
  #loop;
422
+ /**
423
+ * The simulation's clock: tick `#clockTick` was due at `#clockAt`, in epoch
424
+ * milliseconds, and each tick after it `1000 / tickRate` later. Set when
425
+ * the simulation starts, and moved on when ticks are let go.
426
+ */
427
+ #clockTick = 0;
428
+ #clockAt = 0;
429
+ /** Goes up each time the clock starts over or moves on: a client keeps a clock per epoch. */
430
+ #epoch = 0;
431
+ /** When clients were last told the clock, in epoch milliseconds. */
432
+ #clockToldAt = 0;
281
433
  /** The committed state is newer than what is in storage. Only happens while ticking. */
282
434
  #unsaved = false;
283
435
  #ticksSinceSave = 0;
@@ -319,7 +471,9 @@ export class Room extends DurableObject {
319
471
  onTimer(_name) { }
320
472
  /**
321
473
  * Advance the simulation by one step of `dt` seconds (always `1 / tickRate`).
322
- * Runs `tickRate` times a second while the room is ticking.
474
+ * Runs `tickRate` times a second while the room is ticking, on a fixed
475
+ * clock: a room that wakes late runs the ticks it owes back to back. See
476
+ * `maxCatchUpTicks`.
323
477
  */
324
478
  onTick(_dt) { }
325
479
  /**
@@ -359,6 +513,27 @@ export class Room extends DurableObject {
359
513
  view(_player) {
360
514
  return this.state;
361
515
  }
516
+ /**
517
+ * What spectators see: one view for all of them. Defaults to the whole
518
+ * state, in a room where that is what players see too. A room with a
519
+ * `view()` of its own hides something from its players, and has to say
520
+ * here what someone who watches may see: until it does, it takes no
521
+ * spectators.
522
+ */
523
+ spectatorView() {
524
+ return this.state;
525
+ }
526
+ /**
527
+ * Someone asks to watch, in a room with `maxSpectators`. Throw
528
+ * `reject("reason")` to turn them away. `player.connected` says whether
529
+ * they also hold a seat and are connected to it. A hook like the others:
530
+ * what it changes is kept.
531
+ */
532
+ onSpectate(_player) { }
533
+ /** How many spectators are connected. */
534
+ get spectators() {
535
+ return this.#watching().length;
536
+ }
362
537
  /** Everyone with a seat, in join order. */
363
538
  get players() {
364
539
  // One pass over the sockets, not one per player: a join tells everyone this list.
@@ -373,6 +548,27 @@ export class Room extends DurableObject {
373
548
  get tick() {
374
549
  return this.#tick;
375
550
  }
551
+ /**
552
+ * The state as it was after tick `tick`, which is what the patch of that
553
+ * tick showed, or undefined if the room does not have it: `historyTicks`
554
+ * is 0, the tick is older than that many ticks or has not run yet, or the
555
+ * simulation has stopped or the room restarted since. The latest it has is
556
+ * `stateAt(this.tick)`, the state as the last tick left it, without what
557
+ * commands did since. Where there is none, judge by `this.state`.
558
+ *
559
+ * A tick with a fraction, as `BufferedInterpolator.drawnTick()` gives it,
560
+ * is taken as the nearest whole one. Where half a tick matters, take the
561
+ * ticks on either side and blend what you need from them.
562
+ *
563
+ * It is the whole state, not a player's view of it, and a copy of your
564
+ * own, made from that tick's JSON on every call: it costs what the state
565
+ * weighs to parse, so call it once for a command and keep what it gave.
566
+ * Changing the copy changes nothing in the room.
567
+ */
568
+ stateAt(tick) {
569
+ const kept = this.#history.get(Math.round(tick));
570
+ return kept === undefined ? undefined : JSON.parse(kept);
571
+ }
376
572
  /** The id this room is reached under, once someone has connected through the gateway. */
377
573
  get roomId() {
378
574
  return this.#roomId;
@@ -495,7 +691,7 @@ export class Room extends DurableObject {
495
691
  send(playerId, message) {
496
692
  this.#mail.push({ to: playerId, frame: messageFrame(message) });
497
693
  }
498
- /** `send` to every player who is connected. */
694
+ /** `send` to every player who is connected, and to those who watch: see `maxSpectators`. */
499
695
  broadcast(message) {
500
696
  this.#mail.push({ to: null, frame: messageFrame(message) });
501
697
  }
@@ -658,7 +854,9 @@ export class Room extends DurableObject {
658
854
  }
659
855
  /** Durable Object entry point for connections and HTTP requests from the gateway. Tickflare's: override `onHttp` instead. */
660
856
  async fetch(request) {
661
- const playerId = request.headers.get(PLAYER_HEADER);
857
+ // Someone who asks to watch comes under a header of their own: see `routeToRoom`.
858
+ const watcherId = request.headers.get(SPECTATOR_HEADER);
859
+ const playerId = request.headers.get(PLAYER_HEADER) ?? watcherId;
662
860
  if (!playerId) {
663
861
  return new Response("Missing player identity", { status: 401 });
664
862
  }
@@ -685,6 +883,12 @@ export class Room extends DurableObject {
685
883
  }
686
884
  }
687
885
  const asked = new URL(request.url).searchParams;
886
+ // By the header, or by the query alone when the gateway in front is not `routeToRoom`.
887
+ if (watcherId !== null || asked.get("spectate") === "1") {
888
+ const response = this.#spectate(playerId, name);
889
+ await this.#finish();
890
+ return response;
891
+ }
688
892
  const marks = [];
689
893
  if (asked.get("patches") === BINARY_PATCHES)
690
894
  marks.push(BINARY_TAG);
@@ -692,6 +896,14 @@ export class Room extends DurableObject {
692
896
  marks.push(V2_TAG);
693
897
  if (Number(asked.get("v")) >= 3)
694
898
  marks.push(V3_TAG);
899
+ if (Number(asked.get("v")) >= 4)
900
+ marks.push(V4_TAG);
901
+ if (Number(asked.get("v")) >= 5) {
902
+ marks.push(V5_TAG);
903
+ const client = asked.get("client");
904
+ if (this.rememberCommands && client !== null && CLIENT_NAME.test(client))
905
+ marks.push(CLIENT_TAG + client);
906
+ }
695
907
  const response = this.#connect(playerId, name, marks);
696
908
  await this.#finish();
697
909
  return response;
@@ -795,7 +1007,11 @@ export class Room extends DurableObject {
795
1007
  const player = { id: playerId, connected: true };
796
1008
  if (name !== undefined)
797
1009
  player.name = name;
798
- if (!this.#roster.includes(playerId)) {
1010
+ /** The player had their seat before this connection: what their client sent before was sent to this seat. */
1011
+ const seated = this.#roster.includes(playerId);
1012
+ /** The name the client gave itself, if the room remembers commands and it gave one. */
1013
+ const named = marks.find((mark) => mark.startsWith(CLIENT_TAG))?.slice(CLIENT_TAG.length);
1014
+ if (!seated) {
799
1015
  const arrival = this.#store.arrival(playerId);
800
1016
  // A player handed over by another room is always let in.
801
1017
  if (arrival === undefined) {
@@ -822,6 +1038,11 @@ export class Room extends DurableObject {
822
1038
  return refuse(client, server, CloseCode.RoomFull, "room_full");
823
1039
  }
824
1040
  }
1041
+ // A new seat starts over: nothing sent to an earlier one counts. Noted before the join is
1042
+ // saved, so that the same write holds it.
1043
+ this.#handled.delete(playerId);
1044
+ if (named !== undefined)
1045
+ this.#handled.set(playerId, { client: named, last: 0, from: 0, refused: [] });
825
1046
  const joined = this.#apply(() => {
826
1047
  this.#roster.push(playerId);
827
1048
  this.#connecting = playerId;
@@ -834,6 +1055,7 @@ export class Room extends DurableObject {
834
1055
  }
835
1056
  });
836
1057
  if (!joined.ok) {
1058
+ this.#handled.delete(playerId);
837
1059
  return refuse(client, server, CloseCode.JoinRejected, joined.reason);
838
1060
  }
839
1061
  }
@@ -854,12 +1076,119 @@ export class Room extends DurableObject {
854
1076
  // What the client asked for is kept with the socket, where it outlasts the room's sleep.
855
1077
  this.ctx.acceptWebSocket(server, [playerId, ...marks]);
856
1078
  this.#heard.set(server, Date.now());
857
- this.#welcome(server, player, this.#loop !== undefined);
1079
+ let resumed;
1080
+ if (named !== undefined && seated) {
1081
+ const known = this.#handled.get(playerId);
1082
+ if (known?.client === named) {
1083
+ // The client the seat last heard from, on a new connection: it is told how far the room
1084
+ // got with its commands.
1085
+ resumed = known;
1086
+ }
1087
+ else {
1088
+ // Another client than the one the room remembers: a page that was loaded again, or a
1089
+ // second device. Whether the room ever heard from it is not known, so it is told nothing,
1090
+ // and counts from here. Written now: a client the room knows is one in storage.
1091
+ this.#handled.set(playerId, { client: named, last: 0, from: 0, refused: [] });
1092
+ this.#saveHandled();
1093
+ }
1094
+ }
1095
+ this.#welcome(server, player, this.#loop !== undefined, resumed);
858
1096
  this.#broadcastPresence(server);
859
1097
  return new Response(null, { status: 101, webSocket: client });
860
1098
  }
861
- /** Sends a socket everything from the start: who they are, the players and their whole view. */
862
- #welcome(ws, player, ticking) {
1099
+ /** Someone asks to watch: see `maxSpectators`. */
1100
+ #spectate(playerId, name) {
1101
+ const pair = new WebSocketPair();
1102
+ const client = pair[0];
1103
+ const server = pair[1];
1104
+ const tag = SPECTATOR_ID_TAG + playerId;
1105
+ // Cloudflare takes no tag longer than this.
1106
+ if (!(this.maxSpectators > 0) || patchesEachTick.has(this) || tag.length > 256) {
1107
+ return refuse(client, server, CloseCode.JoinRejected, "no_spectators");
1108
+ }
1109
+ if (this.view !== _a.prototype.view && this.spectatorView === _a.prototype.spectatorView) {
1110
+ console.error("[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.");
1111
+ return refuse(client, server, CloseCode.JoinRejected, "no_spectators");
1112
+ }
1113
+ const others = this.#watching().filter((ws) => !this.ctx.getTags(ws).includes(tag));
1114
+ if (others.length >= this.maxSpectators) {
1115
+ return refuse(client, server, CloseCode.RoomFull, "spectators_full");
1116
+ }
1117
+ const player = { id: playerId, connected: this.#isConnected(playerId) };
1118
+ if (name !== undefined)
1119
+ player.name = name;
1120
+ const asked = this.#apply(() => this.onSpectate(player));
1121
+ if (!asked.ok)
1122
+ return refuse(client, server, CloseCode.JoinRejected, asked.reason);
1123
+ // One connection per spectator: the newest wins.
1124
+ for (const old of this.ctx.getWebSockets(tag)) {
1125
+ try {
1126
+ old.close(CloseCode.Replaced, "replaced");
1127
+ }
1128
+ catch {
1129
+ // Already closed.
1130
+ }
1131
+ }
1132
+ // Before this socket is among those the line sends to: what a line without a delay lets out
1133
+ // at once is in the welcome.
1134
+ if (!this.#line.running)
1135
+ this.#show(true);
1136
+ this.ctx.acceptWebSocket(server, [SPECTATOR_TAG, tag]);
1137
+ this.#heard.set(server, Date.now());
1138
+ // Nothing of the room as it is now: who they are, then what the others have been shown. For
1139
+ // the first to watch there is no such view yet, and it follows when its time has come.
1140
+ this.#send(server, {
1141
+ t: "spectating",
1142
+ v: 5,
1143
+ you: playerId,
1144
+ tickRate: this.tickRate,
1145
+ ...(this.#patchRate() > 0 ? { patchRate: this.#patchRate() } : {}),
1146
+ delay: Math.max(0, this.spectatorDelayMs),
1147
+ players: this.#line.players ?? [],
1148
+ });
1149
+ const shown = this.#line.shown;
1150
+ if (shown)
1151
+ this.#send(server, { t: "state", seq: shown.seq, tick: shown.tick, state: shown.view });
1152
+ return new Response(null, { status: 101, webSocket: client });
1153
+ }
1154
+ /** The open sockets of the spectators. */
1155
+ #watching() {
1156
+ return this.ctx.getWebSockets(SPECTATOR_TAG).filter((ws) => ws.readyState === SOCKET_OPEN);
1157
+ }
1158
+ /**
1159
+ * The players have just been sent the state as it is now: the spectators'
1160
+ * line takes their view of it. `starting` when it is to start whoever is
1161
+ * watching, for a spectator who is about to be.
1162
+ */
1163
+ #show(starting = false) {
1164
+ if (!this.#line.running && !starting) {
1165
+ // Stopped while someone watches: it held too much, and starts over.
1166
+ if (!(this.maxSpectators > 0) || this.#watching().length === 0)
1167
+ return;
1168
+ starting = true;
1169
+ }
1170
+ if (!starting && !this.#line.keep(this.#watching().length > 0))
1171
+ return;
1172
+ let view;
1173
+ try {
1174
+ view = this.spectatorView();
1175
+ }
1176
+ catch (err) {
1177
+ console.error("[tickflare] spectatorView() failed; the spectators keep the view they have:", err);
1178
+ return;
1179
+ }
1180
+ const delay = Math.max(0, this.spectatorDelayMs);
1181
+ const begins = !this.#line.running;
1182
+ this.#line.take(view, this.#seq, this.#tick, delay);
1183
+ if (begins)
1184
+ this.#line.tell(this.players, delay);
1185
+ }
1186
+ /**
1187
+ * Sends a socket everything from the start: who they are, the players and
1188
+ * their whole view. `resumed`, on a new connection of a client that held
1189
+ * the seat before, also tells it which of its commands were handled.
1190
+ */
1191
+ #welcome(ws, player, ticking, resumed) {
863
1192
  const welcome = JSON.stringify({
864
1193
  t: "welcome",
865
1194
  v: this.#versionOf(ws),
@@ -867,6 +1196,11 @@ export class Room extends DurableObject {
867
1196
  seq: this.#seq,
868
1197
  tick: this.#tick,
869
1198
  tickRate: this.tickRate,
1199
+ ...(this.#loop !== undefined && this.#socketInfo(ws).clock ? this.#clockReading(Date.now()) : {}),
1200
+ ...(this.#patchRate() > 0 ? { patchRate: this.#patchRate() } : {}),
1201
+ ...(resumed ? { c: resumed.last } : {}),
1202
+ ...(resumed && resumed.from > 0 ? { from: resumed.from } : {}),
1203
+ ...(resumed && resumed.refused.length > 0 ? { refused: resumed.refused } : {}),
870
1204
  state: this.view(player),
871
1205
  players: this.players,
872
1206
  });
@@ -884,7 +1218,7 @@ export class Room extends DurableObject {
884
1218
  this.#owed.delete(old);
885
1219
  try {
886
1220
  // Marked, so that its close is not taken for the player dropping.
887
- old.serializeAttachment({ replaced: true });
1221
+ this.#note(old, { replaced: true });
888
1222
  old.close(CloseCode.Replaced, "replaced");
889
1223
  }
890
1224
  catch {
@@ -894,9 +1228,39 @@ export class Room extends DurableObject {
894
1228
  }
895
1229
  #receive(ws, message) {
896
1230
  const playerId = this.#playerOf(ws);
1231
+ if (!playerId && this.#socketInfo(ws).spectator) {
1232
+ // Watching is all a spectator does. Answered by id, so that a client's promise settles.
1233
+ if (typeof message !== "string" || message.length > this.maxMessageLength)
1234
+ return;
1235
+ let frame;
1236
+ try {
1237
+ frame = readFrame(JSON.parse(message));
1238
+ }
1239
+ catch {
1240
+ return;
1241
+ }
1242
+ if (frame)
1243
+ this.#send(ws, { t: "reject", id: frame.id, reason: "spectator" });
1244
+ return;
1245
+ }
897
1246
  // A socket whose seat is gone is about to be closed; ignore what it still sends.
898
1247
  if (!playerId || !this.#roster.includes(playerId))
899
1248
  return;
1249
+ // What the room notes on the socket of a client that named itself decides what its commands
1250
+ // count for: see `#handledFor`.
1251
+ const client = this.#socketInfo(ws).client;
1252
+ const note = client === undefined ? null : ws.deserializeAttachment();
1253
+ // A newer connection took over. If it is the same client's, it sends again whatever was not
1254
+ // handled when it was welcomed, and what still arrives here would be handled twice. If it is
1255
+ // another's, this one has been told to stop.
1256
+ if (note?.replaced)
1257
+ return;
1258
+ // The same, where the mark is missing: a connection that was closing already when the newer
1259
+ // one came is not among the room's sockets any more, and what it sent before it closed can
1260
+ // still arrive. The room keeps count for the client that connected last, so a socket of
1261
+ // another client is an older one. Its commands would be applied as they come, repeats too.
1262
+ if (client !== undefined && (this.#handled.get(playerId)?.client ?? client) !== client)
1263
+ return;
900
1264
  // Every frame counts against the limit, including the ones refused below.
901
1265
  const allowed = this.#limiter.spend(playerId, this.maxCommandsPerSecond);
902
1266
  if (typeof message !== "string") {
@@ -916,14 +1280,53 @@ export class Room extends DurableObject {
916
1280
  if (!frame) {
917
1281
  return this.#send(ws, { t: "error", reason: allowed ? "invalid_message" : "rate_limited" });
918
1282
  }
1283
+ // While the simulation runs, what a command changed is sent with the next tick.
1284
+ const ticking = this.#loop !== undefined;
1285
+ /** An ack means "you have seen the result": at once, or with the tick that sends the result. */
1286
+ const ack = () => {
1287
+ if (!ticking || frame.t !== "cmd")
1288
+ return this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1289
+ const owed = this.#owed.get(ws);
1290
+ if (owed)
1291
+ owed.push(frame.id);
1292
+ else
1293
+ this.#owed.set(ws, [frame.id]);
1294
+ };
1295
+ const handled = this.#handledFor(ws, playerId, note);
1296
+ if (handled && frame.id <= handled.last) {
1297
+ // Sent before, on a connection that was lost before its answer arrived, and handled
1298
+ // then: answered as it was, and not applied again.
1299
+ const refusal = handled.refused.find(([id]) => id === frame.id);
1300
+ return refusal ? this.#send(ws, { t: "reject", id: frame.id, reason: refusal[1] }) : ack();
1301
+ }
1302
+ // From here on the command is handled, whatever becomes of it. If it changes the state, the
1303
+ // save that holds the change says so too: they are written together.
1304
+ if (handled) {
1305
+ // Not the one after the last: of those between, the room cannot say what became. The client
1306
+ // gave them up, or they were handled without a write before the room slept: a refusal, or a
1307
+ // command that changed nothing. Taking them for applied, as the count alone would have it,
1308
+ // could tell a client that a command it was refused went through.
1309
+ if (frame.id > handled.last + 1)
1310
+ handled.from = frame.id - 1;
1311
+ handled.last = frame.id;
1312
+ handled.json = undefined;
1313
+ }
1314
+ const refuse = (reason) => {
1315
+ if (handled) {
1316
+ handled.refused.push([frame.id, reason.slice(0, REASON_KEPT)]);
1317
+ // A refusal the room forgets is one it can no longer tell from a command it applied.
1318
+ if (handled.refused.length > REFUSALS_KEPT)
1319
+ handled.from = Math.max(handled.from, handled.refused.shift()[0]);
1320
+ handled.json = undefined;
1321
+ }
1322
+ this.#send(ws, { t: "reject", id: frame.id, reason });
1323
+ };
919
1324
  if (!allowed) {
920
1325
  // Answered by id, so the client's pending command settles instead of hanging.
921
- return this.#send(ws, { t: "reject", id: frame.id, reason: "rate_limited" });
1326
+ return refuse("rate_limited");
922
1327
  }
923
1328
  const player = { id: playerId, connected: true };
924
1329
  let outcome;
925
- // While the simulation runs, what a command changed is sent with the next tick.
926
- const ticking = this.#loop !== undefined;
927
1330
  if (frame.t === "leave") {
928
1331
  outcome = this.#apply(() => {
929
1332
  this.onLeave(player);
@@ -939,8 +1342,7 @@ export class Room extends DurableObject {
939
1342
  command = this.parseCommand(frame.data);
940
1343
  }
941
1344
  catch (err) {
942
- const reason = err instanceof Rejection ? err.reason : "invalid_command";
943
- return this.#send(ws, { t: "reject", id: frame.id, reason });
1345
+ return refuse(err instanceof Rejection ? err.reason : "invalid_command");
944
1346
  }
945
1347
  // If this changes what the player sees, the frame that says so says whose command it shows.
946
1348
  this.#answering = { ws, id: frame.id };
@@ -951,20 +1353,47 @@ export class Room extends DurableObject {
951
1353
  this.#answering = undefined;
952
1354
  }
953
1355
  }
954
- if (!outcome.ok) {
955
- return this.#send(ws, { t: "reject", id: frame.id, reason: outcome.reason });
1356
+ if (!outcome.ok)
1357
+ return refuse(outcome.reason);
1358
+ // The state frame, if any, has already gone out.
1359
+ ack();
1360
+ }
1361
+ /**
1362
+ * What the room remembers of the commands of the client on `ws`, to tell
1363
+ * a command that is sent again from a new one. Undefined for a client
1364
+ * that did not name itself, and for one the room has no record of: its
1365
+ * commands are applied as they come.
1366
+ */
1367
+ #handledFor(ws, playerId, note) {
1368
+ const client = this.#socketInfo(ws).client;
1369
+ if (client === undefined)
1370
+ return undefined;
1371
+ const handled = this.#handled.get(playerId);
1372
+ if (handled?.client !== client)
1373
+ return undefined;
1374
+ if (note?.untracked) {
1375
+ // The room came back from an older save under this connection. Commands the save does not
1376
+ // hold may be followed here by later ones, so their numbers no longer say which the room
1377
+ // has. From the first that arrives, the record is not to be trusted: it goes, and this
1378
+ // client is told nothing when it next connects.
1379
+ this.#handled.delete(playerId);
1380
+ return undefined;
956
1381
  }
957
- if (ticking && frame.t === "cmd") {
958
- // An ack means "you have seen the result", and the result goes out with the tick.
959
- const owed = this.#owed.get(ws);
960
- if (owed)
961
- owed.push(frame.id);
962
- else
963
- this.#owed.set(ws, [frame.id]);
1382
+ return handled;
1383
+ }
1384
+ /** Adds to what is noted on a socket itself: see `SocketNote`. */
1385
+ #note(ws, note) {
1386
+ ws.serializeAttachment({ ...ws.deserializeAttachment(), ...note });
1387
+ }
1388
+ /**
1389
+ * Writes which commands were handled, now. Outside the simulation the
1390
+ * state in storage is the state as it is, and the one column is all that
1391
+ * differs. In it, the state goes along, so that the two stay of one moment.
1392
+ */
1393
+ #saveHandled() {
1394
+ if (this.#loop === undefined && !this.#unsaved && this.#store.writeHandled(this.#handledJson()))
964
1395
  return;
965
- }
966
- // The state frame, if any, has already gone out.
967
- this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1396
+ this.#writeRoom();
968
1397
  }
969
1398
  /** Acks the commands `ws` is still owed an answer to, or everyone's. */
970
1399
  #answer(ws) {
@@ -1022,6 +1451,9 @@ export class Room extends DurableObject {
1022
1451
  if (this.#removed.length > 0 || this.#presenceStale) {
1023
1452
  this.#presenceStale = false;
1024
1453
  for (const { id, reason } of this.#removed.splice(0)) {
1454
+ // A seat taken again starts over.
1455
+ if (!this.#roster.includes(id))
1456
+ this.#handled.delete(id);
1025
1457
  for (const ws of this.ctx.getWebSockets(id)) {
1026
1458
  try {
1027
1459
  ws.close(CloseCode.Removed, reason.slice(0, MAX_CLOSE_REASON));
@@ -1156,17 +1588,126 @@ export class Room extends DurableObject {
1156
1588
  #syncLoop() {
1157
1589
  const wanted = this.#wantsTicks(this.#anySeated());
1158
1590
  if (wanted && this.#loop === undefined) {
1159
- this.#loop = setInterval(() => this.#runTick(), 1000 / this.tickRate);
1591
+ // A clock of its own for every run: the time the simulation spent stopped is not owed back.
1592
+ const now = Date.now();
1593
+ this.#clockTick = this.#tick;
1594
+ this.#clockAt = now;
1595
+ this.#epoch += 1;
1596
+ this.#schedule(now);
1597
+ this.#tellClock(now);
1160
1598
  }
1161
1599
  else if (!wanted && this.#loop !== undefined) {
1162
- clearInterval(this.#loop);
1600
+ clearTimeout(this.#loop);
1163
1601
  this.#loop = undefined;
1164
- // Send what changed since the last tick, or it would never go out.
1602
+ // Send what changed since the last patch, or it would never go out.
1165
1603
  this.#broadcastTick();
1604
+ if (this.#heldMail.length > 0) {
1605
+ this.#mail.unshift(...this.#heldMail.splice(0));
1606
+ this.#deliverMail();
1607
+ }
1166
1608
  if (this.#unsaved)
1167
1609
  this.#writeRoom();
1610
+ // From here on the players are shown every change as it is made: no tick stands for what
1611
+ // they see, so there is none to look back at.
1612
+ this.#history.clear();
1613
+ this.#tellClock(Date.now());
1168
1614
  }
1169
1615
  }
1616
+ /** When tick `tick` is due by the simulation's clock, in epoch milliseconds. */
1617
+ #dueAt(tick) {
1618
+ return this.#clockAt + ((tick - this.#clockTick) * 1000) / this.tickRate;
1619
+ }
1620
+ /** Sets the timer for the moment the next tick is due. */
1621
+ #schedule(now) {
1622
+ const wait = Math.max(0, Math.ceil(this.#dueAt(this.#tick + 1) - now));
1623
+ this.#loop = setTimeout(() => this.#wake(), wait);
1624
+ }
1625
+ /**
1626
+ * The simulation's timer fired: run every tick that has come due since the
1627
+ * last wake-up, up to `maxCatchUpTicks`, then send one patch for them all.
1628
+ */
1629
+ #wake() {
1630
+ const now = Date.now();
1631
+ const elapsed = ((now - this.#clockAt) * this.tickRate) / 1000;
1632
+ // A hair of slack, so that floating point does not put a tick that is due a moment later.
1633
+ const due = this.#clockTick + Math.floor(elapsed + 1e-6);
1634
+ const cap = Math.max(1, Math.floor(this.maxCatchUpTicks) || 1);
1635
+ let moved = false;
1636
+ if (due - this.#tick > cap) {
1637
+ // Too far behind to catch up: let the rest go, and move the clock on by as many ticks.
1638
+ this.#clockTick -= due - this.#tick - cap;
1639
+ this.#epoch += 1;
1640
+ moved = true;
1641
+ }
1642
+ const until = Math.min(due, this.#tick + cap);
1643
+ const eachTick = patchesEachTick.has(this);
1644
+ const before = this.#tick;
1645
+ let ran = 0;
1646
+ let halted = false;
1647
+ while (this.#tick < until) {
1648
+ // What the last tick did may have stopped the simulation: checked after every tick, as ever.
1649
+ if (ran > 0 && !this.#wantsTicks(this.#anySeated())) {
1650
+ halted = true;
1651
+ break;
1652
+ }
1653
+ if (ran > 0 && eachTick)
1654
+ this.#broadcastTick();
1655
+ this.#runTick();
1656
+ ran += 1;
1657
+ }
1658
+ if (halted) {
1659
+ // `#finish` stops the simulation in a moment. Until it does, no tick is due at once.
1660
+ this.#loop = setTimeout(() => this.#wake(), 1000 / this.tickRate);
1661
+ }
1662
+ else {
1663
+ this.#schedule(now);
1664
+ }
1665
+ if (ran === 0)
1666
+ return; // Woke a little early: nothing is due yet.
1667
+ if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
1668
+ this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
1669
+ this.#closeSilent(now);
1670
+ }
1671
+ // Counted in ticks, as ever: catching up does not change when saves happen.
1672
+ this.#ticksSinceSave += ran;
1673
+ if (this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
1674
+ this.#ticksSinceSave = 0;
1675
+ if (this.#unsaved)
1676
+ this.#writeRoom();
1677
+ }
1678
+ if (this.#patchDue(before) || this.#removed.length > 0) {
1679
+ // Before what these ticks sent, which `#finish` delivers: messages follow the patch.
1680
+ if (this.#heldMail.length > 0)
1681
+ this.#mail.unshift(...this.#heldMail.splice(0));
1682
+ this.#broadcastTick();
1683
+ }
1684
+ else if (this.#mail.length > 0) {
1685
+ // No patch for these ticks yet. What they sent waits for it, so that a message never
1686
+ // arrives before the state it is about. A player who is being removed has to hear why
1687
+ // before the connection closes, which is why such a tick sends.
1688
+ this.#heldMail.push(...this.#mail.splice(0));
1689
+ }
1690
+ if (moved || now - this.#clockToldAt >= CLOCK_EVERY_MS)
1691
+ this.#tellClock(now);
1692
+ this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1693
+ }
1694
+ /** `patchRate` where it holds anything back, and 0 where the room sends after every tick. */
1695
+ #patchRate() {
1696
+ const rate = this.patchRate;
1697
+ return rate > 0 && rate < this.tickRate && !patchesEachTick.has(this) ? rate : 0;
1698
+ }
1699
+ /**
1700
+ * Whether a patch is due now that the ticks after `before` have run. With
1701
+ * a `patchRate`, patches fall due that many times a second by the count of
1702
+ * ticks, so a room that catches up sends no more often than one that
1703
+ * keeps time.
1704
+ */
1705
+ #patchDue(before) {
1706
+ const rate = this.#patchRate();
1707
+ if (rate === 0)
1708
+ return true;
1709
+ return Math.floor((this.#tick * rate) / this.tickRate) > Math.floor((before * rate) / this.tickRate);
1710
+ }
1170
1711
  #runTick() {
1171
1712
  this.#tick += 1;
1172
1713
  const ticked = this.#apply(() => this.onTick(1 / this.tickRate), false, true);
@@ -1178,18 +1719,51 @@ export class Room extends DurableObject {
1178
1719
  this.#failedTicks = 0;
1179
1720
  this.#stalled = true;
1180
1721
  }
1181
- const now = Date.now();
1182
- if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
1183
- this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
1184
- this.#closeSilent(now);
1722
+ this.#remember();
1723
+ }
1724
+ /** Keeps the state the tick that just ran left, and lets go of those older than `historyTicks`. */
1725
+ #remember() {
1726
+ const keep = Math.floor(this.historyTicks) || 0;
1727
+ if (keep <= 0) {
1728
+ if (this.#history.size > 0)
1729
+ this.#history.clear();
1730
+ return;
1185
1731
  }
1186
- if (++this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
1187
- this.#ticksSinceSave = 0;
1188
- if (this.#unsaved)
1189
- this.#writeRoom();
1732
+ // `onEmpty` may have run after the tick, and what it wrote is not in the JSON yet.
1733
+ this.#freshen();
1734
+ const json = this.#committed.state;
1735
+ const last = this.#history.get(this.#tick - 1);
1736
+ // A tick that changed nothing keeps the string the one before it keeps, not one more like it.
1737
+ this.#history.set(this.#tick, last === json ? last : json);
1738
+ for (const tick of this.#history.keys()) {
1739
+ if (tick > this.#tick - keep)
1740
+ break;
1741
+ this.#history.delete(tick);
1742
+ }
1743
+ }
1744
+ /** Where the clock is at `now`, for a client of version 4: see `ClockFrame`. */
1745
+ #clockReading(now) {
1746
+ return { ms: Math.max(0, Math.round(now - this.#dueAt(this.#tick))), epoch: this.#epoch };
1747
+ }
1748
+ /** Tells every client of version 4 where the clock is, or that it stopped. */
1749
+ #tellClock(now) {
1750
+ this.#clockToldAt = now;
1751
+ let frame;
1752
+ for (const ws of this.ctx.getWebSockets()) {
1753
+ if (ws.readyState !== SOCKET_OPEN || !this.#socketInfo(ws).clock)
1754
+ continue;
1755
+ frame ??= JSON.stringify({
1756
+ t: "clock",
1757
+ tick: this.#tick,
1758
+ ...(this.#loop !== undefined ? this.#clockReading(now) : {}),
1759
+ });
1760
+ try {
1761
+ ws.send(frame);
1762
+ }
1763
+ catch {
1764
+ // Socket is closing.
1765
+ }
1190
1766
  }
1191
- this.#broadcastTick();
1192
- this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1193
1767
  }
1194
1768
  /**
1195
1769
  * Closes the connections that have sent nothing for `silentAfterMs`. What
@@ -1206,7 +1780,7 @@ export class Room extends DurableObject {
1206
1780
  try {
1207
1781
  // Marked: the player drops now, once. If the other end is there after all and answers
1208
1782
  // the close, that is not a second drop.
1209
- ws.serializeAttachment({ silent: true });
1783
+ this.#note(ws, { silent: true });
1210
1784
  ws.close(CloseCode.Silent, "silent");
1211
1785
  }
1212
1786
  catch {
@@ -1243,6 +1817,7 @@ export class Room extends DurableObject {
1243
1817
  this.#teams = meta.has("teams") ? JSON.parse(meta.get("teams")) : null;
1244
1818
  this.#outboxPending = this.#store.hasOutbox();
1245
1819
  this.#seq = room?.seq ?? 0;
1820
+ this.#handled = readHandled(room?.handled);
1246
1821
  let timers = this.#store.timers();
1247
1822
  if (timers.some(([name]) => name === AWAKE_TIMER)) {
1248
1823
  // The deadline lives in memory now. Left with the timers, it would fire for ever.
@@ -1266,6 +1841,10 @@ export class Room extends DurableObject {
1266
1841
  if (sockets.length > 0 && this.#wantsTicks(true)) {
1267
1842
  for (const { ws, id } of sockets) {
1268
1843
  try {
1844
+ // Commands this client sent since the save are gone with the old instance, and later
1845
+ // ones may still be on their way here: see `#handledFor`.
1846
+ if (this.#socketInfo(ws).client !== undefined)
1847
+ this.#note(ws, { untracked: true });
1269
1848
  this.#welcome(ws, { id, connected: true }, true);
1270
1849
  }
1271
1850
  catch (err) {
@@ -1274,6 +1853,22 @@ export class Room extends DurableObject {
1274
1853
  }
1275
1854
  }
1276
1855
  }
1856
+ // Spectators whose connections outlasted the instance: what was on its way to them went with
1857
+ // it, so their view starts over. A room that no longer takes any lets them go.
1858
+ const watching = this.#watching();
1859
+ if (watching.length > 0 && this.maxSpectators > 0) {
1860
+ this.#show(true);
1861
+ }
1862
+ else {
1863
+ for (const ws of watching) {
1864
+ try {
1865
+ ws.close(CloseCode.JoinRejected, "no_spectators");
1866
+ }
1867
+ catch {
1868
+ // Already closed.
1869
+ }
1870
+ }
1871
+ }
1277
1872
  // Seats left by players who dropped while no timeout was running for them (the option was
1278
1873
  // added or shortened since, or the room was torn down mid-event) get one now.
1279
1874
  const connected = this.#connectedIds();
@@ -1346,7 +1941,41 @@ export class Room extends DurableObject {
1346
1941
  this.#unsaved = false;
1347
1942
  }
1348
1943
  #persist(seq, committed) {
1349
- this.#store.writeRoom({ seq, state: committed.state, roster: committed.roster, tick: this.#tick });
1944
+ this.#store.writeRoom({
1945
+ seq,
1946
+ state: committed.state,
1947
+ roster: committed.roster,
1948
+ tick: this.#tick,
1949
+ handled: this.#handledJson(),
1950
+ });
1951
+ }
1952
+ /**
1953
+ * Which commands were handled, for the room's row: by player, the client's
1954
+ * name, its latest `id` and, if any, the refusals. "" when no client named
1955
+ * itself, as in every room whose clients are older than version 5.
1956
+ */
1957
+ #handledJson() {
1958
+ if (this.#handled.size === 0)
1959
+ return "";
1960
+ const seated = new Set(this.#roster);
1961
+ const records = [];
1962
+ let length = 1;
1963
+ for (const [id, handled] of this.#handled) {
1964
+ if (!seated.has(id)) {
1965
+ // A seat that was given up: a seat taken again starts over.
1966
+ this.#handled.delete(id);
1967
+ continue;
1968
+ }
1969
+ const { client, last, from, refused } = handled;
1970
+ handled.json ??= `${JSON.stringify(id)}:${JSON.stringify(from > 0 ? [client, last, refused, from] : refused.length > 0 ? [client, last, refused] : [client, last])}`;
1971
+ records.push(handled.json);
1972
+ length += handled.json.length + 1;
1973
+ }
1974
+ // See `HANDLED_CHARS`. The oldest are first.
1975
+ let skip = 0;
1976
+ while (length > HANDLED_CHARS)
1977
+ length -= records[skip++].length + 1;
1978
+ return skip >= records.length ? "" : `{${(skip > 0 ? records.slice(skip) : records).join(",")}}`;
1350
1979
  }
1351
1980
  /** Remembers the id this room is reached under, the first time it hears it. */
1352
1981
  #learnRoomId(roomId) {
@@ -1520,6 +2149,7 @@ export class Room extends DurableObject {
1520
2149
  * one that nothing is known about gets its whole view.
1521
2150
  */
1522
2151
  #broadcastState(before) {
2152
+ this.#show();
1523
2153
  const sockets = this.#seatedSockets();
1524
2154
  if (sockets.length === 0)
1525
2155
  return;
@@ -1544,11 +2174,12 @@ export class Room extends DurableObject {
1544
2174
  }
1545
2175
  this.#deltas.send(this.#seatedSockets(), this.#seq, this.#tick, this.#state, custom ? (id) => this.view({ id, connected: true }) : undefined, false, shows);
1546
2176
  this.#answer();
2177
+ this.#show();
1547
2178
  }
1548
2179
  /** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
1549
2180
  #versionOf(ws) {
1550
2181
  const info = this.#socketInfo(ws);
1551
- return info.presence ? PROTOCOL_VERSION : info.arrays ? 2 : 1;
2182
+ return info.resumes ? 5 : info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
1552
2183
  }
1553
2184
  /**
1554
2185
  * Tells everyone who is here. Clients of version 3 are told what changed
@@ -1584,6 +2215,8 @@ export class Room extends DurableObject {
1584
2215
  this.#welcomed = new Set();
1585
2216
  const players = this.players;
1586
2217
  const change = this.#presenceChange(players);
2218
+ if (change && this.#line.running)
2219
+ this.#line.tell(players, Math.max(0, this.spectatorDelayMs));
1587
2220
  let whole;
1588
2221
  let brief;
1589
2222
  for (const { ws } of sockets) {
@@ -1644,6 +2277,9 @@ export class Room extends DurableObject {
1644
2277
  const mail = this.#mail.splice(0);
1645
2278
  let everyone;
1646
2279
  for (const { to, frame } of mail) {
2280
+ // What is said to everyone is said to those who watch as well, when their time comes.
2281
+ if (to === null && this.#line.running)
2282
+ this.#line.say(frame, Math.max(0, this.spectatorDelayMs));
1647
2283
  const sockets = to === null
1648
2284
  ? (everyone ??= this.#seatedSockets()).map(({ ws }) => ws)
1649
2285
  : this.#roster.includes(to) || this.#removed.some((seat) => seat.id === to)
@@ -1705,6 +2341,10 @@ export class Room extends DurableObject {
1705
2341
  binary: tags.includes(BINARY_TAG),
1706
2342
  arrays: tags.includes(V2_TAG),
1707
2343
  presence: tags.includes(V3_TAG),
2344
+ clock: tags.includes(V4_TAG),
2345
+ resumes: tags.includes(V5_TAG),
2346
+ client: this.rememberCommands ? tags.find((tag) => tag.startsWith(CLIENT_TAG))?.slice(CLIENT_TAG.length) : undefined,
2347
+ spectator: tags.includes(SPECTATOR_TAG),
1708
2348
  };
1709
2349
  this.#infos.set(ws, info);
1710
2350
  }
@@ -1748,6 +2388,23 @@ function messageFrame(message) {
1748
2388
  throw new TypeError("A message must be JSON-serializable");
1749
2389
  return frame;
1750
2390
  }
2391
+ /** Reads what `#handledJson` wrote. Anything it cannot read is taken for nothing handled. */
2392
+ function readHandled(json) {
2393
+ const handled = new Map();
2394
+ if (!json)
2395
+ return handled;
2396
+ try {
2397
+ const stored = JSON.parse(json);
2398
+ for (const [id, [client, last, refused, from]] of Object.entries(stored)) {
2399
+ handled.set(id, { client, last, from: from ?? 0, refused: refused ?? [] });
2400
+ }
2401
+ }
2402
+ catch (err) {
2403
+ console.error("[tickflare] could not read which commands were handled; taking it for none:", err);
2404
+ handled.clear();
2405
+ }
2406
+ return handled;
2407
+ }
1751
2408
  function isThenable(value) {
1752
2409
  return typeof value?.then === "function";
1753
2410
  }