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
@@ -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";
@@ -32,6 +33,24 @@ const V2_TAG = "\u0001v=2";
32
33
  const V3_TAG = "\u0001v=3";
33
34
  /** Marks the socket of a client that speaks version 4: it is told the room's clock. */
34
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;
35
54
  const isMark = (tag) => tag.charCodeAt(0) === 1;
36
55
  /**
37
56
  * In a room with more than `PRESENCE_CROWD` connections, the least time
@@ -126,6 +145,20 @@ export class Room extends DurableObject {
126
145
  * `rate_limited` and never reach `parseCommand`. `Infinity` turns it off.
127
146
  */
128
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;
129
162
  /**
130
163
  * Where `finishMatch` announces a finished match. Set it to a Queue binding:
131
164
  * `protected override matchQueue = this.env.MATCHES;`
@@ -144,6 +177,74 @@ export class Room extends DurableObject {
144
177
  rooms;
145
178
  /** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
146
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;
147
248
  /**
148
249
  * While the room is ticking, the most ticks it runs back to back to catch
149
250
  * up when it wakes late. The simulation keeps to a fixed clock: tick `n`
@@ -236,6 +337,10 @@ export class Room extends DurableObject {
236
337
  /** Timer name to the time it fires, in epoch milliseconds. */
237
338
  #timers = new Map();
238
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();
239
344
  /** Seats given up during this event. Their sockets are closed once the event is over. */
240
345
  #removed = [];
241
346
  /** The timers changed, so the object's alarm has to be moved before the event ends. */
