// The stored-URL clip cut opens the player's page first and shares the // platform's stored-URL gap with full downloads (release 32 R9). // // A fake ffmpeg (a node script: one ranged GET of its `-i` URL with the // `-headers` it was given, the bytes written to the output; "HTTP error 429" and // exit 1 on a refusal) against the fake CDN on loopback, whose `requireUnlock` // models 2026-10-17's finding: every read answers 429 until a player opened the // video's page. The opener is injected; no test launches a browser or reaches // the network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/fetchWindowStoredCut.test.ts import { test, beforeEach } 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 { FetchWindowError, fetchWindowManaged, type FetchWindowOpts } from "./fetchWindowManaged"; import { newStoredPageSession, type PageOpener } from "./storedUrlPageOpen"; import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; import { clearStoredUrlFiles, noteStoredUrlRead, storedUrlLastFile } from "../jobs/storedUrlPace"; import { storedUrlGapKey, type StoredMediaUrl } from "../lib/storedMediaUrl"; import { listClipWindows } from "../lib/clipWindow-server"; import { fetchWindows } from "../controller/fetchWindows"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; // The exact gaps: the jitter on them is tested in lib/jitter.test.ts and // beside each wait (E2E_PACING_JITTER, lib/envVars.ts). process.env.E2E_PACING_JITTER = "0"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "storedcut-")); const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); await writeFile( FFMPEG, `#!/usr/bin/env node import { writeFileSync } from "node:fs"; const args = process.argv.slice(2); const out = args[args.length - 1]; // The audio check's probe writes to /dev/null: a clean verdict. if (out === "/dev/null") process.exit(0); const url = args[args.indexOf("-i") + 1]; const headers = {}; for (const line of (args[args.indexOf("-headers") + 1] ?? "").split("\\r\\n")) { const m = /^([^:]+):\\s*(.*)$/.exec(line); if (m) headers[m[1]] = m[2]; } headers["User-Agent"] = args[args.indexOf("-user_agent") + 1]; headers.Range = "bytes=0-1023"; const res = await fetch(url, { headers }); if (res.status !== 206 && res.status !== 200) { process.stderr.write(\`[https @ 0x1] HTTP error \${res.status} \${res.status === 429 ? "Too Many Requests" : "Forbidden"}\\n\${url}: Server returned \${res.status}\\n\`); process.exit(1); } writeFileSync(out, Buffer.from(await res.arrayBuffer())); `, ); await chmod(FFMPEG, 0o755); const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; const PAGE = `https://odysee.com/@synthetic:1/a-synthetic-stream:${CLAIM.slice(0, 1)}`; const FILE_PATH = `/v6/streams/${CLAIM}/sd0.mp4`; const BODY = Buffer.alloc(64 * 1024, 7); let n = 0; async function videoDir(): Promise { const d = path.join(ROOT, `case-${++n}`, "data", CLAIM); await mkdir(d, { recursive: true }); return d; } function storedOf(cdn: FakeRangedCdn, p = FILE_PATH): StoredMediaUrl & { why: "only" } { return { url: `${cdn.base}${p}`, host: "player.odycdn.com", platform: "odysee", referer: "https://odysee.com/", why: "only" }; } function opts(dir: string, cdn: FakeRangedCdn, extra: Partial = {}): FetchWindowOpts { return { channelSlug: "c", channelConfig: {} as ChannelConfig, paths: { ffmpegBin: FFMPEG } as unknown as Paths, videoDir: dir, videoId: CLAIM, videoUrl: PAGE, storedMedia: storedOf(cdn), from: 10, to: 20, provenance: { requestedBy: "test" }, onLog: () => {}, signal: new AbortController().signal, corruptRetryGapMs: 0, ...extra, }; } // An opener that unlocks the fake CDN, as a player's page view does. function unlocking(cdn: FakeRangedCdn, pages: string[]): PageOpener { return async ({ pageUrl }) => { pages.push(pageUrl); cdn.unlock(); return { ok: true, mediaStatuses: [206] }; }; } beforeEach(() => { clearPlatformGaps(); clearStoredUrlFiles(); }); test("the cut opens the video's page first, then cuts; the window records the open", async () => { const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true }); try { const pages: string[] = []; const dir = await videoDir(); const res = await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: { openPage: unlocking(cdn, pages), gapMs: 0 } })); assert.deepEqual(pages, [PAGE], "the PAGE url, once"); assert.equal(res.bytes, 1024); const prov = (await listClipWindows(dir))[0]?.provenance; assert.equal(prov?.source, "stored-media-url"); assert.equal(prov?.pageOpens, 1); const read = cdn.requests.find((r) => r.status === 206); assert.equal(read?.referer, "https://odysee.com/"); } finally { await cdn.close(); } }); test("a run's page state: a second window of the same video opens nothing and owes no stored-URL gap", async () => { const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true }); try { const pages: string[] = []; const waits: number[] = []; const sleep = async (ms: number) => { waits.push(ms); clearPlatformGaps(); }; const pageSession = newStoredPageSession(); const cut = { pageSession, openPage: unlocking(cdn, pages), gapMs: 60_000, sleep }; const dir = await videoDir(); await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut })); const second = await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut, from: 40, to: 50 })); assert.deepEqual(pages, [PAGE], "opened before the first cut only"); assert.deepEqual(waits, [], "the same file read last: no stored-URL gap"); assert.equal(second.provenance?.pageOpens, undefined, "the second cut opened nothing"); assert.equal(pageSession.opens, 1); } finally { await cdn.close(); } }); test("a 429 after a cut served since the open opens the page again and cuts once more", async () => { // The unlock lapses after one cut's bytes. const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true, unlockBytes: 1024 }); try { const pages: string[] = []; const log = { s: "" }; const cut = { pageSession: newStoredPageSession(), openPage: unlocking(cdn, pages), gapMs: 0 }; const dir = await videoDir(); await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut })); const second = await fetchWindowManaged( opts(dir, cdn, { storedUrlCut: cut, from: 40, to: 50, onLog: (s) => (log.s += s) }), ); assert.equal(pages.length, 2); assert.equal(second.provenance?.pageOpens, 1); assert.match(log.s, /HTTP Error 429 from player\.odycdn\.com after 1 cut\(s\) since the page was opened; opening it again/); } finally { await cdn.close(); } }); test("a 429 straight after an open is a rate limit: no second open, the backoff recorded", async () => { const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true }); try { const pages: string[] = []; const backoffs: string[] = []; // An open that does NOT unlock (the CDN still refuses). const openPage: PageOpener = async ({ pageUrl }) => { pages.push(pageUrl); return { ok: false, mediaStatuses: [429], error: "the player's media requests were not served" }; }; const err = await fetchWindowManaged( opts(await videoDir(), cdn, { storedUrlCut: { openPage, gapMs: 0 }, onPlatformBackoff: (c) => { backoffs.push(c); }, }), ).then( () => null, (e: unknown) => e, ); assert.ok(err instanceof FetchWindowError); assert.equal(err.failureClass, "rate_limit"); assert.deepEqual(pages, [PAGE], "never twice in a row"); assert.deepEqual(backoffs, ["rate_limit"]); } finally { await cdn.close(); } }); test("one gap: a cut of a new file waits out a full download's rest, and sets the rest a download waits", async () => { const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY } }); try { const waits: number[] = []; const log = { s: "" }; const sleep = async (ms: number) => { waits.push(ms); clearPlatformGaps(); }; // A full download of ANOTHER file on the platform just ended. noteStoredUrlRead("odysee", "https://player.odycdn.com/v6/streams/other/sd.mp4", 60_000); await fetchWindowManaged( opts(await videoDir(), cdn, { storedUrlCut: { openPage: null, gapMs: 60_000, sleep }, onLog: (s) => (log.s += s), }), ); assert.equal(waits.length, 1); assert.ok(waits[0] > 55_000 && waits[0] <= 60_000); assert.match(log.s, /A cut from the stored media URL \(odysee\) asks for a gap between videos: waiting \d+s/); // …and the cut set the rest the next download reads. assert.ok(platformGapRemainingMs(storedUrlGapKey("odysee")) > 55_000); assert.equal(storedUrlLastFile("odysee"), storedOf(cdn).url); } finally { await cdn.close(); } }); test("a page cut (no stored URL) opens no page and touches no stored-URL gap", async () => { const ytdlp = path.join(ROOT, "fake-ytdlp.mjs"); await writeFile( ytdlp, `#!/usr/bin/env node import { writeFileSync } from "node:fs"; const a = process.argv.slice(2); writeFileSync(a[a.indexOf("-o") + 1], "mp4"); `, ); await chmod(ytdlp, 0o755); const pages: string[] = []; const dir = await videoDir(); const res = await fetchWindowManaged({ channelSlug: "c", channelConfig: { audioCheck: { enabled: false } } as ChannelConfig, paths: { ytdlpBin: ytdlp, ffmpegBin: FFMPEG } as unknown as Paths, videoDir: dir, videoId: CLAIM, videoUrl: PAGE, from: 10, to: 20, provenance: { requestedBy: "test" }, onLog: () => {}, signal: new AbortController().signal, storedUrlCut: { openPage: async ({ pageUrl }) => { pages.push(pageUrl); return { ok: true, mediaStatuses: [] }; }, }, }); assert.deepEqual(pages, []); assert.equal(platformGapRemainingMs(storedUrlGapKey("odysee")), 0); assert.equal(await readFile(res.file, "utf8"), "mp4"); }); test("fetch-windows hands every stored-URL cut of one run the same page state", async () => { const seen: unknown[] = []; const paths = { channelsDir: path.join(ROOT, "channels") } as unknown as Paths; for (const id of ["a", "b"]) await mkdir(path.join(ROOT, "channels", "ody", "data", id), { recursive: true }); const result = await fetchWindows({ paths, items: [ { slug: "ody", id: "a", from: 1, to: 2 }, { slug: "ody", id: "a", from: 5, to: 6 }, { slug: "ody", id: "b", from: 1, to: 2 }, ], provenance: { requestedBy: "test" }, gapMs: 0, storedUrl: "only", deps: { getSettings: () => ({ sleepBetweenDownloadsSeconds: 0 }) as never, readChannelConfig: async () => ({ platform: "odysee" }) as ChannelConfig, assertTextReadable: async () => {}, savedWindowSource: async () => ({ kind: "none" }) as never, findVideoSourceUrl: async (_p, _s, id) => `https://odysee.com/@x:1/${id}:1`, storedMediaUrl: async (dir) => ({ url: `https://player.odycdn.com/v6/streams/${path.basename(dir)}/sd.mp4`, host: "player.odycdn.com", platform: "odysee", referer: "https://odysee.com/", }), heldRefusal: async () => null, cooldownRemainingMs: async () => 0, recordBackoff: async () => {}, recordClean: async () => null, gapRemainingMs: () => 0, noteGap: () => {}, sleep: async () => {}, fetchWindow: async (o) => { seen.push(o.storedUrlCut?.pageSession); return { file: "x", from: o.from, to: o.to, bytes: 1, cached: false, provenance: null }; }, }, }); assert.equal(result.storedUrl.length, 3); assert.equal(seen.length, 3); assert.ok(seen[0], "a page state is passed"); assert.ok(seen.every((s) => s === seen[0]), "one page state for the run"); });