Unverified Commit 0329a7e2 authored by Joshua Hannaford's avatar Joshua Hannaford Committed by GitHub

fix(turbopack): Allow google font fetch errors to propagate when in production (#79999)

## Fail Google Fonts in Production Builds When Fetch Fails

### What?
This PR changes the behavior of Google Fonts in Next.js to properly fail
production builds when font fetching fails, while still allowing
development to continue with fallback fonts.

### Why?
Previously, font fetch failures were only logged as warnings but didn't
stop production builds. This could lead to production deployments with
missing fonts, creating a poor user experience. Development mode should
be more forgiving to allow work to continue offline.

### How?
- Added `is_dev_mode()` method to the `ChunkingContext` trait to
determine the current environment
- Modified the Google font fetching logic to:
- In development: Show a warning and use fallback fonts when fetching
fails
- In production: Throw an error that fails the build when fetching fails
- Passed the execution context to the font file replacer to access the
chunking context

This ensures that production builds will fail fast when font resources
can't be fetched, while development builds can continue with appropriate
fallbacks.

Fixes #PACK-4667

### Future Hopes

I would hope to eventually expose an enum for the build mode rather than
just a boolean flag like I have here. I started going down that path for
this PR, but it was expanding the scope significantly of what would have
to be done, so I have left it as a bool to fix this problem.
parent 7a0db3a1
...@@ -161,7 +161,7 @@ pub async fn get_client_resolve_options_context( ...@@ -161,7 +161,7 @@ pub async fn get_client_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_client_import_map = let next_client_import_map =
get_next_client_import_map(*project_path, ty, next_config, execution_context) get_next_client_import_map(*project_path, ty, next_config, mode, execution_context)
.to_resolved() .to_resolved()
.await?; .await?;
let next_client_fallback_import_map = get_next_client_fallback_import_map(ty) let next_client_fallback_import_map = get_next_client_fallback_import_map(ty)
......
...@@ -110,7 +110,7 @@ pub async fn get_edge_resolve_options_context( ...@@ -110,7 +110,7 @@ pub async fn get_edge_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_edge_import_map = let next_edge_import_map =
get_next_edge_import_map(*project_path, ty, next_config, execution_context) get_next_edge_import_map(*project_path, ty, next_config, mode, execution_context)
.to_resolved() .to_resolved()
.await?; .await?;
......
...@@ -20,7 +20,7 @@ use turbopack_core::{ ...@@ -20,7 +20,7 @@ use turbopack_core::{
asset::AssetContent, asset::AssetContent,
context::AssetContext, context::AssetContext,
ident::AssetIdent, ident::AssetIdent,
issue::{IssueExt, IssueSeverity}, issue::{IssueExt, IssueSeverity, StyledString},
reference_type::{InnerAssets, ReferenceType}, reference_type::{InnerAssets, ReferenceType},
resolve::{ resolve::{
ResolveResult, ResolveResult,
...@@ -48,7 +48,8 @@ use super::{ ...@@ -48,7 +48,8 @@ use super::{
}, },
}; };
use crate::{ use crate::{
embed_js::next_js_file_path, next_app::metadata::split_extension, util::load_next_js_templateon, embed_js::next_js_file_path, mode::NextMode, next_app::metadata::split_extension,
next_font::issue::NextFontIssue, util::load_next_js_templateon,
}; };
pub mod font_fallback; pub mod font_fallback;
...@@ -179,6 +180,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer { ...@@ -179,6 +180,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
pub struct NextFontGoogleCssModuleReplacer { pub struct NextFontGoogleCssModuleReplacer {
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
execution_context: ResolvedVc<ExecutionContext>, execution_context: ResolvedVc<ExecutionContext>,
next_mode: ResolvedVc<NextMode>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -187,10 +189,12 @@ impl NextFontGoogleCssModuleReplacer { ...@@ -187,10 +189,12 @@ impl NextFontGoogleCssModuleReplacer {
pub fn new( pub fn new(
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
execution_context: ResolvedVc<ExecutionContext>, execution_context: ResolvedVc<ExecutionContext>,
next_mode: ResolvedVc<NextMode>,
) -> Vc<Self> { ) -> Vc<Self> {
Self::cell(NextFontGoogleCssModuleReplacer { Self::cell(NextFontGoogleCssModuleReplacer {
project_path, project_path,
execution_context, execution_context,
next_mode,
}) })
} }
...@@ -215,6 +219,7 @@ impl NextFontGoogleCssModuleReplacer { ...@@ -215,6 +219,7 @@ impl NextFontGoogleCssModuleReplacer {
// requests to Google Fonts. // requests to Google Fonts.
let env = Vc::upcast::<Box<dyn ProcessEnv>>(CommandLineProcessEnv::new()); let env = Vc::upcast::<Box<dyn ProcessEnv>>(CommandLineProcessEnv::new());
let mocked_responses_path = &*env.read("NEXT_FONT_GOOGLE_MOCKED_RESPONSES".into()).await?; let mocked_responses_path = &*env.read("NEXT_FONT_GOOGLE_MOCKED_RESPONSES".into()).await?;
let stylesheet_str = mocked_responses_path let stylesheet_str = mocked_responses_path
.as_ref() .as_ref()
.map_or_else( .map_or_else(
...@@ -224,7 +229,6 @@ impl NextFontGoogleCssModuleReplacer { ...@@ -224,7 +229,6 @@ impl NextFontGoogleCssModuleReplacer {
.await?; .await?;
let font_fallback = get_font_fallback(*self.project_path, options); let font_fallback = get_font_fallback(*self.project_path, options);
let stylesheet = match stylesheet_str { let stylesheet = match stylesheet_str {
Some(s) => Some( Some(s) => Some(
update_google_stylesheet( update_google_stylesheet(
...@@ -237,10 +241,57 @@ impl NextFontGoogleCssModuleReplacer { ...@@ -237,10 +241,57 @@ impl NextFontGoogleCssModuleReplacer {
.await?, .await?,
), ),
None => { None => {
println!( match *self.next_mode.await? {
"Failed to download `{}` from Google Fonts. Using fallback font instead.", // If we're in production mode, we want to fail the build to ensure proper font
options.await?.font_family // rendering.
); NextMode::Build => {
NextFontIssue {
path: css_virtual_path.to_resolved().await?,
title: StyledString::Line(vec![
StyledString::Code("next/font:".into()),
StyledString::Text(" error:".into()),
])
.resolved_cell(),
description: StyledString::Text(
format!(
"Failed to fetch `{}` from Google Fonts.",
options.await?.font_family
)
.into(),
)
.resolved_cell(),
severity: IssueSeverity::Error.resolved_cell(),
}
.resolved_cell()
.emit();
}
// Inform the user of the failure to retreive the stylesheet / font, but don't
// propagate this error. We don't want e.g. offline connections to prevent page
// renders during development.
NextMode::Development => {
NextFontIssue {
path: css_virtual_path.to_resolved().await?,
title: StyledString::Line(vec![
StyledString::Code("next/font:".into()),
StyledString::Text(" warning:".into()),
])
.resolved_cell(),
description: StyledString::Text(
format!(
"Failed to download `{}` from Google Fonts. Using fallback \
font instead.",
options.await?.font_family
)
.into(),
)
.resolved_cell(),
severity: IssueSeverity::Warning.resolved_cell(),
}
.resolved_cell()
.emit();
}
}
None None
} }
}; };
...@@ -610,16 +661,9 @@ async fn fetch_from_google_fonts( ...@@ -610,16 +661,9 @@ async fn fetch_from_google_fonts(
) )
.await?; .await?;
Ok(match &*result { Ok(match *result {
Ok(r) => Some(*r.await?.body), Ok(r) => Some(*r.await?.body),
Err(err) => { Err(err) => {
// Inform the user of the failure to retreive the stylesheet / font, but don't
// propagate this error. We don't want e.g. offline connections to prevent page
// renders during development. During production builds, however, this error
// should propagate.
//
// TODO(WEB-283): Use fallback in dev in this case
// TODO(WEB-293): Fail production builds (not dev) in this case
err.to_issue(IssueSeverity::Warning.into(), virtual_path) err.to_issue(IssueSeverity::Warning.into(), virtual_path)
.to_resolved() .to_resolved()
.await? .await?
......
...@@ -93,6 +93,7 @@ pub async fn get_next_client_import_map( ...@@ -93,6 +93,7 @@ pub async fn get_next_client_import_map(
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
ty: Value<ClientContextType>, ty: Value<ClientContextType>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
next_mode: Vc<NextMode>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty(); let mut import_map = ImportMap::empty();
...@@ -102,6 +103,7 @@ pub async fn get_next_client_import_map( ...@@ -102,6 +103,7 @@ pub async fn get_next_client_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
next_mode,
false, false,
) )
.await?; .await?;
...@@ -289,6 +291,7 @@ pub async fn get_next_server_import_map( ...@@ -289,6 +291,7 @@ pub async fn get_next_server_import_map(
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
ty: Value<ServerContextType>, ty: Value<ServerContextType>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
next_mode: Vc<NextMode>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty(); let mut import_map = ImportMap::empty();
...@@ -298,6 +301,7 @@ pub async fn get_next_server_import_map( ...@@ -298,6 +301,7 @@ pub async fn get_next_server_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
next_mode,
false, false,
) )
.await?; .await?;
...@@ -384,6 +388,7 @@ pub async fn get_next_edge_import_map( ...@@ -384,6 +388,7 @@ pub async fn get_next_edge_import_map(
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
ty: Value<ServerContextType>, ty: Value<ServerContextType>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
next_mode: Vc<NextMode>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty(); let mut import_map = ImportMap::empty();
...@@ -435,6 +440,7 @@ pub async fn get_next_edge_import_map( ...@@ -435,6 +440,7 @@ pub async fn get_next_edge_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
next_mode,
true, true,
) )
.await?; .await?;
...@@ -845,6 +851,7 @@ async fn insert_next_shared_aliases( ...@@ -845,6 +851,7 @@ async fn insert_next_shared_aliases(
project_path: ResolvedVc<FileSystemPath>, project_path: ResolvedVc<FileSystemPath>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
next_mode: Vc<NextMode>,
is_runtime_edge: bool, is_runtime_edge: bool,
) -> Result<()> { ) -> Result<()> {
let package_root = next_js_fs().root().to_resolved().await?; let package_root = next_js_fs().root().to_resolved().await?;
...@@ -892,7 +899,7 @@ async fn insert_next_shared_aliases( ...@@ -892,7 +899,7 @@ async fn insert_next_shared_aliases(
import_map.insert_alias( import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/google/cssmodule.module.css"), AliasPattern::exact("@vercel/turbopack-next/internal/font/google/cssmodule.module.css"),
ImportMapping::Dynamic(ResolvedVc::upcast( ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontGoogleCssModuleReplacer::new(*project_path, execution_context) NextFontGoogleCssModuleReplacer::new(*project_path, execution_context, next_mode)
.to_resolved() .to_resolved()
.await?, .await?,
)) ))
......
...@@ -134,7 +134,7 @@ pub async fn get_server_resolve_options_context( ...@@ -134,7 +134,7 @@ pub async fn get_server_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_server_import_map = let next_server_import_map =
get_next_server_import_map(*project_path, ty, next_config, execution_context) get_next_server_import_map(*project_path, ty, next_config, mode, execution_context)
.to_resolved() .to_resolved()
.await?; .await?;
let foreign_code_context_condition = let foreign_code_context_condition =
......
...@@ -7745,8 +7745,8 @@ ...@@ -7745,8 +7745,8 @@
"runtimeError": false "runtimeError": false
}, },
"test/e2e/next-font/google-fetch-error.test.ts": { "test/e2e/next-font/google-fetch-error.test.ts": {
"passed": [], "passed": ["next/font/google fetch error should error when not in dev"],
"failed": ["next/font/google fetch error should error when not in dev"], "failed": [],
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
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