// RENDER MODE from umtool (common/lib/renderPriority.mjs; AGENTS.md "Render
// mode"): a render the operator is waiting for gets the machine.
//
// umtool take
--id … --priority on for the take's lifetime: on at
// the start, off at the end, on a
// failure and on a signal
// umtool render-mode on [--for 90m] [--note …] [--json | --print-token] a window (a chain of renders)
// umtool render-mode on [--for 90m] [--note …] -- held while the command runs (holder: its
// pid; its env carries the token), off when it exits
// umtool render-mode off [--force] [--json]
// umtool render-mode status [--json]
//
// On: the state file (beside the heavy slot's lock), then the editor's
// transcription, download and Speakers lanes held through its ops — the `lane` action
// `pnpm ops lane` posts — each only if it was not held already, and recorded,
// so off releases only those. The editor is ARCHILYZER_EDITOR_URL with
// WORKER_TOKEN, read as `pnpm ops` reads them (fetchWindows.mjs editorConfig).
// With no editor to ask, render mode still holds the heavy slot's door; it
// says the lanes were not held.
//
// A take inside a manual window joins it (its render carries the window's
// token); a take with --priority while another render holds it renders
// without it, and its render waits at the door like any other heavy job.
import {
RENDER_MODE_LANES,
RENDER_MODE_REMINDER,
RENDER_PRIORITY_TOKEN_ENV,
clockOf,
describeRenderPriority,
parseDurationMs,
readRenderPriority,
reapRenderMode,
renderModeOff,
renderModeOn,
renderPriorityFile,
} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
import { REPO_ROOT } from "../paths.mjs";
import { editorConfig } from "./fetchWindows.mjs";
/** The state file, as the checkout's queue-lock finds it (not the cwd's: a CLI may run in a workspace). */
export function renderModeFile(env = process.env) {
return renderPriorityFile(env, { root: REPO_ROOT });
}
/**
* The editor's lanes over its ops: read through `GET /api/ops/settings?key=autoQueue`,
* held and released through `POST /api/ops/lane`. Null with no token to ask with.
* @param {{ url: string, token: string, fetch?: typeof fetch }} cfg
* @returns {import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderModeLanes | null}
*/
/**
* WHILE RENDER MODE GIVES THE MACHINE TO A RENDER (lane line-rerun): the sentence a read pressed now says in place of
* "running" -- its synthesis waits at the heavy slot's door until the render ends -- or null when render mode is off.
*/
export function renderWaitSentence(env = process.env, { file = renderModeFile(env) } = {}) {
try {
const s = readRenderPriority(file);
return s.held && s.state ? `waiting for the render (${describeRenderPriority(s.state)}): render mode gives it the machine, and this read is made when it ends` : null;
} catch {
return null;
}
}
export function editorLanes(cfg) {
if (!cfg?.token) return null;
const ask = async (route, body) => {
const f = cfg.fetch ?? fetch;
let res;
try {
res = await f(`${cfg.url}${route}`, {
method: body ? "POST" : "GET",
headers: { authorization: `Bearer ${cfg.token}`, ...(body ? { "content-type": "application/json" } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
cache: "no-store",
signal: AbortSignal.timeout(15_000),
});
} catch (e) {
throw new Error(`could not reach the editor at ${cfg.url}: ${e instanceof Error ? e.message : String(e)}`);
}
const j = await res.json().catch(() => ({}));
if (!res.ok || j?.ok === false) throw new Error(`the editor refused (HTTP ${res.status}): ${j?.error ?? "no reason given"}`);
return j;
};
return {
async isHeld(lane) {
const j = await ask("/api/ops/settings?key=autoQueue");
return j?.value?.[lane]?.held === true;
},
async hold(lane) {
await ask("/api/ops/lane", { lane, held: true });
},
async release(lane) {
await ask("/api/ops/lane", { lane, held: false });
},
};
}
/** The lanes line of a hold: "lanes held: transcription, download (… already held: left alone)". */
export function lanesLine(state) {
const held = state.lanesHeld?.length ? `lanes held: ${state.lanesHeld.join(", ")}` : "no lanes held";
const skipped = state.lanesSkipped?.length ? ` (${state.lanesSkipped.join(", ")} already held — left alone)` : "";
const error = state.lanesError ? ` — ${state.lanesError}` : "";
return `${held}${skipped}${error}`;
}
/**
* Hold render mode while `fn` runs, then let go — done, failed or signalled.
* The one on/off/signal path of `withTakePriority` (holder: this process) and
* `render-mode on -- ` (holder: the command's pid). Returns
* `{ran: false, held}` without calling `fn` when another hold won the claim.
*
* @template T
* @param {{ holder: import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderHolder, by: string,
* log: (s: string) => void, env?: Record, file?: string, lanes?: any,
* signals?: boolean, token?: string, forMs?: number | null, note?: string | null,
* onLine?: (state: any) => void, onSignal?: (sig: NodeJS.Signals) => void }} o
* @param {(token: string) => Promise} fn
* @returns {Promise<{ ran: true, value: T } | { ran: false, held: any }>}
*/
export async function withRenderHold(o, fn) {
const env = o.env ?? process.env;
const file = o.file ?? renderModeFile(env);
const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env));
/** @type {string | null} the claimed hold's token, once the claim is in */
let token = null;
/** @type {NodeJS.Signals | null} */
let signalled = null;
// ONE RELEASE, AWAITED BY EVERY CALLER. A second signal (Ctrl-C twice, a
// runner's TERM then its group's) used to find `ended` set, return at once
// and exit — cutting off the first caller's release of the lanes mid-way.
/** @type {Promise | null} */
let ending = null;
const end = () =>
(ending ??= (async () => {
if (token === null) return;
const t = token;
if (env[RENDER_PRIORITY_TOKEN_ENV] === t) delete env[RENDER_PRIORITY_TOKEN_ENV];
try {
const off = await renderModeOff({ file, token: t, lanes });
o.log(
`render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` +
(off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""),
);
} catch (e) {
o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`);
}
})());
// A signal ends the hold before this process goes (the job runner's Cancel
// signals the group; Ctrl-C the same). Then exit as the signal would.
//
// THE HANDLERS GO ON BEFORE THE CLAIM. The claim writes the state file and
// holds the editor's lanes over HTTP (seconds, on a loaded machine); a signal
// in that time used to take Node's default action — this process gone, its
// hold and its lanes left for the heartbeat to find. Now a signal at any
// point waits for the claim to settle, ends what it claimed, then exits;
// `fn` is never started after one.
/** @type {Promise} */
let claim = Promise.resolve(null);
/** @type {Array<[NodeJS.Signals, () => void]>} */
const handlers = [];
if (o.signals !== false) {
for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
const h = () => {
signalled ??= sig;
// The FIRST signal's code, whichever handler's exit runs.
const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[signalled] ?? 0);
try {
o.onSignal?.(sig);
} catch {
/* the child is gone already */
}
setTimeout(() => process.exit(code), 10_000).unref();
void claim
.catch(() => null)
.then(() => end())
.finally(() => process.exit(code));
};
handlers.push([sig, h]);
process.on(sig, h);
}
}
const unhook = () => {
for (const [sig, h] of handlers) process.off(sig, h);
};
claim = renderModeOn({
file,
holder: o.holder,
by: o.by,
forMs: o.forMs ?? null,
note: o.note ?? null,
editor: lanes ? editorConfig(env).url : null,
lanes,
...(o.token ? { token: o.token } : {}),
}).then((on) => {
// Set here, so a handler's continuation of the claim (chained later) sees it.
if (on.ok && on.state) token = on.state.token;
return on;
});
let on;
try {
on = await claim;
} catch (e) {
unhook();
throw e;
}
// Signalled while claiming: the handler ends the hold and exits; nothing starts.
if (signalled) return new Promise(() => {});
if (!on.ok || !on.state) {
unhook();
return { ran: false, held: on.held ?? null };
}
env[RENDER_PRIORITY_TOKEN_ENV] = /** @type {string} */ (token);
o.onLine?.(on.state);
try {
return { ran: true, value: await fn(/** @type {string} */ (token)) };
} finally {
// Unhooked only once the release is done: a signal meanwhile joins it.
await end();
unhook();
}
}
/**
* Run `fn` (a take's make) in render mode, as `umtool take … --priority` asks.
*
* --priority, render mode off on for this process (holder: its pid), off
* after `fn` — done, failed or signalled
* a manual window on joined: the render carries its token; the
* window stays on afterwards (with or without --priority)
* inside `render-mode on -- …` the chain's hold: this take carries its token already
* --priority, another render run as is; its render waits at the door
*
* The token goes into process.env, so the render queue-lock starts inherits it.
*
* @template T
* @param {{ priority: boolean, project: string, take?: string | null, cmd?: string, log: (s: string) => void,
* env?: Record, file?: string, lanes?: any, signals?: boolean }} o
* @param {() => Promise} fn
* @returns {Promise}
*/
export async function withTakePriority(o, fn) {
const env = o.env ?? process.env;
const file = o.file ?? renderModeFile(env);
const status = readRenderPriority(file);
if (status.held && status.state) {
if (!status.state.holder) {
env[RENDER_PRIORITY_TOKEN_ENV] = status.state.token;
o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take renders in it`);
return fn();
}
if (env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token) {
o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take is part of it`);
return fn();
}
if (o.priority) o.log(`render mode is held by another render (${describeRenderPriority(status.state)}) — this one waits for it`);
return fn();
}
if (!o.priority) return fn();
const cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`;
const r = await withRenderHold(
{
holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null },
by: "umtool take --priority",
log: o.log,
env,
file,
lanes: o.lanes,
signals: o.signals,
onLine: (state) => {
o.log(`render mode on for this take — ${lanesLine(state)}`);
o.log(` ${RENDER_MODE_REMINDER}`);
},
},
() => fn(),
);
if (r.ran) return r.value;
// Another hold went on between the look and the claim: render as any job.
o.log(`render mode is held by another render${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — this one waits for it`);
return fn();
}
/** Quote one argv word for a log line, as a shell would read it. */
function shellWord(w) {
return /^[\w@%+=:,./-]+$/.test(w) ? w : `'${String(w).replace(/'/g, "'\\''")}'`;
}
/**
* `umtool render-mode on [--for D] [--note T] -- `: the command runs in
* render mode and the hold ends when it does. The command is spawned with the
* hold's token in RENDER_PRIORITY_TOKEN (so every heavy job under it is the
* render), the hold's holder is the command's pid (a crash of this process
* leaves a hold that ends with the command), and the hold is released when the
* command exits — done, failed, or this process signalled (the signal is
* passed on to the command). Exits with the command's code.
*
* Inside a manual window it joins (the window's token; the window stays on);
* beside another render's hold it runs as any job and its heavy work waits.
*
* @param {string[]} cmd
* @param {{ forMs: number | null, note: string | null, printToken: boolean, log: (s: string) => void,
* err: (s: string) => void, env: Record, file: string, lanes: any,
* signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} o
* @returns {Promise}
*/
async function renderModeChain(cmd, o) {
const { spawn } = await import("node:child_process");
const { randomBytes } = await import("node:crypto");
const spawnImpl = o.spawnImpl ?? spawn;
const say = o.printToken ? o.err : o.log; // --print-token: stdout carries the token alone
const full = cmd.map(shellWord).join(" ");
const line = full.length > 160 ? `${full.slice(0, 159)}…` : full;
/** @param {string | undefined} token */
const run = (token) => {
const childEnv = { ...o.env };
if (token) childEnv[RENDER_PRIORITY_TOKEN_ENV] = token;
else delete childEnv[RENDER_PRIORITY_TOKEN_ENV];
const child = spawnImpl(cmd[0], cmd.slice(1), { stdio: "inherit", env: /** @type {NodeJS.ProcessEnv} */ (childEnv) });
const exited = new Promise((resolve) => {
child.on("error", (e) => {
o.err(`render-mode: could not run ${cmd[0]}: ${e.message}`);
resolve(127);
});
child.on("exit", (code, sig) => resolve(code ?? 128 + (sig ? ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1, SIGKILL: 9 }[sig] ?? 1) : 1)));
});
return { child, exited: /** @type {Promise} */ (exited) };
};
const status = readRenderPriority(o.file);
if (status.held && status.state) {
const joins = !status.state.holder;
say(
joins
? `render mode is on (${describeRenderPriority(status.state)}) — ${line} runs in it; the window stays on`
: `render mode is held by another render (${describeRenderPriority(status.state)}) — ${line} runs without it; its heavy work waits`,
);
if (o.printToken && joins) o.log(status.state.token);
return run(joins ? status.state.token : undefined).exited;
}
// The token is chosen before the spawn so the command carries it from its
// first instruction; the hold is claimed with the command's pid as holder.
const token = randomBytes(8).toString("hex");
if (o.printToken) o.log(token);
const { child, exited } = run(token);
if (child.pid == null) return exited; // never started ("error" says why)
const r = await withRenderHold(
{
holder: { pid: child.pid, cmd: full.slice(0, 200) },
by: "umtool render-mode on --",
token,
forMs: o.forMs,
note: o.note,
log: say,
env: { ...o.env },
file: o.file,
lanes: o.lanes,
signals: o.signals,
onLine: (state) => {
say(`render mode ON for ${line} (pid ${child.pid}) — ${lanesLine(state)}`);
say(` ${RENDER_MODE_REMINDER}`);
},
onSignal: (sig) => {
// (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.)
if (child.pid !== undefined) child.kill(sig);
},
},
() => exited,
);
if (r.ran) return r.value;
say(`render mode was taken by another render meanwhile${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — ${line} runs without it; its heavy work waits`);
return exited;
}
const USAGE = [
"usage: umtool render-mode on [--for 90m] [--note TEXT] [--json | --print-token]",
" umtool render-mode on [--for 90m] [--note TEXT] [--print-token] -- ",
" umtool render-mode off [--force] [--json]",
" umtool render-mode status [--json]",
"",
"Render mode gives a render the operator is waiting for the machine: every other heavy job",
"(e2e suites, next builds, the publish stages, other renders) waits at the heavy slot's door",
`while it is on, and the editor's ${RENDER_MODE_LANES.join(" and ")} lanes are held — only the`,
"ones not held already, and only those are released at off. `on` is a window (default 2h; --for",
"90m, 1h30m, 45 = minutes) for a chain of renders: every `umtool take` started in it renders in it;",
"another command joins with the RENDER_PRIORITY_TOKEN it prints. For one take, `umtool take …",
"--priority` turns it on for the take's lifetime instead. `off` ends it (a running take's hold",
"only with --force). A hold whose process is gone or whose window is over is no hold: its lanes",
"are released by the editor's heartbeat, /jobs, or the next `status`/`on`.",
"",
"`on -- ` is the form for a script: the command runs in render mode with the token in",
"its environment, the hold is the command's (its pid), and it ends when the command exits — done,",
"failed or signalled (a signal is passed on); the exit code is the command's. No window is left",
"behind for a script that forgot `off`. --print-token prints the token alone on stdout (the other",
"lines go to stderr), for `export RENDER_PRIORITY_TOKEN=$(umtool render-mode on --print-token)`.",
"The same from the editor: pnpm ops render-mode --json '{\"on\": true, \"for\": \"90m\"}' / get render-mode.",
].join("\n");
/**
* `umtool render-mode on|off|status`, and `on -- `.
* @param {string[]} args
* @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record, file?: string, lanes?: any,
* signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} [opts]
* @returns {Promise}
*/
export async function renderModeCommand(allArgs, { log = console.log, err = console.error, env = process.env, file, lanes, signals, spawnImpl } = {}) {
// `on … -- `: everything after the first `--` is the command.
const dash = allArgs.indexOf("--");
const args = dash >= 0 ? allArgs.slice(0, dash) : allArgs;
const cmd = dash >= 0 ? allArgs.slice(dash + 1) : null;
const valued = new Set(["--for", "--note"]);
const sub = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1]));
const flag = (n) => {
const i = args.indexOf(n);
return i >= 0 ? args[i + 1] : undefined;
};
const json = args.includes("--json");
if (args.includes("--help")) {
log(USAGE);
return 0;
}
if (!sub || !["on", "off", "status"].includes(sub)) {
err(USAGE);
return 2;
}
if (cmd && (sub !== "on" || !cmd.length)) {
err(sub === "on" ? "render-mode on --: name the command to run after --" : `render-mode ${sub} takes no command (only \`on -- \` does)`);
return 2;
}
const printToken = args.includes("--print-token");
if (printToken && json) {
err("--print-token and --json: one or the other");
return 2;
}
const where = file ?? renderModeFile(env);
const cfg = editorConfig(env);
const editor = lanes !== undefined ? lanes : editorLanes(cfg);
const out = (v) => log(JSON.stringify(v, null, 2));
if (sub === "status") {
const reaped = editor ? await reapRenderMode({ file: where, lanes: editor }).catch(() => null) : null;
const s = readRenderPriority(where);
if (json) {
out({ ok: true, held: s.held, state: s.state, stale: s.stale, reaped: reaped?.was ? reaped : null, file: where });
return 0;
}
if (reaped?.was) log(`a stale render mode was ended${reaped.released.length ? ` — lanes released: ${reaped.released.join(", ")}` : ""}`);
if (!s.held || !s.state) {
log(s.state ? `render mode is off (the last hold is stale: ${s.stale}; ${lanesLine(s.state)})` : "render mode is off");
return 0;
}
log(`render mode is ON: ${describeRenderPriority(s.state)}`);
log(` ${lanesLine(s.state)}`);
log(` ${RENDER_MODE_REMINDER}`);
return 0;
}
if (sub === "on") {
const raw = flag("--for");
const forMs = raw === undefined ? null : parseDurationMs(raw);
if (raw !== undefined && !forMs) {
err(`--for wants a duration: 90m, 2h, 1h30m, or minutes — not "${raw}"`);
return 2;
}
if (cmd) return renderModeChain(cmd, { forMs, note: flag("--note") ?? null, printToken, log, err, env, file: where, lanes: editor, signals, spawnImpl });
const r = await renderModeOn({ file: where, holder: null, forMs, note: flag("--note") ?? null, by: "umtool render-mode", editor: editor ? cfg.url : null, lanes: editor });
if (!r.ok || !r.state) {
if (json) out({ ok: false, error: "render mode is already on", held: r.held });
else err(`render mode is already on: ${r.held ? describeRenderPriority(r.held) : "?"}`);
return 1;
}
if (json) {
out({ ok: true, state: r.state, file: where, reminder: RENDER_MODE_REMINDER });
return 0;
}
if (printToken) {
log(r.state.token);
err(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}; end it: umtool render-mode off`);
return 0;
}
log(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}`);
log(` ${RENDER_MODE_REMINDER}`);
log(" every `umtool take` started now renders in it; another command joins with:");
log(` export ${RENDER_PRIORITY_TOKEN_ENV}=${r.state.token}`);
log(" end it: umtool render-mode off");
return 0;
}
// off
const s = readRenderPriority(where);
if (s.held && s.state?.holder && !args.includes("--force")) {
const msg = `render mode is held by a running render (${describeRenderPriority(s.state)}) — it ends with it; --force ends it now`;
if (json) out({ ok: false, error: msg });
else err(msg);
return 1;
}
const r = await renderModeOff({ file: where, lanes: editor });
if (json) {
out({ ok: true, was: r.was, released: r.released, failed: r.failed });
return r.failed.length ? 1 : 0;
}
if (!r.was) log("render mode was off");
else log(`render mode off${r.released.length ? ` — lanes released: ${r.released.join(", ")}` : ""}`);
if (r.failed.length) {
err(`NOT released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks`);
return 1;
}
return 0;
}