Unverified Commit 459e8fe9 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

generate the same next/font modules for the same options (#63513)

### What?

Improves caching of next/font generated modules (make them independent
on importer context)


Closes PACK-2796
parent f4fc6876
......@@ -48,7 +48,7 @@ struct Fallback {
pub(super) async fn get_font_fallback(
context: Vc<FileSystemPath>,
options_vc: Vc<NextFontGoogleOptions>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<FontFallback>> {
let options = options_vc.await?;
Ok(match &options.fallback {
......
......@@ -80,38 +80,16 @@ impl NextFontGoogleReplacer {
pub fn new(project_path: Vc<FileSystemPath>) -> Vc<Self> {
Self::cell(NextFontGoogleReplacer { project_path })
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontGoogleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for `next/font/google/target.css` and returns a
/// JavaScript object with a generated className from a referenced css
/// module.
#[turbo_tasks::function]
async fn result(
&self,
_context: Vc<FileSystemPath>,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query: query_vc,
} = request
else {
return Ok(ImportMapResult::NoEntry.into());
};
async fn import_map_result(&self, query: String) -> Result<Vc<ImportMapResult>> {
let request_hash = get_request_hash(&query).await?;
let qstr = qstring::QString::from(query.as_str());
let query_vc = Vc::cell(query);
let font_data = load_font_data(self.project_path);
let query = &*query_vc.await?;
let options = font_options_from_query_map(*query_vc, font_data);
let request_hash = get_request_hash(*query_vc);
let options = font_options_from_query_map(query_vc, font_data);
let fallback = get_font_fallback(self.project_path, options, request_hash);
let properties = get_font_css_properties(options, fallback, request_hash).await?;
let js_asset = VirtualSource::new(
......@@ -136,7 +114,7 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
export default fontData;
"#,
// Pass along whichever options we received to the css handler
qstring::QString::from(&**query),
qstr,
properties.font_family.await?,
properties
.weight
......@@ -155,45 +133,23 @@ impl ImportMappingReplacement for NextFontGoogleReplacer {
)
.into()),
);
Ok(ImportMapResult::Result(ResolveResult::source(Vc::upcast(js_asset)).into()).into())
}
}
#[turbo_tasks::value(shared)]
pub struct NextFontGoogleCssModuleReplacer {
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
}
#[turbo_tasks::value_impl]
impl NextFontGoogleCssModuleReplacer {
#[turbo_tasks::function]
pub fn new(
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
) -> Vc<Self> {
Self::cell(NextFontGoogleCssModuleReplacer {
project_path,
execution_context,
})
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
impl ImportMappingReplacement for NextFontGoogleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for the css module made by the virtual JavaScript
/// asset generated by the above replacer. Returns a VirtualSource of a CSS
/// Module containing font face definitions and exporting class names for
/// the font and an optional css variable.
/// Intercepts requests for `next/font/google/target.css` and returns a
/// JavaScript object with a generated className from a referenced css
/// module.
#[turbo_tasks::function]
async fn result(
&self,
self: Vc<Self>,
_context: Vc<FileSystemPath>,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
......@@ -201,16 +157,42 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
let Request::Module {
module: _,
path: _,
query: query_vc,
query,
} = request
else {
return Ok(ImportMapResult::NoEntry.into());
};
Ok(self.import_map_result(query.await?.to_string()))
}
}
#[turbo_tasks::value(shared)]
pub struct NextFontGoogleCssModuleReplacer {
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
}
#[turbo_tasks::value_impl]
impl NextFontGoogleCssModuleReplacer {
#[turbo_tasks::function]
pub fn new(
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
) -> Vc<Self> {
Self::cell(NextFontGoogleCssModuleReplacer {
project_path,
execution_context,
})
}
#[turbo_tasks::function]
async fn import_map_result(&self, query: String) -> Result<Vc<ImportMapResult>> {
let request_hash = get_request_hash(&query).await?;
let query_vc = Vc::cell(query);
let font_data = load_font_data(self.project_path);
let options = font_options_from_query_map(*query_vc, font_data);
let options = font_options_from_query_map(query_vc, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data);
let request_hash = get_request_hash(*query_vc);
let scoped_font_family = get_scoped_font_family(
FontFamilyType::WebFont.cell(),
options.font_family(),
......@@ -266,12 +248,47 @@ impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
)
.into(),
),
);
)
.resolve()
.await?;
println!("css_asset: {:?}, query: {}", css_asset, query_vc.await?);
Ok(ImportMapResult::Result(ResolveResult::source(Vc::upcast(css_asset)).into()).into())
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontGoogleCssModuleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for the css module made by the virtual JavaScript
/// asset generated by the above replacer. Returns a VirtualSource of a CSS
/// Module containing font face definitions and exporting class names for
/// the font and an optional css variable.
#[turbo_tasks::function]
async fn result(
self: Vc<Self>,
_context: Vc<FileSystemPath>,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query: query_vc,
} = request
else {
return Ok(ImportMapResult::NoEntry.into());
};
Ok(self.import_map_result(query_vc.await?.to_string()))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NextFontGoogleFontFileOptions {
pub url: String,
......@@ -489,7 +506,7 @@ async fn get_stylesheet_url_from_options(
async fn get_font_css_properties(
options_vc: Vc<NextFontGoogleOptions>,
font_fallback: Vc<FontFallback>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<FontCssProperties>> {
let options = &*options_vc.await?;
let scoped_font_family = &*get_scoped_font_family(
......@@ -549,8 +566,9 @@ async fn font_options_from_query_map(
bail!("Expected one entry");
};
options_from_request(&parse_json_with_source_context(&json)?, &*font_data.await?)
.map(|o| NextFontGoogleOptions::new(Value::new(o)))
let options =
options_from_request(&parse_json_with_source_context(&json)?, &*font_data.await?)?;
Ok(NextFontGoogleOptions::new(Value::new(options)))
}
async fn font_file_options_from_query_map(
......
......@@ -28,7 +28,7 @@ static BOLD_WEIGHT: f64 = 700.0;
pub(super) async fn get_font_fallbacks(
context: Vc<FileSystemPath>,
options_vc: Vc<NextFontLocalOptions>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<FontFallbacks>> {
let options = &*options_vc.await?;
let mut font_fallbacks = vec![];
......
......@@ -50,35 +50,17 @@ impl NextFontLocalReplacer {
pub fn new(project_path: Vc<FileSystemPath>) -> Vc<Self> {
Self::cell(NextFontLocalReplacer { project_path })
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for `next/font/local/target.css` and returns a
/// JavaScript object with a generated className from a referenced css
/// module.
#[turbo_tasks::function]
async fn result(
async fn import_map_result(
&self,
context: Vc<FileSystemPath>,
request: Vc<Request>,
query: String,
) -> Result<Vc<ImportMapResult>> {
let Request::Module {
module: _,
path: _,
query: query_vc,
} = &*request.await?
else {
return Ok(ImportMapResult::NoEntry.into());
};
let request_hash = get_request_hash(*query_vc);
let options_vc = font_options_from_query_map(*query_vc);
let request_hash = get_request_hash(&query).await?;
let qstr = qstring::QString::from(query.as_str());
let query_vc = Vc::cell(query);
let options_vc = font_options_from_query_map(query_vc);
let font_fallbacks = get_font_fallbacks(context, options_vc, request_hash);
let properties =
&*get_font_css_properties(options_vc, font_fallbacks, request_hash).await?;
......@@ -100,7 +82,7 @@ impl ImportMappingReplacement for NextFontLocalReplacer {
export default fontData;
"#,
// Pass along whichever options we received to the css handler
qstring::QString::from(&**query_vc.await?),
qstr,
properties.font_family.await?,
properties
.weight
......@@ -127,48 +109,54 @@ impl ImportMappingReplacement for NextFontLocalReplacer {
}
}
#[turbo_tasks::value(shared)]
pub struct NextFontLocalCssModuleReplacer {
project_path: Vc<FileSystemPath>,
}
#[turbo_tasks::value_impl]
impl NextFontLocalCssModuleReplacer {
#[turbo_tasks::function]
pub fn new(project_path: Vc<FileSystemPath>) -> Vc<Self> {
Self::cell(NextFontLocalCssModuleReplacer { project_path })
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalCssModuleReplacer {
impl ImportMappingReplacement for NextFontLocalReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for the css module made by the virtual JavaScript
/// asset generated by the above replacer. Returns a VirtualSource of a CSS
/// Module containing font face definitions and exporting class names for
/// the font and an optional css variable.
/// Intercepts requests for `next/font/local/target.css` and returns a
/// JavaScript object with a generated className from a referenced css
/// module.
#[turbo_tasks::function]
async fn result(
&self,
self: Vc<Self>,
context: Vc<FileSystemPath>,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query: query_vc,
} = request
} = &*request.await?
else {
return Ok(ImportMapResult::NoEntry.into());
};
let options = font_options_from_query_map(*query_vc);
let request_hash = get_request_hash(*query_vc);
Ok(self.import_map_result(context, query_vc.await?.to_string()))
}
}
#[turbo_tasks::value(shared)]
pub struct NextFontLocalCssModuleReplacer {}
#[turbo_tasks::value_impl]
impl NextFontLocalCssModuleReplacer {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
Self::cell(NextFontLocalCssModuleReplacer {})
}
#[turbo_tasks::function]
async fn import_map_result(
context: Vc<FileSystemPath>,
query: String,
) -> Result<Vc<ImportMapResult>> {
let request_hash = get_request_hash(&query).await?;
let query_vc = Vc::cell(query);
let options = font_options_from_query_map(query_vc);
let css_virtual_path = context.join(format!(
"/{}.module.css",
get_request_id(options.font_family(), request_hash).await?
......@@ -176,10 +164,10 @@ impl ImportMappingReplacement for NextFontLocalCssModuleReplacer {
let fallback = get_font_fallbacks(context, options, request_hash);
let stylesheet = build_stylesheet(
font_options_from_query_map(*query_vc),
font_options_from_query_map(query_vc),
fallback,
get_font_css_properties(options, fallback, request_hash),
get_request_hash(*query_vc),
request_hash,
)
.await?;
......@@ -192,6 +180,40 @@ impl ImportMappingReplacement for NextFontLocalCssModuleReplacer {
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalCssModuleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
/// Intercepts requests for the css module made by the virtual JavaScript
/// asset generated by the above replacer. Returns a VirtualSource of a CSS
/// Module containing font face definitions and exporting class names for
/// the font and an optional css variable.
#[turbo_tasks::function]
async fn result(
self: Vc<Self>,
context: Vc<FileSystemPath>,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query: query_vc,
} = request
else {
return Ok(ImportMapResult::NoEntry.into());
};
Ok(Self::import_map_result(
context,
query_vc.await?.to_string(),
))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NextFontLocalFontFileOptions {
pub path: String,
......@@ -270,7 +292,7 @@ impl ImportMappingReplacement for NextFontLocalFontFileReplacer {
async fn get_font_css_properties(
options_vc: Vc<NextFontLocalOptions>,
font_fallbacks: Vc<FontFallbacks>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<FontCssProperties>> {
let options = &*options_vc.await?;
......
......@@ -15,7 +15,7 @@ pub(super) async fn build_stylesheet(
options: Vc<NextFontLocalOptions>,
fallbacks: Vc<FontFallbacks>,
css_properties: Vc<FontCssProperties>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<String>> {
let scoped_font_family = get_scoped_font_family(
FontFamilyType::WebFont.cell(),
......
......@@ -12,7 +12,7 @@ use crate::next_font::{
pub(super) async fn build_font_family_string(
options: Vc<NextFontLocalOptions>,
font_fallbacks: Vc<FontFallbacks>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<String>> {
let mut font_families = vec![format!(
"'{}'",
......
......@@ -16,20 +16,19 @@ pub(crate) struct FontCssProperties {
/// A hash of the requested querymap derived from how the user invoked
/// next/font. Used to uniquely identify font requests for generated filenames
/// and scoped font family names.
#[turbo_tasks::function]
pub(crate) async fn get_request_hash(query_vc: Vc<String>) -> Result<Vc<u32>> {
let query = qstring::QString::from(&**query_vc.await?);
pub(crate) async fn get_request_hash(query: &str) -> Result<u32> {
let query = qstring::QString::from(query);
let mut to_hash = vec![];
for (k, v) in query {
to_hash.push(k);
to_hash.push(v);
}
Ok(Vc::cell(
Ok(
// Truncate the hash to u32. These hashes are ultimately displayed as 6- or 8-character
// hexadecimal values.
hash_xxh3_hash64(to_hash) as u32,
))
)
}
#[turbo_tasks::value(shared)]
......@@ -47,10 +46,10 @@ pub(crate) enum FontFamilyType {
pub(crate) async fn get_scoped_font_family(
ty: Vc<FontFamilyType>,
font_family_name: Vc<String>,
request_hash: Vc<u32>,
request_hash: u32,
) -> Result<Vc<String>> {
let hash = {
let mut hash = format!("{:x?}", request_hash.await?);
let mut hash = format!("{:x?}", request_hash);
hash.truncate(6);
hash
};
......@@ -66,10 +65,10 @@ pub(crate) async fn get_scoped_font_family(
/// Returns a [Vc] for [String] uniquely identifying the request for the font.
#[turbo_tasks::function]
pub async fn get_request_id(font_family: Vc<String>, request_hash: Vc<u32>) -> Result<Vc<String>> {
pub async fn get_request_id(font_family: Vc<String>, request_hash: u32) -> Result<Vc<String>> {
Ok(Vc::cell(format!(
"{}_{:x?}",
font_family.await?.to_lowercase().replace(' ', "_"),
request_hash.await?
request_hash
)))
}
......@@ -841,10 +841,7 @@ async fn insert_next_shared_aliases(
import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/local/cssmodule.module.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalCssModuleReplacer::new(
project_path,
)))
.into(),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalCssModuleReplacer::new())).into(),
);
import_map.insert_alias(
......
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