@steve31415/baselib 3.59.1 → 3.60.1
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.
- package/README.md +5 -2
- package/dist/sync/session.d.ts +35 -1
- package/dist/sync/session.js +56 -4
- package/dist/sync/types.d.ts +29 -0
- package/dist/sync-browser/client.d.ts +120 -8
- package/dist/sync-browser/client.js +569 -36
- package/dist/sync-browser/hub.d.ts +33 -0
- package/dist/sync-browser/hub.js +49 -0
- package/dist/sync-browser/index.d.ts +1 -0
- package/dist/sync-browser/index.js +1 -0
- package/package.json +1 -1
|
@@ -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,20 @@ 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;
|
|
60
|
+
/** Hub mode: at most this many quiet reconnects (1012/1013/4408 on an acked
|
|
61
|
+
* socket) per window; more take the ladder. The hub's own closes come at
|
|
62
|
+
* most every 180-300 s per socket. */
|
|
63
|
+
const HUB_QUIET_CLOSE_BURST = 3;
|
|
64
|
+
const HUB_QUIET_CLOSE_WINDOW_MS = 60_000;
|
|
65
|
+
function isEventsResponse(value) {
|
|
66
|
+
if (value === null || typeof value !== 'object')
|
|
67
|
+
return false;
|
|
68
|
+
const { outcomes, events } = value;
|
|
69
|
+
return Array.isArray(outcomes) && (events === undefined || Array.isArray(events));
|
|
70
|
+
}
|
|
56
71
|
function messageType(raw) {
|
|
57
72
|
try {
|
|
58
73
|
return JSON.parse(raw)?.type;
|
|
@@ -150,8 +165,48 @@ export class SyncClient {
|
|
|
150
165
|
backgroundSocketAttempts: 0,
|
|
151
166
|
httpPostedEvents: 0,
|
|
152
167
|
};
|
|
168
|
+
// Hub mode (null `hub`: same-origin, and none of these move). The socket
|
|
169
|
+
// fields above then hold the hub socket; the app's own reachability has
|
|
170
|
+
// its own ladder here, independent of the socket's.
|
|
171
|
+
hub;
|
|
172
|
+
/** The live hub socket answered our `connect`. */
|
|
173
|
+
hubAcked = false;
|
|
174
|
+
/** Counts acks: a catch-up establishes only if it began under the current one. */
|
|
175
|
+
ackGen = 0;
|
|
176
|
+
/** When recent quiet hub closes happened (wall clock): a burst is not quiet. */
|
|
177
|
+
quietHubCloses = [];
|
|
178
|
+
/** The last POST failed and its edits are still unsettled: reads alone do
|
|
179
|
+
* not make the page live or re-establish it. */
|
|
180
|
+
postFailing = false;
|
|
181
|
+
hubLastHeardAt = 0;
|
|
182
|
+
hubAwaitingPong = false;
|
|
183
|
+
/** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
|
|
184
|
+
appOk = true;
|
|
185
|
+
/** The app-request ladder's step, reset by any app success and on return. */
|
|
186
|
+
appAttempts = 0;
|
|
187
|
+
/** Visible app-request failures in this outage and spell, for its logs. */
|
|
188
|
+
appFailuresInOutage = 0;
|
|
189
|
+
appRetryTimer = null;
|
|
190
|
+
appRetryAt = null;
|
|
191
|
+
/** When the hub socket's ladder retries (its countdown, for the state). */
|
|
192
|
+
hubRetryAt = null;
|
|
193
|
+
floorTimer = null;
|
|
194
|
+
hintWindowTimer = null;
|
|
195
|
+
hintTrailing = false;
|
|
196
|
+
/** One catch-up may wait behind the one in flight. */
|
|
197
|
+
catchupQueued = false;
|
|
198
|
+
postInFlight = null;
|
|
199
|
+
/** An edit was submitted while a POST was in flight: post again after it. */
|
|
200
|
+
postAgain = false;
|
|
153
201
|
constructor(options) {
|
|
154
202
|
this.options = options;
|
|
203
|
+
if (!options.hubUrl) {
|
|
204
|
+
this.hub = null;
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (!options.app || !options.postEvents)
|
|
208
|
+
throw new Error('sync hub mode needs app and postEvents');
|
|
209
|
+
this.hub = { socketUrl: hubSocketUrl(options.hubUrl, options.app), app: options.app, postEvents: options.postEvents };
|
|
155
210
|
}
|
|
156
211
|
init() {
|
|
157
212
|
if (this.disposed)
|
|
@@ -222,6 +277,11 @@ export class SyncClient {
|
|
|
222
277
|
return;
|
|
223
278
|
this.installRuntimeListeners();
|
|
224
279
|
this.connect();
|
|
280
|
+
if (this.hub) {
|
|
281
|
+
// Recovered edits go to the app at once, whatever the hub's state.
|
|
282
|
+
this.armFloor();
|
|
283
|
+
this.kickPost();
|
|
284
|
+
}
|
|
225
285
|
}
|
|
226
286
|
/** The first bootstrap. One that gets no HTTP answer (fetch's TypeError: no
|
|
227
287
|
* network, or one that reaches nothing — a tab Android Chrome restored from
|
|
@@ -327,10 +387,19 @@ export class SyncClient {
|
|
|
327
387
|
this.pending.set(event.eventGuid, entry);
|
|
328
388
|
this.options.store.applyOptimistic(event);
|
|
329
389
|
this.armFailureTimer(event.eventGuid);
|
|
330
|
-
this.
|
|
390
|
+
if (this.hub) {
|
|
391
|
+
// Every mutation goes over POST, one request in flight per tab.
|
|
392
|
+
if (this.postInFlight !== null)
|
|
393
|
+
this.postAgain = true;
|
|
394
|
+
else
|
|
395
|
+
this.kickPost();
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
this.trySend(entry);
|
|
399
|
+
}
|
|
331
400
|
// A visible page in an outage delivers over HTTP at once rather than
|
|
332
401
|
// waiting for a handshake that may be stuck behind another one.
|
|
333
|
-
if (!this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
|
|
402
|
+
if (!this.hub && !this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
|
|
334
403
|
void this.probeSession();
|
|
335
404
|
}
|
|
336
405
|
this.updatePendingState();
|
|
@@ -359,7 +428,9 @@ export class SyncClient {
|
|
|
359
428
|
this.options.onSafetyChange?.();
|
|
360
429
|
}
|
|
361
430
|
refreshConnectionForBuild() {
|
|
362
|
-
|
|
431
|
+
// A hub socket is on no app instance: replacing every page's hub socket
|
|
432
|
+
// on every app deploy would be a reconnect storm for nothing.
|
|
433
|
+
if (this.halted || this.disposed || this.hub)
|
|
363
434
|
return;
|
|
364
435
|
this.options.logger.info('sync reconnect for traffic build');
|
|
365
436
|
this.replaceSocket();
|
|
@@ -480,6 +551,18 @@ export class SyncClient {
|
|
|
480
551
|
if (this.connectReplyTimer !== null)
|
|
481
552
|
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
482
553
|
this.connectReplyTimer = null;
|
|
554
|
+
if (this.hub) {
|
|
555
|
+
// No app-request ladder and no floor while hidden. A tab that keeps
|
|
556
|
+
// its hub socket acts on hints and also runs the 5-minute tick, in
|
|
557
|
+
// case a hint was lost; it was current a moment ago.
|
|
558
|
+
this.cancelAppRetry();
|
|
559
|
+
this.cancelFloor();
|
|
560
|
+
if (this.socket !== null) {
|
|
561
|
+
this.lastTickAt = this.now();
|
|
562
|
+
this.armBackgroundTick();
|
|
563
|
+
this.refreshHubState();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
483
566
|
// A ladder waiting to retry is cancelled: no reconnects while hidden.
|
|
484
567
|
if (this.socket === null)
|
|
485
568
|
this.enterDormant();
|
|
@@ -506,11 +589,17 @@ export class SyncClient {
|
|
|
506
589
|
// (a phone shown for a second, often before its network is back) must
|
|
507
590
|
// not stretch this return's retry to 8-30 s or add up to a WARN.
|
|
508
591
|
this.reconnectAttempts = 0;
|
|
592
|
+
this.appAttempts = 0;
|
|
593
|
+
this.appFailuresInOutage = 0;
|
|
509
594
|
}
|
|
510
595
|
this.wakeConnection();
|
|
511
596
|
// Always: a socket that looks open may be dead (review S2), and a
|
|
512
597
|
// handshake may be slow. One HTTP round trip makes the page current.
|
|
513
598
|
void this.runCatchup('return');
|
|
599
|
+
if (this.hub) {
|
|
600
|
+
this.armFloor();
|
|
601
|
+
this.kickPost();
|
|
602
|
+
}
|
|
514
603
|
}
|
|
515
604
|
onOnline() {
|
|
516
605
|
if (this.halted || this.disposed)
|
|
@@ -524,15 +613,26 @@ export class SyncClient {
|
|
|
524
613
|
return;
|
|
525
614
|
}
|
|
526
615
|
this.wakeConnection();
|
|
616
|
+
if (this.hub && !this.appOk) {
|
|
617
|
+
this.cancelAppRetry();
|
|
618
|
+
void this.retryAppRequest();
|
|
619
|
+
}
|
|
527
620
|
}
|
|
528
621
|
wakeConnection() {
|
|
529
622
|
if (this.halted || this.disposed)
|
|
530
623
|
return;
|
|
531
624
|
const socket = this.socket;
|
|
532
625
|
if (socket?.readyState === SOCKET_OPEN) {
|
|
533
|
-
this.
|
|
534
|
-
|
|
535
|
-
|
|
626
|
+
if (this.hub) {
|
|
627
|
+
// Ask the hub at once: any frame within 5 s says the socket lives.
|
|
628
|
+
this.sendRaw({ type: 'ping' });
|
|
629
|
+
this.hubAwaitingPong = true;
|
|
630
|
+
}
|
|
631
|
+
else {
|
|
632
|
+
this.sendConnect();
|
|
633
|
+
}
|
|
634
|
+
// A socket that looks open may be half-dead: no catch-up reply (hub
|
|
635
|
+
// mode: no frame at all) in 5 s replaces it.
|
|
536
636
|
if (this.connectReplyTimer !== null)
|
|
537
637
|
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
538
638
|
this.connectReplyTimer = this.setTimer(() => {
|
|
@@ -572,6 +672,7 @@ export class SyncClient {
|
|
|
572
672
|
replaceSocket() {
|
|
573
673
|
const previous = this.socket;
|
|
574
674
|
this.socket = null;
|
|
675
|
+
this.hubAcked = false;
|
|
575
676
|
this.clearConnectionTimers();
|
|
576
677
|
this.dropCandidate();
|
|
577
678
|
if (previous) {
|
|
@@ -583,12 +684,14 @@ export class SyncClient {
|
|
|
583
684
|
connect() {
|
|
584
685
|
if (this.halted || this.disposed)
|
|
585
686
|
return;
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
687
|
+
if (!this.hub) {
|
|
688
|
+
this.publish(this.reconnectAttempts > 0
|
|
689
|
+
? { kind: 'disconnected', pending: this.pendingCount() }
|
|
690
|
+
: { kind: 'connecting', pending: this.pendingCount() });
|
|
691
|
+
}
|
|
589
692
|
let socket;
|
|
590
693
|
try {
|
|
591
|
-
socket = this.options.runtime.createSocket(this.
|
|
694
|
+
socket = this.options.runtime.createSocket(this.socketUrl());
|
|
592
695
|
}
|
|
593
696
|
catch (error) {
|
|
594
697
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -600,6 +703,8 @@ export class SyncClient {
|
|
|
600
703
|
return;
|
|
601
704
|
}
|
|
602
705
|
this.socket = socket;
|
|
706
|
+
this.hubAcked = false;
|
|
707
|
+
this.refreshHubState();
|
|
603
708
|
this.socketCreatedAt = this.options.runtime.now();
|
|
604
709
|
this.socketCreatedHidden = this.isHidden();
|
|
605
710
|
this.socketOpenedAt = null;
|
|
@@ -631,7 +736,14 @@ export class SyncClient {
|
|
|
631
736
|
hidden: this.isHidden(),
|
|
632
737
|
});
|
|
633
738
|
}
|
|
634
|
-
this.
|
|
739
|
+
if (this.hub) {
|
|
740
|
+
// A hidden tab with a hub socket keeps its 5-minute tick.
|
|
741
|
+
this.hubLastHeardAt = this.now();
|
|
742
|
+
this.hubAwaitingPong = false;
|
|
743
|
+
}
|
|
744
|
+
else {
|
|
745
|
+
this.cancelBackgroundTick();
|
|
746
|
+
}
|
|
635
747
|
this.sendConnect();
|
|
636
748
|
this.startLiveTimers();
|
|
637
749
|
};
|
|
@@ -644,7 +756,7 @@ export class SyncClient {
|
|
|
644
756
|
if (this.socket !== socket)
|
|
645
757
|
return;
|
|
646
758
|
this.lastContactAt = this.now();
|
|
647
|
-
this.
|
|
759
|
+
this.dispatchMessage(String(event.data));
|
|
648
760
|
};
|
|
649
761
|
socket.onerror = () => {
|
|
650
762
|
// Browsers expose no useful detail; the close event owns recovery.
|
|
@@ -654,6 +766,8 @@ export class SyncClient {
|
|
|
654
766
|
return;
|
|
655
767
|
this.clearConnectionTimers();
|
|
656
768
|
this.socket = null;
|
|
769
|
+
const wasAcked = this.hubAcked;
|
|
770
|
+
this.hubAcked = false;
|
|
657
771
|
if (this.halted || this.disposed)
|
|
658
772
|
return;
|
|
659
773
|
const socketAgeMs = this.now() - this.socketCreatedAt;
|
|
@@ -666,20 +780,30 @@ export class SyncClient {
|
|
|
666
780
|
});
|
|
667
781
|
}
|
|
668
782
|
if (event.code === CLOSE_NO_USER) {
|
|
669
|
-
this.
|
|
670
|
-
|
|
671
|
-
|
|
783
|
+
if (!this.hub) {
|
|
784
|
+
this.options.authState.markBlocked();
|
|
785
|
+
this.halt();
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
// Hub mode: the hub found no identity. The app decides whether the
|
|
789
|
+
// session is gone (its auth failure halts through the auth state);
|
|
790
|
+
// if it answers, the ladder below reconnects.
|
|
791
|
+
void this.runCatchup('probe');
|
|
672
792
|
}
|
|
673
793
|
const openForMs = this.socketOpenedAt === null ? null : Math.max(0, this.now() - this.socketOpenedAt);
|
|
674
794
|
// Ended before its replacement took over: start afresh rather than wait
|
|
675
795
|
// on a handshake begun for a handover.
|
|
676
796
|
const rolling = this.candidate !== null;
|
|
677
797
|
this.dropCandidate();
|
|
678
|
-
if (event.code === CLOSE_SERVICE_RESTART) {
|
|
798
|
+
if (this.hub ? this.takeQuietHubClose(event.code, wasAcked) : event.code === CLOSE_SERVICE_RESTART) {
|
|
679
799
|
// The server's planned close (its age cap: a tab whose own rollover
|
|
680
800
|
// didn't run, such as a frozen one): reconnect at once, as after our
|
|
681
801
|
// own rollover, with no outage and no ladder step. A failure of that
|
|
682
|
-
// reconnect is an ordinary outage.
|
|
802
|
+
// reconnect is an ordinary outage. The hub's 1013 (its auth check
|
|
803
|
+
// was unavailable) and 4408 (it heard nothing for 180 s) are the
|
|
804
|
+
// same, but only for a socket the hub had acked, and not in a burst:
|
|
805
|
+
// the hub refuses with 1013 before acking while its auth is down,
|
|
806
|
+
// and that must back off on the ladder (review 3.60.1, finding 1).
|
|
683
807
|
this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
|
|
684
808
|
this.connectNow();
|
|
685
809
|
return;
|
|
@@ -698,7 +822,7 @@ export class SyncClient {
|
|
|
698
822
|
};
|
|
699
823
|
}
|
|
700
824
|
startLiveTimers() {
|
|
701
|
-
this.pingTimer = this.setRepeating(() => this.sendRaw({ type: 'ping' }), PING_INTERVAL_MS);
|
|
825
|
+
this.pingTimer = this.setRepeating(() => (this.hub ? this.hubPingTick() : this.sendRaw({ type: 'ping' })), PING_INTERVAL_MS);
|
|
702
826
|
this.armRollover();
|
|
703
827
|
}
|
|
704
828
|
armRollover() {
|
|
@@ -724,7 +848,7 @@ export class SyncClient {
|
|
|
724
848
|
return;
|
|
725
849
|
let socket;
|
|
726
850
|
try {
|
|
727
|
-
socket = this.options.runtime.createSocket(this.
|
|
851
|
+
socket = this.options.runtime.createSocket(this.socketUrl());
|
|
728
852
|
}
|
|
729
853
|
catch (error) {
|
|
730
854
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -765,30 +889,36 @@ export class SyncClient {
|
|
|
765
889
|
return;
|
|
766
890
|
const raw = String(event.data);
|
|
767
891
|
const type = messageType(raw);
|
|
768
|
-
|
|
892
|
+
// The hub answers `connect` with `ack` (it sends no catch-up).
|
|
893
|
+
const answered = this.hub ? type === 'ack' : type === 'catchup' || type === 'reload';
|
|
894
|
+
if (!answered) {
|
|
769
895
|
candidate.early.push(raw);
|
|
770
896
|
return;
|
|
771
897
|
}
|
|
772
898
|
this.promoteCandidate(candidate);
|
|
773
899
|
this.lastContactAt = this.now();
|
|
774
|
-
this.
|
|
900
|
+
this.dispatchMessage(raw);
|
|
775
901
|
for (const early of candidate.early) {
|
|
776
902
|
if (this.socket !== socket)
|
|
777
903
|
return;
|
|
778
|
-
this.
|
|
904
|
+
this.dispatchMessage(early);
|
|
779
905
|
}
|
|
780
906
|
};
|
|
781
907
|
socket.onerror = () => { };
|
|
782
908
|
socket.onclose = (event) => {
|
|
783
909
|
if (this.candidate !== candidate)
|
|
784
910
|
return;
|
|
785
|
-
if (event.code === CLOSE_NO_USER) {
|
|
911
|
+
if (event.code === CLOSE_NO_USER && !this.hub) {
|
|
786
912
|
this.dropCandidate();
|
|
787
913
|
this.options.authState.markBlocked();
|
|
788
914
|
this.halt();
|
|
789
915
|
return;
|
|
790
916
|
}
|
|
791
917
|
this.dropCandidate({ closeCode: event.code });
|
|
918
|
+
// Hub mode: the live socket keeps serving; the app decides whether the
|
|
919
|
+
// session is gone.
|
|
920
|
+
if (event.code === CLOSE_NO_USER)
|
|
921
|
+
void this.runCatchup('probe');
|
|
792
922
|
};
|
|
793
923
|
}
|
|
794
924
|
promoteCandidate(candidate) {
|
|
@@ -807,6 +937,8 @@ export class SyncClient {
|
|
|
807
937
|
this.socketCreatedAt = candidate.createdAt;
|
|
808
938
|
this.socketCreatedHidden = candidate.createdHidden;
|
|
809
939
|
this.socketOpenedAt = candidate.openedAt;
|
|
940
|
+
this.hubLastHeardAt = now;
|
|
941
|
+
this.hubAwaitingPong = false;
|
|
810
942
|
candidate.socket.onopen = null;
|
|
811
943
|
this.attachLiveHandlers(candidate.socket, () => false);
|
|
812
944
|
this.startLiveTimers();
|
|
@@ -847,11 +979,16 @@ export class SyncClient {
|
|
|
847
979
|
this.options.runtime.clearInterval(this.countdownTimer);
|
|
848
980
|
this.reconnectTimer = null;
|
|
849
981
|
this.countdownTimer = null;
|
|
982
|
+
this.hubRetryAt = null;
|
|
983
|
+
this.cancelAppRetry();
|
|
850
984
|
this.publish({ kind: 'disconnected', pending: this.pendingCount() });
|
|
851
985
|
if (!this.options.postEvents && !this.beaconedWhileDormant && this.unsettledPending().length > 0) {
|
|
852
986
|
this.beaconedWhileDormant = true;
|
|
853
987
|
this.flushViaBeacon();
|
|
854
988
|
}
|
|
989
|
+
this.armBackgroundTick();
|
|
990
|
+
}
|
|
991
|
+
armBackgroundTick() {
|
|
855
992
|
if (this.backgroundTickTimer !== null)
|
|
856
993
|
return;
|
|
857
994
|
const interval = this.options.backgroundCatchupMs ?? DEFAULT_BACKGROUND_CATCHUP_MS;
|
|
@@ -867,17 +1004,28 @@ export class SyncClient {
|
|
|
867
1004
|
this.backgroundTickTimer = null;
|
|
868
1005
|
}
|
|
869
1006
|
async backgroundTick() {
|
|
870
|
-
if (this.halted || this.disposed || !this.isHidden()
|
|
1007
|
+
if (this.halted || this.disposed || !this.isHidden())
|
|
1008
|
+
return;
|
|
1009
|
+
// Same-origin: a live socket is the page's feed. Hub mode: hints can be
|
|
1010
|
+
// lost, so the tick runs beside the hub socket too (design §5.5).
|
|
1011
|
+
if (!this.hub && this.socket !== null)
|
|
871
1012
|
return;
|
|
872
1013
|
this.lastTickAt = this.now();
|
|
873
1014
|
await this.postPendingOverHttp();
|
|
874
1015
|
const ok = await this.runCatchup('background');
|
|
875
|
-
if (this.halted || this.disposed || !this.isHidden()
|
|
1016
|
+
if (this.halted || this.disposed || !this.isHidden())
|
|
876
1017
|
return;
|
|
1018
|
+
if (this.socket !== null) {
|
|
1019
|
+
if (this.hub)
|
|
1020
|
+
this.armBackgroundTick();
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
877
1023
|
if (ok && !this.hiddenSocketFailed) {
|
|
878
1024
|
// Desktop hidden sockets usually live; one attempt per tick, none after
|
|
879
1025
|
// the first hidden failure in this spell (phones cut them in seconds).
|
|
880
1026
|
this.connectNow();
|
|
1027
|
+
if (this.hub)
|
|
1028
|
+
this.armBackgroundTick();
|
|
881
1029
|
return;
|
|
882
1030
|
}
|
|
883
1031
|
this.enterDormant();
|
|
@@ -886,6 +1034,8 @@ export class SyncClient {
|
|
|
886
1034
|
return [...this.pending.values()].filter((entry) => !this.settledPending.has(entry.event.eventGuid));
|
|
887
1035
|
}
|
|
888
1036
|
async postPendingOverHttp() {
|
|
1037
|
+
if (this.hub)
|
|
1038
|
+
return this.runPost();
|
|
889
1039
|
const postEvents = this.options.postEvents;
|
|
890
1040
|
if (!postEvents)
|
|
891
1041
|
return;
|
|
@@ -918,23 +1068,32 @@ export class SyncClient {
|
|
|
918
1068
|
// Offline or timed out: the next tick, or the socket on return, retries.
|
|
919
1069
|
}
|
|
920
1070
|
}
|
|
921
|
-
/** The
|
|
922
|
-
*
|
|
1071
|
+
/** The HTTP catch-up (review S5): one slot, a return aborts any other
|
|
1072
|
+
* kind in flight, every kind gives up after 15 s. Hub mode: a request that
|
|
1073
|
+
* finds the slot busy queues one more catch-up to start when it frees (one
|
|
1074
|
+
* in flight, at most one queued), and the outcome feeds the app-request
|
|
1075
|
+
* ladder. */
|
|
923
1076
|
async runCatchup(kind) {
|
|
924
1077
|
if (this.halted || this.disposed)
|
|
925
1078
|
return false;
|
|
926
1079
|
if (this.catchupSlot !== null) {
|
|
927
|
-
if (kind === 'return' && this.catchupSlot.kind
|
|
1080
|
+
if (kind === 'return' && this.catchupSlot.kind !== 'return') {
|
|
1081
|
+
this.catchupSlot.preempted = true;
|
|
928
1082
|
this.catchupSlot.controller.abort();
|
|
929
|
-
|
|
1083
|
+
}
|
|
1084
|
+
else {
|
|
1085
|
+
if (this.hub)
|
|
1086
|
+
this.catchupQueued = true;
|
|
930
1087
|
return false;
|
|
1088
|
+
}
|
|
931
1089
|
}
|
|
932
1090
|
const controller = new AbortController();
|
|
933
|
-
const slot = { kind, controller };
|
|
1091
|
+
const slot = { kind, controller, preempted: false };
|
|
934
1092
|
this.catchupSlot = slot;
|
|
935
1093
|
this.abortControllers.add(controller);
|
|
936
1094
|
const timeout = this.setTimer(() => controller.abort(), BACKGROUND_FETCH_TIMEOUT_MS);
|
|
937
1095
|
let ok = false;
|
|
1096
|
+
const ackGen = this.currentAckGen();
|
|
938
1097
|
try {
|
|
939
1098
|
const result = await this.options.fetchCatchup(this.options.store.currentSeq(), controller.signal);
|
|
940
1099
|
if (controller.signal.aborted || this.stopBeforeStoreMutation())
|
|
@@ -945,13 +1104,18 @@ export class SyncClient {
|
|
|
945
1104
|
this.options.onBuildObserved?.(result.buildId);
|
|
946
1105
|
else if (kind === 'background')
|
|
947
1106
|
this.options.onBuildChanged?.();
|
|
1107
|
+
let complete = !result.reload;
|
|
948
1108
|
if (result.reload) {
|
|
949
1109
|
this.requestReload('server');
|
|
950
1110
|
}
|
|
951
1111
|
else {
|
|
952
|
-
for (const event of result.events)
|
|
953
|
-
this.handleServerEvent(event)
|
|
1112
|
+
for (const event of result.events) {
|
|
1113
|
+
if (!this.handleServerEvent(event))
|
|
1114
|
+
complete = false;
|
|
1115
|
+
}
|
|
954
1116
|
}
|
|
1117
|
+
if (this.hub)
|
|
1118
|
+
this.appSucceeded(this.establishesUnder(ackGen, complete));
|
|
955
1119
|
return true;
|
|
956
1120
|
}
|
|
957
1121
|
catch {
|
|
@@ -973,6 +1137,15 @@ export class SyncClient {
|
|
|
973
1137
|
this.returnWindow.catchupOk = ok;
|
|
974
1138
|
this.maybeFinishReturnWindow();
|
|
975
1139
|
}
|
|
1140
|
+
if (this.hub) {
|
|
1141
|
+
// A catch-up a return replaced did not fail.
|
|
1142
|
+
if (!ok && !slot.preempted)
|
|
1143
|
+
this.appFailed();
|
|
1144
|
+
if (this.catchupQueued && this.catchupSlot === null) {
|
|
1145
|
+
this.catchupQueued = false;
|
|
1146
|
+
void this.runCatchup('hint');
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
976
1149
|
}
|
|
977
1150
|
}
|
|
978
1151
|
async withTimeout(operation) {
|
|
@@ -1047,6 +1220,7 @@ export class SyncClient {
|
|
|
1047
1220
|
this.options.runtime.clearInterval(this.countdownTimer);
|
|
1048
1221
|
this.reconnectTimer = null;
|
|
1049
1222
|
this.countdownTimer = null;
|
|
1223
|
+
this.hubRetryAt = null;
|
|
1050
1224
|
this.connect();
|
|
1051
1225
|
}
|
|
1052
1226
|
/** Records a visible socket failure inside a return window. */
|
|
@@ -1080,6 +1254,18 @@ export class SyncClient {
|
|
|
1080
1254
|
const delay = Math.ceil(delayMs / 1000);
|
|
1081
1255
|
this.reconnectAttempts++;
|
|
1082
1256
|
this.totalAttempts++;
|
|
1257
|
+
if (this.hub) {
|
|
1258
|
+
// The hub socket's ladder. App requests have their own and need no
|
|
1259
|
+
// probe from here; the state shows whichever retry comes first.
|
|
1260
|
+
this.hubRetryAt = this.now() + delayMs;
|
|
1261
|
+
this.reconnectTimer = this.setTimer(() => {
|
|
1262
|
+
this.reconnectTimer = null;
|
|
1263
|
+
this.hubRetryAt = null;
|
|
1264
|
+
this.connect();
|
|
1265
|
+
}, delayMs);
|
|
1266
|
+
this.refreshHubState();
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1083
1269
|
if (this.reconnectAttempts >= PROBE_AFTER_ATTEMPTS || this.unsettledPending().length > 0) {
|
|
1084
1270
|
void this.probeSession();
|
|
1085
1271
|
}
|
|
@@ -1178,6 +1364,12 @@ export class SyncClient {
|
|
|
1178
1364
|
}
|
|
1179
1365
|
}, OUTAGE_ESCALATE_MS);
|
|
1180
1366
|
}
|
|
1367
|
+
dispatchMessage(raw) {
|
|
1368
|
+
if (this.hub)
|
|
1369
|
+
this.handleHubMessage(raw, this.hub.app);
|
|
1370
|
+
else
|
|
1371
|
+
this.handleMessage(raw);
|
|
1372
|
+
}
|
|
1181
1373
|
handleMessage(raw) {
|
|
1182
1374
|
let message;
|
|
1183
1375
|
try {
|
|
@@ -1490,7 +1682,8 @@ export class SyncClient {
|
|
|
1490
1682
|
// Failures are only counted (and the ladder only runs) while visible,
|
|
1491
1683
|
// and the count restarts on each return, so `attempts` is what the
|
|
1492
1684
|
// user could have waited through; `totalAttempts` spans every spell.
|
|
1493
|
-
|
|
1685
|
+
// Hub mode counts the hub socket's and the app's failures together.
|
|
1686
|
+
const attempts = this.reconnectAttempts + this.appFailuresInOutage;
|
|
1494
1687
|
const info = this.outageInfo;
|
|
1495
1688
|
const delta = info ? SyncClient.delta(info.counters, this.snapshot()) : null;
|
|
1496
1689
|
const fields = {
|
|
@@ -1534,6 +1727,7 @@ export class SyncClient {
|
|
|
1534
1727
|
this.escalateTimer = null;
|
|
1535
1728
|
this.reconnectAttempts = 0;
|
|
1536
1729
|
this.totalAttempts = 0;
|
|
1730
|
+
this.appFailuresInOutage = 0;
|
|
1537
1731
|
for (const [eventGuid, entry] of this.pending) {
|
|
1538
1732
|
if (this.settledPending.has(eventGuid)) {
|
|
1539
1733
|
this.retrySettlement(eventGuid);
|
|
@@ -1545,7 +1739,10 @@ export class SyncClient {
|
|
|
1545
1739
|
// A complete catch-up IS convergence: end any stall episode and cancel
|
|
1546
1740
|
// its pending backoff retry.
|
|
1547
1741
|
this.endResyncEpisode();
|
|
1548
|
-
this.
|
|
1742
|
+
if (this.hub)
|
|
1743
|
+
this.refreshHubState();
|
|
1744
|
+
else
|
|
1745
|
+
this.updateConnectedState();
|
|
1549
1746
|
}
|
|
1550
1747
|
requestReload(reason) {
|
|
1551
1748
|
// While a resync is reconciling or backing off, further triggers are
|
|
@@ -1677,8 +1874,14 @@ export class SyncClient {
|
|
|
1677
1874
|
this.sendRaw(this.connectMessage());
|
|
1678
1875
|
}
|
|
1679
1876
|
connectMessage() {
|
|
1877
|
+
// The hub routes by user and never sees sequences.
|
|
1878
|
+
if (this.hub)
|
|
1879
|
+
return { type: 'connect', clientGuid: this.options.clientGuid };
|
|
1680
1880
|
return { type: 'connect', clientGuid: this.options.clientGuid, lastSeq: this.options.store.currentSeq() };
|
|
1681
1881
|
}
|
|
1882
|
+
socketUrl() {
|
|
1883
|
+
return this.hub?.socketUrl ?? this.options.socketUrl();
|
|
1884
|
+
}
|
|
1682
1885
|
sendRaw(message) {
|
|
1683
1886
|
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
1684
1887
|
return;
|
|
@@ -1692,6 +1895,11 @@ export class SyncClient {
|
|
|
1692
1895
|
trySend(entry) {
|
|
1693
1896
|
if (this.settledPending.has(entry.event.eventGuid))
|
|
1694
1897
|
return;
|
|
1898
|
+
// Hub mode: nothing mutating ever goes on the hub socket.
|
|
1899
|
+
if (this.hub) {
|
|
1900
|
+
this.kickPost();
|
|
1901
|
+
return;
|
|
1902
|
+
}
|
|
1695
1903
|
this.sendRaw({ type: 'event', clientGuid: this.options.clientGuid, event: entry.event });
|
|
1696
1904
|
}
|
|
1697
1905
|
flushViaBeacon() {
|
|
@@ -1709,7 +1917,7 @@ export class SyncClient {
|
|
|
1709
1917
|
this.options.runtime.sendBeacon(this.options.beaconUrl, new Blob([body], { type: 'application/json' }));
|
|
1710
1918
|
}
|
|
1711
1919
|
updateConnectedState() {
|
|
1712
|
-
if (this.halted || this.disposed || this.
|
|
1920
|
+
if (this.halted || this.disposed || !this.isLive())
|
|
1713
1921
|
return;
|
|
1714
1922
|
const pending = this.pendingCount();
|
|
1715
1923
|
this.publish(pending > 0 ? { kind: 'syncing', pending } : { kind: 'connected', pending: 0 });
|
|
@@ -1717,7 +1925,7 @@ export class SyncClient {
|
|
|
1717
1925
|
updatePendingState() {
|
|
1718
1926
|
if (this.halted || this.disposed)
|
|
1719
1927
|
return;
|
|
1720
|
-
if (this.
|
|
1928
|
+
if (this.isLive()) {
|
|
1721
1929
|
this.updateConnectedState();
|
|
1722
1930
|
return;
|
|
1723
1931
|
}
|
|
@@ -1805,6 +2013,12 @@ export class SyncClient {
|
|
|
1805
2013
|
for (const timer of this.failureTimers.values())
|
|
1806
2014
|
this.options.runtime.clearTimeout(timer);
|
|
1807
2015
|
this.cancelBackgroundTick();
|
|
2016
|
+
this.cancelAppRetry();
|
|
2017
|
+
this.cancelFloor();
|
|
2018
|
+
if (this.hintWindowTimer !== null)
|
|
2019
|
+
this.options.runtime.clearTimeout(this.hintWindowTimer);
|
|
2020
|
+
this.hintWindowTimer = null;
|
|
2021
|
+
this.hubRetryAt = null;
|
|
1808
2022
|
if (this.returnWindow !== null)
|
|
1809
2023
|
this.options.runtime.clearTimeout(this.returnWindow.timer);
|
|
1810
2024
|
this.returnWindow = null;
|
|
@@ -1814,6 +2028,325 @@ export class SyncClient {
|
|
|
1814
2028
|
this.resyncBackoffTimer = null;
|
|
1815
2029
|
this.failureTimers.clear();
|
|
1816
2030
|
}
|
|
2031
|
+
/** Live: the socket is open and, in hub mode, the hub answered our
|
|
2032
|
+
* `connect` and the last app request succeeded (a pong overdue replaces
|
|
2033
|
+
* the socket, so an open one has been heard from recently). */
|
|
2034
|
+
isLive() {
|
|
2035
|
+
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
2036
|
+
return false;
|
|
2037
|
+
return this.hub === null || (this.hubAcked && this.appOk);
|
|
2038
|
+
}
|
|
2039
|
+
/** Hub mode: is this close a quiet reconnect? 1012, 1013 or 4408 on a
|
|
2040
|
+
* socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
|
|
2041
|
+
* closes in the last minute; anything else takes the outage path. */
|
|
2042
|
+
takeQuietHubClose(code, wasAcked) {
|
|
2043
|
+
if (code !== CLOSE_SERVICE_RESTART && code !== CLOSE_TRY_AGAIN_LATER && code !== CLOSE_HUB_IDLE)
|
|
2044
|
+
return false;
|
|
2045
|
+
if (!wasAcked)
|
|
2046
|
+
return false;
|
|
2047
|
+
const now = this.now();
|
|
2048
|
+
this.quietHubCloses = this.quietHubCloses.filter((at) => at <= now && now - at < HUB_QUIET_CLOSE_WINDOW_MS);
|
|
2049
|
+
if (this.quietHubCloses.length >= HUB_QUIET_CLOSE_BURST)
|
|
2050
|
+
return false;
|
|
2051
|
+
this.quietHubCloses.push(now);
|
|
2052
|
+
return true;
|
|
2053
|
+
}
|
|
2054
|
+
/** The ack a catch-up began under, or -1 when the hub socket was not acked. */
|
|
2055
|
+
currentAckGen() {
|
|
2056
|
+
return this.hubAcked ? this.ackGen : -1;
|
|
2057
|
+
}
|
|
2058
|
+
/** Established needs a complete catch-up that began under the current ack
|
|
2059
|
+
* (review 3.60.1, finding 3). */
|
|
2060
|
+
establishesUnder(ackGen, complete) {
|
|
2061
|
+
return complete && ackGen !== -1 && ackGen === this.ackGen && this.hubAcked && this.socket?.readyState === SOCKET_OPEN;
|
|
2062
|
+
}
|
|
2063
|
+
/** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
|
|
2064
|
+
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
2065
|
+
* `connecting`, or `disconnected` once something has failed. */
|
|
2066
|
+
refreshHubState() {
|
|
2067
|
+
if (!this.hub || this.halted || this.disposed)
|
|
2068
|
+
return;
|
|
2069
|
+
const retries = [this.hubRetryAt, this.appRetryAt].filter((at) => at !== null);
|
|
2070
|
+
const live = this.isLive();
|
|
2071
|
+
if ((live || retries.length === 0) && this.countdownTimer !== null) {
|
|
2072
|
+
this.options.runtime.clearInterval(this.countdownTimer);
|
|
2073
|
+
this.countdownTimer = null;
|
|
2074
|
+
}
|
|
2075
|
+
if (live) {
|
|
2076
|
+
// A detected resync loop keeps its error state until it converges.
|
|
2077
|
+
if (!this.loopEscalated)
|
|
2078
|
+
this.updateConnectedState();
|
|
2079
|
+
return;
|
|
2080
|
+
}
|
|
2081
|
+
const pending = this.pendingCount();
|
|
2082
|
+
if (retries.length > 0) {
|
|
2083
|
+
const inSeconds = Math.max(1, Math.ceil((Math.min(...retries) - this.now()) / 1000));
|
|
2084
|
+
this.publish({ kind: 'reconnecting', pending, inSeconds });
|
|
2085
|
+
if (this.countdownTimer === null)
|
|
2086
|
+
this.countdownTimer = this.setRepeating(() => this.refreshHubState(), 1000);
|
|
2087
|
+
return;
|
|
2088
|
+
}
|
|
2089
|
+
const failed = this.reconnectAttempts > 0 || this.appAttempts > 0 || this.socket === null;
|
|
2090
|
+
this.publish({ kind: failed ? 'disconnected' : 'connecting', pending });
|
|
2091
|
+
}
|
|
2092
|
+
handleHubMessage(raw, app) {
|
|
2093
|
+
// Any frame is a sign of life (radar's rule): the pong watchdog and the
|
|
2094
|
+
// return's 5 s check.
|
|
2095
|
+
this.hubLastHeardAt = this.now();
|
|
2096
|
+
this.hubAwaitingPong = false;
|
|
2097
|
+
if (this.connectReplyTimer !== null)
|
|
2098
|
+
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
2099
|
+
this.connectReplyTimer = null;
|
|
2100
|
+
const frame = parseHubFrame(raw, app);
|
|
2101
|
+
switch (frame.kind) {
|
|
2102
|
+
case 'unparseable':
|
|
2103
|
+
this.options.logger.warn('unparseable hub message', { raw: raw.slice(0, 200) });
|
|
2104
|
+
return;
|
|
2105
|
+
case 'ack':
|
|
2106
|
+
this.onHubAck();
|
|
2107
|
+
return;
|
|
2108
|
+
case 'sync_available':
|
|
2109
|
+
this.onSyncHint();
|
|
2110
|
+
return;
|
|
2111
|
+
case 'build_changed':
|
|
2112
|
+
this.options.onBuildChanged?.();
|
|
2113
|
+
return;
|
|
2114
|
+
case 'life':
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
/** The hub routes hints to this socket from now on. Established still
|
|
2119
|
+
* needs a catch-up that began after this (design §5.4); one queues behind
|
|
2120
|
+
* a catch-up already in flight. */
|
|
2121
|
+
onHubAck() {
|
|
2122
|
+
if (this.hubAcked)
|
|
2123
|
+
return;
|
|
2124
|
+
this.hubAcked = true;
|
|
2125
|
+
this.ackGen++;
|
|
2126
|
+
this.refreshHubState();
|
|
2127
|
+
void this.runCatchup('connect');
|
|
2128
|
+
}
|
|
2129
|
+
/** Two missed pongs replace the socket like a rollover (no outage); hints
|
|
2130
|
+
* sent to it meanwhile are lost, and the new socket's ack catches up. */
|
|
2131
|
+
hubPingTick() {
|
|
2132
|
+
const now = this.now();
|
|
2133
|
+
if (this.hubAwaitingPong && now - this.hubLastHeardAt >= HUB_PONG_TIMEOUT_MS) {
|
|
2134
|
+
this.options.logger.info('hub pong timeout', {
|
|
2135
|
+
silentForMs: now - this.hubLastHeardAt,
|
|
2136
|
+
openForMs: this.socketOpenedAt === null ? null : Math.max(0, now - this.socketOpenedAt),
|
|
2137
|
+
});
|
|
2138
|
+
this.replaceSocket();
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
this.sendRaw({ type: 'ping' });
|
|
2142
|
+
this.hubAwaitingPong = true;
|
|
2143
|
+
}
|
|
2144
|
+
/** `sync_available`: leading-edge debounce. The first hint catches up at
|
|
2145
|
+
* once; hints in the next 500 ms fold into one trailing catch-up. */
|
|
2146
|
+
onSyncHint() {
|
|
2147
|
+
if (this.hintWindowTimer !== null) {
|
|
2148
|
+
this.hintTrailing = true;
|
|
2149
|
+
return;
|
|
2150
|
+
}
|
|
2151
|
+
void this.runCatchup('hint');
|
|
2152
|
+
this.openHintWindow();
|
|
2153
|
+
}
|
|
2154
|
+
openHintWindow() {
|
|
2155
|
+
this.hintWindowTimer = this.setTimer(() => {
|
|
2156
|
+
this.hintWindowTimer = null;
|
|
2157
|
+
if (!this.hintTrailing)
|
|
2158
|
+
return;
|
|
2159
|
+
this.hintTrailing = false;
|
|
2160
|
+
void this.runCatchup('hint');
|
|
2161
|
+
this.openHintWindow();
|
|
2162
|
+
}, HUB_HINT_DEBOUNCE_MS);
|
|
2163
|
+
}
|
|
2164
|
+
/** While visible, a catch-up at least every 2 minutes whatever the hub
|
|
2165
|
+
* socket's state; any successful app request restarts the wait. */
|
|
2166
|
+
armFloor() {
|
|
2167
|
+
if (!this.hub || this.halted || this.disposed || this.isHidden())
|
|
2168
|
+
return;
|
|
2169
|
+
this.cancelFloor();
|
|
2170
|
+
this.floorTimer = this.setTimer(() => {
|
|
2171
|
+
this.floorTimer = null;
|
|
2172
|
+
void this.runCatchup('floor');
|
|
2173
|
+
}, HUB_FLOOR_MS);
|
|
2174
|
+
}
|
|
2175
|
+
cancelFloor() {
|
|
2176
|
+
if (this.floorTimer !== null)
|
|
2177
|
+
this.options.runtime.clearTimeout(this.floorTimer);
|
|
2178
|
+
this.floorTimer = null;
|
|
2179
|
+
}
|
|
2180
|
+
/** The app answered. While a failed POST's edits are still unsettled,
|
|
2181
|
+
* reads alone change nothing but the floor: the POST's ladder stays in
|
|
2182
|
+
* charge, and the page is neither live nor re-established (review
|
|
2183
|
+
* 3.60.1, findings 2 and 5). Otherwise the ladder resets, a complete
|
|
2184
|
+
* catch-up under the current ack establishes, and unsettled edits post. */
|
|
2185
|
+
appSucceeded(establishes) {
|
|
2186
|
+
this.armFloor();
|
|
2187
|
+
if (this.postFailing && this.unsettledPending().length > 0) {
|
|
2188
|
+
this.scheduleAppRetry();
|
|
2189
|
+
this.refreshHubState();
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
this.postFailing = false;
|
|
2193
|
+
this.appOk = true;
|
|
2194
|
+
this.appAttempts = 0;
|
|
2195
|
+
this.cancelAppRetry();
|
|
2196
|
+
if (establishes)
|
|
2197
|
+
this.onSyncEstablished();
|
|
2198
|
+
else
|
|
2199
|
+
this.refreshHubState();
|
|
2200
|
+
if (this.unsettledPending().length > 0)
|
|
2201
|
+
this.kickPost();
|
|
2202
|
+
}
|
|
2203
|
+
postFailed() {
|
|
2204
|
+
this.postFailing = true;
|
|
2205
|
+
this.appFailed();
|
|
2206
|
+
}
|
|
2207
|
+
/** A POST or catch-up got no usable answer: the outage starts (if it had
|
|
2208
|
+
* not), and a visible page retries on the app-request ladder whatever the
|
|
2209
|
+
* hub socket's state. An expired session halts instead. */
|
|
2210
|
+
appFailed() {
|
|
2211
|
+
if (this.stopBeforeStoreMutation())
|
|
2212
|
+
return;
|
|
2213
|
+
this.appOk = false;
|
|
2214
|
+
this.startOutage(APP_REQUEST_FAILED);
|
|
2215
|
+
if (!this.isHidden()) {
|
|
2216
|
+
this.appFailuresInOutage++;
|
|
2217
|
+
this.scheduleAppRetry();
|
|
2218
|
+
}
|
|
2219
|
+
this.refreshHubState();
|
|
2220
|
+
}
|
|
2221
|
+
/** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
|
|
2222
|
+
* already scheduled stands. */
|
|
2223
|
+
scheduleAppRetry() {
|
|
2224
|
+
if (this.appRetryTimer !== null || this.isHidden() || this.halted || this.disposed)
|
|
2225
|
+
return;
|
|
2226
|
+
const ladderSeconds = RECONNECT_DELAYS_SECONDS[Math.min(this.appAttempts, RECONNECT_DELAYS_SECONDS.length - 1)];
|
|
2227
|
+
const delayMs = this.takeQuickRetry() ? RETURN_QUICK_RETRY_MS : ladderSeconds * 1000;
|
|
2228
|
+
this.appAttempts++;
|
|
2229
|
+
this.totalAttempts++;
|
|
2230
|
+
this.appRetryAt = this.now() + delayMs;
|
|
2231
|
+
this.appRetryTimer = this.setTimer(() => {
|
|
2232
|
+
this.appRetryTimer = null;
|
|
2233
|
+
this.appRetryAt = null;
|
|
2234
|
+
void this.retryAppRequest();
|
|
2235
|
+
}, delayMs);
|
|
2236
|
+
}
|
|
2237
|
+
cancelAppRetry() {
|
|
2238
|
+
if (this.appRetryTimer !== null)
|
|
2239
|
+
this.options.runtime.clearTimeout(this.appRetryTimer);
|
|
2240
|
+
this.appRetryTimer = null;
|
|
2241
|
+
this.appRetryAt = null;
|
|
2242
|
+
}
|
|
2243
|
+
/** A POST when edits are unsettled (its response carries the catch-up),
|
|
2244
|
+
* else a catch-up. */
|
|
2245
|
+
async retryAppRequest() {
|
|
2246
|
+
if (this.unsettledPending().length > 0)
|
|
2247
|
+
await this.runPost();
|
|
2248
|
+
else
|
|
2249
|
+
await this.runCatchup('retry');
|
|
2250
|
+
}
|
|
2251
|
+
/** Re-send paths (established, resync, return): post the unsettled edits
|
|
2252
|
+
* unless a POST is already in flight. */
|
|
2253
|
+
kickPost() {
|
|
2254
|
+
if (this.postInFlight === null)
|
|
2255
|
+
void this.runPost();
|
|
2256
|
+
}
|
|
2257
|
+
/** Hub mode's mutation path: every unsettled edit in one POST, one POST in
|
|
2258
|
+
* flight per tab. An edit submitted meanwhile posts after it succeeds; a
|
|
2259
|
+
* failure leaves the retry to the app-request ladder. */
|
|
2260
|
+
runPost() {
|
|
2261
|
+
if (this.postInFlight !== null)
|
|
2262
|
+
return this.postInFlight;
|
|
2263
|
+
const events = this.unsettledPending().map((entry) => entry.event);
|
|
2264
|
+
if (!this.hub || events.length === 0 || this.halted || this.disposed)
|
|
2265
|
+
return Promise.resolve();
|
|
2266
|
+
this.postAgain = false;
|
|
2267
|
+
const inFlight = this.postOnce(this.hub.postEvents, events).finally(() => {
|
|
2268
|
+
this.postInFlight = null;
|
|
2269
|
+
if (this.postAgain && this.appOk) {
|
|
2270
|
+
this.postAgain = false;
|
|
2271
|
+
this.kickPost();
|
|
2272
|
+
}
|
|
2273
|
+
});
|
|
2274
|
+
this.postInFlight = inFlight;
|
|
2275
|
+
return inFlight;
|
|
2276
|
+
}
|
|
2277
|
+
async postOnce(postEvents, events) {
|
|
2278
|
+
const ackGen = this.currentAckGen();
|
|
2279
|
+
let response;
|
|
2280
|
+
try {
|
|
2281
|
+
response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
|
|
2282
|
+
}
|
|
2283
|
+
catch {
|
|
2284
|
+
this.postFailed();
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
if (this.stopBeforeStoreMutation())
|
|
2288
|
+
return;
|
|
2289
|
+
// A body that is not the response shape, or a store that throws applying
|
|
2290
|
+
// it, is a failed request: the ladder re-posts (review 3.60.1, finding 4).
|
|
2291
|
+
let complete;
|
|
2292
|
+
try {
|
|
2293
|
+
if (!isEventsResponse(response))
|
|
2294
|
+
throw new Error('response has no outcomes');
|
|
2295
|
+
complete = this.applyPostResponse(response);
|
|
2296
|
+
}
|
|
2297
|
+
catch (error) {
|
|
2298
|
+
if (this.stopBeforeStoreMutation())
|
|
2299
|
+
return;
|
|
2300
|
+
this.options.logger.error('sync post response unusable', { error });
|
|
2301
|
+
this.postFailed();
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2304
|
+
if (this.stopBeforeStoreMutation())
|
|
2305
|
+
return;
|
|
2306
|
+
this.lastContactAt = this.now();
|
|
2307
|
+
this.postFailing = false;
|
|
2308
|
+
this.appSucceeded(this.establishesUnder(ackGen, complete && response.currentSeq !== undefined));
|
|
2309
|
+
// An app answering in the old shape sent no frames: the echoes come by
|
|
2310
|
+
// catch-up, as for a same-origin POST.
|
|
2311
|
+
if (response.currentSeq === undefined && !response.reload)
|
|
2312
|
+
void this.runCatchup('connect');
|
|
2313
|
+
}
|
|
2314
|
+
/** The catch-up slice first: contiguous from the request's `lastSeq`, it
|
|
2315
|
+
* carries the own events in order with any writer that interleaved, so no
|
|
2316
|
+
* forward gap trips a resync. Then the outcomes: frames confirm their
|
|
2317
|
+
* pending entry by GUID even at or below the tab's sequence (a resync may
|
|
2318
|
+
* have moved it past them, review round 2 B1); rejections settle as on
|
|
2319
|
+
* the socket. */
|
|
2320
|
+
applyPostResponse(response) {
|
|
2321
|
+
let complete = !response.reload;
|
|
2322
|
+
if (response.reload) {
|
|
2323
|
+
this.requestReload('server');
|
|
2324
|
+
}
|
|
2325
|
+
else {
|
|
2326
|
+
for (const event of response.events ?? []) {
|
|
2327
|
+
if (!this.handleServerEvent(event))
|
|
2328
|
+
complete = false;
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
for (const outcome of response.outcomes) {
|
|
2332
|
+
if (this.stopBeforeStoreMutation())
|
|
2333
|
+
return false;
|
|
2334
|
+
if (outcome.status === 'rejected') {
|
|
2335
|
+
this.handleRejection({
|
|
2336
|
+
type: 'rejection',
|
|
2337
|
+
eventGuid: outcome.eventGuid,
|
|
2338
|
+
error: outcome.error ?? { code: 'rejected', message: 'rejected' },
|
|
2339
|
+
});
|
|
2340
|
+
continue;
|
|
2341
|
+
}
|
|
2342
|
+
this.counters.httpPostedEvents++;
|
|
2343
|
+
for (const frame of ('events' in outcome ? outcome.events : undefined) ?? []) {
|
|
2344
|
+
if (!this.handleServerEvent(frame))
|
|
2345
|
+
complete = false;
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
return complete;
|
|
2349
|
+
}
|
|
1817
2350
|
detachSocket(socket) {
|
|
1818
2351
|
socket.onopen = null;
|
|
1819
2352
|
socket.onmessage = null;
|