@steve31415/baselib 3.59.0 → 3.60.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.
@@ -1,4 +1,5 @@
1
1
  import { FirstLoadRetry } from './first-load-retry.js';
2
+ import { CLOSE_HUB_IDLE, CLOSE_TRY_AGAIN_LATER, HUB_FLOOR_MS, HUB_HINT_DEBOUNCE_MS, HUB_PONG_TIMEOUT_MS, hubSocketUrl, parseHubFrame, } from './hub.js';
2
3
  const RECONNECT_DELAYS_SECONDS = [1, 2, 4, 8, 16, 30];
3
4
  const PING_INTERVAL_MS = 30_000;
4
5
  // Deliberate (2026-10-20 review, task 1e2cd274): todo's phone hit it 27
@@ -53,6 +54,9 @@ const SLOW_HANDSHAKE_MS = 3_000;
53
54
  const STALL_MIN_MS = 1_000;
54
55
  const SOCKET_CONNECTING = 0;
55
56
  const SOCKET_OPEN = 1;
57
+ /** Outage logs' `closeCode` when a failed app request, not a socket close,
58
+ * began the outage (hub mode). */
59
+ const APP_REQUEST_FAILED = 0;
56
60
  function messageType(raw) {
57
61
  try {
58
62
  return JSON.parse(raw)?.type;
@@ -150,8 +154,41 @@ export class SyncClient {
150
154
  backgroundSocketAttempts: 0,
151
155
  httpPostedEvents: 0,
152
156
  };
157
+ // Hub mode (null `hub`: same-origin, and none of these move). The socket
158
+ // fields above then hold the hub socket; the app's own reachability has
159
+ // its own ladder here, independent of the socket's.
160
+ hub;
161
+ /** The live hub socket answered our `connect`. */
162
+ hubAcked = false;
163
+ hubLastHeardAt = 0;
164
+ hubAwaitingPong = false;
165
+ /** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
166
+ appOk = true;
167
+ /** The app-request ladder's step, reset by any app success and on return. */
168
+ appAttempts = 0;
169
+ /** Visible app-request failures in this outage and spell, for its logs. */
170
+ appFailuresInOutage = 0;
171
+ appRetryTimer = null;
172
+ appRetryAt = null;
173
+ /** When the hub socket's ladder retries (its countdown, for the state). */
174
+ hubRetryAt = null;
175
+ floorTimer = null;
176
+ hintWindowTimer = null;
177
+ hintTrailing = false;
178
+ /** One catch-up may wait behind the one in flight. */
179
+ catchupQueued = false;
180
+ postInFlight = null;
181
+ /** An edit was submitted while a POST was in flight: post again after it. */
182
+ postAgain = false;
153
183
  constructor(options) {
154
184
  this.options = options;
185
+ if (!options.hubUrl) {
186
+ this.hub = null;
187
+ return;
188
+ }
189
+ if (!options.app || !options.postEvents)
190
+ throw new Error('sync hub mode needs app and postEvents');
191
+ this.hub = { socketUrl: hubSocketUrl(options.hubUrl, options.app), app: options.app, postEvents: options.postEvents };
155
192
  }
156
193
  init() {
157
194
  if (this.disposed)
@@ -222,6 +259,11 @@ export class SyncClient {
222
259
  return;
223
260
  this.installRuntimeListeners();
224
261
  this.connect();
262
+ if (this.hub) {
263
+ // Recovered edits go to the app at once, whatever the hub's state.
264
+ this.armFloor();
265
+ this.kickPost();
266
+ }
225
267
  }
226
268
  /** The first bootstrap. One that gets no HTTP answer (fetch's TypeError: no
227
269
  * network, or one that reaches nothing — a tab Android Chrome restored from
@@ -327,10 +369,19 @@ export class SyncClient {
327
369
  this.pending.set(event.eventGuid, entry);
328
370
  this.options.store.applyOptimistic(event);
329
371
  this.armFailureTimer(event.eventGuid);
330
- this.trySend(entry);
372
+ if (this.hub) {
373
+ // Every mutation goes over POST, one request in flight per tab.
374
+ if (this.postInFlight !== null)
375
+ this.postAgain = true;
376
+ else
377
+ this.kickPost();
378
+ }
379
+ else {
380
+ this.trySend(entry);
381
+ }
331
382
  // A visible page in an outage delivers over HTTP at once rather than
332
383
  // waiting for a handshake that may be stuck behind another one.
333
- if (!this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
384
+ if (!this.hub && !this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
334
385
  void this.probeSession();
335
386
  }
336
387
  this.updatePendingState();
@@ -359,7 +410,9 @@ export class SyncClient {
359
410
  this.options.onSafetyChange?.();
360
411
  }
361
412
  refreshConnectionForBuild() {
362
- if (this.halted || this.disposed)
413
+ // A hub socket is on no app instance: replacing every page's hub socket
414
+ // on every app deploy would be a reconnect storm for nothing.
415
+ if (this.halted || this.disposed || this.hub)
363
416
  return;
364
417
  this.options.logger.info('sync reconnect for traffic build');
365
418
  this.replaceSocket();
@@ -480,6 +533,18 @@ export class SyncClient {
480
533
  if (this.connectReplyTimer !== null)
481
534
  this.options.runtime.clearTimeout(this.connectReplyTimer);
482
535
  this.connectReplyTimer = null;
536
+ if (this.hub) {
537
+ // No app-request ladder and no floor while hidden. A tab that keeps
538
+ // its hub socket acts on hints and also runs the 5-minute tick, in
539
+ // case a hint was lost; it was current a moment ago.
540
+ this.cancelAppRetry();
541
+ this.cancelFloor();
542
+ if (this.socket !== null) {
543
+ this.lastTickAt = this.now();
544
+ this.armBackgroundTick();
545
+ this.refreshHubState();
546
+ }
547
+ }
483
548
  // A ladder waiting to retry is cancelled: no reconnects while hidden.
484
549
  if (this.socket === null)
485
550
  this.enterDormant();
@@ -506,11 +571,17 @@ export class SyncClient {
506
571
  // (a phone shown for a second, often before its network is back) must
507
572
  // not stretch this return's retry to 8-30 s or add up to a WARN.
508
573
  this.reconnectAttempts = 0;
574
+ this.appAttempts = 0;
575
+ this.appFailuresInOutage = 0;
509
576
  }
510
577
  this.wakeConnection();
511
578
  // Always: a socket that looks open may be dead (review S2), and a
512
579
  // handshake may be slow. One HTTP round trip makes the page current.
513
580
  void this.runCatchup('return');
581
+ if (this.hub) {
582
+ this.armFloor();
583
+ this.kickPost();
584
+ }
514
585
  }
515
586
  onOnline() {
516
587
  if (this.halted || this.disposed)
@@ -524,15 +595,26 @@ export class SyncClient {
524
595
  return;
525
596
  }
526
597
  this.wakeConnection();
598
+ if (this.hub && !this.appOk) {
599
+ this.cancelAppRetry();
600
+ void this.retryAppRequest();
601
+ }
527
602
  }
528
603
  wakeConnection() {
529
604
  if (this.halted || this.disposed)
530
605
  return;
531
606
  const socket = this.socket;
532
607
  if (socket?.readyState === SOCKET_OPEN) {
533
- this.sendConnect();
534
- // A socket that looks open may be half-dead: no catch-up reply in 5 s
535
- // replaces it.
608
+ if (this.hub) {
609
+ // Ask the hub at once: any frame within 5 s says the socket lives.
610
+ this.sendRaw({ type: 'ping' });
611
+ this.hubAwaitingPong = true;
612
+ }
613
+ else {
614
+ this.sendConnect();
615
+ }
616
+ // A socket that looks open may be half-dead: no catch-up reply (hub
617
+ // mode: no frame at all) in 5 s replaces it.
536
618
  if (this.connectReplyTimer !== null)
537
619
  this.options.runtime.clearTimeout(this.connectReplyTimer);
538
620
  this.connectReplyTimer = this.setTimer(() => {
@@ -572,6 +654,7 @@ export class SyncClient {
572
654
  replaceSocket() {
573
655
  const previous = this.socket;
574
656
  this.socket = null;
657
+ this.hubAcked = false;
575
658
  this.clearConnectionTimers();
576
659
  this.dropCandidate();
577
660
  if (previous) {
@@ -583,12 +666,14 @@ export class SyncClient {
583
666
  connect() {
584
667
  if (this.halted || this.disposed)
585
668
  return;
586
- this.publish(this.reconnectAttempts > 0
587
- ? { kind: 'disconnected', pending: this.pendingCount() }
588
- : { kind: 'connecting', pending: this.pendingCount() });
669
+ if (!this.hub) {
670
+ this.publish(this.reconnectAttempts > 0
671
+ ? { kind: 'disconnected', pending: this.pendingCount() }
672
+ : { kind: 'connecting', pending: this.pendingCount() });
673
+ }
589
674
  let socket;
590
675
  try {
591
- socket = this.options.runtime.createSocket(this.options.socketUrl());
676
+ socket = this.options.runtime.createSocket(this.socketUrl());
592
677
  }
593
678
  catch (error) {
594
679
  this.options.logger.warn('socket creation failed', { error });
@@ -600,6 +685,8 @@ export class SyncClient {
600
685
  return;
601
686
  }
602
687
  this.socket = socket;
688
+ this.hubAcked = false;
689
+ this.refreshHubState();
603
690
  this.socketCreatedAt = this.options.runtime.now();
604
691
  this.socketCreatedHidden = this.isHidden();
605
692
  this.socketOpenedAt = null;
@@ -631,7 +718,14 @@ export class SyncClient {
631
718
  hidden: this.isHidden(),
632
719
  });
633
720
  }
634
- this.cancelBackgroundTick();
721
+ if (this.hub) {
722
+ // A hidden tab with a hub socket keeps its 5-minute tick.
723
+ this.hubLastHeardAt = this.now();
724
+ this.hubAwaitingPong = false;
725
+ }
726
+ else {
727
+ this.cancelBackgroundTick();
728
+ }
635
729
  this.sendConnect();
636
730
  this.startLiveTimers();
637
731
  };
@@ -644,7 +738,7 @@ export class SyncClient {
644
738
  if (this.socket !== socket)
645
739
  return;
646
740
  this.lastContactAt = this.now();
647
- this.handleMessage(String(event.data));
741
+ this.dispatchMessage(String(event.data));
648
742
  };
649
743
  socket.onerror = () => {
650
744
  // Browsers expose no useful detail; the close event owns recovery.
@@ -654,6 +748,7 @@ export class SyncClient {
654
748
  return;
655
749
  this.clearConnectionTimers();
656
750
  this.socket = null;
751
+ this.hubAcked = false;
657
752
  if (this.halted || this.disposed)
658
753
  return;
659
754
  const socketAgeMs = this.now() - this.socketCreatedAt;
@@ -666,20 +761,27 @@ export class SyncClient {
666
761
  });
667
762
  }
668
763
  if (event.code === CLOSE_NO_USER) {
669
- this.options.authState.markBlocked();
670
- this.halt();
671
- return;
764
+ if (!this.hub) {
765
+ this.options.authState.markBlocked();
766
+ this.halt();
767
+ return;
768
+ }
769
+ // Hub mode: the hub found no identity. The app decides whether the
770
+ // session is gone (its auth failure halts through the auth state);
771
+ // if it answers, the ladder below reconnects.
772
+ void this.runCatchup('probe');
672
773
  }
673
774
  const openForMs = this.socketOpenedAt === null ? null : Math.max(0, this.now() - this.socketOpenedAt);
674
775
  // Ended before its replacement took over: start afresh rather than wait
675
776
  // on a handshake begun for a handover.
676
777
  const rolling = this.candidate !== null;
677
778
  this.dropCandidate();
678
- if (event.code === CLOSE_SERVICE_RESTART) {
779
+ if (event.code === CLOSE_SERVICE_RESTART || this.isQuietHubClose(event.code)) {
679
780
  // The server's planned close (its age cap: a tab whose own rollover
680
781
  // didn't run, such as a frozen one): reconnect at once, as after our
681
782
  // own rollover, with no outage and no ladder step. A failure of that
682
- // reconnect is an ordinary outage.
783
+ // reconnect is an ordinary outage. The hub's 1013 (its auth check
784
+ // was unavailable) and 4408 (it heard nothing for 180 s) are the same.
683
785
  this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
684
786
  this.connectNow();
685
787
  return;
@@ -698,7 +800,7 @@ export class SyncClient {
698
800
  };
699
801
  }
700
802
  startLiveTimers() {
701
- this.pingTimer = this.setRepeating(() => this.sendRaw({ type: 'ping' }), PING_INTERVAL_MS);
803
+ this.pingTimer = this.setRepeating(() => (this.hub ? this.hubPingTick() : this.sendRaw({ type: 'ping' })), PING_INTERVAL_MS);
702
804
  this.armRollover();
703
805
  }
704
806
  armRollover() {
@@ -724,7 +826,7 @@ export class SyncClient {
724
826
  return;
725
827
  let socket;
726
828
  try {
727
- socket = this.options.runtime.createSocket(this.options.socketUrl());
829
+ socket = this.options.runtime.createSocket(this.socketUrl());
728
830
  }
729
831
  catch (error) {
730
832
  this.options.logger.warn('socket creation failed', { error });
@@ -765,30 +867,36 @@ export class SyncClient {
765
867
  return;
766
868
  const raw = String(event.data);
767
869
  const type = messageType(raw);
768
- if (type !== 'catchup' && type !== 'reload') {
870
+ // The hub answers `connect` with `ack` (it sends no catch-up).
871
+ const answered = this.hub ? type === 'ack' : type === 'catchup' || type === 'reload';
872
+ if (!answered) {
769
873
  candidate.early.push(raw);
770
874
  return;
771
875
  }
772
876
  this.promoteCandidate(candidate);
773
877
  this.lastContactAt = this.now();
774
- this.handleMessage(raw);
878
+ this.dispatchMessage(raw);
775
879
  for (const early of candidate.early) {
776
880
  if (this.socket !== socket)
777
881
  return;
778
- this.handleMessage(early);
882
+ this.dispatchMessage(early);
779
883
  }
780
884
  };
781
885
  socket.onerror = () => { };
782
886
  socket.onclose = (event) => {
783
887
  if (this.candidate !== candidate)
784
888
  return;
785
- if (event.code === CLOSE_NO_USER) {
889
+ if (event.code === CLOSE_NO_USER && !this.hub) {
786
890
  this.dropCandidate();
787
891
  this.options.authState.markBlocked();
788
892
  this.halt();
789
893
  return;
790
894
  }
791
895
  this.dropCandidate({ closeCode: event.code });
896
+ // Hub mode: the live socket keeps serving; the app decides whether the
897
+ // session is gone.
898
+ if (event.code === CLOSE_NO_USER)
899
+ void this.runCatchup('probe');
792
900
  };
793
901
  }
794
902
  promoteCandidate(candidate) {
@@ -807,6 +915,8 @@ export class SyncClient {
807
915
  this.socketCreatedAt = candidate.createdAt;
808
916
  this.socketCreatedHidden = candidate.createdHidden;
809
917
  this.socketOpenedAt = candidate.openedAt;
918
+ this.hubLastHeardAt = now;
919
+ this.hubAwaitingPong = false;
810
920
  candidate.socket.onopen = null;
811
921
  this.attachLiveHandlers(candidate.socket, () => false);
812
922
  this.startLiveTimers();
@@ -847,11 +957,16 @@ export class SyncClient {
847
957
  this.options.runtime.clearInterval(this.countdownTimer);
848
958
  this.reconnectTimer = null;
849
959
  this.countdownTimer = null;
960
+ this.hubRetryAt = null;
961
+ this.cancelAppRetry();
850
962
  this.publish({ kind: 'disconnected', pending: this.pendingCount() });
851
963
  if (!this.options.postEvents && !this.beaconedWhileDormant && this.unsettledPending().length > 0) {
852
964
  this.beaconedWhileDormant = true;
853
965
  this.flushViaBeacon();
854
966
  }
967
+ this.armBackgroundTick();
968
+ }
969
+ armBackgroundTick() {
855
970
  if (this.backgroundTickTimer !== null)
856
971
  return;
857
972
  const interval = this.options.backgroundCatchupMs ?? DEFAULT_BACKGROUND_CATCHUP_MS;
@@ -867,17 +982,28 @@ export class SyncClient {
867
982
  this.backgroundTickTimer = null;
868
983
  }
869
984
  async backgroundTick() {
870
- if (this.halted || this.disposed || !this.isHidden() || this.socket !== null)
985
+ if (this.halted || this.disposed || !this.isHidden())
986
+ return;
987
+ // Same-origin: a live socket is the page's feed. Hub mode: hints can be
988
+ // lost, so the tick runs beside the hub socket too (design §5.5).
989
+ if (!this.hub && this.socket !== null)
871
990
  return;
872
991
  this.lastTickAt = this.now();
873
992
  await this.postPendingOverHttp();
874
993
  const ok = await this.runCatchup('background');
875
- if (this.halted || this.disposed || !this.isHidden() || this.socket !== null)
994
+ if (this.halted || this.disposed || !this.isHidden())
995
+ return;
996
+ if (this.socket !== null) {
997
+ if (this.hub)
998
+ this.armBackgroundTick();
876
999
  return;
1000
+ }
877
1001
  if (ok && !this.hiddenSocketFailed) {
878
1002
  // Desktop hidden sockets usually live; one attempt per tick, none after
879
1003
  // the first hidden failure in this spell (phones cut them in seconds).
880
1004
  this.connectNow();
1005
+ if (this.hub)
1006
+ this.armBackgroundTick();
881
1007
  return;
882
1008
  }
883
1009
  this.enterDormant();
@@ -886,6 +1012,8 @@ export class SyncClient {
886
1012
  return [...this.pending.values()].filter((entry) => !this.settledPending.has(entry.event.eventGuid));
887
1013
  }
888
1014
  async postPendingOverHttp() {
1015
+ if (this.hub)
1016
+ return this.runPost();
889
1017
  const postEvents = this.options.postEvents;
890
1018
  if (!postEvents)
891
1019
  return;
@@ -918,19 +1046,27 @@ export class SyncClient {
918
1046
  // Offline or timed out: the next tick, or the socket on return, retries.
919
1047
  }
920
1048
  }
921
- /** The background/return catch-up (review S5): one slot, a return aborts
922
- * a background fetch in flight, both give up after 15 s. */
1049
+ /** The HTTP catch-up (review S5): one slot, a return aborts any other
1050
+ * kind in flight, every kind gives up after 15 s. Hub mode: a request that
1051
+ * finds the slot busy queues one more catch-up to start when it frees (one
1052
+ * in flight, at most one queued), and the outcome feeds the app-request
1053
+ * ladder. */
923
1054
  async runCatchup(kind) {
924
1055
  if (this.halted || this.disposed)
925
1056
  return false;
926
1057
  if (this.catchupSlot !== null) {
927
- if (kind === 'return' && this.catchupSlot.kind === 'background')
1058
+ if (kind === 'return' && this.catchupSlot.kind !== 'return') {
1059
+ this.catchupSlot.preempted = true;
928
1060
  this.catchupSlot.controller.abort();
929
- else
1061
+ }
1062
+ else {
1063
+ if (this.hub)
1064
+ this.catchupQueued = true;
930
1065
  return false;
1066
+ }
931
1067
  }
932
1068
  const controller = new AbortController();
933
- const slot = { kind, controller };
1069
+ const slot = { kind, controller, preempted: false };
934
1070
  this.catchupSlot = slot;
935
1071
  this.abortControllers.add(controller);
936
1072
  const timeout = this.setTimer(() => controller.abort(), BACKGROUND_FETCH_TIMEOUT_MS);
@@ -952,6 +1088,8 @@ export class SyncClient {
952
1088
  for (const event of result.events)
953
1089
  this.handleServerEvent(event);
954
1090
  }
1091
+ if (this.hub)
1092
+ this.appSucceeded();
955
1093
  return true;
956
1094
  }
957
1095
  catch {
@@ -973,6 +1111,15 @@ export class SyncClient {
973
1111
  this.returnWindow.catchupOk = ok;
974
1112
  this.maybeFinishReturnWindow();
975
1113
  }
1114
+ if (this.hub) {
1115
+ // A catch-up a return replaced did not fail.
1116
+ if (!ok && !slot.preempted)
1117
+ this.appFailed();
1118
+ if (this.catchupQueued && this.catchupSlot === null) {
1119
+ this.catchupQueued = false;
1120
+ void this.runCatchup('hint');
1121
+ }
1122
+ }
976
1123
  }
977
1124
  }
978
1125
  async withTimeout(operation) {
@@ -1047,6 +1194,7 @@ export class SyncClient {
1047
1194
  this.options.runtime.clearInterval(this.countdownTimer);
1048
1195
  this.reconnectTimer = null;
1049
1196
  this.countdownTimer = null;
1197
+ this.hubRetryAt = null;
1050
1198
  this.connect();
1051
1199
  }
1052
1200
  /** Records a visible socket failure inside a return window. */
@@ -1080,6 +1228,18 @@ export class SyncClient {
1080
1228
  const delay = Math.ceil(delayMs / 1000);
1081
1229
  this.reconnectAttempts++;
1082
1230
  this.totalAttempts++;
1231
+ if (this.hub) {
1232
+ // The hub socket's ladder. App requests have their own and need no
1233
+ // probe from here; the state shows whichever retry comes first.
1234
+ this.hubRetryAt = this.now() + delayMs;
1235
+ this.reconnectTimer = this.setTimer(() => {
1236
+ this.reconnectTimer = null;
1237
+ this.hubRetryAt = null;
1238
+ this.connect();
1239
+ }, delayMs);
1240
+ this.refreshHubState();
1241
+ return;
1242
+ }
1083
1243
  if (this.reconnectAttempts >= PROBE_AFTER_ATTEMPTS || this.unsettledPending().length > 0) {
1084
1244
  void this.probeSession();
1085
1245
  }
@@ -1178,6 +1338,12 @@ export class SyncClient {
1178
1338
  }
1179
1339
  }, OUTAGE_ESCALATE_MS);
1180
1340
  }
1341
+ dispatchMessage(raw) {
1342
+ if (this.hub)
1343
+ this.handleHubMessage(raw, this.hub.app);
1344
+ else
1345
+ this.handleMessage(raw);
1346
+ }
1181
1347
  handleMessage(raw) {
1182
1348
  let message;
1183
1349
  try {
@@ -1490,7 +1656,8 @@ export class SyncClient {
1490
1656
  // Failures are only counted (and the ladder only runs) while visible,
1491
1657
  // and the count restarts on each return, so `attempts` is what the
1492
1658
  // user could have waited through; `totalAttempts` spans every spell.
1493
- const attempts = this.reconnectAttempts;
1659
+ // Hub mode counts the hub socket's and the app's failures together.
1660
+ const attempts = this.reconnectAttempts + this.appFailuresInOutage;
1494
1661
  const info = this.outageInfo;
1495
1662
  const delta = info ? SyncClient.delta(info.counters, this.snapshot()) : null;
1496
1663
  const fields = {
@@ -1534,6 +1701,7 @@ export class SyncClient {
1534
1701
  this.escalateTimer = null;
1535
1702
  this.reconnectAttempts = 0;
1536
1703
  this.totalAttempts = 0;
1704
+ this.appFailuresInOutage = 0;
1537
1705
  for (const [eventGuid, entry] of this.pending) {
1538
1706
  if (this.settledPending.has(eventGuid)) {
1539
1707
  this.retrySettlement(eventGuid);
@@ -1545,7 +1713,10 @@ export class SyncClient {
1545
1713
  // A complete catch-up IS convergence: end any stall episode and cancel
1546
1714
  // its pending backoff retry.
1547
1715
  this.endResyncEpisode();
1548
- this.updateConnectedState();
1716
+ if (this.hub)
1717
+ this.refreshHubState();
1718
+ else
1719
+ this.updateConnectedState();
1549
1720
  }
1550
1721
  requestReload(reason) {
1551
1722
  // While a resync is reconciling or backing off, further triggers are
@@ -1677,8 +1848,14 @@ export class SyncClient {
1677
1848
  this.sendRaw(this.connectMessage());
1678
1849
  }
1679
1850
  connectMessage() {
1851
+ // The hub routes by user and never sees sequences.
1852
+ if (this.hub)
1853
+ return { type: 'connect', clientGuid: this.options.clientGuid };
1680
1854
  return { type: 'connect', clientGuid: this.options.clientGuid, lastSeq: this.options.store.currentSeq() };
1681
1855
  }
1856
+ socketUrl() {
1857
+ return this.hub?.socketUrl ?? this.options.socketUrl();
1858
+ }
1682
1859
  sendRaw(message) {
1683
1860
  if (this.socket?.readyState !== SOCKET_OPEN)
1684
1861
  return;
@@ -1692,6 +1869,11 @@ export class SyncClient {
1692
1869
  trySend(entry) {
1693
1870
  if (this.settledPending.has(entry.event.eventGuid))
1694
1871
  return;
1872
+ // Hub mode: nothing mutating ever goes on the hub socket.
1873
+ if (this.hub) {
1874
+ this.kickPost();
1875
+ return;
1876
+ }
1695
1877
  this.sendRaw({ type: 'event', clientGuid: this.options.clientGuid, event: entry.event });
1696
1878
  }
1697
1879
  flushViaBeacon() {
@@ -1709,7 +1891,7 @@ export class SyncClient {
1709
1891
  this.options.runtime.sendBeacon(this.options.beaconUrl, new Blob([body], { type: 'application/json' }));
1710
1892
  }
1711
1893
  updateConnectedState() {
1712
- if (this.halted || this.disposed || this.socket?.readyState !== SOCKET_OPEN)
1894
+ if (this.halted || this.disposed || !this.isLive())
1713
1895
  return;
1714
1896
  const pending = this.pendingCount();
1715
1897
  this.publish(pending > 0 ? { kind: 'syncing', pending } : { kind: 'connected', pending: 0 });
@@ -1717,7 +1899,7 @@ export class SyncClient {
1717
1899
  updatePendingState() {
1718
1900
  if (this.halted || this.disposed)
1719
1901
  return;
1720
- if (this.socket?.readyState === SOCKET_OPEN) {
1902
+ if (this.isLive()) {
1721
1903
  this.updateConnectedState();
1722
1904
  return;
1723
1905
  }
@@ -1805,6 +1987,12 @@ export class SyncClient {
1805
1987
  for (const timer of this.failureTimers.values())
1806
1988
  this.options.runtime.clearTimeout(timer);
1807
1989
  this.cancelBackgroundTick();
1990
+ this.cancelAppRetry();
1991
+ this.cancelFloor();
1992
+ if (this.hintWindowTimer !== null)
1993
+ this.options.runtime.clearTimeout(this.hintWindowTimer);
1994
+ this.hintWindowTimer = null;
1995
+ this.hubRetryAt = null;
1808
1996
  if (this.returnWindow !== null)
1809
1997
  this.options.runtime.clearTimeout(this.returnWindow.timer);
1810
1998
  this.returnWindow = null;
@@ -1814,6 +2002,262 @@ export class SyncClient {
1814
2002
  this.resyncBackoffTimer = null;
1815
2003
  this.failureTimers.clear();
1816
2004
  }
2005
+ /** Live: the socket is open and, in hub mode, the hub answered our
2006
+ * `connect` and the last app request succeeded (a pong overdue replaces
2007
+ * the socket, so an open one has been heard from recently). */
2008
+ isLive() {
2009
+ if (this.socket?.readyState !== SOCKET_OPEN)
2010
+ return false;
2011
+ return this.hub === null || (this.hubAcked && this.appOk);
2012
+ }
2013
+ isQuietHubClose(code) {
2014
+ return this.hub !== null && (code === CLOSE_TRY_AGAIN_LATER || code === CLOSE_HUB_IDLE);
2015
+ }
2016
+ /** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
2017
+ * to whichever ladder (hub socket or app request) retries first; otherwise
2018
+ * `connecting`, or `disconnected` once something has failed. */
2019
+ refreshHubState() {
2020
+ if (!this.hub || this.halted || this.disposed)
2021
+ return;
2022
+ const retries = [this.hubRetryAt, this.appRetryAt].filter((at) => at !== null);
2023
+ const live = this.isLive();
2024
+ if ((live || retries.length === 0) && this.countdownTimer !== null) {
2025
+ this.options.runtime.clearInterval(this.countdownTimer);
2026
+ this.countdownTimer = null;
2027
+ }
2028
+ if (live) {
2029
+ this.updateConnectedState();
2030
+ return;
2031
+ }
2032
+ const pending = this.pendingCount();
2033
+ if (retries.length > 0) {
2034
+ const inSeconds = Math.max(1, Math.ceil((Math.min(...retries) - this.now()) / 1000));
2035
+ this.publish({ kind: 'reconnecting', pending, inSeconds });
2036
+ if (this.countdownTimer === null)
2037
+ this.countdownTimer = this.setRepeating(() => this.refreshHubState(), 1000);
2038
+ return;
2039
+ }
2040
+ const failed = this.reconnectAttempts > 0 || this.appAttempts > 0 || this.socket === null;
2041
+ this.publish({ kind: failed ? 'disconnected' : 'connecting', pending });
2042
+ }
2043
+ handleHubMessage(raw, app) {
2044
+ // Any frame is a sign of life (radar's rule): the pong watchdog and the
2045
+ // return's 5 s check.
2046
+ this.hubLastHeardAt = this.now();
2047
+ this.hubAwaitingPong = false;
2048
+ if (this.connectReplyTimer !== null)
2049
+ this.options.runtime.clearTimeout(this.connectReplyTimer);
2050
+ this.connectReplyTimer = null;
2051
+ const frame = parseHubFrame(raw, app);
2052
+ switch (frame.kind) {
2053
+ case 'unparseable':
2054
+ this.options.logger.warn('unparseable hub message', { raw: raw.slice(0, 200) });
2055
+ return;
2056
+ case 'ack':
2057
+ this.onHubAck();
2058
+ return;
2059
+ case 'sync_available':
2060
+ this.onSyncHint();
2061
+ return;
2062
+ case 'build_changed':
2063
+ this.options.onBuildChanged?.();
2064
+ return;
2065
+ case 'life':
2066
+ return;
2067
+ }
2068
+ }
2069
+ /** The hub routes hints to this socket from now on. Established still
2070
+ * needs a catch-up that began after this (design §5.4); one queues behind
2071
+ * a catch-up already in flight. */
2072
+ onHubAck() {
2073
+ if (this.hubAcked)
2074
+ return;
2075
+ this.hubAcked = true;
2076
+ this.refreshHubState();
2077
+ void this.runCatchup('connect');
2078
+ }
2079
+ /** Two missed pongs replace the socket like a rollover (no outage); hints
2080
+ * sent to it meanwhile are lost, and the new socket's ack catches up. */
2081
+ hubPingTick() {
2082
+ const now = this.now();
2083
+ if (this.hubAwaitingPong && now - this.hubLastHeardAt >= HUB_PONG_TIMEOUT_MS) {
2084
+ this.options.logger.info('hub pong timeout', {
2085
+ silentForMs: now - this.hubLastHeardAt,
2086
+ openForMs: this.socketOpenedAt === null ? null : Math.max(0, now - this.socketOpenedAt),
2087
+ });
2088
+ this.replaceSocket();
2089
+ return;
2090
+ }
2091
+ this.sendRaw({ type: 'ping' });
2092
+ this.hubAwaitingPong = true;
2093
+ }
2094
+ /** `sync_available`: leading-edge debounce. The first hint catches up at
2095
+ * once; hints in the next 500 ms fold into one trailing catch-up. */
2096
+ onSyncHint() {
2097
+ if (this.hintWindowTimer !== null) {
2098
+ this.hintTrailing = true;
2099
+ return;
2100
+ }
2101
+ void this.runCatchup('hint');
2102
+ this.openHintWindow();
2103
+ }
2104
+ openHintWindow() {
2105
+ this.hintWindowTimer = this.setTimer(() => {
2106
+ this.hintWindowTimer = null;
2107
+ if (!this.hintTrailing)
2108
+ return;
2109
+ this.hintTrailing = false;
2110
+ void this.runCatchup('hint');
2111
+ this.openHintWindow();
2112
+ }, HUB_HINT_DEBOUNCE_MS);
2113
+ }
2114
+ /** While visible, a catch-up at least every 2 minutes whatever the hub
2115
+ * socket's state; any successful app request restarts the wait. */
2116
+ armFloor() {
2117
+ if (!this.hub || this.halted || this.disposed || this.isHidden())
2118
+ return;
2119
+ this.cancelFloor();
2120
+ this.floorTimer = this.setTimer(() => {
2121
+ this.floorTimer = null;
2122
+ void this.runCatchup('floor');
2123
+ }, HUB_FLOOR_MS);
2124
+ }
2125
+ cancelFloor() {
2126
+ if (this.floorTimer !== null)
2127
+ this.options.runtime.clearTimeout(this.floorTimer);
2128
+ this.floorTimer = null;
2129
+ }
2130
+ appSucceeded() {
2131
+ this.appOk = true;
2132
+ this.appAttempts = 0;
2133
+ this.cancelAppRetry();
2134
+ this.armFloor();
2135
+ if (this.hubAcked && this.socket?.readyState === SOCKET_OPEN)
2136
+ this.onSyncEstablished();
2137
+ else
2138
+ this.refreshHubState();
2139
+ }
2140
+ /** A POST or catch-up got no usable answer: the outage starts (if it had
2141
+ * not), and a visible page retries on the app-request ladder whatever the
2142
+ * hub socket's state. An expired session halts instead. */
2143
+ appFailed() {
2144
+ if (this.stopBeforeStoreMutation())
2145
+ return;
2146
+ this.appOk = false;
2147
+ this.startOutage(APP_REQUEST_FAILED);
2148
+ if (!this.isHidden()) {
2149
+ this.appFailuresInOutage++;
2150
+ this.scheduleAppRetry();
2151
+ }
2152
+ this.refreshHubState();
2153
+ }
2154
+ /** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
2155
+ * already scheduled stands. */
2156
+ scheduleAppRetry() {
2157
+ if (this.appRetryTimer !== null || this.isHidden() || this.halted || this.disposed)
2158
+ return;
2159
+ const ladderSeconds = RECONNECT_DELAYS_SECONDS[Math.min(this.appAttempts, RECONNECT_DELAYS_SECONDS.length - 1)];
2160
+ const delayMs = this.takeQuickRetry() ? RETURN_QUICK_RETRY_MS : ladderSeconds * 1000;
2161
+ this.appAttempts++;
2162
+ this.totalAttempts++;
2163
+ this.appRetryAt = this.now() + delayMs;
2164
+ this.appRetryTimer = this.setTimer(() => {
2165
+ this.appRetryTimer = null;
2166
+ this.appRetryAt = null;
2167
+ void this.retryAppRequest();
2168
+ }, delayMs);
2169
+ }
2170
+ cancelAppRetry() {
2171
+ if (this.appRetryTimer !== null)
2172
+ this.options.runtime.clearTimeout(this.appRetryTimer);
2173
+ this.appRetryTimer = null;
2174
+ this.appRetryAt = null;
2175
+ }
2176
+ /** A POST when edits are unsettled (its response carries the catch-up),
2177
+ * else a catch-up. */
2178
+ async retryAppRequest() {
2179
+ if (this.unsettledPending().length > 0)
2180
+ await this.runPost();
2181
+ else
2182
+ await this.runCatchup('retry');
2183
+ }
2184
+ /** Re-send paths (established, resync, return): post the unsettled edits
2185
+ * unless a POST is already in flight. */
2186
+ kickPost() {
2187
+ if (this.postInFlight === null)
2188
+ void this.runPost();
2189
+ }
2190
+ /** Hub mode's mutation path: every unsettled edit in one POST, one POST in
2191
+ * flight per tab. An edit submitted meanwhile posts after it succeeds; a
2192
+ * failure leaves the retry to the app-request ladder. */
2193
+ runPost() {
2194
+ if (this.postInFlight !== null)
2195
+ return this.postInFlight;
2196
+ const events = this.unsettledPending().map((entry) => entry.event);
2197
+ if (!this.hub || events.length === 0 || this.halted || this.disposed)
2198
+ return Promise.resolve();
2199
+ this.postAgain = false;
2200
+ const inFlight = this.postOnce(this.hub.postEvents, events).finally(() => {
2201
+ this.postInFlight = null;
2202
+ if (this.postAgain && this.appOk) {
2203
+ this.postAgain = false;
2204
+ this.kickPost();
2205
+ }
2206
+ });
2207
+ this.postInFlight = inFlight;
2208
+ return inFlight;
2209
+ }
2210
+ async postOnce(postEvents, events) {
2211
+ let response;
2212
+ try {
2213
+ response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
2214
+ }
2215
+ catch {
2216
+ this.appFailed();
2217
+ return;
2218
+ }
2219
+ if (this.stopBeforeStoreMutation())
2220
+ return;
2221
+ this.lastContactAt = this.now();
2222
+ this.applyPostResponse(response);
2223
+ if (this.stopBeforeStoreMutation())
2224
+ return;
2225
+ this.appSucceeded();
2226
+ // An app answering in the old shape sent no frames: the echoes come by
2227
+ // catch-up, as for a same-origin POST.
2228
+ if (response.currentSeq === undefined && !response.reload)
2229
+ void this.runCatchup('connect');
2230
+ }
2231
+ /** The catch-up slice first: contiguous from the request's `lastSeq`, it
2232
+ * carries the own events in order with any writer that interleaved, so no
2233
+ * forward gap trips a resync. Then the outcomes: frames confirm their
2234
+ * pending entry by GUID even at or below the tab's sequence (a resync may
2235
+ * have moved it past them, review round 2 B1); rejections settle as on
2236
+ * the socket. */
2237
+ applyPostResponse(response) {
2238
+ if (response.reload) {
2239
+ this.requestReload('server');
2240
+ }
2241
+ else {
2242
+ for (const event of response.events ?? [])
2243
+ this.handleServerEvent(event);
2244
+ }
2245
+ for (const outcome of response.outcomes) {
2246
+ if (this.stopBeforeStoreMutation())
2247
+ return;
2248
+ if (outcome.status === 'rejected') {
2249
+ this.handleRejection({
2250
+ type: 'rejection',
2251
+ eventGuid: outcome.eventGuid,
2252
+ error: outcome.error ?? { code: 'rejected', message: 'rejected' },
2253
+ });
2254
+ continue;
2255
+ }
2256
+ this.counters.httpPostedEvents++;
2257
+ for (const frame of ('events' in outcome ? outcome.events : undefined) ?? [])
2258
+ this.handleServerEvent(frame);
2259
+ }
2260
+ }
1817
2261
  detachSocket(socket) {
1818
2262
  socket.onopen = null;
1819
2263
  socket.onmessage = null;