@syncular/client 0.65.0 → 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.
@@ -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`, so work a
55
- * failed round left behind resumes without realtime.
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
+
213
254
  /**
214
- * Supported host policy for Syncular's explicit realtime transport. It owns
215
- * exactly one connect attempt, runs an explicit catch-up round before claiming
216
- * connected, retries transient loss with bounded exponential jitter, and
217
- * suspends across offline, background, or protected-preflight state. A host
218
- * `online` report also drives `syncUntilIdle` when realtime is unsupported
219
- * or disabled.
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
+
280
+ /**
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
- #connected = false;
237
- #transportConnected = false;
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,66 +367,82 @@ export class RealtimeSupervisor {
282
367
  start(): void {
283
368
  if (this.#started || this.#stopped) return;
284
369
  this.#started = true;
285
- this.#unsubscribeDiagnostics = this.#client.onDiagnostics((snapshot) =>
286
- this.#observeDiagnostics(snapshot),
370
+ this.#unsubscribers.push(
371
+ this.#client.onDiagnostics((snapshot) => {
372
+ this.#diagnosticRevision += 1;
373
+ this.#observe(snapshot);
374
+ }),
287
375
  );
288
- this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() => {
289
- // §1.8: the host's connectivity signal re-arms the drive a failed
290
- // round left behind. The drive does not wait for the socket, so a
291
- // socket that cannot connect does not hold back an HTTP round.
292
- if (this.#connectivity?.current() === 'online' && !this.#hostBlock()) {
293
- void Promise.resolve()
294
- .then(() => this.#client.syncUntilIdle())
295
- .catch(() => undefined);
296
- }
297
- this.#reconcileHostState();
376
+ const connectivity = this.#connectivity?.subscribe((state) => {
377
+ this.#reconcile();
378
+ if (state === 'online') this.#drive();
298
379
  });
299
- this.#unsubscribeLifecycle = this.#lifecycle?.subscribe(() =>
300
- this.#reconcileHostState(),
301
- );
302
- this.#unsubscribeProtection = this.#protection?.subscribe(() =>
303
- this.#reconcileHostState(),
304
- );
305
- this.#reconcileHostState();
306
- const generation = this.#generation;
307
- void this.#initialize(generation);
380
+ const lifecycle = this.#lifecycle?.subscribe((state) => {
381
+ this.#reconcile();
382
+ if (state === 'active') this.#drive();
383
+ });
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
+ });
308
411
  }
309
412
 
310
- stop(): void {
311
- if (this.#stopped) return;
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
+ });
312
430
  this.#stopped = true;
313
431
  this.#generation += 1;
314
- const disconnect =
315
- this.#connected || this.#transportConnected || this.#connecting;
316
- this.#connected = false;
317
- this.#transportConnected = false;
318
- this.#connecting = false;
319
- this.#attempt = 0;
320
- this.#clearRetry();
321
- this.#unsubscribeDiagnostics?.();
322
- this.#unsubscribeConnectivity?.();
323
- this.#unsubscribeLifecycle?.();
324
- this.#unsubscribeProtection?.();
325
- this.#publish({ phase: 'stopped', attempt: 0 });
326
- this.#listeners.clear();
327
- if (disconnect) this.#disconnect();
328
- }
329
-
330
- async #initialize(generation: number): Promise<void> {
331
- let snapshot: ClientDiagnosticsSnapshot | undefined;
332
- try {
333
- snapshot = await this.#client.diagnosticsSnapshot();
334
- } catch {
335
- // Protected or temporarily unavailable diagnostics must not become a
336
- // startup dependency. Explicit host gates and the connect result remain.
432
+ this.#clearTimer();
433
+ for (const unsubscribe of this.#unsubscribers.splice(0)) {
434
+ try {
435
+ unsubscribe();
436
+ } catch {
437
+ this.#cleanupFailed();
438
+ }
337
439
  }
338
- if (generation !== this.#generation || this.#stopped) return;
339
- this.#initialized = true;
340
- if (snapshot !== undefined) this.#observeDiagnostics(snapshot, true);
341
- this.#reconcileHostState();
440
+ this.#publish({ phase: 'stopped', attempt: 0 });
441
+ void this.#disconnect();
442
+ return this.#stopping;
342
443
  }
343
444
 
344
- #hostBlock(): RealtimeSuspendedPhase | undefined {
445
+ #block(): RealtimeSuspendedPhase | undefined {
345
446
  const protection = this.#protection?.current();
346
447
  if (
347
448
  this.#diagnosticSecurity === 'preflight' ||
@@ -361,23 +462,33 @@ export class RealtimeSupervisor {
361
462
  return undefined;
362
463
  }
363
464
 
364
- #canConnect(): boolean {
365
- return (
366
- this.#initialized &&
367
- !this.#stopped &&
368
- this.#realtimeSupported &&
369
- !this.#hostBlock()
370
- );
465
+ /**
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.
469
+ */
470
+ #drive(): void {
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()
477
+ .then(() => this.#client.syncUntilIdle())
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
+ });
371
488
  }
372
489
 
373
490
  #publish(snapshot: RealtimeSupervisorSnapshot): void {
374
- if (
375
- this.#snapshot.phase === snapshot.phase &&
376
- this.#snapshot.attempt === snapshot.attempt &&
377
- this.#snapshot.retryDelayMs === snapshot.retryDelayMs
378
- ) {
379
- return;
380
- }
491
+ if (JSON.stringify(this.#snapshot) === JSON.stringify(snapshot)) return;
381
492
  this.#snapshot = Object.freeze(snapshot);
382
493
  for (const listener of this.#listeners) {
383
494
  try {
@@ -388,32 +499,28 @@ export class RealtimeSupervisor {
388
499
  }
389
500
  }
390
501
 
391
- #clearRetry(): void {
392
- this.#cancelRetry?.();
393
- this.#cancelRetry = undefined;
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);
394
506
  }
395
507
 
396
- #schedule(delayMs: number): void {
397
- if (
398
- !this.#canConnect() ||
399
- this.#connected ||
400
- this.#connecting ||
401
- this.#cancelRetry
402
- ) {
403
- return;
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;
404
518
  }
405
- this.#publish(
406
- delayMs > 0
407
- ? { phase: 'retrying', attempt: this.#attempt, retryDelayMs: delayMs }
408
- : { phase: 'connecting', attempt: this.#attempt },
409
- );
410
- this.#cancelRetry = this.#scheduleTimer(() => {
411
- this.#cancelRetry = undefined;
412
- void this.#connect();
413
- }, delayMs);
414
519
  }
415
520
 
416
- #retryDelay(): number {
521
+ /** Count one failed attempt and back off with bounded jitter, once per retry. */
522
+ #retry(): void {
523
+ if (this.#delayMs > 0) return;
417
524
  const exponential = Math.min(
418
525
  this.#maximumDelayMs,
419
526
  this.#initialDelayMs * 2 ** this.#attempt,
@@ -422,271 +529,251 @@ export class RealtimeSupervisor {
422
529
  const boundedRandom = Number.isFinite(random)
423
530
  ? Math.max(0, Math.min(1, random))
424
531
  : 0;
425
- const jitter = Math.floor(exponential * 0.25 * boundedRandom);
426
- return Math.min(this.#maximumDelayMs, exponential + jitter);
427
- }
428
-
429
- #scheduleRetry(): void {
430
- if (!this.#canConnect()) {
431
- this.#reconcileHostState();
432
- return;
433
- }
434
- // Count an attempt only when this call actually schedules one. Repeated
435
- // 'disconnected' diagnostics beside a pending retry keep the backoff and
436
- // the worker-mode reconnect nudge intact.
437
- if (
438
- this.#connected ||
439
- this.#connecting ||
440
- this.#cancelRetry !== undefined
441
- ) {
442
- return;
443
- }
444
- const delay = this.#retryDelay();
532
+ this.#delayMs = Math.min(
533
+ this.#maximumDelayMs,
534
+ exponential + Math.floor(exponential * 0.25 * boundedRandom),
535
+ );
445
536
  this.#attempt = Math.min(32, this.#attempt + 1);
446
- this.#schedule(delay);
447
537
  }
448
538
 
449
- /**
450
- * A superseded attempt observed a generation bump mid-flight. Whenever a
451
- * newer generation is mid-connect or holds the transport, that generation
452
- * owns the shared socket and the stale attempt leaves every field alone.
453
- * With the supervisor otherwise quiescent (suspended or stopped), the
454
- * socket this attempt opened is unwanted — release it.
455
- */
456
- #releaseSupersededSocket(): void {
457
- if (this.#connecting || this.#connected || this.#transportConnected) {
458
- 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;
459
543
  }
460
- this.#disconnect();
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();
461
554
  }
462
555
 
463
- async #connect(): Promise<void> {
464
- if (!this.#canConnect() || this.#connected || this.#connecting) return;
465
- const generation = this.#generation;
466
- this.#connecting = true;
467
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
468
- let failed = false;
469
- try {
470
- await this.#client.connectRealtime();
471
- if (generation !== this.#generation) {
472
- this.#releaseSupersededSocket();
473
- return;
474
- }
475
- this.#transportConnected = true;
476
- if (!this.#canConnect()) {
477
- this.#transportConnected = false;
478
- this.#disconnect();
479
- return;
480
- }
481
- await this.#catchUpConnectedTransport(generation);
482
- } catch (error) {
483
- if (generation !== this.#generation) {
484
- this.#releaseSupersededSocket();
485
- 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
+ }
486
568
  }
487
- this.#gateClosed =
488
- error instanceof Error &&
489
- 'code' in error &&
490
- error.code === 'sync.offline';
491
- failed = true;
569
+ if (!this.#clearTimer()) return;
492
570
  this.#connected = false;
493
- this.#transportConnected = false;
494
- this.#disconnect();
495
- } finally {
496
- // A superseded attempt leaves the successor's in-flight state alone.
497
- if (generation === this.#generation) this.#connecting = false;
498
- }
499
- if (failed && generation === this.#generation) this.#scheduleRetry();
500
- }
501
-
502
- async #catchUpConnectedTransport(generation: number): Promise<void> {
503
- await this.#client.syncUntilIdle();
504
- if (generation !== this.#generation) {
505
- this.#releaseSupersededSocket();
571
+ this.#publish({ phase: block, attempt: this.#attempt });
572
+ void this.#disconnect();
506
573
  return;
507
574
  }
508
- if (!this.#canConnect() || !this.#transportConnected) {
509
- this.#disconnect();
510
- return;
575
+ if (!this.#supported) {
576
+ return this.#publish({ phase: 'unsupported', attempt: 0 });
577
+ }
578
+ if (!this.#initialized) {
579
+ return this.#publish({ phase: 'idle', attempt: this.#attempt });
580
+ }
581
+ if (this.#connected) {
582
+ return this.#publish({ phase: 'connected', attempt: 0 });
511
583
  }
512
- this.#connected = true;
513
- this.#attempt = 0;
514
- this.#publish({ phase: 'connected', attempt: 0 });
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();
589
+ }
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);
515
607
  }
516
608
 
517
- async #adoptConnectedTransport(): Promise<void> {
518
- if (!this.#canConnect() || this.#connecting || !this.#transportConnected) {
519
- return;
520
- }
609
+ /** Start the one attempt; it opens a microtask later, so a flap can void it. */
610
+ #run(): void {
521
611
  const generation = this.#generation;
522
- this.#connecting = true;
523
- this.#clearRetry();
524
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
525
- let failed = false;
612
+ this.#delayMs = 0;
613
+ this.#attemptJob = Promise.resolve().then(() => this.#connect(generation));
614
+ }
615
+
616
+ async #connect(generation: number): Promise<void> {
526
617
  try {
527
- await this.#catchUpConnectedTransport(generation);
528
- } catch {
529
- if (generation !== this.#generation) {
530
- this.#releaseSupersededSocket();
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 });
531
643
  return;
532
644
  }
533
- failed = true;
534
- this.#connected = false;
535
- this.#transportConnected = false;
536
- 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();
537
648
  } finally {
538
- // A superseded adoption leaves the successor's in-flight state alone.
539
- if (generation === this.#generation) this.#connecting = false;
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();
540
653
  }
541
- if (failed && generation === this.#generation) this.#scheduleRetry();
542
654
  }
543
655
 
544
- #observeDiagnostics(
545
- snapshot: ClientDiagnosticsSnapshot,
546
- initial = false,
547
- ): void {
548
- if (this.#stopped) return;
549
- this.#diagnosticSecurity = snapshot.securityLifecycle;
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;
550
663
  if (
551
- snapshot.host.realtime === 'unsupported' ||
552
- snapshot.host.realtime === 'disabled'
664
+ !this.#transport &&
665
+ (!this.#attemptJob || this.#disconnectedGeneration === this.#generation)
553
666
  ) {
554
- const disconnect =
555
- this.#connected || this.#transportConnected || this.#connecting;
556
- this.#realtimeSupported = false;
557
- this.#generation += 1;
558
- this.#connected = false;
559
- this.#transportConnected = false;
560
- this.#attempt = 0;
561
- this.#clearRetry();
562
- this.#publish({ phase: 'unsupported', attempt: 0 });
563
- if (disconnect) this.#disconnect();
564
- return;
565
- }
566
- if (!this.#realtimeSupported) {
567
- // A live socket is positive evidence the earlier 'unsupported' report
568
- // was transient (a mid-restart or mis-detected capability probe), so it
569
- // recovers the supervisor. Every other report keeps the latch closed.
570
- if (snapshot.host.realtime !== 'connected') return;
571
- this.#realtimeSupported = true;
667
+ return Promise.resolve();
572
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.
573
693
  if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
574
- // A closed transport gate always reports offline, so any other report
575
- // means the app reopened it.
576
694
  this.#gateClosed = false;
577
- this.#reconcileHostState();
578
- return;
579
695
  }
580
- const block = this.#hostBlock();
581
- if (block) {
582
- this.#suspend(block);
583
- return;
584
- }
585
- if (snapshot.host.realtime === 'connected') {
586
- this.#transportConnected = true;
587
- // Steady state: diagnostics re-announce 'connected' on every sync
588
- // round and subscription change. An already-adopted transport keeps
589
- // its phase and skips the redundant catch-up.
590
- if (this.#connecting || this.#connected) return;
591
- void this.#adoptConnectedTransport();
592
- return;
593
- }
594
- if (snapshot.host.realtime === 'connecting') {
595
- // An attempt is already in flight; the supervisor's own #connect (or
596
- // the host's direct call) owns the outcome.
597
- 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;
598
701
  this.#connected = false;
599
- return;
600
- }
601
- if (
602
- snapshot.host.realtime === 'disconnected' ||
603
- snapshot.host.realtime === 'lost' ||
604
- snapshot.host.realtime === 'refused'
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'
605
713
  ) {
606
- this.#transportConnected = false;
714
+ const held = this.#transport || this.#connected;
715
+ this.#transport = false;
607
716
  this.#connected = false;
608
- if (this.#connecting) return;
609
- if (this.#initialized && !initial) this.#scheduleRetry();
610
- return;
611
- }
612
- this.#reconcileHostState();
613
- }
614
-
615
- #reconcileHostState(): void {
616
- if (this.#stopped) return;
617
- const block = this.#hostBlock();
618
- if (block) {
619
- this.#suspend(block);
620
- return;
621
- }
622
- if (!this.#initialized) {
623
- this.#publish({ phase: 'idle', attempt: 0 });
624
- return;
625
- }
626
- if (!this.#realtimeSupported) {
627
- this.#publish({ phase: 'unsupported', attempt: 0 });
628
- return;
629
- }
630
- if (this.#connected) {
631
- this.#publish({ phase: 'connected', attempt: 0 });
632
- 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
+ }
633
722
  }
634
- this.#schedule(0);
635
- }
636
-
637
- #suspend(phase: RealtimeSuspendedPhase): void {
638
- const disconnect =
639
- this.#connected || this.#transportConnected || this.#connecting;
640
- const hadScheduledWork = this.#cancelRetry !== undefined;
641
- const phaseChanged = this.#snapshot.phase !== phase;
642
- if (!disconnect && !hadScheduledWork && !phaseChanged) return;
643
- this.#generation += 1;
644
- this.#connected = false;
645
- this.#transportConnected = false;
646
- this.#connecting = false;
647
- this.#attempt = 0;
648
- this.#clearRetry();
649
- this.#publish({ phase, attempt: 0 });
650
- if (disconnect) this.#disconnect();
651
- }
652
-
653
- #disconnect(): void {
654
- void Promise.resolve(this.#client.disconnectRealtime()).catch(
655
- () => undefined,
656
- );
723
+ this.#reconcile();
657
724
  }
658
725
  }
659
726
 
660
727
  /**
661
- * Install one supervisor and make client disposal cancel it before close.
662
- * A client accepts exactly one supervisor for its lifetime; installing a
663
- * second throws, because silently keeping the first would discard the second
664
- * call's options.
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.
665
733
  */
666
734
  export function installRealtimeSupervisor<T extends RealtimeSupervisorClient>(
667
735
  client: T,
668
736
  options?: RealtimeSupervisorOptions,
669
737
  ): T {
670
738
  if (attachment(client)) {
671
- throw new Error(
672
- 'installRealtimeSupervisor: this client already has a supervisor; ' +
673
- 'install one supervisor per client lifetime',
739
+ throw new ClientSyncError(
740
+ 'realtime.supervisor_already_installed',
741
+ 'realtime.supervisor_already_installed',
674
742
  );
675
743
  }
676
744
  const supervisor = new RealtimeSupervisor(client, options);
745
+ // Non-writable, non-enumerable and non-configurable by default.
677
746
  Object.defineProperty(client, REALTIME_SUPERVISOR_KEY, {
678
- configurable: false,
679
- enumerable: false,
680
- writable: false,
681
747
  value: { version: 1, supervisor } satisfies RealtimeSupervisorAttachment,
682
748
  });
683
749
  const close = client.close.bind(client);
750
+ let closing: Promise<void> | undefined;
684
751
  Object.defineProperty(client, 'close', {
685
752
  configurable: true,
686
753
  writable: true,
687
- value: async () => {
688
- supervisor.stop();
689
- await close();
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;
690
777
  },
691
778
  });
692
779
  supervisor.start();