@syncular/client 0.65.1 → 0.65.2
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 +9 -5
- package/dist/realtime-supervisor.d.ts +47 -13
- package/dist/realtime-supervisor.js +374 -277
- package/package.json +3 -3
- package/src/realtime-supervisor.ts +408 -303
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
ClientDiagnosticsListener,
|
|
5
5
|
ClientDiagnosticsSnapshot,
|
|
6
6
|
} from './diagnostics';
|
|
7
|
+
import { ClientSyncError } from './errors';
|
|
7
8
|
|
|
8
9
|
type CancelTimer = () => void;
|
|
9
10
|
|
|
@@ -45,14 +46,23 @@ export interface RealtimeSupervisorSnapshot {
|
|
|
45
46
|
readonly attempt: number;
|
|
46
47
|
/** Bounded host-policy delay, never server or transport prose. */
|
|
47
48
|
readonly retryDelayMs?: number;
|
|
49
|
+
/** The latched failure of phase `unsupported` (or `stopped`). */
|
|
50
|
+
readonly failureCode?: RealtimeSupervisorFailureCode;
|
|
48
51
|
}
|
|
49
52
|
|
|
53
|
+
/** SPEC §10.3: client-local supervisor failures, never on the wire. */
|
|
54
|
+
export type RealtimeSupervisorFailureCode =
|
|
55
|
+
| 'realtime.diagnostics_unavailable'
|
|
56
|
+
| 'realtime.disconnect_failed'
|
|
57
|
+
| 'realtime.cleanup_failed';
|
|
58
|
+
|
|
50
59
|
export interface RealtimeSupervisorOptions {
|
|
51
60
|
/**
|
|
52
61
|
* Host online/offline evidence, the only connectivity the supervisor
|
|
53
62
|
* trusts: a failed round does not suspend it. Unknown remains connectable
|
|
54
|
-
* and observable. Each `online` report drives `syncUntilIdle
|
|
55
|
-
* failed round left behind resumes without
|
|
63
|
+
* and observable. Each `online` report drives `syncUntilIdle` while no
|
|
64
|
+
* socket is connected, so work a failed round left behind resumes without
|
|
65
|
+
* realtime.
|
|
56
66
|
*/
|
|
57
67
|
readonly connectivity?: RealtimeSupervisorSignal<ClientDiagnosticsConnectivity>;
|
|
58
68
|
/** Browser/native foreground evidence. Background suspends a tab-owned
|
|
@@ -92,6 +102,8 @@ export interface DocumentLifecycleSignalOptions {
|
|
|
92
102
|
}
|
|
93
103
|
|
|
94
104
|
const REALTIME_SUPERVISOR_KEY = Symbol.for('syncular.realtime-supervisor.v1');
|
|
105
|
+
const CLEANUP_FAILED = 'realtime.cleanup_failed';
|
|
106
|
+
const DIAGNOSTICS_UNAVAILABLE = 'realtime.diagnostics_unavailable';
|
|
95
107
|
const DEFAULT_INITIAL_DELAY_MS = 1_000;
|
|
96
108
|
const DEFAULT_MAXIMUM_DELAY_MS = 30_000;
|
|
97
109
|
const MAXIMUM_CONFIGURED_DELAY_MS = 300_000;
|
|
@@ -210,13 +222,71 @@ export function documentLifecycleSignal(
|
|
|
210
222
|
};
|
|
211
223
|
}
|
|
212
224
|
|
|
225
|
+
/** A Syncular code (§10.3 families) on an own data property, else `unknown`. */
|
|
226
|
+
function causeCode(error: unknown): string {
|
|
227
|
+
try {
|
|
228
|
+
const value =
|
|
229
|
+
typeof error === 'object' && error !== null
|
|
230
|
+
? Object.getOwnPropertyDescriptor(error, 'code')?.value
|
|
231
|
+
: undefined;
|
|
232
|
+
return typeof value === 'string' &&
|
|
233
|
+
/^(?:sync|client|transport|realtime)\.[a-z0-9_]+$/.test(value)
|
|
234
|
+
? value
|
|
235
|
+
: 'unknown';
|
|
236
|
+
} catch {
|
|
237
|
+
// A hostile value (a throwing proxy) carries no code.
|
|
238
|
+
return 'unknown';
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** SPEC §8.4: a stable-coded error the client marked `retryable`, read without getters. */
|
|
243
|
+
function retryable(error: unknown): boolean {
|
|
244
|
+
try {
|
|
245
|
+
return (
|
|
246
|
+
causeCode(error) !== 'unknown' &&
|
|
247
|
+
Object.getOwnPropertyDescriptor(error, 'retryable')?.value === true
|
|
248
|
+
);
|
|
249
|
+
} catch {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* SPEC §8.4: a supervisor failure. `code` is the latest latched failure, or
|
|
256
|
+
* `realtime.cleanup_failed` when only a cancel threw. Every failure of the
|
|
257
|
+
* lifetime is also named in its own field. Cause codes are Syncular codes or
|
|
258
|
+
* `unknown`; no message or original error is retained.
|
|
259
|
+
*/
|
|
260
|
+
export class RealtimeSupervisorError extends ClientSyncError {
|
|
261
|
+
override readonly name = 'RealtimeSupervisorError';
|
|
262
|
+
declare readonly code: RealtimeSupervisorFailureCode;
|
|
263
|
+
declare readonly cleanupFailureCode?: 'realtime.cleanup_failed';
|
|
264
|
+
declare readonly diagnosticsFailureCode?: 'realtime.diagnostics_unavailable';
|
|
265
|
+
/** The code the client's `disconnectRealtime` rejected with. */
|
|
266
|
+
declare readonly disconnectCauseCode?: string;
|
|
267
|
+
/** Set by the installed `close()` when the client close failed as well. */
|
|
268
|
+
declare readonly stopFailureCode?: RealtimeSupervisorFailureCode;
|
|
269
|
+
declare readonly closeFailureCode?: string;
|
|
270
|
+
|
|
271
|
+
constructor(
|
|
272
|
+
code: RealtimeSupervisorFailureCode,
|
|
273
|
+
fields: Omit<Partial<RealtimeSupervisorError>, 'code'> = {},
|
|
274
|
+
) {
|
|
275
|
+
super(code, code);
|
|
276
|
+
Object.assign(this, fields);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
213
280
|
/**
|
|
214
|
-
* Supported host policy for Syncular's explicit realtime transport. It
|
|
215
|
-
*
|
|
216
|
-
* connected
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
281
|
+
* Supported host policy for Syncular's explicit realtime transport (§8.4). It
|
|
282
|
+
* owns one attempt at a time: a connect, then an explicit catch-up round
|
|
283
|
+
* before it claims connected. A successor never starts before the previous
|
|
284
|
+
* attempt and its disconnect settle. Transient loss retries with bounded
|
|
285
|
+
* exponential jitter, and the backoff survives offline, background and
|
|
286
|
+
* protected suspensions. While no socket is connected, each failed connect,
|
|
287
|
+
* each host `online` report and each foreground return drives one HTTP round
|
|
288
|
+
* (§1.8). A disconnect, diagnostics or cleanup failure latches phase
|
|
289
|
+
* `unsupported` with its `failureCode`, and `stop()` rejects with it.
|
|
220
290
|
*/
|
|
221
291
|
export class RealtimeSupervisor {
|
|
222
292
|
readonly #client: RealtimeSupervisorClient;
|
|
@@ -229,25 +299,40 @@ export class RealtimeSupervisor {
|
|
|
229
299
|
readonly #initialDelayMs: number;
|
|
230
300
|
readonly #maximumDelayMs: number;
|
|
231
301
|
readonly #listeners = new Set<() => void>();
|
|
302
|
+
readonly #unsubscribers: (() => void)[] = [];
|
|
232
303
|
|
|
233
304
|
#started = false;
|
|
234
305
|
#initialized = false;
|
|
235
306
|
#stopped = false;
|
|
236
|
-
#
|
|
237
|
-
#
|
|
238
|
-
#connecting = false;
|
|
239
|
-
#realtimeSupported = true;
|
|
307
|
+
#stopping: Promise<void> | undefined;
|
|
308
|
+
#supported = true;
|
|
240
309
|
/** The client refused a connect with `sync.offline`: its transport gate is closed. */
|
|
241
310
|
#gateClosed = false;
|
|
242
311
|
#diagnosticSecurity: RealtimeSupervisorProtectionState = 'unknown';
|
|
312
|
+
#diagnosticRevision = 0;
|
|
313
|
+
/** A socket is open, whether this supervisor or the host opened it. */
|
|
314
|
+
#transport = false;
|
|
315
|
+
/** The open socket completed its catch-up round. */
|
|
316
|
+
#connected = false;
|
|
243
317
|
#attempt = 0;
|
|
318
|
+
/** The delay of the counted retry; zero schedules an immediate attempt. */
|
|
319
|
+
#delayMs = 0;
|
|
320
|
+
/** Bumped by every suspension, failure and stop; a stale attempt only cleans up. */
|
|
244
321
|
#generation = 0;
|
|
322
|
+
#disconnectedGeneration = -1;
|
|
323
|
+
#cancelTimer: CancelTimer | undefined;
|
|
324
|
+
#attemptJob: Promise<void> | undefined;
|
|
325
|
+
#disconnecting: Promise<void> | undefined;
|
|
326
|
+
#round: Promise<void> | undefined;
|
|
327
|
+
#roundAgain = false;
|
|
328
|
+
#failure: RealtimeSupervisorFailureCode | undefined;
|
|
329
|
+
/** Every failure of the lifetime, named for the stop rejection. */
|
|
330
|
+
readonly #failures: {
|
|
331
|
+
cleanupFailureCode?: 'realtime.cleanup_failed';
|
|
332
|
+
diagnosticsFailureCode?: 'realtime.diagnostics_unavailable';
|
|
333
|
+
disconnectCauseCode?: string;
|
|
334
|
+
} = {};
|
|
245
335
|
#snapshot: RealtimeSupervisorSnapshot = { phase: 'idle', attempt: 0 };
|
|
246
|
-
#cancelRetry: CancelTimer | undefined;
|
|
247
|
-
#unsubscribeDiagnostics: (() => void) | undefined;
|
|
248
|
-
#unsubscribeConnectivity: (() => void) | undefined;
|
|
249
|
-
#unsubscribeLifecycle: (() => void) | undefined;
|
|
250
|
-
#unsubscribeProtection: (() => void) | undefined;
|
|
251
336
|
|
|
252
337
|
constructor(
|
|
253
338
|
client: RealtimeSupervisorClient,
|
|
@@ -282,59 +367,82 @@ export class RealtimeSupervisor {
|
|
|
282
367
|
start(): void {
|
|
283
368
|
if (this.#started || this.#stopped) return;
|
|
284
369
|
this.#started = true;
|
|
285
|
-
this.#
|
|
286
|
-
this.#
|
|
370
|
+
this.#unsubscribers.push(
|
|
371
|
+
this.#client.onDiagnostics((snapshot) => {
|
|
372
|
+
this.#diagnosticRevision += 1;
|
|
373
|
+
this.#observe(snapshot);
|
|
374
|
+
}),
|
|
287
375
|
);
|
|
288
|
-
|
|
376
|
+
const connectivity = this.#connectivity?.subscribe((state) => {
|
|
377
|
+
this.#reconcile();
|
|
289
378
|
if (state === 'online') this.#drive();
|
|
290
|
-
this.#reconcileHostState();
|
|
291
379
|
});
|
|
292
|
-
|
|
293
|
-
this.#
|
|
294
|
-
|
|
295
|
-
// absent socket does not.
|
|
296
|
-
const phase = this.#snapshot.phase;
|
|
297
|
-
if (
|
|
298
|
-
state === 'active' &&
|
|
299
|
-
(phase === 'retrying' || phase === 'unsupported')
|
|
300
|
-
) {
|
|
301
|
-
this.#drive();
|
|
302
|
-
}
|
|
380
|
+
const lifecycle = this.#lifecycle?.subscribe((state) => {
|
|
381
|
+
this.#reconcile();
|
|
382
|
+
if (state === 'active') this.#drive();
|
|
303
383
|
});
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
384
|
+
const protection = this.#protection?.subscribe(() => this.#reconcile());
|
|
385
|
+
for (const unsubscribe of [connectivity, lifecycle, protection]) {
|
|
386
|
+
if (unsubscribe) this.#unsubscribers.push(unsubscribe);
|
|
387
|
+
}
|
|
388
|
+
this.#reconcile();
|
|
389
|
+
const revision = this.#diagnosticRevision;
|
|
390
|
+
void Promise.resolve()
|
|
391
|
+
.then(() => this.#client.diagnosticsSnapshot())
|
|
392
|
+
.then((snapshot) => {
|
|
393
|
+
if (this.#stopped) return;
|
|
394
|
+
// Initialization belongs to the lifetime; host flaps cannot void it.
|
|
395
|
+
this.#initialized = true;
|
|
396
|
+
// A live report that arrived meanwhile is newer than this read.
|
|
397
|
+
if (revision === this.#diagnosticRevision) {
|
|
398
|
+
this.#observe(snapshot, true);
|
|
399
|
+
}
|
|
400
|
+
this.#reconcile();
|
|
401
|
+
})
|
|
402
|
+
.catch((error: unknown) => {
|
|
403
|
+
if (this.#stopped) return;
|
|
404
|
+
if (!retryable(error)) return this.#fail(DIAGNOSTICS_UNAVAILABLE);
|
|
405
|
+
// A leader handover or follower timeout: start on the retry schedule
|
|
406
|
+
// and let the live reports and the connect result stand in.
|
|
407
|
+
this.#initialized = true;
|
|
408
|
+
this.#retry();
|
|
409
|
+
this.#reconcile();
|
|
410
|
+
});
|
|
310
411
|
}
|
|
311
412
|
|
|
312
|
-
|
|
313
|
-
|
|
413
|
+
/**
|
|
414
|
+
* Cancel the timer and every subscription, release the socket, and settle
|
|
415
|
+
* once the in-flight attempt, its disconnect and any driven round have
|
|
416
|
+
* settled. Rejects with a {@link RealtimeSupervisorError} when a failure
|
|
417
|
+
* latched during the lifetime or a cancel threw; every caller shares it.
|
|
418
|
+
*/
|
|
419
|
+
stop(): Promise<void> {
|
|
420
|
+
if (this.#stopping) return this.#stopping;
|
|
421
|
+
this.#stopping = Promise.resolve().then(async () => {
|
|
422
|
+
await this.#disconnecting;
|
|
423
|
+
await this.#attemptJob;
|
|
424
|
+
await this.#round;
|
|
425
|
+
this.#listeners.clear();
|
|
426
|
+
if (this.#failure) {
|
|
427
|
+
throw new RealtimeSupervisorError(this.#failure, this.#failures);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
314
430
|
this.#stopped = true;
|
|
315
|
-
this.#
|
|
316
|
-
this.#
|
|
317
|
-
this.#
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
async #initialize(generation: number): Promise<void> {
|
|
324
|
-
let snapshot: ClientDiagnosticsSnapshot | undefined;
|
|
325
|
-
try {
|
|
326
|
-
snapshot = await this.#client.diagnosticsSnapshot();
|
|
327
|
-
} catch {
|
|
328
|
-
// Protected or temporarily unavailable diagnostics must not become a
|
|
329
|
-
// startup dependency. Explicit host gates and the connect result remain.
|
|
431
|
+
this.#generation += 1;
|
|
432
|
+
this.#clearTimer();
|
|
433
|
+
for (const unsubscribe of this.#unsubscribers.splice(0)) {
|
|
434
|
+
try {
|
|
435
|
+
unsubscribe();
|
|
436
|
+
} catch {
|
|
437
|
+
this.#cleanupFailed();
|
|
438
|
+
}
|
|
330
439
|
}
|
|
331
|
-
|
|
332
|
-
this.#
|
|
333
|
-
|
|
334
|
-
this.#reconcileHostState();
|
|
440
|
+
this.#publish({ phase: 'stopped', attempt: 0 });
|
|
441
|
+
void this.#disconnect();
|
|
442
|
+
return this.#stopping;
|
|
335
443
|
}
|
|
336
444
|
|
|
337
|
-
#
|
|
445
|
+
#block(): RealtimeSuspendedPhase | undefined {
|
|
338
446
|
const protection = this.#protection?.current();
|
|
339
447
|
if (
|
|
340
448
|
this.#diagnosticSecurity === 'preflight' ||
|
|
@@ -355,34 +463,32 @@ export class RealtimeSupervisor {
|
|
|
355
463
|
}
|
|
356
464
|
|
|
357
465
|
/**
|
|
358
|
-
* §1.8: one HTTP round
|
|
359
|
-
*
|
|
360
|
-
*
|
|
466
|
+
* §1.8: one HTTP round while no socket carries the rounds. A request during
|
|
467
|
+
* a round adds one round after it. The round's failure is the client's
|
|
468
|
+
* round failure, which its progress and status already report.
|
|
361
469
|
*/
|
|
362
470
|
#drive(): void {
|
|
363
|
-
if (this.#
|
|
364
|
-
|
|
471
|
+
if (this.#stopped || this.#connected || this.#block()) return;
|
|
472
|
+
if (this.#round) {
|
|
473
|
+
this.#roundAgain = true;
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
this.#round = Promise.resolve()
|
|
365
477
|
.then(() => this.#client.syncUntilIdle())
|
|
366
|
-
.
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
478
|
+
.then(
|
|
479
|
+
() => undefined,
|
|
480
|
+
() => undefined,
|
|
481
|
+
)
|
|
482
|
+
.finally(() => {
|
|
483
|
+
this.#round = undefined;
|
|
484
|
+
if (!this.#roundAgain) return;
|
|
485
|
+
this.#roundAgain = false;
|
|
486
|
+
this.#drive();
|
|
487
|
+
});
|
|
376
488
|
}
|
|
377
489
|
|
|
378
490
|
#publish(snapshot: RealtimeSupervisorSnapshot): void {
|
|
379
|
-
if (
|
|
380
|
-
this.#snapshot.phase === snapshot.phase &&
|
|
381
|
-
this.#snapshot.attempt === snapshot.attempt &&
|
|
382
|
-
this.#snapshot.retryDelayMs === snapshot.retryDelayMs
|
|
383
|
-
) {
|
|
384
|
-
return;
|
|
385
|
-
}
|
|
491
|
+
if (JSON.stringify(this.#snapshot) === JSON.stringify(snapshot)) return;
|
|
386
492
|
this.#snapshot = Object.freeze(snapshot);
|
|
387
493
|
for (const listener of this.#listeners) {
|
|
388
494
|
try {
|
|
@@ -393,282 +499,281 @@ export class RealtimeSupervisor {
|
|
|
393
499
|
}
|
|
394
500
|
}
|
|
395
501
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
this.#
|
|
502
|
+
/** A cancel threw: name it, and latch it unless a failure already did. */
|
|
503
|
+
#cleanupFailed(): void {
|
|
504
|
+
this.#failures.cleanupFailureCode = CLEANUP_FAILED;
|
|
505
|
+
if (!this.#failure) this.#fail(CLEANUP_FAILED);
|
|
399
506
|
}
|
|
400
507
|
|
|
401
|
-
/**
|
|
402
|
-
#
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
this.#maximumDelayMs,
|
|
412
|
-
this.#initialDelayMs * 2 ** this.#attempt,
|
|
413
|
-
);
|
|
414
|
-
const random = this.#random();
|
|
415
|
-
const boundedRandom = Number.isFinite(random)
|
|
416
|
-
? Math.max(0, Math.min(1, random))
|
|
417
|
-
: 0;
|
|
418
|
-
delayMs = Math.min(
|
|
419
|
-
this.#maximumDelayMs,
|
|
420
|
-
exponential + Math.floor(exponential * 0.25 * boundedRandom),
|
|
421
|
-
);
|
|
422
|
-
this.#attempt = Math.min(32, this.#attempt + 1);
|
|
508
|
+
/** False when the host's cancel threw; the timer may still fire. */
|
|
509
|
+
#clearTimer(): boolean {
|
|
510
|
+
const cancel = this.#cancelTimer;
|
|
511
|
+
this.#cancelTimer = undefined;
|
|
512
|
+
try {
|
|
513
|
+
cancel?.();
|
|
514
|
+
return true;
|
|
515
|
+
} catch {
|
|
516
|
+
this.#cleanupFailed();
|
|
517
|
+
return false;
|
|
423
518
|
}
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Count one failed attempt and back off with bounded jitter, once per retry. */
|
|
522
|
+
#retry(): void {
|
|
523
|
+
if (this.#delayMs > 0) return;
|
|
524
|
+
const exponential = Math.min(
|
|
525
|
+
this.#maximumDelayMs,
|
|
526
|
+
this.#initialDelayMs * 2 ** this.#attempt,
|
|
428
527
|
);
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
528
|
+
const random = this.#random();
|
|
529
|
+
const boundedRandom = Number.isFinite(random)
|
|
530
|
+
? Math.max(0, Math.min(1, random))
|
|
531
|
+
: 0;
|
|
532
|
+
this.#delayMs = Math.min(
|
|
533
|
+
this.#maximumDelayMs,
|
|
534
|
+
exponential + Math.floor(exponential * 0.25 * boundedRandom),
|
|
535
|
+
);
|
|
536
|
+
this.#attempt = Math.min(32, this.#attempt + 1);
|
|
433
537
|
}
|
|
434
538
|
|
|
435
|
-
/**
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
* With the supervisor otherwise quiescent (suspended or stopped), the
|
|
440
|
-
* socket this attempt opened is unwanted — release it.
|
|
441
|
-
*/
|
|
442
|
-
#releaseSupersededSocket(): void {
|
|
443
|
-
if (this.#connecting || this.#connected || this.#transportConnected) {
|
|
444
|
-
return;
|
|
539
|
+
/** Latch a failure: no further attempt, and the socket is released. */
|
|
540
|
+
#fail(code: RealtimeSupervisorFailureCode): void {
|
|
541
|
+
if (code === DIAGNOSTICS_UNAVAILABLE) {
|
|
542
|
+
this.#failures.diagnosticsFailureCode = code;
|
|
445
543
|
}
|
|
446
|
-
this.#
|
|
544
|
+
this.#failure = code;
|
|
545
|
+
this.#generation += 1;
|
|
546
|
+
this.#connected = false;
|
|
547
|
+
this.#clearTimer();
|
|
548
|
+
this.#publish({
|
|
549
|
+
phase: this.#stopped ? 'stopped' : 'unsupported',
|
|
550
|
+
attempt: this.#attempt,
|
|
551
|
+
failureCode: code,
|
|
552
|
+
});
|
|
553
|
+
void this.#disconnect();
|
|
447
554
|
}
|
|
448
555
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
this.#
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
this.#transportConnected = true;
|
|
462
|
-
if (!this.#canConnect()) {
|
|
463
|
-
this.#transportConnected = false;
|
|
464
|
-
this.#disconnect();
|
|
465
|
-
return;
|
|
466
|
-
}
|
|
467
|
-
await this.#catchUpConnectedTransport(generation);
|
|
468
|
-
} catch (error) {
|
|
469
|
-
if (generation !== this.#generation) {
|
|
470
|
-
this.#releaseSupersededSocket();
|
|
471
|
-
return;
|
|
556
|
+
/** Converge timer, attempt and socket on the current host evidence. */
|
|
557
|
+
#reconcile(): void {
|
|
558
|
+
if (this.#stopped || this.#failure) return;
|
|
559
|
+
const block = this.#block();
|
|
560
|
+
if (block) {
|
|
561
|
+
if (this.#snapshot.phase !== block) {
|
|
562
|
+
this.#generation += 1;
|
|
563
|
+
// An interrupted attempt counts, so flaps keep the backoff. A gate
|
|
564
|
+
// refusal is the attempt's own result, not an interruption.
|
|
565
|
+
if (this.#attemptJob && !this.#connected && !this.#gateClosed) {
|
|
566
|
+
this.#retry();
|
|
567
|
+
}
|
|
472
568
|
}
|
|
473
|
-
this.#
|
|
474
|
-
error instanceof Error &&
|
|
475
|
-
'code' in error &&
|
|
476
|
-
error.code === 'sync.offline';
|
|
477
|
-
failed = true;
|
|
569
|
+
if (!this.#clearTimer()) return;
|
|
478
570
|
this.#connected = false;
|
|
479
|
-
this.#
|
|
480
|
-
this.#disconnect();
|
|
481
|
-
|
|
482
|
-
// A superseded attempt leaves the successor's in-flight state alone.
|
|
483
|
-
if (generation === this.#generation) this.#connecting = false;
|
|
571
|
+
this.#publish({ phase: block, attempt: this.#attempt });
|
|
572
|
+
void this.#disconnect();
|
|
573
|
+
return;
|
|
484
574
|
}
|
|
485
|
-
if (
|
|
486
|
-
this.#
|
|
487
|
-
this.#drive();
|
|
575
|
+
if (!this.#supported) {
|
|
576
|
+
return this.#publish({ phase: 'unsupported', attempt: 0 });
|
|
488
577
|
}
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
async #catchUpConnectedTransport(generation: number): Promise<void> {
|
|
492
|
-
await this.#client.syncUntilIdle();
|
|
493
|
-
if (generation !== this.#generation) {
|
|
494
|
-
this.#releaseSupersededSocket();
|
|
495
|
-
return;
|
|
578
|
+
if (!this.#initialized) {
|
|
579
|
+
return this.#publish({ phase: 'idle', attempt: this.#attempt });
|
|
496
580
|
}
|
|
497
|
-
if (
|
|
498
|
-
this.#
|
|
499
|
-
|
|
581
|
+
if (this.#connected) {
|
|
582
|
+
return this.#publish({ phase: 'connected', attempt: 0 });
|
|
583
|
+
}
|
|
584
|
+
if (this.#attemptJob || this.#disconnecting) return;
|
|
585
|
+
if (this.#transport) {
|
|
586
|
+
// A socket the host opened is adopted after the same catch-up round.
|
|
587
|
+
if (!this.#clearTimer()) return;
|
|
588
|
+
return this.#run();
|
|
500
589
|
}
|
|
501
|
-
this.#
|
|
502
|
-
this.#
|
|
503
|
-
|
|
590
|
+
if (this.#cancelTimer) return;
|
|
591
|
+
this.#publish(
|
|
592
|
+
this.#delayMs > 0
|
|
593
|
+
? {
|
|
594
|
+
phase: 'retrying',
|
|
595
|
+
attempt: this.#attempt,
|
|
596
|
+
retryDelayMs: this.#delayMs,
|
|
597
|
+
}
|
|
598
|
+
: { phase: 'connecting', attempt: this.#attempt },
|
|
599
|
+
);
|
|
600
|
+
this.#cancelTimer = this.#scheduleTimer(() => {
|
|
601
|
+
this.#cancelTimer = undefined;
|
|
602
|
+
if (this.#stopped || this.#failure || this.#attemptJob || this.#block()) {
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
this.#run();
|
|
606
|
+
}, this.#delayMs);
|
|
504
607
|
}
|
|
505
608
|
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
return;
|
|
509
|
-
}
|
|
609
|
+
/** Start the one attempt; it opens a microtask later, so a flap can void it. */
|
|
610
|
+
#run(): void {
|
|
510
611
|
const generation = this.#generation;
|
|
511
|
-
this.#
|
|
512
|
-
this.#
|
|
513
|
-
|
|
514
|
-
|
|
612
|
+
this.#delayMs = 0;
|
|
613
|
+
this.#attemptJob = Promise.resolve().then(() => this.#connect(generation));
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
async #connect(generation: number): Promise<void> {
|
|
515
617
|
try {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
618
|
+
if (generation !== this.#generation) return;
|
|
619
|
+
this.#publish({ phase: 'connecting', attempt: this.#attempt });
|
|
620
|
+
let caughtUp = false;
|
|
621
|
+
try {
|
|
622
|
+
if (!this.#transport) {
|
|
623
|
+
await new Promise<void>((resolve) =>
|
|
624
|
+
resolve(this.#client.connectRealtime()),
|
|
625
|
+
).catch((error: unknown) => {
|
|
626
|
+
if (causeCode(error) === 'sync.offline') this.#gateClosed = true;
|
|
627
|
+
// §1.8: a refused socket still brings one round over HTTP.
|
|
628
|
+
else this.#drive();
|
|
629
|
+
throw error;
|
|
630
|
+
});
|
|
631
|
+
this.#transport = true;
|
|
632
|
+
}
|
|
633
|
+
if (generation === this.#generation) await this.#client.syncUntilIdle();
|
|
634
|
+
caughtUp = generation === this.#generation && this.#transport;
|
|
635
|
+
} catch {
|
|
636
|
+
// A refused socket or a failed catch-up round fails the attempt.
|
|
637
|
+
}
|
|
638
|
+
if (caughtUp) {
|
|
639
|
+
this.#connected = true;
|
|
640
|
+
this.#attempt = 0;
|
|
641
|
+
this.#delayMs = 0;
|
|
642
|
+
this.#publish({ phase: 'connected', attempt: 0 });
|
|
520
643
|
return;
|
|
521
644
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
this.#
|
|
525
|
-
this.#disconnect();
|
|
645
|
+
if (generation === this.#generation && !this.#gateClosed) this.#retry();
|
|
646
|
+
// A stale attempt releases the late socket before a successor may open.
|
|
647
|
+
await this.#disconnect();
|
|
526
648
|
} finally {
|
|
527
|
-
//
|
|
528
|
-
|
|
649
|
+
// Settled in the same turn, so a report right after `connected`
|
|
650
|
+
// meets no attempt in flight.
|
|
651
|
+
this.#attemptJob = undefined;
|
|
652
|
+
this.#reconcile();
|
|
529
653
|
}
|
|
530
|
-
if (failed && generation === this.#generation) this.#schedule(true);
|
|
531
654
|
}
|
|
532
655
|
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
656
|
+
/**
|
|
657
|
+
* Release the socket, or void an attempt in flight, once per generation.
|
|
658
|
+
* `#disconnecting` is set before the call, so diagnostics the call emits
|
|
659
|
+
* synchronously see the teardown and schedule no retry.
|
|
660
|
+
*/
|
|
661
|
+
#disconnect(): Promise<void> {
|
|
662
|
+
if (this.#disconnecting) return this.#disconnecting;
|
|
539
663
|
if (
|
|
540
|
-
|
|
541
|
-
|
|
664
|
+
!this.#transport &&
|
|
665
|
+
(!this.#attemptJob || this.#disconnectedGeneration === this.#generation)
|
|
542
666
|
) {
|
|
543
|
-
|
|
544
|
-
this.#suspend('unsupported');
|
|
545
|
-
return;
|
|
546
|
-
}
|
|
547
|
-
if (!this.#realtimeSupported) {
|
|
548
|
-
// A live socket is positive evidence the earlier 'unsupported' report
|
|
549
|
-
// was transient (a mid-restart or mis-detected capability probe), so it
|
|
550
|
-
// recovers the supervisor. Every other report keeps the latch closed.
|
|
551
|
-
if (snapshot.host.realtime !== 'connected') return;
|
|
552
|
-
this.#realtimeSupported = true;
|
|
667
|
+
return Promise.resolve();
|
|
553
668
|
}
|
|
669
|
+
this.#disconnectedGeneration = this.#generation;
|
|
670
|
+
this.#transport = false;
|
|
671
|
+
this.#connected = false;
|
|
672
|
+
this.#disconnecting = Promise.resolve();
|
|
673
|
+
this.#disconnecting = new Promise<void>((resolve) =>
|
|
674
|
+
resolve(this.#client.disconnectRealtime()),
|
|
675
|
+
)
|
|
676
|
+
.catch((error: unknown) => {
|
|
677
|
+
if (retryable(error)) return this.#retry();
|
|
678
|
+
this.#failures.disconnectCauseCode = causeCode(error);
|
|
679
|
+
this.#fail('realtime.disconnect_failed');
|
|
680
|
+
})
|
|
681
|
+
.finally(() => {
|
|
682
|
+
this.#disconnecting = undefined;
|
|
683
|
+
this.#reconcile();
|
|
684
|
+
});
|
|
685
|
+
return this.#disconnecting;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
#observe(snapshot: ClientDiagnosticsSnapshot, initial = false): void {
|
|
689
|
+
if (this.#stopped) return;
|
|
690
|
+
this.#diagnosticSecurity = snapshot.securityLifecycle;
|
|
691
|
+
// A closed transport gate always reports offline, so any other report
|
|
692
|
+
// means the app reopened it.
|
|
554
693
|
if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
|
|
555
|
-
// A closed transport gate always reports offline, so any other report
|
|
556
|
-
// means the app reopened it.
|
|
557
694
|
this.#gateClosed = false;
|
|
558
|
-
this.#reconcileHostState();
|
|
559
|
-
return;
|
|
560
695
|
}
|
|
561
|
-
const
|
|
562
|
-
if (
|
|
563
|
-
this.#
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
if (snapshot.host.realtime === 'connected') {
|
|
567
|
-
this.#transportConnected = true;
|
|
568
|
-
// Steady state: diagnostics re-announce 'connected' on every sync
|
|
569
|
-
// round and subscription change. An already-adopted transport keeps
|
|
570
|
-
// its phase and skips the redundant catch-up.
|
|
571
|
-
if (this.#connecting || this.#connected) return;
|
|
572
|
-
void this.#adoptConnectedTransport();
|
|
573
|
-
return;
|
|
574
|
-
}
|
|
575
|
-
if (snapshot.host.realtime === 'connecting') {
|
|
576
|
-
// An attempt is already in flight; the supervisor's own #connect (or
|
|
577
|
-
// the host's direct call) owns the outcome.
|
|
578
|
-
this.#transportConnected = false;
|
|
696
|
+
const realtime = snapshot.host.realtime;
|
|
697
|
+
if (realtime === 'unsupported' || realtime === 'disabled') {
|
|
698
|
+
this.#supported = false;
|
|
699
|
+
this.#generation += 1;
|
|
700
|
+
if (!this.#clearTimer()) return;
|
|
579
701
|
this.#connected = false;
|
|
580
|
-
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
702
|
+
void this.#disconnect();
|
|
703
|
+
} else if (realtime === 'connected') {
|
|
704
|
+
// A live socket is positive evidence that an earlier 'unsupported'
|
|
705
|
+
// report was transient (a mid-restart capability probe).
|
|
706
|
+
if (this.#failure) return;
|
|
707
|
+
this.#supported = true;
|
|
708
|
+
this.#transport = true;
|
|
709
|
+
} else if (
|
|
710
|
+
realtime === 'disconnected' ||
|
|
711
|
+
realtime === 'lost' ||
|
|
712
|
+
realtime === 'refused'
|
|
586
713
|
) {
|
|
587
|
-
this.#
|
|
714
|
+
const held = this.#transport || this.#connected;
|
|
715
|
+
this.#transport = false;
|
|
588
716
|
this.#connected = false;
|
|
589
|
-
if (this.#
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
#reconcileHostState(): void {
|
|
597
|
-
if (this.#stopped) return;
|
|
598
|
-
const block = this.#hostBlock();
|
|
599
|
-
if (block) {
|
|
600
|
-
this.#suspend(block);
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
|
-
if (!this.#initialized) {
|
|
604
|
-
this.#publish({ phase: 'idle', attempt: 0 });
|
|
605
|
-
return;
|
|
606
|
-
}
|
|
607
|
-
if (!this.#realtimeSupported) {
|
|
608
|
-
this.#publish({ phase: 'unsupported', attempt: 0 });
|
|
609
|
-
return;
|
|
610
|
-
}
|
|
611
|
-
if (this.#connected) {
|
|
612
|
-
this.#publish({ phase: 'connected', attempt: 0 });
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
this.#schedule(false);
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
/** Cancel every attempt and release the socket, then publish `phase`. */
|
|
619
|
-
#suspend(phase: RealtimeSupervisorPhase): void {
|
|
620
|
-
const disconnect =
|
|
621
|
-
this.#connected || this.#transportConnected || this.#connecting;
|
|
622
|
-
if (!disconnect && !this.#cancelRetry && this.#snapshot.phase === phase) {
|
|
623
|
-
return;
|
|
717
|
+
if (this.#supported && !this.#disconnecting && !initial) {
|
|
718
|
+
// The attempt in flight owns a loss during its catch-up; a report
|
|
719
|
+
// beside a pending retry keeps that retry's count.
|
|
720
|
+
if (!this.#attemptJob && (held || !this.#cancelTimer)) this.#retry();
|
|
721
|
+
}
|
|
624
722
|
}
|
|
625
|
-
this.#
|
|
626
|
-
this.#connected = false;
|
|
627
|
-
this.#transportConnected = false;
|
|
628
|
-
this.#connecting = false;
|
|
629
|
-
this.#attempt = 0;
|
|
630
|
-
this.#clearRetry();
|
|
631
|
-
this.#publish({ phase, attempt: 0 });
|
|
632
|
-
if (disconnect) this.#disconnect();
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
#disconnect(): void {
|
|
636
|
-
void Promise.resolve(this.#client.disconnectRealtime()).catch(
|
|
637
|
-
() => undefined,
|
|
638
|
-
);
|
|
723
|
+
this.#reconcile();
|
|
639
724
|
}
|
|
640
725
|
}
|
|
641
726
|
|
|
642
727
|
/**
|
|
643
|
-
* Install one supervisor and make client disposal
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
*
|
|
728
|
+
* Install one supervisor and make client disposal stop it before close.
|
|
729
|
+
* Repeated and reentrant `close()` calls share one operation. A client accepts
|
|
730
|
+
* exactly one supervisor for its lifetime; installing a second throws
|
|
731
|
+
* `realtime.supervisor_already_installed`, because silently keeping the first
|
|
732
|
+
* would discard the second call's options.
|
|
647
733
|
*/
|
|
648
734
|
export function installRealtimeSupervisor<T extends RealtimeSupervisorClient>(
|
|
649
735
|
client: T,
|
|
650
736
|
options?: RealtimeSupervisorOptions,
|
|
651
737
|
): T {
|
|
652
738
|
if (attachment(client)) {
|
|
653
|
-
throw new
|
|
654
|
-
'
|
|
655
|
-
|
|
739
|
+
throw new ClientSyncError(
|
|
740
|
+
'realtime.supervisor_already_installed',
|
|
741
|
+
'realtime.supervisor_already_installed',
|
|
656
742
|
);
|
|
657
743
|
}
|
|
658
744
|
const supervisor = new RealtimeSupervisor(client, options);
|
|
745
|
+
// Non-writable, non-enumerable and non-configurable by default.
|
|
659
746
|
Object.defineProperty(client, REALTIME_SUPERVISOR_KEY, {
|
|
660
|
-
configurable: false,
|
|
661
|
-
enumerable: false,
|
|
662
|
-
writable: false,
|
|
663
747
|
value: { version: 1, supervisor } satisfies RealtimeSupervisorAttachment,
|
|
664
748
|
});
|
|
665
749
|
const close = client.close.bind(client);
|
|
750
|
+
let closing: Promise<void> | undefined;
|
|
666
751
|
Object.defineProperty(client, 'close', {
|
|
667
752
|
configurable: true,
|
|
668
753
|
writable: true,
|
|
669
|
-
value:
|
|
670
|
-
|
|
671
|
-
|
|
754
|
+
value: () => {
|
|
755
|
+
if (closing) return closing;
|
|
756
|
+
let stopped: Promise<RealtimeSupervisorError | undefined> | undefined;
|
|
757
|
+
closing = Promise.resolve().then(async () => {
|
|
758
|
+
const stopFailure = await stopped;
|
|
759
|
+
try {
|
|
760
|
+
await close();
|
|
761
|
+
} catch (error) {
|
|
762
|
+
if (stopFailure === undefined) throw error;
|
|
763
|
+
throw new RealtimeSupervisorError(stopFailure.code, {
|
|
764
|
+
...stopFailure,
|
|
765
|
+
stopFailureCode: stopFailure.code,
|
|
766
|
+
closeFailureCode: causeCode(error),
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
if (stopFailure) throw stopFailure;
|
|
770
|
+
});
|
|
771
|
+
// Reentrant closes during the synchronous stop share `closing`.
|
|
772
|
+
stopped = supervisor.stop().then(
|
|
773
|
+
() => undefined,
|
|
774
|
+
(error: RealtimeSupervisorError) => error,
|
|
775
|
+
);
|
|
776
|
+
return closing;
|
|
672
777
|
},
|
|
673
778
|
});
|
|
674
779
|
supervisor.start();
|