@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
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.30.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.30.0",
57
+ "@ultimat3/admin": "31.30.0",
58
+ "@ultimat3/ai": "31.30.0",
59
+ "@ultimat3/auth": "31.30.0",
60
+ "@ultimat3/cache": "31.30.0",
61
+ "@ultimat3/core": "31.30.0",
62
+ "@ultimat3/db": "31.30.0",
63
+ "@ultimat3/entity": "31.30.0",
64
+ "@ultimat3/flags": "31.30.0",
65
+ "@ultimat3/http": "31.30.0",
66
+ "@ultimat3/i18n": "31.30.0",
67
+ "@ultimat3/jobs": "31.30.0",
68
+ "@ultimat3/mail": "31.30.0",
69
+ "@ultimat3/manifest": "31.30.0",
70
+ "@ultimat3/mcp": "31.30.0",
71
+ "@ultimat3/money": "31.30.0",
72
+ "@ultimat3/notify": "31.30.0",
73
+ "@ultimat3/policy": "31.30.0",
74
+ "@ultimat3/pwa": "31.30.0",
75
+ "@ultimat3/query": "31.30.0",
76
+ "@ultimat3/realtime": "31.30.0",
77
+ "@ultimat3/render": "31.30.0",
78
+ "@ultimat3/schema": "31.30.0",
79
+ "@ultimat3/scraping": "31.30.0",
80
+ "@ultimat3/seo": "31.30.0",
81
+ "@ultimat3/storage": "31.30.0",
82
+ "@ultimat3/testing": "31.30.0",
83
+ "@ultimat3/time": "31.30.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -0,0 +1,85 @@
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
+ // The read that lists them beside the framework stamp, and writes nothing.
83
+ fix: 'x db status --json',
84
+ });
85
+ }
@@ -6,14 +6,11 @@
6
6
  import { finiteCount } from '@ultimat3/core';
7
7
  import type { CounterDescriptionLike, DbClient } from '@ultimat3/db';
8
8
  import {
9
- baseClient,
10
9
  CROSS_TENANT_SETTING,
11
- dbClientInstalled,
12
10
  recountBatchSql,
13
11
  recountDriftBatchSql,
14
12
  recountLockSql,
15
13
  recountWindowSql,
16
- setDbClient,
17
14
  setLocal,
18
15
  withTransaction,
19
16
  } from '@ultimat3/db';
@@ -21,6 +18,7 @@ import { countersOf, describeCounter, getEntity } from '@ultimat3/entity';
21
18
  import { loadApp } from './app-load';
22
19
  import { loadAppRuntime } from './app-runtime';
23
20
  import type { CommandContext } from './command';
21
+ import { withOpenedDb } from './db-client-displace';
24
22
  import { DevAlreadyRunningError, liveDevLock } from './dev-lock';
25
23
  import { BadFlagError } from './errors';
26
24
  import { msg } from './messages';
@@ -156,44 +154,41 @@ async function recount(ctx: CommandContext, root: string): Promise<CommandResult
156
154
  });
157
155
  }
158
156
  }
