@ultimat3/cli 31.28.0 → 31.30.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.
Files changed (43) hide show
  1. package/CLAUDE.md +1 -0
  2. package/package.json +29 -29
  3. package/src/app-migrations-verdict.ts +85 -0
  4. package/src/cmd-db-recount.ts +38 -43
  5. package/src/cmd-db-spec.ts +3 -2
  6. package/src/cmd-db-status.ts +80 -0
  7. package/src/cmd-db.ts +4 -2
  8. package/src/cmd-drill.ts +23 -9
  9. package/src/codemods/helm-alerts-deploy.ts +85 -0
  10. package/src/codemods/index.ts +4 -0
  11. package/src/codemods/migrate-job-ordered.ts +81 -0
  12. package/src/codemods/migrate-job-stock.ts +41 -0
  13. package/src/db-client-displace.ts +65 -0
  14. package/src/db-diagnostics.ts +25 -28
  15. package/src/db-status.ts +185 -0
  16. package/src/drill-schema-behind.ts +26 -0
  17. package/src/error-codes.ts +3 -0
  18. package/src/framework-schema-apply.ts +7 -19
  19. package/src/framework-schema-stamp.ts +38 -3
  20. package/src/framework-schema-verify.ts +120 -0
  21. package/src/framework-schema-wait.ts +125 -0
  22. package/src/mcp-errors.ts +4 -3
  23. package/src/messages-db.ts +12 -0
  24. package/src/role-pg-stats.ts +21 -0
  25. package/src/role-start.ts +4 -0
  26. package/src/runtime-queue.ts +47 -8
  27. package/src/serve-boot-probe.ts +97 -0
  28. package/src/serve-boot.ts +26 -1
  29. package/src/serve-retire.ts +16 -3
  30. package/src/templates/chart-dashboard-panels.ts +178 -0
  31. package/src/templates/chart-dashboard.ts +9 -135
  32. package/src/templates/scaffold-container.ts +2 -2
  33. package/src/templates/scaffold-helm-alert-deploy.ts +105 -0
  34. package/src/templates/scaffold-helm-alert-rules.ts +7 -1
  35. package/src/templates/scaffold-helm-alerts.ts +3 -0
  36. package/src/templates/scaffold-helm-migrate.ts +85 -0
  37. package/src/templates/scaffold-helm-templates.ts +2 -36
  38. package/src/templates/scaffold-helm.ts +1 -0
  39. package/wiki/CLI-Reference.md +14 -1
  40. package/wiki/Deployment.md +2 -1
  41. package/wiki/Known-Gaps.md +1 -1
  42. package/wiki/Scraping.md +20 -0
  43. package/wiki/Upgrading.md +1 -0
