@steve31415/baselib 3.76.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 CHANGED
@@ -13,8 +13,8 @@ Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`,
13
13
  `sync` provides the Postgres event-log and server protocol primitives, and
14
14
  `handleSyncEventsRequest`, the one handler for every app's
15
15
  `POST /api/sync/events`; `sync-browser` provides the IndexedDB outbox and
16
- offline-first client, whose live socket is either the app's own (default) or
17
- the connection hub's (`hubUrl`, hub mode).
16
+ offline-first client, whose live socket is the connection hub's (`hubUrl`;
17
+ the app's own socket went in 4.0.0).
18
18
  `app-update` renders build-aware shells, matches their ETags, and fetches
19
19
  retained assets for consumer-owned routes;
20
20
  `app-update-browser` detects a new traffic build and reloads when the app's
@@ -35,7 +35,8 @@ Bins: `check-test-owners` — the fleet's structural test-coverage gate; every
35
35
  app runs it from `npm run verify`. `pw-deploy` / `pw-rollback` — the fleet
36
36
  deploy (`~/plasticine-way/docs/OPERATIONS.md`, "Deployment safety"); an
37
37
  app's hooks module (`DeployHooks` in `src/deploy/types.ts`) extends both,
38
- `postRollback` being the one hook `pw-rollback` runs.
38
+ `preRollback` (before traffic moves; a throw refuses) and `postRollback`
39
+ (after) being the hooks `pw-rollback` runs.
39
40
  `pw-sql` / `pw-logs` — read-only production queries (database, Axiom), the
40
41
  first step of any production investigation (same doc, "Investigating
41
42
  production state").
@@ -93,6 +93,34 @@ export async function runRollback(options) {
93
93
  throw new Error(`services would land on different images for ${target.slice(0, 12)}: ` +
94
94
  targets.map((t) => `${t.name}=${t.imageDigest.slice(-12)}`).join(' '));
95
95
  }
96
+ const hookContext = {
97
+ sha: target,
98
+ baseSha: servingShas.length === 1 ? servingShas[0] : null,
99
+ config,
100
+ repoRoot: options.repoRoot,
101
+ contextDir: '',
102
+ evidenceDir,
103
+ imageDigest: targets[0].imageDigest,
104
+ serving,
105
+ exec: runner,
106
+ log,
107
+ };
108
+ // A hooks module that fails to load must not stand between an incident
109
+ // and the traffic move: log it and go on (postRollback below reports it
110
+ // again, after the move). Only a hook that loads and throws refuses.
111
+ let hooks = null;
112
+ let hooksLoadError = null;
113
+ try {
114
+ hooks = await loadHooks(options.repoRoot, config);
115
+ }
116
+ catch (error) {
117
+ hooksLoadError = error;
118
+ log(`hooks module failed to load; rolling back without preRollback: ${String(error)}`);
119
+ }
120
+ if (hooks?.preRollback) {
121
+ timer.enter('preRollback');
122
+ await hooks.preRollback(hookContext);
123
+ }
96
124
  timer.enter('traffic');
97
125
  for (const t of targets) {
98
126
  await must(runner, 'gcloud', [
@@ -152,26 +180,12 @@ export async function runRollback(options) {
152
180
  throw new Error(`${service.name}: post-rollback smoke failed (${lastDetail})`);
153
181
  log(`${service.name}: smoke passed`);
154
182
  }
155
- // The hooks module is loaded only now: a broken one must not stand
156
- // between an incident and the traffic move.
157
183
  timer.enter('hooks');
158
184
  rolledBackTo = target;
159
- const hooks = await loadHooks(options.repoRoot, config);
160
- if (hooks.postRollback) {
161
- const ctx = {
162
- sha: target,
163
- baseSha: servingShas.length === 1 ? servingShas[0] : null,
164
- config,
165
- repoRoot: options.repoRoot,
166
- contextDir: '',
167
- evidenceDir,
168
- imageDigest: targets[0].imageDigest,
169
- serving,
170
- exec: runner,
171
- log,
172
- };
173
- await hooks.postRollback(ctx);
174
- }
185
+ if (hooksLoadError)
186
+ throw hooksLoadError;
187
+ if (hooks?.postRollback)
188
+ await hooks.postRollback(hookContext);
175
189
  timer.close();
176
190
  log(`rolled back to ${target.slice(0, 12)}`);
177
191
  log(`hold placed on ${servingShas.map((sha) => sha.slice(0, 12)).join(', ')} — ` +
@@ -185,7 +199,7 @@ export async function runRollback(options) {
185
199
  console.error(`rollback failed in phase: ${timer.current}`);
186
200
  if (rolledBackTo) {
187
201
  console.error(`traffic IS on ${rolledBackTo.slice(0, 12)} and the hold is placed; only the app's ` +
