Repository navigation
Expand file tree
/
Copy pathrealtime.ts
More file actions
464 lines (396 loc) · 13.7 KB
/
Copy pathrealtime.ts
File metadata and controls
464 lines (396 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import type { LiveTransport } from '@inertiajs/core';
export type RealtimeChannel = {
name: string;
type: 'public' | 'private';
};
export type RealtimeHandler = (payload: unknown) => void;
/**
* The part of Laravel Echo this needs, so anything speaking the Pusher protocol fits, and tests can stand in for it.
*/
export interface RealtimeChannelHandle {
listen(event: string, callback: RealtimeHandler): unknown;
stopListening(event: string, callback: RealtimeHandler): unknown;
subscribed(callback: () => void): unknown;
error(callback: (status: unknown) => void): unknown;
listenToAll(callback: (event: string, payload: unknown) => void): unknown;
}
export interface RealtimeConnection {
channel(name: string): RealtimeChannelHandle;
private(name: string): RealtimeChannelHandle;
leaveChannel(name: string): void;
socketId(): string | undefined;
connector: {
onConnectionChange(callback: (status: string) => void): () => void;
};
}
type ChannelEntry = {
handle: RealtimeChannelHandle;
events: Map<
string,
{ dispatch: RealtimeHandler; handlers: Set<RealtimeHandler> }
>;
syncs: Set<() => void>;
isSubscribed: boolean;
subscribedAt: number | null;
heardAt: Map<string, number>;
leaveTimer: ReturnType<typeof setTimeout> | undefined;
};
/**
* A channel nobody listens to any more is left a moment later, so a page swapping listeners does not rejoin it.
*/
const leaveDelay = 1_000;
/**
* When what the page shows was read, by the browser's clock: when the visit that brought it started, which is no later
* than the server read it. Null while the page shows what was read at a time nobody knows, like a page brought back
* from history, so everything listening on it catches up.
*/
let pageRead: number | null = null;
const liveRefreshers = new Set<() => void>();
let connection: RealtimeConnection | null = null;
let isConnected = false;
let stopWatchingConnection = () => {};
const channels = new Map<string, ChannelEntry>();
const changeListeners = new Set<() => void>();
const keyOf = (channel: RealtimeChannel): string =>
channel.type === 'private' ? `private-${channel.name}` : channel.name;
const notifyChange = (): void =>
changeListeners.forEach((listener) => listener());
/**
* Starts listening through the given connection, or through none at all, in which case nothing is ever heard and
* every page keeps polling as it did before live updates.
*/
export function connectRealtime(next: RealtimeConnection | null): void {
stopWatchingConnection();
channels.forEach((entry) => clearTimeout(entry.leaveTimer));
channels.clear();
connection = next;
isConnected = false;
stopWatchingConnection =
next?.connector.onConnectionChange((status) => {
const connected = status === 'connected';
if (!connected) {
channels.forEach((entry) => {
entry.isSubscribed = false;
entry.subscribedAt = null;
});
}
if (connected !== isConnected) {
isConnected = connected;
notifyChange();
}
}) ?? (() => {});
notifyChange();
}
function entryFor(channel: RealtimeChannel, socket: RealtimeConnection) {
const key = keyOf(channel);
const existing = channels.get(key);
if (existing) {
clearTimeout(existing.leaveTimer);
existing.leaveTimer = undefined;
return existing;
}
const handle =
channel.type === 'private'
? socket.private(channel.name)
: socket.channel(channel.name);
const entry: ChannelEntry = {
handle,
events: new Map(),
syncs: new Set(),
isSubscribed: false,
subscribedAt: null,
heardAt: new Map(),
leaveTimer: undefined,
};
handle.listenToAll((event) =>
entry.heardAt.set(event.replace(/^\./, ''), Date.now()),
);
// Joining again after a dropped connection is when updates may have been missed, so each listener catches up.
handle.subscribed(() => {
entry.isSubscribed = true;
entry.subscribedAt = Date.now();
entry.syncs.forEach((sync) => sync());
notifyChange();
});
handle.error(() => {
entry.isSubscribed = false;
notifyChange();
});
channels.set(key, entry);
return entry;
}
/**
* Listens for events on a channel, calling `onSync` whenever the channel is joined, at first and after every
* reconnection, since updates sent in between were never heard. Returns the function that stops listening.
*/
export function listen(
channel: RealtimeChannel,
events: Record<string, RealtimeHandler>,
onSync?: () => void,
): () => void {
const socket = connection;
if (socket === null) {
return () => {};
}
const key = keyOf(channel);
const entry = entryFor(channel, socket);
let isListening = true;
const sync = () => {
if (isListening && channels.get(key) === entry) {
onSync?.();
}
};
Object.entries(events).forEach(([event, handler]) => {
const listening = entry.events.get(event);
if (listening) {
listening.handlers.add(handler);
return;
}
const handlers = new Set([handler]);
const dispatch: RealtimeHandler = (payload) =>
handlers.forEach((listener) => listener(payload));
entry.events.set(event, { dispatch, handlers });
entry.handle.listen(`.${event}`, dispatch);
});
if (onSync) {
entry.syncs.add(onSync);
if (
entry.isSubscribed &&
mayHaveMissed(entry, Object.keys(events), pageRead)
) {
queueMicrotask(sync);
}
}
return () => {
if (!isListening || channels.get(key) !== entry) {
return;
}
isListening = false;
Object.entries(events).forEach(([event, handler]) => {
const listening = entry.events.get(event);
listening?.handlers.delete(handler);
if (listening?.handlers.size === 0) {
entry.events.delete(event);
entry.handle.stopListening(`.${event}`, listening.dispatch);
}
});
if (onSync) {
entry.syncs.delete(onSync);
}
if (entry.events.size === 0 && entry.syncs.size === 0) {
entry.leaveTimer = setTimeout(() => {
channels.delete(key);
socket.leaveChannel(key);
notifyChange();
}, leaveDelay);
}
};
}
/**
* A listener joining a channel someone already listens on missed what the channel heard since its data was read: it
* catches up when the channel was joined again since, or heard one of its events since, or when nobody knows when its
* data was read. However long ago that was, as a page can be read slowly or a part of it mount late.
*/
function mayHaveMissed(
entry: ChannelEntry,
events: string[],
readAt: number | null,
): boolean {
if (readAt === null || entry.subscribedAt === null) {
return true;
}
return (
entry.subscribedAt >= readAt ||
(events.length === 0
? [...entry.heardAt.values()]
: events.map((event) => entry.heardAt.get(event) ?? -Infinity)
).some((heardAt) => heardAt >= readAt)
);
}
/**
* When what the page shows was read, or null when nobody knows, as for a page brought back from history.
*/
export function pageReadTime(): number | null {
return pageRead;
}
/**
* Called when a page arrives from a visit that started at the given time: what it shows was read since.
*/
export function pageReadAt(at: number): void {
pageRead = at;
}
/**
* Called when a page comes back from history or a prefetch: what it shows was read at a time nobody knows, so
* everything listening on it catches up until the next visit, and live props are read again.
*/
export function catchUpAfterRestore(): void {
pageRead = null;
// The listeners already on the page catch up as well as the ones joining it, each once.
const syncs = new Set(liveRefreshers);
channels.forEach((entry) => entry.syncs.forEach((sync) => syncs.add(sync)));
syncs.forEach((sync) =>
queueMicrotask(() => {
if (
liveRefreshers.has(sync) ||
[...channels.values()].some((entry) => entry.syncs.has(sync))
) {
sync();
}
}),
);
}
/**
* Whether updates on the channel are being heard right now, so whoever relies on them can stop polling.
*/
export function isListening(channel: RealtimeChannel): boolean {
return isConnected && channels.get(keyOf(channel))?.isSubscribed === true;
}
/**
* Calls back whenever the connection or a channel's subscription changes, for pollers to pick their pace again.
*/
export function onRealtimeChange(listener: () => void): () => void {
changeListeners.add(listener);
return () => {
changeListeners.delete(listener);
};
}
/**
* Inertia's live props listen through the same channels, so a page and the stores beside it share one
* subscription. Joining a channel counts as an update, so props read before the page was listening catch up.
*/
export const liveTransport: LiveTransport = {
subscribe: (channel, event, handler) => {
const refresh = () => handler({});
const stop = listen(
{
name: channel.name,
type: channel.type === 'private' ? 'private' : 'public',
},
{ [event]: handler },
refresh,
);
liveRefreshers.add(refresh);
return () => {
liveRefreshers.delete(refresh);
stop();
};
},
socketId: () => connection?.socketId() ?? null,
};
export function userChannel(userId: string): RealtimeChannel {
return { name: `users.${userId}`, type: 'private' };
}
export function commitChannel(commitId: string): RealtimeChannel {
return { name: `commits.${commitId}`, type: 'public' };
}
export const logChannel: RealtimeChannel = { name: 'log', type: 'public' };
/**
* Waits until no visit is under way, as the one that muted someone, so reading again for what it changed doesn't hold
* it up. A visit starting while it waits is waited for too, though never longer than `atMost` in all, so visits that
* keep overlapping can't put reading again off for good. Listens from when it is made, so it knows of visits already
* under way when asked.
*/
export function visitsSettled(
on: (event: 'start' | 'finish', listener: () => void) => unknown,
atMost = 5_000,
): () => Promise<void> {
let active = 0;
let waiting: (() => void)[] = [];
on('start', () => {
active++;
});
on('finish', () => {
active = Math.max(0, active - 1);
if (active === 0) {
const settled = waiting;
waiting = [];
settled.forEach((resolve) => resolve());
}
});
return () =>
active === 0
? Promise.resolve()
: new Promise((resolve) => {
const timer = setTimeout(() => {
waiting = waiting.filter((other) => other !== done);
resolve();
}, atMost);
const done = () => {
clearTimeout(timer);
resolve();
};
waiting.push(done);
});
}
/**
* Runs reads at most `limit` at a time, in the order asked: many listeners reading again for the same change, as every
* thread on a page does when the viewer mutes someone, leave room for the page's own requests.
*/
export function atMostAtOnce(
limit: number,
): <T>(read: () => Promise<T>) => Promise<T> {
let running = 0;
const waiting: (() => void)[] = [];
// A read that finishes hands its place to the next one waiting, so none can start in between and run one too many.
return async (read) => {
if (running >= limit) {
await new Promise<void>((resolve) => waiting.push(resolve));
} else {
running++;
}
try {
return await read();
} finally {
const next = waiting.shift();
if (next) {
next();
} else {
running--;
}
}
};
}
/**
* Runs `refresh` once for a burst of requests, never twice at the same time, and once more afterwards when asked
* again while it ran, so the last request is always followed by a refresh that started after it.
*/
export function coalesce(
refresh: () => Promise<unknown>,
delay = 200,
): { request: () => void; cancel: () => void } {
let timer: ReturnType<typeof setTimeout> | undefined;
let isRunning = false;
let isRequestedAgain = false;
let isCancelled = false;
const schedule = () => {
timer ??= setTimeout(() => {
timer = undefined;
isRunning = true;
void refresh()
.catch(() => undefined)
.finally(() => {
isRunning = false;
if (isRequestedAgain && !isCancelled) {
isRequestedAgain = false;
schedule();
}
});
}, delay);
};
return {
request: () => {
if (isCancelled) {
return;
}
if (isRunning) {
isRequestedAgain = true;
return;
}
schedule();
},
cancel: () => {
isCancelled = true;
clearTimeout(timer);
},
};
}