@stefan.inc/game-networking 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/LICENSE +21 -0
- package/README.md +147 -2
- package/package.json +54 -4
- package/src/index.ts +32 -0
- package/src/memory.ts +187 -0
- package/src/patch.ts +138 -0
- package/src/session.ts +594 -0
- package/src/signal-protocol.ts +48 -0
- package/src/transport.ts +70 -0
- package/src/types.ts +164 -0
- package/src/webrtc.ts +480 -0
- package/src/wire.ts +167 -0
- package/src/worker/index.ts +287 -0
package/src/session.ts
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import { applyPatches, diff, frozen } from "./patch.ts";
|
|
2
|
+
import { MAX_ROOM_INFO_LENGTH } from "./signal-protocol.ts";
|
|
3
|
+
import type { Link, LinkHandlers } from "./transport.ts";
|
|
4
|
+
import {
|
|
5
|
+
NetError,
|
|
6
|
+
peerId,
|
|
7
|
+
roomName,
|
|
8
|
+
type ConnectionStatus,
|
|
9
|
+
type HostOptions,
|
|
10
|
+
type HostSession,
|
|
11
|
+
type PeerId,
|
|
12
|
+
type PeerInfo,
|
|
13
|
+
type PeerOptions,
|
|
14
|
+
type Session,
|
|
15
|
+
type SessionEvents,
|
|
16
|
+
type SessionOptions,
|
|
17
|
+
} from "./types.ts";
|
|
18
|
+
import {
|
|
19
|
+
createReassembler,
|
|
20
|
+
decodeLossy,
|
|
21
|
+
encodeLossy,
|
|
22
|
+
encodeReliable,
|
|
23
|
+
type ReliableWire,
|
|
24
|
+
} from "./wire.ts";
|
|
25
|
+
|
|
26
|
+
/** Long enough for a `replaced` or `removed` notice to flush before the host tears the link down. */
|
|
27
|
+
const NOTICE_GRACE_MS = 1_000;
|
|
28
|
+
|
|
29
|
+
export function createHost<Msg, Presence, State = unknown, View = State>(
|
|
30
|
+
options: HostOptions<Msg, Presence, State, View>,
|
|
31
|
+
): HostSession<Msg, Presence, State> {
|
|
32
|
+
const config = resolveOptions(options);
|
|
33
|
+
const { selfId, room, transport } = config;
|
|
34
|
+
const { view } = options;
|
|
35
|
+
if (view !== undefined && typeof view !== "function")
|
|
36
|
+
throw new TypeError("view must be a function");
|
|
37
|
+
const core = createCore<Msg, Presence, State>(config);
|
|
38
|
+
const roster = new Map<PeerId, PeerInfo>([
|
|
39
|
+
[selfId, { id: selfId, name: config.name, connected: true }],
|
|
40
|
+
]);
|
|
41
|
+
const links = new Map<PeerId, Link>();
|
|
42
|
+
/** Links whose peer has not said hello yet. They are in nobody's roster, and closing the session closes them too. */
|
|
43
|
+
const unjoined = new Set<Link>();
|
|
44
|
+
|
|
45
|
+
/** `seq` counts the changes to the state. Each peer is remembered by the last one it was sent and what it showed. */
|
|
46
|
+
let held: { state: State } | null = null;
|
|
47
|
+
let seq = 0;
|
|
48
|
+
const sent = new Map<PeerId, { seq: number; view: unknown }>();
|
|
49
|
+
/** Peers that mirror the same state are sent the same frames, worked out once. */
|
|
50
|
+
let shared: {
|
|
51
|
+
seq: number;
|
|
52
|
+
base: number;
|
|
53
|
+
before: unknown;
|
|
54
|
+
after: unknown;
|
|
55
|
+
frames: Uint8Array[] | null;
|
|
56
|
+
} | null = null;
|
|
57
|
+
|
|
58
|
+
const sendState = (id: PeerId, link: Link) => {
|
|
59
|
+
if (!held) return;
|
|
60
|
+
const next = view ? view(held.state, id) : held.state;
|
|
61
|
+
const last = sent.get(id);
|
|
62
|
+
if (!last) {
|
|
63
|
+
sendFrames(encodeReliable({ t: "state", seq, state: next }), link);
|
|
64
|
+
sent.set(id, { seq, view: next });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (last.view === next) return;
|
|
68
|
+
if (
|
|
69
|
+
shared?.seq !== seq ||
|
|
70
|
+
shared.base !== last.seq ||
|
|
71
|
+
shared.before !== last.view ||
|
|
72
|
+
shared.after !== next
|
|
73
|
+
) {
|
|
74
|
+
const patch = diff(last.view, next);
|
|
75
|
+
shared = {
|
|
76
|
+
seq,
|
|
77
|
+
base: last.seq,
|
|
78
|
+
before: last.view,
|
|
79
|
+
after: next,
|
|
80
|
+
frames: patch.length ? encodeReliable({ t: "patch", seq, base: last.seq, patch }) : null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (shared.frames) sendFrames(shared.frames, link);
|
|
84
|
+
sent.set(id, { seq: shared.frames ? seq : last.seq, view: next });
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const sendRoster = () => {
|
|
88
|
+
const peers = [...roster.values()];
|
|
89
|
+
core.peers = peers;
|
|
90
|
+
const frames = encodeReliable({ t: "roster", peers });
|
|
91
|
+
for (const link of links.values()) sendFrames(frames, link);
|
|
92
|
+
return peers;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** The links a presence frame is still owed to, so that one backed-up lane does not send it to everyone again. */
|
|
96
|
+
let owed: { frame: Uint8Array; links: Link[] } | null = null;
|
|
97
|
+
const presence = createPresenceSender(config.presenceHz, (frame) => {
|
|
98
|
+
const targets = owed?.frame === frame ? owed.links : [...links.values()];
|
|
99
|
+
const refused = targets.filter(
|
|
100
|
+
(link) => links.get(link.remoteId) === link && !link.sendLossy(frame),
|
|
101
|
+
);
|
|
102
|
+
owed = refused.length ? { frame, links: refused } : null;
|
|
103
|
+
return owed === null;
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const accept = (link: Link): LinkHandlers => {
|
|
107
|
+
const id = link.remoteId;
|
|
108
|
+
const reassembler = createReassembler();
|
|
109
|
+
let joined = false;
|
|
110
|
+
if (core.status === "closed") link.close();
|
|
111
|
+
else unjoined.add(link);
|
|
112
|
+
|
|
113
|
+
const onReliable = (wire: ReliableWire) => {
|
|
114
|
+
if (core.status === "closed") return;
|
|
115
|
+
if (!joined) {
|
|
116
|
+
if (wire.t !== "hello") throw new NetError("protocol", `Peer ${id} spoke before hello`);
|
|
117
|
+
joined = true;
|
|
118
|
+
unjoined.delete(link);
|
|
119
|
+
const previous = links.get(id);
|
|
120
|
+
links.set(id, link);
|
|
121
|
+
if (previous) dismiss(previous, { t: "replaced" });
|
|
122
|
+
roster.set(id, { id, name: wire.name, connected: true });
|
|
123
|
+
sent.delete(id);
|
|
124
|
+
const peers = sendRoster();
|
|
125
|
+
sendState(id, link);
|
|
126
|
+
core.emit("peers", peers);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (links.get(id) !== link) return;
|
|
130
|
+
if (wire.t === "msg") core.deliverMessage(wire.d, id);
|
|
131
|
+
else if (wire.t === "resync") {
|
|
132
|
+
sent.delete(id);
|
|
133
|
+
sendState(id, link);
|
|
134
|
+
} else throw new NetError("protocol", `Unexpected ${wire.t} from peer ${id}`);
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
frame(lane, frame) {
|
|
139
|
+
core.guard(() => {
|
|
140
|
+
if (lane === "reliable") {
|
|
141
|
+
const wire = reassembler.push(frame);
|
|
142
|
+
if (wire) onReliable(wire);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (links.get(id) !== link) return;
|
|
146
|
+
const presenceValue = core.parsePresence(decodeLossy(frame).d);
|
|
147
|
+
if (presenceValue === undefined) return;
|
|
148
|
+
const relay = encodeLossy({ d: presenceValue.value, from: id });
|
|
149
|
+
for (const [otherId, other] of links) if (otherId !== id) other.sendLossy(relay);
|
|
150
|
+
core.emit("presence", presenceValue.value, id);
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
close() {
|
|
154
|
+
unjoined.delete(link);
|
|
155
|
+
if (links.get(id) !== link) return;
|
|
156
|
+
links.delete(id);
|
|
157
|
+
sent.delete(id);
|
|
158
|
+
const entry = roster.get(id);
|
|
159
|
+
if (entry) roster.set(id, { ...entry, connected: false });
|
|
160
|
+
core.emit("peers", sendRoster());
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const listener = transport.listen(
|
|
166
|
+
room,
|
|
167
|
+
selfId,
|
|
168
|
+
{
|
|
169
|
+
link: accept,
|
|
170
|
+
status: (status) => core.setStatus(status),
|
|
171
|
+
fail: (error) => {
|
|
172
|
+
core.report(error);
|
|
173
|
+
session.close();
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
{ takeover: options.takeover === true },
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
core.peers = [...roster.values()];
|
|
180
|
+
|
|
181
|
+
const session: HostSession<Msg, Presence, State> = {
|
|
182
|
+
role: "host",
|
|
183
|
+
selfId,
|
|
184
|
+
room,
|
|
185
|
+
get status() {
|
|
186
|
+
return core.status;
|
|
187
|
+
},
|
|
188
|
+
get peers() {
|
|
189
|
+
return core.peers;
|
|
190
|
+
},
|
|
191
|
+
get state() {
|
|
192
|
+
return held?.state;
|
|
193
|
+
},
|
|
194
|
+
send(msg, to) {
|
|
195
|
+
core.assertOpen();
|
|
196
|
+
const frames = encodeReliable({ t: "msg", d: msg });
|
|
197
|
+
if (to === undefined || typeof to === "object") {
|
|
198
|
+
for (const [id, link] of links) if (id !== to?.except) sendFrames(frames, link);
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
if (!roster.has(to)) throw new Error(`Unknown peer ${to}`);
|
|
202
|
+
const link = links.get(to);
|
|
203
|
+
if (link) sendFrames(frames, link);
|
|
204
|
+
return link !== undefined;
|
|
205
|
+
},
|
|
206
|
+
sendPresence(value) {
|
|
207
|
+
core.assertOpen();
|
|
208
|
+
presence.push(encodeLossy({ d: value, from: selfId }));
|
|
209
|
+
},
|
|
210
|
+
setState(state) {
|
|
211
|
+
core.assertOpen();
|
|
212
|
+
if (held?.state === state) return;
|
|
213
|
+
held = { state };
|
|
214
|
+
seq++;
|
|
215
|
+
for (const [id, link] of links) sendState(id, link);
|
|
216
|
+
},
|
|
217
|
+
remove(peer, reason = "The host removed you from the room") {
|
|
218
|
+
core.assertOpen();
|
|
219
|
+
if (peer === selfId) throw new Error("The host cannot remove itself; close the session");
|
|
220
|
+
if (!roster.has(peer)) return;
|
|
221
|
+
const link = links.get(peer);
|
|
222
|
+
links.delete(peer);
|
|
223
|
+
sent.delete(peer);
|
|
224
|
+
roster.delete(peer);
|
|
225
|
+
if (link) dismiss(link, { t: "removed", reason });
|
|
226
|
+
core.emit("peers", sendRoster());
|
|
227
|
+
},
|
|
228
|
+
publish(info) {
|
|
229
|
+
core.assertOpen();
|
|
230
|
+
const length = info === null ? 0 : JSON.stringify(info).length;
|
|
231
|
+
if (length > MAX_ROOM_INFO_LENGTH)
|
|
232
|
+
throw new RangeError(
|
|
233
|
+
`Room info is ${length} characters of JSON; the limit is ${MAX_ROOM_INFO_LENGTH}`,
|
|
234
|
+
);
|
|
235
|
+
listener.publish(info);
|
|
236
|
+
},
|
|
237
|
+
on: core.on,
|
|
238
|
+
close() {
|
|
239
|
+
if (core.status === "closed") return;
|
|
240
|
+
presence.stop();
|
|
241
|
+
listener.close();
|
|
242
|
+
for (const link of [...links.values(), ...unjoined]) link.close();
|
|
243
|
+
links.clear();
|
|
244
|
+
unjoined.clear();
|
|
245
|
+
sent.clear();
|
|
246
|
+
core.setStatus("closed");
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
return session;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function sendFrames(frames: Uint8Array[], link: Link) {
|
|
253
|
+
for (const frame of frames) link.sendReliable(frame);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Tells a peer why its link is ending, then ends it. */
|
|
257
|
+
function dismiss(link: Link, notice: ReliableWire) {
|
|
258
|
+
sendFrames(encodeReliable(notice), link);
|
|
259
|
+
setTimeout(() => link.close(), NOTICE_GRACE_MS);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function joinHost<Msg, Presence, State = unknown>(
|
|
263
|
+
options: PeerOptions<Msg, Presence, State>,
|
|
264
|
+
): Session<Msg, Presence, State> {
|
|
265
|
+
const config = resolveOptions(options);
|
|
266
|
+
const { selfId, room, transport } = config;
|
|
267
|
+
const parseState = options.parseState ?? ((raw: unknown) => raw as State);
|
|
268
|
+
if (typeof parseState !== "function") throw new TypeError("parseState must be a function");
|
|
269
|
+
const core = createCore<Msg, Presence, State>(config);
|
|
270
|
+
const stop = new AbortController();
|
|
271
|
+
let link: Link | null = null;
|
|
272
|
+
/** The state as the host's change `seq` left it. NaN once the link it came on is gone, so only a whole state is taken next. */
|
|
273
|
+
let mirror: { seq: number; state: State } | null = null;
|
|
274
|
+
/** True from asking the host for the whole state until it arrives, so it is asked for once. */
|
|
275
|
+
let asked = false;
|
|
276
|
+
|
|
277
|
+
const presence = createPresenceSender(
|
|
278
|
+
config.presenceHz,
|
|
279
|
+
(frame) => link?.sendLossy(frame) ?? true,
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
const fail = (error: NetError) => {
|
|
283
|
+
core.report(error);
|
|
284
|
+
session.close();
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const onState = (wire: Extract<ReliableWire, { t: "state" | "patch" }>, from: Link) => {
|
|
288
|
+
if (wire.t === "state") {
|
|
289
|
+
let state: State;
|
|
290
|
+
try {
|
|
291
|
+
state = parseState(wire.state);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return core.report(
|
|
294
|
+
new NetError("invalid-state", "Dropped a state from the host that failed parsing", {
|
|
295
|
+
cause: error,
|
|
296
|
+
}),
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
mirror = { seq: wire.seq, state: frozen(state) };
|
|
300
|
+
asked = false;
|
|
301
|
+
} else {
|
|
302
|
+
let next: State | undefined;
|
|
303
|
+
if (mirror && wire.base === mirror.seq) {
|
|
304
|
+
try {
|
|
305
|
+
next = frozen(applyPatches(mirror.state, wire.patch));
|
|
306
|
+
} catch (error) {
|
|
307
|
+
core.report(
|
|
308
|
+
new NetError("protocol", "A change from the host does not fit the state held", {
|
|
309
|
+
cause: error,
|
|
310
|
+
}),
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (next === undefined) {
|
|
315
|
+
if (!asked) sendFrames(encodeReliable({ t: "resync" }), from);
|
|
316
|
+
asked = true;
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
mirror = { seq: wire.seq, state: next };
|
|
320
|
+
}
|
|
321
|
+
core.emit("state", mirror.state);
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
/** Resolves when the link it opened goes away. */
|
|
325
|
+
const connectOnce = async (): Promise<void> => {
|
|
326
|
+
const reassembler = createReassembler();
|
|
327
|
+
const { promise: lost, resolve: onLost } = Promise.withResolvers<void>();
|
|
328
|
+
let current: Link | null = null;
|
|
329
|
+
current = await transport.connect(
|
|
330
|
+
room,
|
|
331
|
+
selfId,
|
|
332
|
+
{
|
|
333
|
+
frame(lane, frame) {
|
|
334
|
+
if (!current || link !== current) return;
|
|
335
|
+
const host = current;
|
|
336
|
+
core.guard(() => {
|
|
337
|
+
if (lane === "lossy") {
|
|
338
|
+
const wire = decodeLossy(frame);
|
|
339
|
+
if (!wire.from) throw new NetError("protocol", "Presence from host lacks a sender");
|
|
340
|
+
const presenceValue = core.parsePresence(wire.d);
|
|
341
|
+
if (presenceValue !== undefined)
|
|
342
|
+
core.emit("presence", presenceValue.value, wire.from);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const wire = reassembler.push(frame);
|
|
346
|
+
if (!wire) return;
|
|
347
|
+
if (wire.t === "roster") {
|
|
348
|
+
core.peers = wire.peers;
|
|
349
|
+
core.emit("peers", wire.peers);
|
|
350
|
+
} else if (wire.t === "msg") core.deliverMessage(wire.d, host.remoteId);
|
|
351
|
+
else if (wire.t === "state" || wire.t === "patch") onState(wire, host);
|
|
352
|
+
else if (wire.t === "replaced")
|
|
353
|
+
fail(new NetError("replaced", `${selfId} connected from another tab`));
|
|
354
|
+
else if (wire.t === "removed") fail(new NetError("removed", wire.reason));
|
|
355
|
+
else throw new NetError("protocol", `Unexpected ${wire.t} from host`);
|
|
356
|
+
});
|
|
357
|
+
},
|
|
358
|
+
close() {
|
|
359
|
+
if (link === current) link = null;
|
|
360
|
+
onLost();
|
|
361
|
+
},
|
|
362
|
+
noHost() {
|
|
363
|
+
core.report(new NetError("no-host", `Nobody is hosting room ${room}`));
|
|
364
|
+
},
|
|
365
|
+
},
|
|
366
|
+
stop.signal,
|
|
367
|
+
);
|
|
368
|
+
if (stop.signal.aborted) {
|
|
369
|
+
current.close();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
link = current;
|
|
373
|
+
if (mirror) mirror = { seq: Number.NaN, state: mirror.state };
|
|
374
|
+
asked = false;
|
|
375
|
+
sendFrames(encodeReliable({ t: "hello", name: config.name }), current);
|
|
376
|
+
core.setStatus("connected");
|
|
377
|
+
await lost;
|
|
378
|
+
if (stop.signal.aborted) return;
|
|
379
|
+
core.peers = core.peers.map((peer) =>
|
|
380
|
+
peer.id === selfId ? peer : { ...peer, connected: false },
|
|
381
|
+
);
|
|
382
|
+
core.emit("peers", core.peers);
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const run = async () => {
|
|
386
|
+
for (let failures = 0; !stop.signal.aborted;) {
|
|
387
|
+
try {
|
|
388
|
+
await connectOnce();
|
|
389
|
+
failures = 0;
|
|
390
|
+
} catch (error) {
|
|
391
|
+
if (error instanceof NetError && error.fatal) return fail(error);
|
|
392
|
+
failures++;
|
|
393
|
+
}
|
|
394
|
+
if (stop.signal.aborted) return;
|
|
395
|
+
core.setStatus(core.status === "connecting" ? "connecting" : "reconnecting");
|
|
396
|
+
// A link that was up and went away is tried again at once: only attempts that fail back off.
|
|
397
|
+
if (failures > 0) await sleep(backoffMs(failures), stop.signal);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
void run();
|
|
401
|
+
|
|
402
|
+
const session: Session<Msg, Presence, State> = {
|
|
403
|
+
role: "peer",
|
|
404
|
+
selfId,
|
|
405
|
+
room,
|
|
406
|
+
get status() {
|
|
407
|
+
return core.status;
|
|
408
|
+
},
|
|
409
|
+
get peers() {
|
|
410
|
+
return core.peers;
|
|
411
|
+
},
|
|
412
|
+
get state() {
|
|
413
|
+
return mirror?.state;
|
|
414
|
+
},
|
|
415
|
+
send(msg, to) {
|
|
416
|
+
core.assertOpen();
|
|
417
|
+
if (to !== undefined) throw new Error("A peer can only send to the host; omit `to`");
|
|
418
|
+
if (link) sendFrames(encodeReliable({ t: "msg", d: msg }), link);
|
|
419
|
+
return link !== null;
|
|
420
|
+
},
|
|
421
|
+
sendPresence(value) {
|
|
422
|
+
core.assertOpen();
|
|
423
|
+
presence.push(encodeLossy({ d: value }));
|
|
424
|
+
},
|
|
425
|
+
on: core.on,
|
|
426
|
+
close() {
|
|
427
|
+
if (core.status === "closed") return;
|
|
428
|
+
stop.abort();
|
|
429
|
+
presence.stop();
|
|
430
|
+
link?.close();
|
|
431
|
+
link = null;
|
|
432
|
+
core.setStatus("closed");
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
return session;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
type ResolvedOptions<Msg, Presence> = Required<SessionOptions<Msg, Presence>>;
|
|
439
|
+
|
|
440
|
+
function resolveOptions<Msg, Presence>(
|
|
441
|
+
options: SessionOptions<Msg, Presence>,
|
|
442
|
+
): ResolvedOptions<Msg, Presence> {
|
|
443
|
+
const { selfId, name, transport, parseMsg, parsePresence, presenceHz = 30 } = options;
|
|
444
|
+
peerId(selfId);
|
|
445
|
+
const room = roomName(options.room);
|
|
446
|
+
if (typeof name !== "string" || name.trim() === "")
|
|
447
|
+
throw new TypeError("name must be a non-empty string");
|
|
448
|
+
if (
|
|
449
|
+
typeof transport?.listen !== "function" ||
|
|
450
|
+
typeof transport.connect !== "function" ||
|
|
451
|
+
typeof transport.watchRooms !== "function"
|
|
452
|
+
)
|
|
453
|
+
throw new TypeError(
|
|
454
|
+
"transport must come from createWebRtcTransport() or createMemoryTransport()",
|
|
455
|
+
);
|
|
456
|
+
if (typeof parseMsg !== "function" || typeof parsePresence !== "function")
|
|
457
|
+
throw new TypeError("parseMsg and parsePresence must be functions");
|
|
458
|
+
if (!Number.isFinite(presenceHz) || presenceHz <= 0 || presenceHz > 120)
|
|
459
|
+
throw new RangeError("presenceHz must be in (0, 120]");
|
|
460
|
+
return { selfId, name, transport, room, parseMsg, parsePresence, presenceHz };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
type Handlers<Msg, Presence, State> = {
|
|
464
|
+
[E in keyof SessionEvents<Msg, Presence, State>]: Set<SessionEvents<Msg, Presence, State>[E]>;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
function createCore<Msg, Presence, State>(config: ResolvedOptions<Msg, Presence>) {
|
|
468
|
+
type Events = SessionEvents<Msg, Presence, State>;
|
|
469
|
+
const handlers: Handlers<Msg, Presence, State> = {
|
|
470
|
+
message: new Set(),
|
|
471
|
+
presence: new Set(),
|
|
472
|
+
peers: new Set(),
|
|
473
|
+
state: new Set(),
|
|
474
|
+
status: new Set(),
|
|
475
|
+
error: new Set(),
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
const emit = <E extends keyof Events>(event: E, ...args: Parameters<Events[E]>) => {
|
|
479
|
+
for (const handler of handlers[event]) (handler as (...a: typeof args) => void)(...args);
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
const report = (error: NetError) => {
|
|
483
|
+
if (handlers.error.size === 0)
|
|
484
|
+
console.warn(`[net] ${error.code}: ${error.message}`, error.cause ?? "");
|
|
485
|
+
emit("error", error);
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
const core = {
|
|
489
|
+
status: "connecting" as ConnectionStatus,
|
|
490
|
+
peers: [] as PeerInfo[],
|
|
491
|
+
emit,
|
|
492
|
+
report,
|
|
493
|
+
on<E extends keyof Events>(event: E, handler: Events[E]) {
|
|
494
|
+
const set = handlers[event] as Set<Events[E]>;
|
|
495
|
+
set.add(handler);
|
|
496
|
+
return () => void set.delete(handler);
|
|
497
|
+
},
|
|
498
|
+
setStatus(status: ConnectionStatus) {
|
|
499
|
+
if (core.status === status || core.status === "closed") return;
|
|
500
|
+
core.status = status;
|
|
501
|
+
emit("status", status);
|
|
502
|
+
},
|
|
503
|
+
assertOpen() {
|
|
504
|
+
if (core.status === "closed") throw new Error("Session is closed");
|
|
505
|
+
},
|
|
506
|
+
/** Runs frame handling, turning protocol errors into reports so one bad frame never kills the link. */
|
|
507
|
+
guard(handle: () => void) {
|
|
508
|
+
try {
|
|
509
|
+
handle();
|
|
510
|
+
} catch (error) {
|
|
511
|
+
if (error instanceof NetError) report(error);
|
|
512
|
+
else throw error;
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
deliverMessage(raw: unknown, from: PeerId) {
|
|
516
|
+
let msg: Msg;
|
|
517
|
+
try {
|
|
518
|
+
msg = config.parseMsg(raw);
|
|
519
|
+
} catch (error) {
|
|
520
|
+
return report(
|
|
521
|
+
new NetError("invalid-message", `Dropped a message from ${from} that failed parsing`, {
|
|
522
|
+
cause: error,
|
|
523
|
+
}),
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
emit("message", msg, from);
|
|
527
|
+
},
|
|
528
|
+
parsePresence(raw: unknown): { value: Presence } | undefined {
|
|
529
|
+
try {
|
|
530
|
+
return { value: config.parsePresence(raw) };
|
|
531
|
+
} catch (error) {
|
|
532
|
+
report(
|
|
533
|
+
new NetError("invalid-presence", "Dropped presence that failed parsing", {
|
|
534
|
+
cause: error,
|
|
535
|
+
}),
|
|
536
|
+
);
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
return core;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Keeps only the newest frame and sends it at most `hz` times a second. A send the lane refuses keeps that frame
|
|
546
|
+
* pending for the next tick instead of queueing it, so a backed-up lane never replays stale values.
|
|
547
|
+
*/
|
|
548
|
+
function createPresenceSender(hz: number, send: (frame: Uint8Array) => boolean) {
|
|
549
|
+
const intervalMs = 1000 / hz;
|
|
550
|
+
let pending: Uint8Array | null = null;
|
|
551
|
+
let lastSentAt = -Infinity;
|
|
552
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
553
|
+
|
|
554
|
+
const schedule = () => {
|
|
555
|
+
if (timer !== null) return;
|
|
556
|
+
timer = setTimeout(flush, Math.max(0, lastSentAt + intervalMs - performance.now()));
|
|
557
|
+
};
|
|
558
|
+
const flush = () => {
|
|
559
|
+
timer = null;
|
|
560
|
+
if (!pending) return;
|
|
561
|
+
lastSentAt = performance.now();
|
|
562
|
+
if (send(pending)) pending = null;
|
|
563
|
+
else schedule();
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
return {
|
|
567
|
+
push(frame: Uint8Array) {
|
|
568
|
+
pending = frame;
|
|
569
|
+
schedule();
|
|
570
|
+
},
|
|
571
|
+
stop() {
|
|
572
|
+
if (timer !== null) clearTimeout(timer);
|
|
573
|
+
timer = null;
|
|
574
|
+
pending = null;
|
|
575
|
+
},
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function backoffMs(failures: number): number {
|
|
580
|
+
const base = Math.min(5_000, 250 * 2 ** failures);
|
|
581
|
+
return base / 2 + (Math.random() * base) / 2;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
585
|
+
return new Promise((resolve) => {
|
|
586
|
+
const timer = setTimeout(done, ms);
|
|
587
|
+
signal.addEventListener("abort", done, { once: true });
|
|
588
|
+
function done() {
|
|
589
|
+
clearTimeout(timer);
|
|
590
|
+
signal.removeEventListener("abort", done);
|
|
591
|
+
resolve();
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire contract between the WebRTC transport and the signaling Worker. Pure types and constants, because the Worker
|
|
3
|
+
* type-checks this file without the DOM lib.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Peer ids and room names. */
|
|
7
|
+
export const ID_PATTERN = /^[\w-]{1,64}$/;
|
|
8
|
+
|
|
9
|
+
/** The room of a game that never names one. */
|
|
10
|
+
export const DEFAULT_ROOM = "main";
|
|
11
|
+
|
|
12
|
+
/** How long the JSON of what a host publishes about its room may be. A socket attachment holds 16 KiB. */
|
|
13
|
+
export const MAX_ROOM_INFO_LENGTH = 2048;
|
|
14
|
+
|
|
15
|
+
/** `watch` is a browser showing the room list. It takes part in no room. */
|
|
16
|
+
export type SignalRole = "host" | "peer" | "watch";
|
|
17
|
+
|
|
18
|
+
/** `gone` closes a host that stopped answering once someone else wants its room. Only the others end a session. */
|
|
19
|
+
export const SignalClose = {
|
|
20
|
+
replaced: 4000,
|
|
21
|
+
unauthorized: 4001,
|
|
22
|
+
gone: 4002,
|
|
23
|
+
hostTaken: 4009,
|
|
24
|
+
} as const;
|
|
25
|
+
|
|
26
|
+
/** The only frame the Worker answers without waking the Durable Object. */
|
|
27
|
+
export const KEEPALIVE = { ping: "ping", pong: "pong" } as const;
|
|
28
|
+
|
|
29
|
+
/** A room whose host published something about it. `info` is whatever the game put there. */
|
|
30
|
+
export type RoomListing = { room: string; host: string; info: unknown };
|
|
31
|
+
|
|
32
|
+
export type ClientMessage =
|
|
33
|
+
| { t: "signal"; to: string; data: unknown }
|
|
34
|
+
/** From a host: what the room list shows for its room, or null to take the room off the list. */
|
|
35
|
+
| { t: "publish"; info: unknown };
|
|
36
|
+
|
|
37
|
+
/** An `RTCIceServer`, spelled out because the Worker has no DOM types. */
|
|
38
|
+
export type IceServer = { urls: string | string[]; username?: string; credential?: string };
|
|
39
|
+
|
|
40
|
+
export type ServerMessage =
|
|
41
|
+
/** Sent first, before anything that starts a connection: relays for players whom no direct path reaches. */
|
|
42
|
+
| { t: "ice"; servers: IceServer[] }
|
|
43
|
+
| { t: "ready" }
|
|
44
|
+
/** To a peer: who hosts its room, or null while nobody does. */
|
|
45
|
+
| { t: "host"; id: string | null }
|
|
46
|
+
| { t: "signal"; from: string; data: unknown }
|
|
47
|
+
/** To a watcher: every listed room, on connecting and after each change. */
|
|
48
|
+
| { t: "rooms"; rooms: RoomListing[] };
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { RoomListing } from "./signal-protocol.ts";
|
|
2
|
+
import type { NetError, PeerId } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The largest frame a transport must carry. 16 KiB is the size every browser pair exchanges over SCTP without
|
|
6
|
+
* fragmentation trouble; the session chunks anything bigger.
|
|
7
|
+
*/
|
|
8
|
+
export const MAX_FRAME_BYTES = 16 * 1024;
|
|
9
|
+
|
|
10
|
+
export type Lane = "reliable" | "lossy";
|
|
11
|
+
|
|
12
|
+
export type LinkHandlers = {
|
|
13
|
+
frame: (lane: Lane, frame: Uint8Array) => void;
|
|
14
|
+
/** The remote side went away. Not called for a local `close()`. */
|
|
15
|
+
close: () => void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** One host-to-peer connection with an ordered reliable lane and an unordered lossy lane. */
|
|
19
|
+
export interface Link {
|
|
20
|
+
readonly remoteId: PeerId;
|
|
21
|
+
sendReliable(frame: Uint8Array): void;
|
|
22
|
+
/** Returns false and drops the frame when the lane is backed up or closed. */
|
|
23
|
+
sendLossy(frame: Uint8Array): boolean;
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type ListenHandlers = {
|
|
28
|
+
/** A peer finished connecting. Return the handlers for its frames. */
|
|
29
|
+
link: (link: Link) => LinkHandlers;
|
|
30
|
+
status: (status: "connected" | "reconnecting") => void;
|
|
31
|
+
fail: (error: NetError) => void;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type ListenOptions = {
|
|
35
|
+
/** Host the room even when another client is hosting it. That client's session ends as `replaced`. */
|
|
36
|
+
takeover?: boolean;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type Listener = {
|
|
40
|
+
/** What the room list shows for this room, or null to take it off the list. */
|
|
41
|
+
publish(info: unknown): void;
|
|
42
|
+
close(): void;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type ConnectHandlers = LinkHandlers & {
|
|
46
|
+
/** The room has no host right now. The attempt goes on waiting for one. */
|
|
47
|
+
noHost: () => void;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** A network of rooms. A room has one host, and every other player in it holds a link to that host. */
|
|
51
|
+
export interface Transport {
|
|
52
|
+
listen(
|
|
53
|
+
room: string,
|
|
54
|
+
selfId: PeerId,
|
|
55
|
+
handlers: ListenHandlers,
|
|
56
|
+
options?: ListenOptions,
|
|
57
|
+
): Listener;
|
|
58
|
+
/**
|
|
59
|
+
* Resolves once both lanes are open, however long the room waits for a host. Rejects with a fatal NetError, or
|
|
60
|
+
* anything else to mean "retry", which is also how a connection that will not open in reasonable time ends.
|
|
61
|
+
*/
|
|
62
|
+
connect(
|
|
63
|
+
room: string,
|
|
64
|
+
selfId: PeerId,
|
|
65
|
+
handlers: ConnectHandlers,
|
|
66
|
+
signal: AbortSignal,
|
|
67
|
+
): Promise<Link>;
|
|
68
|
+
/** Calls `handler` with every listed room, now and after each change, until the function it returns is called. */
|
|
69
|
+
watchRooms(handler: (rooms: RoomListing[]) => void): () => void;
|
|
70
|
+
}
|