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
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Keeps an estimate of which tick a room is on, from the clock readings the
3
+ * room sends and the round trip to it.
4
+ *
5
+ * A reading says that tick `tick` fell due `ms` milliseconds before the
6
+ * frame was sent. The frame took about half a round trip to arrive, so on
7
+ * this machine `tick` fell due `ms + rtt / 2` before it arrived, and the room
8
+ * has gone on at `tickRate` ticks a second since. Readings of one epoch are
9
+ * averaged, so that one frame held up on the way moves the estimate only a
10
+ * little; a new epoch replaces the estimate.
11
+ */
12
+ export class ServerClock {
13
+ #tickRate = 0;
14
+ #epoch: number | undefined;
15
+ /** The local time (`performance.now()`) at which `#base` fell due, before half the round trip is added. */
16
+ #baseAt: number | undefined;
17
+ #base = 0;
18
+ /** The tick the simulation stopped at, while it is stopped. */
19
+ #stopped: number | undefined;
20
+ #rtt: number | undefined;
21
+
22
+ /** How much of a new reading's difference from the estimate is taken in: the rest is the estimate's. */
23
+ static readonly SMOOTHING = 0.25;
24
+
25
+ /** The smoothed round trip to the room, in milliseconds. Undefined until one has been measured. */
26
+ get rtt(): number | undefined {
27
+ return this.#rtt;
28
+ }
29
+
30
+ /** A round trip took `ms` milliseconds. Averaged with the earlier ones as TCP does: each new one counts for an eighth. */
31
+ roundTrip(ms: number): void {
32
+ if (!Number.isFinite(ms) || ms < 0) return;
33
+ this.#rtt = this.#rtt === undefined ? ms : this.#rtt + (ms - this.#rtt) / 8;
34
+ }
35
+
36
+ /**
37
+ * The room said where its clock is, in a frame that arrived at `now`
38
+ * (local, from `performance.now()`). With `ms` absent the simulation has
39
+ * stopped at `tick`.
40
+ */
41
+ reading(tick: number, tickRate: number, ms: number | undefined, epoch: number | undefined, now = localNow()): void {
42
+ if (ms === undefined || !(tickRate > 0)) {
43
+ this.#stopped = tick;
44
+ this.#baseAt = undefined;
45
+ this.#epoch = undefined;
46
+ return;
47
+ }
48
+ this.#stopped = undefined;
49
+ const at = now - ms;
50
+ if (this.#baseAt === undefined || epoch !== this.#epoch || tickRate !== this.#tickRate) {
51
+ this.#tickRate = tickRate;
52
+ this.#epoch = epoch;
53
+ this.#base = tick;
54
+ this.#baseAt = at;
55
+ return;
56
+ }
57
+ // When `tick` fell due by the estimate so far, then a step towards the new reading.
58
+ const expected = this.#baseAt + ((tick - this.#base) * 1000) / tickRate;
59
+ this.#base = tick;
60
+ this.#baseAt = expected + (at - expected) * ServerClock.SMOOTHING;
61
+ }
62
+
63
+ /** Forget the clock, keeping the round trip: the connection was lost, or the room told nothing yet. */
64
+ reset(): void {
65
+ this.#baseAt = undefined;
66
+ this.#epoch = undefined;
67
+ this.#stopped = undefined;
68
+ }
69
+
70
+ /**
71
+ * The tick the room is on at `now` (local, from `performance.now()`), with
72
+ * the fraction of the next that has passed. The tick it stopped at while
73
+ * its simulation is stopped, and undefined when there is nothing to go on.
74
+ */
75
+ tick(now = localNow()): number | undefined {
76
+ if (this.#stopped !== undefined) return this.#stopped;
77
+ if (this.#baseAt === undefined) return undefined;
78
+ const since = now - this.#baseAt + (this.#rtt ?? 0) / 2;
79
+ return this.#base + (since * this.#tickRate) / 1000;
80
+ }
81
+ }
82
+
83
+ /** A clock that only goes forward, in milliseconds. */
84
+ export function localNow(): number {
85
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
86
+ }
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { BINARY_PATCHES, decodePatchFrame } from "../binary.js";
10
10
  import { applyPatch } from "../patch.js";
11
+ import { ServerClock, localNow } from "./clock.js";
11
12
  import { roomIn, withFreshToken, type TokenSource } from "./token.js";
12
13
  import {
13
14
  CloseCode,
@@ -18,6 +19,7 @@ import {
18
19
  type ClientMessage,
19
20
  type Player,
20
21
  type ServerMessage,
22
+ type WelcomeFrame,
21
23
  } from "../protocol.js";
22
24
 
23
25
  export { CloseCode, type MatchFound, type Player } from "../protocol.js";
@@ -35,16 +37,21 @@ export {
35
37
  type Profile,
36
38
  } from "./accounts.js";
37
39
  export { Interpolator } from "./interpolate.js";
40
+ export { ServerClock } from "./clock.js";
41
+ export { BufferedInterpolator, type BufferedInterpolatorOptions, type TickSource } from "./buffered.js";
38
42
  export { Predictor, type PredictorOptions } from "./predict.js";
39
43
  export { produce } from "./draft.js";
40
44
  export { decodePatchFrame } from "../binary.js";
41
45
  export { LockstepClient, type LockstepClientOptions } from "./lockstep.js";
42
46
  export {
47
+ differences,
43
48
  fingerprint,
44
49
  runReplay,
45
50
  seededRandom,
46
51
  stepThrough,
47
52
  type CatchUp,
53
+ type Desync,
54
+ type DesyncDifference,
48
55
  type LockstepView,
49
56
  type TurnsMessage,
50
57
  type Replay,
@@ -120,6 +127,18 @@ export interface RoomClientOptions<View> {
120
127
  token?: TokenSource;
121
128
  /** The room handed this player to another room, and the client is now connecting there. */
122
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;
123
142
  /** Reconnect after an unexpected close. Defaults to true. */
124
143
  reconnect?: boolean;
125
144
  /**
@@ -138,6 +157,25 @@ export interface RoomClientOptions<View> {
138
157
  * for dead and replaced.
139
158
  */
140
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;
141
179
  }
142
180
 
143
181
  /** A command on its way: sent, and not yet shown by the room's state. */
@@ -148,9 +186,15 @@ export interface SentCommand<Command = unknown> {
148
186
  command: Command;
149
187
  }
150
188
 
151
- /** 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. */
152
190
  export class CommandRejected extends Error {
153
- /** 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
+ */
154
198
  readonly reason: string;
155
199
 
156
200
  constructor(reason: string) {
@@ -161,18 +205,46 @@ export class CommandRejected extends Error {
161
205
  }
162
206
 
163
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
+ }
164
233
 
165
234
  /**
166
235
  * A connection to one room. Holds the latest state the server sent and
167
236
  * reconnects on its own; after a reconnect the server sends the current state
168
- * 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`.
169
239
  */
170
240
  export class RoomClient<View = unknown, Command = unknown> {
171
241
  #state: View | undefined;
172
242
  #seq = 0;
173
243
  #tick = 0;
174
244
  #tickRate = 0;
245
+ #patchRate = 0;
175
246
  #you: string | undefined;
247
+ #delayMs = 0;
176
248
  #players: Player[] = [];
177
249
  #status: ConnectionStatus = "connecting";
178
250
  #listeners = new Map<keyof RoomClientEvents<View>, Set<(...args: never[]) => void>>();
@@ -180,8 +252,13 @@ export class RoomClient<View = unknown, Command = unknown> {
180
252
  #url: string;
181
253
  readonly #options: RoomClientOptions<View>;
182
254
  #socket: WebSocket | undefined;
255
+ /** The name this client goes by: see `clientName`. */
256
+ readonly #name = clientName();
183
257
  #nextId = 1;
184
- #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;
185
262
  /** Commands sent that `#state` does not show yet, oldest first. Replaced, never changed, so that it can be compared by reference. */
186
263
  #unconfirmed: readonly SentCommand<Command>[] = [];
187
264
  #attempt = 0;
@@ -190,6 +267,10 @@ export class RoomClient<View = unknown, Command = unknown> {
190
267
  #pingTimer: ReturnType<typeof setInterval> | undefined;
191
268
  /** A keepalive was sent and nothing has come back since. */
192
269
  #unanswered = false;
270
+ /** When each `ping` that has not been answered yet was sent, oldest first, by `localNow()`. */
271
+ #pingsAt: number[] = [];
272
+ /** Which tick the room is on, from what it says of its clock. */
273
+ readonly #clock = new ServerClock();
193
274
 
194
275
  constructor(url: string | URL, options: RoomClientOptions<View> = {}) {
195
276
  this.#url = String(url);
@@ -217,6 +298,54 @@ export class RoomClient<View = unknown, Command = unknown> {
217
298
  return this.#tickRate;
218
299
  }
219
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
+
310
+ /**
311
+ * The tick the room is on right now, by estimate, with the fraction of the
312
+ * next that has passed: for drawing the game in step with the room, or
313
+ * sending a command in time for a tick. Worked out from the clock the room
314
+ * sends (see `ClockFrame`) and the round trip to it, so it carries on
315
+ * between frames, and is usually ahead of `tick`, which is the latest the
316
+ * room has sent. While the room's simulation is stopped, the tick it
317
+ * stopped at. Undefined in event mode, before the room has said where its
318
+ * clock is, and with a room older than 0.2.
319
+ *
320
+ * @param now the moment to estimate it for, from `performance.now()`
321
+ */
322
+ serverTick(now?: number): number | undefined {
323
+ return this.#clock.tick(now);
324
+ }
325
+
326
+ /**
327
+ * The round trip to the room in milliseconds, smoothed over the latest
328
+ * keepalives. Undefined until one has come back. In a ticking room the
329
+ * client measures it every few seconds; otherwise with the keepalive.
330
+ */
331
+ get rtt(): number | undefined {
332
+ return this.#clock.rtt;
333
+ }
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
+
220
349
  /** This player's id, as the server knows it. Set once connected. */
221
350
  get you(): string | undefined {
222
351
  return this.#you;
@@ -278,7 +407,12 @@ export class RoomClient<View = unknown, Command = unknown> {
278
407
  * Send a command. Resolves once the room applied it, by which time `state`
279
408
  * already reflects it: at once in event mode, and with the next tick in a
280
409
  * room that is ticking. Rejects with `CommandRejected` if the room refused
281
- * 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.
282
416
  */
283
417
  send(command: Command): Promise<void> {
284
418
  return this.#request((id) => {
@@ -305,22 +439,52 @@ export class RoomClient<View = unknown, Command = unknown> {
305
439
  socket.close(1000, "client_closed");
306
440
  } else {
307
441
  // Between reconnect attempts there is no socket left to report the close.
442
+ this.#forget();
308
443
  this.#setStatus("closed", { code: 1000, reason: "client_closed" });
309
444
  }
310
445
  }
311
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
+
312
453
  #request(frame: (id: number) => ClientMessage<Command>): Promise<void> {
454
+ if (this.spectating) return Promise.reject(new CommandRejected("spectator"));
313
455
  const socket = this.#socket;
314
- 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)) {
315
460
  return Promise.reject(new CommandRejected("not_connected"));
316
461
  }
317
462
  const id = this.#nextId++;
463
+ const message = frame(id);
318
464
  return new Promise<void>((resolve, reject) => {
319
- this.#pending.set(id, { resolve, reject });
320
- 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);
321
469
  });
322
470
  }
323
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
+
324
488
  #open(): void {
325
489
  this.#setStatus("connecting");
326
490
  const { token } = this.#options;
@@ -345,6 +509,9 @@ export class RoomClient<View = unknown, Command = unknown> {
345
509
  // The version of the protocol this client speaks: the room answers with the one it will use.
346
510
  asked.searchParams.set("v", String(PROTOCOL_VERSION));
347
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);
348
515
  url = asked.toString();
349
516
  const socket = new WebSocket(url);
350
517
  if (binary) socket.binaryType = "arraybuffer";
@@ -370,7 +537,11 @@ export class RoomClient<View = unknown, Command = unknown> {
370
537
  if (typeof data !== "string") return;
371
538
  // Anything the server sends shows the connection is alive.
372
539
  this.#unanswered = false;
373
- if (data === PONG) return;
540
+ if (data === PONG) {
541
+ const sentAt = this.#pingsAt.shift();
542
+ if (sentAt !== undefined) this.#clock.roundTrip(localNow() - sentAt);
543
+ return;
544
+ }
374
545
  this.#handle(JSON.parse(data) as ServerMessage<View>);
375
546
  });
376
547
 
@@ -385,13 +556,17 @@ export class RoomClient<View = unknown, Command = unknown> {
385
556
  });
386
557
  }
387
558
 
388
- /** 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. */
389
560
  #closed(code: number, reason: string): void {
390
561
  this.#socket = undefined;
391
562
  this.#stopPing();
392
- this.#forget();
563
+ this.#pingsAt = [];
564
+ this.#clock.reset();
393
565
 
394
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;
395
570
  // Handed over to another room: same URL, with that room's id as the last path segment.
396
571
  const next = new URL(this.#url);
397
572
  next.pathname = next.pathname.replace(/[^/]+\/?$/, reason);
@@ -403,24 +578,95 @@ export class RoomClient<View = unknown, Command = unknown> {
403
578
 
404
579
  const retry = !this.#stopped && this.#options.reconnect !== false && !isFatalCloseCode(code);
405
580
  if (!retry) {
581
+ this.#forget();
406
582
  this.#stopped = true;
407
583
  this.#setStatus("closed", { code, reason });
408
584
  return;
409
585
  }
586
+ this.#keep();
410
587
  this.#setStatus("connecting", { code, reason });
411
588
  const backoff = Math.min(MAX_BACKOFF_MS, 250 * 2 ** this.#attempt++);
412
589
  this.#retryTimer = setTimeout(() => this.#open(), backoff / 2 + Math.random() * (backoff / 2));
413
590
  }
414
591
 
415
- /** 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. */
416
593
  #forget(): void {
417
594
  for (const pending of this.#pending.values()) {
418
- pending.reject(new CommandRejected("disconnected"));
595
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
596
+ pending.reject(new CommandRejected(pending.sent ? "disconnected" : "not_connected"));
419
597
  }
420
598
  this.#pending.clear();
421
599
  if (this.#unconfirmed.length > 0) this.#unconfirmed = [];
422
600
  }
423
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
+
424
670
  /** The state about to be set shows this player's commands up to `id`: they are no longer unconfirmed. */
425
671
  #shown(id: number | undefined): void {
426
672
  if (id === undefined || this.#unconfirmed.length === 0) return;
@@ -439,19 +685,37 @@ export class RoomClient<View = unknown, Command = unknown> {
439
685
  #handle(message: ServerMessage<View>): void {
440
686
  switch (message.t) {
441
687
  case "welcome": {
442
- // On a connection that was open already: the room came back from its last save.
443
- this.#forget();
688
+ // Before anything is told to anyone, who might send a command on hearing it.
689
+ const settle = this.#resume(message);
444
690
  this.#attempt = 0;
445
691
  this.#you = message.you;
446
692
  this.#players = message.players;
447
693
  this.#tick = message.tick;
448
694
  this.#tickRate = message.tickRate;
695
+ this.#patchRate = message.patchRate ?? message.tickRate;
696
+ this.#clock.reset();
697
+ if (message.ms !== undefined) this.#clock.reading(message.tick, message.tickRate, message.ms, message.epoch);
449
698
  this.#startPing();
699
+ if (message.tickRate > 0) this.#measure();
450
700
  this.#setStatus("open");
451
701
  this.#emit("presence", this.#players);
452
702
  this.#setState(message.state, message.seq);
703
+ for (const settled of settle) settled();
453
704
  break;
454
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;
455
719
  case "state":
456
720
  if (message.tick !== undefined) this.#tick = message.tick;
457
721
  this.#shown(message.c);
@@ -470,6 +734,10 @@ export class RoomClient<View = unknown, Command = unknown> {
470
734
  this.#setState(applyPatch(this.#state as View, message.p), message.seq);
471
735
  this.#resolveUpTo(message.c);
472
736
  break;
737
+ case "clock":
738
+ this.#clock.reading(message.tick, this.#tickRate, message.ms, message.epoch);
739
+ if (message.ms !== undefined) this.#measure();
740
+ break;
473
741
  case "presence":
474
742
  this.#players = message.players ?? withPresence(this.#players, message.set, message.gone);
475
743
  this.#emit("presence", this.#players);
@@ -540,10 +808,23 @@ export class RoomClient<View = unknown, Command = unknown> {
540
808
  return;
541
809
  }
542
810
  this.#unanswered = true;
811
+ this.#pingsAt.push(localNow());
543
812
  socket.send(PING);
544
813
  }, interval);
545
814
  }
546
815
 
816
+ /** Sends a `ping` to time the round trip, unless one is on its way already. Leaves the keepalive's watch alone. */
817
+ #measure(): void {
818
+ const socket = this.#socket;
819
+ if (socket?.readyState !== 1 || this.#pingsAt.length > 0) return;
820
+ this.#pingsAt.push(localNow());
821
+ try {
822
+ socket.send(PING);
823
+ } catch {
824
+ this.#pingsAt.pop();
825
+ }
826
+ }
827
+
547
828
  #stopPing(): void {
548
829
  if (this.#pingTimer !== undefined) clearInterval(this.#pingTimer);
549
830
  this.#pingTimer = undefined;
@@ -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];