tickflare 0.0.0-stage → 0.1.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 (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,1867 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import {
3
+ CloseCode,
4
+ PING,
5
+ PONG,
6
+ PROTOCOL_VERSION,
7
+ type MatchResult,
8
+ type Player,
9
+ type ServerMessage,
10
+ } from "../protocol.js";
11
+ import { BINARY_PATCHES } from "../binary.js";
12
+ import { DeltaSender, type SeatedSocket } from "./delta.js";
13
+ import { MAX_CLOSE_REASON, readFrame, refuse } from "./frames.js";
14
+ import { NAME_HEADER, PLAYER_HEADER, ROOM_HEADER, type RoomNamespace } from "./gateway.js";
15
+ import { RateLimiter } from "./limiter.js";
16
+ import { SignalSender, type Signal } from "./signals.js";
17
+ import { Tracker } from "./tracked.js";
18
+ import { RoomStorage, type OutboxEntry } from "./storage.js";
19
+
20
+ /** Thrown by a hook to refuse a command, a join or a leave. The reason is sent to the client. */
21
+ export class Rejection extends Error {
22
+ /** Sent to the client as the reason. */
23
+ readonly reason: string;
24
+
25
+ constructor(reason: string) {
26
+ super(reason);
27
+ this.name = "Rejection";
28
+ this.reason = reason;
29
+ }
30
+ }
31
+
32
+ /** What `act` reports: the hook's changes were committed, or it was refused and why. */
33
+ export type ActOutcome =
34
+ | {
35
+ /** The hook's changes were committed and sent. */
36
+ ok: true;
37
+ }
38
+ | {
39
+ /** The hook was refused: nothing it did was kept. */
40
+ ok: false;
41
+ /** What it passed to `reject()`, or `internal_error` if it threw. */
42
+ reason: string;
43
+ };
44
+
45
+ /** What one room or matchmaker asks of another over RPC. @internal */
46
+ export type RoomCall =
47
+ | { op: "arrive"; roomId: string; playerId: string; carry: unknown }
48
+ | { op: "signal"; from: string | null; data: unknown }
49
+ | { op: "reserve"; roomId: string; players: string[]; teams?: string[][] };
50
+
51
+ /** Refuse what the current hook was asked to do. Everything the hook changed is rolled back. */
52
+ export function reject(reason: string): never {
53
+ throw new Rejection(reason);
54
+ }
55
+
56
+ type Outcome = { ok: true } | { ok: false; reason: string };
57
+
58
+ /** Everything a hook may change, as JSON. A hook that fails is rolled back to this. */
59
+ interface Committed {
60
+ state: string;
61
+ roster: string;
62
+ timers: string;
63
+ }
64
+
65
+ const SOCKET_OPEN = 1;
66
+
67
+ /** Marks the socket of a client that asked for patches in binary. No player's id starts with a control character. */
68
+ const BINARY_TAG = "\u0001patches=b1";
69
+ /** Marks the socket of a client that speaks version 2 of the protocol: it knows array patches. */
70
+ const V2_TAG = "\u0001v=2";
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
+ const V3_TAG = "\u0001v=3";
73
+ const isMark = (tag: string) => tag.charCodeAt(0) === 1;
74
+
75
+ /** What a socket's tags say: whose it is, and what its client asked for. */
76
+ interface SocketInfo {
77
+ id: string | undefined;
78
+ /** Whether it has any tag besides the player's id. */
79
+ marked: boolean;
80
+ binary: boolean;
81
+ arrays: boolean;
82
+ /** Version 3: presence as changes. */
83
+ presence: boolean;
84
+ }
85
+ /**
86
+ * In a room with more than `PRESENCE_CROWD` connections, the least time
87
+ * between two tellings of who is here, in milliseconds. What changes sooner
88
+ * than that after the last is told together when it is up: a hundred players
89
+ * who arrive or drop in the same moment are one frame to everyone, not a
90
+ * hundred. In a smaller room every change is told at once.
91
+ */
92
+ const PRESENCE_GAP_MS = 100;
93
+ const PRESENCE_CROWD = 64;
94
+ /** Prefix of every timer name the kernel keeps for itself. */
95
+ const KERNEL_TIMER = "tickflare:";
96
+ /** Prefix of the kernel's own timers, which give up the seats of players who stay away. */
97
+ const AWAY_TIMER = "tickflare:away:";
98
+ /** Set by `deleteRoom()`: when it fires, the room deletes everything it stored. */
99
+ const DELETE_TIMER = "tickflare:delete";
100
+ /** A room that still owes a delivery puts its deletion off by this much, and tries the delivery again. */
101
+ const DELETE_RETRY_MS = 30_000;
102
+ /**
103
+ * While the simulation runs, the room keeps an alarm this far ahead of
104
+ * itself, and sets it again each time it fires.
105
+ *
106
+ * Cloudflare takes an object that has had no incoming event for 70 to 140
107
+ * seconds out of memory, simulation and all. A keepalive does not count:
108
+ * Cloudflare answers it without waking the room. A pending `setInterval`
109
+ * holds the object for at most 15 minutes. So without this, a match in which
110
+ * nobody sends a command would stop, and stay stopped until someone did. An
111
+ * alarm is an event, and when Cloudflare restarts the room for any other
112
+ * reason, it is also what brings the simulation back.
113
+ *
114
+ * Each firing costs a row written and a request. The deadline is kept in
115
+ * memory, not with the timers, so setting it again writes nothing else.
116
+ */
117
+ const AWAKE_MS = 30_000;
118
+ /** Where earlier versions kept the deadline, with the timers. A room saved by one may still have it. */
119
+ const AWAKE_TIMER = "tickflare:awake";
120
+ /** How long a room that is being deleted waits for deferred work that is still running. */
121
+ const DELETE_PATIENCE_MS = 10_000;
122
+ /**
123
+ * How long a room keeps sending a player on to the room it handed them to,
124
+ * counted from the moment it first told them. Long enough for a client whose
125
+ * connection dropped just then to come back and be told again.
126
+ */
127
+ const FORWARD_GRACE_MS = 30_000;
128
+ /** Consecutive failed ticks after which the simulation pauses until the next event. */
129
+ const MAX_FAILED_TICKS = 5;
130
+
131
+ /**
132
+ * An authoritative game room: one Durable Object per room.
133
+ *
134
+ * Event mode (the default) has no tick loop. The room wakes when a player
135
+ * connects, sends a command, drops or leaves, or when a timer fires. It runs
136
+ * the matching hook, saves what changed and sends each connected player their
137
+ * view of the state. Between events it hibernates while the WebSockets stay
138
+ * open, and rebuilds itself from storage on the next event.
139
+ *
140
+ * State sync adds a simulation: set `tickRate` and the room calls `onTick`
141
+ * that many times a second while players are connected, sending each player
142
+ * only what changed in their view since the previous tick.
143
+ *
144
+ * Hooks are synchronous and change `this.state` in place. The state must be
145
+ * JSON-serializable. A hook that calls `reject()` or throws leaves no trace:
146
+ * state, seats and timers go back to what they were.
147
+ */
148
+ export abstract class Room<State, Command = unknown, Env = Cloudflare.Env> extends DurableObject<Env> {
149
+ /** How many distinct players may hold a seat at once. */
150
+ protected maxPlayers = Number.POSITIVE_INFINITY;
151
+
152
+ /** Longest client frame accepted, in characters. */
153
+ protected maxMessageLength = 16 * 1024;
154
+
155
+ /**
156
+ * How long a disconnected player keeps their seat, in milliseconds. When it
157
+ * runs out, `onLeave` is called and the seat is given up, as if the player
158
+ * had left; a later connection from them is a new join. The default,
159
+ * `Infinity`, keeps seats until the player leaves or is removed, which is
160
+ * what a game played over days wants. A real-time room should set it, or
161
+ * closed tabs fill the room for good.
162
+ */
163
+ protected seatTimeoutMs = Number.POSITIVE_INFINITY;
164
+
165
+ /**
166
+ * How many frames a second one player may send, and also how many they may
167
+ * send in a single burst. Frames over the limit are refused with
168
+ * `rate_limited` and never reach `parseCommand`. `Infinity` turns it off.
169
+ */
170
+ protected maxCommandsPerSecond = 30;
171
+
172
+ /**
173
+ * Where `finishMatch` announces a finished match. Set it to a Queue binding:
174
+ * `protected override matchQueue = this.env.MATCHES;`
175
+ */
176
+ protected matchQueue: Queue<MatchResult> | undefined;
177
+
178
+ /**
179
+ * Where `finishMatch` stores the replay it is given, if any. Set it to an R2
180
+ * binding: `protected override matchBucket = this.env.REPLAYS;`
181
+ */
182
+ protected matchBucket: R2Bucket | undefined;
183
+
184
+ /**
185
+ * Where the other rooms are, for `movePlayer` and `signal`: the Durable
186
+ * Object namespace they live in, usually this room's own.
187
+ * `protected override rooms = this.env.ROOMS;`
188
+ */
189
+ protected rooms: RoomNamespace | undefined;
190
+
191
+ /** Simulation rate in ticks per second. 0, the default, is event mode: no tick loop. */
192
+ protected tickRate = 0;
193
+
194
+ /**
195
+ * While the room is ticking, how often the state is written to storage, in
196
+ * milliseconds. It is also written whenever the simulation stops. A room
197
+ * that is torn down mid-simulation (a deploy, a crash) resumes from the
198
+ * last write.
199
+ */
200
+ protected saveIntervalMs = 5_000;
201
+
202
+ /**
203
+ * While the room is ticking, how long a connection may send nothing, not
204
+ * a command and not a keepalive, before it is taken for dead and closed
205
+ * with `CloseCode.Silent`. The player is then away, as after any other
206
+ * drop: `onDisconnect` runs and their seat timeout starts.
207
+ *
208
+ * A room ticks for as long as someone is connected, and is billed for it.
209
+ * A connection whose other end is gone without the room being told would
210
+ * keep it awake for nobody, and this is what ends that. Tickflare's
211
+ * clients send a keepalive every 25 seconds, so the default of two
212
+ * minutes never closes one that is there; a client of your own has to
213
+ * send `ping` at least this often. 0 never closes a connection for
214
+ * silence. A room that is not ticking never does either: it is asleep.
215
+ */
216
+ protected silentAfterMs = 120_000;
217
+
218
+ /**
219
+ * Whether the kernel follows what each hook writes to the state, rather
220
+ * than turning the whole state into JSON after every hook to see what
221
+ * changed and to be able to undo it. On by default: a hook then costs what
222
+ * it touches, not what the state weighs.
223
+ *
224
+ * It means that inside a hook other than `onTick`, `this.state` and
225
+ * everything reached through it are proxies of the state's objects. They
226
+ * read and write like the objects themselves, with two exceptions: a proxy
227
+ * is not `===` to an object that did not come from the state, and
228
+ * `structuredClone` refuses one. `plain(value)` gives the object underneath
229
+ * for those. Reach the state through `this.state` in every hook, rather
230
+ * than through a reference kept from an earlier one: a change made through
231
+ * such a reference is not seen until the next tick or save, and is not
232
+ * undone if the hook is refused.
233
+ *
234
+ * Set to false to have every hook work on the plain state, at the old cost.
235
+ */
236
+ protected trackChanges = true;
237
+
238
+ /**
239
+ * The authoritative state. Change it only inside hooks, through
240
+ * `this.state`: see `trackChanges` for what a hook is handed.
241
+ */
242
+ protected get state(): State {
243
+ return this.#tracker.active ? this.#tracker.wrap(this.#state) : this.#state;
244
+ }
245
+
246
+ /** Replaces the whole state. Like any other change, only inside hooks. */
247
+ protected set state(value: State) {
248
+ if (!this.#tracker.active) {
249
+ this.#state = value;
250
+ return;
251
+ }
252
+ const before = this.#state;
253
+ this.#tracker.note(() => {
254
+ this.#state = before;
255
+ });
256
+ this.#state = this.#tracker.clean(value);
257
+ }
258
+
259
+ /** The state itself: plain objects, never proxies. */
260
+ #state!: State;
261
+ #tracker = new Tracker();
262
+ /**
263
+ * The state has changed since `#committed.state` was written. Happens while
264
+ * ticking, when a tracked hook changes the state and nothing needs its JSON
265
+ * yet. Whatever does need it calls `#snapshot` first.
266
+ */
267
+ #stale = false;
268
+
269
+ #loaded = false;
270
+ /** The room's database. Set by `#load`. */
271
+ #store!: RoomStorage;
272
+ #seq = 0;
273
+ #roster: string[] = [];
274
+ /** Timer name to the time it fires, in epoch milliseconds. */
275
+ #timers = new Map<string, number>();
276
+ #committed: Committed = { state: "", roster: "[]", timers: "[]" };
277
+ /** Seats given up during this event. Their sockets are closed once the event is over. */
278
+ #removed: { id: string; reason: string }[] = [];
279
+ /** The timers changed, so the object's alarm has to be moved before the event ends. */
280
+ #alarmStale = false;
281
+
282
+ /** The id this room is known by. Learned from the gateway or from `reserve`. */
283
+ #roomId: string | null = null;
284
+ /** If set, only these players may take a seat. Set by a matchmaker through `reserve`. */
285
+ #invited: string[] | null = null;
286
+ /** The sides a matchmaker split the invited players into, if it did. */
287
+ #teams: string[][] | null = null;
288
+ /** Players the current hook is handing to another room, not yet committed. */
289
+ #moved: { player: string; to: string; carry: unknown }[] = [];
290
+ /** Messages for other rooms sent by the current hook, not yet committed. */
291
+ #signals: Signal[] = [];
292
+ /** Messages for players, as frames, waiting for the end of the event. `to` null is everyone. */
293
+ #mail: { to: string | null; frame: string }[] = [];
294
+ /** While ticking: the commands each socket has had applied and not yet been told about. */
295
+ #owed = new Map<WebSocket, number[]>();
296
+ /** The command being handled, and who sent it. */
297
+ #answering: { ws: WebSocket; id: number } | undefined;
298
+ /** Work for after the event, from `defer`. */
299
+ #deferred: (() => unknown)[] = [];
300
+ /** Deferred tasks that have started and not finished. */
301
+ #working = new Set<Promise<unknown>>();
302
+ /** Messages for other rooms that are committed and waiting to go out. */
303
+ #outgoing = new SignalSender();
304
+ #flushing = false;
305
+ /** Seats changed in a way the remaining players have not been told about yet. */
306
+ #presenceStale = false;
307
+ /** When each connection last sent a frame, while this instance has been in memory. */
308
+ #heard = new WeakMap<WebSocket, number>();
309
+ /** Since when this instance has been in memory: what it knows of no connection's silence before. */
310
+ readonly #since = Date.now();
311
+ /** When connections are next looked at for silence. */
312
+ #sweepAt = 0;
313
+ /** While the simulation should be running: when the alarm that keeps it going next fires. See `AWAKE_MS`. */
314
+ #awakeAt: number | undefined;
315
+ /**
316
+ * The players as they were last told to everyone, by id. Clients that are
317
+ * told changes hold this list. Unknown after a restart, until the next
318
+ * time the whole list goes out.
319
+ */
320
+ #told: Map<string, Player> | undefined;
321
+ /** When who is here was last told to everyone. */
322
+ #toldAt = 0;
323
+ /** Set while a telling is put off until `PRESENCE_GAP_MS` after the last. */
324
+ #tellLater: ReturnType<typeof setTimeout> | undefined;
325
+ /**
326
+ * The connections welcomed since the last telling. Each holds the list as
327
+ * it was when it connected, which is not what `#told` says.
328
+ */
329
+ #welcomed = new Set<WebSocket>();
330
+ /** Finished matches announced by the current hook, not yet committed. */
331
+ #finished: { message: MatchResult; replay?: string }[] = [];
332
+ /** There are finished matches or handovers in storage that still have to be delivered. */
333
+ #outboxPending = false;
334
+ /** The current hook asked for its changes to be written at once. */
335
+ #saveAsked = false;
336
+ /** The player whose join or reconnect hook is running. Their socket is not accepted yet. */
337
+ #connecting: string | null = null;
338
+ /** A hook has returned a promise, so the state may be changed behind the kernel's back. */
339
+ #suspect = false;
340
+ /** `onHttp` calls that have not returned yet. They may not change the state either. */
341
+ #reading = 0;
342
+
343
+ /** Holds each player to `maxCommandsPerSecond`. */
344
+ #limiter = new RateLimiter();
345
+
346
+ /** Ticks run since the room was created. */
347
+ #tick = 0;
348
+ /** Set while the simulation is running. */
349
+ #loop: ReturnType<typeof setInterval> | undefined;
350
+ /** The committed state is newer than what is in storage. Only happens while ticking. */
351
+ #unsaved = false;
352
+ #ticksSinceSave = 0;
353
+ #failedTicks = 0;
354
+ /** onTick kept failing, so the loop stays off until something else happens. */
355
+ #stalled = false;
356
+ /** Knows what each socket holds, to send it only the difference at the next tick. */
357
+ #deltas = new DeltaSender();
358
+
359
+ constructor(ctx: DurableObjectState, env: Env) {
360
+ super(ctx, env);
361
+ // Keepalives are answered by the runtime, so they never wake the room.
362
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
363
+ }
364
+
365
+ /** The state of a brand new room. */
366
+ protected abstract initialState(): State;
367
+
368
+ /**
369
+ * Turn an untrusted client payload into a command. Check everything here:
370
+ * `raw` is whatever the client sent. Throwing refuses the command.
371
+ */
372
+ protected abstract parseCommand(raw: unknown): Command;
373
+
374
+ /** Apply a command. Call `reject()` to refuse it. */
375
+ protected abstract onCommand(player: Player, command: Command): void;
376
+
377
+ /** A player takes a seat for the first time. Call `reject()` to turn them away. */
378
+ protected onJoin(_player: Player): void {}
379
+
380
+ /** A seated player's last connection closed. They keep their seat. */
381
+ protected onDisconnect(_player: Player): void {}
382
+
383
+ /** A seated player connected again after being fully disconnected. */
384
+ protected onReconnect(_player: Player): void {}
385
+
386
+ /**
387
+ * A player is giving up their seat: they asked to leave, or they stayed
388
+ * disconnected for longer than `seatTimeoutMs`. Tidy up after them here;
389
+ * they are removed when this returns. Call `reject()` to make them stay.
390
+ */
391
+ protected onLeave(_player: Player): void {}
392
+
393
+ /**
394
+ * The last seat was given up: nobody is in the room any more, whichever way
395
+ * they went (they left, stayed away too long, were removed, or moved to
396
+ * another room). `this.players` is empty. Nothing ends a room by itself, so
397
+ * this is where to say what becomes of it: `deleteRoom()`, a timer that
398
+ * deletes it unless somebody comes back, or nothing, for a room that waits
399
+ * for its next players. Not called for a room nobody ever sat in.
400
+ *
401
+ * It runs as a hook of its own, straight after the one that emptied the
402
+ * room. If it fails it alone is undone: the players are still gone.
403
+ */
404
+ protected onEmpty(): void {}
405
+
406
+ /** A timer set with `setTimer(name, ...)` ran out. */
407
+ protected onTimer(_name: string): void {}
408
+
409
+ /**
410
+ * Advance the simulation by one step of `dt` seconds (always `1 / tickRate`).
411
+ * Runs `tickRate` times a second while the room is ticking.
412
+ */
413
+ protected onTick(_dt: number): void {}
414
+
415
+ /**
416
+ * Whether the simulation should be running. Checked after every event and
417
+ * every tick, so base it on the state, e.g. `this.state.phase === "playing"`.
418
+ * While it returns false the room behaves as in event mode and can
419
+ * hibernate. The room does not tick while nobody is connected, unless
420
+ * `ticksWhileEmpty()` says so.
421
+ */
422
+ protected shouldTick(): boolean {
423
+ return true;
424
+ }
425
+
426
+ /**
427
+ * Whether the simulation keeps running while nobody is connected, for a
428
+ * match that has to reach its end whoever is watching. `shouldTick()` has
429
+ * to agree. Checked like `shouldTick()`, so base it on the state.
430
+ *
431
+ * Give such a room an end. It is awake, and billed, for every second it
432
+ * ticks, and nobody is there to notice one that never stops: have `onTick`
433
+ * finish or delete the room when the match is over or has run too long.
434
+ * After a deploy or a crash it carries on from its last save within
435
+ * twenty seconds.
436
+ */
437
+ protected ticksWhileEmpty(): boolean {
438
+ return false;
439
+ }
440
+
441
+ /**
442
+ * A plain HTTP request for this room, sent to `{prefix}/{roomId}/...` and
443
+ * already authenticated by the gateway. For reading from the room, e.g. a
444
+ * replay or a scoreboard: changes made to the state here are not saved or
445
+ * sent to anyone.
446
+ */
447
+ protected onHttp(_request: Request, _player: Player): Response | Promise<Response> {
448
+ return new Response("Not found", { status: 404 });
449
+ }
450
+
451
+ /** What `player` is allowed to see. Defaults to the whole state. */
452
+ protected view(_player: Player): unknown {
453
+ return this.state;
454
+ }
455
+
456
+ /** Everyone with a seat, in join order. */
457
+ protected get players(): Player[] {
458
+ // One pass over the sockets, not one per player: a join tells everyone this list.
459
+ const connected = this.#connectedIds();
460
+ return this.#roster.map((id) => ({ id, connected: id === this.#connecting || connected.has(id) }));
461
+ }
462
+
463
+ /** Number of state changes so far. */
464
+ protected get seq(): number {
465
+ return this.#seq;
466
+ }
467
+
468
+ /** Number of ticks run so far. */
469
+ protected get tick(): number {
470
+ return this.#tick;
471
+ }
472
+
473
+ /** The id this room is reached under, once someone has connected through the gateway. */
474
+ protected get roomId(): string | null {
475
+ return this.#roomId;
476
+ }
477
+
478
+ /**
479
+ * The players a matchmaker reserved this room for, or null if it was not
480
+ * reserved. Only they can take a seat (players handed over from another
481
+ * room aside), so a match can start once all of them have joined.
482
+ */
483
+ protected get invited(): readonly string[] | null {
484
+ return this.#invited;
485
+ }
486
+
487
+ /**
488
+ * The sides the matchmaker split the invited players into, each a list of
489
+ * player ids, or null if it did not: see `Matchmaker.teams`.
490
+ */
491
+ protected get teams(): readonly (readonly string[])[] | null {
492
+ return this.#teams;
493
+ }
494
+
495
+ /**
496
+ * Have what the current hook changes written to storage as soon as the hook
497
+ * returns, instead of at the next save interval. Only matters while the
498
+ * room is ticking; outside the simulation every change is written at once.
499
+ * Use it when the hook also writes to the room's database itself, so the
500
+ * two cannot come apart. Call from inside a hook.
501
+ */
502
+ protected saveNow(): void {
503
+ this.#saveAsked = true;
504
+ }
505
+
506
+ /**
507
+ * Announce that a match is over. `result` is yours to define (winner,
508
+ * scores, ...). It is put on `matchQueue` together with the room id and the
509
+ * players, for a queue consumer such as `recordMatches` to store. Pass a
510
+ * `replay` to have it written to `matchBucket` first; the message then
511
+ * carries its key. Call from inside a hook.
512
+ *
513
+ * The announcement is saved with the room and sent after the hook has
514
+ * committed. If sending fails it is tried again on the room's next event.
515
+ */
516
+ protected finishMatch(result: Record<string, unknown> = {}, replay?: unknown): void {
517
+ if (!this.matchQueue) throw new TypeError("finishMatch() needs matchQueue to be set");
518
+ const message: MatchResult = {
519
+ id: crypto.randomUUID(),
520
+ room: this.#roomId,
521
+ endedAt: Date.now(),
522
+ players: [...this.#roster],
523
+ result,
524
+ };
525
+ if (replay !== undefined && this.matchBucket) {
526
+ message.replayKey = `replays/${message.id}.json`;
527
+ this.#finished.push({ message, replay: JSON.stringify(replay) });
528
+ } else {
529
+ this.#finished.push({ message });
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Hand a player over to another room, for worlds that are split across
535
+ * rooms. Their seat here is given up; once the other room has accepted
536
+ * them, their connection is closed with `CloseCode.Moved` and the client
537
+ * reconnects there by itself. `carry` (JSON) is delivered to the other
538
+ * room's `onArrive`: put in it whatever the player takes along. Remove
539
+ * their part of this room's state yourself. Call from inside a hook, and
540
+ * set `rooms`.
541
+ *
542
+ * A player who is not connected at that moment is sent on when they next
543
+ * connect here.
544
+ */
545
+ protected movePlayer(playerId: string, toRoomId: string, carry?: unknown): void {
546
+ if (!this.roomsFor(toRoomId) && this.handOver === Room.prototype.handOver) {
547
+ throw new TypeError("movePlayer() needs `rooms` to be set");
548
+ }
549
+ const seat = this.#roster.indexOf(playerId);
550
+ if (seat === -1) return;
551
+ this.#roster.splice(seat, 1);
552
+ this.#timers.delete(AWAY_TIMER + playerId);
553
+ this.#moved.push({ player: playerId, to: toRoomId, carry: carry ?? null });
554
+ }
555
+
556
+ /**
557
+ * Deliver a player to another room, through `roomsFor`. If it throws, the
558
+ * handover is tried again on this room's next event.
559
+ */
560
+ protected async handOver(roomId: string, playerId: string, carry: unknown): Promise<void> {
561
+ await this.#roomStub(roomId).tickflare({ op: "arrive", roomId, playerId, carry });
562
+ }
563
+
564
+ /**
565
+ * A player handed over by another room takes their seat. `carry` is what
566
+ * that room passed to `movePlayer`. Defaults to treating them as a new
567
+ * player.
568
+ */
569
+ protected onArrive(player: Player, _carry: unknown): void {
570
+ this.onJoin(player);
571
+ }
572
+
573
+ async #arrive(roomId: string, playerId: string, carry: unknown): Promise<void> {
574
+ this.#load();
575
+ this.#learnRoomId(roomId);
576
+ this.#store.atomically(() => {
577
+ this.#store.putArrival(playerId, carry);
578
+ // They are coming back, so stop sending them to where they went.
579
+ this.#store.removeForward(playerId);
580
+ });
581
+ await this.#finish();
582
+ }
583
+
584
+ /**
585
+ * Send a message to one player, outside the state: an event they should
586
+ * hear about once ("you were hit", a result with more in it than an ack),
587
+ * or a stream you keep in step yourself. The client receives it in
588
+ * `onMessage`.
589
+ *
590
+ * Messages go out when the event that sent them is over, in the order they
591
+ * were sent: after the state frame that event caused, or in a ticking room
592
+ * after the tick's patch. A message sent while handling a command can so
593
+ * arrive before the next tick shows the command's effect. A message to a
594
+ * player who is not connected is dropped, and so is everything a hook sent
595
+ * if that hook is refused. Unlike the state, nothing is sent again on
596
+ * reconnect: send what a returning player needs from `onReconnect`.
597
+ */
598
+ protected send(playerId: string, message: unknown): void {
599
+ this.#mail.push({ to: playerId, frame: messageFrame(message) });
600
+ }
601
+
602
+ /** `send` to every player who is connected. */
603
+ protected broadcast(message: unknown): void {
604
+ this.#mail.push({ to: null, frame: messageFrame(message) });
605
+ }
606
+
607
+ /**
608
+ * Run `task` once this event is over, outside the hook: for talking to the
609
+ * world, which hooks cannot do because they are synchronous. Writing to
610
+ * D1, calling another Durable Object, `fetch`. Dropped if the hook is
611
+ * refused. Not awaited by anything and not retried: failures are logged.
612
+ * To change the state with what comes back, use `act`; to be sure it gets
613
+ * done across restarts, keep what is owed in the state and a timer that
614
+ * tries again.
615
+ */
616
+ protected defer(task: () => unknown): void {
617
+ this.#deferred.push(task);
618
+ }
619
+
620
+ /**
621
+ * Run `hook` like any other hook, from code that is not one: the end of a
622
+ * deferred task, a promise that resolved, an RPC method of your own. Its
623
+ * changes are committed and sent, or all taken back if it throws or calls
624
+ * `reject()`, which is what the returned outcome reports.
625
+ */
626
+ protected async act(hook: () => void): Promise<ActOutcome> {
627
+ this.#load();
628
+ const outcome = this.#apply(hook);
629
+ await this.#finish();
630
+ return outcome;
631
+ }
632
+
633
+ /**
634
+ * Send a message to another room, which receives it in `onSignal`. It goes
635
+ * out once after this hook has committed. It is not saved and not retried:
636
+ * use it for things that are replaced by the next one anyway, such as a
637
+ * snapshot of what is near a border. Call from inside a hook, and set
638
+ * `rooms`.
639
+ *
640
+ * With `onlyIfWatched`, a room that reports nobody connected is left alone
641
+ * for two seconds at a time, so an empty neighbour is not kept awake.
642
+ */
643
+ protected signal(roomId: string, data: unknown, options: { onlyIfWatched?: boolean } = {}): void {
644
+ if (!this.roomsFor(roomId) && this.relay === Room.prototype.relay) {
645
+ throw new TypeError("signal() needs `rooms` to be set");
646
+ }
647
+ // A signal goes out after the hook, so it takes a copy: what it was given may be part of the state.
648
+ const copy: unknown = this.#tracker.active ? JSON.parse(JSON.stringify(data ?? null)) : (data ?? null);
649
+ this.#signals.push({ to: roomId, data: copy, onlyIfWatched: options.onlyIfWatched === true });
650
+ }
651
+
652
+ /**
653
+ * Deliver a signal to another room, through `roomsFor`, resolving to
654
+ * whether anyone is connected there.
655
+ */
656
+ protected async relay(roomId: string, data: unknown): Promise<boolean> {
657
+ const watched = await this.#roomStub(roomId).tickflare({ op: "signal", from: this.roomId, data });
658
+ return watched === true;
659
+ }
660
+
661
+ /** Another room sent this one a message with `signal`. */
662
+ protected onSignal(_fromRoomId: string, _data: unknown): void {}
663
+
664
+ /**
665
+ * How rooms and matchmakers reach each other over RPC: handing a player
666
+ * over, delivering a signal, reserving a room for a match. Reserved for
667
+ * Tickflare: don't call it, and don't name a method of your own `tickflare`.
668
+ * @internal
669
+ */
670
+ async tickflare(call: RoomCall): Promise<unknown> {
671
+ switch (call.op) {
672
+ case "arrive":
673
+ return this.#arrive(call.roomId, call.playerId, call.carry);
674
+ case "signal":
675
+ return this.#hear(call.from ?? "", call.data);
676
+ case "reserve":
677
+ return this.#reserve(call.roomId, call.players, call.teams);
678
+ }
679
+ }
680
+
681
+ /**
682
+ * The namespace the room called `roomId` lives in. Defaults to `rooms`.
683
+ * Override it when handovers and signals go to rooms of more than one
684
+ * class, e.g. by the id's prefix.
685
+ */
686
+ protected roomsFor(_roomId: string): RoomNamespace | undefined {
687
+ return this.rooms;
688
+ }
689
+
690
+ #roomStub(roomId: string): { tickflare(call: RoomCall): Promise<unknown> } {
691
+ const rooms = this.roomsFor(roomId);
692
+ if (!rooms) throw new TypeError("reaching another room needs `rooms` to be set");
693
+ return rooms.get(rooms.idFromName(roomId)) as unknown as { tickflare(call: RoomCall): Promise<unknown> };
694
+ }
695
+
696
+ async #hear(fromRoomId: string, data: unknown): Promise<boolean> {
697
+ this.#load();
698
+ this.#apply(() => this.onSignal(fromRoomId, data));
699
+ await this.#finish();
700
+ return this.#anySeated();
701
+ }
702
+
703
+ /**
704
+ * A matchmaker is about to send a match's players here: the room is created
705
+ * where the matchmaker asked for it and closed to everyone but `playerIds`.
706
+ */
707
+ async #reserve(roomId: string, playerIds: string[], teams?: string[][]): Promise<void> {
708
+ this.#load();
709
+ this.#learnRoomId(roomId);
710
+ this.#invited = [...playerIds];
711
+ this.#store.setMeta("invited", JSON.stringify(playerIds));
712
+ if (teams) {
713
+ this.#teams = teams.map((team) => [...team]);
714
+ this.#store.setMeta("teams", JSON.stringify(teams));
715
+ }
716
+ await this.#finish();
717
+ }
718
+
719
+ /**
720
+ * Run `onTimer(name)` once, `delayMs` from now. A timer with the same name
721
+ * is replaced. Returns the time it fires in epoch milliseconds, which you
722
+ * can put in the state to show a countdown. Call from inside a hook.
723
+ *
724
+ * Timers are saved with the room, so they survive hibernation and restarts.
725
+ */
726
+ protected setTimer(name: string, delayMs: number): number {
727
+ if (!name) throw new TypeError("A timer needs a name");
728
+ if (name.startsWith(KERNEL_TIMER)) throw new TypeError(`Timer names starting with "${KERNEL_TIMER}" are reserved`);
729
+ if (!Number.isFinite(delayMs) || delayMs < 0) {
730
+ throw new RangeError("delayMs must be a non-negative number");
731
+ }
732
+ const firesAt = Date.now() + Math.ceil(delayMs);
733
+ this.#timers.set(name, firesAt);
734
+ return firesAt;
735
+ }
736
+
737
+ /**
738
+ * End this room for good. Shortly after the current event, everyone still
739
+ * connected is disconnected with `CloseCode.Removed` and the reason
740
+ * `"room_deleted"`, and everything the room stored is deleted: its state,
741
+ * seats and timers, a lockstep recording, and any tables of your own. With
742
+ * nothing stored the Durable Object itself ceases to exist.
743
+ *
744
+ * What the room still owes is delivered first: a finished match's result,
745
+ * a player on their way to another room. Until it is, the room stays.
746
+ * Work passed to `defer()` that is still running is given ten seconds to
747
+ * finish.
748
+ *
749
+ * The room id is not used up. Someone who comes to it later finds a new,
750
+ * empty room. Call from inside a hook.
751
+ */
752
+ protected deleteRoom(): void {
753
+ this.#timers.set(DELETE_TIMER, Date.now());
754
+ }
755
+
756
+ /** Cancel a timer. Does nothing if it is not set. Call from inside a hook. */
757
+ protected clearTimer(name: string): void {
758
+ this.#timers.delete(name);
759
+ }
760
+
761
+ /**
762
+ * Take a player's seat away and close their connection with
763
+ * `CloseCode.Removed` and `reason`. `onLeave` is not called: clean up their
764
+ * part of the state yourself. Call from inside a hook.
765
+ */
766
+ protected removePlayer(playerId: string, reason = "removed"): void {
767
+ const seat = this.#roster.indexOf(playerId);
768
+ if (seat === -1) return;
769
+ this.#roster.splice(seat, 1);
770
+ this.#timers.delete(AWAY_TIMER + playerId);
771
+ this.#removed.push({ id: playerId, reason });
772
+ }
773
+
774
+ /** Durable Object entry point for connections and HTTP requests from the gateway. Tickflare's: override `onHttp` instead. */
775
+ override async fetch(request: Request): Promise<Response> {
776
+ const playerId = request.headers.get(PLAYER_HEADER);
777
+ if (!playerId) {
778
+ return new Response("Missing player identity", { status: 401 });
779
+ }
780
+ this.#load();
781
+ const roomId = request.headers.get(ROOM_HEADER);
782
+ if (roomId) this.#learnRoomId(roomId);
783
+ const name = nameFrom(request);
784
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
785
+ // While onHttp runs, the state is compared with `#committed.state` to see that it left it alone.
786
+ this.#freshen();
787
+ this.#reading += 1;
788
+ try {
789
+ const player: Player = { id: playerId, connected: this.#isConnected(playerId) };
790
+ if (name !== undefined) player.name = name;
791
+ return await this.onHttp(request, player);
792
+ } finally {
793
+ // onHttp is for reading. Whatever it changed is not kept.
794
+ this.#reading -= 1;
795
+ this.#undoDrift();
796
+ await this.#finish();
797
+ }
798
+ }
799
+ const asked = new URL(request.url).searchParams;
800
+ const marks: string[] = [];
801
+ if (asked.get("patches") === BINARY_PATCHES) marks.push(BINARY_TAG);
802
+ if (Number(asked.get("v")) >= 2) marks.push(V2_TAG);
803
+ if (Number(asked.get("v")) >= 3) marks.push(V3_TAG);
804
+ const response = this.#connect(playerId, name, marks);
805
+ await this.#finish();
806
+ return response;
807
+ }
808
+
809
+ /** Durable Object entry point for incoming frames. Tickflare's: override `parseCommand` and `onCommand` instead. */
810
+ override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
811
+ this.#heard.set(ws, Date.now());
812
+ this.#load();
813
+ this.#receive(ws, message);
814
+ await this.#finish();
815
+ }
816
+
817
+ /** Durable Object entry point for closed connections. Tickflare's: override `onDisconnect` instead. */
818
+ override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {
819
+ // Runtimes with a compatibility date before 2026-04-07 need the close echoed back.
820
+ try {
821
+ ws.close(code === 1005 || code === 1006 ? 1000 : code, reason);
822
+ } catch {
823
+ // Already closed.
824
+ }
825
+ this.#load();
826
+ this.#dropped(ws);
827
+ await this.#finish();
828
+ }
829
+
830
+ /** Durable Object entry point for broken connections. Tickflare's: override `onDisconnect` instead. */
831
+ override async webSocketError(ws: WebSocket): Promise<void> {
832
+ this.#load();
833
+ this.#dropped(ws);
834
+ await this.#finish();
835
+ }
836
+
837
+ /** Durable Object entry point for the alarm that drives timers and retries. Tickflare's: override `onTimer` instead. */
838
+ override async alarm(): Promise<void> {
839
+ this.#load();
840
+ // The alarm is always set for the earliest timer, so that one is due even
841
+ // if this clock reads a little early.
842
+ const now = Math.max(Date.now(), this.#nextTimer() ?? 0);
843
+ const due = [...this.#timers]
844
+ .filter(([, firesAt]) => firesAt <= now)
845
+ .sort((a, b) => a[1] - b[1]);
846
+
847
+ let doomed = false;
848
+ for (const [name, firesAt] of due) {
849
+ // A timer that fired earlier in this batch may have cleared or moved this one.
850
+ if (this.#timers.get(name) !== firesAt) continue;
851
+ // Deleting comes last, after everything else that is due and after what is owed has gone out.
852
+ if (name === DELETE_TIMER) {
853
+ doomed = true;
854
+ continue;
855
+ }
856
+ // Spend the timer first, on its own, so a failing hook cannot bring it back.
857
+ this.#apply(() => this.#timers.delete(name));
858
+ if (name.startsWith(AWAY_TIMER)) this.#giveUpSeat(name.slice(AWAY_TIMER.length));
859
+ // Saved at once, even while ticking: the timer is spent, so its effect must not be lost.
860
+ else this.#apply(() => this.onTimer(name), true);
861
+ }
862
+ this.#alarmStale = true;
863
+ await this.#finish();
864
+ if (doomed) await this.#delete();
865
+ }
866
+
867
+ /** `deleteRoom()` was called, and its moment has come. */
868
+ async #delete(): Promise<void> {
869
+ // Deferred work that is under way gets to finish: it may be telling someone that this room is going.
870
+ const patience = scheduler.wait(DELETE_PATIENCE_MS);
871
+ while (this.#working.size > 0) {
872
+ const waited = await Promise.race([Promise.allSettled([...this.#working]).then(() => true), patience.then(() => false)]);
873
+ if (!waited) break;
874
+ }
875
+ if (this.#store.hasOutbox()) {
876
+ // Something is still owed, and `#finish` has just failed to deliver it. Keep the room, and
877
+ // let the next alarm try again.
878
+ this.#apply(() => this.#timers.set(DELETE_TIMER, Date.now() + DELETE_RETRY_MS));
879
+ this.#alarmStale = true;
880
+ await this.#finish();
881
+ return;
882
+ }
883
+ for (const ws of this.ctx.getWebSockets()) {
884
+ try {
885
+ ws.close(CloseCode.Removed, "room_deleted");
886
+ } catch {
887
+ // Already closed.
888
+ }
889
+ }
890
+ await this.ctx.storage.deleteAlarm();
891
+ await this.ctx.storage.deleteAll();
892
+ // Wait until the deletion is on disk. That is also when the close frames above are let out.
893
+ await this.ctx.storage.sync();
894
+ // Whatever this instance still holds in memory describes a room that is gone. Start over:
895
+ // the next event, if one ever comes, finds a new room. Cloudflare logs the reason as an
896
+ // uncaught error, so it says what it is.
897
+ (this.ctx.abort as (reason?: string, options?: { retryAlarm?: boolean }) => void)(
898
+ "deleteRoom(): this room deleted itself and its storage. Not a failure.",
899
+ { retryAlarm: false },
900
+ );
901
+ }
902
+
903
+ #connect(playerId: string, name: string | undefined, marks: string[] = []): Response {
904
+ const pair = new WebSocketPair();
905
+ const client = pair[0];
906
+ const server = pair[1];
907
+ const player: Player = { id: playerId, connected: true };
908
+ if (name !== undefined) player.name = name;
909
+
910
+ if (!this.#roster.includes(playerId)) {
911
+ const arrival = this.#store.arrival(playerId);
912
+ // A player handed over by another room is always let in.
913
+ if (arrival === undefined) {
914
+ const forward = this.#store.forward(playerId);
915
+ if (forward && !forward.delivered) {
916
+ // This room is still handing them over. Hold the connection without a seat:
917
+ // it is closed with `Moved` as soon as the other room has them.
918
+ this.#replaceSockets(playerId);
919
+ this.ctx.acceptWebSocket(server, [playerId]);
920
+ return new Response(null, { status: 101, webSocket: client });
921
+ }
922
+ if (forward && (forward.expires === null || forward.expires > Date.now())) {
923
+ // They were handed over while away, or the news did not reach them. Send them on.
924
+ if (forward.expires === null) this.#store.expireForward(playerId, Date.now() + FORWARD_GRACE_MS);
925
+ return refuse(client, server, CloseCode.Moved, forward.room);
926
+ }
927
+ if (forward) this.#store.removeForward(playerId);
928
+ if (this.#invited && !this.#invited.includes(playerId)) {
929
+ return refuse(client, server, CloseCode.JoinRejected, "not_invited");
930
+ }
931
+ if (this.#roster.length >= this.maxPlayers) {
932
+ return refuse(client, server, CloseCode.RoomFull, "room_full");
933
+ }
934
+ }
935
+ const joined = this.#apply(() => {
936
+ this.#roster.push(playerId);
937
+ this.#connecting = playerId;
938
+ if (arrival !== undefined) {
939
+ this.onArrive(player, JSON.parse(arrival));
940
+ this.#store.removeArrival(playerId);
941
+ } else {
942
+ this.onJoin(player);
943
+ }
944
+ });
945
+ if (!joined.ok) {
946
+ return refuse(client, server, CloseCode.JoinRejected, joined.reason);
947
+ }
948
+ } else if (!this.#isConnected(playerId)) {
949
+ this.#apply(() => {
950
+ this.#timers.delete(AWAY_TIMER + playerId);
951
+ this.#connecting = playerId;
952
+ this.onReconnect(player);
953
+ });
954
+ }
955
+ // A hook may have removed the very player who is connecting.
956
+ if (!this.#roster.includes(playerId)) {
957
+ const reason = this.#removed.find((seat) => seat.id === playerId)?.reason ?? "removed";
958
+ return refuse(client, server, CloseCode.Removed, reason);
959
+ }
960
+
961
+ // One connection per player: the newest wins.
962
+ this.#replaceSockets(playerId);
963
+ // What the client asked for is kept with the socket, where it outlasts the room's sleep.
964
+ this.ctx.acceptWebSocket(server, [playerId, ...marks]);
965
+ this.#heard.set(server, Date.now());
966
+ this.#welcome(server, player, this.#loop !== undefined);
967
+ this.#broadcastPresence(server);
968
+
969
+ return new Response(null, { status: 101, webSocket: client });
970
+ }
971
+
972
+ /** Sends a socket everything from the start: who they are, the players and their whole view. */
973
+ #welcome(ws: WebSocket, player: Player, ticking: boolean): void {
974
+ const welcome = JSON.stringify({
975
+ t: "welcome",
976
+ v: this.#versionOf(ws),
977
+ you: player.id,
978
+ seq: this.#seq,
979
+ tick: this.#tick,
980
+ tickRate: this.tickRate,
981
+ state: this.view(player),
982
+ players: this.players,
983
+ } satisfies ServerMessage);
984
+ ws.send(welcome);
985
+ this.#welcomed.add(ws);
986
+ if (ticking || this.view !== Room.prototype.view) {
987
+ // Remember exactly what this socket has, as a copy the room cannot touch. Outside the
988
+ // simulation and without a custom view there is no need: it has the state as it is saved.
989
+ this.#deltas.remember(ws, (JSON.parse(welcome) as { state: unknown }).state, this.#seq);
990
+ }
991
+ }
992
+
993
+ /** Closes a player's open connections because a newer one is taking over. */
994
+ #replaceSockets(playerId: string): void {
995
+ for (const old of this.ctx.getWebSockets(playerId)) {
996
+ this.#owed.delete(old);
997
+ try {
998
+ // Marked, so that its close is not taken for the player dropping.
999
+ old.serializeAttachment({ replaced: true });
1000
+ old.close(CloseCode.Replaced, "replaced");
1001
+ } catch {
1002
+ // Already closed.
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ #receive(ws: WebSocket, message: string | ArrayBuffer): void {
1008
+ const playerId = this.#playerOf(ws);
1009
+ // A socket whose seat is gone is about to be closed; ignore what it still sends.
1010
+ if (!playerId || !this.#roster.includes(playerId)) return;
1011
+
1012
+ // Every frame counts against the limit, including the ones refused below.
1013
+ const allowed = this.#limiter.spend(playerId, this.maxCommandsPerSecond);
1014
+ if (typeof message !== "string") {
1015
+ return this.#send(ws, { t: "error", reason: allowed ? "binary_not_supported" : "rate_limited" });
1016
+ }
1017
+ if (message.length > this.maxMessageLength) {
1018
+ return this.#send(ws, { t: "error", reason: allowed ? "message_too_large" : "rate_limited" });
1019
+ }
1020
+
1021
+ let parsed: unknown;
1022
+ try {
1023
+ parsed = JSON.parse(message);
1024
+ } catch {
1025
+ return this.#send(ws, { t: "error", reason: allowed ? "invalid_json" : "rate_limited" });
1026
+ }
1027
+ const frame = readFrame(parsed);
1028
+ if (!frame) {
1029
+ return this.#send(ws, { t: "error", reason: allowed ? "invalid_message" : "rate_limited" });
1030
+ }
1031
+ if (!allowed) {
1032
+ // Answered by id, so the client's pending command settles instead of hanging.
1033
+ return this.#send(ws, { t: "reject", id: frame.id, reason: "rate_limited" });
1034
+ }
1035
+
1036
+ const player: Player = { id: playerId, connected: true };
1037
+ let outcome: Outcome;
1038
+ // While the simulation runs, what a command changed is sent with the next tick.
1039
+ const ticking = this.#loop !== undefined;
1040
+ if (frame.t === "leave") {
1041
+ outcome = this.#apply(() => {
1042
+ this.onLeave(player);
1043
+ this.removePlayer(playerId, "left");
1044
+ });
1045
+ // They are going: what they were still waiting to hear is said now.
1046
+ if (outcome.ok) this.#answer(ws);
1047
+ } else {
1048
+ let command: Command;
1049
+ try {
1050
+ command = this.parseCommand(frame.data);
1051
+ } catch (err) {
1052
+ const reason = err instanceof Rejection ? err.reason : "invalid_command";
1053
+ return this.#send(ws, { t: "reject", id: frame.id, reason });
1054
+ }
1055
+ // If this changes what the player sees, the frame that says so says whose command it shows.
1056
+ this.#answering = { ws, id: frame.id };
1057
+ try {
1058
+ outcome = this.#apply(() => this.onCommand(player, command));
1059
+ } finally {
1060
+ this.#answering = undefined;
1061
+ }
1062
+ }
1063
+
1064
+ if (!outcome.ok) {
1065
+ return this.#send(ws, { t: "reject", id: frame.id, reason: outcome.reason });
1066
+ }
1067
+ if (ticking && frame.t === "cmd") {
1068
+ // An ack means "you have seen the result", and the result goes out with the tick.
1069
+ const owed = this.#owed.get(ws);
1070
+ if (owed) owed.push(frame.id);
1071
+ else this.#owed.set(ws, [frame.id]);
1072
+ return;
1073
+ }
1074
+ // The state frame, if any, has already gone out.
1075
+ this.#send(ws, { t: "ack", id: frame.id, seq: this.#seq });
1076
+ }
1077
+
1078
+ /** Acks the commands `ws` is still owed an answer to, or everyone's. */
1079
+ #answer(ws?: WebSocket): void {
1080
+ if (this.#owed.size === 0) return;
1081
+ const owed = ws ? new Map([[ws, this.#owed.get(ws) ?? []]]) : this.#owed;
1082
+ if (ws) this.#owed.delete(ws);
1083
+ else this.#owed = new Map();
1084
+ for (const [to, ids] of owed) {
1085
+ for (const id of ids) this.#send(to, { t: "ack", id, seq: this.#seq, tick: this.#tick });
1086
+ }
1087
+ }
1088
+
1089
+ #dropped(ws: WebSocket, silent = false): void {
1090
+ const playerId = this.#playerOf(ws);
1091
+ // Players who left or were removed are not "disconnected": their seat is gone.
1092
+ if (!playerId || !this.#roster.includes(playerId)) return;
1093
+ // A newer connection for the same player took over: nothing to announce, now or
1094
+ // when this close arrives after the newer connection has itself gone.
1095
+ const mark = ws.deserializeAttachment() as { replaced?: boolean; silent?: boolean } | null;
1096
+ // Or it was closed for its silence, and the player's going was dealt with then.
1097
+ if (mark?.replaced || (mark?.silent && !silent)) return;
1098
+ if (this.#isConnected(playerId, ws)) return;
1099
+
1100
+ this.#apply(() => this.onDisconnect({ id: playerId, connected: false }));
1101
+ this.#apply(() => this.#startSeatTimeout(playerId));
1102
+ this.#broadcastPresence(ws);
1103
+ }
1104
+
1105
+ #startSeatTimeout(playerId: string): void {
1106
+ if (Number.isFinite(this.seatTimeoutMs) && this.#roster.includes(playerId)) {
1107
+ this.#timers.set(AWAY_TIMER + playerId, Date.now() + Math.max(0, this.seatTimeoutMs));
1108
+ }
1109
+ }
1110
+
1111
+ /** A player stayed away for `seatTimeoutMs`: let the game tidy up, then take the seat back. */
1112
+ #giveUpSeat(playerId: string): void {
1113
+ if (!this.#roster.includes(playerId) || this.#isConnected(playerId)) return;
1114
+ this.#apply(() => {
1115
+ this.onLeave({ id: playerId, connected: false });
1116
+ this.removePlayer(playerId, "away");
1117
+ });
1118
+ }
1119
+
1120
+ /**
1121
+ * The end of every event and every tick: close the sockets of removed
1122
+ * players, move the alarm, and start or stop the simulation.
1123
+ */
1124
+ async #finish(afterEvent = true): Promise<void> {
1125
+ // Before anyone removed is disconnected, so they hear why.
1126
+ if (this.#mail.length > 0) this.#deliverMail();
1127
+ if (this.#removed.length > 0 || this.#presenceStale) {
1128
+ this.#presenceStale = false;
1129
+ for (const { id, reason } of this.#removed.splice(0)) {
1130
+ for (const ws of this.ctx.getWebSockets(id)) {
1131
+ try {
1132
+ ws.close(CloseCode.Removed, reason.slice(0, MAX_CLOSE_REASON));
1133
+ } catch {
1134
+ // Already closed.
1135
+ }
1136
+ }
1137
+ }
1138
+ this.#broadcastPresence();
1139
+ }
1140
+
1141
+ this.#stayAwake();
1142
+ if (this.#alarmStale) {
1143
+ this.#alarmStale = false;
1144
+ const next = this.#nextTimer();
1145
+ if (next === undefined) await this.ctx.storage.deleteAlarm();
1146
+ else await this.ctx.storage.setAlarm(next);
1147
+ }
1148
+
1149
+ if (this.#outgoing.pending) await this.#outgoing.send((to, data) => this.relay(to, data));
1150
+ if (this.#outboxPending && !this.#flushing) {
1151
+ // One at a time: an event that arrives while a delivery is under way must not repeat it.
1152
+ // What that event adds to the outbox is picked up by the delivery already running.
1153
+ this.#flushing = true;
1154
+ try {
1155
+ await this.#flushOutbox();
1156
+ } finally {
1157
+ this.#flushing = false;
1158
+ }
1159
+ }
1160
+
1161
+ if (afterEvent) this.#stalled = false;
1162
+ this.#syncLoop();
1163
+
1164
+ for (const task of this.#deferred.splice(0)) {
1165
+ const running = Promise.resolve()
1166
+ .then(task)
1167
+ .catch((err) => console.error("[tickflare] deferred task failed:", err))
1168
+ .finally(() => this.#working.delete(running));
1169
+ this.#working.add(running);
1170
+ this.ctx.waitUntil(running);
1171
+ }
1172
+ }
1173
+
1174
+ /**
1175
+ * Delivers what is waiting in storage. A finished match: replay to R2, then
1176
+ * the message to the queue. A handover: the player to the other room, then
1177
+ * their connection is closed so the client follows.
1178
+ */
1179
+ async #flushOutbox(): Promise<void> {
1180
+ let failed = false;
1181
+ let last = 0;
1182
+ // Read one entry at a time: hooks that commit while a delivery is awaited add to the outbox.
1183
+ for (let next = this.#store.nextInOutbox(last); next; next = this.#store.nextInOutbox(last)) {
1184
+ last = next.id;
1185
+ try {
1186
+ await this.#deliver(next.entry);
1187
+ this.#store.removeFromOutbox(next.id);
1188
+ } catch (err) {
1189
+ // Left in storage; the next event tries again. The entries after it still go out.
1190
+ failed = true;
1191
+ console.error("[tickflare] could not deliver a finished match or a handover:", err);
1192
+ }
1193
+ }
1194
+ // Nothing has been awaited since the last read came back empty, so this cannot hide an entry.
1195
+ this.#outboxPending = failed;
1196
+ }
1197
+
1198
+ async #deliver(entry: OutboxEntry): Promise<void> {
1199
+ if (entry.move) {
1200
+ const { player, to, carry } = entry.move;
1201
+ await this.handOver(to, player, carry);
1202
+ let told = false;
1203
+ for (const ws of this.ctx.getWebSockets(player)) {
1204
+ if (ws.readyState === SOCKET_OPEN) told = true;
1205
+ try {
1206
+ ws.close(CloseCode.Moved, to);
1207
+ } catch {
1208
+ // Already closed.
1209
+ }
1210
+ }
1211
+ // If they were away, they are told when they next connect here.
1212
+ this.#store.deliverForward(player, to, told ? Date.now() + FORWARD_GRACE_MS : null);
1213
+ return;
1214
+ }
1215
+ const { message, replay } = entry;
1216
+ if (replay !== undefined && message.replayKey && this.matchBucket) {
1217
+ await this.matchBucket.put(message.replayKey, replay, {
1218
+ httpMetadata: { contentType: "application/json" },
1219
+ });
1220
+ }
1221
+ await this.matchQueue?.send(message);
1222
+ }
1223
+
1224
+ /** Whether the simulation should be running now. `connected` is whether anybody is. */
1225
+ #wantsTicks(connected: boolean, evenIfStalled = false): boolean {
1226
+ if (this.tickRate <= 0 || (this.#stalled && !evenIfStalled)) return false;
1227
+ try {
1228
+ return this.shouldTick() === true && (connected || this.ticksWhileEmpty() === true);
1229
+ } catch (err) {
1230
+ console.error("[tickflare] shouldTick() or ticksWhileEmpty() failed:", err);
1231
+ return false;
1232
+ }
1233
+ }
1234
+
1235
+ /**
1236
+ * A room whose simulation should be running keeps an alarm `AWAKE_MS`
1237
+ * ahead of itself, with players connected or without: see `AWAKE_MS`. A
1238
+ * simulation that keeps failing is woken too, since every alarm is an event
1239
+ * and lets it try again.
1240
+ */
1241
+ #stayAwake(): void {
1242
+ const wanted = this.#wantsTicks(this.#anySeated(), true);
1243
+ const now = Date.now();
1244
+ if (wanted) {
1245
+ // Set again once it has fired. A clock that reads a little early still counts it as fired.
1246
+ if (this.#awakeAt !== undefined && this.#awakeAt > now + 1_000) return;
1247
+ this.#awakeAt = now + AWAKE_MS;
1248
+ } else {
1249
+ if (this.#awakeAt === undefined) return;
1250
+ this.#awakeAt = undefined;
1251
+ }
1252
+ this.#alarmStale = true;
1253
+ }
1254
+
1255
+ /** Starts the simulation if it should be running and stops it if it should not. */
1256
+ #syncLoop(): void {
1257
+ const wanted = this.#wantsTicks(this.#anySeated());
1258
+ if (wanted && this.#loop === undefined) {
1259
+ this.#loop = setInterval(() => this.#runTick(), 1000 / this.tickRate);
1260
+ } else if (!wanted && this.#loop !== undefined) {
1261
+ clearInterval(this.#loop);
1262
+ this.#loop = undefined;
1263
+ // Send what changed since the last tick, or it would never go out.
1264
+ this.#broadcastTick();
1265
+ if (this.#unsaved) this.#writeRoom();
1266
+ }
1267
+ }
1268
+
1269
+ #runTick(): void {
1270
+ this.#tick += 1;
1271
+ const ticked = this.#apply(() => this.onTick(1 / this.tickRate), false, true);
1272
+ if (ticked.ok) {
1273
+ this.#failedTicks = 0;
1274
+ } else if (++this.#failedTicks >= MAX_FAILED_TICKS) {
1275
+ console.error("[tickflare] onTick keeps failing; the simulation is paused until the next event");
1276
+ this.#failedTicks = 0;
1277
+ this.#stalled = true;
1278
+ }
1279
+
1280
+ const now = Date.now();
1281
+ if (this.silentAfterMs > 0 && now >= this.#sweepAt) {
1282
+ this.#sweepAt = now + Math.min(5_000, this.silentAfterMs / 2);
1283
+ this.#closeSilent(now);
1284
+ }
1285
+
1286
+ if (++this.#ticksSinceSave * 1000 >= this.saveIntervalMs * this.tickRate) {
1287
+ this.#ticksSinceSave = 0;
1288
+ if (this.#unsaved) this.#writeRoom();
1289
+ }
1290
+ this.#broadcastTick();
1291
+ this.#finish(false).catch((err) => console.error("[tickflare] tick cleanup failed:", err));
1292
+ }
1293
+
1294
+ /**
1295
+ * Closes the connections that have sent nothing for `silentAfterMs`. What
1296
+ * counts as sending: a frame, or a keepalive, which Cloudflare answers
1297
+ * without waking the room but remembers the time of.
1298
+ */
1299
+ #closeSilent(now: number): void {
1300
+ for (const ws of this.ctx.getWebSockets()) {
1301
+ if (ws.readyState !== SOCKET_OPEN) continue;
1302
+ const heard = Math.max(
1303
+ this.#since,
1304
+ this.#heard.get(ws) ?? 0,
1305
+ this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0,
1306
+ );
1307
+ if (now - heard <= this.silentAfterMs) continue;
1308
+ try {
1309
+ // Marked: the player drops now, once. If the other end is there after all and answers
1310
+ // the close, that is not a second drop.
1311
+ ws.serializeAttachment({ silent: true });
1312
+ ws.close(CloseCode.Silent, "silent");
1313
+ } catch {
1314
+ // Already closed.
1315
+ }
1316
+ this.#dropped(ws, true);
1317
+ }
1318
+ }
1319
+
1320
+ /** Reads the room from storage the first time an event arrives after a (re)start. */
1321
+ #load(): void {
1322
+ if (this.#loaded) {
1323
+ if (this.#suspect || this.#reading > 0) this.#undoDrift();
1324
+ return;
1325
+ }
1326
+ this.#store = new RoomStorage(this.ctx.storage);
1327
+ this.#store.purgeForwards(Date.now());
1328
+ const room = this.#store.room();
1329
+
1330
+ let state: string;
1331
+ if (room) {
1332
+ state = room.state;
1333
+ } else {
1334
+ state = JSON.stringify(this.initialState());
1335
+ if (state === undefined) {
1336
+ throw new TypeError("initialState() must return a JSON-serializable value");
1337
+ }
1338
+ }
1339
+ const meta = this.#store.meta();
1340
+ // Rooms saved before the counter moved into the room's own row still have it here.
1341
+ this.#tick = Math.max(room?.tick ?? 0, Number(meta.get("tick") ?? 0));
1342
+ this.#roomId = meta.get("room") ?? null;
1343
+ this.#invited = meta.has("invited") ? (JSON.parse(meta.get("invited")!) as string[]) : null;
1344
+ this.#teams = meta.has("teams") ? (JSON.parse(meta.get("teams")!) as string[][]) : null;
1345
+ this.#outboxPending = this.#store.hasOutbox();
1346
+ this.#seq = room?.seq ?? 0;
1347
+ let timers = this.#store.timers();
1348
+ if (timers.some(([name]) => name === AWAKE_TIMER)) {
1349
+ // The deadline lives in memory now. Left with the timers, it would fire for ever.
1350
+ timers = timers.filter(([name]) => name !== AWAKE_TIMER);
1351
+ this.#store.replaceTimers(timers);
1352
+ }
1353
+ this.#committed = {
1354
+ state,
1355
+ roster: room?.roster ?? "[]",
1356
+ timers: JSON.stringify(timers),
1357
+ };
1358
+ // Start from the JSON round-trip, so new and resumed rooms behave the same.
1359
+ this.#restore();
1360
+ this.#loaded = true;
1361
+
1362
+ // A room that comes back with its simulation due and players connected was taken out of
1363
+ // memory while it ran. It resumes from its last save, which is older than what the players
1364
+ // hold, and whatever they were waiting to hear is gone with the old instance. So each of them
1365
+ // starts again from the whole view, as after a reconnect, without having to reconnect.
1366
+ if (this.tickRate > 0) {
1367
+ const sockets = this.#seatedSockets();
1368
+ if (sockets.length > 0 && this.#wantsTicks(true)) {
1369
+ for (const { ws, id } of sockets) {
1370
+ try {
1371
+ this.#welcome(ws, { id, connected: true }, true);
1372
+ } catch (err) {
1373
+ console.error(`[tickflare] could not send the state to ${id}:`, err);
1374
+ }
1375
+ }
1376
+ }
1377
+ }
1378
+
1379
+ // Seats left by players who dropped while no timeout was running for them (the option was
1380
+ // added or shortened since, or the room was torn down mid-event) get one now.
1381
+ const connected = this.#connectedIds();
1382
+ const adrift = this.#roster.filter((id) => !this.#timers.has(AWAY_TIMER + id) && !connected.has(id));
1383
+ if (adrift.length > 0 && Number.isFinite(this.seatTimeoutMs)) {
1384
+ this.#apply(() => adrift.forEach((id) => this.#startSeatTimeout(id)));
1385
+ }
1386
+ }
1387
+
1388
+ /** Puts state, seats and timers back to what was last committed. */
1389
+ #restore(): void {
1390
+ this.#state = JSON.parse(this.#committed.state) as State;
1391
+ this.#stale = false;
1392
+ this.#restoreSeats();
1393
+ }
1394
+
1395
+ /** Puts seats and timers back to what was last committed. */
1396
+ #restoreSeats(): void {
1397
+ this.#roster = JSON.parse(this.#committed.roster) as string[];
1398
+ this.#timers = new Map(JSON.parse(this.#committed.timers) as [string, number][]);
1399
+ }
1400
+
1401
+ /** Brings `#committed.state` up to date with the state. Throws if the state is not JSON. */
1402
+ #snapshot(): void {
1403
+ const state = JSON.stringify(this.#state);
1404
+ if (state === undefined) throw new TypeError("Room state must be JSON-serializable");
1405
+ this.#committed = { ...this.#committed, state };
1406
+ this.#stale = false;
1407
+ }
1408
+
1409
+ /**
1410
+ * `#snapshot`, for where there is no hook to blame. A state that cannot be
1411
+ * turned into JSON got that way through a reference kept from outside a
1412
+ * hook, since what hooks write is checked as it is written. There is no
1413
+ * knowing which change it was, so the state goes back to the last JSON
1414
+ * there is.
1415
+ */
1416
+ #freshen(): void {
1417
+ if (!this.#stale) return;
1418
+ try {
1419
+ this.#snapshot();
1420
+ } catch (err) {
1421
+ console.error("[tickflare] the state can no longer be saved; going back to the last state that could:", err);
1422
+ this.#restore();
1423
+ }
1424
+ }
1425
+
1426
+ /**
1427
+ * Puts the state back if something changed it outside a hook: `onHttp`, or
1428
+ * a hook that returned a promise and carried on after it was refused. Such
1429
+ * a change was never checked, saved or sent, and must not ride along with
1430
+ * the next commit. Comparing costs a pass over the state, so this is only
1431
+ * called where one of the two can have happened.
1432
+ */
1433
+ #undoDrift(): void {
1434
+ let live: string | undefined;
1435
+ try {
1436
+ live = JSON.stringify(this.#state);
1437
+ } catch {
1438
+ // Not even serializable: certainly not what was committed.
1439
+ }
1440
+ if (live === this.#committed.state) return;
1441
+ console.error(
1442
+ "[tickflare] the state was changed outside a hook (in onHttp, or by a hook that returned a promise); the change was discarded",
1443
+ );
1444
+ this.#restore();
1445
+ }
1446
+
1447
+ /** Writes the state as it is now. */
1448
+ #writeRoom(): void {
1449
+ this.#freshen();
1450
+ this.#store.atomically(() => this.#persist(this.#seq, this.#committed));
1451
+ this.#unsaved = false;
1452
+ }
1453
+
1454
+ #persist(seq: number, committed: Committed): void {
1455
+ this.#store.writeRoom({ seq, state: committed.state, roster: committed.roster, tick: this.#tick });
1456
+ }
1457
+
1458
+ /** Remembers the id this room is reached under, the first time it hears it. */
1459
+ #learnRoomId(roomId: string): void {
1460
+ if (this.#roomId === roomId) return;
1461
+ this.#roomId = roomId;
1462
+ this.#store.rememberRoomId(roomId);
1463
+ }
1464
+
1465
+ /**
1466
+ * Runs a hook, then commits what it changed. If the hook fails, everything
1467
+ * it touched is put back and the reason is returned. That includes what it
1468
+ * wrote to the room's database: hook and commit run in one transaction.
1469
+ *
1470
+ * Outside the simulation a commit is saved and broadcast at once. While the
1471
+ * room is ticking, state changes are only kept in memory here: the next tick
1472
+ * sends them and the save interval writes them. The exception is a commit
1473
+ * that also changes something which is always saved at once (seats, timers,
1474
+ * the outbox) or that asks for it (`durable`, `saveNow()`): the state is
1475
+ * written with it, so storage never holds one without the other.
1476
+ *
1477
+ * What the hook did to the state is known in one of two ways. A tracked
1478
+ * hook writes through proxies that note each write: the kernel knows at
1479
+ * once whether anything changed and how to undo it, and turns the state
1480
+ * into JSON only if this commit saves or sends it. Otherwise the whole
1481
+ * state is turned into JSON after the hook and compared with the JSON from
1482
+ * before, which is also what it is put back from. That is how `onTick`
1483
+ * runs (`plainly`), since a simulation reads far more than a proxy should
1484
+ * be asked to pass on, and how every hook runs with `trackChanges` off or
1485
+ * while something may be changing the state behind the kernel's back.
1486
+ */
1487
+ #apply(hook: () => void, durable = false, plainly = false): Outcome {
1488
+ if (this.#suspect || this.#reading > 0) this.#undoDrift();
1489
+ const removedBefore = this.#removed.length;
1490
+ const mailBefore = this.#mail.length;
1491
+ const deferredBefore = this.#deferred.length;
1492
+ this.#finished.length = 0;
1493
+ this.#moved.length = 0;
1494
+ this.#signals.length = 0;
1495
+ this.#saveAsked = false;
1496
+ const ticking = this.#loop !== undefined;
1497
+ const seated = this.#roster.length;
1498
+ const tracked = this.trackChanges && !plainly && !this.#suspect && this.#reading === 0;
1499
+ let committed = false;
1500
+ try {
1501
+ // Comparing needs a "before" that is up to date, and so does putting the state back from it.
1502
+ if (!tracked && this.#stale) this.#snapshot();
1503
+ const was = this.#committed;
1504
+ if (tracked) this.#tracker.begin();
1505
+ const { next, seq, stateChanged, saved, current } = this.#store.atomically(() => {
1506
+ const returned = hook() as unknown;
1507
+ if (isThenable(returned)) {
1508
+ returned.then(undefined, () => {});
1509
+ this.#suspect = true;
1510
+ throw new TypeError("Room hooks must be synchronous");
1511
+ }
1512
+ const roster = JSON.stringify(this.#roster);
1513
+ const timers = JSON.stringify([...this.#timers].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1514
+ // Serialized before anything is written, so a value that cannot be is caught here.
1515
+ const owed = [
1516
+ ...this.#finished.map((finished) => JSON.stringify(finished satisfies OutboxEntry)),
1517
+ ...this.#moved.map((move) => JSON.stringify({ move } satisfies OutboxEntry)),
1518
+ ];
1519
+ const rosterChanged = roster !== was.roster;
1520
+ const timersChanged = timers !== was.timers;
1521
+ // What must never be in storage without the state it belongs to.
1522
+ const anchored = rosterChanged || timersChanged || owed.length > 0 || durable || this.#saveAsked;
1523
+ // Whether a state that is newer than storage is written by this commit.
1524
+ const writes = !ticking || anchored;
1525
+
1526
+ // A tracked hook that wrote nothing changed nothing. One that did, while nothing needs
1527
+ // the state as JSON, is taken at its word, and `#committed.state` falls behind.
1528
+ const touched = !tracked || this.#tracker.changed;
1529
+ let state = was.state;
1530
+ let stateChanged = false;
1531
+ let current = !this.#stale;
1532
+ if (!tracked || ((touched || this.#stale) && writes)) {
1533
+ const json = JSON.stringify(this.#state);
1534
+ if (json === undefined) throw new TypeError("Room state must be JSON-serializable");
1535
+ stateChanged = touched && json !== was.state;
1536
+ state = json;
1537
+ current = true;
1538
+ } else if (touched) {
1539
+ stateChanged = true;
1540
+ current = false;
1541
+ }
1542
+ const next: Committed = { state, roster, timers };
1543
+ const seq = stateChanged ? this.#seq + 1 : this.#seq;
1544
+ const saved = rosterChanged || ((stateChanged || this.#unsaved) && writes);
1545
+
1546
+ if (saved) this.#persist(seq, next);
1547
+ if (timersChanged) this.#store.replaceTimers(this.#timers);
1548
+ for (const body of owed) this.#store.addToOutbox(body);
1549
+ for (const move of this.#moved) this.#store.putForward(move.player, move.to);
1550
+ return { next, seq, stateChanged, saved, current };
1551
+ });
1552
+ this.#tracker.end();
1553
+
1554
+ if (saved) this.#unsaved = false;
1555
+ else if (stateChanged) this.#unsaved = true;
1556
+ if (next.timers !== was.timers) this.#alarmStale = true;
1557
+ if (this.#finished.length > 0 || this.#moved.length > 0) this.#outboxPending = true;
1558
+ if (this.#moved.length > 0) this.#presenceStale = true;
1559
+ this.#finished.length = 0;
1560
+ this.#moved.length = 0;
1561
+ this.#outgoing.add(this.#signals.splice(0));
1562
+
1563
+ this.#seq = seq;
1564
+ this.#committed = next;
1565
+ this.#stale = !current;
1566
+ committed = true;
1567
+ if (stateChanged && !ticking) this.#broadcastState(was.state);
1568
+ // No await between the two commits, so storage holds both or neither.
1569
+ if (seated > 0 && this.#roster.length === 0) this.#apply(() => this.onEmpty());
1570
+ return { ok: true };
1571
+ } catch (err) {
1572
+ if (committed) {
1573
+ // The hook's changes stand. What failed came after them: telling the players.
1574
+ console.error("[tickflare] could not send the state:", err);
1575
+ return { ok: true };
1576
+ }
1577
+ if (this.#tracker.active) {
1578
+ this.#tracker.undo();
1579
+ this.#restoreSeats();
1580
+ } else {
1581
+ this.#restore();
1582
+ }
1583
+ this.#removed.length = removedBefore;
1584
+ this.#mail.length = mailBefore;
1585
+ this.#deferred.length = deferredBefore;
1586
+ this.#finished.length = 0;
1587
+ this.#moved.length = 0;
1588
+ this.#signals.length = 0;
1589
+ // From here on every hook compares against `#committed.state`, so it has to be current.
1590
+ if (this.#suspect) this.#freshen();
1591
+ if (err instanceof Rejection) return { ok: false, reason: err.reason };
1592
+ console.error("[tickflare] room hook failed:", err);
1593
+ if (tracked && (err as { name?: unknown } | null)?.name === "DataCloneError") {
1594
+ console.error(
1595
+ "[tickflare] inside a hook, `this.state` and what is read from it are proxies, which cannot be cloned. Use `plain(value)` from tickflare to get the object itself.",
1596
+ );
1597
+ }
1598
+ return { ok: false, reason: "internal_error" };
1599
+ } finally {
1600
+ this.#connecting = null;
1601
+ }
1602
+ }
1603
+
1604
+ /**
1605
+ * Sends everyone what this change did to their view. Used outside the
1606
+ * simulation, where every change is sent as it is made.
1607
+ *
1608
+ * `before` is the state as JSON as it was before the change. Without a
1609
+ * custom view that is what every seated socket holds, since each was sent
1610
+ * every change so far, so a socket nothing is known about (the room has
1611
+ * slept since, or the socket has just joined) can still be sent a patch.
1612
+ * With a custom view only what was actually sent to a socket will do, and
1613
+ * one that nothing is known about gets its whole view.
1614
+ */
1615
+ #broadcastState(before: string): void {
1616
+ const sockets = this.#seatedSockets();
1617
+ if (sockets.length === 0) return;
1618
+ const custom = this.view !== Room.prototype.view;
1619
+ // Not for a room that is about to simulate again: one that was taken out of memory in the
1620
+ // middle of a simulation saved its state some ticks before its players last heard from it.
1621
+ if (!custom && !this.#deltas.knows(sockets) && !this.#wantsTicks(true)) {
1622
+ this.#deltas.seed(sockets, this.#seq - 1, () => JSON.parse(before) as unknown);
1623
+ }
1624
+ const answering = this.#answering;
1625
+ this.#deltas.send(
1626
+ sockets,
1627
+ this.#seq,
1628
+ this.#tick,
1629
+ this.#state,
1630
+ custom ? (id) => this.view({ id, connected: true }) : undefined,
1631
+ true,
1632
+ answering && new Map([[answering.ws, answering.id]]),
1633
+ );
1634
+ }
1635
+
1636
+ /** Sends everyone what changed in their view since the last tick. */
1637
+ #broadcastTick(): void {
1638
+ const custom = this.view !== Room.prototype.view;
1639
+ // Commands handled since the last tick: this is the state that shows them.
1640
+ let shows: Map<WebSocket, number> | undefined;
1641
+ if (this.#owed.size > 0) {
1642
+ shows = new Map();
1643
+ for (const [ws, ids] of this.#owed) shows.set(ws, ids[ids.length - 1]!);
1644
+ }
1645
+ this.#deltas.send(
1646
+ this.#seatedSockets(),
1647
+ this.#seq,
1648
+ this.#tick,
1649
+ this.#state,
1650
+ custom ? (id) => this.view({ id, connected: true }) : undefined,
1651
+ false,
1652
+ shows,
1653
+ );
1654
+ this.#answer();
1655
+ }
1656
+
1657
+ /** The version of the protocol spoken on this socket: the one its client asked for, or the newest this room knows. */
1658
+ #versionOf(ws: WebSocket): number {
1659
+ const info = this.#socketInfo(ws);
1660
+ return info.presence ? PROTOCOL_VERSION : info.arrays ? 2 : 1;
1661
+ }
1662
+
1663
+ /**
1664
+ * Tells everyone who is here. Clients of version 3 are told what changed
1665
+ * since the last time, the others the whole list: with it, a join in a
1666
+ * room of a thousand is a thousand frames of a thousand players each.
1667
+ */
1668
+ #broadcastPresence(except?: WebSocket): void {
1669
+ const sockets = this.#seatedSockets();
1670
+ const now = Date.now();
1671
+ const wait = this.#toldAt + PRESENCE_GAP_MS - now;
1672
+ if (wait > 0 && sockets.length > PRESENCE_CROWD) {
1673
+ // Told a moment ago. This goes out with whatever else changes until the moment is up.
1674
+ this.#tellLater ??= setTimeout(() => {
1675
+ this.#tellLater = undefined;
1676
+ try {
1677
+ this.#broadcastPresence();
1678
+ } catch (err) {
1679
+ console.error("[tickflare] could not tell the players who is here:", err);
1680
+ }
1681
+ }, wait);
1682
+ return;
1683
+ }
1684
+ if (this.#tellLater !== undefined) {
1685
+ clearTimeout(this.#tellLater);
1686
+ this.#tellLater = undefined;
1687
+ }
1688
+ this.#toldAt = now;
1689
+ // Whoever connected since the last telling has the list of that moment, which a change
1690
+ // counted from the last telling would not bring up to date: they get the whole list. The
1691
+ // one whose joining this tells of has it as it is now.
1692
+ const fresh = this.#welcomed;
1693
+ this.#welcomed = new Set();
1694
+
1695
+ const players = this.players;
1696
+ const change = this.#presenceChange(players);
1697
+ let whole: string | undefined;
1698
+ let brief: string | undefined;
1699
+ for (const { ws } of sockets) {
1700
+ if (ws === except) continue;
1701
+ let frame: string;
1702
+ if (change !== "whole" && !fresh.has(ws) && this.#socketInfo(ws).presence) {
1703
+ // Nothing they do not know already.
1704
+ if (!change) continue;
1705
+ frame = brief ??= JSON.stringify({ t: "presence", ...change } satisfies ServerMessage);
1706
+ } else {
1707
+ frame = whole ??= JSON.stringify({ t: "presence", players } satisfies ServerMessage);
1708
+ }
1709
+ try {
1710
+ ws.send(frame);
1711
+ } catch {
1712
+ // Socket is closing.
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ /**
1718
+ * How `players` differs from what was last told, and remembers it as told.
1719
+ * "whole" when that is not known, or when saying it takes as long as the
1720
+ * list; undefined when nothing changed.
1721
+ */
1722
+ #presenceChange(players: Player[]): { set?: Player[]; gone?: string[] } | "whole" | undefined {
1723
+ const told = this.#told;
1724
+ const now = new Map(players.map((player) => [player.id, player]));
1725
+ this.#told = now;
1726
+ if (!told) return "whole";
1727
+ const set = players.filter((player) => {
1728
+ const was = told.get(player.id);
1729
+ return !was || was.connected !== player.connected || was.name !== player.name;
1730
+ });
1731
+ const gone: string[] = [];
1732
+ for (const id of told.keys()) if (!now.has(id)) gone.push(id);
1733
+ if (set.length === 0 && gone.length === 0) return undefined;
1734
+ if (set.length + gone.length >= players.length) return "whole";
1735
+ return { ...(set.length > 0 ? { set } : {}), ...(gone.length > 0 ? { gone } : {}) };
1736
+ }
1737
+
1738
+ #send(ws: WebSocket, message: ServerMessage): void {
1739
+ try {
1740
+ ws.send(JSON.stringify(message));
1741
+ } catch {
1742
+ // Socket is closing.
1743
+ }
1744
+ }
1745
+
1746
+ #deliverMail(): void {
1747
+ const mail = this.#mail.splice(0);
1748
+ let everyone: { ws: WebSocket; id: string }[] | undefined;
1749
+ for (const { to, frame } of mail) {
1750
+ const sockets =
1751
+ to === null
1752
+ ? (everyone ??= this.#seatedSockets()).map(({ ws }) => ws)
1753
+ : this.#roster.includes(to) || this.#removed.some((seat) => seat.id === to)
1754
+ ? this.ctx.getWebSockets(to).filter((ws) => ws.readyState === SOCKET_OPEN)
1755
+ : [];
1756
+ for (const ws of sockets) {
1757
+ try {
1758
+ ws.send(frame);
1759
+ } catch {
1760
+ // Socket is closing.
1761
+ }
1762
+ }
1763
+ }
1764
+ }
1765
+
1766
+ /**
1767
+ * Open sockets of players who still hold a seat.
1768
+ *
1769
+ * This runs several times a tick, so it costs what the sockets cost and no
1770
+ * more: seats are looked up in a set, not the list, and each socket's tags
1771
+ * are read once. With a thousand players, looking each one up in the list
1772
+ * and asking for its tags every time was most of what a tick cost.
1773
+ */
1774
+ #seatedSockets(): SeatedSocket[] {
1775
+ const sockets: SeatedSocket[] = [];
1776
+ const seated = new Set(this.#roster);
1777
+ for (const ws of this.ctx.getWebSockets()) {
1778
+ if (ws.readyState !== SOCKET_OPEN) continue;
1779
+ const info = this.#socketInfo(ws);
1780
+ if (info.id === undefined || !seated.has(info.id)) continue;
1781
+ sockets.push(info.marked ? { ws, id: info.id, binary: info.binary, arrays: info.arrays } : { ws, id: info.id });
1782
+ }
1783
+ return sockets;
1784
+ }
1785
+
1786
+ /** Whether any seated player has an open socket: `#seatedSockets().length > 0`, without making the list. */
1787
+ #anySeated(): boolean {
1788
+ if (this.#roster.length === 0) return false;
1789
+ const seated = new Set(this.#roster);
1790
+ for (const ws of this.ctx.getWebSockets()) {
1791
+ if (ws.readyState !== SOCKET_OPEN) continue;
1792
+ const id = this.#socketInfo(ws).id;
1793
+ if (id !== undefined && seated.has(id)) return true;
1794
+ }
1795
+ return false;
1796
+ }
1797
+
1798
+ /** What a socket's tags say. They never change, so they are read once a socket, while this instance lasts. */
1799
+ #socketInfo(ws: WebSocket): SocketInfo {
1800
+ let info = this.#infos.get(ws);
1801
+ if (!info) {
1802
+ const tags = this.ctx.getTags(ws);
1803
+ info = {
1804
+ id: tags.find((tag) => !isMark(tag)),
1805
+ marked: tags.length > 1,
1806
+ binary: tags.includes(BINARY_TAG),
1807
+ arrays: tags.includes(V2_TAG),
1808
+ presence: tags.includes(V3_TAG),
1809
+ };
1810
+ this.#infos.set(ws, info);
1811
+ }
1812
+ return info;
1813
+ }
1814
+
1815
+ #infos = new WeakMap<WebSocket, SocketInfo>();
1816
+
1817
+ /** The players with an open socket, found in one pass over the sockets. */
1818
+ #connectedIds(): Set<string> {
1819
+ const ids = new Set<string>();
1820
+ for (const ws of this.ctx.getWebSockets()) {
1821
+ if (ws.readyState !== SOCKET_OPEN) continue;
1822
+ const id = this.#socketInfo(ws).id;
1823
+ if (id !== undefined) ids.add(id);
1824
+ }
1825
+ return ids;
1826
+ }
1827
+
1828
+ #playerOf(ws: WebSocket): string | undefined {
1829
+ return this.#socketInfo(ws).id;
1830
+ }
1831
+
1832
+ #isConnected(playerId: string, except?: WebSocket): boolean {
1833
+ return this.ctx
1834
+ .getWebSockets(playerId)
1835
+ .some((ws) => ws !== except && ws.readyState === SOCKET_OPEN);
1836
+ }
1837
+
1838
+ #nextTimer(): number | undefined {
1839
+ let next = this.#awakeAt;
1840
+ for (const firesAt of this.#timers.values()) {
1841
+ if (next === undefined || firesAt < next) next = firesAt;
1842
+ }
1843
+ return next;
1844
+ }
1845
+ }
1846
+
1847
+ function messageFrame(message: unknown): string {
1848
+ const frame = JSON.stringify({ t: "msg", d: message ?? null });
1849
+ // `undefined` and functions vanish in JSON; a cycle or a BigInt throws on its own.
1850
+ if (frame === undefined) throw new TypeError("A message must be JSON-serializable");
1851
+ return frame;
1852
+ }
1853
+
1854
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
1855
+ return typeof (value as { then?: unknown } | null | undefined)?.then === "function";
1856
+ }
1857
+
1858
+ /** The name the gateway forwarded, if any. */
1859
+ function nameFrom(request: Request): string | undefined {
1860
+ const header = request.headers.get(NAME_HEADER);
1861
+ if (!header) return undefined;
1862
+ try {
1863
+ return decodeURIComponent(header);
1864
+ } catch {
1865
+ return undefined;
1866
+ }
1867
+ }