tickflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,99 @@
1
+ import type { MatchResult } from "../protocol.js";
2
+
3
+ /** A finished match as stored in D1. */
4
+ export interface MatchRecord {
5
+ /** The match id, as in `MatchResult.id`. */
6
+ id: string;
7
+ /** The room it was played in, if the room knew its id. */
8
+ room: string | null;
9
+ /** When it ended, in epoch milliseconds. */
10
+ endedAt: number;
11
+ /** Everyone who held a seat when it ended. */
12
+ players: string[];
13
+ /** What the room passed to `finishMatch`. */
14
+ result: Record<string, unknown>;
15
+ /** Where its replay is in R2, if it has one. */
16
+ replayKey: string | null;
17
+ }
18
+
19
+ /** The table `recordMatches` writes to. It creates it on first use; this is here if you prefer migrations. */
20
+ export const MATCHES_SCHEMA = `
21
+ CREATE TABLE IF NOT EXISTS tickflare_matches (
22
+ id TEXT PRIMARY KEY,
23
+ room TEXT,
24
+ ended_at INTEGER NOT NULL,
25
+ players TEXT NOT NULL,
26
+ result TEXT NOT NULL,
27
+ replay_key TEXT
28
+ );
29
+ CREATE INDEX IF NOT EXISTS tickflare_matches_ended_at ON tickflare_matches (ended_at DESC);
30
+ `;
31
+
32
+ const ready = new WeakSet<D1Database>();
33
+
34
+ async function ensureSchema(db: D1Database): Promise<void> {
35
+ if (ready.has(db)) return;
36
+ const statements = MATCHES_SCHEMA.split(";")
37
+ .map((sql) => sql.trim())
38
+ .filter(Boolean)
39
+ .map((sql) => db.prepare(sql));
40
+ await db.batch(statements);
41
+ ready.add(db);
42
+ }
43
+
44
+ /**
45
+ * Queue consumer: stores finished matches in D1. Use it as your Worker's
46
+ * `queue` handler, or call it from one:
47
+ *
48
+ * async queue(batch, env) {
49
+ * await recordMatches(batch, env.DB);
50
+ * }
51
+ *
52
+ * A match is stored once however often its message is delivered.
53
+ */
54
+ export async function recordMatches(batch: MessageBatch<MatchResult>, db: D1Database): Promise<void> {
55
+ await ensureSchema(db);
56
+ const insert = db.prepare(
57
+ `INSERT OR IGNORE INTO tickflare_matches (id, room, ended_at, players, result, replay_key)
58
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)`,
59
+ );
60
+ for (const message of batch.messages) {
61
+ const match = message.body;
62
+ try {
63
+ await insert
64
+ .bind(
65
+ match.id,
66
+ match.room,
67
+ match.endedAt,
68
+ JSON.stringify(match.players),
69
+ JSON.stringify(match.result),
70
+ match.replayKey ?? null,
71
+ )
72
+ .run();
73
+ message.ack();
74
+ } catch (err) {
75
+ console.error("[tickflare] could not store a match:", err);
76
+ message.retry();
77
+ }
78
+ }
79
+ }
80
+
81
+ /** The most recently finished matches, newest first. */
82
+ export async function recentMatches(db: D1Database, limit = 20): Promise<MatchRecord[]> {
83
+ await ensureSchema(db);
84
+ const { results } = await db
85
+ .prepare(
86
+ `SELECT id, room, ended_at, players, result, replay_key
87
+ FROM tickflare_matches ORDER BY ended_at DESC LIMIT ?1`,
88
+ )
89
+ .bind(Math.max(1, Math.min(100, Math.floor(limit))))
90
+ .all<{ id: string; room: string | null; ended_at: number; players: string; result: string; replay_key: string | null }>();
91
+ return results.map((row) => ({
92
+ id: row.id,
93
+ room: row.room,
94
+ endedAt: row.ended_at,
95
+ players: JSON.parse(row.players) as string[],
96
+ result: JSON.parse(row.result) as Record<string, unknown>,
97
+ replayKey: row.replay_key,
98
+ }));
99
+ }
@@ -0,0 +1,537 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { CloseCode, PING, PONG, type MatchFound } from "../protocol.js";
3
+ import { HINT_HEADER, PARTY_HEADER, PLAYER_HEADER, type RoomNamespace } from "./gateway.js";
4
+ import type { RoomCall } from "./room.js";
5
+ import type { Party } from "./tokens.js";
6
+
7
+ interface Waiting {
8
+ player: string;
9
+ hint: string | null;
10
+ /** When the player started waiting, in epoch milliseconds. */
11
+ since: number;
12
+ /** Place in the queue. Two players can arrive in the same millisecond; this still tells them apart. */
13
+ order: number;
14
+ /** What `ratingOf` gave when the player started waiting, if it gave a number. */
15
+ rating?: number;
16
+ /** What `regionOf` gave. */
17
+ region?: string;
18
+ /** What `partyOf` gave: the party's id and how many it has. */
19
+ party?: string;
20
+ partySize?: number;
21
+ }
22
+
23
+ type Queued = Waiting & { ws: WebSocket };
24
+
25
+ /**
26
+ * What is matched: a player alone, or the members of a party who are
27
+ * waiting, which are never split.
28
+ */
29
+ interface Unit {
30
+ members: Queued[];
31
+ size: number;
32
+ /** The members' average rating, if any of them has one. */
33
+ rating?: number;
34
+ /** The members' most common region. */
35
+ region?: string;
36
+ /** When its longest-waiting member started waiting, and that member's place in the queue. */
37
+ since: number;
38
+ order: number;
39
+ /** From when it may be matched: at once, or for a party not all there yet, when it has waited long enough. */
40
+ readyAt: number;
41
+ }
42
+
43
+ /**
44
+ * Puts waiting players together into matches. One Durable Object per queue
45
+ * name.
46
+ *
47
+ * A player waits by holding a WebSocket open. As soon as `matchSize` players
48
+ * are waiting, the matchmaker picks a new room id, reserves the room for
49
+ * them, tells each of them where to go and closes their sockets. The queue
50
+ * is the set of open sockets, so the object hibernates while people wait.
51
+ *
52
+ * Who is matched with whom is first come, first served, unless you say
53
+ * otherwise: `ratingOf` and `ratingGap` keep players of different skill
54
+ * apart, and `regionWaitMs` keeps players of different regions apart, each
55
+ * for as long as you think a player should wait for a better match.
56
+ *
57
+ * Friends who queue together are a party: their join tokens say so, or
58
+ * `partyOf` does. A party is matched as one, never split, and with `teams`
59
+ * set it plays on one side.
60
+ */
61
+ export abstract class Matchmaker<Env = Cloudflare.Env> extends DurableObject<Env> {
62
+ /** Players per match. */
63
+ protected matchSize = 2;
64
+
65
+ /**
66
+ * The fewest players a match may start with once the longest-waiting
67
+ * player has waited `maxWaitMs`. Defaults to `matchSize`: full matches only.
68
+ */
69
+ protected minPlayers: number | undefined;
70
+
71
+ /**
72
+ * How long the longest-waiting player waits for a full match before one
73
+ * starts with whoever is there, provided that is at least `minPlayers`.
74
+ * 0, the default, waits for a full match however long it takes.
75
+ */
76
+ protected maxWaitMs = 0;
77
+
78
+ /**
79
+ * How far apart two players' ratings may be for them to be matched.
80
+ * Infinity, the default, matches players whatever `ratingOf` says. A match
81
+ * is built around whoever has waited longest: the players nearest to them
82
+ * in rating, none further away than this.
83
+ */
84
+ protected ratingGap = Infinity;
85
+
86
+ /**
87
+ * How much `ratingGap` grows for every second a player has waited, so that
88
+ * a player nobody is close to still gets a match. 0, the default, never
89
+ * widens it: such a player waits until someone close enough arrives.
90
+ */
91
+ protected ratingGapPerSecond = 0;
92
+
93
+ /**
94
+ * For how long a player is matched only with players of their own region.
95
+ * After that they are matched with anyone, players of their region first.
96
+ * 0, the default, matches across regions from the start.
97
+ */
98
+ protected regionWaitMs = 0;
99
+
100
+ /**
101
+ * How many sides a match is split into. 1, the default, says nothing about
102
+ * sides. With more, the matchmaker shares each match's players out among
103
+ * that many teams of as equal a size as it can, keeps every party on one
104
+ * team, and evens out the teams' ratings. The teams go in the `match`
105
+ * message and to the room, as `this.teams`. A party larger than a team is
106
+ * turned away.
107
+ */
108
+ protected teams = 1;
109
+
110
+ /**
111
+ * How long the first member of a party to arrive waits for the others.
112
+ * After that the members who are there are matched without the rest.
113
+ */
114
+ protected partyWaitMs = 60_000;
115
+
116
+ /**
117
+ * Where the rooms for matches are: the Durable Object namespace of your
118
+ * `Room` class. `protected override rooms = this.env.ROOMS;`
119
+ */
120
+ protected rooms: RoomNamespace | undefined;
121
+
122
+ /** A pass over the queue is under way. */
123
+ #matching = false;
124
+ /** Someone arrived or the wait ran out during that pass, so the queue needs another look. */
125
+ #again = false;
126
+ /** Reservations that failed in a row. Spaces out the next try. */
127
+ #failures = 0;
128
+
129
+ constructor(ctx: DurableObjectState, env: Env) {
130
+ super(ctx, env);
131
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
132
+ }
133
+
134
+ /**
135
+ * Set the room up for these players. The default creates it in `rooms`,
136
+ * near `locationHint` (where most of the players are), and closes it to
137
+ * everyone else. Override it to do more first, such as writing down the
138
+ * match, and call `super.reserveRoom` from yours. If it throws, the players
139
+ * keep waiting and the match is tried again shortly.
140
+ */
141
+ protected async reserveRoom(
142
+ roomId: string,
143
+ players: string[],
144
+ locationHint: DurableObjectLocationHint | undefined,
145
+ teams?: string[][],
146
+ ): Promise<void> {
147
+ const rooms = this.rooms;
148
+ if (!rooms) throw new TypeError("a matchmaker needs `rooms` to be set");
149
+ const stub = rooms.get(rooms.idFromName(roomId), locationHint ? { locationHint } : undefined) as unknown as {
150
+ tickflare(call: RoomCall): Promise<unknown>;
151
+ };
152
+ await stub.tickflare(teams ? { op: "reserve", roomId, players, teams } : { op: "reserve", roomId, players });
153
+ }
154
+
155
+ /**
156
+ * How good this player is, as a number in which players who are close are
157
+ * a fair match: an Elo rating, a rank, a level. It is asked once, when the
158
+ * player starts waiting, and only matters once `ratingGap` is set. A player
159
+ * without a rating, which is what the default gives everyone, can be
160
+ * matched with anyone.
161
+ *
162
+ * protected override ratingGap = 150;
163
+ * protected override async ratingOf(player: string) {
164
+ * const stats = await new Accounts(this.env.DB, options).stats(player);
165
+ * return stats.rating ?? 1000;
166
+ * }
167
+ */
168
+ protected ratingOf(player: string, request: Request): number | undefined | Promise<number | undefined> {
169
+ void player;
170
+ void request;
171
+ return undefined;
172
+ }
173
+
174
+ /**
175
+ * Which region this player is in, for `regionWaitMs`. The default is the
176
+ * part of the world the gateway saw the request come from, one of
177
+ * Cloudflare's location hints such as "weur" or "enam", and undefined when
178
+ * that is not known, as in local development. A player without a region
179
+ * can be matched with anyone.
180
+ */
181
+ protected regionOf(player: string, request: Request): string | undefined | Promise<string | undefined> {
182
+ void player;
183
+ return request.headers.get(HINT_HEADER) ?? undefined;
184
+ }
185
+
186
+ /**
187
+ * The party this player queues with, if any: friends who are to be matched
188
+ * together. The default is what their join token says, which only your
189
+ * server can write (see `JoinTokenClaims.party`). Override it to look the
190
+ * party up yourself, in a table of your own for instance. Never take it
191
+ * from the request's query: a player who could name any party could join
192
+ * a stranger's.
193
+ */
194
+ protected partyOf(player: string, request: Request): Party | undefined | Promise<Party | undefined> {
195
+ void player;
196
+ const header = request.headers.get(PARTY_HEADER);
197
+ const colon = header?.indexOf(":") ?? -1;
198
+ if (!header || colon < 1) return undefined;
199
+ return { size: Number(header.slice(0, colon)), id: header.slice(colon + 1) };
200
+ }
201
+
202
+ /** The most players a team can have: a party larger than this can never be matched. */
203
+ #largestParty(): number {
204
+ return Math.max(1, Math.floor(this.matchSize / Math.max(1, this.teams)));
205
+ }
206
+
207
+ /** Durable Object entry point for players joining the queue. Tickflare's: don't override it. */
208
+ override async fetch(request: Request): Promise<Response> {
209
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
210
+ return new Response("Expected a WebSocket upgrade", { status: 426 });
211
+ }
212
+ const player = request.headers.get(PLAYER_HEADER);
213
+ if (!player) {
214
+ return new Response("Missing player identity", { status: 401 });
215
+ }
216
+
217
+ let rating: number | undefined;
218
+ let region: string | undefined;
219
+ let party: Party | undefined;
220
+ try {
221
+ if (this.ratingGap !== Infinity) rating = await this.ratingOf(player, request);
222
+ if (this.regionWaitMs > 0) region = await this.regionOf(player, request);
223
+ } catch (err) {
224
+ // They wait as someone about whom nothing is known, which is better than not at all.
225
+ console.error("[tickflare] could not rate or place a player:", err);
226
+ }
227
+ try {
228
+ party = await this.partyOf(player, request);
229
+ } catch (err) {
230
+ console.error("[tickflare] could not look up a player's party:", err);
231
+ }
232
+ if (party && (typeof party.id !== "string" || !party.id || !Number.isInteger(party.size) || party.size < 1)) party = undefined;
233
+ // A party of one is a player alone.
234
+ if (party?.size === 1) party = undefined;
235
+ if (party && party.size > this.#largestParty()) {
236
+ // It could never be matched. Say so, rather than leave them waiting.
237
+ const pair = new WebSocketPair();
238
+ pair[1].accept();
239
+ pair[1].close(CloseCode.JoinRejected, "party_too_large");
240
+ return new Response(null, { status: 101, webSocket: pair[0] });
241
+ }
242
+
243
+ // A player waits once: a newer request replaces the older one.
244
+ for (const old of this.ctx.getWebSockets(player)) {
245
+ old.close(CloseCode.Replaced, "replaced");
246
+ }
247
+ const last = Math.max(
248
+ 0,
249
+ ...this.ctx.getWebSockets().map((ws) => (ws.deserializeAttachment() as Waiting | null)?.order ?? 0),
250
+ );
251
+ const pair = new WebSocketPair();
252
+ this.ctx.acceptWebSocket(pair[1], [player]);
253
+ pair[1].serializeAttachment({
254
+ player,
255
+ hint: request.headers.get(HINT_HEADER),
256
+ since: Date.now(),
257
+ order: last + 1,
258
+ ...(typeof rating === "number" && Number.isFinite(rating) ? { rating } : {}),
259
+ ...(typeof region === "string" && region ? { region: region.slice(0, 64) } : {}),
260
+ ...(party ? { party: party.id.slice(0, 64), partySize: party.size } : {}),
261
+ } satisfies Waiting);
262
+
263
+ await this.#match();
264
+ return new Response(null, { status: 101, webSocket: pair[0] });
265
+ }
266
+
267
+ /** Durable Object entry point for players leaving the queue. Tickflare's: don't override it. */
268
+ override webSocketClose(ws: WebSocket, code: number, reason: string): void {
269
+ try {
270
+ ws.close(code === 1005 || code === 1006 ? 1000 : code, reason);
271
+ } catch {
272
+ // Already closed.
273
+ }
274
+ }
275
+
276
+ /** The wait is over for whoever is in the queue. */
277
+ override async alarm(): Promise<void> {
278
+ await this.#match();
279
+ }
280
+
281
+ /**
282
+ * Forms as many matches as the waiting players allow, longest wait first.
283
+ *
284
+ * Reserving a room takes a moment, and players come and go meanwhile. So
285
+ * only one pass runs at a time: whoever calls during a pass asks for the
286
+ * queue to be looked at again when that pass is done, with whoever is
287
+ * waiting by then.
288
+ */
289
+ async #match(): Promise<void> {
290
+ if (this.#matching) {
291
+ this.#again = true;
292
+ return;
293
+ }
294
+ this.#matching = true;
295
+ try {
296
+ do {
297
+ this.#again = false;
298
+ if ((await this.#pass()) === "changed") this.#again = true;
299
+ } while (this.#again);
300
+ } finally {
301
+ this.#matching = false;
302
+ }
303
+ }
304
+
305
+ /** One look at the queue. "changed" means it has to be looked at again from the start. */
306
+ async #pass(): Promise<"done" | "changed"> {
307
+ const now = Date.now();
308
+ const queue: Queued[] = this.ctx
309
+ .getWebSockets()
310
+ .filter((ws) => ws.readyState === 1)
311
+ .map((ws) => ({ ws, ...(ws.deserializeAttachment() as Waiting) }))
312
+ .sort((a, b) => a.order - b.order);
313
+ const units = this.#units(queue);
314
+
315
+ const fewest = Math.max(1, this.minPlayers ?? this.matchSize);
316
+ // Whether a match may start short of `matchSize`, once someone has waited long enough.
317
+ const short = this.maxWaitMs > 0 && fewest < this.matchSize;
318
+ const ready = units.filter((unit) => unit.readyAt <= now);
319
+ // A party may not fit beside the one who has waited longest, and still make a match with others.
320
+ const picky = this.ratingGap !== Infinity || this.regionWaitMs > 0 || this.teams > 1 || ready.some((unit) => unit.size > 1);
321
+ // Without ratings, regions, teams or parties, every player suits every other, and the one who has waited longest says it all.
322
+ const anchors = picky ? ready : ready.slice(0, 1);
323
+
324
+ // The soonest the queue could look different with nobody arriving or leaving.
325
+ let wake = Infinity;
326
+ for (const unit of units) if (unit.readyAt > now) wake = Math.min(wake, unit.readyAt);
327
+
328
+ for (const anchor of anchors) {
329
+ const others = this.#around(anchor, ready);
330
+ const chosen = this.#fill(anchor, others.filter((other) => other.from <= now).map((other) => other.unit), this.matchSize);
331
+ let group: Unit[] | undefined;
332
+ if (chosen.size === this.matchSize) {
333
+ group = chosen.units;
334
+ } else if (short && chosen.size >= fewest && now >= anchor.since + this.maxWaitMs) {
335
+ group = chosen.units;
336
+ }
337
+ if (group) {
338
+ const players = group.flatMap((unit) => unit.members).sort((a, b) => a.order - b.order);
339
+ const teams = this.teams > 1 ? (this.#split(group) ?? this.#split(group, this.matchSize)) : undefined;
340
+ const started = await this.#start(players, teams);
341
+ if (started === "failed") {
342
+ // They keep waiting. Try again soon, sooner still if someone else arrives.
343
+ await this.ctx.storage.setAlarm(Date.now() + Math.min(30_000, 500 * 2 ** this.#failures++));
344
+ return "done";
345
+ }
346
+ this.#failures = 0;
347
+ // Matched or not, the queue is no longer what was read above.
348
+ return "changed";
349
+ }
350
+
351
+ // When enough of the others will be acceptable to make a match, or a short one.
352
+ const later = others.filter((other) => other.from > now && other.from !== Infinity).sort((a, b) => a.from - b.from);
353
+ let size = chosen.size;
354
+ for (const other of later) {
355
+ size += other.unit.size;
356
+ if (size >= this.matchSize || (short && size >= fewest)) {
357
+ wake = Math.min(wake, short && size < this.matchSize ? Math.max(other.from, anchor.since + this.maxWaitMs) : other.from);
358
+ break;
359
+ }
360
+ }
361
+ if (short && chosen.size >= fewest) wake = Math.min(wake, Math.max(now + 1, anchor.since + this.maxWaitMs));
362
+ }
363
+
364
+ // Only a queue that waits for a moment in time needs an alarm, or to be rid of one.
365
+ if (short || this.ratingGapPerSecond > 0 || this.regionWaitMs > 0 || units.some((unit) => unit.members[0]!.party !== undefined)) {
366
+ if (wake !== Infinity) await this.ctx.storage.setAlarm(Math.max(wake, now + 1));
367
+ else await this.ctx.storage.deleteAlarm();
368
+ }
369
+ return "done";
370
+ }
371
+
372
+ /** The queue as what is matched: players alone, and parties with the members who are waiting. */
373
+ #units(queue: Queued[]): Unit[] {
374
+ const units: Unit[] = [];
375
+ const parties = new Map<string, Queued[]>();
376
+ for (const waiting of queue) {
377
+ if (waiting.party === undefined) {
378
+ units.push({ members: [waiting], size: 1, rating: waiting.rating, region: waiting.region, since: waiting.since, order: waiting.order, readyAt: 0 });
379
+ continue;
380
+ }
381
+ let members = parties.get(waiting.party);
382
+ if (!members) parties.set(waiting.party, (members = []));
383
+ members.push(waiting);
384
+ }
385
+ const largest = this.#largestParty();
386
+ for (const members of parties.values()) {
387
+ // More members than the party said it has, or than a team holds: the first ones, in the order they came.
388
+ const taken = members.slice(0, Math.min(largest, Math.max(...members.map((member) => member.partySize ?? 1))));
389
+ const expected = Math.min(largest, taken[0]!.partySize ?? taken.length);
390
+ const rated = taken.filter((member) => member.rating !== undefined);
391
+ const since = Math.min(...taken.map((member) => member.since));
392
+ units.push({
393
+ members: taken,
394
+ size: taken.length,
395
+ rating: rated.length ? rated.reduce((sum, member) => sum + member.rating!, 0) / rated.length : undefined,
396
+ region: mostCommon(taken.map((member) => member.region)),
397
+ since,
398
+ order: Math.min(...taken.map((member) => member.order)),
399
+ readyAt: taken.length >= expected ? 0 : since + this.partyWaitMs,
400
+ });
401
+ // Anyone past what fits waits as a party of their own, for the next match.
402
+ for (const extra of members.slice(taken.length)) {
403
+ units.push({ members: [extra], size: 1, rating: extra.rating, region: extra.region, since: extra.since, order: extra.order, readyAt: 0 });
404
+ }
405
+ }
406
+ return units.sort((a, b) => a.order - b.order);
407
+ }
408
+
409
+ /**
410
+ * Everyone else in the queue as a match for `anchor`: from when on they may
411
+ * be matched, which is Infinity for never, with the ones to pick first at
412
+ * the front.
413
+ */
414
+ #around(anchor: Unit, units: Unit[]): { unit: Unit; from: number }[] {
415
+ const ranked: { unit: Unit; from: number; far: boolean; distance: number }[] = [];
416
+ for (const unit of units) {
417
+ if (unit === anchor) continue;
418
+ const far = anchor.region !== undefined && unit.region !== undefined && anchor.region !== unit.region;
419
+ let from = far && this.regionWaitMs > 0 ? anchor.since + this.regionWaitMs : 0;
420
+
421
+ let distance = 0;
422
+ if (anchor.rating !== undefined && unit.rating !== undefined) {
423
+ distance = Math.abs(anchor.rating - unit.rating);
424
+ const beyond = distance - this.ratingGap;
425
+ if (beyond > 0) {
426
+ const widened =
427
+ this.ratingGapPerSecond > 0 ? anchor.since + Math.ceil((beyond / this.ratingGapPerSecond) * 1000) : Infinity;
428
+ from = Math.max(from, widened);
429
+ }
430
+ }
431
+ ranked.push({ unit, from, far, distance });
432
+ }
433
+ // Their own region first, then the nearest in rating, then whoever has waited longest.
434
+ return ranked.sort(
435
+ (a, b) => Number(a.far) - Number(b.far) || a.distance - b.distance || a.unit.order - b.unit.order,
436
+ );
437
+ }
438
+
439
+ /**
440
+ * As many of `candidates`, in their order, as fit in a match of `capacity`
441
+ * with `anchor`, taking a party only where all of it fits, and only where
442
+ * the teams can still be made.
443
+ */
444
+ #fill(anchor: Unit, candidates: Unit[], capacity: number): { units: Unit[]; size: number } {
445
+ const units = [anchor];
446
+ let size = anchor.size;
447
+ for (const unit of candidates) {
448
+ if (size === capacity) break;
449
+ if (size + unit.size > capacity) continue;
450
+ if (this.teams > 1 && !this.#split([...units, unit], capacity)) continue;
451
+ units.push(unit);
452
+ size += unit.size;
453
+ }
454
+ return { units, size };
455
+ }
456
+
457
+ /**
458
+ * The players of a match as `teams` sides, or undefined if its parties
459
+ * cannot be shared out so. Each side holds at most `capacity / teams`,
460
+ * rounded up; the largest parties are placed first, each on the side with
461
+ * room for it whose ratings add up to least, which keeps the sides even.
462
+ */
463
+ #split(units: Unit[], capacity = units.reduce((sum, unit) => sum + unit.size, 0)): string[][] | undefined {
464
+ const teams = Math.max(1, this.teams);
465
+ const room = Math.ceil(capacity / teams);
466
+ const sides = Array.from({ length: teams }, () => ({ players: [] as Queued[], rating: 0, size: 0 }));
467
+ // With no ratings at all, units count as equal, and the sides are evened out by size.
468
+ const average = (() => {
469
+ const rated = units.filter((unit) => unit.rating !== undefined);
470
+ return rated.length ? rated.reduce((sum, unit) => sum + unit.rating!, 0) / rated.length : 0;
471
+ })();
472
+ const ordered = [...units].sort((a, b) => b.size - a.size || (b.rating ?? average) - (a.rating ?? average) || a.order - b.order);
473
+ for (const unit of ordered) {
474
+ const fits = sides.filter((side) => side.size + unit.size <= room);
475
+ if (fits.length === 0) return undefined;
476
+ const side = fits.reduce((best, side) => (side.rating < best.rating || (side.rating === best.rating && side.size < best.size) ? side : best));
477
+ side.players.push(...unit.members);
478
+ side.size += unit.size;
479
+ side.rating += (unit.rating ?? average) * unit.size;
480
+ }
481
+ return sides.map((side) => side.players.sort((a, b) => a.order - b.order).map((member) => member.player));
482
+ }
483
+
484
+ /**
485
+ * Reserves a room for the group and sends them there. "failed" if the room
486
+ * could not be reserved, "gone" if one of them stopped waiting meanwhile:
487
+ * the others go back in the queue and the room is left unused.
488
+ */
489
+ async #start(group: Queued[], teams?: string[][]): Promise<"matched" | "gone" | "failed"> {
490
+ const players = group.map((waiting) => waiting.player);
491
+ const room = crypto.randomUUID();
492
+ try {
493
+ await this.reserveRoom(room, players, mostCommonHint(group), teams);
494
+ } catch (err) {
495
+ console.error("[tickflare] could not reserve a room:", err);
496
+ return "failed";
497
+ }
498
+ // Someone who left during the reservation would leave the others in a room that never fills.
499
+ if (group.some(({ ws }) => ws.readyState !== 1)) return "gone";
500
+
501
+ const found = JSON.stringify((teams ? { t: "match", room, players, teams } : { t: "match", room, players }) satisfies MatchFound);
502
+ for (const { ws } of group) {
503
+ try {
504
+ ws.send(found);
505
+ ws.close(1000, "matched");
506
+ } catch {
507
+ // The player gave up at the last moment. Their seat stays reserved.
508
+ }
509
+ }
510
+ return "matched";
511
+ }
512
+ }
513
+
514
+ function mostCommonHint(group: Waiting[]): DurableObjectLocationHint | undefined {
515
+ const counts = new Map<string, number>();
516
+ let best: string | undefined;
517
+ for (const { hint } of group) {
518
+ if (!hint) continue;
519
+ const count = (counts.get(hint) ?? 0) + 1;
520
+ counts.set(hint, count);
521
+ if (best === undefined || count > counts.get(best)!) best = hint;
522
+ }
523
+ return best as DurableObjectLocationHint | undefined;
524
+ }
525
+
526
+ /** The value that occurs most often, ignoring undefined. */
527
+ function mostCommon(values: (string | undefined)[]): string | undefined {
528
+ const counts = new Map<string, number>();
529
+ let best: string | undefined;
530
+ for (const value of values) {
531
+ if (value === undefined) continue;
532
+ const count = (counts.get(value) ?? 0) + 1;
533
+ counts.set(value, count);
534
+ if (best === undefined || count > counts.get(best)!) best = value;
535
+ }
536
+ return best;
537
+ }