// The library's CDN media downloader over a stand-in fetch: no socket is // opened (the harness runs with ARCHILYZER_NO_NETWORK=1 besides). // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xTrendingMedia.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { createLibraryMediaDownloader, libraryMediaPauseMs, type LibraryMediaDeps, type MediaFetch } from "./xTrendingMedia"; import { readXTrendingMediaIndex } from "../lib/xTrending/mediaStore"; import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; import type { TrendingMediaSource } from "./xTrendingParse"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-cdn-")); after(() => rmSync(TMP, { recursive: true, force: true })); const img = (key: string): TrendingMediaSource => ({ kind: "image", url: `https://pbs.twimg.com/media/${key}.jpg`, fetchUrl: `https://pbs.twimg.com/media/${key}?format=jpg&name=orig`, ext: "jpg", }); const vid = (key: string): TrendingMediaSource => ({ kind: "video", url: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, fetchUrl: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, ext: "mp4", }); type Answer = { status?: number; body?: string; length?: number; throws?: string; slowBodyMs?: number }; function harness(name: string, answers: Record, over: Partial = {}) { const root = path.join(TMP, name); const asked: string[] = []; const cancelled: string[] = []; const pauses: number[] = []; const state = { cooldown: 0, limited: 0 }; const fetch: MediaFetch = async (url, init) => { asked.push(url); assert.equal(init.redirect, "error"); assert.equal(init.credentials, "omit"); const a = answers[url]; if (!a) return { status: 404, headers: { get: () => null }, body: null }; if (a.throws) throw new Error(a.throws); const bytes = Buffer.from(a.body ?? ""); return { status: a.status ?? 200, headers: { get: (h) => (h === "content-length" ? String(a.length ?? bytes.length) : null) }, body: Object.assign( (async function* () { // Two chunks, so a cap can fall mid-stream. yield bytes.subarray(0, Math.ceil(bytes.length / 2)); if (a.slowBodyMs) await new Promise((r) => setTimeout(r, a.slowBodyMs)); if (init.signal.aborted) throw new Error("aborted"); yield bytes.subarray(Math.ceil(bytes.length / 2)); })(), { cancel: async () => void cancelled.push(url) }, ), }; }; const deps: LibraryMediaDeps = { fetch, pauseMs: () => 1500, pause: async (ms) => void pauses.push(ms), cooldownMs: async () => state.cooldown, noteRateLimit: async () => { state.limited++; return Date.parse("2026-11-18T10:15:00Z"); }, now: () => Date.parse("2026-11-18T10:00:00Z"), ...over, }; const dirOf = (id: string) => path.join(root, "trending", "posts-media", id); const args = (id: string): PostMediaDownloadArgs => ({ id, dir: dirOf(id), signal: new AbortController().signal }); const noLogin = async (): Promise => { throw new Error("the logged-in download must not run"); }; return { root, asked, cancelled, pauses, state, deps, dirOf, args, noLogin }; } test("files come from the CDN one after another, 1 to 2 s apart, and each is kept once", async () => { const h = harness("fetch", { [img("A").fetchUrl]: { body: "PICTURE-A" }, [img("B").fetchUrl]: { body: "PICTURE-B" }, [vid("V").fetchUrl]: { body: "VIDEO-V" }, // Another address, the same bytes as A. [img("A2").fetchUrl]: { body: "PICTURE-A" }, }); const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([ ["701", [img("A"), img("B")]], ["702", [vid("V"), img("A"), img("A2")]], ]), maxVideoBytes: 100, fallback: "none", deps: h.deps, }); assert.deepEqual(await download(h.args("701"), h.noLogin), { ok: true, files: [ { name: "701_1.jpg", url: img("A").url }, { name: "701_2.jpg", url: img("B").url }, ], }); const second = await download(h.args("702"), h.noLogin); assert.equal(second.ok, true); // A's address is known: 702_2.jpg is linked, never asked for again. assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl, vid("V").fetchUrl, img("A2").fetchUrl]); // A gap before every fetch but the job's first. assert.deepEqual(h.pauses, [1500, 1500, 1500]); const a1 = statSync(path.join(h.dirOf("701"), "701_1.jpg")); assert.equal(statSync(path.join(h.dirOf("702"), "702_2.jpg")).ino, a1.ino); // Same bytes from another address: fetched, then one file with A. assert.equal(statSync(path.join(h.dirOf("702"), "702_3.jpg")).ino, a1.ino); assert.equal(readFileSync(path.join(h.dirOf("702"), "702_1.mp4"), "utf8"), "VIDEO-V"); assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).blobs).length, 3); // No partial left behind. assert.deepEqual(readdirSync(h.dirOf("702")).sort(), ["702_1.mp4", "702_2.jpg", "702_3.jpg"]); // Asked again: everything is on disk, nothing is fetched. h.asked.length = 0; assert.equal((await download(h.args("701"), h.noLogin)).ok, true); assert.deepEqual(h.asked, []); const gap = libraryMediaPauseMs(() => 0.5); assert.ok(gap >= 1000 && gap < 2000); }); test("a 429 stops the job and records the cooldown; a 403 or 404 marks the file and nothing retries", async () => { const h = harness("refused", { [img("Gone").fetchUrl]: { status: 404 }, [img("Forbidden").fetchUrl]: { status: 403 }, [img("Fine").fetchUrl]: { body: "FINE" }, [img("Limited").fetchUrl]: { status: 429 }, [img("Never").fetchUrl]: { body: "NEVER" }, }); const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([ ["711", [img("Gone"), img("Forbidden"), img("Fine")]], ["712", [img("Limited"), img("Never")]], ]), maxVideoBytes: 100, fallback: "none", deps: h.deps, }); const first = await download(h.args("711"), h.noLogin); assert.equal(first.ok, false); if (first.ok) return; assert.match(first.error, /711_1\.jpg: the CDN answered 404; 711_2\.jpg: the CDN answered 403/); assert.deepEqual(first.files, [{ name: "711_3.jpg", url: img("Fine").url }]); // A refused file is an error of the post, not something merely owed; and it does not stop the run. assert.equal(first.owed, undefined); assert.equal(first.stop, undefined); // Each address asked exactly once. assert.deepEqual(h.asked, [img("Gone").fetchUrl, img("Forbidden").fetchUrl, img("Fine").fetchUrl]); const limited = await download(h.args("712"), h.noLogin); assert.equal(limited.ok, false); if (limited.ok) return; assert.match(limited.stop ?? "", /answered 429 \(rate limit\) for 712_1\.jpg.*Nothing X starts before 10:15 UTC; nothing retries by itself/); assert.equal(h.state.limited, 1); // The file after the 429 was never asked for. assert.equal(h.asked.includes(img("Never").fetchUrl), false); assert.equal(existsSync(path.join(h.dirOf("712"), "712_2.jpg")), false); }); test("X's cooldown holds the media: nothing is asked while it runs", async () => { const h = harness("cooling", { [img("A").fetchUrl]: { body: "A" } }); h.state.cooldown = 9 * 60_000; const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["721", [img("A")]]]), maxVideoBytes: 100, fallback: "none", deps: h.deps }); const res = await download(h.args("721"), h.noLogin); assert.equal(res.ok, false); if (res.ok) return; assert.match(res.stop ?? "", /no media fetch starts before 10:09 UTC \(9 min from now\)/); assert.equal(res.owed, "next"); assert.deepEqual(h.asked, []); }); test("a file over the cap is owed, by its declared size or mid-stream; a kept post has no cap", async () => { const answers = { [vid("Declared").fetchUrl]: { body: "x", length: 5000 }, [vid("Streamed").fetchUrl]: { body: "0123456789ABCDEF", length: 4 }, [img("Small").fetchUrl]: { body: "ok" }, }; const h = harness("cap", answers); const sources = new Map([["731", [vid("Declared"), vid("Streamed"), img("Small")]]]); const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: 10, fallback: "none", deps: h.deps }); const res = await watch(h.args("731"), h.noLogin); assert.equal(res.ok, false); if (res.ok) return; assert.equal(res.owed, "kept"); assert.match(res.error, /731_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept; 731_2\.mp4: it is over the 1 MB cap: owed until the post is kept/); assert.deepEqual(res.files, [{ name: "731_3.jpg", url: img("Small").url }]); assert.deepEqual(readdirSync(h.dirOf("731")), ["731_3.jpg"]); // Found over the cap once: the next capture under the same cap does not ask for them again. h.asked.length = 0; const next = await watch(h.args("731"), h.noLogin); assert.equal(next.ok, false); assert.deepEqual(h.asked, []); assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).oversize).length, 2); // Kept: no cap, so the same files come down. const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: null, fallback: "login", deps: h.deps }); const again = await kept(h.args("731"), h.noLogin); assert.equal(again.ok, true); assert.equal(readFileSync(path.join(h.dirOf("731"), "731_2.mp4"), "utf8"), "0123456789ABCDEF"); assert.deepEqual((await readXTrendingMediaIndex(h.root)).oversize, {}); }); test("a job's budget: past it the rest is owed and nothing more is asked", async () => { const h = harness("budget", { [img("A").fetchUrl]: { body: "AAAA" }, [img("B").fetchUrl]: { body: "BBBB" }, [img("C").fetchUrl]: { body: "CCCC" }, }); const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["741", [img("A"), img("B")]], ["742", [img("C"), img("A")]]]), maxVideoBytes: 100, fallback: "none", maxFiles: 2, deps: h.deps, }); assert.equal((await download(h.args("741"), h.noLogin)).ok, true); const res = await download(h.args("742"), h.noLogin); assert.equal(res.ok, false); if (res.ok) return; assert.equal(res.owed, "next"); assert.equal(res.stop, undefined); assert.match(res.error, /742_1\.jpg: owed \(this job's media budget of 2 files/); // What the library already holds is still linked, budget or not. assert.deepEqual(res.files, [{ name: "742_2.jpg", url: img("A").url }]); assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl]); }); test("the logged-in download is the fallback for a kept post only, and what it lands is kept once too", async () => { const h = harness("fallback", { [img("Fine").fetchUrl]: { body: "FINE" } }); const sources = new Map([["751", [img("Fine")]]]); const expected = new Map([["751", 2]]); // A watch: the file the capture names no address for is owed; no login. const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: 100, fallback: "none", deps: h.deps }); const owed = await watch(h.args("751"), h.noLogin); assert.equal(owed.ok, false); if (owed.ok) return; assert.equal(owed.owed, "kept"); assert.match(owed.error, /1 of its 2 media file\(s\) have no CDN address in the saved capture: owed until the post is kept/); // Kept: the fetcher's own download runs once, and its file joins the store. let logins = 0; const { writeFileSync } = await import("node:fs"); const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: null, fallback: "login", deps: h.deps }); const res = await kept(h.args("751"), async ({ dir }) => { logins++; writeFileSync(path.join(dir, "751_2.mp4"), "VIA-LOGIN"); return { ok: true, files: [{ name: "751_1.jpg" }, { name: "751_2.mp4", url: "https://video.twimg.com/x/v.mp4" }] }; }); assert.equal(logins, 1); assert.equal(res.ok, true); const index = await readXTrendingMediaIndex(h.root); const blobs = Object.values(index.blobs); assert.equal(blobs.length, 2); assert.ok(blobs.some((b) => b.urls.includes("https://video.twimg.com/x/v.mp4") && b.posts["751"]?.includes("751_2.mp4"))); }); test("an address off X's media CDN is never asked; a fetch that throws marks the file", async () => { const h = harness("hosts", { "https://pbs.twimg.com/media/T?format=jpg&name=orig": { throws: "socket hang up" } }); const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([ ["761", [{ kind: "image", url: "https://example.test/a.jpg", fetchUrl: "https://example.test/a.jpg", ext: "jpg" }, img("T")]], ]), maxVideoBytes: 100, fallback: "none", deps: h.deps, }); const res = await download(h.args("761"), h.noLogin); assert.equal(res.ok, false); if (res.ok) return; assert.match(res.error, /761_1\.jpg: not an address on X's media CDN; 761_2\.jpg: the CDN did not answer \(socket hang up\)/); assert.deepEqual(h.asked, ["https://pbs.twimg.com/media/T?format=jpg&name=orig"]); }); // Review 1 S3. test("S3: the wait for the headers ends when they arrive — a body slower than it still comes down; an oversize body is cancelled", async () => { const h = harness( "timers", { [img("Slow").fetchUrl]: { body: "SLOW-BUT-WHOLE", slowBodyMs: 80 }, [vid("Big").fetchUrl]: { body: "x", length: 5000 } }, { timeouts: { headersMs: 20, fileMs: 5_000 } }, ); const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["771", [img("Slow"), vid("Big")]]]), maxVideoBytes: 100, fallback: "none", deps: h.deps, }); const res = await download(h.args("771"), h.noLogin); // The body took four times the headers' limit: it is whole. assert.equal(readFileSync(path.join(h.dirOf("771"), "771_1.jpg"), "utf8"), "SLOW-BUT-WHOLE"); assert.equal(res.ok, false); if (res.ok) return; assert.equal(res.owed, "kept"); // The file declared over the cap was not left downloading. assert.deepEqual(h.cancelled, [vid("Big").fetchUrl]); // And the file's own limit is still a limit. const strict = harness("timers-file", { [img("Slow").fetchUrl]: { body: "NEVER-WHOLE", slowBodyMs: 80 } }, { timeouts: { headersMs: 20, fileMs: 30 } }); const cut = await createLibraryMediaDownloader({ channelRoot: strict.root, sources: new Map([["772", [img("Slow")]]]), maxVideoBytes: 100, fallback: "none", deps: strict.deps })(strict.args("772"), strict.noLogin); assert.equal(cut.ok, false); assert.equal(existsSync(path.join(strict.dirOf("772"), "772_1.jpg")), false); assert.deepEqual(readdirSync(strict.dirOf("772")), []); }); // Review 1 S9. test("S9: three refusals in a row (a 403, or no answer) and the job asks the CDN no more; the rest is owed to a later capture", async () => { const answers: Record = { [img("R1").fetchUrl]: { status: 403 }, [img("R2").fetchUrl]: { throws: "socket hang up" }, [img("R3").fetchUrl]: { status: 403 }, [img("Never1").fetchUrl]: { body: "N1" }, [img("Never2").fetchUrl]: { body: "N2" }, }; const h = harness("refusing", answers); const log: string[] = []; const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["781", [img("R1"), img("R2")]], ["782", [img("R3"), img("Never1")]], ["783", [img("Never2")]]]), maxVideoBytes: 100, fallback: "none", deps: h.deps, }); const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) }); await download(withLog("781"), h.noLogin); const second = await download(withLog("782"), h.noLogin); const third = await download(withLog("783"), h.noLogin); assert.deepEqual(h.asked, [img("R1").fetchUrl, img("R2").fetchUrl, img("R3").fetchUrl]); assert.equal(second.ok, false); if (!second.ok) assert.match(second.error, /782_2\.jpg: owed \(the CDN refused 3 files in a row; this job asks it no more\)/); // A post that only met the halt is merely owed, to the next capture. assert.deepEqual(third.ok ? null : [third.owed, third.stop], ["next", undefined]); assert.equal(log.filter((l) => /refused 3 files in a row/.test(l)).length, 1); // A 404 between them is not a refusal, and a file that comes down starts the count again. const mixed = harness("refusing-mixed", { [img("A").fetchUrl]: { status: 403 }, [img("B").fetchUrl]: { status: 403 }, [img("C").fetchUrl]: { body: "FINE" }, [img("D").fetchUrl]: { status: 403 }, [img("E").fetchUrl]: { status: 403 }, [img("G").fetchUrl]: { body: "ALSO FINE" }, }); const res = await createLibraryMediaDownloader({ channelRoot: mixed.root, sources: new Map([["791", [img("A"), img("B"), img("C"), img("D"), img("E"), img("Gone"), img("G")]]]), maxVideoBytes: 100, fallback: "none", deps: mixed.deps, })(mixed.args("791"), mixed.noLogin); assert.equal(mixed.asked.length, 7); assert.deepEqual((res.ok ? [] : res.files ?? []).map((f) => f.name), ["791_3.jpg", "791_7.jpg"]); }); // Review 1 M4, review 2 N3: one predicate, once per post, before its media. test("M4/N3: a post still kept has no cap and the logged-in download; one dropped since the job was queued has neither", async () => { const big = "0123456789ABCDEFGHIJ"; const h = harness("still-kept", { [vid("K").fetchUrl]: { body: big }, [vid("D").fetchUrl]: { body: big } }); const kept = new Set(["801", "803"]); const asked: string[] = []; const log: string[] = []; const download = createLibraryMediaDownloader({ channelRoot: h.root, // 801 and 802: a video over the library's cap. 803 and 804: media the capture names no address for. sources: new Map([["801", [vid("K")]], ["802", [vid("D")]]]), expected: new Map([["801", 1], ["802", 1], ["803", 1], ["804", 1]]), maxVideoBytes: 10, fallback: "login", isKept: async (id) => (asked.push(id), kept.has(id)), deps: h.deps, }); let logins = 0; const login = async ({ id, dir }: PostMediaDownloadArgs): Promise => { logins++; const { writeFileSync } = await import("node:fs"); writeFileSync(path.join(dir, `${id}_1.jpg`), "VIA-LOGIN"); return { ok: true, files: [{ name: `${id}_1.jpg` }] }; }; const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) }); // Kept: the whole video, over the cap or not. assert.equal((await download(withLog("801"), login)).ok, true); assert.equal(readFileSync(path.join(h.dirOf("801"), "801_1.mp4"), "utf8"), big); // Dropped since: the cap applies — the uncapped download is not its any more. const dropped = await download(withLog("802"), login); assert.equal(dropped.ok, false); if (!dropped.ok) { assert.equal(dropped.owed, "kept"); assert.match(dropped.error, /802_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept/); } assert.deepEqual(readdirSync(h.dirOf("802")), []); // Kept, nothing on the CDN: the logged-in download. assert.equal((await download(withLog("803"), login)).ok, true); assert.equal(logins, 1); // Dropped since, nothing on the CDN: no login for it. const noLogin = await download(withLog("804"), login); assert.equal(logins, 1); assert.equal(noLogin.ok, false); if (!noLogin.ok) assert.equal(noLogin.owed, "kept"); // Asked once per post, before its media. assert.deepEqual(asked, ["801", "802", "803", "804"]); assert.equal(log.filter((l) => /no longer marked keep: its media is fetched as any post's/.test(l)).length, 2); });