commit 80a5c0c1d5e4f01372230b372da9c87e04b65f66 parent e19d52d2df9a19661605fcf04dceb8140f2f83c8 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 29 Oct 2026 23:32:48 -0400 umtool Play: a window replaced under its old name is a new file Play the cut (and the bench) could keep playing a clip window's OLD bytes after a refetch, an evict + fetch or a saved-video replace wrote new ones under the same name: the raw and audio routes said `immutable` keyed by the name alone, codecPicture kept each URL's parsed moov for the page's life, and an excerpt of a long recording was "fresh" when newer than its source -- so a good copy landing with an OLDER mtime (yt-dlp --mtime, the saved-video replace) left the excerpts cut from the corrupt one playing. - serve.mjs: windowVersion(win) hashes the file's identity (dev, ino, size, mtime, ctime; an excerpt's is its source's). playView, the clip route, the bench page and cited.ts hand it out as `v`; Play, the bench and the cited player put it in every media URL. - raw/audio/peaks: `immutable` only when the URL's `v` is current, else `no-cache`; a strong ETag on every answer (an excerpt's carries its own file too). rangeResponse takes an `etag`: If-None-Match is a 304, a Range under a stale If-Range is the whole file. audio and peaks answer a 304 before decoding. - codecPicture: the moov cache is keyed by the versioned URL, and holds the ETag it was read under; a block read answered with another drops the entry and fails the clip onto a <video> rather than decode it. - Excerpts: the cut records its source's identity in <excerpt>.src.json (temp + rename, after the excerpt's own rename); windowFileFresh needs an exact match. No sidecar is stale, so every existing excerpt is cut once more on its next open or prep. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
22 files changed, 533 insertions(+), 148 deletions(-)
diff --git a/umtool/app/api/report/audio/route.ts b/umtool/app/api/report/audio/route.ts @@ -1,6 +1,8 @@ import { spawn } from "node:child_process"; import { stat } from "node:fs/promises"; -import { absOf, ensureWindowFile, pickWindow, resolveClip, windowsFor } from "@/lib/report/serve.mjs"; +import { + absOf, ensureWindowFile, notModified, pickWindow, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, +} from "@/lib/report/serve.mjs"; import { MAX_DECODE_SPAN, wavHeader } from "@/lib/report/playback.mjs"; import { FFMPEG_BIN } from "umtool-report-to-video/build-video"; @@ -49,7 +51,15 @@ export async function GET(request: Request) { const abs = absOf(win); if (!abs) return Response.json({ error: "outside the roots" }, { status: 400 }); const st = await stat(abs).catch(() => null); - if (!st) return Response.json({ error: "gone" }, { status: 404 }); + const version = await windowVersion(win); + if (!st || !version) return Response.json({ error: "gone" }, { status: 404 }); + // The sound of THESE bytes (serve.mjs, "A REPLACED FILE IS A NEW FILE"): a + // refetched window under the same name is another file, and another sound. + // `from`/`to` are in the URL, so the file's tag is this answer's tag too, and + // a revalidation that still names it skips the decode. + const etag = windowEtag(version, win, st); + const cache = { "cache-control": windowCacheControl(url.searchParams.get("v"), version), etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); const num = (k: string, dflt: number) => { const v = url.searchParams.get(k); @@ -114,9 +124,8 @@ export async function GET(request: Request) { return new Response(body, { headers: { "content-type": "audio/wav", - // The window is in the file's name, so the same request is the same - // sound: it may be cached for as long as the raw file is. - "cache-control": "private, max-age=3600, immutable", + // Cached as hard as the raw file is: immutable under the current `v`, else revalidated. + ...cache, // What was actually decoded, in absolute source seconds: the client // places the buffer on the source clock from these, not from what it // asked for. diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -1,5 +1,5 @@ import path from "node:path"; -import { ensureWindowFile, projectCache, resolveClip, segmentFor, windowsFor } from "@/lib/report/serve.mjs"; +import { ensureWindowFile, projectCache, resolveClip, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; import { takeToken } from "@/lib/report/takeEdit.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { cuesInWindow, readClipDetail, siblingsOf } from "@/lib/projects/report.mjs"; @@ -69,11 +69,16 @@ export async function GET(request: Request) { muteFrom: clip.muteFrom ?? null, }, view, - windows: windows.map((w: { name: string; from: number; to: number }) => ({ - name: w.name, - from: w.from, - to: w.to, - })), + // `v`: the version of each window's bytes, for the media URLs -- a refetch + // under the same name is a new URL (serve.mjs, "A REPLACED FILE IS A NEW FILE"). + windows: await Promise.all( + windows.map(async (w: { name: string; from: number; to: number; path: string }) => ({ + name: w.name, + from: w.from, + to: w.to, + v: await windowVersion(w), + })), + ), // What resolve-windows WOULD do, computed in-process because widen() is // pure once the cues are read. "Run the widener and see" stops being a // leap of faith. diff --git a/umtool/app/api/report/peaks/route.ts b/umtool/app/api/report/peaks/route.ts @@ -1,4 +1,7 @@ -import { absOf, ensureWindowFile, pickWindow, projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs"; +import { stat } from "node:fs/promises"; +import { + absOf, ensureWindowFile, notModified, pickWindow, projectCache, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, +} from "@/lib/report/serve.mjs"; import { ENV_RATE, analyseMedia } from "@/lib/media"; export const dynamic = "force-dynamic"; @@ -9,9 +12,10 @@ export const dynamic = "force-dynamic"; // the QR's. The file's own start is the only relative number, and it is added // here so nothing downstream has to remember to. // -// analyseMedia decodes once and caches to MIX_CACHE keyed by mtime and size. A -// raw clip's window is IN ITS NAME, so the file is immutable and that cache can -// never miss twice for the same window. +// analyseMedia decodes once and caches to MIX_CACHE keyed by path, mtime and +// size, so it never misses twice for the same file. The browser's copy is +// keyed by the file's version, not its name (serve.mjs, "A REPLACED FILE IS A +// NEW FILE"): a refetch writes new bytes under the same window name. export async function GET(request: Request) { const url = new URL(request.url); @@ -31,6 +35,13 @@ export async function GET(request: Request) { } const abs = absOf(win); if (!abs) return Response.json({ error: "outside the roots" }, { status: 400 }); + const st = await stat(abs).catch(() => null); + const version = await windowVersion(win); + if (!st || !version) return Response.json({ error: "gone" }, { status: 404 }); + // `n` is in the URL, so the file's tag is this answer's tag too. + const etag = windowEtag(version, win, st); + const cache = { "cache-control": windowCacheControl(url.searchParams.get("v"), version), etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); const buckets = Math.max(64, Math.min(4000, Number(url.searchParams.get("n") ?? 1200))); @@ -67,6 +78,6 @@ export async function GET(request: Request) { min, max, }, - { headers: { "cache-control": "private, max-age=3600" } }, + { headers: cache }, ); } diff --git a/umtool/app/api/report/raw/route.ts b/umtool/app/api/report/raw/route.ts @@ -1,7 +1,7 @@ -import { createReadStream } from "node:fs"; import { stat } from "node:fs/promises"; -import { Readable } from "node:stream"; -import { absOf, ensureWindowFile, pickWindow, resolveClaim, resolveClip, windowsFor } from "@/lib/report/serve.mjs"; +import { + absOf, ensureWindowFile, pickWindow, rangeResponse, resolveClaim, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, +} from "@/lib/report/serve.mjs"; import { readClaimDetail } from "@/lib/projects/report.mjs"; export const dynamic = "force-dynamic"; @@ -10,12 +10,18 @@ export const dynamic = "force-dynamic"; // // The alternative -- an ffmpeg slice per requested window, like // /api/clip/[key]/video does -- would put an encode in front of every drag. The -// file is small (one clip plus its pad), immutable (its window is in its name), -// and the browser only needs to be told where to seek: the bench sets -// currentTime = t - fetchStart and windows entirely on the client. +// file is small (one clip plus its pad), and the browser only needs to be told +// where to seek: the bench sets currentTime = t - fetchStart and windows +// entirely on the client. // // Range support is not optional for that. Without a 206 the <video> element // will not seek in a stream it did not fully download. +// +// NOT IMMUTABLE BY NAME. The window is in the name, but a refetch writes new +// bytes under it; the URL's `v` (windowVersion, handed out with the window by +// playView and the clip route) is what names the bytes, and only that is +// cached hard. Every answer carries a strong ETag of the file sent, so a +// revalidation is a 304 and a range under a stale If-Range is the whole file. export async function GET(request: Request) { const url = new URL(request.url); @@ -24,7 +30,7 @@ export async function GET(request: Request) { // A CLAIM names a moment rather than a window, so its candidate files are the // cached windows that CONTAIN its cite. Everything below -- membership, - // root-resolution, ranges, the immutable cache header -- is the clip path's, + // root-resolution, ranges, the versioned cache header -- is the clip path's, // unchanged: the two differ only in which list of windows they may pick from. let windows: Array<{ name: string; from: number; to: number; path: string }>; if (claimId) { @@ -55,48 +61,23 @@ export async function GET(request: Request) { if (!abs) return new Response("outside the roots", { status: 400 }); const st = await stat(abs).catch(() => null); - if (!st) return new Response("gone", { status: 404 }); + const version = await windowVersion(win); + if (!st || !version) return new Response("gone", { status: 404 }); const headers: Record<string, string> = { "content-type": "video/mp4", "accept-ranges": "bytes", - // The file is immutable -- rename the window and it is a different file -- - // so it may be cached hard. That is what makes dragging feel instant. - "cache-control": "private, max-age=3600, immutable", + // Cached hard only under the URL's `v` -- the version of the file being + // sent (serve.mjs, "A REPLACED FILE IS A NEW FILE"): a refetch writes new + // bytes under the same NAME, and an immutable answer keyed by the name + // played the old ones. Without a current `v`, revalidated on the ETag. + "cache-control": windowCacheControl(url.searchParams.get("v"), version), + "x-window-version": version, // The absolute source second the file starts at, so the client can convert // without a second request. "x-fetch-start": String(win.from), "x-fetch-end": String(win.to), "x-window": win.name, }; - - const range = request.headers.get("range"); - const m = range ? /^bytes=(\d*)-(\d*)$/.exec(range.trim()) : null; - if (m) { - const size = st.size; - let start = m[1] ? Number(m[1]) : 0; - let end = m[2] ? Number(m[2]) : size - 1; - if (!m[1] && m[2]) { - // A suffix range: the LAST n bytes. - start = Math.max(0, size - Number(m[2])); - end = size - 1; - } - if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) { - return new Response(null, { status: 416, headers: { "content-range": `bytes */${size}` } }); - } - end = Math.min(end, size - 1); - const stream = createReadStream(abs, { start, end }); - return new Response(Readable.toWeb(stream) as ReadableStream, { - status: 206, - headers: { - ...headers, - "content-range": `bytes ${start}-${end}/${size}`, - "content-length": String(end - start + 1), - }, - }); - } - - return new Response(Readable.toWeb(createReadStream(abs)) as ReadableStream, { - headers: { ...headers, "content-length": String(st.size) }, - }); + return rangeResponse(request, { abs, size: st.size, headers, etag: windowEtag(version, win, st) }); } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -94,7 +94,8 @@ type Sibling = { side: "after" | "before" | "overlap"; gap: number | null; }; -type Win = { name: string; from: number; to: number }; +/** A cached window; `v` the version of its bytes (serve.mjs windowVersion), carried in its media URLs. */ +type Win = { name: string; from: number; to: number; v?: string | null }; type Clip = { id: string; @@ -433,7 +434,10 @@ type WindowPatch = { muteFrom?: number | string; }; -/** A decoded span of the cached window, placed on the source clock. */ +/** + * A decoded span of the cached window, placed on the source clock. `name` is + * the window's name and the version of its bytes (`<name>|<v>`). + */ type Decoded = { name: string; span: { from: number; to: number }; buf: AudioBuffer }; /** @@ -673,6 +677,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // The widest cached file is the one the bench draws from: it is how much room // there is to drag before anything has to be fetched. const cached = windows[0] ?? null; + // The version of its bytes in every media URL: a refetch under the same name is a new URL. + const vq = cached?.v ? `&v=${encodeURIComponent(cached.v)}` : ""; const fetchStart = cached?.from ?? 0; const cachedTo = cached?.to ?? 0; @@ -682,7 +688,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { let live = true; void (async () => { const r = await fetch( - `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}`, + `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`, { cache: "no-store" }, ); if (!r.ok || !live) return; @@ -894,15 +900,15 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { async (want: { from: number; to: number }): Promise<Decoded> => { if (!cached) throw new Error("nothing is cached for this clip"); const have = decoded.current; - if (have && have.name === cached.name && covers(have.span, want.from, want.to)) return have; + if (have && have.name === `${cached.name}|${cached.v ?? ""}` && covers(have.span, want.from, want.to)) return have; const span = decodeSpan({ from: cached.from, to: cached.to }, want); - const key = `${cached.name}|${span.from}|${span.to}`; + const key = `${cached.name}|${cached.v ?? ""}|${span.from}|${span.to}`; if (decoding.current?.key === key) return decoding.current.p; const p = (async () => { setAudio({ state: "loading" }); const r = await fetch( `/api/report/audio?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` + - `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}${tq}`, + `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}${tq}${vq}`, ); if (!r.ok) { const j = (await r.json().catch(() => null)) as { error?: string } | null; @@ -914,7 +920,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { typeof window !== "undefined" ? (window.OfflineAudioContext ?? null) : null; if (!Offline) throw new Error("this browser has no Web Audio"); const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes); - const d: Decoded = { name: cached.name, span: { from, to: from + buf.duration }, buf }; + const d: Decoded = { name: `${cached.name}|${cached.v ?? ""}`, span: { from, to: from + buf.duration }, buf }; decoded.current = d; setAudio({ state: "ready" }); return d; @@ -932,7 +938,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // A different window -- a wider one after "fetch more", or the first after a // fetch -- is different audio: drop the old decode and start the new one // now, so the first play after it does not wait. - const cachedName = cached?.name ?? null; + // (Its name and the version of its bytes: a refetch under the same name is different audio too.) + const cachedName = cached ? `${cached.name}|${cached.v ?? ""}` : null; useEffect(() => { decoded.current = null; decoding.current = null; @@ -2944,7 +2951,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { <video ref={video} data-testid="clip-video" - src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}`} + src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`} // object-contain, because the height is now whatever is left // rather than whatever 16:9 asks for. // The picture and the words SHARE what is left, 3:2, rather diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -10,7 +10,7 @@ import { walkReadiness, } from "@/lib/projects/report.mjs"; import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs"; -import { projectCache, segmentFor, windowsFor } from "@/lib/report/serve.mjs"; +import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { pieceHrefOfProject } from "@/lib/pieces/article"; @@ -122,11 +122,15 @@ export default async function ClipBenchPage({ deckOn: deckOn(manifest.render ?? {}), generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, view, - windows: windows.map((w: { name: string; from: number; to: number }) => ({ - name: w.name, - from: w.from, - to: w.to, - })), + // `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE"). + windows: await Promise.all( + windows.map(async (w: { name: string; from: number; to: number; path: string }) => ({ + name: w.name, + from: w.from, + to: w.to, + v: await windowVersion(w), + })), + ), proposed: entry.proposed ?? null, endsSentence: entry.endsSentence ?? null, noPunctuation: !!entry.noPunctuation, diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -19,7 +19,7 @@ import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from ". import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection"; import { usePlayEngine } from "./playEngine/usePlayEngine"; import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; -import type { EngineInfo } from "./playEngine/engine"; +import type { EngineInfo, MediaRef } from "./playEngine/engine"; import ReelStrip, { type StripCounter } from "./ReelStrip"; import WrongSpeaker from "./WrongSpeaker"; @@ -100,7 +100,7 @@ export type PlayEntry = { cutStart?: number | null; cutEnd?: number | null; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; - media?: { name: string; from: number; to: number } | null; + media?: (MediaRef & { from: number; to: number }) | null; /** Ruled incorrect by the walk: its correction (skipped unless "Show clips marked incorrect"). */ incorrect?: string | null; }; @@ -284,13 +284,17 @@ export default function PlayCut({ // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ---- const bg = doc?.background ?? "#000"; + // `v` (the version of the window's bytes, playView): a window refetched under its old name is a new URL. const srcOf = useCallback( - (id: string, file: string) => `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file }).toString()}`, + (id: string, m: MediaRef) => + `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file: m.name, ...(m.v ? { v: m.v } : {}) }).toString()}`, [project, take], ); const audioOf = useCallback( - (id: string, file: string, from: number, to: number) => - `/api/report/audio?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file, from: String(from), to: String(to) }).toString()}`, + (id: string, m: MediaRef, from: number, to: number) => + `/api/report/audio?${new URLSearchParams({ + project, clip: id, ...(take ? { take } : {}), file: m.name, from: String(from), to: String(to), ...(m.v ? { v: m.v } : {}), + }).toString()}`, [project, take], ); const engine = usePlayEngine({ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style }); diff --git a/umtool/components/projects/review/playEngine/audioBank.ts b/umtool/components/projects/review/playEngine/audioBank.ts @@ -1,4 +1,5 @@ import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; +import type { MediaRef } from "./engine"; // THE PLAY VIEW'S DECODED SOUND (the engine's, engine.ts): each clip's sound, // fetched as PCM from the bench's /api/report/audio -- ffmpeg's decode of the @@ -38,17 +39,17 @@ export class AudioBank { private clock = 0; constructor( - private urlOf: (id: string, file: string, from: number, to: number) => string, + private urlOf: (id: string, media: MediaRef, from: number, to: number) => string, private budget = DEFAULT_BUDGET, ) {} - static keyOf(id: string, file: string, span: { from: number; to: number }) { - return `${id}|${file}|${span.from}|${span.to}`; + static keyOf(id: string, media: MediaRef, span: { from: number; to: number }) { + return `${id}|${media.name}|${media.v ?? ""}|${span.from}|${span.to}`; } /** The decode of a clip's span: started once, shared by every caller. */ - request(id: string, file: string, span: { from: number; to: number }): Promise<ClipSound | null> { - const key = AudioBank.keyOf(id, file, span); + request(id: string, media: MediaRef, span: { from: number; to: number }): Promise<ClipSound | null> { + const key = AudioBank.keyOf(id, media, span); const have = this.slots.get(key); if (have) { have.used = ++this.clock; @@ -57,7 +58,7 @@ export class AudioBank { const slot: Slot = { key, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock }; slot.p = (async () => { try { - const r = await fetch(this.urlOf(id, file, span.from, span.to)); + const r = await fetch(this.urlOf(id, media, span.from, span.to)); if (!r.ok) { const j = (await r.json().catch(() => null)) as { error?: string } | null; throw new Error(j?.error ?? `the audio route answered ${r.status}`); @@ -85,16 +86,16 @@ export class AudioBank { } /** What the bank has for a clip now, without waiting: the sound, "loading", or "failed". */ - peek(id: string, file: string, span: { from: number; to: number }): ClipSound | "loading" | "failed" | null { - const s = this.slots.get(AudioBank.keyOf(id, file, span)); + peek(id: string, media: MediaRef, span: { from: number; to: number }): ClipSound | "loading" | "failed" | null { + const s = this.slots.get(AudioBank.keyOf(id, media, span)); if (!s) return null; s.used = ++this.clock; return s.state === "ready" ? s.sound : s.state; } /** Why a clip's sound did not decode (said in the Approximate line). */ - why(id: string, file: string, span: { from: number; to: number }) { - return this.slots.get(AudioBank.keyOf(id, file, span))?.why ?? null; + why(id: string, media: MediaRef, span: { from: number; to: number }) { + return this.slots.get(AudioBank.keyOf(id, media, span))?.why ?? null; } /** Mark these as in use now, so the trim keeps them. */ diff --git a/umtool/components/projects/review/playEngine/codecPicture.ts b/umtool/components/projects/review/playEngine/codecPicture.ts @@ -39,40 +39,61 @@ const TAIL_BYTES = 512 * 1024; export const codecsAvailable = () => typeof window !== "undefined" && typeof window.VideoDecoder === "function" && typeof window.EncodedVideoChunk === "function"; -async function range(url: string, a: number, b: number, signal: AbortSignal): Promise<ArrayBuffer> { +/** + * Bytes a..b of the window. With `etag` (the one its moov was read under), + * an answer carrying another is refused: the file was replaced under the same + * URL since -- a page opened before a refetch, the `v` it was handed now stale + * -- and its samples are not where the old moov says they are. Decoding them + * anyway is the corrupted picture this exists to prevent. + */ +async function range(url: string, a: number, b: number, signal: AbortSignal, etag: string | null = null): Promise<ArrayBuffer> { const r = await fetch(url, { headers: { Range: `bytes=${a}-${b}` }, signal }); + const got = r.headers.get("etag"); + if (etag && got && got !== etag) { + tracks.delete(url); + throw new Error("the window was replaced on disk since it was opened"); + } if (r.status === 206) return r.arrayBuffer(); if (r.status === 200) return (await r.arrayBuffer()).slice(a, b + 1); throw new Error(`the media route answered ${r.status}`); } -/** The `moov` box's bytes: in the head when it leads (faststart), in the tail when it trails, else walked to box by box. */ -async function readMoov(url: string, signal: AbortSignal): Promise<ArrayBuffer> { +/** + * The `moov` box's bytes, and the ETag of the file they were read from: in the + * head when it leads (faststart), in the tail when it trails, else walked to + * box by box -- every read after the head held to the head's ETag. + */ +async function readMoov(url: string, signal: AbortSignal): Promise<{ moov: ArrayBuffer; etag: string | null }> { const tailP = fetch(url, { headers: { Range: `bytes=-${TAIL_BYTES}` }, signal }) - .then(async (r) => (r.status === 206 ? { buf: await r.arrayBuffer(), range: r.headers.get("content-range") } : null)) + .then(async (r) => (r.status === 206 ? { buf: await r.arrayBuffer(), range: r.headers.get("content-range"), etag: r.headers.get("etag") } : null)) .catch(() => null); - const head = await range(url, 0, 256 * 1024 - 1, signal); + const first = await fetch(url, { headers: { Range: `bytes=0-${256 * 1024 - 1}` }, signal }); + if (first.status !== 206 && first.status !== 200) throw new Error(`the media route answered ${first.status}`); + const etag = first.headers.get("etag"); + const head = first.status === 206 ? await first.arrayBuffer() : (await first.arrayBuffer()).slice(0, 256 * 1024); + const found = (moov: ArrayBuffer) => ({ moov, etag }); let boxes = topBoxes(head); const inHead = boxes.find((b) => b.type === "moov"); - if (inHead && inHead.offset + inHead.size <= head.byteLength) return head.slice(inHead.offset, inHead.offset + inHead.size); - // The tail: where the walk would end up, already here. - const tail = await tailP; + if (inHead && inHead.offset + inHead.size <= head.byteLength) return found(head.slice(inHead.offset, inHead.offset + inHead.size)); + // The tail: where the walk would end up, already here -- when it is of the same file. + const t = await tailP; + const tail = t && (!etag || t.etag === etag) ? t : null; const m = tail?.range ? /^bytes (\d+)-(\d+)\/(\d+)$/.exec(tail.range) : null; for (let hops = 0; hops < 16; hops += 1) { const moov = boxes.find((b) => b.type === "moov"); if (moov) { - if (moov.offset + moov.size <= head.byteLength) return head.slice(moov.offset, moov.offset + moov.size); + if (moov.offset + moov.size <= head.byteLength) return found(head.slice(moov.offset, moov.offset + moov.size)); if (tail && m && moov.offset >= Number(m[1]) && moov.offset + moov.size - 1 <= Number(m[2])) { - return tail.buf.slice(moov.offset - Number(m[1]), moov.offset - Number(m[1]) + moov.size); + return found(tail.buf.slice(moov.offset - Number(m[1]), moov.offset - Number(m[1]) + moov.size)); } - return range(url, moov.offset, moov.offset + moov.size - 1, signal); + return found(await range(url, moov.offset, moov.offset + moov.size - 1, signal, etag)); } const last = boxes[boxes.length - 1]; if (!last || last.size <= 0) break; const at = last.offset + last.size; if (tail && m && at >= Number(m[1]) && at + 16 <= Number(m[2]) + 1) { boxes = topBoxes(tail.buf.slice(at - Number(m[1]), at - Number(m[1]) + 16), at); - } else boxes = topBoxes(await range(url, at, at + 15, signal), at); + } else boxes = topBoxes(await range(url, at, at + 15, signal, etag), at); if (!boxes.length) break; } throw new Error("no moov box"); @@ -81,13 +102,21 @@ async function readMoov(url: string, signal: AbortSignal): Promise<ArrayBuffer> /** * Each window's track, read once per page: a clip seeked away from and back * to (its decoder closed and made again) does not read its moov again. + * + * KEYED BY THE VERSIONED URL. The URL carries the window's `v` (serve.mjs, + * "A REPLACED FILE IS A NEW FILE"), so a window refetched under its old name + * is a new key and its moov is read afresh; a sample index kept for the old + * bytes would read the new file at the old offsets. The ETag the moov was read + * under rides with it, and a block read answered with another (the file + * replaced while this page held a stale `v`) drops the entry and fails the + * clip, which then plays on an element. */ -const tracks = new Map<string, Promise<Track | null>>(); -function trackOf(url: string): Promise<Track | null> { +const tracks = new Map<string, Promise<{ track: Track | null; etag: string | null }>>(); +function trackOf(url: string): Promise<{ track: Track | null; etag: string | null }> { let p = tracks.get(url); if (!p) { // Its own controller: a decoder closed mid-read must not abort what the next one will want. - p = readMoov(url, new AbortController().signal).then((m) => videoTrackOf(m)); + p = readMoov(url, new AbortController().signal).then((m) => ({ track: videoTrackOf(m.moov), etag: m.etag })); p.catch(() => tracks.delete(url)); tracks.set(url, p); if (tracks.size > 32) tracks.delete(tracks.keys().next().value!); @@ -110,6 +139,8 @@ class ClipDecoder { /** A read under way: its first sample → the sample after its last. */ private pending = new Map<number, number>(); private abort = new AbortController(); + /** The ETag the moov was read under: every block read is held to it. */ + private etag: string | null = null; used = 0; constructor(readonly url: string) { @@ -118,7 +149,8 @@ class ClipDecoder { private async open() { try { - const track = await trackOf(this.url); + const { track, etag } = await trackOf(this.url); + this.etag = etag; if (!track) return this.refuse("not a progressive mp4 with a known video codec"); const config: VideoDecoderConfig = { codec: track.codec, @@ -182,7 +214,7 @@ class ClipDecoder { } this.blocks.set(i, null); this.pending.set(i, end); - range(this.url, a, z - 1, this.abort.signal) + range(this.url, a, z - 1, this.abort.signal, this.etag) .then((buf) => { if (this.state === "closed") return; this.blocks.set(i, { end, base: a, buf }); diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -35,9 +35,16 @@ import { ElementPicture } from "./elementPicture"; export type Plan = ReturnType<typeof playPlan>; type Item = Plan["items"][number]; +/** + * A clip's cached window: its name for the media routes, and the version of + * its bytes (`v`, serve.mjs windowVersion) -- in every URL built for it, so a + * window refetched under the same name is a new URL to the browser's cache, + * the moov cache (codecPicture.ts) and the sound bank alike. + */ +export type MediaRef = { name: string; v?: string | null }; export type EngineEntry = { id: string; - media?: { name: string; from: number; to: number } | null; + media?: (MediaRef & { from: number; to: number }) | null; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; }; export type EngineUi = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean }; @@ -51,8 +58,8 @@ export type EngineInfo = { }; type Opts = { - srcOf: (id: string, file: string) => string; - audioOf: (id: string, file: string, from: number, to: number) => string; + srcOf: (id: string, media: MediaRef) => string; + audioOf: (id: string, media: MediaRef, from: number, to: number) => string; onUi: (ui: EngineUi) => void; onFailed: (id: string, why: string) => void; onInfo: (info: EngineInfo) => void; @@ -332,11 +339,11 @@ export class PlayEngine { // ---- the sound ------------------------------------------------------------------ - private spanSound(id: string): { file: string; span: { from: number; to: number } } | null { + private spanSound(id: string): { media: MediaRef; span: { from: number; to: number } } | null { const e = this.entries.get(id); const s = this.spans.find((x) => x.id === id); if (!e?.media || !s) return null; - return { file: e.media.name, span: decodeSpanOf(s) }; + return { media: e.media, span: decodeSpanOf(s) }; } /** Decode the clips around the playhead; the bank lets the far ones go. */ @@ -347,10 +354,10 @@ export class PlayEngine { if (!it.clip) continue; const ss = this.spanSound(it.id); if (!ss) continue; - keys.push(AudioBank.keyOf(it.id, ss.file, ss.span)); - void this.bank.request(it.id, ss.file, ss.span).then((got) => { + keys.push(AudioBank.keyOf(it.id, ss.media, ss.span)); + void this.bank.request(it.id, ss.media, ss.span).then((got) => { if (!got && !this.silent[it.id]) { - this.silent = { ...this.silent, [it.id]: this.bank.why(it.id, ss.file, ss.span) ?? "no sound" }; + this.silent = { ...this.silent, [it.id]: this.bank.why(it.id, ss.media, ss.span) ?? "no sound" }; } }); } @@ -371,7 +378,7 @@ export class PlayEngine { continue; } const ss = this.spanSound(p.id); - const got = ss ? this.bank.peek(p.id, ss.file, ss.span) : "failed"; + const got = ss ? this.bank.peek(p.id, ss.media, ss.span) : "failed"; // (A clip whose PICTURE failed still sounds: its sound is decoded on the server, not by the element.) if (got === "failed" || !ss) { this.started.add(key); // silent: the clock goes on @@ -454,8 +461,8 @@ export class PlayEngine { const p = this.plannedFrom.find((x) => !this.started.has(`${x.id}|${x.atWall}`) && this.t0 + (x.atWall + x.durWall) * this.rate > this.t); const ss = p ? this.spanSound(p.id) : null; // Asked for here too: a hold far from where the prefetch looks (a seek) must not wait on nothing. - if (p && ss) void this.bank.request(p.id, ss.file, ss.span); - const got = p && ss ? this.bank.peek(p.id, ss.file, ss.span) : null; + if (p && ss) void this.bank.request(p.id, ss.media, ss.span); + const got = p && ss ? this.bank.peek(p.id, ss.media, ss.span) : null; if (!p || !ss || got === "failed" || (got && got !== "loading" && this.bank.hasRate(got as ClipSound, this.rate))) { this.restart(this.t); } else if (got && got !== "loading") this.bank.atRate(got as ClipSound, this.rate); @@ -503,7 +510,7 @@ export class PlayEngine { private mediaUrl(i: number) { const it = this.plan.items[i]; const e = it ? this.entries.get(it.id) : null; - return it && e?.media ? this.o.srcOf(it.id, e.media.name) : null; + return it && e?.media ? this.o.srcOf(it.id, e.media) : null; } private mediaTimeOf(i: number, t: number) { diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useRef, useState } from "react"; -import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type Plan } from "./engine"; +import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type MediaRef, type Plan } from "./engine"; // The Play view's engine (engine.ts) as a hook: PlayCut.tsx hands it the plan // and the entries, and gets back what it renders from (`ui`, `failed`, @@ -13,8 +13,8 @@ import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type Plan type Args = { plan: Plan; entries: Map<string, EngineEntry>; - srcOf: (id: string, file: string) => string; - audioOf: (id: string, file: string, from: number, to: number) => string; + srcOf: (id: string, media: MediaRef) => string; + audioOf: (id: string, media: MediaRef, from: number, to: number) => string; blurRendered: boolean; bg: string; /** render.transitionStyle: how a crossfade is drawn (a dissolve, or a dip through the ground). */ @@ -44,8 +44,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, } })(); const e = new PlayEngine({ - srcOf: (id, file) => fns.current.srcOf(id, file), - audioOf: (id, file, from, to) => fns.current.audioOf(id, file, from, to), + srcOf: (id, media) => fns.current.srcOf(id, media), + audioOf: (id, media, from, to) => fns.current.audioOf(id, media, from, to), onUi: setUi, onFailed: (id, why) => setFailed((f) => ({ ...f, [id]: why })), onInfo: setInfo, diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -36,9 +36,18 @@ moment a window is off by the pad and nobody can see why. in the browser. No ffmpeg per drag. **A 206 is not optional** — without one the `<video>` element will not seek in a -stream it did not fully download, and that is the entire interaction. The file is -immutable (its window is in its name), so it is cached hard and `analyseMedia`'s -envelope can never miss twice for the same window. +stream it did not fully download, and that is the entire interaction. + +**Cached by the version of its bytes, not its name.** A window's name says which +seconds it holds; a refetch (`umtool fetch --refetch`, the editor's evict + fetch, +the saved-video replace) writes new bytes under the same name, often with an old +mtime. So the bench page, the clip route and the Play view hand out each window's +`v` — a hash of its file's device, inode, size, mtime and ctime (an excerpt's is +its recording's) — the media URLs carry it, and `/api/report/raw`, `/audio` and +`/peaks` answer `immutable` only to the current `v`, `no-cache` otherwise, with a +strong ETag (a 304 on If-None-Match; the whole file under a stale If-Range). The +Play view's parsed moov is keyed by that URL, and a block read whose ETag is not +the moov's fails the clip onto a `<video>` rather than decode the wrong bytes. `file` must be a member of the server's own scan of that clip's cached windows. Never a path from the client. @@ -275,8 +284,12 @@ it runs), `umtool prep <project>`, and on their own after a fetch lands a window and after a write that moves a clip's extent or adds one (an excerpt is cut only then; a waveform is made too after a fetch). It makes exactly what the first open would: the excerpt, by the same name, and the waveform in the cache -`/api/report/peaks` reads. A clip already prepared is skipped (its excerpt newer -than its recording, its waveform cached). Not the decoded audio: once the +`/api/report/peaks` reads. A clip already prepared is skipped (its excerpt cut +from its recording as it is now, its waveform cached). **Not "newer than its +recording"**: the cut records the recording's identity in +`<excerpt>.src.json`, and an excerpt whose record does not match the recording +today — or that has none — is cut again. A good copy replacing a corrupt one +under an older mtime used to leave the corrupt excerpts playing. Not the decoded audio: once the excerpt exists `/api/report/audio` decodes the first span in a fraction of a second. diff --git a/umtool/e2e/clip-bench.spec.ts b/umtool/e2e/clip-bench.spec.ts @@ -240,6 +240,26 @@ test("the raw window serves byte ranges, and refuses a file that is not this cli expect(part.status()).toBe(206); expect(part.headers()["content-range"]).toMatch(/^bytes 0-1023\/\d+$/); + // Cached by the VERSION of the bytes, never by the window's name (serve.mjs, + // "A REPLACED FILE IS A NEW FILE"): a refetch writes new bytes under the + // same name. The clip route hands out `v`; only a URL carrying the current + // one is immutable, and every answer has a strong ETag to revalidate on. + const etag = full.headers()["etag"]; + expect(etag).toMatch(/^"[0-9a-f]{16}"$/); + expect(full.headers()["cache-control"]).toBe("private, no-cache"); + expect(part.headers()["etag"]).toBe(etag); + const clipInfo = await (await request.get(`/api/report/clip?${q}`)).json(); + const v = clipInfo.windows[0].v as string; + expect(v).toMatch(/^[0-9a-f]{16}$/); + const versioned = await request.get(`/api/report/raw?${q}&file=${encodeURIComponent(clipInfo.windows[0].name)}&v=${v}`); + expect(versioned.headers()["cache-control"]).toContain("immutable"); + expect(versioned.headers()["etag"]).toBe(etag); + expect((await request.get(`/api/report/raw?${q}&v=0000000000000000`)).headers()["cache-control"]).toBe("private, no-cache"); + expect((await request.get(`/api/report/raw?${q}`, { headers: { "If-None-Match": etag } })).status()).toBe(304); + // A range under an If-Range naming another file is the whole file, never a 206 to stitch to it. + const stale = await request.get(`/api/report/raw?${q}`, { headers: { Range: "bytes=0-1023", "If-Range": '"another-file"' } }); + expect(stale.status()).toBe(200); + // `file` must be a member of the server's own scan for THIS clip's video. expect((await request.get(`/api/report/raw?${q}&file=vid2_0.00-9.00.mp4`)).status()).toBe(404); expect((await request.get(`/api/report/raw?${q}&file=../../../etc/passwd`)).status()).toBe(404); diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts @@ -209,10 +209,12 @@ test("a take plays its own timeline (its patch over the project's manifest); a r await page.goto(urls.takesHref(PROJECT)); await expect(page.locator('a[data-play-take="short"]')).toHaveAttribute("href", urls.playHref(PROJECT, { take: "short" })); - // The take's clip comes through the raw route with the take named (whichever path decodes it). + // The take's clip comes through the raw route with the take named (whichever path decodes it), + // and the version of the window's bytes: a refetch under the same name is a new URL. const takeMedia = page.waitForRequest((r) => { const u = new URL(r.url()); - return u.pathname === "/api/report/raw" && u.searchParams.get("clip") === "c01" && u.searchParams.get("take") === "short"; + return u.pathname === "/api/report/raw" && u.searchParams.get("clip") === "c01" && u.searchParams.get("take") === "short" + && /^[0-9a-f]{16}$/.test(u.searchParams.get("v") ?? ""); }); await page.goto(urls.playHref(PROJECT, { take: "short" })); await expect(root(page)).toHaveAttribute("data-play-cut", "short"); diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts @@ -8,7 +8,7 @@ import { resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip import { CHANNELS_DIR } from "@/lib/paths"; import { answerOf } from "@/lib/research/fetch"; import { SourceError } from "@/lib/research/sources"; -import { projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs"; +import { projectCache, resolveClip, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; import { corpusMediaUrl } from "@/lib/articles/article"; import type { CitedFetchAnswer, CitedPlay, CitedTarget } from "./types"; import { fetchFailureSentence } from "./words"; @@ -69,9 +69,11 @@ async function projectPlay(t: CitedTarget): Promise<CitedPlay | null> { .filter((w) => w.from <= t.from + WIN_EPS && w.to >= t.to - WIN_EPS) .sort((a, b) => own(a) - own(b))[0]; if (!win) return null; + const ver = await windowVersion(win as { name: string; path: string; from: number; to: number }); return { kind: "window", - url: `/api/report/raw?${new URLSearchParams({ project: t.project, clip: t.clip, file: win.name })}`, + // `v`: the version of the window's bytes (serve.mjs, "A REPLACED FILE IS A NEW FILE"). + url: `/api/report/raw?${new URLSearchParams({ project: t.project, clip: t.clip, file: win.name, ...(ver ? { v: ver } : {}) })}`, offset: Math.max(0, t.from - win.from), audio: false, label: `clip window ${win.name}`, diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs @@ -9,7 +9,7 @@ // // - the EXCERPT, through serve.mjs's own excerptOf + ensureWindowFile, so the // name, the rounding, the padding and the encode are the bench's, and the -// bench finds it ("newer than its source = done"); +// bench finds it (cut from its source as it is now = done); // - the WAVEFORM, through lib/analyse.mjs, the same disk cache // /api/report/peaks reads (keyed by the file's path, mtime and size). // @@ -99,7 +99,7 @@ const alive = (pid) => { * Per clip: the window the bench would open (windowsFor's first, the same * listing the clip route and the bench page read) and what of it is on disk. * - * `cut`: the excerpt is there and newer than its recording (a real window is + * `cut`: the excerpt is there and was cut from its recording as it is now (a real window is * always "cut"). `peaks`: its analysis is in the cache. A clip whose last prep * of THIS window failed reads `failed` until the window changes (an explicit * prep tries it again; a trigger does not). diff --git a/umtool/lib/report/benchPrep.test.mjs b/umtool/lib/report/benchPrep.test.mjs @@ -143,7 +143,7 @@ test("the bench's serve path takes a prepared file: no cut, and the cached wavef assert.equal((await analyseFile(abs)).label, "from-the-cache", "the peaks route's analysis reads the prepared file"); }); -test("a recording newer than its excerpt is prepared again; a cut in flight in another process is waited for, not repeated", async () => { +test("a recording changed since its excerpt was cut is prepared again; a cut in flight in another process is waited for, not repeated", async () => { const win = await benchWindow("long"); const src = path.join(raw, "vid_0.00-700.00.mp4"); const later = new Date(Date.now() + 5000); @@ -160,6 +160,8 @@ test("a recording newer than its excerpt is prepared again; a cut in flight in a await new Promise((r) => setTimeout(r, 300)); const t = new Date(Date.now() + 10_000); await utimes(win.path, t, t); + // What the other process's cut leaves beside its excerpt: the source it was cut from. + await writeFile(serve.excerptSourceOf(win.path), JSON.stringify(await serve.sourceIdentity(src))); await rm(serve.cutMarkOf(win.path)); })(); // A real cut would need ffmpeg: this one must wait for the other process instead. diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -13,7 +13,7 @@ import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { clipDateKey, clipVerdict, readManifest } from "../projects/report.mjs"; import { dateKeyLabel } from "./playCut.mjs"; -import { pickWindow, projectCache, windowsFor } from "./serve.mjs"; +import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); @@ -79,8 +79,10 @@ export async function playView(project, { take = null } = {}) { blur: e.blur && typeof e.blur === "object" ? e.blur : null, // Ruled incorrect (the walk's verdict): its correction -- Play skips it unless asked to show it. incorrect: clipVerdict(e) === "incorrect" ? text(e.correction) || (e.reason === "wrong-speaker" ? "wrong speaker" : "marked incorrect") : null, - // The window the bench would play: its name for the raw route, and the source second its file starts at. - media: win ? { name: win.name, from: win.from, to: win.to } : null, + // The window the bench would play: its name for the raw route, the source second its file starts at, + // and the version of its bytes (`v`: a refetch under the same name is a new URL -- serve.mjs, + // "A REPLACED FILE IS A NEW FILE"). + media: win ? { name: win.name, from: win.from, to: win.to, v: await windowVersion(win) } : null, }; }), ); diff --git a/umtool/lib/report/prepCli.mjs b/umtool/lib/report/prepCli.mjs @@ -27,7 +27,7 @@ export const PREP_USAGE = [ " umtool prep <project> --status [--json] ready / to prepare / not fetched, and the runner", "", "One clip at a time, each in the heavy slot (estimate " + PREP_ESTIMATE_MB + " MB), under nice -n 19 and ionice -c3.", - "A clip already prepared (its excerpt newer than its recording, its waveform cached) is skipped.", + "A clip already prepared (its excerpt cut from its recording as it is now, its waveform cached) is skipped.", ].join("\n"); /** @param {Awaited<ReturnType<typeof benchPrepState>>} s */ diff --git a/umtool/lib/report/serve-excerpt.test.mjs b/umtool/lib/report/serve-excerpt.test.mjs @@ -6,12 +6,12 @@ import test from "node:test"; import path from "node:path"; import os from "node:os"; import { execFileSync } from "node:child_process"; -import { mkdtemp, rm, stat } from "node:fs/promises"; +import { mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; const root = await mkdtemp(path.join(os.tmpdir(), "bench-excerpt-")); // The roots are read when paths.mjs loads: this file's temp dir is one. process.env.MIX_ROOTS = root; -const { excerptOf, ensureWindowFile, EXCERPT_OVER_S } = await import("./serve.mjs"); +const { excerptOf, excerptSourceOf, ensureWindowFile, windowEtag, windowFileFresh, windowVersion, EXCERPT_OVER_S } = await import("./serve.mjs"); test.after(() => rm(root, { recursive: true, force: true })); @@ -59,3 +59,89 @@ test("the excerpt is cut once, frame-exact, both tracks from zero", async () => // A real window is never touched. await ensureWindowFile({ name: "w.mp4", path: path.join(root, "nope.mp4"), from: 0, to: 1 }); }); + +test("a replaced recording -- even one with an OLDER mtime -- makes its excerpt stale, and it is cut again", async () => { + const src = path.join(root, "replaced-media.mp4"); + const make = (pattern, out) => + execFileSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", `${pattern}=size=320x240:rate=25:duration=40`, + "-f", "lavfi", "-i", "sine=frequency=440:duration=40", + "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", out, + ]); + make("testsrc2", src); + const rec = { name: "replaced-media.mp4", path: src, from: 0, to: 40 }; + const e = excerptOf(rec, { video: "rep", start: 18, end: 22 }, root, { over: 10, pad: 3, step: 5 }); + await ensureWindowFile(e); + assert.equal(await windowFileFresh(e), true); + const side = JSON.parse(await readFile(excerptSourceOf(e.path), "utf8")); + assert.equal(side.path, src); + assert.equal(side.size, (await stat(src)).size, "the sidecar records the source it was cut from"); + const first = await stat(e.path); + const v1 = await windowVersion(e); + assert.equal(v1, await windowVersion(rec), "an excerpt's version is its source's"); + + // The real case: the excerpt was cut AFTER its source's mtime, and a good + // copy lands under the same name dated earlier still (yt-dlp --mtime; the + // saved-video replace). "Newer than its source" said fresh, and Play showed + // the corrupt cut for good. + const next = path.join(root, "replaced-media.next.mp4"); + make("smptebars", next); + const old = new Date(first.mtimeMs - 3_600_000); + await utimes(next, old, old); + await rename(next, src); + assert.ok((await stat(src)).mtimeMs < first.mtimeMs, "the replacement is older than the excerpt"); + assert.equal(await windowFileFresh(e), false, "a replaced source makes the excerpt stale"); + assert.notEqual(await windowVersion(e), v1, "and its version changes, so the URL does"); + await ensureWindowFile(e); + assert.equal(await windowFileFresh(e), true); + assert.notEqual((await stat(e.path)).ino, first.ino, "cut again"); + + // An excerpt with no sidecar (cut before there were any) is stale too. + await rm(excerptSourceOf(e.path)); + assert.equal(await windowFileFresh(e), false); + await ensureWindowFile(e); + assert.equal(await windowFileFresh(e), true); +}); + +test("a window's version changes with its size, its mtime, its inode -- and a rewrite in place that puts the mtime back", async () => { + const f = path.join(root, "w_0.00-10.00.mp4"); + await writeFile(f, Buffer.alloc(1000, 1)); + const t = new Date("2026-01-01T00:00:00Z"); + await utimes(f, t, t); + const win = { name: "w_0.00-10.00.mp4", path: f, from: 0, to: 10 }; + const v0 = await windowVersion(win); + assert.match(String(v0), /^[0-9a-f]{16}$/); + assert.equal(await windowVersion(win), v0, "unchanged, the same"); + const seen = new Set([v0]); + const isNew = async (why) => { + const v = await windowVersion(win); + assert.ok(!seen.has(v), why); + seen.add(v); + }; + + // The same bytes under the same name, by rename, with the old mtime: a new inode. + await writeFile(`${f}.tmp`, Buffer.alloc(1000, 1)); + await utimes(`${f}.tmp`, t, t); + await rename(`${f}.tmp`, f); + await isNew("a replace by rename is a new file"); + // Rewritten in place, the same size, the mtime put back: only ctime says so. + await new Promise((r) => setTimeout(r, 20)); + await writeFile(f, Buffer.alloc(1000, 2)); + await utimes(f, t, t); + await isNew("a rewrite in place with its mtime restored is a new version"); + await writeFile(f, Buffer.alloc(1001, 2)); + await utimes(f, t, t); + await isNew("another size"); + const later = new Date("2026-02-01T00:00:00Z"); + await utimes(f, later, later); + await isNew("another mtime"); + + assert.equal(await windowVersion({ name: "gone.mp4", path: path.join(root, "gone.mp4"), from: 0, to: 1 }), null); + assert.equal(await windowVersion({ name: "x.mp4", path: "/etc/passwd", from: 0, to: 1 }), null, "outside the roots"); + + // The ETag of what is sent: the version, and for an excerpt its own file too. + const st = await stat(f); + assert.equal(windowEtag("abc", win, st), '"abc"'); + assert.match(windowEtag("abc", { excerptOf: {} }, st), /^"abc\.[0-9a-f]{16}"$/); +}); diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs @@ -6,6 +6,7 @@ // name that is simply not there fails, and a traversal fails twice: once on the // membership check and once on resolveInRoots. import path from "node:path"; +import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises"; import { execFile } from "node:child_process"; @@ -238,10 +239,123 @@ export async function foreignCut(file, { now = Date.now(), self = process.pid } return alive(pid) ? { pid, at } : null; } +// --------------------------------------------------------------------------- +// A REPLACED FILE IS A NEW FILE. +// +// A window's NAME says which seconds it holds, not which bytes. `umtool fetch +// --refetch`, the editor's evict-clips + refetch and the saved-video replace +// all write new bytes under the old name -- often with the old mtime, or an +// older one (yt-dlp --mtime; the store keeps the recording's). So nothing that +// caches by name may trust the name: the browser's HTTP cache (the routes said +// `immutable`), the Play view's parsed moov (codecPicture.ts), an excerpt cut +// from the file before. +// +// A file is known instead by its IDENTITY -- device, inode, size, mtime and +// ctime. A replace by rename is a new inode; a rewrite in place moves ctime, +// which no writer can set back. windowVersion() hashes it into `v`: playView +// and the clip route hand it out, the media URLs carry it, and the raw route +// answers `immutable` only to the `v` that is current, with a strong ETag of +// the file it actually sent. An excerpt's `v` is its SOURCE's identity -- the +// excerpt is made from that and nothing else, and need not exist yet when the +// view is read -- and the excerpt records the same identity beside itself +// (`<excerpt>.src.json`) when it is cut. +// --------------------------------------------------------------------------- + +/** + * The identity of the file a stat describes. + * @param {import("node:fs").Stats} st + */ +export const identityOf = (st) => ({ dev: st.dev, ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs }); + +/** + * A file's identity, read now (through any symlink: a tier link points at the bytes). + * @param {string} abs + */ +export async function sourceIdentity(abs) { + return { path: abs, ...identityOf(await stat(abs)) }; +} + +/** + * Two recorded identities are the same file, unchanged. + * @param {any} a + * @param {any} b + */ +export function sameIdentity(a, b) { + if (!a || !b) return false; + return ["path", "dev", "ino", "size", "mtimeMs", "ctimeMs"].every((k) => a[k] === b[k]); +} + +/** + * A short hash of an identity: the `v` a media URL carries, the body of an ETag. + * @param {{ dev: number, ino: number, size: number, mtimeMs: number, ctimeMs: number }} id + */ +export const identityTag = (id) => + createHash("sha1").update(JSON.stringify([id.dev, id.ino, id.size, id.mtimeMs, id.ctimeMs])).digest("hex").slice(0, 16); + +/** Where an excerpt records the identity of the source it was cut from. */ +export const excerptSourceOf = (file) => `${file}.src.json`; + +/** + * The version of a window's bytes: its file's identity, hashed -- for an + * excerpt, its SOURCE's. Null when the file is not there (or is outside the roots). + * + * @param {{path: string, excerptOf?: {path: string}} | null | undefined} win + * @returns {Promise<string | null>} + */ +export async function windowVersion(win) { + const p = win?.excerptOf ? win.excerptOf.path : win?.path; + const abs = p ? resolveInRoots(p) : null; + if (!abs) return null; + const st = await stat(abs).catch(() => null); + return st ? identityTag(identityOf(st)) : null; +} + +/** + * The strong ETag of the file a route sends for a window: its version, and + * for an excerpt the excerpt file's own identity too -- an excerpt cut again + * from the same source is another file, and a range of one must never be + * stitched to a range of the other. + * + * @param {string} version windowVersion(win) + * @param {{excerptOf?: unknown}} win + * @param {import("node:fs").Stats} sent the stat of the file being sent + */ +export const windowEtag = (version, win, sent) => + `"${win?.excerptOf ? `${version}.${identityTag(identityOf(sent))}` : version}"`; + +/** + * The cache-control for a window's bytes: hard (`immutable`) only when the URL + * names the version being served -- a replaced file has a new `v`, so a new + * URL -- and otherwise revalidated against the ETag on every use. + * + * @param {string | null} asked the request's `v` + * @param {string | null} version windowVersion(win) + */ +export const windowCacheControl = (asked, version) => + asked && version && asked === version ? "private, max-age=31536000, immutable" : "private, no-cache"; + +/** + * Does the request's If-None-Match name this ETag? (`*`, or a list; weak or strong, as RFC 9110's weak comparison.) + * @param {Request} request + * @param {string} etag + */ +export function notModified(request, etag) { + const inm = request.headers.get("if-none-match"); + if (!inm) return false; + if (inm.trim() === "*") return true; + const bare = (/** @type {string} */ t) => t.trim().replace(/^W\//, ""); + return inm.split(",").some((t) => bare(t) === bare(etag)); +} + /** * Is a window's file on disk and current? A real window always is (nothing - * here makes one). An excerpt is when it is NEWER THAN ITS SOURCE: a - * re-fetched recording invalidates every excerpt cut from it. + * here makes one). An excerpt is when it was CUT FROM ITS SOURCE AS IT IS NOW: + * the identity its sidecar recorded at the cut is the source's identity today, + * exactly. Not "newer than its source" -- a recording replaced under the same + * name often carries an OLDER mtime (yt-dlp --mtime; the saved-video replace), + * and excerpts cut at 12:30 from a corrupt copy outlived its replacement by a + * good one dated 10:27. No sidecar (an excerpt cut before there were any, or a + * cut that died between its rename and its sidecar) is stale: it is cut again. * * @param {{path: string, excerptOf?: {path: string}}} win */ @@ -249,15 +363,17 @@ export async function windowFileFresh(win) { if (!win?.excerptOf) return true; const src = resolveInRoots(win.excerptOf.path); if (!src) throw new Error("the recording is outside the roots"); - const srcSt = await stat(src); + const now = await sourceIdentity(src); const have = await stat(win.path).catch(() => null); - return !!(have && have.size > 0 && have.mtimeMs >= srcSt.mtimeMs); + if (!have || !(have.size > 0)) return false; + const was = await readFile(excerptSourceOf(win.path), "utf8").then((t) => JSON.parse(t), () => null); + return sameIdentity(was, now); } /** * Make sure a window's file is on disk: a no-op for a real window; for an - * excerpt, cut it once (newer than its source = done) and share the cut with - * every request that asks meanwhile. + * excerpt, cut it once (cut from its source as it is now = done) and share the + * cut with every request that asks meanwhile. * * ACROSS PROCESSES too: the bench's prep (lib/report/benchPrep.mjs, `umtool * prep`) cuts the same files ahead of the walk, in a process of its own. Each @@ -287,7 +403,15 @@ export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN, waitMs = CUT_ await writeFile(mark, JSON.stringify({ pid: process.pid, at: Date.now() })).catch(() => {}); cutSeq += 1; const tmp = `${win.path}.part-${process.pid}-${cutSeq}.mp4`; + const side = excerptSourceOf(win.path); + const sideTmp = `${side}.part-${process.pid}-${cutSeq}`; try { + // The source as it is when the cut starts: what the sidecar says it was + // cut from. Replaced DURING the cut, it no longer matches, and the next + // read cuts again rather than trust these bytes. + const from = await sourceIdentity(src); + // The old record goes first: the excerpt about to land is not the file it describes. + await rm(side, { force: true }); await execFileP(ffmpeg, [ "-v", "error", "-y", "-ss", String(win.from - win.excerptOf.from), @@ -301,8 +425,11 @@ export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN, waitMs = CUT_ tmp, ], { maxBuffer: 4 * 1024 * 1024 }); await rename(tmp, win.path); + await writeFile(sideTmp, `${JSON.stringify(from)}\n`); + await rename(sideTmp, side); } catch (e) { await rm(tmp, { force: true }); + await rm(sideTmp, { force: true }); throw e; } finally { // Only our own mark: another process may have written one since. @@ -392,12 +519,24 @@ export async function resolveClaim(projectId, claimId) { * range (`bytes=-500`) is the LAST n bytes -- Chrome asks for one to find an * mp4's moov atom when it is not at the front. * + * With an `etag` (a strong one), the response carries it and the request's + * conditions are honoured: an If-None-Match naming it is a bare 304, and a + * Range under an If-Range that does not name it is answered with the whole + * file -- the bytes the client holds are of another file, and a 206 of this + * one would be stitched to them. + * * @param {Request} request - * @param {{ abs: string, size: number, headers?: Record<string, string> }} file + * @param {{ abs: string, size: number, headers?: Record<string, string>, etag?: string | null }} file * @returns {Response} */ -export function rangeResponse(request, { abs, size, headers = {} }) { - const range = request.headers.get("range"); +export function rangeResponse(request, { abs, size, headers: given = {}, etag = null }) { + const headers = etag ? { ...given, etag } : given; + if (etag && notModified(request, etag)) return new Response(null, { status: 304, headers }); + const ifRange = request.headers.get("if-range"); + // A date, or a weak or foreign tag, is never a match for a strong ETag (RFC 9110 13.1.5). + // (A caller with no ETag hands out no validator, so no If-Range is about it.) + const rangeOk = !ifRange || !etag || ifRange.trim() === etag; + const range = rangeOk ? request.headers.get("range") : null; const m = range ? /^bytes=(\d*)-(\d*)$/.exec(range.trim()) : null; if (m) { let start = m[1] ? Number(m[1]) : 0; diff --git a/umtool/lib/report/serve.test.mjs b/umtool/lib/report/serve.test.mjs @@ -23,6 +23,7 @@ import { rangeResponse, stampPreviewDir, stampPreviewSrc, + windowCacheControl, } from "./serve.mjs"; const req = (range) => new Request("http://x/", range ? { headers: { range } } : {}); @@ -96,6 +97,63 @@ test("rangeResponse: unsatisfiable is a bare 416; unparseable is the whole file" } }); +test("rangeResponse with an ETag: carried, 304 on If-None-Match, the whole file under a stale If-Range", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-range-")); + try { + const data = Buffer.from(Array.from({ length: 1000 }, (_, i) => i % 251)); + const abs = path.join(dir, "a.mp4"); + await writeFile(abs, data); + const etag = '"abc123"'; + const file = { abs, size: data.length, headers: { "content-type": "video/mp4", "cache-control": "private, no-cache" }, etag }; + const ask = (h) => new Request("http://x/", { headers: h }); + + let res = rangeResponse(ask({}), file); + assert.equal(res.status, 200); + assert.equal(res.headers.get("etag"), etag); + await res.arrayBuffer(); + + // A revalidation naming it (strong, weak, in a list, or `*`): a bare 304 that keeps the validators. + for (const inm of [etag, `W/${etag}`, `"other", ${etag}`, "*"]) { + res = rangeResponse(ask({ "if-none-match": inm }), file); + assert.equal(res.status, 304, inm); + assert.equal(res.headers.get("etag"), etag); + assert.equal(res.headers.get("cache-control"), "private, no-cache"); + assert.equal((await bytes(res)).length, 0); + } + res = rangeResponse(ask({ "if-none-match": '"other"' }), file); + assert.equal(res.status, 200, "another file's tag is not a match"); + await res.arrayBuffer(); + + // If-Range naming this file: the range. Naming another (the client's bytes are of + // a file since replaced), or a date: the whole file, never a 206 to stitch to them. + res = rangeResponse(ask({ range: "bytes=0-99", "if-range": etag }), file); + assert.equal(res.status, 206); + assert.equal(res.headers.get("etag"), etag); + await res.arrayBuffer(); + for (const ir of ['"old-file"', `W/${etag}`, "Wed, 21 Oct 2015 07:28:00 GMT"]) { + res = rangeResponse(ask({ range: "bytes=0-99", "if-range": ir }), file); + assert.equal(res.status, 200, ir); + assert.equal(res.headers.get("content-length"), "1000"); + assert.deepEqual(await bytes(res), data); + } + + // No ETag: exactly as before -- an If-Range is about nothing it handed out. + res = rangeResponse(ask({ range: "bytes=0-99", "if-range": '"x"', "if-none-match": '"x"' }), { abs, size: data.length }); + assert.equal(res.status, 206); + assert.equal(res.headers.get("etag"), null); + await res.arrayBuffer(); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a window's bytes are cached hard only under the URL's current version", () => { + assert.equal(windowCacheControl("abc", "abc"), "private, max-age=31536000, immutable"); + assert.equal(windowCacheControl(null, "abc"), "private, no-cache", "no `v`: revalidate"); + assert.equal(windowCacheControl("old", "abc"), "private, no-cache", "a stale `v`: revalidate"); + assert.equal(windowCacheControl("abc", null), "private, no-cache"); +}); + test("project ids ride as one url segment and come back exactly", () => { for (const id of ["ferret-rescue", "folder/name", "a b/ç"]) { const seg = encodeProjectSegment(id);