@spooky-sync/core 1.0.0-beta.8 → 1.0.0-beta.9

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.
@@ -0,0 +1,383 @@
1
+ import type { HubBus, HubLocks } from './hub';
2
+ import type { RoomLinkFactory, RoomLinkHooks, RoomPeer } from './room';
3
+
4
+ /**
5
+ * Stand-ins for what the room code talks to: the relay (speaking protocol v1
6
+ * as `apps/relay` documents it), a browser's Web Locks and BroadcastChannel,
7
+ * and a WebRTC peer connection.
8
+ */
9
+
10
+ // ---- the relay ---------------------------------------------------------------------
11
+
12
+ interface Member {
13
+ readonly socket: FakeSocket;
14
+ readonly user: string;
15
+ readonly peer: string;
16
+ }
17
+
18
+ /** `t-<name>` is the session token of `user:<name>`; anything else is refused. */
19
+ const userOf = (token: unknown): string | null => (typeof token === 'string' && token.startsWith('t-') ? `user:${token.slice(2)}` : null);
20
+
21
+ export class FakeSocket {
22
+ readyState = 0;
23
+ onopen: (() => void) | null = null;
24
+ onmessage: ((event: { data: unknown }) => void) | null = null;
25
+ onclose: (() => void) | null = null;
26
+ onerror: (() => void) | null = null;
27
+ /** Every frame the client sent, parsed. */
28
+ readonly sent: Array<Record<string, unknown>> = [];
29
+ member: Member | null = null;
30
+
31
+ constructor(
32
+ readonly relay: FakeRelay,
33
+ readonly url: string
34
+ ) {
35
+ relay.sockets.push(this);
36
+ queueMicrotask(() => {
37
+ if (this.readyState !== 0) return;
38
+ if (relay.down) return this.drop();
39
+ this.readyState = 1;
40
+ this.onopen?.();
41
+ });
42
+ }
43
+
44
+ send(text: string): void {
45
+ if (this.readyState !== 1) throw new Error('socket is not open');
46
+ const frame = JSON.parse(text) as Record<string, unknown>;
47
+ this.sent.push(frame);
48
+ queueMicrotask(() => this.relay.receive(this, frame));
49
+ }
50
+
51
+ /** The relay's side: a frame for the client. */
52
+ push(frame: unknown): void {
53
+ const text = JSON.stringify(frame);
54
+ queueMicrotask(() => {
55
+ if (this.readyState === 1) this.onmessage?.({ data: text });
56
+ });
57
+ }
58
+
59
+ close(): void {
60
+ this.drop();
61
+ }
62
+
63
+ /** The connection ends, from either side. */
64
+ drop(): void {
65
+ if (this.readyState === 3) return;
66
+ this.readyState = 3;
67
+ this.relay.left(this);
68
+ queueMicrotask(() => this.onclose?.());
69
+ }
70
+
71
+ /**
72
+ * The connection dies where only the client can tell (a phone changing
73
+ * networks): the relay still holds the seat, until it times the socket out
74
+ * or the same peer says hello again.
75
+ */
76
+ sever(): void {
77
+ if (this.readyState === 3) return;
78
+ this.readyState = 3;
79
+ queueMicrotask(() => this.onclose?.());
80
+ }
81
+ }
82
+
83
+ export class FakeRelay {
84
+ readonly sockets: FakeSocket[] = [];
85
+ readonly rooms = new Map<string, Map<string, Member>>();
86
+ /** Refuse every connection, as an unreachable relay does. */
87
+ down = false;
88
+ /** Answer the next hello with this error code instead of a welcome. */
89
+ refuseWith: string | null = null;
90
+ /** Do not answer pings (a dead connection the client has to notice). */
91
+ mute = false;
92
+ /** Frames forwarded between members: how much went through the relay. */
93
+ forwarded = 0;
94
+
95
+ /** What `roomLink` takes as its `WebSocket`. */
96
+ get WebSocket(): typeof WebSocket {
97
+ const open = (url: string): FakeSocket => new FakeSocket(this, url);
98
+ // Called with `new`: a function that returns an object hands that object out.
99
+ return function (url: string) {
100
+ return open(url);
101
+ } as unknown as typeof WebSocket;
102
+ }
103
+
104
+ receive(socket: FakeSocket, frame: Record<string, unknown>): void {
105
+ if (socket.readyState !== 1) return;
106
+ if (!socket.member) {
107
+ const user = userOf(frame.token);
108
+ const code = this.refuseWith ?? (frame.t !== 'hello' || typeof frame.peer !== 'string' ? 'bad_request' : user ? null : 'unauthorized');
109
+ if (code || !user) {
110
+ this.refuseWith = null;
111
+ socket.push({ t: 'error', code });
112
+ queueMicrotask(() => socket.drop());
113
+ return;
114
+ }
115
+ const room = this.rooms.get(user) ?? new Map<string, Member>();
116
+ this.rooms.set(user, room);
117
+ const peer = frame.peer as string;
118
+ const member: Member = { socket, user, peer };
119
+ socket.member = member;
120
+ socket.push({ t: 'welcome', user, peer, peers: [...room.keys()].filter((p) => p !== peer) });
121
+ // The same peer again takes the seat: the old connection is told, and
122
+ // the others hear it left and came back.
123
+ const old = room.get(peer);
124
+ if (old) {
125
+ old.socket.push({ t: 'error', code: 'replaced' });
126
+ old.socket.member = null;
127
+ if (old.socket.readyState !== 3) queueMicrotask(() => old.socket.drop());
128
+ for (const other of room.values()) if (other.peer !== peer) other.socket.push({ t: 'leave', peer });
129
+ }
130
+ for (const other of room.values()) if (other.peer !== peer) other.socket.push({ t: 'join', peer });
131
+ room.set(peer, member);
132
+ return;
133
+ }
134
+ if (frame.t === 'ping') {
135
+ if (!this.mute) socket.push({ t: 'pong' });
136
+ return;
137
+ }
138
+ if (frame.t !== 'msg') return;
139
+ const { user, peer } = socket.member;
140
+ const to = Array.isArray(frame.to) ? (frame.to as string[]) : null;
141
+ for (const other of this.rooms.get(user)?.values() ?? []) {
142
+ if (other.peer === peer || (to && !to.includes(other.peer))) continue;
143
+ this.forwarded++;
144
+ other.socket.push({ t: 'msg', from: peer, d: frame.d });
145
+ }
146
+ }
147
+
148
+ left(socket: FakeSocket): void {
149
+ const member = socket.member;
150
+ if (!member) return;
151
+ socket.member = null;
152
+ const room = this.rooms.get(member.user);
153
+ if (room?.get(member.peer) !== member) return;
154
+ room.delete(member.peer);
155
+ if (room.size === 0) this.rooms.delete(member.user);
156
+ for (const other of room.values()) other.socket.push({ t: 'leave', peer: member.peer });
157
+ }
158
+
159
+ /** The relay tells a member something and hangs up (`reauth`, `replaced`, ...). */
160
+ kick(user: string, peer: string, code: string): void {
161
+ const member = this.rooms.get(user)?.get(peer);
162
+ if (!member) return;
163
+ member.socket.push({ t: 'error', code });
164
+ queueMicrotask(() => member.socket.drop());
165
+ }
166
+ }
167
+
168
+ // ---- a room without a relay: links that reach each other at once ------------------------
169
+
170
+ /** `RoomLink`s of one user's browsers, wired to each other in memory. */
171
+ export function memoryRoom() {
172
+ const members = new Map<RoomPeer, RoomLinkHooks>();
173
+ const frames: Array<{ from: RoomPeer; to: ReadonlyArray<RoomPeer> | null; data: unknown }> = [];
174
+ const link: RoomLinkFactory = (hooks) => {
175
+ const self = hooks.self();
176
+ if (!self) throw new Error('a link needs somebody signed in');
177
+ const id = self.peer;
178
+ let open = true;
179
+ queueMicrotask(() => {
180
+ if (!open) return;
181
+ // A member before it hears of the others, as after a relay's welcome:
182
+ // what it sends them on hearing of them goes out.
183
+ const others = [...members];
184
+ members.set(id, hooks);
185
+ hooks.onStatus('connected');
186
+ for (const [peer, other] of others) {
187
+ hooks.onPeer(peer, true);
188
+ other.onPeer(id, true);
189
+ }
190
+ });
191
+ return {
192
+ send(to, data) {
193
+ if (!open || !members.has(id)) return;
194
+ frames.push({ from: id, to, data });
195
+ const copy = JSON.stringify(data);
196
+ for (const [peer, other] of members) {
197
+ if (peer === id || (to && !to.includes(peer))) continue;
198
+ queueMicrotask(() => {
199
+ if (members.get(peer) === other) other.onMessage(id, JSON.parse(copy));
200
+ });
201
+ }
202
+ },
203
+ close() {
204
+ if (!open) return;
205
+ open = false;
206
+ if (!members.delete(id)) return;
207
+ for (const other of members.values()) other.onPeer(id, false);
208
+ },
209
+ };
210
+ };
211
+ return { link, members, frames };
212
+ }
213
+
214
+ // ---- a browser: its Web Locks and its BroadcastChannels ----------------------------------
215
+
216
+ interface Waiter {
217
+ readonly shared: boolean;
218
+ readonly grant: () => void;
219
+ }
220
+
221
+ /** One browser profile: tabs made from it see each other's locks and broadcasts. */
222
+ export function fakeBrowser() {
223
+ const held = new Map<string, { shared: boolean; count: number }>();
224
+ const queues = new Map<string, Waiter[]>();
225
+ const buses = new Map<string, Set<FakeBus>>();
226
+
227
+ const pump = (name: string): void => {
228
+ const queue = queues.get(name) ?? [];
229
+ while (queue.length > 0) {
230
+ const lock = held.get(name);
231
+ const next = queue[0];
232
+ if (lock && !(lock.shared && next.shared)) return;
233
+ queue.shift();
234
+ held.set(name, { shared: next.shared, count: (lock?.count ?? 0) + 1 });
235
+ next.grant();
236
+ }
237
+ };
238
+
239
+ const locks: HubLocks = {
240
+ request(name: string, a: unknown, b?: unknown): Promise<unknown> {
241
+ const hold = (typeof a === 'function' ? a : b) as () => Promise<void> | void;
242
+ const shared = typeof a === 'object' && a !== null && (a as { mode?: string }).mode === 'shared';
243
+ return new Promise<void>((resolve) => {
244
+ const queue = queues.get(name) ?? [];
245
+ queues.set(name, queue);
246
+ queue.push({
247
+ shared,
248
+ grant: () => {
249
+ void Promise.resolve()
250
+ .then(() => hold())
251
+ .finally(() => {
252
+ const lock = held.get(name);
253
+ if (lock && --lock.count === 0) held.delete(name);
254
+ resolve();
255
+ pump(name);
256
+ });
257
+ },
258
+ });
259
+ pump(name);
260
+ });
261
+ },
262
+ };
263
+
264
+ class FakeBus implements HubBus {
265
+ onmessage: ((event: { data: unknown }) => void) | null = null;
266
+ /** A crashed tab: it says nothing anymore, not even goodbye. */
267
+ silent = false;
268
+ closed = false;
269
+ constructor(readonly name: string) {
270
+ const set = buses.get(name) ?? new Set<FakeBus>();
271
+ buses.set(name, set);
272
+ set.add(this);
273
+ }
274
+ postMessage(message: unknown): void {
275
+ if (this.closed || this.silent) return;
276
+ const copy = JSON.stringify(message);
277
+ for (const other of buses.get(this.name) ?? []) {
278
+ if (other === this) continue;
279
+ queueMicrotask(() => {
280
+ if (!other.closed) other.onmessage?.({ data: JSON.parse(copy) });
281
+ });
282
+ }
283
+ }
284
+ close(): void {
285
+ this.closed = true;
286
+ buses.get(this.name)?.delete(this);
287
+ }
288
+ }
289
+
290
+ const opened: FakeBus[] = [];
291
+ const bus = (name: string): HubBus => {
292
+ const b = new FakeBus(name);
293
+ opened.push(b);
294
+ return b;
295
+ };
296
+ return { locks, bus, held, opened };
297
+ }
298
+
299
+ // ---- WebRTC ----------------------------------------------------------------------------
300
+
301
+ class FakeDataChannel {
302
+ readyState = 'connecting';
303
+ onopen: (() => void) | null = null;
304
+ onclose: (() => void) | null = null;
305
+ onmessage: ((e: { data: unknown }) => void) | null = null;
306
+ other: FakeDataChannel | null = null;
307
+ send(data: string) {
308
+ queueMicrotask(() => this.other?.onmessage?.({ data }));
309
+ }
310
+ close() {
311
+ if (this.readyState === 'closed') return;
312
+ this.readyState = 'closed';
313
+ this.onclose?.();
314
+ this.other?.close();
315
+ }
316
+ open() {
317
+ this.readyState = 'open';
318
+ this.onopen?.();
319
+ }
320
+ }
321
+
322
+ /** Peer connections that find each other through the SDPs they exchange. */
323
+ export function fakeWebRtc() {
324
+ const offers = new Map<string, FakePC>();
325
+ const all = new Set<FakePC>();
326
+ let seq = 0;
327
+ /** Data channels that opened: how many direct links there were. */
328
+ const stats = { opened: 0 };
329
+
330
+ class FakePC {
331
+ connectionState = 'new';
332
+ localDescription: { type: string; sdp: string } | null = null;
333
+ onicecandidate: ((e: { candidate: { toJSON(): unknown } | null }) => void) | null = null;
334
+ onconnectionstatechange: (() => void) | null = null;
335
+ ondatachannel: ((e: { channel: FakeDataChannel }) => void) | null = null;
336
+ dc: FakeDataChannel | null = null;
337
+ remote: FakePC | null = null;
338
+ constructor() {
339
+ all.add(this);
340
+ }
341
+ createDataChannel() {
342
+ this.dc = new FakeDataChannel();
343
+ return this.dc;
344
+ }
345
+ async createOffer() {
346
+ const sdp = `offer-${++seq}`;
347
+ offers.set(sdp, this);
348
+ return { type: 'offer', sdp };
349
+ }
350
+ async createAnswer() {
351
+ return { type: 'answer', sdp: `answer-${++seq}` };
352
+ }
353
+ async setLocalDescription(d: { type: string; sdp: string }) {
354
+ this.localDescription = d;
355
+ queueMicrotask(() => this.onicecandidate?.({ candidate: { toJSON: () => ({ candidate: 'c' }) } }));
356
+ }
357
+ async setRemoteDescription(d: { type: string; sdp: string }) {
358
+ if (d.type === 'offer') this.remote = offers.get(d.sdp) ?? null;
359
+ if (d.type !== 'answer') return;
360
+ const answerer = [...all].find((p) => p.remote === this);
361
+ if (!answerer || !this.dc) return;
362
+ const theirs = new FakeDataChannel();
363
+ this.dc.other = theirs;
364
+ theirs.other = this.dc;
365
+ answerer.ondatachannel?.({ channel: theirs });
366
+ queueMicrotask(() => {
367
+ stats.opened++;
368
+ this.dc?.open();
369
+ theirs.open();
370
+ });
371
+ }
372
+ async addIceCandidate() {}
373
+ close() {
374
+ this.dc?.close();
375
+ }
376
+ }
377
+ return { RTCPeerConnection: FakePC as unknown as typeof RTCPeerConnection, stats };
378
+ }
379
+
380
+ /** Let queued microtasks and zero-delay timers run. */
381
+ export const settle = async (turns = 30): Promise<void> => {
382
+ for (let i = 0; i < turns; i++) await new Promise((r) => setTimeout(r, 0));
383
+ };