@steve31415/baselib 3.68.0 → 3.69.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.
@@ -2,17 +2,18 @@
2
2
  // preflight -> lock -> build -> assets -> seal -> [image build ‖ gates] ->
3
3
  // fence -> per-service update + explicit traffic pin -> hooks/smoke/log check
4
4
  // -> release record -> unlock. A failure before the traffic switch leaves the
5
- // old revision serving; after it, the failure is reported with the rollback
6
- // command printed.
5
+ // old revision serving; a failed switch also puts the traffic pin back on it
6
+ // (a stray pin left by an earlier run is re-pinned before the update); after
7
+ // the switch, the failure is reported with the rollback command printed.
7
8
  import { createHash } from 'node:crypto';
8
9
  import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
9
10
  import { hostname } from 'node:os';
10
11
  import { join, resolve } from 'node:path';
11
12
  import { DEFAULT_ACCOUNT, loadConfig, loadHooks } from './config.js';
12
- import { must, mustJson } from './exec.js';
13
+ import { CommandFailure, must, mustJson } from './exec.js';
13
14
  import { openEvidence, PhaseTimer } from './evidence.js';
14
15
  import { acquireLock, clearHold, publishRetainedAssets, readHold, readReleaseRecord, releaseLock, verifyLock, writeReleaseRecord, } from './gcs.js';
15
- import { consistentBaseSha, readServingState, SHA40 } from './plan.js';
16
+ import { consistentBaseSha, readServingState, SHA40, strayTrafficPin } from './plan.js';
16
17
  import { writeDeployMarker } from './deploy-marker.js';
17
18
  const RELEASE_DEADLINE_MS = 25 * 60_000;
18
19
  const IMAGE_DIGEST = /@sha256:[0-9a-f]{64}$/;
@@ -109,10 +110,12 @@ export async function runDeploy(options) {
109
110
  'a rollback moved traffic off it. Deploy a fix, or pass --override-hold.');
110
111
  }
111
112
  const serving = [];
113
+ const servingDescribed = [];
112
114
  for (const service of config.services) {
113
115
  const { described, state } = await readServingState(runner, gcloudBase, config.region, service.name);
114
116
  await evidence.save(`${service.name}-before.json`, JSON.stringify(described, null, 2));
115
117
  serving.push(state);
118
+ servingDescribed.push(described);
116
119
  }
117
120
  const base = consistentBaseSha(serving, sha);
118
121
  if (!base.ok)
@@ -267,6 +270,37 @@ export async function runDeploy(options) {
267
270
  }
268
271
  if (hooks.preRelease)
269
272
  await hooks.preRelease(ctx);
273
+ const pinTraffic = (name, revision) => runner('gcloud', [
274
+ 'run', 'services', 'update-traffic', name,
275
+ ...gcloudBase, '--region', config.region, '--quiet', '--format=json',
276
+ '--to-revisions', `${revision}=100`,
277
+ ]);
278
+ const repinCommand = (name, revision) => `gcloud run services update-traffic ${name} --project ${config.project} ` +
279
+ `--region ${config.region} --to-revisions ${revision}=100`;
280
+ // A failed `update-traffic` leaves the service's desired traffic pinned
281
+ // to the revision that failed while the old one goes on serving; the
282
+ // service then reports not ready and every later `services update`
283
+ // fails on the dead revision (notes, 2026-11-20). Put the pin back on
284
+ // the revision that served when this deploy started, which is still
285
+ // serving: the observed traffic never moved.
286
+ const restoreTrafficPin = async (name, revision, failedRevision) => {
287
+ if (!lock || !(await verifyLock(runner, lock))) {
288
+ log(`${name}: traffic switch to ${failedRevision} failed; NOT restoring the pin to ${revision} ` +
289
+ 'because the deploy lock was lost (another deploy or rollback owns the service now)');
290
+ return;
291
+ }
292
+ const restored = await pinTraffic(name, revision);
293
+ await evidence.save(`${name}-traffic-restore.json`, restored.stdout + restored.stderr);
294
+ if (restored.code === 0) {
295
+ log(`${name}: traffic switch to ${failedRevision} failed; restored the traffic pin to ` +
296
+ `${revision}, which still serves`);
297
+ }
298
+ else {
299
+ const tail = (restored.stderr.trim() || restored.stdout.trim()).slice(-500);
300
+ log(`${name}: traffic switch to ${failedRevision} failed AND restoring the pin to ${revision} ` +
301
+ `failed (${tail}); every deploy fails until: ${repinCommand(name, revision)}`);
302
+ }
303
+ };
270
304
  const deployed = [];
271
305
  for (const [index, service] of config.services.entries()) {
272
306
  const current = serving[index];
@@ -277,6 +311,20 @@ export async function runDeploy(options) {
277
311
  });
278
312
  continue;
279
313
  }
314
+ const stray = strayTrafficPin(servingDescribed[index], current.revision);
315
+ if (stray) {
316
+ // An earlier release's failed traffic switch whose pin was not put
317
+ // back (that run was killed, or its restore failed): `services
318
+ // 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) {
321
+ const tail = (repinned.stderr.trim() || repinned.stdout.trim()).slice(-1500);
322
+ throw new CommandFailure(`${service.name}: traffic is pinned to ${stray} while ${current.revision} serves, and ` +
323
+ `re-pinning failed; every deploy fails until: ${repinCommand(service.name, current.revision)}\n${tail}`, repinned);
324
+ }
325
+ log(`${service.name}: traffic was pinned to ${stray} while ${current.revision} served ` +
326
+ `(left by an earlier failed release); re-pinned to ${current.revision}`);
327
+ }
280
328
  // One --update-env-vars with gcloud's alternate-delimiter form (^|^ …)