159
- // `startDb` installs its client as the process's `db()`, and this command closes it: what was
160
- // there before goes back (`undefined`: lazy construction), as `db-diagnostics.ts` does.
161
- const previous = dbClientInstalled() ? baseClient() : undefined;
162
- const started = startDb(services, ctx.env);
163
- try {
164
- const report = await recountInBatches(started.client, parent.$table, counter, { write });
165
- const drift = report.rows;
166
- return {
167
- ok: findings.length === 0 && (write || report.drifted === 0),
168
- command: 'db',
169
- summary: msg(write ? 'cli.db.recount.repaired' : 'cli.db.recount.drift', {
170
- target,
171
- count: report.drifted,
172
- }),
173
- findings: [
174
- ...findings,
175
- ...(write || report.drifted === 0
176
- ? []
177
- : [
178
- {
179
- code: 'X_LIFECYCLE_TRIGGER_MISSING',
180
- cause: `${report.drifted} row(s) of ${parent.$table} hold a ${counter.column} that is not the count of ${counter.table} rows pointing at them`,
181
- fix: `x db recount ${quoteArg(target)} --write --json`,
182
- },
183
- ]),
184
- ],
185
- lines: drift.map((row) => ` ${row.key} stored ${row.stored} actual ${row.actual}`),
186
- data: {
187
- target,
188
- write,
189
- drifted: report.drifted,
190
- batches: report.batches,
191
- rows: drift.map((row) => ({ ...row })),
192
- },
193
- };
194
- } finally {
195
- setDbClient(previous);
196
- await started.client.close();
197
- await started.replica?.close();
198
- }
157
+ // `startDb` installs its client as the process's `db()`; `withOpenedDb` puts back what was there
158
+ // (closing a lazy default it dropped) and closes both pools, as `db-diagnostics.ts` does.
159
+ return withOpenedDb(
160
+ () => startDb(services, ctx.env),
161
+ async (client) => {
162
+ const report = await recountInBatches(client, parent.$table, counter, { write });
163
+ const drift = report.rows;
164
+ return {
165
+ ok: findings.length === 0 && (write || report.drifted === 0),
166
+ command: 'db',
167
+ summary: msg(write ? 'cli.db.recount.repaired' : 'cli.db.recount.drift', {
168
+ target,
169
+ count: report.drifted,
170
+ }),
171
+ findings: [
172
+ ...findings,
173
+ ...(write || report.drifted === 0
174
+ ? []
175
+ : [
176
+ {
177
+ code: 'X_LIFECYCLE_TRIGGER_MISSING',
178
+ cause: `${report.drifted} row(s) of ${parent.$table} hold a ${counter.column} that is not the count of ${counter.table} rows pointing at them`,
179
+ fix: `x db recount ${quoteArg(target)} --write --json`,
180
+ },
181
+ ]),
182
+ ],
183
+ lines: drift.map((row) => ` ${row.key} stored ${row.stored} actual ${row.actual}`),
184
+ data: {
185
+ target,
186
+ write,
187
+ drifted: report.drifted,
188
+ batches: report.batches,
189
+ rows: drift.map((row) => ({ ...row })),
190
+ },
191
+ };
192
+ },
193
+ );
199
194
  }
@@ -13,13 +13,14 @@ export const DB_SUBCOMMANDS = [
13
13
  'backfill',
14
14
  'diagnostics',
15
15
  'recount',
16
+ 'status',
16
17
  ] as const;
17
18
 
