@caprid/relay 0.4.1 → 0.5.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/README.md +4 -3
- package/dist/connect.d.ts +40 -5
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +19 -3
- package/dist/connect.js.map +1 -1
- package/dist/discovery.d.ts +38 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +273 -0
- package/dist/discovery.js.map +1 -0
- package/dist/frame-writer.d.ts +1 -2
- package/dist/frame-writer.d.ts.map +1 -1
- package/dist/frame-writer.js.map +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/media-track-properties.js +1 -1
- package/dist/media-track-properties.js.map +1 -1
- package/dist/media.d.ts +4 -1
- package/dist/media.d.ts.map +1 -1
- package/dist/media.js +4 -1
- package/dist/media.js.map +1 -1
- package/dist/namespace-events.d.ts +32 -3
- package/dist/namespace-events.d.ts.map +1 -1
- package/dist/namespace-events.js +82 -7
- package/dist/namespace-events.js.map +1 -1
- package/dist/node.d.ts +13 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +17 -0
- package/dist/node.js.map +1 -1
- package/dist/presence.d.ts +155 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +485 -0
- package/dist/presence.js.map +1 -0
- package/dist/publish.d.ts +61 -7
- package/dist/publish.d.ts.map +1 -1
- package/dist/publish.js +208 -87
- package/dist/publish.js.map +1 -1
- package/dist/publishing-roots.d.ts +189 -0
- package/dist/publishing-roots.d.ts.map +1 -0
- package/dist/publishing-roots.js +426 -0
- package/dist/publishing-roots.js.map +1 -0
- package/dist/relay-session.d.ts +31 -0
- package/dist/relay-session.d.ts.map +1 -0
- package/dist/relay-session.js +64 -0
- package/dist/relay-session.js.map +1 -0
- package/dist/subscription-events.d.ts +5 -2
- package/dist/subscription-events.d.ts.map +1 -1
- package/dist/subscription-events.js +20 -6
- package/dist/subscription-events.js.map +1 -1
- package/dist/supervised-publisher.d.ts.map +1 -1
- package/dist/supervised-publisher.js +42 -808
- package/dist/supervised-publisher.js.map +1 -1
- package/dist/supervised-relay.d.ts +112 -0
- package/dist/supervised-relay.d.ts.map +1 -0
- package/dist/supervised-relay.js +80 -0
- package/dist/supervised-relay.js.map +1 -0
- package/dist/supervised-subscriber.d.ts +66 -4
- package/dist/supervised-subscriber.d.ts.map +1 -1
- package/dist/supervised-subscriber.js +244 -557
- package/dist/supervised-subscriber.js.map +1 -1
- package/dist/supervised-track.d.ts +63 -0
- package/dist/supervised-track.d.ts.map +1 -0
- package/dist/supervised-track.js +430 -0
- package/dist/supervised-track.js.map +1 -0
- package/dist/supervisor.d.ts +92 -0
- package/dist/supervisor.d.ts.map +1 -0
- package/dist/supervisor.js +720 -0
- package/dist/supervisor.js.map +1 -0
- package/dist/switchable.d.ts +1 -1
- package/dist/write-slot.d.ts +5 -0
- package/dist/write-slot.d.ts.map +1 -1
- package/dist/write-slot.js +3 -0
- package/dist/write-slot.js.map +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
import { assertTimeoutMs, reportEndpoint } from './connect-session.js';
|
|
2
|
+
import { createDiscoveryIndex, DISCOVERY_CAPACITY } from './discovery.js';
|
|
3
|
+
import { RelayError } from './errors.js';
|
|
4
|
+
import { idle, SupervisedTrack } from './supervised-track.js';
|
|
5
|
+
import { backoffDelay, isSetupFailure, newGeneration, ROTATION_OVERLAP_MS, rotationDeadline, rotationDue, sleep, } from './supervision.js';
|
|
6
|
+
import { trackName, trackPropertyPairs } from './validation.js';
|
|
7
|
+
/** A subscriber stand-in for a connection that only publishes: nothing subscribes on it. */
|
|
8
|
+
const NO_SUBSCRIBER = new Proxy({}, {
|
|
9
|
+
get(_target, property) {
|
|
10
|
+
if (property === 'then')
|
|
11
|
+
return undefined;
|
|
12
|
+
throw new Error(`This supervised connection does not subscribe (${String(property)})`);
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
/**
|
|
16
|
+
* Create the loop. Nothing connects until `start()`; publications made before it are served from the first
|
|
17
|
+
* generation on.
|
|
18
|
+
*/
|
|
19
|
+
export function createSupervisor(connect, config) {
|
|
20
|
+
const { what, connection, signal, backoff, rotateBeforeMs, onStatus, onGeneration } = config;
|
|
21
|
+
const publications = new Set();
|
|
22
|
+
/** Every root ever published, by key and as given: a closed publication's root stays taken. */
|
|
23
|
+
const roots = new Set();
|
|
24
|
+
const published = [];
|
|
25
|
+
const stopListeners = [];
|
|
26
|
+
let current;
|
|
27
|
+
/** The connection a rotation is replacing, while what it carries moves off it. */
|
|
28
|
+
let retiring;
|
|
29
|
+
/**
|
|
30
|
+
* Connections ended or given up and still closing: draining groups the relay has not acknowledged. `stop()` waits for
|
|
31
|
+
* them, and a publication's `close()` for those that carry it.
|
|
32
|
+
*/
|
|
33
|
+
const draining = new Map();
|
|
34
|
+
const connectionWaiters = [];
|
|
35
|
+
let status = 'connecting';
|
|
36
|
+
let stopped = false;
|
|
37
|
+
let shutdown;
|
|
38
|
+
let resolveClosed = () => { };
|
|
39
|
+
const closed = new Promise((resolve) => {
|
|
40
|
+
resolveClosed = resolve;
|
|
41
|
+
});
|
|
42
|
+
// Aborts the attempt in progress and the waits between attempts; a live connection is closed cleanly instead.
|
|
43
|
+
const lifetime = new AbortController();
|
|
44
|
+
/** Aborts the connection attempt in progress only: once connected, a connection is closed, not aborted. */
|
|
45
|
+
let attemptInProgress;
|
|
46
|
+
/**
|
|
47
|
+
* The attempt in progress, until the connection it brings back is taken (made current, or discarded): `stop()` closes
|
|
48
|
+
* a connection that comes back, or was not taken, before it ran.
|
|
49
|
+
*/
|
|
50
|
+
let connecting;
|
|
51
|
+
/**
|
|
52
|
+
* Set by `rotate()` while a connection is up, and consumed by the rotation that answers it: the next one to start, or
|
|
53
|
+
* one whose replacement is still connecting or being discarded.
|
|
54
|
+
*/
|
|
55
|
+
let rotateRequested = false;
|
|
56
|
+
/** Wakes a serve loop waiting for its rotation; replaced for each wait. */
|
|
57
|
+
let wakeRotation = () => { };
|
|
58
|
+
const closedError = () => new RelayError('CLOSED', `${what} is closed`, 'connection');
|
|
59
|
+
const allTracks = () => [...publications].flatMap((publication) => [...publication.tracks.values()]);
|
|
60
|
+
const wakeWaiters = () => {
|
|
61
|
+
for (const wake of connectionWaiters.splice(0))
|
|
62
|
+
wake();
|
|
63
|
+
};
|
|
64
|
+
const setStatus = (next, error) => {
|
|
65
|
+
if (status === next && error === undefined)
|
|
66
|
+
return;
|
|
67
|
+
status = next;
|
|
68
|
+
onStatus?.(next, error);
|
|
69
|
+
};
|
|
70
|
+
let first;
|
|
71
|
+
const started = new Promise((resolve, reject) => {
|
|
72
|
+
first = { resolve, reject };
|
|
73
|
+
});
|
|
74
|
+
// Observed here: `start()` hands it to the caller, and a stop before then must not go unhandled.
|
|
75
|
+
started.catch(() => { });
|
|
76
|
+
/** Close `live` on purpose: the promise its session's close returns, if it drains. */
|
|
77
|
+
const closeLive = (live) => {
|
|
78
|
+
live.closing = true;
|
|
79
|
+
for (const generation of live.publications.values())
|
|
80
|
+
generation.ended = true;
|
|
81
|
+
let closing;
|
|
82
|
+
try {
|
|
83
|
+
closing = live.session.close();
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
closing = undefined;
|
|
87
|
+
}
|
|
88
|
+
return closing ? closing.catch(() => { }) : undefined;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Close a connection ended or given up while the loop runs on, draining in the background; `after` runs once it
|
|
92
|
+
* closed. The connection is closed once: a later call only adds its `after`.
|
|
93
|
+
*/
|
|
94
|
+
const drainLive = (live, after) => {
|
|
95
|
+
const already = draining.get(live);
|
|
96
|
+
if (already) {
|
|
97
|
+
// Started when the connection ended, or for a lost root, before a rotation gave it up: its clean-up still runs
|
|
98
|
+
// once it closed.
|
|
99
|
+
if (after)
|
|
100
|
+
void already.then(after);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
let drained;
|
|
104
|
+
// Registered before the close runs: a close that stops the supervisor finds it among the drains to wait for.
|
|
105
|
+
draining.set(live, new Promise((resolve, reject) => {
|
|
106
|
+
drained = { resolve, reject };
|
|
107
|
+
}));
|
|
108
|
+
const closing = live.closing ? undefined : closeLive(live);
|
|
109
|
+
if (!closing) {
|
|
110
|
+
draining.delete(live);
|
|
111
|
+
drained.resolve();
|
|
112
|
+
after?.();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
closing
|
|
116
|
+
.then(() => {
|
|
117
|
+
draining.delete(live);
|
|
118
|
+
after?.();
|
|
119
|
+
})
|
|
120
|
+
.then(drained.resolve, drained.reject);
|
|
121
|
+
};
|
|
122
|
+
/** The connection ended or was given up: release what it ran and stop anything still waiting on it. */
|
|
123
|
+
const settleEnded = (live) => {
|
|
124
|
+
live.ended.abort();
|
|
125
|
+
live.discovery.close();
|
|
126
|
+
};
|
|
127
|
+
const stop = (result) => {
|
|
128
|
+
if (shutdown)
|
|
129
|
+
return shutdown;
|
|
130
|
+
stopped = true;
|
|
131
|
+
// Set first: a `close()` made while this one runs (from a session's close, or onStatus) is the same stop, keeps
|
|
132
|
+
// this one's result, and waits for what this one waits for.
|
|
133
|
+
let settle;
|
|
134
|
+
shutdown = new Promise((resolve, reject) => {
|
|
135
|
+
settle = { resolve, reject };
|
|
136
|
+
});
|
|
137
|
+
// A throwing onStatus fails `close()` for the caller that made it; a stop nobody awaits leaves it observed.
|
|
138
|
+
shutdown.catch(() => { });
|
|
139
|
+
const reason = result.error ?? closedError();
|
|
140
|
+
lifetime.abort(reason);
|
|
141
|
+
attemptInProgress?.abort(reason);
|
|
142
|
+
// An abort while the first connection is still being made rejects the call that is waiting for it.
|
|
143
|
+
first?.reject(reason);
|
|
144
|
+
first = undefined;
|
|
145
|
+
for (const listener of stopListeners.splice(0))
|
|
146
|
+
listener();
|
|
147
|
+
const open = [current, retiring].filter((live) => live !== undefined);
|
|
148
|
+
current = undefined;
|
|
149
|
+
retiring = undefined;
|
|
150
|
+
for (const track of allTracks())
|
|
151
|
+
track.retire();
|
|
152
|
+
for (const live of open) {
|
|
153
|
+
// Registered as drains, so a publication's `close()` after this one waits for its groups too.
|
|
154
|
+
// One the loop already closed, and that closed at once, needs no second close.
|
|
155
|
+
if (!draining.has(live) && !live.closing) {
|
|
156
|
+
const closing = closeLive(live);
|
|
157
|
+
if (closing)
|
|
158
|
+
draining.set(live, closing);
|
|
159
|
+
}
|
|
160
|
+
settleEnded(live);
|
|
161
|
+
}
|
|
162
|
+
const pending = [...draining.values()];
|
|
163
|
+
// A connection still on its way back to the loop, or not yet taken: only this stop sees it.
|
|
164
|
+
if (connecting) {
|
|
165
|
+
pending.push(connecting.then((session) => {
|
|
166
|
+
try {
|
|
167
|
+
return Promise.resolve(session.close()).catch(() => { });
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
// A close that throws at once has nothing left to wait for.
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
}, () => { }));
|
|
174
|
+
}
|
|
175
|
+
wakeWaiters();
|
|
176
|
+
const finish = () => {
|
|
177
|
+
try {
|
|
178
|
+
setStatus('closed');
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
resolveClosed(result);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
if (pending.length === 0) {
|
|
185
|
+
// Nothing drains: report `closed` now, so a throwing onStatus reaches the caller of `close()` as it runs.
|
|
186
|
+
try {
|
|
187
|
+
finish();
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
// Every later `close()` reports the same failure.
|
|
191
|
+
settle.reject(error);
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
settle.resolve();
|
|
195
|
+
return shutdown;
|
|
196
|
+
}
|
|
197
|
+
Promise.all(pending).then(finish).then(settle.resolve, settle.reject);
|
|
198
|
+
return shutdown;
|
|
199
|
+
};
|
|
200
|
+
/** Stop from a place with no caller to tell: a throwing onStatus reporting `closed` settles `closed` regardless. */
|
|
201
|
+
const stopQuietly = (result) => {
|
|
202
|
+
try {
|
|
203
|
+
void stop(result).catch(() => { });
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// A throwing onStatus while reporting `closed`: `closed` is settled either way.
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const onAbort = () => stopQuietly({ error: signal?.reason });
|
|
210
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
211
|
+
const liveConnection = async (scope) => {
|
|
212
|
+
while (!scope.aborted && !stopped) {
|
|
213
|
+
if (current && !current.signal.aborted)
|
|
214
|
+
return current;
|
|
215
|
+
const woken = new Promise((resolve) => connectionWaiters.push(resolve));
|
|
216
|
+
await Promise.race([
|
|
217
|
+
woken,
|
|
218
|
+
new Promise((resolve) => {
|
|
219
|
+
if (scope.aborted)
|
|
220
|
+
resolve();
|
|
221
|
+
else
|
|
222
|
+
scope.addEventListener('abort', () => resolve(), { once: true });
|
|
223
|
+
}),
|
|
224
|
+
]);
|
|
225
|
+
}
|
|
226
|
+
return undefined;
|
|
227
|
+
};
|
|
228
|
+
/** Open one connection, or `undefined` if the loop stopped first. Throws the attempt's failure. */
|
|
229
|
+
const connectOnce = async () => {
|
|
230
|
+
const generation = newGeneration();
|
|
231
|
+
let session;
|
|
232
|
+
// Registered before the connector runs: a `close()` it makes before returning is a `stop()` that must see it.
|
|
233
|
+
let arrived;
|
|
234
|
+
connecting = new Promise((resolve, reject) => {
|
|
235
|
+
arrived = { resolve, reject };
|
|
236
|
+
});
|
|
237
|
+
connecting.catch(() => { });
|
|
238
|
+
try {
|
|
239
|
+
attemptInProgress = new AbortController();
|
|
240
|
+
session = await connect({
|
|
241
|
+
...connection,
|
|
242
|
+
signal: signal ? AbortSignal.any([signal, attemptInProgress.signal]) : attemptInProgress.signal,
|
|
243
|
+
[reportEndpoint]: (endpoint) => {
|
|
244
|
+
connection.url ??= endpoint;
|
|
245
|
+
},
|
|
246
|
+
}, generation);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
arrived.reject(error);
|
|
250
|
+
connecting = undefined;
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
attemptInProgress = undefined;
|
|
255
|
+
}
|
|
256
|
+
arrived.resolve(session);
|
|
257
|
+
// `stop()` ran while the attempt was in progress: it closes what the attempt brought back.
|
|
258
|
+
if (stopped)
|
|
259
|
+
return undefined;
|
|
260
|
+
const ended = new AbortController();
|
|
261
|
+
const retire = new AbortController();
|
|
262
|
+
let fault = () => { };
|
|
263
|
+
const faulted = new Promise((resolve) => {
|
|
264
|
+
fault = (error) => {
|
|
265
|
+
live.faulted = true;
|
|
266
|
+
resolve({ error });
|
|
267
|
+
};
|
|
268
|
+
});
|
|
269
|
+
const subscriber = session.subscriber ?? NO_SUBSCRIBER;
|
|
270
|
+
const live = {
|
|
271
|
+
session,
|
|
272
|
+
generation,
|
|
273
|
+
subscriber,
|
|
274
|
+
signal: ended.signal,
|
|
275
|
+
retiring: retire.signal,
|
|
276
|
+
discovery: createDiscoveryIndex((prefix) => subscriber.namespaceEvents({ prefix, capacity: DISCOVERY_CAPACITY })),
|
|
277
|
+
wakes: new Map(),
|
|
278
|
+
holds: 0,
|
|
279
|
+
rotateAt: rotationDeadline(session.expiresAt, rotateBeforeMs),
|
|
280
|
+
upAt: performance.now(),
|
|
281
|
+
ended,
|
|
282
|
+
retire,
|
|
283
|
+
publications: new Map(),
|
|
284
|
+
over: Promise.race([session.closed, faulted]),
|
|
285
|
+
fault: (error) => fault(error),
|
|
286
|
+
closing: false,
|
|
287
|
+
sessionEnded: false,
|
|
288
|
+
faulted: false,
|
|
289
|
+
};
|
|
290
|
+
void session.closed.then(() => {
|
|
291
|
+
live.sessionEnded = true;
|
|
292
|
+
});
|
|
293
|
+
// Marked in the turn the connection reports its end, before anything awaiting `over` resumes: a rotation in
|
|
294
|
+
// progress sees it and falls back to reconnecting.
|
|
295
|
+
void live.over.then(() => {
|
|
296
|
+
ended.abort();
|
|
297
|
+
if (!stopped) {
|
|
298
|
+
// Given up for a lost publication while the session is still open, whichever path was serving it: close it.
|
|
299
|
+
// Its wants move to the next connection once that is up, as on a rotation (`run`).
|
|
300
|
+
if (live.faulted)
|
|
301
|
+
drainLive(live, () => settleEnded(live));
|
|
302
|
+
// A session can report its end before it drained: after a GOAWAY a duplex session's publisher still waits for
|
|
303
|
+
// the relay to read its tracks' ends. Closing it waits for that, and `stop()` for the close.
|
|
304
|
+
else
|
|
305
|
+
drainLive(live);
|
|
306
|
+
}
|
|
307
|
+
for (const publication of live.publications.values()) {
|
|
308
|
+
publication.ended = true;
|
|
309
|
+
// The connection's end closed its groups under the application, which may never close them itself.
|
|
310
|
+
for (const release of [...publication.groupHolds.keys()])
|
|
311
|
+
release();
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
return live;
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Announce `publication` on `live` and register its tracks there: bound at once on a fresh connection, or handed
|
|
318
|
+
* over on a rotation. Returns the hand-overs. A connection that refuses the announce is ending: nothing is bound.
|
|
319
|
+
*/
|
|
320
|
+
const attach = (live, publication, handOver) => {
|
|
321
|
+
if (!live.session.publish)
|
|
322
|
+
return [];
|
|
323
|
+
const namespace = [...publication.root, live.generation];
|
|
324
|
+
let publisher;
|
|
325
|
+
try {
|
|
326
|
+
publisher = live.session.publish(namespace);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return [];
|
|
330
|
+
}
|
|
331
|
+
const state = { namespace, publisher, ended: false, busy: 0, groupHolds: new Map() };
|
|
332
|
+
live.publications.set(publication, state);
|
|
333
|
+
void publisher.closed.then(({ error }) => {
|
|
334
|
+
state.ended = true;
|
|
335
|
+
for (const release of [...state.groupHolds.keys()])
|
|
336
|
+
release();
|
|
337
|
+
// The relay stopped soliciting the namespace while the connection lives: a generation serves every root it
|
|
338
|
+
// carries or none, so the connection ends and the next generation announces them all again.
|
|
339
|
+
if (error !== undefined &&
|
|
340
|
+
!live.closing &&
|
|
341
|
+
!live.sessionEnded &&
|
|
342
|
+
!publication.closed &&
|
|
343
|
+
live.publications.get(publication) === state)
|
|
344
|
+
live.fault(error);
|
|
345
|
+
});
|
|
346
|
+
return [...publication.tracks.values()].map((track) => {
|
|
347
|
+
if (handOver)
|
|
348
|
+
return track.handOver(state);
|
|
349
|
+
track.bind(state);
|
|
350
|
+
return Promise.resolve();
|
|
351
|
+
});
|
|
352
|
+
};
|
|
353
|
+
/** Every track bound to `live` loses its binding: writes fail with RECONNECTING until the next generation binds. */
|
|
354
|
+
const unbindAll = (live) => {
|
|
355
|
+
for (const [publication, state] of live.publications) {
|
|
356
|
+
for (const track of publication.tracks.values())
|
|
357
|
+
track.unbind(state);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
const report = (live) => {
|
|
361
|
+
onGeneration?.(live.generation);
|
|
362
|
+
};
|
|
363
|
+
/**
|
|
364
|
+
* Bring up the connection that replaces `live` and move what it carries, make-before-break. Returns it, or
|
|
365
|
+
* `undefined` when `live` ended or the loop stopped before a replacement was up, or when an automatic rotation found
|
|
366
|
+
* no fresher credential.
|
|
367
|
+
*/
|
|
368
|
+
const rotateFrom = async (live, manual) => {
|
|
369
|
+
let failures = 0;
|
|
370
|
+
let next;
|
|
371
|
+
// The live connection ending while its replacement is still connecting is a reconnect: report it at once.
|
|
372
|
+
void live.over.then(({ error }) => {
|
|
373
|
+
if (stopped || current !== live)
|
|
374
|
+
return;
|
|
375
|
+
current = undefined;
|
|
376
|
+
unbindAll(live);
|
|
377
|
+
try {
|
|
378
|
+
setStatus('reconnecting', error);
|
|
379
|
+
}
|
|
380
|
+
catch (thrown) {
|
|
381
|
+
stopQuietly({ error: thrown });
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
while (!stopped && !live.signal.aborted) {
|
|
385
|
+
try {
|
|
386
|
+
next = await connectOnce();
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
if (stopped)
|
|
391
|
+
return undefined;
|
|
392
|
+
// The live connection keeps serving; try again after the backoff unless it ends first.
|
|
393
|
+
await Promise.race([sleep(backoffDelay(failures++, backoff), lifetime.signal).catch(() => { }), live.over]);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// `stop()` may have run while the helper's result was on its way here: it closed this connection.
|
|
397
|
+
if (!next || stopped)
|
|
398
|
+
return undefined;
|
|
399
|
+
// Consulted whatever happened to the old connection: a queued `rotate()` is answered by this replacement.
|
|
400
|
+
const asked = manual();
|
|
401
|
+
if (!live.signal.aborted && !asked) {
|
|
402
|
+
// A credential that expires no later than the live one replaces nothing: the relay would end both together.
|
|
403
|
+
const was = live.session.expiresAt?.getTime();
|
|
404
|
+
const now = next.session.expiresAt?.getTime();
|
|
405
|
+
if (was !== undefined && (now === undefined || now <= was)) {
|
|
406
|
+
if (stopped)
|
|
407
|
+
return undefined;
|
|
408
|
+
connecting = undefined;
|
|
409
|
+
drainLive(next);
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
// Checked again just before taking it: an application callback above may have stopped the loop.
|
|
414
|
+
if (stopped)
|
|
415
|
+
return undefined;
|
|
416
|
+
connecting = undefined;
|
|
417
|
+
current = next;
|
|
418
|
+
retiring = live;
|
|
419
|
+
const moved = [...publications].flatMap((publication) => attach(next, publication, true));
|
|
420
|
+
setStatus('live');
|
|
421
|
+
report(next);
|
|
422
|
+
wakeWaiters();
|
|
423
|
+
const wantsMoved = new Promise((resolve) => {
|
|
424
|
+
live.onIdle = resolve;
|
|
425
|
+
});
|
|
426
|
+
// Every want on the old connection ends its attempt there and subscribes on the new one.
|
|
427
|
+
live.retire.abort();
|
|
428
|
+
if (live.holds === 0)
|
|
429
|
+
live.onIdle?.();
|
|
430
|
+
// A group can close without the wrapper hearing of it (its signal, the relay resetting demand): release its hold
|
|
431
|
+
// once it is closed, whatever closed it.
|
|
432
|
+
const sweep = () => {
|
|
433
|
+
for (const state of live.publications.values()) {
|
|
434
|
+
for (const [release, group] of [...state.groupHolds])
|
|
435
|
+
if (group.closed)
|
|
436
|
+
release();
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
const sweeper = setInterval(sweep, 50);
|
|
440
|
+
// Every track and want moved and every write or group still on the old connection finished, or the overlap ran
|
|
441
|
+
// out. The replacement ending cuts the overlap short too: what it carries needs the connection after it now. So does
|
|
442
|
+
// its own rotation falling due, for a credential shorter than the overlap.
|
|
443
|
+
const overlap = new AbortController();
|
|
444
|
+
await Promise.race([
|
|
445
|
+
Promise.all([
|
|
446
|
+
wantsMoved,
|
|
447
|
+
Promise.all(moved).then(() => {
|
|
448
|
+
sweep();
|
|
449
|
+
return Promise.all([...live.publications.values()].map(idle));
|
|
450
|
+
}),
|
|
451
|
+
]),
|
|
452
|
+
sleep(ROTATION_OVERLAP_MS, lifetime.signal).catch(() => { }),
|
|
453
|
+
live.over,
|
|
454
|
+
next.over,
|
|
455
|
+
rotationDue(next.rotateAt, new Promise(() => { }), AbortSignal.any([lifetime.signal, overlap.signal])),
|
|
456
|
+
]);
|
|
457
|
+
overlap.abort();
|
|
458
|
+
clearInterval(sweeper);
|
|
459
|
+
live.onIdle = undefined;
|
|
460
|
+
for (const state of live.publications.values())
|
|
461
|
+
state.onIdle = undefined;
|
|
462
|
+
for (const track of allTracks())
|
|
463
|
+
track.settle();
|
|
464
|
+
// A track whose next generation ended before it moved is still bound here: it has no generation now.
|
|
465
|
+
for (const state of live.publications.values())
|
|
466
|
+
state.ended = true;
|
|
467
|
+
unbindAll(live);
|
|
468
|
+
if (retiring === live)
|
|
469
|
+
retiring = undefined;
|
|
470
|
+
// Closing drains the old connection's unacknowledged groups for up to a write deadline; the next one is served
|
|
471
|
+
// meanwhile, and `stop()` waits for the drain.
|
|
472
|
+
drainLive(live, () => {
|
|
473
|
+
for (const [publication, state] of live.publications) {
|
|
474
|
+
for (const track of publication.tracks.values())
|
|
475
|
+
track.forget(state);
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
settleEnded(live);
|
|
479
|
+
return next;
|
|
480
|
+
};
|
|
481
|
+
/** Serve `live` until it ends, or until a rotation replaced it with the connection returned. */
|
|
482
|
+
const serve = async (live) => {
|
|
483
|
+
const scope = new AbortController();
|
|
484
|
+
/** Cleared once an automatic rotation found no fresher credential: only `rotate()` tries again. */
|
|
485
|
+
let automatic = true;
|
|
486
|
+
try {
|
|
487
|
+
for (;;) {
|
|
488
|
+
const asked = new Promise((resolve) => {
|
|
489
|
+
wakeRotation = resolve;
|
|
490
|
+
});
|
|
491
|
+
if (rotateRequested)
|
|
492
|
+
wakeRotation();
|
|
493
|
+
const due = rotationDue(automatic ? live.rotateAt : undefined, asked, AbortSignal.any([lifetime.signal, scope.signal])).then(() => undefined);
|
|
494
|
+
const outcome = await Promise.race([live.over, due]);
|
|
495
|
+
if (outcome !== undefined || stopped)
|
|
496
|
+
return outcome ?? {};
|
|
497
|
+
// A `rotate()` before the replacement is current makes this rotation a manual one: it takes the replacement.
|
|
498
|
+
let manual = false;
|
|
499
|
+
const isManual = () => {
|
|
500
|
+
if (rotateRequested) {
|
|
501
|
+
rotateRequested = false;
|
|
502
|
+
manual = true;
|
|
503
|
+
}
|
|
504
|
+
return manual;
|
|
505
|
+
};
|
|
506
|
+
isManual();
|
|
507
|
+
const next = await rotateFrom(live, isManual);
|
|
508
|
+
if (next)
|
|
509
|
+
return { next };
|
|
510
|
+
if (live.signal.aborted || stopped)
|
|
511
|
+
return await live.over;
|
|
512
|
+
if (!manual)
|
|
513
|
+
automatic = false;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
finally {
|
|
517
|
+
scope.abort();
|
|
518
|
+
wakeRotation = () => { };
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
const run = async () => {
|
|
522
|
+
let attempt = 0;
|
|
523
|
+
/** A connection a rotation already brought up, reported and moved everything to. */
|
|
524
|
+
let next;
|
|
525
|
+
/**
|
|
526
|
+
* A connection given up for a lost root, still draining: its wants are still subscribed there, and move to the next
|
|
527
|
+
* connection once it is up, make-before-break, rather than wait out the drain.
|
|
528
|
+
*/
|
|
529
|
+
let givenUp;
|
|
530
|
+
while (!stopped) {
|
|
531
|
+
let live = next;
|
|
532
|
+
next = undefined;
|
|
533
|
+
if (!live) {
|
|
534
|
+
try {
|
|
535
|
+
live = await connectOnce();
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
if (stopped)
|
|
539
|
+
return;
|
|
540
|
+
if (first && isSetupFailure(error)) {
|
|
541
|
+
first.reject(error);
|
|
542
|
+
first = undefined;
|
|
543
|
+
await stop({ error });
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
setStatus('reconnecting', error);
|
|
547
|
+
await sleep(backoffDelay(attempt++, backoff), lifetime.signal).catch(() => { });
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
// `stop()` may have run while the helper's result was on its way here: it closed this connection.
|
|
551
|
+
if (!live || stopped)
|
|
552
|
+
return;
|
|
553
|
+
connecting = undefined;
|
|
554
|
+
current = live;
|
|
555
|
+
for (const publication of publications)
|
|
556
|
+
attach(live, publication, false);
|
|
557
|
+
setStatus('live');
|
|
558
|
+
report(live);
|
|
559
|
+
first?.resolve();
|
|
560
|
+
first = undefined;
|
|
561
|
+
wakeWaiters();
|
|
562
|
+
givenUp?.retire.abort();
|
|
563
|
+
givenUp = undefined;
|
|
564
|
+
}
|
|
565
|
+
const outcome = await serve(live);
|
|
566
|
+
if (stopped)
|
|
567
|
+
return;
|
|
568
|
+
if ('next' in outcome) {
|
|
569
|
+
next = outcome.next;
|
|
570
|
+
attempt = 0;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
current = undefined;
|
|
574
|
+
for (const state of live.publications.values())
|
|
575
|
+
state.ended = true;
|
|
576
|
+
unbindAll(live);
|
|
577
|
+
if (live.faulted)
|
|
578
|
+
givenUp = live;
|
|
579
|
+
else
|
|
580
|
+
settleEnded(live);
|
|
581
|
+
// Already reported if the connection ended while a rotation's replacement was connecting.
|
|
582
|
+
if (status !== 'reconnecting')
|
|
583
|
+
setStatus('reconnecting', outcome.error);
|
|
584
|
+
// A connection that stayed up longer than the longest delay was a success: start the backoff over.
|
|
585
|
+
if (performance.now() - live.upAt > backoff.maxDelayMs)
|
|
586
|
+
attempt = 0;
|
|
587
|
+
await sleep(backoffDelay(attempt++, backoff), lifetime.signal).catch(() => { });
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
let startedOnce = false;
|
|
591
|
+
const start = async () => {
|
|
592
|
+
if (startedOnce)
|
|
593
|
+
throw new Error('A supervisor starts once');
|
|
594
|
+
startedOnce = true;
|
|
595
|
+
void (async () => {
|
|
596
|
+
try {
|
|
597
|
+
await run();
|
|
598
|
+
}
|
|
599
|
+
catch (error) {
|
|
600
|
+
// An application callback (onStatus, onGeneration) threw: stop rather than leave the loop neither
|
|
601
|
+
// reconnecting nor closed, and fail a caller still waiting to connect.
|
|
602
|
+
stopQuietly({ error });
|
|
603
|
+
}
|
|
604
|
+
})();
|
|
605
|
+
try {
|
|
606
|
+
await started;
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
signal?.removeEventListener('abort', onAbort);
|
|
610
|
+
throw error;
|
|
611
|
+
}
|
|
612
|
+
if (stopped)
|
|
613
|
+
throw signal?.reason ?? closedError();
|
|
614
|
+
};
|
|
615
|
+
const publish = (root) => {
|
|
616
|
+
if (stopped)
|
|
617
|
+
throw closedError();
|
|
618
|
+
const key = JSON.stringify(root);
|
|
619
|
+
if (roots.has(key))
|
|
620
|
+
throw new RangeError('Namespace is already published on this supervised connection');
|
|
621
|
+
roots.add(key);
|
|
622
|
+
published.push(root);
|
|
623
|
+
const publication = { root, tracks: new Map(), names: new Set(), closed: false };
|
|
624
|
+
publications.add(publication);
|
|
625
|
+
if (current)
|
|
626
|
+
attach(current, publication, false);
|
|
627
|
+
let closing;
|
|
628
|
+
return {
|
|
629
|
+
root,
|
|
630
|
+
get namespace() {
|
|
631
|
+
const state = current?.publications.get(publication);
|
|
632
|
+
return state ? [...state.namespace] : undefined;
|
|
633
|
+
},
|
|
634
|
+
registerTrack(trackOptions) {
|
|
635
|
+
if (typeof trackOptions !== 'object' || trackOptions === null) {
|
|
636
|
+
throw new TypeError('registerTrack takes an options object');
|
|
637
|
+
}
|
|
638
|
+
const { track, trackProperties, writeTimeoutMs = 10_000 } = trackOptions;
|
|
639
|
+
const name = trackName(track);
|
|
640
|
+
trackPropertyPairs(trackProperties);
|
|
641
|
+
assertTimeoutMs('writeTimeoutMs', writeTimeoutMs);
|
|
642
|
+
if (stopped || publication.closed)
|
|
643
|
+
throw closedError();
|
|
644
|
+
if (publication.names.has(name)) {
|
|
645
|
+
throw new RangeError('Track name is already registered on this supervised publication');
|
|
646
|
+
}
|
|
647
|
+
const properties = trackProperties?.map(({ type, value }) => ({
|
|
648
|
+
type,
|
|
649
|
+
// Copied now: every generation registers the track again, after the caller may have reused its buffers.
|
|
650
|
+
value: typeof value === 'number'
|
|
651
|
+
? value
|
|
652
|
+
: new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice(),
|
|
653
|
+
}));
|
|
654
|
+
const supervised = new SupervisedTrack({ track: name, writeTimeoutMs, ...(properties ? { trackProperties: properties } : {}) }, () => publication.tracks.delete(name));
|
|
655
|
+
publication.tracks.set(name, supervised);
|
|
656
|
+
publication.names.add(name);
|
|
657
|
+
const state = current?.publications.get(publication);
|
|
658
|
+
if (state)
|
|
659
|
+
supervised.bind(state);
|
|
660
|
+
return supervised.writer;
|
|
661
|
+
},
|
|
662
|
+
close() {
|
|
663
|
+
closing ??= (async () => {
|
|
664
|
+
publication.closed = true;
|
|
665
|
+
for (const track of [...publication.tracks.values()])
|
|
666
|
+
track.writer.close();
|
|
667
|
+
publications.delete(publication);
|
|
668
|
+
const ends = [];
|
|
669
|
+
for (const live of [current, retiring]) {
|
|
670
|
+
const state = live?.publications.get(publication);
|
|
671
|
+
if (!live || !state)
|
|
672
|
+
continue;
|
|
673
|
+
state.ended = true;
|
|
674
|
+
ends.push(state.publisher.close().catch(() => { }));
|
|
675
|
+
}
|
|
676
|
+
// A connection a rotation or a lost root gave up still drains this publication's groups.
|
|
677
|
+
for (const [live, drain] of draining)
|
|
678
|
+
if (live.publications.has(publication))
|
|
679
|
+
ends.push(drain);
|
|
680
|
+
await Promise.all(ends);
|
|
681
|
+
})();
|
|
682
|
+
return closing;
|
|
683
|
+
},
|
|
684
|
+
};
|
|
685
|
+
};
|
|
686
|
+
return {
|
|
687
|
+
get status() {
|
|
688
|
+
return status;
|
|
689
|
+
},
|
|
690
|
+
get generation() {
|
|
691
|
+
return current?.generation;
|
|
692
|
+
},
|
|
693
|
+
get stopped() {
|
|
694
|
+
return stopped;
|
|
695
|
+
},
|
|
696
|
+
closed,
|
|
697
|
+
start,
|
|
698
|
+
current: () => current,
|
|
699
|
+
liveConnection,
|
|
700
|
+
publish,
|
|
701
|
+
rotate() {
|
|
702
|
+
if (stopped || !current)
|
|
703
|
+
return;
|
|
704
|
+
rotateRequested = true;
|
|
705
|
+
wakeRotation();
|
|
706
|
+
},
|
|
707
|
+
stop: (result) => {
|
|
708
|
+
signal?.removeEventListener('abort', onAbort);
|
|
709
|
+
return stop(result);
|
|
710
|
+
},
|
|
711
|
+
closedError,
|
|
712
|
+
ownsNamespace(namespace) {
|
|
713
|
+
return published.some((root) => root.length < namespace.length && root.every((field, i) => namespace[i] === field));
|
|
714
|
+
},
|
|
715
|
+
onStop(listener) {
|
|
716
|
+
stopListeners.push(listener);
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
//# sourceMappingURL=supervisor.js.map
|