@steve31415/baselib 3.77.0 → 4.0.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 +2 -2
- package/dist/sync/http-events.d.ts +35 -0
- package/dist/sync/http-events.js +106 -0
- package/dist/sync/index.d.ts +1 -2
- package/dist/sync/index.js +1 -2
- package/dist/sync/types.d.ts +8 -56
- package/dist/sync/types.js +2 -3
- package/dist/sync-browser/client.d.ts +45 -74
- package/dist/sync-browser/client.js +193 -469
- package/dist/sync-browser/hub.js +3 -4
- package/dist/sync-browser/page-hub-url.js +3 -4
- package/package.json +1 -1
- package/dist/sync/broadcaster.d.ts +0 -13
- package/dist/sync/broadcaster.js +0 -53
- package/dist/sync/session.d.ts +0 -75
- package/dist/sync/session.js +0 -283
|
@@ -1,7 +1,6 @@
|
|
|
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
|
+
import { CLOSE_HUB_IDLE, CLOSE_TRY_AGAIN_LATER, HUB_FLOOR_MS, HUB_HINT_DEBOUNCE_MS, HUB_PING_INTERVAL_MS, HUB_PONG_TIMEOUT_MS, hubSocketUrl, parseHubFrame, } from './hub.js';
|
|
3
3
|
const RECONNECT_DELAYS_SECONDS = [1, 2, 4, 8, 16, 30];
|
|
4
|
-
const PING_INTERVAL_MS = 30_000;
|
|
5
4
|
// Deliberate (2026-10-20 review, task 1e2cd274): todo's phone hit it 27
|
|
6
5
|
// times in 25 minutes on 10-19, but none of those handshakes ever reached
|
|
7
6
|
// the load balancer, so a longer limit would only have delayed the retry.
|
|
@@ -28,10 +27,9 @@ const RESYNC_RETRY_MS = 60_000;
|
|
|
28
27
|
const GAP_BUFFER_MAX = 1_000;
|
|
29
28
|
const RECONCILE_MOVED_MAX_REFETCHES = 3;
|
|
30
29
|
const CLOSE_NO_USER = 4403;
|
|
31
|
-
const PROBE_AFTER_ATTEMPTS = 2;
|
|
32
30
|
const DEFAULT_BACKGROUND_CATCHUP_MS = 5 * 60 * 1000;
|
|
33
31
|
const BACKGROUND_FETCH_TIMEOUT_MS = 15_000;
|
|
34
|
-
const
|
|
32
|
+
const WAKE_REPLY_MS = 5_000;
|
|
35
33
|
/** A hidden attempt's socket that dies sooner than this counts as failed. */
|
|
36
34
|
const HIDDEN_SOCKET_MIN_LIFE_MS = 60_000;
|
|
37
35
|
const RETURN_REPORT_TIMEOUT_MS = 15_000;
|
|
@@ -55,10 +53,10 @@ const STALL_MIN_MS = 1_000;
|
|
|
55
53
|
const SOCKET_CONNECTING = 0;
|
|
56
54
|
const SOCKET_OPEN = 1;
|
|
57
55
|
/** Outage logs' `closeCode` when a failed app request, not a socket close,
|
|
58
|
-
* began the outage
|
|
56
|
+
* began the outage. */
|
|
59
57
|
const APP_REQUEST_FAILED = 0;
|
|
60
|
-
/**
|
|
61
|
-
*
|
|
58
|
+
/** At most this many quiet reconnects (1012/1013/4408 on an acked socket)
|
|
59
|
+
* per window; more take the ladder. The hub's own closes come at
|
|
62
60
|
* most every 180-300 s per socket. */
|
|
63
61
|
const HUB_QUIET_CLOSE_BURST = 3;
|
|
64
62
|
const HUB_QUIET_CLOSE_WINDOW_MS = 60_000;
|
|
@@ -68,14 +66,6 @@ function isEventsResponse(value) {
|
|
|
68
66
|
const { outcomes, events } = value;
|
|
69
67
|
return Array.isArray(outcomes) && (events === undefined || Array.isArray(events));
|
|
70
68
|
}
|
|
71
|
-
function messageType(raw) {
|
|
72
|
-
try {
|
|
73
|
-
return JSON.parse(raw)?.type;
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
return undefined;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
69
|
class LifecycleAbort {
|
|
80
70
|
reason;
|
|
81
71
|
constructor(reason) {
|
|
@@ -92,7 +82,7 @@ export class SyncClient {
|
|
|
92
82
|
unresolvedFailures = new Set();
|
|
93
83
|
rejected = new Map();
|
|
94
84
|
confirmedPending = new Map();
|
|
95
|
-
pendingRejections = new
|
|
85
|
+
pendingRejections = new Set();
|
|
96
86
|
settlementInFlight = new Set();
|
|
97
87
|
settledPending = new Set();
|
|
98
88
|
failureTimers = new Map();
|
|
@@ -117,8 +107,6 @@ export class SyncClient {
|
|
|
117
107
|
outageEscalated = false;
|
|
118
108
|
halted = false;
|
|
119
109
|
refetchInFlight = false;
|
|
120
|
-
probeInFlight = false;
|
|
121
|
-
probeRequested = false;
|
|
122
110
|
resyncTimes = [];
|
|
123
111
|
/** Forward-gap events delivered while a resync is reconciling; drained
|
|
124
112
|
* after the bootstrap installs. Non-null exactly while reconciling. */
|
|
@@ -136,12 +124,10 @@ export class SyncClient {
|
|
|
136
124
|
// Hidden-page state (docs/SYNC-BACKGROUND-PLAN.md).
|
|
137
125
|
hiddenSince = null;
|
|
138
126
|
hiddenSocketFailed = false;
|
|
139
|
-
beaconedWhileDormant = false;
|
|
140
127
|
backgroundTickTimer = null;
|
|
141
128
|
lastTickAt = null;
|
|
142
129
|
catchupSlot = null;
|
|
143
|
-
|
|
144
|
-
connectReplyTimer = null;
|
|
130
|
+
wakeReplyTimer = null;
|
|
145
131
|
socketCreatedHidden = false;
|
|
146
132
|
socketOpenedAt = null;
|
|
147
133
|
candidate = null;
|
|
@@ -165,11 +151,9 @@ export class SyncClient {
|
|
|
165
151
|
backgroundSocketAttempts: 0,
|
|
166
152
|
httpPostedEvents: 0,
|
|
167
153
|
};
|
|
168
|
-
//
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
hub;
|
|
172
|
-
/** Where the live socket goes: the hub's URL, or the app's own. */
|
|
154
|
+
// The socket fields above hold the hub socket; the app's own reachability
|
|
155
|
+
// has its own ladder here, independent of the socket's.
|
|
156
|
+
/** The hub socket's URL. */
|
|
173
157
|
socketUrl;
|
|
174
158
|
/** The live hub socket answered our `connect`. */
|
|
175
159
|
hubAcked = false;
|
|
@@ -202,19 +186,11 @@ export class SyncClient {
|
|
|
202
186
|
postAgain = false;
|
|
203
187
|
constructor(options) {
|
|
204
188
|
this.options = options;
|
|
205
|
-
if (!options.hubUrl)
|
|
206
|
-
|
|
207
|
-
if (!sameOrigin)
|
|
208
|
-
throw new Error('sync needs hubUrl or socketUrl');
|
|
209
|
-
this.hub = null;
|
|
210
|
-
this.socketUrl = () => sameOrigin();
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
189
|
+
if (!options.hubUrl)
|
|
190
|
+
throw new Error('sync needs hubUrl (the page shell has no pw-hub-url meta)');
|
|
213
191
|
if (!options.app || !options.postEvents)
|
|
214
|
-
throw new Error('sync
|
|
215
|
-
|
|
216
|
-
this.hub = { app: options.app, postEvents: options.postEvents };
|
|
217
|
-
this.socketUrl = () => url;
|
|
192
|
+
throw new Error('sync needs app and postEvents');
|
|
193
|
+
this.socketUrl = hubSocketUrl(options.hubUrl, options.app);
|
|
218
194
|
}
|
|
219
195
|
init() {
|
|
220
196
|
if (this.disposed)
|
|
@@ -285,11 +261,9 @@ export class SyncClient {
|
|
|
285
261
|
return;
|
|
286
262
|
this.installRuntimeListeners();
|
|
287
263
|
this.connect();
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
this.kickPost();
|
|
292
|
-
}
|
|
264
|
+
// Recovered edits go to the app at once, whatever the hub's state.
|
|
265
|
+
this.armFloor();
|
|
266
|
+
this.kickPost();
|
|
293
267
|
}
|
|
294
268
|
/** The first bootstrap. One that gets no HTTP answer (fetch's TypeError: no
|
|
295
269
|
* network, or one that reaches nothing — a tab Android Chrome restored from
|
|
@@ -395,21 +369,11 @@ export class SyncClient {
|
|
|
395
369
|
this.pending.set(event.eventGuid, entry);
|
|
396
370
|
this.options.store.applyOptimistic(event);
|
|
397
371
|
this.armFailureTimer(event.eventGuid);
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
this.kickPost();
|
|
404
|
-
}
|
|
405
|
-
else {
|
|
406
|
-
this.trySend(entry);
|
|
407
|
-
}
|
|
408
|
-
// A visible page in an outage delivers over HTTP at once rather than
|
|
409
|
-
// waiting for a handshake that may be stuck behind another one.
|
|
410
|
-
if (!this.hub && !this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
|
|
411
|
-
void this.probeSession();
|
|
412
|
-
}
|
|
372
|
+
// Every mutation goes over POST, one request in flight per tab.
|
|
373
|
+
if (this.postInFlight !== null)
|
|
374
|
+
this.postAgain = true;
|
|
375
|
+
else
|
|
376
|
+
this.kickPost();
|
|
413
377
|
this.updatePendingState();
|
|
414
378
|
this.options.onSafetyChange?.();
|
|
415
379
|
}
|
|
@@ -435,14 +399,6 @@ export class SyncClient {
|
|
|
435
399
|
this.unresolvedFailures.delete(eventGuid);
|
|
436
400
|
this.options.onSafetyChange?.();
|
|
437
401
|
}
|
|
438
|
-
refreshConnectionForBuild() {
|
|
439
|
-
// A hub socket is on no app instance: replacing every page's hub socket
|
|
440
|
-
// on every app deploy would be a reconnect storm for nothing.
|
|
441
|
-
if (this.halted || this.disposed || this.hub)
|
|
442
|
-
return;
|
|
443
|
-
this.options.logger.info('sync reconnect for traffic build');
|
|
444
|
-
this.replaceSocket();
|
|
445
|
-
}
|
|
446
402
|
state() {
|
|
447
403
|
return this.currentState;
|
|
448
404
|
}
|
|
@@ -555,25 +511,23 @@ export class SyncClient {
|
|
|
555
511
|
this.hiddenSince = this.now();
|
|
556
512
|
this.spellCounters = this.snapshot();
|
|
557
513
|
this.hiddenSocketFailed = false;
|
|
558
|
-
this.
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
this.
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
this.armBackgroundTick();
|
|
571
|
-
this.refreshHubState();
|
|
572
|
-
}
|
|
514
|
+
if (this.wakeReplyTimer !== null)
|
|
515
|
+
this.options.runtime.clearTimeout(this.wakeReplyTimer);
|
|
516
|
+
this.wakeReplyTimer = null;
|
|
517
|
+
// No app-request ladder and no floor while hidden. A tab that keeps its
|
|
518
|
+
// hub socket acts on hints and also runs the 5-minute tick, in case a
|
|
519
|
+
// hint was lost; it was current a moment ago.
|
|
520
|
+
this.cancelAppRetry();
|
|
521
|
+
this.cancelFloor();
|
|
522
|
+
if (this.socket !== null) {
|
|
523
|
+
this.lastTickAt = this.now();
|
|
524
|
+
this.armBackgroundTick();
|
|
525
|
+
this.refreshState();
|
|
573
526
|
}
|
|
574
|
-
|
|
575
|
-
|
|
527
|
+
else {
|
|
528
|
+
// A ladder waiting to retry is cancelled: no reconnects while hidden.
|
|
576
529
|
this.enterDormant();
|
|
530
|
+
}
|
|
577
531
|
}
|
|
578
532
|
onBecameVisible() {
|
|
579
533
|
if (this.halted || this.disposed)
|
|
@@ -588,7 +542,6 @@ export class SyncClient {
|
|
|
588
542
|
this.hiddenSince = null;
|
|
589
543
|
this.spellCounters = null;
|
|
590
544
|
this.cancelBackgroundTick();
|
|
591
|
-
this.httpApplied.clear();
|
|
592
545
|
this.openReturnWindow(hiddenMs, spell);
|
|
593
546
|
this.rearmFailureTimers();
|
|
594
547
|
if (this.outageStartedAt !== null && !this.outageEscalated)
|
|
@@ -604,10 +557,8 @@ export class SyncClient {
|
|
|
604
557
|
// Always: a socket that looks open may be dead (review S2), and a
|
|
605
558
|
// handshake may be slow. One HTTP round trip makes the page current.
|
|
606
559
|
void this.runCatchup('return');
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
this.kickPost();
|
|
610
|
-
}
|
|
560
|
+
this.armFloor();
|
|
561
|
+
this.kickPost();
|
|
611
562
|
}
|
|
612
563
|
onOnline() {
|
|
613
564
|
if (this.halted || this.disposed)
|
|
@@ -621,7 +572,7 @@ export class SyncClient {
|
|
|
621
572
|
return;
|
|
622
573
|
}
|
|
623
574
|
this.wakeConnection();
|
|
624
|
-
if (
|
|
575
|
+
if (!this.appOk) {
|
|
625
576
|
this.cancelAppRetry();
|
|
626
577
|
void this.retryAppRequest();
|
|
627
578
|
}
|
|
@@ -631,23 +582,17 @@ export class SyncClient {
|
|
|
631
582
|
return;
|
|
632
583
|
const socket = this.socket;
|
|
633
584
|
if (socket?.readyState === SOCKET_OPEN) {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
// A socket that looks open may be half-dead: no catch-up reply (hub
|
|
643
|
-
// mode: no frame at all) in 5 s replaces it.
|
|
644
|
-
if (this.connectReplyTimer !== null)
|
|
645
|
-
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
646
|
-
this.connectReplyTimer = this.setTimer(() => {
|
|
647
|
-
this.connectReplyTimer = null;
|
|
585
|
+
// Ask the hub at once: any frame within 5 s says the socket lives. A
|
|
586
|
+
// socket that looks open may be half-dead: silence replaces it.
|
|
587
|
+
this.sendRaw({ type: 'ping' });
|
|
588
|
+
this.hubAwaitingPong = true;
|
|
589
|
+
if (this.wakeReplyTimer !== null)
|
|
590
|
+
this.options.runtime.clearTimeout(this.wakeReplyTimer);
|
|
591
|
+
this.wakeReplyTimer = this.setTimer(() => {
|
|
592
|
+
this.wakeReplyTimer = null;
|
|
648
593
|
if (this.socket === socket && !this.isHidden())
|
|
649
594
|
this.replaceSocket();
|
|
650
|
-
},
|
|
595
|
+
}, WAKE_REPLY_MS);
|
|
651
596
|
return;
|
|
652
597
|
}
|
|
653
598
|
// A handshake still inside its watchdog window may just be slow: leave
|
|
@@ -692,14 +637,9 @@ export class SyncClient {
|
|
|
692
637
|
connect() {
|
|
693
638
|
if (this.halted || this.disposed)
|
|
694
639
|
return;
|
|
695
|
-
if (!this.hub) {
|
|
696
|
-
this.publish(this.reconnectAttempts > 0
|
|
697
|
-
? { kind: 'disconnected', pending: this.pendingCount() }
|
|
698
|
-
: { kind: 'connecting', pending: this.pendingCount() });
|
|
699
|
-
}
|
|
700
640
|
let socket;
|
|
701
641
|
try {
|
|
702
|
-
socket = this.options.runtime.createSocket(this.socketUrl
|
|
642
|
+
socket = this.options.runtime.createSocket(this.socketUrl);
|
|
703
643
|
}
|
|
704
644
|
catch (error) {
|
|
705
645
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -712,7 +652,7 @@ export class SyncClient {
|
|
|
712
652
|
}
|
|
713
653
|
this.socket = socket;
|
|
714
654
|
this.hubAcked = false;
|
|
715
|
-
this.
|
|
655
|
+
this.refreshState();
|
|
716
656
|
this.socketCreatedAt = this.options.runtime.now();
|
|
717
657
|
this.socketCreatedHidden = this.isHidden();
|
|
718
658
|
this.socketOpenedAt = null;
|
|
@@ -744,15 +684,16 @@ export class SyncClient {
|
|
|
744
684
|
hidden: this.isHidden(),
|
|
745
685
|
});
|
|
746
686
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
this.
|
|
687
|
+
this.hubLastHeardAt = this.now();
|
|
688
|
+
this.hubAwaitingPong = false;
|
|
689
|
+
// Hidden with a hub socket, the 5-minute tick runs beside it (hints can
|
|
690
|
+
// be lost). A page hidden later started it at the hide; one loaded
|
|
691
|
+
// hidden starts it here, current since its bootstrap.
|
|
692
|
+
if (this.isHidden() && this.backgroundTickTimer === null) {
|
|
693
|
+
this.lastTickAt ??= this.now();
|
|
694
|
+
this.armBackgroundTick();
|
|
754
695
|
}
|
|
755
|
-
this.
|
|
696
|
+
this.sendRaw(this.connectMessage());
|
|
756
697
|
this.startLiveTimers();
|
|
757
698
|
};
|
|
758
699
|
this.attachLiveHandlers(socket, () => killedByWatchdog);
|
|
@@ -764,7 +705,7 @@ export class SyncClient {
|
|
|
764
705
|
if (this.socket !== socket)
|
|
765
706
|
return;
|
|
766
707
|
this.lastContactAt = this.now();
|
|
767
|
-
this.
|
|
708
|
+
this.handleHubMessage(String(event.data));
|
|
768
709
|
};
|
|
769
710
|
socket.onerror = () => {
|
|
770
711
|
// Browsers expose no useful detail; the close event owns recovery.
|
|
@@ -788,14 +729,9 @@ export class SyncClient {
|
|
|
788
729
|
});
|
|
789
730
|
}
|
|
790
731
|
if (event.code === CLOSE_NO_USER) {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
return;
|
|
795
|
-
}
|
|
796
|
-
// Hub mode: the hub found no identity. The app decides whether the
|
|
797
|
-
// session is gone (its auth failure halts through the auth state);
|
|
798
|
-
// if it answers, the ladder below reconnects.
|
|
732
|
+
// The hub found no identity. The app decides whether the session is
|
|
733
|
+
// gone (its auth failure halts through the auth state); if it
|
|
734
|
+
// answers, the ladder below reconnects.
|
|
799
735
|
void this.runCatchup('probe');
|
|
800
736
|
}
|
|
801
737
|
const openForMs = this.socketOpenedAt === null ? null : Math.max(0, this.now() - this.socketOpenedAt);
|
|
@@ -803,15 +739,16 @@ export class SyncClient {
|
|
|
803
739
|
// on a handshake begun for a handover.
|
|
804
740
|
const rolling = this.candidate !== null;
|
|
805
741
|
this.dropCandidate();
|
|
806
|
-
if (this.
|
|
807
|
-
// The
|
|
808
|
-
// didn't run, such as a frozen one
|
|
809
|
-
// own rollover, with no outage and
|
|
810
|
-
// reconnect is an ordinary outage.
|
|
811
|
-
// was unavailable) and 4408 (it heard nothing
|
|
812
|
-
// same
|
|
813
|
-
// the hub refuses with 1013 before acking
|
|
814
|
-
// and that must back off on the ladder
|
|
742
|
+
if (this.takeQuietHubClose(event.code, wasAcked)) {
|
|
743
|
+
// The hub's planned close (1012: its age cap, for a tab whose own
|
|
744
|
+
// rollover didn't run, such as a frozen one, or a hub copy stopping):
|
|
745
|
+
// reconnect at once, as after our own rollover, with no outage and
|
|
746
|
+
// no ladder step. A failure of that reconnect is an ordinary outage.
|
|
747
|
+
// 1013 (its auth check was unavailable) and 4408 (it heard nothing
|
|
748
|
+
// for 180 s) are the same. All three only for a socket the hub had
|
|
749
|
+
// acked, and not in a burst: the hub refuses with 1013 before acking
|
|
750
|
+
// while its auth is down, and that must back off on the ladder
|
|
751
|
+
// (review 3.60.1, finding 1).
|
|
815
752
|
this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
|
|
816
753
|
this.connectNow();
|
|
817
754
|
return;
|
|
@@ -830,7 +767,7 @@ export class SyncClient {
|
|
|
830
767
|
};
|
|
831
768
|
}
|
|
832
769
|
startLiveTimers() {
|
|
833
|
-
this.pingTimer = this.setRepeating(() =>
|
|
770
|
+
this.pingTimer = this.setRepeating(() => this.hubPingTick(), HUB_PING_INTERVAL_MS);
|
|
834
771
|
this.armRollover();
|
|
835
772
|
}
|
|
836
773
|
armRollover() {
|
|
@@ -846,17 +783,18 @@ export class SyncClient {
|
|
|
846
783
|
return Math.round(DEFAULT_RECONNECT_BEFORE_MS * factor);
|
|
847
784
|
}
|
|
848
785
|
/** Make-before-break, as notes' document sockets do: a replacement connects
|
|
849
|
-
* while the live socket keeps serving
|
|
850
|
-
*
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
* keeps serving until the
|
|
786
|
+
* while the live socket keeps serving hints, and takes over when the hub
|
|
787
|
+
* acks its connect. Nothing the user sees changes, even with an edit
|
|
788
|
+
* unsent. The replacement's handshake re-runs the hub's identity check; a
|
|
789
|
+
* 4403 asks the app whether the session is gone, as on the live socket. If
|
|
790
|
+
* it fails, the live socket keeps serving until the hub's age cap closes it
|
|
791
|
+
* (1012). */
|
|
854
792
|
startRollover() {
|
|
855
793
|
if (this.halted || this.disposed || this.candidate !== null || this.socket?.readyState !== SOCKET_OPEN)
|
|
856
794
|
return;
|
|
857
795
|
let socket;
|
|
858
796
|
try {
|
|
859
|
-
socket = this.options.runtime.createSocket(this.socketUrl
|
|
797
|
+
socket = this.options.runtime.createSocket(this.socketUrl);
|
|
860
798
|
}
|
|
861
799
|
catch (error) {
|
|
862
800
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -896,35 +834,27 @@ export class SyncClient {
|
|
|
896
834
|
if (this.candidate !== candidate)
|
|
897
835
|
return;
|
|
898
836
|
const raw = String(event.data);
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
const answered = this.hub ? type === 'ack' : type === 'catchup' || type === 'reload';
|
|
902
|
-
if (!answered) {
|
|
837
|
+
// The hub answers `connect` with `ack`.
|
|
838
|
+
if (parseHubFrame(raw, this.options.app).kind !== 'ack') {
|
|
903
839
|
candidate.early.push(raw);
|
|
904
840
|
return;
|
|
905
841
|
}
|
|
906
842
|
this.promoteCandidate(candidate);
|
|
907
843
|
this.lastContactAt = this.now();
|
|
908
|
-
this.
|
|
844
|
+
this.handleHubMessage(raw);
|
|
909
845
|
for (const early of candidate.early) {
|
|
910
846
|
if (this.socket !== socket)
|
|
911
847
|
return;
|
|
912
|
-
this.
|
|
848
|
+
this.handleHubMessage(early);
|
|
913
849
|
}
|
|
914
850
|
};
|
|
915
851
|
socket.onerror = () => { };
|
|
916
852
|
socket.onclose = (event) => {
|
|
917
853
|
if (this.candidate !== candidate)
|
|
918
854
|
return;
|
|
919
|
-
if (event.code === CLOSE_NO_USER && !this.hub) {
|
|
920
|
-
this.dropCandidate();
|
|
921
|
-
this.options.authState.markBlocked();
|
|
922
|
-
this.halt();
|
|
923
|
-
return;
|
|
924
|
-
}
|
|
925
855
|
this.dropCandidate({ closeCode: event.code });
|
|
926
|
-
//
|
|
927
|
-
//
|
|
856
|
+
// The live socket keeps serving; the app decides whether the session is
|
|
857
|
+
// gone.
|
|
928
858
|
if (event.code === CLOSE_NO_USER)
|
|
929
859
|
void this.runCatchup('probe');
|
|
930
860
|
};
|
|
@@ -990,10 +920,6 @@ export class SyncClient {
|
|
|
990
920
|
this.hubRetryAt = null;
|
|
991
921
|
this.cancelAppRetry();
|
|
992
922
|
this.publish({ kind: 'disconnected', pending: this.pendingCount() });
|
|
993
|
-
if (!this.options.postEvents && !this.beaconedWhileDormant && this.unsettledPending().length > 0) {
|
|
994
|
-
this.beaconedWhileDormant = true;
|
|
995
|
-
this.flushViaBeacon();
|
|
996
|
-
}
|
|
997
923
|
this.armBackgroundTick();
|
|
998
924
|
}
|
|
999
925
|
armBackgroundTick() {
|
|
@@ -1014,26 +940,22 @@ export class SyncClient {
|
|
|
1014
940
|
async backgroundTick() {
|
|
1015
941
|
if (this.halted || this.disposed || !this.isHidden())
|
|
1016
942
|
return;
|
|
1017
|
-
//
|
|
1018
|
-
//
|
|
1019
|
-
if (!this.hub && this.socket !== null)
|
|
1020
|
-
return;
|
|
943
|
+
// Hints can be lost, so the tick runs beside a hub socket too (design
|
|
944
|
+
// §5.5).
|
|
1021
945
|
this.lastTickAt = this.now();
|
|
1022
|
-
await this.
|
|
946
|
+
await this.runPost();
|
|
1023
947
|
const ok = await this.runCatchup('background');
|
|
1024
948
|
if (this.halted || this.disposed || !this.isHidden())
|
|
1025
949
|
return;
|
|
1026
950
|
if (this.socket !== null) {
|
|
1027
|
-
|
|
1028
|
-
this.armBackgroundTick();
|
|
951
|
+
this.armBackgroundTick();
|
|
1029
952
|
return;
|
|
1030
953
|
}
|
|
1031
954
|
if (ok && !this.hiddenSocketFailed) {
|
|
1032
955
|
// Desktop hidden sockets usually live; one attempt per tick, none after
|
|
1033
956
|
// the first hidden failure in this spell (phones cut them in seconds).
|
|
1034
957
|
this.connectNow();
|
|
1035
|
-
|
|
1036
|
-
this.armBackgroundTick();
|
|
958
|
+
this.armBackgroundTick();
|
|
1037
959
|
return;
|
|
1038
960
|
}
|
|
1039
961
|
this.enterDormant();
|
|
@@ -1041,45 +963,10 @@ export class SyncClient {
|
|
|
1041
963
|
unsettledPending() {
|
|
1042
964
|
return [...this.pending.values()].filter((entry) => !this.settledPending.has(entry.event.eventGuid));
|
|
1043
965
|
}
|
|
1044
|
-
async postPendingOverHttp() {
|
|
1045
|
-
if (this.hub)
|
|
1046
|
-
return this.runPost();
|
|
1047
|
-
const postEvents = this.options.postEvents;
|
|
1048
|
-
if (!postEvents)
|
|
1049
|
-
return;
|
|
1050
|
-
const events = this.unsettledPending()
|
|
1051
|
-
.filter((entry) => !this.httpApplied.has(entry.event.eventGuid))
|
|
1052
|
-
.map((entry) => entry.event);
|
|
1053
|
-
if (events.length === 0)
|
|
1054
|
-
return;
|
|
1055
|
-
try {
|
|
1056
|
-
const { outcomes } = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events }, signal));
|
|
1057
|
-
if (this.stopBeforeStoreMutation())
|
|
1058
|
-
return;
|
|
1059
|
-
for (const outcome of outcomes) {
|
|
1060
|
-
if (outcome.status !== 'rejected')
|
|
1061
|
-
this.counters.httpPostedEvents++;
|
|
1062
|
-
if (outcome.status === 'rejected') {
|
|
1063
|
-
this.handleRejection({
|
|
1064
|
-
type: 'rejection',
|
|
1065
|
-
eventGuid: outcome.eventGuid,
|
|
1066
|
-
error: outcome.error ?? { code: 'rejected', message: 'rejected' },
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1069
|
-
else {
|
|
1070
|
-
// Applied (or a duplicate): the catch-up's echo confirms it.
|
|
1071
|
-
this.httpApplied.add(outcome.eventGuid);
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
catch {
|
|
1076
|
-
// Offline or timed out: the next tick, or the socket on return, retries.
|
|
1077
|
-
}
|
|
1078
|
-
}
|
|
1079
966
|
/** The HTTP catch-up (review S5): one slot, a return aborts any other
|
|
1080
|
-
* kind in flight, every kind gives up after 15 s.
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
967
|
+
* kind in flight, every kind gives up after 15 s. A request that finds the
|
|
968
|
+
* slot busy queues one more catch-up to start when it frees (one in
|
|
969
|
+
* flight, at most one queued), and the outcome feeds the app-request
|
|
1083
970
|
* ladder. */
|
|
1084
971
|
async runCatchup(kind) {
|
|
1085
972
|
if (this.halted || this.disposed)
|
|
@@ -1090,8 +977,7 @@ export class SyncClient {
|
|
|
1090
977
|
this.catchupSlot.controller.abort();
|
|
1091
978
|
}
|
|
1092
979
|
else {
|
|
1093
|
-
|
|
1094
|
-
this.catchupQueued = true;
|
|
980
|
+
this.catchupQueued = true;
|
|
1095
981
|
return false;
|
|
1096
982
|
}
|
|
1097
983
|
}
|
|
@@ -1122,10 +1008,7 @@ export class SyncClient {
|
|
|
1122
1008
|
complete = false;
|
|
1123
1009
|
}
|
|
1124
1010
|
}
|
|
1125
|
-
|
|
1126
|
-
this.appSucceeded(this.establishesUnder(ackGen, complete));
|
|
1127
|
-
else if (kind === 'background' && complete && this.outageEscalated)
|
|
1128
|
-
this.endOutage('background-catchup');
|
|
1011
|
+
this.appSucceeded(this.establishesUnder(ackGen, complete));
|
|
1129
1012
|
return true;
|
|
1130
1013
|
}
|
|
1131
1014
|
catch {
|
|
@@ -1147,14 +1030,12 @@ export class SyncClient {
|
|
|
1147
1030
|
this.returnWindow.catchupOk = ok;
|
|
1148
1031
|
this.maybeFinishReturnWindow();
|
|
1149
1032
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
void this.runCatchup('hint');
|
|
1157
|
-
}
|
|
1033
|
+
// A catch-up a return replaced did not fail.
|
|
1034
|
+
if (!ok && !slot.preempted)
|
|
1035
|
+
this.appFailed();
|
|
1036
|
+
if (this.catchupQueued && this.catchupSlot === null) {
|
|
1037
|
+
this.catchupQueued = false;
|
|
1038
|
+
void this.runCatchup('hint');
|
|
1158
1039
|
}
|
|
1159
1040
|
}
|
|
1160
1041
|
}
|
|
@@ -1258,86 +1139,27 @@ export class SyncClient {
|
|
|
1258
1139
|
window.quickRetryUsed = true;
|
|
1259
1140
|
return true;
|
|
1260
1141
|
}
|
|
1142
|
+
/** The 1-2-4-8-16-30 s ladder's next step after `attempts` failures, or
|
|
1143
|
+
* 250 ms for a return's first failure. Both the hub socket and app
|
|
1144
|
+
* requests retry on it, each with its own count. */
|
|
1145
|
+
nextRetryDelayMs(attempts) {
|
|
1146
|
+
if (this.takeQuickRetry())
|
|
1147
|
+
return RETURN_QUICK_RETRY_MS;
|
|
1148
|
+
return RECONNECT_DELAYS_SECONDS[Math.min(attempts, RECONNECT_DELAYS_SECONDS.length - 1)] * 1000;
|
|
1149
|
+
}
|
|
1261
1150
|
scheduleReconnect() {
|
|
1262
|
-
const
|
|
1263
|
-
const delayMs = this.takeQuickRetry() ? RETURN_QUICK_RETRY_MS : ladderSeconds * 1000;
|
|
1264
|
-
const delay = Math.ceil(delayMs / 1000);
|
|
1151
|
+
const delayMs = this.nextRetryDelayMs(this.reconnectAttempts);
|
|
1265
1152
|
this.reconnectAttempts++;
|
|
1266
1153
|
this.totalAttempts++;
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
this.hubRetryAt = this.now() + delayMs;
|
|
1271
|
-
this.reconnectTimer = this.setTimer(() => {
|
|
1272
|
-
this.reconnectTimer = null;
|
|
1273
|
-
this.hubRetryAt = null;
|
|
1274
|
-
this.connect();
|
|
1275
|
-
}, delayMs);
|
|
1276
|
-
this.refreshHubState();
|
|
1277
|
-
return;
|
|
1278
|
-
}
|
|
1279
|
-
if (this.reconnectAttempts >= PROBE_AFTER_ATTEMPTS || this.unsettledPending().length > 0) {
|
|
1280
|
-
void this.probeSession();
|
|
1281
|
-
}
|
|
1282
|
-
let remaining = delay;
|
|
1283
|
-
this.publish({ kind: 'reconnecting', pending: this.pendingCount(), inSeconds: remaining });
|
|
1284
|
-
this.countdownTimer = this.setRepeating(() => {
|
|
1285
|
-
remaining--;
|
|
1286
|
-
if (remaining > 0) {
|
|
1287
|
-
this.publish({ kind: 'reconnecting', pending: this.pendingCount(), inSeconds: remaining });
|
|
1288
|
-
}
|
|
1289
|
-
}, 1000);
|
|
1154
|
+
// The hub socket's ladder. App requests have their own; the state shows
|
|
1155
|
+
// whichever retry comes first.
|
|
1156
|
+
this.hubRetryAt = this.now() + delayMs;
|
|
1290
1157
|
this.reconnectTimer = this.setTimer(() => {
|
|
1291
|
-
if (this.countdownTimer !== null)
|
|
1292
|
-
this.options.runtime.clearInterval(this.countdownTimer);
|
|
1293
|
-
this.countdownTimer = null;
|
|
1294
1158
|
this.reconnectTimer = null;
|
|
1159
|
+
this.hubRetryAt = null;
|
|
1295
1160
|
this.connect();
|
|
1296
1161
|
}, delayMs);
|
|
1297
|
-
|
|
1298
|
-
/** One HTTP round trip while the visible socket is down: delivers pending
|
|
1299
|
-
* events (`postEvents`), then catches up — which applies their echoes, so
|
|
1300
|
-
* the writes confirm — and doubles as the session probe (an expired
|
|
1301
|
-
* session halts through the auth state). A WebSocket handshake can be
|
|
1302
|
-
* stuck for minutes behind another one in the browser's per-IP queue while
|
|
1303
|
-
* HTTP works at once (notes, 2026-10-01), so writes must not wait for it. */
|
|
1304
|
-
async probeSession() {
|
|
1305
|
-
if (this.halted || this.disposed)
|
|
1306
|
-
return;
|
|
1307
|
-
if (this.probeInFlight) {
|
|
1308
|
-
this.probeRequested = true;
|
|
1309
|
-
return;
|
|
1310
|
-
}
|
|
1311
|
-
this.probeInFlight = true;
|
|
1312
|
-
this.probeRequested = false;
|
|
1313
|
-
try {
|
|
1314
|
-
await this.postPendingOverHttp();
|
|
1315
|
-
if (this.stopBeforeStoreMutation())
|
|
1316
|
-
return;
|
|
1317
|
-
const result = await this.abortable((signal) => this.options.fetchCatchup(this.options.store.currentSeq(), signal));
|
|
1318
|
-
if (this.stopBeforeStoreMutation())
|
|
1319
|
-
return;
|
|
1320
|
-
if (result.buildId)
|
|
1321
|
-
this.options.onBuildObserved?.(result.buildId);
|
|
1322
|
-
if (result.reload) {
|
|
1323
|
-
this.requestReload('server');
|
|
1324
|
-
}
|
|
1325
|
-
else {
|
|
1326
|
-
for (const event of result.events)
|
|
1327
|
-
this.handleServerEvent(event);
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
catch {
|
|
1331
|
-
// Offline or aborted: neither says that the session is expired.
|
|
1332
|
-
}
|
|
1333
|
-
finally {
|
|
1334
|
-
this.probeInFlight = false;
|
|
1335
|
-
}
|
|
1336
|
-
// Something was submitted while this probe was in flight; deliver it
|
|
1337
|
-
// too, unless the socket came back in the meantime.
|
|
1338
|
-
if (this.probeRequested && this.socket?.readyState !== SOCKET_OPEN && !this.isHidden()) {
|
|
1339
|
-
void this.probeSession();
|
|
1340
|
-
}
|
|
1162
|
+
this.refreshState();
|
|
1341
1163
|
}
|
|
1342
1164
|
startOutage(closeCode, wasClean = false, openForMs = null) {
|
|
1343
1165
|
if (this.outageStartedAt !== null)
|
|
@@ -1374,75 +1196,14 @@ export class SyncClient {
|
|
|
1374
1196
|
}
|
|
1375
1197
|
}, OUTAGE_ESCALATE_MS);
|
|
1376
1198
|
}
|
|
1377
|
-
dispatchMessage(raw) {
|
|
1378
|
-
if (this.hub)
|
|
1379
|
-
this.handleHubMessage(raw, this.hub.app);
|
|
1380
|
-
else
|
|
1381
|
-
this.handleMessage(raw);
|
|
1382
|
-
}
|
|
1383
|
-
handleMessage(raw) {
|
|
1384
|
-
let message;
|
|
1385
|
-
try {
|
|
1386
|
-
message = JSON.parse(raw);
|
|
1387
|
-
}
|
|
1388
|
-
catch {
|
|
1389
|
-
this.options.logger.warn('unparseable ws message', { raw: raw.slice(0, 200) });
|
|
1390
|
-
return;
|
|
1391
|
-
}
|
|
1392
|
-
switch (message.type) {
|
|
1393
|
-
case 'build_changed':
|
|
1394
|
-
this.options.onBuildChanged?.();
|
|
1395
|
-
return;
|
|
1396
|
-
case 'sync_available':
|
|
1397
|
-
this.sendConnect();
|
|
1398
|
-
return;
|
|
1399
|
-
case 'pong':
|
|
1400
|
-
if (message.buildId)
|
|
1401
|
-
this.options.onBuildObserved?.(message.buildId);
|
|
1402
|
-
return;
|
|
1403
|
-
case 'catchup':
|
|
1404
|
-
this.handleSocketCatchup(message);
|
|
1405
|
-
return;
|
|
1406
|
-
case 'reload':
|
|
1407
|
-
if (this.connectReplyTimer !== null)
|
|
1408
|
-
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
1409
|
-
this.connectReplyTimer = null;
|
|
1410
|
-
this.requestReload('server');
|
|
1411
|
-
return;
|
|
1412
|
-
case 'event':
|
|
1413
|
-
this.handleServerEvent(message.event);
|
|
1414
|
-
return;
|
|
1415
|
-
case 'rejection':
|
|
1416
|
-
this.handleRejection(message);
|
|
1417
|
-
return;
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
handleSocketCatchup(message) {
|
|
1421
|
-
if (this.connectReplyTimer !== null)
|
|
1422
|
-
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
1423
|
-
this.connectReplyTimer = null;
|
|
1424
|
-
if (message.buildId)
|
|
1425
|
-
this.options.onBuildObserved?.(message.buildId);
|
|
1426
|
-
let complete = true;
|
|
1427
|
-
for (const event of message.events) {
|
|
1428
|
-
if (!this.handleServerEvent(event))
|
|
1429
|
-
complete = false;
|
|
1430
|
-
}
|
|
1431
|
-
if (complete && message.currentSeq > this.options.store.currentSeq()) {
|
|
1432
|
-
this.requestReload('sequence-gap');
|
|
1433
|
-
complete = false;
|
|
1434
|
-
}
|
|
1435
|
-
if (complete)
|
|
1436
|
-
this.onSyncEstablished();
|
|
1437
|
-
}
|
|
1438
1199
|
/** Returns false when a forward gap prevented application. */
|
|
1439
1200
|
handleServerEvent(event) {
|
|
1440
1201
|
if (this.stopBeforeStoreMutation())
|
|
1441
1202
|
return false;
|
|
1442
1203
|
const currentSeq = this.options.store.currentSeq();
|
|
1443
1204
|
if (event.seq <= currentSeq) {
|
|
1444
|
-
// A second echo of an already-confirmed edit (
|
|
1445
|
-
// both deliver it
|
|
1205
|
+
// A second echo of an already-confirmed edit (a POST's frames and a
|
|
1206
|
+
// catch-up both deliver it) must not upgrade the settlement to a full
|
|
1446
1207
|
// reconcile (review S4).
|
|
1447
1208
|
if (this.pending.has(event.eventGuid) && !this.confirmedPending.has(event.eventGuid)) {
|
|
1448
1209
|
this.confirmPending(event.eventGuid, true);
|
|
@@ -1478,45 +1239,45 @@ export class SyncClient {
|
|
|
1478
1239
|
this.confirmPending(event.eventGuid, false);
|
|
1479
1240
|
return true;
|
|
1480
1241
|
}
|
|
1481
|
-
handleRejection(
|
|
1482
|
-
const entry = this.pending.get(
|
|
1242
|
+
handleRejection(eventGuid, error) {
|
|
1243
|
+
const entry = this.pending.get(eventGuid);
|
|
1483
1244
|
if (!entry)
|
|
1484
1245
|
return;
|
|
1485
|
-
if (this.confirmedPending.has(
|
|
1486
|
-
this.retrySettlement(
|
|
1246
|
+
if (this.confirmedPending.has(eventGuid) || this.pendingRejections.has(eventGuid)) {
|
|
1247
|
+
this.retrySettlement(eventGuid);
|
|
1487
1248
|
return;
|
|
1488
1249
|
}
|
|
1489
1250
|
if (this.stopBeforeStoreMutation())
|
|
1490
1251
|
return;
|
|
1491
|
-
this.pendingRejections.
|
|
1492
|
-
this.settledPending.add(
|
|
1493
|
-
this.clearFailureTimer(
|
|
1494
|
-
this.options.store.rejectPending(
|
|
1252
|
+
this.pendingRejections.add(eventGuid);
|
|
1253
|
+
this.settledPending.add(eventGuid);
|
|
1254
|
+
this.clearFailureTimer(eventGuid);
|
|
1255
|
+
this.options.store.rejectPending(eventGuid, error);
|
|
1495
1256
|
if (!entry.recovered) {
|
|
1496
1257
|
const rejectedEntry = {
|
|
1497
1258
|
...entry,
|
|
1498
1259
|
status: 'rejected',
|
|
1499
|
-
error:
|
|
1260
|
+
error: error.message,
|
|
1500
1261
|
};
|
|
1501
|
-
this.unresolvedFailures.add(
|
|
1502
|
-
this.rejected.set(
|
|
1503
|
-
eventGuid
|
|
1262
|
+
this.unresolvedFailures.add(eventGuid);
|
|
1263
|
+
this.rejected.set(eventGuid, {
|
|
1264
|
+
eventGuid,
|
|
1504
1265
|
entry: rejectedEntry,
|
|
1505
|
-
error:
|
|
1266
|
+
error: error.message,
|
|
1506
1267
|
});
|
|
1507
1268
|
this.options.logger.warn('event rejected', {
|
|
1508
|
-
eventGuid
|
|
1509
|
-
code:
|
|
1510
|
-
message:
|
|
1269
|
+
eventGuid,
|
|
1270
|
+
code: error.code,
|
|
1271
|
+
message: error.message,
|
|
1511
1272
|
});
|
|
1512
|
-
this.options.onEventFailed(rejectedEntry,
|
|
1273
|
+
this.options.onEventFailed(rejectedEntry, error.message, true);
|
|
1513
1274
|
}
|
|
1514
1275
|
else {
|
|
1515
|
-
this.unresolvedFailures.add(
|
|
1276
|
+
this.unresolvedFailures.add(eventGuid);
|
|
1516
1277
|
}
|
|
1517
1278
|
this.options.onSafetyChange?.();
|
|
1518
1279
|
this.updateConnectedState();
|
|
1519
|
-
this.retrySettlement(
|
|
1280
|
+
this.retrySettlement(eventGuid);
|
|
1520
1281
|
}
|
|
1521
1282
|
confirmPending(eventGuid, reconcile) {
|
|
1522
1283
|
const entry = this.pending.get(eventGuid);
|
|
@@ -1685,24 +1446,16 @@ export class SyncClient {
|
|
|
1685
1446
|
this.options.onEventFailed(entry, entry.error, false);
|
|
1686
1447
|
this.options.onSafetyChange?.();
|
|
1687
1448
|
}
|
|
1688
|
-
/** Logs and closes the open outage, if any
|
|
1689
|
-
*
|
|
1690
|
-
|
|
1691
|
-
* page stops attempting its socket after one hidden failure, so an
|
|
1692
|
-
* escalated outage that went hidden stayed open, its ERROR unanswered by
|
|
1693
|
-
* any recovery line, until the page was next shown (notes 2026-11-16,
|
|
1694
|
-
* task a0f43dda: a tab left hidden for 9+ hours). The page is current
|
|
1695
|
-
* then; the return reconnects as usual and a failure there opens a new
|
|
1696
|
-
* outage. An outage that never escalated keeps its single log on return,
|
|
1697
|
-
* which reports the whole hidden spell. */
|
|
1698
|
-
endOutage(via) {
|
|
1449
|
+
/** Logs and closes the open outage, if any, once sync is established
|
|
1450
|
+
* again. */
|
|
1451
|
+
endOutage() {
|
|
1699
1452
|
if (this.outageStartedAt !== null) {
|
|
1700
1453
|
this.observeClockJump();
|
|
1701
1454
|
const durationMs = Math.max(0, this.options.runtime.now() - this.outageStartedAt);
|
|
1702
1455
|
// Failures are only counted (and the ladder only runs) while visible,
|
|
1703
1456
|
// and the count restarts on each return, so `attempts` is what the
|
|
1704
1457
|
// user could have waited through; `totalAttempts` spans every spell.
|
|
1705
|
-
//
|
|
1458
|
+
// The hub socket's and the app's failures count together.
|
|
1706
1459
|
const attempts = this.reconnectAttempts + this.appFailuresInOutage;
|
|
1707
1460
|
const info = this.outageInfo;
|
|
1708
1461
|
const delta = info ? SyncClient.delta(info.counters, this.snapshot()) : null;
|
|
@@ -1721,7 +1474,6 @@ export class SyncClient {
|
|
|
1721
1474
|
httpPostedEvents: delta?.httpPostedEvents,
|
|
1722
1475
|
freezes: delta?.freezes,
|
|
1723
1476
|
resumes: delta?.resumes,
|
|
1724
|
-
...(via ? { via } : {}),
|
|
1725
1477
|
};
|
|
1726
1478
|
if (this.outageEscalated) {
|
|
1727
1479
|
this.options.logger.info('sync outage recovered', fields);
|
|
@@ -1729,7 +1481,7 @@ export class SyncClient {
|
|
|
1729
1481
|
else if (attempts >= 2) {
|
|
1730
1482
|
this.options.logger.warn('sync outage recovered', fields);
|
|
1731
1483
|
}
|
|
1732
|
-
else if (attempts === 1
|
|
1484
|
+
else if (attempts === 1) {
|
|
1733
1485
|
this.options.logger.info('ws reconnected first try', fields);
|
|
1734
1486
|
}
|
|
1735
1487
|
else {
|
|
@@ -1757,21 +1509,18 @@ export class SyncClient {
|
|
|
1757
1509
|
this.reconnectAttempts = 0;
|
|
1758
1510
|
this.totalAttempts = 0;
|
|
1759
1511
|
this.appFailuresInOutage = 0;
|
|
1760
|
-
for (const
|
|
1761
|
-
|
|
1512
|
+
for (const eventGuid of this.pending.keys()) {
|
|
1513
|
+
// Unsettled edits go to the app in one POST; nothing mutating ever
|
|
1514
|
+
// goes on the hub socket.
|
|
1515
|
+
if (this.settledPending.has(eventGuid))
|
|
1762
1516
|
this.retrySettlement(eventGuid);
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
this.trySend(entry);
|
|
1766
|
-
}
|
|
1517
|
+
else
|
|
1518
|
+
this.kickPost();
|
|
1767
1519
|
}
|
|
1768
1520
|
// A complete catch-up IS convergence: end any stall episode and cancel
|
|
1769
1521
|
// its pending backoff retry.
|
|
1770
1522
|
this.endResyncEpisode();
|
|
1771
|
-
|
|
1772
|
-
this.refreshHubState();
|
|
1773
|
-
else
|
|
1774
|
-
this.updateConnectedState();
|
|
1523
|
+
this.refreshState();
|
|
1775
1524
|
}
|
|
1776
1525
|
requestReload(reason) {
|
|
1777
1526
|
// While a resync is reconciling or backing off, further triggers are
|
|
@@ -1813,10 +1562,8 @@ export class SyncClient {
|
|
|
1813
1562
|
try {
|
|
1814
1563
|
this.options.logger.info('resyncing from server', { reason });
|
|
1815
1564
|
reconciled = await this.reconcileStore();
|
|
1816
|
-
if (reconciled)
|
|
1817
|
-
|
|
1818
|
-
this.trySend(entry);
|
|
1819
|
-
}
|
|
1565
|
+
if (reconciled)
|
|
1566
|
+
this.kickPost();
|
|
1820
1567
|
}
|
|
1821
1568
|
catch (error) {
|
|
1822
1569
|
if (!isLifecycleAbort(error) && !this.disposed && !this.halted) {
|
|
@@ -1844,11 +1591,11 @@ export class SyncClient {
|
|
|
1844
1591
|
this.drainAfterResync(buffered);
|
|
1845
1592
|
}
|
|
1846
1593
|
}
|
|
1847
|
-
/** Applies the events delivered while the bootstrap was in flight
|
|
1848
|
-
*
|
|
1849
|
-
* where a resync under a live stream converges; a hole (
|
|
1850
|
-
*
|
|
1851
|
-
* path instead. */
|
|
1594
|
+
/** Applies the events delivered while the bootstrap was in flight (hint
|
|
1595
|
+
* catch-ups, POST frames). Contiguous with the install point, they are
|
|
1596
|
+
* where a resync under a live stream converges; a hole (an answer that
|
|
1597
|
+
* skipped ahead, buffer overflow) schedules a fresh resync via the normal
|
|
1598
|
+
* gap path instead. */
|
|
1852
1599
|
drainAfterResync(buffered) {
|
|
1853
1600
|
for (const event of buffered) {
|
|
1854
1601
|
if (this.halted || this.disposed)
|
|
@@ -1859,7 +1606,7 @@ export class SyncClient {
|
|
|
1859
1606
|
this.endResyncEpisode();
|
|
1860
1607
|
}
|
|
1861
1608
|
/** A stall episode ends only on proven convergence: a resync whose drain
|
|
1862
|
-
* scheduled nothing further, or a complete
|
|
1609
|
+
* scheduled nothing further, or a complete catch-up under the hub's ack. A successful
|
|
1863
1610
|
* reconcile alone is not convergence — in a chronic diverge-reconverge
|
|
1864
1611
|
* cycle every reconcile succeeds. */
|
|
1865
1612
|
endResyncEpisode() {
|
|
@@ -1899,14 +1646,9 @@ export class SyncClient {
|
|
|
1899
1646
|
this.options.runtime.clearTimeout(this.resyncFailureTimer);
|
|
1900
1647
|
this.resyncFailureTimer = null;
|
|
1901
1648
|
}
|
|
1902
|
-
sendConnect() {
|
|
1903
|
-
this.sendRaw(this.connectMessage());
|
|
1904
|
-
}
|
|
1905
1649
|
connectMessage() {
|
|
1906
1650
|
// The hub routes by user and never sees sequences.
|
|
1907
|
-
|
|
1908
|
-
return { type: 'connect', clientGuid: this.options.clientGuid };
|
|
1909
|
-
return { type: 'connect', clientGuid: this.options.clientGuid, lastSeq: this.options.store.currentSeq() };
|
|
1651
|
+
return { type: 'connect', clientGuid: this.options.clientGuid };
|
|
1910
1652
|
}
|
|
1911
1653
|
sendRaw(message) {
|
|
1912
1654
|
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
@@ -1918,22 +1660,10 @@ export class SyncClient {
|
|
|
1918
1660
|
// The close handler owns recovery.
|
|
1919
1661
|
}
|
|
1920
1662
|
}
|
|
1921
|
-
trySend(entry) {
|
|
1922
|
-
if (this.settledPending.has(entry.event.eventGuid))
|
|
1923
|
-
return;
|
|
1924
|
-
// Hub mode: nothing mutating ever goes on the hub socket.
|
|
1925
|
-
if (this.hub) {
|
|
1926
|
-
this.kickPost();
|
|
1927
|
-
return;
|
|
1928
|
-
}
|
|
1929
|
-
this.sendRaw({ type: 'event', clientGuid: this.options.clientGuid, event: entry.event });
|
|
1930
|
-
}
|
|
1931
1663
|
flushViaBeacon() {
|
|
1932
|
-
if (this.disposed || this.halted
|
|
1664
|
+
if (this.disposed || this.halted)
|
|
1933
1665
|
return;
|
|
1934
|
-
const events =
|
|
1935
|
-
.filter((entry) => !this.settledPending.has(entry.event.eventGuid))
|
|
1936
|
-
.map((entry) => entry.event);
|
|
1666
|
+
const events = this.unsettledPending().map((entry) => entry.event);
|
|
1937
1667
|
if (events.length === 0)
|
|
1938
1668
|
return;
|
|
1939
1669
|
const body = JSON.stringify({
|
|
@@ -2012,9 +1742,9 @@ export class SyncClient {
|
|
|
2012
1742
|
this.publish({ kind: 'expired', pending: this.pendingCount() });
|
|
2013
1743
|
}
|
|
2014
1744
|
clearConnectionTimers() {
|
|
2015
|
-
if (this.
|
|
2016
|
-
this.options.runtime.clearTimeout(this.
|
|
2017
|
-
this.
|
|
1745
|
+
if (this.wakeReplyTimer !== null)
|
|
1746
|
+
this.options.runtime.clearTimeout(this.wakeReplyTimer);
|
|
1747
|
+
this.wakeReplyTimer = null;
|
|
2018
1748
|
if (this.pingTimer !== null)
|
|
2019
1749
|
this.options.runtime.clearInterval(this.pingTimer);
|
|
2020
1750
|
if (this.watchdogTimer !== null)
|
|
@@ -2054,15 +1784,15 @@ export class SyncClient {
|
|
|
2054
1784
|
this.resyncBackoffTimer = null;
|
|
2055
1785
|
this.failureTimers.clear();
|
|
2056
1786
|
}
|
|
2057
|
-
/** Live: the socket is open
|
|
2058
|
-
*
|
|
2059
|
-
*
|
|
1787
|
+
/** Live: the socket is open, the hub answered our `connect` and the last
|
|
1788
|
+
* app request succeeded (a pong overdue replaces the socket, so an open one
|
|
1789
|
+
* has been heard from recently). */
|
|
2060
1790
|
isLive() {
|
|
2061
1791
|
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
2062
1792
|
return false;
|
|
2063
|
-
return this.
|
|
1793
|
+
return this.hubAcked && this.appOk;
|
|
2064
1794
|
}
|
|
2065
|
-
/**
|
|
1795
|
+
/** Is this close a quiet reconnect? 1012, 1013 or 4408 on a
|
|
2066
1796
|
* socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
|
|
2067
1797
|
* closes in the last minute; anything else takes the outage path. */
|
|
2068
1798
|
takeQuietHubClose(code, wasAcked) {
|
|
@@ -2086,11 +1816,11 @@ export class SyncClient {
|
|
|
2086
1816
|
establishesUnder(ackGen, complete) {
|
|
2087
1817
|
return complete && ackGen !== -1 && ackGen === this.ackGen && this.hubAcked && this.socket?.readyState === SOCKET_OPEN;
|
|
2088
1818
|
}
|
|
2089
|
-
/**
|
|
1819
|
+
/** The state: live as `connected`/`syncing`; otherwise a countdown
|
|
2090
1820
|
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
2091
1821
|
* `connecting`, or `disconnected` once something has failed. */
|
|
2092
|
-
|
|
2093
|
-
if (
|
|
1822
|
+
refreshState() {
|
|
1823
|
+
if (this.halted || this.disposed)
|
|
2094
1824
|
return;
|
|
2095
1825
|
const retries = [this.hubRetryAt, this.appRetryAt].filter((at) => at !== null);
|
|
2096
1826
|
const live = this.isLive();
|
|
@@ -2109,21 +1839,21 @@ export class SyncClient {
|
|
|
2109
1839
|
const inSeconds = Math.max(1, Math.ceil((Math.min(...retries) - this.now()) / 1000));
|
|
2110
1840
|
this.publish({ kind: 'reconnecting', pending, inSeconds });
|
|
2111
1841
|
if (this.countdownTimer === null)
|
|
2112
|
-
this.countdownTimer = this.setRepeating(() => this.
|
|
1842
|
+
this.countdownTimer = this.setRepeating(() => this.refreshState(), 1000);
|
|
2113
1843
|
return;
|
|
2114
1844
|
}
|
|
2115
1845
|
const failed = this.reconnectAttempts > 0 || this.appAttempts > 0 || this.socket === null;
|
|
2116
1846
|
this.publish({ kind: failed ? 'disconnected' : 'connecting', pending });
|
|
2117
1847
|
}
|
|
2118
|
-
handleHubMessage(raw
|
|
1848
|
+
handleHubMessage(raw) {
|
|
2119
1849
|
// Any frame is a sign of life (radar's rule): the pong watchdog and the
|
|
2120
1850
|
// return's 5 s check.
|
|
2121
1851
|
this.hubLastHeardAt = this.now();
|
|
2122
1852
|
this.hubAwaitingPong = false;
|
|
2123
|
-
if (this.
|
|
2124
|
-
this.options.runtime.clearTimeout(this.
|
|
2125
|
-
this.
|
|
2126
|
-
const frame = parseHubFrame(raw, app);
|
|
1853
|
+
if (this.wakeReplyTimer !== null)
|
|
1854
|
+
this.options.runtime.clearTimeout(this.wakeReplyTimer);
|
|
1855
|
+
this.wakeReplyTimer = null;
|
|
1856
|
+
const frame = parseHubFrame(raw, this.options.app);
|
|
2127
1857
|
switch (frame.kind) {
|
|
2128
1858
|
case 'unparseable':
|
|
2129
1859
|
this.options.logger.warn('unparseable hub message', { raw: raw.slice(0, 200) });
|
|
@@ -2149,7 +1879,7 @@ export class SyncClient {
|
|
|
2149
1879
|
return;
|
|
2150
1880
|
this.hubAcked = true;
|
|
2151
1881
|
this.ackGen++;
|
|
2152
|
-
this.
|
|
1882
|
+
this.refreshState();
|
|
2153
1883
|
void this.runCatchup('connect');
|
|
2154
1884
|
}
|
|
2155
1885
|
/** Two missed pongs replace the socket like a rollover (no outage); hints
|
|
@@ -2190,7 +1920,7 @@ export class SyncClient {
|
|
|
2190
1920
|
/** While visible, a catch-up at least every 2 minutes whatever the hub
|
|
2191
1921
|
* socket's state; any successful app request restarts the wait. */
|
|
2192
1922
|
armFloor() {
|
|
2193
|
-
if (
|
|
1923
|
+
if (this.halted || this.disposed || this.isHidden())
|
|
2194
1924
|
return;
|
|
2195
1925
|
this.cancelFloor();
|
|
2196
1926
|
this.floorTimer = this.setTimer(() => {
|
|
@@ -2212,7 +1942,7 @@ export class SyncClient {
|
|
|
2212
1942
|
this.armFloor();
|
|
2213
1943
|
if (this.postFailing && this.unsettledPending().length > 0) {
|
|
2214
1944
|
this.scheduleAppRetry();
|
|
2215
|
-
this.
|
|
1945
|
+
this.refreshState();
|
|
2216
1946
|
return;
|
|
2217
1947
|
}
|
|
2218
1948
|
this.postFailing = false;
|
|
@@ -2222,7 +1952,7 @@ export class SyncClient {
|
|
|
2222
1952
|
if (establishes)
|
|
2223
1953
|
this.onSyncEstablished();
|
|
2224
1954
|
else
|
|
2225
|
-
this.
|
|
1955
|
+
this.refreshState();
|
|
2226
1956
|
if (this.unsettledPending().length > 0)
|
|
2227
1957
|
this.kickPost();
|
|
2228
1958
|
}
|
|
@@ -2242,15 +1972,14 @@ export class SyncClient {
|
|
|
2242
1972
|
this.appFailuresInOutage++;
|
|
2243
1973
|
this.scheduleAppRetry();
|
|
2244
1974
|
}
|
|
2245
|
-
this.
|
|
1975
|
+
this.refreshState();
|
|
2246
1976
|
}
|
|
2247
1977
|
/** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
|
|
2248
1978
|
* already scheduled stands. */
|
|
2249
1979
|
scheduleAppRetry() {
|
|
2250
1980
|
if (this.appRetryTimer !== null || this.isHidden() || this.halted || this.disposed)
|
|
2251
1981
|
return;
|
|
2252
|
-
const
|
|
2253
|
-
const delayMs = this.takeQuickRetry() ? RETURN_QUICK_RETRY_MS : ladderSeconds * 1000;
|
|
1982
|
+
const delayMs = this.nextRetryDelayMs(this.appAttempts);
|
|
2254
1983
|
this.appAttempts++;
|
|
2255
1984
|
this.totalAttempts++;
|
|
2256
1985
|
this.appRetryAt = this.now() + delayMs;
|
|
@@ -2280,17 +2009,17 @@ export class SyncClient {
|
|
|
2280
2009
|
if (this.postInFlight === null)
|
|
2281
2010
|
void this.runPost();
|
|
2282
2011
|
}
|
|
2283
|
-
/**
|
|
2012
|
+
/** The mutation path: every unsettled edit in one POST, one POST in
|
|
2284
2013
|
* flight per tab. An edit submitted meanwhile posts after it succeeds; a
|
|
2285
2014
|
* failure leaves the retry to the app-request ladder. */
|
|
2286
2015
|
runPost() {
|
|
2287
2016
|
if (this.postInFlight !== null)
|
|
2288
2017
|
return this.postInFlight;
|
|
2289
2018
|
const events = this.unsettledPending().map((entry) => entry.event);
|
|
2290
|
-
if (
|
|
2019
|
+
if (events.length === 0 || this.halted || this.disposed)
|
|
2291
2020
|
return Promise.resolve();
|
|
2292
2021
|
this.postAgain = false;
|
|
2293
|
-
const inFlight = this.postOnce(
|
|
2022
|
+
const inFlight = this.postOnce(events).finally(() => {
|
|
2294
2023
|
this.postInFlight = null;
|
|
2295
2024
|
if (this.postAgain && this.appOk) {
|
|
2296
2025
|
this.postAgain = false;
|
|
@@ -2300,11 +2029,11 @@ export class SyncClient {
|
|
|
2300
2029
|
this.postInFlight = inFlight;
|
|
2301
2030
|
return inFlight;
|
|
2302
2031
|
}
|
|
2303
|
-
async postOnce(
|
|
2032
|
+
async postOnce(events) {
|
|
2304
2033
|
const ackGen = this.currentAckGen();
|
|
2305
2034
|
let response;
|
|
2306
2035
|
try {
|
|
2307
|
-
response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
|
|
2036
|
+
response = await this.withTimeout((signal) => this.options.postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
|
|
2308
2037
|
}
|
|
2309
2038
|
catch {
|
|
2310
2039
|
this.postFailed();
|
|
@@ -2333,7 +2062,7 @@ export class SyncClient {
|
|
|
2333
2062
|
this.postFailing = false;
|
|
2334
2063
|
this.appSucceeded(this.establishesUnder(ackGen, complete && response.currentSeq !== undefined));
|
|
2335
2064
|
// An app answering in the old shape sent no frames: the echoes come by
|
|
2336
|
-
// catch-up
|
|
2065
|
+
// catch-up.
|
|
2337
2066
|
if (response.currentSeq === undefined && !response.reload)
|
|
2338
2067
|
void this.runCatchup('connect');
|
|
2339
2068
|
}
|
|
@@ -2341,8 +2070,7 @@ export class SyncClient {
|
|
|
2341
2070
|
* carries the own events in order with any writer that interleaved, so no
|
|
2342
2071
|
* forward gap trips a resync. Then the outcomes: frames confirm their
|
|
2343
2072
|
* pending entry by GUID even at or below the tab's sequence (a resync may
|
|
2344
|
-
* have moved it past them, review round 2 B1)
|
|
2345
|
-
* the socket. */
|
|
2073
|
+
* have moved it past them, review round 2 B1). */
|
|
2346
2074
|
applyPostResponse(response) {
|
|
2347
2075
|
let complete = !response.reload;
|
|
2348
2076
|
if (response.reload) {
|
|
@@ -2358,11 +2086,7 @@ export class SyncClient {
|
|
|
2358
2086
|
if (this.stopBeforeStoreMutation())
|
|
2359
2087
|
return false;
|
|
2360
2088
|
if (outcome.status === 'rejected') {
|
|
2361
|
-
this.handleRejection({
|
|
2362
|
-
type: 'rejection',
|
|
2363
|
-
eventGuid: outcome.eventGuid,
|
|
2364
|
-
error: outcome.error ?? { code: 'rejected', message: 'rejected' },
|
|
2365
|
-
});
|
|
2089
|
+
this.handleRejection(outcome.eventGuid, outcome.error ?? { code: 'rejected', message: 'rejected' });
|
|
2366
2090
|
continue;
|
|
2367
2091
|
}
|
|
2368
2092
|
this.counters.httpPostedEvents++;
|