18
19
  export const dbSpec: CommandSpec = {
19
20
  name: 'db',
20
- summary: 'gen, migrate, reset, seed, branch, backfill, diagnostics, recount',
21
+ summary: 'gen, migrate, reset, seed, branch, backfill, diagnostics, recount, status',
21
22
  usage:
22
- 'x db gen "add publish_at" [--drop-redundant] | migrate | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write]',
23
+ 'x db gen "add publish_at" [--drop-redundant] | migrate | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write] | status',
23
24
  requiresApp: true,
24
25
  subcommands: DB_SUBCOMMANDS,
25
26
  // Declared from the constant `runBranchCommand` validates against, never a second literal: it
@@ -0,0 +1,80 @@
1
+ // `x db status`: one read of the app's database — the framework stamp and the `x_migrations`
2
+ // ledger — judged by `db-status.ts` against the migrations this build ships. No DDL, no ledger
3
+ // write, no migrate lock: `startDb`, never `startQueue` (the queue's boot applies framework
4
+ // tables). An embedded database never created is reported as such, never initialised to say so.
5
+
6
+ // why: Bun has no directory probe — `Bun.file().exists()` answers about a file.
7
+ import { existsSync } from 'node:fs';
8
+ import {
9
+ type DbClient,
10
+ isLedgerMissing,
11
+ pgliteDataDir,
12
+ ROLLBACK_ALLOW_DESTRUCTIVE_ENV,
13
+ readLedger,
14
+ } from '@ultimat3/db';
15
+ import type { CommandContext } from './command';
16
+ import { withOpenedDb } from './db-client-displace';
17
+ import {
18
+ type DbStatusRead,
19
+ dbStatus,
20
+ dbStatusFindings,
21
+ dbStatusJson,
22
+ dbStatusLines,
23
+ } from './db-status';
24
+ import { DevAlreadyRunningError, liveDevLock } from './dev-lock';
25
+ import { readStamp, thisBuild } from './framework-schema-apply';
26
+ import { msg } from './messages';
27
+ import { readMigrations } from './migrations';
28
+ import type { CommandResult } from './output';
29
+ import { resolveServices } from './runtime-bindings';
30
+ import { startDb } from './runtime-queue';
31
+
32
+ /** The stamp, then the ledger; a missing ledger (`42P01`) is a fact, every other failure throws. */
33
+ export async function readDbStatus(client: DbClient): Promise<DbStatusRead> {
34
+ const stamp = await readStamp(client);
35
+ try {
36
+ return { stamp, ledger: await readLedger(client) };
37
+ } catch (error) {
38
+ if (!isLedgerMissing(error)) throw error;
39
+ return { stamp, ledger: undefined };
40
+ }
41
+ }
42
+
43
+ /** Opens the database the way every role does, reads once, and puts the process's `db()` back. */
44
+ async function readFromApp(ctx: CommandContext, root: string): Promise<DbStatusRead> {
45
+ const services = resolveServices(root, ctx.env);
46
+ if (services.db.mode === 'embedded') {
47
+ if (!existsSync(pgliteDataDir(services.db.url))) return { stamp: null, ledger: undefined };
48
+ // PGlite's data directory has one writer: an `x dev` holding it is refused, as diagnostics is.
49
+ const holder = liveDevLock(services.stateDir);
50
+ if (holder !== undefined) {
51
+ throw new DevAlreadyRunningError({
52
+ lock: holder,
53
+ stateDir: services.stateDir,
54
+ embeddedDb: true,
55
+ });
56
+ }
57
+ }
58
+ return withOpenedDb(() => startDb(services, ctx.env), readDbStatus);
59
+ }
60
+
61
+ export async function runDbStatus(ctx: CommandContext, root: string): Promise<CommandResult> {
62
+ const migrations = await readMigrations(root);
63
+ const read = await readFromApp(ctx, root);
64
+ const status = dbStatus(read, migrations, thisBuild());
65
+ const findings = dbStatusFindings(status, migrations, read.ledger, {
66
+ allow: ctx.env[ROLLBACK_ALLOW_DESTRUCTIVE_ENV],
67
+ appVersion: ctx.env['APP_VERSION'],
68
+ });
69
+ return {
70
+ ok: findings.length === 0,
71
+ command: 'db',
72
+ summary:
73
+ findings.length === 0
74
+ ? msg('cli.db.status.current')
75
+ : msg('cli.db.status.behind', { count: findings.length }),
76
+ findings,
77
+ lines: dbStatusLines(status),
78
+ data: dbStatusJson(status),
79
+ };
80
+ }
package/src/cmd-db.ts CHANGED
@@ -1,7 +1,7 @@
1
- // `x db gen|migrate|reset|seed|studio|branch|backfill|diagnostics|recount` — everything that touches the
1
+ // `x db gen|migrate|reset|seed|studio|branch|backfill|diagnostics|recount|status` — everything that touches the
2
2
  // database. One subcommand per line and no fall-through: a word this file does not know is refused,
3
3
  // never re-read as an argument to the last branch. `branch` is `cmd-db-branch.ts`, `diagnostics`
4
- // is `db-diagnostics.ts`.
4
+ // is `db-diagnostics.ts`, `status` is `cmd-db-status.ts`.
5
5
  //
6
6
  // Every subcommand here runs `@ultimat3/db`'s own engine, which is the engine `ROLE=migrate` runs
7
7
  // (`serve.ts`): one `x_migrations` ledger, one checksum rule, one advisory lock, from a laptop to
@@ -20,6 +20,7 @@ import { runBackfillCommand } from './cmd-db-backfill';
20
20
  import { runBranchCommand } from './cmd-db-branch';
21
21
  import { runRecountCommand } from './cmd-db-recount';
22
22
  import { DB_SUBCOMMANDS, dbSpec } from './cmd-db-spec';
23
+ import { runDbStatus } from './cmd-db-status';
23
24
  import type { CliCommand, CommandContext } from './command';
24
25
  import { runDiagnostics } from './db-diagnostics';
25
26
  import { stepFinding } from './db-finding';
@@ -71,6 +72,7 @@ export const dbCommand: CliCommand = {
71
72
  if (sub === 'branch') return runBranchCommand(ctx, root);
72
73
  if (sub === 'diagnostics') return runDiagnostics(ctx, root);
73
74
  if (sub === 'recount') return runRecountCommand(ctx, root);
75
+ if (sub === 'status') return runDbStatus(ctx, root);
74
76
 
75
77
  // Never a fall-through. This used to end `return runBranch(ctx, root, argument ?? 'preview')`,
76
78
  // so ANY subcommand the parser had not already refused was reinterpreted as a branch NAME and
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
+ };