Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const attempt = (o: Partial<FontAttemptDiag> = {}): FontAttemptDiag => ({
cssStatus: 200,
blocksTotal: 0,
regexMatches: 0,
assets: { total: 0, diskCacheHit: 0, fetchedOk: 0, nonOk: {} },
assets: { total: 0, diskCacheHit: 0, fetchedOk: 0, nonOk: {}, errored: 0 },
...o,
});
const diagOf = (attempts: FontAttemptDiag[]): FontDiagnostics => ({
Expand Down Expand Up @@ -132,7 +132,7 @@ const ROWS: Array<{ name: string; css: Rule; woff?: Rule; expected: FontAttemptD
expected: attempt({
blocksTotal: 3,
regexMatches: 3,
assets: { total: 3, diskCacheHit: 0, fetchedOk: 0, nonOk: { "404": 3 } },
assets: { total: 3, diskCacheHit: 0, fetchedOk: 0, nonOk: { "404": 3 }, errored: 0 },
}),
},
];
Expand Down Expand Up @@ -290,7 +290,7 @@ describe("authored stylesheet falling back to the default request", () => {
attempt({
blocksTotal: 1,
regexMatches: 1,
assets: { total: 1, diskCacheHit: 0, fetchedOk: 0, nonOk: { "404": 1 } },
assets: { total: 1, diskCacheHit: 0, fetchedOk: 0, nonOk: { "404": 1 }, errored: 0 },
}),
],
},
Expand Down Expand Up @@ -322,7 +322,7 @@ describe("authored stylesheet falling back to the default request", () => {
authoredAttempt({
blocksTotal: 1,
regexMatches: 1,
assets: { total: 1, diskCacheHit: 0, fetchedOk: 1, nonOk: {} },
assets: { total: 1, diskCacheHit: 0, fetchedOk: 1, nonOk: {}, errored: 0 },
}),
],
},
Expand Down
209 changes: 209 additions & 0 deletions packages/core/src/fonts/deterministicFonts-summaryLine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// @vitest-environment node

import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { beforeEach, describe, expect, it } from "vitest";
import {
_clearGoogleFontCssCacheForTests,
injectDeterministicFontFaces,
} from "./deterministicFonts.js";

const FAMILY = "Bricolage Grotesque";
const PRIVATE_FAMILY = "PRIVATE_FONT_SENTINEL_7f3a";
const PAGE_TEXT = "quick brown fox";
const WOFF2 = new Uint8Array([0x77, 0x4f, 0x46, 0x32, 1, 2, 3]);
const SUMMARY = "[Compiler] font_resolution ";

const face = (family: string, n: number): string =>
`/* latin */\n@font-face {\n font-family: '${family}';\n font-style: normal;\n font-weight: ${n}00;\n src: url(https://fonts.gstatic.com/s/b/v9/f${n}.woff2) format('woff2');\n unicode-range: U+0000-00FF;\n}\n`;
const faces = (family: string, count: number): string =>
Array.from({ length: count }, (_, n) => face(family, n + 1)).join("\n");
const familyIn = (url: string): string =>
decodeURIComponent(/family=([^:&]+)/.exec(url)?.[1] ?? "").replace(/\+/g, " ");

type Rule = (url: string) => Response;
const page = (css: string): string =>
`<!doctype html><html><head><style>${css}</style></head><body><p>The ${PAGE_TEXT} jumps.</p></body></html>`;

async function compile(
html: string,
css: Rule,
woff2: Rule = () => new Response(WOFF2, { status: 200 }),
failClosedFontFetch = false,
): Promise<string[]> {
const lines: string[] = [];
const fetchImpl: typeof fetch = async (input) => {
const url = String(input);
return url.startsWith("https://fonts.gstatic.com/") ? woff2(url) : css(url);
};
await injectDeterministicFontFaces(html, {
failClosedFontFetch,
allowSystemFontCapture: false,
fetchImpl,
fontFetchRetryPolicy: { maxAttempts: 1, baseDelayMs: 0, attemptTimeoutMs: 2000 },
logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line) },
}).catch(() => undefined);
const summaries = lines.filter((line) => line.startsWith(SUMMARY));
for (const summary of summaries) expectEveryFileHasOneOutcome(summary);
return summaries;
}

const fields = (line: string | undefined): Record<string, string> =>
Object.fromEntries(
(line ?? "")
.slice(SUMMARY.length)
.split(" ")
.map((pair) => pair.split("=")),
);

function expectEveryFileHasOneOutcome(line: string): void {
const counted = fields(line);
const outcomes = ["files_cache_hit", "files_fetched", "files_failed", "files_errored"];
expect(outcomes.reduce((total, name) => total + Number(counted[name]), 0)).toBe(
Number(counted.files),
);
}

