// The stored-URL ranged download (release 32 R7) against a fake CDN on // loopback (testing/web/fakeRangedCdn.mjs) and a synthetic recording // (testing/audio/corruptAudio.mjs). Real ffmpeg for the probes and the // extraction; skipped without it. No real network. import test from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, readdir, rm, writeFile, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { corruptBytes, hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; import { startFakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Paths } from "../lib/paths"; import { storedMediaUrlFromInfo } from "../lib/storedMediaUrl"; import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import { STORED_URL_DROP_PAUSE_MS, STORED_URL_MAX_DROPS, storedContainerExt, storedPartNames, storedUrlDownload } from "./storedUrlDownload"; const FF = hasFfmpeg(); const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`; const PAGE = `https://odysee.com/@synth:1/synthetic-stream:${CLAIM}`; const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; const config = { handling: "transcribe", audioFormat: "mp3" } as ChannelConfig; // Every chunk past the first is probed (the cadence and the size gate at 0). const EVERY_CHUNK = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 }; async function recording(dir: string): Promise<{ clean: Buffer; bad: Buffer }> { const src = makeToneFile(path.join(dir, "src.mp4"), { duration: 60, faststart: true }); const badFile = corruptBytes(src, path.join(dir, "bad.mp4"), { fromFrac: 0.45, toFrac: 0.5 }); return { clean: await readFile(src), bad: await readFile(badFile) }; } function storedFor(url: string) { const s = storedMediaUrlFromInfo({ webpage_url: PAGE, formats: [{ url, protocol: "https", ext: "mp4" }] }); assert.ok(s, "the fake's URL passes the allowlist"); return s; } async function setup() { const root = await mkdtemp(path.join(os.tmpdir(), "stored-ranged-")); const videoDir = path.join(root, "data", CLAIM); await import("node:fs/promises").then((m) => m.mkdir(videoDir, { recursive: true })); return { root, videoDir }; } test("names: the container's extension is the URL's when it is media, else mp4", () => { assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.mp4"), "mp4"); assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.m4a"), "m4a"); assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc"), "mp4"); assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.exe"), "mp4"); assert.deepEqual(storedPartNames("https://player.odycdn.com/a/b.mp4"), { container: "audio.mp4", part: "audio.mp4.stored.part", state: "audio.mp4.stored.part.json", }); }); test("the whole file comes down in ranged reads with the player's headers, then audio.mp3; the container goes", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } }); try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 16 * 1024, knobs: EVERY_CHUNK }, }); assert.equal(r.kind, "ok", log); assert.equal(r.bytes, clean.length); assert.equal(r.totalBytes, clean.length); assert.equal(r.finalProbeVerdict, "clean"); assert.ok(r.checkpoints.some((c) => c.action === "advance")); assert.equal(r.rollbacks, 0); // Every read was ranged, sequential, with the player's headers. assert.ok(cdn.requests.length >= 4); let expect = 0; for (const q of cdn.requests) { assert.equal(q.status, 206); assert.match(q.range ?? "", new RegExp(`^bytes=${expect}-`)); assert.equal(q.referer, "https://odysee.com/"); assert.equal(q.origin, "https://odysee.com"); assert.equal(q.ua, storedMediaUserAgent()); expect += q.bytes; } const entries = (await readdir(videoDir)).sort(); assert.deepEqual(entries, ["audio.mp3"], "the container and the scratch are gone"); assert.match(log, /DLOM_PROGRESS status=finished downloaded=\d+ total=\d+/); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a 429 mid-file keeps the partial; the next run resumes from its last good byte and finishes", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, refuseAfterBytes: 40 * 1024 }); const stored = storedFor(cdn.url(FILE_PATH)); const run = () => storedUrlDownload({ paths, videoDir, stored, channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK }, }); try { const first = await run(); assert.equal(first.kind, "rate-limited"); assert.equal(first.httpStatus, 429); const names = storedPartNames(stored.url); const state = JSON.parse(await readFile(path.join(videoDir, names.state), "utf8")); assert.equal(state.url, stored.url); assert.equal(state.totalBytes, clean.length); const partSize = (await stat(path.join(videoDir, names.part))).size; assert.ok(state.goodBytes > 0 && state.goodBytes <= partSize, "a probed-clean prefix is recorded"); // After the rest. cdn.allowAgain(); const before = cdn.requests.length; const second = await run(); assert.equal(second.kind, "ok"); assert.equal(second.resumedFrom, state.goodBytes); assert.equal(cdn.requests[before].range, `bytes=${state.goodBytes}-${state.goodBytes + 8 * 1024 - 1}`); // keepSourceVideo: the container stays, byte-identical to the source. assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); assert.deepEqual((await readdir(videoDir)).sort(), ["audio.mp3", "audio.mp4"]); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a 403 stops the same way (the platform backs off)", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, refuseAfterBytes: 16 * 1024, refuseStatus: 403 }); try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: false, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024 }, }); assert.equal(r.kind, "rate-limited"); assert.equal(r.httpStatus, 403); // With the check off every written byte counts as good. const state = JSON.parse(await readFile(path.join(videoDir, "audio.mp4.stored.part.json"), "utf8")); assert.equal(state.goodBytes, r.bytes); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a malformed chunk is rolled back and read again; the file ends clean", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean, bad } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, corruptOnce: { path: FILE_PATH, buf: bad, from: Math.floor(clean.length * 0.45), to: Math.floor(clean.length * 0.5) }, }); try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK }, }); assert.equal(r.kind, "ok", log); assert.ok(r.rollbacks >= 1, "the malformed checkpoint rolled back"); assert.ok(r.checkpoints.some((c) => c.action === "rollback" && c.verdict === "malformed")); assert.match(log, /Checkpoint MALFORMED at \d+ bytes\. Rolling back to \d+ bytes/); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean, "the re-read bytes are the clean ones"); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a source malformed at every read: more rollbacks than allowed is failed-corrupt-source, the partial kept", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { bad } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: bad } }); try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: { ...EVERY_CHUNK, maxRollbacks: 1 } }, }); assert.equal(r.kind, "failed-corrupt-source"); assert.equal(r.rollbacks, 2); const entries = await readdir(videoDir); assert.ok(entries.includes("audio.mp4.stored.part")); assert.ok(entries.includes("audio.mp4.stored.part.json")); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("malformed past every checkpoint: the final probe re-reads once, then corrupt-full-source keeps the file", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { bad } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: bad } }); try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: (s) => (log += s), signal: new AbortController().signal, // No periodic probe at all: only the final one sees the damage. deps: { fetch: cdn.fetch, chunkBytes: 32 * 1024, knobs: { intervalMs: 3_600_000 } }, }); assert.equal(r.kind, "corrupt-full-source"); assert.equal(r.finalProbeVerdict, "malformed"); assert.match(log, /Re-reading from 0 bytes once before giving up/); assert.deepEqual(await readdir(videoDir), ["audio.mp4"], "the file is kept, no scratch"); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), bad); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a partial with no resume state (or another URL's) is discarded, never extended", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } }); const stored = storedFor(cdn.url(FILE_PATH)); try { await writeFile(path.join(videoDir, "audio.mp4.stored.part"), Buffer.alloc(5000, 7)); await writeFile( path.join(videoDir, "audio.mp4.stored.part.json"), JSON.stringify({ version: 1, url: "https://player.odycdn.com/other.mp4", totalBytes: 9, goodBytes: 5000 }), ); let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored, channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: false, pageUrl: PAGE, openPage: null, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 32 * 1024 }, }); assert.equal(r.kind, "ok"); assert.equal(r.resumedFrom, 0); assert.match(log, /Discarded audio\.mp4\.stored\.part/); assert.match(cdn.requests[0].range ?? "", /^bytes=0-/); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a cancel stops between reads with the partial kept", async () => { const { root, videoDir } = await setup(); const buf = Buffer.alloc(64 * 1024, 1); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: buf } }); const ac = new AbortController(); try { let reads = 0; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: false, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: ac.signal, deps: { fetch: async (u, i) => { reads++; if (reads === 3) ac.abort(); return cdn.fetch(u, i); }, chunkBytes: 8 * 1024, }, }); assert.equal(r.kind, "aborted"); const entries = await readdir(videoDir); assert.ok(entries.includes("audio.mp4.stored.part")); assert.ok(entries.includes("audio.mp4.stored.part.json")); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a CDN that ignores the range: the whole body is the file", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, ignoreRange: true }); try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK }, }); assert.equal(r.kind, "ok"); assert.equal(cdn.requests.length, 1); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a 404 is an http-error, nothing kept", async () => { const { root, videoDir } = await setup(); const cdn = await startFakeRangedCdn({ files: {} }); try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch }, }); assert.equal(r.kind, "http-error"); assert.equal(r.httpStatus, 404); assert.deepEqual(await readdir(videoDir), []); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); // The orchestrator's finding (2026-10-17): the CDN serves a file only after a // player opened its page. The opener is injected; no browser here. function fakeOpener(cdn: { unlock(): void }, calls: string[]) { return async ({ pageUrl, cdnHost }: { pageUrl: string; cdnHost: string }) => { calls.push(`${pageUrl} ${cdnHost}`); cdn.unlock(); return { ok: true, mediaStatuses: [206] }; }; } test("the player's page is opened before the first read; a locked CDN then serves the file", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true }); const calls: string[] = []; try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: fakeOpener(cdn, calls), onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 16 * 1024, knobs: EVERY_CHUNK }, }); assert.equal(r.kind, "ok"); assert.equal(r.pageOpens, 1); assert.deepEqual(calls, [`${PAGE} player.odycdn.com`]); assert.ok(cdn.requests.every((q) => q.status === 206), "no read before the open"); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("an unlock that lapses mid-file: the page is opened again and the read goes on", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true, unlockBytes: 24 * 1024 }); const calls: string[] = []; try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: fakeOpener(cdn, calls), onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK, dropPauseMs: 0 }, }); assert.equal(r.kind, "ok", log); assert.ok(r.pageOpens >= 3, `opened ${r.pageOpens}×`); // Each lapse made progress: the count never climbs past 1 (release 32 R10). assert.equal(r.continuations, r.pageOpens - 1); assert.doesNotMatch(log, /\(2 of \d+\)/); assert.match(log, /HTTP Error 429 at \d+ bytes after \d+ served since the page was opened — opening it again and resuming \(1 of 6\)/); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("an open that does not unlock: one open, then rate-limited — no loop of opens", async () => { const { root, videoDir } = await setup(); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: Buffer.alloc(64 * 1024, 3) }, requireUnlock: true }); let opens = 0; try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: config, audioFormat: "mp3", audioCheck: false, pageUrl: PAGE, openPage: async () => { opens++; return { ok: false, mediaStatuses: [429], error: "the player's media requests were not served" }; }, onLog: () => {}, signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024 }, }); assert.equal(r.kind, "rate-limited"); assert.equal(opens, 1); assert.equal(r.pageOpens, 1); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); // RELEASE 32 R10 — A DROPPED CONNECTION IS THE SAME FILE (2026-10-17: a // 3.3 GB file's ranged reads ended `fetch failed` at 344 MB, then again 100 MB // into the resume). The fake CDN cuts the socket mid-body or before any // response; the injected opener stands for the page; the pause is a recorded // fake. No browser, no real network. const M4A_PATH = `/v6/streams/${CLAIM}/d4e5f6.m4a`; test("the constants: a 45 s pause, 6 continuations without progress", () => { assert.equal(STORED_URL_DROP_PAUSE_MS, 45_000); assert.equal(STORED_URL_MAX_DROPS, 6); }); test("dropped mid-body three times: the same run pauses, reopens the page, resumes from the last clean byte, finishes", { skip: !FF }, async () => { const { root, videoDir } = await setup(); const { clean } = await recording(root); const cut = Math.floor(clean.length / 5); const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true, dropAfterBytes: cut, drops: 3 }); const calls: string[] = []; const pauses: number[] = []; try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(FILE_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "mp3", audioCheck: true, pageUrl: PAGE, openPage: fakeOpener(cdn, calls), onLog: (s) => (log += s), signal: new AbortController().signal, // Large reads, so each cut lands inside a body; at most 2 in a row // without progress — fewer than the drops, which each made progress. deps: { fetch: cdn.fetch, chunkBytes: 64 * 1024, knobs: EVERY_CHUNK, dropPauseMs: 1234, maxDrops: 2, sleep: async (ms) => { pauses.push(ms); }, }, }); assert.equal(r.kind, "ok", log); assert.equal(cdn.requests.filter((q) => q.dropped).length, 3, "the CDN cut three reads"); assert.equal(r.continuations, 3); assert.equal(r.pageOpens, 4, "the first open, then one per continuation"); assert.deepEqual(pauses, [1234, 1234, 1234], "one pause per continuation, nothing else waited"); assert.equal((log.match(/Connection dropped at \d+ bytes — reopening the page and resuming \(1 of 2\)/g) ?? []).length, 3, log); assert.doesNotMatch(log, /\(2 of 2\)/, "each drop made progress: the count starts again"); // Each read after a cut asks from where the partial stood once judged — // the probe brought forward found the bytes clean, so nothing re-read. let expect = 0; for (const q of cdn.requests) { assert.match(q.range ?? "", new RegExp(`^bytes=${expect}-`), JSON.stringify(cdn.requests)); expect += q.bytes; } assert.match(log, /resuming from \d+ bytes \(the last probed-clean byte\)/); assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean, "byte-identical to the source"); assert.deepEqual((await readdir(videoDir)).sort(), ["audio.mp3", "audio.mp4"], "no scratch left"); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("audio check off: a cut before any response (the fetch throws) and one mid-body, both resumed at the exact byte", async () => { const { root, videoDir } = await setup(); const buf = Buffer.alloc(96 * 1024); for (let i = 0; i < buf.length; i++) buf[i] = (i * 7) % 251; // The first cut falls on a request's first byte (24 KiB = three 8 KiB // reads): the fetch throws. The next, 20 KiB later, inside a body. const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 24 * 1024, drops: 2, dropGapBytes: 20 * 1024 }); try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(M4A_PATH)), channelConfig: { ...config, keepSourceVideo: true }, audioFormat: "m4a", audioCheck: false, pageUrl: PAGE, openPage: null, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 }, }); assert.equal(r.kind, "ok", log); assert.equal(r.continuations, 2); assert.equal(r.pageOpens, 0, "no opener: nothing opened"); assert.match(log, /Connection dropped at 24576 bytes — resuming \(1 of 6\): the ranged read at 24576 failed: fetch failed/); assert.match(log, /Connection dropped at 45056 bytes — resuming \(1 of 6\): the read at 40960 ended early at 45056/); assert.deepEqual(await readFile(path.join(videoDir, "audio.m4a")), buf); assert.deepEqual(await readdir(videoDir), ["audio.m4a"]); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("drops with no progress: after the limit the run gives up as network, the partial and its state kept", async () => { const { root, videoDir } = await setup(); const buf = Buffer.alloc(96 * 1024, 5); // 20 KiB come down, then every request is cut before its first byte. const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 20 * 1024, drops: Infinity, dropGapBytes: 0 }); const opens: number[] = []; try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(M4A_PATH)), channelConfig: config, audioFormat: "m4a", audioCheck: false, pageUrl: PAGE, openPage: async () => { opens.push(1); return { ok: true, mediaStatuses: [206] }; }, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 }, }); assert.equal(r.kind, "network", log); assert.equal(r.bytes, 20 * 1024); // The first drop followed progress (1 of 6); five more made none (2…6); // the seventh gives up. assert.equal(r.continuations, STORED_URL_MAX_DROPS); assert.equal(r.pageOpens, 1 + STORED_URL_MAX_DROPS); assert.equal(cdn.requests.filter((q) => q.dropped).length, STORED_URL_MAX_DROPS + 1); assert.match(log, /\(6 of 6\)/); assert.match(log, /6 continuations since the last progress; giving up with the partial kept at 20480 bytes/); assert.match(r.error ?? "", /fetch failed/); const state = JSON.parse(await readFile(path.join(videoDir, "audio.m4a.stored.part.json"), "utf8")); assert.equal(state.goodBytes, 20 * 1024, "the next run resumes there"); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a 429 straight after the reopen that followed a drop gives up at once (rate-limited, no second open)", async () => { const { root, videoDir } = await setup(); const buf = Buffer.alloc(96 * 1024, 9); const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, requireUnlock: true, dropAfterBytes: 20 * 1024 }); let opens = 0; try { let log = ""; const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(M4A_PATH)), channelConfig: config, audioFormat: "m4a", audioCheck: false, pageUrl: PAGE, // The first open unlocks; the reopen after the drop does not. openPage: async () => { opens++; if (opens === 1) cdn.unlock(); else cdn.lock(); return { ok: opens === 1, mediaStatuses: [opens === 1 ? 206 : 429] }; }, onLog: (s) => (log += s), signal: new AbortController().signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, dropPauseMs: 0 }, }); assert.equal(r.kind, "rate-limited", log); assert.equal(r.httpStatus, 429); assert.equal(r.continuations, 1); assert.equal(opens, 2); assert.equal(r.pageOpens, 2); assert.match(log, /Connection dropped at 20480 bytes — reopening the page and resuming \(1 of 6\)/); assert.match(log, /the CDN refused the read at 20480 bytes; the partial is kept/); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } }); test("a cancel during a continuation's pause stops with the partial kept", async () => { const { root, videoDir } = await setup(); const buf = Buffer.alloc(96 * 1024, 2); const cdn = await startFakeRangedCdn({ files: { [M4A_PATH]: buf }, dropAfterBytes: 20 * 1024 }); const ac = new AbortController(); try { const r = await storedUrlDownload({ paths, videoDir, stored: storedFor(cdn.url(M4A_PATH)), channelConfig: config, audioFormat: "m4a", audioCheck: false, pageUrl: PAGE, openPage: null, onLog: () => {}, signal: ac.signal, deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, sleep: async () => { ac.abort(); }, }, }); assert.equal(r.kind, "aborted"); const state = JSON.parse(await readFile(path.join(videoDir, "audio.m4a.stored.part.json"), "utf8")); assert.equal(state.goodBytes, 20 * 1024); assert.equal((await stat(path.join(videoDir, "audio.m4a.stored.part"))).size, 20 * 1024); } finally { await cdn.close(); await rm(root, { recursive: true, force: true }); } });