// downloadOneManaged with a stored media URL (release 32 R7): `only`, // `fallback` after a rate-limited prefetch or download, no stored URL, the gap // between two files, a mid-file 429, and the corrupt-full-source refetch. A // fake yt-dlp (a shell script) and a fake CDN on loopback; real ffmpeg for the // probes and extraction (skipped without it). No real network. import test from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Paths } from "../lib/paths"; import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; import { askedPlatform, storedUrlAttemptOf } from "../lib/downloadOutcome"; import { fullAudioAttemptsOf } from "../lib/fullAudioFirst"; import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; import { storedUrlGapKey } from "../lib/storedMediaUrl"; import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged"; // 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 FF = hasFfmpeg(); const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`; const PAGE = `https://odysee.com/synthetic-stream:${CLAIM}`; const FAST = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 }; type Fixture = { root: string; channelsDir: string; channelDir: string; videoDir: string; ytdlpLog: string; paths: Paths; cdn: FakeRangedCdn; clean: Buffer; }; // A fake yt-dlp: logs its argv; `prefetch` / `download` say how each pass ends. async function fixture(opts: { prefetch?: "ok" | "429"; download?: "ok" | "429"; formats?: unknown[]; cdn?: Parameters[0]; } = {}): Promise { const root = await mkdtemp(path.join(os.tmpdir(), "stored-managed-")); const channelsDir = path.join(root, "channels"); const channelDir = path.join(channelsDir, "c"); const videoDir = path.join(channelDir, "data", CLAIM); await mkdir(videoDir, { recursive: true }); const clean = FF ? await readFile(makeToneFile(path.join(root, "src.mp4"), { duration: 60, faststart: true })) : Buffer.alloc(1); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, ...(opts.cdn ?? {}) }); await writeFile( path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: CLAIM, extractor: "lbry", extractor_key: "LBRY", title: "A synthetic stream", webpage_url: PAGE, duration: 60, formats: opts.formats ?? [{ url: cdn.url(FILE_PATH), protocol: "https", ext: "mp4" }], }), ); const ytdlpLog = path.join(root, "ytdlp.log"); const bin = path.join(root, "fake-ytdlp.sh"); const line429 = `echo "WARNING: [lbry] ${CLAIM}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; echo "ERROR: [lbry] ${CLAIM}: No video formats found!" >&2; exit 1`; await writeFile( bin, `#!/bin/sh\necho "$@" >> ${JSON.stringify(ytdlpLog)}\n` + `case "$*" in *--skip-download*) ${opts.prefetch === "429" ? line429 : "exit 0"} ;; esac\n` + `${opts.download === "429" ? line429 : "exit 0"}\n`, ); await chmod(bin, 0o755); const paths = { channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; return { root, channelsDir, channelDir, videoDir, ytdlpLog, paths, cdn, clean }; } async function ytdlpCalls(f: Fixture): Promise { return (await readFile(f.ytdlpLog, "utf8").catch(() => "")).split("\n").filter(Boolean); } function run(f: Fixture, over: Partial = {}, log: { s: string } = { s: "" }) { return downloadOneManaged({ channelSlug: "c", channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth:1", audioFormat: "mp3" } as ChannelConfig, paths: f.paths, videoUrl: PAGE, onLog: (s) => (log.s += s), signal: new AbortController().signal, storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, openPage: null }, ...over, }); } async function done(f: Fixture) { clearPlatformGaps(); await f.cdn.close(); await rm(f.root, { recursive: true, force: true }); } async function readOutcome(dir: string): Promise { return JSON.parse(await readFile(path.join(dir, "download-outcome.json"), "utf8")); } test("only: the whole file from the stored URL — no yt-dlp, the audio check, the archive line, the sidecar", { skip: !FF }, async () => { const f = await fixture(); try { const log = { s: "" }; const record = await run(f, { storedUrl: "only" }, log); assert.equal(record.status, "ok-audio-checked", log.s); assert.deepEqual(await ytdlpCalls(f), [], "yt-dlp was never run"); assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); const st = storedUrlAttemptOf(record); assert.equal(st?.why, "only"); assert.equal(st?.host, "player.odycdn.com"); assert.equal(st?.bytes, f.clean.length); assert.equal(record.attempts[0].audioCheck?.finalProbeVerdict, "clean"); assert.equal(askedPlatform(record), false); assert.match(log.s, /from the stored media URL \(player\.odycdn\.com\) \(asked: only\)/); assert.equal((await readOutcome(f.videoDir)).status, "ok-audio-checked"); assert.equal(await readFile(path.join(f.channelDir, "archive"), "utf8"), `lbry ${CLAIM}\n`); const entries = await readdir(f.videoDir); assert.ok(entries.includes("audio.mp3")); assert.ok(!entries.includes("audio.mp4"), "the container is not kept"); } finally { await done(f); } }); test("the channel's storedUrlDownloads is the default; a request's storedUrl overrides it", { skip: !FF }, async () => { const f = await fixture(); try { const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "only" } as ChannelConfig; const a = await run(f, { channelConfig: cfg }); assert.equal(storedUrlAttemptOf(a)?.why, "only"); assert.deepEqual(await ytdlpCalls(f), []); const b = await run(f, { channelConfig: cfg, storedUrl: "never" }); assert.ok((await ytdlpCalls(f)).length > 0, "never: the page, as always"); assert.equal(storedUrlAttemptOf(b), null); } finally { await done(f); } }); test("fallback: a rate-limited prefetch goes to the stored URL; the record says why", { skip: !FF }, async () => { const f = await fixture({ prefetch: "429" }); try { const log = { s: "" }; const record = await run(f, { storedUrl: "fallback" }, log); assert.equal(record.status, "ok-audio-checked", log.s); assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "stored-url-ranged"]); assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); assert.equal(askedPlatform(record), true); assert.equal((await ytdlpCalls(f)).length, 1, "only the prefetch asked the platform"); assert.match(log.s, /odysee lookup rate-limited/); // The metadata the prefetch could not refresh is the one the URL came from. const info = JSON.parse(await readFile(path.join(f.videoDir, "metadata.info.json"), "utf8")); assert.equal(info.id, CLAIM); } finally { await done(f); } }); test("fallback: a download yt-dlp got 429 on goes to the stored URL (the audio check off: it stays off)", { skip: !FF }, async () => { const f = await fixture({ download: "429" }); try { const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", audioCheck: { enabled: false }, } as ChannelConfig; const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); assert.equal(record.status, "ok"); assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "primary", "stored-url-ranged"]); assert.equal(record.attempts.at(-1)?.audioCheck, undefined); assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); } finally { await done(f); } }); test("fallback with no rate limit: the page download stands, the stored URL is never read", async () => { const f = await fixture(); try { const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", audioCheck: { enabled: false } } as ChannelConfig; const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); assert.equal(storedUrlAttemptOf(record), null); assert.equal(f.cdn.requests.length, 0); } finally { await done(f); } }); test("only, and the record stores no trusted media URL: a per-video failure, nothing asked", async () => { const f = await fixture({ formats: [ { url: "https://player.odycdn.com/a.mp4", protocol: "https" }, { url: "https://player.odycdn.com/b.mp4", protocol: "https" }, ], }); try { const log = { s: "" }; const record = await run(f, { storedUrl: "only" }, log); assert.equal(record.status, "failed"); assert.equal(record.failureClass, "per_video"); assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); assert.equal(askedPlatform(record), false); assert.deepEqual(await ytdlpCalls(f), []); assert.equal(f.cdn.requests.length, 0); assert.match(log.s, /Nothing was requested/); } finally { await done(f); } }); test("a 429 from the CDN mid-file: failed, rate_limit, the partial kept for the next run", { skip: !FF }, async () => { const f = await fixture({ cdn: { refuseAfterBytes: 40 * 1024 } }); try { const record = await run(f, { storedUrl: "only" }); assert.equal(record.status, "failed"); assert.equal(record.failureClass, "rate_limit"); assert.equal(storedUrlAttemptOf(record)?.httpStatus, 429); const entries = await readdir(f.videoDir); assert.ok(entries.includes("audio.mp4.stored.part")); // After the rest, the next run resumes and finishes. f.cdn.allowAgain(); const again = await run(f, { storedUrl: "only" }); assert.equal(again.status, "ok-audio-checked"); assert.ok((storedUrlAttemptOf(again)?.resumedFrom ?? 0) > 0); } finally { await done(f); } }); test("one new file per rest: the second stored-URL download on a platform waits out the gap", { skip: !FF }, async () => { const f = await fixture(); try { const waits: number[] = []; const sleep = async (ms: number) => { waits.push(ms); clearPlatformGaps(); }; const deps = { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 60_000, sleep, openPage: null }; const log = { s: "" }; await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); assert.deepEqual(waits, [], "the first asks no gap"); assert.ok(platformGapRemainingMs(storedUrlGapKey("odysee")) > 55_000, "the gap is set when it ends"); await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); assert.equal(waits.length, 1); assert.ok(waits[0] > 55_000 && waits[0] <= 60_000); assert.match(log.s, /A download from the stored media URL \(odysee\) asks for a gap between videos: waiting \d+s/); } finally { await done(f); } }); test("a corrupt full source refetched from the stored URL: clean, the kept file goes, the history says so", { skip: !FF }, async () => { const f = await fixture(); try { await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); const previous: DownloadOutcomeRecord = { videoId: CLAIM, webpageUrl: PAGE, status: "corrupt-full-source", startedAt: "2026-10-15T00:00:00.000Z", finishedAt: "2026-10-15T01:00:00.000Z", attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }], }; await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); const record = await run(f, { storedUrl: "only", corruptRefetchDeps: { measure: async () => null }, }); assert.equal(record.status, "ok-audio-checked"); const disk = await readOutcome(f.videoDir); assert.equal(disk.corruptRefetches?.at(-1)?.result, "clean"); const entries = await readdir(f.videoDir); assert.ok(entries.includes("audio.mp3")); assert.ok(!entries.some((e) => e.endsWith(".corrupt-kept")), "the kept file is gone"); } finally { await done(f); } }); test("the managed download opens the player's page (the injected opener) and records it", { skip: !FF }, async () => { const f = await fixture({ cdn: { requireUnlock: true } }); try { const pages: string[] = []; const record = await run(f, { storedUrl: "only", storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, openPage: async ({ pageUrl }) => { pages.push(pageUrl); f.cdn.unlock(); return { ok: true, mediaStatuses: [206] }; }, }, }); assert.equal(record.status, "ok-audio-checked"); assert.deepEqual(pages, [PAGE], "the PAGE url, once"); assert.equal(storedUrlAttemptOf(record)?.pageOpens, 1); } finally { await done(f); } }); // Release 32 R10: a dropped connection is a continuation of the same file // inside the one call — not a new file (no 20-minute rest) and not another // attempt on the record. test("drops mid-file inside one managed download: one attempt, its continuations, no new-file rest waited", { skip: !FF }, async () => { const f = await fixture({ cdn: { dropAfterBytes: 24 * 1024, drops: 2 } }); try { const waits: number[] = []; const log = { s: "" }; const record = await run( f, { storedUrl: "only", storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 64 * 1024, knobs: FAST, // A rest that would show if a continuation waited it out. gapMs: 60_000, dropPauseMs: 777, sleep: async (ms: number) => { waits.push(ms); }, openPage: async () => ({ ok: true, mediaStatuses: [206] }), }, }, log, ); assert.equal(record.status, "ok-audio-checked", log.s); assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"], "one attempt"); const st = storedUrlAttemptOf(record); assert.equal(st?.continuations, 2); assert.equal(st?.pageOpens, 3); assert.equal(st?.bytes, f.clean.length); assert.deepEqual(waits, [777, 777], "the continuations' pauses, and no rest"); assert.match(log.s, /Connection dropped at \d+ bytes — reopening the page and resuming \(1 of 6\)/); } finally { await done(f); } }); test("a run exhausted by drops after progress is ONE full-audio attempt on the corrupt record (R8's count)", { skip: !FF }, async () => { const f = await fixture({ cdn: { dropAfterBytes: 40 * 1024, drops: Infinity, dropGapBytes: 0 } }); try { await corruptPrevious(f, 0); const record = await run(f, { corruptRefetchDeps: { measure: async () => null }, storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, dropPauseMs: 0, openPage: null }, }); assert.equal(record.status, "failed"); assert.equal(record.failureClass, "network"); const st = storedUrlAttemptOf(record); assert.equal(st?.continuations, 6); assert.ok((st?.bytes ?? 0) > 0, "it made progress before the drops"); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "corrupt-full-source", "the bucket stays"); assert.equal(fullAudioAttemptsOf(disk), 1, "one attempt, however many continuations"); assert.ok((await readdir(f.videoDir)).includes("audio.mp4.stored.part"), "the partial is kept for the next attempt"); } finally { await done(f); } }); // Release 32 R8 — FULL AUDIO BEFORE A SALVAGE: a corrupt full source's refetch // reads the stored URL by itself (no storedUrl asked, none on the channel) // until FULL_AUDIO_ATTEMPTS stored-URL downloads are on record; then the page, // as before. An explicit mode (request or channel) is left alone. async function corruptPrevious(f: Fixture, storedAttempts: number): Promise { await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); const previous: DownloadOutcomeRecord = { videoId: CLAIM, webpageUrl: PAGE, status: "corrupt-full-source", startedAt: "2026-10-15T00:00:00.000Z", finishedAt: "2026-10-15T01:00:00.000Z", attempts: [ { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, ...Array.from({ length: storedAttempts }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })), ], }; await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); } test("full audio first: a corrupt full source's refetch reads the stored URL by itself while attempts are owed", { skip: !FF }, async () => { const f = await fixture(); try { await corruptPrevious(f, 0); const log = { s: "" }; const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }, log); assert.equal(record.status, "ok-audio-checked", log.s); assert.deepEqual(await ytdlpCalls(f), [], "no page request"); assert.match(log.s, /Full audio first \(full audio attempts: 0 of 2\): this refetch reads the stored media URL/); assert.equal(storedUrlAttemptOf(record)?.why, "only"); } finally { await done(f); } }); test("full audio first: a refused attempt is counted on the corrupt record; once the attempts are made the refetch asks the page", { skip: !FF }, async () => { const f = await fixture({ cdn: { refuseAfterBytes: 0 } }); try { await corruptPrevious(f, 1); const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }); assert.equal(record.status, "failed"); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "corrupt-full-source", "the bucket stays"); assert.equal(disk.attempts.filter((a) => a.kind === "stored-url-ranged").length, 2, "the attempt is on record"); assert.deepEqual(await ytdlpCalls(f), []); // Two on record: the next refetch is the page's, as before R8. const cdnBefore = f.cdn.requests.length; await run(f, { corruptRefetchDeps: { measure: async () => null } }); assert.ok((await ytdlpCalls(f)).length > 0, "the page is asked"); assert.equal(f.cdn.requests.length, cdnBefore, "the stored URL is not read again"); } finally { await done(f); } }); test("full audio first: an explicit mode (the request's never, the channel's) is left alone", { skip: !FF }, async () => { const f = await fixture(); try { await corruptPrevious(f, 0); await run(f, { storedUrl: "never", corruptRefetchDeps: { measure: async () => null } }); assert.ok((await ytdlpCalls(f)).length > 0, "never: the page"); assert.equal(f.cdn.requests.length, 0); } finally { await done(f); } const g = await fixture(); try { await corruptPrevious(g, 0); const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } as ChannelConfig; await run(g, { channelConfig: cfg, corruptRefetchDeps: { measure: async () => null } }); assert.ok((await ytdlpCalls(g)).length > 0, "the channel's never: the page"); assert.equal(g.cdn.requests.length, 0); } finally { await done(g); } });