fix(producer): a compile's downloads stop when the compile returns, however it ends (#8321)

* test(producer): a failed compile stops its downloads, and a file's media is capped up front

* fix(producer): a compile's downloads stop when the compile returns, however it ends

* test(producer): media with a set duration is capped up front too

* fix(producer): reserve the clamp pass's media before it downloads any

* test(producer): a probe's signal fires on the render's cancel, whatever object carries it
This commit is contained in:
Miguel Ángel
2026-11-21 00:35:24 +00:00
committed by GitHub
parent ca91e800e2
commit 1ce69fd818
3 changed files with 129 additions and 23 deletions
@@ -0,0 +1,79 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { compileForRender, MAX_REMOTE_ASSETS } from "./htmlCompiler.js";
const requests = vi.hoisted(() => [] as { url: string; signal?: AbortSignal }[]);
vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../utils/urlDownloader.js")>()),
// A transport that never answers: only an abort settles a request.
downloadToTemp: (url: string, _dir: string, _timeoutMs?: number, signal?: AbortSignal) => {
requests.push({ url, signal });
return new Promise<string>((_resolve, reject) => {
signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
});
},
fetchPublicHttpsText: async () => {
throw new Error("offline test");
},
}));
const dirs: string[] = [];
afterEach(() => {
requests.length = 0;
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const videos = (prefix: string, count: number) =>
Array.from(
{ length: count },
(_, i) =>
`<video muted src="https://media.example.com/${prefix}${i}.mp4" data-start="0" data-track-index="0"></video>`,
).join("");
const scene = (id: string, body: string) =>
`<template><div data-composition-id="${id}" data-width="16" data-height="16">${body}</div></template>`;
const mount = (id: string) =>
`<div data-composition-id="${id}" data-composition-src="${id}.html" data-start="0" data-duration="1"></div>`;
function compile(files: Record<string, string>) {
const dir = mkdtempSync(join(tmpdir(), "hf-asset-lifetime-"));
dirs.push(dir);
for (const [name, html] of Object.entries(files)) writeFileSync(join(dir, name), html);
return compileForRender(dir, join(dir, "index.html"), join(dir, "out"), {
allowSystemFontCapture: false,
});
}
const root = (body: string) =>
`<!doctype html><html><head></head><body><main data-composition-id="root" data-start="0" data-duration="1" data-width="16" data-height="16">${body}</main></body></html>`;
// fails without the fix: a failed compile left its other downloads running, with nothing to stop them.
it("stops every download of a compile that fails", async () => {
const compiled = compile({
"index.html": root(mount("a") + mount("b")),
"a.html": scene("a", videos("a", 20)),
"b.html": scene("b", videos("b", MAX_REMOTE_ASSETS)),
});
await expect(compiled).rejects.toThrow(`at most ${MAX_REMOTE_ASSETS} are downloaded`);
const started = requests.length;
expect(started).toBeGreaterThan(0);
expect(requests.every((request) => request.signal?.aborted)).toBe(true);
await new Promise(setImmediate);
expect(requests).toHaveLength(started);
});
// fails without the fix: each source was reserved on its own, so the first ones started before the cap refused.
it.each([
["without", "<video "],
["with", '<video data-duration="1" '],
])(
"refuses a file's media %s a set duration past the cap before any of them downloads",
async (_with, tag) => {
const body = videos("v", MAX_REMOTE_ASSETS + 1).replaceAll("<video ", tag);
await expect(compile({ "index.html": root(body) })).rejects.toThrow(
`at most ${MAX_REMOTE_ASSETS} are downloaded`,
);
expect(requests).toHaveLength(0);
},
);
@@ -65,8 +65,9 @@ it.each(cases)(
});
compile.catch(() => {});
await vi.waitFor(() => expect(probes.calls.some((call) => call.name === probe)).toBe(true));
expect(probes.calls.every((call) => call.signal === cancel.signal)).toBe(true);
expect(probes.calls.every((call) => call.signal && !call.signal.aborted)).toBe(true);
cancel.abort(new Error("render cancelled"));
expect(probes.calls.every((call) => call.signal?.aborted)).toBe(true);
await expect(compile).rejects.toThrow("render cancelled");
},
+48 -22
View File
@@ -644,8 +644,17 @@ class AssetDownloads {
private readonly reserved = new Set<string>();
private running = 0;
private readonly queued: (() => void)[] = [];
private readonly ended = new AbortController();
readonly signal: AbortSignal;
constructor(readonly signal?: AbortSignal) {}
constructor(cancel?: AbortSignal) {
this.signal = cancel ? AbortSignal.any([cancel, this.ended.signal]) : this.ended.signal;
}
/** Stops every download still running or queued: the compile that owns them has returned. */
end(): void {
this.ended.abort(new Error("The compile that started this download has ended"));
}
/** Throws before any of `urls` downloads when they would take the compile past the cap. */
reserve(urls: Iterable<string>): void {
@@ -866,6 +875,8 @@ async function compileHtmlFile(
const unresolvedCompositions = unresolved.filter((el) => el.tagName === "div");
// Every remote source of this file counts against the cap before any of them downloads.
run?.assets.reserve(mediaUnresolved.map((el) => el.src!).filter(isHttpUrl));
// Phase 1: Resolve missing durations (parallel ffprobe)
const resolvedResults = await Promise.all(
mediaUnresolved.map((el) =>
@@ -897,26 +908,26 @@ async function compileHtmlFile(
// Explicit video slots may outlive their source and hold the final frame.
const preResolved = extractResolvedMedia(compiledHtml);
const hiddenVideoIds = collectHiddenVideoIds(compiledHtml);
const clampable = preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id));
run?.assets.reserve(clampable.map((el) => el.src!).filter(isHttpUrl));
const clampResults = await Promise.all(
preResolved
.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id))
.map(async (el) => {
const { duration: maxDuration } = await resolveMediaDuration(
el.src!,
el.mediaStart,
el.playbackRate,
projectDir,
baseDir,
downloadDir,
el.tagName,
el.id,
log,
undefined,
run,
assetRoot,
);
return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src! };
}),
clampable.map(async (el) => {
const { duration: maxDuration } = await resolveMediaDuration(
el.src!,
el.mediaStart,
el.playbackRate,
projectDir,
baseDir,
downloadDir,
el.tagName,
el.id,
log,
undefined,
run,
assetRoot,
);
return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src! };
}),
);
const clampList: ResolvedDuration[] = [];
for (const r of clampResults) {
@@ -2563,12 +2574,27 @@ const entryFileName = (projectDir: string, htmlPath: string) =>
* Compile an HTML composition project into a single self-contained HTML string
* with all media metadata resolved.
*/
// fallow-ignore-next-line complexity
export async function compileForRender(
projectDir: string,
htmlPath: string,
downloadDir: string,
options: CompileForRenderOptions = {},
): Promise<CompiledComposition> {
const assets = new AssetDownloads(options.abortSignal);
try {
return await compileWithAssets(projectDir, htmlPath, downloadDir, options, assets);
} finally {
assets.end();
}
}
// fallow-ignore-next-line complexity
async function compileWithAssets(
projectDir: string,
htmlPath: string,
downloadDir: string,
options: CompileForRenderOptions,
assets: AssetDownloads,
): Promise<CompiledComposition> {
const assetRoot = options.allowOutsideProjectAssets ? undefined : projectDir;
const outsideFiles: OutsideFilePolicy = { includeScripts: options.includeOutsideScripts };
@@ -2607,7 +2633,7 @@ export async function compileForRender(
// start.
assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
const run: CompileRun = { probes: new Map(), assets: new AssetDownloads(options.abortSignal) };
const run: CompileRun = { probes: new Map(), assets };
const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
rawHtml,
projectDir,