Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Worker build: import every built module before each build

Adarshc8018cf1ec0a
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index 49545733..184579e3 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -71,6 +71,10 @@ jobs:
- name: Typecheck
run: pnpm exec next typegen && pnpm typecheck
+ # The worker program's built parts, as a worker loads them: every built module is imported (a few seconds).
+ - name: Worker parts load
+ run: node scripts/check-worker-build.mjs
+
- name: Build
run: pnpm build
diff --git a/scripts/check-worker-build.mjs b/scripts/check-worker-build.mjs
new file mode 100644
index 00000000..d790a496
--- /dev/null
+++ b/scripts/check-worker-build.mjs
@@ -0,0 +1,101 @@
+#!/usr/bin/env node
+// Checks that the worker program's shared parts load (docs/gpu-workers.md): builds them with scripts/build-worker.mjs
+// into a new temporary folder (or reads a folder built already), then imports every .mjs file in it and checks the
+// exports the worker program reads from them. A built file that imports something the build doesn't include, or that
+// fails when it loads, stops a worker at its start; typecheck and the tests run the TypeScript sources, so only this
+// finds it. Exit code 1 on any failure, with each one named.
+//
+// node scripts/check-worker-build.mjs # build into a temporary folder, then check it
+// node scripts/check-worker-build.mjs --dir <dir> # check a folder built already (bin/lib/worker/dist after `pnpm build`)
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+
+/**
+ * The exports the worker program (bin/lib/worker/*.mjs) reads from each built file it imports by name. Every
+ * `import("./dist/…")` in the worker program names a file here (the tests hold the list to that).
+ */
+export const WORKER_READS = {
+ "computer-runner.mjs": ["ComputerRunner"],
+ "engine-error.mjs": ["withoutLocalPaths"],
+ "lanes.mjs": ["allLanes"],
+ "compose/lib/ticket-compose.mjs": ["composeTicket", "workerFactsFrom"],
+};
+
+/** Every .mjs file under `dir`, as paths relative to it with forward slashes, sorted. */
+export function builtModules(dir) {
+ const out = [];
+ const walk = (d) => {
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.endsWith(".mjs")) out.push(path.relative(dir, p).split(path.sep).join("/"));
+ }
+ };
+ walk(dir);
+ return out.sort();
+}
+
+/**
+ * Import every .mjs file under `dir`, and check WORKER_READS (`reads`) against what they export. Returns the files it
+ * imported and each failure ("file: why"). A folder with no .mjs file fails too.
+ */
+export async function checkBuilt(dir, reads = WORKER_READS) {
+ const files = builtModules(dir);
+ const failures = [];
+ if (!files.length) failures.push(`${dir}: no built .mjs file`);
+ const loaded = new Map();
+ for (const f of files) {
+ try {
+ loaded.set(f, await import(pathToFileURL(path.join(dir, f)).href));
+ } catch (e) {
+ failures.push(`${f}: ${String(e?.message ?? e).split("\n")[0]}`);
+ }
+ }
+ for (const [f, names] of Object.entries(reads)) {
+ if (!files.includes(f)) {
+ failures.push(`${f}: not built, and the worker program imports it`);
+ continue;
+ }
+ const m = loaded.get(f);
+ if (!m) continue;
+ for (const n of names) if (m[n] === undefined) failures.push(`${f}: has no export ${n}, which the worker program reads`);
+ }
+ return { files, failures };
+}
+
+/** Build the worker's parts into a new temporary folder (scripts/build-worker.mjs --out). Returns the folder; throws when the build fails. */
+export function buildInto(dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-build-")), root = ROOT) {
+ const r = spawnSync(process.execPath, [path.join(root, "scripts/build-worker.mjs"), "--out", dir], { cwd: root, encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`The worker build failed: ${(r.stderr || r.stdout || "").trim() || `exit ${r.status}`}`);
+ return dir;
+}
+
+async function main(argv) {
+ const i = argv.indexOf("--dir");
+ const given = i >= 0 ? argv[i + 1] : undefined;
+ if (i >= 0 && !given) throw new Error("--dir needs a folder");
+ const dir = given ? path.resolve(given) : buildInto();
+ try {
+ const { files, failures } = await checkBuilt(dir);
+ if (failures.length) {
+ console.error(`The worker's built parts don't load (${failures.length}):\n ${failures.join("\n ")}`);
+ process.exitCode = 1;
+ return;
+ }
+ console.log(`worker build: ${files.length} modules load`);
+ } finally {
+ if (!given) fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ main(process.argv.slice(2)).catch((e) => {
+ console.error(e?.message ?? e);
+ process.exit(1);
+ });
+}
diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjs
index 280cbca1..5775aee8 100644
--- a/scripts/lib/worker-build.mjs
+++ b/scripts/lib/worker-build.mjs
@@ -120,7 +120,8 @@ export function workerFiles({ root = ROOT, catalogDir } = {}) {
if (!SOURCES.includes(dep)) throw new Error(`${name}.ts imports ./${dep}, which the worker build doesn't include`);
return `from "./${dep}.mjs"`;
});
- if (/from "(@\/|\.\.\/)/.test(js)) throw new Error(`${name}.ts imports something outside src/lib's worker files`);
+ // A sub-folder of src/lib (./gpu/argv) is outside the build as much as ../ or @/ is.
+ if (/from "(@\/|\.\.\/|\.\/[^"]*\/)/.test(js)) throw new Error(`${name}.ts imports something outside src/lib's worker files`);
files[`${name}.mjs`] = `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`;
}
const json = (data) => `${JSON.stringify({ built: "scripts/build-worker.mjs", ...data }, null, 1)}\n`;
diff --git a/tests/worker-build-loads.test.ts b/tests/worker-build-loads.test.ts
new file mode 100644
index 00000000..27da5ff5
--- /dev/null
+++ b/tests/worker-build-loads.test.ts
@@ -0,0 +1,59 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { WORKER_READS } from "../scripts/check-worker-build.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The worker program's built parts load as a worker loads them (scripts/check-worker-build.mjs, also a step of the
+ * deploy workflow): the build into a fresh folder, then every built .mjs file imported by Node itself (a child process,
+ * not this test runner's module loader, which would find files Node doesn't), and the exports the worker program reads
+ * from them. Typecheck and the other tests run the TypeScript sources, so a built file that imports a file the build
+ * doesn't include passes them and stops every worker at its start; this test fails on it.
+ */
+
+const ROOT = path.resolve(__dirname, "..");
+const check = (...args: string[]) => spawnSync(process.execPath, [path.join(ROOT, "scripts/check-worker-build.mjs"), ...args], { cwd: ROOT, encoding: "utf8" });
+
+describe("the worker's built parts", () => {
+ it("build and load: every built module imports in Node, with the exports the worker program reads", () => {
+ const r = check();
+ expect(r.stderr).toBe("");
+ expect(r.status).toBe(0);
+ expect(r.stdout).toMatch(/^worker build: \d+ modules load\n$/);
+ expect(Number(/(\d+) modules/.exec(r.stdout)![1])).toBeGreaterThan(100);
+ }, 120_000);
+
+ it("names every built file the worker program imports by name", () => {
+ const dir = path.join(ROOT, "bin/lib/worker");
+ const named = new Set<string>();
+ for (const f of fs.readdirSync(dir).filter((x) => x.endsWith(".mjs"))) {
+ for (const m of fs.readFileSync(path.join(dir, f), "utf8").matchAll(/import\(\s*"\.\/dist\/([^"]+\.mjs)"\s*\)/g)) named.add(m[1]);
+ }
+ expect(named.size).toBeGreaterThan(0);
+ expect([...named].sort()).toEqual(Object.keys(WORKER_READS).sort());
+ });
+
+ it("fails on an import the build doesn't include, one with no extension, an export the worker reads that is gone, or a part not built", () => {
+ const dir = tempDir("fuobe-worker-broken-");
+ fs.mkdirSync(path.join(dir, "compose/lib"), { recursive: true });
+ fs.writeFileSync(path.join(dir, "local-comfy.mjs"), 'import { parseArgv } from "./gpu/argv.mjs";\nexport const x = parseArgv;\n');
+ fs.writeFileSync(path.join(dir, "relay.mjs"), 'import { other } from "./lanes";\nexport const y = other;\n');
+ fs.writeFileSync(path.join(dir, "lanes.mjs"), "export const other = 1;\n");
+ fs.writeFileSync(path.join(dir, "engine-error.mjs"), "export const withoutLocalPaths = (s) => s;\n");
+ fs.writeFileSync(path.join(dir, "compose/lib/ticket-compose.mjs"), "export const composeTicket = () => null;\nexport const workerFactsFrom = () => null;\n");
+ const r = check("--dir", dir);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toBe("");
+ const lines = r.stderr.trim().split("\n").slice(1).map((l) => l.trim());
+ expect(lines).toEqual([
+ expect.stringMatching(/^local-comfy\.mjs: .*gpu[\\/]argv\.mjs/),
+ expect.stringMatching(/^relay\.mjs: .*lanes/),
+ "computer-runner.mjs: not built, and the worker program imports it",
+ "lanes.mjs: has no export allLanes, which the worker program reads",
+ ]);
+ const empty = tempDir("fuobe-worker-empty-");
+ expect(check("--dir", empty).stderr).toContain(`${empty}: no built .mjs file`);
+ }, 60_000);
+});