@steve31415/baselib 3.60.1 → 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/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
|
+
}
|
package/package.json
CHANGED