import { test } from "node:test"; import assert from "node:assert/strict"; import { appendFile, mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveRecordingBoot.test.ts // // The boot pass that restarts live recordings an editor restart interrupted // (controller/liveRecordingBoot.ts), over a temp corpus: the rows written // through lib/liveRecordings-server.ts, the job start a stub that records // what it was asked. No request is made by the pass. const ROOT = await mkdtemp(path.join(tmpdir(), "live-boot-")); const CORPUS = path.join(ROOT, "transcripts"); process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(CORPUS, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); const { getPaths } = await import("../lib/paths"); const { restartInterruptedLiveRecordings, LIVE_BOOT_MAX_RESTARTS_PER_HOUR } = await import("./liveRecordingBoot"); const { upsertLiveRecordingRow, loadLiveRecordingRows, rowNeedsAttention } = await import("../lib/liveRecordings-server"); const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-boot"; await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Synth" })); const store = path.join(paths.savedVideosDir, SLUG); await mkdir(store, { recursive: true }); const NOW = new Date("2026-11-21T12:00:00.000Z"); const BOOTED = NOW.getTime() - 30_000; const ago = (min: number) => new Date(NOW.getTime() - min * 60_000).toISOString(); type RowIn = Parameters[2]; const row = (id: string, startedAt: string, extra: Partial = {}): RowIn => ({ id, url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", startedAt, status: "interrupted", stoppedBy: "shutdown", endedAt: startedAt, fromStart: true, attempts: 1, mustKeep: true, parts: [], request: { fromStart: true, doNotClean: true, note: "keep", transcribe: true }, ...extra, }); function starter() { const asked: { slug: string; body: Record; resumeOf: string }[] = []; return { asked, start: async (slug: string, body: Record, resumeOf: string) => { asked.push({ slug, body, resumeOf }); return { ok: true as const, jobId: `boot-${asked.length}` }; }, }; } const pass = (start: import("./liveRecordingBoot").LiveBootStart, extra: Partial[0]> = {}) => restartInterruptedLiveRecordings({ paths, bootedAt: BOOTED, start, isRunning: (jobId) => jobId === "job-running", now: () => NOW, // The orphan check's looks pass at once unless a case says otherwise. sleep: async () => {}, ...extra, }); const rowsOf = async (id: string) => (await loadLiveRecordingRows(paths, SLUG)).filter((r) => r.id === id); test("only a shutdown's or a crash's interruption restarts — never a cancel, an acknowledged one, an old one, one with a job, one restarted already, nor an older run", async () => { await upsertLiveRecordingRow(paths, SLUG, row("exbootshut1", ago(90))); // A crash: the row and the record still say recording, no job runs it. const crashAt = ago(60); await upsertLiveRecordingRow(paths, SLUG, row("exbootcrsh1", crashAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead" })); const dir = path.join(CORPUS, "channels", SLUG, "data", "exbootcrsh1"); await mkdir(dir, { recursive: true }); await liveRecordingSidecar.write(dir, { status: "recording", url: "u", platform: "youtube", fromStart: true, startedAt: crashAt, parts: [] }); await upsertLiveRecordingRow(paths, SLUG, row("exbootcanc1", ago(30), { status: "cancelled", stoppedBy: "operator" })); await upsertLiveRecordingRow(paths, SLUG, row("exbootackd1", ago(30))); const { acknowledgeLiveRecordingRows } = await import("../lib/liveRecordings-server"); await acknowledgeLiveRecordingRows(paths, SLUG, "exbootackd1", { by: "test" }); await upsertLiveRecordingRow(paths, SLUG, row("exbootold01", ago(13 * 60))); await upsertLiveRecordingRow(paths, SLUG, row("exbootrun01", ago(10), { status: "recording", stoppedBy: undefined, jobId: "job-running" })); await upsertLiveRecordingRow(paths, SLUG, row("exbootdone1", ago(20), { restart: { at: ago(19), by: "boot", state: "asked", jobId: "x" } })); await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(50))); await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(40), { status: "landed", stoppedBy: undefined })); const s = starter(); const out = await pass(s.start); assert.deepEqual(s.asked.map((a) => a.body.url).sort(), [ "https://www.youtube.com/watch?v=exbootcrsh1", "https://www.youtube.com/watch?v=exbootshut1", ]); const shut = s.asked.find((a) => a.body.url === "https://www.youtube.com/watch?v=exbootshut1")!; assert.equal(shut.resumeOf, ago(90)); assert.deepEqual(shut.body, { fromStart: true, doNotClean: true, note: "keep", transcribe: true, slug: SLUG, url: "https://www.youtube.com/watch?v=exbootshut1" }); assert.equal(out.filter((o) => o.state === "asked").length, 2); const crash = (await rowsOf("exbootcrsh1"))[0]!; assert.equal(crash.status, "interrupted"); assert.equal(crash.stoppedBy, "crash"); assert.equal(crash.restart?.state, "asked"); assert.equal((await liveRecordingSidecar.load(dir))?.status, "interrupted", "the crashed record says so too"); // HOW A LOOP IS PREVENTED (1): a second boot asks for nothing again. const again = starter(); await pass(again.start); assert.deepEqual(again.asked, []); }); test("a restart loop is refused: three automatic restarts of an id in the last hour, then no more, said and needing a person", async () => { const id = "exbootloop1"; for (let i = 0; i < LIVE_BOOT_MAX_RESTARTS_PER_HOUR; i++) { await upsertLiveRecordingRow(paths, SLUG, row(id, ago(50 - i * 10), { resumeOf: ago(55 - i * 10), restart: { at: ago(49 - i * 10), by: "boot", state: "restarted" } })); } await upsertLiveRecordingRow(paths, SLUG, row(id, ago(5), { resumeOf: ago(10) })); const s = starter(); await pass(s.start); assert.equal(s.asked.filter((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`).length, 0); const newest = (await rowsOf(id)).find((r) => r.startedAt === ago(5))!; assert.equal(newest.restart?.state, "refused"); assert.match(newest.restart?.reason ?? "", /restart loop/); assert.equal(rowNeedsAttention(newest), true); }); test("a part written after this boot began is a recorder of the last process still running: refused, never a second recorder", async () => { const id = "exbootorph1"; const startedAt = ago(30); await upsertLiveRecordingRow(paths, SLUG, row(id, startedAt)); const f = path.join(store, `.${id}.live-2026-11-21T11-30-00-000Z.ytdlp.mp4`); await writeFile(f, "growing"); await utimes(f, new Date(BOOTED + 5_000), new Date(BOOTED + 5_000)); const s = starter(); await pass(s.start); assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0); const r = (await rowsOf(id))[0]!; assert.equal(r.restart?.state, "refused"); assert.match(r.restart?.reason ?? "", /may still be running/); // Written before the boot: an ordinary leftover, restarted. await utimes(f, new Date(BOOTED - 60_000), new Date(BOOTED - 60_000)); await upsertLiveRecordingRow(paths, SLUG, row(id, ago(20))); const s2 = starter(); await pass(s2.start); assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(id)).length, 1); }); test("a start that fails is said on the row and not tried again; the setting off refuses", async () => { const id = "exbootfail1"; await upsertLiveRecordingRow(paths, SLUG, row(id, ago(15))); await pass(async () => ({ ok: false as const, error: "This stream is already being recorded (job j1)" })); const r = (await rowsOf(id))[0]!; assert.equal(r.restart?.state, "failed"); assert.match(r.restart?.reason ?? "", /already being recorded/); const s = starter(); await pass(s.start); assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0); const off = "exbootoff01"; await upsertLiveRecordingRow(paths, SLUG, row(off, ago(15))); const s2 = starter(); await pass(s2.start, { enabled: false }); assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(off)).length, 0); assert.equal((await rowsOf(off))[0]!.restart?.state, "refused"); }); test("REVIEW 1.8 (live-guard-2): the orphan check looks more than once — a part whose size changes between looks (its time kept old) is refused", async () => { const id = "exbootorph2"; await upsertLiveRecordingRow(paths, SLUG, row(id, ago(25))); const f = path.join(store, `.${id}.live-2026-11-21T11-35-00-000Z.ytdlp.mp4`); await writeFile(f, "first bytes"); const old = new Date(BOOTED - 120_000); await utimes(f, old, old); const s = starter(); let looks = 0; await pass(s.start, { orphanLooks: 3, // Between two looks, the last process's recorder appends (and the file's // time is set back, as a coarse clock or a copy would leave it). sleep: async () => { looks++; await appendFile(f, " more"); await utimes(f, old, old); }, }); assert.equal(looks, 1, "it looked again, and the change refused it at once"); assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0); const r = (await rowsOf(id))[0]!; assert.equal(r.restart?.state, "refused"); assert.match(r.restart?.reason ?? "", /changed between two looks/); }); test("REVIEW-5 B6: the age is the recorder's LAST WRITE — a 14-hour part written a minute before the crash restarts; one idle for 13 h is refused, marked and logged", async () => { // A crash 14 h into a stream: one from-start part since hour 0, no end time. const id = "exbootlong1"; const startedAt = ago(14 * 60); await upsertLiveRecordingRow( paths, SLUG, row(id, startedAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead", parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt, stem: `.${id}.live-x.ytdlp` }] }), ); const f = path.join(store, `.${id}.live-x.ytdlp.f136.mp4`); await writeFile(f, "bytes"); const last = new Date(NOW.getTime() - 60_000); await utimes(f, last, last); // Idle for 13 h: its files last written then. const old = "exbootidle1"; await upsertLiveRecordingRow(paths, SLUG, row(old, ago(14 * 60))); const g = path.join(store, `.${old}.live-y.ytdlp.f136.mp4`); await writeFile(g, "bytes"); const then = new Date(NOW.getTime() - 13 * 3_600_000); await utimes(g, then, then); const s = starter(); const lines: string[] = []; await pass(s.start, { log: (l) => void lines.push(l) }); assert.ok(s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`), "restarted: its recorder wrote a minute ago"); assert.ok(!s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${old}`)); const r = (await rowsOf(old))[0]!; assert.equal(r.restart?.state, "refused"); assert.match(r.restart?.reason ?? "", /last wrote 13 h ago/); assert.ok(lines.some((l) => l.includes(old) && /refused/.test(l)), "logged"); });