@@ -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,65 @@
1
+ // A CLI command that opens the app's database for one run (`startDb`) and owes the process its
2
+ // `db()` back: an installed client as it was, a lazily built default it dropped closed — never
3
+ // orphaned — and both of its own pools closed whatever the run did.
4
+
5
+ import { logger, renderThrowable } from '@ultimat3/core';
6
+ import { ambientClient, type DbClient, dbClientInstalled, setDbClient } from '@ultimat3/db';
7
+
8
+ const closable = (client: DbClient): client is DbClient & { close(): Promise<void> } =>
9
+ 'close' in client && typeof client.close === 'function';
10
+
11
+ /**
12
+ * Read BEFORE the command installs anything; call what it returns once it is done. `db()` is put
13
+ * back synchronously on the call, so a caller may settle the returned close beside its own.
14
+ */
15
+ export function displaceAmbient(): () => Promise<void> {
16
+ const installed = dbClientInstalled();
17
+ const previous = ambientClient();
18
+ return async () => {
19
+ if (installed) {
20
+ setDbClient(previous);
21
+ return;
22
+ }
23
+ setDbClient(undefined);
24
+ if (previous !== undefined && closable(previous)) await previous.close();
25
+ };
26
+ }
27
+
28
+ interface Closable {
29
+ close(): Promise<void>;
30
+ }
31
+
32
+ /**
33
+ * Open, run, then put `db()` back and close every pool whatever happened. The open is inside the
34
+ * guarded scope (`startDb` installs before it returns); one rejected close never skips another.
35
+ * The run's own failure is what is thrown, a close failure beside it is logged; after a good run a
36
+ * close failure is thrown.
37
+ */
38
+ export async function withOpenedDb<T>(
39
+ open: () => { readonly client: DbClient & Closable; readonly replica?: Closable | undefined },
40
+ run: (client: DbClient) => Promise<T>,
41
+ ): Promise<T> {
42
+ const restore = displaceAmbient();
43
+ let opened: ReturnType<typeof open> | undefined;
44
+ let outcome: { readonly value: T } | { readonly error: unknown };
45
+ try {
46
+ opened = open();
47
+ outcome = { value: await run(opened.client) };
48
+ } catch (error) {
49
+ outcome = { error };
50
+ }
51
+ const closed = await Promise.allSettled([
52
+ restore(),
53
+ opened?.client.close(),
54
+ opened?.replica?.close(),
55
+ ]);
56
+ const rejected = closed.flatMap((one) => (one.status === 'rejected' ? [one.reason] : []));
57
+ if ('error' in outcome) {
58
+ for (const reason of rejected) {
59
+ logger.warn('x db could not close its database', { cause: renderThrowable(reason) });
60
+ }
61
+ throw outcome.error;
62
+ }
63
+ if (rejected.length > 0) throw rejected[0];
64
+ return outcome.value;
65
+ }
@@ -2,13 +2,13 @@
2
2
  // `dbDiagnostics()` and renders one table per answered section. Facts, never a verdict: exit 0
3
3
  // whatever they say, and the one failure is a connection that never opens (`X_DB_UNAVAILABLE`).
4
4
 
5
- import { baseClient, dbClientInstalled, setDbClient } from '@ultimat3/db';
6
5
  import {
7
6
  type DbDiagnostics,
8
7
  type DiagnosticSection,
9
8
  dbDiagnostics,
10
9
  } from '@ultimat3/db/diagnostics';
11
10
  import type { CommandContext } from './command';
11
+ import { withOpenedDb } from './db-client-displace';
12
12
  import { DevAlreadyRunningError, liveDevLock } from './dev-lock';
13
13
  import { readIntFlag } from './flag-number';
14
14
  import { msg } from './messages';
@@ -89,31 +89,28 @@ export async function runDiagnostics(ctx: CommandContext, root: string): Promise
89
89
  });
90
90
  }
91
91
  }
