// THE SERVER A `runtime: "server"` SPEECH ENGINE RUNS ON (release 25 T1b: // Orpheus 3B on llama.cpp's server, on the GPU). // // One holder per engine, process-wide. The first synthesis on the `tts` queue // starts the server and waits for `GET /health`; the next ones reuse it; once // the last one has released it and `idleStopMs` passes with no other taking it // — the queue has gone idle — it is stopped: SIGTERM to its process group, // SIGKILL after 15 s. That is what frees its VRAM (4–5 GB for Orpheus), so it // is also done on every way out: a failed start, a cancelled job, the editor // exiting. // // BEHIND THE HEAVY SLOT. The server is started through scripts/queue-lock.mjs // --heavy --estimate (the gate `pnpm heavy`, e2e and the publish builds // share), so it waits for the machine's memory floor and never starts beside a // build; the gate's own lines ("waiting for the heavy slot — held by …") go to // the job's log, the server's to `/server.log`. The start timeout // counts from the server's first line of output, not from the wait. A checkout // without the gate (a test's temp root) starts the server directly; HEAVY=0 // bypasses the gate. // // NEVER SHARED: a port something else already answers on is refused, not // used — a server this holder did not start may be another session's, with // another model. import { spawn, type ChildProcess } from "node:child_process"; import { createWriteStream, existsSync, type WriteStream } from "node:fs"; import net from "node:net"; import path from "node:path"; import type { TtsServerCommand } from "../lib/ttsApps"; import "../lib/childKillGuard"; export type TtsServerHandle = { url: string; release: () => void }; export type TtsServerDeps = { // scripts/queue-lock.mjs, or null to start the server directly. gate?: string | null; killGraceMs?: number; pollMs?: number; }; type Entry = { sig: string; child: ChildProcess; url: string; users: number; timer: ReturnType | null; ready: Promise; exited: Promise; isExited: () => boolean; log: WriteStream | null; }; const GATE_LINE = /^(queue-lock:|heavy:|\s+\(heavy jobs)/; /** True when something accepts a TCP connection on host:port. */ export function portAnswers(host: string, port: number, timeoutMs = 1000): Promise { return new Promise((resolve) => { const sock = net.connect({ host, port }); const done = (v: boolean) => { sock.destroy(); resolve(v); }; sock.setTimeout(timeoutMs, () => done(false)); sock.once("connect", () => done(true)); sock.once("error", () => done(false)); }); } async function healthy(url: string): Promise { try { const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(1000) }); return res.status === 200; } catch { return false; } } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); function killGroup(child: ChildProcess, sig: NodeJS.Signals): void { if (child.pid === undefined) return; try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* gone */ } } } export class TtsServerHolder { private entries = new Map(); private exitHooked = false; constructor(private deps: TtsServerDeps = {}) {} /** Whether the server for `key` is running (started, not yet stopped). */ running(key: string): boolean { const e = this.entries.get(key); return e !== undefined && !e.isExited(); } /** The server for `key`: the running one, or a new one started from `cmd`. */ async acquire( key: string, cmd: TtsServerCommand, opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string }, ): Promise { const sig = JSON.stringify(cmd); let e = this.entries.get(key); if (e && (e.sig !== sig || e.isExited())) { // Its settings changed, or it died between syntheses: start afresh. if (e.users === 0) await this.stop(key); else throw new Error(`the ${key} server is in use with other settings`); e = undefined; } if (e) { if (e.timer) clearTimeout(e.timer); e.timer = null; e.users++; try { await e.ready; } catch (err) { e.users--; throw err; } return this.handle(key, e, cmd); } e = await this.start(key, cmd, sig, opts); e.users = 1; try { await e.ready; } catch (err) { await this.stop(key); throw err; } return this.handle(key, e, cmd); } private handle(key: string, e: Entry, cmd: TtsServerCommand): TtsServerHandle { let released = false; return { url: e.url, release: () => { if (released) return; released = true; e.users = Math.max(0, e.users - 1); if (e.users > 0 || this.entries.get(key) !== e) return; if (cmd.idleStopMs <= 0) { void this.stop(key); return; } e.timer = setTimeout(() => void this.stop(key), cmd.idleStopMs); e.timer.unref?.(); }, }; } private async start( key: string, cmd: TtsServerCommand, sig: string, opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string }, ): Promise { const url = `http://${cmd.host}:${cmd.port}`; if (await portAnswers(cmd.host, cmd.port)) { throw new Error( `something already answers on ${cmd.host}:${cmd.port} — refusing to start a second ${key} server ` + `beside it; stop it, or set another port (settings.tts.${key}.port)`, ); } const gate = this.deps.gate ?? null; const gated = gate !== null && existsSync(gate); const [bin, args] = gated ? [ process.execPath, [gate, "--heavy", ...(cmd.estimateMB > 0 ? ["--estimate", String(cmd.estimateMB)] : []), "--", cmd.bin, ...cmd.args], ] : [cmd.bin, cmd.args]; opts.onLog(`Starting the ${key} server on ${cmd.host}:${cmd.port}${gated ? " (behind the heavy slot)" : ""}…`); const child = spawn(bin, args, { env: { ...process.env, ...cmd.env }, // Its own process group: the gate, the server and anything they start // are stopped together. detached: true, stdio: ["ignore", "pipe", "pipe"], }); const log = opts.logFile ? createWriteStream(opts.logFile, { flags: "a" }) : null; log?.on("error", () => {}); let serverSince: number | null = null; let tail: string[] = []; let exitedFlag = false; let exitCode: string | null = null; const exited = new Promise((resolve) => { child.once("exit", (code, signal) => { exitedFlag = true; exitCode = code === null ? String(signal) : String(code); resolve(); }); child.once("error", (err) => { exitedFlag = true; exitCode = err.message; resolve(); }); }); const onData = (buf: Buffer) => { for (const line of buf.toString("utf8").split("\n")) { if (!line.trim()) continue; if (GATE_LINE.test(line)) { opts.onLog(line.trimEnd()); continue; } serverSince ??= Date.now(); tail = [...tail.slice(-4), line.trimEnd()]; log?.write(`${line}\n`); } }; child.stdout?.on("data", onData); child.stderr?.on("data", onData); this.hookExit(); const pollMs = this.deps.pollMs ?? 250; const started = Date.now(); const ready = (async () => { for (;;) { if (exitedFlag) { throw new Error( `the ${key} server exited (${exitCode}) before it answered${opts.logFile ? ` — see ${opts.logFile}` : ""}` + (tail.length ? `: ${tail.slice(-2).join(" | ")}` : ""), ); } if (opts.signal?.aborted) throw new Error(`the ${key} server's start was cancelled`); if (serverSince !== null && Date.now() - serverSince > cmd.startTimeoutMs) { throw new Error(`the ${key} server did not answer ${url}/health within ${Math.round(cmd.startTimeoutMs / 1000)}s`); } if (await healthy(url)) { opts.onLog(`The ${key} server is up (${((Date.now() - started) / 1000).toFixed(1)}s)`); return; } await sleep(pollMs); } })(); ready.catch(() => {}); const entry: Entry = { sig, child, url, users: 0, timer: null, ready, exited, isExited: () => exitedFlag, log, }; this.entries.set(key, entry); return entry; } /** Stop the server for `key`: SIGTERM to its group, SIGKILL after the grace. */ async stop(key: string): Promise { const e = this.entries.get(key); if (!e) return; this.entries.delete(key); if (e.timer) clearTimeout(e.timer); if (!e.isExited()) { killGroup(e.child, "SIGTERM"); const grace = this.deps.killGraceMs ?? 15_000; let timer: ReturnType | undefined; const t = new Promise<"timeout">((r) => { timer = setTimeout(() => r("timeout"), grace); }); const won = await Promise.race([e.exited.then(() => "exited" as const), t]); clearTimeout(timer); if (won === "timeout") { killGroup(e.child, "SIGKILL"); await e.exited; } } e.log?.end(); } async stopAll(): Promise { await Promise.all([...this.entries.keys()].map((k) => this.stop(k))); } // The editor exiting stops every server it started (synchronously: an exit // handler cannot wait), so no VRAM is left held by an orphan. private hookExit(): void { if (this.exitHooked) return; this.exitHooked = true; process.once("exit", () => { for (const e of this.entries.values()) if (!e.isExited()) killGroup(e.child, "SIGTERM"); }); } } declare global { // eslint-disable-next-line no-var var __yttTtsServers__: TtsServerHolder | undefined; } /** The process-wide holder; its gate is `/scripts/queue-lock.mjs`. */ export function getTtsServerHolder(monorepoRoot: string): TtsServerHolder { if (!globalThis.__yttTtsServers__) { globalThis.__yttTtsServers__ = new TtsServerHolder({ gate: path.join(monorepoRoot, "scripts", "queue-lock.mjs"), }); } return globalThis.__yttTtsServers__; }