@steve31415/baselib 3.59.1 → 3.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +99 -8
- package/dist/sync-browser/client.js +478 -34
- 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
package/README.md
CHANGED
|
@@ -10,8 +10,11 @@ Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`,
|
|
|
10
10
|
`client-version`. Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
|
|
11
11
|
`extension-self-update`.
|
|
12
12
|
|
|
13
|
-
`sync` provides the Postgres event-log and server protocol primitives
|
|
14
|
-
`
|
|
13
|
+
`sync` provides the Postgres event-log and server protocol primitives, and
|
|
14
|
+
`handleSyncEventsRequest`, the one handler for every app's
|
|
15
|
+
`POST /api/sync/events`; `sync-browser` provides the IndexedDB outbox and
|
|
16
|
+
offline-first client, whose live socket is either the app's own (default) or
|
|
17
|
+
the connection hub's (`hubUrl`, hub mode).
|
|
15
18
|
`app-update` renders build-aware shells, matches their ETags, and fetches
|
|
16
19
|
retained assets for consumer-owned routes;
|
|
17
20
|
`app-update-browser` detects a new traffic build and reloads when the app's
|
package/dist/sync/session.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ScopeBroadcaster } from './broadcaster.js';
|
|
2
2
|
import { EventLogEngine } from './engine.js';
|
|
3
|
-
import { type ClientEvent, type EventBody, type HttpEventOutcome, type WsServerMessage } from './types.js';
|
|
3
|
+
import { type ClientEvent, type EventBody, type HttpEventOutcome, type HttpEventsResponse, type SyncEvent, type WsServerMessage } from './types.js';
|
|
4
4
|
export interface SyncSocketSessionOptions<C extends EventBody, S extends EventBody> {
|
|
5
5
|
scopeKey: string;
|
|
6
6
|
engine: EventLogEngine<C, S>;
|
|
@@ -26,4 +26,38 @@ export declare class SyncSocketSession<C extends EventBody, S extends EventBody>
|
|
|
26
26
|
private reject;
|
|
27
27
|
private sendToSocket;
|
|
28
28
|
}
|
|
29
|
+
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
30
|
+
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
31
|
+
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. */
|
|
29
32
|
export declare function applyHttpEventBatch<C extends EventBody, S extends EventBody>(engine: EventLogEngine<C, S>, scopeKey: string, request: unknown, parseClientEvent: (value: unknown) => ClientEvent<C>): Promise<HttpEventOutcome[]>;
|
|
33
|
+
/** What one request committed, for `afterCommit`: the events it appended,
|
|
34
|
+
* and the stored event of each retried event that had already committed. */
|
|
35
|
+
export interface SyncEventsCommitted<S extends EventBody> {
|
|
36
|
+
applied: SyncEvent<S>[];
|
|
37
|
+
duplicates: SyncEvent<S>[];
|
|
38
|
+
}
|
|
39
|
+
export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBody> {
|
|
40
|
+
engine: EventLogEngine<C, S>;
|
|
41
|
+
/** Chosen by the app's authenticated, authorized route. */
|
|
42
|
+
scopeKey: string;
|
|
43
|
+
/** The request body as parsed JSON (untrusted). */
|
|
44
|
+
body: unknown;
|
|
45
|
+
parseClientEvent(value: unknown): ClientEvent<C>;
|
|
46
|
+
/** Runs once per request, after every event has been applied and before
|
|
47
|
+
* the catch-up is read, when at least one event was applied or was a
|
|
48
|
+
* duplicate: where the app publishes `applied` to its in-process
|
|
49
|
+
* broadcaster and notifies the hub (whose notify must fire on duplicates
|
|
50
|
+
* too, design §5.3). Awaited; it should not throw (a throw fails the
|
|
51
|
+
* request after the commit, and the client's retry is deduplicated). */
|
|
52
|
+
afterCommit?(committed: SyncEventsCommitted<S>): void | Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
/** One handler for every app's `POST /api/sync/events` (connection hub
|
|
55
|
+
* design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
|
|
56
|
+
* through the engine in order. A request without `lastSeq` (sendBeacon, and
|
|
57
|
+
* clients before hub mode) gets the old shape, `{ outcomes }` with
|
|
58
|
+
* duplicates reported as `applied`. A request with it gets frame outcomes
|
|
59
|
+
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
60
|
+
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
61
|
+
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
62
|
+
* `SyncError('bad_request')` for a malformed batch (answer 400). */
|
|
63
|
+
export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
|
package/dist/sync/session.js
CHANGED
|
@@ -158,7 +158,37 @@ export class SyncSocketSession {
|
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
160
|
}
|
|
161
|
+
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
162
|
+
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
163
|
+
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. */
|
|
161
164
|
export async function applyHttpEventBatch(engine, scopeKey, request, parseClientEvent) {
|
|
165
|
+
const batch = parseBatch(request, false);
|
|
166
|
+
const { outcomes } = await applyBatch(engine, scopeKey, batch, parseClientEvent);
|
|
167
|
+
return outcomes.map(oldShape);
|
|
168
|
+
}
|
|
169
|
+
/** One handler for every app's `POST /api/sync/events` (connection hub
|
|
170
|
+
* design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
|
|
171
|
+
* through the engine in order. A request without `lastSeq` (sendBeacon, and
|
|
172
|
+
* clients before hub mode) gets the old shape, `{ outcomes }` with
|
|
173
|
+
* duplicates reported as `applied`. A request with it gets frame outcomes
|
|
174
|
+
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
175
|
+
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
176
|
+
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
177
|
+
* `SyncError('bad_request')` for a malformed batch (answer 400). */
|
|
178
|
+
export async function handleSyncEventsRequest(options) {
|
|
179
|
+
const batch = parseBatch(options.body, true);
|
|
180
|
+
const { outcomes, committed } = await applyBatch(options.engine, options.scopeKey, batch, options.parseClientEvent);
|
|
181
|
+
if (options.afterCommit && (committed.applied.length > 0 || committed.duplicates.length > 0)) {
|
|
182
|
+
await options.afterCommit(committed);
|
|
183
|
+
}
|
|
184
|
+
if (batch.lastSeq === undefined)
|
|
185
|
+
return { outcomes: outcomes.map(oldShape) };
|
|
186
|
+
const catchup = await options.engine.catchup(options.scopeKey, batch.lastSeq);
|
|
187
|
+
if (catchup.kind === 'reload')
|
|
188
|
+
return { outcomes, reload: true };
|
|
189
|
+
return { outcomes, events: catchup.events, currentSeq: catchup.currentSeq };
|
|
190
|
+
}
|
|
191
|
+
function parseBatch(request, withLastSeq) {
|
|
162
192
|
const envelope = record(request);
|
|
163
193
|
if (!envelope ||
|
|
164
194
|
typeof envelope.clientGuid !== 'string' ||
|
|
@@ -166,8 +196,19 @@ export async function applyHttpEventBatch(engine, scopeKey, request, parseClient
|
|
|
166
196
|
!Array.isArray(envelope.events)) {
|
|
167
197
|
throw new SyncError('bad_request', 'invalid event batch');
|
|
168
198
|
}
|
|
199
|
+
const batch = { clientGuid: envelope.clientGuid, events: envelope.events };
|
|
200
|
+
if (withLastSeq && envelope.lastSeq !== undefined) {
|
|
201
|
+
if (!Number.isSafeInteger(envelope.lastSeq) || envelope.lastSeq < 0) {
|
|
202
|
+
throw new SyncError('bad_request', 'invalid lastSeq');
|
|
203
|
+
}
|
|
204
|
+
batch.lastSeq = envelope.lastSeq;
|
|
205
|
+
}
|
|
206
|
+
return batch;
|
|
207
|
+
}
|
|
208
|
+
async function applyBatch(engine, scopeKey, batch, parseClientEvent) {
|
|
169
209
|
const outcomes = [];
|
|
170
|
-
|
|
210
|
+
const committed = { applied: [], duplicates: [] };
|
|
211
|
+
for (const value of batch.events) {
|
|
171
212
|
const guid = eventGuid(value);
|
|
172
213
|
let event;
|
|
173
214
|
try {
|
|
@@ -177,13 +218,24 @@ export async function applyHttpEventBatch(engine, scopeKey, request, parseClient
|
|
|
177
218
|
outcomes.push({ eventGuid: guid, status: 'rejected', error: parserError(error) });
|
|
178
219
|
continue;
|
|
179
220
|
}
|
|
180
|
-
const outcome = await engine.apply(scopeKey,
|
|
221
|
+
const outcome = await engine.apply(scopeKey, batch.clientGuid, event);
|
|
181
222
|
if (outcome.kind === 'rejected') {
|
|
182
223
|
outcomes.push({ eventGuid: event.eventGuid, status: 'rejected', error: outcome.error });
|
|
183
224
|
}
|
|
225
|
+
else if (outcome.kind === 'duplicate') {
|
|
226
|
+
committed.duplicates.push(outcome.event);
|
|
227
|
+
outcomes.push({ eventGuid: event.eventGuid, status: 'duplicate', events: [outcome.event] });
|
|
228
|
+
}
|
|
184
229
|
else {
|
|
185
|
-
|
|
230
|
+
committed.applied.push(...outcome.events);
|
|
231
|
+
outcomes.push({ eventGuid: event.eventGuid, status: 'applied', events: outcome.events });
|
|
186
232
|
}
|
|
187
233
|
}
|
|
188
|
-
return outcomes;
|
|
234
|
+
return { outcomes, committed };
|
|
235
|
+
}
|
|
236
|
+
function oldShape(outcome) {
|
|
237
|
+
if (outcome.status === 'rejected') {
|
|
238
|
+
return { eventGuid: outcome.eventGuid, status: 'rejected', error: outcome.error };
|
|
239
|
+
}
|
|
240
|
+
return { eventGuid: outcome.eventGuid, status: 'applied' };
|
|
189
241
|
}
|
package/dist/sync/types.d.ts
CHANGED
|
@@ -68,7 +68,13 @@ export type WsServerMessage<T extends EventBody> = WsEventBroadcast<T> | WsCatch
|
|
|
68
68
|
export interface HttpEventsRequest<T extends EventBody> {
|
|
69
69
|
clientGuid: string;
|
|
70
70
|
events: ClientEvent<T>[];
|
|
71
|
+
/** The tab's current sequence (hub-mode clients). A request that carries it
|
|
72
|
+
* is answered with outcome frames and a catch-up from it
|
|
73
|
+
* (`handleSyncEventsRequest`); one without it, the old shape. */
|
|
74
|
+
lastSeq?: number;
|
|
71
75
|
}
|
|
76
|
+
/** One event's outcome in the old response shape: what clients that send no
|
|
77
|
+
* `lastSeq` get, and all they read (anything but `rejected` is applied). */
|
|
72
78
|
export interface HttpEventOutcome {
|
|
73
79
|
eventGuid: string;
|
|
74
80
|
status: 'applied' | 'rejected';
|
|
@@ -77,3 +83,26 @@ export interface HttpEventOutcome {
|
|
|
77
83
|
message: string;
|
|
78
84
|
};
|
|
79
85
|
}
|
|
86
|
+
/** One event's outcome with its frames (a request that carried `lastSeq`):
|
|
87
|
+
* `applied` with the committed events, `duplicate` with the stored event (a
|
|
88
|
+
* retry whose first attempt committed), `rejected` with the error. A superset
|
|
89
|
+
* of `HttpEventOutcome`: old readers see `duplicate` as applied. */
|
|
90
|
+
export interface HttpEventFrameOutcome<T extends EventBody> {
|
|
91
|
+
eventGuid: string;
|
|
92
|
+
status: 'applied' | 'duplicate' | 'rejected';
|
|
93
|
+
error?: {
|
|
94
|
+
code: string;
|
|
95
|
+
message: string;
|
|
96
|
+
};
|
|
97
|
+
events?: SyncEvent<T>[];
|
|
98
|
+
}
|
|
99
|
+
/** The response of `POST /api/sync/events`. Without `lastSeq` in the request
|
|
100
|
+
* it is `{ outcomes }` in the old shape; with it, frame outcomes plus either a
|
|
101
|
+
* contiguous catch-up from `lastSeq` (`events`, `currentSeq`) or `reload`
|
|
102
|
+
* when the tab is too far behind (connection hub design §5.5). */
|
|
103
|
+
export interface HttpEventsResponse<T extends EventBody> {
|
|
104
|
+
outcomes: Array<HttpEventOutcome | HttpEventFrameOutcome<T>>;
|
|
105
|
+
events?: SyncEvent<T>[];
|
|
106
|
+
currentSeq?: number;
|
|
107
|
+
reload?: boolean;
|
|
108
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Logger as BrowserLogger } from '../log-browser.js';
|
|
2
|
-
import type { ClientEvent, EventBody,
|
|
2
|
+
import type { ClientEvent, EventBody, HttpEventsResponse, SyncEvent } from '../sync/index.js';
|
|
3
3
|
import type { IndexedDbOutbox } from './outbox.js';
|
|
4
4
|
export interface PendingEntry<C extends EventBody, Summary = unknown> {
|
|
5
5
|
event: ClientEvent<C>;
|
|
@@ -110,14 +110,24 @@ export interface SyncClientOptions<B, C extends EventBody, S extends EventBody,
|
|
|
110
110
|
* (default 5 min). */
|
|
111
111
|
backgroundCatchupMs?: number;
|
|
112
112
|
/** POSTs events to the app's batch endpoint (the beacon URL) and returns
|
|
113
|
-
*
|
|
114
|
-
*
|
|
113
|
+
* its response. Lets a hidden, disconnected page deliver pending edits and
|
|
114
|
+
* learn about rejections; without it the page beacons once. Hub mode
|
|
115
|
+
* requires it: every mutation travels here, with `lastSeq`, and the
|
|
116
|
+
* response's frames and catch-up (`handleSyncEventsRequest`) settle it. */
|
|
115
117
|
postEvents?(body: {
|
|
116
118
|
clientGuid: string;
|
|
117
119
|
events: ClientEvent<C>[];
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
120
|
+
lastSeq?: number;
|
|
121
|
+
}, signal: AbortSignal): Promise<HttpEventsResponse<S>>;
|
|
122
|
+
/** Hub mode (connection hub design §5.4–§5.5): the hub's base URL, e.g.
|
|
123
|
+
* `https://hub.apps.snewman.net`. The live socket goes to
|
|
124
|
+
* `wss://<hub>/api/ws?app=<app>` and carries hints only; mutations go over
|
|
125
|
+
* `postEvents` and catch-ups over `fetchCatchup`, against the app.
|
|
126
|
+
* Unset or empty: the same-origin socket (`socketUrl`), exactly as before.
|
|
127
|
+
* Requires `app` and `postEvents`. */
|
|
128
|
+
hubUrl?: string;
|
|
129
|
+
/** This app's name on the hub socket (hub mode). */
|
|
130
|
+
app?: string;
|
|
121
131
|
}
|
|
122
132
|
export declare class SyncClient<B, C extends EventBody, S extends EventBody, Summary = unknown> {
|
|
123
133
|
private readonly options;
|
|
@@ -187,6 +197,29 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
187
197
|
private stallCoveredUntil;
|
|
188
198
|
private visibleSinceMono;
|
|
189
199
|
private readonly counters;
|
|
200
|
+
private readonly hub;
|
|
201
|
+
/** The live hub socket answered our `connect`. */
|
|
202
|
+
private hubAcked;
|
|
203
|
+
private hubLastHeardAt;
|
|
204
|
+
private hubAwaitingPong;
|
|
205
|
+
/** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
|
|
206
|
+
private appOk;
|
|
207
|
+
/** The app-request ladder's step, reset by any app success and on return. */
|
|
208
|
+
private appAttempts;
|
|
209
|
+
/** Visible app-request failures in this outage and spell, for its logs. */
|
|
210
|
+
private appFailuresInOutage;
|
|
211
|
+
private appRetryTimer;
|
|
212
|
+
private appRetryAt;
|
|
213
|
+
/** When the hub socket's ladder retries (its countdown, for the state). */
|
|
214
|
+
private hubRetryAt;
|
|
215
|
+
private floorTimer;
|
|
216
|
+
private hintWindowTimer;
|
|
217
|
+
private hintTrailing;
|
|
218
|
+
/** One catch-up may wait behind the one in flight. */
|
|
219
|
+
private catchupQueued;
|
|
220
|
+
private postInFlight;
|
|
221
|
+
/** An edit was submitted while a POST was in flight: post again after it. */
|
|
222
|
+
private postAgain;
|
|
190
223
|
constructor(options: SyncClientOptions<B, C, S, Summary>);
|
|
191
224
|
init(): Promise<void>;
|
|
192
225
|
private initialize;
|
|
@@ -266,12 +299,16 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
266
299
|
/** Hidden and disconnected: no WebSocket retries; HTTP catch-ups on a slow
|
|
267
300
|
* cadence instead (docs/SYNC-BACKGROUND-PLAN.md). */
|
|
268
301
|
private enterDormant;
|
|
302
|
+
private armBackgroundTick;
|
|
269
303
|
private cancelBackgroundTick;
|
|
270
304
|
private backgroundTick;
|
|
271
305
|
private unsettledPending;
|
|
272
306
|
private postPendingOverHttp;
|
|
273
|
-
/** The
|
|
274
|
-
*
|
|
307
|
+
/** The HTTP catch-up (review S5): one slot, a return aborts any other
|
|
308
|
+
* kind in flight, every kind gives up after 15 s. Hub mode: a request that
|
|
309
|
+
* finds the slot busy queues one more catch-up to start when it frees (one
|
|
310
|
+
* in flight, at most one queued), and the outcome feeds the app-request
|
|
311
|
+
* ladder. */
|
|
275
312
|
private runCatchup;
|
|
276
313
|
private withTimeout;
|
|
277
314
|
private openReturnWindow;
|
|
@@ -296,6 +333,7 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
296
333
|
/** ERROR only after OUTAGE_ESCALATE_MS of visible, on-time outage; re-armed
|
|
297
334
|
* on each return so an outage that began hidden still escalates (S3). */
|
|
298
335
|
private armEscalation;
|
|
336
|
+
private dispatchMessage;
|
|
299
337
|
private handleMessage;
|
|
300
338
|
private handleSocketCatchup;
|
|
301
339
|
/** Returns false when a forward gap prevented application. */
|
|
@@ -330,6 +368,7 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
330
368
|
private cancelResyncFailureRetry;
|
|
331
369
|
private sendConnect;
|
|
332
370
|
private connectMessage;
|
|
371
|
+
private socketUrl;
|
|
333
372
|
private sendRaw;
|
|
334
373
|
private trySend;
|
|
335
374
|
private flushViaBeacon;
|
|
@@ -341,6 +380,58 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
341
380
|
private halt;
|
|
342
381
|
private clearConnectionTimers;
|
|
343
382
|
private clearAllTimers;
|
|
383
|
+
/** Live: the socket is open and, in hub mode, the hub answered our
|
|
384
|
+
* `connect` and the last app request succeeded (a pong overdue replaces
|
|
385
|
+
* the socket, so an open one has been heard from recently). */
|
|
386
|
+
private isLive;
|
|
387
|
+
private isQuietHubClose;
|
|
388
|
+
/** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
|
|
389
|
+
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
390
|
+
* `connecting`, or `disconnected` once something has failed. */
|
|
391
|
+
private refreshHubState;
|
|
392
|
+
private handleHubMessage;
|
|
393
|
+
/** The hub routes hints to this socket from now on. Established still
|
|
394
|
+
* needs a catch-up that began after this (design §5.4); one queues behind
|
|
395
|
+
* a catch-up already in flight. */
|
|
396
|
+
private onHubAck;
|
|
397
|
+
/** Two missed pongs replace the socket like a rollover (no outage); hints
|
|
398
|
+
* sent to it meanwhile are lost, and the new socket's ack catches up. */
|
|
399
|
+
private hubPingTick;
|
|
400
|
+
/** `sync_available`: leading-edge debounce. The first hint catches up at
|
|
401
|
+
* once; hints in the next 500 ms fold into one trailing catch-up. */
|
|
402
|
+
private onSyncHint;
|
|
403
|
+
private openHintWindow;
|
|
404
|
+
/** While visible, a catch-up at least every 2 minutes whatever the hub
|
|
405
|
+
* socket's state; any successful app request restarts the wait. */
|
|
406
|
+
private armFloor;
|
|
407
|
+
private cancelFloor;
|
|
408
|
+
private appSucceeded;
|
|
409
|
+
/** A POST or catch-up got no usable answer: the outage starts (if it had
|
|
410
|
+
* not), and a visible page retries on the app-request ladder whatever the
|
|
411
|
+
* hub socket's state. An expired session halts instead. */
|
|
412
|
+
private appFailed;
|
|
413
|
+
/** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
|
|
414
|
+
* already scheduled stands. */
|
|
415
|
+
private scheduleAppRetry;
|
|
416
|
+
private cancelAppRetry;
|
|
417
|
+
/** A POST when edits are unsettled (its response carries the catch-up),
|
|
418
|
+
* else a catch-up. */
|
|
419
|
+
private retryAppRequest;
|
|
420
|
+
/** Re-send paths (established, resync, return): post the unsettled edits
|
|
421
|
+
* unless a POST is already in flight. */
|
|
422
|
+
private kickPost;
|
|
423
|
+
/** Hub mode's mutation path: every unsettled edit in one POST, one POST in
|
|
424
|
+
* flight per tab. An edit submitted meanwhile posts after it succeeds; a
|
|
425
|
+
* failure leaves the retry to the app-request ladder. */
|
|
426
|
+
private runPost;
|
|
427
|
+
private postOnce;
|
|
428
|
+
/** The catch-up slice first: contiguous from the request's `lastSeq`, it
|
|
429
|
+
* carries the own events in order with any writer that interleaved, so no
|
|
430
|
+
* forward gap trips a resync. Then the outcomes: frames confirm their
|
|
431
|
+
* pending entry by GUID even at or below the tab's sequence (a resync may
|
|
432
|
+
* have moved it past them, review round 2 B1); rejections settle as on
|
|
433
|
+
* the socket. */
|
|
434
|
+
private applyPostResponse;
|
|
344
435
|
private detachSocket;
|
|
345
436
|
private abortable;
|
|
346
437
|
private abortFetches;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { FirstLoadRetry } from './first-load-retry.js';
|
|
2
|
+
import { CLOSE_HUB_IDLE, CLOSE_TRY_AGAIN_LATER, HUB_FLOOR_MS, HUB_HINT_DEBOUNCE_MS, HUB_PONG_TIMEOUT_MS, hubSocketUrl, parseHubFrame, } from './hub.js';
|
|
2
3
|
const RECONNECT_DELAYS_SECONDS = [1, 2, 4, 8, 16, 30];
|
|
3
4
|
const PING_INTERVAL_MS = 30_000;
|
|
4
5
|
// Deliberate (2026-10-20 review, task 1e2cd274): todo's phone hit it 27
|
|
@@ -53,6 +54,9 @@ const SLOW_HANDSHAKE_MS = 3_000;
|
|
|
53
54
|
const STALL_MIN_MS = 1_000;
|
|
54
55
|
const SOCKET_CONNECTING = 0;
|
|
55
56
|
const SOCKET_OPEN = 1;
|
|
57
|
+
/** Outage logs' `closeCode` when a failed app request, not a socket close,
|
|
58
|
+
* began the outage (hub mode). */
|
|
59
|
+
const APP_REQUEST_FAILED = 0;
|
|
56
60
|
function messageType(raw) {
|
|
57
61
|
try {
|
|
58
62
|
return JSON.parse(raw)?.type;
|
|
@@ -150,8 +154,41 @@ export class SyncClient {
|
|
|
150
154
|
backgroundSocketAttempts: 0,
|
|
151
155
|
httpPostedEvents: 0,
|
|
152
156
|
};
|
|
157
|
+
// Hub mode (null `hub`: same-origin, and none of these move). The socket
|
|
158
|
+
// fields above then hold the hub socket; the app's own reachability has
|
|
159
|
+
// its own ladder here, independent of the socket's.
|
|
160
|
+
hub;
|
|
161
|
+
/** The live hub socket answered our `connect`. */
|
|
162
|
+
hubAcked = false;
|
|
163
|
+
hubLastHeardAt = 0;
|
|
164
|
+
hubAwaitingPong = false;
|
|
165
|
+
/** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
|
|
166
|
+
appOk = true;
|
|
167
|
+
/** The app-request ladder's step, reset by any app success and on return. */
|
|
168
|
+
appAttempts = 0;
|
|
169
|
+
/** Visible app-request failures in this outage and spell, for its logs. */
|
|
170
|
+
appFailuresInOutage = 0;
|
|
171
|
+
appRetryTimer = null;
|
|
172
|
+
appRetryAt = null;
|
|
173
|
+
/** When the hub socket's ladder retries (its countdown, for the state). */
|
|
174
|
+
hubRetryAt = null;
|
|
175
|
+
floorTimer = null;
|
|
176
|
+
hintWindowTimer = null;
|
|
177
|
+
hintTrailing = false;
|
|
178
|
+
/** One catch-up may wait behind the one in flight. */
|
|
179
|
+
catchupQueued = false;
|
|
180
|
+
postInFlight = null;
|
|
181
|
+
/** An edit was submitted while a POST was in flight: post again after it. */
|
|
182
|
+
postAgain = false;
|
|
153
183
|
constructor(options) {
|
|
154
184
|
this.options = options;
|
|
185
|
+
if (!options.hubUrl) {
|
|
186
|
+
this.hub = null;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (!options.app || !options.postEvents)
|
|
190
|
+
throw new Error('sync hub mode needs app and postEvents');
|
|
191
|
+
this.hub = { socketUrl: hubSocketUrl(options.hubUrl, options.app), app: options.app, postEvents: options.postEvents };
|
|
155
192
|
}
|
|
156
193
|
init() {
|
|
157
194
|
if (this.disposed)
|
|
@@ -222,6 +259,11 @@ export class SyncClient {
|
|
|
222
259
|
return;
|
|
223
260
|
this.installRuntimeListeners();
|
|
224
261
|
this.connect();
|
|
262
|
+
if (this.hub) {
|
|
263
|
+
// Recovered edits go to the app at once, whatever the hub's state.
|
|
264
|
+
this.armFloor();
|
|
265
|
+
this.kickPost();
|
|
266
|
+
}
|
|
225
267
|
}
|
|
226
268
|
/** The first bootstrap. One that gets no HTTP answer (fetch's TypeError: no
|
|
227
269
|
* network, or one that reaches nothing — a tab Android Chrome restored from
|
|
@@ -327,10 +369,19 @@ export class SyncClient {
|
|
|
327
369
|
this.pending.set(event.eventGuid, entry);
|
|
328
370
|
this.options.store.applyOptimistic(event);
|
|
329
371
|
this.armFailureTimer(event.eventGuid);
|
|
330
|
-
this.
|
|
372
|
+
if (this.hub) {
|
|
373
|
+
// Every mutation goes over POST, one request in flight per tab.
|
|
374
|
+
if (this.postInFlight !== null)
|
|
375
|
+
this.postAgain = true;
|
|
376
|
+
else
|
|
377
|
+
this.kickPost();
|
|
378
|
+
}
|
|
379
|
+
else {
|
|
380
|
+
this.trySend(entry);
|
|
381
|
+
}
|
|
331
382
|
// A visible page in an outage delivers over HTTP at once rather than
|
|
332
383
|
// waiting for a handshake that may be stuck behind another one.
|
|
333
|
-
if (!this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
|
|
384
|
+
if (!this.hub && !this.isHidden() && this.outageStartedAt !== null && this.socket?.readyState !== SOCKET_OPEN) {
|
|
334
385
|
void this.probeSession();
|
|
335
386
|
}
|
|
336
387
|
this.updatePendingState();
|
|
@@ -359,7 +410,9 @@ export class SyncClient {
|
|
|
359
410
|
this.options.onSafetyChange?.();
|
|
360
411
|
}
|
|
361
412
|
refreshConnectionForBuild() {
|
|
362
|
-
|
|
413
|
+
// A hub socket is on no app instance: replacing every page's hub socket
|
|
414
|
+
// on every app deploy would be a reconnect storm for nothing.
|
|
415
|
+
if (this.halted || this.disposed || this.hub)
|
|
363
416
|
return;
|
|
364
417
|
this.options.logger.info('sync reconnect for traffic build');
|
|
365
418
|
this.replaceSocket();
|
|
@@ -480,6 +533,18 @@ export class SyncClient {
|
|
|
480
533
|
if (this.connectReplyTimer !== null)
|
|
481
534
|
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
482
535
|
this.connectReplyTimer = null;
|
|
536
|
+
if (this.hub) {
|
|
537
|
+
// No app-request ladder and no floor while hidden. A tab that keeps
|
|
538
|
+
// its hub socket acts on hints and also runs the 5-minute tick, in
|
|
539
|
+
// case a hint was lost; it was current a moment ago.
|
|
540
|
+
this.cancelAppRetry();
|
|
541
|
+
this.cancelFloor();
|
|
542
|
+
if (this.socket !== null) {
|
|
543
|
+
this.lastTickAt = this.now();
|
|
544
|
+
this.armBackgroundTick();
|
|
545
|
+
this.refreshHubState();
|
|
546
|
+
}
|
|
547
|
+
}
|
|
483
548
|
// A ladder waiting to retry is cancelled: no reconnects while hidden.
|
|
484
549
|
if (this.socket === null)
|
|
485
550
|
this.enterDormant();
|
|
@@ -506,11 +571,17 @@ export class SyncClient {
|
|
|
506
571
|
// (a phone shown for a second, often before its network is back) must
|
|
507
572
|
// not stretch this return's retry to 8-30 s or add up to a WARN.
|
|
508
573
|
this.reconnectAttempts = 0;
|
|
574
|
+
this.appAttempts = 0;
|
|
575
|
+
this.appFailuresInOutage = 0;
|
|
509
576
|
}
|
|
510
577
|
this.wakeConnection();
|
|
511
578
|
// Always: a socket that looks open may be dead (review S2), and a
|
|
512
579
|
// handshake may be slow. One HTTP round trip makes the page current.
|
|
513
580
|
void this.runCatchup('return');
|
|
581
|
+
if (this.hub) {
|
|
582
|
+
this.armFloor();
|
|
583
|
+
this.kickPost();
|
|
584
|
+
}
|
|
514
585
|
}
|
|
515
586
|
onOnline() {
|
|
516
587
|
if (this.halted || this.disposed)
|
|
@@ -524,15 +595,26 @@ export class SyncClient {
|
|
|
524
595
|
return;
|
|
525
596
|
}
|
|
526
597
|
this.wakeConnection();
|
|
598
|
+
if (this.hub && !this.appOk) {
|
|
599
|
+
this.cancelAppRetry();
|
|
600
|
+
void this.retryAppRequest();
|
|
601
|
+
}
|
|
527
602
|
}
|
|
528
603
|
wakeConnection() {
|
|
529
604
|
if (this.halted || this.disposed)
|
|
530
605
|
return;
|
|
531
606
|
const socket = this.socket;
|
|
532
607
|
if (socket?.readyState === SOCKET_OPEN) {
|
|
533
|
-
this.
|
|
534
|
-
|
|
535
|
-
|
|
608
|
+
if (this.hub) {
|
|
609
|
+
// Ask the hub at once: any frame within 5 s says the socket lives.
|
|
610
|
+
this.sendRaw({ type: 'ping' });
|
|
611
|
+
this.hubAwaitingPong = true;
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
this.sendConnect();
|
|
615
|
+
}
|
|
616
|
+
// A socket that looks open may be half-dead: no catch-up reply (hub
|
|
617
|
+
// mode: no frame at all) in 5 s replaces it.
|
|
536
618
|
if (this.connectReplyTimer !== null)
|
|
537
619
|
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
538
620
|
this.connectReplyTimer = this.setTimer(() => {
|
|
@@ -572,6 +654,7 @@ export class SyncClient {
|
|
|
572
654
|
replaceSocket() {
|
|
573
655
|
const previous = this.socket;
|
|
574
656
|
this.socket = null;
|
|
657
|
+
this.hubAcked = false;
|
|
575
658
|
this.clearConnectionTimers();
|
|
576
659
|
this.dropCandidate();
|
|
577
660
|
if (previous) {
|
|
@@ -583,12 +666,14 @@ export class SyncClient {
|
|
|
583
666
|
connect() {
|
|
584
667
|
if (this.halted || this.disposed)
|
|
585
668
|
return;
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
669
|
+
if (!this.hub) {
|
|
670
|
+
this.publish(this.reconnectAttempts > 0
|
|
671
|
+
? { kind: 'disconnected', pending: this.pendingCount() }
|
|
672
|
+
: { kind: 'connecting', pending: this.pendingCount() });
|
|
673
|
+
}
|
|
589
674
|
let socket;
|
|
590
675
|
try {
|
|
591
|
-
socket = this.options.runtime.createSocket(this.
|
|
676
|
+
socket = this.options.runtime.createSocket(this.socketUrl());
|
|
592
677
|
}
|
|
593
678
|
catch (error) {
|
|
594
679
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -600,6 +685,8 @@ export class SyncClient {
|
|
|
600
685
|
return;
|
|
601
686
|
}
|
|
602
687
|
this.socket = socket;
|
|
688
|
+
this.hubAcked = false;
|
|
689
|
+
this.refreshHubState();
|
|
603
690
|
this.socketCreatedAt = this.options.runtime.now();
|
|
604
691
|
this.socketCreatedHidden = this.isHidden();
|
|
605
692
|
this.socketOpenedAt = null;
|
|
@@ -631,7 +718,14 @@ export class SyncClient {
|
|
|
631
718
|
hidden: this.isHidden(),
|
|
632
719
|
});
|
|
633
720
|
}
|
|
634
|
-
this.
|
|
721
|
+
if (this.hub) {
|
|
722
|
+
// A hidden tab with a hub socket keeps its 5-minute tick.
|
|
723
|
+
this.hubLastHeardAt = this.now();
|
|
724
|
+
this.hubAwaitingPong = false;
|
|
725
|
+
}
|
|
726
|
+
else {
|
|
727
|
+
this.cancelBackgroundTick();
|
|
728
|
+
}
|
|
635
729
|
this.sendConnect();
|
|
636
730
|
this.startLiveTimers();
|
|
637
731
|
};
|
|
@@ -644,7 +738,7 @@ export class SyncClient {
|
|
|
644
738
|
if (this.socket !== socket)
|
|
645
739
|
return;
|
|
646
740
|
this.lastContactAt = this.now();
|
|
647
|
-
this.
|
|
741
|
+
this.dispatchMessage(String(event.data));
|
|
648
742
|
};
|
|
649
743
|
socket.onerror = () => {
|
|
650
744
|
// Browsers expose no useful detail; the close event owns recovery.
|
|
@@ -654,6 +748,7 @@ export class SyncClient {
|
|
|
654
748
|
return;
|
|
655
749
|
this.clearConnectionTimers();
|
|
656
750
|
this.socket = null;
|
|
751
|
+
this.hubAcked = false;
|
|
657
752
|
if (this.halted || this.disposed)
|
|
658
753
|
return;
|
|
659
754
|
const socketAgeMs = this.now() - this.socketCreatedAt;
|
|
@@ -666,20 +761,27 @@ export class SyncClient {
|
|
|
666
761
|
});
|
|
667
762
|
}
|
|
668
763
|
if (event.code === CLOSE_NO_USER) {
|
|
669
|
-
this.
|
|
670
|
-
|
|
671
|
-
|
|
764
|
+
if (!this.hub) {
|
|
765
|
+
this.options.authState.markBlocked();
|
|
766
|
+
this.halt();
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
// Hub mode: the hub found no identity. The app decides whether the
|
|
770
|
+
// session is gone (its auth failure halts through the auth state);
|
|
771
|
+
// if it answers, the ladder below reconnects.
|
|
772
|
+
void this.runCatchup('probe');
|
|
672
773
|
}
|
|
673
774
|
const openForMs = this.socketOpenedAt === null ? null : Math.max(0, this.now() - this.socketOpenedAt);
|
|
674
775
|
// Ended before its replacement took over: start afresh rather than wait
|
|
675
776
|
// on a handshake begun for a handover.
|
|
676
777
|
const rolling = this.candidate !== null;
|
|
677
778
|
this.dropCandidate();
|
|
678
|
-
if (event.code === CLOSE_SERVICE_RESTART) {
|
|
779
|
+
if (event.code === CLOSE_SERVICE_RESTART || this.isQuietHubClose(event.code)) {
|
|
679
780
|
// The server's planned close (its age cap: a tab whose own rollover
|
|
680
781
|
// didn't run, such as a frozen one): reconnect at once, as after our
|
|
681
782
|
// own rollover, with no outage and no ladder step. A failure of that
|
|
682
|
-
// reconnect is an ordinary outage.
|
|
783
|
+
// reconnect is an ordinary outage. The hub's 1013 (its auth check
|
|
784
|
+
// was unavailable) and 4408 (it heard nothing for 180 s) are the same.
|
|
683
785
|
this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
|
|
684
786
|
this.connectNow();
|
|
685
787
|
return;
|
|
@@ -698,7 +800,7 @@ export class SyncClient {
|
|
|
698
800
|
};
|
|
699
801
|
}
|
|
700
802
|
startLiveTimers() {
|
|
701
|
-
this.pingTimer = this.setRepeating(() => this.sendRaw({ type: 'ping' }), PING_INTERVAL_MS);
|
|
803
|
+
this.pingTimer = this.setRepeating(() => (this.hub ? this.hubPingTick() : this.sendRaw({ type: 'ping' })), PING_INTERVAL_MS);
|
|
702
804
|
this.armRollover();
|
|
703
805
|
}
|
|
704
806
|
armRollover() {
|
|
@@ -724,7 +826,7 @@ export class SyncClient {
|
|
|
724
826
|
return;
|
|
725
827
|
let socket;
|
|
726
828
|
try {
|
|
727
|
-
socket = this.options.runtime.createSocket(this.
|
|
829
|
+
socket = this.options.runtime.createSocket(this.socketUrl());
|
|
728
830
|
}
|
|
729
831
|
catch (error) {
|
|
730
832
|
this.options.logger.warn('socket creation failed', { error });
|
|
@@ -765,30 +867,36 @@ export class SyncClient {
|
|
|
765
867
|
return;
|
|
766
868
|
const raw = String(event.data);
|
|
767
869
|
const type = messageType(raw);
|
|
768
|
-
|
|
870
|
+
// The hub answers `connect` with `ack` (it sends no catch-up).
|
|
871
|
+
const answered = this.hub ? type === 'ack' : type === 'catchup' || type === 'reload';
|
|
872
|
+
if (!answered) {
|
|
769
873
|
candidate.early.push(raw);
|
|
770
874
|
return;
|
|
771
875
|
}
|
|
772
876
|
this.promoteCandidate(candidate);
|
|
773
877
|
this.lastContactAt = this.now();
|
|
774
|
-
this.
|
|
878
|
+
this.dispatchMessage(raw);
|
|
775
879
|
for (const early of candidate.early) {
|
|
776
880
|
if (this.socket !== socket)
|
|
777
881
|
return;
|
|
778
|
-
this.
|
|
882
|
+
this.dispatchMessage(early);
|
|
779
883
|
}
|
|
780
884
|
};
|
|
781
885
|
socket.onerror = () => { };
|
|
782
886
|
socket.onclose = (event) => {
|
|
783
887
|
if (this.candidate !== candidate)
|
|
784
888
|
return;
|
|
785
|
-
if (event.code === CLOSE_NO_USER) {
|
|
889
|
+
if (event.code === CLOSE_NO_USER && !this.hub) {
|
|
786
890
|
this.dropCandidate();
|
|
787
891
|
this.options.authState.markBlocked();
|
|
788
892
|
this.halt();
|
|
789
893
|
return;
|
|
790
894
|
}
|
|
791
895
|
this.dropCandidate({ closeCode: event.code });
|
|
896
|
+
// Hub mode: the live socket keeps serving; the app decides whether the
|
|
897
|
+
// session is gone.
|
|
898
|
+
if (event.code === CLOSE_NO_USER)
|
|
899
|
+
void this.runCatchup('probe');
|
|
792
900
|
};
|
|
793
901
|
}
|
|
794
902
|
promoteCandidate(candidate) {
|
|
@@ -807,6 +915,8 @@ export class SyncClient {
|
|
|
807
915
|
this.socketCreatedAt = candidate.createdAt;
|
|
808
916
|
this.socketCreatedHidden = candidate.createdHidden;
|
|
809
917
|
this.socketOpenedAt = candidate.openedAt;
|
|
918
|
+
this.hubLastHeardAt = now;
|
|
919
|
+
this.hubAwaitingPong = false;
|
|
810
920
|
candidate.socket.onopen = null;
|
|
811
921
|
this.attachLiveHandlers(candidate.socket, () => false);
|
|
812
922
|
this.startLiveTimers();
|
|
@@ -847,11 +957,16 @@ export class SyncClient {
|
|
|
847
957
|
this.options.runtime.clearInterval(this.countdownTimer);
|
|
848
958
|
this.reconnectTimer = null;
|
|
849
959
|
this.countdownTimer = null;
|
|
960
|
+
this.hubRetryAt = null;
|
|
961
|
+
this.cancelAppRetry();
|
|
850
962
|
this.publish({ kind: 'disconnected', pending: this.pendingCount() });
|
|
851
963
|
if (!this.options.postEvents && !this.beaconedWhileDormant && this.unsettledPending().length > 0) {
|
|
852
964
|
this.beaconedWhileDormant = true;
|
|
853
965
|
this.flushViaBeacon();
|
|
854
966
|
}
|
|
967
|
+
this.armBackgroundTick();
|
|
968
|
+
}
|
|
969
|
+
armBackgroundTick() {
|
|
855
970
|
if (this.backgroundTickTimer !== null)
|
|
856
971
|
return;
|
|
857
972
|
const interval = this.options.backgroundCatchupMs ?? DEFAULT_BACKGROUND_CATCHUP_MS;
|
|
@@ -867,17 +982,28 @@ export class SyncClient {
|
|
|
867
982
|
this.backgroundTickTimer = null;
|
|
868
983
|
}
|
|
869
984
|
async backgroundTick() {
|
|
870
|
-
if (this.halted || this.disposed || !this.isHidden()
|
|
985
|
+
if (this.halted || this.disposed || !this.isHidden())
|
|
986
|
+
return;
|
|
987
|
+
// Same-origin: a live socket is the page's feed. Hub mode: hints can be
|
|
988
|
+
// lost, so the tick runs beside the hub socket too (design §5.5).
|
|
989
|
+
if (!this.hub && this.socket !== null)
|
|
871
990
|
return;
|
|
872
991
|
this.lastTickAt = this.now();
|
|
873
992
|
await this.postPendingOverHttp();
|
|
874
993
|
const ok = await this.runCatchup('background');
|
|
875
|
-
if (this.halted || this.disposed || !this.isHidden()
|
|
994
|
+
if (this.halted || this.disposed || !this.isHidden())
|
|
995
|
+
return;
|
|
996
|
+
if (this.socket !== null) {
|
|
997
|
+
if (this.hub)
|
|
998
|
+
this.armBackgroundTick();
|
|
876
999
|
return;
|
|
1000
|
+
}
|
|
877
1001
|
if (ok && !this.hiddenSocketFailed) {
|
|
878
1002
|
// Desktop hidden sockets usually live; one attempt per tick, none after
|
|
879
1003
|
// the first hidden failure in this spell (phones cut them in seconds).
|
|
880
1004
|
this.connectNow();
|
|
1005
|
+
if (this.hub)
|
|
1006
|
+
this.armBackgroundTick();
|
|
881
1007
|
return;
|
|
882
1008
|
}
|
|
883
1009
|
this.enterDormant();
|
|
@@ -886,6 +1012,8 @@ export class SyncClient {
|
|
|
886
1012
|
return [...this.pending.values()].filter((entry) => !this.settledPending.has(entry.event.eventGuid));
|
|
887
1013
|
}
|
|
888
1014
|
async postPendingOverHttp() {
|
|
1015
|
+
if (this.hub)
|
|
1016
|
+
return this.runPost();
|
|
889
1017
|
const postEvents = this.options.postEvents;
|
|
890
1018
|
if (!postEvents)
|
|
891
1019
|
return;
|
|
@@ -918,19 +1046,27 @@ export class SyncClient {
|
|
|
918
1046
|
// Offline or timed out: the next tick, or the socket on return, retries.
|
|
919
1047
|
}
|
|
920
1048
|
}
|
|
921
|
-
/** The
|
|
922
|
-
*
|
|
1049
|
+
/** The HTTP catch-up (review S5): one slot, a return aborts any other
|
|
1050
|
+
* kind in flight, every kind gives up after 15 s. Hub mode: a request that
|
|
1051
|
+
* finds the slot busy queues one more catch-up to start when it frees (one
|
|
1052
|
+
* in flight, at most one queued), and the outcome feeds the app-request
|
|
1053
|
+
* ladder. */
|
|
923
1054
|
async runCatchup(kind) {
|
|
924
1055
|
if (this.halted || this.disposed)
|
|
925
1056
|
return false;
|
|
926
1057
|
if (this.catchupSlot !== null) {
|
|
927
|
-
if (kind === 'return' && this.catchupSlot.kind
|
|
1058
|
+
if (kind === 'return' && this.catchupSlot.kind !== 'return') {
|
|
1059
|
+
this.catchupSlot.preempted = true;
|
|
928
1060
|
this.catchupSlot.controller.abort();
|
|
929
|
-
|
|
1061
|
+
}
|
|
1062
|
+
else {
|
|
1063
|
+
if (this.hub)
|
|
1064
|
+
this.catchupQueued = true;
|
|
930
1065
|
return false;
|
|
1066
|
+
}
|
|
931
1067
|
}
|
|
932
1068
|
const controller = new AbortController();
|
|
933
|
-
const slot = { kind, controller };
|
|
1069
|
+
const slot = { kind, controller, preempted: false };
|
|
934
1070
|
this.catchupSlot = slot;
|
|
935
1071
|
this.abortControllers.add(controller);
|
|
936
1072
|
const timeout = this.setTimer(() => controller.abort(), BACKGROUND_FETCH_TIMEOUT_MS);
|
|
@@ -952,6 +1088,8 @@ export class SyncClient {
|
|
|
952
1088
|
for (const event of result.events)
|
|
953
1089
|
this.handleServerEvent(event);
|
|
954
1090
|
}
|
|
1091
|
+
if (this.hub)
|
|
1092
|
+
this.appSucceeded();
|
|
955
1093
|
return true;
|
|
956
1094
|
}
|
|
957
1095
|
catch {
|
|
@@ -973,6 +1111,15 @@ export class SyncClient {
|
|
|
973
1111
|
this.returnWindow.catchupOk = ok;
|
|
974
1112
|
this.maybeFinishReturnWindow();
|
|
975
1113
|
}
|
|
1114
|
+
if (this.hub) {
|
|
1115
|
+
// A catch-up a return replaced did not fail.
|
|
1116
|
+
if (!ok && !slot.preempted)
|
|
1117
|
+
this.appFailed();
|
|
1118
|
+
if (this.catchupQueued && this.catchupSlot === null) {
|
|
1119
|
+
this.catchupQueued = false;
|
|
1120
|
+
void this.runCatchup('hint');
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
976
1123
|
}
|
|
977
1124
|
}
|
|
978
1125
|
async withTimeout(operation) {
|
|
@@ -1047,6 +1194,7 @@ export class SyncClient {
|
|
|
1047
1194
|
this.options.runtime.clearInterval(this.countdownTimer);
|
|
1048
1195
|
this.reconnectTimer = null;
|
|
1049
1196
|
this.countdownTimer = null;
|
|
1197
|
+
this.hubRetryAt = null;
|
|
1050
1198
|
this.connect();
|
|
1051
1199
|
}
|
|
1052
1200
|
/** Records a visible socket failure inside a return window. */
|
|
@@ -1080,6 +1228,18 @@ export class SyncClient {
|
|
|
1080
1228
|
const delay = Math.ceil(delayMs / 1000);
|
|
1081
1229
|
this.reconnectAttempts++;
|
|
1082
1230
|
this.totalAttempts++;
|
|
1231
|
+
if (this.hub) {
|
|
1232
|
+
// The hub socket's ladder. App requests have their own and need no
|
|
1233
|
+
// probe from here; the state shows whichever retry comes first.
|
|
1234
|
+
this.hubRetryAt = this.now() + delayMs;
|
|
1235
|
+
this.reconnectTimer = this.setTimer(() => {
|
|
1236
|
+
this.reconnectTimer = null;
|
|
1237
|
+
this.hubRetryAt = null;
|
|
1238
|
+
this.connect();
|
|
1239
|
+
}, delayMs);
|
|
1240
|
+
this.refreshHubState();
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1083
1243
|
if (this.reconnectAttempts >= PROBE_AFTER_ATTEMPTS || this.unsettledPending().length > 0) {
|
|
1084
1244
|
void this.probeSession();
|
|
1085
1245
|
}
|
|
@@ -1178,6 +1338,12 @@ export class SyncClient {
|
|
|
1178
1338
|
}
|
|
1179
1339
|
}, OUTAGE_ESCALATE_MS);
|
|
1180
1340
|
}
|
|
1341
|
+
dispatchMessage(raw) {
|
|
1342
|
+
if (this.hub)
|
|
1343
|
+
this.handleHubMessage(raw, this.hub.app);
|
|
1344
|
+
else
|
|
1345
|
+
this.handleMessage(raw);
|
|
1346
|
+
}
|
|
1181
1347
|
handleMessage(raw) {
|
|
1182
1348
|
let message;
|
|
1183
1349
|
try {
|
|
@@ -1490,7 +1656,8 @@ export class SyncClient {
|
|
|
1490
1656
|
// Failures are only counted (and the ladder only runs) while visible,
|
|
1491
1657
|
// and the count restarts on each return, so `attempts` is what the
|
|
1492
1658
|
// user could have waited through; `totalAttempts` spans every spell.
|
|
1493
|
-
|
|
1659
|
+
// Hub mode counts the hub socket's and the app's failures together.
|
|
1660
|
+
const attempts = this.reconnectAttempts + this.appFailuresInOutage;
|
|
1494
1661
|
const info = this.outageInfo;
|
|
1495
1662
|
const delta = info ? SyncClient.delta(info.counters, this.snapshot()) : null;
|
|
1496
1663
|
const fields = {
|
|
@@ -1534,6 +1701,7 @@ export class SyncClient {
|
|
|
1534
1701
|
this.escalateTimer = null;
|
|
1535
1702
|
this.reconnectAttempts = 0;
|
|
1536
1703
|
this.totalAttempts = 0;
|
|
1704
|
+
this.appFailuresInOutage = 0;
|
|
1537
1705
|
for (const [eventGuid, entry] of this.pending) {
|
|
1538
1706
|
if (this.settledPending.has(eventGuid)) {
|
|
1539
1707
|
this.retrySettlement(eventGuid);
|
|
@@ -1545,7 +1713,10 @@ export class SyncClient {
|
|
|
1545
1713
|
// A complete catch-up IS convergence: end any stall episode and cancel
|
|
1546
1714
|
// its pending backoff retry.
|
|
1547
1715
|
this.endResyncEpisode();
|
|
1548
|
-
this.
|
|
1716
|
+
if (this.hub)
|
|
1717
|
+
this.refreshHubState();
|
|
1718
|
+
else
|
|
1719
|
+
this.updateConnectedState();
|
|
1549
1720
|
}
|
|
1550
1721
|
requestReload(reason) {
|
|
1551
1722
|
// While a resync is reconciling or backing off, further triggers are
|
|
@@ -1677,8 +1848,14 @@ export class SyncClient {
|
|
|
1677
1848
|
this.sendRaw(this.connectMessage());
|
|
1678
1849
|
}
|
|
1679
1850
|
connectMessage() {
|
|
1851
|
+
// The hub routes by user and never sees sequences.
|
|
1852
|
+
if (this.hub)
|
|
1853
|
+
return { type: 'connect', clientGuid: this.options.clientGuid };
|
|
1680
1854
|
return { type: 'connect', clientGuid: this.options.clientGuid, lastSeq: this.options.store.currentSeq() };
|
|
1681
1855
|
}
|
|
1856
|
+
socketUrl() {
|
|
1857
|
+
return this.hub?.socketUrl ?? this.options.socketUrl();
|
|
1858
|
+
}
|
|
1682
1859
|
sendRaw(message) {
|
|
1683
1860
|
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
1684
1861
|
return;
|
|
@@ -1692,6 +1869,11 @@ export class SyncClient {
|
|
|
1692
1869
|
trySend(entry) {
|
|
1693
1870
|
if (this.settledPending.has(entry.event.eventGuid))
|
|
1694
1871
|
return;
|
|
1872
|
+
// Hub mode: nothing mutating ever goes on the hub socket.
|
|
1873
|
+
if (this.hub) {
|
|
1874
|
+
this.kickPost();
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1695
1877
|
this.sendRaw({ type: 'event', clientGuid: this.options.clientGuid, event: entry.event });
|
|
1696
1878
|
}
|
|
1697
1879
|
flushViaBeacon() {
|
|
@@ -1709,7 +1891,7 @@ export class SyncClient {
|
|
|
1709
1891
|
this.options.runtime.sendBeacon(this.options.beaconUrl, new Blob([body], { type: 'application/json' }));
|
|
1710
1892
|
}
|
|
1711
1893
|
updateConnectedState() {
|
|
1712
|
-
if (this.halted || this.disposed || this.
|
|
1894
|
+
if (this.halted || this.disposed || !this.isLive())
|
|
1713
1895
|
return;
|
|
1714
1896
|
const pending = this.pendingCount();
|
|
1715
1897
|
this.publish(pending > 0 ? { kind: 'syncing', pending } : { kind: 'connected', pending: 0 });
|
|
@@ -1717,7 +1899,7 @@ export class SyncClient {
|
|
|
1717
1899
|
updatePendingState() {
|
|
1718
1900
|
if (this.halted || this.disposed)
|
|
1719
1901
|
return;
|
|
1720
|
-
if (this.
|
|
1902
|
+
if (this.isLive()) {
|
|
1721
1903
|
this.updateConnectedState();
|
|
1722
1904
|
return;
|
|
1723
1905
|
}
|
|
@@ -1805,6 +1987,12 @@ export class SyncClient {
|
|
|
1805
1987
|
for (const timer of this.failureTimers.values())
|
|
1806
1988
|
this.options.runtime.clearTimeout(timer);
|
|
1807
1989
|
this.cancelBackgroundTick();
|
|
1990
|
+
this.cancelAppRetry();
|
|
1991
|
+
this.cancelFloor();
|
|
1992
|
+
if (this.hintWindowTimer !== null)
|
|
1993
|
+
this.options.runtime.clearTimeout(this.hintWindowTimer);
|
|
1994
|
+
this.hintWindowTimer = null;
|
|
1995
|
+
this.hubRetryAt = null;
|
|
1808
1996
|
if (this.returnWindow !== null)
|
|
1809
1997
|
this.options.runtime.clearTimeout(this.returnWindow.timer);
|
|
1810
1998
|
this.returnWindow = null;
|
|
@@ -1814,6 +2002,262 @@ export class SyncClient {
|
|
|
1814
2002
|
this.resyncBackoffTimer = null;
|
|
1815
2003
|
this.failureTimers.clear();
|
|
1816
2004
|
}
|
|
2005
|
+
/** Live: the socket is open and, in hub mode, the hub answered our
|
|
2006
|
+
* `connect` and the last app request succeeded (a pong overdue replaces
|
|
2007
|
+
* the socket, so an open one has been heard from recently). */
|
|
2008
|
+
isLive() {
|
|
2009
|
+
if (this.socket?.readyState !== SOCKET_OPEN)
|
|
2010
|
+
return false;
|
|
2011
|
+
return this.hub === null || (this.hubAcked && this.appOk);
|
|
2012
|
+
}
|
|
2013
|
+
isQuietHubClose(code) {
|
|
2014
|
+
return this.hub !== null && (code === CLOSE_TRY_AGAIN_LATER || code === CLOSE_HUB_IDLE);
|
|
2015
|
+
}
|
|
2016
|
+
/** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
|
|
2017
|
+
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
2018
|
+
* `connecting`, or `disconnected` once something has failed. */
|
|
2019
|
+
refreshHubState() {
|
|
2020
|
+
if (!this.hub || this.halted || this.disposed)
|
|
2021
|
+
return;
|
|
2022
|
+
const retries = [this.hubRetryAt, this.appRetryAt].filter((at) => at !== null);
|
|
2023
|
+
const live = this.isLive();
|
|
2024
|
+
if ((live || retries.length === 0) && this.countdownTimer !== null) {
|
|
2025
|
+
this.options.runtime.clearInterval(this.countdownTimer);
|
|
2026
|
+
this.countdownTimer = null;
|
|
2027
|
+
}
|
|
2028
|
+
if (live) {
|
|
2029
|
+
this.updateConnectedState();
|
|
2030
|
+
return;
|
|
2031
|
+
}
|
|
2032
|
+
const pending = this.pendingCount();
|
|
2033
|
+
if (retries.length > 0) {
|
|
2034
|
+
const inSeconds = Math.max(1, Math.ceil((Math.min(...retries) - this.now()) / 1000));
|
|
2035
|
+
this.publish({ kind: 'reconnecting', pending, inSeconds });
|
|
2036
|
+
if (this.countdownTimer === null)
|
|
2037
|
+
this.countdownTimer = this.setRepeating(() => this.refreshHubState(), 1000);
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
const failed = this.reconnectAttempts > 0 || this.appAttempts > 0 || this.socket === null;
|
|
2041
|
+
this.publish({ kind: failed ? 'disconnected' : 'connecting', pending });
|
|
2042
|
+
}
|
|
2043
|
+
handleHubMessage(raw, app) {
|
|
2044
|
+
// Any frame is a sign of life (radar's rule): the pong watchdog and the
|
|
2045
|
+
// return's 5 s check.
|
|
2046
|
+
this.hubLastHeardAt = this.now();
|
|
2047
|
+
this.hubAwaitingPong = false;
|
|
2048
|
+
if (this.connectReplyTimer !== null)
|
|
2049
|
+
this.options.runtime.clearTimeout(this.connectReplyTimer);
|
|
2050
|
+
this.connectReplyTimer = null;
|
|
2051
|
+
const frame = parseHubFrame(raw, app);
|
|
2052
|
+
switch (frame.kind) {
|
|
2053
|
+
case 'unparseable':
|
|
2054
|
+
this.options.logger.warn('unparseable hub message', { raw: raw.slice(0, 200) });
|
|
2055
|
+
return;
|
|
2056
|
+
case 'ack':
|
|
2057
|
+
this.onHubAck();
|
|
2058
|
+
return;
|
|
2059
|
+
case 'sync_available':
|
|
2060
|
+
this.onSyncHint();
|
|
2061
|
+
return;
|
|
2062
|
+
case 'build_changed':
|
|
2063
|
+
this.options.onBuildChanged?.();
|
|
2064
|
+
return;
|
|
2065
|
+
case 'life':
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
/** The hub routes hints to this socket from now on. Established still
|
|
2070
|
+
* needs a catch-up that began after this (design §5.4); one queues behind
|
|
2071
|
+
* a catch-up already in flight. */
|
|
2072
|
+
onHubAck() {
|
|
2073
|
+
if (this.hubAcked)
|
|
2074
|
+
return;
|
|
2075
|
+
this.hubAcked = true;
|
|
2076
|
+
this.refreshHubState();
|
|
2077
|
+
void this.runCatchup('connect');
|
|
2078
|
+
}
|
|
2079
|
+
/** Two missed pongs replace the socket like a rollover (no outage); hints
|
|
2080
|
+
* sent to it meanwhile are lost, and the new socket's ack catches up. */
|
|
2081
|
+
hubPingTick() {
|
|
2082
|
+
const now = this.now();
|
|
2083
|
+
if (this.hubAwaitingPong && now - this.hubLastHeardAt >= HUB_PONG_TIMEOUT_MS) {
|
|
2084
|
+
this.options.logger.info('hub pong timeout', {
|
|
2085
|
+
silentForMs: now - this.hubLastHeardAt,
|
|
2086
|
+
openForMs: this.socketOpenedAt === null ? null : Math.max(0, now - this.socketOpenedAt),
|
|
2087
|
+
});
|
|
2088
|
+
this.replaceSocket();
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
this.sendRaw({ type: 'ping' });
|
|
2092
|
+
this.hubAwaitingPong = true;
|
|
2093
|
+
}
|
|
2094
|
+
/** `sync_available`: leading-edge debounce. The first hint catches up at
|
|
2095
|
+
* once; hints in the next 500 ms fold into one trailing catch-up. */
|
|
2096
|
+
onSyncHint() {
|
|
2097
|
+
if (this.hintWindowTimer !== null) {
|
|
2098
|
+
this.hintTrailing = true;
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
void this.runCatchup('hint');
|
|
2102
|
+
this.openHintWindow();
|
|
2103
|
+
}
|
|
2104
|
+
openHintWindow() {
|
|
2105
|
+
this.hintWindowTimer = this.setTimer(() => {
|
|
2106
|
+
this.hintWindowTimer = null;
|
|
2107
|
+
if (!this.hintTrailing)
|
|
2108
|
+
return;
|
|
2109
|
+
this.hintTrailing = false;
|
|
2110
|
+
void this.runCatchup('hint');
|
|
2111
|
+
this.openHintWindow();
|
|
2112
|
+
}, HUB_HINT_DEBOUNCE_MS);
|
|
2113
|
+
}
|
|
2114
|
+
/** While visible, a catch-up at least every 2 minutes whatever the hub
|
|
2115
|
+
* socket's state; any successful app request restarts the wait. */
|
|
2116
|
+
armFloor() {
|
|
2117
|
+
if (!this.hub || this.halted || this.disposed || this.isHidden())
|
|
2118
|
+
return;
|
|
2119
|
+
this.cancelFloor();
|
|
2120
|
+
this.floorTimer = this.setTimer(() => {
|
|
2121
|
+
this.floorTimer = null;
|
|
2122
|
+
void this.runCatchup('floor');
|
|
2123
|
+
}, HUB_FLOOR_MS);
|
|
2124
|
+
}
|
|
2125
|
+
cancelFloor() {
|
|
2126
|
+
if (this.floorTimer !== null)
|
|
2127
|
+
this.options.runtime.clearTimeout(this.floorTimer);
|
|
2128
|
+
this.floorTimer = null;
|
|
2129
|
+
}
|
|
2130
|
+
appSucceeded() {
|
|
2131
|
+
this.appOk = true;
|
|
2132
|
+
this.appAttempts = 0;
|
|
2133
|
+
this.cancelAppRetry();
|
|
2134
|
+
this.armFloor();
|
|
2135
|
+
if (this.hubAcked && this.socket?.readyState === SOCKET_OPEN)
|
|
2136
|
+
this.onSyncEstablished();
|
|
2137
|
+
else
|
|
2138
|
+
this.refreshHubState();
|
|
2139
|
+
}
|
|
2140
|
+
/** A POST or catch-up got no usable answer: the outage starts (if it had
|
|
2141
|
+
* not), and a visible page retries on the app-request ladder whatever the
|
|
2142
|
+
* hub socket's state. An expired session halts instead. */
|
|
2143
|
+
appFailed() {
|
|
2144
|
+
if (this.stopBeforeStoreMutation())
|
|
2145
|
+
return;
|
|
2146
|
+
this.appOk = false;
|
|
2147
|
+
this.startOutage(APP_REQUEST_FAILED);
|
|
2148
|
+
if (!this.isHidden()) {
|
|
2149
|
+
this.appFailuresInOutage++;
|
|
2150
|
+
this.scheduleAppRetry();
|
|
2151
|
+
}
|
|
2152
|
+
this.refreshHubState();
|
|
2153
|
+
}
|
|
2154
|
+
/** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
|
|
2155
|
+
* already scheduled stands. */
|
|
2156
|
+
scheduleAppRetry() {
|
|
2157
|
+
if (this.appRetryTimer !== null || this.isHidden() || this.halted || this.disposed)
|
|
2158
|
+
return;
|
|
2159
|
+
const ladderSeconds = RECONNECT_DELAYS_SECONDS[Math.min(this.appAttempts, RECONNECT_DELAYS_SECONDS.length - 1)];
|
|
2160
|
+
const delayMs = this.takeQuickRetry() ? RETURN_QUICK_RETRY_MS : ladderSeconds * 1000;
|
|
2161
|
+
this.appAttempts++;
|
|
2162
|
+
this.totalAttempts++;
|
|
2163
|
+
this.appRetryAt = this.now() + delayMs;
|
|
2164
|
+
this.appRetryTimer = this.setTimer(() => {
|
|
2165
|
+
this.appRetryTimer = null;
|
|
2166
|
+
this.appRetryAt = null;
|
|
2167
|
+
void this.retryAppRequest();
|
|
2168
|
+
}, delayMs);
|
|
2169
|
+
}
|
|
2170
|
+
cancelAppRetry() {
|
|
2171
|
+
if (this.appRetryTimer !== null)
|
|
2172
|
+
this.options.runtime.clearTimeout(this.appRetryTimer);
|
|
2173
|
+
this.appRetryTimer = null;
|
|
2174
|
+
this.appRetryAt = null;
|
|
2175
|
+
}
|
|
2176
|
+
/** A POST when edits are unsettled (its response carries the catch-up),
|
|
2177
|
+
* else a catch-up. */
|
|
2178
|
+
async retryAppRequest() {
|
|
2179
|
+
if (this.unsettledPending().length > 0)
|
|
2180
|
+
await this.runPost();
|
|
2181
|
+
else
|
|
2182
|
+
await this.runCatchup('retry');
|
|
2183
|
+
}
|
|
2184
|
+
/** Re-send paths (established, resync, return): post the unsettled edits
|
|
2185
|
+
* unless a POST is already in flight. */
|
|
2186
|
+
kickPost() {
|
|
2187
|
+
if (this.postInFlight === null)
|
|
2188
|
+
void this.runPost();
|
|
2189
|
+
}
|
|
2190
|
+
/** Hub mode's mutation path: every unsettled edit in one POST, one POST in
|
|
2191
|
+
* flight per tab. An edit submitted meanwhile posts after it succeeds; a
|
|
2192
|
+
* failure leaves the retry to the app-request ladder. */
|
|
2193
|
+
runPost() {
|
|
2194
|
+
if (this.postInFlight !== null)
|
|
2195
|
+
return this.postInFlight;
|
|
2196
|
+
const events = this.unsettledPending().map((entry) => entry.event);
|
|
2197
|
+
if (!this.hub || events.length === 0 || this.halted || this.disposed)
|
|
2198
|
+
return Promise.resolve();
|
|
2199
|
+
this.postAgain = false;
|
|
2200
|
+
const inFlight = this.postOnce(this.hub.postEvents, events).finally(() => {
|
|
2201
|
+
this.postInFlight = null;
|
|
2202
|
+
if (this.postAgain && this.appOk) {
|
|
2203
|
+
this.postAgain = false;
|
|
2204
|
+
this.kickPost();
|
|
2205
|
+
}
|
|
2206
|
+
});
|
|
2207
|
+
this.postInFlight = inFlight;
|
|
2208
|
+
return inFlight;
|
|
2209
|
+
}
|
|
2210
|
+
async postOnce(postEvents, events) {
|
|
2211
|
+
let response;
|
|
2212
|
+
try {
|
|
2213
|
+
response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
|
|
2214
|
+
}
|
|
2215
|
+
catch {
|
|
2216
|
+
this.appFailed();
|
|
2217
|
+
return;
|
|
2218
|
+
}
|
|
2219
|
+
if (this.stopBeforeStoreMutation())
|
|
2220
|
+
return;
|
|
2221
|
+
this.lastContactAt = this.now();
|
|
2222
|
+
this.applyPostResponse(response);
|
|
2223
|
+
if (this.stopBeforeStoreMutation())
|
|
2224
|
+
return;
|
|
2225
|
+
this.appSucceeded();
|
|
2226
|
+
// An app answering in the old shape sent no frames: the echoes come by
|
|
2227
|
+
// catch-up, as for a same-origin POST.
|
|
2228
|
+
if (response.currentSeq === undefined && !response.reload)
|
|
2229
|
+
void this.runCatchup('connect');
|
|
2230
|
+
}
|
|
2231
|
+
/** The catch-up slice first: contiguous from the request's `lastSeq`, it
|
|
2232
|
+
* carries the own events in order with any writer that interleaved, so no
|
|
2233
|
+
* forward gap trips a resync. Then the outcomes: frames confirm their
|
|
2234
|
+
* pending entry by GUID even at or below the tab's sequence (a resync may
|
|
2235
|
+
* have moved it past them, review round 2 B1); rejections settle as on
|
|
2236
|
+
* the socket. */
|
|
2237
|
+
applyPostResponse(response) {
|
|
2238
|
+
if (response.reload) {
|
|
2239
|
+
this.requestReload('server');
|
|
2240
|
+
}
|
|
2241
|
+
else {
|
|
2242
|
+
for (const event of response.events ?? [])
|
|
2243
|
+
this.handleServerEvent(event);
|
|
2244
|
+
}
|
|
2245
|
+
for (const outcome of response.outcomes) {
|
|
2246
|
+
if (this.stopBeforeStoreMutation())
|
|
2247
|
+
return;
|
|
2248
|
+
if (outcome.status === 'rejected') {
|
|
2249
|
+
this.handleRejection({
|
|
2250
|
+
type: 'rejection',
|
|
2251
|
+
eventGuid: outcome.eventGuid,
|
|
2252
|
+
error: outcome.error ?? { code: 'rejected', message: 'rejected' },
|
|
2253
|
+
});
|
|
2254
|
+
continue;
|
|
2255
|
+
}
|
|
2256
|
+
this.counters.httpPostedEvents++;
|
|
2257
|
+
for (const frame of ('events' in outcome ? outcome.events : undefined) ?? [])
|
|
2258
|
+
this.handleServerEvent(frame);
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
1817
2261
|
detachSocket(socket) {
|
|
1818
2262
|
socket.onopen = null;
|
|
1819
2263
|
socket.onmessage = null;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** The client's ping period; the hub closes a socket silent for 180 s. */
|
|
2
|
+
export declare const HUB_PING_INTERVAL_MS = 30000;
|
|
3
|
+
/** Two missed pongs: a ping unanswered and nothing heard for this long
|
|
4
|
+
* replaces the socket (any frame counts as life, as in Radar's client). */
|
|
5
|
+
export declare const HUB_PONG_TIMEOUT_MS: number;
|
|
6
|
+
/** While visible, one HTTP catch-up at least this often, whatever the hub
|
|
7
|
+
* socket's state: the bound on a lost hint (design §5.5, review C-B1). */
|
|
8
|
+
export declare const HUB_FLOOR_MS: number;
|
|
9
|
+
/** A `sync_available` hint runs a catch-up at once; further hints within
|
|
10
|
+
* this window fold into one trailing catch-up. */
|
|
11
|
+
export declare const HUB_HINT_DEBOUNCE_MS = 500;
|
|
12
|
+
/** The hub's auth check was unavailable ("try again later"): a quiet
|
|
13
|
+
* reconnect, like 1012. */
|
|
14
|
+
export declare const CLOSE_TRY_AGAIN_LATER = 1013;
|
|
15
|
+
/** The hub heard nothing on the socket for 180 s: a quiet reconnect. */
|
|
16
|
+
export declare const CLOSE_HUB_IDLE = 4408;
|
|
17
|
+
/** `ws(s)://<hub host>/api/ws?app=<app>`, the scheme following the hub URL's. */
|
|
18
|
+
export declare function hubSocketUrl(hubUrl: string, app: string): string;
|
|
19
|
+
/** What a hub frame asks of the client. Unknown frames and fields are
|
|
20
|
+
* ignored (hub versions overlap during a hub deploy), and so is a hint for
|
|
21
|
+
* another app. `pong` and anything unknown only count as signs of life. */
|
|
22
|
+
export type HubFrame = {
|
|
23
|
+
kind: 'ack';
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'sync_available';
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'build_changed';
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'life';
|
|
30
|
+
} | {
|
|
31
|
+
kind: 'unparseable';
|
|
32
|
+
};
|
|
33
|
+
export declare function parseHubFrame(raw: string, app: string): HubFrame;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The sync client's hub mode, the parts that need none of its state
|
|
2
|
+
// (connection hub design ~/migration/research/connection-hub-design-2026-10-30.md
|
|
3
|
+
// §5.4–§5.5, as amended by §12, §14.4 and the 2026-11-03 socket age cap).
|
|
4
|
+
// The client itself (client.ts) branches on hub mode at a few seams; these
|
|
5
|
+
// are the hub's wire facts it relies on.
|
|
6
|
+
/** The client's ping period; the hub closes a socket silent for 180 s. */
|
|
7
|
+
export const HUB_PING_INTERVAL_MS = 30_000;
|
|
8
|
+
/** Two missed pongs: a ping unanswered and nothing heard for this long
|
|
9
|
+
* replaces the socket (any frame counts as life, as in Radar's client). */
|
|
10
|
+
export const HUB_PONG_TIMEOUT_MS = 2 * HUB_PING_INTERVAL_MS;
|
|
11
|
+
/** While visible, one HTTP catch-up at least this often, whatever the hub
|
|
12
|
+
* socket's state: the bound on a lost hint (design §5.5, review C-B1). */
|
|
13
|
+
export const HUB_FLOOR_MS = 2 * 60 * 1000;
|
|
14
|
+
/** A `sync_available` hint runs a catch-up at once; further hints within
|
|
15
|
+
* this window fold into one trailing catch-up. */
|
|
16
|
+
export const HUB_HINT_DEBOUNCE_MS = 500;
|
|
17
|
+
/** The hub's auth check was unavailable ("try again later"): a quiet
|
|
18
|
+
* reconnect, like 1012. */
|
|
19
|
+
export const CLOSE_TRY_AGAIN_LATER = 1013;
|
|
20
|
+
/** The hub heard nothing on the socket for 180 s: a quiet reconnect. */
|
|
21
|
+
export const CLOSE_HUB_IDLE = 4408;
|
|
22
|
+
/** `ws(s)://<hub host>/api/ws?app=<app>`, the scheme following the hub URL's. */
|
|
23
|
+
export function hubSocketUrl(hubUrl, app) {
|
|
24
|
+
const url = new URL('/api/ws', hubUrl);
|
|
25
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
26
|
+
url.searchParams.set('app', app);
|
|
27
|
+
return url.toString();
|
|
28
|
+
}
|
|
29
|
+
export function parseHubFrame(raw, app) {
|
|
30
|
+
let frame;
|
|
31
|
+
try {
|
|
32
|
+
frame = JSON.parse(raw);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { kind: 'unparseable' };
|
|
36
|
+
}
|
|
37
|
+
if (frame === null || typeof frame !== 'object')
|
|
38
|
+
return { kind: 'life' };
|
|
39
|
+
const { type, app: frameApp, kind } = frame;
|
|
40
|
+
if (type === 'ack')
|
|
41
|
+
return { kind: 'ack' };
|
|
42
|
+
if (type !== 'hint' || (frameApp !== undefined && frameApp !== app))
|
|
43
|
+
return { kind: 'life' };
|
|
44
|
+
if (kind === 'sync_available')
|
|
45
|
+
return { kind: 'sync_available' };
|
|
46
|
+
if (kind === 'build_changed')
|
|
47
|
+
return { kind: 'build_changed' };
|
|
48
|
+
return { kind: 'life' };
|
|
49
|
+
}
|
package/package.json
CHANGED