92
- // `startDb` installs its client as the process's `db()`, and this command closes it: what was
93
- // there before goes back, or every later `db()` in an embedding process reaches a dead pool.
94
- // `undefined` when nothing was installed, which restores lazy construction rather than building it.
95
- const previous = dbClientInstalled() ? baseClient() : undefined;
96
- const started = startDb(services, ctx.env);
97
- try {
98
- // Embedded, the probe IS the boot — a WASM compile and an initdb, 12.6 s cold under coverage —
99
- // so the 3 s probe wait answered a healthy database X_DB_UNAVAILABLE. A server keeps the default.
100
- const deadlineMs =
101
- services.db.mode === 'embedded' ? EMBEDDED_DIAGNOSTICS_DEADLINE_MS : undefined;
102
- const report = await dbDiagnostics({ client: started.client, limit, deadlineMs });
103
- const sections = Object.values(report);
104
- return {
105
- ok: true,
106
- command: 'db',
107
- summary: msg('cli.db.diagnostics.done', {
108
- available: sections.filter((section) => section.available).length,
109
- total: sections.length,
110
- }),
111
- lines: renderDiagnostics(report),
112
- data: diagnosticsJson(report),
113
- };
114
- } finally {
115
- setDbClient(previous);
116
- await started.client.close();
117
- await started.replica?.close();
118
- }
92
+ // `startDb` installs its client as the process's `db()`; `withOpenedDb` puts back what was there
93
+ // (closing a lazy default it dropped) and closes both pools, or every later `db()` in an
94
+ // embedding process reaches a dead pool.
95
+ return withOpenedDb(
96
+ () => startDb(services, ctx.env),
97
+ async (client) => {
98
+ // Embedded, the probe IS the boot — a WASM compile and an initdb, 12.6 s cold under coverage —
99
+ // so the 3 s probe wait answered a healthy database X_DB_UNAVAILABLE. A server keeps the default.
100
+ const deadlineMs =
101
+ services.db.mode === 'embedded' ? EMBEDDED_DIAGNOSTICS_DEADLINE_MS : undefined;
102
+ const report = await dbDiagnostics({ client, limit, deadlineMs });
103
+ const sections = Object.values(report);
104
+ return {
105
+ ok: true,
106
+ command: 'db',
107
+ summary: msg('cli.db.diagnostics.done', {
108
+ available: sections.filter((section) => section.available).length,
109
+ total: sections.length,
110
+ }),
111
+ lines: renderDiagnostics(report),
112
+ data: diagnosticsJson(report),
113
+ };
114
+ },
115
+ );
119
116
  }
