Unverified Commit ed1db36c authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

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 #

-->
parent 5712c05c
......@@ -288,6 +288,47 @@ pub enum ChunkGroupKey {
},
}
impl ChunkGroupKey {
pub async fn debug_str(
&self,
keys: impl std::ops::Index<usize, Output = Self>,
) -> Result<String> {
Ok(match self {
ChunkGroupKey::Entry(entries) => format!(
"Entry({:?})",
entries
.iter()
.map(|m| m.ident().to_string())
.try_join()
.await?
),
ChunkGroupKey::Async(module) => {
format!("Async({:?})", module.ident().to_string().await?)
}
ChunkGroupKey::Isolated(module) => {
format!("Isolated({:?})", module.ident().to_string().await?)
}
ChunkGroupKey::IsolatedMerged { parent, merge_tag } => {
format!(
"IsolatedMerged {{ parent: {}, merge_tag: {:?} }}",
Box::pin(keys.index(parent.0 as usize).clone().debug_str(keys)).await?,
merge_tag
)
}
ChunkGroupKey::Shared(module) => {
format!("Shared({:?})", module.ident().to_string().await?)
}
ChunkGroupKey::SharedMerged { parent, merge_tag } => {
format!(
"SharedMerged {{ parent: {}, merge_tag: {:?} }}",
Box::pin(keys.index(parent.0 as usize).clone().debug_str(keys)).await?,
merge_tag
)
}
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ChunkGroupId(u32);
......@@ -645,6 +686,53 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
span.record("visit_count", visit_count);
span.record("chunk_group_count", chunk_groups_map.len());
#[cfg(debug_assertions)]
{
use once_cell::sync::Lazy;
static PRINT_CHUNK_GROUP_INFO: Lazy<bool> =
Lazy::new(|| match std::env::var_os("TURBOPACK_PRINT_CHUNK_GROUPS") {
Some(v) => v == "1",
None => false,
});
if *PRINT_CHUNK_GROUP_INFO {
use std::{
collections::{BTreeMap, BTreeSet},
path::absolute,
};
let mut buckets = BTreeMap::default();
for (module, key) in &module_chunk_groups {
if !key.is_empty() {
buckets
.entry(key.iter().collect::<Vec<_>>())
.or_insert(BTreeSet::new())
.insert(module.ident().to_string().await?);
}
}
let mut result = vec![];
result.push("Chunk Groups:".to_string());
for (i, (key, _)) in chunk_groups_map.iter().enumerate() {
result.push(format!(
" {:?}: {}",
i,
key.debug_str(chunk_groups_map.keys()).await?
));
}
result.push("# Module buckets:".to_string());
for (key, modules) in buckets.iter() {
result.push(format!("## {:?}:", key.iter().collect::<Vec<_>>()));
for module in modules {
result.push(format!(" {module}"));
}
result.push("".to_string());
}
let f = absolute("chunk_group_info.log")?;
println!("written to {}", f.display());
std::fs::write(f, result.join("\n"))?;
}
}
Ok(ChunkGroupInfo {
module_chunk_groups,
chunk_group_keys: chunk_groups_map.keys().cloned().collect(),
......
......@@ -1221,6 +1221,21 @@ impl ModuleGraph {
Ok(idx)
}
/// Returns a map of all modules in the graphs to their identifiers.
/// This is primarily useful for debugging.
pub async fn get_ids(&self) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, ReadRef<RcStr>>> {
Ok(self
.get_graphs()
.await?
.iter()
.flat_map(|g| g.iter_nodes())
.map(async |n| Ok((n.module, n.module.ident().to_string().await?)))
.try_join()
.await?
.into_iter()
.collect::<FxHashMap<_, _>>())
}
/// Traverses all reachable edges exactly once and calls the visitor with the edge source and
/// target.
///
......
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