import { after, test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { adoptXTrendingMedia, CAPTURE_IN_FLIGHT, ensureXTrendingMediaIgnore, noteXTrendingOversize, xTrendingMediaIndexPath, linkXTrendingMedia, readXTrendingMediaIndex, removeXTrendingPostCapture, xTrendingBlobByUrl, xTrendingMediaStoreDir, } from "./mediaStore"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-media-")); after(() => rmSync(TMP, { recursive: true, force: true })); // No capture of the library is queued or running. const IDLE = { captureInFlight: () => false }; const sha = (s: string) => createHash("sha256").update(s).digest("hex"); const root = (name: string) => path.join(TMP, name); const postDir = (dir: string, id: string) => path.join(dir, "trending", "posts-media", id); function put(dir: string, id: string, name: string, bytes: string): string { mkdirSync(postDir(dir, id), { recursive: true }); const file = path.join(postDir(dir, id), name); writeFileSync(file, bytes); return file; } const blobOf = (dir: string, bytes: string, ext: string) => path.join(xTrendingMediaStoreDir(dir), sha(bytes).slice(0, 2), `${sha(bytes)}.${ext}`); test("a captured file becomes the blob; the same bytes under another post are one file", async () => { const dir = root("dedupe"); const a = put(dir, "601", "601_1.jpg", "PICTURE-ONE"); const first = await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg", url: "https://pbs.twimg.com/media/One.jpg", now: () => Date.parse("2026-11-18T10:00:00Z") }); assert.deepEqual(first, { sha256: sha("PICTURE-ONE"), bytes: 11, deduped: false, linked: true }); const blob = blobOf(dir, "PICTURE-ONE", "jpg"); assert.equal(statSync(blob).ino, statSync(a).ino); assert.equal(statSync(blob).nlink, 2); // The same picture on another post, in another topic: fetched again, kept once. const b = put(dir, "602", "602_1.jpg", "PICTURE-ONE"); assert.notEqual(statSync(b).ino, statSync(blob).ino); const second = await adoptXTrendingMedia(dir, { postId: "602", name: "602_1.jpg", url: "https://pbs.twimg.com/media/OneAgain.jpg" }); assert.equal(second.deduped, true); assert.equal(statSync(b).ino, statSync(blob).ino); assert.equal(statSync(blob).nlink, 3); assert.equal(readFileSync(b, "utf8"), "PICTURE-ONE"); // Other bytes are another blob: exact duplicates only. put(dir, "602", "602_2.jpg", "PICTURE-ONE."); assert.equal((await adoptXTrendingMedia(dir, { postId: "602", name: "602_2.jpg" })).deduped, false); const index = await readXTrendingMediaIndex(dir); assert.deepEqual(index.blobs[sha("PICTURE-ONE")], { bytes: 11, ext: "jpg", addedAt: "2026-11-18T10:00:00.000Z", urls: ["https://pbs.twimg.com/media/One.jpg", "https://pbs.twimg.com/media/OneAgain.jpg"], posts: { "601": ["601_1.jpg"], "602": ["602_1.jpg"] }, }); assert.equal(Object.keys(index.blobs).length, 2); // Adopting the same name again changes nothing. assert.equal((await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg" })).linked, true); assert.equal(statSync(blob).nlink, 3); // No leftover link temp in the capture directory. assert.deepEqual(readdirSync(postDir(dir, "602")).sort(), ["602_1.jpg", "602_2.jpg"]); }); test("a known address is linked with no fetch; an unknown blob is not", async () => { const dir = root("link"); put(dir, "611", "611_1.mp4", "VIDEO-BYTES"); await adoptXTrendingMedia(dir, { postId: "611", name: "611_1.mp4", url: "https://video.twimg.com/v/high.mp4" }); const index = await readXTrendingMediaIndex(dir); const known = xTrendingBlobByUrl(index, "https://video.twimg.com/v/high.mp4"); assert.equal(known, sha("VIDEO-BYTES")); assert.equal(xTrendingBlobByUrl(index, "https://video.twimg.com/v/other.mp4"), undefined); // The post's directory does not exist yet: it is made. assert.deepEqual(await linkXTrendingMedia(dir, { postId: "612", name: "612_1.mp4", sha256: known! }), { bytes: 11 }); assert.equal(readFileSync(path.join(postDir(dir, "612"), "612_1.mp4"), "utf8"), "VIDEO-BYTES"); assert.equal(statSync(blobOf(dir, "VIDEO-BYTES", "mp4")).nlink, 3); assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs[known!].posts, { "611": ["611_1.mp4"], "612": ["612_1.mp4"] }); assert.equal(await linkXTrendingMedia(dir, { postId: "613", name: "613_1.mp4", sha256: sha("nothing") }), null); // A blob removed from the store under the index: not linked (the caller fetches). rmSync(blobOf(dir, "VIDEO-BYTES", "mp4")); assert.equal(await linkXTrendingMedia(dir, { postId: "614", name: "614_1.mp4", sha256: known! }), null); // ...and adopting a file with those bytes puts the blob back. put(dir, "614", "614_1.mp4", "VIDEO-BYTES"); await adoptXTrendingMedia(dir, { postId: "614", name: "614_1.mp4" }); assert.equal(existsSync(blobOf(dir, "VIDEO-BYTES", "mp4")), true); }); test("deleting a post never deletes media another post still uses", async () => { const dir = root("remove"); put(dir, "621", "621_1.jpg", "SHARED"); put(dir, "621", "621_2.jpg", "ONLY-621"); put(dir, "621", "shot.png", "SHOT"); put(dir, "621", "capture.json", "{}"); put(dir, "622", "622_1.jpg", "SHARED"); await adoptXTrendingMedia(dir, { postId: "621", name: "621_1.jpg" }); await adoptXTrendingMedia(dir, { postId: "621", name: "621_2.jpg" }); await adoptXTrendingMedia(dir, { postId: "622", name: "622_1.jpg" }); const shared = blobOf(dir, "SHARED", "jpg"); const only = blobOf(dir, "ONLY-621", "jpg"); assert.equal(statSync(shared).nlink, 3); const removed = await removeXTrendingPostCapture(dir, "621", IDLE); assert.deepEqual(removed, { files: 4, blobsFreed: 1, bytesFreed: 8, blobsKept: 1 }); assert.equal(existsSync(postDir(dir, "621")), false); // 622's picture is whole, and so is the store's copy of it. assert.equal(readFileSync(path.join(postDir(dir, "622"), "622_1.jpg"), "utf8"), "SHARED"); assert.equal(statSync(shared).nlink, 2); assert.equal(existsSync(only), false); const index = await readXTrendingMediaIndex(dir); assert.deepEqual(Object.keys(index.blobs), [sha("SHARED")]); assert.deepEqual(index.blobs[sha("SHARED")].posts, { "622": ["622_1.jpg"] }); // The last post that carries it takes the blob with it. assert.deepEqual(await removeXTrendingPostCapture(dir, "622", IDLE), { files: 1, blobsFreed: 1, bytesFreed: 6, blobsKept: 0 }); assert.equal(existsSync(shared), false); assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs, {}); // A post with no capture: nothing to remove, nothing thrown. assert.deepEqual(await removeXTrendingPostCapture(dir, "629", IDLE), { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }); }); test("a blob something else still links to is kept, even when the index names no post for it", async () => { const dir = root("stray-link"); put(dir, "631", "631_1.jpg", "KEPT-ELSEWHERE"); await adoptXTrendingMedia(dir, { postId: "631", name: "631_1.jpg" }); // A second name the index never heard of (a file linked by hand). const { linkSync } = await import("node:fs"); mkdirSync(postDir(dir, "632"), { recursive: true }); linkSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg"), path.join(postDir(dir, "632"), "632_1.jpg")); const removed = await removeXTrendingPostCapture(dir, "631", IDLE); assert.equal(removed.blobsFreed, 0); assert.equal(removed.blobsKept, 1); assert.equal(readFileSync(path.join(postDir(dir, "632"), "632_1.jpg"), "utf8"), "KEPT-ELSEWHERE"); assert.equal(existsSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg")), true); }); test("ids and names are checked where they become paths; the media is ignored by the corpus repo", async () => { const dir = root("checks"); await assert.rejects(adoptXTrendingMedia(dir, { postId: "../x", name: "a.jpg" }), /not a post id/); await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: "../a.jpg" }), /not a media file's name/); await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: ".hidden" }), /not a media file's name/); await assert.rejects(removeXTrendingPostCapture(dir, "_avatars", IDLE), /not a post id/); await ensureXTrendingMediaIgnore(dir); const ignore = readFileSync(path.join(dir, "trending", ".gitignore"), "utf8"); assert.match(ignore, /^posts-media\/$/m); assert.match(ignore, /^media-store\/$/m); }); // Review 1 S8. test("S8: a media index that is there and cannot be read is never taken for an empty one: nothing is written over it", async () => { const dir = root("broken-index"); put(dir, "641", "641_1.jpg", "FIRST"); await adoptXTrendingMedia(dir, { postId: "641", name: "641_1.jpg" }); const file = xTrendingMediaIndexPath(dir); // No file at all IS an empty index. assert.deepEqual((await readXTrendingMediaIndex(root("no-index-yet"))).blobs, {}); for (const broken of ['{"version":1,"blobs":{"ab', "[]", ""]) { writeFileSync(file, broken); await assert.rejects(readXTrendingMediaIndex(dir), (e: Error) => { assert.match(e.message, /The library's media index \(.*media-index\.json\) is not (JSON|a media index)/); assert.match(e.message, /Nothing was written/); return true; }); put(dir, "642", "642_1.jpg", "SECOND"); await assert.rejects(adoptXTrendingMedia(dir, { postId: "642", name: "642_1.jpg" }), /media index/); await assert.rejects(linkXTrendingMedia(dir, { postId: "643", name: "643_1.jpg", sha256: sha("FIRST") }), /media index/); await assert.rejects(noteXTrendingOversize(dir, { url: "https://video.twimg.com/v.mp4", bytes: 9 }), /media index/); await assert.rejects(removeXTrendingPostCapture(dir, "641", IDLE), /media index/); assert.equal(readFileSync(path.join(postDir(dir, "641"), "641_1.jpg"), "utf8"), "FIRST"); // The broken file is as it was: not replaced by a one-entry index. assert.equal(readFileSync(file, "utf8"), broken); } }); test("a blob that is not the size of the bytes it is named for is never linked onto; link temps a crash left are swept", async () => { const dir = root("size"); put(dir, "651", "651_1.jpg", "WHOLE-PICTURE"); await adoptXTrendingMedia(dir, { postId: "651", name: "651_1.jpg", url: "https://pbs.twimg.com/media/W.jpg" }); // The store's copy is cut short under it (and no longer shares the post's bytes). const blob = blobOf(dir, "WHOLE-PICTURE", "jpg"); rmSync(blob); writeFileSync(blob, "WHOLE"); const b = put(dir, "652", "652_1.jpg", "WHOLE-PICTURE"); // A crash's leftover link temp beside it. writeFileSync(path.join(postDir(dir, "652"), ".652_1.jpg.link-99999"), "x"); const got = await adoptXTrendingMedia(dir, { postId: "652", name: "652_1.jpg" }); assert.deepEqual([got.deduped, got.linked], [false, false]); assert.equal(readFileSync(b, "utf8"), "WHOLE-PICTURE"); assert.deepEqual(readdirSync(postDir(dir, "652")), ["652_1.jpg"]); // Nor is a known address linked from a blob of the wrong size. assert.equal(await linkXTrendingMedia(dir, { postId: "653", name: "653_1.jpg", sha256: sha("WHOLE-PICTURE") }), null); }); test("a post's capture is not removed while a capture of the library is queued or running", async () => { const dir = root("in-flight"); put(dir, "661", "661_1.jpg", "BYTES"); await adoptXTrendingMedia(dir, { postId: "661", name: "661_1.jpg" }); await assert.rejects(removeXTrendingPostCapture(dir, "661", { captureInFlight: async () => true }), (e: Error) => e.message === CAPTURE_IN_FLIGHT); assert.equal(existsSync(path.join(postDir(dir, "661"), "661_1.jpg")), true); assert.equal((await removeXTrendingPostCapture(dir, "661", IDLE)).files, 1); });