@@ -252,6 +357,8 @@ export class Room extends DurableObject {
252
357
  #signals = [];
253
358
  /** Messages for players, as frames, waiting for the end of the event. `to` null is everyone. */
254
359
  #mail = [];
360
+ /** Messages sent from ticks that no patch has followed yet: see `patchRate`. */
361
+ #heldMail = [];
255
362
  /** While ticking: the commands each socket has had applied and not yet been told about. */
256
363
  #owed = new Map();
257
364
  /** The command being handled, and who sent it. */
@@ -302,6 +409,12 @@ export class Room extends DurableObject {
302
409
  #reading = 0;
303
410
  /** Holds each player to `maxCommandsPerSecond`. */
304
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();
305
418
  /** Ticks run since the room was created. */
306
419
  #tick = 0;
307
420
  /** Set while the simulation is running: the timer for the next wake-up. */
@@ -400,6 +513,27 @@ export class Room extends DurableObject {
400
513
  view(_player) {
401
514
  return this.state;
402
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
+ }
403
537
  /** Everyone with a seat, in join order. */
404
538
  get players() {
405
539
  // One pass over the sockets, not one per player: a join tells everyone this list.
@@ -414,6 +548,27 @@ export class Room extends DurableObject {
414
548
  get tick() {
415
549
  return this.#tick;
416
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
+ }
417
572
  /** The id this room is reached under, once someone has connected through the gateway. */
418
573
  get roomId() {
419
574
  return this.#roomId;
@@ -536,7 +691,7 @@ export class Room extends DurableObject {
536
691
  send(playerId, message) {
537
692
  this.#mail.push({ to: playerId, frame: messageFrame(message) });
538
693
  }
539
- /** `send` to every player who is connected. */
694
+ /** `send` to every player who is connected, and to those who watch: see `maxSpectators`. */
540
695
  broadcast(message) {
541
696
  this.#mail.push({ to: null, frame: messageFrame(message) });
542
697
  }
@@ -699,7 +854,9 @@ export class Room extends DurableObject {
699
854
  }
700
855
  /** Durable Object entry point for connections and HTTP requests from the gateway. Tickflare's: override `onHttp` instead. */
701
856
  async fetch(request) {
702
- 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;
703
860
  if (!playerId) {
704
861
  return new Response("Missing player identity", { status: 401 });
705
862
  }
@@ -726,6 +883,12 @@ export class Room extends DurableObject {
726
883
  }
727
884
  }
728
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
+ }
729
892
  const marks = [];
730
893
  if (asked.get("patches") === BINARY_PATCHES)
731
894
  marks.push(BINARY_TAG);
@@ -735,6 +898,12 @@ export class Room extends DurableObject {
735
898
  marks.push(V3_TAG);
736
899
  if (Number(asked.get("v")) >= 4)
737
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
+ }
738
907
  const response = this.#connect(playerId, name, marks);
739
908
  await this.#finish();
740
909
  return response;
@@ -838,7 +1007,11 @@ export class Room extends DurableObject {
838
1007
  const player = { id: playerId, connected: true };
839
1008
  if (name !== undefined)
840
1009
  player.name = name;
841
- 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) {
842
1015
  const arrival = this.#store.arrival(playerId);
843
1016
  // A player handed over by another room is always let in.
844
1017
  if (arrival === undefined) {
@@ -865,6 +1038,11 @@ export class Room extends DurableObject {
865
1038
  return refuse(client, server, CloseCode.RoomFull, "room_full");
866
1039
  }
867
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: [] });
868
1046
  const joined = this.#apply(() => {
869
1047
  this.#roster.push(playerId);
870
1048
  this.#connecting = playerId;
@@ -877,6 +1055,7 @@ export class Room extends DurableObject {
877
1055
  }
878
1056
  });
879
1057
  if (!joined.ok) {
1058
+ this.#handled.delete(playerId);
880
1059
  return refuse(client, server, CloseCode.JoinRejected, joined.reason);
881
1060
  }
882
1061
  }
@@ -897,12 +1076,119 @@ export class Room extends DurableObject {
897
1076
  // What the client asked for is kept with the socket, where it outlasts the room's sleep.
898
1077
  this.ctx.acceptWebSocket(server, [playerId, ...marks]);
899
1078
  this.#heard.set(server, Date.now());
900
- 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);
901
1096
  this.#broadcastPresence(server);
902
1097
  return new Response(null, { status: 101, webSocket: client });
903
1098
  }
904
- /** Sends a socket everything from the start: who they are, the players and their whole view. */
905
- #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) {
906
1192
  const welcome = JSON.stringify({
907
1193
  t: "welcome",
908
1194
  v: this.#versionOf(ws),
@@ -911,6 +1197,10 @@ export class Room extends DurableObject {
911
1197
  tick: this.#tick,
912
1198
  tickRate: this.tickRate,
913
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 } : {}),
914
1204
  state: this.view(player),
915
1205
  players: this.players,
916
1206
  });
@@ -928,7 +1218,7 @@ export class Room extends DurableObject {
928
1218
  this.#owed.delete(old);
929
1219
  try {
930
1220
  // Marked, so that its close is not taken for the player dropping.
931
- old.serializeAttachment({ replaced: true });
1221
+ this.#note(old, { replaced: true });
932
1222
  old.close(CloseCode.Replaced, "replaced");
933
1223
  }
934
1224
  catch {
@@ -938,9 +1228,39 @@ export class Room extends DurableObject {
938
1228
  }
939
1229
  #receive(ws, message) {
940
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
+ }
941
1246
  // A socket whose seat is gone is about to be closed; ignore what it still sends.
942
1247
  if (!playerId || !this.#roster.includes(playerId))
943
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;
944
1264
  // Every frame counts against the limit, including the ones refused below.
945
1265
  const allowed = this.#limiter.spend(playerId, this.maxCommandsPerSecond);
946
1266
  if (typeof message !== "string") {
@@ -960,14 +1280,53 @@ export class Room extends DurableObject {
960
1280
  if (!frame) {
961
1281
  return this.#send(ws, { t: "error", reason: allowed ? "invalid_message" : "rate_limited" });
962
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
+ };
963
1324
  if (!allowed) {
964
1325
  // Answered by id, so the client's pending command settles instead of hanging.
965
- return this.#send(ws, { t: "reject", id: frame.id, reason: "rate_limited" });
1326
+ return refuse("rate_limited");
966
1327
  }
967
1328
  const player = { id: playerId, connected: true };
968
1329
  let outcome;
969
- // While the simulation runs, what a command changed is sent with the next tick.
970
- const ticking = this.#loop !== undefined;
971
1330
  if (frame.t === "leave") {
972
1331
  outcome = this.#apply(() => {
973
1332
  this.onLeave(player);
@@ -983,8 +1342,7 @@ export class Room extends DurableObject {
983
1342
  command = this.parseCommand(frame.data);
984
1343
  }
985
1344
  catch (err) {
986
- const reason = err instanceof Rejection ? err.reason : "invalid_command";
987
- return this.#send(ws, { t: "reject", id: frame.id, reason });
1345
+ return refuse(err instanceof Rejection ? err.reason : "invalid_command");
988
1346
  }
989
1347
  // If this changes what the player sees, the frame that says so says whose command it shows.
990
1348
  this.#answering = { ws, id: frame.id };
@@ -995,20 +1353,47 @@ export class Room extends DurableObject {
995
1353
  this.#answering = undefined;
996
1354
  }
997
1355
  }
998
- if (!outcome.ok) {
999
- 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;
1000
1381
  }
1001
- if (ticking && frame.t === "cmd") {
1002
- // An ack means "you have seen the result", and the result goes out with the tick.
1003
- const owed = this.#owed.get(ws);
1004
- if (owed)
1005
- owed.push(frame.id);
1006
- else
1007
- 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()))
1008
1395
  return;
1009
- }
1010
- // The state frame, if any, has already gone out.
1011
- this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1396
+ this.#writeRoom();
1012
1397
  }
1013
1398
  /** Acks the commands `ws` is still owed an answer to, or everyone's. */
1014
1399
  #answer(ws) {
@@ -1066,6 +1451,9 @@ export class Room extends DurableObject {
1066
1451
  if (this.#removed.length > 0 || this.#presenceStale) {
1067
1452
  this.#presenceStale = false;
1068
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);
1069
1457
  for (const ws of this.ctx.getWebSockets(id)) {
1070
1458
  try {
1071
1459
  ws.close(CloseCode.Removed, reason.slice(0, MAX_CLOSE_REASON));
@@ -1211,10 +1599,17 @@ export class Room extends DurableObject {
1211
1599
  else if (!wanted && this.#loop !== undefined) {
1212
1600
  clearTimeout(this.#loop);
1213
1601
  this.#loop = undefined;
1214
- // 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.
1215
1603
  this.#broadcastTick();
1604
+ if (this.#heldMail.length > 0) {
1605
+ this.#mail.unshift(...this.#heldMail.splice(0));
1606
+ this.#deliverMail();
1607
+ }
1216
1608
  if (this.#unsaved)
1217
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();
1218
1613
  this.#tellClock(Date.now());
1219
1614
  }
1220
1615
  }
@@ -1246,6 +1641,7 @@ export class Room extends DurableObject {
1246
1641
  }
1247
1642
  const until = Math.min(due, this.#tick + cap);
1248
1643
  const eachTick = patchesEachTick.has(this);
1644
+ const before = this.#tick;
1249
1645
  let ran = 0;
1250
1646
  let halted = false;
1251
1647
  while (this.#tick < until) {
@@ -1279,11 +1675,39 @@ export class Room extends DurableObject {
1279
1675
  if (this.#unsaved)
1280
1676
  this.#writeRoom();
1281
1677
  }
1282
- this.#broadcastTick();
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
+ }
1283
1690
  if (moved || now - this.#clockToldAt >= CLOCK_EVERY_MS)
1284
1691
  this.#tellClock(now);
1285
1692
  this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1286
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
+ }
1287
1711
  #runTick() {
1288
1712
  this.#tick += 1;
1289
1713
  const ticked = this.#apply(() => this.onTick(1 / this.tickRate), false, true);
@@ -1295,6 +1719,27 @@ export class Room extends DurableObject {
1295
1719
  this.#failedTicks = 0;
1296
1720
  this.#stalled = true;
1297
1721
  }
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;
1731
+ }
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
+ }
1298
1743
  }
1299
1744
  /** Where the clock is at `now`, for a client of version 4: see `ClockFrame`. */
1300
1745
  #clockReading(now) {
@@ -1335,7 +1780,7 @@ export class Room extends DurableObject {
1335
1780
  try {
1336
1781
  // Marked: the player drops now, once. If the other end is there after all and answers
1337
1782
  // the close, that is not a second drop.
1338
- ws.serializeAttachment({ silent: true });
1783
+ this.#note(ws, { silent: true });
1339
1784
  ws.close(CloseCode.Silent, "silent");
1340
1785
  }
1341
1786
  catch {
@@ -1372,6 +1817,7 @@ export class Room extends DurableObject {
1372
1817
  this.#teams = meta.has("teams") ? JSON.parse(meta.get("teams")) : null;
1373
1818
  this.#outboxPending = this.#store.hasOutbox();
1374
1819
  this.#seq = room?.seq ?? 0;
1820
+ this.#handled = readHandled(room?.handled);
1375
1821
  let timers = this.#store.timers();
1376
1822
  if (timers.some(([name]) => name === AWAKE_TIMER)) {
1377
1823
  // The deadline lives in memory now. Left with the timers, it would fire for ever.
@@ -1395,6 +1841,10 @@ export class Room extends DurableObject {
1395
1841
  if (sockets.length > 0 && this.#wantsTicks(true)) {
1396
1842
  for (const { ws, id } of sockets) {
1397
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 });
1398
1848
  this.#welcome(ws, { id, connected: true }, true);
1399
1849
  }
1400
1850
  catch (err) {
@@ -1403,6 +1853,22 @@ export class Room extends DurableObject {
1403
1853
  }
1404
1854
  }
1405
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
+ }
1406
1872
  // Seats left by players who dropped while no timeout was running for them (the option was
1407
1873
  // added or shortened since, or the room was torn down mid-event) get one now.
1408
1874
  const connected = this.#connectedIds();
@@ -1475,7 +1941,41 @@ export class Room extends DurableObject {
1475
1941
  this.#unsaved = false;
1476
1942
  }
1477
1943
  #persist(seq, committed) {
1478
- 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(",")}}`;
1479
1979
  }
1480
1980
  /** Remembers the id this room is reached under, the first time it hears it. */
1481
1981
  #learnRoomId(roomId) {
@@ -1649,6 +2149,7 @@ export class Room extends DurableObject {
1649
2149
  * one that nothing is known about gets its whole view.
1650
2150
  */
1651
2151
  #broadcastState(before) {
2152
+ this.#show();
1652
2153
  const sockets = this.#seatedSockets();
1653
2154
  if (sockets.length === 0)
1654
2155
  return;
@@ -1673,11 +2174,12 @@ export class Room extends DurableObject {
1673
2174
  }
1674
2175
  this.#deltas.send(this.#seatedSockets(), this.#seq, this.#tick, this.#state, custom ? (id) => this.view({ id, connected: true }) : undefined, false, shows);
1675
2176
  this.#answer();
2177
+ this.#show();
1676
2178
  }
1677
2179
  /** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
1678
2180
  #versionOf(ws) {
1679
2181
  const info = this.#socketInfo(ws);
1680
- return info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
2182
+ return info.resumes ? 5 : info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
1681
2183
  }
1682
2184
  /**
1683
2185
  * Tells everyone who is here. Clients of version 3 are told what changed
@@ -1713,6 +2215,8 @@ export class Room extends DurableObject {
1713
2215
  this.#welcomed = new Set();
1714
2216
  const players = this.players;
1715
2217
  const change = this.#presenceChange(players);
2218
+ if (change && this.#line.running)
2219
+ this.#line.tell(players, Math.max(0, this.spectatorDelayMs));
1716
2220
  let whole;
1717
2221
  let brief;
1718
2222
  for (const { ws } of sockets) {
@@ -1773,6 +2277,9 @@ export class Room extends DurableObject {
1773
2277
  const mail = this.#mail.splice(0);
1774
2278
  let everyone;
1775
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));
1776
2283
  const sockets = to === null
1777
2284
  ? (everyone ??= this.#seatedSockets()).map(({ ws }) => ws)
1778
2285
  : this.#roster.includes(to) || this.#removed.some((seat) => seat.id === to)
@@ -1835,6 +2342,9 @@ export class Room extends DurableObject {
1835
2342
  arrays: tags.includes(V2_TAG),
1836
2343
  presence: tags.includes(V3_TAG),
1837
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),
1838
2348
  };
1839
2349
  this.#infos.set(ws, info);
1840
2350
  }
@@ -1878,6 +2388,23 @@ function messageFrame(message) {
1878
2388
  throw new TypeError("A message must be JSON-serializable");
1879
2389
  return frame;
1880
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
+ }
1881
2408
  function isThenable(value) {
1882
2409
  return typeof value?.then === "function";
1883
2410
  }