import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { lstat, lutimes, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, 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 lib/storedText.restore.test.ts // // THE RESTORE (REVIEW-1 F3): a stored chat put back into its plain form, the // compressor in reverse — the rollback an older checkout needs. Every case is a // temp channel tree, real files and tier links. Kill points are the `crashAt` // seam (it throws and nothing after it runs, as a SIGKILL). After each: ONE // WHOLE COPY is always readable, and the next run finishes with the plain form // only, the same bytes and the same times (an `lstat` and a `stat` of the // name answer what they did before the file was ever compressed). const ROOT = await mkdtemp(path.join(tmpdir(), "stored-restore-")); test.after(() => rm(ROOT, { recursive: true, force: true })); const { compressStoredText, restoreStoredText, CompressKill } = await import("./storedText-write-server"); const { readStoredText, readdirLogical } = await import("./storedText-server"); const CHAT = "transcript.live_chat.json"; const ZST = `${CHAT}.zst`; const DEAD = 999_999_998; const KILLS = ["restoring", "restore-written", "restore-verified", "restore-placed", "restore-linked"] as const; const ORIGINAL = Array.from({ length: 9_000 }, (_, i) => JSON.stringify({ replayChatItemAction: { actions: [{ text: `m${i} ${createHash("md5").update(String(i)).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }), ).join("\n") + "\n"; let n = 0; type F = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; lstatMs: number; statMs: number }; // A compressed chat, as the compressor leaves it (real or tiered), and the // times the plain name answered before. async function compressed(tiered: boolean): Promise { const slug = `r${++n}`; const channelDir = path.join(ROOT, "channels", slug); const id = "vid00000002"; const videoDir = path.join(channelDir, "data", id); const mediaRoot = path.join(ROOT, "drive", slug, "media"); const mediaDir = path.join(mediaRoot, id); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(videoDir, "metadata.info.json"), "{}"); if (tiered) { await mkdir(mediaDir, { recursive: true }); await symlink(mediaRoot, path.join(channelDir, "media")); await writeFile(path.join(mediaDir, CHAT), ORIGINAL); await utimes(path.join(mediaDir, CHAT), 1763700100.25, 1763700100.333337); await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT)); await lutimes(path.join(videoDir, CHAT), 1763700200.5, 1763700200.777779); } else { await writeFile(path.join(videoDir, CHAT), ORIGINAL); await utimes(path.join(videoDir, CHAT), 1763700100.25, 1763700100.987651); } const lstatMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs; const statMs = (await stat(path.join(videoDir, CHAT))).mtimeMs; const out = await compressStoredText(videoDir, CHAT, { reserveBytes: 0 }); assert.equal(out.status, "compressed", JSON.stringify(out)); return { channelDir, videoDir, mediaDir, tiered, lstatMs, statMs }; } async function assertWhole(f: F, why: string): Promise { assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`); assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`); } async function assertPlainFinal(f: F, why: string): Promise { assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT], `${why}: data/`); assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, `${why}: the plain bytes`); assert.equal((await lstat(path.join(f.videoDir, CHAT))).mtimeMs, f.lstatMs, `${why}: the lstat key`); assert.equal((await stat(path.join(f.videoDir, CHAT))).mtimeMs, f.statMs, `${why}: the stat`); if (f.tiered) { assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink(), `${why}: a tier link`); assert.equal(await readlink(path.join(f.videoDir, CHAT)), path.join("..", "..", "media", "vid00000002", CHAT)); assert.deepEqual(await readdir(f.mediaDir), [CHAT], `${why}: media/`); } } const run = (f: F, extra: Parameters[2] = {}) => restoreStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra }); for (const tiered of [false, true]) { const how = tiered ? "tiered" : "real"; test(`${how}: restored with the same bytes and times, then idempotent; a compress after it is the same as before`, async () => { const f = await compressed(tiered); const out = await run(f); assert.equal(out.status, "restored", JSON.stringify(out)); await assertPlainFinal(f, "restored"); assert.equal((await run(f)).status, "already"); // Round trip: compress again, restore again — the same plain file. assert.equal((await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 })).status, "compressed"); assert.equal((await run(f)).status, "restored"); await assertPlainFinal(f, "second round trip"); }); for (const point of KILLS.filter((p) => tiered || p !== "restore-linked")) { test(`${how}: killed at "${point}" — one whole copy remains, and the next run (a restore, or a compress) finishes`, async () => { for (const next of ["restore", "compress"] as const) { const f = await compressed(tiered); await assert.rejects( run(f, { pid: DEAD, crashAt: (p) => { if (p === point) throw new CompressKill(p); } }), CompressKill, ); await assertWhole(f, `after the kill at ${point}`); if (next === "restore") { const out = await run(f); assert.equal(out.status, "restored", `${point}: ${JSON.stringify(out)}`); await assertPlainFinal(f, `${point}, then restore`); } else { const out = await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 }); assert.ok(["already", "compressed"].includes(out.status), `${point}: ${JSON.stringify(out)}`); await assertWhole(f, `${point}, then compress`); assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST], `${point}: stored form only`); if (tiered) assert.deepEqual(await readdir(f.mediaDir), [ZST], `${point}: media/`); } } }); } test(`${how}: a stored file that does not decode is refused and left as it is`, async () => { const f = await compressed(tiered); const zBytes = f.tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST); const whole = await readFile(zBytes); await writeFile(zBytes, whole.subarray(0, Math.floor(whole.length / 2))); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out)); assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST]); assert.equal((await readFile(zBytes)).length, Math.floor(whole.length / 2), "untouched"); }); test(`${how}: a plain file beside the stored one with DIFFERENT content is refused; with the same content the stored one goes`, async () => { const f = await compressed(tiered); await writeFile(path.join(f.videoDir, CHAT), "NEWER\n"); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out)); assert.ok(await lstat(path.join(f.videoDir, ZST))); await writeFile(path.join(f.videoDir, CHAT), ORIGINAL); assert.equal((await run(f)).status, "restored"); assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]); }); test(`${how}: skipped, touching nothing — a move, a recording, a full disk`, async () => { for (const [reason, arrange] of [ ["relocating", async (f: F) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})], ["recording", async (f: F) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})], ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })], ] as const) { const f = await compressed(tiered); const extra = await arrange(f); const before = (await readdir(f.videoDir)).sort(); const out = await restoreStoredText(f.videoDir, CHAT, extra); assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`); assert.deepEqual((await readdir(f.videoDir)).sort(), before, `${reason}: nothing touched`); await assertWhole(f, reason); } }); } test("a plain chat that was never compressed is `already`; no chat at all is `absent`", async () => { const d = path.join(ROOT, "channels", "plain-only", "data", "v"); await mkdir(d, { recursive: true }); assert.equal((await restoreStoredText(d, CHAT)).status, "absent"); await writeFile(path.join(d, CHAT), "x\n"); assert.equal((await restoreStoredText(d, CHAT)).status, "already"); assert.equal(await readFile(path.join(d, CHAT), "utf8"), "x\n"); });