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

An app whose run names a build output is built once per commit before it starts #17899

opened this

Merged 22h 37m ago, live in production

scout/forge:scout/17891-an-app-whose-run-names-a-build-output-is → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/17891-an-app-whose-run-names-a-build-output-is was merged into main as da85963.

Review

Sign in to review this change.
4 files changed +179 −1
src/apps/entry_build.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * The build an app's entry waits for (#17891): `run` names a file under dist/, build/ or out/,
3 * the checkout lacks it, and package.json has a `build` script. Plain data in, plain data out;
4 * `process.ts` runs the step. A failure is written beside the checkout, so the commit is not
5 * built again: the next commit has another checkout.
6 */
7
8 import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9 import { join } from "node:path";
10 import { buildOutputMissing, isCompound } from "./run_command.ts";
11
12 const OUTPUT_RE = /^(?:\.\/)?(?:dist|build|out)\/[^\s'"]+$/;
13
14 /** The built entry `run` names that is not in `dir`, when a `build` script could make it. */
15 export function builtEntry(dir: string, run: string): { readonly path: string; readonly name: string } | undefined {
16 if (isCompound(run)) return undefined;
17 const path = run.split(/\s+/).find((word) => OUTPUT_RE.test(word));
18 if (path === undefined || path.includes("..") || existsSync(join(dir, path))) return undefined;
19 try {
20 const pkg: unknown = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
21 const scripts = typeof pkg === "object" && pkg !== null ? (pkg as { scripts?: unknown }).scripts : undefined;
22 const build = typeof scripts === "object" && scripts !== null ? (scripts as { build?: unknown }).build : undefined;
23 if (typeof build !== "string" || build.trim() === "") return undefined;
24 } catch {
25 return undefined;
26 }
27 return { path, name: path.split("/").pop() ?? path };
28 }
29
30 /** What the page says of a failed build: the #17834 words, the reason, the build's last lines. */
31 export function buildFailure(name: string, reason: string, tail: readonly string[]): string {
32 const lines = tail.filter((l) => l.trim() !== "").slice(-8).map((l) => l.slice(0, 200));
33 return `${buildOutputMissing(name)}; its build failed (${reason})${lines.length > 0 ? `:\n${lines.join("\n")}` : ""}`;
34 }
35
36 const failedFile = (dir: string): string => `${dir}.build-failed`;
37
38 export function noteBuildFailure(dir: string, message: string): void {
39 try {
40 writeFileSync(failedFile(dir), message);

Nothing deletes this marker when the checkout is dropped, so these files pile up beside checkouts. Remove it in the same place the checkout is swept.

41 } catch {
42 /* the commit is built again, which is all that is lost */
43 }
44 }
45
46 /** The failure noted for this checkout's commit, if its build failed before. */
47 export function priorBuildFailure(dir: string): string | undefined {
48 try {
49 return readFileSync(failedFile(dir), "utf8");
50 } catch {
51 return undefined;
52 }
53 }
54
55 export function forgetBuildFailure(dir: string): void {
56 rmSync(failedFile(dir), { force: true });
57 }
src/apps/process.ts +49
@@ -30,6 +30,7 @@ import { seconds } from "./timing.ts";
3030 import { supervise } from "./supervise.ts";
3131 import { toolchainUse, type ToolchainUse } from "./toolchain.ts";
3232 import { notFoundHint, shellCommand } from "./run_command.ts";
33 import { builtEntry, buildFailure, noteBuildFailure, priorBuildFailure, forgetBuildFailure } from "./entry_build.ts";
3334 import { floorRefusal } from "../spawn/disk_floor.ts";
3435 import { usedRefusal } from "./disk_guard.ts";
3536 import { cellInstall, meteredInstall, prefillInstallCache, withLock, installCommand } from "../checks/install.ts";
@@ -635,6 +636,52 @@ async function install(
635636 return meteredInstall(plan.cell?.label, input.cell?.repoId, step, input.log);
636637 }
637638
639 /**
640 * An entry under dist/, build/ or out/ that the checkout lacks, with a `build` script to make it
641 * (#17891): `bun install` if the manifest's install has not run, then the script, once for the
642 * commit, in the step's cell. A failure is remembered beside the checkout and not retried.
643 */
644 async function buildEntry(
645 input: StartInput,
646 env: Record<string, string>,
647 use: ToolchainUse | undefined,
648 cacheDir: string | undefined,
649 ): Promise<Result<void, string>> {
650 const wanted = builtEntry(input.dir, input.manifest.run);
651 if (wanted === undefined) return ok();
652 const before = priorBuildFailure(input.dir);
653 if (before !== undefined) return err(before);
654 if (input.scriptsOff === true) return ok();
655 const tail: string[] = [];
656 const log = (line: string): void => {
657 tail.push(line);
658 if (tail.length > 20) tail.shift();
659 input.log(line);
660 };
661 const failed = (reason: string): Result<void, string> => {
662 const message = buildFailure(wanted.name, reason, tail);
663 noteBuildFailure(input.dir, message);
664 return err(message);
665 };
666 input.log(`${wanted.name} is not in the checkout: building it with the package's build script`);
667 if (input.manifest.install === null || input.warm === true) {
668 const installed = await install("bun install", { ...input, log }, env, use, cacheDir);
669 if (!installed.ok) return failed(installed.error);
670 }
671 const step = await runStep("build", "bun run build", {
672 cwd: input.dir,
673 env,
674 log,
675 signal: input.signal,
676 cell: stepCell(input, use, cacheDir),
677 build: stepLimits(input),
678 });
679 if (!step.ok) return input.signal.aborted ? step : failed(step.error);
680 if (builtEntry(input.dir, input.manifest.run) !== undefined) return failed("the build ran and did not make it");
681 forgetBuildFailure(input.dir);
682 return ok();
683 }
684
638685 /**
639686 * Install, then start the app and run its tests side by side, and wait for
640687 * the app to answer on its port. Returns as soon as it does — `tested`
@@ -687,6 +734,8 @@ export async function startProcess(
687734 if (!installed.ok)
688735 return err({ stage: "install", message: installed.error });
689736 }
737 const built = await buildEntry(input, stepEnv, use, cacheDir);
738 if (!built.ok) return err({ stage: "install", message: built.error });
690739 if (input.signal.aborted)
691740 return err({ stage: "start", message: "cancelled" });
692741 const noted = (): void => {
src/apps/run_command.ts +9 −1
@@ -21,6 +21,14 @@ const NOT_FOUND_RE = /exec: ([^\s:]+): not found/;
2121 const MISSING_FILE_RE = /(?:Cannot find module|Module not found) ['"]((?:[^'"\s]*\/)?([^'"\s/]+\.(?:[cm]?[jt]s|json)))['"]/;
2222 const BUILT_DIR_RE = /(?:^|\/)(?:dist|build|out|\.output)\//;
2323
24 /**
25 * The cause and the fix when a build output is missing (#17830); a failed build adds its lines to
26 * it.
27 */
28 export function buildOutputMissing(name: string): string {
29 return `${name} is a build output and is not in the checkout: it is not committed and no step builds it before "run"; commit it, or build it in forge.json "install" (as in "bun install && bun run build")`;
30 }
31
2432 /**
2533 * When the app's entry file is not in the checkout (`Cannot find module '…/dist/server.js'`),
2634 * the cause and the fix in a sentence; undefined for anything else, a package name included.
@@ -33,7 +41,7 @@ function missingEntryHint(lines: readonly string[]): string | undefined {
3341 if (!path.includes("/")) continue;
3442 const name = found[2] ?? path;
3543 return BUILT_DIR_RE.test(path)
36 ? `${name} is a build output and is not in the checkout: it is not committed and no step builds it before "run"; commit it, or build it in forge.json "install" (as in "bun install && bun run build")`
44 ? buildOutputMissing(name)
3745 : `${name} is not in the checkout: commit it, or point forge.json "run" at a file that is`;
3846 }
3947 return undefined;
test/apps-compound-run.test.ts +64
@@ -92,3 +92,67 @@ test("an entry file that is not in the checkout ends the start with the cause an
9292 test("a missing package is not called a missing entry file", () => {
9393 expect(notFoundHint(["error: Cannot find module 'left-pad' from '/app/x.ts'"])).toBeUndefined();
9494 });
95
96 const SERVER = "Bun.serve({port:Number(process.env.PORT),hostname:'127.0.0.1',fetch:()=>new Response('built')})";
97
98 test("an entry the build makes is built once, then starts (#17891)", async () => {
99 const dir = await mkdtemp(join(tmpdir(), "forge-build-"));
100 try {
101 await writeFile(
102 join(dir, "package.json"),
103 JSON.stringify({ scripts: { build: "mkdir -p dist && echo x >> ran && cp src.js dist/server.js" } }),
104 );
105 await writeFile(join(dir, "src.js"), SERVER);
106 const lines: string[] = [];
107 const started = await start(dir, "bun dist/server.js", lines);
108 expect(started.ok).toBe(true);
109 if (!started.ok) return;
110 const res = await fetch(`http://127.0.0.1:${started.value.handle.port}/`);
111 expect(await res.text()).toBe("built");
112 await started.value.handle.stop();
113 await started.value.handle.exited;
114 // A second start finds the output: the script does not run again.
115 const again = await start(dir, "bun dist/server.js", lines);
116 expect(again.ok).toBe(true);
117 if (again.ok) {
118 await again.value.handle.stop();
119 await again.value.handle.exited;
120 }
121 expect((await Bun.file(join(dir, "ran")).text()).trim()).toBe("x");
122 } finally {
123 await rm(dir, { recursive: true, force: true });
124 }
125 }, 60_000);
126
127 test("a failed build shows its last lines in the #17834 words and is not retried (#17891)", async () => {
128 const dir = await mkdtemp(join(tmpdir(), "forge-buildfail-"));
129 try {
130 await writeFile(
131 join(dir, "package.json"),
132 JSON.stringify({ scripts: { build: "echo tried >> count; echo boom-line; exit 3" } }),
133 );
134 const first = await start(dir, "bun dist/server.js");
135 expect(first.ok).toBe(false);
136 if (first.ok) return;
137 expect(first.error.message).toContain("server.js is a build output and is not in the checkout");
138 expect(first.error.message).toContain("boom-line");
139 const second = await start(dir, "bun dist/server.js");
140 expect(second.ok).toBe(false);
141 expect((await Bun.file(join(dir, "count")).text()).trim()).toBe("tried");
142 } finally {
143 await rm(dir, { recursive: true, force: true });
144 await rm(`${dir}.build-failed`, { force: true });
145 }
146 }, 60_000);
147
148 test("without a build script the entry's start failure is unchanged (#17891)", async () => {
149 const dir = await mkdtemp(join(tmpdir(), "forge-nobuild-"));
150 try {
151 await writeFile(join(dir, "package.json"), JSON.stringify({ scripts: {} }));
152 const started = await start(dir, "bun dist/server.js");
153 expect(started.ok).toBe(false);
154 if (!started.ok) expect(started.error.message).toContain("server.js is a build output and is not in the checkout");
155 } finally {
156 await rm(dir, { recursive: true, force: true });
157 }
158 }, 30_000);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs