Public: anyone can read this; the crew can change it.

A release that does not boot never reaches production, and a crash-looping roll undoes itself in minutes #2654

Parked opened this in answer to
Closed without merging

mason/forge:mason/2652-a-release-that-does-not-boot-never-reach → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +681 −160
Dockerfile +5
@@ -27,6 +27,11 @@ ENV FORGE_VERSION=$VERSION FORGE_COMMIT=$COMMIT
2727 ENV FORGE_DATA=/data PORT=8080 FORGE_SSH_PORT=2222
2828 EXPOSE 8080 2222
2929 USER bun
30 # The build boots what it built (#2652): `src/main.ts` on an empty data
31 # directory must answer /api/v1/health as $VERSION, or the build fails and
32 # nothing is pushed. 0.7.166 passed its check from the repository and crashed
33 # at import from this image.
34 RUN bun src/release/boot.ts
3035 # tini reaps what an agent run leaves behind: a claude run spawns git, bun,
3136 # the app under test, and their children.
3237 ENTRYPOINT ["tini", "--"]
charts/app/templates/boot-proof.yaml added +65
@@ -0,0 +1,65 @@
1 {{/*
2 The promote preflight (#2652): before an upgrade touches the Deployment, the
3 new image boots beside the running forge on a copy of its data
4 (`src/release/boot.ts --from /data`) and must answer health as its version.
5 A refusal fails the upgrade, so the old pod is never taken down for a
6 release that cannot start. The volume is local-path, bound to its node, so
7 this pod schedules where the forge is; it reads the volume, writes only its
8 own scratch directory on it, and removes that.
9 */}}
10 apiVersion: batch/v1
11 kind: Job
12 metadata:
13 name: {{ .Release.Name }}-boot-proof
14 labels:
15 app: {{ .Release.Name }}-boot-proof
16 annotations:
17 helm.sh/hook: pre-upgrade
18 helm.sh/hook-weight: "0"
19 # A failed proof is kept for its log until the next upgrade replaces it.
20 helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
21 spec:
22 backoffLimit: 0
23 activeDeadlineSeconds: 300
24 template:
25 metadata:
26 labels:
27 app: {{ .Release.Name }}-boot-proof
28 spec:
29 restartPolicy: Never
30 {{- with .Values.imagePullSecrets }}
31 imagePullSecrets:
32 {{- toYaml . | nindent 8 }}
33 {{- end }}
34 securityContext:
35 runAsNonRoot: true
36 runAsUser: 1000
37 runAsGroup: 1000
38 fsGroup: 1000
39 fsGroupChangePolicy: OnRootMismatch
40 seccompProfile:
41 type: RuntimeDefault
42 containers:
43 - name: boot-proof
44 image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
45 command: ["bun", "src/release/boot.ts", "--from", "/data", "--budget", "180"]
46 securityContext:
47 allowPrivilegeEscalation: false
48 capabilities:
49 drop: [ALL]
50 volumeMounts:
51 - name: data
52 mountPath: /data
53 # A forge with no crew, no apps and no SSH: a fraction of the
54 # running one, so it fits beside it where a surge pod may not.
55 resources:
56 requests:
57 cpu: 100m
58 memory: 256Mi
59 limits:
60 cpu: "1"
61 memory: 1Gi
62 volumes:
63 - name: data
64 persistentVolumeClaim:
65 claimName: {{ .Release.Name }}-data
scripts/shards.ts +4 −19
@@ -24,25 +24,10 @@ export const SHARDS_MAX = 32;
2424 */
2525 export const WORKER_MEMORY_BYTES = 512 * 1024 * 1024;
2626
27 /**
28 * The share of a check cell's declared CPUs the workers are sized to. The
29 * cell's watchdog (`src/apps/contain.ts`) stops a check whose tree averages
30 * more than `check.limits.cpus` cores over 30 s, and a worker is more than
31 * one core at its peaks (Bun's own threads, git children, a booted forge):
32 * one worker per declared CPU averaged 16.1 of 16 and stopped main (#2161).
33 */
34 export const CELL_CPU_SHARE = 3 / 4;
35
36 /**
37 * The CPUs the gate sizes its workers to: the machine's, held under
38 * {@link CELL_CPU_SHARE} of the cell's CPU limit (`FORGE_CELL_CPUS`) when
39 * there is one, at least one. `availableParallelism()` sees the host, not
40 * the cell: the cell is a watchdog, not a CPU quota the process can read.
41 */
42 export function workerCpus(machine: number, declared: number | undefined): number {
43 if (declared === undefined || !Number.isFinite(declared) || declared <= 0) return machine;
44 return Math.max(1, Math.min(machine, Math.floor(declared * CELL_CPU_SHARE)));
45 }
27 // Lives in src/ because the running forge sizes its checks with it, and the
28 // image ships src/ alone (#2652).
29 export { CELL_CPU_SHARE, workerCpus } from "../src/core/capacity.ts";
30 import { workerCpus } from "../src/core/capacity.ts";
4631
4732 /**
4833 * How many shards: one per CPU the process may use, no more than its
scripts/smoke.ts +2 −138
@@ -11,144 +11,8 @@
1111 * never answers with `Response.error()`.
1212 */
1313
14 export const AGENTS: Record<string, string> = {
15 phone:
16 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
17 desktop:
18 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
19 };
20
21 export interface Failure {
22 url: string;
23 agent: string;
24 status: number | string;
25 contentType: string;
26 why: string;
27 }
28
29 /** The first stylesheet href in a page, or null. */
30 export function stylesheetHref(html: string): string | null {
31 for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {
32 if (!/\brel\s*=\s*["']?stylesheet/i.test(tag)) continue;
33 const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag);
34 const value = href?.[1] ?? href?.[2];
35 if (value) return value.replaceAll("&amp;", "&");
36 }
37 return null;
38 }
39
40 /** The part of a service worker that answers navigations, comments removed. */
41 export function navigationBranch(source: string): string | null {
42 const at = source.search(/mode\s*===?\s*["']navigate["']/);
43 if (at < 0) return null;
44 const rest = source.slice(at);
45 const end = rest.search(/\breturn\s*;/);
46 return (end < 0 ? rest : rest.slice(0, end)).replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
47 }
48
49 export interface Options {
50 /** Wait for `/healthz` to report this `X-Forge-Version`. */
51 version?: string | undefined;
52 /** Longest wait for it, in milliseconds. */
53 waitMs?: number;
54 /** Pause between polls, in milliseconds. */
55 pollMs?: number;
56 /** The fetch to use; the global one unless a caller (the forge proving itself, a test) gives its own. */
57 fetch?: typeof fetch;
58 /** Accept a redirect from `/board` as the sign-in it is, for a caller holding no token. */
59 anonymousBoard?: boolean;
60 }
61
62 /** Polls `/healthz` until it reports `version`; null when it does, else a failure. */
63 async function waitForVersion(root: URL, version: string, waitMs: number, pollMs: number, fetch: typeof globalThis.fetch): Promise<Failure | null> {
64 const url = new URL("/healthz", root).href;
65 const deadline = Date.now() + waitMs;
66 let seen = "none";
67 let status: number | string = "error";
68 for (;;) {
69 try {
70 const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(5_000) });
71 await res.body?.cancel();
72 status = res.status;
73 seen = res.headers.get("x-forge-version") ?? "none";
74 if (seen === version) return null;
75 } catch (error) {
76 status = "error";
77 seen = `none (${error})`;
78 }
79 if (Date.now() + pollMs > deadline) break;
80 await Bun.sleep(pollMs);
81 }
82 return { url, agent: "-", status, contentType: "", why: `wanted X-Forge-Version ${version}, last saw ${seen}` };
83 }
84
85 /** Runs every check against `base`; returns the failures (empty is green). */
86 export async function smoke(base: string, token = "", options: Options = {}): Promise<Failure[]> {
87 const root = new URL(base);
88 if (root.protocol !== "http:" && root.protocol !== "https:") throw new Error("url must be http(s)");
89 const failures: Failure[] = [];
90 const fetch = options.fetch ?? globalThis.fetch;
91 if (options.version) {
92 const late = await waitForVersion(root, options.version, options.waitMs ?? 120_000, options.pollMs ?? 1_000, fetch);
93 if (late) return [late];
94 }
95
96 const get = async (path: string, agent: string, headers: Record<string, string> = {}) => {
97 const url = new URL(path, root).href;
98 try {
99 const res = await fetch(url, {
100 redirect: "manual",
101 signal: AbortSignal.timeout(10_000),
102 headers: { "user-agent": AGENTS[agent]!, ...headers },
103 });
104 return { url, res, body: await res.text() };
105 } catch (error) {
106 failures.push({ url, agent, status: "error", contentType: "", why: String(error) });
107 return null;
108 }
109 };
110 const fail = (url: string, agent: string, res: Response, why: string) =>
111 failures.push({ url, agent, status: res.status, contentType: res.headers.get("content-type") ?? "", why });
112
113 for (const agent of Object.keys(AGENTS)) {
114 const auth: Record<string, string> = token ? { authorization: `Bearer ${token}` } : {};
115 const home = await get("/", agent);
116 if (home) {
117 if (home.res.status !== 200) fail(home.url, agent, home.res, "expected 200");
118 else {
119 const href = stylesheetHref(home.body);
120 if (!href) failures.push({ url: home.url, agent, status: 200, contentType: "", why: "no stylesheet linked" });
121 else {
122 const css = await get(href, agent);
123 if (css) {
124 const type = css.res.headers.get("content-type") ?? "";
125 if (css.res.status !== 200) fail(css.url, agent, css.res, "expected 200");
126 else if (!/^text\/css\b/i.test(type)) fail(css.url, agent, css.res, "expected text/css");
127 else if (!css.body.trim()) fail(css.url, agent, css.res, "empty stylesheet");
128 }
129 }
130 }
131 }
132 const board = await get("/board", agent, auth);
133 const signIn = options.anonymousBoard && !token && board?.res.status === 302;
134 if (board && board.res.status !== 200 && !signIn) fail(board.url, agent, board.res, "expected 200 (a 302 is sign-in)");
135 const health = await get("/healthz", agent);
136 if (health && health.res.status !== 200) fail(health.url, agent, health.res, "expected 200");
137 }
138
139 const sw = await get("/sw.js", "desktop");
140 if (sw) {
141 const type = sw.res.headers.get("content-type") ?? "";
142 if (sw.res.status !== 200) fail(sw.url, "desktop", sw.res, "expected 200");
143 else if (!/^(text|application)\/(x-)?javascript\b/i.test(type)) fail(sw.url, "desktop", sw.res, "expected javascript");
144 else {
145 const nav = navigationBranch(sw.body);
146 if (nav === null) fail(sw.url, "desktop", sw.res, "no navigation branch");
147 else if (/Response\s*\.\s*error\s*\(/.test(nav)) fail(sw.url, "desktop", sw.res, "a navigation can be answered with Response.error()");
148 }
149 }
150 return failures;
151 }
14 import { smoke } from "../src/release/smoke.ts";
15 export * from "../src/release/smoke.ts";
15216
15317 if (import.meta.main) {
15418 const args = process.argv.slice(2);
src/checks/service.ts +1 −1
@@ -61,7 +61,7 @@ import { appendRunLog } from "../runs/log.ts";
6161 import { runningLimitSentence, runningRuns } from "../settings/quotas.ts";
6262 import { exportTree, readFileAt } from "../apps/checkout.ts";
6363 import { parseCheck } from "../apps/manifest.ts";
64 import { workerCpus } from "../../scripts/shards.ts";
64 import { workerCpus } from "../core/capacity.ts";
6565 import { accountActive } from "../core/accounts.ts";
6666 import { childEnv, runStep } from "../apps/process.ts";
6767 import { noteReached } from "../apps/egress_report.ts";
src/core/capacity.ts +20
@@ -176,6 +176,26 @@ export function cpuLimit(file = "/sys/fs/cgroup/cpu.max"): number {
176176 return machine;
177177 }
178178
179 /**
180 * The share of a check cell's declared CPUs the workers are sized to. The
181 * cell's watchdog (`src/apps/contain.ts`) stops a check whose tree averages
182 * more than `check.limits.cpus` cores over 30 s, and a worker is more than
183 * one core at its peaks (Bun's own threads, git children, a booted forge):
184 * one worker per declared CPU averaged 16.1 of 16 and stopped main (#2161).
185 */
186 export const CELL_CPU_SHARE = 3 / 4;
187
188 /**
189 * The CPUs the gate sizes its workers to: the machine's, held under
190 * {@link CELL_CPU_SHARE} of the cell's CPU limit (`FORGE_CELL_CPUS`) when
191 * there is one, at least one. `availableParallelism()` sees the host, not
192 * the cell: the cell is a watchdog, not a CPU quota the process can read.
193 */
194 export function workerCpus(machine: number, declared: number | undefined): number {
195 if (declared === undefined || !Number.isFinite(declared) || declared <= 0) return machine;
196 return Math.max(1, Math.min(machine, Math.floor(declared * CELL_CPU_SHARE)));
197 }
198
179199 const GIB = 1024 ** 3;
180200 const MIB = 1024 ** 2;
181201
src/release/boot.ts added +231
@@ -0,0 +1,231 @@
1 /**
2 * Does this tree boot? `bun src/release/boot.ts` starts `src/main.ts` on a
3 * scratch data directory and a free loopback port, asks `/api/v1/health`
4 * until it answers as the version the image is stamped with, and stops it
5 * whatever the answer. One line out, exit 0 or 1 (2 for a bad argument).
6 *
7 * bun src/release/boot.ts an empty data directory: the
8 * release build (Dockerfile)
9 * bun src/release/boot.ts --from /data a copy of a live one: the
10 * promote preflight (chart hook)
11 *
12 * 0.7.166 passed the full check from the repository and crashed at boot from
13 * its image (`Cannot find module '../../scripts/smoke.ts'`); nothing had
14 * started the image it was (#2652). This is that start, at build and before
15 * the roll. With `--from`, the copy is the database (`VACUUM INTO`, so a
16 * forge writing it beside this is read whole) and the data directory's
17 * top-level files (the secret key); repositories and app data stay where
18 * they are. It lives in a directory of its own under the data directory and
19 * is removed in a `finally`.
20 *
21 * It imports nothing a release could break but the stamp it reads: the child
22 * is the thing on trial, not this.
23 */
24
25 import { Database } from "bun:sqlite";
26 import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
27 import { tmpdir } from "node:os";
28 import { join } from "node:path";
29 import { running } from "../kernel/version.ts";
30
31 export const BOOT_BUDGET_MS = 120_000;
32 const POLL_MS = 250;
33 /** A scratch directory older than this was left by a killed run. */
34 const STALE_MS = 60 * 60 * 1000;
35 const SCRATCH = "boot-proof-";
36
37 export type BootProof = { ok: true; ms: number } | { ok: false; line: string };
38
39 export interface BootInput {
40 /** The directory holding `src/main.ts`. */
41 readonly tree: string;
42 /** What `/api/v1/health` must say it is. */
43 readonly version: string;
44 /** The data directory the forge boots on; a scratch one, never a live one. */
45 readonly dataDir: string;
46 readonly budgetMs?: number;
47 /** Where PATH, HOME and TMPDIR come from; the process's own unless a test says. */
48 readonly env?: Readonly<Record<string, string | undefined>>;
49 }
50
51 async function freePort(): Promise<number> {
52 const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("") });
53 const port = probe.port ?? 0;
54 await probe.stop(true);
55 return port;
56 }
57
58 /** The line of what the child printed that says why: the first error, else the last line. */
59 export function why(stderr: string): string {
60 const lines = stderr
61 .split("\n")
62 .map((l) => l.trim())
63 .filter((l) => l !== "");
64 const line = lines.find((l) => /\berror\b/i.test(l)) ?? lines.at(-1) ?? "";
65 // eslint-disable-next-line no-control-regex
66 return line.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 300);
67 }
68
69 async function versionAt(port: number): Promise<string | undefined> {
70 try {
71 const res = await fetch(`http://127.0.0.1:${port}/api/v1/health`, {
72 headers: { connection: "close" },
73 signal: AbortSignal.timeout(2_000),
74 });
75 if (!res.ok) return undefined;
76 const body = (await res.json()) as { version?: unknown };
77 return typeof body.version === "string" ? body.version : undefined;
78 } catch {
79 return undefined;
80 }
81 }
82
83 /** Start the tree on `dataDir` and wait for it to answer health as `version`. */
84 export async function bootProof(input: BootInput): Promise<BootProof> {
85 const entry = join(input.tree, "src", "main.ts");
86 if (!existsSync(entry)) return { ok: false, line: `${input.tree} has no src/main.ts` };
87 const host = input.env ?? process.env;
88 const port = await freePort();
89 const env: Record<string, string> = {
90 PATH: host["PATH"] ?? "/usr/local/bin:/usr/bin:/bin",
91 FORGE_DATA: input.dataDir,
92 PORT: String(port),
93 FORGE_SSH_PORT: "0",
94 // The crew stays off a copy of production's queue.
95 FORGE_APP_ENV: "preview",
96 FORGE_VERSION: input.version,
97 };
98 for (const key of ["HOME", "TMPDIR", "FORGE_TEST_SOCKET"]) {
99 const value = host[key];
100 if (value !== undefined && value !== "") env[key] = value;
101 }
102 const started = performance.now();
103 const budget = input.budgetMs ?? BOOT_BUDGET_MS;
104 const child = Bun.spawn([process.execPath, entry], {
105 cwd: input.tree,
106 env,
107 stdin: "ignore",
108 stdout: "ignore",
109 stderr: "pipe",
110 });
111 let stderr = "";
112 const reading = (async () => {
113 const decoder = new TextDecoder();
114 for await (const chunk of child.stderr) stderr = (stderr + decoder.decode(chunk, { stream: true })).slice(-8_192);
115 })().catch(() => undefined);
116 let last = "no answer";
117 try {
118 while (performance.now() - started < budget) {
119 if (child.exitCode !== null) {
120 await reading;
121 const said = why(stderr);
122 return { ok: false, line: `exited with ${child.exitCode} before it answered health${said ? `: ${said}` : ""}` };
123 }
124 const seen = await versionAt(port);
125 if (seen === input.version) return { ok: true, ms: Math.round(performance.now() - started) };
126 if (seen !== undefined) last = `health answered as ${seen}`;
127 await Bun.sleep(POLL_MS);
128 }
129 const said = why(stderr);
130 return {
131 ok: false,
132 line: `did not answer health as ${input.version} within ${Math.round(budget / 1000)}s (${last})${said ? `: ${said}` : ""}`,
133 };
134 } finally {
135 child.kill("SIGKILL");
136 await child.exited;
137 }
138 }
139
140 /**
141 * Copy what a forge boots on from `from` into `to`: the database, whole, as
142 * of one moment, and the data directory's other top-level files.
143 */
144 export function copyData(from: string, to: string): void {
145 mkdirSync(to, { recursive: true });
146 for (const entry of readdirSync(from, { withFileTypes: true })) {
147 if (!entry.isFile() || entry.name.startsWith("forge.db")) continue;
148 copyFileSync(join(from, entry.name), join(to, entry.name));
149 }
150 const live = join(from, "forge.db");
151 if (!existsSync(live)) return;
152 const db = new Database(live, { readonly: true });
153 try {
154 db.run("VACUUM INTO ?", [join(to, "forge.db")]);
155 } finally {
156 db.close();
157 }
158 }
159
160 function sweepStale(dir: string): void {
161 for (const name of readdirSync(dir)) {
162 if (!name.startsWith(SCRATCH)) continue;
163 const path = join(dir, name);
164 try {
165 if (Date.now() - statSync(path).mtimeMs > STALE_MS) rmSync(path, { recursive: true, force: true });
166 } catch {
167 // Gone already, or not ours: leave it.
168 }
169 }
170 }
171
172 export interface ProveBootInput {
173 readonly tree: string;
174 readonly version: string;
175 /** A live data directory to boot a copy of; an empty one when absent. */
176 readonly from?: string | undefined;
177 readonly budgetMs?: number;
178 readonly env?: Readonly<Record<string, string | undefined>>;
179 }
180
181 /** The whole proof: a scratch directory, the copy when asked, the boot, the clean-up. */
182 export async function proveBoot(input: ProveBootInput): Promise<BootProof> {
183 let root = input.env?.["TMPDIR"] || tmpdir();
184 if (input.from !== undefined) {
185 if (!existsSync(join(input.from, "forge.db")))
186 return { ok: false, line: `${input.from} holds no forge.db to copy` };
187 root = input.from;
188 sweepStale(root);
189 }
190 const scratch = mkdtempSync(join(root, SCRATCH));
191 try {
192 const dataDir = join(scratch, "data");
193 if (input.from !== undefined) copyData(input.from, dataDir);
194 else mkdirSync(dataDir);
195 return await bootProof({ ...input, dataDir });
196 } catch (error) {
197 return { ok: false, line: `could not prepare the scratch data directory: ${String(error).slice(0, 200)}` };
198 } finally {
199 rmSync(scratch, { recursive: true, force: true });
200 }
201 }
202
203 /** `--from <dir>` and `--budget <seconds>`, or why not. */
204 export function parseArgs(argv: readonly string[]): { from?: string; budgetMs: number } | string {
205 let from: string | undefined;
206 let budgetMs = BOOT_BUDGET_MS;
207 for (let i = 0; i < argv.length; i++) {
208 const flag = argv[i];
209 const value = argv[i + 1];
210 if (flag === "--from" && value !== undefined && value !== "") from = value;
211 else if (flag === "--budget" && value !== undefined && /^[1-9][0-9]{0,3}$/.test(value)) budgetMs = Number(value) * 1000;
212 else return "usage: bun src/release/boot.ts [--from <data dir>] [--budget <seconds, 1 to 9999>]";
213 i++;
214 }
215 return from === undefined ? { budgetMs } : { from, budgetMs };
216 }
217
218 if (import.meta.main) {
219 const args = parseArgs(process.argv.slice(2));
220 if (typeof args === "string") {
221 console.error(args);
222 process.exit(2);
223 }
224 const { version } = running();
225 const tree = join(import.meta.dir, "..", "..");
226 const result = await proveBoot({ tree, version, ...args });
227 const what = args.from === undefined ? "an empty data directory" : `a copy of ${args.from}`;
228 if (result.ok) console.log(`boot ok: ${version} answered health on ${what} in ${result.ms}ms`);
229 else console.error(`boot failed: ${version} on ${what} ${result.line}`);
230 process.exit(result.ok ? 0 : 1);
231 }
src/release/prove.ts +2 −2
@@ -1,7 +1,7 @@
11 /**
22 * Is this release so: once per version, after a boot that changed it, the
33 * forge waits for its own public URL to answer `/healthz` as that version,
4 * then runs the smoke checks (`scripts/smoke.ts`) against it. The verdict is
4 * then runs the smoke checks (`release/smoke.ts`) against it. The verdict is
55 * one small file under the data directory (`release/proof.json`), so a
66 * restart of the same version never runs it again and vitals reads it
77 * without the network. A failure is a `release` card, paged once by the
@@ -10,7 +10,7 @@
1010
1111 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1212 import { join } from "node:path";
13 import { smoke, type Failure } from "../../scripts/smoke.ts";
13 import { smoke, type Failure } from "./smoke.ts";
1414 import { UNSTAMPED } from "../kernel/version.ts";
1515
1616 /** How long the public URL has to answer as the new version. */
src/release/smoke.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * Is the forge answering, as a phone and as a desktop? Each of `/`, `/board`
3 * (signed in with a token) and `/healthz` is fetched once per user agent and
4 * must answer 200; the stylesheet linked from `/` must be a non-empty
5 * `text/css` 200; `/sw.js` must be a 200 JavaScript response whose navigation
6 * branch never answers with `Response.error()`. With `version`, `/healthz` is
7 * first polled until `X-Forge-Version` is that version.
8 *
9 * The running forge proves each new version with it (`release/prove.ts`), so
10 * it lives here: the image ships src/ and nothing else (#2652).
11 * `bun scripts/smoke.ts <url>` is the same checks from a shell.
12 */
13
14 export const AGENTS: Record<string, string> = {
15 phone:
16 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
17 desktop:
18 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
19 };
20
21 export interface Failure {
22 url: string;
23 agent: string;
24 status: number | string;
25 contentType: string;
26 why: string;
27 }
28
29 /** The first stylesheet href in a page, or null. */
30 export function stylesheetHref(html: string): string | null {
31 for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {
32 if (!/\brel\s*=\s*["']?stylesheet/i.test(tag)) continue;
33 const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag);
34 const value = href?.[1] ?? href?.[2];
35 if (value) return value.replaceAll("&amp;", "&");
36 }
37 return null;
38 }
39
40 /** The part of a service worker that answers navigations, comments removed. */
41 export function navigationBranch(source: string): string | null {
42 const at = source.search(/mode\s*===?\s*["']navigate["']/);
43 if (at < 0) return null;
44 const rest = source.slice(at);
45 const end = rest.search(/\breturn\s*;/);
46 return (end < 0 ? rest : rest.slice(0, end)).replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
47 }
48
49 export interface Options {
50 /** Wait for `/healthz` to report this `X-Forge-Version`. */
51 version?: string | undefined;
52 /** Longest wait for it, in milliseconds. */
53 waitMs?: number;
54 /** Pause between polls, in milliseconds. */
55 pollMs?: number;
56 /** The fetch to use; the global one unless a caller (the forge proving itself, a test) gives its own. */
57 fetch?: typeof fetch;
58 /** Accept a redirect from `/board` as the sign-in it is, for a caller holding no token. */
59 anonymousBoard?: boolean;
60 }
61
62 /** Polls `/healthz` until it reports `version`; null when it does, else a failure. */
63 async function waitForVersion(root: URL, version: string, waitMs: number, pollMs: number, fetch: typeof globalThis.fetch): Promise<Failure | null> {
64 const url = new URL("/healthz", root).href;
65 const deadline = Date.now() + waitMs;
66 let seen = "none";
67 let status: number | string = "error";
68 for (;;) {
69 try {
70 const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(5_000) });
71 await res.body?.cancel();
72 status = res.status;
73 seen = res.headers.get("x-forge-version") ?? "none";
74 if (seen === version) return null;
75 } catch (error) {
76 status = "error";
77 seen = `none (${error})`;
78 }
79 if (Date.now() + pollMs > deadline) break;
80 await Bun.sleep(pollMs);
81 }
82 return { url, agent: "-", status, contentType: "", why: `wanted X-Forge-Version ${version}, last saw ${seen}` };
83 }
84
85 /** Runs every check against `base`; returns the failures (empty is green). */
86 export async function smoke(base: string, token = "", options: Options = {}): Promise<Failure[]> {
87 const root = new URL(base);
88 if (root.protocol !== "http:" && root.protocol !== "https:") throw new Error("url must be http(s)");
89 const failures: Failure[] = [];
90 const fetch = options.fetch ?? globalThis.fetch;
91 if (options.version) {
92 const late = await waitForVersion(root, options.version, options.waitMs ?? 120_000, options.pollMs ?? 1_000, fetch);
93 if (late) return [late];
94 }
95
96 const get = async (path: string, agent: string, headers: Record<string, string> = {}) => {
97 const url = new URL(path, root).href;
98 try {
99 const res = await fetch(url, {
100 redirect: "manual",
101 signal: AbortSignal.timeout(10_000),
102 headers: { "user-agent": AGENTS[agent]!, ...headers },
103 });
104 return { url, res, body: await res.text() };
105 } catch (error) {
106 failures.push({ url, agent, status: "error", contentType: "", why: String(error) });
107 return null;
108 }
109 };
110 const fail = (url: string, agent: string, res: Response, why: string) =>
111 failures.push({ url, agent, status: res.status, contentType: res.headers.get("content-type") ?? "", why });
112
113 for (const agent of Object.keys(AGENTS)) {
114 const auth: Record<string, string> = token ? { authorization: `Bearer ${token}` } : {};
115 const home = await get("/", agent);
116 if (home) {
117 if (home.res.status !== 200) fail(home.url, agent, home.res, "expected 200");
118 else {
119 const href = stylesheetHref(home.body);
120 if (!href) failures.push({ url: home.url, agent, status: 200, contentType: "", why: "no stylesheet linked" });
121 else {
122 const css = await get(href, agent);
123 if (css) {
124 const type = css.res.headers.get("content-type") ?? "";
125 if (css.res.status !== 200) fail(css.url, agent, css.res, "expected 200");
126 else if (!/^text\/css\b/i.test(type)) fail(css.url, agent, css.res, "expected text/css");
127 else if (!css.body.trim()) fail(css.url, agent, css.res, "empty stylesheet");
128 }
129 }
130 }
131 }
132 const board = await get("/board", agent, auth);
133 const signIn = options.anonymousBoard && !token && board?.res.status === 302;
134 if (board && board.res.status !== 200 && !signIn) fail(board.url, agent, board.res, "expected 200 (a 302 is sign-in)");
135 const health = await get("/healthz", agent);
136 if (health && health.res.status !== 200) fail(health.url, agent, health.res, "expected 200");
137 }
138
139 const sw = await get("/sw.js", "desktop");
140 if (sw) {
141 const type = sw.res.headers.get("content-type") ?? "";
142 if (sw.res.status !== 200) fail(sw.url, "desktop", sw.res, "expected 200");
143 else if (!/^(text|application)\/(x-)?javascript\b/i.test(type)) fail(sw.url, "desktop", sw.res, "expected javascript");
144 else {
145 const nav = navigationBranch(sw.body);
146 if (nav === null) fail(sw.url, "desktop", sw.res, "no navigation branch");
147 else if (/Response\s*\.\s*error\s*\(/.test(nav)) fail(sw.url, "desktop", sw.res, "a navigation can be answered with Response.error()");
148 }
149 }
150 return failures;
151 }
test/release-boot.test.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * A release that does not boot is refused before it ships (#2652): the
3 * build and the promote preflight both run `src/release/boot.ts`, which
4 * starts the tree on a scratch data directory and wants `/api/v1/health` to
5 * answer as the stamped version. 0.7.166's image crashed at import; a tree
6 * that does the same is refused here, naming the error.
7 */
8
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { Database } from "bun:sqlite";
11 import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { bootProof, parseArgs, proveBoot, why } from "../src/release/boot.ts";
15
16 let root: string;
17 beforeAll(() => {
18 root = mkdtempSync(join(tmpdir(), "forge-release-boot-"));
19 });
20 afterAll(() => rmSync(root, { recursive: true, force: true }));
21
22 /** A tree whose `src/main.ts` is `main`. */
23 function tree(name: string, main: string): string {
24 const dir = join(root, name);
25 mkdirSync(join(dir, "src"), { recursive: true });
26 writeFileSync(join(dir, "src", "main.ts"), main);
27 return dir;
28 }
29
30 /** A forge in miniature: health answers with whatever `version()` says. */
31 const serving = (version: string) => `
32 Bun.serve({ hostname: "127.0.0.1", port: Number(process.env.PORT), fetch(req) {
33 if (new URL(req.url).pathname !== "/api/v1/health") return new Response("", { status: 404 });
34 return Response.json({ ok: true, version: ${version} });
35 } });
36 `;
37
38 test("a tree whose main import throws is refused, naming the module it could not find", async () => {
39 const dir = tree("broken", `import { smoke } from "../../scripts/smoke.ts";\nconsole.log(smoke);\n`);
40 const result = await proveBoot({ tree: dir, version: "0.7.166", budgetMs: 30_000 });
41 expect(result.ok).toBe(false);
42 if (!result.ok) {
43 expect(result.line).toStartWith("exited with 1 before it answered health: ");
44 expect(result.line).toContain("Cannot find module '../../scripts/smoke.ts'");
45 }
46 });
47
48 test("a tree that answers as its version passes; the scratch directory is gone after", async () => {
49 const dir = tree("well", serving("process.env.FORGE_VERSION"));
50 const before = readdirSync(tmpdir()).filter((n) => n.startsWith("boot-proof-")).length;
51 const result = await proveBoot({ tree: dir, version: "1.2.3", budgetMs: 30_000 });
52 expect(result).toMatchObject({ ok: true });
53 expect(readdirSync(tmpdir()).filter((n) => n.startsWith("boot-proof-")).length).toBe(before);
54 });
55
56 test("an answer as another version is not a pass: the budget runs out and says what it saw", async () => {
57 const dir = tree("stale", serving(`"0.0.1"`));
58 const result = await bootProof({ tree: dir, version: "1.2.3", dataDir: join(root, "stale-data"), budgetMs: 2_000 });
59 expect(result).toEqual({ ok: false, line: "did not answer health as 1.2.3 within 2s (health answered as 0.0.1)" });
60 });
61
62 test("--from boots a copy of the live data: the database as it is, the top-level files, never the live directory", async () => {
63 const live = join(root, "live");
64 mkdirSync(join(live, "repos", "a"), { recursive: true });
65 writeFileSync(join(live, "secret.key"), "k", { mode: 0o600 });
66 const db = new Database(join(live, "forge.db"), { create: true });
67 db.run("PRAGMA journal_mode=WAL");
68 db.run("CREATE TABLE stamp (v TEXT)");
69 db.run("INSERT INTO stamp VALUES ('4.5.6')");
70 // Held open, as the running forge holds it: the row is in the log, not yet the file.
71 const dir = tree(
72 "copied",
73 `import { Database } from "bun:sqlite";
74 import { existsSync, readFileSync } from "node:fs";
75 const data = process.env.FORGE_DATA!;
76 if (readFileSync(data + "/secret.key", "utf8") !== "k" || existsSync(data + "/repos")) process.exit(3);
77 const v = new Database(data + "/forge.db").query("SELECT v FROM stamp").get().v;
78 ${serving("v")}`,
79 );
80 try {
81 expect(await proveBoot({ tree: dir, version: "4.5.6", from: live, budgetMs: 30_000 })).toMatchObject({ ok: true });
82 } finally {
83 db.close();
84 }
85 expect(readdirSync(live).sort()).toEqual(["forge.db", "repos", "secret.key"]);
86 expect(await proveBoot({ tree: dir, version: "4.5.6", from: join(root, "nowhere") })).toEqual({
87 ok: false,
88 line: `${join(root, "nowhere")} holds no forge.db to copy`,
89 });
90 });
91
92 test("this tree, shipped as the image ships it (src/ alone), boots", async () => {
93 const image = join(root, "image");
94 const repo = join(import.meta.dir, "..");
95 cpSync(join(repo, "src"), join(image, "src"), { recursive: true });
96 for (const file of ["package.json", "tsconfig.json"]) cpSync(join(repo, file), join(image, file));
97 expect(existsSync(join(image, "scripts"))).toBe(false);
98 const result = await proveBoot({ tree: image, version: "9.9.9", budgetMs: 60_000 });
99 expect(result).toMatchObject({ ok: true });
100 }, 90_000);
101
102 test("the reason is the error line, one line, bounded", () => {
103 expect(why("\n1 | import x\n ^\nerror: Cannot find module 'x'\n at y\n\nBun v1.3\n")).toBe("error: Cannot find module 'x'");
104 expect(why("just died\n")).toBe("just died");
105 expect(why("")).toBe("");
106 expect(why("x".repeat(500)).length).toBe(300);
107 });
108
109 test("arguments: --from and --budget, nothing else", () => {
110 expect(parseArgs([])).toEqual({ budgetMs: 120_000 });
111 expect(parseArgs(["--from", "/data", "--budget", "60"])).toEqual({ from: "/data", budgetMs: 60_000 });
112 for (const bad of [["--from"], ["--budget", "0"], ["--budget", "1e3"], ["--nope"], ["/data"]])
113 expect(typeof parseArgs(bad)).toBe("string");
114 });
115
116 test("the build runs the proof on the image it built, and the chart runs it on a copy before an upgrade", async () => {
117 const repo = join(import.meta.dir, "..");
118 const docker = await Bun.file(join(repo, "Dockerfile")).text();
119 const lines = docker.split("\n");
120 const copied = lines.findIndex((l) => l.startsWith("COPY src "));
121 const proved = lines.indexOf("RUN bun src/release/boot.ts");
122 expect(copied).toBeGreaterThan(-1);
123 expect(proved).toBeGreaterThan(copied);
124 expect(proved).toBeGreaterThan(lines.findIndex((l) => l.startsWith("ENV FORGE_VERSION=")));
125 const hook = await Bun.file(join(repo, "charts/app/templates/boot-proof.yaml")).text();
126 expect(hook).toContain("helm.sh/hook: pre-upgrade");
127 expect(hook).toContain('command: ["bun", "src/release/boot.ts", "--from", "/data", "--budget", "180"]');
128 expect(hook).toContain("claimName: {{ .Release.Name }}-data");
129 expect(hook).toContain("backoffLimit: 0");
130 });
test/src-imports.test.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * The image ships `src/` and nothing else (Dockerfile): a module under src/
3 * that imports from scripts/ or test/ boots from the repository and crashes
4 * in production. 0.7.166 did, on `src/release/prove.ts` importing
5 * `scripts/smoke.ts`, and was down two hours (#2652). Every relative import
6 * a src/ file makes, static or dynamic, must resolve inside src/.
7 */
8
9 import { expect, test } from "bun:test";
10 import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11 import { dirname, join, relative, resolve, sep } from "node:path";
12
13 const ROOT = resolve(import.meta.dir, "..");
14 const SRC = join(ROOT, "src");
15
16 function sources(dir: string): string[] {
17 const out: string[] = [];
18 for (const entry of readdirSync(dir, { withFileTypes: true })) {
19 const path = join(dir, entry.name);
20 if (entry.isDirectory()) out.push(...sources(path));
21 else if (/\.(ts|tsx|js|mjs)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) out.push(path);
22 }
23 return out;
24 }
25
26 /** Each relative import in `files` that resolves outside `src`, as `file -> specifier`. */
27 export function escapes(files: readonly string[], src: string): string[] {
28 const scanners = { ts: new Bun.Transpiler({ loader: "ts" }), tsx: new Bun.Transpiler({ loader: "tsx" }) };
29 const bad: string[] = [];
30 for (const file of files) {
31 const scanner = file.endsWith(".tsx") ? scanners.tsx : scanners.ts;
32 for (const { path } of scanner.scanImports(readFileSync(file, "utf8").replace(/^#!.*/, ""))) {
33 if (!path.startsWith(".")) continue;
34 const target = resolve(dirname(file), path);
35 if (target !== src && !target.startsWith(src + sep)) bad.push(`${relative(ROOT, file)} -> ${path}`);
36 }
37 }
38 return bad;
39 }
40
41 test("nothing under src/ imports from outside src/ (scripts/, test/, …)", () => {
42 expect(escapes(sources(SRC), SRC)).toEqual([]);
43 });
44
45 test("the walk sees a static import, a re-export and a dynamic import that leave src/", () => {
46 const dir = join(process.env.TMPDIR ?? "/tmp", `src-imports-${process.pid}`);
47 const src = join(dir, "src");
48 const file = join(src, "release", "x.ts");
49 mkdirSync(dirname(file), { recursive: true });
50 writeFileSync(
51 file,
52 [
53 'import { smoke } from "../../scripts/smoke.ts";',
54 'export { h } from "../../test/helpers/h.ts";',
55 'const m = await import("../../scripts/shards.ts");',
56 'import { ok } from "../kernel/result.ts";',
57 'const text = `import { lint } from "../../scripts/lint-design.ts";`;',
58 "console.log(smoke, m, ok, text);",
59 ].join("\n"),
60 );
61 try {
62 expect(escapes([file], src).map((l) => l.split(" -> ")[1])).toEqual([
63 "../../scripts/smoke.ts",
64 "../../test/helpers/h.ts",
65 "../../scripts/shards.ts",
66 ]);
67 } finally {
68 rmSync(dir, { recursive: true, force: true });
69 }
70 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs