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,6 +3,7 @@ import {
3
3
  fingerprintOfText,
4
4
  stepThrough,
5
5
  type CatchUp,
6
+ type Desync,
6
7
  type LockstepView,
7
8
  type Replay,
8
9
  type Simulation,
@@ -13,6 +14,9 @@ import { RoomClient, type CloseDetail, type ConnectionStatus } from "./index.js"
13
14
  import { TurnPacer } from "./pacer.js";
14
15
  import { roomIn, withFreshToken, type TokenSource } from "./token.js";
15
16
 
17
+ /** For how many of the latest hashed turns the saved simulation is kept: see `LockstepClientOptions.explainDesyncs`. */
18
+ const SAVES_KEPT = 2;
19
+
16
20
  /**
17
21
  * The simulation to run, what to report and how to connect. `create` and
18
22
  * `step` are required. With `save` and `load` as well, the client sends the
@@ -41,8 +45,23 @@ export interface LockstepClientOptions<Input, Sim> extends Simulation<Input, Sim
41
45
  onTurn?(sim: Sim, turn: number): void;
42
46
  /** The simulation has caught up with the room and is live. */
43
47
  onReady?(sim: Sim, turn: number): void;
44
- /** Two players' simulations differed at `turn`. */
45
- onDesync?(turn: number): void;
48
+ /** Two players' simulations differed at `turn`. `desync.players` says whose. */
49
+ onDesync?(turn: number, desync: Desync): void;
50
+ /**
51
+ * The room has compared what the two players' simulations had saved at
52
+ * that turn: `desync.differs` says where they differed, as paths into what
53
+ * `save` returns with the two values. Called for every player, a while
54
+ * after `onDesync`, and not at all when a client had nothing to send.
55
+ */
56
+ onDesyncExplained?(desync: Desync): void;
57
+ /**
58
+ * With a `hash` of your own: also keep what `save` returns at each turn
59
+ * a hash is reported, so that the room can be told where two simulations
60
+ * differ. It costs a `save` every `hashEvery` turns, which a hash of your
61
+ * own is there to avoid, so it is off unless asked for. A simulation with
62
+ * `save` and no `hash` keeps it anyway: it is what it fingerprints.
63
+ */
64
+ explainDesyncs?: boolean;
46
65
  /** The connection's status changed: see `RoomClientOptions.onStatus`. */
47
66
  onStatus?(status: ConnectionStatus, detail?: CloseDetail): void;
48
67
  /**
@@ -58,7 +77,11 @@ export interface LockstepClientOptions<Input, Sim> extends Simulation<Input, Sim
58
77
  * the room may answer with only the rest: see `CatchUp`.
59
78
  */
60
79
  loadReplay?(url: string): Promise<Replay<Input> | CatchUp<Input>>;
61
- /** How to send the room a snapshot. Defaults to a `POST` of `data` to `url` with `fetch`. */
80
+ /**
81
+ * How to send the room a snapshot, or what the simulation had saved at a
82
+ * turn it differed from another's. Defaults to a `POST` of `data` to `url`
83
+ * with `fetch`.
84
+ */
62
85
  sendSnapshot?(url: string, data: string): Promise<unknown>;
63
86
  }
64
87
 