@@ -0,0 +1,185 @@
1
+ // `x db status`'s verdict, pure: the app migrations this build ships against the `x_migrations`
2
+ // ledger (`appMigrationsVerdict`, the boot's own rule), an applied migration edited since, and the
3
+ // framework stamp (`stampVerdict`). A finding only where a serving role would wait or `x db migrate`
4
+ // would refuse; the read is `cmd-db-status.ts`'s.
5
+
6
+ import type { LedgerRow, Migration } from '@ultimat3/db';
7
+ import {
8
+ auditLedger,
9
+ ledgerAheadOfBuild,
10
+ migrationChecksum,
11
+ runningAppVersion,
12
+ } from '@ultimat3/db';
13
+ import { AppMigrationsUnappliedError, appMigrationsVerdict } from './app-migrations-verdict';
14
+ import {
15
+ aheadByMajor,
16
+ FrameworkSchemaUnappliedError,
17
+ parseStamp,
18
+ type StampEntry,
19
+ stampVerdict,
20
+ } from './framework-schema-stamp';
21
+ import { msg } from './messages';
22
+ import type { Finding, JsonValue } from './output';
23
+ import { findingFrom } from './output';
24
+
25
+ /** The one read: the stamp comment and the ledger rows, `undefined` when `x_migrations` is absent. */
26
+ export interface DbStatusRead {
27
+ readonly stamp: string | null;
28
+ readonly ledger: readonly LedgerRow[] | undefined;
29
+ }
30
+
31
+ export interface FrameworkStatus {
32
+ readonly version: string;
33
+ readonly schema: string;
34
+ readonly applied: boolean;
35
+ /** The newest build the stamp records, when this one is not in it. */
36
+ readonly newest?: StampEntry;
37
+ /** The newest build, when this one is applied and the newest is another major. */
38
+ readonly skew?: StampEntry;
39
+ readonly aheadByMajor: boolean;
40
+ }
41
+
42
+ export interface DbStatus {
43
+ readonly shipped: readonly string[];
44
+ /** `null` when the ledger table does not exist: no migrate step has run here. */
45
+ readonly applied: readonly string[] | null;
46
+ readonly pending: readonly string[];
47
+ readonly ahead: readonly string[];
48
+ /** Applied, and its file now hashes otherwise. */
49
+ readonly edited: readonly string[];
50
+ readonly framework: FrameworkStatus;
51
+ }
52
+
53
+ export function dbStatus(
54
+ read: DbStatusRead,
55
+ migrations: readonly Migration[],
56
+ mine: StampEntry,
57
+ ): DbStatus {
58
+ const shipped = migrations.map((migration) => migration.id);
59
+ const applied = read.ledger?.map((row) => row.id);
60
+ const verdict = appMigrationsVerdict(shipped, applied);
61
+ const files = new Map(migrations.map((migration) => [migration.id, migration]));
62
+ const edited = (read.ledger ?? []).flatMap((row) => {
63
+ const file = files.get(row.id);
64
+ return file !== undefined && migrationChecksum(file) !== row.checksum ? [row.id] : [];
65
+ });
66
+ const stamp = stampVerdict(parseStamp(read.stamp), mine);
67
+ const framework: FrameworkStatus = stamp.applied
68
+ ? {
69
+ ...mine,
70
+ applied: true,
71
+ ...(stamp.skew === undefined ? {} : { skew: stamp.skew }),
72
+ aheadByMajor: false,
73
+ }
74
+ : {
75
+ ...mine,
76
+ applied: false,
77
+ ...(stamp.newest === undefined ? {} : { newest: stamp.newest }),
78
+ aheadByMajor: aheadByMajor(stamp.newest, mine),
79
+ };
80
+ return {
81
+ shipped,
82
+ applied: applied ?? null,
83
+ pending: verdict.missing,
84
+ ahead: verdict.unknown,
85
+ edited,
86
+ framework,
87
+ };
88
+ }
89
+
90
+ /**
91
+ * The boot's refusals and the migrator's, as findings — each the error the real path throws, so the
92
+ * code and fix are theirs. Ahead is not one: a serving role serves it with a warning (a rollback).
93
+ */
94
+ export function dbStatusFindings(
95
+ status: DbStatus,
96
+ migrations: readonly Migration[],
97
+ ledger: DbStatusRead['ledger'],
98
+ options: {
99
+ /** `ROLLBACK_ALLOW_DESTRUCTIVE` as the migrate role would read it. */
100
+ readonly allow?: string | undefined;
101
+ /** `APP_VERSION` from the command's env, as `runMigrations` hands it to `migrate()`. */
102
+ readonly appVersion?: string | undefined;
103
+ } = {},
104
+ ): Finding[] {
105
+ const findings: Finding[] = [];
106
+ const { framework } = status;
107
+ if (!framework.applied) {
108
+ const mine = { version: framework.version, schema: framework.schema };
109
+ findings.push(
110
+ findingFrom(new FrameworkSchemaUnappliedError({ mine, newest: framework.newest })),
111
+ );
112
+ }
113
+ if (status.pending.length > 0) {
114
+ findings.push(
115
+ findingFrom(
116
+ new AppMigrationsUnappliedError({
117
+ missing: status.pending,
118
+ ledger: status.applied !== null,
119
+ }),
120
+ ),
121
+ );
122
+ }
123
+ if (ledger !== undefined) {
124
+ // `x db migrate`'s own two steps, in its order (migrate.ts): a ledger that is exactly a
125
+ // rollback is accepted and audited over its known rows; anything else ahead, and any applied
126
+ // migration edited since, is the conflict it refuses with — never a second spelling of either.
127
+ try {
128
+ const rolledBack = ledgerAheadOfBuild(ledger, migrations, { allow: options.allow });
129
+ // `migrate()`'s own reader of the build's name, so both commands' causes name the same one.
130
+ auditLedger(rolledBack?.known ?? ledger, migrations, runningAppVersion(options.appVersion));
131
+ } catch (error) {
132
+ findings.push(findingFrom(error));
133
+ }
134
+ }
135
+ return findings;
136
+ }
137
+
138
+ const idsOrNone = (ids: readonly string[]): string =>
139
+ ids.length === 0 ? msg('cli.db.status.none') : ids.join(', ');
140
+
141
+ export function dbStatusLines(status: DbStatus): readonly string[] {
142
+ const { framework } = status;
143
+ const newest = framework.newest ?? framework.skew;
144
+ return [
145
+ msg('cli.db.status.framework', {
146
+ verdict: msg(framework.applied ? 'cli.db.status.applied' : 'cli.db.status.unapplied'),
147
+ version: framework.version,
148
+ schema: framework.schema,
149
+ }),
150
+ ...(newest === undefined
151
+ ? []
152
+ : [msg('cli.db.status.newest', { version: newest.version, schema: newest.schema })]),
153
+ msg('cli.db.status.migrations', {
154
+ shipped: status.shipped.length,
155
+ applied:
156
+ status.applied === null ? msg('cli.db.status.noLedger') : String(status.applied.length),
157
+ }),
158
+ msg('cli.db.status.pending', { ids: idsOrNone(status.pending) }),
159
+ msg('cli.db.status.ahead', { ids: idsOrNone(status.ahead) }),
160
+ ...(status.edited.length === 0
161
+ ? []
162
+ : [msg('cli.db.status.edited', { ids: status.edited.join(', ') })]),
163
+ ];
164
+ }
165
+
166
+ /** The `--json` body: the same facts the lines print. */
167
+ export function dbStatusJson(status: DbStatus): { readonly [key: string]: JsonValue } {
168
+ const entry = (one: StampEntry | undefined): JsonValue =>
169
+ one === undefined ? null : { version: one.version, schema: one.schema };
170
+ return {
171
+ shipped: [...status.shipped],
172
+ applied: status.applied === null ? null : [...status.applied],
173
+ pending: [...status.pending],
174
+ ahead: [...status.ahead],
175
+ edited: [...status.edited],
176
+ framework: {
177
+ version: status.framework.version,
178
+ schema: status.framework.schema,
179
+ applied: status.framework.applied,
180
+ newest: entry(status.framework.newest),
181
+ skew: entry(status.framework.skew),
182
+ aheadByMajor: status.framework.aheadByMajor,
183
+ },
184
+ };
185
+ }
@@ -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
  }