188
- 'postRollback hook failed — finish what it does by hand');
202
+ 'hooks module or its postRollback hook failed — finish what postRollback does by hand');
189
203
  }
190
204
  if (evidenceDir)
191
205
  console.error(`evidence: ${evidenceDir}`);
@@ -123,6 +123,15 @@ export interface DeployHooks {
123
123
  smoke?: (ctx: HookContext) => Promise<void>;
124
124
  /** Runs after everything else succeeded (e.g. notes's release state). */
125
125
  postSuccess?: (ctx: HookContext) => Promise<void>;
126
+ /** pw-rollback only: runs after the target is chosen, the migration check
127
+ * passed and the target's revisions are found, before any traffic moves —
128
+ * for a refusal only the app can judge (e.g. notes refuses a target
129
+ * without its document relay while the serving revision allows more than
130
+ * one copy). Same context as postRollback. A throw aborts the rollback:
131
+ * no traffic moves and no hold is placed. A hooks module that fails to
132
+ * load does not block the rollback here (it is logged; postRollback then
133
+ * reports it). */
134
+ preRollback?: (ctx: HookContext) => Promise<void>;
126
135
  /** pw-rollback only: runs after traffic is back on the target build, the
127
136
  * hold is placed and the smoke passed — for what a traffic move does not
128
137
  * carry (e.g. podcasts' render Job image). `sha` and `imageDigest` are the
@@ -50,6 +50,7 @@ export declare class DbBroadcastBridge {
50
50
  private readonly heartbeatTimeoutMs;
51
51
  private readonly reconnectDelaysMs;
52
52
  private listener;
53
+ private listenerAttachedAt;
53
54
  private stopped;
54
55
  private connecting;
55
56
  /** Set once start() has returned. From then on the app may have sessions
@@ -60,6 +61,12 @@ export declare class DbBroadcastBridge {
60
61
  private reconnectTimer;
61
62
  private heartbeatTimer;
62
63
  constructor(options: DbBroadcastBridgeOptions);
64
+ /** When the current LISTEN connection was attached (`Date.now()`), or
65
+ * null while there is none: before the first connect lands, from the
66
+ * moment a loss is noticed until the reconnect lands, and after stop().
67
+ * For an app that must act on a lost listener (e.g. Notes' document
68
+ * relay, which polls while nothing listens) without parsing the log. */
69
+ get connectedSince(): number | null;
63
70
  /** Makes the first connect attempt; never rejects. A failure is logged
64
71
  * and retried on the reconnect ladder (see the header). */
65
72
  start(): Promise<void>;
@@ -39,6 +39,7 @@ export class DbBroadcastBridge {
39
39
  heartbeatTimeoutMs;
40
40
  reconnectDelaysMs;
41
41
  listener = null;
42
+ listenerAttachedAt = null;
42
43
  stopped = true;
43
44
  connecting = false;
44
45
  /** Set once start() has returned. From then on the app may have sessions
@@ -62,6 +63,14 @@ export class DbBroadcastBridge {
62
63
  this.heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? DB_BRIDGE_HEARTBEAT_TIMEOUT_MS;
63
64
  this.reconnectDelaysMs = options.reconnectDelaysMs ?? DB_BRIDGE_RECONNECT_DELAYS_MS;
64
65
  }
66
+ /** When the current LISTEN connection was attached (`Date.now()`), or
67
+ * null while there is none: before the first connect lands, from the
68
+ * moment a loss is noticed until the reconnect lands, and after stop().
69
+ * For an app that must act on a lost listener (e.g. Notes' document
70
+ * relay, which polls while nothing listens) without parsing the log. */
71
+ get connectedSince() {
72
+ return this.listenerAttachedAt;
73
+ }
65
74
  /** Makes the first connect attempt; never rejects. A failure is logged
66
75
  * and retried on the reconnect ladder (see the header). */
67
76
  async start() {
@@ -148,6 +157,7 @@ export class DbBroadcastBridge {
148
157
  return;
149
158
  }
150
159
  this.listener = client;
160
+ this.listenerAttachedAt = Date.now();
151
161
  this.adjustPoolMin(1);
152
162
  client.on('notification', (notification) => this.onNotification(notification.payload));
153
163
  this.scheduleHeartbeat(client);
@@ -191,6 +201,7 @@ export class DbBroadcastBridge {
191
201
  if (!listener)
192
202
  return null;
193
203
  this.listener = null;
204
+ this.listenerAttachedAt = null;
194
205
  if (this.heartbeatTimer)
195
206
  clearTimeout(this.heartbeatTimer);
196
207
  this.heartbeatTimer = null;
@@ -0,0 +1,35 @@
1
+ import type { EventLogEngine } from './engine.js';
2
+ import { type ClientEvent, type EventBody, type HttpEventsResponse, type SyncEvent } from './types.js';
3
+ /** What one request committed, for `afterCommit`: the events it appended,
4
+ * and the stored event of each retried event that had already committed. */
5
+ export interface SyncEventsCommitted<S extends EventBody> {
6
+ applied: SyncEvent<S>[];
7
+ duplicates: SyncEvent<S>[];
8
+ }
9
+ export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBody> {
10
+ engine: EventLogEngine<C, S>;
11
+ /** Chosen by the app's authenticated, authorized route. */
12
+ scopeKey: string;
13
+ /** The request body as parsed JSON (untrusted). */
14
+ body: unknown;
15
+ parseClientEvent(value: unknown): ClientEvent<C>;
16
+ /** Runs once per request, after every event has been applied and before
17
+ * the catch-up is read, when at least one event was applied or was a
18
+ * duplicate: where the app notifies the hub (whose notify must fire on
19
+ * duplicates too, design §5.3). Awaited; it should not throw (a throw fails the
20
+ * request after the commit, and the client's retry is deduplicated). */
21
+ afterCommit?(committed: SyncEventsCommitted<S>): void | Promise<void>;
22
+ }
23
+ /** One handler for every app's `POST /api/sync/events` (connection hub
24
+ * design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
25
+ * through the engine in order. A request without `lastSeq` (the client's
26
+ * unload beacon) gets the old shape, `{ outcomes }` with
27
+ * duplicates reported as `applied`. A request with it gets frame outcomes
28
+ * (`applied` + committed events, `duplicate` + the stored event, `rejected`
29
+ * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
30
+ * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
31
+ * `SyncError('bad_request')` for a malformed batch (answer 400), and
32
+ * `SyncUnavailableError` when the database fails (answer 5xx; the client
33
+ * retries, and what committed before the failure comes back as duplicates).
34
+ * Events committed before such a failure still get `afterCommit`. */
35
+ export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
@@ -0,0 +1,106 @@
1
+ import { SyncError, } from './types.js';
2
+ function record(value) {
3
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
4
+ ? value
5
+ : null;
6
+ }
7
+ function eventGuid(value) {
8
+ const candidate = record(value);
9
+ return typeof candidate?.eventGuid === 'string' ? candidate.eventGuid : '';
10
+ }
11
+ function parserError(error) {
12
+ return error instanceof SyncError
13
+ ? { code: error.code, message: error.message }
14
+ : { code: 'invalid_payload', message: 'invalid event' };
15
+ }
16
+ /** One handler for every app's `POST /api/sync/events` (connection hub
17
+ * design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
18
+ * through the engine in order. A request without `lastSeq` (the client's
19
+ * unload beacon) gets the old shape, `{ outcomes }` with
20
+ * duplicates reported as `applied`. A request with it gets frame outcomes
21
+ * (`applied` + committed events, `duplicate` + the stored event, `rejected`
22
+ * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
23
+ * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
24
+ * `SyncError('bad_request')` for a malformed batch (answer 400), and
25
+ * `SyncUnavailableError` when the database fails (answer 5xx; the client
26
+ * retries, and what committed before the failure comes back as duplicates).
27
+ * Events committed before such a failure still get `afterCommit`. */
28
+ export async function handleSyncEventsRequest(options) {
29
+ const batch = parseBatch(options.body);
30
+ const committed = { applied: [], duplicates: [] };
31
+ const runAfterCommit = async () => {
32
+ if (options.afterCommit && (committed.applied.length > 0 || committed.duplicates.length > 0)) {
33
+ await options.afterCommit(committed);
34
+ }
35
+ };
36
+ let outcomes;
37
+ try {
38
+ outcomes = await applyBatch(options.engine, options.scopeKey, batch, options.parseClientEvent, committed);
39
+ }
40
+ catch (error) {
41
+ // Peers must still hear of what committed: the retry reports it only as
42
+ // duplicates. The hook's own failure (likely, mid-outage) yields to the
43
+ // original error; the retry's duplicates run the hook again.
44
+ await runAfterCommit().catch(() => { });
45
+ throw error;
46
+ }
47
+ await runAfterCommit();
48
+ if (batch.lastSeq === undefined)
49
+ return { outcomes: outcomes.map(oldShape) };
50
+ const catchup = await options.engine.catchup(options.scopeKey, batch.lastSeq);
51
+ if (catchup.kind === 'reload')
52
+ return { outcomes, reload: true };
53
+ return { outcomes, events: catchup.events, currentSeq: catchup.currentSeq };
54
+ }
55
+ function parseBatch(request) {
56
+ const envelope = record(request);
57
+ if (!envelope ||
58
+ typeof envelope.clientGuid !== 'string' ||
59
+ envelope.clientGuid.length === 0 ||
60
+ !Array.isArray(envelope.events)) {
61
+ throw new SyncError('bad_request', 'invalid event batch');
62
+ }
63
+ const batch = { clientGuid: envelope.clientGuid, events: envelope.events };
64
+ if (envelope.lastSeq !== undefined) {
65
+ if (!Number.isSafeInteger(envelope.lastSeq) || envelope.lastSeq < 0) {
66
+ throw new SyncError('bad_request', 'invalid lastSeq');
67
+ }
68
+ batch.lastSeq = envelope.lastSeq;
69
+ }
70
+ return batch;
71
+ }
72
+ /** Applies the batch in order, recording into `committed` as it goes, so a
73
+ * caller still has it when an event throws partway. */
74
+ async function applyBatch(engine, scopeKey, batch, parseClientEvent, committed) {
75
+ const outcomes = [];
76
+ for (const value of batch.events) {
77
+ const guid = eventGuid(value);
78
+ let event;
79
+ try {
80
+ event = parseClientEvent(value);
81
+ }
82
+ catch (error) {
83
+ outcomes.push({ eventGuid: guid, status: 'rejected', error: parserError(error) });
84
+ continue;
85
+ }
86
+ const outcome = await engine.apply(scopeKey, batch.clientGuid, event);
87
+ if (outcome.kind === 'rejected') {
88
+ outcomes.push({ eventGuid: event.eventGuid, status: 'rejected', error: outcome.error });
89
+ }
90
+ else if (outcome.kind === 'duplicate') {
91
+ committed.duplicates.push(outcome.event);
92
+ outcomes.push({ eventGuid: event.eventGuid, status: 'duplicate', events: [outcome.event] });
93
+ }
94
+ else {
95
+ committed.applied.push(...outcome.events);
96
+ outcomes.push({ eventGuid: event.eventGuid, status: 'applied', events: outcome.events });
97
+ }
98
+ }
99
+ return outcomes;
100
+ }
101
+ function oldShape(outcome) {
102
+ if (outcome.status === 'rejected') {
103
+ return { eventGuid: outcome.eventGuid, status: 'rejected', error: outcome.error };
104
+ }
105
+ return { eventGuid: outcome.eventGuid, status: 'applied' };
106
+ }
@@ -1,6 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './schema.js';
3
3
  export * from './engine.js';
4
- export * from './broadcaster.js';
5
- export * from './session.js';
4
+ export * from './http-events.js';
6
5
  export * from './db-bridge.js';
@@ -1,6 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './schema.js';
3
3
  export * from './engine.js';
4
- export * from './broadcaster.js';
5
- export * from './session.js';
4
+ export * from './http-events.js';
6
5
  export * from './db-bridge.js';
@@ -20,71 +20,23 @@ export declare class SyncError extends Error {
20
20
  /** `EventLogEngine.apply` could not reach a verdict: a failure that is not
21
21
  * about the event (a dropped connection, a failover, a deploy's schema skew)
22
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
23
+ * re-send it, which its GUID makes safe. The HTTP route lets it propagate to
24
+ * a 5xx (the client retries). The engine has already logged
26
25
  * `sync.apply_failed` (ERROR); `cause` is the last failure. */
27
26
  export declare class SyncUnavailableError extends Error {
28
27
  constructor(cause: unknown);
29
28
  }
30
- export interface WsConnect {
31
- type: 'connect';
32
- clientGuid: string;
33
- lastSeq: number;
34
- }
35
- export interface WsClientEvent<T extends EventBody> {
36
- type: 'event';
37
- clientGuid: string;
38
- event: ClientEvent<T>;
39
- }
40
- export interface WsPing {
41
- type: 'ping';
42
- }
43
- export type WsClientMessage<T extends EventBody> = WsConnect | WsClientEvent<T> | WsPing;
44
- export interface WsEventBroadcast<T extends EventBody> {
45
- type: 'event';
46
- event: SyncEvent<T>;
47
- }
48
- export interface WsCatchup<T extends EventBody> {
49
- type: 'catchup';
50
- events: SyncEvent<T>[];
51
- currentSeq: number;
52
- buildId?: string;
53
- }
54
- export interface WsReload {
55
- type: 'reload';
56
- }
57
- export interface WsRejection {
58
- type: 'rejection';
59
- eventGuid: string;
60
- error: {
61
- code: string;
62
- message: string;
63
- };
64
- }
65
- export interface WsPong {
66
- type: 'pong';
67
- buildId?: string;
68
- }
69
- /** Prompt to verify the canonical traffic build over authenticated HTTP. */
70
- export interface WsBuildChanged {
71
- type: 'build_changed';
72
- }
73
- /** Durable events may have advanced; answer with connect(lastSeq). */
74
- export interface WsSyncAvailable {
75
- type: 'sync_available';
76
- }
77
- export type WsServerMessage<T extends EventBody> = WsEventBroadcast<T> | WsCatchup<T> | WsReload | WsRejection | WsPong | WsBuildChanged | WsSyncAvailable;
78
29
  export interface HttpEventsRequest<T extends EventBody> {
79
30
  clientGuid: string;
80
31
  events: ClientEvent<T>[];
81
- /** The tab's current sequence (hub-mode clients). A request that carries it
82
- * is answered with outcome frames and a catch-up from it
83
- * (`handleSyncEventsRequest`); one without it, the old shape. */
32
+ /** The tab's current sequence (every `SyncClient` POST). A request that
33
+ * carries it is answered with outcome frames and a catch-up from it
34
+ * (`handleSyncEventsRequest`); one without it (the unload beacon), the old
35
+ * shape. */
84
36
  lastSeq?: number;
85
37
  }
86
- /** One event's outcome in the old response shape: what clients that send no
87
- * `lastSeq` get, and all they read (anything but `rejected` is applied). */
38
+ /** One event's outcome in the old response shape: what a request without
39
+ * `lastSeq` gets (anything but `rejected` is applied). */
88
40
  export interface HttpEventOutcome {
89
41
  eventGuid: string;
90
42
  status: 'applied' | 'rejected';
@@ -9,9 +9,8 @@ export class SyncError extends Error {
9
9
  /** `EventLogEngine.apply` could not reach a verdict: a failure that is not
10
10
  * about the event (a dropped connection, a failover, a deploy's schema skew)
11
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
12
+ * re-send it, which its GUID makes safe. The HTTP route lets it propagate to
13
+ * a 5xx (the client retries). The engine has already logged
15
14
  * `sync.apply_failed` (ERROR); `cause` is the last failure. */
16
15
  export class SyncUnavailableError extends Error {
17
16
  constructor(cause) {