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,631 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client side: connecting to rooms, lockstep, matchmaking, accounts and
|
|
3
|
+
* smoothing. Runs in browsers, Node and anywhere with a global `WebSocket`
|
|
4
|
+
* and `fetch`.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
* @module tickflare/client
|
|
8
|
+
*/
|
|
9
|
+
import { BINARY_PATCHES, decodePatchFrame } from "../binary.js";
|
|
10
|
+
import { applyPatch } from "../patch.js";
|
|
11
|
+
import { ServerClock, localNow } from "./clock.js";
|
|
12
|
+
import { roomIn, withFreshToken, type TokenSource } from "./token.js";
|
|
13
|
+
import {
|
|
14
|
+
CloseCode,
|
|
15
|
+
PING,
|
|
16
|
+
PONG,
|
|
17
|
+
PROTOCOL_VERSION,
|
|
18
|
+
isFatalCloseCode,
|
|
19
|
+
type ClientMessage,
|
|
20
|
+
type Player,
|
|
21
|
+
type ServerMessage,
|
|
22
|
+
} from "../protocol.js";
|
|
23
|
+
|
|
24
|
+
export { CloseCode, type MatchFound, type Player } from "../protocol.js";
|
|
25
|
+
export { findMatch, type FindMatchOptions } from "./matchmaking.js";
|
|
26
|
+
export type { TokenSource } from "./token.js";
|
|
27
|
+
export {
|
|
28
|
+
AccountClient,
|
|
29
|
+
AccountRequestError,
|
|
30
|
+
type Account,
|
|
31
|
+
type AccountClientOptions,
|
|
32
|
+
type Guest,
|
|
33
|
+
type KeyValueStore,
|
|
34
|
+
type Leaderboard,
|
|
35
|
+
type LeaderboardLine,
|
|
36
|
+
type Profile,
|
|
37
|
+
} from "./accounts.js";
|
|
38
|
+
export { Interpolator } from "./interpolate.js";
|
|
39
|
+
export { ServerClock } from "./clock.js";
|
|
40
|
+
export { BufferedInterpolator, type BufferedInterpolatorOptions, type TickSource } from "./buffered.js";
|
|
41
|
+
export { Predictor, type PredictorOptions } from "./predict.js";
|
|
42
|
+
export { produce } from "./draft.js";
|
|
43
|
+
export { decodePatchFrame } from "../binary.js";
|
|
44
|
+
export { LockstepClient, type LockstepClientOptions } from "./lockstep.js";
|
|
45
|
+
export {
|
|
46
|
+
fingerprint,
|
|
47
|
+
runReplay,
|
|
48
|
+
seededRandom,
|
|
49
|
+
stepThrough,
|
|
50
|
+
type CatchUp,
|
|
51
|
+
type LockstepView,
|
|
52
|
+
type TurnsMessage,
|
|
53
|
+
type Replay,
|
|
54
|
+
type SeededRandom,
|
|
55
|
+
type Simulation,
|
|
56
|
+
type Snapshot,
|
|
57
|
+
type TurnEntry,
|
|
58
|
+
} from "../lockstep.js";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Where a connection stands. `connecting` covers the first attempt and every
|
|
62
|
+
* reconnect; `closed` is final.
|
|
63
|
+
*/
|
|
64
|
+
export type ConnectionStatus = "connecting" | "open" | "closed";
|
|
65
|
+
|
|
66
|
+
/** Why a connection closed: the WebSocket close code and reason. */
|
|
67
|
+
export interface CloseDetail {
|
|
68
|
+
/** The WebSocket close code, e.g. `CloseCode.RoomFull`, or 1006 for a connection that was lost. */
|
|
69
|
+
code: number;
|
|
70
|
+
/** The close reason, e.g. `room_full`, or what the room passed to `removePlayer`. */
|
|
71
|
+
reason: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** What a `RoomClient` reports, for `on(event, listener)`. Each is also an `on…` option. */
|
|
75
|
+
export interface RoomClientEvents<View> {
|
|
76
|
+
/** See `RoomClientOptions.onState`. */
|
|
77
|
+
state(state: View, seq: number): void;
|
|
78
|
+
/** See `RoomClientOptions.onPresence`. */
|
|
79
|
+
presence(players: Player[]): void;
|
|
80
|
+
/** See `RoomClientOptions.onMessage`. */
|
|
81
|
+
message(message: unknown): void;
|
|
82
|
+
/** See `RoomClientOptions.onStatus`. */
|
|
83
|
+
status(status: ConnectionStatus, detail?: CloseDetail): void;
|
|
84
|
+
/** See `RoomClientOptions.onMoved`. */
|
|
85
|
+
moved(roomId: string): void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** What a `RoomClient` reports and how it connects. Every option has a default. */
|
|
89
|
+
export interface RoomClientOptions<View> {
|
|
90
|
+
/**
|
|
91
|
+
* The state changed, or was received for the first time after (re)connecting.
|
|
92
|
+
* Every call gets a new object; parts that did not change are the same
|
|
93
|
+
* objects as before, so they can be compared by reference.
|
|
94
|
+
*/
|
|
95
|
+
onState?(state: View, seq: number): void;
|
|
96
|
+
/** Someone joined, dropped or came back. */
|
|
97
|
+
onPresence?(players: Player[]): void;
|
|
98
|
+
/** A message the room sent with `send` or `broadcast`. */
|
|
99
|
+
onMessage?(message: unknown): void;
|
|
100
|
+
/**
|
|
101
|
+
* `closed` carries the close code and reason, e.g. when the room was full
|
|
102
|
+
* or the seat was removed. So does `connecting` when it follows a
|
|
103
|
+
* connection that was lost or never opened: it is called again for every
|
|
104
|
+
* failed attempt. A client that keeps failing this way while the network is
|
|
105
|
+
* fine is being turned away before it reaches the room, most often because
|
|
106
|
+
* the join token in its URL has expired: see `token`.
|
|
107
|
+
*/
|
|
108
|
+
onStatus?(status: ConnectionStatus, detail?: CloseDetail): void;
|
|
109
|
+
/**
|
|
110
|
+
* Supplies the join token, instead of putting one in the URL. It is called
|
|
111
|
+
* before every connection attempt (the first, every reconnect, and when the
|
|
112
|
+
* room hands the player to another room) with the id of the room being
|
|
113
|
+
* connected to, and what it returns is sent as the `token` query parameter,
|
|
114
|
+
* where `tokenAuth` reads it.
|
|
115
|
+
*
|
|
116
|
+
* Use it whenever tokens expire: a token in the URL is fixed for the life
|
|
117
|
+
* of the client, so once it has run out the client can no longer
|
|
118
|
+
* reconnect. Return the token you have while it is still good and fetch a
|
|
119
|
+
* new one when it is not. If this throws, the attempt counts as failed
|
|
120
|
+
* (`onStatus` gets `connecting` with the reason `token_failed`) and is
|
|
121
|
+
* tried again like any other.
|
|
122
|
+
*/
|
|
123
|
+
token?: TokenSource;
|
|
124
|
+
/** The room handed this player to another room, and the client is now connecting there. */
|
|
125
|
+
onMoved?(roomId: string): void;
|
|
126
|
+
/** Reconnect after an unexpected close. Defaults to true. */
|
|
127
|
+
reconnect?: boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Ask the room for its patches in binary. Off by default, and better left
|
|
130
|
+
* off in a browser or in Node: there the connection is compressed, and
|
|
131
|
+
* binary frames are a few percent smaller than JSON ones at best, and not
|
|
132
|
+
* readable in the developer tools. It is for a client whose WebSocket is
|
|
133
|
+
* not compressed, and here so that the format has a client to be tested
|
|
134
|
+
* with. A room that does not know the format sends JSON, which is read as
|
|
135
|
+
* always.
|
|
136
|
+
*/
|
|
137
|
+
binary?: boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Keepalive interval in milliseconds. Defaults to 25 seconds; 0 disables
|
|
140
|
+
* it. A connection that goes a whole interval without answering is taken
|
|
141
|
+
* for dead and replaced.
|
|
142
|
+
*/
|
|
143
|
+
pingIntervalMs?: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A command on its way: sent, and not yet shown by the room's state. */
|
|
147
|
+
export interface SentCommand<Command = unknown> {
|
|
148
|
+
/** The number it was sent under. They go up with every command. */
|
|
149
|
+
id: number;
|
|
150
|
+
/** The command. */
|
|
151
|
+
command: Command;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A command or leave the room refused, or one that was in flight when the connection dropped. */
|
|
155
|
+
export class CommandRejected extends Error {
|
|
156
|
+
/** What the room passed to `reject()`, or `not_connected` or `disconnected`. */
|
|
157
|
+
readonly reason: string;
|
|
158
|
+
|
|
159
|
+
constructor(reason: string) {
|
|
160
|
+
super(`Command rejected: ${reason}`);
|
|
161
|
+
this.name = "CommandRejected";
|
|
162
|
+
this.reason = reason;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const MAX_BACKOFF_MS = 5_000;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A connection to one room. Holds the latest state the server sent and
|
|
170
|
+
* reconnects on its own; after a reconnect the server sends the current state
|
|
171
|
+
* again, so there is nothing to replay.
|
|
172
|
+
*/
|
|
173
|
+
export class RoomClient<View = unknown, Command = unknown> {
|
|
174
|
+
#state: View | undefined;
|
|
175
|
+
#seq = 0;
|
|
176
|
+
#tick = 0;
|
|
177
|
+
#tickRate = 0;
|
|
178
|
+
#you: string | undefined;
|
|
179
|
+
#players: Player[] = [];
|
|
180
|
+
#status: ConnectionStatus = "connecting";
|
|
181
|
+
#listeners = new Map<keyof RoomClientEvents<View>, Set<(...args: never[]) => void>>();
|
|
182
|
+
|
|
183
|
+
#url: string;
|
|
184
|
+
readonly #options: RoomClientOptions<View>;
|
|
185
|
+
#socket: WebSocket | undefined;
|
|
186
|
+
#nextId = 1;
|
|
187
|
+
#pending = new Map<number, { resolve(): void; reject(error: Error): void }>();
|
|
188
|
+
/** Commands sent that `#state` does not show yet, oldest first. Replaced, never changed, so that it can be compared by reference. */
|
|
189
|
+
#unconfirmed: readonly SentCommand<Command>[] = [];
|
|
190
|
+
#attempt = 0;
|
|
191
|
+
#stopped = false;
|
|
192
|
+
#retryTimer: ReturnType<typeof setTimeout> | undefined;
|
|
193
|
+
#pingTimer: ReturnType<typeof setInterval> | undefined;
|
|
194
|
+
/** A keepalive was sent and nothing has come back since. */
|
|
195
|
+
#unanswered = false;
|
|
196
|
+
/** When each `ping` that has not been answered yet was sent, oldest first, by `localNow()`. */
|
|
197
|
+
#pingsAt: number[] = [];
|
|
198
|
+
/** Which tick the room is on, from what it says of its clock. */
|
|
199
|
+
readonly #clock = new ServerClock();
|
|
200
|
+
|
|
201
|
+
constructor(url: string | URL, options: RoomClientOptions<View> = {}) {
|
|
202
|
+
this.#url = String(url);
|
|
203
|
+
this.#options = options;
|
|
204
|
+
this.#open();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The latest state the room sent: this player's view. Undefined until the first one arrives. */
|
|
208
|
+
get state(): View | undefined {
|
|
209
|
+
return this.#state;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The room's change counter for `state`. It goes up by one with every change. */
|
|
213
|
+
get seq(): number {
|
|
214
|
+
return this.#seq;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Simulation ticks the room has run. Stays 0 in event mode. */
|
|
218
|
+
get tick(): number {
|
|
219
|
+
return this.#tick;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The room's simulation rate in ticks per second; 0 in event mode. */
|
|
223
|
+
get tickRate(): number {
|
|
224
|
+
return this.#tickRate;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The tick the room is on right now, by estimate, with the fraction of the
|
|
229
|
+
* next that has passed: for drawing the game in step with the room, or
|
|
230
|
+
* sending a command in time for a tick. Worked out from the clock the room
|
|
231
|
+
* sends (see `ClockFrame`) and the round trip to it, so it carries on
|
|
232
|
+
* between frames, and is usually ahead of `tick`, which is the latest the
|
|
233
|
+
* room has sent. While the room's simulation is stopped, the tick it
|
|
234
|
+
* stopped at. Undefined in event mode, before the room has said where its
|
|
235
|
+
* clock is, and with a room older than 0.2.
|
|
236
|
+
*
|
|
237
|
+
* @param now the moment to estimate it for, from `performance.now()`
|
|
238
|
+
*/
|
|
239
|
+
serverTick(now?: number): number | undefined {
|
|
240
|
+
return this.#clock.tick(now);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The round trip to the room in milliseconds, smoothed over the latest
|
|
245
|
+
* keepalives. Undefined until one has come back. In a ticking room the
|
|
246
|
+
* client measures it every few seconds; otherwise with the keepalive.
|
|
247
|
+
*/
|
|
248
|
+
get rtt(): number | undefined {
|
|
249
|
+
return this.#clock.rtt;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** This player's id, as the server knows it. Set once connected. */
|
|
253
|
+
get you(): string | undefined {
|
|
254
|
+
return this.#you;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Everyone with a seat in the room, in join order. */
|
|
258
|
+
get players(): Player[] {
|
|
259
|
+
return this.#players;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Where the connection stands. */
|
|
263
|
+
get status(): ConnectionStatus {
|
|
264
|
+
return this.#status;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The commands sent with `send` that `state` does not show yet, oldest
|
|
269
|
+
* first: the room has not applied them, or has and the news is on its way.
|
|
270
|
+
* A command leaves the list in the same moment `state` changes to show it,
|
|
271
|
+
* or when the room refuses it. `Predictor` draws them over `state`. The
|
|
272
|
+
* array is a new one whenever it changes.
|
|
273
|
+
*/
|
|
274
|
+
get unconfirmed(): readonly SentCommand<Command>[] {
|
|
275
|
+
return this.#unconfirmed;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Listen for `state`, `presence`, `message`, `status` or `moved`, in
|
|
280
|
+
* addition to the `on…` options. Returns a function that stops listening,
|
|
281
|
+
* which suits UI frameworks:
|
|
282
|
+
*
|
|
283
|
+
* useEffect(() => room.on("state", setState), [room]);
|
|
284
|
+
*/
|
|
285
|
+
on<E extends keyof RoomClientEvents<View>>(event: E, listener: RoomClientEvents<View>[E]): () => void {
|
|
286
|
+
let listeners = this.#listeners.get(event);
|
|
287
|
+
if (!listeners) this.#listeners.set(event, (listeners = new Set()));
|
|
288
|
+
const added = listener as (...args: never[]) => void;
|
|
289
|
+
listeners.add(added);
|
|
290
|
+
return () => {
|
|
291
|
+
listeners.delete(added);
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
#emit<E extends keyof RoomClientEvents<View>>(event: E, ...args: Parameters<RoomClientEvents<View>[E]>): void {
|
|
296
|
+
const option = {
|
|
297
|
+
state: this.#options.onState,
|
|
298
|
+
presence: this.#options.onPresence,
|
|
299
|
+
message: this.#options.onMessage,
|
|
300
|
+
status: this.#options.onStatus,
|
|
301
|
+
moved: this.#options.onMoved,
|
|
302
|
+
}[event] as ((...a: Parameters<RoomClientEvents<View>[E]>) => void) | undefined;
|
|
303
|
+
option?.(...args);
|
|
304
|
+
for (const listener of this.#listeners.get(event) ?? []) {
|
|
305
|
+
(listener as unknown as (...a: Parameters<RoomClientEvents<View>[E]>) => void)(...args);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Send a command. Resolves once the room applied it, by which time `state`
|
|
311
|
+
* already reflects it: at once in event mode, and with the next tick in a
|
|
312
|
+
* room that is ticking. Rejects with `CommandRejected` if the room refused
|
|
313
|
+
* it or the connection dropped first.
|
|
314
|
+
*/
|
|
315
|
+
send(command: Command): Promise<void> {
|
|
316
|
+
return this.#request((id) => {
|
|
317
|
+
this.#unconfirmed = [...this.#unconfirmed, { id, command }];
|
|
318
|
+
return { t: "cmd", id, data: command };
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Give up the seat in this room. Resolves once the room let the player go,
|
|
324
|
+
* after which it closes the connection and `status` becomes `closed`.
|
|
325
|
+
* Rejects with `CommandRejected` if the room made the player stay.
|
|
326
|
+
*/
|
|
327
|
+
leave(): Promise<void> {
|
|
328
|
+
return this.#request((id) => ({ t: "leave", id }));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Close the connection for good, keeping the seat. No reconnect follows. */
|
|
332
|
+
close(): void {
|
|
333
|
+
this.#stopped = true;
|
|
334
|
+
if (this.#retryTimer !== undefined) clearTimeout(this.#retryTimer);
|
|
335
|
+
const socket = this.#socket;
|
|
336
|
+
if (socket && socket.readyState < 2) {
|
|
337
|
+
socket.close(1000, "client_closed");
|
|
338
|
+
} else {
|
|
339
|
+
// Between reconnect attempts there is no socket left to report the close.
|
|
340
|
+
this.#setStatus("closed", { code: 1000, reason: "client_closed" });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
#request(frame: (id: number) => ClientMessage<Command>): Promise<void> {
|
|
345
|
+
const socket = this.#socket;
|
|
346
|
+
if (!socket || this.#status !== "open") {
|
|
347
|
+
return Promise.reject(new CommandRejected("not_connected"));
|
|
348
|
+
}
|
|
349
|
+
const id = this.#nextId++;
|
|
350
|
+
return new Promise<void>((resolve, reject) => {
|
|
351
|
+
this.#pending.set(id, { resolve, reject });
|
|
352
|
+
socket.send(JSON.stringify(frame(id)));
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
#open(): void {
|
|
357
|
+
this.#setStatus("connecting");
|
|
358
|
+
const { token } = this.#options;
|
|
359
|
+
if (!token) return this.#connect(this.#url);
|
|
360
|
+
|
|
361
|
+
withFreshToken(this.#url, roomIn(this.#url), token).then(
|
|
362
|
+
(url) => {
|
|
363
|
+
// close() may have been called while the token was on its way.
|
|
364
|
+
if (!this.#stopped) this.#connect(url);
|
|
365
|
+
},
|
|
366
|
+
(err) => {
|
|
367
|
+
if (this.#stopped) return;
|
|
368
|
+
console.warn("[tickflare] could not get a join token:", err);
|
|
369
|
+
this.#closed(1006, "token_failed");
|
|
370
|
+
},
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
#connect(url: string): void {
|
|
375
|
+
const { binary } = this.#options;
|
|
376
|
+
const asked = new URL(url);
|
|
377
|
+
// The version of the protocol this client speaks: the room answers with the one it will use.
|
|
378
|
+
asked.searchParams.set("v", String(PROTOCOL_VERSION));
|
|
379
|
+
if (binary) asked.searchParams.set("patches", BINARY_PATCHES);
|
|
380
|
+
url = asked.toString();
|
|
381
|
+
const socket = new WebSocket(url);
|
|
382
|
+
if (binary) socket.binaryType = "arraybuffer";
|
|
383
|
+
this.#socket = socket;
|
|
384
|
+
/** The keys the room has defined on this connection, by number. */
|
|
385
|
+
const keys: string[] = [];
|
|
386
|
+
|
|
387
|
+
socket.addEventListener("message", (event) => {
|
|
388
|
+
if (socket !== this.#socket) return;
|
|
389
|
+
const data: unknown = event.data;
|
|
390
|
+
if (data instanceof ArrayBuffer) {
|
|
391
|
+
this.#unanswered = false;
|
|
392
|
+
let frame: ServerMessage<View>;
|
|
393
|
+
try {
|
|
394
|
+
frame = decodePatchFrame(new Uint8Array(data), keys);
|
|
395
|
+
} catch (err) {
|
|
396
|
+
// Whatever it was, the keys can no longer be trusted. Start again from a welcome.
|
|
397
|
+
console.warn("[tickflare] could not read a binary frame:", err);
|
|
398
|
+
return this.#resync();
|
|
399
|
+
}
|
|
400
|
+
return this.#handle(frame);
|
|
401
|
+
}
|
|
402
|
+
if (typeof data !== "string") return;
|
|
403
|
+
// Anything the server sends shows the connection is alive.
|
|
404
|
+
this.#unanswered = false;
|
|
405
|
+
if (data === PONG) {
|
|
406
|
+
const sentAt = this.#pingsAt.shift();
|
|
407
|
+
if (sentAt !== undefined) this.#clock.roundTrip(localNow() - sentAt);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
this.#handle(JSON.parse(data) as ServerMessage<View>);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
socket.addEventListener("close", (event) => {
|
|
414
|
+
if (socket === this.#socket) this.#closed(event.code, event.reason);
|
|
415
|
+
});
|
|
416
|
+
// Browsers follow a failed connection's error with a close. Node's WebSocket does not when the
|
|
417
|
+
// server turns the upgrade away, which would leave the client waiting on a socket that will
|
|
418
|
+
// never open. A socket that errs before it opened has failed either way.
|
|
419
|
+
socket.addEventListener("error", () => {
|
|
420
|
+
if (socket === this.#socket && socket.readyState === 0) this.#closed(1006, "");
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** The current connection is over: settle what was in flight, then follow, retry or stop. */
|
|
425
|
+
#closed(code: number, reason: string): void {
|
|
426
|
+
this.#socket = undefined;
|
|
427
|
+
this.#stopPing();
|
|
428
|
+
this.#pingsAt = [];
|
|
429
|
+
this.#clock.reset();
|
|
430
|
+
this.#forget();
|
|
431
|
+
|
|
432
|
+
if (code === CloseCode.Moved && reason && !this.#stopped) {
|
|
433
|
+
// Handed over to another room: same URL, with that room's id as the last path segment.
|
|
434
|
+
const next = new URL(this.#url);
|
|
435
|
+
next.pathname = next.pathname.replace(/[^/]+\/?$/, reason);
|
|
436
|
+
this.#url = next.toString();
|
|
437
|
+
this.#emit("moved", reason);
|
|
438
|
+
this.#open();
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const retry = !this.#stopped && this.#options.reconnect !== false && !isFatalCloseCode(code);
|
|
443
|
+
if (!retry) {
|
|
444
|
+
this.#stopped = true;
|
|
445
|
+
this.#setStatus("closed", { code, reason });
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
this.#setStatus("connecting", { code, reason });
|
|
449
|
+
const backoff = Math.min(MAX_BACKOFF_MS, 250 * 2 ** this.#attempt++);
|
|
450
|
+
this.#retryTimer = setTimeout(() => this.#open(), backoff / 2 + Math.random() * (backoff / 2));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** What was in flight is lost: the connection is, or the room started again from its last save. */
|
|
454
|
+
#forget(): void {
|
|
455
|
+
for (const pending of this.#pending.values()) {
|
|
456
|
+
pending.reject(new CommandRejected("disconnected"));
|
|
457
|
+
}
|
|
458
|
+
this.#pending.clear();
|
|
459
|
+
if (this.#unconfirmed.length > 0) this.#unconfirmed = [];
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** The state about to be set shows this player's commands up to `id`: they are no longer unconfirmed. */
|
|
463
|
+
#shown(id: number | undefined): void {
|
|
464
|
+
if (id === undefined || this.#unconfirmed.length === 0) return;
|
|
465
|
+
const left = this.#unconfirmed.filter((sent) => sent.id > id);
|
|
466
|
+
if (left.length !== this.#unconfirmed.length) this.#unconfirmed = left;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Resolves the commands up to `id`, whose effect `state` now has. */
|
|
470
|
+
#resolveUpTo(id: number | undefined): void {
|
|
471
|
+
if (id === undefined) return;
|
|
472
|
+
for (const pending of [...this.#pending.keys()]) {
|
|
473
|
+
if (pending <= id) this.#settle(pending)?.resolve();
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
#handle(message: ServerMessage<View>): void {
|
|
478
|
+
switch (message.t) {
|
|
479
|
+
case "welcome": {
|
|
480
|
+
// On a connection that was open already: the room came back from its last save.
|
|
481
|
+
this.#forget();
|
|
482
|
+
this.#attempt = 0;
|
|
483
|
+
this.#you = message.you;
|
|
484
|
+
this.#players = message.players;
|
|
485
|
+
this.#tick = message.tick;
|
|
486
|
+
this.#tickRate = message.tickRate;
|
|
487
|
+
this.#clock.reset();
|
|
488
|
+
if (message.ms !== undefined) this.#clock.reading(message.tick, message.tickRate, message.ms, message.epoch);
|
|
489
|
+
this.#startPing();
|
|
490
|
+
if (message.tickRate > 0) this.#measure();
|
|
491
|
+
this.#setStatus("open");
|
|
492
|
+
this.#emit("presence", this.#players);
|
|
493
|
+
this.#setState(message.state, message.seq);
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
case "state":
|
|
497
|
+
if (message.tick !== undefined) this.#tick = message.tick;
|
|
498
|
+
this.#shown(message.c);
|
|
499
|
+
this.#setState(message.state, message.seq);
|
|
500
|
+
this.#resolveUpTo(message.c);
|
|
501
|
+
break;
|
|
502
|
+
case "patch":
|
|
503
|
+
if (message.from !== undefined && message.from !== this.#seq) {
|
|
504
|
+
// A patch of a view this client does not hold. Applying it would leave the screen
|
|
505
|
+
// wrong with nothing to show for it, so start again from the whole view.
|
|
506
|
+
this.#resync();
|
|
507
|
+
break;
|
|
508
|
+
}
|
|
509
|
+
this.#tick = message.tick;
|
|
510
|
+
this.#shown(message.c);
|
|
511
|
+
this.#setState(applyPatch(this.#state as View, message.p), message.seq);
|
|
512
|
+
this.#resolveUpTo(message.c);
|
|
513
|
+
break;
|
|
514
|
+
case "clock":
|
|
515
|
+
this.#clock.reading(message.tick, this.#tickRate, message.ms, message.epoch);
|
|
516
|
+
if (message.ms !== undefined) this.#measure();
|
|
517
|
+
break;
|
|
518
|
+
case "presence":
|
|
519
|
+
this.#players = message.players ?? withPresence(this.#players, message.set, message.gone);
|
|
520
|
+
this.#emit("presence", this.#players);
|
|
521
|
+
break;
|
|
522
|
+
case "ack":
|
|
523
|
+
// The view is of this tick even if nothing in it changed and no frame said so.
|
|
524
|
+
if (message.tick !== undefined && message.tick > this.#tick) this.#tick = message.tick;
|
|
525
|
+
this.#shown(message.id);
|
|
526
|
+
this.#settle(message.id)?.resolve();
|
|
527
|
+
break;
|
|
528
|
+
case "reject":
|
|
529
|
+
if (this.#unconfirmed.some((sent) => sent.id === message.id)) {
|
|
530
|
+
this.#unconfirmed = this.#unconfirmed.filter((sent) => sent.id !== message.id);
|
|
531
|
+
}
|
|
532
|
+
this.#settle(message.id)?.reject(new CommandRejected(message.reason));
|
|
533
|
+
break;
|
|
534
|
+
case "error":
|
|
535
|
+
console.warn(`[tickflare] server could not read a frame: ${message.reason}`);
|
|
536
|
+
break;
|
|
537
|
+
case "msg":
|
|
538
|
+
this.#emit("message", message.d);
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Drops the connection and opens a new one, which begins with the whole view. */
|
|
544
|
+
#resync(): void {
|
|
545
|
+
const socket = this.#socket;
|
|
546
|
+
if (!socket) return;
|
|
547
|
+
console.warn("[tickflare] out of step with the room; reconnecting");
|
|
548
|
+
this.#socket = undefined;
|
|
549
|
+
try {
|
|
550
|
+
socket.close(1000, "resync");
|
|
551
|
+
} catch {
|
|
552
|
+
// Already closing.
|
|
553
|
+
}
|
|
554
|
+
this.#closed(1006, "resync");
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
#setState(state: View, seq: number): void {
|
|
558
|
+
this.#state = state;
|
|
559
|
+
this.#seq = seq;
|
|
560
|
+
this.#emit("state", state, seq);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
#settle(id: number) {
|
|
564
|
+
const pending = this.#pending.get(id);
|
|
565
|
+
this.#pending.delete(id);
|
|
566
|
+
return pending;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
#startPing(): void {
|
|
570
|
+
const interval = this.#options.pingIntervalMs ?? 25_000;
|
|
571
|
+
this.#stopPing();
|
|
572
|
+
if (interval <= 0) return;
|
|
573
|
+
this.#unanswered = false;
|
|
574
|
+
this.#pingTimer = setInterval(() => {
|
|
575
|
+
const socket = this.#socket;
|
|
576
|
+
if (socket?.readyState !== 1) return;
|
|
577
|
+
if (this.#unanswered) {
|
|
578
|
+
// A dead connection can stay "open" for minutes. Do not wait for the browser to notice.
|
|
579
|
+
this.#closed(1006, "keepalive_timeout");
|
|
580
|
+
try {
|
|
581
|
+
socket.close();
|
|
582
|
+
} catch {
|
|
583
|
+
// Already closed.
|
|
584
|
+
}
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
this.#unanswered = true;
|
|
588
|
+
this.#pingsAt.push(localNow());
|
|
589
|
+
socket.send(PING);
|
|
590
|
+
}, interval);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** Sends a `ping` to time the round trip, unless one is on its way already. Leaves the keepalive's watch alone. */
|
|
594
|
+
#measure(): void {
|
|
595
|
+
const socket = this.#socket;
|
|
596
|
+
if (socket?.readyState !== 1 || this.#pingsAt.length > 0) return;
|
|
597
|
+
this.#pingsAt.push(localNow());
|
|
598
|
+
try {
|
|
599
|
+
socket.send(PING);
|
|
600
|
+
} catch {
|
|
601
|
+
this.#pingsAt.pop();
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
#stopPing(): void {
|
|
606
|
+
if (this.#pingTimer !== undefined) clearInterval(this.#pingTimer);
|
|
607
|
+
this.#pingTimer = undefined;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
#setStatus(status: ConnectionStatus, detail?: CloseDetail): void {
|
|
611
|
+
if (this.#status === status && !detail) return;
|
|
612
|
+
this.#status = status;
|
|
613
|
+
this.#emit("status", status, detail);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** The list of players after a `presence` frame that says what changed: a new array, in join order. */
|
|
618
|
+
function withPresence(players: Player[], set: Player[] = [], gone: string[] = []): Player[] {
|
|
619
|
+
const changed = new Map(set.map((player) => [player.id, player]));
|
|
620
|
+
const left = new Set(gone);
|
|
621
|
+
const out: Player[] = [];
|
|
622
|
+
for (const player of players) {
|
|
623
|
+
if (left.has(player.id)) continue;
|
|
624
|
+
const now = changed.get(player.id);
|
|
625
|
+
out.push(now ?? player);
|
|
626
|
+
if (now) changed.delete(player.id);
|
|
627
|
+
}
|
|
628
|
+
// Whoever is left is new, and goes to the end in the order the room gave.
|
|
629
|
+
for (const player of set) if (changed.has(player.id)) out.push(player);
|
|
630
|
+
return out;
|
|
631
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Smooths values that arrive once per tick, for drawing between ticks.
|
|
3
|
+
*
|
|
4
|
+
* State sync delivers positions 10 to 30 times a second; a screen draws 60
|
|
5
|
+
* or more. Each time a new value arrives for an id, the interpolator glides
|
|
6
|
+
* to it from wherever that id was being drawn, over `durationMs` (one tick
|
|
7
|
+
* is the usual choice). Because it always starts from what is on screen, a
|
|
8
|
+
* late or bunched update bends the motion instead of making it jump.
|
|
9
|
+
*
|
|
10
|
+
* const glide = new Interpolator(1000 / client.tickRate, ["x", "y"]);
|
|
11
|
+
* onState: (state) => glide.update(state.units),
|
|
12
|
+
* // in the render loop:
|
|
13
|
+
* const { x, y } = glide.at(id) ?? state.units[id];
|
|
14
|
+
*/
|
|
15
|
+
export class Interpolator<Field extends string> {
|
|
16
|
+
readonly #durationMs: number;
|
|
17
|
+
readonly #fields: readonly Field[];
|
|
18
|
+
#tracks = new Map<string, { from: Record<Field, number>; to: Record<Field, number>; since: number }>();
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param durationMs how long a glide takes, usually the time between ticks
|
|
22
|
+
* @param fields the numeric fields to smooth, e.g. `["x", "y"]`
|
|
23
|
+
*/
|
|
24
|
+
constructor(durationMs: number, fields: readonly Field[]) {
|
|
25
|
+
this.#durationMs = Math.max(1, durationMs);
|
|
26
|
+
this.#fields = fields;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Feed the latest values, keyed by id. Ids missing from `targets` are
|
|
31
|
+
* forgotten; new ones start at their target.
|
|
32
|
+
*/
|
|
33
|
+
update(targets: Record<string, Record<Field, number>>, now = performance.now()): void {
|
|
34
|
+
const tracks = new Map<string, { from: Record<Field, number>; to: Record<Field, number>; since: number }>();
|
|
35
|
+
for (const id of Object.keys(targets)) {
|
|
36
|
+
const target = targets[id]!;
|
|
37
|
+
const to = {} as Record<Field, number>;
|
|
38
|
+
for (const field of this.#fields) to[field] = target[field];
|
|
39
|
+
tracks.set(id, { from: this.at(id, now) ?? to, to, since: now });
|
|
40
|
+
}
|
|
41
|
+
this.#tracks = tracks;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The values to draw for `id` right now, or undefined if it is not known. */
|
|
45
|
+
at(id: string, now = performance.now()): Record<Field, number> | undefined {
|
|
46
|
+
const track = this.#tracks.get(id);
|
|
47
|
+
if (!track) return undefined;
|
|
48
|
+
const t = Math.min(1, Math.max(0, (now - track.since) / this.#durationMs));
|
|
49
|
+
const shown = {} as Record<Field, number>;
|
|
50
|
+
for (const field of this.#fields) {
|
|
51
|
+
shown[field] = track.from[field] + (track.to[field] - track.from[field]) * t;
|
|
52
|
+
}
|
|
53
|
+
return shown;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Forget everything, e.g. after moving to another room. */
|
|
57
|
+
clear(): void {
|
|
58
|
+
this.#tracks.clear();
|
|
59
|
+
}
|
|
60
|
+
}
|