@spooky-sync/core 1.0.0-beta.7 → 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,355 @@
1
+ import type { Logger } from '../../services/logger/index';
2
+ import type { ChannelTransport, PeerRef, TransportHooks } from './index';
3
+ import { roomSupported, type RoomLink, type RoomLinkFactory, type RoomPeer } from './room';
4
+
5
+ /**
6
+ * One link per browser, shared by its tabs.
7
+ *
8
+ * Every tab of a user runs this transport. One of them, the hub, holds the
9
+ * browser's link to the user's other browsers (`RoomLink`); which one is
10
+ * decided by a Web Lock, so when the hub's tab closes the next one takes over
11
+ * and connects. The other tabs reach the hub over a `BroadcastChannel`.
12
+ *
13
+ * To the `ChannelManager` nothing changes: a peer is still one tab. The hubs
14
+ * tell each other which tabs they speak for, every tab is told about the
15
+ * tabs of the other browsers, and a message names the tab it comes from and
16
+ * the tabs it is for. So a value a tab wrote still disappears with that tab,
17
+ * not with its browser.
18
+ *
19
+ * Tabs of one browser are not peers of each other here: they may share one
20
+ * local store, where a peer's write would be undone under the tab that made
21
+ * it.
22
+ *
23
+ * Where there are no Web Locks or no `BroadcastChannel`, every tab is a hub
24
+ * with a link of its own.
25
+ */
26
+
27
+ type Status = 'connecting' | 'connected' | 'failed';
28
+
29
+ /** What tabs of one browser say to each other. */
30
+ type Bus =
31
+ | { k: 'here'; tab: string }
32
+ | { k: 'bye'; tab: string }
33
+ | { k: 'hub'; tab: string }
34
+ | { k: 'remote'; browsers: Record<RoomPeer, string[]>; status: Status }
35
+ | { k: 'out'; tab: string; to: string[]; m: unknown }
36
+ | { k: 'in'; from: string; to: string[] | null; m: unknown };
37
+
38
+ /** What hubs say to each other over the link. */
39
+ type Between = { h: 'tabs'; tabs: string[] } | { h: 'm'; from: string; to: string[] | null; m: unknown };
40
+
41
+ /** The part of `navigator.locks` this needs. */
42
+ export interface HubLocks {
43
+ request(name: string, callback: () => Promise<void>): Promise<unknown>;
44
+ request(name: string, options: { mode: 'shared' | 'exclusive' }, callback: () => Promise<void> | void): Promise<unknown>;
45
+ }
46
+
47
+ /** The part of a `BroadcastChannel` this needs. */
48
+ export interface HubBus {
49
+ postMessage(message: unknown): void;
50
+ onmessage: ((event: { data: unknown }) => void) | null;
51
+ close(): void;
52
+ }
53
+
54
+ export interface HubOptions {
55
+ /** Names the room of one user in this browser; the lock and the bus carry it. */
56
+ scope: (user: string) => string;
57
+ /** Builds the browser's link. Called in the tab that holds it. */
58
+ link: RoomLinkFactory;
59
+ logger?: Pick<Logger, 'debug' | 'warn'>;
60
+ /** `null` forces a link per tab. Default `navigator.locks`. */
61
+ locks?: HubLocks | null;
62
+ /** `null` forces a link per tab. Default `BroadcastChannel`. */
63
+ bus?: ((name: string) => HubBus) | null;
64
+ supported?: boolean;
65
+ }
66
+
67
+ const MAX_TABS = 64;
68
+ const isTabId = (v: unknown): v is string => typeof v === 'string' && v.length > 0 && v.length <= 64;
69
+ const tabList = (v: unknown): string[] | null => (Array.isArray(v) && v.length <= MAX_TABS && v.every(isTabId) ? (v as string[]) : null);
70
+
71
+ const defaultLocks = (): HubLocks | null => (globalThis as { navigator?: { locks?: HubLocks } }).navigator?.locks ?? null;
72
+ const defaultBus = (): ((name: string) => HubBus) | null => {
73
+ const BC = (globalThis as { BroadcastChannel?: new (name: string) => HubBus }).BroadcastChannel;
74
+ return BC ? (name) => new BC(name) : null;
75
+ };
76
+
77
+ export function hubTransport(hooks: TransportHooks, opts: HubOptions): ChannelTransport {
78
+ const locks = opts.locks === undefined ? defaultLocks() : opts.locks;
79
+ const openBus = opts.bus === undefined ? defaultBus() : opts.bus;
80
+ const log = opts.logger;
81
+
82
+ /** This tab while it takes part, else null. */
83
+ let me: PeerRef | null = null;
84
+ /** Counts starts, so a lock granted for an earlier one does nothing. */
85
+ let run = 0;
86
+ let bus: HubBus | null = null;
87
+ let isHub = false;
88
+ let link: RoomLink | null = null;
89
+ let releaseHub: (() => void) | null = null;
90
+ let releaseTab: (() => void) | null = null;
91
+ /** The hub's: the other tabs of this browser. */
92
+ const localTabs = new Set<string>();
93
+ /** The other browsers and the tabs each speaks for. The hub's is the truth, the other tabs hold a copy. */
94
+ const browsers = new Map<RoomPeer, Set<string>>();
95
+ /** The tabs of other browsers this tab has reported as up. */
96
+ const up = new Set<string>();
97
+ let status: Status = 'connecting';
98
+ let reported: Status | null = null;
99
+ /** Messages of this turn, each with the tabs it goes to: one frame per message, not one per tab. */
100
+ const pending = new Map<unknown, string[]>();
101
+ let flushing = false;
102
+
103
+ const post = (message: Bus): void => {
104
+ try {
105
+ bus?.postMessage(message);
106
+ } catch (error) {
107
+ log?.debug({ error, Category: 'sp00ky-client::channel' }, 'channel bus post failed');
108
+ }
109
+ };
110
+
111
+ /** Tell the manager which tabs of other browsers came and went, and how the link is doing. */
112
+ const apply = (): void => {
113
+ const self = me;
114
+ if (!self) return;
115
+ const now = new Set<string>();
116
+ for (const tabs of browsers.values()) for (const t of tabs) if (t !== self.peer) now.add(t);
117
+ for (const t of [...up]) {
118
+ if (now.has(t)) continue;
119
+ up.delete(t);
120
+ hooks.onPeer({ user: self.user, peer: t }, false);
121
+ }
122
+ for (const t of now) {
123
+ if (up.has(t)) continue;
124
+ up.add(t);
125
+ hooks.onPeer({ user: self.user, peer: t }, true);
126
+ }
127
+ if (status !== reported) {
128
+ reported = status;
129
+ hooks.onStatus(self.user, status);
130
+ }
131
+ };
132
+
133
+ // ---- the hub -----------------------------------------------------------------
134
+
135
+ const publish = (): void => {
136
+ apply();
137
+ const out: Record<RoomPeer, string[]> = {};
138
+ for (const [b, tabs] of browsers) out[b] = [...tabs];
139
+ post({ k: 'remote', browsers: out, status });
140
+ };
141
+
142
+ /** The tabs this browser speaks for changed: the other hubs hear it. */
143
+ const announceTabs = (to: ReadonlyArray<RoomPeer> | null): void => {
144
+ if (me) link?.send(to, { h: 'tabs', tabs: [me.peer, ...localTabs] } satisfies Between);
145
+ };
146
+
147
+ const hubSend = (from: string, to: string[], m: unknown): void => {
148
+ const dest: RoomPeer[] = [];
149
+ for (const [b, tabs] of browsers) if (to.some((t) => tabs.has(t))) dest.push(b);
150
+ if (dest.length > 0) link?.send(dest.length === browsers.size ? null : dest, { h: 'm', from, to, m } satisfies Between);
151
+ };
152
+
153
+ /** A message of another browser's tab: to this tab, and on to the others it names. */
154
+ const deliver = (from: string, to: string[] | null, m: unknown): void => {
155
+ const self = me;
156
+ if (!self) return;
157
+ if (localTabs.size > 0 && (to === null || to.some((t) => localTabs.has(t)))) post({ k: 'in', from, to, m });
158
+ if (to === null || to.includes(self.peer)) hooks.onMessage({ user: self.user, peer: from }, m);
159
+ };
160
+
161
+ /** Hold on to a tab of this browser until it is gone, however it goes. */
162
+ const watch = (tab: string, at: number): void => {
163
+ if (!locks) return;
164
+ // Every tab holds a lock under its own name for as long as it lives, so
165
+ // this request is granted the moment that tab is gone.
166
+ void locks
167
+ .request(tabLock(tab), { mode: 'shared' }, () => {
168
+ if (at === run && isHub && localTabs.delete(tab)) announceTabs(null);
169
+ })
170
+ .catch(() => {});
171
+ };
172
+
173
+ const becomeHub = (self: PeerRef): void => {
174
+ isHub = true;
175
+ browsers.clear();
176
+ status = 'connecting';
177
+ link = opts.link({
178
+ self: () => (me ? { user: me.user, peer: me.peer } : null),
179
+ onPeer: (browser, isUp) => {
180
+ if (isUp) {
181
+ browsers.set(browser, new Set());
182
+ announceTabs([browser]);
183
+ } else if (!browsers.delete(browser)) return;
184
+ publish();
185
+ },
186
+ onMessage: (browser, data) => {
187
+ const tabs = browsers.get(browser);
188
+ if (!tabs || data === null || typeof data !== 'object') return;
189
+ const d = data as Partial<Between> & Record<string, unknown>;
190
+ if (d.h === 'tabs') {
191
+ const list = tabList(d.tabs);
192
+ if (!list) return;
193
+ browsers.set(browser, new Set(list));
194
+ publish();
195
+ } else if (d.h === 'm') {
196
+ const to = d.to === null ? null : tabList(d.to);
197
+ // A hub speaks for its own tabs only.
198
+ if (!isTabId(d.from) || !tabs.has(d.from) || (d.to !== null && to === null)) return;
199
+ deliver(d.from, to, d.m);
200
+ }
201
+ },
202
+ onStatus: (next) => {
203
+ status = next;
204
+ publish();
205
+ },
206
+ });
207
+ post({ k: 'hub', tab: self.peer });
208
+ publish();
209
+ };
210
+
211
+ // ---- every tab ---------------------------------------------------------------
212
+
213
+ const hubLock = (): string => `sp00ky-channels:${opts.scope(me?.user ?? '')}`;
214
+ const tabLock = (tab: string): string => `${hubLock()}:tab:${tab}`;
215
+
216
+ const onBus = (data: unknown): void => {
217
+ const self = me;
218
+ if (!self || data === null || typeof data !== 'object') return;
219
+ const msg = data as Bus;
220
+ switch (msg.k) {
221
+ case 'here':
222
+ if (!isHub || !isTabId(msg.tab) || msg.tab === self.peer) return;
223
+ if (!localTabs.has(msg.tab)) {
224
+ localTabs.add(msg.tab);
225
+ watch(msg.tab, run);
226
+ announceTabs(null);
227
+ }
228
+ publish();
229
+ return;
230
+ case 'bye':
231
+ if (isHub && localTabs.delete(msg.tab)) announceTabs(null);
232
+ return;
233
+ case 'hub':
234
+ // A tab took the link over: it starts out knowing nobody.
235
+ if (!isHub) post({ k: 'here', tab: self.peer });
236
+ return;
237
+ case 'remote': {
238
+ if (isHub || msg.browsers === null || typeof msg.browsers !== 'object') return;
239
+ browsers.clear();
240
+ for (const [b, tabs] of Object.entries(msg.browsers)) {
241
+ const list = tabList(tabs);
242
+ if (list) browsers.set(b, new Set(list));
243
+ }
244
+ status = msg.status;
245
+ apply();
246
+ return;
247
+ }
248
+ case 'out':
249
+ if (isHub && localTabs.has(msg.tab) && tabList(msg.to)) hubSend(msg.tab, msg.to, msg.m);
250
+ return;
251
+ case 'in':
252
+ if (!isHub && (msg.to === null || (Array.isArray(msg.to) && msg.to.includes(self.peer)))) {
253
+ hooks.onMessage({ user: self.user, peer: msg.from }, msg.m);
254
+ }
255
+ return;
256
+ }
257
+ };
258
+
259
+ const flush = (): void => {
260
+ flushing = false;
261
+ const self = me;
262
+ const batch = [...pending];
263
+ pending.clear();
264
+ if (!self) return;
265
+ for (const [m, to] of batch) {
266
+ if (isHub) hubSend(self.peer, to, m);
267
+ else post({ k: 'out', tab: self.peer, to, m });
268
+ }
269
+ };
270
+
271
+ const start = (self: PeerRef): void => {
272
+ me = self;
273
+ const at = ++run;
274
+ status = 'connecting';
275
+ reported = null;
276
+ if (!locks || !openBus) {
277
+ becomeHub(self);
278
+ return;
279
+ }
280
+ bus = openBus(hubLock());
281
+ bus.onmessage = (event) => onBus(event.data);
282
+ // The tab's own lock first: a hub that hears `here` waits on it to learn
283
+ // when this tab is gone, so it has to be held by then.
284
+ void locks
285
+ .request(
286
+ tabLock(self.peer),
287
+ () =>
288
+ new Promise<void>((resolve) => {
289
+ if (at !== run) return resolve();
290
+ releaseTab = resolve;
291
+ if (!isHub) post({ k: 'here', tab: self.peer });
292
+ })
293
+ )
294
+ .catch(() => {});
295
+ void locks
296
+ .request(
297
+ hubLock(),
298
+ () =>
299
+ new Promise<void>((resolve) => {
300
+ if (at !== run) return resolve();
301
+ releaseHub = resolve;
302
+ becomeHub(self);
303
+ })
304
+ )
305
+ .catch(() => {});
306
+ };
307
+
308
+ const stop = (): void => {
309
+ const self = me;
310
+ if (!self) return;
311
+ if (!isHub) post({ k: 'bye', tab: self.peer });
312
+ run++;
313
+ link?.close();
314
+ link = null;
315
+ isHub = false;
316
+ releaseHub?.();
317
+ releaseTab?.();
318
+ releaseHub = null;
319
+ releaseTab = null;
320
+ try {
321
+ bus?.close();
322
+ } catch {
323
+ // already closed
324
+ }
325
+ bus = null;
326
+ localTabs.clear();
327
+ browsers.clear();
328
+ pending.clear();
329
+ for (const t of [...up]) hooks.onPeer({ user: self.user, peer: t }, false);
330
+ up.clear();
331
+ me = null;
332
+ };
333
+
334
+ return {
335
+ supported: opts.supported ?? roomSupported(),
336
+ want(users) {
337
+ const self = hooks.self();
338
+ const wanted = self !== null && users.has(self.user);
339
+ if (me && (!wanted || !self || self.user !== me.user || self.peer !== me.peer)) stop();
340
+ if (wanted && self && !me) start(self);
341
+ },
342
+ send(to, message) {
343
+ if (!me || to.user !== me.user) return;
344
+ const list = pending.get(message);
345
+ if (list) list.push(to.peer);
346
+ else pending.set(message, [to.peer]);
347
+ if (flushing) return;
348
+ flushing = true;
349
+ void Promise.resolve().then(flush);
350
+ },
351
+ close() {
352
+ stop();
353
+ },
354
+ };
355
+ }