@steve31415/baselib 3.69.0 → 3.71.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.
@@ -22,6 +22,9 @@ function validateService(raw, index) {
22
22
  fail(`services[${index}].health.audience`);
23
23
  if (s.health.kind === 'public-canonical' && !s.canonicalUrl)
24
24
  fail(`services[${index}].canonicalUrl`);
25
+ // The path also goes into gcloud's comma-separated --startup-probe value.
26
+ if (s.health.path !== undefined && !/^\/[A-Za-z0-9/_.-]*$/.test(s.health.path))
27
+ fail(`services[${index}].health.path (want /[A-Za-z0-9/_.-]*)`);
25
28
  return s;
26
29
  }
27
30
  export function validateConfig(raw) {
@@ -1,6 +1,25 @@
1
- import type { Runner } from './types.js';
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
+ /**
5
+ * The `--startup-probe` value every `services update` asserts: Cloud Run
6
+ * sends `GET <health path>` to each new instance and lets it take traffic
7
+ * only on a success, instead of its default check that the port merely
8
+ * accepts connections. null for `health.kind: 'none'` (the probe is left as
9
+ * configured). Omitting httpGet.port probes the container port.
10
+ *
11
+ * Timing: one attempt a second, each allowed one second, 240 attempts — the
12
+ * same four-minute window as Cloud Run's default TCP probe. 2026-11-21: the
13
+ * slowest serving revision fleet-wide became healthy in 5.2 s (corpus), about
14
+ * 2% of the window; the window is deliberately generous because a slow start
15
+ * that times out fails the deploy (safely: traffic stays put). A one-second
16
+ * period costs at most a second over the TCP probe — the first attempt usually
17
+ * lands before the server listens (measured on a throwaway service: healthy
18
+ * 1.3 s after start). The /health it hits is baselib's addHealth, a static
19
+ * reply in every app, so the probe proves the HTTP app answers, not that its
20
+ * dependencies are up.
21
+ */
22
+ export declare function startupProbeArg(health: ServiceHealth): string | null;
4
23
  export interface DeployOptions {
5
24
  repoRoot: string;
6
25
  runner: Runner;
@@ -13,7 +13,7 @@ import { DEFAULT_ACCOUNT, loadConfig, loadHooks } from './config.js';
13
13
  import { CommandFailure, must, mustJson } from './exec.js';
14
14
  import { openEvidence, PhaseTimer } from './evidence.js';
15
15
  import { acquireLock, clearHold, publishRetainedAssets, readHold, readReleaseRecord, releaseLock, verifyLock, writeReleaseRecord, } from './gcs.js';
16
- import { consistentBaseSha, readServingState, SHA40, strayTrafficPin } from './plan.js';
16
+ import { consistentBaseSha, readServingState, servingRevisionName, SHA40, strayTrafficPin } from './plan.js';
17
17
  import { writeDeployMarker } from './deploy-marker.js';
18
18
  const RELEASE_DEADLINE_MS = 25 * 60_000;
19
19
  const IMAGE_DIGEST = /@sha256:[0-9a-f]{64}$/;
@@ -23,6 +23,30 @@ 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
+ /**
27
+ * The `--startup-probe` value every `services update` asserts: Cloud Run
28
+ * sends `GET <health path>` to each new instance and lets it take traffic
29
+ * only on a success, instead of its default check that the port merely
30
+ * accepts connections. null for `health.kind: 'none'` (the probe is left as
31
+ * configured). Omitting httpGet.port probes the container port.
32
+ *
33
+ * Timing: one attempt a second, each allowed one second, 240 attempts — the
34
+ * same four-minute window as Cloud Run's default TCP probe. 2026-11-21: the
35
+ * slowest serving revision fleet-wide became healthy in 5.2 s (corpus), about
36
+ * 2% of the window; the window is deliberately generous because a slow start
37
+ * that times out fails the deploy (safely: traffic stays put). A one-second
38
+ * period costs at most a second over the TCP probe — the first attempt usually
39
+ * lands before the server listens (measured on a throwaway service: healthy
40
+ * 1.3 s after start). The /health it hits is baselib's addHealth, a static
41
+ * reply in every app, so the probe proves the HTTP app answers, not that its
42
+ * dependencies are up.
43
+ */
44
+ export function startupProbeArg(health) {
45
+ if (health.kind === 'none')
46
+ return null;
47
+ const path = health.path ?? '/health';
48
+ return `httpGet.path=${path},periodSeconds=1,timeoutSeconds=1,failureThreshold=240`;
49
+ }
26
50
  const MAX_DIRTY_PATHS = 20;
27
51
  /** The clean-worktree refusal, naming what made the tree dirty (`git status
28
52
  * --porcelain` lines) so the reader need not go and look (2026-10-11: games'
@@ -121,6 +145,9 @@ export async function runDeploy(options) {
121
145
  if (!base.ok)
122
146
  throw new Error(base.detail);
123
147
  const baseSha = base.baseSha;
148
+ if (baseSha && baseSha !== sha) {
149
+ await refuseEditedShippedMigrations(runner, options.repoRoot, baseSha, sha, log);
150
+ }
124
151
  if (config.refuseMigrationDiffOnDeploy && baseSha && baseSha !== sha) {
125
152
  await must(runner, 'git', ['cat-file', '-e', `${baseSha}^{commit}`], {
126
153
  cwd: options.repoRoot,
@@ -275,6 +302,34 @@ export async function runDeploy(options) {
275
302
  ...gcloudBase, '--region', config.region, '--quiet', '--format=json',
276
303
  '--to-revisions', `${revision}=100`,
277
304
  ]);
305
+ // Pin, then read the pin back: the read-back is the verdict, not gcloud's
306
+ // exit status. `update-traffic` waits for the whole service to become
307
+ // ready, which it does not while its newest revision is the one that
308
+ // failed, so a pin back to the serving revision exits nonzero (120)
309
+ // although it took effect (throwaway service pw-probe-test, 2026-11-21).
310
+ const pinAndConfirm = async (name, revision) => {
311
+ const result = await pinTraffic(name, revision);
312
+ const read = await runner('gcloud', [
313
+ 'run', 'services', 'describe', name,
314
+ ...gcloudBase, '--region', config.region, '--format=json',
315
+ ]);
316
+ let confirmed = false;
317
+ if (read.code === 0) {
318
+ try {
319
+ const described = JSON.parse(read.stdout);
320
+ confirmed =
321
+ strayTrafficPin(described, revision) === null && servingRevisionName(name, described) === revision;
322
+ }
323
+ catch {
324
+ confirmed = false;
325
+ }
326
+ }
327
+ const note = confirmed && result.code !== 0
328
+ ? ` (gcloud exited ${result.code} because the service stays not ready while its newest ` +
329
+ 'revision is the failed one; the pin was read back and is correct)'
330
+ : '';
331
+ return { result, confirmed, note };
332
+ };
278
333
  const repinCommand = (name, revision) => `gcloud run services update-traffic ${name} --project ${config.project} ` +
279
334
  `--region ${config.region} --to-revisions ${revision}=100`;
280
335
  // A failed `update-traffic` leaves the service's desired traffic pinned
@@ -289,11 +344,11 @@ export async function runDeploy(options) {
289
344
  'because the deploy lock was lost (another deploy or rollback owns the service now)');
290
345
  return;
291
346
  }
292
- const restored = await pinTraffic(name, revision);
347
+ const { result: restored, confirmed, note } = await pinAndConfirm(name, revision);
293
348
  await evidence.save(`${name}-traffic-restore.json`, restored.stdout + restored.stderr);
294
- if (restored.code === 0) {
349
+ if (confirmed) {
295
350
  log(`${name}: traffic switch to ${failedRevision} failed; restored the traffic pin to ` +
296
- `${revision}, which still serves`);
351
+ `${revision}, which still serves${note}`);
297
352
  }
298
353
  else {
299
354
  const tail = (restored.stderr.trim() || restored.stdout.trim()).slice(-500);
@@ -316,14 +371,14 @@ export async function runDeploy(options) {
316
371
  // An earlier release's failed traffic switch whose pin was not put
317
372
  // back (that run was killed, or its restore failed): `services
318
373
  // update` would fail on it, so re-pin to what serves first.
319
- const repinned = await pinTraffic(service.name, current.revision);
320
- if (repinned.code !== 0) {
374
+ const { result: repinned, confirmed, note } = await pinAndConfirm(service.name, current.revision);
375
+ if (!confirmed) {
321
376
  const tail = (repinned.stderr.trim() || repinned.stdout.trim()).slice(-1500);
322
377
  throw new CommandFailure(`${service.name}: traffic is pinned to ${stray} while ${current.revision} serves, and ` +
323
378
  `re-pinning failed; every deploy fails until: ${repinCommand(service.name, current.revision)}\n${tail}`, repinned);
324
379
  }
325
380
  log(`${service.name}: traffic was pinned to ${stray} while ${current.revision} served ` +
326
- `(left by an earlier failed release); re-pinned to ${current.revision}`);
381
+ `(left by an earlier failed release); re-pinned to ${current.revision}${note}`);
327
382
  }
328
383
  // One --update-env-vars with gcloud's alternate-delimiter form (^|^ …)
329
384
  // so declared values may contain commas; '|' is rejected by validateConfig.
@@ -341,6 +396,9 @@ export async function runDeploy(options) {
341
396
  .join(',');
342
397
  updateArgs.push('--update-secrets', pairs);
343
398
  }
399
+ const probe = startupProbeArg(service.health);
400
+ if (probe)
401
+ updateArgs.push('--startup-probe', probe);
344
402
  const updated = await must(runner, 'gcloud', updateArgs, { timeoutMs: 10 * 60_000 });
345
403
  await evidence.save(`${service.name}-update.json`, updated.stdout);
346
404
  const after = await mustJson(runner, 'gcloud', [
@@ -356,10 +414,13 @@ export async function runDeploy(options) {
356
414
  // here proves only the configuration and image import: Cloud Run starts
357
415
  // no instance of a revision without traffic (notes-00156-dkv reported
358
416
  // Ready 5 s before its first instance existed, and that instance exited
359
- // at startup). The boot check is `update-traffic` below: Cloud Run starts
360
- // the revision and moves no traffic unless its startup probe passes,
361
- // for min-instance and scale-to-zero services alike (2026-11-20
362
- // investigation; a revision-tag URL is no alternative while ingress is
417
+ // at startup); gcloud's --deploy-health-check, documented as starting
418
+ // one instance, changed nothing at 0% traffic (2026-11-21, throwaway
419
+ // service). The boot check is `update-traffic` below: Cloud Run starts
420
+ // the revision and moves no traffic unless its startup probe (the HTTP
421
+ // /health probe asserted above) passes, for min-instance and
422
+ // scale-to-zero services alike (2026-11-20 investigation; a
423
+ // revision-tag URL is no alternative while ingress is
363
424
  // internal-and-cloud-load-balancing, as for all but one service).
364
425
  let ready = false;
365
426
  let lastCondition = '';
@@ -524,3 +585,29 @@ export async function runDeploy(options) {
524
585
  await removeDeployMarker();
525
586
  }
526
587
  }
588
+ /**
589
+ * A migration file present in the serving build has been applied (every app
590
+ * applies its migrations/ at boot, and the serving revision booted), so the
591
+ * release must carry it byte-for-byte: baselib `migrate` refuses to boot on
592
+ * a changed checksum, and a removed or renamed file would leave fresh
593
+ * databases without it or re-apply it under the new name. Fail here, before
594
+ * the lock and build, rather than minutes later at the traffic switch with a
595
+ * crash-looping revision (notes 2026-11-20: a repo-wide path rewrite touched
596
+ * 0008_comments.sql's header comment; verify and E2E use fresh databases, so
597
+ * nothing else caught it). Skipped with a warning when the serving commit is
598
+ * not in this checkout.
599
+ */
600
+ async function refuseEditedShippedMigrations(runner, repoRoot, baseSha, sha, log) {
601
+ const known = await runner('git', ['cat-file', '-e', `${baseSha}^{commit}`], { cwd: repoRoot });
602
+ if (known.code !== 0) {
603
+ log(`warning: serving build ${baseSha.slice(0, 12)} is not in this checkout; shipped migrations not checked`);
604
+ return;
605
+ }
606
+ const edited = (await must(runner, 'git', ['diff', '--name-only', '--no-renames', '--diff-filter=DMT', `${baseSha}..${sha}`, '--', 'migrations'], { cwd: repoRoot })).stdout.trim();
607
+ if (edited) {
608
+ throw new Error(`migrations already applied by serving build ${baseSha.slice(0, 12)} were edited, renamed or removed:\n` +
609
+ `${edited}\nA shipped migration is never edited (its comments are part of its checksum, and the new ` +
610
+ 'revision would refuse to boot): restore each file byte-for-byte ' +
611
+ `(git checkout ${baseSha.slice(0, 12)} -- <file>) and put the change in a new migration.`);
612
+ }
613
+ }
@@ -6,6 +6,9 @@ export interface ServiceHealth {
6
6
  * - none: no shared health check (app hook covers it) */
7
7
  kind: 'public-canonical' | 'oidc-run-url' | 'oidc-audience' | 'none';
8
8
  audience?: string;
9
+ /** Health path (default /health): the smoke's target, and since 3.71.0 the
10
+ * path of the HTTP startup probe every deploy asserts (kind 'none' leaves
11
+ * the probe alone). */
9
12
  path?: string;
10
13
  }
11
14
  export interface ServiceConfig {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.69.0",
3
+ "version": "3.71.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",