@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 +1 -0
- package/package.json +29 -29
- package/src/app-migrations-verdict.ts +84 -0
- package/src/cmd-drill.ts +23 -9
- package/src/codemods/helm-alerts-deploy.ts +85 -0
- package/src/codemods/index.ts +4 -0
- package/src/codemods/migrate-job-ordered.ts +81 -0
- package/src/codemods/migrate-job-stock.ts +41 -0
- package/src/drill-schema-behind.ts +26 -0
- package/src/error-codes.ts +3 -0
- package/src/framework-schema-apply.ts +7 -19
- package/src/framework-schema-stamp.ts +38 -3
- package/src/framework-schema-verify.ts +120 -0
- package/src/framework-schema-wait.ts +125 -0
- package/src/mcp-errors.ts +1 -0
- package/src/role-pg-stats.ts +21 -0
- package/src/role-start.ts +4 -0
- package/src/runtime-queue.ts +27 -6
- package/src/serve-boot-probe.ts +97 -0
- package/src/serve-boot.ts +26 -1
- package/src/serve-retire.ts +16 -3
- package/src/templates/chart-dashboard-panels.ts +178 -0
- package/src/templates/chart-dashboard.ts +9 -135
- package/src/templates/scaffold-container.ts +2 -2
- package/src/templates/scaffold-helm-alert-deploy.ts +105 -0
- package/src/templates/scaffold-helm-alert-rules.ts +7 -1
- package/src/templates/scaffold-helm-alerts.ts +3 -0
- package/src/templates/scaffold-helm-migrate.ts +85 -0
- package/src/templates/scaffold-helm-templates.ts +2 -36
- package/src/templates/scaffold-helm.ts +1 -0
- package/wiki/CLI-Reference.md +12 -1
- package/wiki/Deployment.md +2 -1
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/Upgrading.md +1 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// A serving role over a schema still behind its build — the framework stamp or the app's ledger:
|
|
2
|
+
// wait for the migrate step, bounded by `ULTIMATE_SCHEMA_WAIT_MS`, on core's one backoff curve,
|
|
3
|
+
// saying so once — never exit at once and crash-loop a rollout that started the roles before the
|
|
4
|
+
// migrate Job finished (plan 101, D2). A SIGTERM mid-wait is a drain, never a wait to the deadline.
|
|
5
|
+
|
|
6
|
+
import type { Random, SleepClock } from '@ultimat3/core';
|
|
7
|
+
import {
|
|
8
|
+
ambientClock,
|
|
9
|
+
backoffDelay,
|
|
10
|
+
failureStreak,
|
|
11
|
+
isDraining,
|
|
12
|
+
onShutdown,
|
|
13
|
+
UltimateError,
|
|
14
|
+
} from '@ultimat3/core';
|
|
15
|
+
import { SCHEMA_WAIT_ENV } from './framework-schema-stamp';
|
|
16
|
+
|
|
17
|
+
export { SCHEMA_WAIT_ENV };
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Five minutes: a migrate Job that has not stamped the database by then is failing, not slow, and
|
|
21
|
+
* it is the default `helm --wait` budget, so a rollout gives up on the pod no sooner than this.
|
|
22
|
+
*/
|
|
23
|
+
export const DEFAULT_SCHEMA_WAIT_MS = 300_000;
|
|
24
|
+
|
|
25
|
+
/** The first wait and the ceiling of any one: a catalog read every 15s at worst, per pod. */
|
|
26
|
+
const WAIT_BASE_MS = 1_000;
|
|
27
|
+
const WAIT_MAX_MS = 15_000;
|
|
28
|
+
|
|
29
|
+
/** `X_CONFIG_INVALID`: a deadline that is not whole milliseconds is refused, never read as NaN. */
|
|
30
|
+
export class SchemaWaitInvalidError extends UltimateError {
|
|
31
|
+
constructor(value: string) {
|
|
32
|
+
super({
|
|
33
|
+
code: 'X_CONFIG_INVALID',
|
|
34
|
+
cause: `${SCHEMA_WAIT_ENV} is "${value}"; it is the whole number of milliseconds a serving role waits for the migrate step to bring the schema to its build, 0 to refuse at once`,
|
|
35
|
+
// Literal: a spliced value in a command position is what the fix-shell-arg ratchet refuses.
|
|
36
|
+
// `framework-schema-wait.test.ts` holds it equal to the two constants.
|
|
37
|
+
fix: 'docker run -e ULTIMATE_SCHEMA_WAIT_MS=300000 <image> # or unset it for the default',
|
|
38
|
+
meta: { key: SCHEMA_WAIT_ENV },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The declared deadline: unset or blank is the default; anything but decimal digits is refused. */
|
|
44
|
+
export function schemaWaitMsFromEnv(env: Readonly<Record<string, string | undefined>>): number {
|
|
45
|
+
const raw = env[SCHEMA_WAIT_ENV]?.trim();
|
|
46
|
+
if (raw === undefined || raw.length === 0) return DEFAULT_SCHEMA_WAIT_MS;
|
|
47
|
+
const ms = Number(raw);
|
|
48
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(ms)) throw new SchemaWaitInvalidError(raw);
|
|
49
|
+
return ms;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SchemaWaitOptions {
|
|
53
|
+
/** How long to wait; the boot's `schemaWaitMsFromEnv(env)`. `0` refuses on the first read. */
|
|
54
|
+
readonly deadlineMs: number;
|
|
55
|
+
readonly clock?: SleepClock;
|
|
56
|
+
readonly random?: Random;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One read's answer: ready with what the caller reports, or the refusal it would end in. */
|
|
60
|
+
export type SchemaCheck<T> =
|
|
61
|
+
| { readonly ready: true; readonly value: T }
|
|
62
|
+
| {
|
|
63
|
+
readonly ready: false;
|
|
64
|
+
/** Built with how long the role waited, or without when it refuses on the first read. */
|
|
65
|
+
readonly refuse: (waitedMs?: number) => UltimateError;
|
|
66
|
+
/** No wait can help — a newer major migrated: refused on this read. */
|
|
67
|
+
readonly atOnce?: boolean;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `check` until it is ready, the deadline passes, or a drain begins. One line when the wait opens
|
|
72
|
+
* and one if its cause changes — the framework stamp landing with the app's migrations still
|
|
73
|
+
* pending is news — and one when it ends; never a line per read per pod.
|
|
74
|
+
*/
|
|
75
|
+
export async function waitForSchema<T>(
|
|
76
|
+
check: () => Promise<SchemaCheck<T>>,
|
|
77
|
+
options: SchemaWaitOptions,
|
|
78
|
+
): Promise<T> {
|
|
79
|
+
const { deadlineMs } = options;
|
|
80
|
+
const clock = options.clock ?? ambientClock();
|
|
81
|
+
const startedAt = clock.monotonic();
|
|
82
|
+
const streak = failureStreak({
|
|
83
|
+
event: 'ultimate schema waiting',
|
|
84
|
+
recoveredEvent: 'ultimate schema applied',
|
|
85
|
+
level: 'warn',
|
|
86
|
+
fields: { deadlineMs },
|
|
87
|
+
});
|
|
88
|
+
const stop = new AbortController();
|
|
89
|
+
// The `accept` phase, the first: the boot is under `holdWhileBooting`'s handlers, so a SIGTERM
|
|
90
|
+
// here is a drain, and this wait is the boot work it must end.
|
|
91
|
+
const unregister = onShutdown('cli:schema-wait', () => stop.abort(), { phase: 'accept' });
|
|
92
|
+
try {
|
|
93
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
94
|
+
const verdict = await check();
|
|
95
|
+
if (verdict.ready) {
|
|
96
|
+
streak.passed();
|
|
97
|
+
return verdict.value;
|
|
98
|
+
}
|
|
99
|
+
const waitedMs = clock.monotonic() - startedAt;
|
|
100
|
+
if (verdict.atOnce === true || deadlineMs === 0) throw verdict.refuse();
|
|
101
|
+
if (waitedMs >= deadlineMs || stop.signal.aborted || isDraining()) {
|
|
102
|
+
throw verdict.refuse(waitedMs);
|
|
103
|
+
}
|
|
104
|
+
streak.failed(verdict.refuse());
|
|
105
|
+
const delay = backoffDelay({
|
|
106
|
+
attempt,
|
|
107
|
+
base: WAIT_BASE_MS,
|
|
108
|
+
max: WAIT_MAX_MS,
|
|
109
|
+
jitter: 'equal',
|
|
110
|
+
random: options.random,
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
// Cut to the deadline: the last read lands ON it, never a whole backoff past it.
|
|
114
|
+
await clock.sleep(Math.min(delay, deadlineMs - waitedMs), stop.signal);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
// The drain's abort ends the wait with the refusal `holdWhileBooting` turns into an exit
|
|
117
|
+
// of `drainExitCode()`; any other rejection is the clock's own, and is rethrown as it came.
|
|
118
|
+
if (!stop.signal.aborted) throw error;
|
|
119
|
+
throw verdict.refuse(clock.monotonic() - startedAt);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
unregister();
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/mcp-errors.ts
CHANGED
|
@@ -403,6 +403,7 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
|
|
|
403
403
|
X_ADVISORY_FLOOR_UNMET: 'bun update source-map-js immutable',
|
|
404
404
|
X_UPGRADE_CODEMODS_PENDING: 'x upgrade --json',
|
|
405
405
|
X_UPGRADE_LOCKED: 'cat .x/upgrade.lock',
|
|
406
|
+
X_APP_MIGRATIONS_UNAPPLIED: 'x db migrate --json',
|
|
406
407
|
};
|
|
407
408
|
|
|
408
409
|
const isCliCode = (code: string): code is CliErrorCode =>
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The scheduler's sampler of the Postgres server's own health (`@ultimat3/db`'s pg stats gauges):
|
|
2
|
+
// one role samples, because these are server facts every pod would read the same of. A real
|
|
3
|
+
// server only — the embedded database is one process's private copy and describes no fleet.
|
|
4
|
+
|
|
5
|
+
import type { PgExecutor, Role } from '@ultimat3/core';
|
|
6
|
+
import { startPostgresStatsGauges } from '@ultimat3/db';
|
|
7
|
+
import type { ServiceMode } from './runtime-bindings';
|
|
8
|
+
|
|
9
|
+
/** The stop, for the role's unwind list; `null` when nothing was started. */
|
|
10
|
+
export function startRolePgStats(
|
|
11
|
+
roles: readonly Role[],
|
|
12
|
+
mode: ServiceMode,
|
|
13
|
+
executor: PgExecutor,
|
|
14
|
+
/** `@ultimat3/db`'s sampler, its own interval; a test hands a recorder, so no timer runs. */
|
|
15
|
+
start: (executor: PgExecutor) => () => Promise<void> = startPostgresStatsGauges,
|
|
16
|
+
): (() => Promise<void>) | null {
|
|
17
|
+
if (!roles.includes('scheduler') || mode !== 'external') return null;
|
|
18
|
+
// The stop itself, never wrapped: it awaits the round in flight, and a wrapper that dropped
|
|
19
|
+
// that promise let the role's unwind close the pool under a sampling query.
|
|
20
|
+
return start(executor);
|
|
21
|
+
}
|
package/src/role-start.ts
CHANGED
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
startMetricsEndpoint,
|
|
39
39
|
whenMetricsPortTaken,
|
|
40
40
|
} from './metrics-endpoint';
|
|
41
|
+
import { startRolePgStats } from './role-pg-stats';
|
|
41
42
|
import { rolesUnderRealtime } from './role-realtime';
|
|
42
43
|
import { startReplicator } from './role-replicator';
|
|
43
44
|
import { type DeviceMount, hostDeviceSockets } from './role-start-devices';
|
|
@@ -429,6 +430,9 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
|
|
|
429
430
|
: null;
|
|
430
431
|
scheduler?.start();
|
|
431
432
|
if (scheduler !== null) started.push(() => scheduler.stop());
|
|
433
|
+
// The server's own health, sampled beside the scheduler on the primary's executor.
|
|
434
|
+
const pgStats = startRolePgStats(selected, options.runtime.services.db.mode, executor);
|
|
435
|
+
if (pgStats !== null) started.push(pgStats);
|
|
432
436
|
|
|
433
437
|
// Last, and only after the transport it publishes to exists: a replicator started ahead of the
|
|
434
438
|
// sync node would decode changes with nothing subscribed to receive them, and the slot it
|
package/src/runtime-queue.ts
CHANGED
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
resetJobsFacade,
|
|
34
34
|
setJobsFacade,
|
|
35
35
|
} from '@ultimat3/jobs';
|
|
36
|
-
import { applyLockedSchema, ensureSchema
|
|
36
|
+
import { applyLockedSchema, ensureSchema } from './framework-schema-apply';
|
|
37
37
|
import { appExtensions } from './migration-extensions';
|
|
38
38
|
import type { DevServices } from './runtime-bindings';
|
|
39
39
|
import type { RuntimeOverrides } from './runtime-overrides';
|
|
@@ -142,9 +142,29 @@ export function startDb(services: DevServices, env: ReplicaEnv): StartedDb {
|
|
|
142
142
|
*/
|
|
143
143
|
export type SchemaMode = 'apply' | 'ensure' | 'verify';
|
|
144
144
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
145
|
+
/** The boot's own facts `'verify'` reads: how long to wait, and what this image ships. */
|
|
146
|
+
interface SchemaBoot {
|
|
147
|
+
readonly root: string;
|
|
148
|
+
/** The env the boot was HANDED — `ULTIMATE_SCHEMA_WAIT_MS` from it, never from `process.env`. */
|
|
149
|
+
readonly env: ReplicaEnv;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function applySchema(client: DevDbClient, mode: SchemaMode, boot: SchemaBoot): Promise<void> {
|
|
153
|
+
// The deadline first: a malformed one is refused before any read, not after a wait.
|
|
154
|
+
if (mode === 'verify') {
|
|
155
|
+
// Behind `await import()`: `ROLE=migrate` and every CLI command reach this module and never
|
|
156
|
+
// verify, so the wait, the ledger verdict and the migrations reader stay off their graphs.
|
|
157
|
+
const [{ verifySchema }, { schemaWaitMsFromEnv }, { readMigrations }] = await Promise.all([
|
|
158
|
+
import('./framework-schema-verify'),
|
|
159
|
+
import('./framework-schema-wait'),
|
|
160
|
+
import('./migrations'),
|
|
161
|
+
]);
|
|
162
|
+
const deadlineMs = schemaWaitMsFromEnv(boot.env);
|
|
163
|
+
// The image's own migrations — the files `ROLE=migrate` of this same image applies — so a role
|
|
164
|
+
// of release N over release N-1's ledger waits, instead of failing on its first new column.
|
|
165
|
+
const shipped = (await readMigrations(boot.root)).map((migration) => migration.id);
|
|
166
|
+
await verifySchema(client, { deadlineMs, shipped });
|
|
167
|
+
} else if (mode === 'ensure') await ensureSchema(client);
|
|
148
168
|
else await applyLockedSchema(client);
|
|
149
169
|
}
|
|
150
170
|
/**
|
|
@@ -182,8 +202,9 @@ async function startJobs(
|
|
|
182
202
|
replica: PostgresClient | undefined,
|
|
183
203
|
overrides: RuntimeOverrides | undefined,
|
|
184
204
|
schema: SchemaMode,
|
|
205
|
+
boot: SchemaBoot,
|
|
185
206
|
): Promise<RunningQueue> {
|
|
186
|
-
await applySchema(client, schema);
|
|
207
|
+
await applySchema(client, schema, boot);
|
|
187
208
|
// Bound to `client`, never the ambient `db()`: the queue and the idempotency reservations stay
|
|
188
209
|
// on the boot's pool whatever transaction is open.
|
|
189
210
|
const executor = dbExecutor(() => client);
|
|
@@ -313,7 +334,7 @@ export async function startQueue(
|
|
|
313
334
|
// Pay the Postgres boot here, so the first request is not the slow one and a broken database
|
|
314
335
|
// fails at boot rather than on some later query.
|
|
315
336
|
await db.ping();
|
|
316
|
-
return await startJobs(db, replica, overrides, schema);
|
|
337
|
+
return await startJobs(db, replica, overrides, schema, { root: services.root, env });
|
|
317
338
|
} catch (error) {
|
|
318
339
|
// `db.ping()` or `startJobs` is where a broken database is supposed to fail. Without this,
|
|
319
340
|
// the caller exits holding the PGlite lock and the ambient accessors, and nothing is left to
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// The web or sync role's own port while it boots: `/healthz` from the process's liveness, `/readyz`
|
|
2
|
+
// 503, every other path 503 — so the pod's startup and liveness probes, which knock on THIS port,
|
|
3
|
+
// see a live pod that is not ready while it waits for the migrate step, never a closed socket that
|
|
4
|
+
// restarts it at the startup probe's budget. `bootRoles` stops it just before the role binds.
|
|
5
|
+
|
|
6
|
+
import type { HealthPayload, Role } from '@ultimat3/core';
|
|
7
|
+
import { markListening, readyzPayload, stringField } from '@ultimat3/core';
|
|
8
|
+
import { rolePorts } from './metrics-endpoint';
|
|
9
|
+
import { livenessPayload } from './runtime-liveness';
|
|
10
|
+
import {
|
|
11
|
+
type ListenerTls,
|
|
12
|
+
ListenerTlsInvalidError,
|
|
13
|
+
TLS_CERT_ENV,
|
|
14
|
+
TLS_KEY_ENV,
|
|
15
|
+
} from './serve-env-tls';
|
|
16
|
+
|
|
17
|
+
export interface BootProbe {
|
|
18
|
+
/** Idempotent, and synchronous: the port is free for the role's listener when this returns. */
|
|
19
|
+
stop(): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface BootProbeInput {
|
|
23
|
+
readonly role: Role;
|
|
24
|
+
/** The app port; the sync role's listener is on `PORT + 1` (`rolePorts`). `0` opens none. */
|
|
25
|
+
readonly port: number;
|
|
26
|
+
readonly hostname: string;
|
|
27
|
+
readonly tls?: ListenerTls;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Seconds a client is told to come back after, while the pod boots. */
|
|
31
|
+
const RETRY_AFTER_S = '5';
|
|
32
|
+
|
|
33
|
+
function answer(payload: HealthPayload, role: Role): Response {
|
|
34
|
+
return Response.json(
|
|
35
|
+
{ state: payload.body.state, ready: payload.body.ready, role },
|
|
36
|
+
{ status: payload.status, headers: { 'cache-control': 'no-store' } },
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** OpenSSL's code alone: its message can quote the input, and the input can be a private key. */
|
|
41
|
+
const OPENSSL_CODE = /^ERR_OSSL_[A-Z0-9_]+$/;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The FIRST place `TLS_CERT` / `TLS_KEY` reach OpenSSL, before `defineHttpConfig` judges them, so
|
|
45
|
+
* a pair it refuses is `X_CONFIG_INVALID` here (both variables and the code, never the bytes)
|
|
46
|
+
* rather than a bare `ERR_OSSL_*` with no fix. Any other failure (a taken port) is the bind's own.
|
|
47
|
+
*/
|
|
48
|
+
function servedWithTls<T>(serve: () => T): T {
|
|
49
|
+
try {
|
|
50
|
+
return serve();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const code = stringField(error, 'code');
|
|
53
|
+
if (code === undefined || !OPENSSL_CODE.test(code)) throw error;
|
|
54
|
+
throw new ListenerTlsInvalidError({
|
|
55
|
+
name: `${TLS_CERT_ENV} or ${TLS_KEY_ENV}`,
|
|
56
|
+
reason: `was refused by OpenSSL (${code}): the pair must be a PEM certificate and its own PEM private key`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `undefined` for the roles whose probes knock on the metrics port — open before any boot work
|
|
63
|
+
* (`serve.ts`) — and for an ephemeral boot (a test), whose real port is not known yet.
|
|
64
|
+
*/
|
|
65
|
+
export function openBootProbe(input: BootProbeInput): BootProbe | undefined {
|
|
66
|
+
const port = rolePorts(input.port, [input.role])[0]?.port;
|
|
67
|
+
if (port === undefined) return undefined;
|
|
68
|
+
const { role } = input;
|
|
69
|
+
const serve = () =>
|
|
70
|
+
Bun.serve({
|
|
71
|
+
port,
|
|
72
|
+
hostname: input.hostname,
|
|
73
|
+
...(input.tls === undefined ? {} : { tls: { cert: input.tls.cert, key: input.tls.key } }),
|
|
74
|
+
fetch(request: Request): Response {
|
|
75
|
+
const path = new URL(request.url).pathname;
|
|
76
|
+
if (path === '/healthz') return answer(livenessPayload(), role);
|
|
77
|
+
if (path === '/readyz') return answer(readyzPayload(), role);
|
|
78
|
+
// Not served from a half-booted process: a request that reached a pod no probe called ready
|
|
79
|
+
// is told to come back, never answered by a schema it cannot read yet.
|
|
80
|
+
return Response.json(
|
|
81
|
+
{ state: 'starting', ready: false, role },
|
|
82
|
+
{ status: 503, headers: { 'cache-control': 'no-store', 'retry-after': RETRY_AFTER_S } },
|
|
83
|
+
);
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
const server = input.tls === undefined ? serve() : servedWithTls(serve);
|
|
87
|
+
const stopListening = markListening(server.url.origin);
|
|
88
|
+
let stopped = false;
|
|
89
|
+
return {
|
|
90
|
+
stop(): void {
|
|
91
|
+
if (stopped) return;
|
|
92
|
+
stopped = true;
|
|
93
|
+
server.stop(true);
|
|
94
|
+
stopListening();
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
package/src/serve-boot.ts
CHANGED
|
@@ -24,6 +24,7 @@ import type { RunningServices } from './runtime-services';
|
|
|
24
24
|
import { releaseOrThrow, startServices } from './runtime-services';
|
|
25
25
|
import type { BootTimeline } from './serve-boot-phases';
|
|
26
26
|
import { bootTimeline } from './serve-boot-phases';
|
|
27
|
+
import { type BootProbe, openBootProbe } from './serve-boot-probe';
|
|
27
28
|
import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
|
|
28
29
|
import { loadDrainConfig, loadHealthConfig } from './serve-drain';
|
|
29
30
|
import { configureReporting, containerBinding, metricsPortFor, portFromEnv } from './serve-env';
|
|
@@ -93,6 +94,10 @@ export async function bootServing(boot: {
|
|
|
93
94
|
readonly metrics: MetricsEndpoint;
|
|
94
95
|
}): Promise<ServedApp> {
|
|
95
96
|
const { options } = boot;
|
|
97
|
+
// The role's own grace FIRST, before the services: the schema wait runs inside them, and a worker
|
|
98
|
+
// SIGTERMed mid-wait sat through web's readiness grace. `app.config.ts`'s `drain` section is
|
|
99
|
+
// applied over this once the app is loaded (`bootRoles`).
|
|
100
|
+
configureLifecycle(lifecycleForRole(boot.role, undefined));
|
|
96
101
|
// Before any service starts: a half-declared pair is refused while there is nothing to unwind.
|
|
97
102
|
const tls = boot.role === 'web' ? await tlsFromEnv(options.env) : undefined;
|
|
98
103
|
// One `boot.phase` line as each step ends, so a slow boot names its slow step (U12).
|
|
@@ -102,11 +107,27 @@ export async function bootServing(boot: {
|
|
|
102
107
|
// tables first, and this boot only verifies the stamp it left (`framework-schema-apply.ts`).
|
|
103
108
|
// The embedded database has no migrate step to have run, so it applies its own.
|
|
104
109
|
const schema = services.db.mode === 'external' ? 'verify' : 'apply';
|
|
110
|
+
// The web or sync role's own port answers its probes from here — alive, not ready — so a pod
|
|
111
|
+
// that waits on the migrate step (`verify`, inside `startServices`) is never restarted by a
|
|
112
|
+
// startup probe knocking on a closed socket. The role's listener takes the port in `bootRoles`.
|
|
113
|
+
const probe = openBootProbe({
|
|
114
|
+
role: boot.role,
|
|
115
|
+
port: options.port ?? portFromEnv(options.env),
|
|
116
|
+
hostname: containerBinding(options.env, options.hostname).hostname,
|
|
117
|
+
...(tls === undefined ? {} : { tls }),
|
|
118
|
+
});
|
|
119
|
+
if (probe !== undefined) boot.acquired.push(() => probe.stop());
|
|
105
120
|
// The role decides whether this boot waits for the bus: only `sync` and the replicator do.
|
|
106
121
|
const runtime = await startServices(services, options.env, options.runtime, schema, [boot.role]);
|
|
107
122
|
boot.acquired.push(() => runtime.stop());
|
|
108
123
|
timeline.phase('services');
|
|
109
|
-
return bootRoles({
|
|
124
|
+
return bootRoles({
|
|
125
|
+
...boot,
|
|
126
|
+
runtime,
|
|
127
|
+
timeline,
|
|
128
|
+
...(tls === undefined ? {} : { tls }),
|
|
129
|
+
...(probe === undefined ? {} : { probe }),
|
|
130
|
+
});
|
|
110
131
|
}
|
|
111
132
|
|
|
112
133
|
/**
|
|
@@ -143,6 +164,8 @@ async function bootRoles(boot: {
|
|
|
143
164
|
readonly timeline: BootTimeline;
|
|
144
165
|
/** `TLS_CERT`/`TLS_KEY`, read by `bootServing`; the web role's listener serves TLS with it. */
|
|
145
166
|
readonly tls?: ListenerTls;
|
|
167
|
+
/** The boot's holder of this role's port (`serve-boot-probe.ts`), freed just before it binds. */
|
|
168
|
+
readonly probe?: BootProbe;
|
|
146
169
|
}): Promise<ServedApp> {
|
|
147
170
|
const { options, role, runtime, acquired, metrics, timeline } = boot;
|
|
148
171
|
// Before the app's modules, because importing one may register a `close` hook, and that phase
|
|
@@ -222,6 +245,8 @@ async function bootRoles(boot: {
|
|
|
222
245
|
const health = await loadHealthConfig(options.root);
|
|
223
246
|
if (health?.readiness !== undefined) configureLifecycle({ readiness: health.readiness });
|
|
224
247
|
const replicaOverride = replicaOverrides(options.runtime, runtime.services.db, options.env);
|
|
248
|
+
// The instant before the role binds the same port: synchronous, so the port is free on return.
|
|
249
|
+
boot.probe?.stop();
|
|
225
250
|
const running = await startRoles({
|
|
226
251
|
roles: [role],
|
|
227
252
|
port,
|
package/src/serve-retire.ts
CHANGED
|
@@ -27,7 +27,7 @@ export interface WorkerRetireOptions {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
export interface WorkerRetire {
|
|
30
|
-
/** The worker the boot started (`null` when it started none) — a signal before this
|
|
30
|
+
/** The worker the boot started (`null` when it started none) — a signal before this drains. */
|
|
31
31
|
adopt(worker: RetiringWorker | null): void;
|
|
32
32
|
/** Give the listener back: a boot that failed, or a hold that is over. */
|
|
33
33
|
disarm(): void;
|
|
@@ -39,7 +39,7 @@ const NOTHING: WorkerRetire = Object.freeze({ adopt: () => undefined, disarm: ()
|
|
|
39
39
|
* Listen for `RETIRE_SIGNAL` NOW, before the boot: Bun's default for an unhandled SIGUSR2 ends the
|
|
40
40
|
* process — except as PID 1 (a container's ENTRYPOINT), where the kernel DROPS a signal with no
|
|
41
41
|
* listener, so a `preStop` that lands before this line runs is lost. The chart's preStop therefore
|
|
42
|
-
* re-sends it every 5 s until PID 1 is gone;
|
|
42
|
+
* re-sends it every 5 s until PID 1 is gone; before the boot hands a worker over it drains at once.
|
|
43
43
|
* One retire per process; a second signal joins it.
|
|
44
44
|
*
|
|
45
45
|
* Exits rather than holds, decided 2026-10-07: the `preStop` has no channel back but PID 1 itself,
|
|
@@ -56,6 +56,7 @@ export function armWorkerRetire(options: WorkerRetireOptions = {}): WorkerRetire
|
|
|
56
56
|
const adopted = new Promise<RetiringWorker | null>((resolve) => {
|
|
57
57
|
adopt = resolve;
|
|
58
58
|
});
|
|
59
|
+
let handedOver = false;
|
|
59
60
|
let retiring = false;
|
|
60
61
|
|
|
61
62
|
const retire = async (): Promise<void> => {
|
|
@@ -96,12 +97,24 @@ export function armWorkerRetire(options: WorkerRetireOptions = {}): WorkerRetire
|
|
|
96
97
|
// At the signal, before the worker is awaited or stopped: the app's `isRetiring()` is how its
|
|
97
98
|
// own code (a heartbeat, a status row) sees a retire that `isDraining()` only shows at the end.
|
|
98
99
|
markRetiring();
|
|
100
|
+
// Before the boot handed a worker over, nothing here holds a job — and a boot waiting on the
|
|
101
|
+
// migrate step may not reach one for minutes. Drain NOW: its `accept` phase ends the schema
|
|
102
|
+
// wait, and `holdWhileBooting` exits `drainExitCode()`. Waiting for `adopt` sat the pod out to
|
|
103
|
+
// the wait's deadline and exited it 1, a crash, on every rollout over a failed migrate.
|
|
104
|
+
if (!handedOver) {
|
|
105
|
+
logger.info('jobs.worker.retired', { signal: RETIRE_SIGNAL, before: 'boot' });
|
|
106
|
+
void finish(RETIRE_SIGNAL);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
99
109
|
// Never rejects: `retire` catches its own failure and always reaches the drain.
|
|
100
110
|
void retire();
|
|
101
111
|
};
|
|
102
112
|
signals.on(RETIRE_SIGNAL, listener);
|
|
103
113
|
return {
|
|
104
|
-
adopt: (worker) =>
|
|
114
|
+
adopt: (worker) => {
|
|
115
|
+
handedOver = true;
|
|
116
|
+
adopt(worker);
|
|
117
|
+
},
|
|
105
118
|
disarm: () => signals.off(RETIRE_SIGNAL, listener),
|
|
106
119
|
};
|
|
107
120
|
}
|