// A LIVE RECORDING THE EDITOR'S RESTART INTERRUPTED RESTARTS BY ITSELF // (operator ruling, 21 Nov 2026) — the boot pass, armed by the editor's // instrumentation (editor/app/api/ops/_liveRecordingBoot.ts) below the idle // gate and never on the test server. // // Per recorded id of every channel, the NEWEST run's row is a candidate when // it is // interrupted, stopped by the shutdown (stoppedBy "shutdown"), or // recording with no job running it — the editor died under it (a crash); // it is written `interrupted`, stoppedBy "crash", first. // Never a cancelled run (a person's Cancel), a failed or a landed one. // Skipped: acknowledged; already carrying `restart` (a row restarts at most // once); last active more than LIVE_BOOT_MAX_AGE_MS ago; the setting off // (settings.liveRecording.autoRestartOnBoot). // // HOW A RESTART LOOP IS PREVENTED: // 1. The row is marked `restart: {state: "starting"}` BEFORE the job is asked // for, and a marked row is never a candidate again — an editor that dies // in the middle of this pass does not restart that row twice. // 2. At most LIVE_BOOT_MAX_RESTARTS_PER_HOUR automatic restarts of one id // (its rows carrying `resumeOf`, started in the last 60 minutes): a // crash-looping editor stops restarting after three, and the row says so // and needs a person. // 3. A part file of the id written after this process booted, or one whose // size or time changes between LIVE_BOOT_ORPHAN_LOOKS looks // LIVE_BOOT_ORPHAN_LOOK_MS apart: a recorder of the last process may still // be running (an orphan, perhaps mid-write) — never a second one beside // it, and nothing of it lands; refused, said, needs a person. // // The pass itself makes NO request. It asks for a record-live run with the // interrupted run's own url and request (`resumeOf` its startedAt); that run's // first step is record-live's one paced metadata read (the platform's pace, // the channel's cookies, as every record-live run), and it decides: // live record — a new run beside the earlier parts (slice 1's landing // keeps or removes them); the row says `restarted` // ended no recorder; whatever the earlier run left in staging lands // (`landing`), or with nothing left the row says `ended` // unknown the read failed: NOTHING is started and nothing lands — never a // recording on a guess; the row says `unknown` and needs a person // (Record again) // (controller/recordLive.ts, `resumeOf`). import path from "node:path"; import { readdir, stat } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { livePartFiles, type LiveBootRestart } from "../lib/liveCapture"; import { liveRecordingSidecar } from "../lib/mediaImport-server"; import { loadLiveRecordingRows, patchLiveRecordingRow, type LiveRecordingRow, } from "../lib/liveRecordings-server"; import { savedVideoRoot } from "../lib/savedVideo"; import { readChannelConfig } from "./channels"; export const LIVE_BOOT_MAX_RESTARTS_PER_HOUR = 3; export const LIVE_BOOT_MAX_AGE_MS = 12 * 3_600_000; // How long after boot the pass runs (an orphan recorder has written by then). export const LIVE_BOOT_DELAY_MS = 30_000; // The orphan check: this many looks at the id's part files, this far apart. export const LIVE_BOOT_ORPHAN_LOOKS = 3; export const LIVE_BOOT_ORPHAN_LOOK_MS = 20_000; export type LiveBootStart = ( slug: string, body: Record, resumeOf: string, ) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; export type LiveBootOutcome = { slug: string; id: string; startedAt: string; state: LiveBootRestart["state"]; jobId?: string; reason?: string; }; async function channelSlugs(paths: Paths): Promise { const entries = await readdir(paths.channelsDir, { withFileTypes: true }).catch(() => []); return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort(); } function lastActivityMs(r: LiveRecordingRow): number { const times = [r.startedAt, r.endedAt, ...r.parts.flatMap((p) => [p.startedAt, p.endedAt])] .filter((t): t is string => typeof t === "string") .map((t) => Date.parse(t)) .filter(Number.isFinite); return times.length ? Math.max(...times) : 0; } export async function restartInterruptedLiveRecordings(o: { paths: Paths; // When this process started: a part file written since is an orphan's. bootedAt: number; start: LiveBootStart; // A record-live job of this id runs (the registry). isRunning: (jobId: string | undefined, slug: string, id: string) => boolean; enabled?: boolean; now?: () => Date; log?: (line: string) => void; // The orphan check's looks and the wait between two (tests). orphanLooks?: number; orphanLookMs?: number; sleep?: (ms: number) => Promise; }): Promise { const now = o.now ?? (() => new Date()); const log = o.log ?? (() => {}); const out: LiveBootOutcome[] = []; for (const slug of await channelSlugs(o.paths)) { const rows = await loadLiveRecordingRows(o.paths, slug).catch(() => [] as LiveRecordingRow[]); if (!rows.length) continue; const newest = new Map(); for (const r of rows) { const cur = newest.get(r.id); if (!cur || Date.parse(r.startedAt) > Date.parse(cur.startedAt)) newest.set(r.id, r); } let names: string[] | null = null; for (const row of newest.values()) { const crashed = row.status === "recording" && !o.isRunning(row.jobId, slug, row.id); const shutdown = row.status === "interrupted" && (row.stoppedBy === "shutdown" || row.stoppedBy === "crash"); if (!crashed && !shutdown) continue; if (row.acknowledgedAt || row.restart) continue; const at = now(); const tag = `${slug}/${row.id}`; const mark = (restart: Partial & { state: LiveBootRestart["state"] }) => patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (r) => { r.restart = { ...(r.restart ?? { at: at.toISOString(), by: "boot" as const }), ...restart }; if (crashed && r.status === "recording") { r.status = "interrupted"; r.stoppedBy = "crash"; } }); const result = (state: LiveBootRestart["state"], extra: { jobId?: string; reason?: string } = {}) => { out.push({ slug, id: row.id, startedAt: row.startedAt, state, ...extra }); log(`[boot] live recording ${tag}: ${state}${extra.jobId ? ` (job ${extra.jobId})` : ""}${extra.reason ? ` — ${extra.reason}` : ""}`); }; // A crash leaves the record saying `recording`: it says interrupted now. if (crashed) { const dir = path.join(o.paths.channelsDir, slug, "data", row.id); const rec = await liveRecordingSidecar.load(dir).catch(() => null); if (rec && rec.startedAt === row.startedAt && rec.status === "recording") { await liveRecordingSidecar.write(dir, { ...rec, status: "interrupted", stoppedBy: "crash" }).catch(() => {}); } } let refusal: string | null = null; // THE AGE (REVIEW-5 B6): from the recorder's LAST WRITE — the newest // mtime of the id's part files — or the row's own times, whichever is // later; a part that is recording has no end time, and a killed editor // writes none. A row skipped for its age is marked and logged. { const config = await readChannelConfig(o.paths, slug).catch(() => null); const slugStore = path.join(savedVideoRoot(o.paths, config), slug); const listing = await readdir(slugStore).catch(() => [] as string[]); let newest = lastActivityMs(row); for (const g of livePartFiles(row.id, listing)) { for (const f of [...g.finished, ...g.streams, ...g.scratch]) { const st = await stat(path.join(slugStore, f)).catch(() => null); if (st) newest = Math.max(newest, st.mtimeMs); } } const idle = at.getTime() - newest; if (idle > LIVE_BOOT_MAX_AGE_MS) { refusal = `its recorder last wrote ${Math.round(idle / 3_600_000)} h ago (more than ${LIVE_BOOT_MAX_AGE_MS / 3_600_000} h): too old to restart automatically`; } } if (!refusal && o.enabled === false) refusal = "settings.liveRecording.autoRestartOnBoot is off"; if (!refusal) { const recent = rows.filter((r) => r.id === row.id && r.resumeOf && at.getTime() - Date.parse(r.startedAt) < 3_600_000).length; if (recent >= LIVE_BOOT_MAX_RESTARTS_PER_HOUR) { refusal = `${recent} automatic restarts of it in the last hour (at most ${LIVE_BOOT_MAX_RESTARTS_PER_HOUR}): a restart loop?`; } } if (!refusal) { const config = await readChannelConfig(o.paths, slug).catch(() => null); const slugStore = path.join(savedVideoRoot(o.paths, config), slug); const looks = Math.max(1, o.orphanLooks ?? LIVE_BOOT_ORPHAN_LOOKS); const wait = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); let before: Map | null = null; for (let look = 0; look < looks && !refusal; look++) { if (look > 0) await wait(o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS); names = await readdir(slugStore).catch(() => [] as string[]); const seen = new Map(); for (const g of livePartFiles(row.id, names)) { for (const f of [...g.finished, ...g.streams, ...g.scratch]) { const st = await stat(path.join(slugStore, f)).catch(() => null); if (!st) continue; seen.set(f, `${st.size}:${st.mtimeMs}`); if (st.mtimeMs >= o.bootedAt) { refusal = `${f} was written after this editor started: a recorder of the last process may still be running`; break; } } if (refusal) break; } if (!refusal && before) { for (const [f, v] of seen) { if (before.get(f) !== v) { refusal = `${f} changed between two looks ${Math.round((o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS) / 1000)} s apart: a recorder of the last process may still be writing it`; break; } } } before = seen; } } if (refusal) { await mark({ state: "refused", reason: refusal }); result("refused", { reason: refusal }); continue; } if (!row.url) { await mark({ state: "failed", reason: "the row names no url" }); result("failed", { reason: "the row names no url" }); continue; } // Marked first: this row is never restarted twice. await mark({ state: "starting" }); const body = { ...(row.request ?? { fromStart: row.fromStart }), slug, url: row.url }; let r: Awaited>; try { r = await o.start(slug, body, row.startedAt); } catch (err) { r = { ok: false, error: (err as Error).message }; } if (r.ok) { // The run writes what it found (restarted, landing, ended, unknown) // over this; until then the row says it was asked. const jobId = r.jobId; await patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (x) => { if (x.restart?.state !== "starting") return false; x.restart = { ...x.restart, state: "asked", jobId }; }); result("asked", { jobId: r.jobId }); } else { await mark({ state: "failed", reason: r.error }); result("failed", { reason: r.error }); } } } return out; } // What a restarted run writes on the interrupted run's row. export async function markLiveBootRestart( paths: Paths, slug: string, id: string, resumeOf: string, patch: { state: LiveBootRestart["state"]; jobId?: string; reason?: string }, now: () => Date = () => new Date(), ): Promise { await patchLiveRecordingRow(paths, slug, id, resumeOf, (r) => { r.restart = { ...(r.restart ?? { at: now().toISOString(), by: "boot" as const }), ...patch }; }); }