From 8ad346357590d215cb426815969b6d058ea1c9e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Fri, 20 Nov 2026 18:50:05 +0000 Subject: [PATCH] fix(producer): reserve each font's inline size before reading it (#8302) * test(producer): font embedding reads only the fonts that fit the page's budget * fix(producer): reserve each font's inline size before reading it * test(producer): give the font budget test room to embed 44 MiB under load --- .../src/services/compositionSizeLimit.ts | 4 ++ .../services/htmlCompiler.fontReserve.test.ts | 50 +++++++++++++++++++ .../producer/src/services/htmlCompiler.ts | 37 ++++++++++---- 3 files changed, 82 insertions(+), 9 deletions(-) create mode 100644 packages/producer/src/services/htmlCompiler.fontReserve.test.ts diff --git a/packages/producer/src/services/compositionSizeLimit.ts b/packages/producer/src/services/compositionSizeLimit.ts index 287db782d5..d553a82951 100644 --- a/packages/producer/src/services/compositionSizeLimit.ts +++ b/packages/producer/src/services/compositionSizeLimit.ts @@ -117,6 +117,10 @@ export class CompositionExpansionBudget { }); } + get generatedRoom(): number { + return MAX_EXPANDED_COMPOSITION_BYTES - this.generated; + } + chargeGeneratedIfItFits(bytes: number): boolean { if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false; this.generated += bytes; diff --git a/packages/producer/src/services/htmlCompiler.fontReserve.test.ts b/packages/producer/src/services/htmlCompiler.fontReserve.test.ts new file mode 100644 index 0000000000..8590b88484 --- /dev/null +++ b/packages/producer/src/services/htmlCompiler.fontReserve.test.ts @@ -0,0 +1,50 @@ +import { mkdirSync, 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 } from "./htmlCompiler.js"; + +const fontReads = vi.hoisted(() => [] as string[]); +vi.mock("fs", async (importOriginal) => { + const fs = await importOriginal(); + return { + ...fs, + createReadStream: ((path: string, ...rest: unknown[]) => { + if (String(path).endsWith(".woff2")) fontReads.push(String(path)); + return (fs.createReadStream as (...args: unknown[]) => unknown)(path, ...rest); + }) as typeof fs.createReadStream, + }; +}); + +const dirs: string[] = []; +afterEach(() => { + fontReads.length = 0; + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +// fails without the fix: every font was read and kept as a data URI before the budget was checked. +it("reads only the fonts whose data URIs fit the page's inline budget", async () => { + const fonts = 14; + const dir = mkdtempSync(join(tmpdir(), "hf-font-reserve-")); + dirs.push(dir); + mkdirSync(join(dir, "fonts")); + const font = Buffer.alloc(4 * 1024 * 1024, 7); + const faces = Array.from({ length: fonts }, (_, i) => { + writeFileSync(join(dir, "fonts", `f${i}.woff2`), font); + return `@font-face { font-family: F${i}; src: url(fonts/f${i}.woff2); } .f${i} { font-family: F${i}; }`; + }).join("\n"); + const text = Array.from({ length: fonts }, (_, i) => `

text

`).join(""); + writeFileSync( + join(dir, "index.html"), + `
${text}
`, + ); + + const { html } = await compileForRender(dir, join(dir, "index.html"), join(dir, "out"), { + allowSystemFontCapture: false, + }); + + const embedded = html.split("data:font/").length - 1; + expect(embedded).toBeGreaterThan(0); + expect(embedded).toBeLessThan(fonts); + expect(fontReads).toHaveLength(embedded); +}, 30_000); diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 4a50719581..669c94b61b 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -25,7 +25,7 @@ import { */ import { createHash } from "node:crypto"; -import { createReadStream, existsSync, mkdirSync, readFileSync } from "fs"; +import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from "fs"; import { join, dirname, resolve, basename, relative, sep } from "path"; import { parseHTML } from "linkedom"; import { bundledScript } from "./bundledScripts.js"; @@ -2256,7 +2256,8 @@ async function localFontDataUri( assetRoot: string | undefined, dataUriByAbsolutePath: Map, log: ProducerLogger, - downloadedPath?: string, + downloadedPath: string | undefined, + reserve: (dataUriBytes: number) => boolean, ): Promise { const absPath = downloadedPath ?? (localPath.startsWith("/") ? localPath : resolve(projectDir, localPath)); @@ -2273,6 +2274,11 @@ async function localFontDataUri( if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath); const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf"; try { + // Base64 plus a short data: prefix; a font that cannot fit is never read. + if (!reserve(Math.ceil(statSync(absPath).size / 3) * 4 + 64)) { + dataUriByAbsolutePath.set(absPath, undefined); + return undefined; + } const font = await readLocalFont(absPath); if (font.kind === "file-backed") { dataUriByAbsolutePath.set(absPath, undefined); @@ -2319,6 +2325,24 @@ async function embedLocalFontFaces( ): Promise { const dataUriByPath = new Map(); const dataUriByAbsolutePath = new Map(); + let warned = false; + const keptFileBacked = (localPath: string) => { + if (warned) return; + warned = true; + log.warn( + `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`, + ); + }; + // The fonts read here are kept until every copy is placed, so together they fit the budget's room. + let reserved = 0; + const reserveFor = (localPath: string) => (bytes: number) => { + if (reserved + bytes > budget.generatedRoom) { + keptFileBacked(localPath); + return false; + } + reserved += bytes; + return true; + }; for (const { parts: style } of styleBlockMatches(html)) { for (const { parts: face } of fontFaceBlockMatches(style[1])) { for (const { parts } of localFontFaceUrlMatches(face[1])) { @@ -2333,6 +2357,7 @@ async function embedLocalFontFaces( dataUriByAbsolutePath, log, downloadedFonts.get(localPath), + reserveFor(localPath), ), ); } @@ -2340,18 +2365,12 @@ async function embedLocalFontFaces( } if (![...dataUriByPath.values()].some(Boolean)) return html; - let warned = false; const embed = (source: string, localPath: string) => { const dataUri = dataUriByPath.get(localPath); if (!dataUri) return source; const inlined = `url("${dataUri}")`; if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined; - if (!warned) { - warned = true; - log.warn( - `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`, - ); - } + keptFileBacked(localPath); return source; }; return replaceMatches(html, styleBlockMatches(html), (style, css) =>