@caprid/relay 0.0.0 → 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 +202 -0
- package/README.md +160 -1
- package/dist/connect-session.d.ts +125 -0
- package/dist/connect-session.d.ts.map +1 -0
- package/dist/connect-session.js +300 -0
- package/dist/connect-session.js.map +1 -0
- package/dist/connect.d.ts +143 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +129 -0
- package/dist/connect.js.map +1 -0
- package/dist/delivery-timeouts.d.ts +37 -0
- package/dist/delivery-timeouts.d.ts.map +1 -0
- package/dist/delivery-timeouts.js +48 -0
- package/dist/delivery-timeouts.js.map +1 -0
- package/dist/document-service.d.ts +58 -0
- package/dist/document-service.d.ts.map +1 -0
- package/dist/document-service.js +166 -0
- package/dist/document-service.js.map +1 -0
- package/dist/errors.d.ts +71 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +99 -0
- package/dist/errors.js.map +1 -0
- package/dist/frame-reader.d.ts +81 -0
- package/dist/frame-reader.d.ts.map +1 -0
- package/dist/frame-reader.js +110 -0
- package/dist/frame-reader.js.map +1 -0
- package/dist/frame-writer.d.ts +109 -0
- package/dist/frame-writer.d.ts.map +1 -0
- package/dist/frame-writer.js +409 -0
- package/dist/frame-writer.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/media-track-properties.d.ts +59 -0
- package/dist/media-track-properties.d.ts.map +1 -0
- package/dist/media-track-properties.js +120 -0
- package/dist/media-track-properties.js.map +1 -0
- package/dist/media.d.ts +28 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +28 -0
- package/dist/media.js.map +1 -0
- package/dist/namespace-events.d.ts +44 -0
- package/dist/namespace-events.d.ts.map +1 -0
- package/dist/namespace-events.js +107 -0
- package/dist/namespace-events.js.map +1 -0
- package/dist/node.d.ts +75 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +114 -0
- package/dist/node.js.map +1 -0
- package/dist/payload.d.ts +8 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +23 -0
- package/dist/payload.js.map +1 -0
- package/dist/publish.d.ts +209 -0
- package/dist/publish.d.ts.map +1 -0
- package/dist/publish.js +123 -0
- package/dist/publish.js.map +1 -0
- package/dist/room-endpoint.d.ts +21 -0
- package/dist/room-endpoint.d.ts.map +1 -0
- package/dist/room-endpoint.js +47 -0
- package/dist/room-endpoint.js.map +1 -0
- package/dist/send-order.d.ts +14 -0
- package/dist/send-order.d.ts.map +1 -0
- package/dist/send-order.js +11 -0
- package/dist/send-order.js.map +1 -0
- package/dist/settling-groups.d.ts +35 -0
- package/dist/settling-groups.d.ts.map +1 -0
- package/dist/settling-groups.js +73 -0
- package/dist/settling-groups.js.map +1 -0
- package/dist/subscription-events.d.ts +51 -0
- package/dist/subscription-events.d.ts.map +1 -0
- package/dist/subscription-events.js +125 -0
- package/dist/subscription-events.js.map +1 -0
- package/dist/subscription.d.ts +207 -0
- package/dist/subscription.d.ts.map +1 -0
- package/dist/subscription.js +283 -0
- package/dist/subscription.js.map +1 -0
- package/dist/supervised-publisher.d.ts +92 -0
- package/dist/supervised-publisher.d.ts.map +1 -0
- package/dist/supervised-publisher.js +839 -0
- package/dist/supervised-publisher.js.map +1 -0
- package/dist/supervised-subscriber.d.ts +201 -0
- package/dist/supervised-subscriber.d.ts.map +1 -0
- package/dist/supervised-subscriber.js +1420 -0
- package/dist/supervised-subscriber.js.map +1 -0
- package/dist/supervision.d.ts +78 -0
- package/dist/supervision.d.ts.map +1 -0
- package/dist/supervision.js +149 -0
- package/dist/supervision.js.map +1 -0
- package/dist/switchable.d.ts +164 -0
- package/dist/switchable.d.ts.map +1 -0
- package/dist/switchable.js +327 -0
- package/dist/switchable.js.map +1 -0
- package/dist/validation.d.ts +64 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +137 -0
- package/dist/validation.js.map +1 -0
- package/dist/write-slot.d.ts +87 -0
- package/dist/write-slot.d.ts.map +1 -0
- package/dist/write-slot.js +519 -0
- package/dist/write-slot.js.map +1 -0
- package/package.json +82 -4
|
@@ -0,0 +1,1420 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The supervised subscriber: one subscriber connection at a time, replaced with backoff whenever it ends, and one
|
|
3
|
+
* supervisor per wanted track that keeps a subscription to it open across connections, publisher restarts and
|
|
4
|
+
* generations. Each want retries the announce race, backs off after a publisher's done or a rejection, resubscribes a
|
|
5
|
+
* subscription that went stale, and follows a supervised publisher's newest generation through namespace discovery.
|
|
6
|
+
* Objects are never fetched to fill a gap: a replacement subscription starts live, and `onRestarted` tells the
|
|
7
|
+
* application to drop state that assumed continuity. A move to a newer generation, or to another track or parameters
|
|
8
|
+
* on a re-want, is made before the break instead, as `switchTo` makes one (issue #282): the replacement opens while the
|
|
9
|
+
* current subscription keeps delivering, and `onSwitched` marks the cutover. Before the connection's credential
|
|
10
|
+
* expires, the supervisor rotates to a new connection the same way (issue #261): every want's subscription moves to it
|
|
11
|
+
* make-before-break, and a want that keeps its target sees no break and no repeat. See spec/behavior.md, "Supervised
|
|
12
|
+
* connections".
|
|
13
|
+
*/
|
|
14
|
+
import { isMoqtProtocolError, } from '@caprid/moq-core';
|
|
15
|
+
import { connectRelaySubscriber } from './connect.js';
|
|
16
|
+
import { assertTimeoutMs } from './connect-session.js';
|
|
17
|
+
import { RelayError } from './errors.js';
|
|
18
|
+
import { SubscriptionConnectionClosedError, SubscriptionRequestError, synchronousCallback } from './subscription.js';
|
|
19
|
+
import { backoffDelay, backoffOptions, isFreshNamespaceRejection, isPermanentRequestError, isSetupFailure, RECONNECT_BACKOFF, RESUBSCRIBE_BACKOFF, ROTATION_OVERLAP_MS, rotateBeforeOption, rotationDeadline, rotationDue, sleep, whenAborted, } from './supervision.js';
|
|
20
|
+
import { assertDrainMs, heldAfter, holdEvent, untilPredicate, } from './switchable.js';
|
|
21
|
+
import { namespaceFields, trackName } from './validation.js';
|
|
22
|
+
/**
|
|
23
|
+
* Open a subscriber that reconnects and keeps every wanted track subscribed across connections, publisher restarts
|
|
24
|
+
* and generations. Resolves once the first connection is up; see spec/behavior.md, "Supervised connections". The
|
|
25
|
+
* primitives (`connectRelaySubscriber`) never reconnect or resubscribe.
|
|
26
|
+
*/
|
|
27
|
+
export function connectSupervisedSubscriber(options) {
|
|
28
|
+
return superviseRelaySubscriber(connectRelaySubscriber, options);
|
|
29
|
+
}
|
|
30
|
+
/** Count a use of `connection` until the returned release runs. */
|
|
31
|
+
function hold(connection) {
|
|
32
|
+
connection.holds += 1;
|
|
33
|
+
let released = false;
|
|
34
|
+
return () => {
|
|
35
|
+
if (released)
|
|
36
|
+
return;
|
|
37
|
+
released = true;
|
|
38
|
+
connection.holds -= 1;
|
|
39
|
+
if (connection.holds === 0)
|
|
40
|
+
connection.onIdle?.();
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Open a supervised subscriber with `connect`. Resolves once the first connection is up. A first attempt that fails
|
|
45
|
+
* on its arguments or the relay refusing the credentials rejects with that failure; any other failure is retried with
|
|
46
|
+
* backoff, bounded only by `signal`, whose abort rejects with its reason.
|
|
47
|
+
*/
|
|
48
|
+
export async function superviseRelaySubscriber(connect, options) {
|
|
49
|
+
if (typeof options !== 'object' || options === null) {
|
|
50
|
+
throw new TypeError('connectSupervisedSubscriber takes an options object');
|
|
51
|
+
}
|
|
52
|
+
const { reconnect, rotateBeforeMs: rotateBefore, onStatus, signal, ...connection } = options;
|
|
53
|
+
const backoff = backoffOptions('reconnect', reconnect, RECONNECT_BACKOFF);
|
|
54
|
+
const rotateBeforeMs = rotateBeforeOption(rotateBefore);
|
|
55
|
+
signal?.throwIfAborted();
|
|
56
|
+
const wants = new Map();
|
|
57
|
+
let status = 'connecting';
|
|
58
|
+
let stopped = false;
|
|
59
|
+
let current;
|
|
60
|
+
const connectionWaiters = [];
|
|
61
|
+
let resolveClosed = () => { };
|
|
62
|
+
const closed = new Promise((resolve) => {
|
|
63
|
+
resolveClosed = resolve;
|
|
64
|
+
});
|
|
65
|
+
const lifetime = new AbortController();
|
|
66
|
+
/** Aborts the connection attempt in progress only: a live connection is closed cleanly on `close()`. */
|
|
67
|
+
let attemptInProgress;
|
|
68
|
+
/** The connection a rotation is replacing, while its wants move off it. */
|
|
69
|
+
let retiring;
|
|
70
|
+
/**
|
|
71
|
+
* Set by `rotate()` while a connection is up, and consumed by the rotation that answers it: the next one to start, or
|
|
72
|
+
* one whose replacement is still connecting or being discarded.
|
|
73
|
+
*/
|
|
74
|
+
let rotateRequested = false;
|
|
75
|
+
/** Wakes a serve loop waiting for its rotation; replaced for each wait. */
|
|
76
|
+
let wakeRotation = () => { };
|
|
77
|
+
const requestRotation = () => {
|
|
78
|
+
if (stopped || !current)
|
|
79
|
+
return;
|
|
80
|
+
rotateRequested = true;
|
|
81
|
+
wakeRotation();
|
|
82
|
+
};
|
|
83
|
+
const setStatus = (next, error) => {
|
|
84
|
+
if (status === next && error === undefined)
|
|
85
|
+
return;
|
|
86
|
+
status = next;
|
|
87
|
+
onStatus?.(next, error);
|
|
88
|
+
};
|
|
89
|
+
let first;
|
|
90
|
+
const started = new Promise((resolve, reject) => {
|
|
91
|
+
first = { resolve, reject };
|
|
92
|
+
});
|
|
93
|
+
const stop = (result) => {
|
|
94
|
+
if (stopped)
|
|
95
|
+
return;
|
|
96
|
+
stopped = true;
|
|
97
|
+
const reason = result.error ?? new RelayError('CLOSED', 'Supervised subscriber is closed', 'connection');
|
|
98
|
+
lifetime.abort(reason);
|
|
99
|
+
attemptInProgress?.abort(reason);
|
|
100
|
+
// An abort while the first connection is still being made rejects the call that is waiting for it.
|
|
101
|
+
first?.reject(reason);
|
|
102
|
+
first = undefined;
|
|
103
|
+
for (const want of wants.values())
|
|
104
|
+
want.controller.abort();
|
|
105
|
+
wants.clear();
|
|
106
|
+
current?.subscriber.close();
|
|
107
|
+
current = undefined;
|
|
108
|
+
retiring?.subscriber.close();
|
|
109
|
+
retiring = undefined;
|
|
110
|
+
for (const wake of connectionWaiters.splice(0))
|
|
111
|
+
wake();
|
|
112
|
+
try {
|
|
113
|
+
setStatus('closed');
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
resolveClosed(result);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const onAbort = () => {
|
|
120
|
+
try {
|
|
121
|
+
stop({ error: signal?.reason });
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// A throwing onStatus while reporting `closed`: `closed` is settled, and an abort listener has no caller to tell.
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
128
|
+
/** The live connection, waiting for one while reconnecting; `undefined` once `scope` aborts. */
|
|
129
|
+
const liveConnection = async (scope) => {
|
|
130
|
+
while (!scope.aborted && !stopped) {
|
|
131
|
+
if (current && !current.signal.aborted)
|
|
132
|
+
return current;
|
|
133
|
+
const woken = new Promise((resolve) => connectionWaiters.push(resolve));
|
|
134
|
+
await Promise.race([woken, whenAborted(scope)]);
|
|
135
|
+
}
|
|
136
|
+
return undefined;
|
|
137
|
+
};
|
|
138
|
+
/** Open one connection, or `undefined` if the supervisor stopped first. Throws the attempt's failure. */
|
|
139
|
+
const connectOnce = async () => {
|
|
140
|
+
let subscriber;
|
|
141
|
+
try {
|
|
142
|
+
attemptInProgress = new AbortController();
|
|
143
|
+
subscriber = await connect({
|
|
144
|
+
...connection,
|
|
145
|
+
signal: signal ? AbortSignal.any([signal, attemptInProgress.signal]) : attemptInProgress.signal,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
attemptInProgress = undefined;
|
|
150
|
+
}
|
|
151
|
+
if (stopped) {
|
|
152
|
+
subscriber.close();
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const ended = new AbortController();
|
|
156
|
+
// Aborted the moment the connection ends, so a rotation in progress sees it and falls back to reconnecting.
|
|
157
|
+
void subscriber.closed.then(() => ended.abort());
|
|
158
|
+
const retire = new AbortController();
|
|
159
|
+
const live = {
|
|
160
|
+
subscriber,
|
|
161
|
+
signal: ended.signal,
|
|
162
|
+
retiring: retire.signal,
|
|
163
|
+
roots: new Map(),
|
|
164
|
+
holds: 0,
|
|
165
|
+
rotateAt: rotationDeadline(subscriber.expiresAt, rotateBeforeMs),
|
|
166
|
+
};
|
|
167
|
+
return { live, ended, retire };
|
|
168
|
+
};
|
|
169
|
+
/** The connection ended: release what it ran and stop anything still waiting on it. */
|
|
170
|
+
const settleEnded = (opened) => {
|
|
171
|
+
opened.ended.abort();
|
|
172
|
+
for (const watch of opened.live.roots.values())
|
|
173
|
+
watch.close();
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Open the connection that replaces `opened`, move every want to it, and close the old one once they have moved.
|
|
177
|
+
* Returns the new connection, or `undefined` when the old one ended or the supervisor stopped before a replacement
|
|
178
|
+
* was up, or when an automatic rotation found no fresher credential.
|
|
179
|
+
*/
|
|
180
|
+
const rotateFrom = async (opened, manual) => {
|
|
181
|
+
const old = opened.live;
|
|
182
|
+
let failures = 0;
|
|
183
|
+
let next;
|
|
184
|
+
// The live connection ending while its replacement is still connecting is a reconnect: report it at once.
|
|
185
|
+
void old.subscriber.closed.then(({ error }) => {
|
|
186
|
+
if (stopped || current !== old)
|
|
187
|
+
return;
|
|
188
|
+
current = undefined;
|
|
189
|
+
try {
|
|
190
|
+
setStatus('reconnecting', error);
|
|
191
|
+
}
|
|
192
|
+
catch (thrown) {
|
|
193
|
+
try {
|
|
194
|
+
stop({ error: thrown });
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
// A throwing onStatus while reporting `closed`: `closed` is settled either way.
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
while (!stopped && !old.signal.aborted) {
|
|
202
|
+
try {
|
|
203
|
+
next = await connectOnce();
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
if (stopped)
|
|
208
|
+
return undefined;
|
|
209
|
+
// The live connection keeps serving; try again after the backoff unless it ends first.
|
|
210
|
+
await Promise.race([
|
|
211
|
+
sleep(backoffDelay(failures++, backoff), lifetime.signal).catch(() => { }),
|
|
212
|
+
whenAborted(old.signal),
|
|
213
|
+
]);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!next)
|
|
217
|
+
return undefined;
|
|
218
|
+
// `close()` may have run while the helper's result was on its way here: it could not see this connection.
|
|
219
|
+
if (stopped) {
|
|
220
|
+
next.live.subscriber.close();
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
223
|
+
// Consulted whatever happened to the old connection: a queued `rotate()` is answered by this replacement.
|
|
224
|
+
const asked = manual();
|
|
225
|
+
if (!old.signal.aborted && !asked) {
|
|
226
|
+
// A credential that expires no later than the live one replaces nothing: the relay would end both together.
|
|
227
|
+
const was = old.subscriber.expiresAt?.getTime();
|
|
228
|
+
const now = next.live.subscriber.expiresAt?.getTime();
|
|
229
|
+
if (was !== undefined && (now === undefined || now <= was)) {
|
|
230
|
+
next.live.subscriber.close();
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
current = next.live;
|
|
235
|
+
retiring = old;
|
|
236
|
+
setStatus('live');
|
|
237
|
+
for (const wake of connectionWaiters.splice(0))
|
|
238
|
+
wake();
|
|
239
|
+
const idle = new Promise((resolve) => {
|
|
240
|
+
old.onIdle = resolve;
|
|
241
|
+
});
|
|
242
|
+
// Every want on the old connection ends its attempt there and subscribes on the new one.
|
|
243
|
+
opened.retire.abort();
|
|
244
|
+
if (old.holds === 0)
|
|
245
|
+
old.onIdle?.();
|
|
246
|
+
// The replacement ending cuts the overlap short too: the wants on it need the next connection now. So does its own
|
|
247
|
+
// rotation falling due, for a credential shorter than the overlap.
|
|
248
|
+
const overlap = new AbortController();
|
|
249
|
+
await Promise.race([
|
|
250
|
+
idle,
|
|
251
|
+
sleep(ROTATION_OVERLAP_MS, lifetime.signal).catch(() => { }),
|
|
252
|
+
whenAborted(old.signal),
|
|
253
|
+
whenAborted(next.live.signal),
|
|
254
|
+
rotationDue(next.live.rotateAt, new Promise(() => { }), AbortSignal.any([lifetime.signal, overlap.signal])),
|
|
255
|
+
]);
|
|
256
|
+
overlap.abort();
|
|
257
|
+
old.onIdle = undefined;
|
|
258
|
+
if (retiring === old)
|
|
259
|
+
retiring = undefined;
|
|
260
|
+
old.subscriber.close();
|
|
261
|
+
settleEnded(opened);
|
|
262
|
+
return next;
|
|
263
|
+
};
|
|
264
|
+
/** Serve `opened` until it ends, or until a rotation replaced it with the connection returned. */
|
|
265
|
+
const serve = async (opened) => {
|
|
266
|
+
const { subscriber } = opened.live;
|
|
267
|
+
const scope = new AbortController();
|
|
268
|
+
/** Cleared once an automatic rotation found no fresher credential: only `rotate()` tries again. */
|
|
269
|
+
let automatic = true;
|
|
270
|
+
try {
|
|
271
|
+
for (;;) {
|
|
272
|
+
const asked = new Promise((resolve) => {
|
|
273
|
+
wakeRotation = resolve;
|
|
274
|
+
});
|
|
275
|
+
if (rotateRequested)
|
|
276
|
+
wakeRotation();
|
|
277
|
+
const due = rotationDue(automatic ? opened.live.rotateAt : undefined, asked, AbortSignal.any([lifetime.signal, scope.signal])).then(() => undefined);
|
|
278
|
+
const outcome = await Promise.race([subscriber.closed, due]);
|
|
279
|
+
if (outcome !== undefined || stopped)
|
|
280
|
+
return outcome ?? {};
|
|
281
|
+
// A `rotate()` before the replacement is current makes this rotation a manual one: it takes the replacement.
|
|
282
|
+
let manual = false;
|
|
283
|
+
const isManual = () => {
|
|
284
|
+
if (rotateRequested) {
|
|
285
|
+
rotateRequested = false;
|
|
286
|
+
manual = true;
|
|
287
|
+
}
|
|
288
|
+
return manual;
|
|
289
|
+
};
|
|
290
|
+
isManual();
|
|
291
|
+
const next = await rotateFrom(opened, isManual);
|
|
292
|
+
if (next)
|
|
293
|
+
return { next };
|
|
294
|
+
if (opened.live.signal.aborted || stopped)
|
|
295
|
+
return await subscriber.closed;
|
|
296
|
+
if (!manual)
|
|
297
|
+
automatic = false;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
finally {
|
|
301
|
+
scope.abort();
|
|
302
|
+
wakeRotation = () => { };
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
const run = async () => {
|
|
306
|
+
let attempt = 0;
|
|
307
|
+
/** A connection a rotation already opened and moved the wants to. */
|
|
308
|
+
let next;
|
|
309
|
+
while (!stopped) {
|
|
310
|
+
let opened = next;
|
|
311
|
+
next = undefined;
|
|
312
|
+
if (!opened) {
|
|
313
|
+
try {
|
|
314
|
+
opened = await connectOnce();
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
if (stopped)
|
|
318
|
+
return;
|
|
319
|
+
if (first && isSetupFailure(error)) {
|
|
320
|
+
first.reject(error);
|
|
321
|
+
first = undefined;
|
|
322
|
+
stop({ error });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
setStatus('reconnecting', error);
|
|
326
|
+
await sleep(backoffDelay(attempt++, backoff), lifetime.signal).catch(() => { });
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (!opened)
|
|
330
|
+
return;
|
|
331
|
+
// `close()` may have run while the helper's result was on its way here: it could not see this connection.
|
|
332
|
+
if (stopped) {
|
|
333
|
+
opened.live.subscriber.close();
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
current = opened.live;
|
|
337
|
+
setStatus('live');
|
|
338
|
+
first?.resolve();
|
|
339
|
+
first = undefined;
|
|
340
|
+
for (const wake of connectionWaiters.splice(0))
|
|
341
|
+
wake();
|
|
342
|
+
}
|
|
343
|
+
const upAt = performance.now();
|
|
344
|
+
const outcome = await serve(opened);
|
|
345
|
+
if ('next' in outcome) {
|
|
346
|
+
if (stopped)
|
|
347
|
+
return;
|
|
348
|
+
next = outcome.next;
|
|
349
|
+
attempt = 0;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
settleEnded(opened);
|
|
353
|
+
if (stopped)
|
|
354
|
+
return;
|
|
355
|
+
current = undefined;
|
|
356
|
+
// Already reported if the connection ended while a rotation's replacement was connecting.
|
|
357
|
+
if (status !== 'reconnecting')
|
|
358
|
+
setStatus('reconnecting', outcome.error);
|
|
359
|
+
if (performance.now() - upAt > backoff.maxDelayMs)
|
|
360
|
+
attempt = 0;
|
|
361
|
+
await sleep(backoffDelay(attempt++, backoff), lifetime.signal).catch(() => { });
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
const supervise = async () => {
|
|
365
|
+
try {
|
|
366
|
+
await run();
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
// An application callback (onStatus) threw: stop rather than leave the supervisor neither reconnecting nor
|
|
370
|
+
// closed, and fail a caller still waiting to connect.
|
|
371
|
+
stop({ error });
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
// A second throw, from onStatus reporting `closed`, has nowhere to go: `closed` is settled either way.
|
|
375
|
+
void supervise().catch(() => { });
|
|
376
|
+
try {
|
|
377
|
+
await started;
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
signal?.removeEventListener('abort', onAbort);
|
|
381
|
+
throw error;
|
|
382
|
+
}
|
|
383
|
+
if (stopped)
|
|
384
|
+
throw signal?.reason ?? new RelayError('CLOSED', 'Supervised subscriber is closed', 'connection');
|
|
385
|
+
const forget = (key, want) => {
|
|
386
|
+
want.controller.abort();
|
|
387
|
+
if (wants.get(key) === want)
|
|
388
|
+
wants.delete(key);
|
|
389
|
+
};
|
|
390
|
+
return {
|
|
391
|
+
get status() {
|
|
392
|
+
return status;
|
|
393
|
+
},
|
|
394
|
+
closed,
|
|
395
|
+
want(key, wantOptions, handlers = {}) {
|
|
396
|
+
if (typeof key !== 'string')
|
|
397
|
+
throw new TypeError('want key must be a string');
|
|
398
|
+
if (typeof wantOptions !== 'object' || wantOptions === null) {
|
|
399
|
+
throw new TypeError('want takes an options object');
|
|
400
|
+
}
|
|
401
|
+
if (typeof handlers !== 'object' || handlers === null)
|
|
402
|
+
throw new TypeError('want handlers must be an object');
|
|
403
|
+
// The primitive's guard: a declared-async callback is refused, a returned promise is observed, never left unhandled.
|
|
404
|
+
const guarded = {};
|
|
405
|
+
for (const [name, callback] of Object.entries(handlers)) {
|
|
406
|
+
if (callback === undefined)
|
|
407
|
+
continue;
|
|
408
|
+
if (typeof callback !== 'function')
|
|
409
|
+
throw new TypeError(`${name} must be a function`);
|
|
410
|
+
guarded[name] = synchronousCallback(name, callback, handlers);
|
|
411
|
+
}
|
|
412
|
+
const safeHandlers = guarded;
|
|
413
|
+
const { parameters, generations = false, staleAfterMs, retry, until, drainMs = 0 } = wantOptions;
|
|
414
|
+
const namespace = namespaceFields(wantOptions.namespace);
|
|
415
|
+
if (generations)
|
|
416
|
+
namespaceFields([...namespace, 'x']);
|
|
417
|
+
const track = trackName(wantOptions.track);
|
|
418
|
+
if (staleAfterMs !== undefined)
|
|
419
|
+
assertTimeoutMs('staleAfterMs', staleAfterMs);
|
|
420
|
+
const retryBackoff = backoffOptions('retry', retry, RESUBSCRIBE_BACKOFF);
|
|
421
|
+
const predicate = untilPredicate(until);
|
|
422
|
+
assertDrainMs(drainMs);
|
|
423
|
+
if (stopped)
|
|
424
|
+
throw new RelayError('CLOSED', 'Supervised subscriber is closed', 'connection');
|
|
425
|
+
const source = JSON.stringify([namespace, generations]);
|
|
426
|
+
const target = targetKey([], track, parameters);
|
|
427
|
+
const existing = wants.get(key);
|
|
428
|
+
if (existing && existing.source === source) {
|
|
429
|
+
existing.handlers = safeHandlers;
|
|
430
|
+
existing.retry = retryBackoff;
|
|
431
|
+
existing.until = predicate;
|
|
432
|
+
existing.drainMs = drainMs;
|
|
433
|
+
const moved = existing.target !== target;
|
|
434
|
+
if (!moved && existing.options.staleAfterMs === staleAfterMs)
|
|
435
|
+
return;
|
|
436
|
+
existing.options = { ...existing.options, track, parameters, staleAfterMs };
|
|
437
|
+
existing.target = target;
|
|
438
|
+
for (const changed of [...existing.changes])
|
|
439
|
+
changed();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (existing)
|
|
443
|
+
forget(key, existing);
|
|
444
|
+
const want = {
|
|
445
|
+
options: { namespace, track, parameters, generations, staleAfterMs },
|
|
446
|
+
source,
|
|
447
|
+
target,
|
|
448
|
+
handlers: safeHandlers,
|
|
449
|
+
retry: retryBackoff,
|
|
450
|
+
until: predicate,
|
|
451
|
+
drainMs,
|
|
452
|
+
changes: new Set(),
|
|
453
|
+
controller: new AbortController(),
|
|
454
|
+
};
|
|
455
|
+
wants.set(key, want);
|
|
456
|
+
void runWant(want, liveConnection, () => current, () => forget(key, want));
|
|
457
|
+
},
|
|
458
|
+
unwant(key) {
|
|
459
|
+
const want = wants.get(key);
|
|
460
|
+
if (want)
|
|
461
|
+
forget(key, want);
|
|
462
|
+
},
|
|
463
|
+
catchUp(key) {
|
|
464
|
+
if (typeof key !== 'string')
|
|
465
|
+
throw new TypeError('want key must be a string');
|
|
466
|
+
wants.get(key)?.catchUp?.();
|
|
467
|
+
},
|
|
468
|
+
rotate() {
|
|
469
|
+
requestRotation();
|
|
470
|
+
},
|
|
471
|
+
close() {
|
|
472
|
+
signal?.removeEventListener('abort', onAbort);
|
|
473
|
+
stop({});
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Whether a request refused at the call is the want's own fault, which no connection fixes: an argument, or a root
|
|
479
|
+
* overlapping another followed root. Anything else thrown there (CLOSED, the connection's TRANSPORT_ERROR or GOAWAY)
|
|
480
|
+
* is the connection ending before the supervisor has heard of it.
|
|
481
|
+
*/
|
|
482
|
+
function refusedForGood(error) {
|
|
483
|
+
// The core's encoders refuse a request the wire cannot carry (a field too long to encode) the same way every time.
|
|
484
|
+
if (error instanceof TypeError || error instanceof RangeError || isMoqtProtocolError(error))
|
|
485
|
+
return true;
|
|
486
|
+
return error instanceof RelayError && error.code === 'PREFIX_OVERLAP';
|
|
487
|
+
}
|
|
488
|
+
/** Supervise `want`; a failure its loop did not expect forgets it rather than leave it registered but dead. */
|
|
489
|
+
async function runWant(want, liveConnection, nextConnection, forget) {
|
|
490
|
+
try {
|
|
491
|
+
await superviseWant(want, liveConnection, nextConnection, forget);
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
forget();
|
|
495
|
+
// biome-ignore lint/suspicious/noConsole: the want has no caller left to report its failure to
|
|
496
|
+
console.error(new Error('A want stopped on an unexpected failure and was forgotten', { cause: error }));
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
/** Keep `want` subscribed until it is cancelled or fails for good. */
|
|
500
|
+
async function superviseWant(want, liveConnection, nextConnection, forget) {
|
|
501
|
+
const scope = want.controller.signal;
|
|
502
|
+
let failures = 0;
|
|
503
|
+
// A re-want asks for something new: its first failure waits the shortest delay again.
|
|
504
|
+
const changed = () => {
|
|
505
|
+
failures = 0;
|
|
506
|
+
};
|
|
507
|
+
want.changes.add(changed);
|
|
508
|
+
try {
|
|
509
|
+
await keepSubscribed();
|
|
510
|
+
}
|
|
511
|
+
finally {
|
|
512
|
+
want.changes.delete(changed);
|
|
513
|
+
}
|
|
514
|
+
async function keepSubscribed() {
|
|
515
|
+
while (!scope.aborted) {
|
|
516
|
+
if (want.deferred) {
|
|
517
|
+
// A discovery refusal seen while backing off is reported as one seen during an attempt would be.
|
|
518
|
+
forget();
|
|
519
|
+
want.handlers.onError?.(want.deferred.error);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
const started = await liveConnection(scope);
|
|
523
|
+
// A want replaced while waiting must not open anything: its replacement may already hold an overlapping root.
|
|
524
|
+
if (!started || scope.aborted)
|
|
525
|
+
return;
|
|
526
|
+
want.settledTarget = undefined;
|
|
527
|
+
want.connection = started;
|
|
528
|
+
let outcome = await attempt(want, started, nextConnection);
|
|
529
|
+
// A rotation may have moved the attempt to another connection: what follows waits on the one it ended on.
|
|
530
|
+
const connection = want.connection ?? started;
|
|
531
|
+
const asked = want.settledTarget ?? want.target;
|
|
532
|
+
if (scope.aborted)
|
|
533
|
+
return;
|
|
534
|
+
if (outcome.kind === 'cancelled')
|
|
535
|
+
return;
|
|
536
|
+
// A re-want that came after the attempt settled asks for another track or parameters: the old target's failure
|
|
537
|
+
// is not the new one's, so try the new one at once. A subscription the failed move cancelled was a restart.
|
|
538
|
+
if (outcome.kind === 'fatal' && want.target !== asked)
|
|
539
|
+
outcome = {
|
|
540
|
+
kind: 'retry',
|
|
541
|
+
accepted: outcome.accepted ?? false,
|
|
542
|
+
progressed: false,
|
|
543
|
+
reason: outcome.reason ?? 'terminated',
|
|
544
|
+
};
|
|
545
|
+
if (outcome.kind === 'fatal') {
|
|
546
|
+
forget();
|
|
547
|
+
want.handlers.onError?.(outcome.error);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const reason = outcome.kind === 'connection' ? 'connection' : outcome.kind === 'moved' ? 'generation' : outcome.reason;
|
|
551
|
+
if (outcome.accepted && reason) {
|
|
552
|
+
try {
|
|
553
|
+
want.handlers.onRestarted?.({ reason, namespace: [...(want.namespace ?? [])] });
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
// A delivery callback's failure is the application's; the want keeps its track subscribed.
|
|
557
|
+
// biome-ignore lint/suspicious/noConsole: the application's callback failed and has no caller to report to
|
|
558
|
+
console.error(new Error('onRestarted threw; the want resubscribes regardless', { cause: error }));
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (outcome.kind === 'connection') {
|
|
562
|
+
// The request can see the end before the connection reports it; wait for that rather than spin on it.
|
|
563
|
+
await Promise.race([whenAborted(connection.signal), sleep(1_000, scope).catch(() => { })]);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (outcome.kind !== 'retry' || want.target !== asked)
|
|
567
|
+
continue;
|
|
568
|
+
// A catch-up replaces a subscription that was delivering: the replacement is wanted now, not after a backoff.
|
|
569
|
+
if (outcome.reason === 'catch-up' && outcome.progressed) {
|
|
570
|
+
failures = 0;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
// Cached objects followed by a done are not progress: only a later group resets the backoff.
|
|
574
|
+
if (outcome.progressed)
|
|
575
|
+
failures = 0;
|
|
576
|
+
await backoff(want, connection, backoffDelay(failures++, want.retry));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Wait out a retry delay, cut short when a fresh attempt can do better at once: the connection ended, or (following
|
|
582
|
+
* generations) a generation other than the last one tried became the newest.
|
|
583
|
+
*/
|
|
584
|
+
async function backoff(want, connection, delayMs) {
|
|
585
|
+
const wake = new AbortController();
|
|
586
|
+
// A rotation replacing the connection wakes it too: the want's next attempt belongs on the new one.
|
|
587
|
+
const scope = AbortSignal.any([want.controller.signal, connection.signal, connection.retiring, wake.signal]);
|
|
588
|
+
let held;
|
|
589
|
+
if (want.options.generations && !connection.signal.aborted) {
|
|
590
|
+
try {
|
|
591
|
+
held = rootWatch(connection, want.options.namespace);
|
|
592
|
+
}
|
|
593
|
+
catch {
|
|
594
|
+
// The attempt itself reports a discovery it cannot open.
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
// Released in the turn the want is cancelled, as in an attempt, so a replacement can claim an overlapping root.
|
|
598
|
+
if (held)
|
|
599
|
+
want.controller.signal.addEventListener('abort', held.release, { once: true });
|
|
600
|
+
// Only a newer generation wakes the wait. A discovery that fails again does not: the next attempt reports it after
|
|
601
|
+
// the delay, so failing discovery is retried no faster than the backoff.
|
|
602
|
+
const changed = () => {
|
|
603
|
+
if (!held)
|
|
604
|
+
return;
|
|
605
|
+
const failure = held.watch.failure();
|
|
606
|
+
if (failure) {
|
|
607
|
+
// A failure no wait fixes is kept for the next turn of the loop, which surfaces it; any other waits out the delay.
|
|
608
|
+
const outcome = discoveryFailed(failure.error, new AbortController().signal, () => ({ kind: 'cancelled' }), false);
|
|
609
|
+
if (outcome.kind === 'fatal') {
|
|
610
|
+
want.deferred = { error: failure.error };
|
|
611
|
+
wake.abort();
|
|
612
|
+
}
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
// A fresh discovery starts empty; no generation yet is not a newer one.
|
|
616
|
+
const newest = held.watch.current();
|
|
617
|
+
if (newest !== undefined && newest !== want.generation)
|
|
618
|
+
wake.abort();
|
|
619
|
+
};
|
|
620
|
+
const unwatch = held?.watch.onChange(changed);
|
|
621
|
+
// A re-want asks for something the failed attempt did not: try it at once.
|
|
622
|
+
const rewanted = () => wake.abort();
|
|
623
|
+
want.changes.add(rewanted);
|
|
624
|
+
try {
|
|
625
|
+
changed();
|
|
626
|
+
await sleep(delayMs, scope).catch(() => { });
|
|
627
|
+
}
|
|
628
|
+
finally {
|
|
629
|
+
want.changes.delete(rewanted);
|
|
630
|
+
unwatch?.();
|
|
631
|
+
if (held)
|
|
632
|
+
want.controller.signal.removeEventListener('abort', held.release);
|
|
633
|
+
held?.release();
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/** One attempt for `want` on `connection`: its discovery, if it follows generations, and its subscriptions. */
|
|
637
|
+
async function attempt(want, connection, nextConnection) {
|
|
638
|
+
const { options } = want;
|
|
639
|
+
const scope = AbortSignal.any([want.controller.signal, connection.signal]);
|
|
640
|
+
const cancelledOrConnection = (accepted) => want.controller.signal.aborted ? { kind: 'cancelled' } : { kind: 'connection', accepted };
|
|
641
|
+
let namespace = options.namespace;
|
|
642
|
+
let watch;
|
|
643
|
+
let release = () => { };
|
|
644
|
+
if (options.generations) {
|
|
645
|
+
try {
|
|
646
|
+
({ watch, release } = rootWatch(connection, options.namespace));
|
|
647
|
+
// Released in the turn the want is cancelled, so a replacement want can claim an overlapping root at once.
|
|
648
|
+
scope.addEventListener('abort', release, { once: true });
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
// As for a subscribe: a connection ending under the call refuses the request with its own error.
|
|
652
|
+
if (scope.aborted || !refusedForGood(error))
|
|
653
|
+
return cancelledOrConnection(false);
|
|
654
|
+
return { kind: 'fatal', error };
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
try {
|
|
658
|
+
let generation;
|
|
659
|
+
if (watch) {
|
|
660
|
+
const found = await watch.newest(AbortSignal.any([scope, connection.retiring]));
|
|
661
|
+
if (found.kind === 'failed')
|
|
662
|
+
return discoveryFailed(found.error, scope, cancelledOrConnection, false);
|
|
663
|
+
// Rotated away before a generation was found: start over on the new connection at once.
|
|
664
|
+
if (found.kind !== 'found' && connection.retiring.aborted && !scope.aborted)
|
|
665
|
+
return { kind: 'moved', accepted: false };
|
|
666
|
+
if (found.kind !== 'found')
|
|
667
|
+
return cancelledOrConnection(false);
|
|
668
|
+
generation = found.generation;
|
|
669
|
+
namespace = [...options.namespace, generation];
|
|
670
|
+
}
|
|
671
|
+
want.namespace = namespace;
|
|
672
|
+
want.generation = generation;
|
|
673
|
+
// The want's own signal, not the connection's: a rotation moves the attempt to the next connection.
|
|
674
|
+
return await follow(want, connection, namespace, generation, want.controller.signal, watch, cancelledOrConnection, nextConnection);
|
|
675
|
+
}
|
|
676
|
+
finally {
|
|
677
|
+
release();
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
/** Whether `object` is at or before `latest`, by group and then object ID. */
|
|
681
|
+
function atOrBefore(object, latest) {
|
|
682
|
+
if (latest === undefined)
|
|
683
|
+
return false;
|
|
684
|
+
return object.groupId < latest.groupId || (object.groupId === latest.groupId && object.objectId <= latest.objectId);
|
|
685
|
+
}
|
|
686
|
+
/** The later of two locations, either of which may be unknown. */
|
|
687
|
+
function later(a, b) {
|
|
688
|
+
if (a === undefined)
|
|
689
|
+
return b;
|
|
690
|
+
if (b === undefined)
|
|
691
|
+
return a;
|
|
692
|
+
return a.groupId > b.groupId || (a.groupId === b.groupId && a.objectId >= b.objectId) ? a : b;
|
|
693
|
+
}
|
|
694
|
+
/** Record `object` as the latest `slot` delivered, if it is later than what it had. */
|
|
695
|
+
function delivered(slot, object) {
|
|
696
|
+
if (!atOrBefore(object, slot.latest))
|
|
697
|
+
slot.latest = { groupId: object.groupId, objectId: object.objectId };
|
|
698
|
+
}
|
|
699
|
+
/** What a subscription is made with, as a comparable key. */
|
|
700
|
+
function targetKey(namespace, track, parameters) {
|
|
701
|
+
return JSON.stringify([namespace, track, parameters ?? null], (_, value) => typeof value === 'bigint' ? `${value}n` : value);
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* The want's subscriptions from the first SUBSCRIBE on `connection` to whatever ends the attempt. A move (a newer
|
|
705
|
+
* generation, or a re-want with another track or parameters) is made before the break: the replacement opens pending
|
|
706
|
+
* while the active subscription keeps delivering, and takes over once one of its objects passes `until`. A rotation is
|
|
707
|
+
* a move to the next connection: with the target unchanged, the replacement takes over at the first object the active
|
|
708
|
+
* one had not delivered, and no callback marks it.
|
|
709
|
+
*/
|
|
710
|
+
async function follow(want, connection, namespace, generation, scope, initialWatch, cancelledOrConnection, nextConnection) {
|
|
711
|
+
/** The followed root's discovery on the active subscription's connection. */
|
|
712
|
+
let watch = initialWatch;
|
|
713
|
+
const handlers = () => want.handlers;
|
|
714
|
+
const settled = new AbortController();
|
|
715
|
+
let outcome;
|
|
716
|
+
const settle = (next) => {
|
|
717
|
+
if (outcome)
|
|
718
|
+
return;
|
|
719
|
+
// A failure no wait fixes still ends an accepted subscription, which a superseding re-want reports as a restart.
|
|
720
|
+
outcome = next.kind === 'fatal' ? { ...next, accepted: accepted(), reason: active.ended } : next;
|
|
721
|
+
want.settledTarget = want.target;
|
|
722
|
+
settled.abort();
|
|
723
|
+
};
|
|
724
|
+
const over = () => outcome !== undefined || scope.aborted;
|
|
725
|
+
let active;
|
|
726
|
+
let pending;
|
|
727
|
+
/** Old subscriptions draining after a cutover, each with the timer that cancels it. */
|
|
728
|
+
const draining = new Map();
|
|
729
|
+
/** A move whose replacement failed, retried after the backoff unless the want asks for something else first. */
|
|
730
|
+
let retryMove;
|
|
731
|
+
let moveFailures = 0;
|
|
732
|
+
/** The target of the latest move, whose failures `moveFailures` counts. */
|
|
733
|
+
let moveTarget;
|
|
734
|
+
let lastObjectAt = 0;
|
|
735
|
+
const accepted = () => active.accepted !== undefined;
|
|
736
|
+
/** A rotation under way: the connection the subscriptions move to, and its discovery of the root. */
|
|
737
|
+
let rotationTo;
|
|
738
|
+
/** The discovery a rotation swapped in, released when the attempt ends; the first is the attempt's to release. */
|
|
739
|
+
let releaseWatch = () => { };
|
|
740
|
+
/** The connections a subscription of this attempt is on, each held so a rotation closes it only once none are. */
|
|
741
|
+
const holds = new Map();
|
|
742
|
+
/** How to stop observing each connection the attempt observes; dropped with its hold. */
|
|
743
|
+
const observed = new Map();
|
|
744
|
+
const observe = (on) => {
|
|
745
|
+
if (observed.has(on))
|
|
746
|
+
return;
|
|
747
|
+
// Runs inside the supervisor's abort of the retiring signal: an unexpected failure restarts this want alone.
|
|
748
|
+
const onRetiring = () => {
|
|
749
|
+
try {
|
|
750
|
+
rotate(on);
|
|
751
|
+
}
|
|
752
|
+
catch (error) {
|
|
753
|
+
// biome-ignore lint/suspicious/noConsole: the want's own failure, with no caller to report it to
|
|
754
|
+
console.error(new Error('A want failed to start its rotation; it restarts on the new connection', { cause: error }));
|
|
755
|
+
settle(cancelledOrConnection(accepted()));
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
on.retiring.addEventListener('abort', onRetiring, { once: true });
|
|
759
|
+
observed.set(on, () => on.retiring.removeEventListener('abort', onRetiring));
|
|
760
|
+
if (on.retiring.aborted)
|
|
761
|
+
queueMicrotask(onRetiring);
|
|
762
|
+
};
|
|
763
|
+
const holdOn = (on) => {
|
|
764
|
+
if (holds.has(on))
|
|
765
|
+
return;
|
|
766
|
+
holds.set(on, hold(on));
|
|
767
|
+
observe(on);
|
|
768
|
+
};
|
|
769
|
+
const releaseUnused = () => {
|
|
770
|
+
for (const [on, release] of [...holds]) {
|
|
771
|
+
const used = active.connection === on ||
|
|
772
|
+
pending?.connection === on ||
|
|
773
|
+
rotationTo?.connection === on ||
|
|
774
|
+
[...draining.keys()].some((slot) => slot.connection === on);
|
|
775
|
+
if (used)
|
|
776
|
+
continue;
|
|
777
|
+
holds.delete(on);
|
|
778
|
+
release();
|
|
779
|
+
observed.get(on)?.();
|
|
780
|
+
observed.delete(on);
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
/**
|
|
784
|
+
* The targets a pending replacement heard PUBLISH_DONE on, until the next cutover: a restarted publisher numbers its
|
|
785
|
+
* groups from 0, so a rotation's replacement for that target no longer skips what the active subscription delivered.
|
|
786
|
+
* Another target's publisher ending says nothing about the active one's.
|
|
787
|
+
*/
|
|
788
|
+
const endedTargets = new Set();
|
|
789
|
+
/** Whether `slot` replaces the active subscription on the next connection, with the same target. */
|
|
790
|
+
const rotating = (slot) => slot.connection !== active.connection && slot.key === active.key;
|
|
791
|
+
const clearRetry = () => {
|
|
792
|
+
clearTimeout(retryMove?.timer);
|
|
793
|
+
retryMove?.unobserve();
|
|
794
|
+
retryMove = undefined;
|
|
795
|
+
};
|
|
796
|
+
const stopDrain = (slot) => {
|
|
797
|
+
clearTimeout(draining.get(slot));
|
|
798
|
+
draining.delete(slot);
|
|
799
|
+
slot.subscription.cancel();
|
|
800
|
+
releaseUnused();
|
|
801
|
+
};
|
|
802
|
+
/** Whether a subgroup event of `slot` reaches the handlers. */
|
|
803
|
+
const reaches = (slot, groupId) => slot !== undefined &&
|
|
804
|
+
!over() &&
|
|
805
|
+
((slot === active && !slot.ended) || (draining.has(slot) && groupId <= slot.drainThrough));
|
|
806
|
+
/** The active subscription ended without the connection: with a move pending, the move carries on. */
|
|
807
|
+
const activeEnded = (reason) => {
|
|
808
|
+
if (pending) {
|
|
809
|
+
active.ended = reason;
|
|
810
|
+
active.subscription.cancel();
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
settle({ kind: 'retry', accepted: accepted(), progressed: active.progressed, reason });
|
|
814
|
+
};
|
|
815
|
+
/** A move's replacement ended before its cutover. */
|
|
816
|
+
const pendingFailed = (slot, end) => {
|
|
817
|
+
pending = undefined;
|
|
818
|
+
slot.subscription.cancel();
|
|
819
|
+
// The connection's end reaches the active subscription and the attempt's scope as well.
|
|
820
|
+
if (end?.cause === 'connection-closed') {
|
|
821
|
+
settle(cancelledOrConnection(accepted()));
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
const failed = end ? classify(end, false, false, cancelledOrConnection) : undefined;
|
|
825
|
+
if (failed?.kind === 'fatal') {
|
|
826
|
+
settle(failed);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
if (active.ended) {
|
|
830
|
+
settle({ kind: 'retry', accepted: true, progressed: active.progressed, reason: active.ended });
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
// The active subscription keeps delivering; the move is retried after the backoff.
|
|
834
|
+
const key = slot.key;
|
|
835
|
+
const on = slot.connection;
|
|
836
|
+
// The connection the move is to be retried on closing leaves nothing to retry on: restart now, not after the delay.
|
|
837
|
+
const closed = () => {
|
|
838
|
+
if (retryMove?.connection !== on || over())
|
|
839
|
+
return;
|
|
840
|
+
clearRetry();
|
|
841
|
+
settle(cancelledOrConnection(accepted()));
|
|
842
|
+
};
|
|
843
|
+
on.signal.addEventListener('abort', closed, { once: true });
|
|
844
|
+
retryMove = {
|
|
845
|
+
key,
|
|
846
|
+
connection: on,
|
|
847
|
+
timer: setTimeout(() => {
|
|
848
|
+
if (retryMove?.key !== key)
|
|
849
|
+
return;
|
|
850
|
+
clearRetry();
|
|
851
|
+
reconcile();
|
|
852
|
+
}, backoffDelay(moveFailures++, want.retry)),
|
|
853
|
+
unobserve: () => on.signal.removeEventListener('abort', closed),
|
|
854
|
+
};
|
|
855
|
+
if (on.signal.aborted)
|
|
856
|
+
closed();
|
|
857
|
+
};
|
|
858
|
+
const cutover = (slot, object) => {
|
|
859
|
+
const from = active;
|
|
860
|
+
// A rotation that keeps the target continues the same stream: nothing to mark, and no drain to repeat objects.
|
|
861
|
+
const silent = rotating(slot);
|
|
862
|
+
// Same stream, same numbering: what the old subscription delivered stays delivered, even arriving late here.
|
|
863
|
+
if (silent && !endedTargets.has(slot.key) && from.ended !== 'publisher-done') {
|
|
864
|
+
slot.skipThrough = later(from.latest, from.skipThrough);
|
|
865
|
+
}
|
|
866
|
+
endedTargets.clear();
|
|
867
|
+
pending = undefined;
|
|
868
|
+
clearRetry();
|
|
869
|
+
moveFailures = 0;
|
|
870
|
+
active = slot;
|
|
871
|
+
want.namespace = slot.namespace;
|
|
872
|
+
want.generation = slot.generation;
|
|
873
|
+
want.connection = slot.connection;
|
|
874
|
+
if (rotationTo && rotationTo.connection === slot.connection) {
|
|
875
|
+
// The followed root's discovery moves to the new connection with the subscription.
|
|
876
|
+
unwatch?.();
|
|
877
|
+
unwatchNext?.();
|
|
878
|
+
unwatchNext = undefined;
|
|
879
|
+
watch = rotationTo.watch;
|
|
880
|
+
releaseWatch = rotationTo.release;
|
|
881
|
+
rotationTo = undefined;
|
|
882
|
+
unwatch = watch?.onChange(reconcile);
|
|
883
|
+
}
|
|
884
|
+
if (!silent && !from.ended && want.drainMs > 0 && from.largestGroup !== undefined) {
|
|
885
|
+
from.drainThrough = from.largestGroup;
|
|
886
|
+
draining.set(from, setTimeout(() => stopDrain(from), want.drainMs));
|
|
887
|
+
}
|
|
888
|
+
else
|
|
889
|
+
from.subscription.cancel();
|
|
890
|
+
releaseUnused();
|
|
891
|
+
slot.firstGroup = object.groupId;
|
|
892
|
+
slot.largestGroup = object.groupId;
|
|
893
|
+
lastObjectAt = performance.now();
|
|
894
|
+
if (!silent) {
|
|
895
|
+
try {
|
|
896
|
+
handlers().onSwitched?.({
|
|
897
|
+
from: { namespace: [...from.namespace], track: from.track },
|
|
898
|
+
to: { namespace: [...slot.namespace], track: slot.track },
|
|
899
|
+
// A subscription that delivered an object was accepted.
|
|
900
|
+
subscribed: slot.accepted,
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
catch (error) {
|
|
904
|
+
// A delivery callback's failure is the application's; the want keeps delivering.
|
|
905
|
+
// biome-ignore lint/suspicious/noConsole: the application's callback failed and has no caller to report to
|
|
906
|
+
console.error(new Error('onSwitched threw; the want delivers regardless', { cause: error }));
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
// Later groups that reached the replacement early, out of order, follow the object that cut over. Each delivery
|
|
910
|
+
// is isolated, so one throwing callback loses neither the rest nor the held events.
|
|
911
|
+
const replay = heldAfter(slot.held, object);
|
|
912
|
+
slot.held = [];
|
|
913
|
+
const deliver = (call) => {
|
|
914
|
+
try {
|
|
915
|
+
call();
|
|
916
|
+
}
|
|
917
|
+
catch (error) {
|
|
918
|
+
// biome-ignore lint/suspicious/noConsole: the application's callback failed and has no caller to report to
|
|
919
|
+
console.error(new Error('A want handler threw at a cutover; the want delivers regardless', { cause: error }));
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
// A handler may have moved the want again or cancelled it; the object still belongs to this cutover.
|
|
923
|
+
delivered(slot, object);
|
|
924
|
+
if (!over() && active === slot)
|
|
925
|
+
deliver(() => handlers().onObject?.(object));
|
|
926
|
+
for (const event of replay) {
|
|
927
|
+
if (over() || active !== slot)
|
|
928
|
+
break;
|
|
929
|
+
if (event.type === 'object') {
|
|
930
|
+
delivered(slot, event.value);
|
|
931
|
+
if (event.value.groupId > slot.firstGroup)
|
|
932
|
+
slot.progressed = true;
|
|
933
|
+
if (event.value.groupId > slot.largestGroup)
|
|
934
|
+
slot.largestGroup = event.value.groupId;
|
|
935
|
+
deliver(() => handlers().onObject?.(event.value));
|
|
936
|
+
}
|
|
937
|
+
else if (event.type === 'subgroupEnd')
|
|
938
|
+
deliver(() => handlers().onSubgroupEnd?.(event.value));
|
|
939
|
+
else
|
|
940
|
+
deliver(() => handlers().onSubgroupReset?.(event.value));
|
|
941
|
+
}
|
|
942
|
+
};
|
|
943
|
+
const onObject = (slot, object) => {
|
|
944
|
+
if (!slot || over())
|
|
945
|
+
return;
|
|
946
|
+
if (slot === active) {
|
|
947
|
+
if (slot.ended)
|
|
948
|
+
return;
|
|
949
|
+
if (atOrBefore(object, slot.skipThrough))
|
|
950
|
+
return;
|
|
951
|
+
lastObjectAt = performance.now();
|
|
952
|
+
if (slot.firstGroup === undefined)
|
|
953
|
+
slot.firstGroup = object.groupId;
|
|
954
|
+
else if (object.groupId > slot.firstGroup)
|
|
955
|
+
slot.progressed = true;
|
|
956
|
+
if (slot.largestGroup === undefined || object.groupId > slot.largestGroup)
|
|
957
|
+
slot.largestGroup = object.groupId;
|
|
958
|
+
delivered(slot, object);
|
|
959
|
+
handlers().onObject?.(object);
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
if (draining.has(slot)) {
|
|
963
|
+
if (object.groupId <= slot.drainThrough)
|
|
964
|
+
handlers().onObject?.(object);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
if (slot !== pending)
|
|
968
|
+
return;
|
|
969
|
+
lastObjectAt = performance.now();
|
|
970
|
+
// The active subscription's ending reaches `ended` a turn later; one already recorded counts now.
|
|
971
|
+
const activeEnd = active.subscription.end;
|
|
972
|
+
if (!active.ended && activeEnd) {
|
|
973
|
+
onEnded(active, activeEnd);
|
|
974
|
+
if (over() || pending !== slot)
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
// A rotation's replacement starts at the latest group, which the active subscription may have delivered: skip it.
|
|
978
|
+
// Not once the publisher ended or the subscription was ended by it: a restarted publisher numbers from 0 again.
|
|
979
|
+
const rotation = rotating(slot);
|
|
980
|
+
// Only PUBLISH_DONE says the publisher may number from 0 again; a stale, terminated or disconnected subscription
|
|
981
|
+
// does not.
|
|
982
|
+
const continues = !endedTargets.has(slot.key) && active.ended !== 'publisher-done';
|
|
983
|
+
if (rotation && continues && atOrBefore(object, active.latest))
|
|
984
|
+
return;
|
|
985
|
+
// With the active subscription gone there is nothing left to compare with: the next object cuts over. A rotation's
|
|
986
|
+
// replacement continues the same stream, so its first new object does too.
|
|
987
|
+
let passed = true;
|
|
988
|
+
if (!active.ended && !rotation) {
|
|
989
|
+
try {
|
|
990
|
+
passed = want.until(object);
|
|
991
|
+
}
|
|
992
|
+
catch (error) {
|
|
993
|
+
// biome-ignore lint/suspicious/noConsole: the application's predicate failed and has no caller to report to
|
|
994
|
+
console.error(new Error('until threw; the want cuts over on this object', { cause: error }));
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
// The predicate is application code: it may have moved the want again or cancelled it.
|
|
998
|
+
if (!passed)
|
|
999
|
+
holdEvent(slot.held, { type: 'object', value: object });
|
|
1000
|
+
else if (!over() && pending === slot)
|
|
1001
|
+
cutover(slot, object);
|
|
1002
|
+
};
|
|
1003
|
+
/** One subscription's ending; safe to run again for the same slot. */
|
|
1004
|
+
const onEnded = (slot, end) => {
|
|
1005
|
+
if (over())
|
|
1006
|
+
return;
|
|
1007
|
+
if (draining.has(slot))
|
|
1008
|
+
stopDrain(slot);
|
|
1009
|
+
else if (slot === pending)
|
|
1010
|
+
pendingFailed(slot, end);
|
|
1011
|
+
else if (slot === active && !slot.ended) {
|
|
1012
|
+
// The retiring connection closed under the active subscription: the rotation's replacement carries on, or is
|
|
1013
|
+
// tried again on the next connection after its backoff.
|
|
1014
|
+
if (end.cause === 'connection-closed' && pending && pending.connection !== slot.connection) {
|
|
1015
|
+
activeEnded('connection');
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
const elsewhere = (retryMove && retryMove.connection !== slot.connection) ||
|
|
1019
|
+
(rotationTo && rotationTo.connection !== slot.connection);
|
|
1020
|
+
if (end.cause === 'connection-closed' && !pending && elsewhere) {
|
|
1021
|
+
slot.ended = 'connection';
|
|
1022
|
+
slot.subscription.cancel();
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
const next = classify(end, accepted(), slot.progressed, cancelledOrConnection);
|
|
1026
|
+
if (next.kind === 'retry' && next.reason)
|
|
1027
|
+
activeEnded(next.reason);
|
|
1028
|
+
else
|
|
1029
|
+
settle(next);
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
const open = (target, targetGeneration, on) => {
|
|
1033
|
+
const { track, parameters } = want.options;
|
|
1034
|
+
let slot;
|
|
1035
|
+
const subscription = on.subscriber.subscribe({ namespace: target, track, ...(parameters ? { parameters } : {}) }, {
|
|
1036
|
+
onSubscribed: (info) => {
|
|
1037
|
+
if (!slot || over())
|
|
1038
|
+
return;
|
|
1039
|
+
slot.accepted = info;
|
|
1040
|
+
if (slot !== active)
|
|
1041
|
+
return;
|
|
1042
|
+
lastObjectAt = performance.now();
|
|
1043
|
+
handlers().onSubscribed?.(info, { namespace: [...slot.namespace] });
|
|
1044
|
+
},
|
|
1045
|
+
onObject: (object) => onObject(slot, object),
|
|
1046
|
+
onSubgroupEnd: (info) => {
|
|
1047
|
+
if (slot && slot === pending && !over())
|
|
1048
|
+
holdEvent(slot.held, { type: 'subgroupEnd', value: info });
|
|
1049
|
+
else if (reaches(slot, info.groupId))
|
|
1050
|
+
handlers().onSubgroupEnd?.(info);
|
|
1051
|
+
},
|
|
1052
|
+
onSubgroupReset: (info) => {
|
|
1053
|
+
if (slot && slot === pending && !over())
|
|
1054
|
+
holdEvent(slot.held, { type: 'subgroupReset', value: info });
|
|
1055
|
+
else if (reaches(slot, info.groupId))
|
|
1056
|
+
handlers().onSubgroupReset?.(info);
|
|
1057
|
+
},
|
|
1058
|
+
onPublisherDone: (info) => {
|
|
1059
|
+
if (!slot || over())
|
|
1060
|
+
return;
|
|
1061
|
+
// Heard on the replacement: the publisher behind both ended. An old subscription a move left behind hearing
|
|
1062
|
+
// its own publisher end says nothing about the current one.
|
|
1063
|
+
if (slot === pending)
|
|
1064
|
+
endedTargets.add(slot.key);
|
|
1065
|
+
if (slot === pending)
|
|
1066
|
+
pendingFailed(slot, undefined);
|
|
1067
|
+
else if (slot === active && !slot.ended) {
|
|
1068
|
+
activeEnded('publisher-done');
|
|
1069
|
+
handlers().onPublisherDone?.(info);
|
|
1070
|
+
}
|
|
1071
|
+
},
|
|
1072
|
+
});
|
|
1073
|
+
const opened = {
|
|
1074
|
+
namespace: target,
|
|
1075
|
+
generation: targetGeneration,
|
|
1076
|
+
track,
|
|
1077
|
+
key: targetKey(target, track, parameters),
|
|
1078
|
+
connection: on,
|
|
1079
|
+
subscription,
|
|
1080
|
+
progressed: false,
|
|
1081
|
+
held: [],
|
|
1082
|
+
};
|
|
1083
|
+
slot = opened;
|
|
1084
|
+
holdOn(on);
|
|
1085
|
+
void subscription.subscribed.catch(() => { });
|
|
1086
|
+
void subscription.ended.then((end) => onEnded(opened, end));
|
|
1087
|
+
return opened;
|
|
1088
|
+
};
|
|
1089
|
+
/** Bring the subscriptions in line with what the want asks for now: its options and the newest generation. */
|
|
1090
|
+
const reconcile = () => {
|
|
1091
|
+
if (over())
|
|
1092
|
+
return;
|
|
1093
|
+
// During a rotation the subscription belongs on the next connection, following that connection's discovery.
|
|
1094
|
+
const on = rotationTo?.connection ?? active.connection;
|
|
1095
|
+
const discovery = rotationTo ? rotationTo.watch : watch;
|
|
1096
|
+
let target = want.options.namespace;
|
|
1097
|
+
let targetGeneration;
|
|
1098
|
+
if (discovery) {
|
|
1099
|
+
const failure = discovery.failure();
|
|
1100
|
+
if (failure) {
|
|
1101
|
+
settle(discoveryFailed(failure.error, scope, cancelledOrConnection, accepted()));
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
targetGeneration = discovery.current();
|
|
1105
|
+
// A rotation's discovery on the next connection has found nothing yet: wait for it, the old one still delivers.
|
|
1106
|
+
if (targetGeneration === undefined && rotationTo)
|
|
1107
|
+
return;
|
|
1108
|
+
// None announced: nothing to move to, so the want waits for one, as after a withdrawal.
|
|
1109
|
+
if (targetGeneration === undefined) {
|
|
1110
|
+
settle({ kind: 'moved', accepted: accepted() });
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
target = [...target, targetGeneration];
|
|
1114
|
+
}
|
|
1115
|
+
const key = targetKey(target, want.options.track, want.options.parameters);
|
|
1116
|
+
if (key === active.key && on === active.connection) {
|
|
1117
|
+
// Asked for what is active again: a pending move is no longer wanted.
|
|
1118
|
+
clearRetry();
|
|
1119
|
+
moveTarget = undefined;
|
|
1120
|
+
if (pending) {
|
|
1121
|
+
pending.subscription.cancel();
|
|
1122
|
+
pending = undefined;
|
|
1123
|
+
}
|
|
1124
|
+
if (active.ended)
|
|
1125
|
+
settle({ kind: 'retry', accepted: true, progressed: active.progressed, reason: active.ended });
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
if ((pending?.key === key && pending.connection === on) || (retryMove?.key === key && retryMove.connection === on))
|
|
1129
|
+
return;
|
|
1130
|
+
clearRetry();
|
|
1131
|
+
// An unanswered subscription delivers nothing to overlap: replace it at once.
|
|
1132
|
+
if (!accepted()) {
|
|
1133
|
+
settle({ kind: 'moved', accepted: false });
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
if (pending) {
|
|
1137
|
+
pending.subscription.cancel();
|
|
1138
|
+
pending = undefined;
|
|
1139
|
+
}
|
|
1140
|
+
// A new target starts its own backoff; a retry of the same one keeps counting.
|
|
1141
|
+
if (moveTarget !== key)
|
|
1142
|
+
moveFailures = 0;
|
|
1143
|
+
moveTarget = key;
|
|
1144
|
+
try {
|
|
1145
|
+
pending = open(target, targetGeneration, on);
|
|
1146
|
+
}
|
|
1147
|
+
catch (error) {
|
|
1148
|
+
settle(scope.aborted || !refusedForGood(error) ? cancelledOrConnection(true) : { kind: 'fatal', error });
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
try {
|
|
1152
|
+
active = open(namespace, generation, connection);
|
|
1153
|
+
}
|
|
1154
|
+
catch (error) {
|
|
1155
|
+
want.settledTarget = want.target;
|
|
1156
|
+
// An argument the relay can never take is the want's fault; anything else is the connection ending under the call.
|
|
1157
|
+
if (scope.aborted || !refusedForGood(error))
|
|
1158
|
+
return cancelledOrConnection(false);
|
|
1159
|
+
return { kind: 'fatal', error };
|
|
1160
|
+
}
|
|
1161
|
+
/** A rotation replaced the active subscription's connection: move the subscription to the next one. */
|
|
1162
|
+
const rotate = (from) => {
|
|
1163
|
+
if (over())
|
|
1164
|
+
return;
|
|
1165
|
+
// The active subscription's connection, or the one a rotation is already moving to, if that one retires in turn.
|
|
1166
|
+
if (rotationTo ? rotationTo.connection !== from : active.connection !== from)
|
|
1167
|
+
return;
|
|
1168
|
+
const next = nextConnection();
|
|
1169
|
+
if (!next || next === from || next.signal.aborted)
|
|
1170
|
+
return;
|
|
1171
|
+
// Nothing accepted yet to overlap: start over on the new connection at once.
|
|
1172
|
+
if (!accepted()) {
|
|
1173
|
+
settle({ kind: 'moved', accepted: false });
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
holdOn(next);
|
|
1177
|
+
let nextWatch;
|
|
1178
|
+
let release = () => { };
|
|
1179
|
+
if (watch) {
|
|
1180
|
+
try {
|
|
1181
|
+
({ watch: nextWatch, release } = rootWatch(next, want.options.namespace));
|
|
1182
|
+
}
|
|
1183
|
+
catch {
|
|
1184
|
+
// Discovery the new connection refuses cannot follow there: restart on it as after a connection's end.
|
|
1185
|
+
releaseUnused();
|
|
1186
|
+
settle(cancelledOrConnection(accepted()));
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
// Recorded at once, before the new connection's discovery has found the generation: reconcile waits for it, and
|
|
1191
|
+
// the rotation is in flight meanwhile, so the old connection closing or this one retiring in turn keeps continuity.
|
|
1192
|
+
// A rotation to a connection that retired in turn gives way to this one.
|
|
1193
|
+
unwatchNext?.();
|
|
1194
|
+
rotationTo?.release();
|
|
1195
|
+
rotationTo = { connection: next, watch: nextWatch, release };
|
|
1196
|
+
// A move waiting to be retried on a connection being rotated away is the rotation's to make now, on the next one:
|
|
1197
|
+
// left in place, its connection closing would restart the want.
|
|
1198
|
+
if (retryMove && retryMove.connection !== next)
|
|
1199
|
+
clearRetry();
|
|
1200
|
+
unwatchNext = nextWatch?.onChange(reconcile);
|
|
1201
|
+
reconcile();
|
|
1202
|
+
releaseUnused();
|
|
1203
|
+
};
|
|
1204
|
+
let unwatchNext;
|
|
1205
|
+
let stale;
|
|
1206
|
+
const watchStale = () => {
|
|
1207
|
+
clearInterval(stale);
|
|
1208
|
+
const staleAfterMs = want.options.staleAfterMs;
|
|
1209
|
+
if (staleAfterMs === undefined)
|
|
1210
|
+
return;
|
|
1211
|
+
stale = setInterval(() => {
|
|
1212
|
+
if (over() || !accepted() || performance.now() - lastObjectAt < staleAfterMs)
|
|
1213
|
+
return;
|
|
1214
|
+
// During a move only the old subscription went stale: the replacement gets a window of its own.
|
|
1215
|
+
if (pending && !active.ended) {
|
|
1216
|
+
activeEnded('stale');
|
|
1217
|
+
lastObjectAt = performance.now();
|
|
1218
|
+
}
|
|
1219
|
+
else
|
|
1220
|
+
settle({ kind: 'retry', accepted: true, progressed: active.progressed, reason: 'stale' });
|
|
1221
|
+
}, Math.max(10, Math.min(1_000, Math.floor(staleAfterMs / 4))));
|
|
1222
|
+
};
|
|
1223
|
+
const changed = () => {
|
|
1224
|
+
watchStale();
|
|
1225
|
+
reconcile();
|
|
1226
|
+
};
|
|
1227
|
+
const catchUp = () => {
|
|
1228
|
+
if (over() || !accepted())
|
|
1229
|
+
return;
|
|
1230
|
+
settle({ kind: 'retry', accepted: true, progressed: active.progressed, reason: 'catch-up' });
|
|
1231
|
+
};
|
|
1232
|
+
want.catchUp = catchUp;
|
|
1233
|
+
watchStale();
|
|
1234
|
+
want.changes.add(changed);
|
|
1235
|
+
let unwatch = watch?.onChange(reconcile);
|
|
1236
|
+
// A change that landed between choosing the subscription and attaching the listeners is not lost.
|
|
1237
|
+
reconcile();
|
|
1238
|
+
try {
|
|
1239
|
+
await whenAborted(AbortSignal.any([scope, settled.signal]));
|
|
1240
|
+
return outcome ?? cancelledOrConnection(accepted());
|
|
1241
|
+
}
|
|
1242
|
+
finally {
|
|
1243
|
+
// Settles the attempt, so nothing reaches the handlers from here on.
|
|
1244
|
+
settle({ kind: 'cancelled' });
|
|
1245
|
+
if (want.catchUp === catchUp)
|
|
1246
|
+
want.catchUp = undefined;
|
|
1247
|
+
clearInterval(stale);
|
|
1248
|
+
clearRetry();
|
|
1249
|
+
unwatch?.();
|
|
1250
|
+
unwatchNext?.();
|
|
1251
|
+
for (const stop of observed.values())
|
|
1252
|
+
stop();
|
|
1253
|
+
observed.clear();
|
|
1254
|
+
want.changes.delete(changed);
|
|
1255
|
+
for (const slot of [...draining.keys()])
|
|
1256
|
+
stopDrain(slot);
|
|
1257
|
+
pending?.subscription.cancel();
|
|
1258
|
+
active.subscription.cancel();
|
|
1259
|
+
rotationTo?.release();
|
|
1260
|
+
rotationTo = undefined;
|
|
1261
|
+
releaseWatch();
|
|
1262
|
+
for (const release of holds.values())
|
|
1263
|
+
release();
|
|
1264
|
+
holds.clear();
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* What a root's discovery ending means for the want: the connection's end moves it on, the relay ending the request
|
|
1269
|
+
* or a REQUEST_ERROR a wait may fix is retried with backoff on a fresh request, and anything else is surfaced.
|
|
1270
|
+
*/
|
|
1271
|
+
function discoveryFailed(error, scope, cancelledOrConnection, accepted) {
|
|
1272
|
+
if (scope.aborted || error instanceof SubscriptionConnectionClosedError)
|
|
1273
|
+
return cancelledOrConnection(accepted);
|
|
1274
|
+
const retry = { kind: 'retry', accepted, progressed: false, reason: 'generation' };
|
|
1275
|
+
if (error === undefined)
|
|
1276
|
+
return retry;
|
|
1277
|
+
if (error instanceof SubscriptionRequestError && !isPermanentRequestError(error.requestError))
|
|
1278
|
+
return retry;
|
|
1279
|
+
return { kind: 'fatal', error };
|
|
1280
|
+
}
|
|
1281
|
+
/** What a subscription's own ending means for the want. */
|
|
1282
|
+
function classify(end, accepted, progressed, cancelledOrConnection) {
|
|
1283
|
+
switch (end.cause) {
|
|
1284
|
+
case 'connection-closed':
|
|
1285
|
+
case 'cancelled':
|
|
1286
|
+
return cancelledOrConnection(accepted);
|
|
1287
|
+
case 'request-error':
|
|
1288
|
+
if (!end.accepted) {
|
|
1289
|
+
if (isFreshNamespaceRejection(end.error))
|
|
1290
|
+
return { kind: 'retry', accepted: false, progressed: false };
|
|
1291
|
+
if (isPermanentRequestError(end.error)) {
|
|
1292
|
+
return { kind: 'fatal', error: new SubscriptionRequestError(end.error) };
|
|
1293
|
+
}
|
|
1294
|
+
return { kind: 'retry', accepted: false, progressed: false };
|
|
1295
|
+
}
|
|
1296
|
+
return { kind: 'retry', accepted, progressed, reason: 'terminated' };
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
/** Whether two namespace prefixes overlap field by field: equal, or one contains the other. */
|
|
1300
|
+
function overlaps(a, b) {
|
|
1301
|
+
const [shorter, longer] = a.length <= b.length ? [a, b] : [b, a];
|
|
1302
|
+
return shorter.every((field, i) => field === longer[i]);
|
|
1303
|
+
}
|
|
1304
|
+
/** The connection's watch for `root`, opened on first use and closed when its last user releases it. */
|
|
1305
|
+
function rootWatch(connection, root) {
|
|
1306
|
+
const key = JSON.stringify(root);
|
|
1307
|
+
let entry = connection.roots.get(key);
|
|
1308
|
+
if (!entry) {
|
|
1309
|
+
// A watch kept for reuse but unused would hold its prefix and refuse an overlapping root: close it first.
|
|
1310
|
+
for (const [heldKey, held] of connection.roots) {
|
|
1311
|
+
if (held.users === 0 && overlaps(JSON.parse(heldKey), root)) {
|
|
1312
|
+
connection.roots.delete(heldKey);
|
|
1313
|
+
held.close();
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
// An ended discovery leaves the map at once, so the next attempt asks the relay again.
|
|
1317
|
+
const forgetEnded = () => {
|
|
1318
|
+
if (connection.roots.get(key) === entry)
|
|
1319
|
+
connection.roots.delete(key);
|
|
1320
|
+
};
|
|
1321
|
+
entry = Object.assign(openRootWatch(connection.subscriber, root, forgetEnded), { users: 0 });
|
|
1322
|
+
connection.roots.set(key, entry);
|
|
1323
|
+
}
|
|
1324
|
+
const watch = entry;
|
|
1325
|
+
watch.users += 1;
|
|
1326
|
+
let released = false;
|
|
1327
|
+
return {
|
|
1328
|
+
watch,
|
|
1329
|
+
release() {
|
|
1330
|
+
if (released)
|
|
1331
|
+
return;
|
|
1332
|
+
released = true;
|
|
1333
|
+
watch.users -= 1;
|
|
1334
|
+
if (watch.users === 0) {
|
|
1335
|
+
// Kept a moment so a want that resubscribes at once reuses the snapshot instead of asking again.
|
|
1336
|
+
setTimeout(() => {
|
|
1337
|
+
if (watch.users === 0 && connection.roots.get(key) === watch) {
|
|
1338
|
+
connection.roots.delete(key);
|
|
1339
|
+
watch.close();
|
|
1340
|
+
}
|
|
1341
|
+
}, 5_000);
|
|
1342
|
+
}
|
|
1343
|
+
},
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
function openRootWatch(subscriber, root, onEnd) {
|
|
1347
|
+
const generations = new Set();
|
|
1348
|
+
const listeners = new Set();
|
|
1349
|
+
let failure;
|
|
1350
|
+
// Throws PREFIX_OVERLAP synchronously when another followed root overlaps this one.
|
|
1351
|
+
const events = subscriber.namespaceEvents({ prefix: root });
|
|
1352
|
+
const notify = () => {
|
|
1353
|
+
for (const listener of [...listeners])
|
|
1354
|
+
listener();
|
|
1355
|
+
};
|
|
1356
|
+
void (async () => {
|
|
1357
|
+
try {
|
|
1358
|
+
for await (const event of events) {
|
|
1359
|
+
// Only one field below the root is a generation; anything deeper belongs to someone else.
|
|
1360
|
+
if (event.namespace.length !== root.length + 1)
|
|
1361
|
+
continue;
|
|
1362
|
+
const generation = event.namespace[root.length];
|
|
1363
|
+
if (event.type === 'announced')
|
|
1364
|
+
generations.add(generation);
|
|
1365
|
+
else
|
|
1366
|
+
generations.delete(generation);
|
|
1367
|
+
notify();
|
|
1368
|
+
}
|
|
1369
|
+
// The relay ended the request, or the watch was closed: neither is a failure of the want.
|
|
1370
|
+
failure = { error: undefined };
|
|
1371
|
+
}
|
|
1372
|
+
catch (error) {
|
|
1373
|
+
failure = { error };
|
|
1374
|
+
}
|
|
1375
|
+
onEnd();
|
|
1376
|
+
notify();
|
|
1377
|
+
})();
|
|
1378
|
+
const current = () => {
|
|
1379
|
+
let newest;
|
|
1380
|
+
for (const generation of generations)
|
|
1381
|
+
if (newest === undefined || generation > newest)
|
|
1382
|
+
newest = generation;
|
|
1383
|
+
return newest;
|
|
1384
|
+
};
|
|
1385
|
+
return {
|
|
1386
|
+
current,
|
|
1387
|
+
failure: () => failure,
|
|
1388
|
+
async newest(scope) {
|
|
1389
|
+
for (;;) {
|
|
1390
|
+
if (failure)
|
|
1391
|
+
return { kind: 'failed', error: failure.error };
|
|
1392
|
+
const found = current();
|
|
1393
|
+
if (found !== undefined)
|
|
1394
|
+
return { kind: 'found', generation: found };
|
|
1395
|
+
if (scope.aborted)
|
|
1396
|
+
return { kind: 'aborted' };
|
|
1397
|
+
await new Promise((resolve) => {
|
|
1398
|
+
const remove = () => {
|
|
1399
|
+
listeners.delete(wake);
|
|
1400
|
+
scope.removeEventListener('abort', wake);
|
|
1401
|
+
};
|
|
1402
|
+
const wake = () => {
|
|
1403
|
+
remove();
|
|
1404
|
+
resolve();
|
|
1405
|
+
};
|
|
1406
|
+
listeners.add(wake);
|
|
1407
|
+
scope.addEventListener('abort', wake, { once: true });
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
},
|
|
1411
|
+
onChange(listener) {
|
|
1412
|
+
listeners.add(listener);
|
|
1413
|
+
return () => listeners.delete(listener);
|
|
1414
|
+
},
|
|
1415
|
+
close() {
|
|
1416
|
+
void events.return();
|
|
1417
|
+
},
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
//# sourceMappingURL=supervised-subscriber.js.map
|