281
329
  // so declared values may contain commas; '|' is rejected by validateConfig.
282
330
  const envPairs = [`BUILD_ID=${sha}`, ...Object.entries(config.updateEnv ?? {}).map(([k, v]) => `${k}=${v}`)];
@@ -304,7 +352,15 @@ export async function runDeploy(options) {
304
352
  throw new Error(`${service.name}: expected a new revision, got ${newRevision || 'none'}`);
305
353
  }
306
354
  // On a traffic-pinned service, `services update` can return before the
307
- // 0%-traffic revision reports Ready — poll the revision itself.
355
+ // 0%-traffic revision reports Ready — poll the revision itself. Ready
356
+ // here proves only the configuration and image import: Cloud Run starts
357
+ // no instance of a revision without traffic (notes-00156-dkv reported
358
+ // 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
363
+ // internal-and-cloud-load-balancing, as for all but one service).
308
364
  let ready = false;
309
365
  let lastCondition = '';
310
366
  for (let attempt = 0; attempt < 60; attempt += 1) {
@@ -325,11 +381,14 @@ export async function runDeploy(options) {
325
381
  if (!ready) {
326
382
  throw new Error(`${service.name}: revision ${newRevision} is not ready (${lastCondition})`);
327
383
  }
328
- await must(runner, 'gcloud', [
329
- 'run', 'services', 'update-traffic', service.name,
330
- ...gcloudBase, '--region', config.region, '--quiet', '--format=json',
331
- '--to-revisions', `${newRevision}=100`,
332
- ]);
384
+ const switched = await pinTraffic(service.name, newRevision);
385
+ await evidence.save(`${service.name}-traffic.json`, switched.stdout + switched.stderr);
386
+ if (switched.code !== 0) {
387
+ await restoreTrafficPin(service.name, current.revision, newRevision);
388
+ const tail = (switched.stderr.trim() || switched.stdout.trim()).slice(-1500);
389
+ throw new CommandFailure(`${service.name}: traffic switch to ${newRevision} failed (exit ${switched.code}); ` +
390
+ `${current.revision} still serves\n${tail}`, switched);
391
+ }
333
392
  trafficMoved = true;
334
393
  log(`${service.name}: serving ${newRevision}`);
335
394
  deployed.push({ name: service.name, revision: newRevision, imageDigest, updated: true });
@@ -45,6 +45,19 @@ export declare function pickRevisionForSha(revisions: unknown[], targetSha: stri
45
45
  * describe --format=json`, from *observed* traffic (`status.traffic`, never
46
46
  * `spec.traffic`, which is only the desired state). */
47
47
  export declare function servingRevisionName(service: string, described: unknown): string;
48
+ /** A traffic pin that routes somewhere other than the revision actually
49
+ * serving, in a `gcloud run services describe --format=json`: the desired
50
+ * state (`spec.traffic`) names another revision (or the latest one) for a
51
+ * share of traffic while observed traffic (`status.traffic`) stays on
52
+ * `servingRevision`. Returns that target, or null when the pin agrees.
53
+ * Entries carrying no traffic (tags at 0%) are ignored.
54
+ *
55
+ * It arises when `update-traffic` fails: Cloud Run keeps the new pin in
56
+ * the spec although the old revision goes on serving, the service reports
57
+ * not ready, and every later `services update` fails on the dead revision
58
+ * (notes, 2026-11-20: a pin to notes-00156-dkv, whose container exited at
59
+ * startup, failed the next deploy's update of a healthy revision). */
60
+ export declare function strayTrafficPin(described: unknown, servingRevision: string): string | null;
48
61
  /**
49
62
  * Extract serving state from a `gcloud run services describe --format=json`.
50
63
  *
@@ -113,6 +113,30 @@ export function servingRevisionName(service, described) {
113
113
  }
114
114
  return active[0].revisionName;
115
115
  }
116
+ /** A traffic pin that routes somewhere other than the revision actually
117
+ * serving, in a `gcloud run services describe --format=json`: the desired
118
+ * state (`spec.traffic`) names another revision (or the latest one) for a
119
+ * share of traffic while observed traffic (`status.traffic`) stays on
120
+ * `servingRevision`. Returns that target, or null when the pin agrees.
121
+ * Entries carrying no traffic (tags at 0%) are ignored.
122
+ *
123
+ * It arises when `update-traffic` fails: Cloud Run keeps the new pin in
124
+ * the spec although the old revision goes on serving, the service reports
125
+ * not ready, and every later `services update` fails on the dead revision
126
+ * (notes, 2026-11-20: a pin to notes-00156-dkv, whose container exited at
127
+ * startup, failed the next deploy's update of a healthy revision). */
128
+ export function strayTrafficPin(described, servingRevision) {
129
+ const spec = described.spec?.traffic ?? [];
130
+ for (const target of spec) {
131
+ if ((target.percent ?? 0) <= 0)
132
+ continue;
133
+ if (target.latestRevision)
134
+ return 'the latest revision';
135
+ if (target.revisionName && target.revisionName !== servingRevision)
136
+ return target.revisionName;
137
+ }
138
+ return null;
139
+ }
116
140
  /**
117
141
  * Extract serving state from a `gcloud run services describe --format=json`.
118
142
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.68.0",
3
+ "version": "3.69.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",