@@ -100,6 +123,9 @@ export class LockstepClient<Input = unknown, Sim = unknown> {
100
123
  /** Guards against an older catch-up finishing after a newer one started. */
101
124
  #syncId = 0;
102
125
  #desyncReported = false;
126
+ #desyncExplained = false;
127
+ /** What `save` returned at the latest turns a hash was reported for, as JSON text: see `#explain`. */
128
+ #saved = new Map<number, string>();
103
129
  /** The run of the room the simulation was built in: see `CatchUp.epoch`. */
104
130
  #epoch: string | undefined;
105
131
  /** Turns between snapshots, as the room says. 0 when it keeps none. */
@@ -192,7 +218,13 @@ export class LockstepClient<Input = unknown, Sim = unknown> {
192
218
  #receive(view: LockstepView<Input>): void {
193
219
  if (view.desync && !this.#desyncReported) {
194
220
  this.#desyncReported = true;
195
- this.#options.onDesync?.(view.desync.turn);
221
+ this.#options.onDesync?.(view.desync.turn, view.desync);
222
+ void this.#explain(view.desync);
223
+ }
224
+ if (view.desync?.differs && !this.#desyncExplained) {
225
+ this.#desyncExplained = true;
226
+ this.#saved.clear();
227
+ this.#options.onDesyncExplained?.(view.desync);
196
228
  }
197
229
  this.#snapshotEvery = view.snapshotEvery ?? 0;
198
230
  if (this.#needsSync) {
@@ -356,15 +388,44 @@ export class LockstepClient<Input = unknown, Sim = unknown> {
356
388
  const snapshot = this.#snapshotEvery > 0 && turn % this.#snapshotEvery === 0;
357
389
  // Only live turns are reported: hashes of old turns have nobody left to be compared with.
358
390
  if (live && hash && (snapshot || turn % hashEvery === 0)) {
359
- const data = snapshot && save && load && this.#sendsSnapshots() ? JSON.stringify(save(sim)) : undefined;
360
- // With no hash of the game's own, the text about to be sent is the text to fingerprint.
391
+ const sends = snapshot && save !== undefined && load !== undefined && this.#sendsSnapshots();
392
+ // Saved for a snapshot, to be fingerprinted, or to say later where it differed from another's.
393
+ const keeps = save !== undefined && !this.#desyncReported && (!this.#options.hash || this.#options.explainDesyncs === true);
394
+ const data = save !== undefined && (sends || keeps) ? JSON.stringify(save(sim)) : undefined;
395
+ // With no hash of the game's own, the text at hand is the text to fingerprint.
361
396
  const reported = data !== undefined && !this.#options.hash ? fingerprintOfText(data) : hash(sim);
397
+ if (data !== undefined && keeps) {
398
+ this.#saved.set(turn, data);
399
+ // The room finds two hashes differ within a round trip of the second: the last two turns cover it.
400
+ for (const old of this.#saved.keys()) if (this.#saved.size > SAVES_KEPT) this.#saved.delete(old);
401
+ }
362
402
  this.#room.send({ k: "h", n: turn, h: reported }).catch(() => {});
363
- if (data !== undefined) void this.#sendSnapshot(data, turn, reported);
403
+ if (data !== undefined && sends) void this.#sendSnapshot(data, turn, reported);
364
404
  }
365
405
  if (live) this.#options.onTurn?.(sim, turn);
366
406
  }
367
407
 
408
+ /**
409
+ * Two simulations differed, and this is one of them: sends the room what
410
+ * this one had saved at that turn, if it still has it, so that the room
411
+ * can say where the two differ.
412
+ */
413
+ async #explain(desync: Desync): Promise<void> {
414
+ const data = this.#saved.get(desync.turn);
415
+ this.#saved.clear();
416
+ if (data === undefined || desync.differs !== undefined || !desync.players?.includes(this.#room.you ?? "")) return;
417
+ try {
418
+ const to = new URL(this.#snapshotUrl);
419
+ to.pathname = to.pathname.replace(/snapshot$/, "desync");
420
+ to.searchParams.set("turn", String(desync.turn));
421
+ const { token } = this.#options;
422
+ const url = token ? await withFreshToken(to.toString(), this.#roomId, token) : to.toString();
423
+ await (this.#options.sendSnapshot ?? sendSnapshot)(url, data);
424
+ } catch (err) {
425
+ console.warn("[tickflare] could not send the room what this simulation had when it differed from another", err);
426
+ }
427
+ }
428
+
368
429
  /** One client sends the snapshots: that of the connected player whose id sorts first. */
369
430
  #sendsSnapshots(): boolean {
370
431
  const connected = this.#room.players.filter((player) => player.connected).map((player) => player.id).sort();
@@ -64,6 +64,8 @@ export class Predictor<View = unknown, Command = unknown> {
64
64
  readonly #room: RoomClient<View, Command>;
65
65
  readonly #options: PredictorOptions<View, Command>;
66
66
  readonly #stop: () => void;
67
+ /** How often the connection's status has changed: a command that waited through a change says nothing of the lead. */
68
+ #statusChanges = 0;
67
69
  /** The tick each command of this predictor's was sent at, by the room's reckoning, by command id. */
68
70
  #sentAt = new Map<number, number>();
69
71
  /** For the latest frames: when each arrived, less the time its tick stands for. The least is the room's clock. */
@@ -80,10 +82,17 @@ export class Predictor<View = unknown, Command = unknown> {
80
82
  constructor(room: RoomClient<View, Command>, options: PredictorOptions<View, Command>) {
81
83
  this.#room = room;
82
84
  this.#options = options;
83
- this.#stop = room.on("state", () => {
85
+ const stopState = room.on("state", () => {
84
86
  this.#hear();
85
87
  this.#changed();
86
88
  });
89
+ const stopStatus = room.on("status", () => {
90
+ this.#statusChanges += 1;
91
+ });
92
+ this.#stop = () => {
93
+ stopState();
94
+ stopStatus();
95
+ };
87
96
  if (room.state !== undefined) this.#hear();
88
97
  }
89
98
 
@@ -153,15 +162,19 @@ export class Predictor<View = unknown, Command = unknown> {
153
162
  const room = this.#room;
154
163
  const before = room.unconfirmed;
155
164
  const sent = room.send(command);
156
- // Not sent at all when there is no connection: then there is nothing to predict.
165
+ // Refused at once when there is no connection and none is being waited for: then there is nothing to predict.
157
166
  const id = room.unconfirmed === before ? undefined : room.unconfirmed[room.unconfirmed.length - 1]!.id;
158
167
  const at = Math.max(room.tick, this.#roomTick());
159
168
  if (id !== undefined) this.#sentAt.set(id, at);
169
+ const statusChanges = this.#statusChanges;
170
+ // A command that is sent without a connection, or loses it on the way, takes as long as the connection does.
171
+ const direct = () => room.status === "open" && statusChanges === this.#statusChanges;
172
+ const sentDirect = direct();
160
173
  const settle = (applied: boolean) => {
161
174
  if (id === undefined) return;
162
175
  this.#sentAt.delete(id);
163
176
  // The room's tick is now the one that first showed the command.
164
- if (applied && this.#options.tick && room.tickRate > 0) this.#learn(room.tick - at);
177
+ if (applied && sentDirect && direct() && this.#options.tick && room.tickRate > 0) this.#learn(room.tick - at);
165
178
  this.#changed();
166
179
  };
167
180
  sent.then(
package/src/lockstep.ts CHANGED
@@ -23,10 +23,7 @@ export interface LockstepView<Input = unknown> {
23
23
  /** What happened in the latest turn, in the order every client must apply it. */
24
24
  entries: TurnEntry<Input>[];
25
25
  /** Set once two players reported different hashes for the same turn. */
26
- desync: {
27
- /** The first turn two players' hashes differed on. */
28
- turn: number;
29
- } | null;
26
+ desync: Desync | null;
30
27
  /**
31
28
  * Set to `"players"` by a room whose `turnClock` is `"players"`: the room
32
29
  * sleeps between turns, and closes them when a player's client asks.
@@ -40,6 +37,72 @@ export interface LockstepView<Input = unknown> {
40
37
  snapshotEvery?: number;
41
38
  }
42
39
 
40
+ /** Two players' simulations were found to differ: when, whose, and, once the room knows, where. */
41
+ export interface Desync {
42
+ /** The first turn two players' hashes differed on. */
43
+ turn: number;
44
+ /**
45
+ * The two players whose hashes differed. With more players in the room,
46
+ * the others agree with one of them or have not reported that turn.
47
+ * Absent in a room saved before this was noted.
48
+ */
49
+ players?: [string, string];
50
+ /**
51
+ * Where the two simulations differed at that turn: see `differences`.
52
+ * Set once both players' clients have sent the room what they saved then,
53
+ * which they do by themselves when the simulation has `save`. Empty when
54
+ * what they saved is the same, and the difference is in something `save`
55
+ * leaves out. Absent until then, and for good when a client had nothing
56
+ * to send.
57
+ */
58
+ differs?: DesyncDifference[];
59
+ }
60
+
61
+ /** One place where two simulations differed. */
62
+ export interface DesyncDifference {
63
+ /** Where, as a path into what `save` returned: `units.12.x`. Empty when the two differ as a whole. */
64
+ path: string;
65
+ /**
66
+ * What each of the two had there, as JSON text, in the order of
67
+ * `Desync.players`. `undefined` where one had nothing, and cut to a
68
+ * hundred characters where it is long.
69
+ */
70
+ values: [string, string];
71
+ }
72
+
73
+ /**
74
+ * Where two values that JSON can hold differ: the first `limit` places, 8
75
+ * unless said otherwise, in the order of the first one's keys. It goes down
76
+ * to what cannot be taken apart further, so two units that differ in one
77
+ * coordinate are one difference, at `units.12.x`, and not two whole units.
78
+ *
79
+ * It is what a lockstep room uses to say where two players' simulations
80
+ * differed. Use it yourself to compare two saved simulations, in a test
81
+ * that runs the same recording twice for instance.
82
+ */
83
+ export function differences(a: unknown, b: unknown, limit = 8): DesyncDifference[] {
84
+ const found: DesyncDifference[] = [];
85
+ const show = (value: unknown): string => {
86
+ const text = value === undefined ? "undefined" : (JSON.stringify(value) ?? "undefined");
87
+ return text.length > 100 ? `${text.slice(0, 99)}…` : text;
88
+ };
89
+ const walk = (x: unknown, y: unknown, path: string): void => {
90
+ if (found.length >= limit || x === y) return;
91
+ if (typeof x === "object" && x !== null && typeof y === "object" && y !== null && Array.isArray(x) === Array.isArray(y)) {
92
+ const keys = Array.isArray(x)
93
+ ? Array.from({ length: Math.max(x.length, (y as unknown[]).length) }, (_, index) => String(index))
94
+ : [...new Set([...Object.keys(x), ...Object.keys(y)])];
95
+ for (const key of keys) {
96
+ walk((x as Record<string, unknown>)[key], (y as Record<string, unknown>)[key], path === "" ? key : `${path}.${key}`);
97
+ }
98
+ return;
99
+ }
100
+ found.push({ path, values: [show(x), show(y)] });
101
+ };
102
+ walk(a, b, "");
103
+ return found;
104
+ }
105
+
43
106
  /**
44
107
  * What a room with `turnClock = "players"` sends when it closes turns: turns
45
108
  * `n` to `n + c - 1`, all empty but the last, which has `e`.
package/src/protocol.ts CHANGED
@@ -18,8 +18,17 @@ import type { Patch } from "./patch.js";
18
18
  *
19
19
  * Version 3 adds presence as changes: a `presence` frame can say who is new
20
20
  * or different (`set`) and who is gone (`gone`) in place of the whole list.
21
+ *
22
+ * Version 4 adds the room's clock: while the simulation runs, `welcome`
23
+ * says where the clock is (`ms` and `epoch`), and `clock` frames say it
24
+ * again every few seconds, whenever it starts, stops or moves on.
25
+ *
26
+ * Version 5 adds commands that outlive a connection: a client that names
27
+ * itself with `client` in the query is told in `welcome` which of its
28
+ * commands the room has handled (`c`, `from` and `refused`), so that it can
29
+ * send the others again, and the room applies none of them twice.
21
30
  */
22
- export const PROTOCOL_VERSION = 3;
31
+ export const PROTOCOL_VERSION = 5;
23
32
 
24
33
  /** The keepalive a client sends, as a plain text frame. @internal */
25
34
  export const PING = "ping";
@@ -45,7 +54,13 @@ export interface Player {
45
54
  export interface CommandFrame<Command = unknown> {
46
55
  /** Frame type. */
47
56
  t: "cmd";
48
- /** Chosen by the client, unique per connection, echoed in the answer. */
57
+ /**
58
+ * Chosen by the client and echoed in the answer. Unique per connection; a
59
+ * client that names itself (`client` in the query, version 5) numbers its
60
+ * commands and leaves 1, 2, 3 and so on for as long as it lives, across
61
+ * connections, and the room takes one whose `id` is not above the latest it
62
+ * has handled for a command it has seen before.
63
+ */
49
64
  id: number;
50
65
  /** The command, as the room's `parseCommand` will receive it. */
51
66
  data: Command;
@@ -76,12 +91,90 @@ export interface WelcomeFrame<View = unknown> {
76
91
  tick: number;
77
92
  /** Ticks a second; 0 in event mode. */
78
93
  tickRate: number;
94
+ /**
95
+ * How many times a second the room sends what changed while it ticks, when
96
+ * that is less often than it ticks: see `Room.patchRate`. Absent from a
97
+ * room that sends after every tick. Sent whatever version the client asked
98
+ * for: one that does not know it loses nothing but the hint.
99
+ */
100
+ patchRate?: number;
101
+ /** Version 4, while the simulation runs: as in `ClockFrame`. Absent while it does not. */
102
+ ms?: number;
103
+ /** Version 4, while the simulation runs: as in `ClockFrame`. */
104
+ epoch?: number;
105
+ /**
106
+ * Version 5, to a client that named itself and that the room knows, on a
107
+ * new connection to a seat the player already had: the `id` of the latest
108
+ * command or leave of that client's the room has handled, applied or
109
+ * refused, or 0 for none. `state` shows every one of them that was
110
+ * applied. What the client sent after it never arrived, or was lost when
111
+ * the room went back to its last save: the client sends those again, in
112
+ * order, before anything new.
113
+ *
114
+ * Absent when the room knows nothing of what the client sent before, and
115
+ * the client gives up waiting for it: the seat is newly taken, the room
116
+ * last heard from another client of the same player, the room does not
117
+ * remember commands, or the `welcome` is one sent on a connection that was
118
+ * open already.
119
+ */
120
+ c?: number;
121
+ /**
122
+ * With `c`, when the room cannot say what became of the client's earliest
123
+ * commands: it can say of those after this `id`, up to `c`, and not of
124
+ * those up to it. A command the client is still waiting to hear about, and
125
+ * whose `id` is not above this, is given up as one whose outcome is not
126
+ * known. Absent when the room can say of every command up to `c`, which is
127
+ * nearly always: see the protocol reference for when it cannot.
128
+ */
129
+ from?: number;
130
+ /**
131
+ * With `c`: the latest of those commands that were refused, oldest first,
132
+ * each with the reason its `reject` frame gave, cut to 120 characters.
133
+ * Every other command after `from` and up to `c` was applied. The room
134
+ * remembers the last eight refusals of a client, and leaves this out when
135
+ * there are none.
136
+ */
137
+ refused?: [id: number, reason: string][];
79
138
  /** This player's whole view. */
80
139
  state: View;
81
140
  /** Everyone with a seat, in join order. */
82
141
  players: Player[];
83
142
  }
84
143
 
144
+ /**
145
+ * First frame on the connection of a spectator, who asked to watch with
146
+ * `spectate=1`, in place of a `welcome`. It says who they are and how the
147
+ * room runs, and nothing of the game: the spectators' view follows in a
148
+ * `state` frame, at once if other spectators have it already, and when its
149
+ * time has come if the room delays its spectators and this is the first to
150
+ * watch. After that the connection carries that view kept up to date with
151
+ * `state` and `patch` frames, who is here as whole `presence` lists, and
152
+ * what the room broadcasts as `msg` frames, each as long after the players
153
+ * were sent it as `delay` says.
154
+ *
155
+ * A spectator has no seat. Anything they send with an `id` is answered with
156
+ * a `reject` whose reason is `spectator`.
157
+ */
158
+ export interface SpectatingFrame {
159
+ /** Frame type. */
160
+ t: "spectating";
161
+ /** The version of the protocol the room speaks on this connection. */
162
+ v: number;
163
+ /** The spectator's id. They are not among `players`. */
164
+ you: string;
165
+ /** Ticks a second; 0 in event mode. */
166
+ tickRate: number;
167
+ /** As in `WelcomeFrame`. */
168
+ patchRate?: number;
169
+ /** How far behind the room everything on this connection is, in milliseconds. 0 for not at all. */
170
+ delay: number;
171
+ /**
172
+ * Everyone with a seat, as the spectators have last been told. Empty for
173
+ * the first to watch: a `presence` frame follows with the view.
174
+ */
175
+ players: Player[];
176
+ }
177
+
85
178
  /**
86
179
  * The state changed, and this is the player's whole view: sent when the room
87
180
  * does not know what the player holds, or when the view is not an object and
@@ -163,6 +256,37 @@ export interface AckFrame {
163
256
  tick?: number;
164
257
  }
165
258
 
259
+ /**
260
+ * Version 4: where the room's clock is. Ticks fall due on a fixed clock, one
261
+ * every `1 / tickRate` seconds from when the simulation started, so a client
262
+ * that knows how long ago one tick was due can tell which tick the room is on
263
+ * at any moment: `tick + (ms + elapsed) * tickRate / 1000`, where `elapsed`
264
+ * is the time since the frame was sent, about half a round trip when it
265
+ * arrives. `RoomClient.serverTick()` works this out.
266
+ *
267
+ * Sent every five seconds while the simulation runs, and at once when it
268
+ * starts, stops, or lets ticks go after a stall. The same reading is in
269
+ * `welcome` for a client that connects while it runs.
270
+ */
271
+ export interface ClockFrame {
272
+ /** Frame type. */
273
+ t: "clock";
274
+ /** The latest tick the room has run. */
275
+ tick: number;
276
+ /**
277
+ * How long before this frame was sent `tick` fell due, in milliseconds:
278
+ * usually less than one tick, more when the room is running late. Absent
279
+ * when the simulation has stopped, at `tick`, until a frame says otherwise.
280
+ */
281
+ ms?: number;
282
+ /**
283
+ * Which run of the clock this is. It changes when the simulation starts
284
+ * again, and when the room lets ticks go after a stall; while it stays the
285
+ * same, readings can be averaged.
286
+ */
287
+ epoch?: number;
288
+ }
289
+
166
290
  /** The command or leave with this `id` was refused, and nothing changed. */
167
291
  export interface RejectFrame {
168
292
  /** Frame type. */
@@ -195,9 +319,11 @@ export interface MessageFrame {
195
319
  /** Every frame a room sends, apart from the `pong` keepalive. */
196
320
  export type ServerMessage<View = unknown> =
197
321
  | WelcomeFrame<View>
322
+ | SpectatingFrame
198
323
  | StateFrame<View>
199
324
  | PatchFrame
200
325
  | PresenceFrame
326
+ | ClockFrame
201
327
  | AckFrame
202
328
  | RejectFrame
203
329
  | ErrorFrame
@@ -207,9 +333,13 @@ export type ServerMessage<View = unknown> =
207
333
  export const CloseCode = {
208
334
  /** The same player opened a newer connection. */
209
335
  Replaced: 4000,
210
- /** Every seat is taken. */
336
+ /** Every seat is taken. For a spectator, with the reason `spectators_full`: as many are watching as may. */
211
337
  RoomFull: 4001,
212
- /** `onJoin` refused the player; the close reason carries why. */
338
+ /**
339
+ * `onJoin` refused the player; the close reason carries why. For a
340
+ * spectator it is `onSpectate` that refused, or the reason is
341
+ * `no_spectators`: the room takes none.
342
+ */
213
343
  JoinRejected: 4002,
214
344
  /** The player no longer has a seat: they left, or the room removed them. The close reason says which. */
215
345
  Removed: 4003,
@@ -2,6 +2,11 @@ import type { Party } from "./tokens.js";
2
2
 
3
3
  /** Header the gateway uses to tell a room who is connecting. Never trusted from the client. */
4
4
  export const PLAYER_HEADER = "x-tickflare-player";
5
+ /**
6
+ * Header the gateway uses to tell a room who asks to watch it, in place of
7
+ * `PLAYER_HEADER`: see `routeToRoom`. Never trusted from the client.
8
+ */
9
+ export const SPECTATOR_HEADER = "x-tickflare-spectator";
5
10
  /** Header the gateway uses to tell a room the id it is known by. */
6
11
  export const ROOM_HEADER = "x-tickflare-room";
7
12
  /** Header the gateway uses to tell a room the player's name, URI-encoded. Never trusted from the client. */
@@ -98,6 +103,14 @@ export async function routeToRoom(
98
103
 
99
104
  const headers = identityHeaders(request, identity);
100
105
  headers.set(ROOM_HEADER, roomId);
106
+ if (upgrade && new URL(request.url).searchParams.get("spectate") === "1") {
107
+ // Someone who asks to watch is named under a header of their own. Cloudflare can leave a
108
+ // busy room on older code for minutes after the Worker in front of it has the new: a room
109
+ // from before there were spectators knows only the player's header, and would seat whoever
110
+ // it names. Without it, such a room turns the request away, and the client tries again.
111
+ headers.delete(PLAYER_HEADER);
112
+ headers.set(SPECTATOR_HEADER, identity.id);
113
+ }
101
114
 
102
115
  const stub = options.rooms.get(options.rooms.idFromName(roomId));
103
116
  return stub.fetch(new Request(request, { headers }));
@@ -137,6 +150,7 @@ type Checked = { id: string; name?: string; party?: Party };
137
150
  function identityHeaders(request: Request, identity: Checked): Headers {
138
151
  const headers = new Headers(request.headers);
139
152
  headers.set(PLAYER_HEADER, identity.id);
153
+ headers.delete(SPECTATOR_HEADER);
140
154
  if (identity.name === undefined) headers.delete(NAME_HEADER);
141
155
  else headers.set(NAME_HEADER, encodeURIComponent(identity.name));
142
156
  if (identity.party === undefined) headers.delete(PARTY_HEADER);
@@ -7,14 +7,18 @@
7
7
  * @module tickflare
8
8
  */
9
9
  export { Room, Rejection, reject, type ActOutcome } from "./room.js";
10
+ export { parseWith, type StandardSchemaIssue, type StandardSchemaResult, type StandardSchemaV1 } from "./schema.js";
10
11
  export { plain } from "./tracked.js";
11
12
  export { LockstepRoom, type LockstepCommand, type LockstepState } from "./lockstep.js";
12
13
  export {
14
+ differences,
13
15
  fingerprint,
14
16
  runReplay,
15
17
  seededRandom,
16
18
  stepThrough,
17
19
  type CatchUp,
20
+ type Desync,
21
+ type DesyncDifference,
18
22
  type LockstepView,
19
23
  type TurnsMessage,
20
24
  type Replay,
@@ -57,6 +61,7 @@ export {
57
61
  routeToRoom,
58
62
  NAME_HEADER,
59
63
  PLAYER_HEADER,
64
+ SPECTATOR_HEADER,
60
65
  type Authenticated,
61
66
  type MatchmakerRouteOptions,
62
67
  type RoomNamespace,
@@ -68,6 +73,7 @@ export {
68
73
  CloseCode,
69
74
  PROTOCOL_VERSION,
70
75
  type AckFrame,
76
+ type ClockFrame,
71
77
  type ClientMessage,
72
78
  type CommandFrame,
73
79
  type ErrorFrame,
@@ -80,6 +86,7 @@ export {
80
86
  type PresenceFrame,
81
87
  type RejectFrame,
82
88
  type ServerMessage,
89
+ type SpectatingFrame,
83
90
  type StateFrame,
84
91
  type WelcomeFrame,
85
92
  } from "../protocol.js";
@@ -1,6 +1,6 @@
1
- import type { CatchUp, LockstepView, Replay, Snapshot, TurnEntry, TurnsMessage } from "../lockstep.js";
1
+ import { differences, type CatchUp, type Desync, type DesyncDifference, type LockstepView, type Replay, type Snapshot, type TurnEntry, type TurnsMessage } from "../lockstep.js";
2
2
  import type { Player } from "../protocol.js";
3
- import { Room, reject } from "./room.js";
3
+ import { Room, patchEachTick, reject } from "./room.js";
4
4
  import { pieces } from "./storage.js";
5
5
 
6
6
  /** What a lockstep room keeps: what clients see, and the inputs waiting for the next turn. */
@@ -77,6 +77,15 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
77
77
  /** Inputs one player may send within a single turn. More are refused. */
78
78
  protected maxInputsPerTurn = 32;
79
79
 
80
+ /**
81
+ * Off in a lockstep room. A turn is recorded as it closes and the room is
82
+ * saved less often, so after a restart the recording holds inputs that the
83
+ * room's own save knows nothing of: one that was sent again would be
84
+ * recorded twice. An input that was in flight when the connection dropped
85
+ * is answered with `disconnected`, as it always was.
86
+ */
87
+ protected override rememberCommands = false;
88
+
80
89
  /**
81
90
  * Who keeps time.
82
91
  *
@@ -133,19 +142,40 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
133
142
  #hashes = new Map<number, { hash: string; by: string }>();
134
143
  /** For the latest turns a snapshot could be of: the first hash reported, and everyone who reported that one. */
135
144
  #vouched = new Map<number, { hash: string; by: Set<string> }>();
145
+ /** What the players of a desync have sent of their simulations at that turn, as JSON text, until both have. */
146
+ #explanations = new Map<string, string>();
136
147
  /** A snapshot that has arrived and waits for the other players to report its hash, and who sent it. */
137
148
  #candidate: (Snapshot & { by: string }) | undefined;
138
149
  /** Names this run of the room: see `CatchUp.epoch`. */
139
150
  #epoch: string | undefined;
140
151
 
152
+ constructor(ctx: DurableObjectState, env: Env) {
153
+ super(ctx, env);
154
+ // The view is one turn: when the room catches up on several, each still needs a frame of its own.
155
+ patchEachTick(this);
156
+ }
157
+
141
158
  /**
142
159
  * Turn an untrusted client payload into an input. Every client will feed
143
160
  * what this returns to its simulation, so reject anything malformed here.
144
161
  */
145
162
  protected abstract parseInput(raw: unknown): Input;
146
163
 
147
- /** Two players reported different hashes for `turn`: their simulations have diverged. */
148
- protected onDesync(_turn: number): void {}
164
+ /**
165
+ * Two players reported different hashes for `turn`: their simulations have
166
+ * diverged. `players` are the two. Where they differ is not known yet: see
167
+ * `onDesyncExplained`.
168
+ */
169
+ protected onDesync(_turn: number, _players: [string, string]): void {}
170
+
171
+ /**
172
+ * Both players of a desync have sent what their simulations had saved at
173
+ * that turn, and the room has compared the two: `desync.differs` says
174
+ * where they differed. It is in the view too, so every client is told.
175
+ * The place to log it. Not called when a client had nothing to send: a
176
+ * simulation without `save`, or a player who was gone by then.
177
+ */
178
+ protected onDesyncExplained(_desync: Desync & { players: [string, string]; differs: DesyncDifference[] }): void {}
149
179
 
150
180
  protected initialState(): LockstepState<Input> {
151
181
  const seed = crypto.getRandomValues(new Uint32Array(1))[0]!;
@@ -296,9 +326,9 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
296
326
  }
297
327
  } else if (first.by !== player.id && first.hash !== command.h && !this.state.desync) {
298
328
  // It takes two players to disagree: one changing their mind proves nothing.
299
- this.state.desync = { turn: command.n };
329
+ this.state.desync = { turn: command.n, players: [first.by, player.id] };
300
330
  this.#candidate = undefined; // Nobody can say which simulation a snapshot should be of.
301
- this.onDesync(command.n);
331
+ this.onDesync(command.n, [first.by, player.id]);
302
332
  }
303
333
  }
304
334
 
@@ -483,6 +513,41 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
483
513
  this.#event({ player: player.id, event: "reconnect" });
484
514
  }
485
515
 
516
+ /**
517
+ * One of the two players of a desync sends what their simulation had saved
518
+ * at that turn. When both have, the room says where the two differ.
519
+ */
520
+ async #explain(request: Request, params: URLSearchParams, player: Player): Promise<Response> {
521
+ const waiting = (): Desync | undefined => {
522
+ const desync = this.state.desync;
523
+ return desync?.players?.includes(player.id) && desync.differs === undefined && Number(params.get("turn")) === desync.turn
524
+ ? desync
525
+ : undefined;
526
+ };
527
+ // Checked before the body is read, and again after: the other player's may have settled it.
528
+ if (!waiting()) return new Response("Nothing this room is waiting for", { status: 409 });
529
+ const data = await textUpTo(request, this.maxSnapshotLength * 3);
530
+ if (data === undefined || data.length > this.maxSnapshotLength) return new Response("Too long", { status: 413 });
531
+ try {
532
+ JSON.parse(data);
533
+ } catch {
534
+ return new Response("Not JSON", { status: 400 });
535
+ }
536
+ const desync = waiting();
537
+ if (!desync) return new Response("Nothing this room is waiting for", { status: 409 });
538
+ this.#explanations.set(player.id, data);
539
+ const [one, other] = desync.players!.map((id) => this.#explanations.get(id));
540
+ if (one === undefined || other === undefined) return new Response("Held until the other player's arrives", { status: 202 });
541
+ this.#explanations.clear();
542
+ const differs = differences(JSON.parse(one), JSON.parse(other));
543
+ await this.act(() => {
544
+ const explained = { ...desync, players: desync.players!, differs };
545
+ this.state.desync = explained;
546
+ this.onDesyncExplained(explained);
547
+ });
548
+ return new Response("Compared", { status: 201 });
549
+ }
550
+
486
551
  /**
487
552
  * Closes the turn: whatever arrived since the last one becomes this turn's
488
553
  * entries. A turn with something in it is one row in the recording, written
@@ -524,7 +589,9 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
524
589
 
525
590
  /**
526
591
  * `GET …/replay` is the recording, or the end of it for a client that is
527
- * catching up. `POST …/snapshot` is a player's client sending a snapshot.
592
+ * catching up. `POST …/snapshot` is a player's client sending a snapshot,
593
+ * and `POST …/desync` one sending what it had saved at a turn two players
594
+ * disagreed on.
528
595
  * If you override this, pass on what is not yours with `super.onHttp`.
529
596
  */
530
597
  protected override onHttp(request: Request, player: Player): Response | Promise<Response> {
@@ -535,6 +602,9 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
535
602
  if (request.method === "POST" && url.pathname.endsWith("/snapshot")) {
536
603
  return this.#offered(request, url.searchParams, player);
537
604
  }
605
+ if (request.method === "POST" && url.pathname.endsWith("/desync")) {
606
+ return this.#explain(request, url.searchParams, player);
607
+ }
538
608
  return new Response("Not found", { status: 404 });
539
609
  }
540
610