@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.
@@ -1,4 +1,7 @@
1
+ import { ClientSyncError } from './errors.js';
1
2
  const REALTIME_SUPERVISOR_KEY = Symbol.for('syncular.realtime-supervisor.v1');
3
+ const CLEANUP_FAILED = 'realtime.cleanup_failed';
4
+ const DIAGNOSTICS_UNAVAILABLE = 'realtime.diagnostics_unavailable';
2
5
  const DEFAULT_INITIAL_DELAY_MS = 1_000;
3
6
  const DEFAULT_MAXIMUM_DELAY_MS = 30_000;
4
7
  const MAXIMUM_CONFIGURED_DELAY_MS = 300_000;
@@ -100,13 +103,55 @@ export function documentLifecycleSignal(options = {}) {
100
103
  },
101
104
  };
102
105
  }
106
+ /** A Syncular code (§10.3 families) on an own data property, else `unknown`. */
107
+ function causeCode(error) {
108
+ try {
109
+ const value = typeof error === 'object' && error !== null
110
+ ? Object.getOwnPropertyDescriptor(error, 'code')?.value
111
+ : undefined;
112
+ return typeof value === 'string' &&
113
+ /^(?:sync|client|transport|realtime)\.[a-z0-9_]+$/.test(value)
114
+ ? value
115
+ : 'unknown';
116
+ }
117
+ catch {
118
+ // A hostile value (a throwing proxy) carries no code.
119
+ return 'unknown';
120
+ }
121
+ }
122
+ /** SPEC §8.4: a stable-coded error the client marked `retryable`, read without getters. */
123
+ function retryable(error) {
124
+ try {
125
+ return (causeCode(error) !== 'unknown' &&
126
+ Object.getOwnPropertyDescriptor(error, 'retryable')?.value === true);
127
+ }
128
+ catch {
129
+ return false;
130
+ }
131
+ }
132
+ /**
133
+ * SPEC §8.4: a supervisor failure. `code` is the latest latched failure, or
134
+ * `realtime.cleanup_failed` when only a cancel threw. Every failure of the
135
+ * lifetime is also named in its own field. Cause codes are Syncular codes or
136
+ * `unknown`; no message or original error is retained.
137
+ */
138
+ export class RealtimeSupervisorError extends ClientSyncError {
139
+ name = 'RealtimeSupervisorError';
140
+ constructor(code, fields = {}) {
141
+ super(code, code);
142
+ Object.assign(this, fields);
143
+ }
144
+ }
103
145
  /**
104
- * Supported host policy for Syncular's explicit realtime transport. It owns
105
- * exactly one connect attempt, runs an explicit catch-up round before claiming
106
- * connected, retries transient loss with bounded exponential jitter, and
107
- * suspends across offline, background, or protected-preflight state. A host
108
- * `online` report also drives `syncUntilIdle` when realtime is unsupported
109
- * or disabled.
146
+ * Supported host policy for Syncular's explicit realtime transport (§8.4). It
147
+ * owns one attempt at a time: a connect, then an explicit catch-up round
148
+ * before it claims connected. A successor never starts before the previous
149
+ * attempt and its disconnect settle. Transient loss retries with bounded
150
+ * exponential jitter, and the backoff survives offline, background and
151
+ * protected suspensions. While no socket is connected, each failed connect,
152
+ * each host `online` report and each foreground return drives one HTTP round
153
+ * (§1.8). A disconnect, diagnostics or cleanup failure latches phase
154
+ * `unsupported` with its `failureCode`, and `stop()` rejects with it.
110
155
  */
