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,213 @@
|
|
|
1
|
+
import type { Party } from "./tokens.js";
|
|
2
|
+
|
|
3
|
+
/** Header the gateway uses to tell a room who is connecting. Never trusted from the client. */
|
|
4
|
+
export const PLAYER_HEADER = "x-tickflare-player";
|
|
5
|
+
/** Header the gateway uses to tell a room the id it is known by. */
|
|
6
|
+
export const ROOM_HEADER = "x-tickflare-room";
|
|
7
|
+
/** Header the gateway uses to tell a room the player's name, URI-encoded. Never trusted from the client. */
|
|
8
|
+
export const NAME_HEADER = "x-tickflare-name";
|
|
9
|
+
/** Header the gateway uses to tell a matchmaker roughly where a player is. */
|
|
10
|
+
export const HINT_HEADER = "x-tickflare-hint";
|
|
11
|
+
/** Header the gateway uses to tell a matchmaker the player's party, as `size:id`. Never trusted from the client. */
|
|
12
|
+
export const PARTY_HEADER = "x-tickflare-party";
|
|
13
|
+
|
|
14
|
+
const ROOM_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
15
|
+
/** Visible ASCII without spaces: safe as a header value and as a WebSocket tag. */
|
|
16
|
+
const PLAYER_ID = /^[\x21-\x7E]{1,128}$/;
|
|
17
|
+
/** Up to 64 characters without control characters. */
|
|
18
|
+
const PLAYER_NAME = /^[^\p{Cc}]{1,64}$/u;
|
|
19
|
+
/** Visible ASCII without spaces, as player ids are. */
|
|
20
|
+
const PARTY_ID = /^[\x21-\x7E]{1,64}$/;
|
|
21
|
+
/** The most members a party can have. */
|
|
22
|
+
const MOST_IN_A_PARTY = 64;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Who `authenticate` found: a player id, or a player id with a display name.
|
|
26
|
+
* A name reaches the room's hooks as `player.name`.
|
|
27
|
+
*/
|
|
28
|
+
export type Authenticated =
|
|
29
|
+
| string
|
|
30
|
+
| {
|
|
31
|
+
/** The player id. */
|
|
32
|
+
id: string;
|
|
33
|
+
/** A display name, e.g. the account name. */
|
|
34
|
+
name?: string;
|
|
35
|
+
/** The party the player queues with, for a matchmaker. See `JoinTokenClaims.party`. */
|
|
36
|
+
party?: Party;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The part of a Durable Object namespace Tickflare needs to reach rooms and
|
|
41
|
+
* matchmakers. Any namespace binding fits, e.g. `env.ROOMS`.
|
|
42
|
+
*/
|
|
43
|
+
export interface RoomNamespace {
|
|
44
|
+
/** The id of the object with this name. */
|
|
45
|
+
idFromName(name: string): DurableObjectId;
|
|
46
|
+
/** A stub for the object with this id. */
|
|
47
|
+
get(
|
|
48
|
+
id: DurableObjectId,
|
|
49
|
+
options?: DurableObjectNamespaceGetDurableObjectOptions,
|
|
50
|
+
): {
|
|
51
|
+
/** Sends the object a request. */
|
|
52
|
+
fetch(request: Request): Promise<Response>;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** How `routeToRoom` finds rooms and decides who may connect. */
|
|
57
|
+
export interface RouteOptions {
|
|
58
|
+
/** Durable Object namespace of your `Room` class, e.g. `env.ROOMS`. */
|
|
59
|
+
rooms: RoomNamespace;
|
|
60
|
+
/** URL prefix rooms live under. Defaults to `/rooms`. */
|
|
61
|
+
prefix?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Work out who is connecting. Return the player's id (or `{ id, name }`),
|
|
64
|
+
* or a `Response` to refuse the connection. This is the only place
|
|
65
|
+
* identity is established: rooms trust whatever this returns. `roomId` is
|
|
66
|
+
* the room being opened. `tokenAuth` gives you one that checks signed join
|
|
67
|
+
* tokens, and `Accounts.authenticate` one that also knows signed-in players.
|
|
68
|
+
*/
|
|
69
|
+
authenticate(request: Request, roomId: string): Authenticated | Response | Promise<Authenticated | Response>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Forwards room traffic to the room's Durable Object: WebSocket upgrades on
|
|
74
|
+
* `{prefix}/{roomId}`, and plain HTTP requests on `{prefix}/{roomId}/...`,
|
|
75
|
+
* which reach the room's `onHttp` hook. Both are authenticated first.
|
|
76
|
+
* Returns `null` when the URL is not a room URL, so the caller can fall
|
|
77
|
+
* through to its other routes.
|
|
78
|
+
*/
|
|
79
|
+
export async function routeToRoom(
|
|
80
|
+
request: Request,
|
|
81
|
+
options: RouteOptions,
|
|
82
|
+
): Promise<Response | null> {
|
|
83
|
+
const prefix = (options.prefix ?? "/rooms").replace(/\/+$/, "");
|
|
84
|
+
const { pathname } = new URL(request.url);
|
|
85
|
+
if (!pathname.startsWith(`${prefix}/`)) return null;
|
|
86
|
+
|
|
87
|
+
const [roomId = "", ...rest] = pathname.slice(prefix.length + 1).split("/");
|
|
88
|
+
const upgrade = request.headers.get("Upgrade")?.toLowerCase() === "websocket";
|
|
89
|
+
if (!ROOM_ID.test(roomId) || (upgrade && rest.length > 0)) {
|
|
90
|
+
return new Response("Invalid room id", { status: 400 });
|
|
91
|
+
}
|
|
92
|
+
if (!upgrade && rest.length === 0) {
|
|
93
|
+
return new Response("Expected a WebSocket upgrade", { status: 426 });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const identity = checkIdentity(await options.authenticate(request, roomId));
|
|
97
|
+
if (identity instanceof Response) return identity;
|
|
98
|
+
|
|
99
|
+
const headers = identityHeaders(request, identity);
|
|
100
|
+
headers.set(ROOM_HEADER, roomId);
|
|
101
|
+
|
|
102
|
+
const stub = options.rooms.get(options.rooms.idFromName(roomId));
|
|
103
|
+
return stub.fetch(new Request(request, { headers }));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** What `authenticate` returned, as an id and maybe a name, or the answer for something that cannot be a player. */
|
|
107
|
+
function checkIdentity(identity: unknown): Checked | Response {
|
|
108
|
+
if (identity instanceof Response) return identity;
|
|
109
|
+
const id = typeof identity === "object" && identity !== null ? (identity as { id?: unknown }).id : identity;
|
|
110
|
+
const name = typeof identity === "object" && identity !== null ? (identity as { name?: unknown }).name : undefined;
|
|
111
|
+
const party = typeof identity === "object" && identity !== null ? (identity as { party?: unknown }).party : undefined;
|
|
112
|
+
// An `authenticate` that falls off its end returns undefined. That is nobody, not a player.
|
|
113
|
+
if (typeof id !== "string") {
|
|
114
|
+
return new Response("Not authenticated", { status: 401 });
|
|
115
|
+
}
|
|
116
|
+
// "__proto__" would do damage as a key in a game's state.
|
|
117
|
+
if (!PLAYER_ID.test(id) || id === "__proto__") {
|
|
118
|
+
return new Response("Invalid player id", { status: 400 });
|
|
119
|
+
}
|
|
120
|
+
if (name !== undefined && (typeof name !== "string" || !PLAYER_NAME.test(name))) {
|
|
121
|
+
return new Response("Invalid player name", { status: 400 });
|
|
122
|
+
}
|
|
123
|
+
const checked: Checked = name === undefined ? { id } : { id, name };
|
|
124
|
+
if (party !== undefined) {
|
|
125
|
+
const { id: partyId, size } = (party ?? {}) as { id?: unknown; size?: unknown };
|
|
126
|
+
if (typeof partyId !== "string" || !PARTY_ID.test(partyId) || !Number.isInteger(size) || (size as number) < 1 || (size as number) > MOST_IN_A_PARTY) {
|
|
127
|
+
return new Response("Invalid party", { status: 400 });
|
|
128
|
+
}
|
|
129
|
+
checked.party = { id: partyId, size: size as number };
|
|
130
|
+
}
|
|
131
|
+
return checked;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
type Checked = { id: string; name?: string; party?: Party };
|
|
135
|
+
|
|
136
|
+
/** The request's headers with the gateway's own: anything the client sent under the same names is replaced or dropped. */
|
|
137
|
+
function identityHeaders(request: Request, identity: Checked): Headers {
|
|
138
|
+
const headers = new Headers(request.headers);
|
|
139
|
+
headers.set(PLAYER_HEADER, identity.id);
|
|
140
|
+
if (identity.name === undefined) headers.delete(NAME_HEADER);
|
|
141
|
+
else headers.set(NAME_HEADER, encodeURIComponent(identity.name));
|
|
142
|
+
if (identity.party === undefined) headers.delete(PARTY_HEADER);
|
|
143
|
+
else headers.set(PARTY_HEADER, `${identity.party.size}:${identity.party.id}`);
|
|
144
|
+
return headers;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** How `routeToMatchmaker` finds queues and decides who may join them. */
|
|
148
|
+
export interface MatchmakerRouteOptions {
|
|
149
|
+
/** Durable Object namespace of your `Matchmaker` class, e.g. `env.MATCHMAKERS`. Each queue is one object in it. */
|
|
150
|
+
matchmakers: RoomNamespace;
|
|
151
|
+
/** URL prefix queues live under. Defaults to `/matchmaking`. */
|
|
152
|
+
prefix?: string;
|
|
153
|
+
/** Same contract as for rooms: the player's id (or `{ id, name }`), or a `Response` to refuse. `queue` is the queue name. */
|
|
154
|
+
authenticate(request: Request, queue: string): Authenticated | Response | Promise<Authenticated | Response>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Forwards `{prefix}/{queue}` WebSocket upgrades to a matchmaker. Each queue
|
|
159
|
+
* name is its own Durable Object, so `/matchmaking/ranked` and
|
|
160
|
+
* `/matchmaking/casual` fill separately. Returns `null` for other URLs.
|
|
161
|
+
*/
|
|
162
|
+
export async function routeToMatchmaker(
|
|
163
|
+
request: Request,
|
|
164
|
+
options: MatchmakerRouteOptions,
|
|
165
|
+
): Promise<Response | null> {
|
|
166
|
+
const prefix = (options.prefix ?? "/matchmaking").replace(/\/+$/, "");
|
|
167
|
+
const { pathname } = new URL(request.url);
|
|
168
|
+
if (!pathname.startsWith(`${prefix}/`)) return null;
|
|
169
|
+
|
|
170
|
+
const queue = pathname.slice(prefix.length + 1);
|
|
171
|
+
if (!ROOM_ID.test(queue)) {
|
|
172
|
+
return new Response("Invalid queue name", { status: 400 });
|
|
173
|
+
}
|
|
174
|
+
if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
175
|
+
return new Response("Expected a WebSocket upgrade", { status: 426 });
|
|
176
|
+
}
|
|
177
|
+
const identity = checkIdentity(await options.authenticate(request, queue));
|
|
178
|
+
if (identity instanceof Response) return identity;
|
|
179
|
+
|
|
180
|
+
const headers = identityHeaders(request, identity);
|
|
181
|
+
const hint = locationHintFor(request);
|
|
182
|
+
if (hint) headers.set(HINT_HEADER, hint);
|
|
183
|
+
else headers.delete(HINT_HEADER);
|
|
184
|
+
|
|
185
|
+
const stub = options.matchmakers.get(options.matchmakers.idFromName(queue));
|
|
186
|
+
return stub.fetch(new Request(request, { headers }));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The Durable Object location hint closest to where a request came from,
|
|
191
|
+
* worked out from Cloudflare's `request.cf`. Undefined when that is missing,
|
|
192
|
+
* as it is in local development.
|
|
193
|
+
*/
|
|
194
|
+
export function locationHintFor(request: Request): DurableObjectLocationHint | undefined {
|
|
195
|
+
const cf = (request as { cf?: { continent?: string; longitude?: string } }).cf;
|
|
196
|
+
const longitude = Number(cf?.longitude);
|
|
197
|
+
switch (cf?.continent) {
|
|
198
|
+
case "NA":
|
|
199
|
+
return longitude < -100 ? "wnam" : "enam";
|
|
200
|
+
case "SA":
|
|
201
|
+
return "sam";
|
|
202
|
+
case "EU":
|
|
203
|
+
return longitude > 20 ? "eeur" : "weur";
|
|
204
|
+
case "AS":
|
|
205
|
+
return longitude < 60 ? "me" : "apac";
|
|
206
|
+
case "OC":
|
|
207
|
+
return "oc";
|
|
208
|
+
case "AF":
|
|
209
|
+
return "afr";
|
|
210
|
+
default:
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server side: rooms, the gateway, join tokens, accounts, matchmaking,
|
|
3
|
+
* match results and the helpers for worlds split across rooms. Runs in a
|
|
4
|
+
* Cloudflare Worker.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
* @module tickflare
|
|
8
|
+
*/
|
|
9
|
+
export { Room, Rejection, reject, type ActOutcome } from "./room.js";
|
|
10
|
+
export { plain } from "./tracked.js";
|
|
11
|
+
export { LockstepRoom, type LockstepCommand, type LockstepState } from "./lockstep.js";
|
|
12
|
+
export {
|
|
13
|
+
fingerprint,
|
|
14
|
+
runReplay,
|
|
15
|
+
seededRandom,
|
|
16
|
+
stepThrough,
|
|
17
|
+
type CatchUp,
|
|
18
|
+
type LockstepView,
|
|
19
|
+
type TurnsMessage,
|
|
20
|
+
type Replay,
|
|
21
|
+
type SeededRandom,
|
|
22
|
+
type Simulation,
|
|
23
|
+
type Snapshot,
|
|
24
|
+
type TurnEntry,
|
|
25
|
+
} from "../lockstep.js";
|
|
26
|
+
export { Matchmaker } from "./matchmaker.js";
|
|
27
|
+
export {
|
|
28
|
+
createJoinToken,
|
|
29
|
+
tokenAuth,
|
|
30
|
+
verifyJoinToken,
|
|
31
|
+
type JoinTokenClaims,
|
|
32
|
+
type Party,
|
|
33
|
+
type TokenAuthOptions,
|
|
34
|
+
type VerifiedJoinToken,
|
|
35
|
+
} from "./tokens.js";
|
|
36
|
+
export { cellOf, shardFor, type Cell } from "../world.js";
|
|
37
|
+
export { MATCHES_SCHEMA, recentMatches, recordMatches, type MatchRecord } from "./matches.js";
|
|
38
|
+
export {
|
|
39
|
+
ACCOUNTS_SCHEMA,
|
|
40
|
+
AccountError,
|
|
41
|
+
Accounts,
|
|
42
|
+
hashPassword,
|
|
43
|
+
verifyPassword,
|
|
44
|
+
type AccountsOptions,
|
|
45
|
+
type DataPolicy,
|
|
46
|
+
type Identity,
|
|
47
|
+
type ImportedAccount,
|
|
48
|
+
type LeaderboardEntry,
|
|
49
|
+
type LeaderboardPage,
|
|
50
|
+
type OwnAccount,
|
|
51
|
+
type PasswordReset,
|
|
52
|
+
type PublicProfile,
|
|
53
|
+
} from "./accounts.js";
|
|
54
|
+
export {
|
|
55
|
+
locationHintFor,
|
|
56
|
+
routeToMatchmaker,
|
|
57
|
+
routeToRoom,
|
|
58
|
+
NAME_HEADER,
|
|
59
|
+
PLAYER_HEADER,
|
|
60
|
+
type Authenticated,
|
|
61
|
+
type MatchmakerRouteOptions,
|
|
62
|
+
type RoomNamespace,
|
|
63
|
+
type RouteOptions,
|
|
64
|
+
} from "./gateway.js";
|
|
65
|
+
export { applyPatch, diff, type ArrayPatch, type Patch } from "../patch.js";
|
|
66
|
+
export { decodePatchFrame } from "../binary.js";
|
|
67
|
+
export {
|
|
68
|
+
CloseCode,
|
|
69
|
+
PROTOCOL_VERSION,
|
|
70
|
+
type AckFrame,
|
|
71
|
+
type ClockFrame,
|
|
72
|
+
type ClientMessage,
|
|
73
|
+
type CommandFrame,
|
|
74
|
+
type ErrorFrame,
|
|
75
|
+
type LeaveFrame,
|
|
76
|
+
type MatchFound,
|
|
77
|
+
type MatchResult,
|
|
78
|
+
type MessageFrame,
|
|
79
|
+
type PatchFrame,
|
|
80
|
+
type Player,
|
|
81
|
+
type PresenceFrame,
|
|
82
|
+
type RejectFrame,
|
|
83
|
+
type ServerMessage,
|
|
84
|
+
type StateFrame,
|
|
85
|
+
type WelcomeFrame,
|
|
86
|
+
} from "../protocol.js";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** How often idle buckets are cleared out. */
|
|
2
|
+
const SWEEP_MS = 10_000;
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A token bucket per key: it refills at `rate` a second and holds at most
|
|
6
|
+
* one second's worth (never less than one), so `rate` is both the sustained
|
|
7
|
+
* limit and the largest burst. A bucket belongs to the key, not to a
|
|
8
|
+
* connection: dropping and reconnecting does not refill it. Kept in memory
|
|
9
|
+
* only: a room that restarts starts everyone afresh.
|
|
10
|
+
*/
|
|
11
|
+
export class RateLimiter {
|
|
12
|
+
#buckets = new Map<string, { left: number; at: number }>();
|
|
13
|
+
#sweptAt = 0;
|
|
14
|
+
|
|
15
|
+
/** Take one from `key`'s bucket. False when it is empty. An infinite rate always passes. */
|
|
16
|
+
spend(key: string, rate: number): boolean {
|
|
17
|
+
if (rate === Number.POSITIVE_INFINITY) return true;
|
|
18
|
+
if (!(rate > 0)) return false;
|
|
19
|
+
// A rate below one a second still lets single frames through, just further apart.
|
|
20
|
+
const size = Math.max(1, rate);
|
|
21
|
+
const now = Date.now();
|
|
22
|
+
if (now - this.#sweptAt >= SWEEP_MS) this.#sweep(now, rate, size);
|
|
23
|
+
|
|
24
|
+
const bucket = this.#buckets.get(key) ?? { left: size, at: now };
|
|
25
|
+
bucket.left = Math.min(size, bucket.left + ((now - bucket.at) / 1000) * rate);
|
|
26
|
+
bucket.at = now;
|
|
27
|
+
this.#buckets.set(key, bucket);
|
|
28
|
+
if (bucket.left < 1) return false;
|
|
29
|
+
bucket.left -= 1;
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Forgets the keys that have been quiet for long enough to be full again. */
|
|
34
|
+
#sweep(now: number, rate: number, size: number): void {
|
|
35
|
+
this.#sweptAt = now;
|
|
36
|
+
const refillMs = (size / rate) * 1000;
|
|
37
|
+
for (const [key, bucket] of this.#buckets) {
|
|
38
|
+
if (now - bucket.at >= refillMs) this.#buckets.delete(key);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|