Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix(pdf): load CJK resume previews on slow connections (#3633)

Amruth Pillaief0c187eb474
diff --git a/packages/fonts/src/index.ts b/packages/fonts/src/index.ts
index 92b104923..fb1075c94 100644
--- a/packages/fonts/src/index.ts
+++ b/packages/fonts/src/index.ts
@@ -161,6 +161,17 @@ function getPunctuationFallbackFont(category: FontCategory | null) {
return getWebFont(family) ? family : null;
}
+// The Noto CJK faces, 10–15 MB per weight file.
+const cjkFontFamilies = new Set(
+ Object.entries(scriptFonts)
+ .filter(([script]) => isCjkScript(script as Script))
+ .flatMap(([, variants]) => [variants.serif, variants.sansSerif]),
+);
+
+export function isCjkFontFamily(family: string) {
+ return cjkFontFamilies.has(family);
+}
+
export function isStandardPdfFontFamily(family: string) {
return standardFontList.some((font) => font.family === family);
}
diff --git a/packages/pdf/src/forme/fonts.test.ts b/packages/pdf/src/forme/fonts.test.ts
index ee515bcbe..7391e61d9 100644
--- a/packages/pdf/src/forme/fonts.test.ts
+++ b/packages/pdf/src/forme/fonts.test.ts
@@ -32,3 +32,27 @@ it("falls back to fonts.gstatic.cn when fonts.gstatic.com doesn't answer, then s
expect(requested.at(-1)).toBe("fonts.gstatic.cn");
expect(requested).toHaveLength(3);
});
+
+it("finishes a slow download that keeps sending, and fails one that stops (#3627)", async () => {
+ vi.useFakeTimers();
+ // Sends a byte every 20 s, ten times, then ends; a path with "stops" never ends. Aborting errors it, as with fetch.
+ vi.stubGlobal("fetch", (input: URL, init: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ async start(stream) {
+ init.signal?.addEventListener("abort", () => stream.error(init.signal?.reason));
+ for (let index = 0; index < 10; index++) {
+ await new Promise((resolve) => setTimeout(resolve, 20_000));
+ stream.enqueue(new Uint8Array([index]));
+ }
+ if (!input.pathname.includes("stops")) stream.close();
+ },
+ });
+ return Promise.resolve(new Response(body));
+ });
+
+ const slow = loadFonts([font("/s/test/slow.ttf")]);
+ const stops = loadFonts([font("/s/test/stops.ttf")]);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect((await slow).missing).toEqual([]);
+ expect((await stops).missing).toEqual(["Test"]);
+});
diff --git a/packages/pdf/src/forme/fonts.ts b/packages/pdf/src/forme/fonts.ts
index 88ac6309d..efe396737 100644
--- a/packages/pdf/src/forme/fonts.ts
+++ b/packages/pdf/src/forme/fonts.ts
@@ -4,8 +4,9 @@ import { prepareFontBytes } from "./font-bytes";
// One download per font file for the life of the page or server process.
const cache = new Map<string, Promise<Uint8Array>>();
-// A stalled download fails the render instead of holding the preview on its loader. CJK faces are 10–15 MB.
-const DOWNLOAD_TIMEOUT_MS = 120_000;
+// A download that stops sending fails the render instead of holding the preview on its loader. One that is slow but
+// still sending finishes: CJK faces are 10–15 MB, and a resume can need five at once (#3627).
+const STALL_TIMEOUT_MS = 30_000;
// Google serves the same files from fonts.gstatic.cn, which loads where fonts.gstatic.com is blocked or slow
// (mainland China). Each download starts on the host that last answered; when that host fails, or sends nothing
@@ -62,12 +63,35 @@ function fetchFont(src: string, signal: AbortSignal): Promise<Response> {
});
}
+async function download(src: string): Promise<Uint8Array> {
+ const controller = new AbortController();
+ let stall: ReturnType<typeof setTimeout> | undefined;
+ const progress = () => {
+ clearTimeout(stall);
+ stall = setTimeout(() => controller.abort(new Error(`Font ${src}: download stalled`)), STALL_TIMEOUT_MS);
+ };
+ progress();
+ try {
+ const response = await fetchFont(src, controller.signal);
+ progress();
+ const body = response.body?.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ transform: (chunk, stream) => {
+ progress();
+ stream.enqueue(chunk);
+ },
+ }),
+ );
+ return new Uint8Array(await new Response(body).arrayBuffer());
+ } finally {
+ clearTimeout(stall);
+ }
+}
+
const load = (src: string) => {
let bytes = cache.get(src);
if (!bytes) {
- bytes = fetchFont(src, AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS))
- .then((response) => response.arrayBuffer())
- .then((buffer) => prepareFontBytes(new Uint8Array(buffer)));
+ bytes = download(src).then(prepareFontBytes);
// A failed download may succeed next time.
bytes.catch(() => cache.delete(src));
cache.set(src, bytes);
diff --git a/packages/pdf/src/hooks/use-register-fonts.test.ts b/packages/pdf/src/hooks/use-register-fonts.test.ts
index b7330f131..bf57f1bc3 100644
--- a/packages/pdf/src/hooks/use-register-fonts.test.ts
+++ b/packages/pdf/src/hooks/use-register-fonts.test.ts
@@ -70,6 +70,23 @@ describe("resolvePdfFonts", () => {
expect([...cjkWeights].sort()).toEqual([400, 700]);
});
+ it("downloads only Regular and Bold of a CJK body or heading font (#3627)", () => {
+ const { registered, registerFonts } = withRegistry();
+ const cjkTypography = {
+ ...typography,
+ body: { ...typography.body, fontFamily: "Noto Serif SC", fontWeights: ["400", "600"] },
+ heading: { ...typography.heading, fontFamily: "Noto Sans SC", fontWeights: ["600"] },
+ } satisfies Typography;
+
+ registerFonts(cjkTypography, "zh-CN", true, new Set(["han-simplified"]), false);
+
+ const cjkFaces = registered
+ .filter((font) => font.family.endsWith(" SC"))
+ .map((font) => `${font.family} ${font.weight}`)
+ .sort();
+ expect(cjkFaces).toEqual(["Noto Sans SC 700", "Noto Serif SC 400", "Noto Serif SC 700"]);
+ });
+
it("registers the family's true Bold face when the stored weights stop below it (#3310)", () => {
const { registered, registerFonts } = withRegistry();
diff --git a/packages/pdf/src/hooks/use-register-fonts.ts b/packages/pdf/src/hooks/use-register-fonts.ts
index 2dd2d01bd..446b7c144 100644
--- a/packages/pdf/src/hooks/use-register-fonts.ts
+++ b/packages/pdf/src/hooks/use-register-fonts.ts
@@ -6,6 +6,7 @@ import {
getFont,
getPdfFallbackFontFamilies,
getWebFontSource,
+ isCjkFontFamily,
isStandardPdfFontFamily,
resolveBoldFontWeight,
resolveLegacyFontAlias,
@@ -254,7 +255,9 @@ export const resolvePdfFonts = (
const registerFont = (family: string, weight: number, italic = false) => {
if (isStandardPdfFontFamily(family)) return;
- const normalizedWeight = toFontWeight(weight);
+ // A CJK face is 10–15 MB, so CJK families get Regular and Bold only; Forme draws other weights with the
+ // nearest one. Every stored weight made a CJK resume's first preview download up to ~70 MB (#3593, #3627).
+ const normalizedWeight = isCjkFontFamily(family) ? (weight <= 500 ? "400" : "700") : toFontWeight(weight);
const key = `${family}:${normalizedWeight}:${italic}`;
if (fonts.has(key)) return;
@@ -287,8 +290,7 @@ export const resolvePdfFonts = (
const bodyFallbacks = getPdfFallbackFontFamilies(bodyFontFamily, { locale, scripts: fallbackScripts });
const headingFallbacks = getPdfFallbackFontFamilies(headingFontFamily, { locale, scripts: fallbackScripts });
- // Fallbacks get Regular and Bold only; Forme draws other weights with the nearest face. A Noto CJK face is
- // 10–15 MB, so every weight of the primary font made a CJK resume's first preview download ~60 MB (#3593).
+ // Fallbacks get Regular and Bold only; Forme draws other weights with the nearest face.
const registerFallbacks = (families: string[], storedWeights: readonly string[]) => {
for (const family of families) {
const weights = new Set([400]);