Unverified Commit 9f68435d authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: implement optimized css production chunking (#77284)

### What?

Port the webpack css chunking implementation for app dir to Turbopack.

It also computes ordered entries in module batches

Pages router also uses the app dir chunking, but that's incorrect and leads to some breaking test cases.
parent 13ad4661
......@@ -471,7 +471,7 @@ pub async fn get_client_chunking_context(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......
......@@ -256,7 +256,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......@@ -319,7 +319,7 @@ pub async fn get_edge_chunking_context(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......
......@@ -1041,7 +1041,7 @@ pub async fn get_server_chunking_context_with_client_assets(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......@@ -1106,7 +1106,7 @@ pub async fn get_server_chunking_context(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......
......@@ -192,11 +192,7 @@ describe('app dir - css', () => {
const $ = await next.render$('/loading-bug/hi')
// The link tag should be hoist into head with precedence properties
const styles = $('head link[data-precedence]').length
if (process.env.TURBOPACK && !isNextDev) {
expect(styles).toBe(3)
} else {
expect(styles).toBe(2)
}
expect(styles).toBe(2)
expect($('body h2').text()).toBe('Loading...')
})
......@@ -313,11 +309,7 @@ describe('app dir - css', () => {
/<link rel="stylesheet" href="[^<]+\.css(\?v=\d+)?"/g
),
].length
if (process.env.TURBOPACK && !isNextDev) {
expect(stylesheets).toBe(5)
} else {
expect(stylesheets).toBe(3)
}
expect(stylesheets).toBe(3)
})
})
......
......@@ -7,15 +7,19 @@ describe('css-chunking', () => {
// do not contain styles for the `/other` page, which can happen
// when the CSSChunkingPlugin is enabled and styles are shared across
// both routes.
it('should be possible to disable the chunking plugin', async () => {
const $ = await next.render$('/')
const stylesheets = $('link[rel="stylesheet"]')
stylesheets.each(async (_, element) => {
const href = element.attribs.href
const result = await next.fetch(href)
const css = await result.text()
;(process.env.TURBOPACK ? it.skip : it)(
'should be possible to disable the chunking plugin',
async () => {
const $ = await next.render$('/')
const stylesheets = $('link[rel="stylesheet"]')
stylesheets.each(async (_, element) => {
const href = element.attribs.href
const result = await next.fetch(href)
const css = await result.text()
expect(css).not.toContain('.otherPage')
})
})
// eslint-disable-next-line jest/no-standalone-expect
expect(css).not.toContain('.otherPage')
})
}
)
})
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -2,7 +2,7 @@ import { jsx as _jsx } from 'react/jsx-runtime'
import styles from './index.module.css'
export function MyContainer({ children, className, ...props }) {
return /*#__PURE__*/ _jsx('dev', {
return /*#__PURE__*/ _jsx('p', {
...props,
className: `${styles.button_my_container} ${className ?? ''}`,
children: children,
......
......@@ -27,7 +27,6 @@ const PAGES: Record<
conflict?: boolean
brokenLoading?: boolean
brokenLoadingDev?: boolean
brokenLoadingTurbo?: boolean
}
> = {
first: {
......@@ -62,16 +61,12 @@ const PAGES: Record<
},
'interleaved-a': {
group: 'interleaved',
// TODO fix this case
brokenLoadingTurbo: true,
url: '/interleaved/a',
selector: '#helloia',
color: 'rgb(0, 255, 0)',
},
'interleaved-b': {
group: 'interleaved',
// TODO fix this case
brokenLoadingTurbo: true,
url: '/interleaved/b',
selector: '#helloib',
color: 'rgb(255, 0, 255)',
......@@ -244,10 +239,6 @@ describe.each(process.env.TURBOPACK ? ['turbo'] : ['strict', true])(
// TODO fix this case
let broken =
isNextDev || ordering.some((page) => PAGES[page].brokenLoading)
if (mode === 'turbo') {
// TODO fix this case
broken ||= ordering.some((page) => PAGES[page].brokenLoadingTurbo)
}
if (broken) {
it.todo(name)
continue
......@@ -304,10 +295,6 @@ describe.each(process.env.TURBOPACK ? ['turbo'] : ['strict', 'loose'])(
PAGES[page].brokenLoading ||
(isNextDev && PAGES[page].brokenLoadingDev)
)
if (mode === 'turbo') {
// TODO fix this case
broken ||= ordering.some((page) => PAGES[page].brokenLoadingTurbo)
}
if (broken) {
it.todo(name)
continue
......@@ -341,7 +328,7 @@ describe.each(process.env.TURBOPACK ? ['turbo'] : ['strict', 'loose'])(
const { next } = nextTestSetup(options(mode))
for (const [page, pageInfo] of Object.entries(PAGES)) {
const name = `should load correct styles on ${page}`
if (mode === 'loose' && pageInfo.conflict) {
if (mode !== 'strict' && pageInfo.conflict) {
// Conflict scenarios won't support that case
continue
}
......
.red-text {
color: red;
background-image: url('./dark.svg') url(dark2.svg);
background-image: url('./dark.svg'), url(dark2.svg);
}
......@@ -576,9 +576,10 @@ module.exports = {
if (process.env.TURBOPACK && useLightningcss) {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_global1_69590c47.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}",
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_3a258468._.css:
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_46281715._.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg),url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
......@@ -588,9 +589,10 @@ module.exports = {
} else if (process.env.TURBOPACK && !useLightningcss) {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_global1_69590c47.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}",
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_3a258468._.css:
"/_next/static/chunks/test_integration_css-fixtures_url-global_styles_46281715._.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg),url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
......@@ -600,15 +602,15 @@ module.exports = {
} else if (useLightningcss) {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/css/b52d68d7050c7314.css:
.red-text{color:red;background-image:url(/_next/static/media/dark.6b01655b.svg) url(/_next/static/media/dark2.6b01655b.svg)}.blue-text{color:orange;background-image:url(/_next/static/media/light.2da1d3d6.svg);font-weight:bolder;color:#00f}",
"/_next/static/css/02830b0dd136adeb.css:
.red-text{color:red;background-image:url(/_next/static/media/dark.6b01655b.svg),url(/_next/static/media/dark2.6b01655b.svg)}.blue-text{color:orange;background-image:url(/_next/static/media/light.2da1d3d6.svg);font-weight:bolder;color:#00f}",
]
`)
} else {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/css/766d42b9536ee6bb.css:
.red-text{color:red;background-image:url(/_next/static/media/dark.6b01655b.svg) url(/_next/static/media/dark2.6b01655b.svg)}.blue-text{color:orange;font-weight:bolder;background-image:url(/_next/static/media/light.2da1d3d6.svg);color:blue}",
"/_next/static/css/bf86b6e30872ca37.css:
.red-text{color:red;background-image:url(/_next/static/media/dark.6b01655b.svg),url(/_next/static/media/dark2.6b01655b.svg)}.blue-text{color:orange;font-weight:bolder;background-image:url(/_next/static/media/light.2da1d3d6.svg);color:blue}",
]
`)
}
......@@ -651,9 +653,10 @@ describe('CSS URL via `file-loader` and asset prefix (1)', () => {
if (process.env.TURBOPACK) {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-1_styles_global1_64764808.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}",
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-1_styles_0a127993._.css:
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-1_styles_e99cb7f8._.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
......@@ -706,9 +709,10 @@ describe('CSS URL via `file-loader` and asset prefix (2)', () => {
if (process.env.TURBOPACK) {
expect(cssContent).toMatchInlineSnapshot(`
[
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-2_styles_global1_cfbf8de3.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}",
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-2_styles_764eafae._.css:
"/_next/static/chunks/test_integration_css-fixtures_url-global-asset-prefix-2_styles_7b29c72b._.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
......
......@@ -362,7 +362,8 @@ module.exports = {
})
}
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
// This test case will fail in Turbopack when both pages share some css chunks. Deleting them will cause the / page to fail too.
;(process.env.TURBOPACK ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => {
......
......@@ -1565,6 +1565,7 @@
"css-order turbo should load correct styles navigating back again pages-first -> pages-second -> pages-first -> pages-second",
"css-order turbo should load correct styles navigating back again pages-first -> pages-third -> pages-first -> pages-third",
"css-order turbo should load correct styles navigating back again pages-interleaved-a -> pages-interleaved-b -> pages-interleaved-a -> pages-interleaved-b",
"css-order turbo should load correct styles navigating back again pages-interleaved-b -> pages-interleaved-a -> pages-interleaved-b -> pages-interleaved-a",
"css-order turbo should load correct styles navigating back again pages-second -> pages-first -> pages-second -> pages-first",
"css-order turbo should load correct styles navigating back again pages-second -> pages-third -> pages-second -> pages-third",
"css-order turbo should load correct styles navigating back again pages-third -> pages-first -> pages-third -> pages-first",
......@@ -1592,6 +1593,7 @@
"css-order turbo should load correct styles navigating pages-first -> pages-second",
"css-order turbo should load correct styles navigating pages-first -> pages-third",
"css-order turbo should load correct styles navigating pages-interleaved-a -> pages-interleaved-b",
"css-order turbo should load correct styles navigating pages-interleaved-b -> pages-interleaved-a",
"css-order turbo should load correct styles navigating pages-second -> pages-first",
"css-order turbo should load correct styles navigating pages-second -> pages-third",
"css-order turbo should load correct styles navigating pages-third -> pages-first",
......@@ -1620,31 +1622,25 @@
"css-order turbo should load correct styles on pages-interleaved-a",
"css-order turbo should load correct styles on pages-interleaved-b",
"css-order turbo should load correct styles on pages-partial-reversed-a",
"css-order turbo should load correct styles on pages-partial-reversed-b",
"css-order turbo should load correct styles on pages-reversed-a",
"css-order turbo should load correct styles on pages-reversed-b",
"css-order turbo should load correct styles on pages-second",
"css-order turbo should load correct styles on pages-third",
"css-order turbo should load correct styles on partial-reversed-a",
"css-order turbo should load correct styles on partial-reversed-b",
"css-order turbo should load correct styles on reversed-a",
"css-order turbo should load correct styles on reversed-b",
"css-order turbo should load correct styles on second",
"css-order turbo should load correct styles on second-client",
"css-order turbo should load correct styles on third",
"css-order turbo should load correct styles on vendor"
],
"failed": [
"css-order turbo should load correct styles navigating back again pages-interleaved-b -> pages-interleaved-a -> pages-interleaved-b -> pages-interleaved-a",
"css-order turbo should load correct styles navigating back again pages-partial-reversed-a -> pages-partial-reversed-b -> pages-partial-reversed-a -> pages-partial-reversed-b",
"css-order turbo should load correct styles navigating back again pages-partial-reversed-b -> pages-partial-reversed-a -> pages-partial-reversed-b -> pages-partial-reversed-a",
"css-order turbo should load correct styles navigating back again pages-reversed-a -> pages-reversed-b -> pages-reversed-a -> pages-reversed-b",
"css-order turbo should load correct styles navigating back again pages-reversed-b -> pages-reversed-a -> pages-reversed-b -> pages-reversed-a",
"css-order turbo should load correct styles navigating pages-interleaved-b -> pages-interleaved-a",
"css-order turbo should load correct styles navigating pages-partial-reversed-a -> pages-partial-reversed-b",
"css-order turbo should load correct styles navigating pages-partial-reversed-b -> pages-partial-reversed-a",
"css-order turbo should load correct styles navigating pages-reversed-a -> pages-reversed-b",
"css-order turbo should load correct styles navigating pages-reversed-b -> pages-reversed-a"
"css-order turbo should load correct styles navigating pages-reversed-b -> pages-reversed-a",
"css-order turbo should load correct styles on pages-partial-reversed-b",
"css-order turbo should load correct styles on pages-reversed-b"
],
"pending": [
"css-order turbo should load correct styles navigating back again big-interleaved-a -> big-interleaved-b -> big-interleaved-a -> big-interleaved-b",
......@@ -7274,15 +7270,16 @@
"next/font import values Variable font without weight range",
"next/font import values page with font",
"next/font import values page with local fonts",
"next/font preload page with fonts",
"next/font should not have deprecation warning"
],
"failed": [
"next/font preload font without preloadable subsets",
"next/font preload font without size adjust",
"next/font preload google fonts with multiple weights/styles",
"next/font preload page with fonts",
"next/font preload page with local fonts",
"next/font preload page without fonts",
"next/font should not have deprecation warning"
"next/font preload page without fonts"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
......@@ -9705,13 +9702,13 @@
"CSS Support Page hydrates with CSS and not waiting on dependencies useLightnincsss(true) production mode should hydrate black without dependencies manifest",
"CSS Support Page hydrates with CSS and not waiting on dependencies useLightnincsss(true) production mode should hydrate red without dependencies manifest",
"CSS Support Page hydrates with CSS and not waiting on dependencies useLightnincsss(true) production mode should route from black to red without dependencies",
"CSS Support Page reload on CSS missing useLightnincsss(false) production mode should fall back to server-side transition on missing CSS",
"CSS Support Page reload on CSS missing useLightnincsss(true) production mode should fall back to server-side transition on missing CSS",
"CSS Support production mode CSS Import from node_modules useLightnincsss(false) should fail the build",
"CSS Support production mode CSS Import from node_modules useLightnincsss(true) should fail the build"
],
"failed": [],
"pending": [
"CSS Support Page reload on CSS missing useLightnincsss(false) production mode should fall back to server-side transition on missing CSS",
"CSS Support Page reload on CSS missing useLightnincsss(true) production mode should fall back to server-side transition on missing CSS",
"CSS Support CSS Cleanup on Render Failure useLightnincsss(false) production mode not have intermediary page styles on error rendering",
"CSS Support CSS Cleanup on Render Failure useLightnincsss(true) production mode not have intermediary page styles on error rendering"
],
......@@ -350,7 +350,7 @@ async fn build_internal(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......@@ -393,7 +393,7 @@ async fn build_internal(
builder = builder.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
);
......
......@@ -20,7 +20,7 @@ use crate::{
},
};
async fn attach_async_info_to_chunkable_module(
pub async fn attach_async_info_to_chunkable_module(
module: ResolvedVc<Box<dyn ChunkableModule>>,
async_module_info: &ReadRef<AsyncModulesInfo>,
module_graph: Vc<ModuleGraph>,
......@@ -105,6 +105,7 @@ impl ChunkItemOrBatchWithAsyncModuleInfo {
}
#[turbo_tasks::value]
#[derive(Debug, Clone, Hash, TaskInput)]
pub struct ChunkItemBatchWithAsyncModuleInfo {
pub chunk_items: Vec<ChunkItemWithAsyncModuleInfo>,
pub chunk_groups: Option<RoaringBitmapWrapper>,
......@@ -112,6 +113,15 @@ pub struct ChunkItemBatchWithAsyncModuleInfo {
#[turbo_tasks::value_impl]
impl ChunkItemBatchWithAsyncModuleInfo {
#[turbo_tasks::function]
pub fn new(chunk_items: Vec<ChunkItemWithAsyncModuleInfo>) -> Vc<Self> {
Self {
chunk_items,
chunk_groups: None,
}
.cell()
}
#[turbo_tasks::function]
pub async fn from_module_batch(
batch: Vc<ModuleBatch>,
......
......@@ -21,8 +21,8 @@ use crate::{
},
chunking::{
dev::{app_vendors_split, expand_batches},
ordered_production::make_production_chunks_keeping_order,
production::make_production_chunks,
style_production::make_style_production_chunks,
},
},
module_graph::ModuleGraph,
......@@ -30,8 +30,8 @@ use crate::{
};
mod dev;
mod ordered_production;
mod production;
mod style_production;
#[turbo_tasks::value]
struct ChunkItemsWithInfo {
......@@ -336,17 +336,18 @@ pub async fn make_chunks(
if let Some(chunking_config) = chunking_configs.get(&ty) {
// Production chunking
if !*ty.must_keep_item_order().await? {
make_production_chunks(
if *ty.is_style().await? {
make_style_production_chunks(
chunk_items,
batch_groups.into_iter().collect(),
module_graph,
chunking_context,
chunking_config,
split_context,
)
.await?;
} else {
make_production_chunks_keeping_order(
make_production_chunks(
chunk_items,
batch_groups.into_iter().collect(),
module_graph,
......@@ -357,20 +358,20 @@ pub async fn make_chunks(
}
} else {
// Development chunking
if !*ty.must_keep_item_order().await? {
let chunk_items = expand_batches(chunk_items, ty, chunking_context).await?;
let chunk_items = chunk_items.iter().collect();
app_vendors_split(
if *ty.is_style().await? {
make_chunk(
chunk_items,
format!("{key_prefix}{ty_name}"),
Vec::new(),
&mut format!("{key_prefix}{ty_name}"),
&mut split_context,
)
.await?;
} else {
make_chunk(
let chunk_items = expand_batches(chunk_items, ty, chunking_context).await?;
let chunk_items = chunk_items.iter().collect();
app_vendors_split(
chunk_items,
Vec::new(),
&mut format!("{key_prefix}{ty_name}"),
format!("{key_prefix}{ty_name}"),
&mut split_context,
)
.await?;
......
use anyhow::Result;
use tracing::Instrument;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{
chunk::{
chunking::{make_chunk, ChunkItemOrBatchWithInfo, SplitContext},
ChunkItemBatchGroup, ChunkingConfig,
},
module_graph::ModuleGraph,
};
pub async fn make_production_chunks_keeping_order(
chunk_items: Vec<&ChunkItemOrBatchWithInfo>,
_batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
_module_graph: Vc<ModuleGraph>,
_chunking_config: &ChunkingConfig,
mut split_context: SplitContext<'_>,
) -> Result<()> {
let span_outer = tracing::info_span!(
"make production chunks keeping order",
chunk_items = chunk_items.len(),
);
async move {
for chunk_item in chunk_items {
make_chunk(
vec![chunk_item],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
}
Ok(())
}
.instrument(span_outer)
.await
}
use anyhow::Result;
use rustc_hash::FxHashSet;
use tracing::Instrument;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{
chunk::{
chunking::{make_chunk, ChunkItemOrBatchWithInfo, SplitContext},
ChunkItemBatchGroup, ChunkItemWithAsyncModuleInfo, ChunkingConfig, ChunkingContext,
},
module_graph::{style_groups::StyleGroupsConfig, ModuleGraph},
};
pub async fn make_style_production_chunks(
chunk_items: Vec<&ChunkItemOrBatchWithInfo>,
_batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
chunking_config: &ChunkingConfig,
mut split_context: SplitContext<'_>,
) -> Result<()> {
let span_outer = tracing::info_span!(
"make production chunks keeping order",
chunk_items = chunk_items.len(),
);
async move {
let style_groups = module_graph
.style_groups(
chunking_context,
StyleGroupsConfig {
max_chunk_size: chunking_config.max_merge_chunk_size,
},
)
.await?;
let mut handled = FxHashSet::default();
let mut handle_chunk_item = async |chunk_item: &ChunkItemWithAsyncModuleInfo| {
if let Some(&batch) = style_groups.shared_chunk_items.get(chunk_item) {
if handled.insert(batch) {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::Batch { batch, size: 0 }],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
}
} else {
make_chunk(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: chunk_item.clone(),
size: 0,
asset_ident: "".into(),
}],
vec![],
&mut String::new(),
&mut split_context,
)
.await?;
}
anyhow::Ok(())
};
for chunk_item in chunk_items {
match chunk_item {
ChunkItemOrBatchWithInfo::ChunkItem { chunk_item, .. } => {
handle_chunk_item(chunk_item).await?;
}
ChunkItemOrBatchWithInfo::Batch { batch, .. } => {
for chunk_item in &batch.await?.chunk_items {
handle_chunk_item(chunk_item).await?;
}
}
};
}
Ok(())
}
.instrument(span_outer)
.await
}
......@@ -310,7 +310,7 @@ pub trait ChunkItem {
#[turbo_tasks::value_trait]
pub trait ChunkType: ValueToString {
/// Whether the source (reference) order of items needs to be retained during chunking.
fn must_keep_item_order(self: Vc<Self>) -> Vc<bool>;
fn is_style(self: Vc<Self>) -> Vc<bool>;
/// Create a new chunk for the given chunk items
fn chunk(
......@@ -417,6 +417,8 @@ mod tests {
assert_eq!(round_chunk_item_size(6), 6);
assert_eq!(round_chunk_item_size(7), 6);
assert_eq!(round_chunk_item_size(8), 8);
assert_eq!(round_chunk_item_size(49000), 32_768);
assert_eq!(round_chunk_item_size(50000), 49_152);
assert_eq!(changes_in_range(0..1000), 19);
assert_eq!(changes_in_range(1000..2000), 2);
......
use turbo_tasks::{ResolvedVc, Vc};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, NonLocalValue, ResolvedVc, Vc};
use crate::{asset::Asset, ident::AssetIdent, reference::ModuleReferences};
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue)]
pub enum StyleType {
IsolatedStyle,
GlobalStyle,
}
#[turbo_tasks::value(transparent)]
pub struct OptionStyleType(Option<StyleType>);
/// A module. This usually represents parsed source code, which has references
/// to other modules.
#[turbo_tasks::value_trait]
......@@ -20,6 +30,11 @@ pub trait Module: Asset {
fn is_self_async(self: Vc<Self>) -> Vc<bool> {
Vc::cell(false)
}
/// The style type of the module.
fn style_type(self: Vc<Self>) -> Vc<OptionStyleType> {
Vc::cell(None)
}
}
#[turbo_tasks::value(transparent)]
......
......@@ -20,13 +20,14 @@ use turbo_tasks::{
};
use crate::{
chunk::{AsyncModuleInfo, ChunkingType},
chunk::{AsyncModuleInfo, ChunkingContext, ChunkingType},
issue::Issue,
module::Module,
module_graph::{
async_module_info::{compute_async_module_info, AsyncModulesInfo},
chunk_group_info::{compute_chunk_group_info, ChunkGroupEntry, ChunkGroupInfo},
module_batches::{compute_module_batches, ModuleBatchesGraph},
style_groups::{compute_style_groups, StyleGroups, StyleGroupsConfig},
traced_di_graph::{iter_neighbors_rev, TracedDiGraph},
},
reference::primary_chunkable_referenced_modules,
......@@ -36,6 +37,7 @@ pub mod async_module_info;
pub mod chunk_group_info;
pub mod module_batch;
pub(crate) mod module_batches;
pub(crate) mod style_groups;
mod traced_di_graph;
pub use self::module_batches::BatchingConfig;
......@@ -730,10 +732,18 @@ impl ModuleGraph {
self: Vc<Self>,
config: Vc<BatchingConfig>,
) -> Result<Vc<ModuleBatchesGraph>> {
// TODO dev: Return modules only
compute_module_batches(self, &*config.await?).await
}
#[turbo_tasks::function]
pub async fn style_groups(
self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
config: StyleGroupsConfig,
) -> Result<Vc<StyleGroups>> {
compute_style_groups(self, chunking_context, &config).await
}
#[turbo_tasks::function]
pub async fn async_module_info(self: Vc<Self>) -> Result<Vc<AsyncModulesInfo>> {
// `compute_async_module_info` calls `module.is_self_async()`, so we need to again ignore
......
use std::cmp::Reverse;
use anyhow::Result;
use indexmap::map::Entry;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_tasks::{
trace::TraceRawVcs, FxIndexMap, FxIndexSet, NonLocalValue, ResolvedVc, TaskInput,
TryJoinIterExt, ValueToString, Vc,
};
use crate::{
chunk::{
chunk_item_batch::attach_async_info_to_chunkable_module, ChunkItem,
ChunkItemBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, ChunkingType,
},
module::{Module, StyleType},
module_graph::{
module_batch::ModuleOrBatch, module_batches::ModuleBatchesGraphEdge, GraphTraversalAction,
ModuleGraph,
},
};
#[derive(
TaskInput, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, NonLocalValue, TraceRawVcs,
)]
pub struct StyleGroupsConfig {
pub max_chunk_size: usize,
}
/// Styling must not be duplicated in the application. The simplest way to achieve this is to put
/// every styling chunk item into a separate chunk. That works, but isn't efficient since it would
/// cause a lot of requests. Instead we multiple chunk items are groups together and placed in a
/// single shared chunk. `StyleGroups` specifies how chunk items are grouped together.
#[turbo_tasks::value]
pub struct StyleGroups {
/// The key chunk item is contained in the value chunk item batch. All chunk items that are not
/// contained in this map are placed in a separate chunk per chunk item.
pub shared_chunk_items:
FxIndexMap<ChunkItemWithAsyncModuleInfo, ResolvedVc<ChunkItemBatchWithAsyncModuleInfo>>,
}
#[derive(Debug)]
struct ModuleInfo {
style_type: StyleType,
ident: RcStr,
chunk_group_indicies: FxHashMap<usize, usize>,
index_sum: usize,
size: usize,
chunk_item: Option<ChunkItemWithAsyncModuleInfo>,
}
impl ModuleInfo {
fn new(style_type: StyleType, ident: RcStr) -> Self {
Self {
style_type,
ident,
chunk_group_indicies: Default::default(),
index_sum: 0,
size: 0,
chunk_item: None,
}
}
}
struct ChunkGroupState {
styles: FxIndexSet<ResolvedVc<Box<dyn ChunkableModule>>>,
requests: usize,
}
pub async fn compute_style_groups(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
config: &StyleGroupsConfig,
) -> Result<Vc<StyleGroups>> {
let chunk_group_info = module_graph.chunk_group_info().await?;
let batches_graph = module_graph
.module_batches(chunking_context.batching_config())
.await?;
let async_info = module_graph.async_module_info().await?;
let mut module_info_map: FxIndexMap<ResolvedVc<Box<dyn ChunkableModule>>, Option<ModuleInfo>> =
FxIndexMap::default();
// Compute the style modules in each chunk group
let mut chunk_group_state = Vec::new();
let mut idx = 0;
for (i, chunk_group) in chunk_group_info.chunk_groups.iter().enumerate() {
let ordered_entries = batches_graph.get_ordered_entries(&chunk_group_info, i);
let mut entries = Vec::with_capacity(chunk_group.entries_count());
for entry in ordered_entries {
entries.push(batches_graph.get_entry_index(entry).await?);
}
let mut visited = FxHashSet::default();
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_topological(
entries.iter().copied(),
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info {
if !matches!(
ty,
ChunkingType::Parallel | ChunkingType::ParallelInheritAsync
) {
return Ok(GraphTraversalAction::Exclude);
}
}
if visited.insert(module) {
Ok(GraphTraversalAction::Continue)
} else {
Ok(GraphTraversalAction::Exclude)
}
},
|parent_info, item, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info {
if !matches!(
ty,
ChunkingType::Parallel | ChunkingType::ParallelInheritAsync
) {
return;
}
}
items_in_postorder.insert(*item);
},
)?;
let mut styles = FxIndexSet::default();
let mut handle_module = async |module| {
match module_info_map.entry(module) {
Entry::Occupied(mut e) => {
if let Some(info) = e.get_mut() {
info.chunk_group_indicies.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
}
}
Entry::Vacant(e) => {
let style_type = *module.style_type().await?;
if let Some(style_type) = style_type {
let mut info =
ModuleInfo::new(style_type, module.ident().to_string().owned().await?);
info.chunk_group_indicies.insert(idx, styles.len());
info.index_sum += styles.len();
styles.insert(module);
e.insert(Some(info));
} else {
e.insert(None);
}
}
}
anyhow::Ok(())
};
for item in items_in_postorder {
match item {
ModuleOrBatch::Batch(batch) => {
for &module in &batch.await?.modules {
handle_module(module).await?;
}
}
ModuleOrBatch::Module(module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) {
handle_module(chunkable_module).await?;
}
}
ModuleOrBatch::None(_) => {}
}
}
if !styles.is_empty() {
chunk_group_state.push(ChunkGroupState {
requests: styles.len(),
styles,
});
idx += 1;
}
}
module_info_map.retain(|_, info| info.is_some());
module_info_map.sort_by(|_, a, _, b| {
let a = a.as_ref().unwrap();
let b = b.as_ref().unwrap();
a.index_sum
.cmp(&b.index_sum)
.then_with(|| a.ident.cmp(&b.ident))
});
// Compute the dependents of each module
let mut module_dependents: FxHashMap<_, Vec<_>> = FxHashMap::default();
for (&module, info) in &module_info_map {
let info = info.as_ref().unwrap();
// Find the shortest chunk group as it's most efficient to iterate
let (&idx, &start_pos) = info
.chunk_group_indicies
.iter()
.min_by_key(|&(&idx, _)| chunk_group_state[idx].styles.len())
.unwrap();
let potential_dependents = &chunk_group_state[idx].styles[start_pos + 1..];
let dependents = potential_dependents
.iter()
.copied()
.filter(|dependent| {
let dependent_info = module_info_map.get(dependent).unwrap();
let dependent_info = dependent_info.as_ref().unwrap();
// module is a dependency of dependent when it's included in all chunk groups of
// dependent with an index lower than the index of the dependent
let is_dependent =
info.chunk_group_indicies.len() >= dependent_info.chunk_group_indicies.len()
&& dependent_info.chunk_group_indicies.iter().all(
|(idx, &dependent_pos)| {
info.chunk_group_indicies
.get(idx)
.is_some_and(|&module_pos| module_pos < dependent_pos)
},
);
is_dependent
})
.collect::<Vec<_>>();
if !dependents.is_empty() {
module_dependents.insert(module, dependents);
}
}
// Compute the chunk item and size of each module
let chunk_item_and_sizes = module_info_map
.keys()
.map(async |&module| {
let chunk_item = attach_async_info_to_chunkable_module(
module,
&async_info,
module_graph,
chunking_context,
)
.await?;
let ty = chunk_item.chunk_item.ty();
let size = *ty
.chunk_item_size(chunking_context, *chunk_item.chunk_item, None)
.await?;
Ok((chunk_item, size))
})
.try_join()
.await?;
module_info_map
.iter_mut()
.zip(chunk_item_and_sizes)
.for_each(|((_, info), (chunk_item, size))| {
let info = info.as_mut().unwrap();
info.size = size;
info.chunk_item = Some(chunk_item);
});
let mut ordered_modules_with_state = module_info_map
.keys()
.copied()
.map(|m| (m, false))
.collect::<FxIndexMap<_, _>>();
let mut shared_chunk_items = FxIndexMap::default();
for i in 0..ordered_modules_with_state.len() {
let (&module, processed) = ordered_modules_with_state.get_index_mut(i).unwrap();
if *processed {
continue;
}
*processed = true;
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let mut global_mode = info.style_type == StyleType::GlobalStyle;
// The current position of processing in all selected chunk groups
let mut all_chunk_states = info.chunk_group_indicies.clone();
// The list of modules and chunk items that go into the new chunk
let mut new_chunk_modules = [module].into_iter().collect::<FxHashSet<_>>();
let mut new_chunk_items = vec![info.chunk_item.as_ref().unwrap().clone()];
// The current size of the new chunk
let mut current_size = info.size;
// A pool of potential modules where the next module is selected from.
// It's filled from the next module of the selected modules in every chunk group.
let mut potential_next_modules = all_chunk_states
.iter()
.filter_map(|(&idx, pos)| {
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
let i = following_styles
.iter()
.position(|m| !*ordered_modules_with_state.get(m).unwrap());
i.map(|i| following_styles[i])
})
.collect::<FxHashSet<_>>();
// Try to add modules to the chunk until a break condition is met
'outer: loop {
// We try to select a module that reduces request count and
// has the highest number of requests
let mut ordered_potential_next_modules = potential_next_modules
.iter()
.copied()
.map(|module| {
let info = module_info_map.get(&module).unwrap().as_ref().unwrap();
let requests = info
.chunk_group_indicies
.keys()
.filter(|idx| all_chunk_states.contains_key(idx))
.map(|&idx| chunk_group_state[idx].requests)
.max()
.unwrap();
(module, info, requests)
})
.collect::<Vec<_>>();
ordered_potential_next_modules
.sort_by_key(|(_, info, requests)| (Reverse(*requests), &info.ident));
// Try every potential module
for (module, info, _) in ordered_potential_next_modules {
if current_size + info.size > config.max_chunk_size {
// Chunk would be too large
continue;
}
// In loose mode we only check if the dependencies are not violated
if let Some(dependents) = module_dependents.get(&module) {
if dependents.iter().any(|m| new_chunk_modules.contains(m)) {
// A dependent of the module is already in the chunk, which would violate
// the order
continue;
}
}
// Global CSS must not leak into unrelated chunks
let is_global = info.style_type == StyleType::GlobalStyle;
if is_global
&& global_mode
&& all_chunk_states.len() != info.chunk_group_indicies.len()
{
// Fast check: chunk groups need to be identical
continue;
}
if global_mode
&& info
.chunk_group_indicies
.keys()
.any(|idx| !all_chunk_states.contains_key(idx))
{
// Global CSS in new_chunk_items would leak into new chunk_group
continue;
}
if is_global
&& all_chunk_states
.keys()
.any(|idx| !info.chunk_group_indicies.contains_key(idx))
{
// Global CSS would leak into existing chunk_group
continue;
}
potential_next_modules.remove(&module);
current_size += info.size;
if is_global {
global_mode = true;
}
for &idx in info.chunk_group_indicies.keys() {
if all_chunk_states.contains_key(&idx) {
// This reduces the request count of the chunk group
chunk_group_state[idx].requests -= 1;
}
let pos = chunk_group_state[idx].styles.get_index_of(&module).unwrap();
all_chunk_states.insert(idx, pos);
let following_styles = &chunk_group_state[idx].styles[pos + 1..];
if let Some(i) = following_styles.iter().position(|m| {
!*ordered_modules_with_state.get(m).unwrap()
&& !new_chunk_modules.contains(m)
}) {
let module = following_styles[i];
potential_next_modules.insert(module);
}
}
new_chunk_items.push(info.chunk_item.as_ref().unwrap().clone());
new_chunk_modules.insert(module);
*ordered_modules_with_state.get_mut(&module).unwrap() = true;
continue 'outer;
}
break;
}
if new_chunk_items.len() > 1 {
let style_group = ChunkItemBatchWithAsyncModuleInfo::new(new_chunk_items.clone())
.to_resolved()
.await?;
for chunk_item in new_chunk_items {
shared_chunk_items.insert(chunk_item, style_group);
}
}
}
Ok(StyleGroups { shared_chunk_items }.cell())
}
......@@ -7,7 +7,7 @@ use turbopack_core::{
chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkingContext, MinifyType},
context::AssetContext,
ident::AssetIdent,
module::Module,
module::{Module, OptionStyleType, StyleType},
module_graph::ModuleGraph,
output::OutputAssets,
reference::{ModuleReference, ModuleReferences},
......@@ -133,6 +133,15 @@ impl Module for CssModuleAsset {
ParseCssResult::NotFound => Ok(ModuleReferences::empty()),
}
}
#[turbo_tasks::function]
fn style_type(&self) -> Vc<OptionStyleType> {
let style_type = match self.ty {
CssModuleAssetType::Default => StyleType::GlobalStyle,
CssModuleAssetType::Module => StyleType::IsolatedStyle,
};
Vc::cell(Some(style_type))
}
}
#[turbo_tasks::value_impl]
......
......@@ -498,7 +498,7 @@ impl ValueToString for CssChunkType {
#[turbo_tasks::value_impl]
impl ChunkType for CssChunkType {
#[turbo_tasks::function]
fn must_keep_item_order(self: Vc<Self>) -> Vc<bool> {
fn is_style(self: Vc<Self>) -> Vc<bool> {
Vc::cell(true)
}
......
......@@ -27,7 +27,7 @@ impl ValueToString for EcmascriptChunkType {
#[turbo_tasks::value_impl]
impl ChunkType for EcmascriptChunkType {
#[turbo_tasks::function]
fn must_keep_item_order(self: Vc<Self>) -> Vc<bool> {
fn is_style(self: Vc<Self>) -> Vc<bool> {
Vc::cell(false)
}
......
......@@ -427,7 +427,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
.chunking_config(
Vc::<CssChunkType>::default().to_resolved().await?,
ChunkingConfig {
min_chunk_size: 0,
max_merge_chunk_size: 100_000,
..Default::default()
},
)
......
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