import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { lstat, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.lock.test.ts // // TWO PROCESSES ON ONE VIDEO DIR (REVIEW-2 R3). Compress, restore and the files // card's delete take `.stored-text.lock` in the video dir; a second process // honours it ("busy", nothing touched) while its owner runs, and takes over a // stale one (its owner gone, or this pid from an earlier start). And the // restore looks at the plain file again right before the stored form goes. // Temp dirs only; the second process is a real child process. const ROOT = await mkdtemp(path.join(tmpdir(), "stored-lock-")); test.after(() => rm(ROOT, { recursive: true, force: true })); const W = await import("./storedText-write-server"); const { readStoredText, decodeStoredBytes } = await import("./storedText-server"); const CHAT = "transcript.live_chat.json"; const ZST = `${CHAT}.zst`; const LOCK = ".stored-text.lock"; const BODY = Array.from({ length: 30_000 }, (_, i) => `{"replayChatItemAction":{"n":${i},"h":"${createHash("md5").update(String(i)).digest("hex")}"}}`).join("\n") + "\n"; let n = 0; async function videoDir(): Promise { const d = path.join(ROOT, "channels", `c${++n}`, "data", "v"); await mkdir(d, { recursive: true }); await writeFile(path.join(d, CHAT), BODY); return d; } const exists = (p: string) => lstat(p).then(() => true, () => false); async function snapshot(d: string): Promise { const out: string[] = []; for (const e of (await readdir(d)).sort()) out.push(`${e} ${createHash("sha256").update(await readFile(path.join(d, e))).digest("hex")}`); return out; } test("a lock held by a live run of another process: compress, restore and delete answer busy, touching nothing", async () => { const d = await videoDir(); const other = process.ppid; const token = W.processStartToken(other); assert.ok(token); await writeFile(path.join(d, LOCK), JSON.stringify({ pid: other, token })); const before = await snapshot(d); const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c)); const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r)); assert.equal(await W.removeStoredTextForm(d, CHAT), "busy"); assert.deepEqual(await snapshot(d), before, "nothing touched, the lock kept"); }); test("a stale lock (a reused pid's, a dead pid's, this pid's from an earlier start) is taken over and released", async () => { for (const owner of [{ pid: process.ppid, token: "reused0" }, { pid: 999_999_995, token: "gone0" }, { pid: process.pid, token: "earlier0" }]) { const d = await videoDir(); await writeFile(path.join(d, LOCK), JSON.stringify(owner)); const out = await W.compressStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(out.status, "compressed", `${JSON.stringify(owner)}: ${JSON.stringify(out)}`); assert.equal(await exists(path.join(d, LOCK)), false, "released"); assert.deepEqual((await readdir(d)).sort(), [ZST]); } }); test("two processes at once: while a child process compresses, this one's restore and compress are refused; one whole copy throughout", async () => { const d = await videoDir(); const child = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "compress", d, CHAT, "40"], { stdio: ["ignore", "pipe", "pipe"], }); let out = ""; let err = ""; child.stdout.on("data", (b) => (out += b)); child.stderr.on("data", (b) => (err += b)); const done = new Promise((resolve) => child.on("exit", resolve)); // Wait for the child to hold the dir. for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25)); assert.ok(await exists(path.join(d, LOCK)), `the child holds the lock (${err})`); const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r)); const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c)); assert.equal(await readStoredText(d, CHAT, "utf8"), BODY, "one whole copy while the child runs"); assert.equal(await done, 0, err); assert.equal(JSON.parse(out).status, "compressed", out); assert.equal(await exists(path.join(d, LOCK)), false); assert.deepEqual((await readdir(d)).sort(), [ZST]); // And the other way round: the child restores, this process is refused. const back = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "restore", d, CHAT, "40"], { stdio: ["ignore", "pipe", "pipe"], }); let out2 = ""; back.stdout.on("data", (b) => (out2 += b)); const done2 = new Promise((resolve) => back.on("exit", resolve)); for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25)); const c2 = await W.compressStoredText(d, CHAT, { reserveBytes: 0 }); assert.equal(c2.status === "skipped" && c2.reason, "busy", JSON.stringify(c2)); assert.equal(await done2, 0); assert.equal(JSON.parse(out2).status, "restored", out2); assert.equal(await readFile(path.join(d, CHAT), "utf8"), BODY); assert.deepEqual((await readdir(d)).sort(), [CHAT]); }); test("restore: the plain file is looked at again right before the stored form goes — a changed one keeps the stored form", async () => { const { writeFileSync } = await import("node:fs"); const d = await videoDir(); assert.equal((await W.compressStoredText(d, CHAT, { reserveBytes: 0 })).status, "compressed"); const out = await W.restoreStoredText(d, CHAT, { reserveBytes: 0, // Another process's write lands in the placed plain file after it was verified. crashAt: (p) => { if (p === "restore-placed") writeFileSync(path.join(d, CHAT), BODY.replace("\"n\":7,", "\"n\":8,")); }, }); assert.equal(out.status, "changed", JSON.stringify(out)); assert.ok(await exists(path.join(d, ZST)), "the stored form stays"); assert.equal((await decodeStoredBytes(await readFile(path.join(d, ZST)))).toString("utf8"), BODY, "whole"); });