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
Stop at once on SIGTERM: end live-update streams and stop the runners
Adarsh547b947a1f3c
diff --git a/src/app/api/live/events/route.ts b/src/app/api/live/events/route.tsindex 83cad67a..63a0f806 100644--- a/src/app/api/live/events/route.ts+++ b/src/app/api/live/events/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { liveWho } from "@/server/live/access";import { onLiveStatus, type LiveStatus } from "@/server/live/comfy-live";import { sessionOf } from "@/server/live/sessions";+import { onShutdown } from "@/server/shutdown";/*** Live edit's status for this tab (server-sent events): `status` (online, who runs on ComfyUI, the queue, whether@@ -28,7 +29,9 @@ export async function GET(request: Request) {const status = (st: LiveStatus) => send(`event: status\ndata: ${JSON.stringify(st)}\n\n`);const off = s.gpu ? (status({ online: true, running: null, queue: 0, otherRan: false }), () => {}) : onLiveStatus(status);const ping = setInterval(() => send(": ping\n\n"), 15_000);+ let unhook = () => {};stop = () => {+ unhook();clearInterval(ping);off();try {@@ -36,6 +39,8 @@ export async function GET(request: Request) {} catch {}};request.signal.addEventListener("abort", () => stop(), { once: true });+ // Ends when the server starts stopping, so an update's old instance stops at once (src/server/shutdown.ts).+ unhook = onShutdown(() => stop());},cancel() {stop();diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 7b095166..90b19fd1 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -2,10 +2,13 @@* Runs once when the server starts: start the generation runner right away, so jobs that were in* flight before a restart keep advancing (and live updates flow) even when the UI only lists them.* Also empties what has been in the Trash for 30 days (then daily), starts Assist's scheduled tasks and Character- * Swap Studio's sweep.+ * Swap Studio's sweep. On SIGTERM or SIGINT, ends the live-updates streams and stops these runners, so the server+ * stops at once (src/server/shutdown.ts).*/export async function register() {if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;+ const { drainOnSignals } = await import("./server/shutdown");+ drainOnSignals();const { ensureRunner } = await import("./server/generations");ensureRunner();const { ensureTrashPurge } = await import("./server/library");diff --git a/src/server/live.ts b/src/server/live.tsindex 7dc7f91f..db746111 100644--- a/src/server/live.ts+++ b/src/server/live.ts@@ -1,5 +1,6 @@import "server-only";import type Database from "better-sqlite3";+import { onShutdown } from "@/server/shutdown";/*** Live updates for the feed (GET /api/generations/stream). Every write to the generations@@ -103,7 +104,8 @@ const PING_MS = 15_000;/*** A server-sent events stream of generation changes: `event: generation` (the Generation JSON,* exactly as GET /api/generations returns it), `event: deleted` ({"id"}), `: ping` every 15 s.- * The listener and the ping are removed as soon as the client goes away.+ * The listener and the ping are removed as soon as the client goes away. The stream also ends when the server starts+ * stopping (shutdown.ts); the browser then reconnects, to whichever instance serves the site by then.** `allowed`: whether whoever opened the stream may still read it, asked before every event and on every ping (`ping`* true: look again even when nothing changed, so a sign-in that expires is caught too). The stream ends at the first@@ -136,9 +138,11 @@ export function generationEventStream(signal: AbortSignal, opts: { pingMs?: numbconst ping = setInterval(() => {if (still(true)) send(": ping\n\n");}, opts.pingMs ?? PING_MS);+ let unhook = () => {};stop = () => {if (!open) return;open = false;+ unhook();off();clearInterval(ping);signal.removeEventListener("abort", stop);@@ -150,6 +154,9 @@ export function generationEventStream(signal: AbortSignal, opts: { pingMs?: numb};signal.addEventListener("abort", stop);if (signal.aborted) return stop();+ // Ends when the server starts stopping, so an update's old instance stops at once (shutdown.ts).+ unhook = onShutdown(stop);+ if (!open) return;// Reconnect quickly after a restart; the first comment flushes the headers through proxies.send("retry: 2000\n: connected\n\n");},diff --git a/src/server/shutdown.ts b/src/server/shutdown.tsnew file mode 100644index 00000000..3ae7da3b--- /dev/null+++ b/src/server/shutdown.ts@@ -0,0 +1,91 @@+import "server-only";++/**+ * A quick, clean stop when the server is asked to stop (SIGTERM from the service manager, SIGINT from a terminal).+ *+ * `next start` stops by closing its HTTP server and waiting for every open request to end. A live-updates stream never+ * ends by itself, so without this the old instance of an update kept running until the service manager killed it,+ * which also cut every request still in progress. On the signal, this:+ * - ends every live-updates stream (each browser reconnects on its own, to whichever instance serves the site now), so+ * Next's own stop finishes once the real requests are done;+ * - stops the background runners (generations, trash, sweeps, schedules, skills, studios), so a stopping instance takes+ * no new steps while the next one runs them. A step already under way finishes.+ *+ * Next's own signal handler still does the stopping and exits; this only adds to it.+ */++type Stop = () => void;++interface ShutdownState {+ stops: Set<Stop>;+ draining: boolean;+ hooked: boolean;+}++declare global {+ var __fuobeShutdown: ShutdownState | undefined;+}++const state = (): ShutdownState => (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });++/** Whether the server is stopping. */+export const draining = () => state().draining;++/**+ * Calls `stop` once when the server starts stopping (right away when it already is). Returns the function that forgets+ * it, for a stream that ends for another reason first.+ */+export function onShutdown(stop: Stop): () => void {+ const s = state();+ if (s.draining) {+ stop();+ return () => {};+ }+ s.stops.add(stop);+ return () => void s.stops.delete(stop);+}++/** The intervals the background runners keep on globalThis (each module's `ensure…`). */+function runnerTimers(): (ReturnType<typeof setInterval> | undefined)[] {+ const g = globalThis;+ return [+ g.__fuobeRunner?.timer,+ g.__fuobeRunner?.fastTimer,+ g.__fuobeTrashPurge?.timer,+ g.__fuobeAccountSweep?.timer,+ g.__fuobeRelaySweep,+ g.__fuobeFacelessRunner?.timer,+ g.__fuobeScheduleRunner?.timer,+ g.__fuobeSkillRuns?.timer,+ g.__fuobeSwapStudioRunner,+ ];+}++/** Ends the streams and stops the runners. Safe to call more than once. */+export function drain(): void {+ const s = state();+ if (s.draining) return;+ s.draining = true;+ // The timers stay set on their objects, so a late `ensure…` call sees a runner and doesn't start another one.+ for (const t of runnerTimers()) if (t) clearInterval(t);+ for (const stop of [...s.stops]) {+ try {+ stop();+ } catch {+ // A stream the browser already closed.+ }+ }+ s.stops.clear();+}++/**+ * Drains on SIGTERM and SIGINT, next to Next's own handler (which then exits). Not when NEXT_MANUAL_SIG_HANDLE is set:+ * then Next adds no handler, and a listener here would keep the process from exiting on the signal.+ */+export function drainOnSignals(): void {+ const s = state();+ if (s.hooked || process.env.NEXT_MANUAL_SIG_HANDLE) return;+ s.hooked = true;+ process.once("SIGTERM", drain);+ process.once("SIGINT", drain);+}diff --git a/tests/shutdown-drain.test.ts b/tests/shutdown-drain.test.tsnew file mode 100644index 00000000..5b54d49a--- /dev/null+++ b/tests/shutdown-drain.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";++// When the server is asked to stop, the live-updates streams end and the background runners stop, so `next start`+// finishes its own stop at once instead of waiting on a stream that never ends.+process.env.FUOBE_DATA_DIR = tempDir("fuobe-drain-");+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const live = await import("@/server/live");+const gens = await import("@/server/generations");+const shutdown = await import("@/server/shutdown");++type Reader = ReadableStreamDefaultReader<Uint8Array>;+const dec = new TextDecoder();++/** Reads a stream to its end; null when it is still open after `ms`. */+async function readToEnd(reader: Reader, ms: number): Promise<string | null> {+ let text = "";+ const end = Date.now() + ms;+ for (;;) {+ const left = end - Date.now();+ if (left <= 0) return null;+ const r = await Promise.race([reader.read(), new Promise<"wait">((ok) => setTimeout(() => ok("wait"), left))]);+ if (r === "wait") return null;+ if (r.done) return text;+ text += dec.decode(r.value);+ }+}++describe("stopping the server", () => {+ it("ends every open live-updates stream and stops the runners", async () => {+ gens.ensureRunner();+ const runner = globalThis.__fuobeRunner!;+ let ticks = 0;+ const tick = runner.tick;+ runner.tick = async () => {+ ticks++;+ await tick();+ };+ const before = live.listenerCount();+ const a = live.generationEventStream(new AbortController().signal, { pingMs: 60_000 }).body!.getReader();+ const b = live.generationEventStream(new AbortController().signal, { pingMs: 60_000 }).body!.getReader();+ expect(live.listenerCount()).toBe(before + 2);+ // Open streams stay open (a read that is still waiting after 300 ms).+ expect(dec.decode((await a.read()).value)).toMatch(/^retry: 2000\n/);+ const waiting = a.read();+ expect(await Promise.race([waiting.then(() => "read"), new Promise((ok) => setTimeout(() => ok("open"), 300))])).toBe("open");++ shutdown.drain();++ expect((await waiting).done).toBe(true);+ expect(await readToEnd(b, 2000)).toMatch(/^retry: 2000\n/);+ expect(live.listenerCount()).toBe(before);+ // No tick after the drain (the runner polls every 1.5 s).+ const seen = ticks;+ await new Promise((r) => setTimeout(r, 2000));+ expect(ticks).toBe(seen);+ // A runner asked for again doesn't start a second one.+ gens.ensureRunner();+ await new Promise((r) => setTimeout(r, 1700));+ expect(ticks).toBe(seen);++ // A stream opened while stopping ends at once.+ const late = live.generationEventStream(new AbortController().signal, { pingMs: 60_000 }).body!.getReader();+ expect(await readToEnd(late, 1000)).toBe("");+ expect(live.listenerCount()).toBe(before);+ expect(shutdown.draining()).toBe(true);+ });+});