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
This commit is contained in:
Miguel Ángel
2026-11-20 18:50:05 +00:00
committed by GitHub
parent 31959db985
commit 8ad3463575
3 changed files with 82 additions and 9 deletions
@@ -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;
@@ -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<typeof import("fs")>();
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) => `<p class="f${i}">text</p>`).join("");
writeFileSync(
join(dir, "index.html"),
`<!doctype html><html><head><style>${faces}</style></head><body><main data-composition-id="root" data-start="0" data-duration="1" data-width="16" data-height="16">${text}</main></body></html>`,
);
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);
+28 -9
View File
@@ -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<string, string | undefined>,
log: ProducerLogger,
downloadedPath?: string,
downloadedPath: string | undefined,
reserve: (dataUriBytes: number) => boolean,
): Promise<string | undefined> {
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<string> {
const dataUriByPath = new Map<string, string | undefined>();
const dataUriByAbsolutePath = new Map<string, string | undefined>();
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) =>