@syncular/client 0.65.1 → 0.66.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.
@@ -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
+
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 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. Each
218
- * failed attempt, each host `online` report, and each foreground return
219
- * while no attempt starts at once drives one HTTP round (§1.8).
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,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.#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((state) => {
376
+ const connectivity = this.#connectivity?.subscribe((state) => {
377
+ this.#reconcile();
289
378
  if (state === 'online') this.#drive();
290
- this.#reconcileHostState();
291
379
  });
292
- this.#unsubscribeLifecycle = this.#lifecycle?.subscribe((state) => {
293
- this.#reconcileHostState();
294
- // An immediate attempt brings its own round; a pending retry or an
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
- this.#unsubscribeProtection = this.#protection?.subscribe(() =>
305
- this.#reconcileHostState(),
306
- );
307
- this.#reconcileHostState();
308
- const generation = this.#generation;
309
- void this.#initialize(generation);
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
- stop(): void {
313
- 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
+ });
314
430
  this.#stopped = true;
315
- this.#suspend('stopped');
316
- this.#unsubscribeDiagnostics?.();
317
- this.#unsubscribeConnectivity?.();
318
- this.#unsubscribeLifecycle?.();
319
- this.#unsubscribeProtection?.();
320
- this.#listeners.clear();
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
- if (generation !== this.#generation || this.#stopped) return;
332
- this.#initialized = true;
333
- if (snapshot !== undefined) this.#observeDiagnostics(snapshot, true);
334
- this.#reconcileHostState();
440
+ this.#publish({ phase: 'stopped', attempt: 0 });
441
+ void this.#disconnect();
442
+ return this.#stopping;
335
443
  }
336
444
 
337
- #hostBlock(): RealtimeSuspendedPhase | undefined {
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 that re-arms the drive a refused fetch left behind.
359
- * It does not wait for the socket, so a socket that cannot connect does not
360
- * hold back the round.
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.#hostBlock()) return;
364
- void Promise.resolve()
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
- .catch(() => undefined);
367
- }
368
-
369
- #canConnect(): boolean {
370
- return (
371
- this.#initialized &&
372
- !this.#stopped &&
373
- this.#realtimeSupported &&
374
- !this.#hostBlock()
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
- #clearRetry(): void {
397
- this.#cancelRetry?.();
398
- 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);
399
506
  }
400
507
 
401
- /** A retry counts one attempt and backs off with bounded jitter. */
402
- #schedule(retry: boolean): void {
403
- if (!this.#canConnect()) return this.#reconcileHostState();
404
- // Count an attempt only when this call actually schedules one. Repeated
405
- // 'disconnected' diagnostics beside a pending retry keep the backoff and
406
- // the worker-mode reconnect nudge intact.
407
- if (this.#connected || this.#connecting || this.#cancelRetry) return;
408
- let delayMs = 0;
409
- if (retry) {
410
- const exponential = Math.min(
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
- this.#publish(
425
- retry
426
- ? { phase: 'retrying', attempt: this.#attempt, retryDelayMs: delayMs }
427
- : { phase: 'connecting', attempt: this.#attempt },
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
- this.#cancelRetry = this.#scheduleTimer(() => {
430
- this.#cancelRetry = undefined;
431
- void this.#connect();
432
- }, delayMs);
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
- * A superseded attempt observed a generation bump mid-flight. Whenever a
437
- * newer generation is mid-connect or holds the transport, that generation
438
- * owns the shared socket and the stale attempt leaves every field alone.
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.#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();
447
554
  }
448
555
 
449
- async #connect(): Promise<void> {
450
- if (!this.#canConnect() || this.#connected || this.#connecting) return;
451
- const generation = this.#generation;
452
- this.#connecting = true;
453
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
454
- let failed = false;
455
- try {
456
- await this.#client.connectRealtime();
457
- if (generation !== this.#generation) {
458
- this.#releaseSupersededSocket();
459
- return;
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.#gateClosed =
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.#transportConnected = false;
480
- this.#disconnect();
481
- } finally {
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 (failed && generation === this.#generation) {
486
- this.#schedule(true);
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 (!this.#canConnect() || !this.#transportConnected) {
498
- this.#disconnect();
499
- return;
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.#connected = true;
502
- this.#attempt = 0;
503
- this.#publish({ phase: 'connected', attempt: 0 });
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
- async #adoptConnectedTransport(): Promise<void> {
507
- if (!this.#canConnect() || this.#connecting || !this.#transportConnected) {
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.#connecting = true;
512
- this.#clearRetry();
513
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
514
- 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> {
515
617
  try {
516
- await this.#catchUpConnectedTransport(generation);
517
- } catch {
518
- if (generation !== this.#generation) {
519
- 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 });
520
643
  return;
521
644
  }
522
- failed = true;
523
- this.#connected = false;
524
- this.#transportConnected = false;
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
- // A superseded adoption leaves the successor's in-flight state alone.
528
- 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();
529
653
  }
530
- if (failed && generation === this.#generation) this.#schedule(true);
531
654
  }
532
655
 
533
- #observeDiagnostics(
534
- snapshot: ClientDiagnosticsSnapshot,
535
- initial = false,
536
- ): void {
537
- if (this.#stopped) return;
538
- 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;
539
663
  if (
540
- snapshot.host.realtime === 'unsupported' ||
541
- snapshot.host.realtime === 'disabled'
664
+ !this.#transport &&
665
+ (!this.#attemptJob || this.#disconnectedGeneration === this.#generation)
542
666
  ) {
543
- this.#realtimeSupported = false;
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 block = this.#hostBlock();
562
- if (block) {
563
- this.#suspend(block);
564
- return;
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
- return;
581
- }
582
- if (
583
- snapshot.host.realtime === 'disconnected' ||
584
- snapshot.host.realtime === 'lost' ||
585
- 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'
586
713
  ) {
587
- this.#transportConnected = false;
714
+ const held = this.#transport || this.#connected;
715
+ this.#transport = false;
588
716
  this.#connected = false;
589
- if (this.#connecting) return;
590
- if (this.#initialized && !initial) this.#schedule(true);
591
- return;
592
- }
593
- this.#reconcileHostState();
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.#generation += 1;
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 cancel it before close.
644
- * A client accepts exactly one supervisor for its lifetime; installing a
645
- * second throws, because silently keeping the first would discard the second
646
- * 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.
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 Error(
654
- 'installRealtimeSupervisor: this client already has a supervisor; ' +
655
- 'install one supervisor per client lifetime',
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: async () => {
670
- supervisor.stop();
671
- 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;
672
777
  },
673
778
  });
674
779
  supervisor.start();