@@ -0,0 +1,120 @@
1
+ // A serving role's boot over an external database: no DDL, one statement per attempt once a
2
+ // migrate has run — the framework stamp and the app's `x_migrations` ledger together — and the
3
+ // wait for the migrate step when either is behind this build (`framework-schema-wait.ts`).
4
+
5
+ import { recordFrameworkSchema } from '@ultimat3/core';
6
+ import type { DbClient } from '@ultimat3/db';
7
+ import { isLedgerMissing, LEDGER_TABLE, raw } from '@ultimat3/db';
8
+ import {
9
+ AppMigrationsUnappliedError,
10
+ appMigrationsVerdict,
11
+ parseAppliedIds,
12
+ reportAppMigrationsAhead,
13
+ } from './app-migrations-verdict';
14
+ import { readStamp, reportSkew, thisBuild } from './framework-schema-apply';
15
+ import {
16
+ aheadByMajor,
17
+ FrameworkSchemaUnappliedError,
18
+ otherMajor,
19
+ parseStamp,
20
+ STAMP_RELATION,
21
+ type StampEntry,
22
+ stampVerdict,
23
+ } from './framework-schema-stamp';
24
+ import { type SchemaCheck, type SchemaWaitOptions, waitForSchema } from './framework-schema-wait';
25
+
26
+ export interface VerifySchemaOptions extends SchemaWaitOptions {
27
+ /** The migration ids this build ships (`readMigrations(root)`), oldest first. None: not read. */
28
+ readonly shipped?: readonly string[];
29
+ }
30
+
31
+ interface BootRead {
32
+ readonly stamp: string | null;
33
+ /** `undefined` when `x_migrations` does not exist. */
34
+ readonly applied: readonly string[] | undefined;
35
+ }
36
+
37
+ /**
38
+ * ONE statement on every database a migrate step has touched: the stamp and the ledger together.
39
+ * A missing ledger fails the whole of it (`42P01`) — Postgres resolves a relation when it PARSES,
40
+ * so no `case when to_regclass(…)` guard can name a table that may not exist — and only then is
41
+ * the stamp read alone: a second statement on a database no migrate has ever run on, never after.
42
+ */
43
+ async function readBoot(client: DbClient, withLedger: boolean): Promise<BootRead> {
44
+ if (!withLedger) return { stamp: await readStamp(client), applied: [] };
45
+ try {
46
+ const rows = await client.query<{ readonly stamp: string | null; readonly applied: unknown }>(
47
+ raw(
48
+ `select obj_description(to_regclass('${STAMP_RELATION}'), 'pg_class') as stamp, ` +
49
+ `(select coalesce(json_agg(id order by id), '[]'::json)::text from ${LEDGER_TABLE}) as applied`,
50
+ ),
51
+ );
52
+ return { stamp: rows[0]?.stamp ?? null, applied: parseAppliedIds(rows[0]?.applied) };
53
+ } catch (error) {
54
+ if (!isLedgerMissing(error)) throw error;
55
+ return { stamp: await readStamp(client), applied: undefined };
56
+ }
57
+ }
58
+
59
+ interface Served {
60
+ readonly skew: StampEntry | undefined;
61
+ readonly unknown: readonly string[];
62
+ }
63
+
64
+ function judge(read: BootRead, mine: StampEntry, shipped: readonly string[]): SchemaCheck<Served> {
65
+ const framework = stampVerdict(parseStamp(read.stamp), mine);
66
+ const app = appMigrationsVerdict(shipped, read.applied);
67
+ // Every read, each round of a wait included, scraped off the metrics listener `serveApp` opened
68
+ // before this boot began. `applied` is 0 while the role waits for EITHER half: what the alert
69
+ // reads is "this role is not serving because its schema is not applied".
70
+ recordFrameworkSchema({
71
+ applied: framework.applied && app.missing.length === 0,
72
+ majorSkew: framework.applied
73
+ ? framework.skew !== undefined
74
+ : otherMajor(framework.newest, mine),
75
+ });
76
+ if (!framework.applied) {
77
+ const { newest } = framework;
78
+ return {
79
+ ready: false,
80
+ atOnce: aheadByMajor(newest, mine),
81
+ refuse: (waitedMs) =>
82
+ new FrameworkSchemaUnappliedError({
83
+ mine,
84
+ newest,
85
+ ...(waitedMs === undefined ? {} : { waitedMs }),
86
+ }),
87
+ };
88
+ }
89
+ if (app.missing.length > 0) {
90
+ return {
91
+ ready: false,
92
+ refuse: (waitedMs) =>
93
+ new AppMigrationsUnappliedError({
94
+ missing: app.missing,
95
+ ledger: read.applied !== undefined,
96
+ ...(waitedMs === undefined ? {} : { waitedMs }),
97
+ }),
98
+ };
99
+ }
100
+ return { ready: true, value: { skew: framework.skew, unknown: app.unknown } };
101
+ }
102
+
103
+ /**
104
+ * Served once the framework stamp holds this build and the ledger holds every migration it ships.
105
+ * Behind on either WAITS — a rollout that starts the roles before the migrate Job finishes is a
106
+ * normal deploy, and refusing at once crash-looped it — then is refused with the command that
107
+ * applies. A database a newer major stamped is refused at once. Ahead is served and said once: a
108
+ * fleet straddling a major (`reportSkew`), a ledger holding migrations this build does not ship
109
+ * (`reportAppMigrationsAhead`) — both are the old pods of a rollout or a rollback.
110
+ */
111
+ export async function verifySchema(client: DbClient, options: VerifySchemaOptions): Promise<void> {
112
+ const mine = thisBuild();
113
+ const shipped = options.shipped ?? [];
114
+ const served = await waitForSchema(
115
+ async () => judge(await readBoot(client, shipped.length > 0), mine, shipped),
116
+ options,
117
+ );
118
+ reportSkew(mine, served.skew);
119
+ reportAppMigrationsAhead(served.unknown);
120
+ }