Skip to content

Commit ed1db36

Browse files
authored
Turbopack: chunking debugging utilities (#83801)
<!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # -->
1 parent 5712c05 commit ed1db36

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed

turbopack/crates/turbopack-core/src/module_graph/chunk_group_info.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,47 @@ pub enum ChunkGroupKey {
288288
},
289289
}
290290

291+
impl ChunkGroupKey {
292+
pub async fn debug_str(
293+
&self,
294+
keys: impl std::ops::Index<usize, Output = Self>,
295+
) -> Result<String> {
296+
Ok(match self {
297+
ChunkGroupKey::Entry(entries) => format!(
298+
"Entry({:?})",
299+
entries
300+
.iter()
301+
.map(|m| m.ident().to_string())
302+
.try_join()
303+
.await?
304+
),
305+
ChunkGroupKey::Async(module) => {
306+
format!("Async({:?})", module.ident().to_string().await?)
307+
}
308+
ChunkGroupKey::Isolated(module) => {
309+
format!("Isolated({:?})", module.ident().to_string().await?)
310+
}
311+
ChunkGroupKey::IsolatedMerged { parent, merge_tag } => {
312+
format!(
313+
"IsolatedMerged {{ parent: {}, merge_tag: {:?} }}",
314+
Box::pin(keys.index(parent.0 as usize).clone().debug_str(keys)).await?,
315+
merge_tag
316+
)
317+
}
318+
ChunkGroupKey::Shared(module) => {
319+
format!("Shared({:?})", module.ident().to_string().await?)
320+
}
321+
ChunkGroupKey::SharedMerged { parent, merge_tag } => {
322+
format!(
323+
"SharedMerged {{ parent: {}, merge_tag: {:?} }}",
324+
Box::pin(keys.index(parent.0 as usize).clone().debug_str(keys)).await?,
325+
merge_tag
326+
)
327+
}
328+
})
329+
}
330+
}
331+
291332
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
292333
pub struct ChunkGroupId(u32);
293334

@@ -645,6 +686,53 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
645686
span.record("visit_count", visit_count);
646687
span.record("chunk_group_count", chunk_groups_map.len());
647688

689+
#[cfg(debug_assertions)]
690+
{
691+
use once_cell::sync::Lazy;
692+
static PRINT_CHUNK_GROUP_INFO: Lazy<bool> =
693+
Lazy::new(|| match std::env::var_os("TURBOPACK_PRINT_CHUNK_GROUPS") {
694+
Some(v) => v == "1",
695+
None => false,
696+
});
697+
if *PRINT_CHUNK_GROUP_INFO {
698+
use std::{
699+
collections::{BTreeMap, BTreeSet},
700+
path::absolute,
701+
};
702+
703+
let mut buckets = BTreeMap::default();
704+
for (module, key) in &module_chunk_groups {
705+
if !key.is_empty() {
706+
buckets
707+
.entry(key.iter().collect::<Vec<_>>())
708+
.or_insert(BTreeSet::new())
709+
.insert(module.ident().to_string().await?);
710+
}
711+
}
712+
713+
let mut result = vec![];
714+
result.push("Chunk Groups:".to_string());
715+
for (i, (key, _)) in chunk_groups_map.iter().enumerate() {
716+
result.push(format!(
717+
" {:?}: {}",
718+
i,
719+
key.debug_str(chunk_groups_map.keys()).await?
720+
));
721+
}
722+
result.push("# Module buckets:".to_string());
723+
for (key, modules) in buckets.iter() {
724+
result.push(format!("## {:?}:", key.iter().collect::<Vec<_>>()));
725+
for module in modules {
726+
result.push(format!(" {module}"));
727+
}
728+
result.push("".to_string());
729+
}
730+
let f = absolute("chunk_group_info.log")?;
731+
println!("written to {}", f.display());
732+
std::fs::write(f, result.join("\n"))?;
733+
}
734+
}
735+
648736
Ok(ChunkGroupInfo {
649737
module_chunk_groups,
650738
chunk_group_keys: chunk_groups_map.keys().cloned().collect(),

turbopack/crates/turbopack-core/src/module_graph/mod.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1221,6 +1221,21 @@ impl ModuleGraph {
12211221
Ok(idx)
12221222
}
12231223

1224+
/// Returns a map of all modules in the graphs to their identifiers.
1225+
/// This is primarily useful for debugging.
1226+
pub async fn get_ids(&self) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, ReadRef<RcStr>>> {
1227+
Ok(self
1228+
.get_graphs()
1229+
.await?
1230+
.iter()
1231+
.flat_map(|g| g.iter_nodes())
1232+
.map(async |n| Ok((n.module, n.module.ident().to_string().await?)))
1233+
.try_join()
1234+
.await?
1235+
.into_iter()
1236+
.collect::<FxHashMap<_, _>>())
1237+
}
1238+
12241239
/// Traverses all reachable edges exactly once and calls the visitor with the edge source and
12251240
/// target.
12261241
///

0 commit comments

Comments
 (0)