111
156
  export class RealtimeSupervisor {
112
157
  #client;
@@ -119,24 +164,35 @@ export class RealtimeSupervisor {
119
164
  #initialDelayMs;
120
165
  #maximumDelayMs;
121
166
  #listeners = new Set();
167
+ #unsubscribers = [];
122
168
  #started = false;
123
169
  #initialized = false;
124
170
  #stopped = false;
125
- #connected = false;
126
- #transportConnected = false;
127
- #connecting = false;
128
- #realtimeSupported = true;
171
+ #stopping;
172
+ #supported = true;
129
173
  /** The client refused a connect with `sync.offline`: its transport gate is closed. */
130
174
  #gateClosed = false;
131
175
  #diagnosticSecurity = 'unknown';
176
+ #diagnosticRevision = 0;
177
+ /** A socket is open, whether this supervisor or the host opened it. */
178
+ #transport = false;
179
+ /** The open socket completed its catch-up round. */
180
+ #connected = false;
132
181
  #attempt = 0;
182
+ /** The delay of the counted retry; zero schedules an immediate attempt. */
183
+ #delayMs = 0;
184
+ /** Bumped by every suspension, failure and stop; a stale attempt only cleans up. */
133
185
  #generation = 0;
186
+ #disconnectedGeneration = -1;
187
+ #cancelTimer;
188
+ #attemptJob;
189
+ #disconnecting;
190
+ #round;
191
+ #roundAgain = false;
192
+ #failure;
193
+ /** Every failure of the lifetime, named for the stop rejection. */
194
+ #failures = {};
134
195
  #snapshot = { phase: 'idle', attempt: 0 };
135
- #cancelRetry;
136
- #unsubscribeDiagnostics;
137
- #unsubscribeConnectivity;
138
- #unsubscribeLifecycle;
139
- #unsubscribeProtection;
140
196
  constructor(client, options = {}) {
141
197
  this.#client = client;
142
198
  this.#connectivity = options.connectivity;
@@ -159,61 +215,86 @@ export class RealtimeSupervisor {
159
215
  if (this.#started || this.#stopped)
160
216
  return;
161
217
  this.#started = true;
162
- this.#unsubscribeDiagnostics = this.#client.onDiagnostics((snapshot) => this.#observeDiagnostics(snapshot));
163
- this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() => {
164
- // §1.8: the host's connectivity signal re-arms the drive a failed
165
- // round left behind. The drive does not wait for the socket, so a
166
- // socket that cannot connect does not hold back an HTTP round.
167
- if (this.#connectivity?.current() === 'online' && !this.#hostBlock()) {
168
- void Promise.resolve()
169
- .then(() => this.#client.syncUntilIdle())
170
- .catch(() => undefined);
218
+ this.#unsubscribers.push(this.#client.onDiagnostics((snapshot) => {
219
+ this.#diagnosticRevision += 1;
220
+ this.#observe(snapshot);
221
+ }));
222
+ const connectivity = this.#connectivity?.subscribe((state) => {
223
+ this.#reconcile();
224
+ if (state === 'online')
225
+ this.#drive();
226
+ });
227
+ const lifecycle = this.#lifecycle?.subscribe((state) => {
228
+ this.#reconcile();
229
+ if (state === 'active')
230
+ this.#drive();
231
+ });
232
+ const protection = this.#protection?.subscribe(() => this.#reconcile());
233
+ for (const unsubscribe of [connectivity, lifecycle, protection]) {
234
+ if (unsubscribe)
235
+ this.#unsubscribers.push(unsubscribe);
236
+ }
237
+ this.#reconcile();
238
+ const revision = this.#diagnosticRevision;
239
+ void Promise.resolve()
240
+ .then(() => this.#client.diagnosticsSnapshot())
241
+ .then((snapshot) => {
242
+ if (this.#stopped)
243
+ return;
244
+ // Initialization belongs to the lifetime; host flaps cannot void it.
245
+ this.#initialized = true;
246
+ // A live report that arrived meanwhile is newer than this read.
247
+ if (revision === this.#diagnosticRevision) {
248
+ this.#observe(snapshot, true);
171
249
  }
172
- this.#reconcileHostState();
250
+ this.#reconcile();
251
+ })
252
+ .catch((error) => {
253
+ if (this.#stopped)
254
+ return;
255
+ if (!retryable(error))
256
+ return this.#fail(DIAGNOSTICS_UNAVAILABLE);
257
+ // A leader handover or follower timeout: start on the retry schedule
258
+ // and let the live reports and the connect result stand in.
259
+ this.#initialized = true;
260
+ this.#retry();
261
+ this.#reconcile();
173
262
  });
174
- this.#unsubscribeLifecycle = this.#lifecycle?.subscribe(() => this.#reconcileHostState());
175
- this.#unsubscribeProtection = this.#protection?.subscribe(() => this.#reconcileHostState());
176
- this.#reconcileHostState();
177
- const generation = this.#generation;
178
- void this.#initialize(generation);
179
263
  }
264
+ /**
265
+ * Cancel the timer and every subscription, release the socket, and settle
266
+ * once the in-flight attempt, its disconnect and any driven round have
267
+ * settled. Rejects with a {@link RealtimeSupervisorError} when a failure
268
+ * latched during the lifetime or a cancel threw; every caller shares it.
269
+ */
180
270
  stop() {
181
- if (this.#stopped)
182
- return;
271
+ if (this.#stopping)
272
+ return this.#stopping;
273
+ this.#stopping = Promise.resolve().then(async () => {
274
+ await this.#disconnecting;
275
+ await this.#attemptJob;
276
+ await this.#round;
277
+ this.#listeners.clear();
278
+ if (this.#failure) {
279
+ throw new RealtimeSupervisorError(this.#failure, this.#failures);
280
+ }
281
+ });
183
282
  this.#stopped = true;
184
283
  this.#generation += 1;
185
- const disconnect = this.#connected || this.#transportConnected || this.#connecting;
186
- this.#connected = false;
187
- this.#transportConnected = false;
188
- this.#connecting = false;
189
- this.#attempt = 0;
190
- this.#clearRetry();
191
- this.#unsubscribeDiagnostics?.();
192
- this.#unsubscribeConnectivity?.();
193
- this.#unsubscribeLifecycle?.();
194
- this.#unsubscribeProtection?.();
195
- this.#publish({ phase: 'stopped', attempt: 0 });
196
- this.#listeners.clear();
197
- if (disconnect)
198
- this.#disconnect();
199
- }
200
- async #initialize(generation) {
201
- let snapshot;
202
- try {
203
- snapshot = await this.#client.diagnosticsSnapshot();
204
- }
205
- catch {
206
- // Protected or temporarily unavailable diagnostics must not become a
207
- // startup dependency. Explicit host gates and the connect result remain.
284
+ this.#clearTimer();
285
+ for (const unsubscribe of this.#unsubscribers.splice(0)) {
286
+ try {
287
+ unsubscribe();
288
+ }
289
+ catch {
290
+ this.#cleanupFailed();
291
+ }
208
292
  }
209
- if (generation !== this.#generation || this.#stopped)
210
- return;
211
- this.#initialized = true;
212
- if (snapshot !== undefined)
213
- this.#observeDiagnostics(snapshot, true);
214
- this.#reconcileHostState();
293
+ this.#publish({ phase: 'stopped', attempt: 0 });
294
+ void this.#disconnect();
295
+ return this.#stopping;
215
296
  }
216
- #hostBlock() {
297
+ #block() {
217
298
  const protection = this.#protection?.current();
218
299
  if (this.#diagnosticSecurity === 'preflight' ||
219
300
  protection === 'preflight' ||
@@ -230,18 +311,32 @@ export class RealtimeSupervisor {
230
311
  }
231
312
  return undefined;
232
313
  }
233
- #canConnect() {
234
- return (this.#initialized &&
235
- !this.#stopped &&
236
- this.#realtimeSupported &&
237
- !this.#hostBlock());
314
+ /**
315
+ * §1.8: one HTTP round while no socket carries the rounds. A request during
316
+ * a round adds one round after it. The round's failure is the client's
317
+ * round failure, which its progress and status already report.
318
+ */
319
+ #drive() {
320
+ if (this.#stopped || this.#connected || this.#block())
321
+ return;
322
+ if (this.#round) {
323
+ this.#roundAgain = true;
324
+ return;
325
+ }
326
+ this.#round = Promise.resolve()
327
+ .then(() => this.#client.syncUntilIdle())
328
+ .then(() => undefined, () => undefined)
329
+ .finally(() => {
330
+ this.#round = undefined;
331
+ if (!this.#roundAgain)
332
+ return;
333
+ this.#roundAgain = false;
334
+ this.#drive();
335
+ });
238
336
  }
239
337
  #publish(snapshot) {
240
- if (this.#snapshot.phase === snapshot.phase &&
241
- this.#snapshot.attempt === snapshot.attempt &&
242
- this.#snapshot.retryDelayMs === snapshot.retryDelayMs) {
338
+ if (JSON.stringify(this.#snapshot) === JSON.stringify(snapshot))
243
339
  return;
244
- }
245
340
  this.#snapshot = Object.freeze(snapshot);
246
341
  for (const listener of this.#listeners) {
247
342
  try {
@@ -252,286 +347,274 @@ export class RealtimeSupervisor {
252
347
  }
253
348
  }
254
349
  }
255
- #clearRetry() {
256
- this.#cancelRetry?.();
257
- this.#cancelRetry = undefined;
350
+ /** A cancel threw: name it, and latch it unless a failure already did. */
351
+ #cleanupFailed() {
352
+ this.#failures.cleanupFailureCode = CLEANUP_FAILED;
353
+ if (!this.#failure)
354
+ this.#fail(CLEANUP_FAILED);
258
355
  }
259
- #schedule(delayMs) {
260
- if (!this.#canConnect() ||
261
- this.#connected ||
262
- this.#connecting ||
263
- this.#cancelRetry) {
264
- return;
356
+ /** False when the host's cancel threw; the timer may still fire. */
357
+ #clearTimer() {
358
+ const cancel = this.#cancelTimer;
359
+ this.#cancelTimer = undefined;
360
+ try {
361
+ cancel?.();
362
+ return true;
363
+ }
364
+ catch {
365
+ this.#cleanupFailed();
366
+ return false;
265
367
  }
266
- this.#publish(delayMs > 0
267
- ? { phase: 'retrying', attempt: this.#attempt, retryDelayMs: delayMs }
268
- : { phase: 'connecting', attempt: this.#attempt });
269
- this.#cancelRetry = this.#scheduleTimer(() => {
270
- this.#cancelRetry = undefined;
271
- void this.#connect();
272
- }, delayMs);
273
368
  }
274
- #retryDelay() {
369
+ /** Count one failed attempt and back off with bounded jitter, once per retry. */
370
+ #retry() {
371
+ if (this.#delayMs > 0)
372
+ return;
275
373
  const exponential = Math.min(this.#maximumDelayMs, this.#initialDelayMs * 2 ** this.#attempt);
276
374
  const random = this.#random();
277
375
  const boundedRandom = Number.isFinite(random)
278
376
  ? Math.max(0, Math.min(1, random))
279
377
  : 0;
280
- const jitter = Math.floor(exponential * 0.25 * boundedRandom);
281
- return Math.min(this.#maximumDelayMs, exponential + jitter);
282
- }
283
- #scheduleRetry() {
284
- if (!this.#canConnect()) {
285
- this.#reconcileHostState();
286
- return;
287
- }
288
- // Count an attempt only when this call actually schedules one. Repeated
289
- // 'disconnected' diagnostics beside a pending retry keep the backoff and
290
- // the worker-mode reconnect nudge intact.
291
- if (this.#connected ||
292
- this.#connecting ||
293
- this.#cancelRetry !== undefined) {
294
- return;
295
- }
296
- const delay = this.#retryDelay();
378
+ this.#delayMs = Math.min(this.#maximumDelayMs, exponential + Math.floor(exponential * 0.25 * boundedRandom));
297
379
  this.#attempt = Math.min(32, this.#attempt + 1);
298
- this.#schedule(delay);
299
380
  }
300
- /**
301
- * A superseded attempt observed a generation bump mid-flight. Whenever a
302
- * newer generation is mid-connect or holds the transport, that generation
303
- * owns the shared socket and the stale attempt leaves every field alone.
304
- * With the supervisor otherwise quiescent (suspended or stopped), the
305
- * socket this attempt opened is unwanted — release it.
306
- */
307
- #releaseSupersededSocket() {
308
- if (this.#connecting || this.#connected || this.#transportConnected) {
309
- return;
381
+ /** Latch a failure: no further attempt, and the socket is released. */
382
+ #fail(code) {
383
+ if (code === DIAGNOSTICS_UNAVAILABLE) {
384
+ this.#failures.diagnosticsFailureCode = code;
310
385
  }
311
- this.#disconnect();
386
+ this.#failure = code;
387
+ this.#generation += 1;
388
+ this.#connected = false;
389
+ this.#clearTimer();
390
+ this.#publish({
391
+ phase: this.#stopped ? 'stopped' : 'unsupported',
392
+ attempt: this.#attempt,
393
+ failureCode: code,
394
+ });
395
+ void this.#disconnect();
312
396
  }
313
- async #connect() {
314
- if (!this.#canConnect() || this.#connected || this.#connecting)
397
+ /** Converge timer, attempt and socket on the current host evidence. */
398
+ #reconcile() {
399
+ if (this.#stopped || this.#failure)
315
400
  return;
316
- const generation = this.#generation;
317
- this.#connecting = true;
318
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
319
- let failed = false;
320
- try {
321
- await this.#client.connectRealtime();
322
- if (generation !== this.#generation) {
323
- this.#releaseSupersededSocket();
324
- return;
325
- }
326
- this.#transportConnected = true;
327
- if (!this.#canConnect()) {
328
- this.#transportConnected = false;
329
- this.#disconnect();
330
- return;
401
+ const block = this.#block();
402
+ if (block) {
403
+ if (this.#snapshot.phase !== block) {
404
+ this.#generation += 1;
405
+ // An interrupted attempt counts, so flaps keep the backoff. A gate
406
+ // refusal is the attempt's own result, not an interruption.
407
+ if (this.#attemptJob && !this.#connected && !this.#gateClosed) {
408
+ this.#retry();
409
+ }
331
410
  }
332
- await this.#catchUpConnectedTransport(generation);
333
- }
334
- catch (error) {
335
- if (generation !== this.#generation) {
336
- this.#releaseSupersededSocket();
411
+ if (!this.#clearTimer())
337
412
  return;
338
- }
339
- this.#gateClosed =
340
- error instanceof Error &&
341
- 'code' in error &&
342
- error.code === 'sync.offline';
343
- failed = true;
344
413
  this.#connected = false;
345
- this.#transportConnected = false;
346
- this.#disconnect();
414
+ this.#publish({ phase: block, attempt: this.#attempt });
415
+ void this.#disconnect();
416
+ return;
347
417
  }
348
- finally {
349
- // A superseded attempt leaves the successor's in-flight state alone.
350
- if (generation === this.#generation)
351
- this.#connecting = false;
418
+ if (!this.#supported) {
419
+ return this.#publish({ phase: 'unsupported', attempt: 0 });
352
420
  }
353
- if (failed && generation === this.#generation)
354
- this.#scheduleRetry();
355
- }
356
- async #catchUpConnectedTransport(generation) {
357
- await this.#client.syncUntilIdle();
358
- if (generation !== this.#generation) {
359
- this.#releaseSupersededSocket();
360
- return;
421
+ if (!this.#initialized) {
422
+ return this.#publish({ phase: 'idle', attempt: this.#attempt });
361
423
  }
362
- if (!this.#canConnect() || !this.#transportConnected) {
363
- this.#disconnect();
364
- return;
424
+ if (this.#connected) {
425
+ return this.#publish({ phase: 'connected', attempt: 0 });
365
426
  }
366
- this.#connected = true;
367
- this.#attempt = 0;
368
- this.#publish({ phase: 'connected', attempt: 0 });
369
- }
370
- async #adoptConnectedTransport() {
371
- if (!this.#canConnect() || this.#connecting || !this.#transportConnected) {
427
+ if (this.#attemptJob || this.#disconnecting)
372
428
  return;
429
+ if (this.#transport) {
430
+ // A socket the host opened is adopted after the same catch-up round.
431
+ if (!this.#clearTimer())
432
+ return;
433
+ return this.#run();
373
434
  }
435
+ if (this.#cancelTimer)
436
+ return;
437
+ this.#publish(this.#delayMs > 0
438
+ ? {
439
+ phase: 'retrying',
440
+ attempt: this.#attempt,
441
+ retryDelayMs: this.#delayMs,
442
+ }
443
+ : { phase: 'connecting', attempt: this.#attempt });
444
+ this.#cancelTimer = this.#scheduleTimer(() => {
445
+ this.#cancelTimer = undefined;
446
+ if (this.#stopped || this.#failure || this.#attemptJob || this.#block()) {
447
+ return;
448
+ }
449
+ this.#run();
450
+ }, this.#delayMs);
451
+ }
452
+ /** Start the one attempt; it opens a microtask later, so a flap can void it. */
453
+ #run() {
374
454
  const generation = this.#generation;
375
- this.#connecting = true;
376
- this.#clearRetry();
377
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
378
- let failed = false;
455
+ this.#delayMs = 0;
456
+ this.#attemptJob = Promise.resolve().then(() => this.#connect(generation));
457
+ }
458
+ async #connect(generation) {
379
459
  try {
380
- await this.#catchUpConnectedTransport(generation);
381
- }
382
- catch {
383
- if (generation !== this.#generation) {
384
- this.#releaseSupersededSocket();
460
+ if (generation !== this.#generation)
385
461
  return;
462
+ this.#publish({ phase: 'connecting', attempt: this.#attempt });
463
+ let caughtUp = false;
464
+ try {
465
+ if (!this.#transport) {
466
+ await new Promise((resolve) => resolve(this.#client.connectRealtime())).catch((error) => {
467
+ if (causeCode(error) === 'sync.offline')
468
+ this.#gateClosed = true;
469
+ // §1.8: a refused socket still brings one round over HTTP.
470
+ else
471
+ this.#drive();
472
+ throw error;
473
+ });
474
+ this.#transport = true;
475
+ }
476
+ if (generation === this.#generation)
477
+ await this.#client.syncUntilIdle();
478
+ caughtUp = generation === this.#generation && this.#transport;
386
479
  }
387
- failed = true;
388
- this.#connected = false;
389
- this.#transportConnected = false;
390
- this.#disconnect();
480
+ catch {
481
+ // A refused socket or a failed catch-up round fails the attempt.
482
+ }
483
+ if (caughtUp) {
484
+ this.#connected = true;
485
+ this.#attempt = 0;
486
+ this.#delayMs = 0;
487
+ this.#publish({ phase: 'connected', attempt: 0 });
488
+ return;
489
+ }
490
+ if (generation === this.#generation && !this.#gateClosed)
491
+ this.#retry();
492
+ // A stale attempt releases the late socket before a successor may open.
493
+ await this.#disconnect();
391
494
  }
392
495
  finally {
393
- // A superseded adoption leaves the successor's in-flight state alone.
394
- if (generation === this.#generation)
395
- this.#connecting = false;
496
+ // Settled in the same turn, so a report right after `connected`
497
+ // meets no attempt in flight.
498
+ this.#attemptJob = undefined;
499
+ this.#reconcile();
396
500
  }
397
- if (failed && generation === this.#generation)
398
- this.#scheduleRetry();
399
501
  }
400
- #observeDiagnostics(snapshot, initial = false) {
502
+ /**
503
+ * Release the socket, or void an attempt in flight, once per generation.
504
+ * `#disconnecting` is set before the call, so diagnostics the call emits
505
+ * synchronously see the teardown and schedule no retry.
506
+ */
507
+ #disconnect() {
508
+ if (this.#disconnecting)
509
+ return this.#disconnecting;
510
+ if (!this.#transport &&
511
+ (!this.#attemptJob || this.#disconnectedGeneration === this.#generation)) {
512
+ return Promise.resolve();
513
+ }
514
+ this.#disconnectedGeneration = this.#generation;
515
+ this.#transport = false;
516
+ this.#connected = false;
517
+ this.#disconnecting = Promise.resolve();
518
+ this.#disconnecting = new Promise((resolve) => resolve(this.#client.disconnectRealtime()))
519
+ .catch((error) => {
520
+ if (retryable(error))
521
+ return this.#retry();
522
+ this.#failures.disconnectCauseCode = causeCode(error);
523
+ this.#fail('realtime.disconnect_failed');
524
+ })
525
+ .finally(() => {
526
+ this.#disconnecting = undefined;
527
+ this.#reconcile();
528
+ });
529
+ return this.#disconnecting;
530
+ }
531
+ #observe(snapshot, initial = false) {
401
532
  if (this.#stopped)
402
533
  return;
403
534
  this.#diagnosticSecurity = snapshot.securityLifecycle;
404
- if (snapshot.host.realtime === 'unsupported' ||
405
- snapshot.host.realtime === 'disabled') {
406
- const disconnect = this.#connected || this.#transportConnected || this.#connecting;
407
- this.#realtimeSupported = false;
408
- this.#generation += 1;
409
- this.#connected = false;
410
- this.#transportConnected = false;
411
- this.#attempt = 0;
412
- this.#clearRetry();
413
- this.#publish({ phase: 'unsupported', attempt: 0 });
414
- if (disconnect)
415
- this.#disconnect();
416
- return;
417
- }
418
- if (!this.#realtimeSupported) {
419
- // A live socket is positive evidence the earlier 'unsupported' report
420
- // was transient (a mid-restart or mis-detected capability probe), so it
421
- // recovers the supervisor. Every other report keeps the latch closed.
422
- if (snapshot.host.realtime !== 'connected')
423
- return;
424
- this.#realtimeSupported = true;
425
- }
535
+ // A closed transport gate always reports offline, so any other report
536
+ // means the app reopened it.
426
537
  if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
427
- // A closed transport gate always reports offline, so any other report
428
- // means the app reopened it.
429
538
  this.#gateClosed = false;
430
- this.#reconcileHostState();
431
- return;
432
539
  }
433
- const block = this.#hostBlock();
434
- if (block) {
435
- this.#suspend(block);
436
- return;
437
- }
438
- if (snapshot.host.realtime === 'connected') {
439
- this.#transportConnected = true;
440
- // Steady state: diagnostics re-announce 'connected' on every sync
441
- // round and subscription change. An already-adopted transport keeps
442
- // its phase and skips the redundant catch-up.
443
- if (this.#connecting || this.#connected)
540
+ const realtime = snapshot.host.realtime;
541
+ if (realtime === 'unsupported' || realtime === 'disabled') {
542
+ this.#supported = false;
543
+ this.#generation += 1;
544
+ if (!this.#clearTimer())
444
545
  return;
445
- void this.#adoptConnectedTransport();
446
- return;
447
- }
448
- if (snapshot.host.realtime === 'connecting') {
449
- // An attempt is already in flight; the supervisor's own #connect (or
450
- // the host's direct call) owns the outcome.
451
- this.#transportConnected = false;
452
546
  this.#connected = false;
453
- return;
547
+ void this.#disconnect();
454
548
  }
455
- if (snapshot.host.realtime === 'disconnected' ||
456
- snapshot.host.realtime === 'lost' ||
457
- snapshot.host.realtime === 'refused') {
458
- this.#transportConnected = false;
459
- this.#connected = false;
460
- if (this.#connecting)
549
+ else if (realtime === 'connected') {
550
+ // A live socket is positive evidence that an earlier 'unsupported'
551
+ // report was transient (a mid-restart capability probe).
552
+ if (this.#failure)
461
553
  return;
462
- if (this.#initialized && !initial)
463
- this.#scheduleRetry();
464
- return;
465
- }
466
- this.#reconcileHostState();
467
- }
468
- #reconcileHostState() {
469
- if (this.#stopped)
470
- return;
471
- const block = this.#hostBlock();
472
- if (block) {
473
- this.#suspend(block);
474
- return;
475
- }
476
- if (!this.#initialized) {
477
- this.#publish({ phase: 'idle', attempt: 0 });
478
- return;
554
+ this.#supported = true;
555
+ this.#transport = true;
479
556
  }
480
- if (!this.#realtimeSupported) {
481
- this.#publish({ phase: 'unsupported', attempt: 0 });
482
- return;
483
- }
484
- if (this.#connected) {
485
- this.#publish({ phase: 'connected', attempt: 0 });
486
- return;
557
+ else if (realtime === 'disconnected' ||
558
+ realtime === 'lost' ||
559
+ realtime === 'refused') {
560
+ const held = this.#transport || this.#connected;
561
+ this.#transport = false;
562
+ this.#connected = false;
563
+ if (this.#supported && !this.#disconnecting && !initial) {
564
+ // The attempt in flight owns a loss during its catch-up; a report
565
+ // beside a pending retry keeps that retry's count.
566
+ if (!this.#attemptJob && (held || !this.#cancelTimer))
567
+ this.#retry();
568
+ }
487
569
  }
488
- this.#schedule(0);
489
- }
490
- #suspend(phase) {
491
- const disconnect = this.#connected || this.#transportConnected || this.#connecting;
492
- const hadScheduledWork = this.#cancelRetry !== undefined;
493
- const phaseChanged = this.#snapshot.phase !== phase;
494
- if (!disconnect && !hadScheduledWork && !phaseChanged)
495
- return;
496
- this.#generation += 1;
497
- this.#connected = false;
498
- this.#transportConnected = false;
499
- this.#connecting = false;
500
- this.#attempt = 0;
501
- this.#clearRetry();
502
- this.#publish({ phase, attempt: 0 });
503
- if (disconnect)
504
- this.#disconnect();
505
- }
506
- #disconnect() {
507
- void Promise.resolve(this.#client.disconnectRealtime()).catch(() => undefined);
570
+ this.#reconcile();
508
571
  }
509
572
  }
510
573
  /**
511
- * Install one supervisor and make client disposal cancel it before close.
512
- * A client accepts exactly one supervisor for its lifetime; installing a
513
- * second throws, because silently keeping the first would discard the second
514
- * call's options.
574
+ * Install one supervisor and make client disposal stop it before close.
575
+ * Repeated and reentrant `close()` calls share one operation. A client accepts
576
+ * exactly one supervisor for its lifetime; installing a second throws
577
+ * `realtime.supervisor_already_installed`, because silently keeping the first
578
+ * would discard the second call's options.
515
579
  */
516
580
  export function installRealtimeSupervisor(client, options) {
517
581
  if (attachment(client)) {
518
- throw new Error('installRealtimeSupervisor: this client already has a supervisor; ' +
519
- 'install one supervisor per client lifetime');
582
+ throw new ClientSyncError('realtime.supervisor_already_installed', 'realtime.supervisor_already_installed');
520
583
  }
521
584
  const supervisor = new RealtimeSupervisor(client, options);
585
+ // Non-writable, non-enumerable and non-configurable by default.
522
586
  Object.defineProperty(client, REALTIME_SUPERVISOR_KEY, {
523
- configurable: false,
524
- enumerable: false,
525
- writable: false,
526
587
  value: { version: 1, supervisor },
527
588
  });
528
589
  const close = client.close.bind(client);
590
+ let closing;
529
591
  Object.defineProperty(client, 'close', {
530
592
  configurable: true,
531
593
  writable: true,
532
- value: async () => {
533
- supervisor.stop();
534
- await close();
594
+ value: () => {
595
+ if (closing)
596
+ return closing;
597
+ let stopped;
598
+ closing = Promise.resolve().then(async () => {
599
+ const stopFailure = await stopped;
600
+ try {
601
+ await close();
602
+ }
603
+ catch (error) {
604
+ if (stopFailure === undefined)
605
+ throw error;
606
+ throw new RealtimeSupervisorError(stopFailure.code, {
607
+ ...stopFailure,
608
+ stopFailureCode: stopFailure.code,
609
+ closeFailureCode: causeCode(error),
610
+ });
611
+ }
612
+ if (stopFailure)
613
+ throw stopFailure;
614
+ });
615
+ // Reentrant closes during the synchronous stop share `closing`.
616
+ stopped = supervisor.stop().then(() => undefined, (error) => error);
617
+ return closing;
535
618
  },
536
619
  });
537
620
  supervisor.start();