@steve31415/baselib 3.60.1 → 3.62.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 CHANGED
@@ -6,7 +6,7 @@ What it provides and why: `docs/SPEC.md`. How it's put together:
6
6
  `~/migration/research/base-services-design.md`.
7
7
 
8
8
  Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`, `s2s`, `db`, `http`, `sync`,
9
- `app-update`, `llm`, `email`, `twitter`, `hub` (the connection hub's server core, app notifier and daemon-token mint; `hub/testing` a local hub for tests), `hub-daemon` (the daemons' hub client), `code-manifest` and
9
+ `app-update`, `llm`, `email`, `twitter`, `hub` (the connection hub's server core, app notifier, per-request hint batch `HubHints` and daemon-token mint; `hub/testing` a local hub for tests), `hub-daemon` (the daemons' hub client), `code-manifest` and
10
10
  `client-version`. Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
11
11
  `extension-self-update`.
12
12
 
@@ -0,0 +1,40 @@
1
+ import type { MiddlewareHandler } from 'hono';
2
+ import type { AppHint, HubNotifier } from './notify.js';
3
+ /** How long a run's first hint waits for others to fold into its send. */
4
+ export declare const HUB_HINT_WINDOW_MS = 25;
5
+ export interface HubHintsOptions {
6
+ notifier: HubNotifier;
7
+ /** Default HUB_HINT_WINDOW_MS. */
8
+ windowMs?: number;
9
+ }
10
+ export interface HubHintsMiddlewareOptions {
11
+ /** Send `{user: '*', kind: 'build_changed'}` in the batch of the first
12
+ * request this copy serves other than `/health`, once per HubHints. For an
13
+ * app with no deploy-hook announcement: a copy receives load-balancer
14
+ * traffic only once its revision serves, so its first real request is when
15
+ * it knows its build is the one open pages should check for (design §14.3:
16
+ * announced through the app's own notifier, never from the deploy hook). A
17
+ * second copy, or a copy started from zero, announces too, costing each
18
+ * open page one build check that finds nothing new. */
19
+ announceBuild?: boolean;
20
+ }
21
+ export declare class HubHints {
22
+ private readonly notifier;
23
+ private readonly windowMs;
24
+ private readonly scope;
25
+ private buildAnnounced;
26
+ constructor(opts: HubHintsOptions);
27
+ /** Runs `work` with its own hint batch. Settles as `work` does (its value,
28
+ * or its error) once `work` has ended and every send it started has
29
+ * settled; a hint raised before `work` threw is still sent. */
30
+ run<T>(work: () => Promise<T>): Promise<T>;
31
+ /** Runs each request inside `run`, so it answers only after its hints have
32
+ * gone. Mount it after the request logger (so a request's logged duration
33
+ * includes the sends) and before every route that commits. */
34
+ middleware(opts?: HubHintsMiddlewareOptions): MiddlewareHandler;
35
+ /** Call after the commit the hint describes. Inside an open run the hint
36
+ * joins its window and the promise resolves at once (the run awaits the
37
+ * send); outside, it is sent now and the promise resolves once it has
38
+ * gone, so background work can await it. Never rejects. */
39
+ send(hint: AppHint): Promise<void>;
40
+ }
@@ -0,0 +1,107 @@
1
+ // One windowed hint batch per request (design §5.3: hints "coalesced once per
2
+ // request", sent after the commit and awaited inside the request so a
3
+ // throttled Cloud Run instance still has CPU for them). Consolidates the
4
+ // helpers radar, lurch, coder, chime, reader, notes and todo each wrote by
5
+ // hand on top of HubNotifier in session 5.
6
+ //
7
+ // Inside `run` (or the Hono `middleware`, which runs each request in one), a
8
+ // hint is not sent at once: the first opens a window of `windowMs` (25 ms),
9
+ // hints raised in the window fold into it (HubNotifyBatch's per-user-and-kind
10
+ // coalescing), and when the window closes they go in one send. A hint after a
11
+ // send has started opens a new window, so a request that works for minutes (a
12
+ // tick, a calendar sync) delivers each commit's hint within ~25 ms rather
13
+ // than holding them to its end. When the work ends, an open window is sent at
14
+ // once, and `run` settles only after every send it started has settled. A
15
+ // hint raised outside any run, or by a callback that outlives its run, is sent
16
+ // at once. HubNotifier bounds each send at 1 s, never throws, and opens a
17
+ // circuit after repeated failures, so a hub outage costs a request at most
18
+ // that second.
19
+ import { AsyncLocalStorage } from 'node:async_hooks';
20
+ /** How long a run's first hint waits for others to fold into its send. */
21
+ export const HUB_HINT_WINDOW_MS = 25;
22
+ /** One run's hints. */
23
+ class RunHints {
24
+ notifier;
25
+ windowMs;
26
+ batch;
27
+ pending = false;
28
+ timer = null;
29
+ sends = new Set();
30
+ closed = false;
31
+ constructor(notifier, windowMs) {
32
+ this.notifier = notifier;
33
+ this.windowMs = windowMs;
34
+ this.batch = notifier.batch();
35
+ }
36
+ add(hint) {
37
+ this.batch.add(hint);
38
+ this.pending = true;
39
+ this.timer ??= setTimeout(() => this.flush(), this.windowMs);
40
+ }
41
+ /** Send what has collected; close() awaits it. */
42
+ flush() {
43
+ if (this.timer)
44
+ clearTimeout(this.timer);
45
+ this.timer = null;
46
+ if (!this.pending)
47
+ return;
48
+ const batch = this.batch;
49
+ this.batch = this.notifier.batch();
50
+ this.pending = false;
51
+ const send = batch.flush().finally(() => this.sends.delete(send));
52
+ this.sends.add(send);
53
+ }
54
+ /** The work has ended: send the open window and wait for every send. */
55
+ async close() {
56
+ this.closed = true;
57
+ this.flush();
58
+ while (this.sends.size > 0)
59
+ await Promise.all([...this.sends]);
60
+ }
61
+ }
62
+ export class HubHints {
63
+ notifier;
64
+ windowMs;
65
+ scope = new AsyncLocalStorage();
66
+ buildAnnounced = false;
67
+ constructor(opts) {
68
+ this.notifier = opts.notifier;
69
+ this.windowMs = opts.windowMs ?? HUB_HINT_WINDOW_MS;
70
+ }
71
+ /** Runs `work` with its own hint batch. Settles as `work` does (its value,
72
+ * or its error) once `work` has ended and every send it started has
73
+ * settled; a hint raised before `work` threw is still sent. */
74
+ async run(work) {
75
+ const hints = new RunHints(this.notifier, this.windowMs);
76
+ try {
77
+ return await this.scope.run(hints, work);
78
+ }
79
+ finally {
80
+ await hints.close();
81
+ }
82
+ }
83
+ /** Runs each request inside `run`, so it answers only after its hints have
84
+ * gone. Mount it after the request logger (so a request's logged duration
85
+ * includes the sends) and before every route that commits. */
86
+ middleware(opts = {}) {
87
+ return (c, next) => this.run(async () => {
88
+ if (opts.announceBuild && !this.buildAnnounced && c.req.path !== '/health') {
89
+ this.buildAnnounced = true;
90
+ void this.send({ user: '*', kind: 'build_changed' });
91
+ }
92
+ await next();
93
+ });
94
+ }
95
+ /** Call after the commit the hint describes. Inside an open run the hint
96
+ * joins its window and the promise resolves at once (the run awaits the
97
+ * send); outside, it is sent now and the promise resolves once it has
98
+ * gone, so background work can await it. Never rejects. */
99
+ send(hint) {
100
+ const hints = this.scope.getStore();
101
+ if (hints && !hints.closed) {
102
+ hints.add(hint);
103
+ return Promise.resolve();
104
+ }
105
+ return this.notifier.notify(hint);
106
+ }
107
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './server.js';
3
3
  export * from './notify.js';
4
+ export * from './hints.js';
4
5
  export * from './mint.js';
package/dist/hub/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './server.js';
3
3
  export * from './notify.js';
4
+ export * from './hints.js';
4
5
  export * from './mint.js';
@@ -12,6 +12,16 @@ export interface EventLogEngineOptions<C extends EventBody, S extends EventBody>
12
12
  retentionDays?: number;
13
13
  randomGuid?: () => string;
14
14
  now?: () => number;
15
+ /** Called after every `apply` whose outcome is `applied` or `duplicate`
16
+ * (committed now, or by an earlier attempt), with the scope key and that
17
+ * outcome, whoever called the engine: the POST route, a socket session, a
18
+ * server-side writer. The connection hub's `sync_available` seam (a
19
+ * duplicate must hint too: the retry of a write whose first attempt
20
+ * committed). Per event, so in a batch a later event's
21
+ * `SyncUnavailableError` does not hide the events committed before it.
22
+ * Synchronous and must not throw; a throw is logged as ERROR
23
+ * `sync.on_applied_failed` and the apply still returns its outcome. */
24
+ onApplied?: (scopeKey: string, outcome: CommittedApplyOutcome<S>) => void;
15
25
  }
16
26
  export type ApplyOutcome<S extends EventBody> = {
17
27
  kind: 'applied';
@@ -26,6 +36,10 @@ export type ApplyOutcome<S extends EventBody> = {
26
36
  message: string;
27
37
  };
28
38
  };
39
+ /** An apply outcome whose event is in the log. */
40
+ export type CommittedApplyOutcome<S extends EventBody> = Exclude<ApplyOutcome<S>, {
41
+ kind: 'rejected';
42
+ }>;
29
43
  export type CatchupOutcome<S extends EventBody> = {
30
44
  kind: 'events';
31
45
  events: SyncEvent<S>[];
@@ -42,11 +56,17 @@ export declare class EventLogEngine<C extends EventBody, S extends EventBody> {
42
56
  private readonly retentionDays;
43
57
  private readonly randomGuid;
44
58
  private readonly now;
59
+ private readonly onApplied?;
45
60
  constructor(options: EventLogEngineOptions<C, S>);
46
- /** Apply one event. Domain validation failures are stable rejections; an
47
- * unexpected failure is retried once because event GUID dedupe makes an
48
- * ambiguous commit safe to replay. */
61
+ /** Apply one event. Domain validation failures (`SyncError`) are stable
62
+ * rejections. An unexpected failure is retried once, because event GUID
63
+ * dedupe makes an ambiguous commit safe to replay; if the retry fails too,
64
+ * a failure about the event's own data (`deterministicFailure`) is
65
+ * rejected as `internal`, and any other throws `SyncUnavailableError`: no
66
+ * verdict, the caller must make the client re-send. */
49
67
  apply(scopeKey: string, clientGuid: string | null, event: ClientEvent<C>): Promise<ApplyOutcome<S>>;
68
+ private notifyApplied;
69
+ private applyWithRetry;
50
70
  private rejectedOutcome;
51
71
  private applyOnce;
52
72
  currentSeq(scopeKey: string): Promise<number>;
@@ -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),
@@ -46,6 +62,7 @@ export class EventLogEngine {
46
62
  retentionDays;
47
63
  randomGuid;
48
64
  now;
65
+ onApplied;
49
66
  constructor(options) {
50
67
  this.pool = options.pool;
51
68
  this.logger = options.logger;
@@ -55,11 +72,29 @@ export class EventLogEngine {
55
72
  this.retentionDays = options.retentionDays ?? DEFAULT_RETENTION_DAYS;
56
73
  this.randomGuid = options.randomGuid ?? randomUUID;
57
74
  this.now = options.now ?? Date.now;
75
+ this.onApplied = options.onApplied;
58
76
  }
59
- /** Apply one event. Domain validation failures are stable rejections; an
60
- * unexpected failure is retried once because event GUID dedupe makes an
61
- * ambiguous commit safe to replay. */
77
+ /** Apply one event. Domain validation failures (`SyncError`) are stable
78
+ * rejections. An unexpected failure is retried once, because event GUID
79
+ * dedupe makes an ambiguous commit safe to replay; if the retry fails too,
80
+ * a failure about the event's own data (`deterministicFailure`) is
81
+ * rejected as `internal`, and any other throws `SyncUnavailableError`: no
82
+ * verdict, the caller must make the client re-send. */
62
83
  async apply(scopeKey, clientGuid, event) {
84
+ const outcome = await this.applyWithRetry(scopeKey, clientGuid, event);
85
+ if (this.onApplied && outcome.kind !== 'rejected')
86
+ this.notifyApplied(scopeKey, outcome);
87
+ return outcome;
88
+ }
89
+ notifyApplied(scopeKey, outcome) {
90
+ try {
91
+ this.onApplied(scopeKey, outcome);
92
+ }
93
+ catch (error) {
94
+ this.logger.error('sync.on_applied_failed', { scopeKey, outcome: outcome.kind, error });
95
+ }
96
+ }
97
+ async applyWithRetry(scopeKey, clientGuid, event) {
63
98
  try {
64
99
  return await this.applyOnce(scopeKey, clientGuid, event);
65
100
  }
@@ -79,12 +114,16 @@ export class EventLogEngine {
79
114
  if (retryError instanceof SyncError) {
80
115
  return this.rejectedOutcome(scopeKey, event, retryError);
81
116
  }
117
+ const retryable = !deterministicFailure(retryError);
82
118
  this.logger.error('sync.apply_failed', {
83
119
  scopeKey,
84
120
  eventGuid: event.eventGuid,
85
121
  eventType: event.type,
86
122
  error: retryError,
123
+ retryable,
87
124
  });
125
+ if (retryable)
126
+ throw new SyncUnavailableError(retryError);
88
127
  return {
89
128
  kind: 'rejected',
90
129
  error: { code: 'internal', message: 'internal error applying event' },
@@ -123,7 +162,7 @@ export class EventLogEngine {
123
162
  }
124
163
  const prepared = await this.prepareMutation(client, scopeKey, event);
125
164
  if (prepared.filter((candidate) => candidate.trigger === true).length !== 1) {
126
- throw new Error('mutation preparer must return exactly one trigger event');
165
+ throw new PreparerContractError('mutation preparer must return exactly one trigger event');
127
166
  }
128
167
  const eventCount = prepared.length;
129
168
  const bump = await client.query(`update ${scopesTable} set last_seq = last_seq + $2
