Unverified Commit fa8dcf34 authored by Abhay Mishra's avatar Abhay Mishra Committed by GitHub

Turbopack: report next/font/google font file fetch failures instead of Module not found (#99574)

Fixes #97378

### What?

Turbopack turns a failed `next/font/google` font file download into an
unresolvable request. Build then dies with:

```
Module not found: Can't resolve '@vercel/turbopack-next/internal/font/google/font'
```

Real cause (`Received response with status 404 when requesting <url>`)
shows only as a warning earlier in the log.

### Why?

Hit this on Vercel with 16.3.6 and EB Garamond. Build failed with 56 of
these errors, redeploy of same commit passed. Nothing in the error
pointed at the font download.

### How?

Font file fetch now follows the stylesheet fetch: error in `next build`,
warning in `next dev`. A failed file is served empty, so dev falls back
to the next font in the stack. Retries unchanged; `max_retries: 1`
already covers connect errors, timeouts and 5xx.

Differs from #97520: dev keeps rendering instead of failing, message
comes from the existing fetch issue, and global retry count and webpack
mock stay as they are.

### Tests

`test/e2e/next-font/google-font-file-fetch-error.test.ts`, Turbopack
only, since webpack in mock mode does not download font files. Mocked
stylesheet points at a missing gstatic file.

Without the fix both dev and start fail with `Module not found`. With it
both pass. `google-fetch-error` and `index` next-font suites still pass
in Turbopack dev and start. `cargo clippy -D warnings`, rustfmt,
prettier and eslint clean.
parent 21d3ab34
......@@ -348,6 +348,7 @@ struct NextFontGoogleFontFileOptions {
#[turbo_tasks::value(shared)]
pub struct NextFontGoogleFontFileReplacer {
project_path: FileSystemPath,
next_mode: ResolvedVc<NextMode>,
fetch_client: ResolvedVc<FetchClientConfig>,
}
......@@ -356,10 +357,12 @@ impl NextFontGoogleFontFileReplacer {
#[turbo_tasks::function]
pub fn new(
project_path: FileSystemPath,
next_mode: ResolvedVc<NextMode>,
fetch_client: ResolvedVc<FetchClientConfig>,
) -> Vc<Self> {
Self::cell(NextFontGoogleFontFileReplacer {
project_path,
next_mode,
fetch_client,
})
}
......@@ -414,20 +417,30 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer {
.await?
.join(&format!("/{name}.{ext}"))?;
// Like the stylesheet fetch, a failure fails `next build` and only warns in `next dev`,
// where an empty file lets the browser fall back to the next font in the stack.
let severity = if matches!(*self.next_mode.await?, NextMode::Development) {
IssueSeverity::Warning
} else {
IssueSeverity::Error
};
// doesn't seem ideal to download the font into a string, but probably doesn't
// really matter either.
let Some(font) =
fetch_from_google_fonts(*self.fetch_client, url.into(), font_virtual_path.clone())
.await?
else {
return Ok(
ImportMapResult::Result(ResolveResult::unresolvable().resolved_cell()).cell(),
);
let font: File = match fetch_from_google_fonts(
*self.fetch_client,
url.into(),
font_virtual_path.clone(),
severity,
)
.await?
{
Some(font) => font.await?.0.as_slice().into(),
None => File::from(Vec::new()),
};
let font_source = VirtualSource::new(
font_virtual_path,
AssetContent::file(FileContent::Content(font.await?.0.as_slice().into()).cell()),
AssetContent::file(FileContent::Content(font).cell()),
)
.to_resolved()
.await?;
......@@ -654,7 +667,14 @@ async fn fetch_real_stylesheet(
stylesheet_url: RcStr,
css_virtual_path: FileSystemPath,
) -> Result<Option<Vc<RcStr>>> {
let body = fetch_from_google_fonts(fetch_client, stylesheet_url, css_virtual_path).await?;
// The caller reports a failed stylesheet through GoogleFontsFetchIssue.
let body = fetch_from_google_fonts(
fetch_client,
stylesheet_url,
css_virtual_path,
IssueSeverity::Warning,
)
.await?;
Ok(body.map(|body| body.to_string()))
}
......@@ -663,6 +683,7 @@ async fn fetch_from_google_fonts(
fetch_client: Vc<FetchClientConfig>,
url: RcStr,
virtual_path: FileSystemPath,
severity: IssueSeverity,
) -> Result<Option<Vc<HttpResponseBody>>> {
let result = fetch_client
.fetch(url, Some(USER_AGENT_FOR_GOOGLE_FONTS))
......@@ -671,7 +692,7 @@ async fn fetch_from_google_fonts(
Ok(match *result {
Ok(r) => Some(*r.await?.body),
Err(err) => {
err.to_issue(IssueSeverity::Warning, virtual_path)
err.to_issue(severity, virtual_path)
.to_resolved()
.await?
.emit();
......
......@@ -1204,7 +1204,7 @@ async fn insert_next_shared_aliases(
import_map.insert_alias(
AliasPattern::exact(GOOGLE_FONTS_INTERNAL_PREFIX),
ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontGoogleFontFileReplacer::new(project_path.clone(), fetch_client)
NextFontGoogleFontFileReplacer::new(project_path.clone(), next_mode, fetch_client)
.to_resolved()
.await?,
))
......
import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'path'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
// Turbopack only: with mocked responses, webpack does not download font files.
// Deploy mode exclusion: This suite intentionally fails the build, so there is no successful deployment to exercise.
// @force-gate turbopack && !deploy
describe('next/font/google font file fetch error', () => {
const isDev = (global as any).isNextDev
const fetchError =
'Received response with status 404 when requesting https://fonts.gstatic.com/s/bitter/v42/does-not-exist.woff2'
const missingModule =
"Can't resolve '@vercel/turbopack-next/internal/font/google/font'"
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'google-font-file-fetch-error/pages')),
},
env: {
NEXT_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses,
},
skipStart: true,
})
if (isDev) {
it('should warn and render in dev', async () => {
await next.start()
const browser = await next.browser('/')
expect(await browser.elementByCss('#bitter').text()).toInclude('Bitter')
expect(next.cliOutput).toInclude(fetchError)
expect(next.cliOutput).not.toInclude(missingModule)
})
} else {
it('should report the failed fetch when not in dev', async () => {
await expect(next.start()).rejects.toThrow('next build failed')
expect(next.cliOutput).toInclude(fetchError)
expect(next.cliOutput).not.toInclude(missingModule)
})
}
})
import { Bitter } from 'next/font/google'
const bitter = Bitter({ weight: '400', subsets: ['latin'] })
export default function Page() {
return (
<p id="bitter" className={bitter.className}>
{JSON.stringify(bitter)}
</p>
)
}
......@@ -982,4 +982,14 @@ body {
src: url(https://fonts.gstatic.com/s/notosansmath/v19/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf) format('truetype');
}
`,
// The font file does not exist, so fetching it returns 404.
'https://fonts.googleapis.com/css2?family=Bitter:wght@400&display=swap': `
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v42/does-not-exist.woff2) format('woff2');
}
`,
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment