tickflare 0.1.0 → 0.2.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.
- package/CHANGELOG.md +7 -0
- package/README.md +2 -0
- package/dist/client/buffered.d.ts +88 -0
- package/dist/client/buffered.js +229 -0
- package/dist/client/buffered.js.map +1 -0
- package/dist/client/clock.d.ts +36 -0
- package/dist/client/clock.js +83 -0
- package/dist/client/clock.js.map +1 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.js +61 -1
- package/dist/client/index.js.map +1 -1
- package/dist/protocol.d.ts +40 -2
- package/dist/protocol.js +5 -1
- package/dist/protocol.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/lockstep.d.ts +1 -0
- package/dist/server/lockstep.js +6 -1
- package/dist/server/lockstep.js.map +1 -1
- package/dist/server/room.d.ts +20 -1
- package/dist/server/room.js +147 -17
- package/dist/server/room.js.map +1 -1
- package/package.json +1 -1
- package/src/client/buffered.ts +264 -0
- package/src/client/clock.ts +86 -0
- package/src/client/index.ts +59 -1
- package/src/protocol.ts +41 -1
- package/src/server/index.ts +1 -0
- package/src/server/lockstep.ts +7 -1
- package/src/server/room.ts +149 -17
package/src/client/index.ts
CHANGED
|
@@ -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,
|
|
@@ -35,6 +36,8 @@ export {
|
|
|
35
36
|
type Profile,
|
|
36
37
|
} from "./accounts.js";
|
|
37
38
|
export { Interpolator } from "./interpolate.js";
|
|
39
|
+
export { ServerClock } from "./clock.js";
|
|
40
|
+
export { BufferedInterpolator, type BufferedInterpolatorOptions, type TickSource } from "./buffered.js";
|
|
38
41
|
export { Predictor, type PredictorOptions } from "./predict.js";
|
|
39
42
|
export { produce } from "./draft.js";
|
|
40
43
|
export { decodePatchFrame } from "../binary.js";
|
|
@@ -190,6 +193,10 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
190
193
|
#pingTimer: ReturnType<typeof setInterval> | undefined;
|
|
191
194
|
/** A keepalive was sent and nothing has come back since. */
|
|
192
195
|
#unanswered = false;
|
|
196
|
+
/** When each `ping` that has not been answered yet was sent, oldest first, by `localNow()`. */
|
|
197
|
+
#pingsAt: number[] = [];
|
|
198
|
+
/** Which tick the room is on, from what it says of its clock. */
|
|
199
|
+
readonly #clock = new ServerClock();
|
|
193
200
|
|
|
194
201
|
constructor(url: string | URL, options: RoomClientOptions<View> = {}) {
|
|
195
202
|
this.#url = String(url);
|
|
@@ -217,6 +224,31 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
217
224
|
return this.#tickRate;
|
|
218
225
|
}
|
|
219
226
|
|
|
227
|
+
/**
|
|
228
|
+
* The tick the room is on right now, by estimate, with the fraction of the
|
|
229
|
+
* next that has passed: for drawing the game in step with the room, or
|
|
230
|
+
* sending a command in time for a tick. Worked out from the clock the room
|
|
231
|
+
* sends (see `ClockFrame`) and the round trip to it, so it carries on
|
|
232
|
+
* between frames, and is usually ahead of `tick`, which is the latest the
|
|
233
|
+
* room has sent. While the room's simulation is stopped, the tick it
|
|
234
|
+
* stopped at. Undefined in event mode, before the room has said where its
|
|
235
|
+
* clock is, and with a room older than 0.2.
|
|
236
|
+
*
|
|
237
|
+
* @param now the moment to estimate it for, from `performance.now()`
|
|
238
|
+
*/
|
|
239
|
+
serverTick(now?: number): number | undefined {
|
|
240
|
+
return this.#clock.tick(now);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The round trip to the room in milliseconds, smoothed over the latest
|
|
245
|
+
* keepalives. Undefined until one has come back. In a ticking room the
|
|
246
|
+
* client measures it every few seconds; otherwise with the keepalive.
|
|
247
|
+
*/
|
|
248
|
+
get rtt(): number | undefined {
|
|
249
|
+
return this.#clock.rtt;
|
|
250
|
+
}
|
|
251
|
+
|
|
220
252
|
/** This player's id, as the server knows it. Set once connected. */
|
|
221
253
|
get you(): string | undefined {
|
|
222
254
|
return this.#you;
|
|
@@ -370,7 +402,11 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
370
402
|
if (typeof data !== "string") return;
|
|
371
403
|
// Anything the server sends shows the connection is alive.
|
|
372
404
|
this.#unanswered = false;
|
|
373
|
-
if (data === PONG)
|
|
405
|
+
if (data === PONG) {
|
|
406
|
+
const sentAt = this.#pingsAt.shift();
|
|
407
|
+
if (sentAt !== undefined) this.#clock.roundTrip(localNow() - sentAt);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
374
410
|
this.#handle(JSON.parse(data) as ServerMessage<View>);
|
|
375
411
|
});
|
|
376
412
|
|
|
@@ -389,6 +425,8 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
389
425
|
#closed(code: number, reason: string): void {
|
|
390
426
|
this.#socket = undefined;
|
|
391
427
|
this.#stopPing();
|
|
428
|
+
this.#pingsAt = [];
|
|
429
|
+
this.#clock.reset();
|
|
392
430
|
this.#forget();
|
|
393
431
|
|
|
394
432
|
if (code === CloseCode.Moved && reason && !this.#stopped) {
|
|
@@ -446,7 +484,10 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
446
484
|
this.#players = message.players;
|
|
447
485
|
this.#tick = message.tick;
|
|
448
486
|
this.#tickRate = message.tickRate;
|
|
487
|
+
this.#clock.reset();
|
|
488
|
+
if (message.ms !== undefined) this.#clock.reading(message.tick, message.tickRate, message.ms, message.epoch);
|
|
449
489
|
this.#startPing();
|
|
490
|
+
if (message.tickRate > 0) this.#measure();
|
|
450
491
|
this.#setStatus("open");
|
|
451
492
|
this.#emit("presence", this.#players);
|
|
452
493
|
this.#setState(message.state, message.seq);
|
|
@@ -470,6 +511,10 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
470
511
|
this.#setState(applyPatch(this.#state as View, message.p), message.seq);
|
|
471
512
|
this.#resolveUpTo(message.c);
|
|
472
513
|
break;
|
|
514
|
+
case "clock":
|
|
515
|
+
this.#clock.reading(message.tick, this.#tickRate, message.ms, message.epoch);
|
|
516
|
+
if (message.ms !== undefined) this.#measure();
|
|
517
|
+
break;
|
|
473
518
|
case "presence":
|
|
474
519
|
this.#players = message.players ?? withPresence(this.#players, message.set, message.gone);
|
|
475
520
|
this.#emit("presence", this.#players);
|
|
@@ -540,10 +585,23 @@ export class RoomClient<View = unknown, Command = unknown> {
|
|
|
540
585
|
return;
|
|
541
586
|
}
|
|
542
587
|
this.#unanswered = true;
|
|
588
|
+
this.#pingsAt.push(localNow());
|
|
543
589
|
socket.send(PING);
|
|
544
590
|
}, interval);
|
|
545
591
|
}
|
|
546
592
|
|
|
593
|
+
/** Sends a `ping` to time the round trip, unless one is on its way already. Leaves the keepalive's watch alone. */
|
|
594
|
+
#measure(): void {
|
|
595
|
+
const socket = this.#socket;
|
|
596
|
+
if (socket?.readyState !== 1 || this.#pingsAt.length > 0) return;
|
|
597
|
+
this.#pingsAt.push(localNow());
|
|
598
|
+
try {
|
|
599
|
+
socket.send(PING);
|
|
600
|
+
} catch {
|
|
601
|
+
this.#pingsAt.pop();
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
547
605
|
#stopPing(): void {
|
|
548
606
|
if (this.#pingTimer !== undefined) clearInterval(this.#pingTimer);
|
|
549
607
|
this.#pingTimer = undefined;
|
package/src/protocol.ts
CHANGED
|
@@ -18,8 +18,12 @@ 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.
|
|
21
25
|
*/
|
|
22
|
-
export const PROTOCOL_VERSION =
|
|
26
|
+
export const PROTOCOL_VERSION = 4;
|
|
23
27
|
|
|
24
28
|
/** The keepalive a client sends, as a plain text frame. @internal */
|
|
25
29
|
export const PING = "ping";
|
|
@@ -76,6 +80,10 @@ export interface WelcomeFrame<View = unknown> {
|
|
|
76
80
|
tick: number;
|
|
77
81
|
/** Ticks a second; 0 in event mode. */
|
|
78
82
|
tickRate: number;
|
|
83
|
+
/** Version 4, while the simulation runs: as in `ClockFrame`. Absent while it does not. */
|
|
84
|
+
ms?: number;
|
|
85
|
+
/** Version 4, while the simulation runs: as in `ClockFrame`. */
|
|
86
|
+
epoch?: number;
|
|
79
87
|
/** This player's whole view. */
|
|
80
88
|
state: View;
|
|
81
89
|
/** Everyone with a seat, in join order. */
|
|
@@ -163,6 +171,37 @@ export interface AckFrame {
|
|
|
163
171
|
tick?: number;
|
|
164
172
|
}
|
|
165
173
|
|
|
174
|
+
/**
|
|
175
|
+
* Version 4: where the room's clock is. Ticks fall due on a fixed clock, one
|
|
176
|
+
* every `1 / tickRate` seconds from when the simulation started, so a client
|
|
177
|
+
* that knows how long ago one tick was due can tell which tick the room is on
|
|
178
|
+
* at any moment: `tick + (ms + elapsed) * tickRate / 1000`, where `elapsed`
|
|
179
|
+
* is the time since the frame was sent, about half a round trip when it
|
|
180
|
+
* arrives. `RoomClient.serverTick()` works this out.
|
|
181
|
+
*
|
|
182
|
+
* Sent every five seconds while the simulation runs, and at once when it
|
|
183
|
+
* starts, stops, or lets ticks go after a stall. The same reading is in
|
|
184
|
+
* `welcome` for a client that connects while it runs.
|
|
185
|
+
*/
|
|
186
|
+
export interface ClockFrame {
|
|
187
|
+
/** Frame type. */
|
|
188
|
+
t: "clock";
|
|
189
|
+
/** The latest tick the room has run. */
|
|
190
|
+
tick: number;
|
|
191
|
+
/**
|
|
192
|
+
* How long before this frame was sent `tick` fell due, in milliseconds:
|
|
193
|
+
* usually less than one tick, more when the room is running late. Absent
|
|
194
|
+
* when the simulation has stopped, at `tick`, until a frame says otherwise.
|
|
195
|
+
*/
|
|
196
|
+
ms?: number;
|
|
197
|
+
/**
|
|
198
|
+
* Which run of the clock this is. It changes when the simulation starts
|
|
199
|
+
* again, and when the room lets ticks go after a stall; while it stays the
|
|
200
|
+
* same, readings can be averaged.
|
|
201
|
+
*/
|
|
202
|
+
epoch?: number;
|
|
203
|
+
}
|
|
204
|
+
|
|
166
205
|
/** The command or leave with this `id` was refused, and nothing changed. */
|
|
167
206
|
export interface RejectFrame {
|
|
168
207
|
/** Frame type. */
|
|
@@ -198,6 +237,7 @@ export type ServerMessage<View = unknown> =
|
|
|
198
237
|
| StateFrame<View>
|
|
199
238
|
| PatchFrame
|
|
200
239
|
| PresenceFrame
|
|
240
|
+
| ClockFrame
|
|
201
241
|
| AckFrame
|
|
202
242
|
| RejectFrame
|
|
203
243
|
| ErrorFrame
|
package/src/server/index.ts
CHANGED
package/src/server/lockstep.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { CatchUp, LockstepView, Replay, Snapshot, TurnEntry, 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. */
|
|
@@ -138,6 +138,12 @@ export abstract class LockstepRoom<Input, Env = Cloudflare.Env> extends Room<
|
|
|
138
138
|
/** Names this run of the room: see `CatchUp.epoch`. */
|
|
139
139
|
#epoch: string | undefined;
|
|
140
140
|
|
|
141
|
+
constructor(ctx: DurableObjectState, env: Env) {
|
|
142
|
+
super(ctx, env);
|
|
143
|
+
// The view is one turn: when the room catches up on several, each still needs a frame of its own.
|
|
144
|
+
patchEachTick(this);
|
|
145
|
+
}
|
|
146
|
+
|
|
141
147
|
/**
|
|
142
148
|
* Turn an untrusted client payload into an input. Every client will feed
|
|
143
149
|
* what this returns to its simulation, so reject anything malformed here.
|
package/src/server/room.ts
CHANGED
|
@@ -70,6 +70,8 @@ const BINARY_TAG = "\u0001patches=b1";
|
|
|
70
70
|
const V2_TAG = "\u0001v=2";
|
|
71
71
|
/** Marks the socket of a client that speaks version 3: it is told who came and went, not the whole list of players. */
|
|
72
72
|
const V3_TAG = "\u0001v=3";
|
|
73
|
+
/** Marks the socket of a client that speaks version 4: it is told the room's clock. */
|
|
74
|
+
const V4_TAG = "\u0001v=4";
|
|
73
75
|
const isMark = (tag: string) => tag.charCodeAt(0) === 1;
|
|
74
76
|
|
|
75
77
|
/** What a socket's tags say: whose it is, and what its client asked for. */
|
|
@@ -81,6 +83,8 @@ interface SocketInfo {
|
|
|
81
83
|
arrays: boolean;
|
|
82
84
|
/** Version 3: presence as changes. */
|
|
83
85
|
presence: boolean;
|
|
86
|
+
/** Version 4: told the room's clock. */
|
|
87
|
+
clock: boolean;
|
|
84
88
|
}
|
|
85
89
|
/**
|
|
86
90
|
* In a room with more than `PRESENCE_CROWD` connections, the least time
|
|
@@ -105,7 +109,7 @@ const DELETE_RETRY_MS = 30_000;
|
|
|
105
109
|
*
|
|
106
110
|
* Cloudflare takes an object that has had no incoming event for 70 to 140
|
|
107
111
|
* seconds out of memory, simulation and all. A keepalive does not count:
|
|
108
|
-
* Cloudflare answers it without waking the room. A pending
|
|
112
|
+
* Cloudflare answers it without waking the room. A pending timer
|
|
109
113
|
* holds the object for at most 15 minutes. So without this, a match in which
|
|
110
114
|
* nobody sends a command would stop, and stay stopped until someone did. An
|
|
111
115
|
* alarm is an event, and when Cloudflare restarts the room for any other
|
|
@@ -127,6 +131,19 @@ const DELETE_PATIENCE_MS = 10_000;
|
|
|
127
131
|
const FORWARD_GRACE_MS = 30_000;
|
|
128
132
|
/** Consecutive failed ticks after which the simulation pauses until the next event. */
|
|
129
133
|
const MAX_FAILED_TICKS = 5;
|
|
134
|
+
/**
|
|
135
|
+
* Rooms that send a patch for every tick, even when they catch up several at
|
|
136
|
+
* once: a lockstep room's view is one turn, and a client must see each.
|
|
137
|
+
*/
|
|
138
|
+
const patchesEachTick = new WeakSet<object>();
|
|
139
|
+
|
|
140
|
+
/** Has `room` send a patch for every tick it runs, also when catching up. @internal */
|
|
141
|
+
export function patchEachTick(room: object): void {
|
|
142
|
+
patchesEachTick.add(room);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** While the simulation runs, how often clients of version 4 are told the room's clock, in milliseconds. */
|
|
146
|
+
const CLOCK_EVERY_MS = 5_000;
|
|
130
147
|
|
|
131
148
|
/**
|
|
132
149
|
* An authoritative game room: one Durable Object per room.
|
|
@@ -191,6 +208,22 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
191
208
|
/** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
|
|
192
209
|
protected tickRate = 0;
|
|
193
210
|
|
|
211
|
+
/**
|
|
212
|
+
* While the room is ticking, the most ticks it runs back to back to catch
|
|
213
|
+
* up when it wakes late. The simulation keeps to a fixed clock: tick `n`
|
|
214
|
+
* is due `n / tickRate` seconds after the clock started, and a room that
|
|
215
|
+
* wakes late, because a tick or an event took long or the machine was
|
|
216
|
+
* busy, runs every tick that has come due since, each with the same `dt`,
|
|
217
|
+
* and sends one patch for all of them.
|
|
218
|
+
*
|
|
219
|
+
* When more than this many are due, after a stall of a fraction of a
|
|
220
|
+
* second, the room runs this many and lets the rest go: the clock moves on,
|
|
221
|
+
* and the game is that much behind the wall clock for good, instead of
|
|
222
|
+
* fast-forwarding through a burst of ticks. 1 never catches up, which is
|
|
223
|
+
* how rooms ran before 0.2.
|
|
224
|
+
*/
|
|
225
|
+
protected maxCatchUpTicks = 5;
|
|
226
|
+
|
|
194
227
|
/**
|
|
195
228
|
* While the room is ticking, how often the state is written to storage, in
|
|
196
229
|
* milliseconds. It is also written whenever the simulation stops. A room
|
|
@@ -345,8 +378,19 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
345
378
|
|
|
346
379
|
/** Ticks run since the room was created. */
|
|
347
380
|
#tick = 0;
|
|
348
|
-
/** Set while the simulation is running. */
|
|
349
|
-
#loop: ReturnType<typeof
|
|
381
|
+
/** Set while the simulation is running: the timer for the next wake-up. */
|
|
382
|
+
#loop: ReturnType<typeof setTimeout> | undefined;
|
|
383
|
+
/**
|
|
384
|
+
* The simulation's clock: tick `#clockTick` was due at `#clockAt`, in epoch
|
|
385
|
+
* milliseconds, and each tick after it `1000 / tickRate` later. Set when
|
|
386
|
+
* the simulation starts, and moved on when ticks are let go.
|
|
387
|
+
*/
|
|
388
|
+
#clockTick = 0;
|
|
389
|
+
#clockAt = 0;
|
|
390
|
+
/** Goes up each time the clock starts over or moves on: a client keeps a clock per epoch. */
|
|
391
|
+
#epoch = 0;
|
|
392
|
+
/** When clients were last told the clock, in epoch milliseconds. */
|
|
393
|
+
#clockToldAt = 0;
|
|
350
394
|
/** The committed state is newer than what is in storage. Only happens while ticking. */
|
|
351
395
|
#unsaved = false;
|
|
352
396
|
#ticksSinceSave = 0;
|
|
@@ -408,7 +452,9 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
408
452
|
|
|
409
453
|
/**
|
|
410
454
|
* Advance the simulation by one step of `dt` seconds (always `1 / tickRate`).
|
|
411
|
-
* Runs `tickRate` times a second while the room is ticking
|
|
455
|
+
* Runs `tickRate` times a second while the room is ticking, on a fixed
|
|
456
|
+
* clock: a room that wakes late runs the ticks it owes back to back. See
|
|
457
|
+
* `maxCatchUpTicks`.
|
|
412
458
|
*/
|
|
413
459
|
protected onTick(_dt: number): void {}
|
|
414
460
|
|
|
@@ -801,6 +847,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
801
847
|
if (asked.get("patches") === BINARY_PATCHES) marks.push(BINARY_TAG);
|
|
802
848
|
if (Number(asked.get("v")) >= 2) marks.push(V2_TAG);
|
|
803
849
|
if (Number(asked.get("v")) >= 3) marks.push(V3_TAG);
|
|
850
|
+
if (Number(asked.get("v")) >= 4) marks.push(V4_TAG);
|
|
804
851
|
const response = this.#connect(playerId, name, marks);
|
|
805
852
|
await this.#finish();
|
|
806
853
|
return response;
|
|
@@ -978,6 +1025,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
978
1025
|
seq: this.#seq,
|
|
979
1026
|
tick: this.#tick,
|
|
980
1027
|
tickRate: this.tickRate,
|
|
1028
|
+
...(this.#loop !== undefined && this.#socketInfo(ws).clock ? this.#clockReading(Date.now()) : {}),
|
|
981
1029
|
state: this.view(player),
|
|
982
1030
|
players: this.players,
|
|
983
1031
|
} satisfies ServerMessage);
|
|
@@ -1256,14 +1304,86 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
1256
1304
|
#syncLoop(): void {
|
|
1257
1305
|
const wanted = this.#wantsTicks(this.#anySeated());
|
|
1258
1306
|
if (wanted && this.#loop === undefined) {
|
|
1259
|
-
|
|
1307
|
+
// A clock of its own for every run: the time the simulation spent stopped is not owed back.
|
|
1308
|
+
const now = Date.now();
|
|
1309
|
+
this.#clockTick = this.#tick;
|
|
1310
|
+
this.#clockAt = now;
|
|
1311
|
+
this.#epoch += 1;
|
|
1312
|
+
this.#schedule(now);
|
|
1313
|
+
this.#tellClock(now);
|
|
1260
1314
|
} else if (!wanted && this.#loop !== undefined) {
|
|
1261
|
-
|
|
1315
|
+
clearTimeout(this.#loop);
|
|
1262
1316
|
this.#loop = undefined;
|
|
1263
1317
|
// Send what changed since the last tick, or it would never go out.
|
|
1264
1318
|
this.#broadcastTick();
|
|
1265
1319
|
if (this.#unsaved) this.#writeRoom();
|
|
1320
|
+
this.#tellClock(Date.now());
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
/** When tick `tick` is due by the simulation's clock, in epoch milliseconds. */
|
|
1325
|
+
#dueAt(tick: number): number {
|
|
1326
|
+
return this.#clockAt + ((tick - this.#clockTick) * 1000) / this.tickRate;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/** Sets the timer for the moment the next tick is due. */
|
|
1330
|
+
#schedule(now: number): void {
|
|
1331
|
+
const wait = Math.max(0, Math.ceil(this.#dueAt(this.#tick + 1) - now));
|
|
1332
|
+
this.#loop = setTimeout(() => this.#wake(), wait);
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* The simulation's timer fired: run every tick that has come due since the
|
|
1337
|
+
* last wake-up, up to `maxCatchUpTicks`, then send one patch for them all.
|
|
1338
|
+
*/
|
|
1339
|
+
#wake(): void {
|
|
1340
|
+
const now = Date.now();
|
|
1341
|
+
const elapsed = ((now - this.#clockAt) * this.tickRate) / 1000;
|
|
1342
|
+
// A hair of slack, so that floating point does not put a tick that is due a moment later.
|
|
1343
|
+
const due = this.#clockTick + Math.floor(elapsed + 1e-6);
|
|
1344
|
+
const cap = Math.max(1, Math.floor(this.maxCatchUpTicks) || 1);
|
|
1345
|
+
let moved = false;
|
|
1346
|
+
if (due - this.#tick > cap) {
|
|
1347
|
+
// Too far behind to catch up: let the rest go, and move the clock on by as many ticks.
|
|
1348
|
+
this.#clockTick -= due - this.#tick - cap;
|
|
1349
|
+
this.#epoch += 1;
|
|
1350
|
+
moved = true;
|
|
1351
|
+
}
|
|
1352
|
+
const until = Math.min(due, this.#tick + cap);
|
|
1353
|
+
const eachTick = patchesEachTick.has(this);
|
|
1354
|
+
let ran = 0;
|
|
1355
|
+
let halted = false;
|
|
1356
|
+
while (this.#tick < until) {
|
|
1357
|
+
// What the last tick did may have stopped the simulation: checked after every tick, as ever.
|
|
1358
|
+
if (ran > 0 && !this.#wantsTicks(this.#anySeated())) {
|
|
1359
|
+
halted = true;
|
|
1360
|
+
break;
|
|
1361
|
+
}
|
|
1362
|
+
if (ran > 0 && eachTick) this.#broadcastTick();
|
|
1363
|
+
this.#runTick();
|
|
1364
|
+
ran += 1;
|
|
1365
|
+
}
|
|
1366
|
+
if (halted) {
|
|
1367
|
+
// `#finish` stops the simulation in a moment. Until it does, no tick is due at once.
|
|
1368
|
+
this.#loop = setTimeout(() => this.#wake(), 1000 / this.tickRate);
|
|
1369
|
+
} else {
|
|
1370
|
+
this.#schedule(now);
|
|
1371
|
+
}
|
|
1372
|
+
if (ran === 0) return; // Woke a little early: nothing is due yet.
|
|
1373
|
+
|
|
1374
|
+
if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
|
|
1375
|
+
this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
|
|
1376
|
+
this.#closeSilent(now);
|
|
1377
|
+
}
|
|
1378
|
+
// Counted in ticks, as ever: catching up does not change when saves happen.
|
|
1379
|
+
this.#ticksSinceSave += ran;
|
|
1380
|
+
if (this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
|
|
1381
|
+
this.#ticksSinceSave = 0;
|
|
1382
|
+
if (this.#unsaved) this.#writeRoom();
|
|
1266
1383
|
}
|
|
1384
|
+
this.#broadcastTick();
|
|
1385
|
+
if (moved || now - this.#clockToldAt >= CLOCK_EVERY_MS) this.#tellClock(now);
|
|
1386
|
+
this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
|
|
1267
1387
|
}
|
|
1268
1388
|
|
|
1269
1389
|
#runTick(): void {
|
|
@@ -1276,19 +1396,30 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
1276
1396
|
this.#failedTicks = 0;
|
|
1277
1397
|
this.#stalled = true;
|
|
1278
1398
|
}
|
|
1399
|
+
}
|
|
1279
1400
|
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
}
|
|
1401
|
+
/** Where the clock is at `now`, for a client of version 4: see `ClockFrame`. */
|
|
1402
|
+
#clockReading(now: number): { ms: number; epoch: number } {
|
|
1403
|
+
return { ms: Math.max(0, Math.round(now - this.#dueAt(this.#tick))), epoch: this.#epoch };
|
|
1404
|
+
}
|
|
1285
1405
|
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1406
|
+
/** Tells every client of version 4 where the clock is, or that it stopped. */
|
|
1407
|
+
#tellClock(now: number): void {
|
|
1408
|
+
this.#clockToldAt = now;
|
|
1409
|
+
let frame: string | undefined;
|
|
1410
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
1411
|
+
if (ws.readyState !== SOCKET_OPEN || !this.#socketInfo(ws).clock) continue;
|
|
1412
|
+
frame ??= JSON.stringify({
|
|
1413
|
+
t: "clock",
|
|
1414
|
+
tick: this.#tick,
|
|
1415
|
+
...(this.#loop !== undefined ? this.#clockReading(now) : {}),
|
|
1416
|
+
} satisfies ServerMessage);
|
|
1417
|
+
try {
|
|
1418
|
+
ws.send(frame);
|
|
1419
|
+
} catch {
|
|
1420
|
+
// Socket is closing.
|
|
1421
|
+
}
|
|
1289
1422
|
}
|
|
1290
|
-
this.#broadcastTick();
|
|
1291
|
-
this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
|
|
1292
1423
|
}
|
|
1293
1424
|
|
|
1294
1425
|
/**
|
|
@@ -1657,7 +1788,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
1657
1788
|
/** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
|
|
1658
1789
|
#versionOf(ws: WebSocket): number {
|
|
1659
1790
|
const info = this.#socketInfo(ws);
|
|
1660
|
-
return info.presence ?
|
|
1791
|
+
return info.clock ? 4 : info.presence ? 3 : info.arrays ? 2 : 1;
|
|
1661
1792
|
}
|
|
1662
1793
|
|
|
1663
1794
|
/**
|
|
@@ -1806,6 +1937,7 @@ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> exten
|
|
|
1806
1937
|
binary: tags.includes(BINARY_TAG),
|
|
1807
1938
|
arrays: tags.includes(V2_TAG),
|
|
1808
1939
|
presence: tags.includes(V3_TAG),
|
|
1940
|
+
clock: tags.includes(V4_TAG),
|
|
1809
1941
|
};
|
|
1810
1942
|
this.#infos.set(ws, info);
|
|
1811
1943
|
}
|