@steve31415/baselib 3.77.0 → 4.0.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 +2 -2
- package/dist/sync/http-events.d.ts +35 -0
- package/dist/sync/http-events.js +106 -0
- package/dist/sync/index.d.ts +1 -2
- package/dist/sync/index.js +1 -2
- package/dist/sync/types.d.ts +8 -56
- package/dist/sync/types.js +2 -3
- package/dist/sync-browser/client.d.ts +45 -74
- package/dist/sync-browser/client.js +187 -470
- package/dist/sync-browser/hub.js +3 -4
- package/dist/sync-browser/page-hub-url.js +3 -4
- package/package.json +1 -1
- package/dist/sync/broadcaster.d.ts +0 -13
- package/dist/sync/broadcaster.js +0 -53
- package/dist/sync/session.d.ts +0 -75
- package/dist/sync/session.js +0 -283
package/dist/sync-browser/hub.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
// The sync client's hub
|
|
1
|
+
// The sync client's hub channel, the parts that need none of its state
|
|
2
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
|
-
//
|
|
5
|
-
// are the hub's wire facts it relies on.
|
|
3
|
+
// §5.4–§5.5, as amended by §12, §14.4 and the 2026-11-03 socket age cap):
|
|
4
|
+
// the hub's wire facts the client (client.ts) relies on.
|
|
6
5
|
/** The client's ping period; the hub closes a socket silent for 180 s. */
|
|
7
6
|
export const HUB_PING_INTERVAL_MS = 30_000;
|
|
8
7
|
/** Two missed pongs: a ping unanswered and nothing heard for this long
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
// The connection hub's base URL from the page shell's `pw-hub-url` meta tag
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// carries hints only), and with `undefined` keeps its same-origin socket.
|
|
1
|
+
// The connection hub's base URL from the page shell's `pw-hub-url` meta tag,
|
|
2
|
+
// which an app's server writes from its HUB_URL: the sync client's `hubUrl`.
|
|
3
|
+
// With `undefined` (no tag) the client refuses to start.
|
|
5
4
|
/** The meta tag's name. */
|
|
6
5
|
export const PAGE_HUB_URL_META = 'pw-hub-url';
|
|
7
6
|
/** The tag's trimmed content, or undefined when the tag is absent or empty. */
|
package/package.json
CHANGED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export declare class ScopeBroadcaster<T> {
|
|
2
|
-
private readonly listeners;
|
|
3
|
-
subscribe(scopeKey: string, send: (message: T) => void): () => void;
|
|
4
|
-
/** Deliver to every matching listener in subscription order. Throwing
|
|
5
|
-
* listeners are detached immediately, but their errors are reported only
|
|
6
|
-
* after the remaining listeners have received the message. */
|
|
7
|
-
publish(scopeKey: string, message: T, except?: (message: T) => void): void;
|
|
8
|
-
count(scopeKey: string): number;
|
|
9
|
-
/** The scopes with at least one listener: for an app that must
|
|
10
|
-
* re-announce to every local scope, e.g. after its database bridge may
|
|
11
|
-
* have missed notifications. */
|
|
12
|
-
scopes(): string[];
|
|
13
|
-
}
|
package/dist/sync/broadcaster.js
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
export class ScopeBroadcaster {
|
|
2
|
-
listeners = new Map();
|
|
3
|
-
subscribe(scopeKey, send) {
|
|
4
|
-
let scopeListeners = this.listeners.get(scopeKey);
|
|
5
|
-
if (!scopeListeners) {
|
|
6
|
-
scopeListeners = new Set();
|
|
7
|
-
this.listeners.set(scopeKey, scopeListeners);
|
|
8
|
-
}
|
|
9
|
-
scopeListeners.add(send);
|
|
10
|
-
return () => {
|
|
11
|
-
scopeListeners.delete(send);
|
|
12
|
-
if (scopeListeners.size === 0 && this.listeners.get(scopeKey) === scopeListeners) {
|
|
13
|
-
this.listeners.delete(scopeKey);
|
|
14
|
-
}
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
/** Deliver to every matching listener in subscription order. Throwing
|
|
18
|
-
* listeners are detached immediately, but their errors are reported only
|
|
19
|
-
* after the remaining listeners have received the message. */
|
|
20
|
-
publish(scopeKey, message, except) {
|
|
21
|
-
const scopeListeners = this.listeners.get(scopeKey);
|
|
22
|
-
if (!scopeListeners)
|
|
23
|
-
return;
|
|
24
|
-
const errors = [];
|
|
25
|
-
for (const listener of scopeListeners) {
|
|
26
|
-
if (listener === except)
|
|
27
|
-
continue;
|
|
28
|
-
try {
|
|
29
|
-
listener(message);
|
|
30
|
-
}
|
|
31
|
-
catch (error) {
|
|
32
|
-
scopeListeners.delete(listener);
|
|
33
|
-
errors.push(error);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
if (scopeListeners.size === 0 && this.listeners.get(scopeKey) === scopeListeners) {
|
|
37
|
-
this.listeners.delete(scopeKey);
|
|
38
|
-
}
|
|
39
|
-
if (errors.length === 1)
|
|
40
|
-
throw errors[0];
|
|
41
|
-
if (errors.length > 1)
|
|
42
|
-
throw new AggregateError(errors, 'scope broadcast failed');
|
|
43
|
-
}
|
|
44
|
-
count(scopeKey) {
|
|
45
|
-
return this.listeners.get(scopeKey)?.size ?? 0;
|
|
46
|
-
}
|
|
47
|
-
/** The scopes with at least one listener: for an app that must
|
|
48
|
-
* re-announce to every local scope, e.g. after its database bridge may
|
|
49
|
-
* have missed notifications. */
|
|
50
|
-
scopes() {
|
|
51
|
-
return [...this.listeners.keys()];
|
|
52
|
-
}
|
|
53
|
-
}
|
package/dist/sync/session.d.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { ScopeBroadcaster } from './broadcaster.js';
|
|
2
|
-
import { EventLogEngine } from './engine.js';
|
|
3
|
-
import { type ClientEvent, type EventBody, type HttpEventOutcome, type HttpEventsResponse, type SyncEvent, type WsServerMessage } from './types.js';
|
|
4
|
-
export interface SyncSocketSessionOptions<C extends EventBody, S extends EventBody> {
|
|
5
|
-
scopeKey: string;
|
|
6
|
-
engine: EventLogEngine<C, S>;
|
|
7
|
-
broadcaster: ScopeBroadcaster<WsServerMessage<S>>;
|
|
8
|
-
send(message: WsServerMessage<S>): void;
|
|
9
|
-
buildId: string;
|
|
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;
|
|
17
|
-
}
|
|
18
|
-
export declare class SyncSocketSession<C extends EventBody, S extends EventBody> {
|
|
19
|
-
private readonly scopeKey;
|
|
20
|
-
private readonly engine;
|
|
21
|
-
private readonly broadcaster;
|
|
22
|
-
private readonly send;
|
|
23
|
-
private readonly buildId;
|
|
24
|
-
private readonly parseClientEvent;
|
|
25
|
-
private readonly closeSocket;
|
|
26
|
-
private readonly broadcastListener;
|
|
27
|
-
private readonly unsubscribe;
|
|
28
|
-
private clientGuid;
|
|
29
|
-
private closed;
|
|
30
|
-
constructor(options: SyncSocketSessionOptions<C, S>);
|
|
31
|
-
onMessage(message: unknown): Promise<void>;
|
|
32
|
-
close(): void;
|
|
33
|
-
private reject;
|
|
34
|
-
private sendToSocket;
|
|
35
|
-
}
|
|
36
|
-
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
37
|
-
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
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). */
|
|
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[]>;
|
|
42
|
-
/** What one request committed, for `afterCommit`: the events it appended,
|
|
43
|
-
* and the stored event of each retried event that had already committed. */
|
|
44
|
-
export interface SyncEventsCommitted<S extends EventBody> {
|
|
45
|
-
applied: SyncEvent<S>[];
|
|
46
|
-
duplicates: SyncEvent<S>[];
|
|
47
|
-
}
|
|
48
|
-
export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBody> {
|
|
49
|
-
engine: EventLogEngine<C, S>;
|
|
50
|
-
/** Chosen by the app's authenticated, authorized route. */
|
|
51
|
-
scopeKey: string;
|
|
52
|
-
/** The request body as parsed JSON (untrusted). */
|
|
53
|
-
body: unknown;
|
|
54
|
-
parseClientEvent(value: unknown): ClientEvent<C>;
|
|
55
|
-
/** Runs once per request, after every event has been applied and before
|
|
56
|
-
* the catch-up is read, when at least one event was applied or was a
|
|
57
|
-
* duplicate: where the app publishes `applied` to its in-process
|
|
58
|
-
* broadcaster and notifies the hub (whose notify must fire on duplicates
|
|
59
|
-
* too, design §5.3). Awaited; it should not throw (a throw fails the
|
|
60
|
-
* request after the commit, and the client's retry is deduplicated). */
|
|
61
|
-
afterCommit?(committed: SyncEventsCommitted<S>): void | Promise<void>;
|
|
62
|
-
}
|
|
63
|
-
/** One handler for every app's `POST /api/sync/events` (connection hub
|
|
64
|
-
* design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
|
|
65
|
-
* through the engine in order. A request without `lastSeq` (sendBeacon, and
|
|
66
|
-
* clients before hub mode) gets the old shape, `{ outcomes }` with
|
|
67
|
-
* duplicates reported as `applied`. A request with it gets frame outcomes
|
|
68
|
-
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
69
|
-
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
70
|
-
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
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`. */
|
|
75
|
-
export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
|
package/dist/sync/session.js
DELETED
|
@@ -1,283 +0,0 @@
|
|
|
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;
|
|
5
|
-
function record(value) {
|
|
6
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
7
|
-
? value
|
|
8
|
-
: null;
|
|
9
|
-
}
|
|
10
|
-
function eventGuid(value) {
|
|
11
|
-
const candidate = record(value);
|
|
12
|
-
return typeof candidate?.eventGuid === 'string' ? candidate.eventGuid : '';
|
|
13
|
-
}
|
|
14
|
-
function parserError(error) {
|
|
15
|
-
return error instanceof SyncError
|
|
16
|
-
? { code: error.code, message: error.message }
|
|
17
|
-
: { code: 'invalid_payload', message: 'invalid event' };
|
|
18
|
-
}
|
|
19
|
-
export class SyncSocketSession {
|
|
20
|
-
scopeKey;
|
|
21
|
-
engine;
|
|
22
|
-
broadcaster;
|
|
23
|
-
send;
|
|
24
|
-
buildId;
|
|
25
|
-
parseClientEvent;
|
|
26
|
-
closeSocket;
|
|
27
|
-
broadcastListener;
|
|
28
|
-
unsubscribe;
|
|
29
|
-
clientGuid = null;
|
|
30
|
-
closed = false;
|
|
31
|
-
constructor(options) {
|
|
32
|
-
this.scopeKey = options.scopeKey;
|
|
33
|
-
this.engine = options.engine;
|
|
34
|
-
this.broadcaster = options.broadcaster;
|
|
35
|
-
this.send = options.send;
|
|
36
|
-
this.buildId = options.buildId;
|
|
37
|
-
this.parseClientEvent = options.parseClientEvent;
|
|
38
|
-
this.closeSocket = options.closeSocket;
|
|
39
|
-
this.broadcastListener = (message) => this.sendToSocket(message);
|
|
40
|
-
this.unsubscribe = this.broadcaster.subscribe(this.scopeKey, this.broadcastListener);
|
|
41
|
-
}
|
|
42
|
-
async onMessage(message) {
|
|
43
|
-
if (this.closed)
|
|
44
|
-
return;
|
|
45
|
-
const envelope = record(message);
|
|
46
|
-
if (!envelope || typeof envelope.type !== 'string') {
|
|
47
|
-
this.reject('', 'bad_message', 'invalid client message');
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
if (envelope.type === 'ping') {
|
|
51
|
-
this.sendToSocket({ type: 'pong', buildId: this.buildId });
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (envelope.type === 'connect') {
|
|
55
|
-
if (typeof envelope.clientGuid !== 'string' ||
|
|
56
|
-
envelope.clientGuid.length === 0 ||
|
|
57
|
-
!Number.isSafeInteger(envelope.lastSeq) ||
|
|
58
|
-
envelope.lastSeq < 0 ||
|
|
59
|
-
(this.clientGuid !== null && this.clientGuid !== envelope.clientGuid)) {
|
|
60
|
-
this.reject('', 'bad_message', 'invalid connect message');
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
this.clientGuid = envelope.clientGuid;
|
|
64
|
-
const outcome = await this.engine.catchup(this.scopeKey, envelope.lastSeq);
|
|
65
|
-
if (this.closed)
|
|
66
|
-
return;
|
|
67
|
-
if (outcome.kind === 'reload') {
|
|
68
|
-
this.sendToSocket({ type: 'reload' });
|
|
69
|
-
}
|
|
70
|
-
else {
|
|
71
|
-
this.sendToSocket({
|
|
72
|
-
type: 'catchup',
|
|
73
|
-
events: outcome.events,
|
|
74
|
-
currentSeq: outcome.currentSeq,
|
|
75
|
-
buildId: this.buildId,
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
if (envelope.type !== 'event' ||
|
|
81
|
-
typeof envelope.clientGuid !== 'string' ||
|
|
82
|
-
envelope.clientGuid.length === 0 ||
|
|
83
|
-
!('event' in envelope)) {
|
|
84
|
-
this.reject('', 'bad_message', 'invalid client message');
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
const guid = eventGuid(envelope.event);
|
|
88
|
-
let parsedEvent;
|
|
89
|
-
try {
|
|
90
|
-
parsedEvent = this.parseClientEvent(envelope.event);
|
|
91
|
-
}
|
|
92
|
-
catch (error) {
|
|
93
|
-
const parsedError = parserError(error);
|
|
94
|
-
this.reject(guid, parsedError.code, parsedError.message);
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
if (this.clientGuid === null) {
|
|
98
|
-
this.reject(guid, 'not_connected', 'connect before sending events');
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
if (envelope.clientGuid !== this.clientGuid) {
|
|
102
|
-
this.reject(guid, 'client_guid_mismatch', 'event client guid does not match socket');
|
|
103
|
-
return;
|
|
104
|
-
}
|
|
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
|
-
}
|
|
120
|
-
if (outcome.kind === 'applied') {
|
|
121
|
-
// A committed event must reach every healthy peer even when this socket
|
|
122
|
-
// or another peer is stale. Report delivery failures only after fan-out.
|
|
123
|
-
const deliveryErrors = [];
|
|
124
|
-
for (const appliedEvent of outcome.events) {
|
|
125
|
-
const outgoing = { type: 'event', event: appliedEvent };
|
|
126
|
-
if (!this.closed) {
|
|
127
|
-
try {
|
|
128
|
-
this.sendToSocket(outgoing);
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
deliveryErrors.push(error);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
try {
|
|
135
|
-
this.broadcaster.publish(this.scopeKey, outgoing, this.broadcastListener);
|
|
136
|
-
}
|
|
137
|
-
catch (error) {
|
|
138
|
-
deliveryErrors.push(error);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
if (deliveryErrors.length === 1)
|
|
142
|
-
throw deliveryErrors[0];
|
|
143
|
-
if (deliveryErrors.length > 1) {
|
|
144
|
-
throw new AggregateError(deliveryErrors, 'sync event delivery failed');
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
else if (outcome.kind === 'duplicate') {
|
|
148
|
-
if (!this.closed)
|
|
149
|
-
this.sendToSocket({ type: 'event', event: outcome.event });
|
|
150
|
-
}
|
|
151
|
-
else if (!this.closed) {
|
|
152
|
-
this.sendToSocket({
|
|
153
|
-
type: 'rejection',
|
|
154
|
-
eventGuid: parsedEvent.eventGuid,
|
|
155
|
-
error: outcome.error,
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
close() {
|
|
160
|
-
if (this.closed)
|
|
161
|
-
return;
|
|
162
|
-
this.closed = true;
|
|
163
|
-
this.unsubscribe();
|
|
164
|
-
}
|
|
165
|
-
reject(eventGuid, code, message) {
|
|
166
|
-
this.sendToSocket({ type: 'rejection', eventGuid, error: { code, message } });
|
|
167
|
-
}
|
|
168
|
-
sendToSocket(message) {
|
|
169
|
-
if (this.closed)
|
|
170
|
-
return;
|
|
171
|
-
try {
|
|
172
|
-
this.send(message);
|
|
173
|
-
}
|
|
174
|
-
catch (error) {
|
|
175
|
-
this.close();
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
/** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
|
|
181
|
-
* duplicate reported as `applied`, nothing else. Kept for apps not yet on
|
|
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). */
|
|
185
|
-
export async function applyHttpEventBatch(engine, scopeKey, request, parseClientEvent) {
|
|
186
|
-
const batch = parseBatch(request, false);
|
|
187
|
-
const outcomes = await applyBatch(engine, scopeKey, batch, parseClientEvent, emptyCommitted());
|
|
188
|
-
return outcomes.map(oldShape);
|
|
189
|
-
}
|
|
190
|
-
/** One handler for every app's `POST /api/sync/events` (connection hub
|
|
191
|
-
* design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
|
|
192
|
-
* through the engine in order. A request without `lastSeq` (sendBeacon, and
|
|
193
|
-
* clients before hub mode) gets the old shape, `{ outcomes }` with
|
|
194
|
-
* duplicates reported as `applied`. A request with it gets frame outcomes
|
|
195
|
-
* (`applied` + committed events, `duplicate` + the stored event, `rejected`
|
|
196
|
-
* + error) and a contiguous catch-up from `lastSeq`, read after the commits:
|
|
197
|
-
* `events` + `currentSeq`, or `reload: true` when too far behind. Throws
|
|
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`. */
|
|
202
|
-
export async function handleSyncEventsRequest(options) {
|
|
203
|
-
const batch = parseBatch(options.body, true);
|
|
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);
|
|
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();
|
|
222
|
-
if (batch.lastSeq === undefined)
|
|
223
|
-
return { outcomes: outcomes.map(oldShape) };
|
|
224
|
-
const catchup = await options.engine.catchup(options.scopeKey, batch.lastSeq);
|
|
225
|
-
if (catchup.kind === 'reload')
|
|
226
|
-
return { outcomes, reload: true };
|
|
227
|
-
return { outcomes, events: catchup.events, currentSeq: catchup.currentSeq };
|
|
228
|
-
}
|
|
229
|
-
function parseBatch(request, withLastSeq) {
|
|
230
|
-
const envelope = record(request);
|
|
231
|
-
if (!envelope ||
|
|
232
|
-
typeof envelope.clientGuid !== 'string' ||
|
|
233
|
-
envelope.clientGuid.length === 0 ||
|
|
234
|
-
!Array.isArray(envelope.events)) {
|
|
235
|
-
throw new SyncError('bad_request', 'invalid event batch');
|
|
236
|
-
}
|
|
237
|
-
const batch = { clientGuid: envelope.clientGuid, events: envelope.events };
|
|
238
|
-
if (withLastSeq && envelope.lastSeq !== undefined) {
|
|
239
|
-
if (!Number.isSafeInteger(envelope.lastSeq) || envelope.lastSeq < 0) {
|
|
240
|
-
throw new SyncError('bad_request', 'invalid lastSeq');
|
|
241
|
-
}
|
|
242
|
-
batch.lastSeq = envelope.lastSeq;
|
|
243
|
-
}
|
|
244
|
-
return batch;
|
|
245
|
-
}
|
|
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) {
|
|
252
|
-
const outcomes = [];
|
|
253
|
-
for (const value of batch.events) {
|
|
254
|
-
const guid = eventGuid(value);
|
|
255
|
-
let event;
|
|
256
|
-
try {
|
|
257
|
-
event = parseClientEvent(value);
|
|
258
|
-
}
|
|
259
|
-
catch (error) {
|
|
260
|
-
outcomes.push({ eventGuid: guid, status: 'rejected', error: parserError(error) });
|
|
261
|
-
continue;
|
|
262
|
-
}
|
|
263
|
-
const outcome = await engine.apply(scopeKey, batch.clientGuid, event);
|
|
264
|
-
if (outcome.kind === 'rejected') {
|
|
265
|
-
outcomes.push({ eventGuid: event.eventGuid, status: 'rejected', error: outcome.error });
|
|
266
|
-
}
|
|
267
|
-
else if (outcome.kind === 'duplicate') {
|
|
268
|
-
committed.duplicates.push(outcome.event);
|
|
269
|
-
outcomes.push({ eventGuid: event.eventGuid, status: 'duplicate', events: [outcome.event] });
|
|
270
|
-
}
|
|
271
|
-
else {
|
|
272
|
-
committed.applied.push(...outcome.events);
|
|
273
|
-
outcomes.push({ eventGuid: event.eventGuid, status: 'applied', events: outcome.events });
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
return outcomes;
|
|
277
|
-
}
|
|
278
|
-
function oldShape(outcome) {
|
|
279
|
-
if (outcome.status === 'rejected') {
|
|
280
|
-
return { eventGuid: outcome.eventGuid, status: 'rejected', error: outcome.error };
|
|
281
|
-
}
|
|
282
|
-
return { eventGuid: outcome.eventGuid, status: 'applied' };
|
|
283
|
-
}
|