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,467 @@
|
|
|
1
|
+
import { encodePatch, encodePatchFrame, KeyTable, type SharedEncodings } from "../binary.js";
|
|
2
|
+
import { applyPatch, diff, diffArrays, isPlainObject, jsonEqual, withoutArrayPatches, type Patch } from "../patch.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How to bring a socket up to date: a patch as JSON, or its whole view as
|
|
6
|
+
* JSON, or neither if nothing changed for it. And the snapshot it then holds.
|
|
7
|
+
*/
|
|
8
|
+
interface Update {
|
|
9
|
+
patch?: string;
|
|
10
|
+
/** The patch as an object, when one is at hand. */
|
|
11
|
+
parsed?: Patch;
|
|
12
|
+
/** The patch in binary, once a socket has needed it. */
|
|
13
|
+
binary?: Uint8Array;
|
|
14
|
+
/**
|
|
15
|
+
* The same change for sockets whose clients do not know array patches,
|
|
16
|
+
* once one has needed it: this update itself when the patch has none.
|
|
17
|
+
*/
|
|
18
|
+
plain?: { patch: string; parsed?: Patch; binary?: Uint8Array };
|
|
19
|
+
whole?: string;
|
|
20
|
+
next: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SeatedSocket {
|
|
24
|
+
ws: WebSocket;
|
|
25
|
+
/** The player the socket belongs to. */
|
|
26
|
+
id: string;
|
|
27
|
+
/** Whether its client asked for patches in binary. */
|
|
28
|
+
binary?: boolean;
|
|
29
|
+
/** Whether its client said it knows array patches. */
|
|
30
|
+
arrays?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Sends each socket what changed in its view since it was last sent
|
|
35
|
+
* anything: after a tick while the room simulates, after a change otherwise.
|
|
36
|
+
*
|
|
37
|
+
* It remembers, per socket, a copy of what that socket holds. A socket it
|
|
38
|
+
* knows nothing about gets its whole view; the others get a patch, or
|
|
39
|
+
* nothing if their view did not change.
|
|
40
|
+
*
|
|
41
|
+
* Work that is the same for several sockets is done once. Without a custom
|
|
42
|
+
* view everyone sees the same state, so sockets holding the same snapshot
|
|
43
|
+
* share one diff. With a custom view, the same holds one level down: a
|
|
44
|
+
* top-level field of the view that is the same object for several players
|
|
45
|
+
* (a public part built once per tick, say) is diffed and serialized once for
|
|
46
|
+
* all the sockets that hold the same copy of it, and they all end the tick
|
|
47
|
+
* holding one copy again.
|
|
48
|
+
*/
|
|
49
|
+
export class DeltaSender {
|
|
50
|
+
/** What each socket was last sent. Snapshots are never mutated, so sockets may share one. */
|
|
51
|
+
#baselines = new Map<WebSocket, unknown>();
|
|
52
|
+
/** The `seq` of what each socket was last sent: what its client says its view is of. */
|
|
53
|
+
#seqs = new Map<WebSocket, number>();
|
|
54
|
+
/** The `seq` of the last send. */
|
|
55
|
+
#sentSeq = -1;
|
|
56
|
+
/** Without a custom view: the snapshot every socket held after the last send, and the `seq` it is of. */
|
|
57
|
+
#common: { seq: number; snapshot: unknown } | undefined;
|
|
58
|
+
/** The names sent as keys in binary patches, numbered. One table for the room. */
|
|
59
|
+
#keys = new KeyTable();
|
|
60
|
+
/** How much of that table each socket has been told, and of which generation of it. */
|
|
61
|
+
#told = new WeakMap<WebSocket, { generation: number; known: number }>();
|
|
62
|
+
/**
|
|
63
|
+
* During a send: what has been encoded in binary already, for the patches that have it too,
|
|
64
|
+
* and the frames made around each encoded patch, by what sets them apart. Players whose views
|
|
65
|
+
* change alike are sent bytes made once.
|
|
66
|
+
*/
|
|
67
|
+
#shared: SharedEncodings = { values: new Map(), changes: new Map() };
|
|
68
|
+
#framed = new Map<Uint8Array, Map<string, Uint8Array>>();
|
|
69
|
+
|
|
70
|
+
/** Record exactly what a socket has just been sent in full, as a copy the room cannot touch. */
|
|
71
|
+
remember(ws: WebSocket, snapshot: unknown, seq: number): void {
|
|
72
|
+
this.#baselines.set(ws, snapshot);
|
|
73
|
+
this.#seqs.set(ws, seq);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Forget what the sockets hold: the next send gives each its whole view. */
|
|
77
|
+
reset(): void {
|
|
78
|
+
this.#baselines.clear();
|
|
79
|
+
this.#seqs.clear();
|
|
80
|
+
this.#common = undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Whether it is known what every one of these sockets holds. */
|
|
84
|
+
knows(sockets: SeatedSocket[]): boolean {
|
|
85
|
+
return sockets.every(({ ws }) => this.#baselines.has(ws));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* For a room without a custom view, whose sockets are known to hold the
|
|
90
|
+
* state as it was at `seq`: records that for the sockets nothing else is
|
|
91
|
+
* known about. `snapshot` makes a copy of that state, and is called only
|
|
92
|
+
* if the copy from the last send is of another `seq` or gone.
|
|
93
|
+
*/
|
|
94
|
+
seed(sockets: SeatedSocket[], seq: number, snapshot: () => unknown): void {
|
|
95
|
+
let base = this.#common?.seq === seq ? this.#common.snapshot : undefined;
|
|
96
|
+
for (const { ws } of sockets) {
|
|
97
|
+
if (this.#baselines.has(ws)) continue;
|
|
98
|
+
this.#baselines.set(ws, (base ??= snapshot()));
|
|
99
|
+
this.#seqs.set(ws, seq);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param state the room's state, which is what everyone sees when `viewOf` is undefined
|
|
105
|
+
* @param viewOf what one player sees, when the room has a custom view
|
|
106
|
+
* @param named whether a patch says which `seq` it is a patch of, so that a client that
|
|
107
|
+
* holds another can tell. For changes sent outside the simulation.
|
|
108
|
+
* @param shows for the sockets whose commands this state is the first to show: the id of
|
|
109
|
+
* the latest of them, which their frame then carries as `c`
|
|
110
|
+
*/
|
|
111
|
+
send(
|
|
112
|
+
sockets: SeatedSocket[],
|
|
113
|
+
seq: number,
|
|
114
|
+
tick: number,
|
|
115
|
+
state: unknown,
|
|
116
|
+
viewOf: ((playerId: string) => unknown) | undefined,
|
|
117
|
+
named = false,
|
|
118
|
+
shows?: Map<WebSocket, number>,
|
|
119
|
+
): void {
|
|
120
|
+
if (!viewOf && seq === this.#sentSeq && sockets.every(({ ws }) => this.#baselines.has(ws))) return;
|
|
121
|
+
const head = `"seq":${seq},"tick":${tick}`;
|
|
122
|
+
const baselines = new Map<WebSocket, unknown>();
|
|
123
|
+
const seqs = new Map<WebSocket, number>();
|
|
124
|
+
this.#keys.renew();
|
|
125
|
+
/** Sends a socket its update, and records what it then holds. */
|
|
126
|
+
const deliver = (ws: WebSocket, update: Update, binary = false, arrays = false): void => {
|
|
127
|
+
const held = this.#seqs.get(ws);
|
|
128
|
+
const shown = shows?.get(ws);
|
|
129
|
+
const c = shown === undefined ? "" : `,"c":${shown}`;
|
|
130
|
+
if (update.patch !== undefined) {
|
|
131
|
+
const from = named && held !== undefined ? held : undefined;
|
|
132
|
+
// The patch in the form this socket's client reads.
|
|
133
|
+
const form = arrays ? (update as { patch: string }) : plainForm(update);
|
|
134
|
+
const frame = binary ? this.#binaryFrame(ws, form, { seq, tick, from, c: shown }) : undefined;
|
|
135
|
+
if (frame) {
|
|
136
|
+
ws.send(frame);
|
|
137
|
+
this.#told.set(ws, { generation: this.#keys.generation, known: this.#keys.size });
|
|
138
|
+
} else {
|
|
139
|
+
ws.send(`{"t":"patch",${head}${from === undefined ? "" : `,"from":${from}`}${c},"p":${form.patch}}`);
|
|
140
|
+
}
|
|
141
|
+
} else if (update.whole !== undefined) {
|
|
142
|
+
ws.send(`{"t":"state",${head}${c},"state":${update.whole}}`);
|
|
143
|
+
}
|
|
144
|
+
baselines.set(ws, update.next);
|
|
145
|
+
// A socket that was sent nothing still holds the view of the `seq` it had.
|
|
146
|
+
seqs.set(ws, update.patch !== undefined || update.whole !== undefined || held === undefined ? seq : held);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
if (viewOf) this.#sendViews(sockets, viewOf, deliver);
|
|
151
|
+
else this.#sendState(sockets, state, deliver);
|
|
152
|
+
} finally {
|
|
153
|
+
this.#shared.values.clear();
|
|
154
|
+
this.#shared.changes.clear();
|
|
155
|
+
this.#framed.clear();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// A socket that could not be sent to, or whose view() threw, keeps what it had and gets the
|
|
159
|
+
// difference next time.
|
|
160
|
+
for (const { ws } of sockets) {
|
|
161
|
+
if (baselines.has(ws) || !this.#baselines.has(ws)) continue;
|
|
162
|
+
baselines.set(ws, this.#baselines.get(ws));
|
|
163
|
+
const held = this.#seqs.get(ws);
|
|
164
|
+
if (held !== undefined) seqs.set(ws, held);
|
|
165
|
+
}
|
|
166
|
+
const common = viewOf ? undefined : this.#latest;
|
|
167
|
+
this.#baselines = baselines;
|
|
168
|
+
this.#seqs = seqs;
|
|
169
|
+
this.#sentSeq = seq;
|
|
170
|
+
this.#common = common === undefined ? undefined : { seq, snapshot: common };
|
|
171
|
+
this.#latest = undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** During a send without a custom view: the snapshot everyone ends up holding. */
|
|
175
|
+
#latest: unknown;
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A patch as a binary frame for one socket, or undefined if it cannot be
|
|
179
|
+
* said in binary, in which case the socket is sent the JSON: its client
|
|
180
|
+
* reads both. A patch is encoded once in a send, however many sockets are
|
|
181
|
+
* sent it, and so is a frame around it for the sockets that need the same.
|
|
182
|
+
*/
|
|
183
|
+
#binaryFrame(
|
|
184
|
+
ws: WebSocket,
|
|
185
|
+
update: { patch: string; parsed?: Patch; binary?: Uint8Array },
|
|
186
|
+
head: { seq: number; tick: number; from: number | undefined; c: number | undefined },
|
|
187
|
+
): Uint8Array | undefined {
|
|
188
|
+
let patch = update.binary;
|
|
189
|
+
if (patch === undefined) {
|
|
190
|
+
try {
|
|
191
|
+
patch = encodePatch(update.parsed ?? (JSON.parse(update.patch) as Patch), this.#keys, this.#shared);
|
|
192
|
+
} catch {
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
update.binary = patch;
|
|
196
|
+
}
|
|
197
|
+
const told = this.#told.get(ws);
|
|
198
|
+
// A socket this instance has not sent a frame to, or that knows a table since started again,
|
|
199
|
+
// is told to forget its keys and is given all of them.
|
|
200
|
+
const forget = told === undefined || told.generation !== this.#keys.generation;
|
|
201
|
+
const known = forget ? 0 : told.known;
|
|
202
|
+
// The frame gives the keys from `known` to the table's present size, which grows as patches
|
|
203
|
+
// with new names are encoded: that size is part of what sets a frame apart.
|
|
204
|
+
const key = `${forget ? "f" : known}/${this.#keys.size}/${head.from ?? ""}/${head.c ?? ""}`;
|
|
205
|
+
let frames = this.#framed.get(patch);
|
|
206
|
+
if (frames === undefined) this.#framed.set(patch, (frames = new Map()));
|
|
207
|
+
let frame = frames.get(key);
|
|
208
|
+
if (frame === undefined) {
|
|
209
|
+
try {
|
|
210
|
+
frame = encodePatchFrame(head, this.#keys, known, forget, patch);
|
|
211
|
+
} catch {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
frames.set(key, frame);
|
|
215
|
+
}
|
|
216
|
+
return frame;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
#sendState(sockets: SeatedSocket[], state: unknown, deliver: Deliver): void {
|
|
220
|
+
// Sockets that were last sent the same snapshot share one diff, and everyone ends up
|
|
221
|
+
// holding the same snapshot.
|
|
222
|
+
const shared = new Map<unknown, Update>();
|
|
223
|
+
let common: Update | undefined;
|
|
224
|
+
for (const { ws, id, binary, arrays } of sockets) {
|
|
225
|
+
try {
|
|
226
|
+
const base = this.#baselines.get(ws);
|
|
227
|
+
let update = base === undefined ? undefined : shared.get(base);
|
|
228
|
+
if (!update) {
|
|
229
|
+
update = updateFor(base, state);
|
|
230
|
+
if (common) update.next = common.next;
|
|
231
|
+
else common = update;
|
|
232
|
+
if (base !== undefined) shared.set(base, update);
|
|
233
|
+
}
|
|
234
|
+
deliver(ws, update, binary, arrays);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
console.error(`[tickflare] could not send the state to ${id}:`, err);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
this.#latest = common?.next;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
#sendViews(
|
|
243
|
+
sockets: SeatedSocket[],
|
|
244
|
+
viewOf: (playerId: string) => unknown,
|
|
245
|
+
deliver: Deliver,
|
|
246
|
+
): void {
|
|
247
|
+
// Every view first, then the diffs: a field shared between views is final by the time it is diffed.
|
|
248
|
+
const views: (SeatedSocket & { live: unknown })[] = [];
|
|
249
|
+
for (const socket of sockets) {
|
|
250
|
+
try {
|
|
251
|
+
views.push({ ...socket, live: viewOf(socket.id) });
|
|
252
|
+
} catch (err) {
|
|
253
|
+
// A view() that threw must not starve the other players.
|
|
254
|
+
console.error(`[tickflare] could not send the state to ${socket.id}:`, err);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const fields = new FieldCache();
|
|
259
|
+
for (const { ws, id, binary, arrays, live } of views) {
|
|
260
|
+
try {
|
|
261
|
+
const base = this.#baselines.get(ws);
|
|
262
|
+
deliver(
|
|
263
|
+
ws,
|
|
264
|
+
isPlainObject(live) && (base === undefined || isPlainObject(base))
|
|
265
|
+
? viewUpdate(base, live, fields, binary === true || arrays !== true)
|
|
266
|
+
: updateFor(base, live),
|
|
267
|
+
binary,
|
|
268
|
+
arrays,
|
|
269
|
+
);
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error(`[tickflare] could not send the state to ${id}:`, err);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
type Deliver = (ws: WebSocket, update: Update, binary?: boolean, arrays?: boolean) => void;
|
|
278
|
+
|
|
279
|
+
/** The patch of an update without array patches in it, worked out once for the sockets that need it so. */
|
|
280
|
+
function plainForm(update: Update): { patch: string; parsed?: Patch; binary?: Uint8Array } {
|
|
281
|
+
if (update.plain) return update.plain;
|
|
282
|
+
const parsed = (update.parsed ??= JSON.parse(update.patch!) as Patch);
|
|
283
|
+
const without = withoutArrayPatches(parsed, update.next);
|
|
284
|
+
update.plain = without === parsed ? (update as { patch: string }) : { patch: JSON.stringify(without), parsed: without };
|
|
285
|
+
return update.plain;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* What is known, during one send, about each top-level field value that is an
|
|
290
|
+
* object: its JSON, the copy everyone who is brought up to date ends up holding,
|
|
291
|
+
* and the patch from each copy that was being held before.
|
|
292
|
+
*/
|
|
293
|
+
class FieldCache {
|
|
294
|
+
#byValue = new Map<
|
|
295
|
+
object,
|
|
296
|
+
{ json?: string; next?: unknown; patches: Map<unknown, string | null>; changes?: Map<unknown, unknown> }
|
|
297
|
+
>();
|
|
298
|
+
|
|
299
|
+
#entry(live: object) {
|
|
300
|
+
let entry = this.#byValue.get(live);
|
|
301
|
+
if (!entry) this.#byValue.set(live, (entry = { patches: new Map() }));
|
|
302
|
+
return entry;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The JSON of the whole value. */
|
|
306
|
+
json(live: object): string {
|
|
307
|
+
const entry = this.#entry(live);
|
|
308
|
+
return (entry.json ??= JSON.stringify(live));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* How to bring `base` up to `live`: a patch as JSON, or null when nothing
|
|
313
|
+
* changed. Also settles the copy that holders of `live` share afterwards.
|
|
314
|
+
*/
|
|
315
|
+
patch(base: Record<string, unknown>, live: Record<string, unknown>): string | null {
|
|
316
|
+
const entry = this.#entry(live);
|
|
317
|
+
const known = entry.patches.get(base);
|
|
318
|
+
if (known !== undefined) return known;
|
|
319
|
+
const patch = diff(base, live);
|
|
320
|
+
let json: string | null = null;
|
|
321
|
+
if (patch) {
|
|
322
|
+
json = JSON.stringify(patch);
|
|
323
|
+
entry.next ??= applyPatch(base, JSON.parse(json) as Patch);
|
|
324
|
+
(entry.changes ??= new Map()).set(base, patch);
|
|
325
|
+
} else {
|
|
326
|
+
entry.next ??= base;
|
|
327
|
+
}
|
|
328
|
+
entry.patches.set(base, json);
|
|
329
|
+
return json;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* How to bring the array `base` up to `live`, as the JSON of the change to
|
|
334
|
+
* its key: a patch of its elements or the whole array. Null when nothing
|
|
335
|
+
* changed.
|
|
336
|
+
*/
|
|
337
|
+
arrayChange(base: unknown[], live: unknown[]): string | null {
|
|
338
|
+
const entry = this.#entry(live);
|
|
339
|
+
const known = entry.patches.get(base);
|
|
340
|
+
if (known !== undefined) return known;
|
|
341
|
+
const patch = diffArrays(base, live);
|
|
342
|
+
let json: string | null = null;
|
|
343
|
+
if (patch === undefined) {
|
|
344
|
+
entry.next ??= base;
|
|
345
|
+
} else if (patch === null) {
|
|
346
|
+
json = `[${this.json(live)}]`;
|
|
347
|
+
(entry.changes ??= new Map()).set(base, [live]);
|
|
348
|
+
} else {
|
|
349
|
+
json = JSON.stringify(patch);
|
|
350
|
+
entry.next ??= applyPatch({ v: base }, { v: JSON.parse(json) as Patch[string] }).v;
|
|
351
|
+
(entry.changes ??= new Map()).set(base, patch);
|
|
352
|
+
}
|
|
353
|
+
entry.patches.set(base, json);
|
|
354
|
+
return json;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* The change `patch` or `arrayChange` gave for `base` and `live`, as an
|
|
359
|
+
* object: what its JSON was written from, which holds the state's own
|
|
360
|
+
* values. For encoding in this send, never to keep.
|
|
361
|
+
*/
|
|
362
|
+
change(base: unknown, live: object): unknown {
|
|
363
|
+
return this.#entry(live).changes?.get(base);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** The copy of `live` that everyone who holds it after this send shares. */
|
|
367
|
+
next(live: object): unknown {
|
|
368
|
+
const entry = this.#entry(live);
|
|
369
|
+
return (entry.next ??= JSON.parse(this.json(live)));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* What brings a socket from `base` to the view `live`, field by field, so
|
|
375
|
+
* that fields shared with other views cost nothing extra.
|
|
376
|
+
*/
|
|
377
|
+
function viewUpdate(
|
|
378
|
+
base: Record<string, unknown> | undefined,
|
|
379
|
+
live: Record<string, unknown>,
|
|
380
|
+
fields: FieldCache,
|
|
381
|
+
parse = false,
|
|
382
|
+
): Update {
|
|
383
|
+
if (base === undefined) {
|
|
384
|
+
const parts: string[] = [];
|
|
385
|
+
const next: Record<string, unknown> = {};
|
|
386
|
+
for (const key of Object.keys(live)) {
|
|
387
|
+
const value = live[key];
|
|
388
|
+
if (value === undefined) continue;
|
|
389
|
+
if (typeof value === "object" && value !== null) {
|
|
390
|
+
parts.push(`${JSON.stringify(key)}:${fields.json(value)}`);
|
|
391
|
+
next[key] = fields.next(value);
|
|
392
|
+
} else {
|
|
393
|
+
const json = JSON.stringify(value);
|
|
394
|
+
if (json === undefined) continue;
|
|
395
|
+
parts.push(`${JSON.stringify(key)}:${json}`);
|
|
396
|
+
next[key] = JSON.parse(json);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return { whole: `{${parts.join(",")}}`, next };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const parts: string[] = [];
|
|
403
|
+
const next: Record<string, unknown> = { ...base };
|
|
404
|
+
// For a client that needs the patch as an object, binary or without array patches: the same
|
|
405
|
+
// patch, built from what its JSON was written from instead of parsed back for each player. It
|
|
406
|
+
// holds the state's own values, so that what several players are sent is the same object.
|
|
407
|
+
// `__proto__` would be the object's prototype here, where it is an ordinary key in JSON.
|
|
408
|
+
let parsed: Patch | undefined = parse ? {} : undefined;
|
|
409
|
+
for (const key of Object.keys(live)) {
|
|
410
|
+
const to = live[key];
|
|
411
|
+
if (to === undefined) continue;
|
|
412
|
+
const from = Object.prototype.hasOwnProperty.call(base, key) ? base[key] : undefined;
|
|
413
|
+
const name = JSON.stringify(key);
|
|
414
|
+
if (key === "__proto__") parsed = undefined;
|
|
415
|
+
if (typeof to === "object" && to !== null) {
|
|
416
|
+
if (isPlainObject(from) && isPlainObject(to)) {
|
|
417
|
+
const patch = fields.patch(from, to);
|
|
418
|
+
if (patch !== null) {
|
|
419
|
+
parts.push(`${name}:${patch}`);
|
|
420
|
+
if (parsed) parsed[key] = fields.change(from, to) as Patch;
|
|
421
|
+
}
|
|
422
|
+
} else if (Array.isArray(from) && Array.isArray(to)) {
|
|
423
|
+
const change = fields.arrayChange(from, to);
|
|
424
|
+
if (change !== null) {
|
|
425
|
+
parts.push(`${name}:${change}`);
|
|
426
|
+
if (parsed) parsed[key] = fields.change(from, to) as Patch[string];
|
|
427
|
+
}
|
|
428
|
+
} else if (from === undefined || !jsonEqual(from, to)) {
|
|
429
|
+
parts.push(`${name}:[${fields.json(to)}]`);
|
|
430
|
+
if (parsed) parsed[key] = [to];
|
|
431
|
+
}
|
|
432
|
+
next[key] = fields.next(to);
|
|
433
|
+
} else if (from === undefined || !jsonEqual(from, to)) {
|
|
434
|
+
const json = JSON.stringify(to);
|
|
435
|
+
if (json === undefined) continue;
|
|
436
|
+
parts.push(`${name}:[${json}]`);
|
|
437
|
+
next[key] = JSON.parse(json);
|
|
438
|
+
if (parsed) parsed[key] = [next[key]];
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
for (const key of Object.keys(base)) {
|
|
442
|
+
if (base[key] !== undefined && (!Object.prototype.hasOwnProperty.call(live, key) || live[key] === undefined)) {
|
|
443
|
+
parts.push(`${JSON.stringify(key)}:0`);
|
|
444
|
+
delete next[key];
|
|
445
|
+
if (key === "__proto__") parsed = undefined;
|
|
446
|
+
else if (parsed) parsed[key] = 0;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
if (parts.length === 0) return { next: base };
|
|
450
|
+
return parsed ? { patch: `{${parts.join(",")}}`, parsed, next } : { patch: `{${parts.join(",")}}`, next };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** What brings a socket from `base` to `live`, and the snapshot it will then hold. */
|
|
454
|
+
function updateFor(base: unknown, live: unknown): Update {
|
|
455
|
+
if (base !== undefined) {
|
|
456
|
+
const patch = diff(base, live);
|
|
457
|
+
if (patch === undefined) return { next: base };
|
|
458
|
+
if (patch !== null) {
|
|
459
|
+
const json = JSON.stringify(patch);
|
|
460
|
+
// A copy of its own, so that what the socket holds shares nothing with the room's state.
|
|
461
|
+
const parsed = JSON.parse(json) as Patch;
|
|
462
|
+
return { patch: json, parsed, next: applyPatch(base, parsed) };
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const json = JSON.stringify(live) ?? "null";
|
|
466
|
+
return { whole: json, next: JSON.parse(json) };
|
|
467
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** A frame from a client, after its shape has been checked. */
|
|
2
|
+
export type ClientFrame = { t: "cmd"; id: number; data: unknown } | { t: "leave"; id: number };
|
|
3
|
+
|
|
4
|
+
/** Close reasons are limited to 123 bytes by the WebSocket protocol. */
|
|
5
|
+
export const MAX_CLOSE_REASON = 120;
|
|
6
|
+
|
|
7
|
+
/** Checks the shape of a parsed client frame. `data` is passed on untouched: the room's `parseCommand` checks it. */
|
|
8
|
+
export function readFrame(value: unknown): ClientFrame | undefined {
|
|
9
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
10
|
+
const frame = value as { t?: unknown; id?: unknown; data?: unknown };
|
|
11
|
+
if (!Number.isSafeInteger(frame.id)) return undefined;
|
|
12
|
+
const id = frame.id as number;
|
|
13
|
+
if (frame.t === "cmd") return { t: "cmd", id, data: frame.data };
|
|
14
|
+
if (frame.t === "leave") return { t: "leave", id };
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Completes the upgrade, then closes straight away so the client learns why it was turned away. */
|
|
19
|
+
export function refuse(client: WebSocket, server: WebSocket, code: number, reason: string): Response {
|
|
20
|
+
server.accept();
|
|
21
|
+
server.close(code, reason.slice(0, MAX_CLOSE_REASON));
|
|
22
|
+
return new Response(null, { status: 101, webSocket: client });
|
|
23
|
+
}
|