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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: the worker program saves the next token from its beat answer and uses it
Adarsh993595c3e9dc
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 18e6cd3b..fb44f11f 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -19,7 +19,7 @@ import { fileURLToPath } from "node:url";import { StayAwake } from "./awake.mjs";import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";-import { ffmpegOf, PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";+import { ffmpegOf, PROTOCOL, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";@@ -62,6 +62,9 @@ export const MODELS_CHECK_MS = 60_000;*/export const SLEPT_MS = 60_000;+/** A worker token as the studio makes them. */+const NEXT_TOKEN = /^fuobe_wkr_[A-Za-z0-9_-]{43}$/;+/** Kept results that the studio hasn't taken for this long are deleted (the studio drops its jobs after a day). */export const HOLD_MAX_AGE_MS = 24 * HOUR;@@ -284,7 +287,22 @@ async function work(saved, deps, owner) {};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}` } });+ // Its token: worker.json's, until the studio gives it the next one (a token with a lifetime, docs/gpu-workers.md).+ let token = cfg.token;+ const call = (p, init = {}) => api(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${token}`, "User-Agent": `FuobeWorker/${VERSION}` } });+ /** The studio's next token: saved in worker.json first, then used from the next call on (the old one stops then). */+ const takeToken = (next) => {+ if (!next || typeof next.value !== "string" || !NEXT_TOKEN.test(next.value) || next.value === token) return;+ if (!deps.home) return;+ try {+ saveConfig(deps.home, { ...savedConfig(deps.home), token: next.value });+ } catch (e) {+ log(`Couldn't save its next token in worker.json (${e.message}): it keeps the one it has, and asks again later.`);+ return;+ }+ token = next.value;+ log(`Saved its next token in worker.json${Number.isFinite(next.expiresAt) ? ` (it lasts until ${new Date(next.expiresAt).toISOString().slice(0, 10)})` : ""}.`);+ };async function scan() {packs = packFolders(cfg.comfyDir, index);@@ -387,6 +405,8 @@ async function work(saved, deps, owner) {return {protocol: PROTOCOL,version: VERSION,+ // It saves the next token a beat answer gives it.+ canRotateToken: !!deps.home,local: pause,gpu: gpuInfo,inventoryHash: invHash,@@ -405,6 +425,7 @@ async function work(saved, deps, owner) {const min = Number(a?.worker?.minProtocol);if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");answer = a;+ takeToken(a?.worker?.token);// The owner's switch on the Workers page wins over worker.json; null leaves worker.json's.const s = a?.worker?.autoResume;gpu.o.autoResume = typeof s === "boolean" ? s : !!cfg.autoResume;diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex cb47427b..6d6aefa6 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -490,9 +490,10 @@ worker's token lasts that many days. A worker added before the lifetime was sethalf of it is gone, the beat answer of a worker that says it saves tokens (`canRotateToken: true` in its beat) gives itthe next token (`worker.token: { value, expiresAt }`). The worker saves it and uses it from its next call on. The oldtoken stops at the new one's first use. A next token that is never used is given again, as a new one, after 10-minutes. A paired ComfyUI's token keeps no lifetime. Set the lifetime only once every pool worker sends-`canRotateToken: true`: the token of a worker that doesn't expires at the end of its lifetime, and the worker stops-until you rotate its token in Settings → Workers.+minutes. A paired ComfyUI's token keeps no lifetime. The worker program sends `canRotateToken: true`: it saves the+next token in `worker.json` first, then uses it. If it can't save it, it keeps the token it has and gets the next one+again later. An older worker program doesn't rotate its token: update every worker before you set the lifetime, or+its token expires at the end of its lifetime and the worker stops until you rotate its token in Settings → Workers.**Where a token is used from.** For a pool worker, the studio remembers the countries (Cloudflare's `cf-ipcountry`)and the networks (an IPv4 address's /24 or an IPv6 address's /64, read only with `FUOBE_TRUST_PROXY=1`) its token wasdiff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.tsindex 72a5d991..a21b1172 100644--- a/tests/worker-recovery.test.ts+++ b/tests/worker-recovery.test.ts@@ -12,6 +12,8 @@* - 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.+ * - A token with a lifetime: the worker saves the next token from a beat answer in worker.json and uses it, and the old+ * token stops.* - Its PC sleeps mid-run and the studio takes the job back: the next beat says how long it slept, the attempt is taken* back, and the output arrives once.* - A model folder that isn't there yet (a drive still locked after a restart): the worker waits for it, says so, and@@ -104,6 +106,8 @@ interface Studio {reports: { at: number; body: Record<string, unknown> }[];inventories: Record<string, unknown>[];intercept: ((p: string, init: RequestInit) => Promise<Response | undefined> | Response | undefined) | null;+ /** Next tokens the studio gave the worker in its beat answers (the worker may use them from then on). */+ tokens: string[];}/** fetch for the worker: the studio's routes for SITE, its own ComfyUI for the rest. */@@ -122,8 +126,13 @@ function router(w: W, s: Studio) {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);+ expect([w.token, ...s.tokens].map((t) => `Bearer ${t}`)).toContain(new Headers(init.headers).get("authorization"));+ const res = await api(p, init);+ if (p === "/api/gpu/computer/beat" && res.ok) {+ const next = ((await res.clone().json()) as { worker?: { token?: { value: string } } }).worker?.token?.value;+ if (next) s.tokens.push(next);+ }+ return res;};}@@ -205,7 +214,7 @@ function start(return r;}-const studio = (): Studio => ({ calls: [], reports: [], inventories: [], intercept: null });+const studio = (): Studio => ({ calls: [], reports: [], inventories: [], intercept: null, tokens: [] });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;@@ -679,4 +688,37 @@ describe("its model folders", () => {const last = beats.at(-1)!;expect(last.slept).toBeUndefined();});++ it("a token with a lifetime: it saves the next one in worker.json, uses it, and the old one stops", async () => {+ process.env.FUOBE_WORKER_TOKEN_DAYS = "2";+ try {+ const w = addWorker();+ const s = studio();+ const p = pc();+ // Half its life is gone: its next beat answer gives it the next token.+ db().prepare("UPDATE relay_workers SET expires_at = ? WHERE id = ?").run(Date.now() + 60 * 60_000, w.id);+ start(w, s, p);+ const saved = await until(() => {+ try {+ const t = (JSON.parse(fs.readFileSync(path.join(p.home, "worker.json"), "utf8")) as { token?: string }).token;+ return t && t !== w.token ? t : null;+ } catch {+ return null;+ }+ });+ expect(s.tokens).toContain(saved);+ // It uses the new one: the studio switches to it, and the old one no longer works.+ const hash = crypto.createHash("sha256").update(saved).digest("hex");+ await until(() => (db().prepare("SELECT token_hash FROM relay_workers WHERE id = ?").get(w.id) as { token_hash: string }).token_hash === hash);+ const workersModule = await import("@/server/computer/workers");+ expect(workersModule.workerFromAuth("Bearer " + w.token)).toBeNull();+ expect(workersModule.workerFromAuth("Bearer " + saved)?.id).toBe(w.id);+ // And it goes on working with it.+ const { id } = addTask();+ expect((await ended(id)).state).toBe("done");+ expect(p.logs.some((l) => /Saved its next token/.test(l))).toBe(true);+ } finally {+ delete process.env.FUOBE_WORKER_TOKEN_DAYS;+ }+ });});