@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.
- package/CLAUDE.md +1 -0
- package/package.json +29 -29
- package/src/app-migrations-verdict.ts +85 -0
- package/src/cmd-db-recount.ts +38 -43
- package/src/cmd-db-spec.ts +3 -2
- package/src/cmd-db-status.ts +80 -0
- package/src/cmd-db.ts +4 -2
- 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/db-client-displace.ts +65 -0
- package/src/db-diagnostics.ts +25 -28
- package/src/db-status.ts +185 -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 +4 -3
- package/src/messages-db.ts +12 -0
- package/src/role-pg-stats.ts +21 -0
- package/src/role-start.ts +4 -0
- package/src/runtime-queue.ts +47 -8
- 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 +14 -1
- package/wiki/Deployment.md +2 -1
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/Scraping.md +20 -0
- package/wiki/Upgrading.md +1 -0
|
@@ -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
|
@@ -143,9 +143,9 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
|
|
|
143
143
|
// The path, not `x dev`: the boot has already refused and rerunning it refuses again. The
|
|
144
144
|
// error's own `fix:` carries the resolved `.x/dev.lock`; this table cannot know the state dir.
|
|
145
145
|
X_DEV_LOCK_UNREADABLE: 'rm .x/dev.lock # then: x dev --json',
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
146
|
+
// `x doctor`, not `x db status`: generation failing is a reachability question, and `x db status`
|
|
147
|
+
// reads the migration ledger only. `x doctor` is already this table's answer for
|
|
148
|
+
// X_DB_STUDIO_FAILED.
|
|
149
149
|
X_DB_GEN_FAILED: 'x doctor --json # cause carries the Postgres error verbatim',
|
|
150
150
|
// Both directions resolve through the same command, and the CAUSE is what differs: one names a
|
|
151
151
|
// declaration the migrations never carried, the other one they carry and nothing declares. The
|
|
@@ -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 =>
|
package/src/messages-db.ts
CHANGED
|
@@ -53,4 +53,16 @@ export const DB_MESSAGES = {
|
|
|
53
53
|
'cli.db.seed.dryRun': '{count} seed(s) would run — nothing written while --dry-run is set',
|
|
54
54
|
'cli.db.seed.failed': '{failed} of {count} seed(s) failed',
|
|
55
55
|
'cli.db.seed.none': 'no seed matched — nothing to run',
|
|
56
|
+
'cli.db.status.current': 'this database is at this build: every shipped migration applied',
|
|
57
|
+
'cli.db.status.behind': '{count} finding(s): this database is not at this build',
|
|
58
|
+
'cli.db.status.framework': 'framework {verdict} — this build {version} ({schema})',
|
|
59
|
+
'cli.db.status.applied': 'applied',
|
|
60
|
+
'cli.db.status.unapplied': 'NOT applied',
|
|
61
|
+
'cli.db.status.newest': 'newest {version} ({schema}) in the stamp',
|
|
62
|
+
'cli.db.status.migrations': 'migrations {shipped} shipped, {applied} applied',
|
|
63
|
+
'cli.db.status.noLedger': 'none (no x_migrations ledger)',
|
|
64
|
+
'cli.db.status.pending': 'pending {ids}',
|
|
65
|
+
'cli.db.status.ahead': 'ahead {ids}',
|
|
66
|
+
'cli.db.status.edited': 'edited {ids} (applied, the file hashes otherwise)',
|
|
67
|
+
'cli.db.status.none': '-',
|
|
56
68
|
} as const;
|
|
@@ -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
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
postgresMeterStore,
|
|
11
11
|
requestDeadlineMs,
|
|
12
12
|
} from '@ultimat3/action';
|
|
13
|
+
import { logger, renderThrowable } from '@ultimat3/core';
|
|
13
14
|
import type { PgliteClient, PostgresClient } from '@ultimat3/db';
|
|
14
15
|
import {
|
|
15
16
|
baseClient,
|
|
@@ -33,7 +34,7 @@ import {
|
|
|
33
34
|
resetJobsFacade,
|
|
34
35
|
setJobsFacade,
|
|
35
36
|
} from '@ultimat3/jobs';
|
|
36
|
-
import { applyLockedSchema, ensureSchema
|
|
37
|
+
import { applyLockedSchema, ensureSchema } from './framework-schema-apply';
|
|
37
38
|
import { appExtensions } from './migration-extensions';
|
|
38
39
|
import type { DevServices } from './runtime-bindings';
|
|
39
40
|
import type { RuntimeOverrides } from './runtime-overrides';
|
|
@@ -92,7 +93,12 @@ export interface RunningQueue {
|
|
|
92
93
|
* neither reports anything. A default here is what let the caller forget; the type is what stops
|
|
93
94
|
* the next one. Exported for the test that proves which environment decides.
|
|
94
95
|
*/
|
|
95
|
-
export function startDb(
|
|
96
|
+
export function startDb(
|
|
97
|
+
services: DevServices,
|
|
98
|
+
env: ReplicaEnv,
|
|
99
|
+
// A seam for the one failure after the primary exists: the standby refused at construction.
|
|
100
|
+
attach: typeof attachReplica = attachReplica,
|
|
101
|
+
): StartedDb {
|
|
96
102
|
const binding = services.db;
|
|
97
103
|
// `DATABASE_POOL_MAX` from the env the boot was HANDED, for `env`'s reason below. Installing a
|
|
98
104
|
// client here means `defaultClient()` — the only other reader — never runs in a served role, so
|
|
@@ -112,7 +118,19 @@ export function startDb(services: DevServices, env: ReplicaEnv): StartedDb {
|
|
|
112
118
|
extensions: () => appExtensions(services.root),
|
|
113
119
|
})
|
|
114
120
|
: postgresClient({ url: binding.url, profile, env });
|
|
115
|
-
|
|
121
|
+
let attached: ReturnType<typeof attachReplica>;
|
|
122
|
+
try {
|
|
123
|
+
attached = attach(client, replicaUrlFor(binding, env), profile);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
// The primary is built and nothing will hold it: close it here, and say so if that fails too,
|
|
126
|
+
// without letting the close's answer replace the error the caller is handed.
|
|
127
|
+
client.close().catch((closeError: unknown) => {
|
|
128
|
+
logger.warn('ultimate db could not close the primary after the replica failed', {
|
|
129
|
+
cause: renderThrowable(closeError),
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
116
134
|
setDbClient(attached.client);
|
|
117
135
|
return { client, replica: attached.replica };
|
|
118
136
|
}
|
|
@@ -142,9 +160,29 @@ export function startDb(services: DevServices, env: ReplicaEnv): StartedDb {
|
|
|
142
160
|
*/
|
|
143
161
|
export type SchemaMode = 'apply' | 'ensure' | 'verify';
|
|
144
162
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
163
|
+
/** The boot's own facts `'verify'` reads: how long to wait, and what this image ships. */
|
|
164
|
+
interface SchemaBoot {
|
|
165
|
+
readonly root: string;
|
|
166
|
+
/** The env the boot was HANDED — `ULTIMATE_SCHEMA_WAIT_MS` from it, never from `process.env`. */
|
|
167
|
+
readonly env: ReplicaEnv;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function applySchema(client: DevDbClient, mode: SchemaMode, boot: SchemaBoot): Promise<void> {
|
|
171
|
+
// The deadline first: a malformed one is refused before any read, not after a wait.
|
|
172
|
+
if (mode === 'verify') {
|
|
173
|
+
// Behind `await import()`: `ROLE=migrate` and every CLI command reach this module and never
|
|
174
|
+
// verify, so the wait, the ledger verdict and the migrations reader stay off their graphs.
|
|
175
|
+
const [{ verifySchema }, { schemaWaitMsFromEnv }, { readMigrations }] = await Promise.all([
|
|
176
|
+
import('./framework-schema-verify'),
|
|
177
|
+
import('./framework-schema-wait'),
|
|
178
|
+
import('./migrations'),
|
|
179
|
+
]);
|
|
180
|
+
const deadlineMs = schemaWaitMsFromEnv(boot.env);
|
|
181
|
+
// The image's own migrations — the files `ROLE=migrate` of this same image applies — so a role
|
|
182
|
+
// of release N over release N-1's ledger waits, instead of failing on its first new column.
|
|
183
|
+
const shipped = (await readMigrations(boot.root)).map((migration) => migration.id);
|
|
184
|
+
await verifySchema(client, { deadlineMs, shipped });
|
|
185
|
+
} else if (mode === 'ensure') await ensureSchema(client);
|
|
148
186
|
else await applyLockedSchema(client);
|
|
149
187
|
}
|
|
150
188
|
/**
|
|
@@ -182,8 +220,9 @@ async function startJobs(
|
|
|
182
220
|
replica: PostgresClient | undefined,
|
|
183
221
|
overrides: RuntimeOverrides | undefined,
|
|
184
222
|
schema: SchemaMode,
|
|
223
|
+
boot: SchemaBoot,
|
|
185
224
|
): Promise<RunningQueue> {
|
|
186
|
-
await applySchema(client, schema);
|
|
225
|
+
await applySchema(client, schema, boot);
|
|
187
226
|
// Bound to `client`, never the ambient `db()`: the queue and the idempotency reservations stay
|
|
188
227
|
// on the boot's pool whatever transaction is open.
|
|
189
228
|
const executor = dbExecutor(() => client);
|
|
@@ -313,7 +352,7 @@ export async function startQueue(
|
|
|
313
352
|
// Pay the Postgres boot here, so the first request is not the slow one and a broken database
|
|
314
353
|
// fails at boot rather than on some later query.
|
|
315
354
|
await db.ping();
|
|
316
|
-
return await startJobs(db, replica, overrides, schema);
|
|
355
|
+
return await startJobs(db, replica, overrides, schema, { root: services.root, env });
|
|
317
356
|
} catch (error) {
|
|
318
357
|
// `db.ping()` or `startJobs` is where a broken database is supposed to fail. Without this,
|
|
319
358
|
// 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
|
}
|