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.

Workers: a guarded ComfyUI that recovers from every stop, and clips and sound made again

Adarsha72780e32d23
diff --git a/bin/lib/worker/awake.mjs b/bin/lib/worker/awake.mjs
new file mode 100644
index 00000000..39650661
--- /dev/null
+++ b/bin/lib/worker/awake.mjs
@@ -0,0 +1,79 @@
+// Keeps the PC from sleeping while the worker holds a job or waits for one (docs/gpu-workers.md). A sleeping PC stops its
+// jobs halfway. A small helper process asks the system to stay awake for as long as it runs: on Windows it calls
+// SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED) and waits; on macOS it is `caffeinate -i`; on Linux
+// `systemd-inhibit`. Each one ends when the worker closes its input, or when the worker itself stops, and the PC may
+// sleep again. The screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.
+import { spawn } from "node:child_process";
+
+/** ES_CONTINUOUS (0x80000000) | ES_SYSTEM_REQUIRED (0x1), written in decimal for Windows PowerShell 5.1. */
+const WINDOWS_SCRIPT = `$ErrorActionPreference = "Stop"
+$k = Add-Type -Name Power -Namespace FuobeWorker -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint flags);'
+if ($k::SetThreadExecutionState([uint32]2147483649) -eq 0) { exit 3 }
+[void][Console]::In.ReadLine()
+`;
+
+/** The helper's command for this system, or null (none: the PC's own power settings decide). */
+export function helperCommand(platform = process.platform, pid = process.pid) {
+ if (platform === "win32") return ["powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(WINDOWS_SCRIPT, "utf16le").toString("base64")]];
+ if (platform === "darwin") return ["caffeinate", ["-i", "-w", String(pid)]];
+ if (platform === "linux") return ["systemd-inhibit", ["--what=sleep:idle", "--who=Fuobe worker", "--why=Running a job", "--mode=block", "cat"]];
+ return null;
+}
+
+/** A helper that stopped by itself is started again at most this often. */
+const RETRY_MS = 10 * 60_000;
+
+export class StayAwake {
+ /** `o`: { spawn, platform, now, log } (tests give their own). */
+ constructor(o = {}) {
+ this.o = o;
+ this.child = null;
+ this.failedAt = -Infinity;
+ }
+
+ get on() {
+ return !!this.child;
+ }
+
+ /** Awake (true) or free to sleep (false). */
+ set(on) {
+ if (on && !this.child) this.start();
+ else if (!on && this.child) this.stop();
+ }
+
+ start() {
+ const now = (this.o.now ?? Date.now)();
+ if (now - this.failedAt < RETRY_MS) return;
+ const cmd = helperCommand(this.o.platform ?? process.platform);
+ if (!cmd) return;
+ let child;
+ try {
+ child = (this.o.spawn ?? spawn)(cmd[0], cmd[1], { stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
+ } catch {
+ this.failedAt = now;
+ return;
+ }
+ this.child = child;
+ const gone = () => {
+ if (this.child !== child) return;
+ this.child = null;
+ this.failedAt = (this.o.now ?? Date.now)();
+ this.o.log?.("The PC may sleep while the worker runs: its keep-awake helper stopped.");
+ };
+ child.once("error", gone);
+ child.once("exit", gone);
+ child.stdin?.on?.("error", () => {});
+ }
+
+ stop() {
+ const child = this.child;
+ this.child = null;
+ if (!child) return;
+ try {
+ child.stdin?.end();
+ } catch {}
+ try {
+ child.kill();
+ } catch {}
+ }
+}
diff --git a/bin/lib/worker/checks.mjs b/bin/lib/worker/checks.mjs
index e6b0600d..0b020555 100644
--- a/bin/lib/worker/checks.mjs
+++ b/bin/lib/worker/checks.mjs
@@ -61,13 +61,18 @@ export function emptyFolders(f) {
}
}
-/** After a job: its inputs and results leave this PC, its history entry goes, and the temp folder is emptied. */
-export async function cleanJob(task, f, comfyBase, fetchFn = fetch) {
- for (const i of task.inputs ?? []) if (/^fuobe_[A-Za-z0-9_-]{8,24}\.[a-z0-9]{1,5}$/.test(i.name)) fs.rmSync(path.join(f.input, i.name), { force: true });
- // Everything in output and temp is this worker's (its own ComfyUI writes only there), and it runs one job at a time.
- for (const dir of [f.output, f.temp]) {
+/**
+ * After a job, however it ended: nothing of it stays in its ComfyUI (the queue emptied, a running prompt stopped, the
+ * whole history cleared, a meta-batch's passes included), and its inputs and results leave this PC. Everything in these
+ * folders is this worker's (its own ComfyUI writes only there), and it runs one job at a time.
+ */
+export async function cleanJob(f, comfyBase, fetchFn = fetch) {
+ const post = (p, body) => fetchFn(`${comfyBase}${p}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
+ await post("/queue", { clear: true });
+ await post("/interrupt", {});
+ await post("/history", { clear: true });
+ for (const dir of [f.input, f.output, f.temp]) {
if (!fs.existsSync(dir)) continue;
for (const e of fs.readdirSync(dir)) fs.rmSync(path.join(dir, e), { recursive: true, force: true });
}
- await fetchFn(`${comfyBase}/history`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [task.promptId] }) }).catch(() => null);
}
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjs
index 6e7237e0..d78c1dbc 100644
--- a/bin/lib/worker/comfy.mjs
+++ b/bin/lib/worker/comfy.mjs
@@ -1,15 +1,33 @@
// The worker's own ComfyUI (docs/gpu-workers.md): it always starts and stops its own process, on its own port, with its
// own folders, and it never uses a ComfyUI it didn't start.
//
-// The port guard: before each start the worker binds the port itself and lets it go at once. If that fails, something
-// else listens there: the worker refuses to start, pauses itself ("port-busy"), and never connects to that port. So it
-// can never take over, or even talk to, another ComfyUI (the one on 8188 included).
-import { spawn } from "node:child_process";
+// The port guard: each start takes a free port at random (or the one worker.json pins, never 8188). Before the start the
+// worker binds the port itself and lets it go at once. If that fails, something else listens there: the worker refuses
+// to start, pauses itself ("port-busy"), and never connects to that port. So it can never take over, or even talk to,
+// another ComfyUI (the one on 8188 included).
+//
+// The guard (comfy_guard.py): ComfyUI starts through it, with a key made for that start. It refuses every request whose
+// Host isn't 127.0.0.1:<port> or that lacks the key, so a web page in a browser on this PC reaches nothing. Before the
+// worker sends the key anywhere, the process on the port proves it has it (it signs a random challenge) and that it is
+// the process the worker started.
+import { execFile, spawn } from "node:child_process";
+import crypto from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
export class PortBusy extends Error {}
+/** Its ComfyUI answered without the guard: the worker won't use it. */
+export class GuardMissing extends Error {}
+
+/** The guard's names (comfy_guard.py says the same). */
+export const GUARD = { env: "FUOBE_WORKER_GUARD_KEY", key: "X-Fuobe-Worker-Key", challenge: "X-Fuobe-Worker-Challenge", hello: "/fuobe-worker/hello" };
+
+/** The port of the PC owner's own ComfyUI: never the worker's. */
+export const OWNER_PORT = 8188;
/** Can this worker have the port? (A bind test: nothing is sent to whatever listens there.) */
export function portFree(port, host = "127.0.0.1") {
@@ -20,6 +38,19 @@ export function portFree(port, host = "127.0.0.1") {
});
}
+/** The port for one start: the one worker.json pins, else a random free one from 20000 to 59999. */
+export async function pickPort(pinned, random = () => 20_000 + crypto.randomInt(40_000)) {
+ if (pinned) {
+ if (Number(pinned) === OWNER_PORT) throw new PortBusy(`Port ${OWNER_PORT} is your own ComfyUI's`);
+ return Number(pinned);
+ }
+ for (let i = 0; i < 40; i++) {
+ const p = random();
+ if (p !== OWNER_PORT && (await portFree(p))) return p;
+ }
+ throw new PortBusy("No free port for its ComfyUI");
+}
+
/** The Python that runs ComfyUI: the portable one beside it, its venv, else python on the PATH. */
export function pythonFor(comfyDir) {
const win = process.platform === "win32";
@@ -47,14 +78,27 @@ export function modelPathsYaml(modelDirs, folderNames) {
return `${lines.join("\n")}\n`;
}
-/** ComfyUI's start arguments (3.3): localhost only, its own folders, no metadata, no browser, only the packs it needs. */
-export function comfyArgs(cfg, packs = []) {
+/** This ComfyUI can leave out its partner nodes (the paid API nodes): its own argument list names the flag. */
+export function partnerFlag(comfyDir) {
+ try {
+ return fs.readFileSync(path.join(comfyDir, "comfy", "cli_args.py"), "utf8").includes('"--disable-partner-nodes"');
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * ComfyUI's start arguments (3.3): localhost only, its own folders, no metadata, no browser, only the packs it needs,
+ * and no partner nodes where this ComfyUI has the flag. `o.port`: this start's port (else worker.json's).
+ */
+export function comfyArgs(cfg, packs = [], o = {}) {
const f = folders(cfg.workDir);
return [
"--listen", "127.0.0.1",
- "--port", String(cfg.port),
+ "--port", String(o.port ?? cfg.port),
"--disable-auto-launch",
"--disable-metadata",
+ ...(o.partnerFlag ? ["--disable-partner-nodes"] : []),
"--user-directory", f.user,
"--input-directory", f.input,
"--output-directory", f.output,
@@ -106,76 +150,257 @@ export function comfyEnv(env = process.env, extra = {}) {
return { ...out, ...OFFLINE_ENV };
}
-/** At most this many restarts an hour; then the worker pauses itself ("comfy-crashes"). */
+/** At most this many times an hour its ComfyUI may stop by itself with no job running; then the worker pauses itself. */
export const MAX_RESTARTS_AN_HOUR = 3;
+/** The wait before a start after its ComfyUI stopped: 5 s, then twice as long each time in a row, at most 2 minutes. */
+export const restartDelayMs = (inARow) => (inARow <= 0 ? 0 : Math.min(120_000, 5_000 * 2 ** (inARow - 1)));
+/** A ComfyUI up this long counts as steady: the next stop waits 5 s again. */
+const STEADY_MS = 10 * 60_000;
+
+/** The command line of a running process, or null (not running, or it can't be read). */
+export function commandLineOf(pid) {
+ const n = Number(pid);
+ if (!Number.isInteger(n) || n <= 0) return Promise.resolve(null);
+ if (process.platform === "linux") {
+ try {
+ return Promise.resolve(fs.readFileSync(`/proc/${n}/cmdline`, "utf8").replaceAll("\0", " ").trim() || null);
+ } catch {
+ return Promise.resolve(null);
+ }
+ }
+ const [cmd, args] =
+ process.platform === "win32"
+ ? ["powershell", ["-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${n}").CommandLine`]]
+ : ["ps", ["-o", "command=", "-p", String(n)]];
+ return new Promise((resolve) => execFile(cmd, args, { timeout: 20_000, windowsHide: true }, (err, out) => resolve(err ? null : String(out).trim() || null)));
+}
+
+/** Stop a process and everything it started. */
+export function killTree(pid) {
+ return new Promise((resolve) => {
+ if (process.platform === "win32") {
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).once("exit", resolve).once("error", resolve);
+ return;
+ }
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {}
+ resolve();
+ });
+}
+
+/** comfyui.log and the two before it: a new one at each start, and a new one when it passes 20 MB. */
+export class RotatingLog {
+ constructor(file, o = {}) {
+ this.file = file;
+ this.max = o.maxBytes ?? 20 * 2 ** 20;
+ this.keep = o.keep ?? 2;
+ this.fd = null;
+ this.bytes = 0;
+ this.rotate();
+ }
+
+ rotate() {
+ if (this.fd !== null) fs.closeSync(this.fd);
+ const name = (i) => (i === 0 ? this.file : this.file.replace(/(\.log)?$/, `.${i}.log`));
+ fs.rmSync(name(this.keep), { force: true });
+ for (let i = this.keep - 1; i >= 0; i--) if (fs.existsSync(name(i))) fs.renameSync(name(i), name(i + 1));
+ this.fd = fs.openSync(this.file, "a", 0o600);
+ this.bytes = 0;
+ }
+
+ write(chunk) {
+ if (this.fd === null) return;
+ if (this.bytes + chunk.length > this.max) this.rotate();
+ fs.writeSync(this.fd, chunk);
+ this.bytes += chunk.length;
+ }
+
+ close() {
+ if (this.fd !== null) fs.closeSync(this.fd);
+ this.fd = null;
+ }
+}
export class OwnComfy {
/**
- * @param cfg the worker's settings (comfyDir, workDir, port, modelDirs, comfyEnv; `comfyCommand` replaces the whole
- * command, for tests)
- * @param o { now, log, fetch, folderNames, env (this PC's environment, for tests) }
+ * @param cfg the worker's settings (comfyDir, workDir, port (pins one), modelDirs, comfyEnv, python; `comfyCommand`
+ * replaces the whole command, for tests, with {port} in it, and `comfyGuard` says that command keeps the guard)
+ * @param o { now, log, fetch, folderNames, env (this PC's environment), commandLineOf, killTree, randomPort (tests) }
*/
constructor(cfg, o = {}) {
this.cfg = cfg;
this.o = o;
this.child = null;
this.ready = false;
- this.starts = [];
+ this.port = null;
+ this.key = null;
+ this.crashes = [];
+ this.inARow = 0;
+ this.startedAt = 0;
this.expectExit = false;
this.onCrash = null;
+ /** The task its ComfyUI runs now (the worker says), so a crash counts against it. */
+ this.task = null;
+ this.log = null;
}
get base() {
- return `http://127.0.0.1:${this.cfg.port}`;
+ return `http://127.0.0.1:${this.port ?? this.cfg.port ?? 0}`;
}
get pid() {
return this.child?.pid ?? null;
}
+ /** It keeps the guard: the real start always does; a test's command only when it says so. */
+ get guarded() {
+ return !this.cfg.comfyCommand || this.cfg.comfyGuard === true;
+ }
+
+ get pidFile() {
+ return path.join(this.cfg.workDir, "comfyui.pid");
+ }
+
alive() {
- return !!this.child && this.child.exitCode === null && !this.child.killed;
+ return !!this.child?.pid && this.child.exitCode === null && this.child.signalCode === null && !this.child.killed;
}
- /** Restarts in the last hour have used up the allowance. */
+ /** Stops with no job running in the last hour have used up the allowance. */
crashedTooOften(now = Date.now()) {
- return this.starts.filter((t) => now - t < 3_600_000).length > MAX_RESTARTS_AN_HOUR;
+ return this.crashes.filter((c) => !c.task && now - c.at < 3_600_000).length > MAX_RESTARTS_AN_HOUR;
+ }
+
+ /** When it may start again after stopping by itself (the short backoff). */
+ get restartAt() {
+ const last = this.crashes.at(-1);
+ return last ? last.at + restartDelayMs(this.inARow) : 0;
+ }
+
+ /** The address made this start's, for a URL the runner built (http or ws, 127.0.0.1, any port). */
+ rebase(url) {
+ return String(url).replace(/^(http|ws)(s?):\/\/127\.0\.0\.1:\d+/, (_, p, s) => `${p}${s}://127.0.0.1:${this.port}`);
+ }
+
+ /** The key's header, for every request to it. */
+ headers() {
+ return this.guarded && this.key ? { [GUARD.key]: this.key } : {};
+ }
+
+ /** A request to its own ComfyUI (its address and key are this start's). */
+ fetch(url, init = {}) {
+ const headers = new Headers(init.headers);
+ for (const [k, v] of Object.entries(this.headers())) headers.set(k, v);
+ return (this.o.fetch ?? fetch)(this.rebase(url), { ...init, headers });
}
- /** Start its own ComfyUI and wait until it answers. Throws PortBusy when the port is taken. */
+ /** A ComfyUI left running by a worker that stopped without stopping it (its pid file says): stop it. True when it did. */
+ async stopLeftover() {
+ let rec;
+ try {
+ rec = JSON.parse(fs.readFileSync(this.pidFile, "utf8"));
+ } catch {
+ return false;
+ }
+ let stopped = false;
+ if (Number.isInteger(rec?.pid) && rec.pid > 0 && typeof rec.marker === "string" && rec.marker) {
+ // Only that process: its command line still names what this worker started (a reused pid doesn't).
+ const line = await (this.o.commandLineOf ?? commandLineOf)(rec.pid);
+ if (line && line.includes(rec.marker)) {
+ await (this.o.killTree ?? killTree)(rec.pid);
+ stopped = true;
+ this.o.log?.("Stopped a ComfyUI that a stopped worker left running.");
+ }
+ }
+ fs.rmSync(this.pidFile, { force: true });
+ return stopped;
+ }
+
+ /** The process on the port proves it is the one the worker started, and has this start's key. */
+ async proven(pid) {
+ const challenge = crypto.randomBytes(16).toString("hex");
+ const r = await (this.o.fetch ?? fetch)(`${this.base}${GUARD.hello}`, { headers: { [GUARD.challenge]: challenge } });
+ if (!r.ok) return false;
+ const a = await r.json().catch(() => ({}));
+ const want = crypto.createHmac("sha256", this.key).update(challenge).digest("hex");
+ if (typeof a.proof !== "string" || a.proof.length !== want.length || !crypto.timingSafeEqual(Buffer.from(a.proof), Buffer.from(want)) || a.pid !== pid) {
+ throw new PortBusy(`Another program answered on port ${this.port}`);
+ }
+ return true;
+ }
+
+ /** Start its own ComfyUI and wait until it answers. Throws PortBusy when the port is taken, GuardMissing without the guard. */
async start(packs = []) {
if (this.alive()) return;
- if (!(await portFree(this.cfg.port))) throw new PortBusy(`Port ${this.cfg.port} is in use by another program`);
+ await this.stopLeftover();
+ this.port = await pickPort(this.cfg.port, this.o.randomPort);
+ if (!(await portFree(this.port))) throw new PortBusy(`Port ${this.port} is in use by another program`);
const f = folders(this.cfg.workDir);
for (const dir of Object.values(f)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(this.cfg.workDir, "extra_model_paths.yaml"), modelPathsYaml(this.cfg.modelDirs ?? [], this.o.folderNames ?? []));
- const cmd = this.cfg.comfyCommand
- ? this.cfg.comfyCommand.map((a) => String(a).replaceAll("{port}", String(this.cfg.port)))
- : [this.cfg.python || pythonFor(this.cfg.comfyDir), path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs)];
- this.starts.push((this.o.now ?? Date.now)());
+ this.key = crypto.randomBytes(32).toString("hex");
+ let cmd;
+ let marker;
+ if (this.cfg.comfyCommand) {
+ cmd = this.cfg.comfyCommand.map((a) => String(a).replaceAll("{port}", String(this.port)));
+ marker = cmd.slice(1).find((a) => /[\\/]/.test(a)) ?? cmd.join(" ");
+ } else {
+ // The guard is written fresh into the worker folder at each start, and ComfyUI starts through it.
+ const guard = path.join(this.cfg.workDir, "guard", "comfy_guard.py");
+ fs.mkdirSync(path.dirname(guard), { recursive: true });
+ fs.copyFileSync(path.join(here, "comfy_guard.py"), guard);
+ cmd = [this.cfg.python || pythonFor(this.cfg.comfyDir), "-s", guard, path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs, { port: this.port, partnerFlag: partnerFlag(this.cfg.comfyDir) })];
+ marker = guard;
+ }
+ this.crashes = this.crashes.filter((c) => (this.o.now ?? Date.now)() - c.at < 3_600_000);
this.expectExit = false;
this.ready = false;
- const env = comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv);
- const child = spawn(cmd[0], cmd.slice(1), { cwd: this.cfg.comfyDir || this.cfg.workDir, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+ const env = { ...comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv), ...(this.guarded && { [GUARD.env]: this.key }) };
+ // Its working folder is the worker folder: a node that writes a relative path writes there, not into ComfyUI's.
+ const child = spawn(cmd[0], cmd.slice(1), { cwd: this.cfg.workDir, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
this.child = child;
- const log = fs.createWriteStream(path.join(this.cfg.workDir, "comfyui.log"), { flags: "a" });
- child.stdout.pipe(log);
- child.stderr.pipe(log);
+ this.startedAt = (this.o.now ?? Date.now)();
+ if (child.pid) fs.writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, port: this.port, marker, at: this.startedAt }), { mode: 0o600 });
+ this.log?.close();
+ const log = (this.log = new RotatingLog(path.join(this.cfg.workDir, "comfyui.log")));
+ child.stdout.on("data", (d) => log.write(d));
+ child.stderr.on("data", (d) => log.write(d));
+ child.once("error", () => {});
child.once("exit", (code) => {
this.ready = false;
- if (!this.expectExit) this.onCrash?.(code);
+ if (this.expectExit) return;
+ const at = (this.o.now ?? Date.now)();
+ this.inARow = at - this.startedAt >= STEADY_MS ? 1 : this.inARow + 1;
+ this.crashes.push({ at, task: this.task });
+ this.onCrash?.(code, this.task);
});
- // Only now, with its own process up, does the worker talk to the port.
- const fetchFn = this.o.fetch ?? fetch;
+ // Only now, with its own process up, does the worker talk to the port: first the proof, then with the key.
+ let proof = !this.guarded;
for (let i = 0; i < 360; i++) {
if (!this.alive()) throw new Error("ComfyUI stopped while starting (see comfyui.log in the worker folder)");
try {
- const r = await fetchFn(`${this.base}/system_stats`);
- if (r.ok) {
- this.ready = true;
- return;
+ if (!proof) proof = await this.proven(child.pid);
+ if (proof) {
+ const r = await this.fetch(`${this.base}/system_stats`);
+ if (r.ok) {
+ if (this.guarded) {
+ // Without the key it must refuse: else the guard isn't there, and the worker won't use this ComfyUI.
+ const open = await (this.o.fetch ?? fetch)(`${this.base}/system_stats`).catch(() => null);
+ if (open?.status !== 403) {
+ await this.stop();
+ throw new GuardMissing("Its ComfyUI answered without the worker's guard");
+ }
+ }
+ this.ready = true;
+ return;
+ }
}
- } catch {}
+ } catch (e) {
+ if (e instanceof PortBusy || e instanceof GuardMissing) {
+ await this.stop();
+ throw e;
+ }
+ }
await new Promise((r) => setTimeout(r, 500));
}
await this.stop();
@@ -188,24 +413,27 @@ export class OwnComfy {
if (!child) return;
this.expectExit = true;
this.ready = false;
- if (child.exitCode === null) {
- if (process.platform === "win32" && child.pid) {
- await new Promise((r) => spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).once("exit", r).once("error", r));
- } else child.kill("SIGTERM");
+ if (child.exitCode === null && child.signalCode === null) {
+ if (process.platform === "win32" && child.pid) await (this.o.killTree ?? killTree)(child.pid);
+ else child.kill("SIGTERM");
await new Promise((r) => {
- if (child.exitCode !== null) return r();
+ if (child.exitCode !== null || child.signalCode !== null) return r();
const t = setTimeout(() => (child.kill("SIGKILL"), r()), 10_000);
child.once("exit", () => (clearTimeout(t), r()));
});
}
this.child = null;
+ this.key = null;
+ fs.rmSync(this.pidFile, { force: true });
+ this.log?.close();
+ this.log = null;
}
/** Its own VRAM, from its own /system_stats (MB), or null. */
async vramMb() {
if (!this.ready) return null;
try {
- const s = await (await (this.o.fetch ?? fetch)(`${this.base}/system_stats`)).json();
+ const s = await (await this.fetch(`${this.base}/system_stats`)).json();
const d = s?.devices?.[0];
const bytes = d?.torch_vram_total ?? null;
return typeof bytes === "number" ? Math.round(bytes / 2 ** 20) : null;
@@ -213,4 +441,19 @@ export class OwnComfy {
return null;
}
}
+
+ /** Free its memory: models unloaded, caches emptied (before a retry after running out of memory). */
+ async free() {
+ if (!this.ready) return;
+ await this.fetch(`${this.base}/free`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ unload_models: true, free_memory: true }) }).catch(() => null);
+ }
+
+ /** Nothing of a job stays in it: the running prompt stopped, the queue and the whole history emptied. */
+ async clear() {
+ if (!this.ready) return;
+ const post = (p, body) => this.fetch(`${this.base}${p}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
+ await post("/queue", { clear: true });
+ await post("/interrupt", {});
+ await post("/history", { clear: true });
+ }
}
diff --git a/bin/lib/worker/comfy_guard.py b/bin/lib/worker/comfy_guard.py
new file mode 100644
index 00000000..675187b6
--- /dev/null
+++ b/bin/lib/worker/comfy_guard.py
@@ -0,0 +1,112 @@
+"""The guard of a Fuobe worker's own ComfyUI (docs/gpu-workers.md).
+
+The worker starts its ComfyUI through this file instead of main.py:
+
+ python comfy_guard.py <ComfyUI>/main.py --listen 127.0.0.1 --port <port> ...
+
+It reads the key the worker made for this start (FUOBE_WORKER_GUARD_KEY, then removes it from the environment), puts
+a check in front of every aiohttp application ComfyUI makes, and runs main.py as ComfyUI's own start does. The check
+answers 403 to any request whose Host is not exactly 127.0.0.1:<port>, or that does not carry the key in
+X-Fuobe-Worker-Key. A web page that points its own name at 127.0.0.1 (DNS rebinding) sends neither, so it reaches
+nothing.
+
+One request needs no key: GET /fuobe-worker/hello with X-Fuobe-Worker-Challenge (16 to 128 hex digits). The answer is
+the challenge signed with the key (HMAC-SHA-256) and this process's id. The worker checks both before it sends the key,
+so a program that took the port first never learns it.
+
+Only the Python standard library and aiohttp (which ComfyUI needs anyway).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import os
+import re
+import runpy
+import sys
+
+KEY_ENV = "FUOBE_WORKER_GUARD_KEY"
+KEY_HEADER = "X-Fuobe-Worker-Key"
+CHALLENGE_HEADER = "X-Fuobe-Worker-Challenge"
+HELLO_PATH = "/fuobe-worker/hello"
+CHALLENGE = re.compile(r"^[0-9a-f]{16,128}$")
+
+
+def _bytes(text: str) -> bytes:
+ return text.encode("utf-8", "surrogateescape")
+
+
+def proof(key: str, challenge: str) -> str:
+ """The challenge signed with the key."""
+ return hmac.new(_bytes(key), _bytes(challenge), hashlib.sha256).hexdigest()
+
+
+def allowed(headers, key: str, host: str) -> bool:
+ """The request names this ComfyUI exactly and carries the key."""
+ return headers.get("Host", "") == host and hmac.compare_digest(_bytes(headers.get(KEY_HEADER, "")), _bytes(key))
+
+
+def make_middleware(web, key: str, host: str):
+ """The check, as an aiohttp middleware."""
+
+ @web.middleware
+ async def fuobe_worker_guard(request, handler):
+ if request.headers.get("Host", "") != host:
+ return web.Response(status=403)
+ if request.method == "GET" and request.path == HELLO_PATH and KEY_HEADER not in request.headers:
+ challenge = request.headers.get(CHALLENGE_HEADER, "")
+ if not CHALLENGE.match(challenge):
+ return web.Response(status=403)
+ return web.json_response({"proof": proof(key, challenge), "pid": os.getpid()})
+ if not allowed(request.headers, key, host):
+ return web.Response(status=403)
+ return await handler(request)
+
+ return fuobe_worker_guard
+
+
+def install(web, key: str, host: str) -> None:
+ """Every aiohttp application made from now on gets the check first (ComfyUI's server, and its sub-applications)."""
+ original = web.Application.__init__
+ guard = make_middleware(web, key, host)
+
+ def guarded_init(self, *args, middlewares=(), **kwargs):
+ original(self, *args, middlewares=[guard, *list(middlewares)], **kwargs)
+
+ web.Application.__init__ = guarded_init
+
+
+def port_of(args: list[str]) -> int:
+ """The --port ComfyUI is started with."""
+ for i, a in enumerate(args):
+ if a == "--port" and i + 1 < len(args):
+ return int(args[i + 1])
+ if a.startswith("--port="):
+ return int(a.split("=", 1)[1])
+ raise SystemExit("The worker's guard needs --port")
+
+
+def main(argv: list[str]) -> None:
+ key = os.environ.pop(KEY_ENV, "")
+ if len(key) < 32:
+ raise SystemExit("The worker's guard has no key: start ComfyUI from the worker")
+ if len(argv) < 2:
+ raise SystemExit("Usage: comfy_guard.py <ComfyUI>/main.py [ComfyUI's arguments]")
+ main_py = os.path.abspath(argv[1])
+ args = argv[2:]
+ host = f"127.0.0.1:{port_of(args)}"
+ comfy_dir = os.path.dirname(main_py)
+ # Imports come from ComfyUI's folder, never from this file's folder (the worker's own).
+ here = os.path.dirname(os.path.abspath(__file__))
+ sys.path[:] = [p for p in sys.path if os.path.abspath(p or os.curdir) != here]
+ sys.path.insert(0, comfy_dir)
+ from aiohttp import web
+
+ install(web, key, host)
+ sys.argv = [main_py, *args]
+ runpy.run_path(main_py, run_name="__main__")
+
+
+if __name__ == "__main__":
+ main(sys.argv)
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index f8f12021..6a550343 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -14,7 +14,12 @@ export function workerHome(env = process.env, home = os.homedir()) {
}
export const DEFAULTS = {
- port: 8190,
+ /** Its ComfyUI's port: none set takes a free one at random at each start (`port` in worker.json pins one). */
+ port: null,
+ /** A job that makes no progress for this many minutes goes back to the line, and a stuck ComfyUI is started again. */
+ stallMin: 10,
+ /** ffmpeg, which makes every clip and sound again before its ComfyUI reads them. None: the worker takes pictures only. */
+ ffmpeg: null,
/** Another program's VRAM above this pauses the worker. */
busyVramMb: 1024,
/** The automatic resume: off unless switched on for this PC (here, or on the studio's Workers page). */
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjs
index 9196d39b..aae7eeeb 100644
--- a/bin/lib/worker/index.mjs
+++ b/bin/lib/worker/index.mjs
@@ -2,8 +2,7 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { portFree } from "./comfy.mjs";
-import { DEFAULTS, loadConfig, parseFor, readControl, readStatus, saveConfig, syncedFolder, workerHome, writeControl } from "./config.mjs";
+import { loadConfig, parseFor, readControl, readStatus, saveConfig, syncedFolder, workerHome, writeControl } from "./config.mjs";
import { installScript } from "./install.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
@@ -34,16 +33,23 @@ export async function worker(args, io) {
io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");
return 2;
}
- const { runWorker } = await import("./run.mjs");
+ const { runWorker, siteProblem } = await import("./run.mjs");
+ const problem = siteProblem(cfg.site);
+ if (problem) {
+ io.stderr.write(`${problem} Run: fuobe worker setup\n`);
+ return 2;
+ }
const ctrl = new AbortController();
const off = io.onInterrupt?.(() => ctrl.abort());
- say(`Fuobe worker for ${cfg.site}. Its own ComfyUI uses port ${cfg.port}. Ctrl+C stops it.`);
+ say(`Fuobe worker for ${cfg.site}. ${cfg.port ? `Its own ComfyUI uses port ${cfg.port}` : "Its own ComfyUI takes a free local port at each start"}. Ctrl+C stops it.`);
+ let why;
try {
- await runWorker(cfg, { home, signal: ctrl.signal });
+ why = await runWorker(cfg, { home, signal: ctrl.signal });
} finally {
off?.();
}
- return 0;
+ // Stopped by hand: done. Stopped by the studio: not 0, so the sign-in task starts it again a minute later.
+ return why === "aborted" ? 0 : why === "signed-out" ? 3 : 1;
}
case "pause": {
const forMs = value(rest, "for") ? parseFor(value(rest, "for")) : null;
@@ -109,6 +115,12 @@ async function setup(home, io, say) {
const ask = async (q, def, o = {}) => ((await io.ask(`${q}${def ? ` [${def}]` : ""}: `, o)) || def || "").trim();
say("Set up this PC as a Fuobe worker. It takes the studio's jobs over HTTPS and runs them on its own ComfyUI.");
const site = await ask("The studio's address", old.site ?? "https://");
+ const { siteProblem } = await import("./run.mjs");
+ const bad = siteProblem(site);
+ if (bad) {
+ io.stderr.write(`${bad}\n`);
+ return 2;
+ }
const token = await ask("The worker's token (Settings → Workers → Add a worker)", "", { hidden: true });
if (!/^fuobe_wkr_/.test(token) && !old.token) {
io.stderr.write("That isn't a worker token (they start with fuobe_wkr_).\n");
@@ -128,13 +140,12 @@ async function setup(home, io, say) {
io.stderr.write("That folder is synced to a cloud drive. Pick one outside OneDrive, Dropbox and the like: people's files must stay on this PC.\n");
return 2;
}
- const port = Number(await ask("The port for the worker's own ComfyUI", String(old.port ?? DEFAULTS.port)));
- if (!Number.isInteger(port) || port < 1024 || port > 65535 || port === 8188) {
- io.stderr.write("Pick a free port above 1024 other than 8188 (your own ComfyUI's).\n");
- return 2;
- }
- if (!(await portFree(port))) {
- io.stderr.write(`Something already listens on port ${port}. The worker only uses a ComfyUI it starts itself: pick another port.\n`);
+ // ffmpeg makes every clip and sound again before its ComfyUI reads them. Without it, the worker takes pictures only.
+ const { ffmpegVersion } = await import("./media.mjs");
+ const ffmpegAnswer = await ask("ffmpeg's path, for clips and sound (leave empty for pictures only)", old.ffmpeg ?? ((await ffmpegVersion("ffmpeg")) ? "ffmpeg" : ""));
+ const ffmpeg = ffmpegAnswer && ffmpegAnswer !== "-" ? ffmpegAnswer : null;
+ if (ffmpeg && !(await ffmpegVersion(ffmpeg))) {
+ io.stderr.write(`There's no working ffmpeg at ${ffmpeg}. Give its full path, or leave it empty for pictures only.\n`);
return 2;
}
const autoResume = /^y/i.test(await ask("Resume by itself when the GPU has been free for 10 minutes? (y/N)", old.autoResume ? "y" : "n"));
@@ -144,7 +155,8 @@ async function setup(home, io, say) {
const { spawnSync } = await import("node:child_process");
spawnSync("attrib", ["+I", workDir], { windowsHide: true });
}
- saveConfig(home, { ...old, site: site.replace(/\/+$/, ""), token: token || old.token, comfyDir, modelDirs, workDir, port, autoResume });
+ // No port is kept: its ComfyUI takes a free one at random at each start (`port` in worker.json pins one by hand).
+ saveConfig(home, { ...old, port: null, site: site.replace(/\/+$/, ""), token: token || old.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume });
writeControl(home, { paused: true, now: false, until: null });
say(`Saved in ${path.join(home, "worker.json")} (readable by you only). The worker starts paused here.`);
say("Next: fuobe worker run. Resume it here with fuobe worker resume, and on the website in Settings → Workers.");
diff --git a/bin/lib/worker/media.mjs b/bin/lib/worker/media.mjs
new file mode 100644
index 00000000..d45092e2
--- /dev/null
+++ b/bin/lib/worker/media.mjs
@@ -0,0 +1,103 @@
+// Clips and sound for the worker's ComfyUI (docs/gpu-workers.md). Every clip and every sound a job sends is made again by
+// ffmpeg into a fresh file before ComfyUI reads it: the streams are decoded and encoded again, and nothing else of the
+// file (metadata, chapters, subtitles, attachments, data streams) is kept. Only ffmpeg ever reads the file as it came,
+// in its own short-lived process at low priority. A worker without ffmpeg takes pictures only: it says so in its
+// inventory, so no job that reads a clip or a sound comes to it.
+import { execFile, spawn } from "node:child_process";
+import os from "node:os";
+
+const VIDEO_EXT = new Set(["mp4", "m4v", "mov", "mkv", "webm", "avi", "gif", "mpg", "mpeg", "wmv", "flv", "3gp", "ts", "mts", "m2ts"]);
+const AUDIO_EXT = new Set(["wav", "mp3", "flac", "ogg", "oga", "opus", "m4a", "aac", "wma", "aif", "aiff"]);
+
+/** The loader inputs that read a clip, and a sound, the job sent (src/lib/lanes.ts MEDIA_LOADERS, by input). */
+const VIDEO_INPUTS = { LoadVideo: ["file"], VHS_LoadVideo: ["video"], VHS_LoadVideoPath: ["video"], VHS_LoadVideoFFmpeg: ["video"], VHS_LoadVideoFFmpegPath: ["video"] };
+const AUDIO_INPUTS = { LoadAudio: ["audio"], VHS_LoadAudio: ["audio_file"], VHS_LoadAudioUpload: ["audio"] };
+
+const extOf = (name) => (String(name).includes(".") ? String(name).split(".").pop().toLowerCase() : "");
+
+/**
+ * Is this input a clip or a sound: by its type, its name, or a loader of the graph that reads it as one. Null: a
+ * picture (the studio already made it again from its pixels).
+ */
+export function mediaKind(input, graph) {
+ const type = String(input.contentType ?? "").split("/")[0].toLowerCase();
+ const ext = extOf(input.name);
+ const readBy = (map) =>
+ Object.values(graph ?? {}).some((n) => (map[n?.class_type] ?? []).some((k) => typeof n.inputs?.[k] === "string" && n.inputs[k].replace(/ \[input\]$/, "") === input.name));
+ if (type === "video" || VIDEO_EXT.has(ext) || readBy(VIDEO_INPUTS)) return "video";
+ if (type === "audio" || AUDIO_EXT.has(ext) || readBy(AUDIO_INPUTS)) return "audio";
+ return null;
+}
+
+const EVEN = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2"];
+const H264 = [...EVEN, "-c:v", "libx264", "-preset", "veryfast", "-crf", "16", "-pix_fmt", "yuv420p"];
+const VIDEO = {
+ mp4: [...H264, "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-f", "mp4"],
+ m4v: [...H264, "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-f", "mp4"],
+ mov: [...H264, "-c:a", "aac", "-b:a", "192k", "-f", "mov"],
+ mkv: [...H264, "-c:a", "aac", "-b:a", "192k", "-f", "matroska"],
+ webm: [...EVEN, "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", "-row-mt", "1", "-crf", "20", "-b:v", "0", "-c:a", "libopus", "-b:a", "160k", "-f", "webm"],
+ avi: [...H264, "-c:a", "libmp3lame", "-q:a", "2", "-f", "avi"],
+ gif: ["-an", "-filter_complex", "[0:v:0]split[a][b];[a]palettegen[p];[b][p]paletteuse", "-f", "gif"],
+};
+const AUDIO = {
+ wav: ["-c:a", "pcm_s24le", "-f", "wav"],
+ mp3: ["-c:a", "libmp3lame", "-q:a", "0", "-f", "mp3"],
+ flac: ["-c:a", "flac", "-f", "flac"],
+ ogg: ["-c:a", "libvorbis", "-q:a", "8", "-f", "ogg"],
+ oga: ["-c:a", "libvorbis", "-q:a", "8", "-f", "ogg"],
+ opus: ["-c:a", "libopus", "-b:a", "192k", "-f", "opus"],
+ m4a: ["-c:a", "aac", "-b:a", "256k", "-f", "ipod"],
+ aac: ["-c:a", "aac", "-b:a", "256k", "-f", "adts"],
+ mp4: ["-c:a", "aac", "-b:a", "256k", "-f", "mp4"],
+ webm: ["-c:a", "libopus", "-b:a", "192k", "-f", "webm"],
+ aif: ["-c:a", "pcm_s16be", "-f", "aiff"],
+ aiff: ["-c:a", "pcm_s16be", "-f", "aiff"],
+};
+
+/**
+ * ffmpeg's arguments to make `src` again as `dst`: the first video stream and the first sound stream for a clip (the
+ * format its name says: H.264 and AAC in MP4 when it says nothing ffmpeg writes well), the first sound stream for a
+ * sound; no metadata, chapters, subtitles or data.
+ */
+export function encodeArgs(kind, name, src, dst) {
+ const ext = extOf(name);
+ const head = ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", src, "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn"];
+ if (kind === "video") {
+ const fmt = VIDEO[ext] ?? VIDEO.mp4;
+ return ext === "gif" ? [...head, ...fmt, dst] : [...head, "-map", "0:v:0", "-map", "0:a:0?", ...fmt, dst];
+ }
+ return [...head, "-vn", "-map", "0:a:0", ...(AUDIO[ext] ?? AUDIO.wav), dst];
+}
+
+/** ffmpeg's version line, or null when there is no working ffmpeg at `bin`. */
+export function ffmpegVersion(bin) {
+ if (!bin) return Promise.resolve(null);
+ return new Promise((resolve) =>
+ execFile(bin, ["-hide_banner", "-version"], { timeout: 15_000, windowsHide: true }, (err, out) => {
+ const line = String(out ?? "").split(/\r?\n/)[0] ?? "";
+ resolve(!err && /^ffmpeg version /i.test(line) ? line.slice(0, 120) : null);
+ }),
+ );
+}
+
+/**
+ * Make a clip or a sound again (`encodeArgs`) in its own process at low priority, stopped after `timeoutMs`. True when
+ * ffmpeg made it.
+ */
+export function reencode({ ffmpeg, kind, name, src, dst, timeoutMs = 20 * 60_000, spawnFn = spawn }) {
+ return new Promise((resolve) => {
+ let child;
+ try {
+ child = spawnFn(ffmpeg, encodeArgs(kind, name, src, dst), { stdio: ["ignore", "ignore", "ignore"], windowsHide: true });
+ } catch {
+ return resolve(false);
+ }
+ try {
+ if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
+ child.once("error", () => (clearTimeout(timer), resolve(false)));
+ child.once("exit", (code) => (clearTimeout(timer), resolve(code === 0)));
+ });
+}
diff --git a/bin/lib/worker/retry.mjs b/bin/lib/worker/retry.mjs
new file mode 100644
index 00000000..92ce56a1
--- /dev/null
+++ b/bin/lib/worker/retry.mjs
@@ -0,0 +1,65 @@
+// One retry policy for the worker's calls to the studio (docs/gpu-workers.md). A studio that is restarting (a deploy), a
+// proxy in front of it with nothing to say (502, 503, Cloudflare's 52x), a busy studio that says when to come back
+// (429 with Retry-After) or a network that drops for a moment are waited out with a growing pause (1 s, 2 s, 4 s … at
+// most 30 s at a time): up to 2 minutes for a call, and up to an hour for a part of a result. A beat is never waited
+// out: the next one comes soon anyway. A call that may have reached the studio is sent again only when sending it twice
+// is safe (a read, or a part of a result, which the studio takes only at its own offset). A proxy's page in place of an
+// answer (a 403 that isn't the studio's JSON) never stops the worker: it counts as no answer.
+
+export const RETRY = { callMs: 2 * 60_000, uploadMs: 60 * 60_000, maxPauseMs: 30_000 };
+
+/** Network failures where the call never reached the studio. */
+const NOT_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"]);
+/** Answers from a proxy that never reached the studio. */
+const NOT_REACHED = new Set([502, 503, 521, 522, 523, 525, 526, 530]);
+/** Answers that may come after the studio got the call (a slow answer): safe to send again only when that is harmless. */
+const MAYBE_REACHED = new Set([500, 504, 520, 524, 527]);
+
+const codeOf = (e) => e?.cause?.code ?? e?.code;
+const isJson = (res) => /json/i.test(res.headers.get("content-type") ?? "");
+/** A proxy's page in place of the studio's answer. */
+const notTheStudio = (res) => res.status === 403 && !isJson(res);
+
+/** Is this answer worth waiting out? `safe`: the call can be sent twice. */
+export function passing(res, safe) {
+ if (NOT_REACHED.has(res.status)) return true;
+ if (MAYBE_REACHED.has(res.status)) return safe;
+ if (res.status === 429) return !!res.headers.get("retry-after");
+ return notTheStudio(res);
+}
+
+/** `fetchFn` with the policy. `o`: { now, sleep, signal, log }. */
+export function retrying(fetchFn, o = {}) {
+ const now = o.now ?? Date.now;
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ return async (url, init = {}) => {
+ const method = String(init.method ?? "GET").toUpperCase();
+ const upload = method === "PUT" && /\/outputs\/\d+/.test(String(url));
+ const beat = /\/api\/gpu\/computer\/beat$/.test(String(url));
+ const safe = method === "GET" || upload;
+ const until = now() + (beat ? 0 : upload ? RETRY.uploadMs : RETRY.callMs);
+ for (let i = 0; ; i++) {
+ let res = null;
+ let err = null;
+ try {
+ res = await fetchFn(url, init);
+ } catch (e) {
+ err = e;
+ }
+ const again = err ? (safe && !init.signal?.aborted) || NOT_SENT.has(codeOf(err)) : passing(res, safe);
+ if (!again || now() >= until || o.signal?.aborted) {
+ if (err) throw err;
+ if (notTheStudio(res)) {
+ res.body?.cancel().catch(() => {});
+ return Response.json({ error: "The studio didn't answer" }, { status: 503 });
+ }
+ return res;
+ }
+ const after = res ? Number(res.headers.get("retry-after")) : NaN;
+ res?.body?.cancel().catch(() => {});
+ const pause = Math.min(RETRY.maxPauseMs, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** Math.min(i, 5), Math.max(0, until - now()));
+ if (i === 0) o.log?.(`The studio didn't answer${res ? ` (HTTP ${res.status})` : ""}: trying again.`);
+ await sleep(pause);
+ }
+ };
+}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index b628cde1..32f9ec54 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -1,15 +1,26 @@
// `fuobe worker run`: the worker's loop (docs/gpu-workers.md). It beats to the studio, keeps its own ComfyUI running
// only while it may work, takes one job at a time with the same runner the browser uses, checks each graph itself,
// cleans up after each job, and pauses itself when another program uses the GPU.
+//
+// It also keeps jobs going through trouble: finished results stay on its disk until the studio has them (hold.mjs), so a
+// stop before the upload never runs a job twice; every call to the studio follows one retry policy (retry.mjs); a job
+// that stalls or runs past its run limit goes back to the line and a stuck ComfyUI is started again; a ComfyUI that ran
+// out of memory is freed and the job sent once more; a job its ComfyUI stopped on twice fails, not the worker; inputs are
+// read from the studio once and every clip and sound is made again by ffmpeg (media.mjs); the PC stays awake while it
+// holds a job or waits for one (awake.mjs); and it looks at its model folders again every 10 minutes.
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import { StayAwake } from "./awake.mjs";
import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";
-import { folders, OwnComfy, PortBusy } from "./comfy.mjs";
+import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";
import { PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";
import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";
+import { Hold } from "./hold.mjs";
import { inventoryHash, modelFiles, packFolders } from "./inventory.mjs";
+import { ffmpegVersion, mediaKind, reencode } from "./media.mjs";
+import { retrying } from "./retry.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "../../..");
@@ -27,6 +38,25 @@ export function loadRequirements(file = path.join(ROOT, "workflows/comfyui/requi
return JSON.parse(fs.readFileSync(file, "utf8"));
}
+/** The worker looks at its model folders again this often (a folder that comes back after a restart counts). */
+export const RESCAN_MS = 10 * 60_000;
+
+/**
+ * Why the studio's address won't do, or null: it must be https, so the token and people's files never cross the
+ * network in the clear. This PC itself (127.0.0.1, localhost) may use http, for tests.
+ */
+export function siteProblem(site) {
+ let u;
+ try {
+ u = new URL(String(site));
+ } catch {
+ return "That isn't a web address.";
+ }
+ if (u.protocol === "https:") return null;
+ if (u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)) return null;
+ return "The studio's address must start with https://.";
+}
+
/**
* The worker's local pause, from its switch (`worker pause`), the GPU, and its ComfyUI: { paused, why, until }.
* A pause by hand ("here", "here-until:<ms>", "here-now") always wins over the GPU's.
@@ -39,65 +69,161 @@ export function localPause(control, gpu, comfyTrouble, now) {
return { paused: false, why: null, until: null };
}
+const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
+const arrayBuffer = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+
/**
- * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner, rules, pins }
- * (rules and pins: the built input rules and file hashes, read from dist/ when not given).
+ * Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),
+ * "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home,
+ * signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own
+ * options) }.
*/
export async function runWorker(cfg, deps) {
const now = deps.now ?? Date.now;
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
const log = deps.log ?? ((line) => console.log(`[${new Date().toISOString().slice(11, 19)}] ${line}`));
const fetchFn = deps.fetch ?? fetch;
+ const problem = siteProblem(cfg.site);
+ if (problem) throw new Error(problem);
const index = deps.requirements ?? loadRequirements();
const { ComputerRunner } = deps.ComputerRunner ? { ComputerRunner: deps.ComputerRunner } : await import("./dist/computer-runner.mjs");
const site = cfg.site.replace(/\/+$/, "");
const f = folders(cfg.workDir);
fs.mkdirSync(cfg.workDir, { recursive: true });
emptyFolders(f);
- const allowed = allowedNodes(cfg.allowNodesFile);
+ // Inputs kept by their SHA-256 while their job runs here (a job sent again reads nothing from the studio twice).
+ const cacheDir = path.join(cfg.workDir, "cache");
+ const emptyCache = () => fs.rmSync(cacheDir, { recursive: true, force: true });
+ emptyCache();
+ const hold = new Hold(path.join(cfg.workDir, "hold"));
+ const allowed = deps.allowed ?? allowedNodes(cfg.allowNodesFile);
const rules = deps.rules ?? inputRules();
- const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [] });
+ const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, ...deps.comfy });
+ // A ComfyUI that a stopped worker left running is stopped now, before anything else uses the GPU.
+ await comfy.stopLeftover();
const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75 });
+ const awake = deps.awake ?? new StayAwake({ now, log });
+ const ffmpeg = await (deps.ffmpegVersion ?? ffmpegVersion)(cfg.ffmpeg);
+ log(ffmpeg ? "ffmpeg is there: it takes clips and sound, and makes each one again first." : "No ffmpeg set (ffmpeg in worker.json): it takes pictures only.");
let comfyTrouble = null;
let troubleAt = 0;
let answer = null;
- let inv = { files: [], nodePacks: [] };
+ let inv = { files: [], nodePacks: [], media: ffmpeg ? ["image", "video", "audio"] : ["image"] };
let packs = [];
let invHash = null;
let gpuInfo = { otherApps: [], tempC: null };
let lastGpuAt = 0;
let pause = { paused: true, why: "here", until: null };
let busyJob = false;
- comfy.onCrash = (code) => log(`ComfyUI stopped (exit ${code}).`);
+ let job = Promise.resolve();
+ let lastTask = null;
+
+ // How often its ComfyUI stopped while running each task (a task that stops it twice fails, not the worker).
+ const crashFile = path.join(cfg.workDir, "crashes.json");
+ const crashes = (() => {
+ try {
+ const c = JSON.parse(fs.readFileSync(crashFile, "utf8"));
+ return c && typeof c === "object" ? c : {};
+ } catch {
+ return {};
+ }
+ })();
+ const saveCrashes = () => {
+ try {
+ fs.writeFileSync(crashFile, JSON.stringify(crashes), { mode: 0o600 });
+ } catch {}
+ };
+ comfy.onCrash = (code, task) => {
+ log(`ComfyUI stopped (exit ${code}).`);
+ if (!task) return;
+ crashes[task] = (crashes[task] ?? 0) + 1;
+ saveCrashes();
+ };
- const api = (p, init = {}) => fetchFn(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${cfg.token}`, "User-Agent": `FuobeWorker/${VERSION}` } });
+ const api = retrying(fetchFn, { now, sleep, signal: deps.signal, log });
+ const call = (p, init = {}) => api(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${cfg.token}`, "User-Agent": `FuobeWorker/${VERSION}` } });
async function scan() {
packs = packFolders(cfg.comfyDir, index);
- inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins), nodePacks: packs.map(({ name, commit }) => ({ name, commit })) };
+ inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins), nodePacks: packs.map(({ name, commit }) => ({ name, commit })), media: inv.media };
invHash = inventoryHash(inv);
}
+ // One look at a time; the next beat carries a changed hash, and the studio then asks for the list.
+ let scanning = null;
+ let scannedAt = now();
+ const rescan = () =>
+ (scanning ??= scan()
+ .catch((e) => log(`Couldn't look at its model folders: ${e.message}`))
+ .finally(() => {
+ scanning = null;
+ scannedAt = now();
+ }));
await scan();
+ /** An input for its ComfyUI: read from the studio once, kept by its SHA-256, and a clip or sound made again. */
+ async function takeInput(t, input, read) {
+ if (!/^[0-9a-f]{64}$/.test(String(input.sha256))) return "input-changed";
+ fs.mkdirSync(cacheDir, { recursive: true });
+ const kept = path.join(cacheDir, input.sha256);
+ let data = null;
+ if (fs.existsSync(kept)) {
+ const b = fs.readFileSync(kept);
+ if (sha256(b) === input.sha256) data = b;
+ }
+ if (!data) {
+ const got = await read();
+ if (typeof got === "string") return got;
+ data = Buffer.from(got);
+ fs.writeFileSync(kept, data, { mode: 0o600 });
+ }
+ const kind = mediaKind(input, t.graph);
+ if (!kind) return arrayBuffer(data);
+ // Without ffmpeg it takes no clip or sound: another worker that can make them again runs the job.
+ if (!ffmpeg) return "give-back";
+ const made = path.join(cacheDir, `${input.sha256}.${kind}`);
+ if (!fs.existsSync(made)) {
+ const part = `${made}.part`;
+ if (!(await (deps.reencode ?? reencode)({ ffmpeg: cfg.ffmpeg, kind, name: input.name, src: kept, dst: part }))) {
+ fs.rmSync(part, { force: true });
+ log(`Job ${t.id}: ffmpeg couldn't read one of its ${kind === "video" ? "clips" : "sounds"}.`);
+ return "input-unreadable";
+ }
+ fs.renameSync(part, made);
+ }
+ return arrayBuffer(fs.readFileSync(made));
+ }
+
const runner = new ComputerRunner(
{
- api,
+ api: call,
// Only its own ComfyUI, and only while the process it started is up: never whatever else listens on that port.
- local: (url, init) => (comfy.alive() && comfy.ready ? fetchFn(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running"))),
- sha256: async (data) => crypto.createHash("sha256").update(Buffer.from(data)).digest("hex"),
+ local: (url, init) => (comfy.alive() && comfy.ready ? comfy.fetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running"))),
+ sha256: async (data) => sha256(Buffer.from(data)),
origin: site,
- socket: typeof WebSocket === "function" ? (url) => new WebSocket(url) : undefined,
+ socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
now,
sleep,
- vet: (t) => {
- const problem = graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
+ vet: async (t) => {
+ const check = () => graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
+ let problem = check();
+ // A model file it doesn't have yet (a drive that came back after a restart): look again once before refusing.
+ if (problem?.reason === "model-unverified") {
+ log(`Job ${t.id} needs a model file it hasn't found: looking at its model folders again.`);
+ await rescan();
+ problem = check();
+ }
// Which node and input, for the PC's owner (never a value: those are someone's prompt or file).
if (problem) log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
return problem?.reason ?? null;
},
- ended: (t, phase) => {
+ ended: async (t, phase) => {
log(`Job ${t.id} ${phase}.`);
- return cleanJob(t, f, comfy.base, fetchFn);
+ // Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is.
+ if (phase === "done") hold.drop(t.id);
+ delete crashes[t.id];
+ saveCrashes();
+ await cleanJob(f, comfy.base, (url, init) => comfy.fetch(url, init));
+ emptyCache();
},
beatExtra: () => ({
protocol: PROTOCOL,
@@ -110,112 +236,156 @@ export async function runWorker(cfg, deps) {
onBeat: (a) => {
answer = a;
// The owner's switch on the Workers page wins over worker.json; null leaves worker.json's.
- const site = a?.worker?.autoResume;
- gpu.o.autoResume = typeof site === "boolean" ? site : !!cfg.autoResume;
+ const s = a?.worker?.autoResume;
+ gpu.o.autoResume = typeof s === "boolean" ? s : !!cfg.autoResume;
+ },
+ worker: {
+ hold,
+ input: takeInput,
+ stallMs: (cfg.stallMin ?? 10) * 60_000,
+ free: () => comfy.free(),
+ crashes: (t) => crashes[t.id] ?? 0,
+ stuck: async () => {
+ log("Its ComfyUI didn't let go of a job: starting it again.");
+ await comfy.stop();
+ },
+ claimed: async (t) => {
+ // Kept results of any other job aren't this worker's any more (one job at a time).
+ hold.dropAllBut(t?.id ?? null);
+ if (!t) return;
+ comfy.task = t.id;
+ // Another job than the one its ComfyUI last had: nothing of that one stays.
+ if (t.id !== lastTask) {
+ await cleanJob(f, comfy.base, (url, init) => comfy.fetch(url, init));
+ lastTask = t.id;
+ }
+ },
},
},
- { device: "worker", port: cfg.port, clientId: crypto.randomBytes(8).toString("hex") },
+ { device: "worker", port: cfg.port || 8190, clientId: crypto.randomBytes(8).toString("hex") },
);
const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;
const state = () => (pause.paused ? `Paused here (${pause.why})` : !answer ? "Connecting" : answer.worker?.paused ? "Paused on the website" : !answer.worker?.insideHours ? "Outside its hours" : answer.worker?.drain ? "Finishing, then pausing" : comfy.ready ? "Ready" : "Starting ComfyUI");
+ const take = (o) => {
+ busyJob = true;
+ job = runner
+ .claimAndRun(o)
+ .catch((e) => log(`A job stopped: ${e.message}`))
+ .finally(() => {
+ busyJob = false;
+ comfy.task = null;
+ });
+ };
let beatAt = 0;
let lastState = "";
- while (!deps.signal?.aborted) {
- const t = now();
- // Its own switch, and --for running out.
- let control = readControl(deps.home);
- if (control.paused && control.until && t >= control.until) {
- writeControl(deps.home, { paused: false });
- control = { paused: false };
- gpu.clear();
- log("The pause ran out: back to work.");
- }
- if (control.resumedAt && control.resumedAt > (gpu.clearedAt ?? 0)) {
- gpu.clear();
- gpu.clearedAt = control.resumedAt;
- }
- // The GPU, every 5 s, from nvidia-smi only.
- if (t - lastGpuAt >= 5000) {
- lastGpuAt = t;
- const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);
- if (reading) {
- const verdict = othersOf(reading, { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid }, cfg.busyVramMb ?? 1024);
- const was = gpu.paused;
- gpu.update(verdict, reading.tempC, t);
- gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC };
- if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing.`);
- if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
+ try {
+ while (!deps.signal?.aborted) {
+ const t = now();
+ // Its own switch, and --for running out.
+ let control = readControl(deps.home);
+ if (control.paused && control.until && t >= control.until) {
+ writeControl(deps.home, { paused: false });
+ control = { paused: false };
+ gpu.clear();
+ log("The pause ran out: back to work.");
}
- }
- if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t)) comfyTrouble = null;
- const next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };
- const changed = next.paused !== pause.paused || next.why !== pause.why;
- pause = next;
- // A new pause, or every 5 s while busy and 10 s otherwise: beat.
- if (changed || t - beatAt >= (busyJob ? 5000 : 10_000)) {
- beatAt = t;
- try {
- const a = await runner.beat();
- if (runner.view.stopped) {
- log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");
- break;
+ if (control.resumedAt && control.resumedAt > (gpu.clearedAt ?? 0)) {
+ gpu.clear();
+ gpu.clearedAt = control.resumedAt;
+ }
+ // The GPU, every 5 s, from nvidia-smi only.
+ if (t - lastGpuAt >= 5000) {
+ lastGpuAt = t;
+ const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);
+ if (reading) {
+ const verdict = othersOf(reading, { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid }, cfg.busyVramMb ?? 1024);
+ const was = gpu.paused;
+ gpu.update(verdict, reading.tempC, t);
+ gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC };
+ if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing.`);
+ if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
}
- if (a?.worker?.sendInventory) {
- await scan();
- const r = await api("/api/gpu/computer/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });
- if (r.ok) {
- const body = await r.json();
- log(`Sent its files: it can run ${body.workflows?.length ?? 0} of the studio's workflows.`);
+ }
+ if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t)) comfyTrouble = null;
+ const next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };
+ const changed = next.paused !== pause.paused || next.why !== pause.why;
+ pause = next;
+ // A new pause, or every 5 s while busy and 10 s otherwise: beat.
+ if (changed || t - beatAt >= (busyJob ? 5000 : 10_000)) {
+ beatAt = t;
+ try {
+ const a = await runner.beat();
+ if (runner.view.stopped) {
+ log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");
+ break;
}
+ if (a?.worker?.sendInventory) {
+ const r = await call("/api/gpu/computer/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });
+ if (r.ok) {
+ const body = await r.json();
+ log(`Sent its files: it can run ${body.workflows?.length ?? 0} of the studio's workflows.`);
+ }
+ }
+ } catch (e) {
+ log(`Can't reach the studio: ${e.message}`);
}
- } catch (e) {
- log(`Can't reach the studio: ${e.message}`);
}
- }
- // Its own ComfyUI runs only while it may work; a pause (and a stop-now) frees the GPU.
- const stopNow = pause.paused && (pause.why === "here-now" || pause.why?.startsWith("gpu-busy")) || answer?.worker?.pauseNow;
- if (mayWork()) {
- if (!comfy.alive() && !comfyTrouble) {
- if (comfy.crashedTooOften(t)) {
- comfyTrouble = "comfy-crashes";
- log("ComfyUI keeps stopping: pausing for an hour.");
- } else {
- try {
- log("Starting its own ComfyUI.");
- // The packs by their folder names on disk, which is what ComfyUI matches (whatever the catalog's case).
- await comfy.start(packs.map((p) => p.folder));
- } catch (e) {
- if (e instanceof PortBusy) {
- comfyTrouble = "port-busy";
- troubleAt = t;
- log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
- } else log(`ComfyUI didn't start: ${e.message}`);
+ // Its model folders, again every 10 minutes (in the background: beats go on while it hashes a new file).
+ if (t - scannedAt >= (deps.rescanMs ?? RESCAN_MS) && !scanning) void rescan();
+ // Its own ComfyUI runs only while it may work; a pause (and a stop-now) frees the GPU.
+ const stopNow = (pause.paused && (pause.why === "here-now" || pause.why?.startsWith("gpu-busy"))) || answer?.worker?.pauseNow;
+ if (mayWork()) {
+ if (!comfy.alive() && !comfyTrouble && t >= comfy.restartAt) {
+ if (comfy.crashedTooOften(t)) {
+ comfyTrouble = "comfy-crashes";
+ log("ComfyUI keeps stopping: pausing for an hour.");
+ } else {
+ try {
+ log("Starting its own ComfyUI.");
+ // The packs by their folder names on disk, which is what ComfyUI matches (whatever the catalog's case).
+ await comfy.start(packs.map((p) => p.folder));
+ } catch (e) {
+ if (e instanceof PortBusy) {
+ comfyTrouble = "port-busy";
+ troubleAt = t;
+ log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
+ } else if (e instanceof GuardMissing) {
+ comfyTrouble = "comfy-crashes";
+ log(`${e.message}: it won't use it.`);
+ } else log(`ComfyUI didn't start: ${e.message}`);
+ }
}
}
+ if (comfy.ready && answer?.runner && !busyJob) take();
+ } else if (comfy.alive() && (stopNow || !busyJob)) {
+ log("Stopping its own ComfyUI (paused).");
+ await comfy.stop();
}
- if (comfy.ready && answer?.runner && !busyJob) {
- busyJob = true;
- void runner
- .claimAndRun()
- .catch((e) => log(`A job stopped: ${e.message}`))
- .finally(() => (busyJob = false));
+ // Kept results go up even while it may not work: they need no GPU and no ComfyUI.
+ if (!busyJob && answer && hold.ids().length && !(mayWork() && comfy.ready)) take({ onlyHeld: true });
+ // Awake while it holds a job, has results to send, or waits for work.
+ awake.set(!!answer?.worker && (busyJob || hold.ids().length > 0 || !!mayWork()));
+ // A taken port is tried again (a bind test, never a connection) once a minute.
+ if (comfyTrouble === "port-busy" && t - troubleAt >= 60_000) comfyTrouble = null;
+ const s = state();
+ if (s !== lastState) {
+ lastState = s;
+ log(s);
}
- } else if (comfy.alive() && (stopNow || !busyJob)) {
- log("Stopping its own ComfyUI (paused).");
- await comfy.stop();
- }
- // A taken port is tried again (a bind test, never a connection) once a minute.
- if (comfyTrouble === "port-busy" && t - troubleAt >= 60_000) comfyTrouble = null;
- const s = state();
- if (s !== lastState) {
- lastState = s;
- log(s);
+ writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null });
+ await sleep(1000);
}
- writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null });
- await sleep(1000);
+ } finally {
+ // Every way out: the job in hand stops (its kept results stay for the next start), its ComfyUI stops, the PC may
+ // sleep again, and no input, result or cached file stays in its folders.
+ runner.stop();
+ await Promise.race([job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);
+ awake.set(false);
+ await comfy.stop();
+ emptyFolders(f);
+ emptyCache();
}
- runner.stop();
- await comfy.stop();
+ return deps.signal?.aborted ? "aborted" : (runner.view.stopped ?? "disconnected");
}
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 7c8098a3..29db94d0 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -48,10 +48,11 @@ or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected
that you have verified (see "Install and update"). Run `node scripts/build-worker.mjs`, then run
`node bin/fuobe.mjs worker setup`.
Setup asks for the studio's address, the token (as hidden input), ComfyUI's folder, the model folders, a worker
- folder and a port for the worker's own ComfyUI (default 8190). It refuses these:
+ folder and the path of ffmpeg (see "Clips and sound"). It refuses these:
+ - a studio address that does not start with `https://` (only `http://127.0.0.1` and `http://localhost` are allowed,
+ for tests);
- a folder that a cloud drive syncs;
- - a port that another program is using;
- - port 8188.
+ - an ffmpeg path where no ffmpeg runs.
On Windows it marks the worker folder as "not content indexed". The settings go to `worker.json`, and only you can
read that file. Setup also pauses the worker on the PC.
@@ -82,10 +83,14 @@ from a zip file, from a copy that someone sends you, or from a branch.
The worker always starts and stops its own ComfyUI process. It never uses a ComfyUI that it did not start. Its ComfyUI:
-- listens on `127.0.0.1` only, on the worker's own port;
+- listens on `127.0.0.1` only, on a free port that the worker picks at random (20000 to 59999) at each start. Port
+ 8188 is never used. To fix one port instead, set `port` in `worker.json`;
+- starts through the worker's guard (see below), with the worker folder as its working folder. A node that writes to
+ a relative path writes into the worker folder, not into ComfyUI's folder;
- uses its own `user`, `input`, `output` and `temp` folders in the worker folder;
- gets the model folders through `extra_model_paths.yaml`;
-- starts with `--disable-metadata` and `--disable-auto-launch`;
+- starts with `--disable-metadata` and `--disable-auto-launch`, and with `--disable-partner-nodes` when that ComfyUI
+ has the flag (the worker reads ComfyUI's `comfy/cli_args.py` to find out);
- loads only the custom node packs that the worker found (`--disable-all-custom-nodes --whitelist-custom-nodes …`).
The worker finds a pack whatever the case of its folder name, and gives ComfyUI the folder name as it is on disk;
- gets only the environment variables that it needs: the system's own, `PATH`, the temp folder, the user folders
@@ -99,8 +104,32 @@ another program is using the port. The worker then does not start ComfyUI, pause
and never connects to that port. The worker also talks to its ComfyUI only while the process that it started is
running.
-If its ComfyUI stops by itself, the worker starts it again, at most 3 times in one hour. After that, it pauses itself
-("ComfyUI keeps stopping").
+**The guard.** The worker makes a new random key at each start. It starts ComfyUI through
+`bin/lib/worker/comfy_guard.py`, which it copies into the worker folder (`guard/`) first. The guard reads the key from
+the environment, removes it from there, and puts a check in front of every request to ComfyUI:
+
+- The `Host` header must be exactly `127.0.0.1:<port>`. A web page that points its own name at 127.0.0.1 (DNS
+ rebinding) sends its own name, so it is refused.
+- The request must carry the key in `X-Fuobe-Worker-Key`. The worker sends it with every request and with the live
+ socket. Without it, the answer is 403.
+
+Before the worker sends the key, the process on the port must prove two things. It signs a random challenge with the
+key (`GET /fuobe-worker/hello`, HMAC-SHA-256), and it names its process id, which must be the one that the worker
+started. A program that took the port first learns nothing. When ComfyUI is ready, the worker also checks that a
+request without the key is refused. If it is not refused, the guard is missing, and the worker does not use that
+ComfyUI.
+
+**A ComfyUI left running.** The worker writes its ComfyUI's process id to `comfyui.pid` in the worker folder. If the
+worker stops without stopping ComfyUI (a crash), the next start finds that file. It stops that process, but only when
+the process's command line still names the guard in this worker folder, so a reused process id is never stopped.
+
+**Its log.** ComfyUI's output goes to `comfyui.log` in the worker folder. Each start begins a new file, and so does a
+file that passes 20 MB. The worker keeps the two files before it (`comfyui.1.log`, `comfyui.2.log`).
+
+**When its ComfyUI stops by itself.** The worker starts it again after a short wait: 5 seconds, then twice as long each
+time in a row, at most 2 minutes. If ComfyUI stops twice while it runs the same job, that job fails with plain words
+("This run stopped twice at the same point"), and the worker goes on with the next job. If ComfyUI stops more than 3
+times in one hour with no job running, the worker pauses itself ("ComfyUI keeps stopping").
### Pauses
@@ -185,11 +214,63 @@ The worker reports a model file only when its SHA-256 matches the hash that the
is not reported, so no job that needs it comes to the worker. The worker keeps the hashes it computed, so a restart
does not read the files again.
-After each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from its
-ComfyUI's history. At start, it empties its folders.
+After each job, however it ended, nothing of it stays in its ComfyUI: the worker empties the queue, stops a prompt that
+still runs, and clears the whole history (a meta-batch's passes too). It also deletes the job's inputs and results from
+its folders, and its copies of the inputs. At start, and whenever it stops, it empties these folders too. Before it
+starts a job that its ComfyUI did not have last, it clears its ComfyUI the same way.
Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). Clips and sound go to workers
-only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default; `image,video,audio` for all).
+only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default; `image,video,audio` for all). The worker then makes
+each one again before its ComfyUI reads it (see "Clips and sound").
+
+### Clips and sound
+
+Set `ffmpeg` in `worker.json` to the path of ffmpeg (setup asks for it). The worker then makes every clip and every
+sound that a job sends again, into a fresh file, before its ComfyUI sees it:
+
+- a clip keeps its first picture stream and its first sound stream, encoded again in the format that its name says
+ (H.264 and AAC in MP4 for most names, VP9 and Opus for WebM);
+- a sound keeps its first sound stream, in the format that its name says (WAV for any other name);
+- nothing else of the file is kept: no metadata, chapters, subtitles, attachments or data streams.
+
+The worker knows a clip or a sound by its type, by its name, or by the loader that reads it in the graph. ffmpeg runs
+in its own process, at low priority, for at most 20 minutes. If ffmpeg cannot read a file, the job fails with plain
+words ("A clip or a sound in this run couldn't be read").
+
+Without `ffmpeg`, the worker takes pictures only. Its inventory says so (`media: ["image"]`), and the studio sends it no
+workflow that reads a clip or a sound. If such a job comes anyway, the worker gives it back to the line.
+
+### When something goes wrong
+
+The worker keeps its jobs going by itself:
+
+- **Results are kept until the studio has them.** When its ComfyUI finishes a job, the worker copies every result into
+ `hold/<job>/` in the worker folder before it tells the studio. The copy stays until the studio has every file. If
+ the worker or its ComfyUI stops in between, the next claim gives the job back to this worker, and it uploads the
+ kept files from where the studio's copy got to. The job never runs twice. Kept results go up even while the worker
+ is paused, because they need no GPU. Kept results of a job that is no longer this worker's are deleted.
+- **One retry policy for the studio.** A studio that restarts, a proxy that answers 502, 503 or 52x, a network that
+ drops, or a busy studio that says when to come back is waited out. The pause grows from 1 second to at most 30
+ seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a call
+ again only when that is safe. A proxy's page in place of the studio's answer (a 403 that is not JSON) never stops
+ the worker.
+- **A job that stalls goes back to the line.** If a job makes no progress for `stallMin` minutes (10), or runs past the
+ run limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps
+ its place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and
+ starts it again. A job that is given back counts as an attempt; the third time, it fails.
+- **Out of memory.** The worker frees its ComfyUI's memory (`/free`) and sends the job once more. Only a second time
+ fails the job.
+- **Inputs are read once.** The worker keeps a copy of each input (by its SHA-256) while its job runs, so a job that
+ is sent again reads nothing from the studio twice. If the studio will not send an input again (429 with no
+ `Retry-After`), the job fails at once instead of looping.
+- **The PC stays awake** while the worker holds a job, has results to send, or waits for work. A small helper asks the
+ system to stay awake (`SetThreadExecutionState` on Windows, `caffeinate` on macOS, `systemd-inhibit` on Linux). The
+ screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.
+- **Its model folders are read again** every 10 minutes, and whenever a job needs a model file that the worker has not
+ found yet. A drive that comes back after a restart is noticed, and the studio gets the new list.
+- **When the studio stops the worker.** If the studio no longer knows the worker's token, `fuobe worker run` ends with
+ exit code 3; any other stop that you did not ask for ends with exit code 1. The sign-in task that
+ `fuobe worker install` adds then starts the worker again after a minute. Ctrl+C ends with 0.
### The protocol
@@ -200,15 +281,21 @@ token on every call, so a revoked token stops at once.
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {
otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
insideHours, nextChangeAt, lanes, minProtocol, sendInventory }`.
-- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }] }` →
- `{ lanes, workflows, missing }`.
+- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }], media }`
+ → `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,
+ `audio`). With no `media`, the studio counts every kind.
- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,
models }`.
- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finished
job also count: the last 20 jobs in each lane give the median and the 90th percentile.
-- Reports, inputs and results work as they do for the browser. `failed` can also give `unknown-node`, `unsafe-path` (a
- path, or an input outside its rule) or `model-unverified` as the reason. The worker's own log names the node and the
- input, never the value.
+- Reports, inputs and results work as they do for the browser, with these additions:
+ - `finished`, and the last `passes` report, carry `execMs` (the time that its ComfyUI spent executing the job, from
+ ComfyUI's own timestamps: no waits, no uploads) and `device` (the GPU's name). The studio keeps both with the job.
+ - `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and
+ counts as an attempt. Only a worker's job can be given back.
+ - `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
+ `input-crashed` (its ComfyUI stopped twice on the job) or `input-unreadable` (ffmpeg could not read a clip or a
+ sound) as the reason. The worker's own log names the node and the input, never the value.
Each worker counts against its own rate limits, so three workers that beat every 5 seconds never hold each other up.
@@ -230,9 +317,14 @@ routes.
## Tests
- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,
- `tests/worker-input-rules.test.ts`, `tests/worker-environment.test.ts`). The input-rule tests send graphs that try to
- write or read files outside the worker's folders, and check that the worker refuses them. They also prepare every
- catalog workflow the way the studio does, and check that the worker accepts each one.
+ `tests/worker-input-rules.test.ts`, `tests/worker-environment.test.ts`, `tests/worker-guard.test.ts`,
+ `tests/worker-runner.test.ts`, `tests/worker-recovery.test.ts`, `tests/worker-parts.test.ts`). The input-rule tests
+ send graphs that try to write or read files outside the worker's folders, and check that the worker refuses them.
+ They also prepare every catalog workflow the way the studio does, and check that the worker accepts each one. The
+ recovery tests run the worker against the studio's routes and a stand-in ComfyUI that the worker starts: they kill
+ its ComfyUI halfway, stop the worker before an upload, make its ComfyUI hang, and check that the output arrives
+ each time, once. The guard tests run the real guard in front of a stand-in ComfyUI when a Python with aiohttp is
+ there (`FUOBE_TEST_PYTHON`, else `python3` or `python`); the clip tests need `ffmpeg` on the `PATH`.
- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). These
use a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.
- `python -m unittest discover -s tests` in `integrations/fuobe-connect`
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 1ea521bd..4036108b 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -425,8 +425,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now(), ...(origin && { origin }) };
log.push(entry);
- // The stand-in's own count (never a ComfyUI route) stays readable for a test in another process.
- if (opts.workerGuard && url.pathname !== "/__fake/stats") {
+ // The stand-in's own routes (never ComfyUI's) stay readable for a test in another process.
+ if (opts.workerGuard && !url.pathname.startsWith("/__fake/")) {
const deny = () => {
entry.status = 403;
res.writeHead(403);
@@ -472,6 +472,11 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
if (req.method === "OPTIONS") return reply(200, "");
// The stand-in's own count, for a test driving it from another process (never a ComfyUI route).
if (url.pathname === "/__fake/stats") return reply(200, { posts, uploads: inputs.size, history: history.size, pid: process.pid, running: running?.id ?? null, step: running ? currentStep : null });
+ // An input as it arrived (what a worker sent its ComfyUI).
+ if (url.pathname === "/__fake/input") {
+ const got = inputs.get(url.searchParams.get("name") ?? "");
+ return got ? reply(200, got, "application/octet-stream") : reply(404, { error: "no file" });
+ }
// ComfyUI's own: unload models and free memory.
if (url.pathname === "/free" && req.method === "POST") {
entry.body = JSON.parse(body.toString("utf8") || "{}");
diff --git a/tests/worker-guard.test.ts b/tests/worker-guard.test.ts
new file mode 100644
index 00000000..5689a4a3
--- /dev/null
+++ b/tests/worker-guard.test.ts
@@ -0,0 +1,277 @@
+/**
+ * The guard of a worker's own ComfyUI (bin/lib/worker/comfy_guard.py and comfy.mjs): every start takes a free port at
+ * random and a new key; a request with another Host or without the key is refused; the process on the port proves it
+ * is the one the worker started before the worker sends the key; a ComfyUI that a stopped worker left running is
+ * stopped at the next start; its log turns over.
+ *
+ * The Python guard runs for real in front of a stand-in ComfyUI main.py (an aiohttp server made the way ComfyUI's
+ * server.py makes its own). That needs a Python with aiohttp (FUOBE_TEST_PYTHON, else python3 or python when they have
+ * aiohttp); without one, those checks are skipped. Never a real ComfyUI, never a GPU.
+ */
+import { spawn, spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import http from "node:http";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { comfyArgs, GUARD, GuardMissing, OwnComfy, partnerFlag, pickPort, PortBusy, restartDelayMs, RotatingLog } from "../bin/lib/worker/comfy.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.setConfig({ testTimeout: 60_000 });
+
+const ROOT = path.resolve(__dirname, "..");
+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
+
+function pythonWithAiohttp(): string | null {
+ for (const exe of [process.env.FUOBE_TEST_PYTHON, "python3", "python"].filter(Boolean) as string[]) {
+ const r = spawnSync(exe, ["-I", "-c", "import aiohttp"], { encoding: "utf8", timeout: 20_000 });
+ if (r.status === 0) return exe;
+ }
+ return null;
+}
+const python = pythonWithAiohttp();
+
+/** A raw request, with any Host (fetch can't send another one). */
+function raw(port: number, p: string, headers: Record<string, string>): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> {
+ return new Promise((resolve, reject) => {
+ const req = http.request({ host: "127.0.0.1", port, path: p, method: "GET", headers }, (res) => {
+ let body = "";
+ res.on("data", (d) => (body += d));
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body, headers: res.headers }));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+}
+
+/** A stand-in for ComfyUI's main.py: its server made as server.py makes it, with its own middleware and a sub-app. */
+const STAND_IN_MAIN = String.raw`
+import argparse, os
+from aiohttp import web
+
+p = argparse.ArgumentParser()
+p.add_argument("--listen")
+p.add_argument("--port", type=int)
+args, _ = p.parse_known_args()
+
+async def own(request, handler):
+ response = await handler(request)
+ response.headers["X-Own-Middleware"] = "1"
+ return response
+
+async def stats(request):
+ return web.json_response({"system": {"comfyui_version": "stand-in", "os": "nt"}, "devices": []})
+
+async def env(request):
+ return web.json_response({"keyInEnv": "FUOBE_WORKER_GUARD_KEY" in os.environ, "cwd": os.getcwd()})
+
+async def files(request):
+ return web.json_response(["a"])
+
+async def ws(request):
+ s = web.WebSocketResponse()
+ await s.prepare(request)
+ await s.send_str("hello")
+ await s.close()
+ return s
+
+if __name__ == "__main__":
+ internal = web.Application()
+ internal.router.add_get("/files", files)
+ app = web.Application(client_max_size=1024, middlewares=[own])
+ app.router.add_get("/system_stats", stats)
+ app.router.add_get("/env", env)
+ app.router.add_get("/ws", ws)
+ app.add_subapp("/internal", internal)
+ web.run_app(app, host=args.listen, port=args.port, print=None)
+`;
+
+const started: OwnComfy[] = [];
+afterEach(async () => {
+ for (const c of started.splice(0)) await c.stop().catch(() => {});
+});
+
+function wsOpens(url: string, headers: Record<string, string>): Promise<boolean> {
+ return new Promise((resolve) => {
+ const ws = new WebSocket(url, { headers } as unknown as string[]);
+ const done = (ok: boolean) => {
+ try {
+ ws.close();
+ } catch {}
+ resolve(ok);
+ };
+ ws.onopen = () => done(true);
+ ws.onerror = () => done(false);
+ setTimeout(() => done(false), 10_000);
+ });
+}
+
+describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", () => {
+ it("refuses another Host and a missing key, proves itself before the key is sent, and lets the worker's own requests through", async () => {
+ const comfyDir = tempDir("fuobe-guard-comfy-");
+ const workDir = tempDir("fuobe-guard-work-");
+ fs.writeFileSync(path.join(comfyDir, "main.py"), STAND_IN_MAIN);
+ const c = new OwnComfy({ comfyDir, workDir, python, modelDirs: [] });
+ started.push(c);
+ await c.start();
+ expect(c.ready).toBe(true);
+ const port = c.port!;
+ expect(port).toBeGreaterThanOrEqual(20_000);
+ expect(port).not.toBe(8188);
+ // ComfyUI started from the guard, written into the worker folder, with the worker folder as its working folder.
+ expect(fs.existsSync(path.join(workDir, "guard", "comfy_guard.py"))).toBe(true);
+ const host = `127.0.0.1:${port}`;
+ const key = { [GUARD.key]: c.headers()[GUARD.key] };
+ // The worker's own requests: through, ComfyUI's own middleware still runs, its sub-app answers too.
+ const ok = await c.fetch(`${c.base}/system_stats`);
+ expect(ok.status).toBe(200);
+ expect(ok.headers.get("x-own-middleware")).toBe("1");
+ expect((await c.fetch(`${c.base}/internal/files`)).status).toBe(200);
+ const env = (await (await c.fetch(`${c.base}/env`)).json()) as { keyInEnv: boolean; cwd: string };
+ expect(env.keyInEnv).toBe(false);
+ expect(fs.realpathSync(env.cwd)).toBe(fs.realpathSync(workDir));
+ // No key, a wrong key, another Host (a rebinding page's name, localhost): refused.
+ expect((await raw(port, "/system_stats", { Host: host })).status).toBe(403);
+ expect((await raw(port, "/system_stats", { Host: host, [GUARD.key]: "0".repeat(64) })).status).toBe(403);
+ expect((await raw(port, "/system_stats", { Host: `evil.example:${port}`, ...key })).status).toBe(403);
+ expect((await raw(port, "/system_stats", { Host: `localhost:${port}`, ...key })).status).toBe(403);
+ expect((await raw(port, "/internal/files", { Host: host })).status).toBe(403);
+ expect((await raw(port, "/system_stats", { Host: host, ...key })).status).toBe(200);
+ // The proof: the challenge signed with the key, and the process the worker started. Never without the right Host.
+ const challenge = crypto.randomBytes(16).toString("hex");
+ const hello = await raw(port, GUARD.hello, { Host: host, [GUARD.challenge]: challenge });
+ expect(hello.status).toBe(200);
+ const proof = JSON.parse(hello.body) as { proof: string; pid: number };
+ expect(proof.proof).toBe(crypto.createHmac("sha256", key[GUARD.key]).update(challenge).digest("hex"));
+ expect(proof.pid).toBe(c.pid);
+ expect((await raw(port, GUARD.hello, { Host: host })).status).toBe(403);
+ expect((await raw(port, GUARD.hello, { Host: `evil.example:${port}`, [GUARD.challenge]: challenge })).status).toBe(403);
+ // The live socket: only with the key.
+ expect(await wsOpens(`ws://${host}/ws`, key)).toBe(true);
+ expect(await wsOpens(`ws://${host}/ws`, {})).toBe(false);
+ // The next start: another key (and, most likely, another port); the old key opens nothing.
+ const oldKey = key[GUARD.key];
+ await c.stop();
+ await c.start();
+ expect(c.headers()[GUARD.key]).not.toBe(oldKey);
+ expect((await raw(c.port!, "/system_stats", { Host: `127.0.0.1:${c.port}`, [GUARD.key]: oldKey })).status).toBe(403);
+ });
+});
+
+describe("the guard as the worker checks it", () => {
+ const fakeCommand = (more: string[] = []) => [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--worker-guard", "1", ...more];
+
+ it("takes a random free port at each start (never 8188), and refuses a request with another Host or without the key", async () => {
+ const workDir = tempDir("fuobe-guard-fake-");
+ const c = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true });
+ started.push(c);
+ await c.start();
+ const port = c.port!;
+ expect(port).toBeGreaterThanOrEqual(20_000);
+ expect(port).toBeLessThan(60_000);
+ expect(JSON.parse(fs.readFileSync(path.join(workDir, "comfyui.pid"), "utf8"))).toMatchObject({ pid: c.pid, port });
+ expect((await c.fetch(`http://127.0.0.1:1/system_stats`)).status).toBe(200);
+ expect((await fetch(`${c.base}/system_stats`)).status).toBe(403);
+ expect((await raw(port, "/system_stats", { Host: `rebound.example:${port}`, ...c.headers() })).status).toBe(403);
+ await c.stop();
+ expect(fs.existsSync(path.join(workDir, "comfyui.pid"))).toBe(false);
+ expect(await pickPort(null, (() => {
+ const tries = [8188, port];
+ return () => tries.shift() ?? 30_000;
+ })())).toBe(port);
+ await expect(pickPort(8188)).rejects.toBeInstanceOf(PortBusy);
+ expect(await pickPort(40_123)).toBe(40_123);
+ });
+
+ it("never sends the key to a program that can't prove it has it, and won't use a ComfyUI without the guard", async () => {
+ const dir = tempDir("fuobe-guard-impostor-");
+ const seen = path.join(dir, "seen.txt");
+ // Answers the challenge wrongly, and writes down every key it is sent.
+ fs.writeFileSync(
+ path.join(dir, "impostor.mjs"),
+ `import http from "node:http"; import fs from "node:fs";
+http.createServer((q, s) => { if (q.headers["${GUARD.key.toLowerCase()}"]) fs.appendFileSync(${JSON.stringify(seen)}, "key\\n");
+ s.writeHead(200, { "content-type": "application/json" }); s.end(JSON.stringify({ proof: "0".repeat(64), pid: process.pid })); }).listen(Number(process.argv[2]), "127.0.0.1");`,
+ );
+ const impostor = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: [process.execPath, path.join(dir, "impostor.mjs"), "{port}"], comfyGuard: true });
+ await expect(impostor.start()).rejects.toBeInstanceOf(PortBusy);
+ expect(impostor.alive()).toBe(false);
+ expect(fs.existsSync(seen)).toBe(false);
+ // Proves itself, but answers without the key: the guard isn't there.
+ fs.writeFileSync(
+ path.join(dir, "open.mjs"),
+ `import http from "node:http"; import crypto from "node:crypto"; const key = process.env.${GUARD.env};
+http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/json" });
+ s.end(JSON.stringify(q.url.startsWith("${GUARD.hello}") ? { proof: crypto.createHmac("sha256", key).update(String(q.headers["${GUARD.challenge.toLowerCase()}"])).digest("hex"), pid: process.pid } : {})); }).listen(Number(process.argv[2]), "127.0.0.1");`,
+ );
+ const open = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: [process.execPath, path.join(dir, "open.mjs"), "{port}"], comfyGuard: true });
+ await expect(open.start()).rejects.toBeInstanceOf(GuardMissing);
+ expect(open.alive()).toBe(false);
+ });
+
+ it("stops a ComfyUI that a stopped worker left running, and nothing else", async () => {
+ const workDir = tempDir("fuobe-guard-leftover-");
+ const first = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true });
+ await first.start();
+ const pid = first.pid!;
+ // The worker stops without stopping its ComfyUI (a crash): the next one finds the pid file.
+ const second = new OwnComfy({ workDir, comfyDir: workDir, comfyCommand: fakeCommand(), comfyGuard: true });
+ started.push(second, first);
+ expect(await second.stopLeftover()).toBe(true);
+ await new Promise((r) => setTimeout(r, 500));
+ expect(() => process.kill(pid, 0)).toThrow();
+ // A pid file naming a process that isn't one this worker started (a reused pid): left alone.
+ const other = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
+ try {
+ fs.writeFileSync(path.join(workDir, "comfyui.pid"), JSON.stringify({ pid: other.pid, port: 1, marker: FAKE }));
+ expect(await second.stopLeftover()).toBe(false);
+ expect(() => process.kill(other.pid!, 0)).not.toThrow();
+ expect(fs.existsSync(path.join(workDir, "comfyui.pid"))).toBe(false);
+ } finally {
+ other.kill();
+ }
+ });
+});
+
+describe("its start, its restarts and its log", () => {
+ it("leaves out partner nodes where this ComfyUI can", () => {
+ const comfyDir = tempDir("fuobe-guard-args-");
+ expect(partnerFlag(comfyDir)).toBe(false);
+ fs.mkdirSync(path.join(comfyDir, "comfy"));
+ fs.writeFileSync(path.join(comfyDir, "comfy", "cli_args.py"), 'parser.add_argument("--disable-partner-nodes", action="store_true")\n');
+ expect(partnerFlag(comfyDir)).toBe(true);
+ expect(comfyArgs({ workDir: "/w" }, [], { port: 41_000, partnerFlag: true })).toEqual(expect.arrayContaining(["--port", "41000", "--disable-partner-nodes"]));
+ expect(comfyArgs({ workDir: "/w" }, [], { port: 41_000 })).not.toContain("--disable-partner-nodes");
+ });
+
+ it("starts again after a short wait that grows, and pauses only for stops with no job running", () => {
+ expect([1, 2, 3, 4, 5, 6, 7].map(restartDelayMs)).toEqual([5_000, 10_000, 20_000, 40_000, 80_000, 120_000, 120_000]);
+ const c = new OwnComfy({ workDir: "/w" });
+ const t = 10_000_000;
+ c.crashes = [1, 2, 3, 4].map((i) => ({ at: t - i * 1000, task: "AAAAAAAAAAAAAAAA" }));
+ expect(c.crashedTooOften(t)).toBe(false);
+ c.crashes.push(...[1, 2, 3, 4].map((i) => ({ at: t - i * 1000, task: null })));
+ expect(c.crashedTooOften(t)).toBe(true);
+ expect(c.crashedTooOften(t + 3_600_000)).toBe(false);
+ });
+
+ it("turns its log over at each start and when it grows too big, keeping the two before", () => {
+ const dir = tempDir("fuobe-guard-log-");
+ const file = path.join(dir, "comfyui.log");
+ for (const n of [1, 2, 3]) {
+ const log = new RotatingLog(file, { maxBytes: 10 });
+ log.write(Buffer.from(`start ${n}`));
+ log.close();
+ }
+ expect(fs.readdirSync(dir).sort()).toEqual(["comfyui.1.log", "comfyui.2.log", "comfyui.log"]);
+ expect(fs.readFileSync(file, "utf8")).toBe("start 3");
+ expect(fs.readFileSync(path.join(dir, "comfyui.2.log"), "utf8")).toBe("start 1");
+ const log = new RotatingLog(file, { maxBytes: 10 });
+ log.write(Buffer.from("0123456789"));
+ log.write(Buffer.from("next"));
+ log.close();
+ expect(fs.readFileSync(file, "utf8")).toBe("next");
+ expect(fs.readFileSync(path.join(dir, "comfyui.1.log"), "utf8")).toBe("0123456789");
+ });
+});
diff --git a/tests/worker-parts.test.ts b/tests/worker-parts.test.ts
new file mode 100644
index 00000000..c5637a7e
--- /dev/null
+++ b/tests/worker-parts.test.ts
@@ -0,0 +1,188 @@
+/**
+ * The worker program's smaller parts: its one retry policy for calls to the studio (bin/lib/worker/retry.mjs), keeping
+ * the PC awake while it works (awake.mjs), how it makes clips and sound again (media.mjs), and the studio's address.
+ */
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vitest";
+import { helperCommand, StayAwake } from "../bin/lib/worker/awake.mjs";
+import { encodeArgs, mediaKind } from "../bin/lib/worker/media.mjs";
+import { RETRY, retrying } from "../bin/lib/worker/retry.mjs";
+import { siteProblem } from "../bin/lib/worker/run.mjs";
+
+/** A clock that moves only when the policy sleeps. */
+function clock() {
+ let t = 1_000_000;
+ const slept: number[] = [];
+ return { now: () => t, sleep: async (ms: number) => void (slept.push(ms), (t += ms)), slept };
+}
+
+/** A studio that answers each call with the next of `list` (the last one again and again). */
+const answers = (list: (() => Response | Error)[]) => {
+ const calls: string[] = [];
+ const fetchFn = async (url: string, init: RequestInit = {}) => {
+ calls.push(`${init.method ?? "GET"} ${url}`);
+ const next = (list.length > 1 ? list.shift()! : list[0])();
+ if (next instanceof Error) throw next;
+ return next;
+ };
+ return { fetchFn, calls };
+};
+const netError = (code: string) => () => Object.assign(new TypeError("fetch failed"), { cause: { code } });
+const page = (status: number) => () => new Response("<html>challenge</html>", { status, headers: { "content-type": "text/html" } });
+const json = (body: unknown, status = 200, headers: Record<string, string> = {}) => () => Response.json(body, { status, headers });
+const text = (body: string, status = 200, headers: Record<string, string> = {}) => () => new Response(body, { status, headers });
+
+describe("one retry policy for calls to the studio", () => {
+ it("waits out a studio that is restarting, with a pause that grows, and gets the answer", async () => {
+ const c = clock();
+ const a = answers([page(502), page(503), json({ ok: true })]);
+ const res = await retrying(a.fetchFn, c)("https://studio.test/api/gpu/computer/claim", { method: "POST" });
+ expect(res.status).toBe(200);
+ expect(c.slept).toEqual([1000, 2000]);
+ });
+
+ it("gives up on a call after 2 minutes, and on a part of a result after an hour", async () => {
+ const c = clock();
+ const call = await retrying(answers([page(503)]).fetchFn, c)("https://studio.test/api/gpu/computer/tasks/x/report", { method: "POST" });
+ expect(call.status).toBe(503);
+ expect(c.slept.reduce((a, b) => a + b, 0)).toBe(RETRY.callMs);
+ expect(Math.max(...c.slept)).toBeLessThanOrEqual(RETRY.maxPauseMs);
+ const c2 = clock();
+ const part = await retrying(answers([page(503)]).fetchFn, c2)("https://studio.test/api/gpu/computer/tasks/x/outputs/0?offset=0&total=9", { method: "PUT", body: "x" });
+ expect(part.status).toBe(503);
+ expect(c2.slept.reduce((a, b) => a + b, 0)).toBe(RETRY.uploadMs);
+ });
+
+ it("never waits out a beat: the next one comes soon", async () => {
+ const c = clock();
+ const a = answers([page(503), json({})]);
+ expect((await retrying(a.fetchFn, c)("https://studio.test/api/gpu/computer/beat", { method: "POST" })).status).toBe(503);
+ expect(a.calls).toHaveLength(1);
+ });
+
+ it("a proxy's page in place of the studio's answer (403 without JSON) is no answer, never a stop", async () => {
+ const c = clock();
+ const res = await retrying(answers([page(403)]).fetchFn, c)("https://studio.test/api/gpu/computer/beat", { method: "POST" });
+ expect(res.status).toBe(503);
+ // The studio's own 403 (JSON) is its answer.
+ const own = await retrying(answers([json({ error: "no" }, 403)]).fetchFn, clock())("https://studio.test/api/gpu/computer/claim", { method: "POST" });
+ expect(own.status).toBe(403);
+ });
+
+ it("sends a call again only when that is safe: a read, a part of a result, or a call that never left", async () => {
+ // A read: any network failure.
+ const read = answers([netError("ECONNRESET"), text("data")]);
+ expect((await retrying(read.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/inputs/0")).status).toBe(200);
+ // A report that may have arrived: not sent twice.
+ const sent = answers([netError("ECONNRESET"), json({ ok: true })]);
+ await expect(retrying(sent.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/report", { method: "POST" })).rejects.toThrow();
+ expect(sent.calls).toHaveLength(1);
+ // A report that never left: sent again.
+ const refused = answers([netError("ECONNREFUSED"), json({ ok: true })]);
+ expect((await retrying(refused.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/report", { method: "POST" })).status).toBe(200);
+ // A slow answer (504) to a report: it may have arrived, so not again; to a read, again.
+ const slow = answers([page(504), json({ ok: true })]);
+ expect((await retrying(slow.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/report", { method: "POST" })).status).toBe(504);
+ const slowRead = answers([page(504), text("data")]);
+ expect((await retrying(slowRead.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/inputs/0")).status).toBe(200);
+ });
+
+ it("a busy studio is waited out as long as it says; a 429 that says nothing (a file sent enough times) is the answer", async () => {
+ const c = clock();
+ const busy = answers([text("busy", 429, { "Retry-After": "7" }), json({ ok: true })]);
+ expect((await retrying(busy.fetchFn, c)("https://studio.test/api/gpu/computer/claim", { method: "POST" })).status).toBe(200);
+ expect(c.slept).toEqual([7000]);
+ const spent = answers([json({ error: "That file was sent enough times." }, 429), text("data")]);
+ expect((await retrying(spent.fetchFn, clock())("https://studio.test/api/gpu/computer/tasks/x/inputs/0")).status).toBe(429);
+ expect(spent.calls).toHaveLength(1);
+ });
+
+ it("stops waiting once the worker is stopping", async () => {
+ const ctrl = new AbortController();
+ ctrl.abort();
+ const a = answers([page(503), json({})]);
+ expect((await retrying(a.fetchFn, { ...clock(), signal: ctrl.signal })("https://studio.test/api/gpu/computer/claim", { method: "POST" })).status).toBe(503);
+ expect(a.calls).toHaveLength(1);
+ });
+});
+
+describe("keeping the PC awake while it works", () => {
+ class FakeChild extends EventEmitter {
+ stdin = { ended: false, end: () => void (this.stdin.ended = true), on: () => {} };
+ killed = false;
+ kill() {
+ this.killed = true;
+ }
+ }
+
+ it("starts one helper while it works and stops it after; one that stops by itself is tried again only after a while", () => {
+ const spawned: FakeChild[] = [];
+ let t = 0;
+ const a = new StayAwake({ platform: "win32", now: () => t, spawn: (() => (spawned.push(new FakeChild()), spawned.at(-1))) as never });
+ a.set(true);
+ a.set(true);
+ expect(spawned).toHaveLength(1);
+ expect(a.on).toBe(true);
+ a.set(false);
+ expect(spawned[0].stdin.ended).toBe(true);
+ expect(spawned[0].killed).toBe(true);
+ expect(a.on).toBe(false);
+ a.set(true);
+ spawned[1].emit("exit", 1);
+ expect(a.on).toBe(false);
+ t += 60_000;
+ a.set(true);
+ expect(spawned).toHaveLength(2);
+ t += 10 * 60_000;
+ a.set(true);
+ expect(spawned).toHaveLength(3);
+ });
+
+ it("asks each system its own way: SetThreadExecutionState on Windows, caffeinate on macOS, systemd-inhibit on Linux", () => {
+ const [cmd, args] = helperCommand("win32")!;
+ expect(cmd).toBe("powershell");
+ const script = Buffer.from(String(args.at(-1)), "base64").toString("utf16le");
+ expect(script).toContain("SetThreadExecutionState([uint32]2147483649)");
+ expect(script).toContain("[Console]::In.ReadLine()");
+ expect(helperCommand("darwin", 42)).toEqual(["caffeinate", ["-i", "-w", "42"]]);
+ expect(helperCommand("linux")![0]).toBe("systemd-inhibit");
+ expect(helperCommand("aix")).toBeNull();
+ });
+});
+
+describe("clips and sound, made again", () => {
+ it("knows a clip or a sound by its type, its name, or the loader that reads it", () => {
+ const graph = { "1": { class_type: "LoadVideo", inputs: { file: "fuobe_aaaaaaaaaaaa.bin" } }, "2": { class_type: "LoadAudio", inputs: { audio: "fuobe_bbbbbbbbbbbb.bin [input]" } } };
+ expect(mediaKind({ name: "fuobe_x1234567.png", contentType: "image/png" }, graph)).toBeNull();
+ expect(mediaKind({ name: "fuobe_x1234567.mp4", contentType: "application/octet-stream" }, {})).toBe("video");
+ expect(mediaKind({ name: "fuobe_x1234567.bin", contentType: "audio/wav" }, {})).toBe("audio");
+ // Labelled a picture, but a clip loader reads it: made again as a clip.
+ expect(mediaKind({ name: "fuobe_aaaaaaaaaaaa.bin", contentType: "image/png" }, graph)).toBe("video");
+ expect(mediaKind({ name: "fuobe_bbbbbbbbbbbb.bin", contentType: "image/png" }, graph)).toBe("audio");
+ });
+
+ it("keeps one picture and one sound stream and nothing else of the file, in the format its name says", () => {
+ const mp4 = encodeArgs("video", "fuobe_a.mp4", "in", "out");
+ expect(mp4.slice(0, 7)).toEqual(["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", "in"]);
+ expect(mp4).toEqual(expect.arrayContaining(["-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn", "-map", "0:v:0", "0:a:0?", "libx264", "aac", "mp4"]));
+ expect(mp4.at(-1)).toBe("out");
+ expect(encodeArgs("video", "fuobe_a.webm", "in", "out")).toEqual(expect.arrayContaining(["libvpx-vp9", "libopus", "webm"]));
+ expect(encodeArgs("video", "fuobe_a.xyz", "in", "out")).toEqual(expect.arrayContaining(["libx264", "mp4"]));
+ const wav = encodeArgs("audio", "fuobe_a.wav", "in", "out");
+ expect(wav).toEqual(expect.arrayContaining(["-vn", "-map", "0:a:0", "pcm_s24le", "wav"]));
+ expect(wav).not.toContain("0:v:0");
+ expect(encodeArgs("audio", "fuobe_a.mp3", "in", "out")).toEqual(expect.arrayContaining(["libmp3lame", "mp3"]));
+ });
+});
+
+describe("the studio's address", () => {
+ it("is https, or this PC itself", () => {
+ expect(siteProblem("https://studio.example")).toBeNull();
+ expect(siteProblem("http://127.0.0.1:3361")).toBeNull();
+ expect(siteProblem("http://localhost:3000")).toBeNull();
+ expect(siteProblem("http://studio.example")).toMatch(/https/);
+ expect(siteProblem("http://192.168.1.5:3000")).toMatch(/https/);
+ expect(siteProblem("ftp://studio.example")).toMatch(/https/);
+ expect(siteProblem("studio")).toMatch(/web address/);
+ });
+});
diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.ts
index 6b290dd0..32910050 100644
--- a/tests/worker-program.test.ts
+++ b/tests/worker-program.test.ts
@@ -119,21 +119,23 @@ describe("its own ComfyUI (check 12)", () => {
});
describe("cleanup (check 13) and setup", () => {
- it("after a job, its files leave the worker folder and its history entry goes", async () => {
+ it("after a job, its files leave the worker folder, and its ComfyUI keeps nothing of it: no queue, no prompt, no history", async () => {
const dir = tempDir("fuobe-worker-clean-");
const f = { input: path.join(dir, "input"), output: path.join(dir, "output"), temp: path.join(dir, "temp") };
for (const d of Object.values(f)) fs.mkdirSync(d, { recursive: true });
fs.writeFileSync(path.join(f.input, "fuobe_abcdefgh12.png"), "x");
+ fs.writeFileSync(path.join(f.input, "fuobe_leftover1234.mp4"), "x");
fs.mkdirSync(path.join(f.output, "fuobe"));
fs.writeFileSync(path.join(f.output, "fuobe", "out_00001_.png"), "x");
fs.writeFileSync(path.join(f.temp, "preview.png"), "x");
const calls: string[] = [];
- await cleanJob({ inputs: [{ name: "fuobe_abcdefgh12.png" }], promptId: "p-1" }, f, "http://127.0.0.1:1", (async (url: string, init: RequestInit) => {
+ await cleanJob(f, "http://127.0.0.1:1", (async (url: string, init: RequestInit) => {
calls.push(`${init.method} ${url} ${init.body}`);
return new Response("{}");
}) as typeof fetch);
expect(Object.values(f).flatMap((d) => fs.readdirSync(d))).toEqual([]);
- expect(calls).toEqual(['POST http://127.0.0.1:1/history {"delete":["p-1"]}']);
+ // The whole history goes (a meta-batch's passes included), not only the job's own entry.
+ expect(calls).toEqual(['POST http://127.0.0.1:1/queue {"clear":true}', "POST http://127.0.0.1:1/interrupt {}", 'POST http://127.0.0.1:1/history {"clear":true}']);
});
it("refuses a synced folder", () => {
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
new file mode 100644
index 00000000..c74b7d5c
--- /dev/null
+++ b/tests/worker-recovery.test.ts
@@ -0,0 +1,392 @@
+/**
+ * The worker program end to end (bin/lib/worker/run.mjs), against the studio's real routes and its own stand-in
+ * ComfyUI (tests/helpers/fake-local-comfy.ts, started and stopped by the worker as a process of its own, behind the
+ * worker's guard). Never a real ComfyUI, never a GPU.
+ *
+ * - Its ComfyUI is killed at 50%: the output arrives.
+ * - The worker stops after the render and before the upload (or before the studio heard it finished): the output
+ * arrives after the next start, and its ComfyUI got exactly one prompt. Paused here, it still sends kept results.
+ * - Its ComfyUI hangs: the job is given back within the stall limit, and then runs to the end.
+ * - A request to its ComfyUI with another Host or without the key is refused.
+ * - A clip is made again by ffmpeg before its ComfyUI sees it; without ffmpeg, the job goes back to the line.
+ * - A model file that turns up later is reported within one look at its folders.
+ */
+import { spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import http from "node:http";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { runWorker } from "../bin/lib/worker/run.mjs";
+import { Hold } from "../bin/lib/worker/hold.mjs";
+import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";
+import { FAKE_PNG } from "./helpers/fake-local-comfy";
+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = tempDir("fuobe-worker-recovery-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const { ComputerRunner } = await import("@/lib/computer-runner");
+
+const ROOT = path.resolve(__dirname, "..");
+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
+const SITE = "http://127.0.0.1:9";
+const RULES = inputRules(readCatalog(ROOT));
+const ALLOWED = new Set(["LoadImage", "KSampler", "SaveImage", "LoadVideo"]);
+const hasFfmpeg = spawnSync("ffmpeg", ["-hide_banner", "-version"]).status === 0;
+const realFetch = globalThis.fetch;
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+let routes: ComputerRoutes;
+beforeAll(async () => {
+ routes = await loadRoutes();
+ setSetting("comfyWhere", "workers");
+});
+afterAll(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+});
+beforeEach(() => {
+ resetRates();
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+type W = { id: string; token: string };
+const state = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+
+/** A worker the owner added and resumed, all day, for the "small" lane, with one workflow it can run. */
+function addWorker(): W {
+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } });
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: ["small"], workflows: ["wf-test"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ return w;
+}
+
+let gens = 0;
+/** A job for the workers that loads one input (a picture, or a clip) and saves a picture. */
+function addTask(o: { clip?: Buffer } = {}): { id: string; input: string } {
+ const gid = `recovery-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")
+ .run(gid, now, now);
+ const input = o.clip ? tasks.stageInput("owner", o.clip, "video/mp4", "clip.mp4") : tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");
+ const loader = o.clip ? { class_type: "LoadVideo", inputs: { file: input } } : { class_type: "LoadImage", inputs: { image: input } };
+ const t = tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph: { "1": loader, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },
+ pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
+ });
+ return { id: t.id, input };
+}
+
+interface Studio {
+ calls: string[];
+ reports: { at: number; body: Record<string, unknown> }[];
+ inventories: Record<string, unknown>[];
+ intercept: ((p: string, init: RequestInit) => Promise<Response | undefined> | Response | undefined) | null;
+}
+
+/** fetch for the worker: the studio's routes for SITE, its own ComfyUI for the rest. */
+function router(w: W, s: Studio) {
+ const api = apiAs(routes, null);
+ return async (url: string, init: RequestInit = {}) => {
+ if (!String(url).startsWith(SITE)) return realFetch(url, init);
+ const u = new URL(url);
+ const p = u.pathname + u.search;
+ const mine = await s.intercept?.(p, init);
+ if (mine) return mine;
+ s.calls.push(`${init.method ?? "GET"} ${u.pathname}`);
+ if (p.endsWith("/report")) s.reports.push({ at: Date.now(), body: JSON.parse(String(init.body)) });
+ // The inventory is written down, not saved: the worker keeps the lanes the test gave it.
+ if (p === "/api/gpu/computer/inventory") {
+ s.inventories.push(JSON.parse(String(init.body)));
+ return Response.json({ ok: true, lanes: ["small"], workflows: ["wf-test"], missing: [] });
+ }
+ expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);
+ return api(p, init);
+ };
+}
+
+const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];
+afterEach(async () => {
+ for (const r of running.splice(0)) {
+ r.ctrl.abort();
+ await r.done.catch(() => {});
+ }
+});
+
+interface Pc {
+ home: string;
+ workDir: string;
+ comfyDir: string;
+ countFile: string;
+ logs: string[];
+ awake: boolean[];
+}
+
+function pc(): Pc {
+ const base = tempDir("fuobe-worker-pc-");
+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), logs: [], awake: [] };
+ for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });
+ return p;
+}
+
+/** Start `fuobe worker run` in this process (its ComfyUI a stand-in process of its own). */
+function start(w: W, s: Studio, p: Pc, o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; ffmpeg?: string | null; rescanMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string> } = {}) {
+ const ctrl = new AbortController();
+ const cfg = {
+ site: SITE,
+ token: w.token,
+ comfyDir: p.comfyDir,
+ workDir: p.workDir,
+ modelDirs: o.modelDirs ?? [],
+ comfyCommand: [
+ process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off",
+ "--steps", String(o.steps ?? 4), "--step-ms", String(o.stepMs ?? 40), "--worker-guard", "1", "--count-file", p.countFile,
+ ...(o.failNext ? ["--fail-next", o.failNext] : []),
+ ],
+ comfyGuard: true,
+ stallMin: o.stallMin ?? 10,
+ ffmpeg: o.ffmpeg ?? null,
+ };
+ const done = runWorker(cfg, {
+ fetch: router(w, s),
+ home: p.home,
+ signal: ctrl.signal,
+ requirements: o.requirements ?? { folders: [], files: {}, packs: {}, workflows: {} },
+ ComputerRunner,
+ rules: RULES,
+ pins: o.pins ?? {},
+ allowed: ALLOWED,
+ readGpu: async () => null,
+ ...(o.ffmpeg === undefined || o.ffmpeg === null ? { ffmpegVersion: async () => null } : {}),
+ awake: { set: (on: boolean) => void (p.awake.at(-1) !== on && p.awake.push(on)) },
+ sleep: (ms: number) => sleep(Math.min(ms, 50)),
+ log: (line: string) => void p.logs.push(line),
+ ...(o.rescanMs && { rescanMs: o.rescanMs }),
+ });
+ const r = { ctrl, done };
+ running.push(r);
+ return r;
+}
+
+const studio = (): Studio => ({ calls: [], reports: [], inventories: [], intercept: null });
+
+async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 100): Promise<Exclude<T, false | null | undefined | 0 | "">> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await fn();
+ if (v) return v as Exclude<T, false | null | undefined | 0 | "">;
+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);
+ await sleep(every);
+ }
+}
+
+/** Its ComfyUI now: the pid and port the worker wrote down for this start. */
+const comfyOf = (p: Pc) => {
+ try {
+ return JSON.parse(fs.readFileSync(path.join(p.workDir, "comfyui.pid"), "utf8")) as { pid: number; port: number };
+ } catch {
+ return null;
+ }
+};
+const fakeStats = async (port: number) => (await realFetch(`http://127.0.0.1:${port}/__fake/stats`)).json() as Promise<{ posts: number; running: string | null; step: number | null }>;
+const prompts = (p: Pc) => (fs.existsSync(p.countFile) ? fs.readFileSync(p.countFile, "utf8").trim().split("\n").filter(Boolean).length : 0);
+const ended = (id: string) => until(() => ["done", "failed", "canceled"].includes(state(id).state) && state(id), 90_000);
+
+function raw(port: number, p: string, headers: Record<string, string>): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const req = http.request({ host: "127.0.0.1", port, path: p, headers }, (res) => {
+ res.resume();
+ res.on("end", () => resolve(res.statusCode ?? 0));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+}
+
+describe("a worker keeps its jobs going", () => {
+ it("its ComfyUI is killed at 50%: the output arrives (and its guard refuses another Host and a missing key)", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ start(w, s, p, { steps: 10, stepMs: 150 });
+ const comfy = await until(async () => {
+ const c = comfyOf(p);
+ return c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 5 ? c : null;
+ });
+ // Its own ComfyUI: refused without the key, and to a page that named itself 127.0.0.1 (DNS rebinding).
+ expect(await raw(comfy.port, "/system_stats", { Host: `127.0.0.1:${comfy.port}` })).toBe(403);
+ expect(await raw(comfy.port, "/prompt", { Host: `rebound.example:${comfy.port}` })).toBe(403);
+ process.kill(comfy.pid, "SIGKILL");
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
+ // Sent again once, from its own copy of the input: the studio sent the input once.
+ expect(prompts(p)).toBe(2);
+ expect(s.calls.filter((c) => c.includes("/inputs/"))).toHaveLength(1);
+ expect(p.logs.some((l) => /ComfyUI stopped/.test(l))).toBe(true);
+ expect(p.awake).toContain(true);
+ });
+
+ it("stopped after the render and before the upload: the next start uploads it, and its ComfyUI got exactly one prompt", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ const first = start(w, s, p);
+ s.intercept = (q, init) => {
+ if (!q.includes("/outputs/") || init.method !== "PUT") return undefined;
+ first.ctrl.abort();
+ return new Response("stopping", { status: 503 });
+ };
+ expect(await first.done).toBe("aborted");
+ expect(state(id).state).toBe("collecting");
+ expect(new Hold(path.join(p.workDir, "hold")).ids()).toEqual([id]);
+ // Nothing else of the job stayed on this PC, and its ComfyUI stopped with it; the PC may sleep again.
+ expect(["input", "output", "temp"].flatMap((d) => fs.readdirSync(path.join(p.workDir, d)))).toEqual([]);
+ expect(comfyOf(p)).toBeNull();
+ expect(p.awake.at(-1)).toBe(false);
+ s.intercept = null;
+ start(w, s, p);
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
+ expect(prompts(p)).toBe(1);
+ expect(new Hold(path.join(p.workDir, "hold")).ids()).toEqual([]);
+ });
+
+ it("stopped before the studio heard it finished: the next start, paused here, sends the kept results without its ComfyUI", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ const first = start(w, s, p);
+ s.intercept = (q, init) => {
+ if (!q.endsWith("/report") || JSON.parse(String(init.body)).event !== "finished") return undefined;
+ first.ctrl.abort();
+ return new Response("stopping", { status: 503 });
+ };
+ await first.done;
+ expect(state(id).state).toBe("running");
+ s.intercept = null;
+ // Paused here: it starts no ComfyUI, but its kept results need none.
+ fs.writeFileSync(path.join(p.home, "control.json"), JSON.stringify({ paused: true }));
+ start(w, s, p);
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ expect(fs.readFileSync(tasks.outputFile(id, 0)).equals(FAKE_PNG)).toBe(true);
+ expect(prompts(p)).toBe(1);
+ expect(comfyOf(p)).toBeNull();
+ expect(tasks.execOf(t)?.ms).toBeTypeOf("number");
+ });
+
+ it("its ComfyUI hangs: the job is given back within the stall limit, then runs to the end", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask();
+ const stallMs = 3_000;
+ start(w, s, p, { failNext: "never", stallMin: stallMs / 60_000 });
+ await until(() => prompts(p) >= 1);
+ const sentAt = Date.now();
+ const back = await until(() => s.reports.find((r) => r.body.event === "give-back"));
+ expect(back.body).toEqual({ event: "give-back", why: "stalled" });
+ expect(back.at - sentAt).toBeLessThan(stallMs + 10_000);
+ const t = await ended(id);
+ expect(t).toMatchObject({ state: "done", requeues: 1 });
+ expect(prompts(p)).toBe(2);
+ });
+
+ it("stops when the studio no longer knows its token, and says so", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const r = start(w, s, p);
+ await until(() => s.calls.some((c) => c.endsWith("/beat")));
+ pool.patchWorker(w.id, { revoke: true });
+ expect(await r.done).toBe("signed-out");
+ });
+
+ it("refuses a studio address that isn't https (this PC itself aside)", async () => {
+ const p = pc();
+ await expect(runWorker({ site: "http://studio.example", token: "t", workDir: p.workDir, comfyDir: p.comfyDir }, { home: p.home })).rejects.toThrow(/https/);
+ });
+});
+
+describe("clips and sound", () => {
+ const clip = (dirName: string) => {
+ const out = path.join(tempDir(dirName), "clip.mp4");
+ const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-metadata", "title=private-note", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", out]);
+ if (r.status !== 0) throw new Error(String(r.stderr));
+ return fs.readFileSync(out);
+ };
+
+ it.runIf(hasFfmpeg)("a clip is made again by ffmpeg before its ComfyUI sees it", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const original = clip("fuobe-worker-clip-");
+ expect(original.includes("private-note")).toBe(true);
+ const { id, input } = addTask({ clip: original });
+ start(w, s, p, { ffmpeg: "ffmpeg" });
+ await until(() => s.inventories.length > 0);
+ expect(s.inventories[0].media).toEqual(["image", "video", "audio"]);
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ const comfy = comfyOf(p)!;
+ const sent = Buffer.from(await (await realFetch(`http://127.0.0.1:${comfy.port}/__fake/input?name=${input}`)).arrayBuffer());
+ expect(sent.length).toBeGreaterThan(0);
+ expect(sent.equals(original)).toBe(false);
+ expect(sent.subarray(4, 8).toString("latin1")).toBe("ftyp");
+ expect(sent.includes("private-note")).toBe(false);
+ // Its copies of people's files went with the job.
+ expect(fs.existsSync(path.join(p.workDir, "cache"))).toBe(false);
+ });
+
+ it("without ffmpeg it takes pictures only, and gives a job with a clip back to the line", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const { id } = addTask({ clip: Buffer.concat([Buffer.from("000000186674797069736f6d0000020069736f6d69736f32", "hex"), Buffer.alloc(64, 1)]) });
+ start(w, s, p, { ffmpeg: null });
+ const back = await until(() => s.reports.find((r) => r.body.event === "give-back"));
+ expect(back.body).toEqual({ event: "give-back", why: "media" });
+ expect(s.inventories[0].media).toEqual(["image"]);
+ expect(prompts(p)).toBe(0);
+ await until(() => state(id).requeues >= 1 && state(id));
+ });
+});
+
+describe("its model folders", () => {
+ it("a model file that turns up after the start is reported within one look", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const models = tempDir("fuobe-worker-models-");
+ const sha = crypto.createHash("sha256").update("hello").digest("hex");
+ const requirements = { folders: ["loras"], files: { late: { folder: "loras", file: "late.safetensors", sizeBytes: 5 } }, packs: {}, workflows: {} };
+ start(w, s, p, { modelDirs: [models], requirements, pins: { "loras/late.safetensors": sha }, rescanMs: 1_000 });
+ await until(() => s.inventories.length > 0);
+ expect(s.inventories[0].files).toEqual([]);
+ fs.mkdirSync(path.join(models, "loras"));
+ fs.writeFileSync(path.join(models, "loras", "late.safetensors"), "hello");
+ const seen = await until(() => s.inventories.find((i) => (i.files as unknown[]).length > 0), 60_000);
+ expect(seen.files).toEqual([{ folder: "loras", name: "late.safetensors", size: 5, sha256: sha }]);
+ });
+});
diff --git a/tests/worker-runner.test.ts b/tests/worker-runner.test.ts
index d0472469..e6a9f6f4 100644
--- a/tests/worker-runner.test.ts
+++ b/tests/worker-runner.test.ts
@@ -36,7 +36,7 @@ const { tabFailureWords } = await import("@/lib/relay");
let fake: LocalComfy;
let routes: ComputerRoutes;
const realFetch = globalThis.fetch;
-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
beforeAll(async () => {
fake = await startLocalComfy({ cors: "off", steps: 4, stepMs: 20, latencyMs: 10 });
@@ -364,7 +364,7 @@ describe("results kept until the studio has them", () => {
},
};
const asked: string[] = [];
- await hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async (f) => {
+ await hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async (f: { filename: string; subfolder: string; type: string }) => {
asked.push(`${f.type}/${f.subfolder}/${f.filename}`);
return new Response(FAKE_PNG);
});