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