diff --git a/packages/producer/src/services/htmlCompiler.compileAssetCap.test.ts b/packages/producer/src/services/htmlCompiler.compileAssetCap.test.ts
new file mode 100644
index 0000000000..cbfba2dc7b
--- /dev/null
+++ b/packages/producer/src/services/htmlCompiler.compileAssetCap.test.ts
@@ -0,0 +1,83 @@
+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 transport = vi.hoisted(() => ({ requested: [] as string[], inFlight: 0, mostInFlight: 0 }));
+vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ downloadToTemp: (url: string) => {
+ transport.requested.push(url);
+ transport.inFlight += 1;
+ transport.mostInFlight = Math.max(transport.mostInFlight, transport.inFlight);
+ return new Promise((_resolve, reject) =>
+ setImmediate(() => {
+ transport.inFlight -= 1;
+ reject(new Error("offline test"));
+ }),
+ );
+ },
+ fetchPublicHttpsText: async () => {
+ throw new Error("offline test");
+ },
+}));
+
+const dirs: string[] = [];
+afterEach(() => {
+ Object.assign(transport, { requested: [], inFlight: 0, mostInFlight: 0 });
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const images = (count: number) =>
+ Array.from({ length: count }, (_, i) => `
`).join(
+ "",
+ );
+const backgrounds = (count: number) =>
+ Array.from(
+ { length: count },
+ (_, i) => ``,
+ ).join("");
+
+function compile(body: string) {
+ const dir = mkdtempSync(join(tmpdir(), "hf-asset-cap-"));
+ dirs.push(dir);
+ writeFileSync(
+ join(dir, "index.html"),
+ `${body}`,
+ );
+ return compileForRender(dir, join(dir, "index.html"), join(dir, "out"), {
+ allowSystemFontCapture: false,
+ });
+}
+
+// fails without the fix: every distinct remote asset of a pass started downloading at once.
+it("keeps at most a few asset downloads in flight", async () => {
+ await compile(images(50));
+
+ expect(transport.requested).toHaveLength(50);
+ expect(transport.mostInFlight).toBeLessThanOrEqual(8);
+});
+
+// fails without the fix: no count limited the remote assets one compile downloads.
+it("refuses a composition naming more remote assets than the cap before downloading them", async () => {
+ await expect(compile(images(MAX_REMOTE_ASSETS + 1))).rejects.toThrow(
+ `at most ${MAX_REMOTE_ASSETS} are downloaded`,
+ );
+ expect(transport.requested).toHaveLength(0);
+});
+
+it("refuses the pass that would cross the cap before it starts any of its downloads", async () => {
+ const half = MAX_REMOTE_ASSETS / 2 + 1;
+ await expect(compile(images(half) + backgrounds(half))).rejects.toThrow(
+ `at most ${MAX_REMOTE_ASSETS} are downloaded`,
+ );
+ expect(transport.requested.filter((url) => url.endsWith(".png"))).toHaveLength(half);
+ expect(transport.requested.filter((url) => url.endsWith(".jpg"))).toHaveLength(0);
+});
+
+it("downloads a composition at the cap", async () => {
+ await compile(images(MAX_REMOTE_ASSETS));
+
+ expect(new Set(transport.requested).size).toBe(MAX_REMOTE_ASSETS);
+});
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 5e5d80a0e4..d64a0313eb 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -635,10 +635,61 @@ type SourceProbe = { profile: MediaProbeProfile; fileDuration: number | null } |
/** One probe per unique source for a whole compile, whatever number of elements point at it. */
type SourceProbes = Map>;
+/** At most this many distinct remote media, image and font files download for one compile. */
+export const MAX_REMOTE_ASSETS = 1000;
+const ASSET_DOWNLOADS_AT_ONCE = 8;
+
+/** One compile's media, image and font downloads: its cancel, a cap on distinct files, a few at a time. */
+class AssetDownloads {
+ private readonly reserved = new Set();
+ private running = 0;
+ private readonly queued: (() => void)[] = [];
+
+ constructor(readonly signal?: AbortSignal) {}
+
+ /** Throws before any of `urls` downloads when they would take the compile past the cap. */
+ reserve(urls: Iterable): void {
+ this.signal?.throwIfAborted();
+ const fresh = new Set([...urls].filter((url) => !this.reserved.has(url)));
+ if (this.reserved.size + fresh.size > MAX_REMOTE_ASSETS) {
+ throw new Error(
+ `The composition links more than ${MAX_REMOTE_ASSETS} remote media, image and font files; at most ${MAX_REMOTE_ASSETS} are downloaded at compile time`,
+ );
+ }
+ for (const url of fresh) this.reserved.add(url);
+ }
+
+ async download(url: string, destDir: string): Promise {
+ while (this.running >= ASSET_DOWNLOADS_AT_ONCE) {
+ await new Promise((resolve) => this.queued.push(resolve));
+ }
+ if (this.signal?.aborted) {
+ this.queued.shift()?.();
+ this.signal.throwIfAborted();
+ }
+ this.running += 1;
+ try {
+ return await downloadToTemp(url, destDir, undefined, this.signal, undefined, {
+ onTelemetry: logRemoteDownloadTelemetry,
+ });
+ } finally {
+ this.running -= 1;
+ this.queued.shift()?.();
+ }
+ }
+}
+
+const downloadAsset = (url: string, destDir: string, assets?: AssetDownloads) =>
+ assets
+ ? assets.download(url, destDir)
+ : downloadToTemp(url, destDir, undefined, undefined, undefined, {
+ onTelemetry: logRemoteDownloadTelemetry,
+ });
+
/** What one compile shares across the root and every sub-composition it compiles. */
interface CompileRun {
probes: SourceProbes;
- signal?: AbortSignal;
+ assets: AssetDownloads;
}
async function resolveMediaDuration(
@@ -660,12 +711,11 @@ async function resolveMediaDuration(
if (isHttpUrl(src)) {
const remoteDir = join(downloadDir, REMOTE_MEDIA_SUBDIR);
if (!existsSync(remoteDir)) mkdirSync(remoteDir, { recursive: true });
+ run?.assets.reserve([src]);
try {
- filePath = await downloadToTemp(src, remoteDir, undefined, run?.signal, undefined, {
- onTelemetry: logRemoteDownloadTelemetry,
- });
+ filePath = await downloadAsset(src, remoteDir, run?.assets);
} catch (err) {
- if (run?.signal?.aborted) throw err;
+ if (run?.assets.signal?.aborted) throw err;
// Download failed (e.g. 404 placeholder URL) — skip gracefully.
// The element will get duration 0 and be excluded from the render.
return { duration: null, resolvedPath: src };
@@ -1764,10 +1814,10 @@ async function downloadAndRewriteUrls(
remoteDir: string,
warnLabel: string,
logLabel: string,
- signal: AbortSignal | undefined,
+ assets: AssetDownloads | undefined,
extraRewrite?: (html: string, url: string, relPath: string) => string,
): Promise<{ html: string; remoteMediaAssets: Map }> {
- signal?.throwIfAborted();
+ assets?.reserve(urlSet);
if (urlSet.size === 0) return { html, remoteMediaAssets: new Map() };
if (!existsSync(remoteDir)) mkdirSync(remoteDir, { recursive: true });
@@ -1775,12 +1825,10 @@ async function downloadAndRewriteUrls(
await Promise.all(
[...urlSet].map(async (url) => {
try {
- const localPath = await downloadToTemp(url, remoteDir, undefined, signal, undefined, {
- onTelemetry: logRemoteDownloadTelemetry,
- });
+ const localPath = await downloadAsset(url, remoteDir, assets);
urlToLocal.set(url, localPath);
} catch (err) {
- if (signal?.aborted) throw err;
+ if (assets?.signal?.aborted) throw err;
const identity = safeDownloadUrlIdentity(url);
defaultLogger.warn(`[Compiler] ${warnLabel}, using original URL as fallback.`, {
urlFingerprint: identity.urlFingerprint,
@@ -1831,7 +1879,7 @@ async function downloadAndRewriteUrls(
export async function localizeRemoteMediaSources(
html: string,
downloadDir: string,
- signal?: AbortSignal,
+ assets?: AssetDownloads,
): Promise<{ html: string; remoteMediaAssets: Map }> {
const urlSet = new Set([...remoteSrcUrls(html, "media"), ...remoteSrcUrls(html, "source")]);
const localized = await downloadAndRewriteUrls(
@@ -1840,7 +1888,7 @@ export async function localizeRemoteMediaSources(
join(downloadDir, REMOTE_MEDIA_SUBDIR),
"Remote media download failed",
"Localized remote media source(s)",
- signal,
+ assets,
);
return { ...localized, html: dropBindingOnLocalizedMedia(localized.html) };
}
@@ -1889,7 +1937,7 @@ function dropBindingOnLocalizedMedia(html: string): string {
export async function localizeRemoteImageSources(
html: string,
downloadDir: string,
- signal?: AbortSignal,
+ assets?: AssetDownloads,
): Promise<{ html: string; remoteMediaAssets: Map }> {
// frameCapture's `pollImagesReady`/`decodeAllImages` cover any remote URL this misses.
const urlSet = new Set(remoteSrcUrls(html, "img"));
@@ -1899,7 +1947,7 @@ export async function localizeRemoteImageSources(
join(downloadDir, REMOTE_MEDIA_SUBDIR),
"Remote image download failed",
"Localized remote image source(s)",
- signal,
+ assets,
);
}
@@ -1919,7 +1967,7 @@ export async function localizeRemoteImageSources(
export async function localizeRemoteBackgroundImages(
html: string,
downloadDir: string,
- signal?: AbortSignal,
+ assets?: AssetDownloads,
): Promise<{ html: string; remoteMediaAssets: Map }> {
const urlSet = new Set();
for (const { parts } of remoteBackgroundUrlMatches(html)) {
@@ -1931,7 +1979,7 @@ export async function localizeRemoteBackgroundImages(
join(downloadDir, REMOTE_MEDIA_SUBDIR),
"Remote background-image download failed",
"Localized remote background-image(s)",
- signal,
+ assets,
// Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
// replaceAll; this handles the unquoted url(https://..) form.
(h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`),
@@ -2164,7 +2212,7 @@ export async function localizeRemoteFontFaces(
function localizeFontFaceUrls(
html: string,
downloadDir: string,
- signal?: AbortSignal,
+ assets?: AssetDownloads,
): Promise<{ html: string; remoteMediaAssets: Map }> {
return downloadAndRewriteUrls(
collectFontFaceUrls(html),
@@ -2172,7 +2220,7 @@ function localizeFontFaceUrls(
join(downloadDir, REMOTE_MEDIA_SUBDIR),
"Remote font download failed",
"Localized remote font face(s)",
- signal,
+ assets,
(h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`),
);
}
@@ -2535,7 +2583,7 @@ export async function compileForRender(
// start.
assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
- const run: CompileRun = { probes: new Map(), signal: options.abortSignal };
+ const run: CompileRun = { probes: new Map(), assets: new AssetDownloads(options.abortSignal) };
const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
rawHtml,
projectDir,
@@ -2643,7 +2691,7 @@ export async function compileForRender(
const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
htmlWithDeferredScripts,
downloadDir,
- options.abortSignal,
+ run.assets,
);
// Download remote
sources. Same race shape as video/audio: the
@@ -2651,20 +2699,20 @@ export async function compileForRender(
// evict decoded pixels mid-render and re-fetch, producing intermittent
// blank-frame flicker. Localising to disk removes both races.
const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } =
- await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir, options.abortSignal);
+ await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir, run.assets);
// Download remote CSS background-image url() references. drawElementImage omits
// cross-origin content, so remote backgrounds render black on the fast path;
// localising them to same-origin closes that gap.
const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } =
- await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir, options.abortSignal);
+ await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir, run.assets);
// Download remote @font-face src URLs and rewrite to local paths.
// Remote font URLs fail with a CORS rejection at render time (S3 does not
// allow http://localhost:PORT as origin), causing Chrome to silently fall
// back to the next font in the stack.
const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } =
- await localizeFontFaceUrls(htmlWithLocalBg, downloadDir, options.abortSignal);
+ await localizeFontFaceUrls(htmlWithLocalBg, downloadDir, run.assets);
// Chrome cannot decode HEIC, and ffprobe reads a tiled one as video streams,
// so convert to JPEG before the media-type preflight sees it.