@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
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// How many processes one production container runs: `ULTIMATE_PROCESSES` = auto | a count. auto is
|
|
2
|
+
// the minimum of every clamp below and names the one that bound it; an explicit count is honoured
|
|
3
|
+
// and checked. ONE decision for per-process state (`unsharedState`): auto clamps on it, an
|
|
4
|
+
// explicit count is refused on it, and a supervised child refuses what only its boot can see.
|
|
5
|
+
|
|
6
|
+
import type { Environment, Role } from '@ultimat3/core';
|
|
7
|
+
import { ROLE_INFO, renderFixShellArg } from '@ultimat3/core';
|
|
8
|
+
import type { CgroupFacts } from './supervise-cgroup';
|
|
9
|
+
import {
|
|
10
|
+
PROCESSES_ENV,
|
|
11
|
+
ProcessesInvalidError,
|
|
12
|
+
ProcessesOverPoolError,
|
|
13
|
+
ProcessesRoleSingletonError,
|
|
14
|
+
ProcessesUnbalancedError,
|
|
15
|
+
ProcessesUnsharedStateError,
|
|
16
|
+
} from './supervise-errors';
|
|
17
|
+
|
|
18
|
+
/** Measured private memory of a reference-app child at peak (227 MiB), rounded up. */
|
|
19
|
+
export const CHILD_MEMORY_BYTES = 256 * 1024 * 1024;
|
|
20
|
+
/** The supervisor's own share of the ceiling, kept out before children are counted. */
|
|
21
|
+
export const SUPERVISOR_MEMORY_BYTES = 32 * 1024 * 1024;
|
|
22
|
+
|
|
23
|
+
export type ProcessesRequest = 'auto' | number;
|
|
24
|
+
|
|
25
|
+
/** `auto` (also unset or blank) or a positive whole number; anything else refuses. */
|
|
26
|
+
export function readProcessesRequest(
|
|
27
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
28
|
+
): ProcessesRequest {
|
|
29
|
+
const raw = env[PROCESSES_ENV]?.trim() ?? '';
|
|
30
|
+
if (raw === '' || raw === 'auto') return 'auto';
|
|
31
|
+
if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
|
|
32
|
+
throw new ProcessesInvalidError(raw);
|
|
33
|
+
}
|
|
34
|
+
return Number(raw);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A store the boot was handed, by the name an operator finds it under in `runtime.ts`. */
|
|
38
|
+
export interface StoreScope {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly scope: string | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface SharedStateFacts {
|
|
44
|
+
readonly role: Role;
|
|
45
|
+
/** `cache.tiers` names `lru`. */
|
|
46
|
+
readonly lruTier: boolean;
|
|
47
|
+
/** `NATS_URL` is set, or `runtime.ts` supplied a transport that is not the in-process bus. */
|
|
48
|
+
readonly crossingBus: boolean;
|
|
49
|
+
/** `REDIS_URL` / `VALKEY_URL`: the cache's invalidations ride Redis pub/sub. */
|
|
50
|
+
readonly redis: boolean;
|
|
51
|
+
/** No `DATABASE_URL`: PGlite in a directory one process owns. */
|
|
52
|
+
readonly embeddedDatabase: boolean;
|
|
53
|
+
readonly stores: readonly StoreScope[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The stores among `stores` whose scope is not `'shared'`. Its own export because one store is only
|
|
58
|
+
* seen by a child, after the app's modules ran (`runtime-idempotency-scope.ts`): same rule, later.
|
|
59
|
+
*/
|
|
60
|
+
export const unsharedStores = (stores: readonly StoreScope[]): readonly string[] =>
|
|
61
|
+
stores
|
|
62
|
+
.filter((store) => store.scope !== 'shared')
|
|
63
|
+
.map(
|
|
64
|
+
(store) =>
|
|
65
|
+
`${store.name} keeps its records per process (scope ${store.scope ?? 'undeclared'})`,
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
/** Every piece of state N children would each keep to themselves, as a cause names it. */
|
|
69
|
+
export function unsharedState(facts: SharedStateFacts): readonly string[] {
|
|
70
|
+
return [
|
|
71
|
+
...(facts.lruTier && !facts.crossingBus && !facts.redis
|
|
72
|
+
? [
|
|
73
|
+
'the lru cache tier, whose invalidations ride the in-process bus (no NATS_URL, REDIS_URL or VALKEY_URL)',
|
|
74
|
+
]
|
|
75
|
+
: []),
|
|
76
|
+
...unsharedStores(facts.stores),
|
|
77
|
+
...(facts.embeddedDatabase
|
|
78
|
+
? ['the embedded database (no DATABASE_URL), one directory per process']
|
|
79
|
+
: []),
|
|
80
|
+
...(facts.role === 'sync' && !facts.crossingBus
|
|
81
|
+
? ['the sync role with no NATS_URL: channel fan-out and presence stay inside one process']
|
|
82
|
+
: []),
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What the resolver reads. Every source is injected, so each branch is a unit test. */
|
|
87
|
+
export interface CountSources {
|
|
88
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
89
|
+
readonly role: Role;
|
|
90
|
+
readonly platform: string;
|
|
91
|
+
readonly environment: Environment | undefined;
|
|
92
|
+
readonly cgroup: () => Promise<CgroupFacts>;
|
|
93
|
+
/** `navigator.hardwareConcurrency`: the cores this process may run on, the cap under a quota. */
|
|
94
|
+
readonly parallelism: () => number;
|
|
95
|
+
/** The container's pool: `DATABASE_POOL_MAX`, else the role's profile. */
|
|
96
|
+
readonly pool: () => number;
|
|
97
|
+
readonly shared: () => Promise<SharedStateFacts>;
|
|
98
|
+
/** The image carries `x build --target prebuilt`'s store; a boot without it compiles. */
|
|
99
|
+
readonly prebuilt: () => Promise<boolean>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export type ClampName =
|
|
103
|
+
| 'environment'
|
|
104
|
+
| 'platform'
|
|
105
|
+
| 'role'
|
|
106
|
+
| 'cpu'
|
|
107
|
+
| 'memory'
|
|
108
|
+
| 'pool'
|
|
109
|
+
| 'shared-state'
|
|
110
|
+
| 'image'
|
|
111
|
+
| 'requested';
|
|
112
|
+
|
|
113
|
+
export interface ProcessCount {
|
|
114
|
+
readonly count: number;
|
|
115
|
+
readonly requested: ProcessesRequest;
|
|
116
|
+
/** The clamp that set the count: what the boot line names. */
|
|
117
|
+
readonly binding: ClampName;
|
|
118
|
+
/** Each clamp's value, in the order auto takes their minimum. */
|
|
119
|
+
readonly clamps: Readonly<Partial<Record<ClampName, number>>>;
|
|
120
|
+
/** A line the boot owes beside the count: an ignored request, a count above the memory fit. */
|
|
121
|
+
readonly note?: {
|
|
122
|
+
readonly level: 'info' | 'warn';
|
|
123
|
+
readonly msg: string;
|
|
124
|
+
readonly cause: string;
|
|
125
|
+
readonly fix?: string;
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const memoryFit = (bytes: number | undefined): number | undefined =>
|
|
130
|
+
bytes === undefined
|
|
131
|
+
? undefined
|
|
132
|
+
: Math.max(1, Math.floor((bytes - SUPERVISOR_MEMORY_BYTES) / CHILD_MEMORY_BYTES));
|
|
133
|
+
|
|
134
|
+
const singleton = (role: Role): boolean => ROLE_INFO[role].maxReplicas === 1;
|
|
135
|
+
|
|
136
|
+
const PRODUCTION_LIKE: ReadonlySet<Environment | undefined> = new Set(['production', 'staging']);
|
|
137
|
+
|
|
138
|
+
/** The minimum of the clamps that are bounded; the first one at that minimum is the binding. */
|
|
139
|
+
function lowest(clamps: Partial<Record<ClampName, number>>): {
|
|
140
|
+
count: number;
|
|
141
|
+
binding: ClampName;
|
|
142
|
+
} {
|
|
143
|
+
let best: { count: number; binding: ClampName } = {
|
|
144
|
+
count: Number.POSITIVE_INFINITY,
|
|
145
|
+
binding: 'cpu',
|
|
146
|
+
};
|
|
147
|
+
for (const [name, value] of Object.entries(clamps) as [ClampName, number][]) {
|
|
148
|
+
if (value < best.count) best = { count: value, binding: name };
|
|
149
|
+
}
|
|
150
|
+
return best;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function resolveAuto(sources: CountSources): Promise<ProcessCount> {
|
|
154
|
+
if (sources.platform !== 'linux') return one('platform', { platform: 1 });
|
|
155
|
+
if (singleton(sources.role)) return one('role', { role: 1 });
|
|
156
|
+
const cgroup = await sources.cgroup();
|
|
157
|
+
// No quota declared reads as one process: a quota-less pod must never read the node's cores.
|
|
158
|
+
if (cgroup.cpus === undefined) return one('cpu', { cpu: 1 });
|
|
159
|
+
const fit = memoryFit(cgroup.memoryBytes);
|
|
160
|
+
// Insertion order IS the tie-break: the first clamp at the minimum is the one the line names.
|
|
161
|
+
const clamps: Partial<Record<ClampName, number>> = {
|
|
162
|
+
cpu: Math.min(cgroup.cpus, Math.max(1, sources.parallelism())),
|
|
163
|
+
...(fit === undefined ? {} : { memory: fit }),
|
|
164
|
+
pool: sources.pool(),
|
|
165
|
+
...(unsharedState(await sources.shared()).length === 0 ? {} : { 'shared-state': 1 }),
|
|
166
|
+
...((await sources.prebuilt()) ? {} : { image: 1 }),
|
|
167
|
+
};
|
|
168
|
+
return { ...lowest(clamps), requested: 'auto', clamps };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const one = (binding: ClampName, clamps: Partial<Record<ClampName, number>>): ProcessCount => ({
|
|
172
|
+
count: 1,
|
|
173
|
+
requested: 'auto',
|
|
174
|
+
binding,
|
|
175
|
+
clamps,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
async function checkExplicit(sources: CountSources, requested: number): Promise<ProcessCount> {
|
|
179
|
+
if (requested === 1) return { count: 1, requested, binding: 'requested', clamps: {} };
|
|
180
|
+
if (singleton(sources.role))
|
|
181
|
+
throw new ProcessesRoleSingletonError({ role: sources.role, requested });
|
|
182
|
+
if (sources.platform !== 'linux') {
|
|
183
|
+
throw new ProcessesUnbalancedError({ requested, platform: sources.platform });
|
|
184
|
+
}
|
|
185
|
+
const reasons = unsharedState(await sources.shared());
|
|
186
|
+
if (reasons.length > 0) throw new ProcessesUnsharedStateError({ requested, reasons });
|
|
187
|
+
const pool = sources.pool();
|
|
188
|
+
if (requested > pool) throw new ProcessesOverPoolError({ requested, pool });
|
|
189
|
+
const fit = memoryFit((await sources.cgroup()).memoryBytes);
|
|
190
|
+
const result: ProcessCount = {
|
|
191
|
+
count: requested,
|
|
192
|
+
requested,
|
|
193
|
+
binding: 'requested',
|
|
194
|
+
clamps: { pool, ...(fit === undefined ? {} : { memory: fit }) },
|
|
195
|
+
};
|
|
196
|
+
if (fit === undefined || requested <= fit) return result;
|
|
197
|
+
return {
|
|
198
|
+
...result,
|
|
199
|
+
note: {
|
|
200
|
+
level: 'warn',
|
|
201
|
+
msg: 'ultimate processes above the memory fit',
|
|
202
|
+
cause: `${PROCESSES_ENV}=${String(requested)} children at about 256 MiB each fit ${String(fit)} into this container's memory ceiling, so an OOM kill takes a child under load`,
|
|
203
|
+
fix: `export ULTIMATE_PROCESSES=${renderFixShellArg(String(fit), '<count>')} # in this service's deploy environment, or raise the service's memory limit (mem_limit, resources.limits.memory)`,
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The count, or a coded refusal. Only a production-like container supervises: `x dev`, the test
|
|
210
|
+
* runner and any other environment run one process, and a valid count asked for there is ignored
|
|
211
|
+
* with one info line rather than refused — a `.env` shared with production must not stop a laptop.
|
|
212
|
+
* A value that is no count at all (`two`, `0`) is refused everywhere: production would refuse it.
|
|
213
|
+
*/
|
|
214
|
+
export async function resolveProcessCount(sources: CountSources): Promise<ProcessCount> {
|
|
215
|
+
const requested = readProcessesRequest(sources.env);
|
|
216
|
+
if (!PRODUCTION_LIKE.has(sources.environment)) {
|
|
217
|
+
return {
|
|
218
|
+
count: 1,
|
|
219
|
+
requested,
|
|
220
|
+
binding: 'environment',
|
|
221
|
+
clamps: { environment: 1 },
|
|
222
|
+
...ignoredRequest(requested, sources.environment ?? 'unnamed'),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
return requested === 'auto' ? resolveAuto(sources) : checkExplicit(sources, requested);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The one line a process that always runs as one owes a count asked of it: the test runner and any
|
|
230
|
+
* non-production environment here, `x dev` (`dev-boot.ts`) everywhere. Nothing for auto or `1`.
|
|
231
|
+
*/
|
|
232
|
+
export function ignoredRequest(
|
|
233
|
+
requested: ProcessesRequest,
|
|
234
|
+
where: string,
|
|
235
|
+
): { readonly note?: NonNullable<ProcessCount['note']> } {
|
|
236
|
+
if (requested === 'auto' || requested === 1) return {};
|
|
237
|
+
return {
|
|
238
|
+
note: {
|
|
239
|
+
level: 'info',
|
|
240
|
+
msg: 'ultimate processes ignored',
|
|
241
|
+
cause: `${PROCESSES_ENV}=${String(requested)} applies to production containers only; this ${where} process runs as one`,
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// The refusals a production container's process count can meet: the count itself, the role, the
|
|
2
|
+
// state the children would not share, the pool they split, the platform, and a child that keeps
|
|
3
|
+
// crashing. Beside their throwers (`supervise-count.ts`, `supervise.ts`), one class per condition.
|
|
4
|
+
|
|
5
|
+
import type { Role } from '@ultimat3/core';
|
|
6
|
+
import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The variable every cause below names. Each fix spells it out: `export ${…}` would put a value in
|
|
10
|
+
* a pasted command's position (`fix-shell-arg`); `supervise-errors.test.ts` holds the two equal.
|
|
11
|
+
*/
|
|
12
|
+
export const PROCESSES_ENV = 'ULTIMATE_PROCESSES';
|
|
13
|
+
|
|
14
|
+
export class ProcessesInvalidError extends UltimateError {
|
|
15
|
+
constructor(raw: string) {
|
|
16
|
+
super({
|
|
17
|
+
code: 'X_PROCESSES_INVALID',
|
|
18
|
+
cause: `${PROCESSES_ENV}=${renderCauseValue(raw)} is neither auto nor a positive whole number, so the container cannot tell how many processes to start`,
|
|
19
|
+
fix: `export ULTIMATE_PROCESSES=auto # in this service's deploy environment, or a positive whole number such as 2`,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class ProcessesRoleSingletonError extends UltimateError {
|
|
25
|
+
constructor(input: { readonly role: Role; readonly requested: number }) {
|
|
26
|
+
super({
|
|
27
|
+
code: 'X_PROCESSES_ROLE_SINGLETON',
|
|
28
|
+
cause: `${PROCESSES_ENV}=${String(input.requested)} on ROLE=${input.role}, which holds a leader lease, a replication slot or runs once — a second process is idle at best`,
|
|
29
|
+
fix: `export ULTIMATE_PROCESSES=1 # in the environment of the ${input.role} service`,
|
|
30
|
+
meta: { role: input.role, requested: input.requested },
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class ProcessesUnsharedStateError extends UltimateError {
|
|
36
|
+
constructor(input: { readonly requested: number; readonly reasons: readonly string[] }) {
|
|
37
|
+
super({
|
|
38
|
+
code: 'X_PROCESSES_UNSHARED_STATE',
|
|
39
|
+
cause: `${PROCESSES_ENV}=${String(input.requested)} over state each child would keep to itself: ${input.reasons.join('; ')}`,
|
|
40
|
+
fix: `export ULTIMATE_PROCESSES=1 # in this service's deploy environment, or share the state: NATS_URL=nats://<host>:4222 (REDIS_URL or VALKEY_URL for the cache), DATABASE_URL for an embedded database, and drop the per-process store from apps/<app>/runtime.ts`,
|
|
41
|
+
meta: { requested: input.requested, reasons: [...input.reasons] },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class ProcessesOverPoolError extends UltimateError {
|
|
47
|
+
constructor(input: { readonly requested: number; readonly pool: number }) {
|
|
48
|
+
super({
|
|
49
|
+
code: 'X_PROCESSES_OVER_POOL',
|
|
50
|
+
cause: `${PROCESSES_ENV}=${String(input.requested)} is more than the container's ${String(input.pool)} database connections (DATABASE_POOL_MAX, else the role's profile): the pool is split across the children, never multiplied, so a child would get none`,
|
|
51
|
+
fix: `export DATABASE_POOL_MAX=${renderFixShellArg(String(input.requested), '<processes>')} # or ${PROCESSES_ENV}=${String(input.pool)}`,
|
|
52
|
+
meta: { requested: input.requested, pool: input.pool },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class ProcessesUnbalancedError extends UltimateError {
|
|
58
|
+
constructor(input: { readonly requested: number; readonly platform: string }) {
|
|
59
|
+
super({
|
|
60
|
+
code: 'X_PROCESSES_UNBALANCED',
|
|
61
|
+
cause: `${PROCESSES_ENV}=${String(input.requested)} on ${renderCauseValue(input.platform)}, where Bun ignores reusePort (SO_REUSEPORT is Linux only), so the children cannot share one port`,
|
|
62
|
+
fix: `export ULTIMATE_PROCESSES=1 # in this service's deploy environment, or run the image in a Linux container`,
|
|
63
|
+
meta: { requested: input.requested, platform: input.platform },
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class ProcessCrashLoopError extends UltimateError {
|
|
69
|
+
constructor(input: {
|
|
70
|
+
readonly index: number;
|
|
71
|
+
readonly code: number | null;
|
|
72
|
+
readonly crashes: number;
|
|
73
|
+
readonly windowMs: number;
|
|
74
|
+
}) {
|
|
75
|
+
const exit = input.code === null ? 'was killed' : `exited ${String(input.code)}`;
|
|
76
|
+
super({
|
|
77
|
+
code: 'X_PROCESS_CRASH_LOOP',
|
|
78
|
+
cause: `child ${String(input.index)} ${exit}, its ${String(input.crashes)}th unexpected exit within ${String(Math.round(input.windowMs / 60_000))} minutes, so the supervisor drained its siblings and the container exits 1 for the platform to restart`,
|
|
79
|
+
fix: `docker compose logs --tail 200 <service> # the last error line with "child":${String(input.index)} names the boot error to fix`,
|
|
80
|
+
meta: { child: input.index, exitCode: input.code, crashes: input.crashes },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// What the supervisor can see of per-process state before any child boots: the environment,
|
|
2
|
+
// `apps/<app>/runtime.ts`'s stores and transport, and `app.config.ts`'s cache tiers. Loaded only
|
|
3
|
+
// when the CPU budget already allows more than one process (`supervise-boot.ts`).
|
|
4
|
+
|
|
5
|
+
import type { Role } from '@ultimat3/core';
|
|
6
|
+
import { redisUrlSource } from '@ultimat3/core/redis';
|
|
7
|
+
import { InProcessTransport } from '@ultimat3/realtime/server';
|
|
8
|
+
import { loadAppConfig } from './app-config-load';
|
|
9
|
+
import { cacheTiersOf } from './runtime-cache';
|
|
10
|
+
import type { ServeOptions } from './serve-types';
|
|
11
|
+
import type { SharedStateFacts, StoreScope } from './supervise-count';
|
|
12
|
+
|
|
13
|
+
const set = (value: string | undefined): boolean => value !== undefined && value.trim() !== '';
|
|
14
|
+
|
|
15
|
+
/** What the supervisor can see before any child boots: env, `runtime.ts`, `app.config.ts`. */
|
|
16
|
+
export async function sharedStateFacts(
|
|
17
|
+
options: ServeOptions,
|
|
18
|
+
role: Role,
|
|
19
|
+
): Promise<SharedStateFacts> {
|
|
20
|
+
const runtime = options.runtime;
|
|
21
|
+
const transport = runtime?.transport;
|
|
22
|
+
const stores: StoreScope[] = [
|
|
23
|
+
...(runtime?.rateLimitStore === undefined
|
|
24
|
+
? []
|
|
25
|
+
: [{ name: 'runtime.rateLimitStore', scope: runtime.rateLimitStore.scope }]),
|
|
26
|
+
...(runtime?.idempotencyStore === undefined
|
|
27
|
+
? []
|
|
28
|
+
: [{ name: 'runtime.idempotencyStore', scope: runtime.idempotencyStore.scope }]),
|
|
29
|
+
];
|
|
30
|
+
return {
|
|
31
|
+
role,
|
|
32
|
+
lruTier: cacheTiersOf(await loadAppConfig(options.root)).includes('lru'),
|
|
33
|
+
crossingBus:
|
|
34
|
+
set(options.env['NATS_URL']) ||
|
|
35
|
+
(transport !== undefined && !(transport instanceof InProcessTransport)),
|
|
36
|
+
redis: redisUrlSource(options.env) !== undefined,
|
|
37
|
+
embeddedDatabase: !set(options.env['DATABASE_URL']),
|
|
38
|
+
stores,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The control messages between the production supervisor and its children, over `ipc` with
|
|
2
|
+
// `serialization: 'json'`. Every value is a string, a number or a boolean: JSON turns a `Date` into
|
|
3
|
+
// a string and a `Map` into `{}` silently, and a `BigInt` throws on send (measured on Bun 1.4.4).
|
|
4
|
+
|
|
5
|
+
/** Every message carries it, so a stray `process.send` from an app module is never read as one. */
|
|
6
|
+
export const PROCESS_MESSAGE_TYPE = 'x-proc';
|
|
7
|
+
|
|
8
|
+
export type DrainSignal = 'SIGTERM' | 'SIGINT' | 'SIGUSR2';
|
|
9
|
+
|
|
10
|
+
/** Child → supervisor. */
|
|
11
|
+
export type ChildMessage =
|
|
12
|
+
/** Booted and bound: `metricsUrl` is its loopback scrape base; `budgetMs` its drain bound. */
|
|
13
|
+
| {
|
|
14
|
+
readonly type: typeof PROCESS_MESSAGE_TYPE;
|
|
15
|
+
readonly event: 'ready';
|
|
16
|
+
readonly metricsUrl: string;
|
|
17
|
+
readonly budgetMs: number;
|
|
18
|
+
}
|
|
19
|
+
/** Its drain began; the supervisor's per-child budget starts HERE, not at its own send. */
|
|
20
|
+
| {
|
|
21
|
+
readonly type: typeof PROCESS_MESSAGE_TYPE;
|
|
22
|
+
readonly event: 'draining';
|
|
23
|
+
readonly budgetMs: number;
|
|
24
|
+
}
|
|
25
|
+
/** Leaving with `code`: the supervisor reads the exit, this is said first. */
|
|
26
|
+
| { readonly type: typeof PROCESS_MESSAGE_TYPE; readonly event: 'gone'; readonly code: number }
|
|
27
|
+
/** A refusal no restart can fix (`X_PROCESSES_UNSHARED_STATE`): stop restarting, exit 1. */
|
|
28
|
+
| { readonly type: typeof PROCESS_MESSAGE_TYPE; readonly event: 'fatal'; readonly code: string };
|
|
29
|
+
|
|
30
|
+
/** Supervisor → child: drain as if `signal` had arrived. */
|
|
31
|
+
export interface DrainMessage {
|
|
32
|
+
readonly type: typeof PROCESS_MESSAGE_TYPE;
|
|
33
|
+
readonly event: 'drain';
|
|
34
|
+
readonly signal: DrainSignal;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const SIGNALS: ReadonlySet<unknown> = new Set(['SIGTERM', 'SIGINT', 'SIGUSR2']);
|
|
38
|
+
|
|
39
|
+
const fieldsOf = (message: unknown): Record<string, unknown> | undefined =>
|
|
40
|
+
typeof message === 'object' &&
|
|
41
|
+
message !== null &&
|
|
42
|
+
(message as Record<string, unknown>)['type'] === PROCESS_MESSAGE_TYPE
|
|
43
|
+
? (message as Record<string, unknown>)
|
|
44
|
+
: undefined;
|
|
45
|
+
|
|
46
|
+
const count = (value: unknown): value is number =>
|
|
47
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
48
|
+
|
|
49
|
+
/** A child's message, screened: anything else is `undefined` and ignored. */
|
|
50
|
+
export function readChildMessage(message: unknown): ChildMessage | undefined {
|
|
51
|
+
const fields = fieldsOf(message);
|
|
52
|
+
if (fields === undefined) return undefined;
|
|
53
|
+
const { event } = fields;
|
|
54
|
+
if (event === 'ready' && typeof fields['metricsUrl'] === 'string' && count(fields['budgetMs'])) {
|
|
55
|
+
return {
|
|
56
|
+
type: PROCESS_MESSAGE_TYPE,
|
|
57
|
+
event,
|
|
58
|
+
metricsUrl: fields['metricsUrl'],
|
|
59
|
+
budgetMs: fields['budgetMs'],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (event === 'draining' && count(fields['budgetMs'])) {
|
|
63
|
+
return { type: PROCESS_MESSAGE_TYPE, event, budgetMs: fields['budgetMs'] };
|
|
64
|
+
}
|
|
65
|
+
if (event === 'gone' && typeof fields['code'] === 'number') {
|
|
66
|
+
return { type: PROCESS_MESSAGE_TYPE, event, code: fields['code'] };
|
|
67
|
+
}
|
|
68
|
+
if (event === 'fatal' && typeof fields['code'] === 'string') {
|
|
69
|
+
return { type: PROCESS_MESSAGE_TYPE, event, code: fields['code'] };
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function readDrainMessage(message: unknown): DrainMessage | undefined {
|
|
75
|
+
const fields = fieldsOf(message);
|
|
76
|
+
if (fields?.['event'] !== 'drain' || !SIGNALS.has(fields['signal'])) return undefined;
|
|
77
|
+
return { type: PROCESS_MESSAGE_TYPE, event: 'drain', signal: fields['signal'] as DrainSignal };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const drainMessage = (signal: DrainSignal): DrainMessage => ({
|
|
81
|
+
type: PROCESS_MESSAGE_TYPE,
|
|
82
|
+
event: 'drain',
|
|
83
|
+
signal,
|
|
84
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// When a crashed child comes back, and when the supervisor stops trying. Pure: the loop in
|
|
2
|
+
// `supervise.ts` hands in the clock's reading and the child's uptime, and keeps what comes back.
|
|
3
|
+
|
|
4
|
+
import { backoffDelay, DRAIN_TIMEOUT_EXIT_CODE } from '@ultimat3/core';
|
|
5
|
+
|
|
6
|
+
/** The first restart waits a second, then 2, 4, 8… */
|
|
7
|
+
export const BACKOFF_BASE_MS = 1_000;
|
|
8
|
+
export const BACKOFF_CAP_MS = 30_000;
|
|
9
|
+
/** A child up this long before it crashed was healthy: its backoff starts over. */
|
|
10
|
+
export const STABLE_UPTIME_MS = 60_000;
|
|
11
|
+
/** This many unexpected exits of one child inside the window is a crash loop. */
|
|
12
|
+
export const CRASH_LIMIT = 5;
|
|
13
|
+
export const CRASH_WINDOW_MS = 5 * 60_000;
|
|
14
|
+
|
|
15
|
+
export interface CrashHistory {
|
|
16
|
+
/** Crashes since the child last stayed up `STABLE_UPTIME_MS`. */
|
|
17
|
+
readonly consecutive: number;
|
|
18
|
+
/** When each crash inside the window happened, oldest first. */
|
|
19
|
+
readonly at: readonly number[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const NO_CRASHES: CrashHistory = { consecutive: 0, at: [] };
|
|
23
|
+
|
|
24
|
+
export interface RestartDecision {
|
|
25
|
+
readonly history: CrashHistory;
|
|
26
|
+
readonly delayMs: number;
|
|
27
|
+
/** `CRASH_LIMIT` inside `CRASH_WINDOW_MS`: drain the siblings and exit 1. */
|
|
28
|
+
readonly loop: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function afterCrash(history: CrashHistory, now: number, uptimeMs: number): RestartDecision {
|
|
32
|
+
const consecutive = (uptimeMs >= STABLE_UPTIME_MS ? 0 : history.consecutive) + 1;
|
|
33
|
+
const at = [...history.at.filter((when) => now - when < CRASH_WINDOW_MS), now];
|
|
34
|
+
return {
|
|
35
|
+
history: { consecutive, at },
|
|
36
|
+
// Core's one curve, no jitter: a supervisor restarting its own children has no herd to spread.
|
|
37
|
+
delayMs: backoffDelay({ attempt: consecutive, base: BACKOFF_BASE_MS, max: BACKOFF_CAP_MS }),
|
|
38
|
+
loop: at.length >= CRASH_LIMIT,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Exit codes, aggregated over the children of one stop: core's 70 wins, then any failure. */
|
|
43
|
+
export function aggregateExit(codes: readonly (number | null)[], killedAtCeiling: boolean): number {
|
|
44
|
+
if (killedAtCeiling || codes.includes(DRAIN_TIMEOUT_EXIT_CODE)) return DRAIN_TIMEOUT_EXIT_CODE;
|
|
45
|
+
return codes.every((code) => code === 0) ? 0 : 1;
|
|
46
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The container's database pool — `DATABASE_POOL_MAX`, else the role's profile — which the
|
|
2
|
+
// supervisor splits across its children (`childShare`) and the count never exceeds.
|
|
3
|
+
|
|
4
|
+
import type { Role } from '@ultimat3/core';
|
|
5
|
+
import { POOL_PROFILES, poolMaxFromEnv } from '@ultimat3/db';
|
|
6
|
+
import type { ServeOptions } from './serve-types';
|
|
7
|
+
|
|
8
|
+
/** The container's pool: `DATABASE_POOL_MAX`, else the role's profile — what the children split. */
|
|
9
|
+
export const containerPool = (options: ServeOptions, role: Role): number =>
|
|
10
|
+
poolMaxFromEnv(options.env).max ?? POOL_PROFILES[role].max;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// The supervised container's `METRICS_PORT`: `/healthz` (the supervisor is alive and not in a
|
|
2
|
+
// crash loop), `/readyz` (every child that is not draining said ready), and `/metrics` — each
|
|
3
|
+
// child's loopback scrape, merged under one HELP/TYPE per family with a `child="<i>"` label.
|
|
4
|
+
|
|
5
|
+
import { METRICS_CONTENT_TYPE, METRICS_PATH, markListening } from '@ultimat3/core';
|
|
6
|
+
import { bindScrapePort } from './metrics-endpoint';
|
|
7
|
+
import type { ChildView, SupervisorView } from './supervise';
|
|
8
|
+
|
|
9
|
+
/** One child's scrape may not hold the container's: a saturated child answers late (measured). */
|
|
10
|
+
export const CHILD_SCRAPE_TIMEOUT_MS = 2_000;
|
|
11
|
+
|
|
12
|
+
const METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*/;
|
|
13
|
+
const COMMENT = /^#\s+(HELP|TYPE)\s+([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\s|$)/;
|
|
14
|
+
|
|
15
|
+
/** `name{a="1"} 2` → `name{child="i",a="1"} 2`; `name 2` → `name{child="i"} 2`. */
|
|
16
|
+
export function labelSample(line: string, index: number): string {
|
|
17
|
+
const name = METRIC_NAME.exec(line)?.[0];
|
|
18
|
+
if (name === undefined) return line;
|
|
19
|
+
const label = `child="${String(index)}"`;
|
|
20
|
+
const rest = line.slice(name.length);
|
|
21
|
+
if (!rest.startsWith('{')) return `${name}{${label}}${rest}`;
|
|
22
|
+
return `${name}{${label}${rest.startsWith('{}') ? '' : ','}${rest.slice(1)}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface Family {
|
|
26
|
+
help: string | undefined;
|
|
27
|
+
type: string | undefined;
|
|
28
|
+
readonly samples: string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Every child's exposition as one: a family's HELP and TYPE once (the first child's), then its
|
|
33
|
+
* samples from every child in child order. A sample belongs to the family the comment above it
|
|
34
|
+
* named — a histogram's `_bucket`, `_sum` and `_count` stay under their family.
|
|
35
|
+
*/
|
|
36
|
+
export function mergeMetrics(
|
|
37
|
+
bodies: readonly { readonly index: number; readonly body: string }[],
|
|
38
|
+
): string {
|
|
39
|
+
const families = new Map<string, Family>();
|
|
40
|
+
const familyOf = (name: string): Family => {
|
|
41
|
+
let family = families.get(name);
|
|
42
|
+
if (family === undefined) {
|
|
43
|
+
family = { help: undefined, type: undefined, samples: [] };
|
|
44
|
+
families.set(name, family);
|
|
45
|
+
}
|
|
46
|
+
return family;
|
|
47
|
+
};
|
|
48
|
+
for (const { index, body } of bodies) {
|
|
49
|
+
let current: string | undefined;
|
|
50
|
+
for (const line of body.split('\n')) {
|
|
51
|
+
if (line.trim() === '') continue;
|
|
52
|
+
const comment = COMMENT.exec(line);
|
|
53
|
+
if (comment !== null) {
|
|
54
|
+
const [, kind, name = ''] = comment;
|
|
55
|
+
current = name;
|
|
56
|
+
const family = familyOf(name);
|
|
57
|
+
if (kind === 'HELP') family.help ??= line;
|
|
58
|
+
else family.type ??= line;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (line.startsWith('#')) continue;
|
|
62
|
+
const name = METRIC_NAME.exec(line)?.[0];
|
|
63
|
+
if (name === undefined) continue;
|
|
64
|
+
const owner = current !== undefined && name.startsWith(current) ? current : name;
|
|
65
|
+
familyOf(owner).samples.push(labelSample(line, index));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const out: string[] = [];
|
|
69
|
+
for (const family of families.values()) {
|
|
70
|
+
if (family.help !== undefined) out.push(family.help);
|
|
71
|
+
if (family.type !== undefined) out.push(family.type);
|
|
72
|
+
out.push(...family.samples);
|
|
73
|
+
}
|
|
74
|
+
return out.length === 0 ? '' : `${out.join('\n')}\n`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Whether a child's loopback `/healthz` answers 200 in time. */
|
|
78
|
+
export async function childHealthy(metricsUrl: string): Promise<boolean> {
|
|
79
|
+
try {
|
|
80
|
+
const response = await fetch(`${metricsUrl}/healthz`, {
|
|
81
|
+
signal: AbortSignal.timeout(CHILD_SCRAPE_TIMEOUT_MS),
|
|
82
|
+
});
|
|
83
|
+
await response.body?.cancel();
|
|
84
|
+
return response.status === 200;
|
|
85
|
+
} catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function scrape(child: ChildView): Promise<{ index: number; body: string } | undefined> {
|
|
91
|
+
if (child.metricsUrl === undefined) return undefined;
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetch(`${child.metricsUrl}${METRICS_PATH}`, {
|
|
94
|
+
signal: AbortSignal.timeout(CHILD_SCRAPE_TIMEOUT_MS),
|
|
95
|
+
});
|
|
96
|
+
if (!response.ok) {
|
|
97
|
+
// Given back now, as `childHealthy` does: unread, the stream and its socket stay held.
|
|
98
|
+
await response.body?.cancel();
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
return { index: child.index, body: await response.text() };
|
|
102
|
+
} catch {
|
|
103
|
+
// A child that is restarting or saturated is absent from this scrape, never the scrape's end.
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface SupervisorProbeInput {
|
|
109
|
+
readonly port: number;
|
|
110
|
+
readonly hostname: string;
|
|
111
|
+
readonly role: string;
|
|
112
|
+
readonly view: SupervisorView;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface SupervisorProbe {
|
|
116
|
+
readonly url: string;
|
|
117
|
+
stop(): void;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const verdict = (ok: boolean, state: string, role: string): Response =>
|
|
121
|
+
Response.json(
|
|
122
|
+
{ state, ready: ok, role },
|
|
123
|
+
{ status: ok ? 200 : 503, headers: { 'cache-control': 'no-store' } },
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
/** Opened before the first child spawns, so the platform's probes reach a socket from the start. */
|
|
127
|
+
export function startSupervisorProbe(input: SupervisorProbeInput): SupervisorProbe {
|
|
128
|
+
const server = bindScrapePort(input.port, 'refuse', (port) =>
|
|
129
|
+
Bun.serve({
|
|
130
|
+
port,
|
|
131
|
+
hostname: input.hostname,
|
|
132
|
+
async fetch(request: Request): Promise<Response> {
|
|
133
|
+
const path = new URL(request.url).pathname;
|
|
134
|
+
if (path === '/healthz') {
|
|
135
|
+
const live = input.view.live();
|
|
136
|
+
return verdict(live, live ? 'live' : 'crash-loop', input.role);
|
|
137
|
+
}
|
|
138
|
+
if (path === '/readyz') {
|
|
139
|
+
const ready = input.view.ready();
|
|
140
|
+
return verdict(ready, ready ? 'ready' : 'not-ready', input.role);
|
|
141
|
+
}
|
|
142
|
+
if (path !== METRICS_PATH) return new Response('not found', { status: 404 });
|
|
143
|
+
const bodies = await Promise.all(input.view.children().map(scrape));
|
|
144
|
+
return new Response(mergeMetrics(bodies.filter((body) => body !== undefined)), {
|
|
145
|
+
headers: { 'content-type': METRICS_CONTENT_TYPE, 'cache-control': 'no-store' },
|
|
146
|
+
});
|
|
147
|
+
},
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
150
|
+
const stopListening = markListening(server.url.origin);
|
|
151
|
+
return {
|
|
152
|
+
url: server.url.origin,
|
|
153
|
+
stop(): void {
|
|
154
|
+
server.stop(true);
|
|
155
|
+
stopListening();
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|