@ultimat3/cli 31.47.1 → 31.49.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 +30 -23
- package/README.md +96 -4
- package/package.json +29 -29
- package/src/api-registration.ts +28 -14
- package/src/app-load.ts +6 -1
- package/src/app-root.ts +7 -1
- package/src/clean-services.ts +142 -0
- package/src/cmd-auth.ts +3 -0
- package/src/cmd-clean-spec.ts +10 -3
- package/src/cmd-clean.ts +23 -9
- package/src/cmd-db-backfill.ts +6 -0
- package/src/cmd-db-branch.ts +10 -4
- package/src/cmd-db-recount.ts +5 -12
- package/src/cmd-db-rollback.ts +77 -0
- package/src/cmd-db-spec.ts +18 -2
- package/src/cmd-db-status.ts +5 -10
- package/src/cmd-db.ts +105 -33
- package/src/cmd-deploy-verify.ts +14 -6
- package/src/cmd-docs-topic.ts +94 -0
- package/src/cmd-docs.ts +15 -1
- package/src/cmd-doctor.ts +109 -41
- package/src/cmd-drill.ts +100 -19
- package/src/cmd-env.ts +30 -8
- package/src/cmd-errors-app.ts +63 -0
- package/src/cmd-errors.ts +50 -14
- package/src/cmd-generate.ts +17 -4
- package/src/cmd-heavy-spec.ts +36 -0
- package/src/cmd-heavy.ts +244 -0
- package/src/cmd-jobs.ts +27 -1
- package/src/cmd-merge-driver-spec.ts +12 -0
- package/src/cmd-merge-driver.ts +95 -0
- package/src/cmd-new.ts +23 -3
- package/src/cmd-policy-spec.ts +9 -1
- package/src/cmd-policy.ts +72 -17
- package/src/cmd-stop.ts +18 -4
- package/src/cmd-tasks-run.ts +87 -0
- package/src/cmd-tasks-spec.ts +10 -3
- package/src/cmd-tasks.ts +8 -5
- package/src/cmd-test.ts +15 -4
- package/src/cmd-upgrade-spec.ts +8 -1
- package/src/cmd-upgrade.ts +32 -5
- package/src/cmd-verify.ts +9 -41
- package/src/codemods/agents-doc-row.ts +73 -0
- package/src/codemods/define-error-leaf.ts +37 -12
- package/src/codemods/docs-many-agents.ts +26 -0
- package/src/codemods/docs-worker-commands.ts +26 -0
- package/src/codemods/index.ts +6 -0
- package/src/codemods/merge-drivers.ts +66 -0
- package/src/command.ts +3 -0
- package/src/db-applied-edits.ts +117 -0
- package/src/db-dev-wire.ts +18 -0
- package/src/db-diagnostics.ts +5 -10
- package/src/db-generate.ts +82 -7
- package/src/db-migrate-pass.ts +51 -0
- package/src/db-migrate-through-dev.ts +209 -0
- package/src/db-rollback-consent.ts +128 -0
- package/src/db-rollback-pass.ts +76 -0
- package/src/db-seed-generate.ts +5 -1
- package/src/db-seed.ts +7 -1
- package/src/deploy-verify-findings.ts +3 -0
- package/src/deploy-verify-grade.ts +3 -0
- package/src/deploy-verify-processes.ts +32 -0
- package/src/dev-boot.ts +3 -0
- package/src/dev-db-migrate.ts +155 -0
- package/src/dev-db-rollback.ts +33 -0
- package/src/dev-db-settled.ts +22 -0
- package/src/dev-lock-errors.ts +78 -0
- package/src/dev-lock-holder-dir.ts +64 -0
- package/src/dev-lock-live.ts +44 -0
- package/src/dev-lock.ts +59 -84
- package/src/dev-policy.ts +11 -8
- package/src/dev-rebuild-schema.ts +116 -13
- package/src/dev-rebuild.ts +13 -4
- package/src/dev-route-table.ts +7 -0
- package/src/dispatch.ts +21 -1
- package/src/doctor-advisory-floors.ts +30 -8
- package/src/doctor-api-listing.ts +114 -0
- package/src/doctor-guarded.ts +41 -0
- package/src/doctor-port.ts +90 -17
- package/src/doctor-probe.ts +36 -5
- package/src/doctor-processes-probe.ts +127 -0
- package/src/doctor-processes.ts +136 -0
- package/src/doctor-warnings.ts +17 -0
- package/src/error-codes-agents.ts +35 -0
- package/src/error-codes-processes.ts +30 -0
- package/src/error-codes-tooling.ts +11 -3
- package/src/error-codes.ts +12 -13
- package/src/errors-suite.ts +27 -0
- package/src/errors.ts +18 -22
- package/src/exec.ts +11 -3
- package/src/exercise-registration.ts +4 -3
- package/src/framework-env.ts +7 -3
- package/src/generate-files.ts +1 -0
- package/src/generate-grant-findings.ts +7 -5
- package/src/generate-grants.ts +9 -8
- package/src/generate-kinds.ts +30 -6
- package/src/generate-roles-file.ts +30 -0
- package/src/generate-slice-policy.ts +3 -3
- package/src/guards.ts +2 -2
- package/src/heavy-cores.ts +51 -0
- package/src/heavy-env.ts +21 -0
- package/src/heavy-errors.ts +54 -0
- package/src/heavy-flock.ts +73 -0
- package/src/heavy-holders.ts +78 -0
- package/src/heavy-ledger.ts +400 -0
- package/src/heavy-memory.ts +67 -0
- package/src/heavy-pressure.ts +104 -0
- package/src/heavy-weights.ts +47 -0
- package/src/heavy.ts +308 -0
- package/src/i18n-registration.ts +22 -2
- package/src/island-harness.ts +2 -2
- package/src/job-budget.ts +4 -2
- package/src/job-registration.ts +64 -8
- package/src/jobs-queue-known.ts +43 -0
- package/src/local-cli.ts +6 -5
- package/src/mcp-errors-agents.ts +20 -0
- package/src/mcp-errors-doctor.ts +27 -0
- package/src/mcp-errors-processes.ts +23 -0
- package/src/mcp-errors.ts +18 -29
- package/src/mcp-host.ts +2 -2
- package/src/merge-driver-catalog.ts +58 -0
- package/src/merge-driver-config.ts +43 -0
- package/src/merge-driver-lines.ts +140 -0
- package/src/merge-state.ts +105 -0
- package/src/messages-db.ts +22 -1
- package/src/messages-processes.ts +13 -0
- package/src/messages-upgrade.ts +6 -0
- package/src/messages.ts +62 -1
- package/src/output-findings.ts +48 -21
- package/src/parse.ts +37 -6
- package/src/policy-facts.ts +38 -21
- package/src/policy-row.ts +99 -0
- package/src/port-pair-free.ts +28 -0
- package/src/registry-lines.ts +110 -0
- package/src/registry.ts +4 -0
- package/src/retain-sweep.ts +1 -1
- package/src/role-replicator.ts +9 -4
- package/src/role-select.ts +86 -0
- package/src/role-start.ts +13 -55
- package/src/role-sync.ts +10 -5
- package/src/runtime-cache-frame.ts +46 -0
- package/src/runtime-cache-ttl.ts +23 -0
- package/src/runtime-cache.ts +56 -18
- package/src/runtime-database-ssl.ts +84 -0
- package/src/runtime-idempotency-scope.ts +16 -2
- package/src/runtime-jobs-share.ts +52 -0
- package/src/runtime-jobs.ts +43 -12
- package/src/runtime-overrides.ts +4 -2
- package/src/runtime-queue.ts +18 -3
- package/src/runtime-services.ts +8 -1
- package/src/schema-drift.ts +19 -2
- package/src/schema-dump-drift.ts +4 -1
- package/src/serve-boot-probe.ts +30 -2
- package/src/serve-boot.ts +11 -1
- package/src/serve-env.ts +39 -3
- package/src/serve.ts +61 -10
- package/src/stop-run-start.ts +12 -0
- package/src/supervise-boot.ts +61 -0
- package/src/supervise-cgroup.ts +84 -0
- package/src/supervise-child.ts +206 -0
- package/src/supervise-count.ts +244 -0
- package/src/supervise-errors.ts +83 -0
- package/src/supervise-facts.ts +40 -0
- package/src/supervise-messages.ts +84 -0
- package/src/supervise-policy.ts +46 -0
- package/src/supervise-pool.ts +10 -0
- package/src/supervise-probe.ts +158 -0
- package/src/supervise-run.ts +54 -0
- package/src/supervise.ts +383 -0
- package/src/templates/generate-purge.ts +6 -6
- package/src/templates/guard-animated-layout-property.ts +2 -2
- package/src/templates/guard-bare-error.ts +1 -1
- package/src/templates/guard-error-declared.ts +2 -2
- package/src/templates/guard-focus-visible.ts +1 -1
- package/src/templates/guard-image-dimensions.ts +2 -2
- package/src/templates/guard-island-mount-clears.ts +1 -1
- package/src/templates/guard-native-confirm.ts +1 -1
- package/src/templates/guard-raw-breakpoint.ts +2 -2
- package/src/templates/guard-raw-colour.ts +2 -2
- package/src/templates/guard-raw-fetch.ts +1 -1
- package/src/templates/guard-raw-interval.ts +1 -1
- package/src/templates/guard-raw-length.ts +3 -3
- package/src/templates/guard-raw-motion.ts +1 -1
- package/src/templates/guard-raw-shadow.ts +1 -1
- package/src/templates/guard-raw-z-index.ts +1 -1
- package/src/templates/guard-released-forms.ts +59 -13
- package/src/templates/guard-repo-await-in-loop.ts +1 -1
- package/src/templates/guard-repo-raw-sql.ts +4 -4
- package/src/templates/guard-repo-unbounded.ts +1 -1
- package/src/templates/guard-runtime-pin.ts +1 -1
- package/src/templates/guard-semantic-interactive.ts +2 -2
- package/src/templates/guard-unbounded-fanout.ts +1 -1
- package/src/templates/guard-undeclared-custom-property.ts +3 -3
- package/src/templates/guard-undefined-style-class.ts +3 -3
- package/src/templates/guard-unzoned-date.ts +3 -3
- package/src/templates/query-slice.ts +82 -0
- package/src/templates/query.ts +76 -30
- package/src/templates/resource-page.ts +3 -2
- package/src/templates/scaffold-bin.ts +2 -0
- package/src/templates/scaffold-claude-agents.ts +9 -6
- package/src/templates/scaffold-claude-commands.ts +7 -1
- package/src/templates/scaffold-claude.ts +4 -4
- package/src/templates/scaffold-container-compose.ts +47 -7
- package/src/templates/scaffold-docs.ts +11 -6
- package/src/templates/scaffold-gitattributes.ts +18 -1
- package/src/templates/scaffold-helm-templates.ts +9 -0
- package/src/templates/scaffold-repo.ts +4 -1
- package/src/templates/scaffold-test-services.ts +33 -11
- package/src/templates/shapes/offline.ts +0 -7
- package/src/templates/shapes/realtime.ts +2 -6
- package/src/templates/sign-in-action-tests.ts +6 -4
- package/src/templates/sign-in-challenge.ts +62 -0
- package/src/templates/sign-in-oidc-mfa.ts +31 -0
- package/src/templates/sign-in-oidc.ts +11 -3
- package/src/templates/sign-in-password.ts +18 -56
- package/src/test-batches.ts +9 -3
- package/src/test-shards.ts +117 -37
- package/src/test-slots.ts +35 -161
- package/src/test-verdict.ts +79 -0
- package/src/test-workers.ts +15 -0
- package/src/upgrade-gate-codemods.ts +5 -3
- package/src/upgrade-gate.ts +19 -1
- package/src/upgrade-merge-drivers.ts +25 -0
- package/src/upgrade-report.ts +18 -4
- package/src/upgrade-scope.ts +62 -0
- package/src/verify-checks.ts +6 -11
- package/src/verify-coverage-run.ts +9 -5
- package/src/verify-deadline.ts +18 -2
- package/src/verify-heavy-steps.ts +26 -0
- package/src/verify-live.ts +38 -14
- package/src/verify-only.ts +67 -0
- package/src/verify-progress.ts +7 -3
- package/src/verify-run.ts +20 -2
- package/src/verify-services-stack.ts +165 -0
- package/src/verify-services.ts +84 -2
- package/src/verify-test-run.ts +9 -9
- package/src/verify-tests.ts +35 -22
- package/src/verify-typecheck.ts +25 -2
- package/wiki/Actions.md +2 -1
- package/wiki/Admin-Dashboard.md +2 -2
- package/wiki/Agents.md +5 -5
- package/wiki/Auth.md +15 -5
- package/wiki/Bare-VM.md +1 -1
- package/wiki/Building-Your-Own-Base.md +15 -2
- package/wiki/CI-Parallel-Gate.md +4 -4
- package/wiki/CLI-Reference.md +127 -48
- package/wiki/Caching-And-Invalidation.md +2 -2
- package/wiki/Client-Navigation.md +1 -1
- package/wiki/Configuration.md +32 -13
- package/wiki/Deployment.md +44 -4
- package/wiki/Entities-And-Migrations.md +5 -1
- package/wiki/FAQ.md +1 -1
- package/wiki/Getting-Started.md +2 -2
- package/wiki/Home.md +2 -1
- package/wiki/I18n.md +5 -3
- package/wiki/Installation.md +12 -11
- package/wiki/Interface-Rules.md +1 -1
- package/wiki/Jobs-And-Workflows.md +24 -4
- package/wiki/Known-Gaps.md +2 -2
- package/wiki/MCP-And-AI.md +8 -5
- package/wiki/Mail.md +1 -1
- package/wiki/Many-Agents.md +127 -0
- package/wiki/Migrations-And-Backfills.md +18 -0
- package/wiki/Notify.md +1 -1
- package/wiki/Observability.md +13 -0
- package/wiki/Queries-And-Live-Queries.md +2 -2
- package/wiki/Realtime.md +10 -1
- package/wiki/Routes-And-Render-Modes.md +1 -1
- package/wiki/Scheduled-Tasks.md +4 -1
- package/wiki/Testing.md +12 -9
- package/wiki/Timezones-And-Dates.md +5 -1
- package/wiki/Troubleshooting.md +1 -0
- package/wiki/Tutorial-01-First-App.md +5 -5
- package/wiki/Tutorial-02-First-Feature.md +1 -1
- package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
- package/wiki/Upgrading.md +37 -0
package/src/serve-boot.ts
CHANGED
|
@@ -30,7 +30,13 @@ import { bootTimeline } from './serve-boot-phases';
|
|
|
30
30
|
import { type BootProbe, openBootProbe } from './serve-boot-probe';
|
|
31
31
|
import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
|
|
32
32
|
import { loadDrainConfig, loadHealthConfig } from './serve-drain';
|
|
33
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
assertRoleDeclared,
|
|
35
|
+
configureReporting,
|
|
36
|
+
containerBinding,
|
|
37
|
+
metricsPortFor,
|
|
38
|
+
portFromEnv,
|
|
39
|
+
} from './serve-env';
|
|
34
40
|
import { type ListenerTls, tlsFromEnv } from './serve-env-tls';
|
|
35
41
|
import { adoptPrebuiltStyles, reportBootBuilds, watchBootBuilds } from './serve-prebuilt';
|
|
36
42
|
import type { ServedApp, ServeOptions } from './serve-types';
|
|
@@ -97,6 +103,9 @@ export async function bootServing(boot: {
|
|
|
97
103
|
readonly metrics: MetricsEndpoint;
|
|
98
104
|
}): Promise<ServedApp> {
|
|
99
105
|
const { options } = boot;
|
|
106
|
+
// Before anything is started or created: a role `app.config.ts` does not list is refused while
|
|
107
|
+
// there is nothing to unwind but the scrape listener.
|
|
108
|
+
assertRoleDeclared(boot.role, await loadAppConfig(options.root));
|
|
100
109
|
// The role's own grace FIRST, before the services: the schema wait runs inside them, and a worker
|
|
101
110
|
// SIGTERMed mid-wait sat through web's readiness grace. `app.config.ts`'s `drain` section is
|
|
102
111
|
// applied over this once the app is loaded (`bootRoles`).
|
|
@@ -117,6 +126,7 @@ export async function bootServing(boot: {
|
|
|
117
126
|
role: boot.role,
|
|
118
127
|
port: options.port ?? portFromEnv(options.env),
|
|
119
128
|
hostname: containerBinding(options.env, options.hostname).hostname,
|
|
129
|
+
env: options.env,
|
|
120
130
|
...(tls === undefined ? {} : { tls }),
|
|
121
131
|
});
|
|
122
132
|
if (probe !== undefined) boot.acquired.push(() => probe.stop());
|
package/src/serve-env.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// What a container's environment decides about a boot: which role
|
|
2
|
-
// and where errors are reported. Split from `serve.ts`, which re-exports every name here.
|
|
1
|
+
// What a container's environment decides about a boot: which role (and whether the app declares
|
|
2
|
+
// it), which port, which interface, and where errors are reported. Split from `serve.ts`, which re-exports every name here.
|
|
3
3
|
|
|
4
|
-
import type { ErrorReporter, Role } from '@ultimat3/core';
|
|
4
|
+
import type { AppConfig, ErrorReporter, Role } from '@ultimat3/core';
|
|
5
5
|
import {
|
|
6
|
+
ConfigInvalidError,
|
|
6
7
|
chainErrorReporters,
|
|
7
8
|
configureErrorReporting,
|
|
8
9
|
errorReportersOf,
|
|
@@ -12,6 +13,7 @@ import {
|
|
|
12
13
|
isSentryErrorReporter,
|
|
13
14
|
logger,
|
|
14
15
|
ROLES,
|
|
16
|
+
renderFixShellArg,
|
|
15
17
|
sentryErrorReporter,
|
|
16
18
|
UltimateError,
|
|
17
19
|
} from '@ultimat3/core';
|
|
@@ -64,6 +66,40 @@ export function roleFromEnv(env: Env): Role {
|
|
|
64
66
|
return role;
|
|
65
67
|
}
|
|
66
68
|
|
|
69
|
+
/**
|
|
70
|
+
* May this app run `role`? The ONE answer the container's `ROLE` (`assertRoleDeclared`) and
|
|
71
|
+
* `x dev`'s selection (`rolesDeclaredForDev`, `role-select.ts`) both ask, by the rule below.
|
|
72
|
+
*/
|
|
73
|
+
export function roleDeclared(role: Role, config: AppConfig | undefined): boolean {
|
|
74
|
+
return config === undefined || role === 'migrate' || config.roles.includes(role);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Throws `X_CONFIG_INVALID` when `role` is absent from `config.roles`. Unset, `roles` is every
|
|
79
|
+
* role (core's default), so an app that never wrote the key boots each one as it always did; so
|
|
80
|
+
* does a root with no `app.config.ts`. `migrate` is never refused: it is the release phase — run
|
|
81
|
+
* once, then exit — not a process the app "runs", and an app listing `['web', 'worker']` still has
|
|
82
|
+
* migrations to apply.
|
|
83
|
+
*/
|
|
84
|
+
export function assertRoleDeclared(role: Role, config: AppConfig | undefined): void {
|
|
85
|
+
if (roleDeclared(role, config)) return;
|
|
86
|
+
if (config === undefined) return;
|
|
87
|
+
const declared = config.roles.map((name) => `'${name}'`);
|
|
88
|
+
// Members of core's closed `ROLES` set (`defineConfig` refused the rest, `roleFromEnv` the
|
|
89
|
+
// env's), screened all the same: a fix is pasted, and the guard reads the call, not the proof.
|
|
90
|
+
const runnable = config.roles.find((name) => name !== 'migrate');
|
|
91
|
+
const roles = `roles: [${[...declared, `'${role}'`].join(', ')}]`;
|
|
92
|
+
throw new ConfigInvalidError({
|
|
93
|
+
cause: `ROLE=${role} is not a role this app declares: roles in app.config.ts lists ${config.roles.join(', ')}`,
|
|
94
|
+
// `roles: ['migrate']` declares no process to serve: the edit is then the only remedy.
|
|
95
|
+
fix:
|
|
96
|
+
runnable === undefined
|
|
97
|
+
? `defineConfig({ ${roles} }) // in app.config.ts: migrate is the release phase, never a serving process`
|
|
98
|
+
: `ROLE=${renderFixShellArg(runnable, '<role>')} bun apps/web/server.ts # a declared role — or declare this one in app.config.ts: ${roles}`,
|
|
99
|
+
meta: { key: 'roles', role, declared: [...config.roles] },
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
67
103
|
/**
|
|
68
104
|
* `Number.parseInt` would read `80abc` as 80, and `Number` reads `0x1F90` as 8080 and `8e3` as
|
|
69
105
|
* 8000, so the whole string has to be decimal digits — a port spelled any other way is a deploy
|
package/src/serve.ts
CHANGED
|
@@ -7,7 +7,12 @@
|
|
|
7
7
|
// production-shaped decisions live here: which role, which port, and which interface — every one by
|
|
8
8
|
// default, because a container is reached through a port mapping.
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
assertNoDevSecretsOutsideLocal,
|
|
12
|
+
frameworkVersion,
|
|
13
|
+
logger,
|
|
14
|
+
supervisedChild,
|
|
15
|
+
} from '@ultimat3/core';
|
|
11
16
|
import { assertNoSchemaDrift, checkDrift, migrate } from '@ultimat3/db';
|
|
12
17
|
import { loadAppRuntime } from './app-runtime';
|
|
13
18
|
import { acceptCreatedTables } from './db-accept-created';
|
|
@@ -20,6 +25,7 @@ import { containerBinding, metricsPortFor, portFromEnv, roleFromEnv } from './se
|
|
|
20
25
|
import type { MigratedApp, ServedApp, ServeOptions, StartedApp } from './serve-types';
|
|
21
26
|
|
|
22
27
|
export {
|
|
28
|
+
assertRoleDeclared,
|
|
23
29
|
CONTAINER_BINDING,
|
|
24
30
|
configureReporting,
|
|
25
31
|
containerBinding,
|
|
@@ -135,7 +141,22 @@ export async function withAppRuntime(options: ServeOptions): Promise<ServeOption
|
|
|
135
141
|
return runtime === undefined ? options : { ...options, runtime };
|
|
136
142
|
}
|
|
137
143
|
|
|
138
|
-
export
|
|
144
|
+
export function serveApp(input: ServeOptions): Promise<ServedApp> {
|
|
145
|
+
return serveAppBound(input);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Where a supervised child's own scrape listener lives: loopback, a port the kernel picks. */
|
|
149
|
+
const CHILD_METRICS = { port: 0, hostname: '127.0.0.1' } as const;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* `serveApp`, telling `onBound` the scrape listener's base once the roles are up — what a
|
|
153
|
+
* supervised child reports as `ready`. A child's listener is loopback on an ephemeral port: the
|
|
154
|
+
* supervisor owns `METRICS_PORT` for the container and merges each child's scrape behind it.
|
|
155
|
+
*/
|
|
156
|
+
async function serveAppBound(
|
|
157
|
+
input: ServeOptions,
|
|
158
|
+
onBound?: (metricsUrl: string) => void,
|
|
159
|
+
): Promise<ServedApp> {
|
|
139
160
|
// FIRST, before any service starts: a production process on a key this framework publishes is
|
|
140
161
|
// refused, rather than reported by `x doctor` and served anyway (plan 101, slices 01 e and 12 h).
|
|
141
162
|
// The storage twin is `startStorage`'s own `LocalDiskUnsafeError`, one step later, where the
|
|
@@ -147,9 +168,12 @@ export async function serveApp(input: ServeOptions): Promise<ServedApp> {
|
|
|
147
168
|
// so a cold pod answers `/metrics` (and the chart's startup probe on it) while it boots. It was
|
|
148
169
|
// opened inside `startRoles`, after all of that, so `_helpers.tpl`'s "FIRST" was not true.
|
|
149
170
|
const port = options.port ?? portFromEnv(options.env);
|
|
171
|
+
const child = supervisedChild(options.env) !== undefined;
|
|
150
172
|
const metrics = startMetricsEndpoint({
|
|
151
|
-
port: metricsPortFor(options.env, port, options.metricsPort),
|
|
152
|
-
hostname:
|
|
173
|
+
port: child ? CHILD_METRICS.port : metricsPortFor(options.env, port, options.metricsPort),
|
|
174
|
+
hostname: child
|
|
175
|
+
? CHILD_METRICS.hostname
|
|
176
|
+
: containerBinding(options.env, options.hostname).hostname,
|
|
153
177
|
role,
|
|
154
178
|
// Opened before the roles are, so the check `startRoles` makes is made here: adopted, the
|
|
155
179
|
// listener is never re-checked, and one on the web or sync port would take it first.
|
|
@@ -162,7 +186,9 @@ export async function serveApp(input: ServeOptions): Promise<ServedApp> {
|
|
|
162
186
|
// exits, and the services and the role boot are ~240 modules it never calls
|
|
163
187
|
// (`serve-graph.test.ts` pins the count each role is left with).
|
|
164
188
|
const { bootServing } = await import('./serve-boot');
|
|
165
|
-
|
|
189
|
+
const app = await bootServing({ options, role, acquired, metrics });
|
|
190
|
+
onBound?.(metrics.url);
|
|
191
|
+
return app;
|
|
166
192
|
} catch (error) {
|
|
167
193
|
await releaseBoot(acquired);
|
|
168
194
|
throw error;
|
|
@@ -179,6 +205,18 @@ export async function runRole(input: ServeOptions): Promise<StartedApp> {
|
|
|
179
205
|
// always going to fail creates nothing under it — the same order `resolveServices` is held to.
|
|
180
206
|
const role = input.role ?? roleFromEnv(input.env);
|
|
181
207
|
const options = await withAppRuntime(input);
|
|
208
|
+
// How many processes this container runs (`ULTIMATE_PROCESSES`), decided once, by the process
|
|
209
|
+
// the platform started — never by a child it spawned (`ULTIMATE_CHILD`), which serves as one.
|
|
210
|
+
// More than one: this process supervises and never boots the app itself.
|
|
211
|
+
if (supervisedChild(options.env) === undefined) {
|
|
212
|
+
const boot = await import('./supervise-boot');
|
|
213
|
+
const count = await boot.processCountFor(options, role);
|
|
214
|
+
boot.logProcessCount(count, role);
|
|
215
|
+
if (count.count > 1) {
|
|
216
|
+
const { runSupervised } = await import('./supervise-run');
|
|
217
|
+
process.exit(await runSupervised(options, role, count.count));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
182
220
|
if (role === 'migrate') {
|
|
183
221
|
const migrated = await runMigrations({ ...options, role });
|
|
184
222
|
// The release phase has one channel — the exit code — so drift is thrown here rather than
|
|
@@ -200,16 +238,29 @@ export async function runRole(input: ServeOptions): Promise<StartedApp> {
|
|
|
200
238
|
// while the pod still boots. The retire ends in the same drain, so the same hold exits 0.
|
|
201
239
|
// Behind `await import()`, as the serving graph is: `ROLE=migrate` never loads it.
|
|
202
240
|
const retire = role === 'worker' ? (await import('./serve-retire')).armWorkerRetire() : undefined;
|
|
241
|
+
// A supervised child's link, before the boot as the drain's handlers are: a SIGTERM during the
|
|
242
|
+
// boot is acknowledged too, and a supervisor that dies mid-boot still takes this child with it.
|
|
243
|
+
const link =
|
|
244
|
+
supervisedChild(options.env) === undefined
|
|
245
|
+
? undefined
|
|
246
|
+
: (await import('./supervise-child')).linkToSupervisor(options.env);
|
|
203
247
|
let booted: BootedHold<ServedApp>;
|
|
204
248
|
try {
|
|
205
|
-
booted = await holdWhileBooting(
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
249
|
+
booted = await holdWhileBooting(
|
|
250
|
+
'serve',
|
|
251
|
+
() => serveAppBound({ ...options, role }, (metricsUrl) => link?.ready(metricsUrl)),
|
|
252
|
+
{
|
|
253
|
+
exit: (code) => {
|
|
254
|
+
retire?.disarm();
|
|
255
|
+
link?.gone(code);
|
|
256
|
+
process.exit(code);
|
|
257
|
+
},
|
|
209
258
|
},
|
|
210
|
-
|
|
259
|
+
);
|
|
211
260
|
} catch (error) {
|
|
212
261
|
retire?.disarm();
|
|
262
|
+
// Said as this child, and `fatal` for a refusal no restart can fix (`supervise-child.ts`).
|
|
263
|
+
link?.refused(error);
|
|
213
264
|
throw error;
|
|
214
265
|
}
|
|
215
266
|
const { app, hold } = booted;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The one "stop the holder, run it alone, start again" fix line: what a command that needs the
|
|
2
|
+
// embedded database to itself is told beside a live `x dev`. One builder, one quoting rule.
|
|
3
|
+
|
|
4
|
+
import { quoteArg } from './shell-quote';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `x stop --json && x <command> && x dev`. `x stop`, not `kill <pid>`: a kill returns before the
|
|
8
|
+
* drain ends and the next boot refuses. `command` is the refused command's own words, each quoted
|
|
9
|
+
* on its own (`quoteArg`), never spliced; a caller's trailing `# remark` goes after the line.
|
|
10
|
+
*/
|
|
11
|
+
export const stopRunStartFix = (command: readonly string[]): string =>
|
|
12
|
+
['x', 'stop', '--json', '&&', 'x', ...command.map(quoteArg), '&&', 'x', 'dev'].join(' ');
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// How many processes `runRole` runs, as the process the platform started decides it: the facts
|
|
2
|
+
// the count depends on, read here, and the count with the clamp that bound it, said in one boot
|
|
3
|
+
// line. Running the children is `supervise-run.ts`, loaded only when the count is more than one.
|
|
4
|
+
|
|
5
|
+
// why: one synchronous stat of a directory; `Bun.file().exists()` answers for files only.
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
// why: Bun ships no path-join primitive.
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import type { Role } from '@ultimat3/core';
|
|
10
|
+
import { logger, tryResolveEnvironment } from '@ultimat3/core';
|
|
11
|
+
import { PREBUILT_REGISTRY_DIR } from './serve-prebuilt-paths';
|
|
12
|
+
import type { ServeOptions } from './serve-types';
|
|
13
|
+
import { readCgroup } from './supervise-cgroup';
|
|
14
|
+
import type { ProcessCount } from './supervise-count';
|
|
15
|
+
import { ignoredRequest, readProcessesRequest, resolveProcessCount } from './supervise-count';
|
|
16
|
+
import { containerPool } from './supervise-pool';
|
|
17
|
+
|
|
18
|
+
export function processCountFor(options: ServeOptions, role: Role): Promise<ProcessCount> {
|
|
19
|
+
return resolveProcessCount({
|
|
20
|
+
env: options.env,
|
|
21
|
+
role,
|
|
22
|
+
platform: process.platform,
|
|
23
|
+
environment: tryResolveEnvironment({ env: options.env }),
|
|
24
|
+
cgroup: () => readCgroup(),
|
|
25
|
+
parallelism: () => navigator.hardwareConcurrency,
|
|
26
|
+
pool: () => containerPool(options, role),
|
|
27
|
+
// Behind `await import()`: the app config and the cache and realtime packages it reads are
|
|
28
|
+
// asked only when the CPU budget already allows more than one process.
|
|
29
|
+
shared: async () => (await import('./supervise-facts')).sharedStateFacts(options, role),
|
|
30
|
+
prebuilt: async () => existsSync(join(options.root, PREBUILT_REGISTRY_DIR)),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `ultimate processes` — `count=`, `binding=` and each clamp: a fixed vocabulary a script may parse. */
|
|
35
|
+
export function logProcessCount(count: ProcessCount, role: Role): void {
|
|
36
|
+
logger.info('ultimate processes', {
|
|
37
|
+
role,
|
|
38
|
+
count: count.count,
|
|
39
|
+
requested: count.requested,
|
|
40
|
+
binding: count.binding,
|
|
41
|
+
...count.clamps,
|
|
42
|
+
});
|
|
43
|
+
logNote(count.note);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `x dev` runs every role in one process whatever `ULTIMATE_PROCESSES` says (it has its own
|
|
48
|
+
* restarting supervisor); a count asked of it is said once, never refused. An invalid value is
|
|
49
|
+
* refused as a container's boot refuses it: the `.env` that carries it would stop production too.
|
|
50
|
+
*/
|
|
51
|
+
export function logDevProcesses(env: ServeOptions['env']): void {
|
|
52
|
+
logNote(ignoredRequest(readProcessesRequest(env), 'x dev').note);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function logNote(note: ProcessCount['note']): void {
|
|
56
|
+
if (note === undefined) return;
|
|
57
|
+
logger[note.level](note.msg, {
|
|
58
|
+
cause: note.cause,
|
|
59
|
+
...(note.fix === undefined ? {} : { fix: note.fix }),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// What the container's cgroup DECLARES: a CPU budget and a memory ceiling. Read from the files, not
|
|
2
|
+
// from `navigator.hardwareConcurrency`, because that answers every host core when no quota is set
|
|
3
|
+
// (`cpu.max = max`), and "undeclared" must read as one process, never as the node's core count.
|
|
4
|
+
|
|
5
|
+
/** A file's text, or `undefined` when it does not exist or cannot be read: a fact, not a failure. */
|
|
6
|
+
export type ReadText = (path: string) => Promise<string | undefined>;
|
|
7
|
+
|
|
8
|
+
export const readText: ReadText = async (path) => {
|
|
9
|
+
try {
|
|
10
|
+
const file = Bun.file(path);
|
|
11
|
+
return (await file.exists()) ? await file.text() : undefined;
|
|
12
|
+
} catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const CGROUP_PATHS = Object.freeze({
|
|
18
|
+
cpuMax: '/sys/fs/cgroup/cpu.max',
|
|
19
|
+
cfsQuota: '/sys/fs/cgroup/cpu/cpu.cfs_quota_us',
|
|
20
|
+
cfsPeriod: '/sys/fs/cgroup/cpu/cpu.cfs_period_us',
|
|
21
|
+
memoryMax: '/sys/fs/cgroup/memory.max',
|
|
22
|
+
memoryLimit: '/sys/fs/cgroup/memory/memory.limit_in_bytes',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** cgroup v1 writes "unlimited" as the largest page-aligned 63-bit value; anything this big is none. */
|
|
26
|
+
const V1_UNLIMITED_FLOOR = 2 ** 62;
|
|
27
|
+
|
|
28
|
+
const positive = (text: string | undefined): number | undefined => {
|
|
29
|
+
if (text === undefined) return undefined;
|
|
30
|
+
const value = Number(text.trim());
|
|
31
|
+
return Number.isFinite(value) && value > 0 ? value : undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Whole CPUs a quota buys, floored, at least 1. `--cpus=1.5` is 1: the safe answer. */
|
|
35
|
+
const wholeCpus = (quota: number, period: number): number =>
|
|
36
|
+
Math.max(1, Math.floor(quota / period));
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* cgroup v2 `cpu.max` (`"<quota> <period>"` or `"max <period>"`), else v1's CFS pair (quota `-1` is
|
|
40
|
+
* none). `undefined` = no budget declared. A v2 file saying `max` is the answer: v1 is not asked.
|
|
41
|
+
*/
|
|
42
|
+
export function cpuBudget(
|
|
43
|
+
cpuMax: string | undefined,
|
|
44
|
+
cfsQuota?: string,
|
|
45
|
+
cfsPeriod?: string,
|
|
46
|
+
): number | undefined {
|
|
47
|
+
if (cpuMax !== undefined) {
|
|
48
|
+
const [quota, period] = cpuMax.trim().split(/\s+/);
|
|
49
|
+
const q = positive(quota);
|
|
50
|
+
const p = positive(period);
|
|
51
|
+
return q === undefined || p === undefined ? undefined : wholeCpus(q, p);
|
|
52
|
+
}
|
|
53
|
+
const q = positive(cfsQuota);
|
|
54
|
+
const p = positive(cfsPeriod);
|
|
55
|
+
return q === undefined || p === undefined ? undefined : wholeCpus(q, p);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Bytes the container may hold: v2 `memory.max` (`max` is none), else v1's limit. */
|
|
59
|
+
export function memoryCeiling(memoryMax: string | undefined, v1Limit?: string): number | undefined {
|
|
60
|
+
if (memoryMax !== undefined) return positive(memoryMax);
|
|
61
|
+
const limit = positive(v1Limit);
|
|
62
|
+
return limit === undefined || limit >= V1_UNLIMITED_FLOOR ? undefined : limit;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface CgroupFacts {
|
|
66
|
+
/** Whole CPUs the quota declares; `undefined` when none is. */
|
|
67
|
+
readonly cpus: number | undefined;
|
|
68
|
+
/** The memory ceiling in bytes; `undefined` when unlimited. */
|
|
69
|
+
readonly memoryBytes: number | undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function readCgroup(read: ReadText = readText): Promise<CgroupFacts> {
|
|
73
|
+
const [cpuMax, cfsQuota, cfsPeriod, memoryMax, memoryLimit] = await Promise.all([
|
|
74
|
+
read(CGROUP_PATHS.cpuMax),
|
|
75
|
+
read(CGROUP_PATHS.cfsQuota),
|
|
76
|
+
read(CGROUP_PATHS.cfsPeriod),
|
|
77
|
+
read(CGROUP_PATHS.memoryMax),
|
|
78
|
+
read(CGROUP_PATHS.memoryLimit),
|
|
79
|
+
]);
|
|
80
|
+
return {
|
|
81
|
+
cpus: cpuBudget(cpuMax, cfsQuota, cfsPeriod),
|
|
82
|
+
memoryBytes: memoryCeiling(memoryMax, memoryLimit),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// A supervised child's half of the link: say `ready` once booted and bound, acknowledge a drain
|
|
2
|
+
// the moment its handler runs, drain on the supervisor's message, and leave when the supervisor
|
|
3
|
+
// is gone — IPC `disconnect` first, a poll of the ORIGINAL ppid behind it (an orphan is re-parented
|
|
4
|
+
// to the nearest subreaper, not to pid 1: measured), so a SIGKILLed supervisor leaves no orphan.
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
DRAIN_TIMEOUT_EXIT_CODE,
|
|
8
|
+
drain,
|
|
9
|
+
drainDeadlineMs,
|
|
10
|
+
isUltimateError,
|
|
11
|
+
logger,
|
|
12
|
+
readinessGraceMs,
|
|
13
|
+
renderThrowable,
|
|
14
|
+
supervisedChild,
|
|
15
|
+
} from '@ultimat3/core';
|
|
16
|
+
import type { ChildMessage, DrainSignal } from './supervise-messages';
|
|
17
|
+
import { PROCESS_MESSAGE_TYPE, readDrainMessage } from './supervise-messages';
|
|
18
|
+
|
|
19
|
+
/** How often the ppid is asked; `disconnect` usually answers first (~20 ms, measured). */
|
|
20
|
+
export const PARENT_POLL_MS = 1_000;
|
|
21
|
+
/** Past its own drain bound, a child whose supervisor is gone exits whatever the drain did. */
|
|
22
|
+
export const ORPHAN_EXIT_SLACK_MS = 2_000;
|
|
23
|
+
|
|
24
|
+
type Release = () => void;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Boot refusals that are a function of the image and its environment alone: a restart of the same
|
|
28
|
+
* child meets each again, unchanged, so the supervisor stops at the first and the container exits 1
|
|
29
|
+
* with the child's own code and fix. Never what can heal by itself while the child waits — a
|
|
30
|
+
* database, Redis or NATS still starting, migrations the migrate job has not applied yet
|
|
31
|
+
* (`X_APP_MIGRATIONS_UNAPPLIED`, `X_FRAMEWORK_SCHEMA_UNAPPLIED`), a port still held, a pool
|
|
32
|
+
* timeout — nor state outside the image (`X_DB_ROW_SECURITY_BYPASSED`: a grant;
|
|
33
|
+
* `X_SEAL_KEY_UNKNOWN`: rows), nor `X_APP_MODULE_LOAD_FAILED`, which wraps whatever an app module
|
|
34
|
+
* threw at import.
|
|
35
|
+
*/
|
|
36
|
+
export const FATAL_BOOT_CODES: ReadonlySet<string> = new Set([
|
|
37
|
+
// The environment: a required variable missing or malformed, a value no deploy names.
|
|
38
|
+
'X_ENV_MISSING',
|
|
39
|
+
'X_ROLE_UNKNOWN',
|
|
40
|
+
'X_ROLE_INVALID',
|
|
41
|
+
'X_ENVIRONMENT_INVALID',
|
|
42
|
+
'X_PORT_INVALID',
|
|
43
|
+
'X_CURSOR_SECRET_DEV',
|
|
44
|
+
// `app.config.ts`, the TLS pair, a role the config does not list, a database a newer major
|
|
45
|
+
// stamped.
|
|
46
|
+
'X_CONFIG_INVALID',
|
|
47
|
+
// The committed secrets against the key the environment holds.
|
|
48
|
+
'X_SEAL_KEY_MISSING',
|
|
49
|
+
'X_SECRETS_KEY_MISSING',
|
|
50
|
+
'X_SECRETS_KEY_INVALID',
|
|
51
|
+
'X_SECRETS_KEY_MISMATCH',
|
|
52
|
+
'X_SECRETS_FILE_INVALID',
|
|
53
|
+
'X_SECRETS_TAMPERED',
|
|
54
|
+
// What the image holds: an import that resolves nowhere, an app that registers nothing, a role
|
|
55
|
+
// missing what the manifest names, a queue, disk or store the app never declared.
|
|
56
|
+
'X_APP_IMPORT_UNRESOLVED',
|
|
57
|
+
'X_APP_EMPTY',
|
|
58
|
+
'X_ROLE_LOAD_INCOMPLETE',
|
|
59
|
+
'X_WORKER_QUEUE_UNKNOWN',
|
|
60
|
+
'X_STORAGE_DISK_UNKNOWN',
|
|
61
|
+
'X_IDEMPOTENCY_NOT_SHARED',
|
|
62
|
+
'X_NOTIFY_STORE_MISSING',
|
|
63
|
+
// The count itself and per-process state under it.
|
|
64
|
+
'X_PROCESSES_INVALID',
|
|
65
|
+
'X_PROCESSES_ROLE_SINGLETON',
|
|
66
|
+
'X_PROCESSES_UNSHARED_STATE',
|
|
67
|
+
'X_PROCESSES_OVER_POOL',
|
|
68
|
+
'X_PROCESSES_UNBALANCED',
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
/** Every process seam the link touches, injected so a test drives it without a second process. */
|
|
72
|
+
export interface ChildLinkHost {
|
|
73
|
+
send(message: ChildMessage): void;
|
|
74
|
+
onMessage(listener: (message: unknown) => void): Release;
|
|
75
|
+
onDisconnect(listener: () => void): Release;
|
|
76
|
+
onSignal(signal: DrainSignal, listener: () => void): Release;
|
|
77
|
+
/** Delivers `signal` to this process, so a drain by message takes the signal's own path. */
|
|
78
|
+
raise(signal: DrainSignal): void;
|
|
79
|
+
ppid(): number;
|
|
80
|
+
every(ms: number, run: () => void): Release;
|
|
81
|
+
/** A timer that is NOT unref'd: the one that must still fire when everything else is stuck. */
|
|
82
|
+
after(ms: number, run: () => void): void;
|
|
83
|
+
drain(reason: string): Promise<void>;
|
|
84
|
+
exit(code: number): void;
|
|
85
|
+
budgetMs(): number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const processHost: ChildLinkHost = {
|
|
89
|
+
send: (message) => {
|
|
90
|
+
try {
|
|
91
|
+
process.send?.(message);
|
|
92
|
+
} catch {
|
|
93
|
+
// The channel closed under us: the supervisor is gone, and `disconnect` says so.
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
onMessage: (listener) => {
|
|
97
|
+
process.on('message', listener);
|
|
98
|
+
return () => process.off('message', listener);
|
|
99
|
+
},
|
|
100
|
+
onDisconnect: (listener) => {
|
|
101
|
+
process.on('disconnect', listener);
|
|
102
|
+
return () => process.off('disconnect', listener);
|
|
103
|
+
},
|
|
104
|
+
onSignal: (signal, listener) => {
|
|
105
|
+
process.on(signal, listener);
|
|
106
|
+
return () => process.off(signal, listener);
|
|
107
|
+
},
|
|
108
|
+
raise: (signal) => process.kill(process.pid, signal),
|
|
109
|
+
ppid: () => process.ppid,
|
|
110
|
+
every: (ms, run) => {
|
|
111
|
+
const timer = setInterval(run, ms);
|
|
112
|
+
// Never what keeps a child alive: its hold is.
|
|
113
|
+
timer.unref();
|
|
114
|
+
return () => clearInterval(timer);
|
|
115
|
+
},
|
|
116
|
+
after: (ms, run) => {
|
|
117
|
+
setTimeout(run, ms);
|
|
118
|
+
},
|
|
119
|
+
drain,
|
|
120
|
+
exit: (code) => process.exit(code),
|
|
121
|
+
// What core's drain is bounded by: the readiness grace runs first, outside the deadline.
|
|
122
|
+
budgetMs: () => readinessGraceMs() + drainDeadlineMs(),
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export interface ChildLink {
|
|
126
|
+
readonly index: number;
|
|
127
|
+
readonly count: number;
|
|
128
|
+
/** Booted, and the shared port bound: `metricsUrl` is this child's loopback scrape base. */
|
|
129
|
+
ready(metricsUrl: string): void;
|
|
130
|
+
/** Leaving with `code` — said before the exit, which the supervisor reads anyway. */
|
|
131
|
+
gone(code: number): void;
|
|
132
|
+
/** A refusal no restart can fix: the supervisor stops restarting and the container exits 1. */
|
|
133
|
+
fatal(code: string): void;
|
|
134
|
+
/**
|
|
135
|
+
* The boot threw: one `error` line through the logger, so it carries this child's index (Bun's
|
|
136
|
+
* own print of the uncaught throw names none, and the crash loop's fix points at this line);
|
|
137
|
+
* `fatal` too when it is a refusal only a redeploy changes (`FATAL_BOOT_CODES`).
|
|
138
|
+
*/
|
|
139
|
+
refused(error: unknown): void;
|
|
140
|
+
release(): void;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** `undefined` for a process no supervisor started (`ULTIMATE_CHILD` unset). */
|
|
144
|
+
export function linkToSupervisor(
|
|
145
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
146
|
+
host: ChildLinkHost = processHost,
|
|
147
|
+
): ChildLink | undefined {
|
|
148
|
+
const place = supervisedChild(env);
|
|
149
|
+
if (place === undefined) return undefined;
|
|
150
|
+
const originalPpid = host.ppid();
|
|
151
|
+
let acked = false;
|
|
152
|
+
let orphaned = false;
|
|
153
|
+
const ack = (): void => {
|
|
154
|
+
if (acked) return;
|
|
155
|
+
acked = true;
|
|
156
|
+
host.send({ type: PROCESS_MESSAGE_TYPE, event: 'draining', budgetMs: host.budgetMs() });
|
|
157
|
+
};
|
|
158
|
+
const orphan = (why: string): void => {
|
|
159
|
+
if (orphaned) return;
|
|
160
|
+
orphaned = true;
|
|
161
|
+
logger.warn('ultimate supervisor gone', {
|
|
162
|
+
cause: `${why}, so this child drains and exits rather than serve with nobody to restart or stop it`,
|
|
163
|
+
});
|
|
164
|
+
host.after(host.budgetMs() + ORPHAN_EXIT_SLACK_MS, () => host.exit(DRAIN_TIMEOUT_EXIT_CODE));
|
|
165
|
+
void host.drain('supervisor-gone');
|
|
166
|
+
};
|
|
167
|
+
const releases: Release[] = [
|
|
168
|
+
// Beside core's own handlers, never instead of them: the drain is theirs, the ack is this.
|
|
169
|
+
...(['SIGTERM', 'SIGINT', 'SIGUSR2'] as const).map((signal) => host.onSignal(signal, ack)),
|
|
170
|
+
host.onMessage((message) => {
|
|
171
|
+
const asked = readDrainMessage(message);
|
|
172
|
+
if (asked !== undefined) host.raise(asked.signal);
|
|
173
|
+
}),
|
|
174
|
+
host.onDisconnect(() => orphan('the supervisor closed its IPC channel')),
|
|
175
|
+
host.every(PARENT_POLL_MS, () => {
|
|
176
|
+
if (host.ppid() !== originalPpid) orphan('this child was re-parented');
|
|
177
|
+
}),
|
|
178
|
+
];
|
|
179
|
+
return {
|
|
180
|
+
index: place.index,
|
|
181
|
+
count: place.count,
|
|
182
|
+
ready: (metricsUrl) =>
|
|
183
|
+
host.send({
|
|
184
|
+
type: PROCESS_MESSAGE_TYPE,
|
|
185
|
+
event: 'ready',
|
|
186
|
+
metricsUrl,
|
|
187
|
+
budgetMs: host.budgetMs(),
|
|
188
|
+
}),
|
|
189
|
+
gone: (code) => host.send({ type: PROCESS_MESSAGE_TYPE, event: 'gone', code }),
|
|
190
|
+
fatal: (code) => host.send({ type: PROCESS_MESSAGE_TYPE, event: 'fatal', code }),
|
|
191
|
+
refused: (error) => {
|
|
192
|
+
logger.error(
|
|
193
|
+
'ultimate child refused to boot',
|
|
194
|
+
isUltimateError(error)
|
|
195
|
+
? { code: error.code, cause: error.cause, fix: error.fix }
|
|
196
|
+
: { cause: renderThrowable(error) },
|
|
197
|
+
);
|
|
198
|
+
if (isUltimateError(error) && FATAL_BOOT_CODES.has(error.code)) {
|
|
199
|
+
host.send({ type: PROCESS_MESSAGE_TYPE, event: 'fatal', code: error.code });
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
release: () => {
|
|
203
|
+
for (const release of releases.splice(0)) release();
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|