import { test } from "node:test"; import assert from "node:assert/strict"; import { appendFile, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { accountStream, checkpointName, dropFragments, fragmentGaps, pruneStream, reconcileStream } from "./liveFragments-server"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveFragments-server.test.ts // // The layout is the one the installed yt-dlp leaves with --keep-fragments // (measured, LOG.md DESIGN-4): `` the appended fragments, `-Frag` // each fragment, `.ytdl` the count appended. const ROOT = await mkdtemp(path.join(tmpdir(), "live-frags-")); test.after(() => rm(ROOT, { recursive: true, force: true })); let k = 0; const frag = (n: number) => Buffer.from(``); // A stream file of fragments 1..n appended, each kept, the state at n. async function laid(n: number) { const dir = path.join(ROOT, `d${k++}`); const { mkdir } = await import("node:fs/promises"); await mkdir(dir); const name = "s.f136.mp4"; await writeFile(path.join(dir, name), ""); for (let i = 1; i <= n; i++) { await writeFile(path.join(dir, `${name}-Frag${i}`), frag(i)); await appendFile(path.join(dir, name), frag(i)); } await writeFile(path.join(dir, `${name}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: n } } })); return { dir, name, file: path.join(dir, name) }; } test("aligned: the size is the sum of fragments 1..index", async () => { const s = await laid(12); const a = await accountStream(s.dir, s.name); assert.equal(a.ok, true); assert.deepEqual(await reconcileStream(s.dir, s.name, true), { ok: true }); }); test("a stop inside the append of the next fragment (torn tail): truncated back, logged with both lengths; a whole uncounted fragment too", async () => { const s = await laid(12); const before = (await stat(s.file)).size; await writeFile(`${s.file}-Frag13`, frag(13)); await appendFile(s.file, frag(13).subarray(0, 20)); const said: string[] = []; assert.deepEqual(await reconcileStream(s.dir, s.name, false), { ok: true, truncated: { from: before + 20, to: before } }); assert.equal((await stat(s.file)).size, before + 20, "a dry run writes nothing"); const r = await reconcileStream(s.dir, s.name, true, (l) => void said.push(l)); assert.deepEqual(r, { ok: true, truncated: { from: before + 20, to: before } }); assert.equal((await stat(s.file)).size, before); assert.match(said[0]!, new RegExp(`from ${before + 20} to ${before} bytes`)); // The whole fragment appended, the state not yet rewritten. await appendFile(s.file, frag(13)); assert.equal((await reconcileStream(s.dir, s.name, true)).ok, true); assert.equal((await stat(s.file)).size, before); }); test("REFUSED: an excess that is not the start of the next fragment, and an excess with the next fragment not kept — nothing written", async () => { const s = await laid(12); const before = (await stat(s.file)).size; await writeFile(`${s.file}-Frag13`, frag(13)); await appendFile(s.file, Buffer.from("something else entirely")); const r = await reconcileStream(s.dir, s.name, true); assert.equal(r.ok, false); assert.match((r as { why: string }).why, /not the start of fragment 13/); assert.equal((await stat(s.file)).size, before + 23, "untouched"); await rm(`${s.file}-Frag13`); const r2 = await reconcileStream(s.dir, s.name, true); assert.equal(r2.ok, false); assert.match((r2 as { why: string }).why, /fragment 13 is not kept/); assert.equal((await stat(s.file)).size, before + 23, "untouched"); }); test("REFUSED: a file shorter than its fragments (a crash lost unflushed bytes), a missing fragment, no accounting at all", async () => { const s = await laid(12); const { truncate } = await import("node:fs/promises"); await truncate(s.file, (await stat(s.file)).size - 5); assert.match(((await accountStream(s.dir, s.name)) as { why: string }).why, /not in the file/); const t = await laid(12); await rm(`${t.file}-Frag5`); assert.match(((await accountStream(t.dir, t.name)) as { why: string }).why, /fragment 5 .* is not kept/); // A part of an earlier build: bytes and a state, no fragments kept. const u = await laid(3); for (const n of [1, 2, 3]) await rm(`${u.file}-Frag${n}`); assert.equal((await reconcileStream(u.dir, u.name, true)).ok, false); }); test("the prune: checkpoint written BEFORE the fragments it covers go; a crash between the two leaves the accounting whole", async () => { const s = await laid(10); // The delete dies after two fragments (a crash). let n = 0; await assert.rejects( pruneStream(s.dir, s.name, { remove: async (f) => { if (n++ === 2) throw new Error("crash"); await rm(f); }, }), ); assert.deepEqual(JSON.parse(await readFile(path.join(s.dir, checkpointName(s.name)), "utf8")), { index: 10, bytes: (await stat(s.file)).size }); assert.equal((await accountStream(s.dir, s.name)).ok, true, "the leftovers are below the checkpoint"); // More fragments, a second prune: only the checkpoint and nothing kept below it. for (const i of [11, 12]) { await writeFile(`${s.file}-Frag${i}`, frag(i)); await appendFile(s.file, frag(i)); } await writeFile(`${s.file}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: 12 } } })); assert.equal((await accountStream(s.dir, s.name)).ok, true); const p = await pruneStream(s.dir, s.name); assert.equal((p as { index: number }).index, 12); assert.deepEqual((await readdir(s.dir)).filter((x) => /-Frag/.test(x)), []); // A torn append after a prune is still repaired from the next kept fragment. await writeFile(`${s.file}-Frag13`, frag(13)); await appendFile(s.file, frag(13).subarray(0, 9)); assert.equal((await reconcileStream(s.dir, s.name, true)).ok, true); }); test("short of disk: the fragments are dropped (resumability goes, the recording does not); gaps in kept numbers are skips", async () => { const s = await laid(6); await writeFile(`${s.file}-Frag7`, frag(7)); assert.equal(await dropFragments(s.dir, s.name), 6, "up to the state's index; the one in flight stays"); assert.equal((await accountStream(s.dir, s.name)).ok, false); assert.deepEqual(fragmentGaps([3, 4, 7, 8, 10], 3), [5, 6, 9]); }); test("REVIEW-6 6: an EMPTY kept fragment is no proof, and the file must END with its last fragment's bytes", async () => { const s = await laid(4); await writeFile(`${s.file}-Frag3`, ""); assert.match(((await accountStream(s.dir, s.name)) as { why: string }).why, /fragment 3 .* is empty/); const t = await laid(4); // Same sizes, other bytes at the end: not the fragments. const { open } = await import("node:fs/promises"); const fh = await open(t.file, "r+"); await fh.write(Buffer.from("XX"), 0, 2, (await stat(t.file)).size - 2); await fh.close(); assert.match(((await accountStream(t.dir, t.name)) as { why: string }).why, /does not end with its fragment 4/); }); test("REVIEW-6 11: with the state unreadable (caught mid-rewrite), nothing is dropped", async () => { const s = await laid(5); await writeFile(`${s.file}.ytdl`, "{ half"); assert.equal(await dropFragments(s.dir, s.name), 0); assert.equal((await readdir(s.dir)).filter((x) => /-Frag/.test(x)).length, 5); }); test("REVIEW-6 2/3: the fragments past the state go before a resume; a stream file equals its fragments byte for byte, or not", async () => { const { dropFragmentsAbove, streamEqualsFragments } = await import("./liveFragments-server"); const s = await laid(6); await writeFile(`${s.file}-Frag7`, frag(7)); assert.deepEqual(await dropFragmentsAbove(s.dir, s.name, 6), [7]); assert.deepEqual(await streamEqualsFragments(s.dir, s.name), { ok: true, fragments: 6 }); await writeFile(`${s.file}-Frag2`, Buffer.from(frag(2).toString().replace("2", "9"))); assert.match(((await streamEqualsFragments(s.dir, s.name)) as { why: string }).why, /not fragment 2/); });