@steve31415/baselib 3.60.0 → 3.61.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/dist/sync/engine.d.ts +6 -3
- package/dist/sync/engine.js +28 -5
- package/dist/sync/session.d.ts +14 -2
- package/dist/sync/session.js +53 -11
- package/dist/sync/types.d.ts +10 -0
- package/dist/sync/types.js +13 -0
- package/dist/sync-browser/client.d.ts +22 -1
- package/dist/sync-browser/client.js +109 -20
- package/package.json +1 -1
package/dist/sync/engine.d.ts
CHANGED
|
@@ -43,9 +43,12 @@ export declare class EventLogEngine<C extends EventBody, S extends EventBody> {
|
|
|
43
43
|
private readonly randomGuid;
|
|
44
44
|
private readonly now;
|
|
45
45
|
constructor(options: EventLogEngineOptions<C, S>);
|
|
46
|
-
/** Apply one event. Domain validation failures are stable
|
|
47
|
-
* unexpected failure is retried once because event GUID
|
|
48
|
-
* ambiguous commit safe to replay
|
|
46
|
+
/** Apply one event. Domain validation failures (`SyncError`) are stable
|
|
47
|
+
* rejections. An unexpected failure is retried once, because event GUID
|
|
48
|
+
* dedupe makes an ambiguous commit safe to replay; if the retry fails too,
|
|
49
|
+
* a failure about the event's own data (`deterministicFailure`) is
|
|
50
|
+
* rejected as `internal`, and any other throws `SyncUnavailableError`: no
|
|
51
|
+
* verdict, the caller must make the client re-send. */
|
|
49
52
|
apply(scopeKey: string, clientGuid: string | null, event: ClientEvent<C>): Promise<ApplyOutcome<S>>;
|
|
50
53
|
private rejectedOutcome;
|
|
51
54
|
private applyOnce;
|
package/dist/sync/engine.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { SyncError, } from './types.js';
|
|
2
|
+
import { SyncError, SyncUnavailableError, } from './types.js';
|
|
3
3
|
// Past this many events a client is told to reload (a full bootstrap)
|
|
4
4
|
// rather than catch up. Deliberate (2026-10-20, task 1e2cd274): a todo page
|
|
5
5
|
// 138 events behind resynced as designed; the fault was its cached, stale
|
|
@@ -28,6 +28,22 @@ function validatedSchema(schema) {
|
|
|
28
28
|
scopeColumn: validate('scopeColumn', scopeColumn),
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
+
/** The preparer broke its contract: a code bug, the same on every attempt. */
|
|
32
|
+
class PreparerContractError extends Error {
|
|
33
|
+
}
|
|
34
|
+
/** A failure retrying cannot fix: the event's own data violates the schema
|
|
35
|
+
* (SQLSTATE class 22, data exception; 23, integrity constraint) or the
|
|
36
|
+
* preparer broke its contract. Such an event is rejected. Any other failure
|
|
37
|
+
* may pass (a dropped connection, a failover, a deadlock, or schema skew
|
|
38
|
+
* during a deploy), so the event is kept for the client to re-send: losing
|
|
39
|
+
* an edit is worse than a client that keeps retrying, visibly and with an
|
|
40
|
+
* ERROR per attempt, until a fix ships. */
|
|
41
|
+
function deterministicFailure(error) {
|
|
42
|
+
if (error instanceof PreparerContractError)
|
|
43
|
+
return true;
|
|
44
|
+
const code = error !== null && typeof error === 'object' ? error.code : undefined;
|
|
45
|
+
return typeof code === 'string' && /^2[23][0-9A-Z]{3}$/.test(code);
|
|
46
|
+
}
|
|
31
47
|
function syncEventFromRow(row) {
|
|
32
48
|
return {
|
|
33
49
|
seq: Number(row.seq),
|
|
@@ -56,9 +72,12 @@ export class EventLogEngine {
|
|
|
56
72
|
this.randomGuid = options.randomGuid ?? randomUUID;
|
|
57
73
|
this.now = options.now ?? Date.now;
|
|
58
74
|
}
|
|
59
|
-
/** Apply one event. Domain validation failures are stable
|
|
60
|
-
* unexpected failure is retried once because event GUID
|
|
61
|
-
* ambiguous commit safe to replay
|
|
75
|
+
/** Apply one event. Domain validation failures (`SyncError`) are stable
|
|
76
|
+
* rejections. An unexpected failure is retried once, because event GUID
|
|
77
|
+
* dedupe makes an ambiguous commit safe to replay; if the retry fails too,
|
|
78
|
+
* a failure about the event's own data (`deterministicFailure`) is
|
|
79
|
+
* rejected as `internal`, and any other throws `SyncUnavailableError`: no
|
|
80
|
+
* verdict, the caller must make the client re-send. */
|
|
62
81
|
async apply(scopeKey, clientGuid, event) {
|
|
63
82
|
try {
|
|
64
83
|
return await this.applyOnce(scopeKey, clientGuid, event);
|
|
@@ -79,12 +98,16 @@ export class EventLogEngine {
|
|
|
79
98
|
if (retryError instanceof SyncError) {
|
|
80
99
|
return this.rejectedOutcome(scopeKey, event, retryError);
|
|
81
100
|
}
|
|
101
|
+
const retryable = !deterministicFailure(retryError);
|
|
82
102
|
this.logger.error('sync.apply_failed', {
|
|
83
103
|
scopeKey,
|
|
84
104
|
eventGuid: event.eventGuid,
|
|
85
105
|
eventType: event.type,
|
|
86
106
|
error: retryError,
|
|
107
|
+
retryable,
|
|
87
108
|
});
|
|
109
|
+
if (retryable)
|
|
110
|
+
throw new SyncUnavailableError(retryError);
|
|
88
111
|
return {
|
|
89
112
|
kind: 'rejected',
|
|
90
113
|
error: { code: 'internal', message: 'internal error applying event' },
|
|
@@ -123,7 +146,7 @@ export class EventLogEngine {
|
|
|
123
146
|
}
|
|
124
147
|
const prepared = await this.prepareMutation(client, scopeKey, event);
|
|
125
148
|
if (prepared.filter((candidate) => candidate.trigger === true).length !== 1) {
|
|
126
|
-
throw new
|
|
149
|
+
throw new PreparerContractError('mutation preparer must return exactly one trigger event');
|
|
127
150
|
}
|
|
128
151
|
const eventCount = prepared.length;
|
|
129
152
|
const bump = await client.query(`update ${scopesTable} set last_seq = last_seq + $2
|
package/dist/sync/session.d.ts
CHANGED
|
@@ -8,6 +8,12 @@ export interface SyncSocketSessionOptions<C extends EventBody, S extends EventBo
|
|
|
8
8
|
send(message: WsServerMessage<S>): void;
|
|
9
9
|
buildId: string;
|
|
10
10
|
parseClientEvent(value: unknown): ClientEvent<C>;
|
|
11
|
+
/** Close the WebSocket (`ws.close(code, reason)`). Called with 1011 when
|
|
12
|
+
* the engine throws `SyncUnavailableError`: the client keeps the event,
|
|
13
|
+
* reconnects and re-sends it. Every app should pass it; without it the
|
|
14
|
+
* error propagates out of `onMessage` and the socket stays open, the event
|
|
15
|
+
* unconfirmed until the client's next reconnect. */
|
|
16
|
+
closeSocket?(code: number, reason: string): void;
|
|
11
17
|
}
|
|
12
18
|
export declare class SyncSocketSession<C extends EventBody, S extends EventBody> {
|
|
13
19
|
private readonly scopeKey;
|
|
@@ -16,6 +22,7 @@ export declare class SyncSocketSession<C extends EventBody, S extends EventBody>
|
|
|
16
22
|
private readonly send;
|
|
17
23
|
private readonly buildId;
|
|
18
24
|
private readonly parseClientEvent;
|
|
25
|
+
private readonly closeSocket;
|
|
19
26
|
private readonly broadcastListener;
|
|
20
27
|
private readonly unsubscribe;
|
|
21
28
|
private clientGuid;
|
|
@@ -28,7 +35,9 @@ export declare class SyncSocketSession<C extends EventBody, S extends EventBody>
|
|
|
28
35
|
}
|
|
29
36
|
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
30
37
|
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
31
|
-
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored.
|
|
38
|
+
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. Throws
|
|
39
|
+
* `SyncUnavailableError` when the database fails (let it reach a 5xx; the
|
|
40
|
+
* client's retry deduplicates what committed before it). */
|
|
32
41
|
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
42
|
/** What one request committed, for `afterCommit`: the events it appended,
|
|
34
43
|
* and the stored event of each retried event that had already committed. */
|
|
@@ -59,5 +68,8 @@ export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBo
|
|
|
59
68
|
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
60
69
|
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
61
70
|
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
62
|
-
* `SyncError('bad_request')` for a malformed batch (answer 400)
|
|
71
|
+
* `SyncError('bad_request')` for a malformed batch (answer 400), and
|
|
72
|
+
* `SyncUnavailableError` when the database fails (answer 5xx; the client
|
|
73
|
+
* retries, and what committed before the failure comes back as duplicates).
|
|
74
|
+
* Events committed before such a failure still get `afterCommit`. */
|
|
63
75
|
export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
|
package/dist/sync/session.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import { SyncError, } from './types.js';
|
|
1
|
+
import { SyncError, SyncUnavailableError, } from './types.js';
|
|
2
|
+
/** The WebSocket close code for "server error": the client reconnects on its
|
|
3
|
+
* ordinary ladder. */
|
|
4
|
+
const CLOSE_SYNC_UNAVAILABLE = 1011;
|
|
2
5
|
function record(value) {
|
|
3
6
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
4
7
|
? value
|
|
@@ -20,6 +23,7 @@ export class SyncSocketSession {
|
|
|
20
23
|
send;
|
|
21
24
|
buildId;
|
|
22
25
|
parseClientEvent;
|
|
26
|
+
closeSocket;
|
|
23
27
|
broadcastListener;
|
|
24
28
|
unsubscribe;
|
|
25
29
|
clientGuid = null;
|
|
@@ -31,6 +35,7 @@ export class SyncSocketSession {
|
|
|
31
35
|
this.send = options.send;
|
|
32
36
|
this.buildId = options.buildId;
|
|
33
37
|
this.parseClientEvent = options.parseClientEvent;
|
|
38
|
+
this.closeSocket = options.closeSocket;
|
|
34
39
|
this.broadcastListener = (message) => this.sendToSocket(message);
|
|
35
40
|
this.unsubscribe = this.broadcaster.subscribe(this.scopeKey, this.broadcastListener);
|
|
36
41
|
}
|
|
@@ -97,7 +102,21 @@ export class SyncSocketSession {
|
|
|
97
102
|
this.reject(guid, 'client_guid_mismatch', 'event client guid does not match socket');
|
|
98
103
|
return;
|
|
99
104
|
}
|
|
100
|
-
|
|
105
|
+
let outcome;
|
|
106
|
+
try {
|
|
107
|
+
outcome = await this.engine.apply(this.scopeKey, this.clientGuid, parsedEvent);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!(error instanceof SyncUnavailableError) || !this.closeSocket)
|
|
111
|
+
throw error;
|
|
112
|
+
// No verdict, so no rejection: the client keeps the event, reconnects
|
|
113
|
+
// and re-sends it (deduplicated by its GUID if it did commit).
|
|
114
|
+
if (this.closed)
|
|
115
|
+
return;
|
|
116
|
+
this.close();
|
|
117
|
+
this.closeSocket(CLOSE_SYNC_UNAVAILABLE, 'sync unavailable');
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
101
120
|
if (outcome.kind === 'applied') {
|
|
102
121
|
// A committed event must reach every healthy peer even when this socket
|
|
103
122
|
// or another peer is stale. Report delivery failures only after fan-out.
|
|
@@ -160,10 +179,12 @@ export class SyncSocketSession {
|
|
|
160
179
|
}
|
|
161
180
|
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
162
181
|
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
163
|
-
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored.
|
|
182
|
+
* `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. Throws
|
|
183
|
+
* `SyncUnavailableError` when the database fails (let it reach a 5xx; the
|
|
184
|
+
* client's retry deduplicates what committed before it). */
|
|
164
185
|
export async function applyHttpEventBatch(engine, scopeKey, request, parseClientEvent) {
|
|
165
186
|
const batch = parseBatch(request, false);
|
|
166
|
-
const
|
|
187
|
+
const outcomes = await applyBatch(engine, scopeKey, batch, parseClientEvent, emptyCommitted());
|
|
167
188
|
return outcomes.map(oldShape);
|
|
168
189
|
}
|
|
169
190
|
/** One handler for every app's `POST /api/sync/events` (connection hub
|
|
@@ -174,13 +195,30 @@ export async function applyHttpEventBatch(engine, scopeKey, request, parseClient
|
|
|
174
195
|
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
175
196
|
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
176
197
|
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
177
|
-
* `SyncError('bad_request')` for a malformed batch (answer 400)
|
|
198
|
+
* `SyncError('bad_request')` for a malformed batch (answer 400), and
|
|
199
|
+
* `SyncUnavailableError` when the database fails (answer 5xx; the client
|
|
200
|
+
* retries, and what committed before the failure comes back as duplicates).
|
|
201
|
+
* Events committed before such a failure still get `afterCommit`. */
|
|
178
202
|
export async function handleSyncEventsRequest(options) {
|
|
179
203
|
const batch = parseBatch(options.body, true);
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
204
|
+
const committed = emptyCommitted();
|
|
205
|
+
const runAfterCommit = async () => {
|
|
206
|
+
if (options.afterCommit && (committed.applied.length > 0 || committed.duplicates.length > 0)) {
|
|
207
|
+
await options.afterCommit(committed);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
let outcomes;
|
|
211
|
+
try {
|
|
212
|
+
outcomes = await applyBatch(options.engine, options.scopeKey, batch, options.parseClientEvent, committed);
|
|
183
213
|
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
// Peers must still hear of what committed: the retry reports it only as
|
|
216
|
+
// duplicates. The hook's own failure (likely, mid-outage) yields to the
|
|
217
|
+
// original error; the retry's duplicates run the hook again.
|
|
218
|
+
await runAfterCommit().catch(() => { });
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
await runAfterCommit();
|
|
184
222
|
if (batch.lastSeq === undefined)
|
|
185
223
|
return { outcomes: outcomes.map(oldShape) };
|
|
186
224
|
const catchup = await options.engine.catchup(options.scopeKey, batch.lastSeq);
|
|
@@ -205,9 +243,13 @@ function parseBatch(request, withLastSeq) {
|
|
|
205
243
|
}
|
|
206
244
|
return batch;
|
|
207
245
|
}
|
|
208
|
-
|
|
246
|
+
function emptyCommitted() {
|
|
247
|
+
return { applied: [], duplicates: [] };
|
|
248
|
+
}
|
|
249
|
+
/** Applies the batch in order, recording into `committed` as it goes, so a
|
|
250
|
+
* caller still has it when an event throws partway. */
|
|
251
|
+
async function applyBatch(engine, scopeKey, batch, parseClientEvent, committed) {
|
|
209
252
|
const outcomes = [];
|
|
210
|
-
const committed = { applied: [], duplicates: [] };
|
|
211
253
|
for (const value of batch.events) {
|
|
212
254
|
const guid = eventGuid(value);
|
|
213
255
|
let event;
|
|
@@ -231,7 +273,7 @@ async function applyBatch(engine, scopeKey, batch, parseClientEvent) {
|
|
|
231
273
|
outcomes.push({ eventGuid: event.eventGuid, status: 'applied', events: outcome.events });
|
|
232
274
|
}
|
|
233
275
|
}
|
|
234
|
-
return
|
|
276
|
+
return outcomes;
|
|
235
277
|
}
|
|
236
278
|
function oldShape(outcome) {
|
|
237
279
|
if (outcome.status === 'rejected') {
|
package/dist/sync/types.d.ts
CHANGED
|
@@ -17,6 +17,16 @@ export declare class SyncError extends Error {
|
|
|
17
17
|
readonly code: string;
|
|
18
18
|
constructor(code: string, message: string);
|
|
19
19
|
}
|
|
20
|
+
/** `EventLogEngine.apply` could not reach a verdict: a failure that is not
|
|
21
|
+
* about the event (a dropped connection, a failover, a deploy's schema skew)
|
|
22
|
+
* outlasted its retry. Not a rejection: the client must keep the event and
|
|
23
|
+
* re-send it, which its GUID makes safe. `SyncSocketSession` closes the
|
|
24
|
+
* socket with 1011 (the client reconnects and re-sends); an HTTP route lets
|
|
25
|
+
* it propagate to a 5xx (the client retries). The engine has already logged
|
|
26
|
+
* `sync.apply_failed` (ERROR); `cause` is the last failure. */
|
|
27
|
+
export declare class SyncUnavailableError extends Error {
|
|
28
|
+
constructor(cause: unknown);
|
|
29
|
+
}
|
|
20
30
|
export interface WsConnect {
|
|
21
31
|
type: 'connect';
|
|
22
32
|
clientGuid: string;
|
package/dist/sync/types.js
CHANGED
|
@@ -6,3 +6,16 @@ export class SyncError extends Error {
|
|
|
6
6
|
this.name = 'SyncError';
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
+
/** `EventLogEngine.apply` could not reach a verdict: a failure that is not
|
|
10
|
+
* about the event (a dropped connection, a failover, a deploy's schema skew)
|
|
11
|
+
* outlasted its retry. Not a rejection: the client must keep the event and
|
|
12
|
+
* re-send it, which its GUID makes safe. `SyncSocketSession` closes the
|
|
13
|
+
* socket with 1011 (the client reconnects and re-sends); an HTTP route lets
|
|
14
|
+
* it propagate to a 5xx (the client retries). The engine has already logged
|
|
15
|
+
* `sync.apply_failed` (ERROR); `cause` is the last failure. */
|
|
16
|
+
export class SyncUnavailableError extends Error {
|
|
17
|
+
constructor(cause) {
|
|
18
|
+
super('sync temporarily unavailable', { cause });
|
|
19
|
+
this.name = 'SyncUnavailableError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -200,6 +200,13 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
200
200
|
private readonly hub;
|
|
201
201
|
/** The live hub socket answered our `connect`. */
|
|
202
202
|
private hubAcked;
|
|
203
|
+
/** Counts acks: a catch-up establishes only if it began under the current one. */
|
|
204
|
+
private ackGen;
|
|
205
|
+
/** When recent quiet hub closes happened (wall clock): a burst is not quiet. */
|
|
206
|
+
private quietHubCloses;
|
|
207
|
+
/** The last POST failed and its edits are still unsettled: reads alone do
|
|
208
|
+
* not make the page live or re-establish it. */
|
|
209
|
+
private postFailing;
|
|
203
210
|
private hubLastHeardAt;
|
|
204
211
|
private hubAwaitingPong;
|
|
205
212
|
/** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
|
|
@@ -384,7 +391,15 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
384
391
|
* `connect` and the last app request succeeded (a pong overdue replaces
|
|
385
392
|
* the socket, so an open one has been heard from recently). */
|
|
386
393
|
private isLive;
|
|
387
|
-
|
|
394
|
+
/** Hub mode: is this close a quiet reconnect? 1012, 1013 or 4408 on a
|
|
395
|
+
* socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
|
|
396
|
+
* closes in the last minute; anything else takes the outage path. */
|
|
397
|
+
private takeQuietHubClose;
|
|
398
|
+
/** The ack a catch-up began under, or -1 when the hub socket was not acked. */
|
|
399
|
+
private currentAckGen;
|
|
400
|
+
/** Established needs a complete catch-up that began under the current ack
|
|
401
|
+
* (review 3.60.1, finding 3). */
|
|
402
|
+
private establishesUnder;
|
|
388
403
|
/** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
|
|
389
404
|
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
390
405
|
* `connecting`, or `disconnected` once something has failed. */
|
|
@@ -405,7 +420,13 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
405
420
|
* socket's state; any successful app request restarts the wait. */
|
|
406
421
|
private armFloor;
|
|
407
422
|
private cancelFloor;
|
|
423
|
+
/** The app answered. While a failed POST's edits are still unsettled,
|
|
424
|
+
* reads alone change nothing but the floor: the POST's ladder stays in
|
|
425
|
+
* charge, and the page is neither live nor re-established (review
|
|
426
|
+
* 3.60.1, findings 2 and 5). Otherwise the ladder resets, a complete
|
|
427
|
+
* catch-up under the current ack establishes, and unsettled edits post. */
|
|
408
428
|
private appSucceeded;
|
|
429
|
+
private postFailed;
|
|
409
430
|
/** A POST or catch-up got no usable answer: the outage starts (if it had
|
|
410
431
|
* not), and a visible page retries on the app-request ladder whatever the
|
|
411
432
|
* hub socket's state. An expired session halts instead. */
|
|
@@ -57,6 +57,17 @@ const SOCKET_OPEN = 1;
|
|
|
57
57
|
/** Outage logs' `closeCode` when a failed app request, not a socket close,
|
|
58
58
|
* began the outage (hub mode). */
|
|
59
59
|
const APP_REQUEST_FAILED = 0;
|
|
60
|
+
/** Hub mode: at most this many quiet reconnects (1012/1013/4408 on an acked
|
|
61
|
+
* socket) per window; more take the ladder. The hub's own closes come at
|
|
62
|
+
* most every 180-300 s per socket. */
|
|
63
|
+
const HUB_QUIET_CLOSE_BURST = 3;
|
|
64
|
+
const HUB_QUIET_CLOSE_WINDOW_MS = 60_000;
|
|
65
|
+
function isEventsResponse(value) {
|
|
66
|
+
if (value === null || typeof value !== 'object')
|
|
67
|
+
return false;
|
|
68
|
+
const { outcomes, events } = value;
|
|
69
|
+
return Array.isArray(outcomes) && (events === undefined || Array.isArray(events));
|
|
70
|
+
}
|
|
60
71
|
function messageType(raw) {
|
|
61
72
|
try {
|
|
62
73
|
return JSON.parse(raw)?.type;
|
|
@@ -160,6 +171,13 @@ export class SyncClient {
|
|
|
160
171
|
hub;
|
|
161
172
|
/** The live hub socket answered our `connect`. */
|
|
162
173
|
hubAcked = false;
|
|
174
|
+
/** Counts acks: a catch-up establishes only if it began under the current one. */
|
|
175
|
+
ackGen = 0;
|
|
176
|
+
/** When recent quiet hub closes happened (wall clock): a burst is not quiet. */
|
|
177
|
+
quietHubCloses = [];
|
|
178
|
+
/** The last POST failed and its edits are still unsettled: reads alone do
|
|
179
|
+
* not make the page live or re-establish it. */
|
|
180
|
+
postFailing = false;
|
|
163
181
|
hubLastHeardAt = 0;
|
|
164
182
|
hubAwaitingPong = false;
|
|
165
183
|
/** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
|
|
@@ -748,6 +766,7 @@ export class SyncClient {
|
|
|
748
766
|
return;
|
|
749
767
|
this.clearConnectionTimers();
|
|
750
768
|
this.socket = null;
|
|
769
|
+
const wasAcked = this.hubAcked;
|
|
751
770
|
this.hubAcked = false;
|
|
752
771
|
if (this.halted || this.disposed)
|
|
753
772
|
return;
|
|
@@ -776,12 +795,15 @@ export class SyncClient {
|
|
|
776
795
|
// on a handshake begun for a handover.
|
|
777
796
|
const rolling = this.candidate !== null;
|
|
778
797
|
this.dropCandidate();
|
|
779
|
-
if (
|
|
798
|
+
if (this.hub ? this.takeQuietHubClose(event.code, wasAcked) : event.code === CLOSE_SERVICE_RESTART) {
|
|
780
799
|
// The server's planned close (its age cap: a tab whose own rollover
|
|
781
800
|
// didn't run, such as a frozen one): reconnect at once, as after our
|
|
782
801
|
// own rollover, with no outage and no ladder step. A failure of that
|
|
783
802
|
// 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
|
|
803
|
+
// was unavailable) and 4408 (it heard nothing for 180 s) are the
|
|
804
|
+
// same, but only for a socket the hub had acked, and not in a burst:
|
|
805
|
+
// the hub refuses with 1013 before acking while its auth is down,
|
|
806
|
+
// and that must back off on the ladder (review 3.60.1, finding 1).
|
|
785
807
|
this.options.logger.info('ws closed by server', { closeCode: event.code, openForMs, rolling });
|
|
786
808
|
this.connectNow();
|
|
787
809
|
return;
|
|
@@ -1071,6 +1093,7 @@ export class SyncClient {
|
|
|
1071
1093
|
this.abortControllers.add(controller);
|
|
1072
1094
|
const timeout = this.setTimer(() => controller.abort(), BACKGROUND_FETCH_TIMEOUT_MS);
|
|
1073
1095
|
let ok = false;
|
|
1096
|
+
const ackGen = this.currentAckGen();
|
|
1074
1097
|
try {
|
|
1075
1098
|
const result = await this.options.fetchCatchup(this.options.store.currentSeq(), controller.signal);
|
|
1076
1099
|
if (controller.signal.aborted || this.stopBeforeStoreMutation())
|
|
@@ -1081,15 +1104,18 @@ export class SyncClient {
|
|
|
1081
1104
|
this.options.onBuildObserved?.(result.buildId);
|
|
1082
1105
|
else if (kind === 'background')
|
|
1083
1106
|
this.options.onBuildChanged?.();
|
|
1107
|
+
let complete = !result.reload;
|
|
1084
1108
|
if (result.reload) {
|
|
1085
1109
|
this.requestReload('server');
|
|
1086
1110
|
}
|
|
1087
1111
|
else {
|
|
1088
|
-
for (const event of result.events)
|
|
1089
|
-
this.handleServerEvent(event)
|
|
1112
|
+
for (const event of result.events) {
|
|
1113
|
+
if (!this.handleServerEvent(event))
|
|
1114
|
+
complete = false;
|
|
1115
|
+
}
|
|
1090
1116
|
}
|
|
1091
1117
|
if (this.hub)
|
|
1092
|
-
this.appSucceeded();
|
|
1118
|
+
this.appSucceeded(this.establishesUnder(ackGen, complete));
|
|
1093
1119
|
return true;
|
|
1094
1120
|
}
|
|
1095
1121
|
catch {
|
|
@@ -2010,8 +2036,29 @@ export class SyncClient {
|
|
|
2010
2036
|
return false;
|
|
2011
2037
|
return this.hub === null || (this.hubAcked && this.appOk);
|
|
2012
2038
|
}
|
|
2013
|
-
|
|
2014
|
-
|
|
2039
|
+
/** Hub mode: is this close a quiet reconnect? 1012, 1013 or 4408 on a
|
|
2040
|
+
* socket the hub had acked, and fewer than HUB_QUIET_CLOSE_BURST such
|
|
2041
|
+
* closes in the last minute; anything else takes the outage path. */
|
|
2042
|
+
takeQuietHubClose(code, wasAcked) {
|
|
2043
|
+
if (code !== CLOSE_SERVICE_RESTART && code !== CLOSE_TRY_AGAIN_LATER && code !== CLOSE_HUB_IDLE)
|
|
2044
|
+
return false;
|
|
2045
|
+
if (!wasAcked)
|
|
2046
|
+
return false;
|
|
2047
|
+
const now = this.now();
|
|
2048
|
+
this.quietHubCloses = this.quietHubCloses.filter((at) => at <= now && now - at < HUB_QUIET_CLOSE_WINDOW_MS);
|
|
2049
|
+
if (this.quietHubCloses.length >= HUB_QUIET_CLOSE_BURST)
|
|
2050
|
+
return false;
|
|
2051
|
+
this.quietHubCloses.push(now);
|
|
2052
|
+
return true;
|
|
2053
|
+
}
|
|
2054
|
+
/** The ack a catch-up began under, or -1 when the hub socket was not acked. */
|
|
2055
|
+
currentAckGen() {
|
|
2056
|
+
return this.hubAcked ? this.ackGen : -1;
|
|
2057
|
+
}
|
|
2058
|
+
/** Established needs a complete catch-up that began under the current ack
|
|
2059
|
+
* (review 3.60.1, finding 3). */
|
|
2060
|
+
establishesUnder(ackGen, complete) {
|
|
2061
|
+
return complete && ackGen !== -1 && ackGen === this.ackGen && this.hubAcked && this.socket?.readyState === SOCKET_OPEN;
|
|
2015
2062
|
}
|
|
2016
2063
|
/** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
|
|
2017
2064
|
* to whichever ladder (hub socket or app request) retries first; otherwise
|
|
@@ -2026,7 +2073,9 @@ export class SyncClient {
|
|
|
2026
2073
|
this.countdownTimer = null;
|
|
2027
2074
|
}
|
|
2028
2075
|
if (live) {
|
|
2029
|
-
|
|
2076
|
+
// A detected resync loop keeps its error state until it converges.
|
|
2077
|
+
if (!this.loopEscalated)
|
|
2078
|
+
this.updateConnectedState();
|
|
2030
2079
|
return;
|
|
2031
2080
|
}
|
|
2032
2081
|
const pending = this.pendingCount();
|
|
@@ -2073,6 +2122,7 @@ export class SyncClient {
|
|
|
2073
2122
|
if (this.hubAcked)
|
|
2074
2123
|
return;
|
|
2075
2124
|
this.hubAcked = true;
|
|
2125
|
+
this.ackGen++;
|
|
2076
2126
|
this.refreshHubState();
|
|
2077
2127
|
void this.runCatchup('connect');
|
|
2078
2128
|
}
|
|
@@ -2127,15 +2177,32 @@ export class SyncClient {
|
|
|
2127
2177
|
this.options.runtime.clearTimeout(this.floorTimer);
|
|
2128
2178
|
this.floorTimer = null;
|
|
2129
2179
|
}
|
|
2130
|
-
|
|
2180
|
+
/** The app answered. While a failed POST's edits are still unsettled,
|
|
2181
|
+
* reads alone change nothing but the floor: the POST's ladder stays in
|
|
2182
|
+
* charge, and the page is neither live nor re-established (review
|
|
2183
|
+
* 3.60.1, findings 2 and 5). Otherwise the ladder resets, a complete
|
|
2184
|
+
* catch-up under the current ack establishes, and unsettled edits post. */
|
|
2185
|
+
appSucceeded(establishes) {
|
|
2186
|
+
this.armFloor();
|
|
2187
|
+
if (this.postFailing && this.unsettledPending().length > 0) {
|
|
2188
|
+
this.scheduleAppRetry();
|
|
2189
|
+
this.refreshHubState();
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
this.postFailing = false;
|
|
2131
2193
|
this.appOk = true;
|
|
2132
2194
|
this.appAttempts = 0;
|
|
2133
2195
|
this.cancelAppRetry();
|
|
2134
|
-
|
|
2135
|
-
if (this.hubAcked && this.socket?.readyState === SOCKET_OPEN)
|
|
2196
|
+
if (establishes)
|
|
2136
2197
|
this.onSyncEstablished();
|
|
2137
2198
|
else
|
|
2138
2199
|
this.refreshHubState();
|
|
2200
|
+
if (this.unsettledPending().length > 0)
|
|
2201
|
+
this.kickPost();
|
|
2202
|
+
}
|
|
2203
|
+
postFailed() {
|
|
2204
|
+
this.postFailing = true;
|
|
2205
|
+
this.appFailed();
|
|
2139
2206
|
}
|
|
2140
2207
|
/** A POST or catch-up got no usable answer: the outage starts (if it had
|
|
2141
2208
|
* not), and a visible page retries on the app-request ladder whatever the
|
|
@@ -2208,21 +2275,37 @@ export class SyncClient {
|
|
|
2208
2275
|
return inFlight;
|
|
2209
2276
|
}
|
|
2210
2277
|
async postOnce(postEvents, events) {
|
|
2278
|
+
const ackGen = this.currentAckGen();
|
|
2211
2279
|
let response;
|
|
2212
2280
|
try {
|
|
2213
2281
|
response = await this.withTimeout((signal) => postEvents({ clientGuid: this.options.clientGuid, events, lastSeq: this.options.store.currentSeq() }, signal));
|
|
2214
2282
|
}
|
|
2215
2283
|
catch {
|
|
2216
|
-
this.
|
|
2284
|
+
this.postFailed();
|
|
2217
2285
|
return;
|
|
2218
2286
|
}
|
|
2219
2287
|
if (this.stopBeforeStoreMutation())
|
|
2220
2288
|
return;
|
|
2221
|
-
|
|
2222
|
-
|
|
2289
|
+
// A body that is not the response shape, or a store that throws applying
|
|
2290
|
+
// it, is a failed request: the ladder re-posts (review 3.60.1, finding 4).
|
|
2291
|
+
let complete;
|
|
2292
|
+
try {
|
|
2293
|
+
if (!isEventsResponse(response))
|
|
2294
|
+
throw new Error('response has no outcomes');
|
|
2295
|
+
complete = this.applyPostResponse(response);
|
|
2296
|
+
}
|
|
2297
|
+
catch (error) {
|
|
2298
|
+
if (this.stopBeforeStoreMutation())
|
|
2299
|
+
return;
|
|
2300
|
+
this.options.logger.error('sync post response unusable', { error });
|
|
2301
|
+
this.postFailed();
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2223
2304
|
if (this.stopBeforeStoreMutation())
|
|
2224
2305
|
return;
|
|
2225
|
-
this.
|
|
2306
|
+
this.lastContactAt = this.now();
|
|
2307
|
+
this.postFailing = false;
|
|
2308
|
+
this.appSucceeded(this.establishesUnder(ackGen, complete && response.currentSeq !== undefined));
|
|
2226
2309
|
// An app answering in the old shape sent no frames: the echoes come by
|
|
2227
2310
|
// catch-up, as for a same-origin POST.
|
|
2228
2311
|
if (response.currentSeq === undefined && !response.reload)
|
|
@@ -2235,16 +2318,19 @@ export class SyncClient {
|
|
|
2235
2318
|
* have moved it past them, review round 2 B1); rejections settle as on
|
|
2236
2319
|
* the socket. */
|
|
2237
2320
|
applyPostResponse(response) {
|
|
2321
|
+
let complete = !response.reload;
|
|
2238
2322
|
if (response.reload) {
|
|
2239
2323
|
this.requestReload('server');
|
|
2240
2324
|
}
|
|
2241
2325
|
else {
|
|
2242
|
-
for (const event of response.events ?? [])
|
|
2243
|
-
this.handleServerEvent(event)
|
|
2326
|
+
for (const event of response.events ?? []) {
|
|
2327
|
+
if (!this.handleServerEvent(event))
|
|
2328
|
+
complete = false;
|
|
2329
|
+
}
|
|
2244
2330
|
}
|
|
2245
2331
|
for (const outcome of response.outcomes) {
|
|
2246
2332
|
if (this.stopBeforeStoreMutation())
|
|
2247
|
-
return;
|
|
2333
|
+
return false;
|
|
2248
2334
|
if (outcome.status === 'rejected') {
|
|
2249
2335
|
this.handleRejection({
|
|
2250
2336
|
type: 'rejection',
|
|
@@ -2254,9 +2340,12 @@ export class SyncClient {
|
|
|
2254
2340
|
continue;
|
|
2255
2341
|
}
|
|
2256
2342
|
this.counters.httpPostedEvents++;
|
|
2257
|
-
for (const frame of ('events' in outcome ? outcome.events : undefined) ?? [])
|
|
2258
|
-
this.handleServerEvent(frame)
|
|
2343
|
+
for (const frame of ('events' in outcome ? outcome.events : undefined) ?? []) {
|
|
2344
|
+
if (!this.handleServerEvent(frame))
|
|
2345
|
+
complete = false;
|
|
2346
|
+
}
|
|
2259
2347
|
}
|
|
2348
|
+
return complete;
|
|
2260
2349
|
}
|
|
2261
2350
|
detachSocket(socket) {
|
|
2262
2351
|
socket.onopen = null;
|
package/package.json
CHANGED