@syncular/client 0.65.1 → 0.65.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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. Each
108
- * failed attempt, each host `online` report, and each foreground return
109
- * while no attempt starts at once drives one HTTP round (§1.8).
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,55 +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((state) => {
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();
164
224
  if (state === 'online')
165
225
  this.#drive();
166
- this.#reconcileHostState();
167
226
  });
168
- this.#unsubscribeLifecycle = this.#lifecycle?.subscribe((state) => {
169
- this.#reconcileHostState();
170
- // An immediate attempt brings its own round; a pending retry or an
171
- // absent socket does not.
172
- const phase = this.#snapshot.phase;
173
- if (state === 'active' &&
174
- (phase === 'retrying' || phase === 'unsupported')) {
227
+ const lifecycle = this.#lifecycle?.subscribe((state) => {
228
+ this.#reconcile();
229
+ if (state === 'active')
175
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);
176
249
  }
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();
177
262
  });
178
- this.#unsubscribeProtection = this.#protection?.subscribe(() => this.#reconcileHostState());
179
- this.#reconcileHostState();
180
- const generation = this.#generation;
181
- void this.#initialize(generation);
182
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
+ */
183
270
  stop() {
184
- if (this.#stopped)
185
- 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
+ });
186
282
  this.#stopped = true;
187
- this.#suspend('stopped');
188
- this.#unsubscribeDiagnostics?.();
189
- this.#unsubscribeConnectivity?.();
190
- this.#unsubscribeLifecycle?.();
191
- this.#unsubscribeProtection?.();
192
- this.#listeners.clear();
193
- }
194
- async #initialize(generation) {
195
- let snapshot;
196
- try {
197
- snapshot = await this.#client.diagnosticsSnapshot();
198
- }
199
- catch {
200
- // Protected or temporarily unavailable diagnostics must not become a
201
- // startup dependency. Explicit host gates and the connect result remain.
283
+ this.#generation += 1;
284
+ this.#clearTimer();
285
+ for (const unsubscribe of this.#unsubscribers.splice(0)) {
286
+ try {
287
+ unsubscribe();
288
+ }
289
+ catch {
290
+ this.#cleanupFailed();
291
+ }
202
292
  }
203
- if (generation !== this.#generation || this.#stopped)
204
- return;
205
- this.#initialized = true;
206
- if (snapshot !== undefined)
207
- this.#observeDiagnostics(snapshot, true);
208
- this.#reconcileHostState();
293
+ this.#publish({ phase: 'stopped', attempt: 0 });
294
+ void this.#disconnect();
295
+ return this.#stopping;
209
296
  }
210
- #hostBlock() {
297
+ #block() {
211
298
  const protection = this.#protection?.current();
212
299
  if (this.#diagnosticSecurity === 'preflight' ||
213
300
  protection === 'preflight' ||
@@ -225,29 +312,31 @@ export class RealtimeSupervisor {
225
312
  return undefined;
226
313
  }
227
314
  /**
228
- * §1.8: one HTTP round that re-arms the drive a refused fetch left behind.
229
- * It does not wait for the socket, so a socket that cannot connect does not
230
- * hold back the round.
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.
231
318
  */
232
319
  #drive() {
233
- if (this.#hostBlock())
320
+ if (this.#stopped || this.#connected || this.#block())
234
321
  return;
235
- void Promise.resolve()
322
+ if (this.#round) {
323
+ this.#roundAgain = true;
324
+ return;
325
+ }
326
+ this.#round = Promise.resolve()
236
327
  .then(() => this.#client.syncUntilIdle())
237
- .catch(() => undefined);
238
- }
239
- #canConnect() {
240
- return (this.#initialized &&
241
- !this.#stopped &&
242
- this.#realtimeSupported &&
243
- !this.#hostBlock());
328
+ .then(() => undefined, () => undefined)
329
+ .finally(() => {
330
+ this.#round = undefined;
331
+ if (!this.#roundAgain)
332
+ return;
333
+ this.#roundAgain = false;
334
+ this.#drive();
335
+ });
244
336
  }
245
337
  #publish(snapshot) {
246
- if (this.#snapshot.phase === snapshot.phase &&
247
- this.#snapshot.attempt === snapshot.attempt &&
248
- this.#snapshot.retryDelayMs === snapshot.retryDelayMs) {
338
+ if (JSON.stringify(this.#snapshot) === JSON.stringify(snapshot))
249
339
  return;
250
- }
251
340
  this.#snapshot = Object.freeze(snapshot);
252
341
  for (const listener of this.#listeners) {
253
342
  try {
@@ -258,266 +347,274 @@ export class RealtimeSupervisor {
258
347
  }
259
348
  }
260
349
  }
261
- #clearRetry() {
262
- this.#cancelRetry?.();
263
- 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);
264
355
  }
265
- /** A retry counts one attempt and backs off with bounded jitter. */
266
- #schedule(retry) {
267
- if (!this.#canConnect())
268
- return this.#reconcileHostState();
269
- // Count an attempt only when this call actually schedules one. Repeated
270
- // 'disconnected' diagnostics beside a pending retry keep the backoff and
271
- // the worker-mode reconnect nudge intact.
272
- if (this.#connected || this.#connecting || this.#cancelRetry)
273
- return;
274
- let delayMs = 0;
275
- if (retry) {
276
- const exponential = Math.min(this.#maximumDelayMs, this.#initialDelayMs * 2 ** this.#attempt);
277
- const random = this.#random();
278
- const boundedRandom = Number.isFinite(random)
279
- ? Math.max(0, Math.min(1, random))
280
- : 0;
281
- delayMs = Math.min(this.#maximumDelayMs, exponential + Math.floor(exponential * 0.25 * boundedRandom));
282
- this.#attempt = Math.min(32, this.#attempt + 1);
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;
283
367
  }
284
- this.#publish(retry
285
- ? { phase: 'retrying', attempt: this.#attempt, retryDelayMs: delayMs }
286
- : { phase: 'connecting', attempt: this.#attempt });
287
- this.#cancelRetry = this.#scheduleTimer(() => {
288
- this.#cancelRetry = undefined;
289
- void this.#connect();
290
- }, delayMs);
291
368
  }
292
- /**
293
- * A superseded attempt observed a generation bump mid-flight. Whenever a
294
- * newer generation is mid-connect or holds the transport, that generation
295
- * owns the shared socket and the stale attempt leaves every field alone.
296
- * With the supervisor otherwise quiescent (suspended or stopped), the
297
- * socket this attempt opened is unwanted — release it.
298
- */
299
- #releaseSupersededSocket() {
300
- if (this.#connecting || this.#connected || this.#transportConnected) {
369
+ /** Count one failed attempt and back off with bounded jitter, once per retry. */
370
+ #retry() {
371
+ if (this.#delayMs > 0)
301
372
  return;
373
+ const exponential = Math.min(this.#maximumDelayMs, this.#initialDelayMs * 2 ** this.#attempt);
374
+ const random = this.#random();
375
+ const boundedRandom = Number.isFinite(random)
376
+ ? Math.max(0, Math.min(1, random))
377
+ : 0;
378
+ this.#delayMs = Math.min(this.#maximumDelayMs, exponential + Math.floor(exponential * 0.25 * boundedRandom));
379
+ this.#attempt = Math.min(32, this.#attempt + 1);
380
+ }
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;
302
385
  }
303
- 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();
304
396
  }
305
- async #connect() {
306
- 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)
307
400
  return;
308
- const generation = this.#generation;
309
- this.#connecting = true;
310
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
311
- let failed = false;
312
- try {
313
- await this.#client.connectRealtime();
314
- if (generation !== this.#generation) {
315
- this.#releaseSupersededSocket();
316
- return;
317
- }
318
- this.#transportConnected = true;
319
- if (!this.#canConnect()) {
320
- this.#transportConnected = false;
321
- this.#disconnect();
322
- 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
+ }
323
410
  }
324
- await this.#catchUpConnectedTransport(generation);
325
- }
326
- catch (error) {
327
- if (generation !== this.#generation) {
328
- this.#releaseSupersededSocket();
411
+ if (!this.#clearTimer())
329
412
  return;
330
- }
331
- this.#gateClosed =
332
- error instanceof Error &&
333
- 'code' in error &&
334
- error.code === 'sync.offline';
335
- failed = true;
336
413
  this.#connected = false;
337
- this.#transportConnected = false;
338
- this.#disconnect();
414
+ this.#publish({ phase: block, attempt: this.#attempt });
415
+ void this.#disconnect();
416
+ return;
339
417
  }
340
- finally {
341
- // A superseded attempt leaves the successor's in-flight state alone.
342
- if (generation === this.#generation)
343
- this.#connecting = false;
418
+ if (!this.#supported) {
419
+ return this.#publish({ phase: 'unsupported', attempt: 0 });
344
420
  }
345
- if (failed && generation === this.#generation) {
346
- this.#schedule(true);
347
- this.#drive();
421
+ if (!this.#initialized) {
422
+ return this.#publish({ phase: 'idle', attempt: this.#attempt });
348
423
  }
349
- }
350
- async #catchUpConnectedTransport(generation) {
351
- await this.#client.syncUntilIdle();
352
- if (generation !== this.#generation) {
353
- this.#releaseSupersededSocket();
354
- return;
424
+ if (this.#connected) {
425
+ return this.#publish({ phase: 'connected', attempt: 0 });
355
426
  }
356
- if (!this.#canConnect() || !this.#transportConnected) {
357
- this.#disconnect();
427
+ if (this.#attemptJob || this.#disconnecting)
358
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();
359
434
  }
360
- this.#connected = true;
361
- this.#attempt = 0;
362
- this.#publish({ phase: 'connected', attempt: 0 });
363
- }
364
- async #adoptConnectedTransport() {
365
- if (!this.#canConnect() || this.#connecting || !this.#transportConnected) {
435
+ if (this.#cancelTimer)
366
436
  return;
367
- }
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() {
368
454
  const generation = this.#generation;
369
- this.#connecting = true;
370
- this.#clearRetry();
371
- this.#publish({ phase: 'connecting', attempt: this.#attempt });
372
- let failed = false;
455
+ this.#delayMs = 0;
456
+ this.#attemptJob = Promise.resolve().then(() => this.#connect(generation));
457
+ }
458
+ async #connect(generation) {
373
459
  try {
374
- await this.#catchUpConnectedTransport(generation);
375
- }
376
- catch {
377
- if (generation !== this.#generation) {
378
- this.#releaseSupersededSocket();
460
+ if (generation !== this.#generation)
379
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;
380
479
  }
381
- failed = true;
382
- this.#connected = false;
383
- this.#transportConnected = false;
384
- 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();
385
494
  }
386
495
  finally {
387
- // A superseded adoption leaves the successor's in-flight state alone.
388
- if (generation === this.#generation)
389
- 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();
500
+ }
501
+ }
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();
390
513
  }
391
- if (failed && generation === this.#generation)
392
- this.#schedule(true);
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;
393
530
  }
394
- #observeDiagnostics(snapshot, initial = false) {
531
+ #observe(snapshot, initial = false) {
395
532
  if (this.#stopped)
396
533
  return;
397
534
  this.#diagnosticSecurity = snapshot.securityLifecycle;
398
- if (snapshot.host.realtime === 'unsupported' ||
399
- snapshot.host.realtime === 'disabled') {
400
- this.#realtimeSupported = false;
401
- this.#suspend('unsupported');
402
- return;
403
- }
404
- if (!this.#realtimeSupported) {
405
- // A live socket is positive evidence the earlier 'unsupported' report
406
- // was transient (a mid-restart or mis-detected capability probe), so it
407
- // recovers the supervisor. Every other report keeps the latch closed.
408
- if (snapshot.host.realtime !== 'connected')
409
- return;
410
- this.#realtimeSupported = true;
411
- }
535
+ // A closed transport gate always reports offline, so any other report
536
+ // means the app reopened it.
412
537
  if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
413
- // A closed transport gate always reports offline, so any other report
414
- // means the app reopened it.
415
538
  this.#gateClosed = false;
416
- this.#reconcileHostState();
417
- return;
418
- }
419
- const block = this.#hostBlock();
420
- if (block) {
421
- this.#suspend(block);
422
- return;
423
539
  }
424
- if (snapshot.host.realtime === 'connected') {
425
- this.#transportConnected = true;
426
- // Steady state: diagnostics re-announce 'connected' on every sync
427
- // round and subscription change. An already-adopted transport keeps
428
- // its phase and skips the redundant catch-up.
429
- 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())
430
545
  return;
431
- void this.#adoptConnectedTransport();
432
- return;
433
- }
434
- if (snapshot.host.realtime === 'connecting') {
435
- // An attempt is already in flight; the supervisor's own #connect (or
436
- // the host's direct call) owns the outcome.
437
- this.#transportConnected = false;
438
546
  this.#connected = false;
439
- return;
547
+ void this.#disconnect();
440
548
  }
441
- if (snapshot.host.realtime === 'disconnected' ||
442
- snapshot.host.realtime === 'lost' ||
443
- snapshot.host.realtime === 'refused') {
444
- this.#transportConnected = false;
445
- this.#connected = false;
446
- 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)
447
553
  return;
448
- if (this.#initialized && !initial)
449
- this.#schedule(true);
450
- return;
451
- }
452
- this.#reconcileHostState();
453
- }
454
- #reconcileHostState() {
455
- if (this.#stopped)
456
- return;
457
- const block = this.#hostBlock();
458
- if (block) {
459
- this.#suspend(block);
460
- return;
554
+ this.#supported = true;
555
+ this.#transport = true;
461
556
  }
462
- if (!this.#initialized) {
463
- this.#publish({ phase: 'idle', attempt: 0 });
464
- return;
465
- }
466
- if (!this.#realtimeSupported) {
467
- this.#publish({ phase: 'unsupported', attempt: 0 });
468
- return;
469
- }
470
- if (this.#connected) {
471
- this.#publish({ phase: 'connected', attempt: 0 });
472
- return;
473
- }
474
- this.#schedule(false);
475
- }
476
- /** Cancel every attempt and release the socket, then publish `phase`. */
477
- #suspend(phase) {
478
- const disconnect = this.#connected || this.#transportConnected || this.#connecting;
479
- if (!disconnect && !this.#cancelRetry && this.#snapshot.phase === phase) {
480
- 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
+ }
481
569
  }
482
- this.#generation += 1;
483
- this.#connected = false;
484
- this.#transportConnected = false;
485
- this.#connecting = false;
486
- this.#attempt = 0;
487
- this.#clearRetry();
488
- this.#publish({ phase, attempt: 0 });
489
- if (disconnect)
490
- this.#disconnect();
491
- }
492
- #disconnect() {
493
- void Promise.resolve(this.#client.disconnectRealtime()).catch(() => undefined);
570
+ this.#reconcile();
494
571
  }
495
572
  }
496
573
  /**
497
- * Install one supervisor and make client disposal cancel it before close.
498
- * A client accepts exactly one supervisor for its lifetime; installing a
499
- * second throws, because silently keeping the first would discard the second
500
- * 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.
501
579
  */
502
580
  export function installRealtimeSupervisor(client, options) {
503
581
  if (attachment(client)) {
504
- throw new Error('installRealtimeSupervisor: this client already has a supervisor; ' +
505
- 'install one supervisor per client lifetime');
582
+ throw new ClientSyncError('realtime.supervisor_already_installed', 'realtime.supervisor_already_installed');
506
583
  }
507
584
  const supervisor = new RealtimeSupervisor(client, options);
585
+ // Non-writable, non-enumerable and non-configurable by default.
508
586
  Object.defineProperty(client, REALTIME_SUPERVISOR_KEY, {
509
- configurable: false,
510
- enumerable: false,
511
- writable: false,
512
587
  value: { version: 1, supervisor },
513
588
  });
514
589
  const close = client.close.bind(client);
590
+ let closing;
515
591
  Object.defineProperty(client, 'close', {
516
592
  configurable: true,
517
593
  writable: true,
518
- value: async () => {
519
- supervisor.stop();
520
- 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;
521
618
  },
522
619
  });
523
620
  supervisor.start();