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