import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { HOLD_PAUSE_MS, MAX_HOLDS, MAX_REARMS, armCleanRetriesAtBoot, cancelCleanRetries, cleanRetriesFile, finishCleanRetry, readCleanRetries, resetCleanRetryTimers, scheduleCleanRetry, startCleanRetry, type CleanRetryDeps, type ScheduledCleanRetry, } from "./cleanRetrySchedule"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanRetrySchedule.test.ts // // A RATE-LIMITED CLEAN'S RETRY WAITS OFF THE QUEUE (lane clean-unverified, // rulings 4 and 5): a durable record and a timer; nothing is queued until its // not-before time; a restart re-arms it with its attempt and time; Cancel // reaches it. A fake clock and a fake timer table: no real wait. const T0 = Date.parse("2026-11-21T03:00:00.000Z"); const MIN = 60_000; let n = 0; async function jobsDir(): Promise> { return { jobsDir: path.join(await mkdtemp(path.join(tmpdir(), "clean-retry-")), `j${n++}`) }; } // A fake "process": a clock, a timer table, and recorders for what it queues // and cancels. `restart()` is a new process: every timer is gone. function fakeProcess(start = T0) { let now = start; let seq = 0; const pending = new Map Promise }>(); const enqueued: ScheduledCleanRetry[] = []; const cancelledJobs: string[] = []; let cooldown = 0; let hold: string | null = null; let refuse: string | null = null; const deps: CleanRetryDeps = { now: () => now, setTimer: (fn, ms) => { const id = ++seq; pending.set(id, { at: now + ms, fn }); return id; }, clearTimer: (h) => void pending.delete(h as number), cooldownRemainingMs: async () => cooldown, enqueue: async (e) => { if (refuse) return { ok: false, error: refuse }; enqueued.push({ ...e }); return { ok: true, jobId: `job-${enqueued.length}` }; }, mediaHold: async () => hold, cancelJob: (id) => (cancelledJobs.push(id), true), }; return { deps, enqueued, cancelledJobs, pending, setCooldown: (ms: number) => void (cooldown = ms), setHold: (why: string | null) => void (hold = why), setRefuse: (why: string | null) => void (refuse = why), // Advance the clock, firing due timers (and letting their async work run). async advance(ms: number) { now += ms; for (;;) { const due = [...pending.entries()].filter(([, t]) => t.at <= now).sort((a, b) => a[1].at - b[1].at); if (due.length === 0) break; for (const [id, t] of due) { pending.delete(id); await t.fn(); } } }, restart() { resetCleanRetryTimers({ clearTimer: (h) => void pending.delete(h as number) }); pending.clear(); }, }; } const REQ = { slug: "ch", attempt: 1, of: "J0", deferredJobId: "J0", platform: "rumble", notBefore: T0 + 15 * MIN }; test("a scheduled retry holds nothing while it waits: no job until its not-before, then exactly one", async () => { const p = await jobsDir(); const proc = fakeProcess(); const entry = await scheduleCleanRetry(p, REQ, proc.deps); assert.equal(entry.id, "J0.retry1"); assert.equal(entry.state, "scheduled"); // Durable: on disk, with its attempt and time. const onDisk = JSON.parse(await readFile(cleanRetriesFile(p), "utf8")); assert.deepEqual( onDisk.retries.map((e: ScheduledCleanRetry) => [e.id, e.attempt, e.notBefore, e.state]), [["J0.retry1", 1, T0 + 15 * MIN, "scheduled"]], ); await proc.advance(15 * MIN - 1000); assert.equal(proc.enqueued.length, 0, "nothing queued a second before its time"); await proc.advance(1000); assert.equal(proc.enqueued.length, 1); assert.equal(proc.enqueued[0].attempt, 1); const [after] = await readCleanRetries(p); assert.equal(after.state, "enqueued"); assert.equal(after.jobId, "job-1"); proc.restart(); }); test("a cooldown still running when the timer fires moves it to the cooldown's end, a bounded number of times", async () => { const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); proc.setCooldown(10 * MIN); await proc.advance(15 * MIN); assert.equal(proc.enqueued.length, 0, "not queued inside the cooldown"); const [moved] = await readCleanRetries(p); assert.equal(moved.notBefore, T0 + 25 * MIN); assert.equal(moved.rearms, 1); // A cooldown that never ends is waited out MAX_REARMS times, then the retry // is queued and meets it (judged a rate limit again). for (let i = 0; i < MAX_REARMS; i++) await proc.advance(10 * MIN); assert.equal(proc.enqueued.length, 1); proc.restart(); }); test("restart: the record survives, keeps its attempt and time, and is never queued early", async () => { const p = await jobsDir(); const first = fakeProcess(); await scheduleCleanRetry(p, { ...REQ, attempt: 2 }, first.deps); await first.advance(5 * MIN); first.restart(); // the server goes down; its timer is gone const second = fakeProcess(T0 + 6 * MIN); const boot = await armCleanRetriesAtBoot(p, second.deps); assert.deepEqual(boot.armed, ["J0.retry2"]); await second.advance(8 * MIN); // T0 + 14 min assert.equal(second.enqueued.length, 0, "still before its not-before"); await second.advance(1 * MIN); // T0 + 15 min assert.equal(second.enqueued.length, 1); assert.equal(second.enqueued[0].attempt, 2, "the attempt count survived the restart"); second.restart(); }); test("restart: a retry caught queued is queued again by its schedule; one caught running is re-armed once, then dropped", async () => { const p = await jobsDir(); const a = fakeProcess(); await scheduleCleanRetry(p, REQ, a.deps); await a.advance(15 * MIN); assert.equal((await readCleanRetries(p))[0].state, "enqueued"); a.restart(); // Caught queued: the boot pass closes the stale meta; the schedule re-queues. const b = fakeProcess(T0 + 20 * MIN); await armCleanRetriesAtBoot(p, b.deps); await b.advance(0); assert.equal(b.enqueued.length, 1); assert.equal(b.enqueued[0].attempt, 1); // Caught running, twice: re-armed the first time, dropped the second. assert.ok(await startCleanRetry(p, "J0.retry1", "job-1")); b.restart(); const c = fakeProcess(T0 + 30 * MIN); const boot1 = await armCleanRetriesAtBoot(p, c.deps); assert.deepEqual(boot1, { armed: ["J0.retry1"], dropped: [] }); await c.advance(0); assert.ok(await startCleanRetry(p, "J0.retry1", "job-2")); c.restart(); const d = fakeProcess(T0 + 40 * MIN); const boot2 = await armCleanRetriesAtBoot(p, d.deps); assert.deepEqual(boot2, { armed: [], dropped: ["J0.retry1"] }); assert.deepEqual(await readCleanRetries(p), []); d.restart(); }); test("cancel by the deferred job's id removes the record and its timer; nothing is queued, and a late start is refused", async () => { const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); assert.equal(proc.pending.size, 1); const removed = await cancelCleanRetries(p, { id: "J0" }, proc.deps); assert.deepEqual(removed.map((e) => e.id), ["J0.retry1"]); assert.equal(proc.pending.size, 0, "its timer is cleared"); await proc.advance(60 * MIN); assert.equal(proc.enqueued.length, 0); assert.equal(await startCleanRetry(p, "J0.retry1", "job-x"), null, "a job whose record is gone does not run"); }); test("cancel of a retry the schedule already queued cancels its job too", async () => { const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); await proc.advance(15 * MIN); await cancelCleanRetries(p, { slug: "ch" }, proc.deps); assert.deepEqual(proc.cancelledJobs, ["job-1"]); assert.deepEqual(await readCleanRetries(p), []); }); test("one retry per channel: a new one supersedes the old; another channel's is untouched; finish removes it", async () => { const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); await scheduleCleanRetry(p, { ...REQ, slug: "other", of: "J5", deferredJobId: "J5" }, proc.deps); await scheduleCleanRetry(p, { ...REQ, of: "J9", deferredJobId: "J9" }, proc.deps); assert.deepEqual((await readCleanRetries(p)).map((e) => e.id).sort(), ["J5.retry1", "J9.retry1"]); assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug).sort(), ["ch", "other"]); await finishCleanRetry(p, "J9.retry1"); assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug), ["other"]); proc.restart(); }); test("review 2 F3: a relocation or an absent drive when its time comes DEFERS the retry, same attempt — never a silent drop", async () => { const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); proc.setHold('Channel "ch" media is in transition: a media relocation (out) is in progress'); await proc.advance(15 * MIN); assert.equal(proc.enqueued.length, 0, "not queued while held"); const [held] = await readCleanRetries(p); assert.equal(held.attempt, 1, "the same attempt"); assert.equal(held.holds, 1); assert.match(held.heldReason ?? "", /in transition/); assert.equal(held.notBefore, T0 + 15 * MIN + HOLD_PAUSE_MS); // A refused enqueue (the job's own media guard) holds it the same way. proc.setHold(null); proc.setRefuse("media unreachable"); await proc.advance(HOLD_PAUSE_MS); assert.equal((await readCleanRetries(p))[0].holds, 2); // The media is back: queued, with the same attempt; the reason is cleared. proc.setRefuse(null); await proc.advance(HOLD_PAUSE_MS); assert.equal(proc.enqueued.length, 1); assert.equal(proc.enqueued[0].attempt, 1); assert.equal((await readCleanRetries(p))[0].heldReason, undefined); proc.restart(); }); test("review 2 F3: held for 24 h it gives up VISIBLY — the record stays, says why, is not re-armed at boot, and Cancel dismisses it", async () => { assert.equal(MAX_HOLDS * HOLD_PAUSE_MS, 24 * 60 * MIN); const p = await jobsDir(); const proc = fakeProcess(); await scheduleCleanRetry(p, REQ, proc.deps); proc.setHold("the drive is not mounted"); await proc.advance(15 * MIN); for (let i = 1; i < MAX_HOLDS; i++) await proc.advance(HOLD_PAUSE_MS); assert.equal(proc.enqueued.length, 0); const [gone] = await readCleanRetries(p); assert.ok(gone, "kept, not dropped"); assert.match(gone.gaveUp ?? "", /^Gave up after 96 tries over 24 h: the drive is not mounted/); assert.equal(proc.pending.size, 0, "no timer"); proc.restart(); const next = fakeProcess(T0 + 48 * 60 * MIN); const boot = await armCleanRetriesAtBoot(p, next.deps); assert.deepEqual(boot.armed, []); assert.equal((await readCleanRetries(p)).length, 1, "still there for the Cleanup stage"); await cancelCleanRetries(p, { slug: "ch" }, next.deps); assert.deepEqual(await readCleanRetries(p), []); });