Commit 95e991e0 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig

Use correct ChunkGroups for chunking

parent 6d82715d
......@@ -1328,16 +1328,31 @@ impl AppEndpoint {
*client_chunking_context,
availability_info,
ssr_chunking_context.map(|ctx| *ctx),
if let Some(rsc_edge_inner) = app_entry.rsc_edge_inner {
ChunkGroup::Async(rsc_edge_inner)
} else {
ChunkGroup::Entry([app_entry.rsc_entry].into_iter().collect())
},
project.project_path(),
)
.to_resolved()
.await?;
let client_references_chunks_ref = client_references_chunks.await?;
for &assets in client_references_chunks_ref
for assets in client_references_chunks_ref
.layout_segment_client_chunks
.values()
{
client_assets.extend(assets.all_assets().await?.iter().copied());
client_assets.extend(
assets
.iter()
.map(|a| a.all_assets())
.try_join()
.await?
.iter()
.flatten()
.copied(),
);
}
for &assets in client_references_chunks_ref
.client_component_client_chunks
......@@ -1790,7 +1805,7 @@ impl AppEndpoint {
let chunk_group2_assets = chunking_context.evaluated_chunk_group_assets(
app_entry.rsc_entry.ident(),
ChunkGroup::Entry(vec![app_entry.rsc_entry]),
ChunkGroup::Entry([app_entry.rsc_entry].into_iter().collect()),
module_graph,
chunk_group1.await?.availability_info,
);
......@@ -1803,7 +1818,8 @@ impl AppEndpoint {
async {
let mut current_chunk_group = ChunkGroupResult::empty_resolved();
let entry_chunk_group = ChunkGroup::Entry(vec![app_entry.rsc_entry]);
let entry_chunk_group =
ChunkGroup::Entry([app_entry.rsc_entry].into_iter().collect());
let chunk_group_info = module_graph.chunk_group_info();
......@@ -1822,7 +1838,9 @@ impl AppEndpoint {
.iter()
.map(async |m| Ok(ResolvedVc::upcast(m.await?.module)))
.try_join()
.await?;
.await?
.into_iter()
.collect();
let chunk_group = chunking_context
.chunk_group(
AssetIdent::from_path(
......@@ -1832,7 +1850,7 @@ impl AppEndpoint {
ChunkGroup::SharedMerged {
merge_tag: NEXT_SERVER_UTILITY_MERGE_TAG.clone(),
entries: server_utils,
parent: parent_chunk_group,
parent: parent_chunk_group as usize,
},
module_graph,
AvailabilityInfo::root(),
......
......@@ -105,7 +105,7 @@ impl InstrumentationEndpoint {
let edge_chunking_context = this.project.edge_chunking_context(false);
Ok(edge_chunking_context.evaluated_chunk_group_assets(
module.ident(),
ChunkGroup::Entry(vec![module]),
ChunkGroup::Entry([module].into_iter().collect()),
module_graph,
AvailabilityInfo::root(),
))
......@@ -126,7 +126,7 @@ impl InstrumentationEndpoint {
.node_root()
.await?
.join("server/instrumentation.js")?,
ChunkGroup::Entry(vec![userland_module]),
ChunkGroup::Entry([userland_module].into_iter().collect()),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
......
......@@ -115,7 +115,7 @@ impl MiddlewareEndpoint {
let edge_chunking_context = this.project.edge_chunking_context(false);
let edge_chunk_grou = edge_chunking_context.evaluated_chunk_group_assets(
module.ident(),
ChunkGroup::Entry(vec![module]),
ChunkGroup::Entry([module].into_iter().collect()),
module_graph,
AvailabilityInfo::root(),
);
......@@ -137,7 +137,7 @@ impl MiddlewareEndpoint {
.node_root()
.await?
.join("server/middleware.js")?,
ChunkGroup::Entry(vec![userland_module]),
ChunkGroup::Entry([userland_module].into_iter().collect()),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
......
......@@ -1022,7 +1022,7 @@ impl PageEndpoint {
if is_edge {
let chunk_assets = edge_chunking_context.evaluated_chunk_group_assets(
ssr_module.ident(),
ChunkGroup::Entry(vec![ssr_module]),
ChunkGroup::Entry([ssr_module].into_iter().collect()),
ssr_module_graph,
current_chunk_group.await?.availability_info,
);
......@@ -1050,7 +1050,7 @@ impl PageEndpoint {
let ssr_entry_chunk = node_chunking_context
.entry_chunk_group_asset(
ssr_entry_chunk_path,
ChunkGroup::Entry(vec![ssr_module]),
ChunkGroup::Entry([ssr_module].into_iter().collect()),
ssr_module_graph,
current_chunk_group.primary_assets(),
current_chunk_group.referenced_assets(),
......
use std::cmp::Ordering;
use anyhow::Result;
use futures::join;
use tracing::Instrument;
use turbo_rcstr::rcstr;
use turbo_tasks::{
FxIndexMap, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueToStringRef, Vc,
};
use turbo_tasks::{FxIndexMap, ResolvedVc, TryJoinIterExt, ValueToStringRef, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
chunk::{ChunkGroupResult, ChunkingContext, availability_info::AvailabilityInfo},
ident::AssetIdent,
module::Module,
module_graph::{ModuleGraph, chunk_group_info::ChunkGroup},
output::OutputAssetsWithReferenced,
......@@ -20,8 +23,11 @@ use crate::{
visit_client_reference::ClientReferenceGraphResult,
},
next_server_component::server_component_module::NextServerComponentModule,
next_server_utility::NEXT_SERVER_UTILITY_MERGE_TAG,
};
type ServerComponentOrUtilites = Option<ResolvedVc<NextServerComponentModule>>;
#[turbo_tasks::value]
pub struct ClientReferencesChunks {
#[bincode(with = "turbo_bincode::indexmap")]
......@@ -32,7 +38,7 @@ pub struct ClientReferencesChunks {
FxIndexMap<ClientReferenceType, ResolvedVc<OutputAssetsWithReferenced>>,
#[bincode(with = "turbo_bincode::indexmap")]
pub layout_segment_client_chunks:
FxIndexMap<ResolvedVc<NextServerComponentModule>, ResolvedVc<OutputAssetsWithReferenced>>,
FxIndexMap<ServerComponentOrUtilites, Vec<ResolvedVc<OutputAssetsWithReferenced>>>,
}
/// Computes all client references chunks.
......@@ -46,6 +52,8 @@ pub async fn get_app_client_references_chunks(
client_chunking_context: Vc<Box<dyn ChunkingContext>>,
client_availability_info: AvailabilityInfo,
ssr_chunking_context: Option<Vc<Box<dyn ChunkingContext>>>,
entry_chunk_group: ChunkGroup,
project_path: Vc<FileSystemPath>,
) -> Result<Vc<ClientReferencesChunks>> {
async move {
// TODO Reconsider this. Maybe it need to be true in production.
......@@ -138,27 +146,24 @@ pub async fn get_app_client_references_chunks(
// }
// .cell())
} else {
// First None = server utils / "framework refernces", and then all layout segment server
// components (in order)
let mut client_references_by_server_component: FxIndexMap<_, Vec<_>> =
FxIndexMap::default();
let mut framework_reference_types = Vec::new();
for &server_component in app_client_references.server_component_entries.iter() {
client_references_by_server_component
.entry(server_component)
.or_default();
}
FxIndexMap::from_iter(
std::iter::once(None)
.chain(
app_client_references
.server_component_entries
.iter()
.map(Some),
)
.map(|server_component| (server_component.cloned(), vec![])),
);
for client_reference in app_client_references.client_references.iter() {
if let Some(server_component) = client_reference.server_component {
client_references_by_server_component
.entry(server_component)
.or_default()
.push(client_reference.ty);
} else {
framework_reference_types.push(client_reference.ty);
}
}
// Framework components need to go into first layout segment
if let Some((_, list)) = client_references_by_server_component.first_mut() {
list.extend(framework_reference_types);
client_references_by_server_component
.entry(client_reference.server_component)
.or_default()
.push(client_reference.ty);
}
let chunk_group_info = module_graph.chunk_group_info();
......@@ -172,150 +177,233 @@ pub async fn get_app_client_references_chunks(
.resolved_cell();
let mut current_ssr_chunk_group = ChunkGroupResult::empty_resolved();
let mut layout_segment_client_chunks = FxIndexMap::default();
let mut layout_segment_client_chunks: FxIndexMap<
ServerComponentOrUtilites,
Vec<ResolvedVc<OutputAssetsWithReferenced>>,
> = FxIndexMap::default();
let mut client_component_ssr_chunks = FxIndexMap::default();
let mut client_component_client_chunks = FxIndexMap::default();
let server_utils_chunk_group = chunk_group_info
.get_merged_group(
entry_chunk_group.clone(),
NEXT_SERVER_UTILITY_MERGE_TAG.clone(),
)
.await?
.first()
.cloned()
// Some entypoints have server utilites that aren't marked as such, fall back to
// page chunk group in that case.
.unwrap_or(entry_chunk_group);
for (server_component, client_reference_types) in
client_references_by_server_component.into_iter()
{
let parent_chunk_group = *chunk_group_info
.get_index_of(ChunkGroup::Shared(ResolvedVc::upcast(server_component)))
.await?;
if server_component.is_none() && client_reference_types.is_empty() {
// Skip if there are no references from server utilites, there is no
// corresponding ChunkGroup in the graph in this case.
continue;
}
let base_ident = server_component.ident();
let mut client_to_ref_ty: FxIndexMap<
ResolvedVc<Box<dyn Module>>,
Vec<ClientReferenceType>,
> = FxIndexMap::default();
for ty in client_reference_types {
match ty {
ClientReferenceType::EcmascriptClientReference(proxy) => {
let proxy = proxy.await?;
client_to_ref_ty
.entry(ResolvedVc::upcast::<Box<dyn Module>>(proxy.client_module))
.or_default()
.push(ty);
client_to_ref_ty
.entry(ResolvedVc::upcast::<Box<dyn Module>>(proxy.ssr_module))
.or_default()
.push(ty);
}
ClientReferenceType::CssClientReference(r) => client_to_ref_ty
.entry(ResolvedVc::upcast::<Box<dyn Module>>(r))
.or_default()
.push(ty),
}
}
let server_path = server_component.server_path().owned().await?;
let is_layout = server_path.file_stem() == Some("layout");
let server_component_path = server_path.to_string_ref().await?;
let parent_chunk_group = if let Some(server_component) = server_component {
ChunkGroup::Shared(ResolvedVc::upcast(server_component.await?.module))
} else {
server_utils_chunk_group.clone()
};
let ssr_modules = client_reference_types
.iter()
.map(|client_reference_ty| async move {
Ok(match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference,
) => {
let ecmascript_client_reference_ref =
ecmascript_client_reference.await?;
Some(ResolvedVc::upcast(
ecmascript_client_reference_ref.ssr_module,
))
}
_ => None,
})
})
.try_flat_join()
let parent_chunk_group_id = chunk_group_info
.get_index_of(parent_chunk_group.clone())
.await?;
let ssr_chunk_group = if !ssr_modules.is_empty()
&& let Some(ssr_chunking_context) = ssr_chunking_context
{
let availability_info = current_ssr_chunk_group.await?.availability_info;
let _span = tracing::info_span!(
"server side rendering",
layout_segment = display(&server_component_path),
let client_chunk_groups = chunk_group_info
.get_all_merged_groups(
parent_chunk_group.clone(),
ecmascript_client_reference_merge_tag().clone(),
)
.entered();
Some(ssr_chunking_context.chunk_group(
base_ident.with_modifier(rcstr!("ssr modules")),
ChunkGroup::IsolatedMerged {
parent: parent_chunk_group,
merge_tag: ecmascript_client_reference_merge_tag_ssr(),
entries: ssr_modules,
},
module_graph,
availability_info,
))
} else {
None
.await?;
let ssr_chunk_groups = chunk_group_info
.get_all_merged_groups(
parent_chunk_group.clone(),
ecmascript_client_reference_merge_tag_ssr().clone(),
)
.await?;
let (base_ident, server_component_path, is_layout) =
if let Some(server_component) = server_component {
let server_path = server_component.server_path().await?;
(
server_component.ident(),
&server_path.to_string_ref().await?,
server_path.file_stem() == Some("layout"),
)
} else {
(
AssetIdent::from_path(project_path.owned().await?),
&*NEXT_SERVER_UTILITY_MERGE_TAG,
false,
)
};
let ssr_chunk_group = async {
if let Some(ssr_chunking_context) = ssr_chunking_context {
let availability_info = current_ssr_chunk_group.await?.availability_info;
ssr_chunk_groups
.iter()
.map(async |chunk_group| {
if let Some(chunk_group_reordered) =
reorder_isolated_merged_entries(chunk_group, &client_to_ref_ty)
{
Ok(Some((
chunk_group.clone(),
ssr_chunking_context.chunk_group(
base_ident.with_modifier(rcstr!("ssr modules")),
chunk_group_reordered,
module_graph,
availability_info,
),
)))
} else {
Ok(None)
}
})
.try_join()
.instrument(tracing::info_span!(
"server side rendering",
layout_segment = display(&server_component_path),
))
.await
} else {
Ok(vec![])
}
};
let client_modules = client_reference_types
let client_chunk_group = client_chunk_groups
.iter()
.map(|client_reference_ty| async move {
Ok(match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference,
) => {
ResolvedVc::upcast(ecmascript_client_reference.await?.client_module)
}
ClientReferenceType::CssClientReference(css_client_reference) => {
ResolvedVc::upcast(*css_client_reference)
}
})
.map(async |chunk_group| {
if let Some(chunk_group_reordered) =
reorder_isolated_merged_entries(chunk_group, &client_to_ref_ty)
{
let availability_info =
current_client_chunk_group.await?.availability_info;
Ok(Some((
chunk_group.clone(),
client_chunking_context.chunk_group(
base_ident.with_modifier(rcstr!("client modules")),
chunk_group_reordered,
module_graph,
availability_info,
),
)))
} else {
Ok(None)
}
})
.try_join()
.await?;
let client_chunk_group = if !client_modules.is_empty() {
let availability_info = current_client_chunk_group.await?.availability_info;
let _span = tracing::info_span!(
.instrument(tracing::info_span!(
"client side rendering",
layout_segment = display(&server_component_path),
)
.entered();
Some(client_chunking_context.chunk_group(
base_ident.with_modifier(rcstr!("client modules")),
ChunkGroup::IsolatedMerged {
parent: parent_chunk_group,
merge_tag: ecmascript_client_reference_merge_tag(),
entries: client_modules,
},
module_graph,
availability_info,
))
} else {
None
};
));
if let Some(client_chunk_group) = client_chunk_group {
let client_chunk_group = current_client_chunk_group
.concatenate(client_chunk_group)
let (client_chunk_group, ssr_chunk_group) =
join!(client_chunk_group, ssr_chunk_group);
for (chunk_group, chunks_group_result) in ssr_chunk_group?.into_iter().flatten() {
let ssr_chunk_group = current_ssr_chunk_group
.concatenate(chunks_group_result)
.to_resolved()
.await?;
if is_layout {
current_client_chunk_group = client_chunk_group;
let ChunkGroup::IsolatedMerged {
parent, entries, ..
} = chunk_group
else {
unreachable!("unexpected ChunkGroup type")
};
if is_layout && parent == (*parent_chunk_group_id as usize) {
// This server component is a layout segment, and this chunk is a direct
// child of that layout segment (not inside of an async import).
current_ssr_chunk_group = ssr_chunk_group;
}
let assets = client_chunk_group
let assets = ssr_chunk_group
.output_assets_with_referenced()
.to_resolved()
.await?;
layout_segment_client_chunks.insert(server_component, assets);
for &client_reference_ty in client_reference_types.iter() {
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
for entry in &*entries {
for client_reference_ty in client_to_ref_ty.get(entry).into_iter().flatten()
{
client_component_client_chunks
.insert(client_reference_ty, client_chunk_group);
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
{
client_component_ssr_chunks.insert(*client_reference_ty, assets);
}
}
}
}
if let Some(ssr_chunk_group) = ssr_chunk_group {
let ssr_chunk_group = current_ssr_chunk_group
.concatenate(ssr_chunk_group)
for (chunk_group, chunk_group_result) in client_chunk_group?.into_iter().flatten() {
let client_chunk_group = current_client_chunk_group
.concatenate(chunk_group_result)
.to_resolved()
.await?;
if is_layout {
current_ssr_chunk_group = ssr_chunk_group;
let ChunkGroup::IsolatedMerged {
parent, entries, ..
} = chunk_group
else {
unreachable!("unexpected ChunkGroup type")
};
if is_layout && parent == (*parent_chunk_group_id as usize) {
// This server component is a layout segment, and this chunk is a direct
// child of that layout segment (not inside of an async import).
current_client_chunk_group = client_chunk_group;
}
let assets = ssr_chunk_group
let assets = client_chunk_group
.output_assets_with_referenced()
.to_resolved()
.await?;
for &client_reference_ty in client_reference_types.iter() {
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
layout_segment_client_chunks
.entry(server_component)
.or_default()
.push(assets);
for entry in &*entries {
for client_reference_ty in client_to_ref_ty.get(entry).into_iter().flatten()
{
client_component_ssr_chunks.insert(client_reference_ty, assets);
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
{
client_component_client_chunks
.insert(*client_reference_ty, client_chunk_group);
}
}
}
}
......@@ -332,3 +420,47 @@ pub async fn get_app_client_references_chunks(
.instrument(tracing::info_span!("process client references"))
.await
}
fn reorder_isolated_merged_entries(
chunk_group: &ChunkGroup,
client_to_ref_ty: &FxIndexMap<ResolvedVc<Box<dyn Module>>, Vec<ClientReferenceType>>,
) -> Option<ChunkGroup> {
let ChunkGroup::IsolatedMerged {
parent,
entries,
merge_tag,
} = chunk_group
else {
unreachable!("expected ChunkGroup::IsolatedMerged for client reference")
};
// Reorder the entries, because the order of IsolatedMerged entries obtained by chunk_group_info
// is unspecified (and thus not strictly execution order, which is a problem for CSS).
//
// However, any client references that are not listed in client_to_ref_ty still need to be
// retained (they were already chunked in a preceding layout segment), but the order doesn't
// matter in this case (since they will not be chunked in this step anyway).
if entries.iter().any(|m| client_to_ref_ty.contains_key(m)) {
let mut entries = entries.clone();
entries.sort_by(|a, b| {
match (
client_to_ref_ty.get_index_of(a),
client_to_ref_ty.get_index_of(b),
) {
(Some(a), Some(b)) => a.cmp(&b),
// We don't know, so just keep the same order.
_ => Ordering::Equal,
}
});
Some(ChunkGroup::IsolatedMerged {
parent: *parent,
entries,
merge_tag: merge_tag.clone(),
})
} else {
// Not a single client reference is "new" in the current layout segment, the result of
// chunking will be an empty list anyway.
None
}
}
......@@ -14,6 +14,8 @@ pub struct AppEntry {
pub original_name: RcStr,
/// The RSC module asset for the route or page.
pub rsc_entry: ResolvedVc<Box<dyn Module>>,
/// For edge, the module wrapped by the sync-ifying facade
pub rsc_edge_inner: Option<ResolvedVc<Box<dyn Module>>>,
/// The source code config for this entry.
pub config: ResolvedVc<NextSegmentConfig>,
}
......@@ -101,27 +101,41 @@ pub async fn get_app_page_entry(
AssetContent::file(FileContent::Content(file).cell()),
);
let mut rsc_entry = module_asset_context
let rsc_entry = module_asset_context
.process(
Vc::upcast(source),
ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
)
.module();
if is_edge {
rsc_entry = wrap_edge_page(
let (rsc_entry, rsc_edge_inner) = if is_edge {
let rsc_entry = wrap_edge_page(
*ResolvedVc::upcast(module_asset_context),
project_root.clone(),
rsc_entry,
page,
page.clone(),
next_config,
);
)
.to_resolved()
.await?;
(
wrap_edge_entry(
*ResolvedVc::upcast(module_asset_context),
project_root,
*rsc_entry,
app_function_name(&page).into(),
),
Some(rsc_entry),
)
} else {
(rsc_entry, None)
};
Ok(AppEntry {
pathname,
original_name,
rsc_entry: rsc_entry.to_resolved().await?,
rsc_edge_inner,
config: config.to_resolved().await?,
}
.cell())
......@@ -213,10 +227,5 @@ async fn wrap_edge_page(
)
.module();
Ok(wrap_edge_entry(
asset_context,
project_root,
wrapped,
app_function_name(&page).into(),
))
Ok(wrapped)
}
......@@ -101,27 +101,41 @@ pub async fn get_app_route_entry(
inner => userland_module
};
let mut rsc_entry = module_asset_context
let rsc_entry = module_asset_context
.process(
virtual_source,
ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
)
.module();
if is_edge {
rsc_entry = wrap_edge_route(
let (rsc_entry, rsc_edge_inner) = if is_edge {
let rsc_entry = wrap_edge_route(
Vc::upcast(module_asset_context),
project_root,
project_root.clone(),
rsc_entry,
page,
page.clone(),
next_config,
);
}
)
.to_resolved()
.await?;
(
wrap_edge_entry(
Vc::upcast(module_asset_context),
project_root,
*rsc_entry,
app_function_name(&page).into(),
),
Some(rsc_entry),
)
} else {
(rsc_entry, None)
};
Ok(AppEntry {
pathname,
original_name,
rsc_entry: rsc_entry.to_resolved().await?,
rsc_edge_inner,
config: config.to_resolved().await?,
}
.cell())
......@@ -213,10 +227,5 @@ async fn wrap_edge_route(
)
.module();
Ok(wrap_edge_entry(
asset_context,
project_root.clone(),
wrapped,
app_function_name(&page).into(),
))
Ok(wrapped)
}
......@@ -409,8 +409,16 @@ async fn build_manifest(
}
}
// The server utility chunks are merged into the first layout segment
let mut server_utility_chunks = layout_segment_client_chunks.get(&None);
// per layout segment chunks need to be emitted into the manifest too
for (server_component, client_assets) in layout_segment_client_chunks.iter() {
let Some(server_component) = server_component else {
// Handled via server_utility_chunks
continue;
};
// Use source_path() to get the original source path (e.g., page.mdx) instead of
// server_path() which returns the transformed path (e.g., page.mdx.tsx).
// This ensures the manifest key matches what the LoaderTree stores and what
......@@ -430,10 +438,17 @@ async fn build_manifest(
.entry(server_component_name)
.or_default();
let client_chunks = client_assets.primary_assets().await?;
let client_chunks_with_path =
cached_chunk_paths(&mut client_chunk_path_cache, client_chunks.iter().copied())
.await?;
let client_chunks = client_assets
.iter()
.chain(server_utility_chunks.take().into_iter().flatten())
.map(|assets| assets.primary_assets())
.try_join()
.await?;
let client_chunks_with_path = cached_chunk_paths(
&mut client_chunk_path_cache,
client_chunks.iter().flatten().copied(),
)
.await?;
// Inlining breaks HMR so it is always disabled in dev.
let inlined_css = *next_config.inline_css().await? && mode.is_production();
......
use std::time::Duration;
use std::{
hash::{BuildHasher, Hash},
ops::{Deref, DerefMut},
time::Duration,
};
use anyhow::Result;
use bincode::{
Decode, Encode,
de::Decoder,
enc::Encoder,
error::{DecodeError, EncodeError},
};
use rustc_hash::FxBuildHasher;
use turbo_rcstr::RcStr;
use turbo_tasks_macros::primitive as __turbo_tasks_internal_primitive;
use turbo_tasks_macros::{TraceRawVcs, primitive as __turbo_tasks_internal_primitive};
use crate::{
self as turbo_tasks, Vc,
self as turbo_tasks, FxIndexSet, NonLocalValue, TaskInput, Vc,
value_type::{ManualDecodeWrapper, ManualEncodeWrapper},
};
......@@ -75,3 +81,72 @@ impl<Context> Decode<Context> for JsonValueDecodeWrapper {
Ok(Self(turbo_bincode::serde_self_describing::decode(decoder)?))
}
}
/// An IndexSet with a Hash implementation that is order-independent (and just like IndexSet,
/// equality is also order-independent).
#[derive(Clone, Debug, PartialEq, Eq, Decode, Encode, TraceRawVcs)]
pub struct HashableIndexSet<T: Hash + Eq + Decode<()> + Encode>(
#[bincode(with = "turbo_bincode::indexset")] pub FxIndexSet<T>,
);
impl<T: Hash + Eq + Decode<()> + Encode> From<FxIndexSet<T>> for HashableIndexSet<T> {
fn from(set: FxIndexSet<T>) -> Self {
HashableIndexSet(set)
}
}
impl<T: Hash + Eq + Decode<()> + Encode> FromIterator<T> for HashableIndexSet<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
HashableIndexSet(iter.into_iter().collect())
}
}
impl<T: Hash + Eq + Decode<()> + Encode> Deref for HashableIndexSet<T> {
type Target = FxIndexSet<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: Hash + Eq + Decode<()> + Encode> DerefMut for HashableIndexSet<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: Hash + Eq + Decode<()> + Encode> Hash for HashableIndexSet<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let mut result = 0u64;
for item in self.iter() {
let item_hash = FxBuildHasher.hash_one(item);
result ^= item_hash;
}
state.write_u64(result);
}
}
impl<T> TaskInput for HashableIndexSet<T>
where
T: TaskInput,
{
fn is_resolved(&self) -> bool {
self.iter().all(TaskInput::is_resolved)
}
fn is_transient(&self) -> bool {
self.iter().any(TaskInput::is_transient)
}
async fn resolve_input(&self) -> Result<Self> {
let mut resolved = FxIndexSet::with_capacity_and_hasher(self.len(), Default::default());
for value in self.iter() {
resolved.insert(value.resolve_input().await?);
}
Ok(HashableIndexSet(resolved))
}
}
unsafe impl<T: NonLocalValue + Hash + Eq + Decode<()> + Encode> NonLocalValue
for HashableIndexSet<T>
{
}
......@@ -476,7 +476,11 @@ async fn build_internal(
.unwrap(),
)?
.with_extension("entry.js"),
ChunkGroup::Entry(vec![ResolvedVc::upcast(ecmascript)]),
ChunkGroup::Entry(
[ResolvedVc::upcast(ecmascript)]
.into_iter()
.collect(),
),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
......
use std::{
collections::VecDeque,
hash::Hash,
ops::{Deref, DerefMut},
};
......@@ -13,7 +14,7 @@ use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, ValueToString,
Vc, debug::ValueDebugFormat, trace::TraceRawVcs, turbofmt,
Vc, debug::ValueDebugFormat, primitives::HashableIndexSet, trace::TraceRawVcs, turbofmt,
};
use crate::{
......@@ -94,6 +95,12 @@ pub struct ChunkGroupInfo {
#[turbo_tasks(trace_ignore)]
#[bincode(with = "turbo_bincode::indexset")]
pub chunk_group_keys: FxIndexSet<ChunkGroupKey>,
/// Map parent chunk group & merge tag -> children (immediate or via async)
#[turbo_tasks(trace_ignore)]
#[bincode(with = "turbo_bincode::indexmap")]
pub merged_chunk_groups: FxIndexMap<(ChunkGroupId, RcStr), Vec<ChunkGroupId>>,
#[turbo_tasks(trace_ignore)]
pub chunk_group_children: FxHashMap<ChunkGroupId, Vec<ChunkGroupId>>,
}
#[turbo_tasks::value_impl]
......@@ -104,9 +111,9 @@ impl ChunkGroupInfo {
}
#[turbo_tasks::function]
pub async fn get_index_of(&self, chunk_group: ChunkGroup) -> Result<Vc<usize>> {
pub async fn get_index_of(&self, chunk_group: ChunkGroup) -> Result<Vc<ChunkGroupId>> {
if let Some(idx) = self.chunk_groups.get_index_of(&chunk_group) {
Ok(Vc::cell(idx))
Ok(Vc::cell(idx as u32))
} else {
bail!(
"Couldn't find chunk group index for {} in {}",
......@@ -120,6 +127,89 @@ impl ChunkGroupInfo {
);
}
}
#[turbo_tasks::function]
pub async fn get_merged_group(
&self,
parent: ChunkGroup,
merge_tag: RcStr,
) -> Result<Vc<ChunkGroups>> {
if let Some(parent_idx) = self.chunk_groups.get_index_of(&parent) {
let merged = self
.merged_chunk_groups
.get(&(ChunkGroupId(parent_idx as u32), merge_tag))
.iter()
.flat_map(|v| v.iter())
.map(|&idx| self.chunk_groups[*idx as usize].clone())
.collect();
Ok(Vc::cell(merged))
} else {
bail!(
"Couldn't find chunk group index for parent {} in {}",
parent.debug_str(self).await?,
self.chunk_groups
.iter()
.map(|c| c.debug_str(self))
.try_join()
.await?
.join(", ")
);
}
}
#[turbo_tasks::function]
pub async fn get_all_merged_groups(
&self,
parent: ChunkGroup,
merge_tag: RcStr,
) -> Result<Vc<ChunkGroups>> {
if let Some(parent_idx) = self.chunk_groups.get_index_of(&parent) {
let mut result = RoaringBitmap::new();
self.traverse_chunk_groups(ChunkGroupId(parent_idx as u32), |idx| {
result.extend(
self.merged_chunk_groups
.get(&(idx, merge_tag.clone()))
.iter()
.flat_map(|v| v.iter())
.map(|v| v.0),
);
});
Ok(Vc::cell(
result
.iter()
.map(|idx| self.chunk_groups[idx as usize].clone())
.collect(),
))
} else {
bail!(
"Couldn't find chunk group index for parent {} in {}",
parent.debug_str(self).await?,
self.chunk_groups
.iter()
.map(|c| c.debug_str(self))
.try_join()
.await?
.join(", ")
);
}
}
}
impl ChunkGroupInfo {
pub fn traverse_chunk_groups(&self, entry: ChunkGroupId, mut visit: impl FnMut(ChunkGroupId)) {
let mut visited = RoaringBitmap::from_sorted_iter(std::iter::once(entry.0)).unwrap();
let mut queue = VecDeque::from(vec![entry]);
while let Some(group) = queue.pop_front() {
visit(group);
if let Some(children) = self.chunk_group_children.get(&group) {
for child in children {
if visited.insert(child.0) {
queue.push_back(*child);
}
}
}
}
}
}
/// See [ChunkGroup] for documentation
......@@ -157,11 +247,13 @@ impl ChunkGroupEntry {
}
}
#[derive(Debug, Clone, Hash, TaskInput, PartialEq, Eq, TraceRawVcs, Encode, Decode)]
#[derive(
Debug, Clone, Hash, TaskInput, PartialEq, Eq, TraceRawVcs, Encode, Decode, NonLocalValue,
)]
pub enum ChunkGroup {
/// The entry chunk group of the compilation, e.g. src/index.js for a SPA, or app/foo/page.js
/// for Next.js.
Entry(Vec<ResolvedVc<Box<dyn Module>>>),
Entry(HashableIndexSet<ResolvedVc<Box<dyn Module>>>),
/// An async chunk group. Corresponds to an incoming [ChunkingType::Async] reference
Async(ResolvedVc<Box<dyn Module>>),
/// An isolated chunk group. Corresponds to an incoming [ChunkingType::Isolated] reference with
......@@ -172,19 +264,19 @@ pub enum ChunkGroup {
IsolatedMerged {
parent: usize,
merge_tag: RcStr,
entries: Vec<ResolvedVc<Box<dyn Module>>>,
entries: HashableIndexSet<ResolvedVc<Box<dyn Module>>>,
},
/// A shared chunk group. Corresponds to an incoming [ChunkingType::Shared] reference with
/// `merge_tag: None`
Shared(ResolvedVc<Box<dyn Module>>),
/// A shared chunk group with multiple entries.
SharedMultiple(Vec<ResolvedVc<Box<dyn Module>>>),
SharedMultiple(HashableIndexSet<ResolvedVc<Box<dyn Module>>>),
/// A shared chunk group. Corresponds to an incoming [ChunkingType::Shared] reference with
/// `merge_tag: Some(_)`
SharedMerged {
parent: usize,
merge_tag: RcStr,
entries: Vec<ResolvedVc<Box<dyn Module>>>,
entries: HashableIndexSet<ResolvedVc<Box<dyn Module>>>,
},
}
......@@ -306,7 +398,6 @@ pub enum ChunkGroupKey {
merge_tag: RcStr,
},
}
impl ChunkGroupKey {
pub async fn debug_str(
&self,
......@@ -356,7 +447,8 @@ impl ChunkGroupKey {
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encode, Decode)]
#[turbo_tasks::value(transparent)]
#[derive(Debug, Copy, Clone, Hash)]
pub struct ChunkGroupId(u32);
impl From<usize> for ChunkGroupId {
......@@ -365,6 +457,10 @@ impl From<usize> for ChunkGroupId {
}
}
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone, Hash)]
pub struct ChunkGroups(Vec<ChunkGroup>);
impl Deref for ChunkGroupId {
type Target = u32;
fn deref(&self) -> &Self::Target {
......@@ -374,7 +470,7 @@ impl Deref for ChunkGroupId {
#[derive(Debug, Clone, PartialEq, Eq)]
struct TraversalPriority {
depth: usize,
depth: u32,
chunk_group_len: u64,
}
impl PartialOrd for TraversalPriority {
......@@ -405,12 +501,17 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
let span = span_outer.clone();
async move {
// chunk group -> its id and (for merged groups) list of contained modules
#[allow(clippy::type_complexity)]
let mut chunk_groups_map: FxIndexMap<
ChunkGroupKey,
(ChunkGroupId, FxIndexSet<ResolvedVc<Box<dyn Module>>>),
> = FxIndexMap::default();
// chunk group -> child async chunk groups
let mut chunk_group_children: FxHashMap<ChunkGroupId, FxIndexSet<ChunkGroupId>> =
FxHashMap::default();
// For each module, the indices in the bitmap store which chunk groups in `chunk_groups_map`
// that module is part of.
let mut module_chunk_groups: FxHashMap<ResolvedVc<Box<dyn Module>>, RoaringBitmapWrapper> =
......@@ -431,7 +532,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
.collect::<Vec<_>>();
// First, compute the depth for each module in the graph
let module_depth: FxHashMap<ResolvedVc<Box<dyn Module>>, usize> = {
let module_depth: FxHashMap<ResolvedVc<Box<dyn Module>>, u32> = {
let mut module_depth =
FxHashMap::with_capacity_and_hasher(module_count, Default::default());
graph.traverse_edges_bfs(
......@@ -619,7 +720,8 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
ChunkGroupKey::IsolatedMerged { .. }
| ChunkGroupKey::SharedMerged { .. }
);
match chunk_groups_map.entry(chunk_group) {
let is_async = matches!(chunk_group, ChunkGroupKey::Async { .. });
let id = match chunk_groups_map.entry(chunk_group) {
Entry::Occupied(mut e) => {
let (id, merged_entries) = e.get_mut();
if is_merged {
......@@ -636,7 +738,21 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
e.insert((ChunkGroupId(chunk_group_id), set));
chunk_group_id
}
};
if is_async && let Some((parent, _, _)) = parent_info {
let parent_groups = module_chunk_groups
.get(&parent)
.unwrap()
.iter()
.map(ChunkGroupId);
for parent in parent_groups {
chunk_group_children
.entry(parent)
.or_default()
.insert(ChunkGroupId(id));
}
}
id
});
let chunk_groups =
......@@ -759,30 +875,51 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
}
}
let mut chunk_groups =
FxIndexSet::with_capacity_and_hasher(chunk_groups_map.len(), Default::default());
let mut merged_chunk_groups: FxIndexMap<_, Vec<_>> = FxIndexMap::default();
for (key, (id, merged_entries)) in &chunk_groups_map {
if let ChunkGroupKey::IsolatedMerged { parent, merge_tag }
| ChunkGroupKey::SharedMerged { parent, merge_tag } = key
{
merged_chunk_groups
.entry((*parent, merge_tag.clone()))
.or_default()
.push(*id);
}
chunk_groups.insert(match key {
ChunkGroupKey::Entry(entries) => {
ChunkGroup::Entry(entries.iter().copied().collect())
}
ChunkGroupKey::Async(module) => ChunkGroup::Async(*module),
ChunkGroupKey::Isolated(module) => ChunkGroup::Isolated(*module),
ChunkGroupKey::IsolatedMerged { parent, merge_tag } => ChunkGroup::IsolatedMerged {
parent: parent.0 as usize,
merge_tag: merge_tag.clone(),
entries: merged_entries.into_iter().copied().collect(),
},
ChunkGroupKey::Shared(module) => ChunkGroup::Shared(*module),
ChunkGroupKey::SharedMultiple(entries) => {
ChunkGroup::SharedMultiple(entries.iter().copied().collect())
}
ChunkGroupKey::SharedMerged { parent, merge_tag } => ChunkGroup::SharedMerged {
parent: parent.0 as usize,
merge_tag: merge_tag.clone(),
entries: merged_entries.into_iter().copied().collect(),
},
});
}
Ok(ChunkGroupInfo {
module_chunk_groups: ResolvedVc::cell(module_chunk_groups),
chunk_group_keys: chunk_groups_map.keys().cloned().collect(),
chunk_groups: chunk_groups_map
chunk_groups,
merged_chunk_groups,
chunk_group_children: chunk_group_children
.into_iter()
.map(|(k, (_, merged_entries))| match k {
ChunkGroupKey::Entry(entries) => ChunkGroup::Entry(entries),
ChunkGroupKey::Async(module) => ChunkGroup::Async(module),
ChunkGroupKey::Isolated(module) => ChunkGroup::Isolated(module),
ChunkGroupKey::IsolatedMerged { parent, merge_tag } => {
ChunkGroup::IsolatedMerged {
parent: parent.0 as usize,
merge_tag,
entries: merged_entries.into_iter().collect(),
}
}
ChunkGroupKey::Shared(module) => ChunkGroup::Shared(module),
ChunkGroupKey::SharedMultiple(entries) => ChunkGroup::SharedMultiple(entries),
ChunkGroupKey::SharedMerged { parent, merge_tag } => ChunkGroup::SharedMerged {
parent: parent.0 as usize,
merge_tag,
entries: merged_entries.into_iter().collect(),
},
})
.map(|(k, v)| (k, v.into_iter().collect()))
.collect(),
}
.cell())
......
......@@ -170,7 +170,9 @@ impl DevHtmlAsset {
chunking_context
.root_chunk_group_assets(
chunkable_module.ident(),
ChunkGroup::Entry(vec![ResolvedVc::upcast(chunkable_module)]),
ChunkGroup::Entry(
[ResolvedVc::upcast(chunkable_module)].into_iter().collect(),
),
*module_graph,
)
.await?
......
......@@ -726,7 +726,7 @@ impl EvaluateContext for WebpackLoaderContext {
let bootstrap = self.chunking_context.root_entry_chunk_group_asset(
entry_path.clone(),
ChunkGroup::Entry(vec![ResolvedVc::upcast(evaluatable)]),
ChunkGroup::Entry([ResolvedVc::upcast(evaluatable)].into_iter().collect()),
*import_module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
......
......@@ -603,7 +603,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
chunk_root_path
.join(entry_module.ident().path().await?.file_stem().unwrap())?
.with_extension("entry.js"),
ChunkGroup::Entry(entry_modules),
ChunkGroup::Entry(entry_modules.into_iter().collect()),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
......
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