import test from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm -C editor exec tsx --test "app/api/media/fetch-window/route.storedUrl.test.ts" // // `storedUrl` on the single-window route (release 32 R6) — the fetch-windows // batch's rule for one window. yt-dlp and ffmpeg are fakes (YTDLP_BIN, // FFMPEG_BIN): an odysee.com page answers 429, a cut from an http input is // written. In order: a fallback with the platform answering (the page 429s, the // window is cut from the stored URL — and the 429 leaves Odysee cooling), then // the cooling platform: never refuses, fallback without a stored URL refuses, // only and fallback with one cut it without asking the page. const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-stored-")); const SLUG = "demo-odysee"; const ARGS_LOG = path.join(ROOT, "argv.jsonl"); const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); await writeFile( YTDLP, `#!/usr/bin/env node import { appendFileSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n"); const url = args[args.length - 1]; if (url.startsWith("https://odysee.com/")) { process.stderr.write("ERROR: [lbry] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n"); process.exit(1); } writeFileSync(args[args.indexOf("-o") + 1], "mp4"); `, ); 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(${JSON.stringify(ARGS_LOG)}, JSON.stringify([...args, input]) + "\\n"); writeFileSync(args[args.length - 1], "mp4"); } process.exit(0); `, ); await chmod(YTDLP, 0o755); await chmod(FFMPEG, 0o755); process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.YTDLP_BIN = YTDLP; process.env.FFMPEG_BIN = FFMPEG; // NO BROWSER, HOWEVER THIS FILE IS RUN. The real player-page opener stays off // under `node --test` (NODE_TEST_CONTEXT), but a bare `tsx ` sets no such // thing, and this file's stored-URL cuts then opened odysee.com in headless // Chromium. With a (empty) page fixture named, the opener opens nothing. process.env.E2E_ODYSEE_PAGE_FIXTURE = path.join(ROOT, "odysee-pages.json"); await writeFile(process.env.E2E_ODYSEE_PAGE_FIXTURE, "{}"); // The fallback's pause, as on the e2e server. process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); await writeFile( path.join(ROOT, "channels", SLUG, "config.json"), JSON.stringify({ name: "Demo", handling: "youtube", url: "https://odysee.com/@demo", platform: "odysee" }), ); const page = (id: string) => `https://odysee.com/@demo:1/stream-${id}:${id}`; const cdn = (id: string) => `https://player.odycdn.com/v6/streams/${id}/f0.mp4`; async function video(id: string, withStored: boolean): Promise { const dir = path.join(ROOT, "channels", SLUG, "data", id); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "metadata.info.json"), JSON.stringify({ id, webpage_url: page(id), ...(withStored ? { formats: [{ format_id: "original", url: cdn(id), protocol: "https", ext: "mp4" }] } : {}), }), ); return dir; } const S1 = await video("s1", true); const S2 = await video("s2", true); await video("n1", false); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); // The jobs' ends still write after their status reads done — the sidecars, and // the report regeneration each end arms (snapshot.json in the channel dir): all // of it is waited for before the corpus is removed. test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); }); function post(body: Record): Promise { return POST( new Request("http://localhost/api/media/fetch-window", { method: "POST", headers: { authorization: "Bearer test-token", "content-type": "application/json" }, body: JSON.stringify(body), }), ); } const ask = (videoId: string, extra: Record = {}) => post({ channelSlug: SLUG, videoId, requestedBy: "test", from: 1, to: 3, ...extra }); const targets = async () => (await readFile(ARGS_LOG, "utf8").catch(() => "")) .trim() .split("\n") .filter(Boolean) .map((l) => (JSON.parse(l) as string[]).at(-1)); // The job's end, its sidecar written — bounded by the job's own end, not a // fixed number of polls a loaded machine can outlast. const settle = (jobId: string) => settleJob(jobId); test("a storedUrl that is not a mode is refused with 400", async () => { const res = await ask("s1", { storedUrl: "always" }); assert.equal(res.status, 400); assert.match(((await res.json()) as { error: string }).error, /storedUrl must be one of "never", "fallback", "only"/); }); test("fallback, the platform answering: the page 429s, then the window is cut from the stored URL", async () => { const res = await ask("s1", { storedUrl: "fallback" }); assert.equal(res.status, 202); const { jobId } = (await res.json()) as { jobId: string }; assert.equal(await settle(jobId), "done"); assert.equal(getRegistry().get(jobId)?.spec?.params?.storedUrl, "fallback", "a Retry keeps the mode"); assert.deepEqual(await targets(), [page("s1"), cdn("s1")], "the page first, then the stored file"); const sidecar = JSON.parse(await readFile(path.join(S1, "clips", "1.00-3.00.json"), "utf8")); assert.equal(sidecar.source, "stored-media-url"); assert.equal(sidecar.sourceHost, "player.odycdn.com"); }); test("never (the default), the platform cooling after that 429: refused with 409", async () => { const res = await ask("s2"); assert.equal(res.status, 409); const body = (await res.json()) as { error: string; platform: string }; assert.equal(body.platform, "odysee"); assert.match(body.error, /rate-limit cooldown/); }); test("fallback with no stored URL, the platform cooling: refused as before", async () => { const res = await ask("n1", { storedUrl: "fallback" }); assert.equal(res.status, 409); }); test("only, the platform cooling: cut from the stored URL with no page request", async () => { const before = (await targets()).length; const res = await ask("s2", { storedUrl: "only" }); assert.equal(res.status, 202); const { jobId } = (await res.json()) as { jobId: string }; assert.equal(await settle(jobId), "done"); assert.deepEqual((await targets()).slice(before), [cdn("s2")]); const sidecar = JSON.parse(await readFile(path.join(S2, "clips", "1.00-3.00.json"), "utf8")); assert.equal(sidecar.source, "stored-media-url"); });