Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 8f9574521541ce1620d0066afcb198fd8c0c7eec
parent de7260e8d3c9abb38b15e216def69aab1951b7a8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 01:19:38 -0400

common: a stored-URL clip cut opens the player's page first and shares the platform's one stored-URL rest with full downloads — fetchWindowManaged's ffmpeg cut opens the video's page before its first cut in a run (one page state per fetch-windows run), again on a 429 after a cut served since the open, never twice in a row; a cut of a NEW file waits out `stored-url:<platform>` (jobs/storedUrlPace.ts, the last file remembered) and sets it, a second window of the same file owes only the clip gap; the window's provenance records pageOpens; the real opener refuses under a test runner; E2E_CLIP_WINDOW_GAP_MS also zeroes a cut's rest in tests; the duplicate StoredUrlMode import the R6/R7 merge left in videoActions.ts removed

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MENVIRONMENT.md | 2+-
Mcommon/controller/fetchWindows.ts | 12++++++++++--
Mcommon/controller/fetchWindowsStoredUrl.test.ts | 3+++
Acommon/jobs/storedUrlPace.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/clipWindow.ts | 6++++++
Mcommon/lib/envVars.test.ts | 6++++--
Mcommon/lib/envVars.ts | 2+-
Mcommon/ytdlp/downloadOneManaged.ts | 8+++++---
Mcommon/ytdlp/fetchWindowManaged.ts | 119++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Acommon/ytdlp/fetchWindowStoredCut.test.ts | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/storedUrlPageOpen.ts | 25+++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 1-
12 files changed, 535 insertions(+), 17 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -220,7 +220,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AUDIO_CHECK_RECOVER_STEP_MS` | the real step | Likewise, the recovery step. | common/ytdlp/audioCheckedDownload.ts | | `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts | | `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts | -| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts | +| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | | `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts | | `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts | | `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs | diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -47,6 +47,7 @@ import { type StoredUrlWhy, } from "../lib/storedMediaUrl"; import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import { newStoredPageSession } from "../ytdlp/storedUrlPageOpen"; import { readChannelConfig } from "./channels"; import { findVideoSourceUrl } from "./undownloadedVideos"; @@ -101,7 +102,10 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; // `notAttempted` (and the run reports the stop). The backoff is still recorded // (the lookup IS limited); a stored-URL success never records the platform // clean; a 429 from the stored URL itself stops the run as any 429 does. Same -// queue, same gaps. +// queue, same gaps — plus, since release 32 R9, the platform's stored-URL rest +// (jobs/storedUrlPace.ts, shared with full downloads) before a cut of a NEW +// file, and the video's player page opened before its first cut in the run +// (fetchWindowManaged, one page state per run). // // A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's per-channel text // guard has no channel to ask. It is asked here instead, once per channel: an @@ -435,6 +439,10 @@ export async function fetchWindows({ const interrupted = (): FetchWindowsStop | null => signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null; + // THE RUN'S PAGE STATE for stored-URL cuts (release 32 R9): a video's page + // is opened before its first cut in this run, not before every window. + const pageSession = newStoredPageSession(); + // Network attempts so far (the gap is owed before every one after the // first), and the run of consecutive network-class failures. let networkAttempts = 0; @@ -636,7 +644,7 @@ export async function fetchWindows({ videoDir, videoId: dirId, videoUrl: url, - ...(target ? { storedMedia: target } : {}), + ...(target ? { storedMedia: target, storedUrlCut: { pageSession } } : {}), cwd: path.join(paths.channelsDir, item.slug), from: item.from, to: item.to, diff --git a/common/controller/fetchWindowsStoredUrl.test.ts b/common/controller/fetchWindowsStoredUrl.test.ts @@ -26,6 +26,9 @@ 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 diff --git a/common/jobs/storedUrlPace.ts b/common/jobs/storedUrlPace.ts @@ -0,0 +1,63 @@ +// ONE PACING STATE FOR A PLATFORM'S STORED-URL FILES (release 32 R9). +// +// Odysee's CDN allows one new original file per rest (measured 2026-10-16: the +// next file a minute later answered 429). Release 32 R7 spaced full downloads +// from the stored media URL by STORED_URL_NEW_FILE_GAP_MS under the platformGap +// key `stored-url:<platform>`; the clip cut kept only the clip gap +// (`clip-window:<platform>`, 30 s), so a cut and a download minutes apart were +// two new files inside one rest. Now both read the SAME state: +// +// - a full download always waits out the gap (it is a whole file); +// - a clip cut waits it out unless the last stored-URL read on the platform +// was the SAME file (two windows of one video are one file, already +// unlocked by its page open) — a cut of a new file waits like a download; +// - both note the gap at their start and their end, and remember the file. +// +// In memory and process-wide (on globalThis, as platformGap.ts is): a restart +// is itself a gap. + +import { notePlatformGap, platformGapRemainingMs } from "./platformGap"; +import { storedUrlGapKey } from "../lib/storedMediaUrl"; + +declare global { + // eslint-disable-next-line no-var + var __yttStoredUrlLastFile__: Map<string, string> | undefined; +} + +function lastFiles(): Map<string, string> { + if (!globalThis.__yttStoredUrlLastFile__) globalThis.__yttStoredUrlLastFile__ = new Map(); + return globalThis.__yttStoredUrlLastFile__; +} + +// The URL of the last stored-URL file read on `platform` in this process. +export function storedUrlLastFile(platform: string): string | null { + return lastFiles().get(storedUrlGapKey(platform)) ?? null; +} + +// Milliseconds before a stored-URL read of `url` on `platform` may start. +// `sameFileFree`: a read of the file read last owes no gap (the clip cut). +export function storedUrlGapRemainingMs( + platform: string, + opts: { url?: string; sameFileFree?: boolean } = {}, + now: number = Date.now(), +): number { + if (opts.sameFileFree && opts.url && storedUrlLastFile(platform) === opts.url) return 0; + return platformGapRemainingMs(storedUrlGapKey(platform), now); +} + +// A stored-URL read of `url` on `platform` started or ended at `now`: the next +// new file waits `gapMs` from now (never shortened), and this is the last file. +export function noteStoredUrlRead( + platform: string, + url: string, + gapMs: number, + now: number = Date.now(), +): void { + notePlatformGap(storedUrlGapKey(platform), gapMs, now); + lastFiles().set(storedUrlGapKey(platform), url); +} + +// Tests only. +export function clearStoredUrlFiles(): void { + lastFiles().clear(); +} diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -160,6 +160,10 @@ export type ClipProvenance = { // window fetched through the page. source?: ClipWindowSource; sourceHost?: string; + // How many times the player's page was opened for this window's cut (release + // 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the + // first cut of each video in a run. Absent when none was. + pageOpens?: number; // WHICH COPY a window of a gone recording was fetched from (release 29 E2, // publish/findCopy.ts): a Wayback Machine capture of its page, or an // archive.org mirror's file — and its URL. Absent when the window came from @@ -228,6 +232,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null { } const sourceHost = str(r.sourceHost); if (sourceHost) out.sourceHost = sourceHost; + const pageOpens = num(r.pageOpens); + if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens; const copy = coerceClipCopy(r.copy); if (copy) out.copy = copy; const ac = r.audioCheck as { verdict?: unknown; attempts?: unknown } | undefined; diff --git a/common/lib/envVars.test.ts b/common/lib/envVars.test.ts @@ -23,8 +23,10 @@ const SKIP_DIRS = new Set(["node_modules", ".next", "out", "out-private", "publi // Playwright (TEST_WORKER_INDEX, which it sets in each worker process; the // two-origin config reads it to stage only in the runner — and // TEST_PARALLEL_INDEX, the worker's slot, which the editor suite reads to find -// its own servers and data root). -const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX", "TEST_PARALLEL_INDEX"]); +// its own servers and data root), and node's test runner (NODE_TEST_CONTEXT, +// set in each test file's process; the player-page opener never launches a +// browser under it). +const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX", "TEST_PARALLEL_INDEX", "NODE_TEST_CONTEXT"]); function codeFiles(): string[] { const out: string[] = []; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -217,7 +217,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AUDIO_CHECK_RECOVER_STEP_MS", audience: "test", default: "the real step", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery step." }, { name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." }, { name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." }, - { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts", doc: "The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, + { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -115,7 +115,8 @@ import { } from "../lib/storedMediaUrl"; import { storedMediaUrl } from "../lib/storedMediaUrl-server"; import type { DownloadFailureClass } from "../lib/availability"; -import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { noteStoredUrlRead } from "../jobs/storedUrlPace"; import { storedUrlDownload, type StoredUrlDownloadDeps, @@ -2096,7 +2097,8 @@ async function runStoredUrlDownload( failureClass: "unknown", }); } - notePlatformGap(key, gapMs); + // The one pacing state the clip cut reads too (jobs/storedUrlPace.ts). + noteStoredUrlRead(stored.platform, stored.url, gapMs); let r: StoredUrlDownloadResult; try { r = await storedUrlDownload({ @@ -2119,7 +2121,7 @@ async function runStoredUrlDownload( ...(deps ? { deps } : {}), }); } finally { - notePlatformGap(key, gapMs); + noteStoredUrlRead(stored.platform, stored.url, gapMs); } if (gapMs > 0) { opts.onLog( diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts @@ -52,10 +52,20 @@ import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged"; import { clipFormatSelector, copyClipFormatSelector } from "./downloadFormat"; import { STORED_MEDIA_USER_AGENT, + STORED_URL_NEW_FILE_GAP_MS, storedUrlWhyText, type StoredMediaUrl, type StoredUrlWhy, } from "../lib/storedMediaUrl"; +import { + newStoredPageSession, + openPlayerPage, + PAGE_OPEN_PLATFORMS, + type PageOpener, + type StoredPageSession, +} from "./storedUrlPageOpen"; +import { waitForPlatformGap } from "../jobs/platformGap"; +import { noteStoredUrlRead, storedUrlGapRemainingMs } from "../jobs/storedUrlPace"; // The source height a clip is worth fetching at. 720 is umtool's number and the // reason is the render: the deliverable is 1080p with a clip inset, so pixels @@ -123,6 +133,21 @@ export type FetchWindowOpts = { // extractor, the copy path's lenient selector, the platform player's // Referer) and no page or API request is made. `why` is for the log. storedMedia?: StoredMediaUrl & { why: StoredUrlWhy }; + // THE STORED-URL CUT'S PAGE AND GAP (release 32 R9). Every field optional; + // production callers pass at most `pageSession`. + storedUrlCut?: { + // The run's page state (storedUrlPageOpen.ts): the batch passes one per + // run so a video's page is opened before its FIRST cut only. Absent = a + // fresh one for this window. + pageSession?: StoredPageSession; + // Absent = the real opener for a platform in PAGE_OPEN_PLATFORMS; null = + // no page open. Tests inject a fake (never a browser). + openPage?: PageOpener | null; + // The one stored-URL gap (jobs/storedUrlPace.ts); absent = + // STORED_URL_NEW_FILE_GAP_MS. Tests pass 0 or a sleep. + gapMs?: number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + }; // Working directory for the yt-dlp process. Nothing it writes is // cwd-relative (`-o` is absolute and `--ignore-config` stops the operator's // own config redirecting anything), so this only decides where yt-dlp's own @@ -223,9 +248,25 @@ export function storedMediaFfmpegArgs( ]; } +// TEST-ONLY: E2E_CLIP_WINDOW_GAP_MS (the e2e server's and the editor route +// tests' clip gap) also replaces the stored-URL rest a cut sets, so a test's +// second stored-URL window does not wait 20 minutes. A full download's rest has +// no knob (storedUrlDeps.gapMs is its seam). +function e2eStoredUrlRestMs(): number | undefined { + if (process.env.E2E_CLIP_WINDOW_GAP_MS === undefined) return undefined; + const raw = Number(process.env.E2E_CLIP_WINDOW_GAP_MS); + return Number.isFinite(raw) && raw >= 0 ? raw : undefined; +} + export async function fetchWindowManaged( - opts: FetchWindowOpts, + given: FetchWindowOpts, ): Promise<FetchWindowResult> { + // One page state across this window's attempts (a corrupt re-fetch is a + // second cut of the same video, not a first). + const opts: FetchWindowOpts = + given.storedMedia && !given.storedUrlCut?.pageSession + ? { ...given, storedUrlCut: { ...given.storedUrlCut, pageSession: newStoredPageSession() } } + : given; for (let attempt = 1; ; attempt++) { try { return await fetchWindowOnce(opts, attempt); @@ -362,6 +403,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< ]; let args: string[] = []; + let pageOpens = 0; if (stored) { // A STORED MEDIA URL IS READ THE WAY THE SITE'S OWN PLAYER READS IT (release 32): ranged GETs // with the page's Referer and Origin and a browser's user agent — ffmpeg's input seek (-ss @@ -369,15 +411,77 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< // URL with one unranged GET first, which the CDN answers like a bulk download (429 on Odysee, // 2026-10-16) while it serves the player's ranged requests (206). No yt-dlp, no cookies. args = storedMediaFfmpegArgs(stored, from, to, maxHeight, part); - const outcome = await runOneYtdlp( - { ytdlpBin: opts.paths.ffmpegBin, onLog: opts.onLog, signal: opts.signal }, - opts.cwd ?? videoDir, - args, - ); + const cut = opts.storedUrlCut ?? {}; + const session = cut.pageSession ?? newStoredPageSession(); + const openPage: PageOpener | null = + cut.openPage !== undefined + ? cut.openPage + : PAGE_OPEN_PLATFORMS.includes(stored.platform) + ? openPlayerPage + : null; + const gapMs = cut.gapMs ?? e2eStoredUrlRestMs() ?? STORED_URL_NEW_FILE_GAP_MS; + + // THE ONE GAP (release 32 R9, jobs/storedUrlPace.ts): a cut of a NEW file + // waits out the platform's stored-URL rest exactly as a full download + // does; a cut of the file read last (another window of the same video) + // owes nothing more than the clip gap its caller already kept. + try { + await waitForPlatformGap({ + label: `A cut from the stored media URL (${stored.platform})`, + remainingMs: () => storedUrlGapRemainingMs(stored.platform, { url: stored.url, sameFileFree: true }), + signal: opts.signal, + onLog: (line) => opts.onLog(`${line}\n`), + ...(cut.sleep ? { sleep: cut.sleep } : {}), + }); + } catch { + throw new FetchWindowError( + `cancelled while waiting for the gap between stored-URL files (${stored.platform})`, + "unknown", + "public", + ); + } + noteStoredUrlRead(stored.platform, stored.url, gapMs); + + // THE PLAYER'S PAGE FIRST (release 32 R9; R7's finding): the CDN serves a + // file only after a player opened the video's page. Before the first cut + // of each video in a run; again on a 429 that follows a cut served since + // the last open; never twice in a row. + let page = session.pages.get(opts.videoUrl); + const open = async (): Promise<void> => { + if (!openPage || opts.signal.aborted) return; + session.opens++; + pageOpens++; + page = { cutsSinceOpen: 0 }; + session.pages.set(opts.videoUrl, page); + const r = await openPage({ pageUrl: opts.videoUrl, cdnHost: stored.host, signal: opts.signal, onLog: opts.onLog }); + if (!r.ok) { + opts.onLog(`The page open did not show the player served (${r.error ?? "no media request"}); cutting anyway.\n`); + } + }; + if (openPage && !page) await open(); + const cutOnce = () => + runOneYtdlp( + { ytdlpBin: opts.paths.ffmpegBin, onLog: opts.onLog, signal: opts.signal }, + opts.cwd ?? videoDir, + args, + ); + const refused = (tail: string) => /\b429\b|Too Many Requests/i.test(tail); + let outcome = await cutOnce(); + if (outcome.exitCode !== 0 && refused(outcome.stderrTail) && openPage && page && page.cutsSinceOpen > 0 && !opts.signal.aborted) { + opts.onLog( + `HTTP Error 429 from ${stored.host} after ${page.cutsSinceOpen} cut(s) since the page was opened; ` + + `opening it again.\n`, + ); + await rm(part, { force: true }); + await open(); + outcome = await cutOnce(); + } + noteStoredUrlRead(stored.platform, stored.url, gapMs); + if (outcome.exitCode === 0 && page) page.cutsSinceOpen++; if (outcome.exitCode !== 0) { await rm(part, { force: true }); const tail = outcome.stderrTail.trim().split("\n").slice(-4).join(" / "); - const failureClass: DownloadFailureClass = /\b429\b|Too Many Requests/i.test(outcome.stderrTail) + const failureClass: DownloadFailureClass = refused(outcome.stderrTail) ? "rate_limit" : /\b(403|404|410)\b|Forbidden|Not Found/i.test(outcome.stderrTail) ? "per_video" @@ -518,6 +622,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< : {}), ...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}), ...(stored ? { source: "stored-media-url" as const, sourceHost: stored.host } : {}), + ...(pageOpens > 0 ? { pageOpens } : {}), ...(audioCheck ? { audioCheck } : {}), bytes: st.size, fetchedAt: new Date().toISOString(), diff --git a/common/ytdlp/fetchWindowStoredCut.test.ts b/common/ytdlp/fetchWindowStoredCut.test.ts @@ -0,0 +1,305 @@ +// 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"; + +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<string> { + 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> = {}): 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"); +}); diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts @@ -57,6 +57,15 @@ function abortableWait(ms: number, signal: AbortSignal): Promise<void> { // regardless (the CDN may serve it anyway). export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onLog }) => { const mediaStatuses: number[] = []; + // NEVER A BROWSER UNDER A TEST RUNNER (release 32 R9). node's runner (and + // tsx --test) sets NODE_TEST_CONTEXT in every test file's process: a test + // that reaches the real opener — an editor route test running the whole cut — + // gets "not opened" and reads on, instead of a headless browser on the + // network. Tests that exercise the open inject their own opener. + if (process.env.NODE_TEST_CONTEXT) { + onLog(`Not opening the player's page under a test runner (${pageUrl}).\n`); + return { ok: false, mediaStatuses, error: "not opened under a test runner" }; + } let browser: { close: () => Promise<void> } | null = null; try { const { chromium } = await importPlaywright(); @@ -96,3 +105,19 @@ export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onL await browser?.close().catch(() => {}); } }; + +// THE CLIP CUT'S PAGE STATE FOR ONE RUN (release 32 R9). A fetch-windows run +// opens a video's page before the first cut of that video, and again only on +// a refusal that follows a cut served since the last open (the unlock may +// have lapsed) — never twice in a row: a refusal straight after an open means +// the open did not unlock the file, and another will not either. Keyed by the +// video's PAGE url. A run that passes none gets a fresh one per window (a +// single-window job opens the page before its one cut). +export type StoredPageSession = { + pages: Map<string, { cutsSinceOpen: number }>; + opens: number; +}; + +export function newStoredPageSession(): StoredPageSession { + return { pages: new Map(), opens: 0 }; +} diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -118,7 +118,6 @@ import { runYtdlp } from "yt-dlp-transcript-common/ytdlp/runYtdlp"; import { isStoredUrlMode, resolveStoredUrlMode, - type StoredUrlMode, } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { storedUrlAttemptOf,