import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, 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/compressText.test.ts // // THE MIGRATION (lane text-compress, slice 2): `compress-text` over a temp // corpus — a dry run that touches nothing, a real run, its limit, its check, // the render-mode wait and the slower pace while a recording runs. const ROOT = await mkdtemp(path.join(tmpdir(), "compress-text-")); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(process.env.TRANSCRIPTS_DIR, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); test.after(() => rm(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); const { compressText, byteThrottle } = await import("./compressText"); const { readStoredText } = await import("../lib/storedText-server"); const paths = getPaths(); const CHAT = "transcript.live_chat.json"; const body = (seed: string, lines: number) => Array.from({ length: lines }, (_, i) => JSON.stringify({ replayChatItemAction: { actions: [{ text: `${seed} ${i} ${createHash("md5").update(seed + i).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }), ).join("\n") + "\n"; async function channel(slug: string, videos: Record, opts: { tiered?: boolean } = {}): Promise { const channelDir = path.join(paths.channelsDir, slug); await mkdir(path.join(channelDir, "data"), { recursive: true }); await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: `https://www.youtube.com/@${slug}` })); if (opts.tiered) await mkdir(path.join(channelDir, "media"), { recursive: true }); for (const [id, chat] of Object.entries(videos)) { const dir = path.join(channelDir, "data", id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id })); if (opts.tiered) { await mkdir(path.join(channelDir, "media", id), { recursive: true }); await writeFile(path.join(channelDir, "media", id, CHAT), chat); await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT)); } else { await writeFile(path.join(dir, CHAT), chat); } // Old enough for the quiet period. await utimes(path.join(dir, CHAT), 1_700_000_000, 1_700_000_000.5); } } async function tree(dir: string): Promise { const out: string[] = []; async function walk(d: string): Promise { for (const e of (await readdir(d).catch(() => [] as string[])).sort()) { const p = path.join(d, e); const l = await lstat(p); if (l.isSymbolicLink()) out.push(`${p} -> ${await readlink(p)} ${l.mtimeMs}`); else if (l.isDirectory()) { out.push(`${p}/ ${l.mtimeMs}`); await walk(p); } else out.push(`${p} ${l.size} ${l.mtimeMs} ${createHash("sha256").update(await readFile(p)).digest("hex")}`); } } await walk(dir); return out; } const A = { a1: body("a1", 4000), a2: body("a2", 2000) }; const B = { b1: body("b1", 3000) }; await channel("alpha", A); await channel("beta", B, { tiered: true }); test("a dry run reports bytes before and the estimate after, per channel — and touches NOTHING", async () => { const before = await tree(ROOT); const lines: string[] = []; const r = await compressText({ paths, dryRun: true, onLog: (l) => lines.push(l) }); assert.deepEqual(await tree(ROOT), before, "not one entry changed, not one mtime"); const alpha = r.channels.find((c) => c.slug === "alpha")!; assert.equal(alpha.plainFiles, 2); assert.equal(alpha.plainBytes, A.a1.length + A.a2.length); assert.equal(alpha.estimateAfterBytes, Math.round(alpha.plainBytes * 0.05)); assert.ok(typeof alpha.free?.corpus === "number"); const beta = r.channels.find((c) => c.slug === "beta")!; assert.equal(beta.plainFiles, 1, "a tier link's bytes are counted through the link"); assert.equal(beta.plainBytes, B.b1.length); assert.match(lines.join(""), /Nothing was written/); }); test("a real run with a limit compresses that many, smallest first; a re-run continues; the check passes", async () => { const waits: number[] = []; const first = await compressText({ paths, quietMs: 0, slugs: ["alpha"], limit: 1, onLog: () => {}, waitForRender: async () => (waits.push(1), 0), }); assert.equal(first.stopped, "limit"); const alpha = first.channels[0]; assert.equal(alpha.compressed, 1); // Smallest first: a2. const a2 = path.join(paths.channelsDir, "alpha", "data", "a2"); assert.deepEqual((await readdir(a2)).sort(), ["metadata.info.json", `${CHAT}.zst`]); assert.equal(await readStoredText(a2, CHAT, "utf8"), A.a2); assert.equal(waits.length, 1, "render mode was asked before the file"); const rest = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} }); assert.equal(rest.stopped, undefined); const byslug = Object.fromEntries(rest.channels.map((c) => [c.slug, c])); assert.equal(byslug.alpha.compressed, 1); assert.equal(byslug.alpha.already, 1); assert.equal(byslug.beta.compressed, 1); for (const [slug, vids] of [["alpha", A], ["beta", B]] as const) { for (const [id, chat] of Object.entries(vids)) { assert.equal(await readStoredText(path.join(paths.channelsDir, slug, "data", id), CHAT, "utf8"), chat, `${slug}/${id}`); } } const again = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} }); assert.equal(again.channels.reduce((a, c) => a + (c.compressed ?? 0), 0), 0); const check = await compressText({ paths, verify: true, slugs: ["alpha", "beta"], onLog: () => {} }); assert.deepEqual( check.channels.map((c) => [c.slug, c.verified, c.problems?.length]), [["alpha", 2, 0], ["beta", 1, 0]], ); }); test("render mode ending the wait by a cancel stops the run before any file", async () => { await channel("gamma", { g1: body("g1", 100) }); const r = await compressText({ paths, slugs: ["gamma"], onLog: () => {}, waitForRender: async () => null }); assert.equal(r.stopped, "cancelled"); assert.deepEqual((await readdir(path.join(paths.channelsDir, "gamma", "data", "g1"))).sort(), ["metadata.info.json", CHAT]); }); test("the pace: a token bucket over bytes, at whatever rate is asked each time (slower while recording)", async () => { let t = 0; const slept: number[] = []; let recording = false; const throttle = byteThrottle( () => (recording ? 8 : 40) * 1024 * 1024, async (ms) => { slept.push(Math.round(ms)); t += ms; }, () => t, ); await throttle(40 * 1024 * 1024); // the first second's worth: no wait await throttle(40 * 1024 * 1024); // the next waits a second recording = true; await throttle(8 * 1024 * 1024); // queued behind the second; 8 MB at 8 MB/s is one more second await throttle(8 * 1024 * 1024); assert.deepEqual(slept, [1000, 1000, 1000]); }); // REVIEW-1 F4(a): THE JOB VISITS EVERY DIR A STOPPED RUN LEFT, not only the // ones where the plain file opens. A kill after the original was set aside // leaves the name absent (the stored form only) beside the set-aside; a kill // inside the original's removal leaves a dangling tier link. Through the job // (compressText), each is finished: the stored form only, no leftover. const { CompressKill } = await import("../lib/storedText-write-server"); const killAt = (point: string) => (p: string) => { if (p === point) throw new CompressKill(p as never); }; const leftovers = async (slug: string, id: string) => (await readdir(path.join(paths.channelsDir, slug, "data", id))).filter((e) => e.startsWith(".")); test("the job finishes a run killed after the set-aside, and one killed inside the original's removal", async () => { await channel("delta", { d1: body("d1", 500) }); await channel("epsilon", { e1: body("e1", 500) }, { tiered: true }); // A run killed at "retired" (a dead pid). await assert.rejects( compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_997, crashAt: killAt("retired") } }), CompressKill, ); const d1 = path.join(paths.channelsDir, "delta", "data", "d1"); assert.ok(!(await readdir(d1)).includes(CHAT), "the name is absent: the stored form only"); assert.equal((await leftovers("delta", "d1")).length, 1, "the set-aside original"); // The dry run sees the dir as work (the action starts a job for it). const plan = await compressText({ paths, slugs: ["delta"], dryRun: true, onLog: () => {} }); assert.equal(plan.channels[0].pending, 1); assert.equal(plan.channels[0].plainFiles, 0); const r = await compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {} }); assert.deepEqual(await leftovers("delta", "d1"), [], "finished by the job"); assert.deepEqual((await readdir(d1)).sort(), ["metadata.info.json", `${CHAT}.zst`]); assert.equal(await readStoredText(d1, CHAT, "utf8"), body("d1", 500)); assert.ok((r.channels[0].compressed ?? 0) + (r.channels[0].already ?? 0) >= 1); // Tiered: compressed, then the plain link put back dangling (what a kill // between the bytes' removal and the link's leaves). assert.equal((await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} })).channels[0].compressed, 1); const e1 = path.join(paths.channelsDir, "epsilon", "data", "e1"); await symlink(path.join("..", "..", "media", "e1", CHAT), path.join(e1, CHAT)); const before = await compressText({ paths, slugs: ["epsilon"], dryRun: true, onLog: () => {} }); assert.equal(before.channels[0].pending, 1, "a dangling plain link is work"); await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} }); assert.deepEqual((await readdir(e1)).sort(), ["metadata.info.json", `${CHAT}.zst`], "the dangling link is gone"); assert.equal(await readStoredText(e1, CHAT, "utf8"), body("e1", 500)); }); // REVIEW-1 F4(b), through the job: this process's pid, an earlier start. test("the job treats this pid's leftovers from an earlier process start as dead: a set-aside and a temp", async () => { await channel("zeta", { z1: body("z1", 400), z2: body("z2", 400) }); await assert.rejects( compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: process.pid, token: "earlier0", crashAt: killAt("retired") } }), CompressKill, ); // z2: a partial temp of this pid from an earlier start, beside its plain file. const z2 = path.join(paths.channelsDir, "zeta", "data", "z2"); await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}-earlier0`), "partial"); await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}`), "partial, a name from before the token"); await compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {} }); for (const id of ["z1", "z2"]) { assert.deepEqual(await leftovers("zeta", id), [], id); assert.equal(await readStoredText(path.join(paths.channelsDir, "zeta", "data", id), CHAT, "utf8"), body(id, 400), id); } }); // REVIEW-1 F3, through the job: the restore. test("restore through the job: a dry run touches nothing; a restore with a limit, killed, re-run — the plain files with their times", async () => { const before: Record = {}; await channel("eta", { h1: body("h1", 300), h2: body("h2", 600) }); await channel("theta", { t1: body("t1", 300) }, { tiered: true }); for (const [slug, id] of [["eta", "h1"], ["eta", "h2"], ["theta", "t1"]]) { before[`${slug}/${id}`] = (await lstat(path.join(paths.channelsDir, slug, "data", id, CHAT))).mtimeMs; } await compressText({ paths, slugs: ["eta", "theta"], quietMs: 0, onLog: () => {} }); const tr = await tree(path.join(paths.channelsDir, "eta")); const plan = await compressText({ paths, slugs: ["eta"], restore: true, dryRun: true, onLog: () => {} }); assert.deepEqual(await tree(path.join(paths.channelsDir, "eta")), tr, "the restore's dry run touches nothing"); assert.equal(plan.channels[0].storedFiles, 2); assert.equal(plan.channels[0].estimateAfterBytes, body("h1", 300).length + body("h2", 600).length, "exact, from the headers"); assert.equal(plan.channels[0].pending, 2); const one = await compressText({ paths, slugs: ["eta"], restore: true, limit: 1, onLog: () => {} }); assert.equal(one.stopped, "limit"); assert.equal(one.channels[0].restored, 1); // A run killed mid-restore (after the plain copy is placed), then re-run. await assert.rejects( compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {}, compressOpts: { pid: 999_999_996, crashAt: killAt("restore-placed") } }), CompressKill, ); await compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {} }); for (const [slug, id, lines] of [["eta", "h1", 300], ["eta", "h2", 600], ["theta", "t1", 300]] as const) { const d = path.join(paths.channelsDir, slug, "data", id); assert.deepEqual((await readdir(d)).sort(), ["metadata.info.json", CHAT], `${slug}/${id}`); assert.equal(await readFile(path.join(d, CHAT), "utf8"), body(id, lines), `${slug}/${id}`); assert.equal((await lstat(path.join(d, CHAT))).mtimeMs, before[`${slug}/${id}`], `${slug}/${id}: the index key`); } assert.deepEqual(await readdir(path.join(paths.channelsDir, "theta", "media", "t1")), [CHAT]); }); // REVIEW-2 R1: an earlier capture a re-fetch kept is listed by the dry run as // "earlier captures kept", with its bytes — and no run touches it. test("the dry run lists earlier captures kept; neither a compress nor a restore touches one", async () => { await channel("iota", { i1: body("i1", 200) }); const d = path.join(paths.channelsDir, "iota", "data", "i1"); const keptName = "chat-capture-kept.20261121T040000Z.json.zst"; const { encodeStoredBytes } = await import("../lib/storedText-server"); const keptBytes = await encodeStoredBytes(Buffer.from(body("earlier", 300))); await writeFile(path.join(d, keptName), keptBytes); const lines: string[] = []; const plan = await compressText({ paths, slugs: ["iota"], dryRun: true, onLog: (l) => lines.push(l) }); assert.equal(plan.channels[0].keptCaptures, 1); assert.equal(plan.channels[0].keptCaptureBytes, keptBytes.length); assert.match(lines.join(""), /earlier captures kept: 1 \(/); await compressText({ paths, slugs: ["iota"], quietMs: 0, onLog: () => {} }); await compressText({ paths, slugs: ["iota"], restore: true, onLog: () => {} }); assert.deepEqual(await readFile(path.join(d, keptName)), keptBytes, "untouched"); });