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.
- package/CHANGELOG.md +233 -0
- package/LICENSE +21 -0
- package/README.md +110 -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/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 +161 -0
- package/dist/client/index.js +436 -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 +230 -0
- package/dist/protocol.js +50 -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 +126 -0
- package/dist/server/lockstep.js +544 -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 +383 -0
- package/dist/server/room.js +1766 -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/draft.ts +138 -0
- package/src/client/index.ts +573 -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 +260 -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 +85 -0
- package/src/server/limiter.ts +41 -0
- package/src/server/lockstep.ts +611 -0
- package/src/server/matches.ts +99 -0
- package/src/server/matchmaker.ts +537 -0
- package/src/server/room.ts +1867 -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,398 @@
|
|
|
1
|
+
import {
|
|
2
|
+
fingerprint,
|
|
3
|
+
fingerprintOfText,
|
|
4
|
+
stepThrough,
|
|
5
|
+
type CatchUp,
|
|
6
|
+
type LockstepView,
|
|
7
|
+
type Replay,
|
|
8
|
+
type Simulation,
|
|
9
|
+
type TurnEntry,
|
|
10
|
+
type TurnsMessage,
|
|
11
|
+
} from "../lockstep.js";
|
|
12
|
+
import { RoomClient, type CloseDetail, type ConnectionStatus } from "./index.js";
|
|
13
|
+
import { TurnPacer } from "./pacer.js";
|
|
14
|
+
import { roomIn, withFreshToken, type TokenSource } from "./token.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The simulation to run, what to report and how to connect. `create` and
|
|
18
|
+
* `step` are required. With `save` and `load` as well, the client sends the
|
|
19
|
+
* room snapshots and starts from one when it joins late.
|
|
20
|
+
*/
|
|
21
|
+
export interface LockstepClientOptions<Input, Sim> extends Simulation<Input, Sim> {
|
|
22
|
+
/**
|
|
23
|
+
* A fingerprint of the simulation, at most 64 characters long. It is sent
|
|
24
|
+
* to the room every `hashEvery` turns, and the room flags the match if two
|
|
25
|
+
* players disagree. A simulation with `save` needs none: its hash is then
|
|
26
|
+
* `fingerprint` of what `save` returns, which covers everything saved.
|
|
27
|
+
* Give your own to hash less than that, for speed; a snapshot is then
|
|
28
|
+
* checked only as far as your hash goes.
|
|
29
|
+
*/
|
|
30
|
+
hash?(sim: Sim): string | number;
|
|
31
|
+
/** How often to report the hash, in turns. Defaults to 20. */
|
|
32
|
+
hashEvery?: number;
|
|
33
|
+
/**
|
|
34
|
+
* How many turns to hold back so that the simulation advances at an even
|
|
35
|
+
* pace when the network delivers turns unevenly. Defaults to 1, which adds
|
|
36
|
+
* one turn of delay and absorbs up to one turn of jitter. 0 applies every
|
|
37
|
+
* turn the moment it arrives.
|
|
38
|
+
*/
|
|
39
|
+
bufferTurns?: number;
|
|
40
|
+
/** The simulation advanced to `turn`. Not called while catching up after (re)connecting. */
|
|
41
|
+
onTurn?(sim: Sim, turn: number): void;
|
|
42
|
+
/** The simulation has caught up with the room and is live. */
|
|
43
|
+
onReady?(sim: Sim, turn: number): void;
|
|
44
|
+
/** Two players' simulations differed at `turn`. */
|
|
45
|
+
onDesync?(turn: number): void;
|
|
46
|
+
/** The connection's status changed: see `RoomClientOptions.onStatus`. */
|
|
47
|
+
onStatus?(status: ConnectionStatus, detail?: CloseDetail): void;
|
|
48
|
+
/**
|
|
49
|
+
* Supplies the join token, instead of putting one in the URL: see
|
|
50
|
+
* `RoomClientOptions.token`. Also asked before the recording is loaded.
|
|
51
|
+
*/
|
|
52
|
+
token?: TokenSource;
|
|
53
|
+
/** Ask the room for its patches in binary: see `RoomClientOptions.binary`. */
|
|
54
|
+
binary?: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* How to load the recording when (re)connecting. Defaults to `fetch` on
|
|
57
|
+
* the room's `/replay` URL. The URL says what the client has already, and
|
|
58
|
+
* the room may answer with only the rest: see `CatchUp`.
|
|
59
|
+
*/
|
|
60
|
+
loadReplay?(url: string): Promise<Replay<Input> | CatchUp<Input>>;
|
|
61
|
+
/** How to send the room a snapshot. Defaults to a `POST` of `data` to `url` with `fetch`. */
|
|
62
|
+
sendSnapshot?(url: string, data: string): Promise<unknown>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Plays in a lockstep room: sends this player's inputs, and runs the
|
|
67
|
+
* simulation over the turns the room sends back.
|
|
68
|
+
*
|
|
69
|
+
* On every (re)connect the simulation catches up with the room and then
|
|
70
|
+
* follows the live turns, so a reload or a dropped connection ends up in
|
|
71
|
+
* exactly the same state as everyone else. A client that still has its
|
|
72
|
+
* simulation is sent the turns it missed. One that has none starts from the
|
|
73
|
+
* room's latest snapshot if the simulation has `save`, `load` and `hash`,
|
|
74
|
+
* and from turn 1 of the recording otherwise.
|
|
75
|
+
*
|
|
76
|
+
* In a room whose `turnClock` is `"players"` the client also keeps time for
|
|
77
|
+
* it: one player's client at a time asks the room for each turn as it falls
|
|
78
|
+
* due, and the others stand by to take over. There is nothing to set up.
|
|
79
|
+
*/
|
|
80
|
+
export class LockstepClient<Input = unknown, Sim = unknown> {
|
|
81
|
+
#sim: Sim | undefined;
|
|
82
|
+
#turn = 0;
|
|
83
|
+
#ready = false;
|
|
84
|
+
|
|
85
|
+
readonly #room: RoomClient<LockstepView<Input>, unknown>;
|
|
86
|
+
readonly #options: LockstepClientOptions<Input, Sim>;
|
|
87
|
+
/** The hash to report: the game's own, or a fingerprint of what `save` returns. */
|
|
88
|
+
readonly #hash: ((sim: Sim) => string) | undefined;
|
|
89
|
+
readonly #replayUrl: string;
|
|
90
|
+
readonly #snapshotUrl: string;
|
|
91
|
+
/** The room's id, which is what a token is asked for. */
|
|
92
|
+
readonly #roomId: string;
|
|
93
|
+
/** Live turns that arrived while the recording was loading. */
|
|
94
|
+
#buffer = new Map<number, TurnEntry<Input>[]>();
|
|
95
|
+
/** Plays live turns out evenly. Created once the turn rate is known. */
|
|
96
|
+
#pacer: TurnPacer<{ turn: number; entries: TurnEntry<Input>[] }> | undefined;
|
|
97
|
+
/** The latest turn received, which can be ahead of the one the simulation is at. */
|
|
98
|
+
#received = 0;
|
|
99
|
+
#needsSync = true;
|
|
100
|
+
/** Guards against an older catch-up finishing after a newer one started. */
|
|
101
|
+
#syncId = 0;
|
|
102
|
+
#desyncReported = false;
|
|
103
|
+
/** The run of the room the simulation was built in: see `CatchUp.epoch`. */
|
|
104
|
+
#epoch: string | undefined;
|
|
105
|
+
/** Turns between snapshots, as the room says. 0 when it keeps none. */
|
|
106
|
+
#snapshotEvery = 0;
|
|
107
|
+
/** The turn of a snapshot that did not load into what its hash promised. None that old is asked for again. */
|
|
108
|
+
#distrusted = 0;
|
|
109
|
+
/** The room sleeps between turns and closes them when a player asks. */
|
|
110
|
+
#clocked = false;
|
|
111
|
+
/** This client is the one asking, because the latest turns were closed at its request. */
|
|
112
|
+
#asking = false;
|
|
113
|
+
#askTimer: ReturnType<typeof setTimeout> | undefined;
|
|
114
|
+
/** When the pending request is due, when the last one was due, and when turns last arrived. */
|
|
115
|
+
#askAt = 0;
|
|
116
|
+
#askedAt = 0;
|
|
117
|
+
#turnsAt = 0;
|
|
118
|
+
|
|
119
|
+
constructor(url: string | URL, options: LockstepClientOptions<Input, Sim>) {
|
|
120
|
+
this.#options = options;
|
|
121
|
+
const { hash, save } = options;
|
|
122
|
+
this.#hash = hash ? (sim) => String(hash(sim)) : save ? (sim) => fingerprint(save(sim)) : undefined;
|
|
123
|
+
const replay = new URL(String(url));
|
|
124
|
+
replay.protocol = replay.protocol === "wss:" ? "https:" : "http:";
|
|
125
|
+
replay.pathname = `${replay.pathname.replace(/\/+$/, "")}/replay`;
|
|
126
|
+
this.#replayUrl = replay.toString();
|
|
127
|
+
const snapshot = new URL(replay);
|
|
128
|
+
snapshot.pathname = snapshot.pathname.replace(/replay$/, "snapshot");
|
|
129
|
+
this.#snapshotUrl = snapshot.toString();
|
|
130
|
+
this.#roomId = roomIn(String(url));
|
|
131
|
+
|
|
132
|
+
this.#room = new RoomClient<LockstepView<Input>, unknown>(url, {
|
|
133
|
+
onStatus: (status, detail) => {
|
|
134
|
+
if (status !== "open") {
|
|
135
|
+
this.#ready = false;
|
|
136
|
+
this.#pacer?.clear();
|
|
137
|
+
this.#asking = false;
|
|
138
|
+
this.#scheduleAsk();
|
|
139
|
+
}
|
|
140
|
+
if (status === "open") this.#needsSync = true;
|
|
141
|
+
options.onStatus?.(status, detail);
|
|
142
|
+
},
|
|
143
|
+
token: options.token,
|
|
144
|
+
...(options.binary ? { binary: true } : {}),
|
|
145
|
+
onState: (view) => this.#receive(view),
|
|
146
|
+
onMessage: (message) => this.#turns(message),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The simulation. Undefined until the first catch-up finishes. */
|
|
151
|
+
get sim(): Sim | undefined {
|
|
152
|
+
return this.#sim;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The turn the simulation is at. */
|
|
156
|
+
get turn(): number {
|
|
157
|
+
return this.#turn;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** True once the simulation has caught up with the room. */
|
|
161
|
+
get ready(): boolean {
|
|
162
|
+
return this.#ready;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Where the connection stands. */
|
|
166
|
+
get status(): ConnectionStatus {
|
|
167
|
+
return this.#room.status;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** This player's id, as the server knows it. Set once connected. */
|
|
171
|
+
get you(): string | undefined {
|
|
172
|
+
return this.#room.you;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Send an input. It takes effect in the turn the room puts it in, for everyone at once. */
|
|
176
|
+
input(input: Input): Promise<void> {
|
|
177
|
+
return this.#room.send({ k: "i", d: input });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Give up the seat. Every simulation sees the player leave in the same turn. See `RoomClient.leave`. */
|
|
181
|
+
leave(): Promise<void> {
|
|
182
|
+
return this.#room.leave();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Close the connection for good, keeping the seat. No reconnect follows. */
|
|
186
|
+
close(): void {
|
|
187
|
+
this.#pacer?.clear();
|
|
188
|
+
this.#room.close();
|
|
189
|
+
this.#scheduleAsk();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#receive(view: LockstepView<Input>): void {
|
|
193
|
+
if (view.desync && !this.#desyncReported) {
|
|
194
|
+
this.#desyncReported = true;
|
|
195
|
+
this.#options.onDesync?.(view.desync.turn);
|
|
196
|
+
}
|
|
197
|
+
this.#snapshotEvery = view.snapshotEvery ?? 0;
|
|
198
|
+
if (this.#needsSync) {
|
|
199
|
+
this.#needsSync = false;
|
|
200
|
+
this.#buffer.clear();
|
|
201
|
+
void this.#catchUp();
|
|
202
|
+
}
|
|
203
|
+
if (view.clock === "players") {
|
|
204
|
+
// This room's turns arrive as messages, when someone has asked for them: see `#turns`.
|
|
205
|
+
if (!this.#clocked) {
|
|
206
|
+
this.#clocked = true;
|
|
207
|
+
this.#turnsAt = Date.now();
|
|
208
|
+
}
|
|
209
|
+
this.#scheduleAsk();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
this.#take(view.turn, 1, view.entries);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Turns `first` to `first + count - 1` have arrived. All are empty but the last, which has `entries`. */
|
|
216
|
+
#take(first: number, count: number, entries: TurnEntry<Input>[]): void {
|
|
217
|
+
const last = first + count - 1;
|
|
218
|
+
const of = (turn: number) => (turn === last ? entries : []);
|
|
219
|
+
if (!this.#ready) {
|
|
220
|
+
for (let turn = first; turn <= last; turn++) this.#buffer.set(turn, of(turn));
|
|
221
|
+
} else if (first > this.#received + 1) {
|
|
222
|
+
// A turn went missing. Start over from the recording.
|
|
223
|
+
this.#ready = false;
|
|
224
|
+
this.#pacer?.clear();
|
|
225
|
+
this.#buffer.clear();
|
|
226
|
+
void this.#catchUp();
|
|
227
|
+
} else {
|
|
228
|
+
for (let turn = this.#received + 1; turn <= last; turn++) {
|
|
229
|
+
this.#received = turn;
|
|
230
|
+
this.#pacer?.push({ turn, entries: of(turn) });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** A room that sleeps between turns has closed some. */
|
|
236
|
+
#turns(message: unknown): void {
|
|
237
|
+
const turns = message as Partial<TurnsMessage<Input>> | null;
|
|
238
|
+
if (turns?.tickflare !== "turns" || !Number.isSafeInteger(turns.n) || !Number.isSafeInteger(turns.c)) return;
|
|
239
|
+
this.#turnsAt = Date.now();
|
|
240
|
+
// Whoever's request closed them keeps asking. Turns closed for another reason change nothing.
|
|
241
|
+
if (turns.b !== undefined) this.#asking = turns.b === this.#room.you;
|
|
242
|
+
this.#scheduleAsk();
|
|
243
|
+
this.#take(turns.n!, turns.c!, turns.e ?? []);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Arms the next request for turns. The client that is asking does so once
|
|
248
|
+
* a turn, on its own clock. The others wait for turns to stop arriving,
|
|
249
|
+
* each a little longer than the one before it, so that one takes over.
|
|
250
|
+
*/
|
|
251
|
+
#scheduleAsk(): void {
|
|
252
|
+
if (this.#askTimer !== undefined) clearTimeout(this.#askTimer);
|
|
253
|
+
this.#askTimer = undefined;
|
|
254
|
+
if (!this.#clocked || this.#room.status !== "open") return;
|
|
255
|
+
const turnMs = 1000 / (this.#room.tickRate || 10);
|
|
256
|
+
if (this.#asking) {
|
|
257
|
+
this.#askAt = this.#askedAt + turnMs;
|
|
258
|
+
} else {
|
|
259
|
+
const connected = this.#room.players.filter((player) => player.connected).map((player) => player.id).sort();
|
|
260
|
+
const place = Math.max(0, connected.indexOf(this.#room.you ?? ""));
|
|
261
|
+
this.#askAt = Math.max(this.#turnsAt, this.#askedAt) + turnMs * (1.5 + 0.4 * place);
|
|
262
|
+
}
|
|
263
|
+
this.#askTimer = setTimeout(() => {
|
|
264
|
+
// From when it was due, not from when the timer got round to it: lateness must not add up.
|
|
265
|
+
this.#askedAt = Math.max(this.#askAt, Date.now() - turnMs);
|
|
266
|
+
this.#room.send({ k: "t" }).catch(() => {});
|
|
267
|
+
this.#scheduleAsk();
|
|
268
|
+
}, Math.max(0, this.#askAt - Date.now()));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async #catchUp(): Promise<void> {
|
|
272
|
+
const id = ++this.#syncId;
|
|
273
|
+
const { token, load } = this.#options;
|
|
274
|
+
const hash = this.#hash;
|
|
275
|
+
// What the room is told: the turn this simulation is at and the run of the room it got there
|
|
276
|
+
// in, and whether a snapshot would be of use.
|
|
277
|
+
const mine = this.#sim !== undefined && this.#epoch !== undefined ? this.#turn : 0;
|
|
278
|
+
const asked = new URL(this.#replayUrl);
|
|
279
|
+
asked.searchParams.set("since", String(mine));
|
|
280
|
+
if (mine > 0) asked.searchParams.set("epoch", this.#epoch!);
|
|
281
|
+
if (load && hash) asked.searchParams.set("snapshot", String(this.#distrusted));
|
|
282
|
+
let answer: CatchUp<Input>;
|
|
283
|
+
try {
|
|
284
|
+
const url = token ? await withFreshToken(asked.toString(), this.#roomId, token) : asked.toString();
|
|
285
|
+
answer = await (this.#options.loadReplay ?? loadReplay)(url);
|
|
286
|
+
} catch (err) {
|
|
287
|
+
console.warn("[tickflare] could not load the recording; retrying on the next turn", err);
|
|
288
|
+
if (id === this.#syncId) this.#needsSync = true;
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (id !== this.#syncId) return;
|
|
292
|
+
|
|
293
|
+
let sim: Sim;
|
|
294
|
+
let from = 0;
|
|
295
|
+
if (answer.snapshot && load && hash) {
|
|
296
|
+
// Somebody else's simulation. It is taken only if it hashes to what the players agreed on.
|
|
297
|
+
let loaded: Sim | undefined;
|
|
298
|
+
try {
|
|
299
|
+
const candidate = load(JSON.parse(answer.snapshot.data));
|
|
300
|
+
if (hash(candidate) === answer.snapshot.hash) loaded = candidate;
|
|
301
|
+
} catch {
|
|
302
|
+
// Not something `load` can read: the same as a wrong hash.
|
|
303
|
+
}
|
|
304
|
+
if (loaded === undefined) {
|
|
305
|
+
console.warn(`[tickflare] the snapshot of turn ${answer.snapshot.turn} did not load into what its hash says; catching up without it`);
|
|
306
|
+
const again = answer.snapshot.turn <= this.#distrusted;
|
|
307
|
+
this.#distrusted = Math.max(this.#distrusted, answer.snapshot.turn);
|
|
308
|
+
// Sent the one it said it had no use for: asking again at once would only repeat that.
|
|
309
|
+
if (again) this.#needsSync = true;
|
|
310
|
+
else await this.#catchUp();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
sim = loaded;
|
|
314
|
+
from = answer.snapshot.turn;
|
|
315
|
+
} else if (answer.from !== undefined && answer.from > 0) {
|
|
316
|
+
if (answer.from !== mine) {
|
|
317
|
+
// The end of a recording, and nothing it continues from. Ask for all of it.
|
|
318
|
+
this.#epoch = undefined;
|
|
319
|
+
if (mine === 0) this.#needsSync = true;
|
|
320
|
+
else await this.#catchUp();
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
sim = this.#sim as Sim;
|
|
324
|
+
from = mine;
|
|
325
|
+
} else {
|
|
326
|
+
sim = this.#options.create(answer.seed);
|
|
327
|
+
}
|
|
328
|
+
stepThrough(sim, answer, this.#options, from);
|
|
329
|
+
this.#sim = sim;
|
|
330
|
+
this.#epoch = answer.epoch;
|
|
331
|
+
this.#turn = Math.max(answer.turn, from);
|
|
332
|
+
// Turns that arrived while the recording was loading continue where it ends.
|
|
333
|
+
for (let turn = this.#turn + 1; this.#buffer.has(turn); turn++) {
|
|
334
|
+
this.#advance(this.#buffer.get(turn)!, turn, false);
|
|
335
|
+
}
|
|
336
|
+
this.#buffer.clear();
|
|
337
|
+
this.#received = this.#turn;
|
|
338
|
+
this.#pacer?.clear();
|
|
339
|
+
this.#pacer = new TurnPacer(
|
|
340
|
+
1000 / (this.#room.tickRate || 10),
|
|
341
|
+
this.#options.bufferTurns ?? 1,
|
|
342
|
+
({ turn, entries }) => this.#advance(entries, turn, true),
|
|
343
|
+
);
|
|
344
|
+
this.#ready = true;
|
|
345
|
+
this.#options.onReady?.(this.#sim, this.#turn);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
#advance(entries: TurnEntry<Input>[], turn: number, live: boolean): void {
|
|
349
|
+
const sim = this.#sim as Sim;
|
|
350
|
+
this.#options.step(sim, entries, turn);
|
|
351
|
+
this.#turn = turn;
|
|
352
|
+
const { hashEvery = 20, save, load } = this.#options;
|
|
353
|
+
const hash = this.#hash;
|
|
354
|
+
// A turn a snapshot can be of is one every client reports, so that the room can tell whether
|
|
355
|
+
// the players agree on what the snapshot holds.
|
|
356
|
+
const snapshot = this.#snapshotEvery > 0 && turn % this.#snapshotEvery === 0;
|
|
357
|
+
// Only live turns are reported: hashes of old turns have nobody left to be compared with.
|
|
358
|
+
if (live && hash && (snapshot || turn % hashEvery === 0)) {
|
|
359
|
+
const data = snapshot && save && load && this.#sendsSnapshots() ? JSON.stringify(save(sim)) : undefined;
|
|
360
|
+
// With no hash of the game's own, the text about to be sent is the text to fingerprint.
|
|
361
|
+
const reported = data !== undefined && !this.#options.hash ? fingerprintOfText(data) : hash(sim);
|
|
362
|
+
this.#room.send({ k: "h", n: turn, h: reported }).catch(() => {});
|
|
363
|
+
if (data !== undefined) void this.#sendSnapshot(data, turn, reported);
|
|
364
|
+
}
|
|
365
|
+
if (live) this.#options.onTurn?.(sim, turn);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** One client sends the snapshots: that of the connected player whose id sorts first. */
|
|
369
|
+
#sendsSnapshots(): boolean {
|
|
370
|
+
const connected = this.#room.players.filter((player) => player.connected).map((player) => player.id).sort();
|
|
371
|
+
return connected[0] === this.#room.you;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Sends the room this simulation as it stood after `turn`. The room may have no use for it: that is not an error. */
|
|
375
|
+
async #sendSnapshot(data: string, turn: number, hash: string): Promise<void> {
|
|
376
|
+
try {
|
|
377
|
+
const to = new URL(this.#snapshotUrl);
|
|
378
|
+
to.searchParams.set("turn", String(turn));
|
|
379
|
+
to.searchParams.set("hash", hash);
|
|
380
|
+
const { token } = this.#options;
|
|
381
|
+
const url = token ? await withFreshToken(to.toString(), this.#roomId, token) : to.toString();
|
|
382
|
+
await (this.#options.sendSnapshot ?? sendSnapshot)(url, data);
|
|
383
|
+
} catch (err) {
|
|
384
|
+
console.warn("[tickflare] could not send a snapshot; the next one is tried as usual", err);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function loadReplay<Input>(url: string): Promise<CatchUp<Input>> {
|
|
390
|
+
const response = await fetch(url);
|
|
391
|
+
if (!response.ok) throw new Error(`Replay request failed with ${response.status}`);
|
|
392
|
+
return (await response.json()) as CatchUp<Input>;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function sendSnapshot(url: string, data: string): Promise<void> {
|
|
396
|
+
// Sent as plain text, so that a page on another origin needs no preflight for it.
|
|
397
|
+
await fetch(url, { method: "POST", body: data });
|
|
398
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { PING, type MatchFound } from "../protocol.js";
|
|
2
|
+
import { roomIn, withFreshToken, type TokenSource } from "./token.js";
|
|
3
|
+
|
|
4
|
+
/** How long to wait and how to authenticate. Both are optional. */
|
|
5
|
+
export interface FindMatchOptions {
|
|
6
|
+
/** Abort to stop waiting. The promise then rejects with the signal's reason. */
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
/**
|
|
9
|
+
* Supplies the join token, as `RoomClientOptions.token` does for rooms. It
|
|
10
|
+
* is called with the queue's name, and what it returns is sent as the
|
|
11
|
+
* `token` query parameter.
|
|
12
|
+
*/
|
|
13
|
+
token?: TokenSource;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Wait in a matchmaking queue. Resolves with the room to connect to and the
|
|
18
|
+
* players in it once the matchmaker has put a match together.
|
|
19
|
+
*
|
|
20
|
+
* const { room } = await findMatch("wss://my-game.example/matchmaking/ranked");
|
|
21
|
+
* const client = new RoomClient(`wss://my-game.example/rooms/${room}`);
|
|
22
|
+
*/
|
|
23
|
+
export async function findMatch(url: string | URL, options: FindMatchOptions = {}): Promise<MatchFound> {
|
|
24
|
+
const { signal, token } = options;
|
|
25
|
+
signal?.throwIfAborted();
|
|
26
|
+
let target = String(url);
|
|
27
|
+
if (token) target = await withFreshToken(target, roomIn(target), token);
|
|
28
|
+
signal?.throwIfAborted();
|
|
29
|
+
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const socket = new WebSocket(target);
|
|
32
|
+
let found: MatchFound | undefined;
|
|
33
|
+
let settled = false;
|
|
34
|
+
const ping = setInterval(() => {
|
|
35
|
+
if (socket.readyState === 1) socket.send(PING);
|
|
36
|
+
}, 25_000);
|
|
37
|
+
const abort = () => socket.close(1000, "cancelled");
|
|
38
|
+
signal?.addEventListener("abort", abort);
|
|
39
|
+
|
|
40
|
+
const finish = (code: number, reason: string) => {
|
|
41
|
+
if (settled) return;
|
|
42
|
+
settled = true;
|
|
43
|
+
clearInterval(ping);
|
|
44
|
+
signal?.removeEventListener("abort", abort);
|
|
45
|
+
if (found) resolve(found);
|
|
46
|
+
else if (signal?.aborted) reject(signal.reason);
|
|
47
|
+
else reject(new Error(`Matchmaking ended without a match (${code} ${reason})`));
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
socket.addEventListener("message", (event) => {
|
|
51
|
+
if (typeof event.data !== "string" || !event.data.startsWith("{")) return;
|
|
52
|
+
const message = JSON.parse(event.data) as MatchFound;
|
|
53
|
+
if (message.t === "match") found = message;
|
|
54
|
+
});
|
|
55
|
+
socket.addEventListener("close", (event) => finish(event.code, event.reason));
|
|
56
|
+
// A socket turned away before it opened may never report a close (Node's does not).
|
|
57
|
+
socket.addEventListener("error", () => {
|
|
58
|
+
if (socket.readyState === 0) finish(1006, "");
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plays items out at a steady pace, however unevenly they arrive.
|
|
3
|
+
*
|
|
4
|
+
* Lockstep turns leave the room at a fixed rate, but a real network delivers
|
|
5
|
+
* them in fits: two together, then a gap. Applying them as they arrive makes
|
|
6
|
+
* the game stutter. The pacer holds a small reserve and releases one item per
|
|
7
|
+
* interval, so the simulation advances evenly. When a hiccup leaves more
|
|
8
|
+
* waiting than the reserve is meant to hold, it plays at double speed until
|
|
9
|
+
* the surplus is gone, instead of keeping it as extra delay for good.
|
|
10
|
+
*/
|
|
11
|
+
export class TurnPacer<T> {
|
|
12
|
+
readonly #intervalMs: number;
|
|
13
|
+
readonly #reserve: number;
|
|
14
|
+
readonly #play: (item: T) => void;
|
|
15
|
+
#queue: T[] = [];
|
|
16
|
+
#timer: ReturnType<typeof setTimeout> | undefined;
|
|
17
|
+
/** When the next item is due, in epoch milliseconds. */
|
|
18
|
+
#dueAt = 0;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param intervalMs time between items at the source
|
|
22
|
+
* @param reserve how many intervals to hold an item back when starting from empty
|
|
23
|
+
* @param play called for each item, in order
|
|
24
|
+
*/
|
|
25
|
+
constructor(intervalMs: number, reserve: number, play: (item: T) => void) {
|
|
26
|
+
this.#intervalMs = intervalMs;
|
|
27
|
+
this.#reserve = Math.max(0, reserve);
|
|
28
|
+
this.#play = play;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
push(item: T): void {
|
|
32
|
+
if (this.#reserve === 0) {
|
|
33
|
+
// No reserve asked for: pass straight through.
|
|
34
|
+
this.#play(item);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
this.#queue.push(item);
|
|
38
|
+
if (this.#timer === undefined) {
|
|
39
|
+
// Starting, or ran dry: build the reserve up again before playing.
|
|
40
|
+
this.#dueAt = Date.now() + this.#intervalMs * this.#reserve;
|
|
41
|
+
this.#arm();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Drop everything waiting and stop. */
|
|
46
|
+
clear(): void {
|
|
47
|
+
this.#queue = [];
|
|
48
|
+
if (this.#timer !== undefined) clearTimeout(this.#timer);
|
|
49
|
+
this.#timer = undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
#arm(): void {
|
|
53
|
+
this.#timer = setTimeout(() => this.#release(), Math.max(0, this.#dueAt - Date.now()));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#release(): void {
|
|
57
|
+
this.#timer = undefined;
|
|
58
|
+
const item = this.#queue.shift();
|
|
59
|
+
// Nothing arrived in time: wait for the next push, which rebuilds the reserve.
|
|
60
|
+
if (item === undefined) return;
|
|
61
|
+
this.#play(item);
|
|
62
|
+
// Keep to the clock, not to "now", so timer lateness does not add up.
|
|
63
|
+
const surplus = this.#queue.length > this.#reserve;
|
|
64
|
+
this.#dueAt += surplus ? this.#intervalMs / 2 : this.#intervalMs;
|
|
65
|
+
this.#arm();
|
|
66
|
+
}
|
|
67
|
+
}
|