@ultimat3/cli 31.28.0 → 31.29.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/CLAUDE.md CHANGED
@@ -135,6 +135,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
135
135
  | `runtime-bindings.ts` | which service each binding points at (embedded or external); events follow `NATS_URL` |
136
136
  | `runtime-queue.ts` / `runtime-services.ts` / `runtime-bus.ts` | db + queue; every other accessor; the bus |
137
137
  | `framework-schema-apply.ts` / `framework-schema-stamp.ts` | the framework tables, applied in one locked transaction † |
138
+ | `framework-schema-verify.ts` / `-wait.ts` / `app-migrations-verdict.ts` / `serve-boot-probe.ts` | a serving role behind its schema (stamp or app ledger) WAITS, `ULTIMATE_SCHEMA_WAIT_MS`, probe port up; a newer major refuses at once |
138
139
  | `runtime-isr.ts` | the ISR controller both boots serve through, attached to `invalidateTags` (`attachedIsr`) † |
139
140
  | `runtime-mfa-warning.ts` / `runtime-idempotency-scope.ts` | boot warnings: unsealed MFA secrets, a per-process idempotency store † |
140
141
  | `app-config-load.ts` | the ONE reader of `app.config.ts` (`loadAppConfig`) † |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.28.0",
3
+ "version": "31.29.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.9",
56
- "@ultimat3/action": "31.28.0",
57
- "@ultimat3/admin": "31.28.0",
58
- "@ultimat3/ai": "31.28.0",
59
- "@ultimat3/auth": "31.28.0",
60
- "@ultimat3/cache": "31.28.0",
61
- "@ultimat3/core": "31.28.0",
62
- "@ultimat3/db": "31.28.0",
63
- "@ultimat3/entity": "31.28.0",
64
- "@ultimat3/flags": "31.28.0",
65
- "@ultimat3/http": "31.28.0",
66
- "@ultimat3/i18n": "31.28.0",
67
- "@ultimat3/jobs": "31.28.0",
68
- "@ultimat3/mail": "31.28.0",
69
- "@ultimat3/manifest": "31.28.0",
70
- "@ultimat3/mcp": "31.28.0",
71
- "@ultimat3/money": "31.28.0",
72
- "@ultimat3/notify": "31.28.0",
73
- "@ultimat3/policy": "31.28.0",
74
- "@ultimat3/pwa": "31.28.0",
75
- "@ultimat3/query": "31.28.0",
76
- "@ultimat3/realtime": "31.28.0",
77
- "@ultimat3/render": "31.28.0",
78
- "@ultimat3/schema": "31.28.0",
79
- "@ultimat3/scraping": "31.28.0",
80
- "@ultimat3/seo": "31.28.0",
81
- "@ultimat3/storage": "31.28.0",
82
- "@ultimat3/testing": "31.28.0",
83
- "@ultimat3/time": "31.28.0",
56
+ "@ultimat3/action": "31.29.0",
57
+ "@ultimat3/admin": "31.29.0",
58
+ "@ultimat3/ai": "31.29.0",
59
+ "@ultimat3/auth": "31.29.0",
60
+ "@ultimat3/cache": "31.29.0",
61
+ "@ultimat3/core": "31.29.0",
62
+ "@ultimat3/db": "31.29.0",
63
+ "@ultimat3/entity": "31.29.0",
64
+ "@ultimat3/flags": "31.29.0",
65
+ "@ultimat3/http": "31.29.0",
66
+ "@ultimat3/i18n": "31.29.0",
67
+ "@ultimat3/jobs": "31.29.0",
68
+ "@ultimat3/mail": "31.29.0",
69
+ "@ultimat3/manifest": "31.29.0",
70
+ "@ultimat3/mcp": "31.29.0",
71
+ "@ultimat3/money": "31.29.0",
72
+ "@ultimat3/notify": "31.29.0",
73
+ "@ultimat3/policy": "31.29.0",
74
+ "@ultimat3/pwa": "31.29.0",
75
+ "@ultimat3/query": "31.29.0",
76
+ "@ultimat3/realtime": "31.29.0",
77
+ "@ultimat3/render": "31.29.0",
78
+ "@ultimat3/schema": "31.29.0",
79
+ "@ultimat3/scraping": "31.29.0",
80
+ "@ultimat3/seo": "31.29.0",
81
+ "@ultimat3/storage": "31.29.0",
82
+ "@ultimat3/testing": "31.29.0",
83
+ "@ultimat3/time": "31.29.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -0,0 +1,84 @@
1
+ // The app's own migrations, as a serving role judges them at boot: which ones this build ships that
2
+ // the `x_migrations` ledger lacks (behind: wait for the migrate step), and which ones the ledger
3
+ // holds that this build does not know (ahead: a rollback, served with one warning). Pure; the read
4
+ // is `framework-schema-apply.ts`'s, one statement beside the framework stamp.
5
+
6
+ import { logger, UltimateError } from '@ultimat3/core';
7
+ import { LEDGER_TABLE } from '@ultimat3/db';
8
+
9
+ export interface AppMigrationsVerdict {
10
+ /** Shipped by this build, absent from the ledger — every one when the ledger does not exist. */
11
+ readonly missing: readonly string[];
12
+ /** In the ledger, unknown to this build: a newer release migrated, and this one rolled back. */
13
+ readonly unknown: readonly string[];
14
+ }
15
+
16
+ /** `applied` is `undefined` when the ledger table does not exist: no migrate step has run at all. */
17
+ export function appMigrationsVerdict(
18
+ shipped: readonly string[],
19
+ applied: readonly string[] | undefined,
20
+ ): AppMigrationsVerdict {
21
+ const ledger = new Set(applied ?? []);
22
+ const known = new Set(shipped);
23
+ return {
24
+ missing: shipped.filter((id) => !ledger.has(id)),
25
+ unknown: (applied ?? []).filter((id) => !known.has(id)),
26
+ };
27
+ }
28
+
29
+ /** The ledger's ids as the boot read returns them — a JSON array — and nothing it is not. */
30
+ export function parseAppliedIds(value: unknown): readonly string[] {
31
+ if (typeof value !== 'string') return [];
32
+ const parsed: unknown = JSON.parse(value);
33
+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
34
+ }
35
+
36
+ /** At most this many ids in a line: the count says the rest, and a log line is not a listing. */
37
+ const NAMED = 5;
38
+
39
+ const named = (ids: readonly string[]): string =>
40
+ ids.length <= NAMED
41
+ ? ids.join(', ')
42
+ : `${ids.slice(0, NAMED).join(', ')} and ${String(ids.length - NAMED)} more`;
43
+
44
+ /** A serving role over a database the migrate step has not yet brought to this build's migrations. */
45
+ export class AppMigrationsUnappliedError extends UltimateError {
46
+ constructor(input: {
47
+ readonly missing: readonly string[];
48
+ /** `false` when `x_migrations` does not exist: no migrate step ever ran against this database. */
49
+ readonly ledger: boolean;
50
+ readonly waitedMs?: number;
51
+ }) {
52
+ const waited =
53
+ input.waitedMs === undefined
54
+ ? ''
55
+ : `. This role waited ${String(Math.round(input.waitedMs))}ms (ULTIMATE_SCHEMA_WAIT_MS) for them`;
56
+ super({
57
+ code: 'X_APP_MIGRATIONS_UNAPPLIED',
58
+ cause: `this build ships ${String(input.missing.length)} migration(s) the database has not applied — ${named(input.missing)}${
59
+ input.ledger ? '' : ` (${LEDGER_TABLE} does not exist: no ROLE=migrate has run here)`
60
+ }. Serving would fail on the first statement naming a column they add: the migrate step must run first${waited}`,
61
+ fix: 'x db migrate',
62
+ meta: {
63
+ missing: [...input.missing],
64
+ ledger: input.ledger,
65
+ ...(input.waitedMs === undefined ? {} : { waitedMs: Math.round(input.waitedMs) }),
66
+ },
67
+ });
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Served, said once. A ledger ahead of the build is a rollback — or the old pods of a rollout the
73
+ * migrate step already ran for — and the rolling rail (`X_MIGRATION_ROLLING_UNSAFE`) is what makes
74
+ * that schema one the previous release can run on. Refusing it would crash-loop every old pod of
75
+ * every deploy; serving it silently would hide a rollback nobody finished.
76
+ */
77
+ export function reportAppMigrationsAhead(unknown: readonly string[]): void {
78
+ if (unknown.length === 0) return;
79
+ logger.warn('ultimate app migrations ahead', {
80
+ migrations: unknown.length,
81
+ cause: `the database holds ${String(unknown.length)} migration(s) this build does not ship — ${named(unknown)}: a newer release migrated and this one is mid-rollout or rolled back`,
82
+ fix: 'x db migrate --json',
83
+ });
84
+ }
package/src/cmd-drill.ts CHANGED
@@ -1,10 +1,10 @@
1
- // `x drill [<name>] [--list] [--budget-ms n]` — the app's web and worker roles as real processes on
2
- // real services, each fault in `@ultimat3/testing`'s drill table played through a proxy or a
3
- // signal, red on any framework contract that does not hold. CLI wiring only: the table, the fleet
1
+ // `x drill [<name>] [--list] [--budget-ms n]` — the app's roles as real processes on real services,
2
+ // each fault in `@ultimat3/testing`'s drill table played through a proxy, a signal or the rollout
3
+ // order, red on any framework contract that does not hold. CLI wiring only: the table, the fleet
4
4
  // and the verdict are testing's. Not a gate step: it needs Postgres, and `x verify` needs nothing.
5
5
 
6
6
  import type { AppConfig } from '@ultimat3/core';
7
- import { DRAIN_DEADLINE_DEFAULT_MS, MAX_TIMER_MS } from '@ultimat3/core';
7
+ import { DRAIN_DEADLINE_DEFAULT_MS, frameworkVersion, MAX_TIMER_MS } from '@ultimat3/core';
8
8
  import type {
9
9
  Drill,
10
10
  DrillConfig,
@@ -23,12 +23,14 @@ import {
23
23
  drillRoles,
24
24
  drillServices,
25
25
  runDrill,
26
+ runRollout,
26
27
  startDrillFleet,
27
28
  } from '@ultimat3/testing';
28
29
  import { loadAppConfig } from './app-config-load';
29
30
  import { requireAppRoot } from './app-root';
30
31
  import { drillSpec } from './cmd-drill-spec';
31
32
  import type { CliCommand, CommandContext } from './command';
33
+ import { behindStampSql } from './drill-schema-behind';
32
34
  import { drillSyncLane } from './drill-sync-lane';
33
35
  import { drillTargets } from './drill-targets';
34
36
  import { UnknownCommandError } from './errors';
@@ -74,12 +76,15 @@ const drillConfigOf = (config: AppConfig | undefined): DrillConfig =>
74
76
  readiness: config.health.readiness,
75
77
  };
76
78
 
79
+ const faultJson = (fault: Drill['fault']): JsonValue => {
80
+ if (fault.kind === 'service') return { service: fault.service };
81
+ if (fault.kind === 'signal') return { role: fault.role, signal: fault.signal };
82
+ return { order: 'roles-before-migrate', waitCode: fault.waitCode };
83
+ };
84
+
77
85
  const listing = (drill: Drill): JsonValue => ({
78
86
  name: drill.name,
79
- fault:
80
- drill.fault.kind === 'service'
81
- ? { service: drill.fault.service }
82
- : { role: drill.fault.role, signal: drill.fault.signal },
87
+ fault: faultJson(drill.fault),
83
88
  holds: [...drill.holds],
84
89
  });
85
90
 
@@ -174,15 +179,24 @@ export const drillCommand: CliCommand = {
174
179
  const { targets, skipped } = await drillTargets(root);
175
180
  const reports: DrillReport[] = [];
176
181
  for (const { drill, services } of planned) {
182
+ const { fault } = drill;
183
+ // The rollout order: the stamp is this package's to write, so the rewind is handed in.
184
+ const order =
185
+ fault.kind === 'order'
186
+ ? { rewind: behindStampSql(frameworkVersion()), watch: fault.waitCode }
187
+ : undefined;
177
188
  const fleet = await startDrillFleet({
178
189
  root,
179
190
  services,
180
191
  roles: drillRoles(drill),
181
192
  readyTimeoutMs: READY_TIMEOUT_MS,
193
+ beforeMigrate: order,
182
194
  });
183
195
  reports.push(
184
196
  await withDrillFleet(fleet, bunDrillSql, (sql) =>
185
- runDrill({ drill, fleet, budgets, targets, sql, sync: drillSyncLane(fleet) }),
197
+ order === undefined
198
+ ? runDrill({ drill, fleet, budgets, targets, sql, sync: drillSyncLane(fleet) })
199
+ : runRollout({ drill, fleet, budgets, readyTimeoutMs: READY_TIMEOUT_MS }),
186
200
  ),
187
201
  );
188
202
  }
@@ -0,0 +1,85 @@
1
+ // 31.29.0: the chart's alerts gain the deploy-contract rules (latency, the Postgres server, the
2
+ // framework schema, volumes) and its dashboard their panels. Each file, still exactly as 31.18.0
3
+ // through 31.28.x wrote it (recognised by hash), is replaced whole; one the app edited is reported.
4
+
5
+ import { CHART_FILE } from '../generate-chart-alerts';
6
+ import { DASHBOARD_FILE, dashboardJson } from '../templates/chart-dashboard';
7
+ import { names } from '../templates/naming';
8
+ import { helmMonitoringFiles } from '../templates/scaffold-helm-alerts';
9
+ import { chartName } from './chart-dashboard';
10
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
11
+ import { unifiedDiff } from './engine-diff';
12
+ import { mergeResults, readText } from './engine-edits';
13
+
14
+ export const RULES_FILE = 'docker/helm/templates/alert-rules.yaml';
15
+
16
+ /** SHA-256 of `alert-rules.yaml` as 31.18.0–31.28.x wrote it, its chart name spelled `<APP>`. */
17
+ export const RULES_31_18_SHA256 =
18
+ 'ae896fa5eea1c56d93f6c498fbf3dc026318be9feabcf0dbcbad2bc850c3d348';
19
+
20
+ /** SHA-256 of `dashboards/ultimate-app.json` as 31.18.0–31.28.x wrote it (it names no chart). */
21
+ export const DASHBOARD_31_18_SHA256 =
22
+ 'db34c29579f532cb5dac35de3f3e63141cf64e30643917b74e0eb9ecbd081f38';
23
+
24
+ const sha256 = (text: string): string => new Bun.CryptoHasher('sha256').update(text).digest('hex');
25
+
26
+ /** The chart's name in its helpers, spelled `<APP>`: one hash recognises every app's copy. */
27
+ export const unnamed = (text: string, chart: string): string =>
28
+ text.replaceAll(`include "${chart}.`, 'include "<APP>.');
29
+
30
+ /**
31
+ * Today's bytes over the stock ones; a file already today's, or absent, is left alone. Anything else
32
+ * is the app's, reported with what writing today's would change.
33
+ */
34
+ async function replaceStock(
35
+ app: CodemodApp,
36
+ path: string,
37
+ stock: (text: string) => boolean,
38
+ today: string,
39
+ what: string,
40
+ ): Promise<CodemodResult> {
41
+ const file = await readText(app, path);
42
+ if (file === undefined || file.text === today) return { changed: [], skipped: [] };
43
+ if (stock(file.text)) {
44
+ await app.write(path, file.restore(today));
45
+ return { changed: [path], skipped: [] };
46
+ }
47
+ return {
48
+ changed: [],
49
+ skipped: [
50
+ {
51
+ path,
52
+ reason: `the chart's ${what} is the app's own, so the deploy-contract additions were not written: the diff is today's file against yours, to merge by hand`,
53
+ diff: unifiedDiff(path, file.text, today),
54
+ },
55
+ ],
56
+ };
57
+ }
58
+
59
+ export const codemod: Codemod = {
60
+ id: 'helm-alerts-deploy',
61
+ since: '31.29.0',
62
+ summary: `${RULES_FILE} gains the latency, Postgres, framework-schema and volume rules, and ${DASHBOARD_FILE} their panels`,
63
+ async run(app) {
64
+ const chart = chartName((await readText(app, CHART_FILE))?.text ?? '');
65
+ if (chart === undefined) return { changed: [], skipped: [] };
66
+ const rules = helmMonitoringFiles(names(chart)).find((one) => one.path === RULES_FILE);
67
+ if (typeof rules?.contents !== 'string') return { changed: [], skipped: [] };
68
+ return mergeResults([
69
+ await replaceStock(
70
+ app,
71
+ RULES_FILE,
72
+ (text) => sha256(unnamed(text, chart)) === RULES_31_18_SHA256,
73
+ rules.contents,
74
+ 'alert rules',
75
+ ),
76
+ await replaceStock(
77
+ app,
78
+ DASHBOARD_FILE,
79
+ (text) => sha256(text) === DASHBOARD_31_18_SHA256,
80
+ dashboardJson(),
81
+ 'dashboard',
82
+ ),
83
+ ]);
84
+ },
85
+ };
@@ -16,8 +16,10 @@ import { codemod as docsIslandRows } from './docs-island-rows';
16
16
  import { codemod as docsShippedGuards } from './docs-shipped-guards';
17
17
  import { codemod as docsTestServices } from './docs-test-services';
18
18
  import { codemod as formatEditedHook } from './format-edited-hook';
19
+ import { codemod as helmAlertsDeploy } from './helm-alerts-deploy';
19
20
  import { codemod as helmAlertsObjective } from './helm-alerts-objective';
20
21
  import { codemod as metricsProbeHealthz } from './metrics-probe-healthz';
22
+ import { codemod as migrateJobOrdered } from './migrate-job-ordered';
21
23
  import { codemod as reproGitignore } from './repro-gitignore';
22
24
  import { codemod as runtimePin } from './runtime-pin';
23
25
  import { codemod as solidFloor } from './solid-floor';
@@ -53,4 +55,6 @@ export const CODEMODS: readonly Codemod[] = [
53
55
  solidFloor,
54
56
  vendoredGuards,
55
57
  verifyFloorSteps,
58
+ helmAlertsDeploy,
59
+ migrateJobOrdered,
56
60
  ];
@@ -0,0 +1,81 @@
1
+ // 31.29.0: the chart's migrate Job orders every rollout under any applier — a Helm hook, an Argo CD
2
+ // Sync hook in wave -1 (no longer the PreSync Argo mapped the Helm hook to), and named by its image
3
+ // so an applier that ignores hooks gets a new Job per image. The Job, still exactly the old
4
+ // template, is replaced whole; `docker/README.md`'s two rows move where they stand.
5
+
6
+ import { CHART_FILE } from '../generate-chart-alerts';
7
+ import { names } from '../templates/naming';
8
+ import { helmMigrateFile, MIGRATE_JOB_PATH } from '../templates/scaffold-helm-migrate';
9
+ import { chartName } from './chart-dashboard';
10
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
11
+ import { unifiedDiff } from './engine-diff';
12
+ import type { SnippetEdit } from './engine-edits';
13
+ import { editSnippets, mergeResults, readText } from './engine-edits';
14
+ import { MIGRATE_JOB_31_28_LINES } from './migrate-job-stock';
15
+
16
+ const README = 'docker/README.md';
17
+ const VALUES = 'docker/helm/values.yaml';
18
+
19
+ /** The TTL's own line; absent, the template collects after the same day, so it is optional. */
20
+ export const MIGRATE_VALUES_EDITS: readonly SnippetEdit[] = [
21
+ {
22
+ from: 'migrate:\n enabled: true\n backoffLimit: 1\n',
23
+ to: 'migrate:\n enabled: true\n backoffLimit: 1\n ttlSecondsAfterFinished: 86400 # a finished Job, and its logs, are collected after a day\n',
24
+ optional: true,
25
+ },
26
+ ];
27
+
28
+ /** What no file shows: the cluster still holds the Job the old fixed name made. */
29
+ const ORPHAN =
30
+ 'a cluster deployed from the old chart keeps its fixed-name Job: kubectl delete job <release>-migrate, once';
31
+
32
+ export const MIGRATE_README_EDITS: readonly SnippetEdit[] = [
33
+ {
34
+ from: '| Kubernetes | an `initContainer` or a `Job` on the same image with `ROLE=migrate` |',
35
+ to: "| Kubernetes | the chart's one `migrate` Job on the same image (`docker/helm`), ordered before every role — never a per-pod `initContainer` |",
36
+ optional: true,
37
+ },
38
+ {
39
+ from: '| Job | release | `ROLE=migrate`, a `pre-install,pre-upgrade` hook — it runs to completion first |',
40
+ to: '| Job | release | `ROLE=migrate`, run to completion first: a `pre-install,pre-upgrade,pre-rollback` hook, an Argo CD `Sync` hook in wave -1, and named by its image so any other applier gets a new Job per image |',
41
+ optional: true,
42
+ },
43
+ ];
44
+
45
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
46
+
47
+ /** Today's Job when the app's is still the old template exactly; an edited one is reported. */
48
+ async function job(app: CodemodApp, chart: string): Promise<CodemodResult> {
49
+ const file = await readText(app, MIGRATE_JOB_PATH);
50
+ const next = String(helmMigrateFile(names(chart)).contents);
51
+ if (file === undefined || file.text === next) return NOTHING;
52
+ const stock = `${MIGRATE_JOB_31_28_LINES.map((line) => line.replaceAll('<APP>', chart)).join('\n')}\n`;
53
+ if (file.text === stock) {
54
+ await app.write(MIGRATE_JOB_PATH, file.restore(next));
55
+ return { changed: [MIGRATE_JOB_PATH], skipped: [] };
56
+ }
57
+ return {
58
+ changed: [],
59
+ skipped: [
60
+ {
61
+ path: MIGRATE_JOB_PATH,
62
+ reason: `the app's migrate Job is its own, so the ordering annotations, the image-derived name and the TTL were not written: the diff is the template's change, to make by hand; ${ORPHAN}`,
63
+ diff: unifiedDiff(MIGRATE_JOB_PATH, stock, next),
64
+ },
65
+ ],
66
+ };
67
+ }
68
+
69
+ export const codemod: Codemod = {
70
+ id: 'migrate-job-ordered',
71
+ since: '31.29.0',
72
+ summary: `${MIGRATE_JOB_PATH} orders every rollout under helm, Argo CD and a hook-blind applier alike, and is collected a day after it finishes; ${ORPHAN}`,
73
+ async run(app) {
74
+ const chart = chartName((await readText(app, CHART_FILE))?.text ?? '');
75
+ return mergeResults([
76
+ chart === undefined ? NOTHING : await job(app, chart),
77
+ await editSnippets(app, README, MIGRATE_README_EDITS),
78
+ await editSnippets(app, VALUES, MIGRATE_VALUES_EDITS),
79
+ ]);
80
+ },
81
+ };
@@ -0,0 +1,41 @@
1
+ // `docker/helm/templates/migrate-job.yaml` as `x new` wrote it through 31.28.x — a Helm hook alone,
2
+ // under one fixed name — kept byte for byte (the chart's name as `<APP>`), so a template still
3
+ // exactly that is recognised and replaced whole, and an edited one is not.
4
+
5
+ // biome-ignore-all lint/suspicious/noTemplateCurlyInString: Helm's own {{ … }}, never a JS template
6
+
7
+ export const MIGRATE_JOB_31_28_LINES: readonly string[] = [
8
+ '{{/*',
9
+ 'The release phase, as a pre-install / pre-upgrade hook: ROLE=migrate applies every pending',
10
+ 'migration under an advisory lock and exits, before any serving role starts. Same image, same entry',
11
+ 'point — there is no second migration engine and no toolchain in the container.',
12
+ '*/}}',
13
+ '{{- if .Values.migrate.enabled }}',
14
+ 'apiVersion: batch/v1',
15
+ 'kind: Job',
16
+ 'metadata:',
17
+ ' name: {{ include "<APP>.fullname" . }}-migrate',
18
+ ' labels:',
19
+ ' {{- include "<APP>.labels" . | nindent 4 }}',
20
+ ' app.kubernetes.io/component: migrate',
21
+ ' annotations:',
22
+ ' helm.sh/hook: pre-install,pre-upgrade',
23
+ ' helm.sh/hook-weight: "-5"',
24
+ ' helm.sh/hook-delete-policy: before-hook-creation',
25
+ 'spec:',
26
+ ' backoffLimit: {{ .Values.migrate.backoffLimit }}',
27
+ ' template:',
28
+ ' metadata:',
29
+ ' labels:',
30
+ ' {{- include "<APP>.labels" . | nindent 8 }}',
31
+ ' app.kubernetes.io/component: migrate',
32
+ ' spec:',
33
+ ' restartPolicy: Never',
34
+ ' automountServiceAccountToken: false',
35
+ ' securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }}',
36
+ ' containers:',
37
+ ' {{- include "<APP>.container" (dict "role" "migrate" "cfg" .Values.migrate "root" .) | nindent 8 }}',
38
+ ' volumes:',
39
+ ' {{- include "<APP>.tmpVolume" . | nindent 8 }}',
40
+ '{{- end }}',
41
+ ];
@@ -0,0 +1,26 @@
1
+ // The statement `x drill roll-before-migrate` hands its fleet: the framework schema stamp rewound
2
+ // to name one older build only, so every serving role this build starts meets a schema behind it.
3
+ // Here and not in `@ultimat3/testing`: the stamp is this package's (`framework-schema-stamp.ts`).
4
+
5
+ import { literal } from '@ultimat3/db';
6
+ import { nextStamp, STAMP_RELATION } from './framework-schema-stamp';
7
+
8
+ /** No build's DDL hashes to this, so the stamp names a build this one is not. */
9
+ const OLDER_SCHEMA = '0000000000000000';
10
+
11
+ /** A version before `version`: the previous minor, else the previous patch, else the last major. */
12
+ export function olderVersion(version: string): string {
13
+ const [major = 0, minor = 0, patch = 0] = version
14
+ .split(/[.+-]/)
15
+ .slice(0, 3)
16
+ .map((part) => Number.parseInt(part, 10) || 0);
17
+ if (minor > 0) return `${String(major)}.${String(minor - 1)}.0`;
18
+ if (patch > 0) return `${String(major)}.0.${String(patch - 1)}`;
19
+ return `${String(Math.max(major - 1, 0))}.0.0`;
20
+ }
21
+
22
+ /** The statement that leaves the stamp naming only a build older than `version`. */
23
+ export const behindStampSql = (version: string): string =>
24
+ `comment on table ${STAMP_RELATION} is ${
25
+ literal(nextStamp(null, { version: olderVersion(version), schema: OLDER_SCHEMA })).text
26
+ }`;
@@ -240,6 +240,7 @@ export const CLI_OWNED_ERROR_CODES = [
240
240
  'X_GUARD_BUILT_IN',
241
241
  'X_REPRO_BUNDLE_INVALID',
242
242
  'X_UPGRADE_LOCKED',
243
+ 'X_APP_MIGRATIONS_UNAPPLIED',
243
244
  ] as const;
244
245
 
245
246
  /**
@@ -468,6 +469,8 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
468
469
  X_GUARD_BUILT_IN: 'x g guard named a shipped guard',
469
470
  X_REPRO_BUNDLE_INVALID: 'the file is not a repro bundle this version can open',
470
471
  X_UPGRADE_LOCKED: 'another x upgrade holds this app',
472
+ X_APP_MIGRATIONS_UNAPPLIED:
473
+ 'a serving role booted over a database missing migrations this build ships',
471
474
  };
472
475
 
473
476
  // One unconditional call, so a second package claiming one of the CLI's codes throws
@@ -1,8 +1,8 @@
1
1
  // The three ways a boot meets the framework schema (plan 101, s1-con #5): `applyLockedSchema` runs
2
2
  // the DDL in ONE transaction behind the migration advisory lock with a bounded `lock_timeout`, then
3
- // stamps the build; `verifySchema` runs no DDL and refuses a database this build was never applied
4
- // to; `ensureSchema` reads the stamp and applies only when this build is absent from it. Which boot
5
- // takes which is `runtime-queue.ts`'s `SchemaMode`.
3
+ // stamps the build; `verifySchema` (`framework-schema-verify.ts`) runs none; `ensureSchema` reads
4
+ // the stamp and applies only when this build is absent from it. Which boot takes which is
5
+ // `runtime-queue.ts`'s `SchemaMode`.
6
6
 
7
7
  import { frameworkVersion, logger } from '@ultimat3/core';
8
8
  import type { DbClient } from '@ultimat3/db';
@@ -16,7 +16,6 @@ import {
16
16
  } from '@ultimat3/db';
17
17
  import { applyFrameworkSchema } from './framework-schema';
18
18
  import {
19
- FrameworkSchemaUnappliedError,
20
19
  frameworkSchemaHash,
21
20
  nextStamp,
22
21
  parseStamp,
@@ -25,13 +24,14 @@ import {
25
24
  stampVerdict,
26
25
  } from './framework-schema-stamp';
27
26
 
28
- const thisBuild = (): StampEntry => ({
27
+ /** This process's build, as the stamp records one. */
28
+ export const thisBuild = (): StampEntry => ({
29
29
  version: frameworkVersion(),
30
30
  schema: frameworkSchemaHash(),
31
31
  });
32
32
 
33
33
  /** The stamp as the catalog holds it; `null` when the relation or its comment is absent. */
34
- async function readStamp(client: DbClient): Promise<string | null> {
34
+ export async function readStamp(client: DbClient): Promise<string | null> {
35
35
  const rows = await client.query<{ readonly stamp: string | null }>(
36
36
  raw(`select obj_description(to_regclass('${STAMP_RELATION}'), 'pg_class') as stamp`),
37
37
  );
@@ -62,18 +62,6 @@ export async function applyLockedSchema(client: DbClient): Promise<void> {
62
62
  );
63
63
  }
64
64
 
65
- /**
66
- * One catalog read. A build absent from the stamp is refused with the command that applies it; a
67
- * fleet straddling a major is reported once and served — refusing it would crash-loop the old pods
68
- * of every rolling deploy across a breaking release.
69
- */
70
- export async function verifySchema(client: DbClient): Promise<void> {
71
- const mine = thisBuild();
72
- const verdict = stampVerdict(parseStamp(await readStamp(client)), mine);
73
- if (!verdict.applied) throw new FrameworkSchemaUnappliedError({ mine, newest: verdict.newest });
74
- reportSkew(mine, verdict.skew);
75
- }
76
-
77
65
  /**
78
66
  * A CLI command's boot — `x db backfill`, `x jobs`, `x auth`: no DDL when this build's stamp is
79
67
  * already there, the locked apply when it is not.
@@ -100,7 +88,7 @@ export async function ensureSchema(client: DbClient): Promise<void> {
100
88
  * A fleet straddling a major is reported once and served — refusing it would crash-loop the old
101
89
  * pods of every rolling deploy across a breaking release.
102
90
  */
103
- function reportSkew(mine: StampEntry, skew: StampEntry | undefined): void {
91
+ export function reportSkew(mine: StampEntry, skew: StampEntry | undefined): void {
104
92
  if (skew === undefined) return;
105
93
  logger.warn('ultimate framework major skew', {
106
94
  cause: `this process runs ${mine.version} and the database's framework schema was last applied by ${skew.version}: a fleet across a major boundary is mid-rollout or half rolled back`,
@@ -54,6 +54,22 @@ export function nextStamp(previous: string | null | undefined, mine: StampEntry)
54
54
 
55
55
  const majorOf = (version: string): string => version.split('.')[0] ?? version;
56
56
 
57
+ /**
58
+ * A newest build whose major is numerically above this one's: a database a later breaking release
59
+ * migrated. A serving role of the older build does not wait on it — no migrate of this build is
60
+ * coming in that rollout — and is refused at once.
61
+ */
62
+ export function aheadByMajor(newest: StampEntry | undefined, mine: StampEntry): boolean {
63
+ if (newest === undefined) return false;
64
+ const theirs = Number(majorOf(newest.version));
65
+ const ours = Number(majorOf(mine.version));
66
+ return Number.isFinite(theirs) && Number.isFinite(ours) && theirs > ours;
67
+ }
68
+
69
+ /** Whether `newest` is another major than this build, in either direction — the skew gauge's fact. */
70
+ export const otherMajor = (newest: StampEntry | undefined, mine: StampEntry): boolean =>
71
+ newest !== undefined && majorOf(newest.version) !== majorOf(mine.version);
72
+
57
73
  export type StampVerdict =
58
74
  | { readonly applied: true; readonly skew?: StampEntry }
59
75
  | { readonly applied: false; readonly newest?: StampEntry };
@@ -68,14 +84,27 @@ export function stampVerdict(entries: readonly StampEntry[], mine: StampEntry):
68
84
  if (!entries.some((entry) => entry.schema === mine.schema)) {
69
85
  return newest === undefined ? { applied: false } : { applied: false, newest };
70
86
  }
71
- return newest !== undefined && majorOf(newest.version) !== majorOf(mine.version)
87
+ return newest !== undefined && otherMajor(newest, mine)
72
88
  ? { applied: true, skew: newest }
73
89
  : { applied: true };
74
90
  }
75
91
 
92
+ /** The variable that bounds a serving role's wait for the migrate step (`framework-schema-wait.ts`). */
93
+ export const SCHEMA_WAIT_ENV = 'ULTIMATE_SCHEMA_WAIT_MS';
94
+
76
95
  /** A serving role over a database its build's framework tables were never applied to. */
77
96
  export class FrameworkSchemaUnappliedError extends UltimateError {
78
- constructor(input: { readonly mine: StampEntry; readonly newest: StampEntry | undefined }) {
97
+ constructor(input: {
98
+ readonly mine: StampEntry;
99
+ readonly newest: StampEntry | undefined;
100
+ /** How long the role waited for the migrate step before this refusal; absent when it did not. */
101
+ readonly waitedMs?: number;
102
+ }) {
103
+ const ahead = aheadByMajor(input.newest, input.mine);
104
+ const waited =
105
+ input.waitedMs === undefined
106
+ ? ''
107
+ : `. This role waited ${String(Math.round(input.waitedMs))}ms (${SCHEMA_WAIT_ENV}) for it`;
79
108
  super({
80
109
  code: 'X_FRAMEWORK_SCHEMA_UNAPPLIED',
81
110
  cause:
@@ -84,12 +113,18 @@ export class FrameworkSchemaUnappliedError extends UltimateError {
84
113
  input.newest === undefined
85
114
  ? `${STAMP_RELATION} carries no stamp, so no ROLE=migrate of this release ran`
86
115
  : `the newest applied build is ${input.newest.version} (${input.newest.schema})`
87
- }. A serving role verifies and never runs DDL: the migrate step must run first`,
116
+ }${
117
+ ahead
118
+ ? ', a newer major: this role refuses without waiting, since no migrate of this build is coming'
119
+ : ''
120
+ }. A serving role verifies and never runs DDL: the migrate step must run first${waited}`,
88
121
  fix: 'x db migrate',
89
122
  meta: {
90
123
  version: input.mine.version,
91
124
  schema: input.mine.schema,
92
125
  ...(input.newest === undefined ? {} : { newest: { ...input.newest } }),
126
+ ...(ahead ? { aheadByMajor: true } : {}),
127
+ ...(input.waitedMs === undefined ? {} : { waitedMs: Math.round(input.waitedMs) }),
93
128
  },
94
129
  });
95
130
  }