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
@@ -19,6 +19,7 @@ import {
19
19
  type ClientMessage,
20
20
  type Player,
21
21
  type ServerMessage,
22
+ type WelcomeFrame,
22
23
  } from "../protocol.js";
23
24
 
24
25
  export { CloseCode, type MatchFound, type Player } from "../protocol.js";
@@ -43,11 +44,14 @@ export { produce } from "./draft.js";
43
44
  export { decodePatchFrame } from "../binary.js";
44
45
  export { LockstepClient, type LockstepClientOptions } from "./lockstep.js";
45
46
  export {
47
+ differences,
46
48
  fingerprint,
47
49
  runReplay,
48
50
  seededRandom,
49
51
  stepThrough,
50
52
  type CatchUp,
53
+ type Desync,
54
+ type DesyncDifference,
51
55
  type LockstepView,
52
56
  type TurnsMessage,
53
57
  type Replay,
@@ -123,6 +127,18 @@ export interface RoomClientOptions<View> {
123
127
  token?: TokenSource;
124
128
  /** The room handed this player to another room, and the client is now connecting there. */
125
129
  onMoved?(roomId: string): void;
130
+ /**
131
+ * Watch the room without taking a seat in it, if it takes spectators
132
+ * (`maxSpectators`). `state` is then what the room shows its spectators,
133
+ * kept up to date like a player's view; `players`, `onPresence` and
134
+ * `onMessage` work as for a player, the last for what the room broadcasts.
135
+ * A spectator sends nothing: `send` and `leave` reject with `spectator`.
136
+ *
137
+ * A room may keep its spectators behind its players (`spectatorDelayMs`):
138
+ * `delayMs` says by how much. The first to watch such a room is connected
139
+ * at once, and has no `state` until that long has passed.
140
+ */
141
+ spectate?: boolean;
126
142
  /** Reconnect after an unexpected close. Defaults to true. */
127
143
  reconnect?: boolean;
128
144
  /**
@@ -141,6 +157,25 @@ export interface RoomClientOptions<View> {
141
157
  * for dead and replaced.
142
158
  */
143
159
  pingIntervalMs?: number;
160
+ /**
161
+ * How long a command may wait for a connection, in milliseconds. Defaults
162
+ * to 10 seconds.
163
+ *
164
+ * A command sent while the client is connecting, the first time or again,
165
+ * is held and sent as soon as the room answers. A command that was on its
166
+ * way when the connection dropped is kept too: when the client is back,
167
+ * the room says which of them it handled, the client sends the others
168
+ * again, and none is applied twice. Either way the promise `send` returned
169
+ * settles as if nothing had happened.
170
+ *
171
+ * A command that has waited this long is given up: its promise rejects
172
+ * with `not_connected` if it was never sent, and `disconnected` if it was.
173
+ * Keep it short in a game where a late command is worse than a lost one.
174
+ *
175
+ * 0 keeps nothing: `send` rejects at once while there is no connection,
176
+ * and whatever is in flight when one drops rejects with `disconnected`.
177
+ */
178
+ keepCommandsMs?: number;
144
179
  }
145
180
 
146
181
  /** A command on its way: sent, and not yet shown by the room's state. */
@@ -151,9 +186,15 @@ export interface SentCommand<Command = unknown> {
151
186
  command: Command;
152
187
  }
153
188
 
154
- /** A command or leave the room refused, or one that was in flight when the connection dropped. */
189
+ /** A command or leave the room refused, or one the client gave up on for want of a connection. */
155
190
  export class CommandRejected extends Error {
156
- /** What the room passed to `reject()`, or `not_connected` or `disconnected`. */
191
+ /**
192
+ * What the room passed to `reject()`. Or `not_connected`: the command never
193
+ * left this client, and was not applied. Or `disconnected`: it was sent,
194
+ * the connection dropped, and the client could not learn what became of
195
+ * it. It may or may not have been applied. Or `spectator`: this client
196
+ * watches the room, and has no seat to send from.
197
+ */
157
198
  readonly reason: string;
158
199
 
159
200
  constructor(reason: string) {
@@ -164,18 +205,46 @@ export class CommandRejected extends Error {
164
205
  }
165
206
 
166
207
  const MAX_BACKOFF_MS = 5_000;
208
+ /** How long a command waits for a connection unless `keepCommandsMs` says otherwise. */
209
+ const KEEP_COMMANDS_MS = 10_000;
210
+
211
+ /** A command or leave that the room has not answered yet. */
212
+ interface Pending<Command> {
213
+ resolve(): void;
214
+ reject(error: Error): void;
215
+ /** The frame, as it is sent, and sent again if it has to be. */
216
+ frame: ClientMessage<Command>;
217
+ /** It has been sent, on this connection or an earlier one. */
218
+ sent: boolean;
219
+ /** Set while it waits for a connection: gives it up when `keepCommandsMs` has passed. */
220
+ timer?: ReturnType<typeof setTimeout>;
221
+ }
222
+
223
+ /**
224
+ * A name for one client, for as long as it lives. The room tells one
225
+ * client's commands from another's by it, so only the same player's other
226
+ * clients must not share it: a few random characters are plenty.
227
+ */
228
+ function clientName(): string {
229
+ let name = "";
230
+ while (name.length < 12) name += Math.random().toString(36).slice(2);
231
+ return name.slice(0, 12);
232
+ }
167
233
 
168
234
  /**
169
235
  * A connection to one room. Holds the latest state the server sent and
170
236
  * reconnects on its own; after a reconnect the server sends the current state
171
- * again, so there is nothing to replay.
237
+ * again, so there is nothing to replay. Commands that were on their way when
238
+ * the connection dropped are settled then too: see `keepCommandsMs`.
172
239
  */
173
240
  export class RoomClient<View = unknown, Command = unknown> {
174
241
  #state: View | undefined;
175
242
  #seq = 0;
176
243
  #tick = 0;
177
244
  #tickRate = 0;
245
+ #patchRate = 0;
178
246
  #you: string | undefined;
247
+ #delayMs = 0;
179
248
  #players: Player[] = [];
180
249
  #status: ConnectionStatus = "connecting";
181
250
  #listeners = new Map<keyof RoomClientEvents<View>, Set<(...args: never[]) => void>>();
@@ -183,8 +252,13 @@ export class RoomClient<View = unknown, Command = unknown> {
183
252
  #url: string;
184
253
  readonly #options: RoomClientOptions<View>;
185
254
  #socket: WebSocket | undefined;
255
+ /** The name this client goes by: see `clientName`. */
256
+ readonly #name = clientName();
186
257
  #nextId = 1;
187
- #pending = new Map<number, { resolve(): void; reject(error: Error): void }>();
258
+ /** By id, which is also the order they were sent in: ids only go up, and none is put back. */
259
+ #pending = new Map<number, Pending<Command>>();
260
+ /** The room speaks version 5, by its last welcome: after a drop it can say which commands it handled. */
261
+ #resumes = false;
188
262
  /** Commands sent that `#state` does not show yet, oldest first. Replaced, never changed, so that it can be compared by reference. */
189
263
  #unconfirmed: readonly SentCommand<Command>[] = [];
190
264
  #attempt = 0;
@@ -224,6 +298,15 @@ export class RoomClient<View = unknown, Command = unknown> {
224
298
  return this.#tickRate;
225
299
  }
226
300
 
301
+ /**
302
+ * How many times a second the room sends what changed while it ticks: its
303
+ * `patchRate` if it has one, and otherwise `tickRate`. 0 in event mode.
304
+ * It is what to set the duration of an `Interpolator` from.
305
+ */
306
+ get patchRate(): number {
307
+ return this.#patchRate;
308
+ }
309
+
227
310
  /**
228
311
  * The tick the room is on right now, by estimate, with the fraction of the
229
312
  * next that has passed: for drawing the game in step with the room, or
@@ -249,6 +332,20 @@ export class RoomClient<View = unknown, Command = unknown> {
249
332
  return this.#clock.rtt;
250
333
  }
251
334
 
335
+ /** Whether this client watches the room without a seat: it was made with `spectate`. */
336
+ get spectating(): boolean {
337
+ return this.#options.spectate === true;
338
+ }
339
+
340
+ /**
341
+ * For a spectator: how far behind the room everything this client is sent
342
+ * is, in milliseconds. 0 when the room does not delay its spectators, and
343
+ * for a player.
344
+ */
345
+ get delayMs(): number {
346
+ return this.#delayMs;
347
+ }
348
+
252
349
  /** This player's id, as the server knows it. Set once connected. */
253
350
  get you(): string | undefined {
254
351
  return this.#you;
@@ -310,7 +407,12 @@ export class RoomClient<View = unknown, Command = unknown> {
310
407
  * Send a command. Resolves once the room applied it, by which time `state`
311
408
  * already reflects it: at once in event mode, and with the next tick in a
312
409
  * room that is ticking. Rejects with `CommandRejected` if the room refused
313
- * it or the connection dropped first.
410
+ * it.
411
+ *
412
+ * A connection that drops on the way does not lose the command, or apply
413
+ * it twice: the client learns what became of it when it is back, and sends
414
+ * it again if it never arrived. Without a connection the command waits for
415
+ * one. Both for at most `keepCommandsMs`, after which it rejects.
314
416
  */
315
417
  send(command: Command): Promise<void> {
316
418
  return this.#request((id) => {
@@ -337,22 +439,52 @@ export class RoomClient<View = unknown, Command = unknown> {
337
439
  socket.close(1000, "client_closed");
338
440
  } else {
339
441
  // Between reconnect attempts there is no socket left to report the close.
442
+ this.#forget();
340
443
  this.#setStatus("closed", { code: 1000, reason: "client_closed" });
341
444
  }
342
445
  }
343
446
 
447
+ /** How long a command may wait for a connection. 0: not at all. */
448
+ #keepMs(): number {
449
+ const keep = this.#options.keepCommandsMs ?? KEEP_COMMANDS_MS;
450
+ return keep > 0 ? keep : 0;
451
+ }
452
+
344
453
  #request(frame: (id: number) => ClientMessage<Command>): Promise<void> {
454
+ if (this.spectating) return Promise.reject(new CommandRejected("spectator"));
345
455
  const socket = this.#socket;
346
- if (!socket || this.#status !== "open") {
456
+ const open = socket !== undefined && this.#status === "open";
457
+ const keep = this.#keepMs();
458
+ // Without a connection it waits for one, if the client is still trying and may keep it.
459
+ if (!open && (this.#status === "closed" || keep === 0)) {
347
460
  return Promise.reject(new CommandRejected("not_connected"));
348
461
  }
349
462
  const id = this.#nextId++;
463
+ const message = frame(id);
350
464
  return new Promise<void>((resolve, reject) => {
351
- this.#pending.set(id, { resolve, reject });
352
- socket.send(JSON.stringify(frame(id)));
465
+ const pending: Pending<Command> = { resolve, reject, frame: message, sent: open };
466
+ this.#pending.set(id, pending);
467
+ if (open) socket.send(JSON.stringify(message));
468
+ else this.#waitFor(id, pending, keep);
353
469
  });
354
470
  }
355
471
 
472
+ /** Has `pending` wait for a connection, for `keep` milliseconds at most. */
473
+ #waitFor(id: number, pending: Pending<Command>, keep: number): void {
474
+ // `setTimeout` takes no delay longer than this, some 24 days: a wait without end is one of those.
475
+ pending.timer = setTimeout(() => this.#giveUp(id, pending), Math.min(keep, 2 ** 31 - 1));
476
+ }
477
+
478
+ /** `pending` has waited for a connection as long as it may. */
479
+ #giveUp(id: number, pending: Pending<Command>): void {
480
+ if (this.#pending.get(id) !== pending || pending.timer === undefined) return;
481
+ this.#pending.delete(id);
482
+ if (this.#unconfirmed.some((sent) => sent.id === id)) {
483
+ this.#unconfirmed = this.#unconfirmed.filter((sent) => sent.id !== id);
484
+ }
485
+ pending.reject(new CommandRejected(pending.sent ? "disconnected" : "not_connected"));
486
+ }
487
+
356
488
  #open(): void {
357
489
  this.#setStatus("connecting");
358
490
  const { token } = this.#options;
@@ -377,6 +509,9 @@ export class RoomClient<View = unknown, Command = unknown> {
377
509
  // The version of the protocol this client speaks: the room answers with the one it will use.
378
510
  asked.searchParams.set("v", String(PROTOCOL_VERSION));
379
511
  if (binary) asked.searchParams.set("patches", BINARY_PATCHES);
512
+ if (this.spectating) asked.searchParams.set("spectate", "1");
513
+ // Who is asking, so that the room can say which of this client's commands it has handled.
514
+ else if (this.#keepMs() > 0) asked.searchParams.set("client", this.#name);
380
515
  url = asked.toString();
381
516
  const socket = new WebSocket(url);
382
517
  if (binary) socket.binaryType = "arraybuffer";
@@ -421,15 +556,17 @@ export class RoomClient<View = unknown, Command = unknown> {
421
556
  });
422
557
  }
423
558
 
424
- /** The current connection is over: settle what was in flight, then follow, retry or stop. */
559
+ /** The current connection is over: keep or settle what was in flight, then follow, retry or stop. */
425
560
  #closed(code: number, reason: string): void {
426
561
  this.#socket = undefined;
427
562
  this.#stopPing();
428
563
  this.#pingsAt = [];
429
564
  this.#clock.reset();
430
- this.#forget();
431
565
 
432
566
  if (code === CloseCode.Moved && reason && !this.#stopped) {
567
+ // What was sent to the room this player has left, or was waiting to be, stays behind.
568
+ this.#forget();
569
+ this.#resumes = false;
433
570
  // Handed over to another room: same URL, with that room's id as the last path segment.
434
571
  const next = new URL(this.#url);
435
572
  next.pathname = next.pathname.replace(/[^/]+\/?$/, reason);
@@ -441,24 +578,95 @@ export class RoomClient<View = unknown, Command = unknown> {
441
578
 
442
579
  const retry = !this.#stopped && this.#options.reconnect !== false && !isFatalCloseCode(code);
443
580
  if (!retry) {
581
+ this.#forget();
444
582
  this.#stopped = true;
445
583
  this.#setStatus("closed", { code, reason });
446
584
  return;
447
585
  }
586
+ this.#keep();
448
587
  this.#setStatus("connecting", { code, reason });
449
588
  const backoff = Math.min(MAX_BACKOFF_MS, 250 * 2 ** this.#attempt++);
450
589
  this.#retryTimer = setTimeout(() => this.#open(), backoff / 2 + Math.random() * (backoff / 2));
451
590
  }
452
591
 
453
- /** What was in flight is lost: the connection is, or the room started again from its last save. */
592
+ /** Gives up on everything: what was sent and not answered, and what was waiting to be sent. */
454
593
  #forget(): void {
455
594
  for (const pending of this.#pending.values()) {
456
- pending.reject(new CommandRejected("disconnected"));
595
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
596
+ pending.reject(new CommandRejected(pending.sent ? "disconnected" : "not_connected"));
457
597
  }
458
598
  this.#pending.clear();
459
599
  if (this.#unconfirmed.length > 0) this.#unconfirmed = [];
460
600
  }
461
601
 
602
+ /**
603
+ * The connection dropped, and the client is about to try for another. What
604
+ * was on its way waits for it, if the room is one that can say what became
605
+ * of it: see `#resume`. If not, it is given up now.
606
+ */
607
+ #keep(): void {
608
+ const keep = this.#keepMs();
609
+ const lost = new Set<number>();
610
+ for (const [id, pending] of this.#pending) {
611
+ // Waiting already, from before this attempt: its time runs from when it began to.
612
+ if (pending.timer !== undefined) continue;
613
+ if (keep > 0 && this.#resumes) {
614
+ this.#waitFor(id, pending, keep);
615
+ } else {
616
+ this.#pending.delete(id);
617
+ lost.add(id);
618
+ pending.reject(new CommandRejected("disconnected"));
619
+ }
620
+ }
621
+ if (this.#unconfirmed.some((sent) => lost.has(sent.id))) {
622
+ this.#unconfirmed = this.#unconfirmed.filter((sent) => !lost.has(sent.id));
623
+ }
624
+ }
625
+
626
+ /**
627
+ * A welcome has arrived: the room is there, and has said what it knows of
628
+ * the commands that were on their way when the last connection dropped.
629
+ *
630
+ * Those it handled are settled, by what this returns, once `state` has
631
+ * been set: the state in the welcome already shows them. Those it did not
632
+ * are sent again, and those that waited to be sent are sent, all in the
633
+ * order they were first sent in and before anything else can be: the room
634
+ * takes a command with a lower number than the last for one it has seen.
635
+ *
636
+ * Without `c` the room knows nothing of what this client sent before: it
637
+ * is older than version 5, the seat is newly taken, or it came back from
638
+ * its last save on a connection that stayed open. What was sent is then
639
+ * given up, as `disconnected`. So is a command up to `from`, of which the
640
+ * room cannot say what became.
641
+ */
642
+ #resume(welcome: WelcomeFrame<View>): (() => void)[] {
643
+ this.#resumes = welcome.v >= 5;
644
+ const socket = this.#socket;
645
+ const handled = this.#resumes ? welcome.c : undefined;
646
+ /** Up to this one the room cannot say what became of a command: see `WelcomeFrame.from`. */
647
+ const from = welcome.from ?? 0;
648
+ const refused = new Map(welcome.refused ?? []);
649
+ const settle: (() => void)[] = [];
650
+ const answered = new Set<number>();
651
+ for (const [id, pending] of this.#pending) {
652
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
653
+ pending.timer = undefined;
654
+ if (!pending.sent || (handled !== undefined && id > handled)) {
655
+ pending.sent = true;
656
+ socket?.send(JSON.stringify(pending.frame));
657
+ continue;
658
+ }
659
+ this.#pending.delete(id);
660
+ answered.add(id);
661
+ const reason = handled === undefined || id <= from ? "disconnected" : refused.get(id);
662
+ settle.push(reason === undefined ? pending.resolve : () => pending.reject(new CommandRejected(reason)));
663
+ }
664
+ if (this.#unconfirmed.some((sent) => answered.has(sent.id))) {
665
+ this.#unconfirmed = this.#unconfirmed.filter((sent) => !answered.has(sent.id));
666
+ }
667
+ return settle;
668
+ }
669
+
462
670
  /** The state about to be set shows this player's commands up to `id`: they are no longer unconfirmed. */
463
671
  #shown(id: number | undefined): void {
464
672
  if (id === undefined || this.#unconfirmed.length === 0) return;
@@ -477,13 +685,14 @@ export class RoomClient<View = unknown, Command = unknown> {
477
685
  #handle(message: ServerMessage<View>): void {
478
686
  switch (message.t) {
479
687
  case "welcome": {
480
- // On a connection that was open already: the room came back from its last save.
481
- this.#forget();
688
+ // Before anything is told to anyone, who might send a command on hearing it.
689
+ const settle = this.#resume(message);
482
690
  this.#attempt = 0;
483
691
  this.#you = message.you;
484
692
  this.#players = message.players;
485
693
  this.#tick = message.tick;
486
694
  this.#tickRate = message.tickRate;
695
+ this.#patchRate = message.patchRate ?? message.tickRate;
487
696
  this.#clock.reset();
488
697
  if (message.ms !== undefined) this.#clock.reading(message.tick, message.tickRate, message.ms, message.epoch);
489
698
  this.#startPing();
@@ -491,8 +700,22 @@ export class RoomClient<View = unknown, Command = unknown> {
491
700
  this.#setStatus("open");
492
701
  this.#emit("presence", this.#players);
493
702
  this.#setState(message.state, message.seq);
703
+ for (const settled of settle) settled();
494
704
  break;
495
705
  }
706
+ case "spectating":
707
+ // In, to watch. The view follows: at once, or when a room that delays it lets it out.
708
+ this.#attempt = 0;
709
+ this.#you = message.you;
710
+ this.#players = message.players;
711
+ this.#tickRate = message.tickRate;
712
+ this.#patchRate = message.patchRate ?? message.tickRate;
713
+ this.#delayMs = message.delay;
714
+ this.#clock.reset();
715
+ this.#startPing();
716
+ this.#setStatus("open");
717
+ this.#emit("presence", this.#players);
718
+ break;
496
719
  case "state":
497
720
  if (message.tick !== undefined) this.#tick = message.tick;
498
721
  this.#shown(message.c);
@@ -1,13 +1,14 @@
1
1
  /**
2
- * Smooths values that arrive once per tick, for drawing between ticks.
2
+ * Smooths values that arrive once per patch, for drawing between patches.
3
3
  *
4
4
  * State sync delivers positions 10 to 30 times a second; a screen draws 60
5
5
  * or more. Each time a new value arrives for an id, the interpolator glides
6
- * to it from wherever that id was being drawn, over `durationMs` (one tick
7
- * is the usual choice). Because it always starts from what is on screen, a
8
- * late or bunched update bends the motion instead of making it jump.
6
+ * to it from wherever that id was being drawn, over `durationMs` (the time
7
+ * between two patches is the usual choice). Because it always starts from
8
+ * what is on screen, a late or bunched update bends the motion instead of
9
+ * making it jump.
9
10
  *
10
- * const glide = new Interpolator(1000 / client.tickRate, ["x", "y"]);
11
+ * const glide = new Interpolator(1000 / client.patchRate, ["x", "y"]);
11
12
  * onState: (state) => glide.update(state.units),
12
13
  * // in the render loop:
13
14
  * const { x, y } = glide.at(id) ?? state.units[id];
@@ -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(