import { test, after } from "node:test";
import assert from "node:assert/strict";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import http from "node:http";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { TtsServerHolder, portAnswers } from "./ttsServer";
import type { TtsServerCommand } from "../lib/ttsApps";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/ttsServer.test.ts
//
// The server lifecycle against a FAKE llama-server (a node script that answers
// /health): started once for a batch, reused, stopped after the idle window
// (SIGTERM to its group), stopped at once when the start fails or is
// cancelled, SIGKILLed when it ignores SIGTERM, and never started beside
// something already answering on its port. No GPU, no model.
const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-server-"));
after(() => rm(ROOT, { recursive: true, force: true }));
// The fake: `--port
`; answers /health 200 after DELAY_MS (503 before);
// writes "started"/"term" lines to EVENTS; IGNORE_TERM ignores SIGTERM;
// EXIT_AT_ONCE exits 3 before listening.
const fake = path.join(ROOT, "fake-llama-server");
await writeFile(
fake,
`#!/usr/bin/env node
const http = require("node:http");
const fs = require("node:fs");
const args = process.argv.slice(2);
const port = Number(args[args.indexOf("--port") + 1]);
const ev = (l) => fs.appendFileSync(process.env.EVENTS, l + " " + process.pid + "\\n");
console.error("fake llama-server: loading model " + args[args.indexOf("-m") + 1]);
if (process.env.EXIT_AT_ONCE) { console.error("fake: cannot load the model"); process.exit(3); }
ev("started");
const t0 = Date.now();
http.createServer((q, r) => {
const ready = Date.now() - t0 >= Number(process.env.DELAY_MS || 0);
r.statusCode = q.url === "/health" && ready ? 200 : 503;
r.end("{}");
}).listen(port, "127.0.0.1");
process.on("SIGTERM", () => { ev("term"); if (!process.env.IGNORE_TERM) process.exit(0); });
`,
);
await chmod(fake, 0o755);
async function freePort(): Promise {
return new Promise((resolve) => {
const s = net.createServer().listen(0, "127.0.0.1", () => {
const p = (s.address() as net.AddressInfo).port;
s.close(() => resolve(p));
});
});
}
let n = 0;
async function cmd(env: Record = {}, over: Partial = {}) {
const port = await freePort();
const events = path.join(ROOT, `events-${n++}.log`);
const c: TtsServerCommand = {
bin: fake,
args: ["-m", "/models/x.gguf", "--host", "127.0.0.1", "--port", String(port)],
env: { EVENTS: events, ...env },
host: "127.0.0.1",
port,
estimateMB: 0,
startTimeoutMs: 10_000,
idleStopMs: 150,
...over,
};
return { c, events, port };
}
const events = async (f: string) => (await readFile(f, "utf8").catch(() => "")).split("\n").filter(Boolean);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function until(pred: () => Promise, ms = 5000) {
const t0 = Date.now();
while (!(await pred())) {
if (Date.now() - t0 > ms) throw new Error("timed out");
await sleep(25);
}
}
test("one server for a batch: started once, reused, stopped once the queue is idle", async () => {
const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
const { c, events: ev, port } = await cmd({ DELAY_MS: "200" });
const lines: string[] = [];
const logFile = path.join(ROOT, "server-a.log");
const a = await holder.acquire("orpheus", c, { onLog: (l) => lines.push(l), logFile });
assert.equal(a.url, `http://127.0.0.1:${port}`);
assert.equal((await fetch(`${a.url}/health`)).status, 200);
assert.match(lines[0], /Starting the orpheus server on 127\.0\.0\.1:\d+…/);
assert.match(lines[lines.length - 1], /The orpheus server is up/);
// The server's own lines go to its log, not the job's.
assert.match(await readFile(logFile, "utf8"), /fake llama-server: loading model \/models\/x\.gguf/);
a.release();
// The next synthesis arrives inside the idle window: the same server.
await sleep(50);
const b = await holder.acquire("orpheus", c, { onLog: () => {} });
assert.equal((await events(ev)).filter((l) => l.startsWith("started")).length, 1);
b.release();
b.release(); // a second release is a no-op
assert.equal(holder.running("orpheus"), true);
await until(async () => !holder.running("orpheus"));
await until(async () => !(await portAnswers("127.0.0.1", port)));
assert.deepEqual((await events(ev)).map((l) => l.split(" ")[0]), ["started", "term"]);
});
test("changed settings restart it; idleStopMs 0 stops it at once", async () => {
const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
const one = await cmd();
const a = await holder.acquire("orpheus", one.c, { onLog: () => {} });
a.release();
const two = await cmd({}, { idleStopMs: 0 });
const b = await holder.acquire("orpheus", two.c, { onLog: () => {} });
assert.deepEqual((await events(one.events)).map((l) => l.split(" ")[0]), ["started", "term"]);
b.release();
await until(async () => (await events(two.events)).length === 2);
assert.equal(holder.running("orpheus"), false);
assert.deepEqual((await events(two.events)).map((l) => l.split(" ")[0]), ["started", "term"]);
});
test("a port something else answers on is refused, never shared", async () => {
const { c, port } = await cmd();
const other = http.createServer((_q, r) => r.end("ok")).listen(port, "127.0.0.1");
await new Promise((r) => other.once("listening", r));
try {
const holder = new TtsServerHolder({ gate: null });
await assert.rejects(
holder.acquire("orpheus", c, { onLog: () => {} }),
/something already answers on 127\.0\.0\.1:\d+ — refusing to start a second orpheus server/,
);
assert.equal(holder.running("orpheus"), false);
} finally {
other.close();
}
});
test("a server that dies before it answers fails with its last words", async () => {
const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
const { c } = await cmd({ EXIT_AT_ONCE: "1" });
await assert.rejects(
holder.acquire("orpheus", c, { onLog: () => {}, logFile: path.join(ROOT, "dead.log") }),
/the orpheus server exited \(3\) before it answered — see .*dead\.log: .*cannot load the model/,
);
assert.equal(holder.running("orpheus"), false);
});
// Stopped: the fake logged its SIGTERM, or the process it logged as started is
// gone. (A fake still booting node when the SIGTERM lands dies before its handler
// exists and logs nothing — on a loaded machine the stop is real, the line is not.)
async function stopped(file: string): Promise {
const lines = await events(file);
if (lines.some((l) => l.startsWith("term"))) return true;
const pid = Number(lines.find((l) => l.startsWith("started"))?.split(" ")[1]);
if (!pid) return false;
try {
process.kill(pid, 0);
return false;
} catch {
return true;
}
}
test("a start that times out, or is cancelled, stops the server", async () => {
const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
// 1.5 s: room for the fake's node to boot and listen first, even under load.
const slow = await cmd({ DELAY_MS: "60000" }, { startTimeoutMs: 1500 });
await assert.rejects(holder.acquire("orpheus", slow.c, { onLog: () => {} }), /did not answer .*\/health within \d+s/);
await until(() => stopped(slow.events));
const ac = new AbortController();
const late = await cmd({ DELAY_MS: "60000" });
setTimeout(() => ac.abort(), 1500);
await assert.rejects(holder.acquire("orpheus", late.c, { onLog: () => {}, signal: ac.signal }), /start was cancelled/);
await until(() => stopped(late.events));
assert.equal(holder.running("orpheus"), false);
});
test("a server that ignores SIGTERM is SIGKILLed after the grace", async () => {
const holder = new TtsServerHolder({ gate: null, pollMs: 25, killGraceMs: 300 });
const { c, port } = await cmd({ IGNORE_TERM: "1" });
const a = await holder.acquire("orpheus", c, { onLog: () => {} });
a.release();
const t0 = Date.now();
await holder.stop("orpheus");
assert.ok(Date.now() - t0 >= 250, "it waited for the grace");
await until(async () => !(await portAnswers("127.0.0.1", port)));
});