beforeEach(() => {
process.env.HYPERFRAMES_FONT_CACHE_DIR = mkdtempSync(join(tmpdir(), "hf-summary-cache-"));
_clearGoogleFontCssCacheForTests();
});

describe("one font summary line per compile", () => {
it("counts fetched files on a cold cache and cache hits on the next compile", async () => {
const html = page(`.a{font-family:'${FAMILY}',sans-serif}`);
const css: Rule = (url) => new Response(faces(familyIn(url), 3), { status: 200 });

const cold = await compile(html, css);
const warm = await compile(html, css);

expect(cold).toHaveLength(1);
expect(fields(cold[0])).toEqual({
mode: "open",
families: "1",
resolved: "1",
unresolved_required: "0",
unresolved_optional: "0",
bundled_faces_only: "0",
css_lookups: "1",
css_cache_hit: "0",
css_failed: "0",
files: "3",
files_cache_hit: "0",
files_fetched: "3",
files_failed: "0",
files_errored: "0",
});
expect(warm).toHaveLength(1);
expect(fields(warm[0])).toMatchObject({
css_cache_hit: "1",
files: "3",
files_cache_hit: "3",
files_fetched: "0",
});
});

it("counts a shipped family whose extra faces could not be fetched", async () => {
const [line, ...rest] = await compile(
page(".i{font-family:'Inter',sans-serif}"),
() => new Response("x", { status: 500 }),
);

expect(rest).toEqual([]);
expect(fields(line)).toMatchObject({
families: "1",
resolved: "1",
bundled_faces_only: "1",
css_failed: "1",
files: "0",
});
});

it("does not count a shipped family whose extra faces arrived", async () => {
const [line] = await compile(
page(".i{font-family:'Inter',sans-serif}"),
(url) => new Response(faces(familyIn(url), 2), { status: 200 }),
);

expect(fields(line)).toMatchObject({ resolved: "1", bundled_faces_only: "0", files: "2" });
});

it("separates required from optional families that stayed unresolved, and failed files", async () => {
const [line, ...rest] = await compile(
page(`.a{font-family:'${FAMILY}',sans-serif}.b{font-family:var(--none, 'Zzz Example')}`),
(url) =>
familyIn(url) === FAMILY
? new Response(faces(FAMILY, 2), { status: 200 })
: new Response("x", { status: 400 }),
() => new Response("x", { status: 404 }),
);

expect(rest).toEqual([]);
expect(fields(line)).toMatchObject({
families: "2",
resolved: "0",
unresolved_required: "1",
unresolved_optional: "1",
css_lookups: "2",
css_failed: "1",
files: "2",
files_failed: "2",
});
});

it("is written once when a compile that requires every font stops on an unresolved one", async () => {
const lines = await compile(
page(`.a{font-family:'${FAMILY}',sans-serif}`),
() => new Response("x", { status: 400 }),
undefined,
true,
);

expect(lines).toHaveLength(1);
expect(fields(lines[0])).toMatchObject({ mode: "closed", unresolved_required: "1" });
});

it.each([
["open", false],
["closed", true],
] as const)("counts a file fetch that rejects, in %s mode", async (mode, failClosed) => {
const lines = await compile(
page(`.a{font-family:'${FAMILY}',sans-serif}`),
(url) => new Response(faces(familyIn(url), 1), { status: 200 }),
() => {
throw new TypeError("fetch failed");
},
failClosed,
);

expect(lines).toHaveLength(1);
expect(fields(lines[0])).toMatchObject({
mode,
files: "1",
files_fetched: "0",
files_failed: "0",
files_errored: "1",
});
});

it("is not written for a page that asks for no font", async () => {
expect(await compile(page(".a{color:red}"), () => new Response("x", { status: 500 }))).toEqual(
[],
);
});

it("holds numbers and a mode only: no family name, address or page text", async () => {
const [line] = await compile(
page(
`.a{font-family:'${FAMILY}',sans-serif}.b{font-family:var(--n, '${PRIVATE_FAMILY}')}.i{font-family:'Inter'}`,
),
(url) => new Response(faces(familyIn(url), 1), { status: 200 }),
);

expect(line).toMatch(/^\[Compiler\] font_resolution mode=open( [a-z_]+=\d+)+$/);
for (const secret of [FAMILY, PRIVATE_FAMILY, PAGE_TEXT, "Inter", "http"]) {
expect(line).not.toContain(secret);
}
});
});
13 changes: 10 additions & 3 deletions packages/core/src/fonts/deterministicFonts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { fontToDataUri } from "./fontCompression.js";
import { authoredGoogleFontStylesheets, withPageText } from "./authoredGoogleFonts.js";
import {
FontDiagCollector,
summarizeFontDiagnostics,
type FontAssetDiag,
type FontAttemptDiag,
type FontDiagnostics,
Expand Down Expand Up @@ -1524,13 +1525,15 @@ async function ensureWoff2DataUri(
tally.fetchedOk += 1;
} catch (err) {
throwIfCallerAborted(options.abortSignal);
if (err instanceof FontFetchError) throw err;
if ((err as NodeJS.ErrnoException).code === "EEXIST") {
// Concurrent call wrote it — read their result below.
tally.diskCacheHit += 1;
} else if (options.failClosedFontFetch) {
throw fontFetchError(familyName, woff2Url, woff2What, { error: err });
} else {
tally.errored += 1;
if (err instanceof FontFetchError) throw err;
if (options.failClosedFontFetch) {
throw fontFetchError(familyName, woff2Url, woff2What, { error: err });
}
return null;
}
}
Expand Down Expand Up @@ -2213,6 +2216,10 @@ export async function injectDeterministicFontFaces(
fetchOptions,
() => (declaredFamilies ??= collectDeclaredFontFamilies(html)),
extractGoogleFontsText(html),
).finally(() =>
fetchOptions.log.info(
`[Compiler] font_resolution ${summarizeFontDiagnostics(diag.snapshot(), failClosedFontFetch ? "closed" : "open")}`,
),
);
// An optional family that no source serves, or that stayed unavailable, is tolerated.
const required = unresolved.filter(
Expand Down
48 changes: 47 additions & 1 deletion packages/core/src/fonts/fontDiagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface FontAssetDiag {
diskCacheHit: number;
fetchedOk: number;
nonOk: Record<string, number>;
/** Fetches that ended in an error instead of an HTTP response. */
errored: number;
}

export interface FontAttemptDiag {
Expand Down Expand Up @@ -58,7 +60,7 @@ export class FontDiagCollector {
cssStatus: null,
blocksTotal: 0,
regexMatches: 0,
assets: { total: 0, diskCacheHit: 0, fetchedOk: 0, nonOk: {} },
assets: { total: 0, diskCacheHit: 0, fetchedOk: 0, nonOk: {}, errored: 0 },
};
this.current?.attempts.push(attempt);
return attempt;
Expand All @@ -68,3 +70,47 @@ export class FontDiagCollector {
return { families: this.families };
}
}

const usableFiles = (attempt: FontAttemptDiag): number =>
attempt.assets.diskCacheHit + attempt.assets.fetchedOk;

const lookupFailed = ({ cssStatus }: FontAttemptDiag): boolean =>
cssStatus === null || cssStatus < 200 || cssStatus >= 300;

const bundledFacesOnly = (family: FontFamilyDiag): boolean => {
const supplements = family.attempts.filter((attempt) => attempt.path === "bundled_supplement");
return family.resolved && supplements.length > 0 && !supplements.some(usableFiles);
};

const count = <T>(items: readonly T[], matches: (item: T) => unknown): number =>
items.filter(matches).length;

const sum = <T>(items: readonly T[], value: (item: T) => number): number =>
items.reduce((total, item) => total + value(item), 0);

export function summarizeFontDiagnostics(
{ families }: FontDiagnostics,
mode: "open" | "closed",
): string {
const attempts = families.flatMap((family) => family.attempts);
const fields: Array<[string, string | number]> = [
["mode", mode],
["families", families.length],
["resolved", count(families, (family) => family.resolved)],
["unresolved_required", count(families, (family) => !family.resolved && family.required)],
["unresolved_optional", count(families, (family) => !family.resolved && !family.required)],
["bundled_faces_only", count(families, bundledFacesOnly)],
["css_lookups", attempts.length],
["css_cache_hit", count(attempts, (attempt) => attempt.cssCache === "hit")],
["css_failed", count(attempts, lookupFailed)],
["files", sum(attempts, (attempt) => attempt.assets.total)],
["files_cache_hit", sum(attempts, (attempt) => attempt.assets.diskCacheHit)],
["files_fetched", sum(attempts, (attempt) => attempt.assets.fetchedOk)],
[
"files_failed",
sum(attempts, (attempt) => sum(Object.values(attempt.assets.nonOk), (failed) => failed)),
],
["files_errored", sum(attempts, (attempt) => attempt.assets.errored)],
];
return fields.map(([name, value]) => `${name}=${value}`).join(" ");
}
Loading