// fetchWindows with `storedUrl` (release 32 R5) against a fake yt-dlp that 429s // for an Odysee PAGE URL and serves the CDN URL, through the real // fetchWindowManaged and the real stored-URL reader (each video dir gets a // synthetic metadata.info.json). ffmpeg is a fake too: the audio check's probe // counts its runs. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchWindowsStoredUrl.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fetchWindows, storedUrlDoor, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows"; import { parseClipProvenance } from "../lib/clipWindow"; import { detectPlatform } from "../lib/platform"; import type { StoredUrlMode } from "../lib/storedMediaUrl"; import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchwindows-stored-")); const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); const ARGS_LOG = path.join(ROOT, "argv.jsonl"); const PROBES = path.join(ROOT, "probes"); process.env.FAKE_ARGS_LOG = ARGS_LOG; process.env.FAKE_PROBES = PROBES; // Release 32 R9: a stored-URL cut of a new file waits out the platform's // stored-URL rest (20 min); the test-only knob makes the rest it sets 0. process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; // The target decides: an odysee.com page (the lookup) answers 429, as the live // lbry extractor did; a CDN file named `cdn429` answers 429 too; anything else // writes the window. await writeFile( YTDLP, `#!/usr/bin/env node import { appendFileSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); const url = args[args.length - 1]; const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); }; if (url.startsWith("https://odysee.com/")) fail("ERROR: [lbry] stream: Unable to download webpage: HTTP Error 429: Too Many Requests (caused by )"); if (url.includes("cdn429")) fail("ERROR: [generic] x: Unable to download webpage: HTTP Error 429: Too Many Requests"); writeFileSync(args[args.indexOf("-o") + 1], "mp4"); `, ); // ffmpeg cuts a STORED URL (an http input: logged like a yt-dlp run, the URL as // its target; a \`cdn429\` file answers 429) and probes the window (a local // input: counted). await writeFile( FFMPEG, `#!/usr/bin/env node import { appendFileSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); const input = args[args.indexOf("-i") + 1] ?? ""; if (input.startsWith("http")) { appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify([...args, input]) + "\\n"); if (input.includes("cdn429")) { process.stderr.write("[https @ 0x1] HTTP error 429 Too Many Requests\\n" + input + ": Server returned 4XX Client Error\\n"); process.exit(1); } writeFileSync(args[args.length - 1], "mp4"); process.exit(0); } appendFileSync(process.env.FAKE_PROBES, "p\\n"); process.exit(0); `, ); await chmod(YTDLP, 0o755); await chmod(FFMPEG, 0o755); const ODYSEE: ChannelConfig = { url: "https://odysee.com/@synthetic", platform: "odysee" } as unknown as ChannelConfig; const YOUTUBE: ChannelConfig = { url: "https://www.youtube.com/@synthetic", platform: "youtube" } as unknown as ChannelConfig; const page = (id: string) => `https://odysee.com/@synthetic:1/stream-${id}:${id}`; const cdn = (id: string, file = "f0") => `https://player.odycdn.com/v6/streams/${id}/${file}.mp4`; let run = 0; async function corpus(): Promise { const channelsDir = path.join(ROOT, `corpus-${++run}`, "channels"); await mkdir(channelsDir, { recursive: true }); return { ytdlpBin: YTDLP, ffmpegBin: FFMPEG, channelsDir } as unknown as Paths; } // A record's metadata.info.json: its page and ONE stored format (or none). async function record(paths: Paths, slug: string, id: string, info: Record | null) { const dir = path.join(paths.channelsDir, slug, "data", id); await mkdir(dir, { recursive: true }); if (info) await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(info)); return dir; } const odyseeInfo = (id: string, url = cdn(id)) => ({ webpage_url: page(id), extractor: "lbry", formats: [{ format_id: "original", url, protocol: "https", ext: "mp4", http_headers: { Referer: "https://odysee.com/" } }], }); const argv = async (): Promise => (await readFile(ARGS_LOG, "utf8").catch(() => "")) .trim() .split("\n") .filter(Boolean) .map((l) => JSON.parse(l) as string[]); const probes = async () => (await readFile(PROBES, "utf8").catch(() => "")).split("\n").filter(Boolean).length; async function marks() { return { argv: (await argv()).length, probes: await probes() }; } async function since(m: { argv: number; probes: number }) { const all = await argv(); const spawned = all.slice(m.argv); return { spawned, targets: spawned.map((a) => a[a.length - 1]), probes: (await probes()) - m.probes }; } function harness(over: Partial = {}) { const rec = { sleeps: [] as number[], backoffs: [] as [string, string][], cleans: [] as string[], logs: [] as string[] }; const deps: Partial = { sleep: async (ms) => { rec.sleeps.push(ms); }, getSettings: () => ({ sleepBetweenDownloadsSeconds: 0 }) as unknown as SiteSettings, readChannelConfig: async (_p, slug) => (slug === "o" ? ODYSEE : slug === "y" ? YOUTUBE : null), findVideoSourceUrl: async () => null, assertTextReadable: async () => undefined, cooldownRemainingMs: async () => 0, heldRefusal: async () => null, recordBackoff: async (platform, _p, cls) => { rec.backoffs.push([platform, cls]); }, recordClean: async (platform) => { rec.cleans.push(platform); return null; }, gapRemainingMs: () => 0, noteGap: () => {}, ...over, }; return { rec, deps }; } const item = (id: string, slug = "o", webpageUrl = page(id)): FetchWindowsItem => ({ slug, id, from: 10, to: 20, webpageUrl }); async function go(paths: Paths, items: FetchWindowsItem[], h: ReturnType, storedUrl?: StoredUrlMode) { return fetchWindows({ paths, items, provenance: { requestedBy: "test" }, gapMs: 1000, ...(storedUrl ? { storedUrl } : {}), onLog: (l) => h.rec.logs.push(l), deps: h.deps, }); } const provenanceOf = async (dir: string) => parseClipProvenance(JSON.parse(await readFile(path.join(dir, "clips", "10.00-20.00.json"), "utf8"))); test("never (the default): the page's 429 fails the window and stops the run, as today", async () => { const paths = await corpus(); await record(paths, "o", "a1", odyseeInfo("a1")); await record(paths, "o", "a2", odyseeInfo("a2")); const h = harness(); const m = await marks(); const r = await go(paths, [item("a1"), item("a2")], h); const s = await since(m); assert.deepEqual(s.targets, [page("a1")], "only the page, once; the CDN never asked"); assert.equal(r.failed[0]?.class, "rate_limit"); assert.equal(r.stopped, "rate-limit"); assert.equal(r.notAttempted.length, 1); assert.deepEqual(r.storedUrl, []); assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]]); }); test("fallback: the page 429s, the window is cut from the stored CDN URL after the gap; the audio probe ran, keyed on the page", async () => { const paths = await corpus(); const dir = await record(paths, "o", "b1", odyseeInfo("b1")); const h = harness(); const m = await marks(); const r = await go(paths, [item("b1")], h, "fallback"); const s = await since(m); assert.deepEqual(s.targets, [page("b1"), cdn("b1")]); const cdnArgs = s.spawned[1]; // ffmpeg, read the way the site's player reads it: the page's Referer AND Origin, // a browser user agent, an input seek to the window (ranged requests), the window's length. assert.equal(cdnArgs[cdnArgs.indexOf("-headers") + 1], "Referer: https://odysee.com/\r\nOrigin: https://odysee.com\r\n"); assert.equal(cdnArgs[cdnArgs.indexOf("-user_agent") + 1], storedMediaUserAgent()); assert.ok(cdnArgs.indexOf("-ss") < cdnArgs.indexOf("-i"), "an input seek: only the window's bytes are fetched"); assert.equal(cdnArgs[cdnArgs.indexOf("-ss") + 1], "10.00"); assert.equal(cdnArgs[cdnArgs.indexOf("-t") + 1], "10.00"); assert.equal(r.fetched.length, 1); assert.deepEqual(r.storedUrl.map((i) => i.id), ["b1"]); assert.equal(r.failed.length, 0); assert.equal(r.stopped, undefined, "nothing left over: the run did what it was asked"); // The CDN URL is no platform's: the probe ran because the PAGE is Odysee's. assert.equal(detectPlatform(cdn("b1")), null); assert.equal(s.probes, 1); const p = await provenanceOf(dir); assert.equal(p?.source, "stored-media-url"); assert.equal(p?.sourceHost, "player.odycdn.com"); assert.deepEqual(p?.audioCheck, { verdict: "clean", attempts: 1 }); assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]], "the lookup's backoff is still signalled"); assert.deepEqual(h.rec.cleans, [], "a stored-URL success does not record the platform clean"); assert.deepEqual(h.rec.sleeps, [1000], "the gap before the fallback fetch"); assert.match(h.rec.logs.join(""), /cut from the stored media URL \(player\.odycdn\.com\) — odysee lookup rate-limited/); }); test("fallback, after the 429: stored-URL items go straight to the CDN; one without a stored URL is left for later", async () => { const paths = await corpus(); await record(paths, "o", "c1", odyseeInfo("c1")); await record(paths, "o", "c2", odyseeInfo("c2")); await record(paths, "o", "c3", null); await record(paths, "o", "c4", odyseeInfo("c4")); const h = harness(); const m = await marks(); const r = await go(paths, [item("c1"), item("c2"), item("c3"), item("c4")], h, "fallback"); const s = await since(m); assert.deepEqual(s.targets, [page("c1"), cdn("c1"), cdn("c2"), cdn("c4")], "the page asked once, never again"); assert.deepEqual(r.storedUrl.map((i) => i.id), ["c1", "c2", "c4"]); assert.deepEqual(r.notAttempted.map((i) => i.id), ["c3"]); assert.equal(r.stopped, "rate-limit"); assert.deepEqual(h.rec.sleeps, [1000, 1000, 1000], "the same gaps between fetches"); }); test("fallback: a page 429 on an item with no stored URL fails it; the stored-URL items after it go on", async () => { const paths = await corpus(); await record(paths, "o", "d1", null); await record(paths, "o", "d2", odyseeInfo("d2")); const h = harness(); const m = await marks(); const r = await go(paths, [item("d1"), item("d2")], h, "fallback"); const s = await since(m); assert.deepEqual(s.targets, [page("d1"), cdn("d2")]); assert.deepEqual(r.failed.map((f) => [f.item.id, f.class]), [["d1", "rate_limit"]]); assert.deepEqual(r.storedUrl.map((i) => i.id), ["d2"]); }); test("only: no page request at all", async () => { const paths = await corpus(); const dir = await record(paths, "o", "e1", odyseeInfo("e1")); await record(paths, "o", "e2", odyseeInfo("e2")); const h = harness(); const m = await marks(); const r = await go(paths, [item("e1"), item("e2")], h, "only"); const s = await since(m); assert.deepEqual(s.targets, [cdn("e1"), cdn("e2")]); assert.ok(!s.targets.some((t) => t.startsWith("https://odysee.com/"))); assert.equal(r.fetched.length, 2); assert.equal(s.probes, 2); assert.deepEqual(h.rec.backoffs, []); assert.deepEqual(h.rec.cleans, []); assert.deepEqual(h.rec.sleeps, [1000], "one gap between the two"); assert.match(h.rec.logs.join(""), /cut from the stored media URL \(player\.odycdn\.com\) \(asked: only\)/); assert.equal((await provenanceOf(dir))?.source, "stored-media-url"); }); for (const mode of ["only", "fallback"] as const) { test(`a held platform + ${mode}: items with a stored URL run; one without is left, and the run says held`, async () => { const paths = await corpus(); await record(paths, "o", "f1", odyseeInfo("f1")); await record(paths, "o", "f2", null); await record(paths, "o", "f3", odyseeInfo("f3")); const h = harness({ heldRefusal: async (p) => (p === "odysee" ? "odysee is held (test)" : null) }); const m = await marks(); const r = await go(paths, [item("f1"), item("f2"), item("f3")], h, mode); const s = await since(m); assert.deepEqual(s.targets, [cdn("f1"), cdn("f3")], "no page request while held"); assert.deepEqual(r.notAttempted.map((i) => i.id), ["f2"]); assert.equal(r.stopped, "held"); assert.match(h.rec.logs.join(""), /f2 10\.00–20\.00: not attempted — odysee is held \(test\), and it has no stored media URL/); if (mode === "fallback") { assert.match(h.rec.logs.join(""), /— odysee lookup held/); } }); } test("never + a held platform: stopped at the door, as today", async () => { const paths = await corpus(); await record(paths, "o", "g1", odyseeInfo("g1")); const h = harness({ heldRefusal: async () => "odysee is held (test)" }); const m = await marks(); const r = await go(paths, [item("g1")], h); assert.deepEqual((await since(m)).targets, []); assert.equal(r.stopped, "held"); }); test("a 429 from the stored URL itself stops the run", async () => { const paths = await corpus(); await record(paths, "o", "h1", odyseeInfo("h1", cdn("h1", "cdn429"))); await record(paths, "o", "h2", odyseeInfo("h2")); const h = harness(); const r = await go(paths, [item("h1"), item("h2")], h, "only"); assert.equal(r.stopped, "rate-limit"); assert.deepEqual(r.notAttempted.map((i) => i.id), ["h2"]); assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]]); }); test("an off-allowlist platform's stored URL is ignored: fetched from its page", async () => { const paths = await corpus(); const yt = "https://www.youtube.com/watch?v=synthetic01"; const dir = await record(paths, "y", "synthetic01", { webpage_url: yt, formats: [{ url: cdn("synthetic01"), protocol: "https" }], }); const h = harness(); const m = await marks(); const r = await go(paths, [item("synthetic01", "y", yt)], h, "only"); assert.deepEqual((await since(m)).targets, [yt]); assert.equal(r.fetched.length, 1); assert.deepEqual(r.storedUrl, []); assert.equal((await provenanceOf(dir))?.source, undefined); assert.deepEqual(h.rec.cleans, ["youtube"]); }); test("a stored URL off the platform's CDN host is ignored: the page is asked (and 429s)", async () => { const paths = await corpus(); await record(paths, "o", "i1", odyseeInfo("i1", "https://cdn.example.net/v6/streams/i1/f0.mp4")); const h = harness(); const m = await marks(); const r = await go(paths, [item("i1")], h, "only"); assert.deepEqual((await since(m)).targets, [page("i1")]); assert.equal(r.failed[0]?.class, "rate_limit"); assert.deepEqual(r.storedUrl, []); }); test("a find-copy item (another recording's URL) never uses the stored URL", async () => { const paths = await corpus(); await record(paths, "o", "j1", odyseeInfo("j1")); const h = harness(); const m = await marks(); // On the allowlisted platform itself, so only the copy guard keeps it off the CDN. const copyUrl = "https://odysee.com/@mirror:2/stream-j1:j1"; await go(paths, [{ ...item("j1", "o", copyUrl), copy: { from: "archive.org", url: copyUrl } }], h, "only"); assert.deepEqual((await since(m)).targets, [copyUrl]); }); test("the editor's door: no refusal runs all; never refuses all; a mode runs only the stored-URL items", () => { const has = (n: number) => n % 2 === 0; assert.deepEqual(storedUrlDoor([1, 2, 3, 4], null, "never", has), { run: [1, 2, 3, 4], refused: [] }); assert.deepEqual(storedUrlDoor([1, 2, 3, 4], "held", "never", has), { run: [], refused: [1, 2, 3, 4] }); assert.deepEqual(storedUrlDoor([1, 2, 3, 4], "held", "only", has), { run: [2, 4], refused: [1, 3] }); assert.deepEqual(storedUrlDoor([1, 3], "held", "fallback", has), { run: [], refused: [1, 3] }); });