@@ -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>>;
@@ -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
- const outcome = await this.engine.apply(this.scopeKey, this.clientGuid, parsedEvent);
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 { outcomes } = await applyBatch(engine, scopeKey, batch, parseClientEvent);
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 { 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);
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
- async function applyBatch(engine, scopeKey, batch, parseClientEvent) {
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 { outcomes, committed };
276
+ return outcomes;
235
277
  }
236
278
  function oldShape(outcome) {
237
279
  if (outcome.status === 'rejected') {
@@ -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;
@@ -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
+ }
@@ -2,3 +2,4 @@ export * from './outbox.js';
2
2
  export * from './client.js';
3
3
  export * from './quiet-status.js';
4
4
  export * from './hub.js';
5
+ export * from './page-hub-url.js';
@@ -2,3 +2,4 @@ export * from './outbox.js';
2
2
  export * from './client.js';
3
3
  export * from './quiet-status.js';
4
4
  export * from './hub.js';
5
+ export * from './page-hub-url.js';
@@ -0,0 +1,4 @@
1
+ /** The meta tag's name. */
2
+ export declare const PAGE_HUB_URL_META = "pw-hub-url";
3
+ /** The tag's trimmed content, or undefined when the tag is absent or empty. */
4
+ export declare function pageHubUrl(doc?: Pick<Document, 'querySelector'>): string | undefined;
@@ -0,0 +1,11 @@
1
+ // The connection hub's base URL from the page shell's `pw-hub-url` meta tag.
2
+ // An app's server writes the tag only when it has HUB_URL; a client handed the
3
+ // result as `hubUrl` runs in hub mode (the live socket is the hub's and
4
+ // carries hints only), and with `undefined` keeps its same-origin socket.
5
+ /** The meta tag's name. */
6
+ export const PAGE_HUB_URL_META = 'pw-hub-url';
7
+ /** The tag's trimmed content, or undefined when the tag is absent or empty. */
8
+ export function pageHubUrl(doc = document) {
9
+ const content = doc.querySelector(`meta[name="${PAGE_HUB_URL_META}"]`)?.getAttribute('content')?.trim();
10
+ return content ? content : undefined;
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.60.1",
3
+ "version": "3.62.0",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",