@steve31415/baselib 3.75.0 → 3.77.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
@@ -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").
@@ -1,6 +1,8 @@
1
1
  import type { Runner, ServiceHealth } from './types.js';
2
2
  /** A gate's output shows its test browser process crashed (e.g. a segfault). */
3
3
  export declare function testBrowserCrashed(output: string): boolean;
4
+ /** A Cloud Build log shows a registry refused a pull for request quota. */
5
+ export declare function registryRateLimited(buildLog: string): boolean;
4
6
  /**
5
7
  * The `--startup-probe` value every `services update` asserts: Cloud Run
6
8
  * sends `GET <health path>` to each new instance and lets it take traffic
@@ -23,6 +23,19 @@ const BROWSER_CRASH = /^\s*\[pid=\d+\]\[err\] Received signal \d+ /m;
23
23
  export function testBrowserCrashed(output) {
24
24
  return BROWSER_CRASH.test(output);
25
25
  }
26
+ /** The Cloud Build id `gcloud builds submit` prints when it creates a build. */
27
+ const CLOUD_BUILD_ID = /\/builds\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/;
28
+ /** A registry refusing a pull for request quota (Docker's error code). */
29
+ const REGISTRY_RATE_LIMIT = /\btoomanyrequests\b|429 Too Many Requests/i;
30
+ /**
31
+ * Pause before resubmitting a rate-limited build: the quota that refused it
32
+ * is counted per minute.
33
+ */
34
+ const RATE_LIMIT_PAUSE_MS = 60_000;
35
+ /** A Cloud Build log shows a registry refused a pull for request quota. */
36
+ export function registryRateLimited(buildLog) {
37
+ return REGISTRY_RATE_LIMIT.test(buildLog);
38
+ }
26
39
  /**
27
40
  * The `--startup-probe` value every `services update` asserts: Cloud Run
28
41
  * sends `GET <health path>` to each new instance and lets it take traffic
@@ -226,13 +239,35 @@ export async function runDeploy(options) {
226
239
  log('reusing existing immutable commit image');
227
240
  }
228
241
  else {
229
- const submit = await must(runner, 'gcloud', [
242
+ const submitArgs = [
230
243
  'builds', 'submit', contextDir,
231
244
  '--config', join(contextDir, 'cloudbuild.yaml'),
232
245
  '--region', config.region, ...gcloudBase,
233
246
  '--substitutions', `_IMAGE=${imageUri}`,
234
247
  '--suppress-logs', '--format=json',
235
- ], { timeoutMs: 15 * 60_000 });
248
+ ];
249
+ const submitBuild = () => runner('gcloud', submitArgs, { timeoutMs: 15 * 60_000 });
250
+ let submit = await submitBuild();
251
+ const buildId = CLOUD_BUILD_ID.exec(submit.stderr + submit.stdout)?.[1];
252
+ if (submit.code !== 0 && buildId) {
253
+ // The registry refusing a base-image pull for its per-minute request
254
+ // quota is outside anything the commit controls: resubmit once after
255
+ // a pause. Any other build failure fails at once. backup3 lost a
256
+ // deploy to mirror.gcr.io's "toomanyrequests" on 2026-11-30 (Cloud
257
+ // Build 6fb71ed9, Coder task 66468cf5) — 1 of ~1,140 builds since
258
+ // 2026-10-01.
259
+ const buildLog = await runner('gcloud', ['builds', 'log', buildId, '--region', config.region, ...gcloudBase]);
260
+ if (registryRateLimited(buildLog.stdout + buildLog.stderr)) {
261
+ await evidence.save('cloud-build-rate-limited.log', buildLog.stdout + buildLog.stderr);
262
+ log(`image build ${buildId} failed on a registry rate limit; resubmitting once in ${RATE_LIMIT_PAUSE_MS / 1000} s`);
263
+ await sleep(RATE_LIMIT_PAUSE_MS);
264
+ submit = await submitBuild();
265
+ }
266
+ }
267
+ if (submit.code !== 0) {
268
+ const tail = (submit.stderr.trim() || submit.stdout.trim()).slice(-2000);
269
+ throw new CommandFailure(`gcloud ${submitArgs.join(' ')} exited ${submit.code}\n${tail}`, submit);
270
+ }
236
271
  await evidence.save('cloud-build.json', submit.stdout);
237
272
  }
238
273
  const digest = (await describeImage()).image_summary?.fully_qualified_digest ?? '';
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.75.0",
3
+ "version": "3.77.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",