Unverified Commit 8b9cdc5e authored by Jimmy Miller's avatar Jimmy Miller Committed by GitHub

perf(turbopack): skip ignored files during server tracing (#97475)

So I was playing around with profiling some very simple next apps when I
noticed this. Basically, because of how things were set up we were
spending a good chunk of our build time analyzing files we were going to
reject. I went around and around trying different combinations to make
sure we ignore those files (and only the files we should ignore) to
speed up build times. Since it is a constant impact, mostly on small
projects, but on some, it can make a big difference. I had some
adversarial rounds with agents to see if they can break the config in
the ways the old comments hints at why we didn't do that. And this final
round finally couldn't get it to break.

For a v0-generated Hello World app, compile time is 28.0% faster
(+/-1.7%) and a full clean build is 15.9% faster (+/- 1.2%).

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 4e2abec3
...@@ -5,14 +5,17 @@ use bincode::{Decode, Encode}; ...@@ -5,14 +5,17 @@ use bincode::{Decode, Encode};
use either::Either; use either::Either;
use next_core::{get_next_package, next_server::get_tracing_compile_time_info}; use next_core::{get_next_package, next_server::get_tracing_compile_time_info};
use serde_json::json; use serde_json::json;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc, trace::TraceRawVcs}; use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
DirectoryContent, DirectoryEntry, File, FileContent, FileSystemPath, glob::Glob, DirectoryContent, DirectoryEntry, File, FileContent, FileSystemPath,
glob::{Glob, GlobOptions},
}; };
use turbo_tasks_hash::HashAlgorithm; use turbo_tasks_hash::HashAlgorithm;
use turbopack::externals_tracing_module_context; use turbopack::externals_tracing_module_context;
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
context::AssetContext,
module::{Module, Modules}, module::{Module, Modules},
module_graph::{GraphEntries, ModuleGraph, SingleModuleGraph}, module_graph::{GraphEntries, ModuleGraph, SingleModuleGraph},
output::{OutputAsset, OutputAssets, OutputAssetsReference}, output::{OutputAsset, OutputAssets, OutputAssetsReference},
...@@ -34,11 +37,10 @@ use crate::{nft::traced_modules_for_entries, project::Project}; ...@@ -34,11 +37,10 @@ use crate::{nft::traced_modules_for_entries, project::Project};
/// Used by the server NFTs below and, so that they are part of every endpoint's trace regardless /// Used by the server NFTs below and, so that they are part of every endpoint's trace regardless
/// of how the output is assembled, by [`Project::additional_traced_modules`]. /// of how the output is assembled, by [`Project::additional_traced_modules`].
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn require_hook_modules(project_path: FileSystemPath) -> Result<Vc<Modules>> { pub(crate) async fn require_hook_modules(
let asset_context = Vc::upcast(externals_tracing_module_context( project_path: FileSystemPath,
get_tracing_compile_time_info(), asset_context: Vc<Box<dyn AssetContext>>,
false, ) -> Result<Vc<Modules>> {
));
let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new( let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new(
asset_context, asset_context,
get_next_package(project_path).await?.join("_")?, get_next_package(project_path).await?.join("_")?,
...@@ -75,6 +77,7 @@ pub(crate) async fn pages_renderer_modules(project_path: FileSystemPath) -> Resu ...@@ -75,6 +77,7 @@ pub(crate) async fn pages_renderer_modules(project_path: FileSystemPath) -> Resu
let asset_context = Vc::upcast(externals_tracing_module_context( let asset_context = Vc::upcast(externals_tracing_module_context(
get_tracing_compile_time_info(), get_tracing_compile_time_info(),
false, false,
None,
)); ));
let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new( let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new(
asset_context, asset_context,
...@@ -282,15 +285,97 @@ impl Asset for ServerNftJsonAsset { ...@@ -282,15 +285,97 @@ impl Asset for ServerNftJsonAsset {
} }
} }
/// These globs are used to prune the module graph for the server NFT JSON assets. They are always
/// ignored for every page, so we can completely skip even parsing/walking these modules.
fn next_owned_ignores(
ty: &ServerNftType,
has_next_support: bool,
is_standalone: bool,
) -> Vec<RcStr> {
let mut globs = vec![
rcstr!("**/node_modules/react{,-dom,-server-dom-turbopack}/**/*.development.js"),
rcstr!("**/*.d.ts"),
rcstr!("**/*.map"),
rcstr!("**/next/dist/pages/**/*"),
rcstr!("**/next/dist/compiled/next-server/**/*.dev.js"),
rcstr!("**/next/dist/compiled/webpack/*"),
rcstr!("**/node_modules/webpack5/**/*"),
rcstr!("**/next/dist/server/lib/route-resolver*"),
// The testmode interceptors bundle reads its HTTP parser WASM with a
// dynamic path, making the tracer include the bundle's whole
// directory. Test proxying is not supported in standalone output, so
// keep the parser asset (and the license file picked up by the
// directory glob) out of production traces.
rcstr!("**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE"),
rcstr!("**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**"),
rcstr!("**/next/dist/compiled/semver/semver/**/*.js"),
rcstr!("**/next/dist/compiled/jest-worker/**/*"),
// -- The following were added for Turbopack specifically --
// client/components/use-action-queue.ts has a process.env.NODE_ENV guard, but we can't set that due to React: https://github.com/vercel/next.js/pull/75254
rcstr!("**/next/dist/next-devtools/userspace/use-app-dev-rendering-indicator.js"),
// client/components/app-router.js has a process.env.NODE_ENV guard, but we
// can't set that.
rcstr!("**/next/dist/client/dev/hot-reloader/app/hot-reloader-app.js"),
// server/lib/router-server.js doesn't guard this require:
rcstr!("**/next/dist/server/lib/router-utils/setup-dev-bundler.js"),
// server/next.js doesn't guard this require
rcstr!("**/next/dist/server/dev/next-dev-server.js"),
// next/dist/compiled/babel* pulls in this, but we never actually transpile at
// deploy-time
rcstr!("**/next/dist/compiled/browserslist/**"),
];
// only ignore image-optimizer code when
// this is being handled outside of next-server
if has_next_support {
globs.extend([
rcstr!("**/node_modules/sharp/**/*"),
rcstr!("**/@img/sharp-libvips*/**/*"),
rcstr!("**/next/dist/server/image-optimizer.js"),
]);
}
if !is_standalone {
globs.extend([
rcstr!("**/*/next/dist/server/next.js"),
rcstr!("**/*/next/dist/bin/next"),
]);
}
if matches!(ty, ServerNftType::Minimal) {
globs.extend([
rcstr!("**/next/dist/compiled/edge-runtime/**/*"),
rcstr!("**/next/dist/server/web/sandbox/**/*"),
rcstr!("**/next/dist/server/post-process.js"),
]);
}
globs
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ServerNftJsonAsset { impl ServerNftJsonAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn entries(&self) -> Result<Vc<Modules>> { async fn entries(&self) -> Result<Vc<Modules>> {
let is_standalone = *self.project.next_config().is_standalone().await?; let is_standalone = *self.project.next_config().is_standalone().await?;
let prune = Glob::alternatives(
next_owned_ignores(
&self.ty,
*self.project.ci_has_next_support().await?,
is_standalone,
)
.into_iter()
.map(|g| Glob::new(g, GlobOptions::default()))
.collect(),
)
.to_resolved()
.await?;
let asset_context = Vc::upcast(externals_tracing_module_context( let asset_context = Vc::upcast(externals_tracing_module_context(
get_tracing_compile_time_info(), get_tracing_compile_time_info(),
false, false,
Some((self.project.project_root_path().owned().await?, prune)),
)); ));
let project_path = self.project.project_path().owned().await?; let project_path = self.project.project_path().owned().await?;
...@@ -324,7 +409,9 @@ impl ServerNftJsonAsset { ...@@ -324,7 +409,9 @@ impl ServerNftJsonAsset {
// The modules the require hook needs are part of every endpoint's trace (see // The modules the require hook needs are part of every endpoint's trace (see
// `Project::additional_traced_modules`), but `next-server.js` / `next-minimal-server.js` // `Project::additional_traced_modules`), but `next-server.js` / `next-minimal-server.js`
// are traced on their own for `output: 'standalone'`, so they have to be added here too. // are traced on their own for `output: 'standalone'`, so they have to be added here too.
let hook_modules = require_hook_modules(project_path).owned().await?; let hook_modules = require_hook_modules(project_path, asset_context)
.owned()
.await?;
Ok(Vc::cell( Ok(Vc::cell(
hook_modules hook_modules
...@@ -369,86 +456,25 @@ impl ServerNftJsonAsset { ...@@ -369,86 +456,25 @@ impl ServerNftJsonAsset {
if route_glob.await?.matches("next-server") { if route_glob.await?.matches("next-server") {
for (glob, root) in exclude_patterns { for (glob, root) in exclude_patterns {
additional_ignores.insert(if root.path.is_empty() { additional_ignores.insert(if root.path.is_empty() {
glob.to_string() glob.clone()
} else { } else {
format!("{root}/{glob}") format!("{root}/{glob}").into()
}); });
} }
} }
} }
let server_ignores_glob = [ // The project-provided ignores can match one of the entry requests `entries()` resolves,
"**/node_modules/react{,-dom,-server-dom-turbopack}/**/*.development.js", // so they can only be applied to the finished graph:
"**/*.d.ts", // `traced_modules_for_entries` inserts entries without consulting the glob (the
"**/*.map", // `parent == None` arm in `nft.rs`), whereas pruning one would delete it and everything
"**/next/dist/pages/**/*", // reachable only through it.
"**/next/dist/compiled/next-server/**/*.dev.js", let server_ignores_glob = next_owned_ignores(&self.ty, has_next_support, is_standalone)
"**/next/dist/compiled/webpack/*", .into_iter()
"**/node_modules/webpack5/**/*", .chain(additional_ignores)
"**/next/dist/server/lib/route-resolver*", .map(|g| Glob::new(g, Default::default()))
// The testmode interceptors bundle reads its HTTP parser WASM with a .collect::<Vec<_>>();
// dynamic path, making the tracer include the bundle's whole
// directory. Test proxying is not supported in standalone output, so Ok(Glob::alternatives(server_ignores_glob))
// keep the parser asset (and the license file picked up by the
// directory glob) out of production traces.
"**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE",
"**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**",
"**/next/dist/compiled/semver/semver/**/*.js",
"**/next/dist/compiled/jest-worker/**/*",
// -- The following were added for Turbopack specifically --
// client/components/use-action-queue.ts has a process.env.NODE_ENV guard, but we can't set that due to React: https://github.com/vercel/next.js/pull/75254
"**/next/dist/next-devtools/userspace/use-app-dev-rendering-indicator.js",
// client/components/app-router.js has a process.env.NODE_ENV guard, but we
// can't set that.
"**/next/dist/client/dev/hot-reloader/app/hot-reloader-app.js",
// server/lib/router-server.js doesn't guard this require:
"**/next/dist/server/lib/router-utils/setup-dev-bundler.js",
// server/next.js doesn't guard this require
"**/next/dist/server/dev/next-dev-server.js",
// next/dist/compiled/babel* pulls in this, but we never actually transpile at
// deploy-time
"**/next/dist/compiled/browserslist/**",
]
.into_iter()
.chain(additional_ignores.iter().map(|s| s.as_str()))
// only ignore image-optimizer code when
// this is being handled outside of next-server
.chain(if has_next_support {
Either::Left(
[
"**/node_modules/sharp/**/*",
"**/@img/sharp-libvips*/**/*",
"**/next/dist/server/image-optimizer.js",
]
.into_iter(),
)
} else {
Either::Right(std::iter::empty())
})
.chain(if is_standalone {
Either::Left(std::iter::empty())
} else {
Either::Right(["**/*/next/dist/server/next.js", "**/*/next/dist/bin/next"].into_iter())
})
.map(|g| Glob::new(g.into(), Default::default()))
.collect::<Vec<_>>();
Ok(match self.ty {
ServerNftType::Full => Glob::alternatives(server_ignores_glob),
ServerNftType::Minimal => Glob::alternatives(
server_ignores_glob
.into_iter()
.chain(
[
"**/next/dist/compiled/edge-runtime/**/*",
"**/next/dist/server/web/sandbox/**/*",
"**/next/dist/server/post-process.js",
]
.into_iter()
.map(|g| Glob::new(g.into(), Default::default())),
)
.collect(),
),
})
} }
} }
...@@ -2682,7 +2682,7 @@ impl Project { ...@@ -2682,7 +2682,7 @@ impl Project {
.await?; .await?;
let asset_context = let asset_context =
externals_tracing_module_context(get_tracing_compile_time_info(), false); externals_tracing_module_context(get_tracing_compile_time_info(), false, None);
Ok(Vc::cell( Ok(Vc::cell(
cache_handler cache_handler
...@@ -2707,7 +2707,12 @@ impl Project { ...@@ -2707,7 +2707,12 @@ impl Project {
/// Other endpoints use [`Project::additional_traced_modules`]. /// Other endpoints use [`Project::additional_traced_modules`].
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn pages_traced_modules(self: Vc<Self>) -> Result<Vc<Modules>> { pub async fn pages_traced_modules(self: Vc<Self>) -> Result<Vc<Modules>> {
let hook_modules = require_hook_modules(self.project_path().owned().await?) let asset_context = Vc::upcast(externals_tracing_module_context(
get_tracing_compile_time_info(),
false,
None,
));
let hook_modules = require_hook_modules(self.project_path().owned().await?, asset_context)
.owned() .owned()
.await?; .await?;
let renderer_modules = pages_renderer_modules(self.project_path().owned().await?) let renderer_modules = pages_renderer_modules(self.project_path().owned().await?)
......
...@@ -140,5 +140,6 @@ pub async fn config_tracing_module_context( ...@@ -140,5 +140,6 @@ pub async fn config_tracing_module_context(
.cell() .cell()
.await?, .await?,
true, true,
None,
))) )))
} }
...@@ -12,13 +12,14 @@ pub mod transition; ...@@ -12,13 +12,14 @@ pub mod transition;
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use module_options::{ use module_options::{
ConfiguredModuleType, ModuleOptions, ModuleOptionsContext, ModuleRuleEffect, ModuleType, ConfiguredModuleType, ModuleOptions, ModuleOptionsContext, ModuleRule, ModuleRuleEffect,
ModuleType, RuleCondition,
}; };
pub use runtime_asset_context::get_runtime_asset_context; pub use runtime_asset_context::get_runtime_asset_context;
use tracing::{Instrument, field::Empty}; use tracing::{Instrument, field::Empty};
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::{FileSystemPath, glob::Glob};
pub use turbopack_core::condition; pub use turbopack_core::condition;
use turbopack_core::{ use turbopack_core::{
asset::Asset, asset::Asset,
...@@ -910,16 +911,30 @@ async fn process_default_internal( ...@@ -910,16 +911,30 @@ async fn process_default_internal(
Ok(module) Ok(module)
} }
/// `prune` skips matching files as the graph is walked, rather than filtering them out of the
/// result afterwards.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn externals_tracing_module_context( pub async fn externals_tracing_module_context(
compile_time_info: Vc<CompileTimeInfo>, compile_time_info: Vc<CompileTimeInfo>,
resolve_typescript: bool, resolve_typescript: bool,
prune: Option<(FileSystemPath, ResolvedVc<Glob>)>,
) -> Result<Vc<ModuleAssetContext>> { ) -> Result<Vc<ModuleAssetContext>> {
let mut extensions = vec![rcstr!(".js"), rcstr!(".node"), rcstr!(".json")]; let mut extensions = vec![rcstr!(".js"), rcstr!(".node"), rcstr!(".json")];
if resolve_typescript { if resolve_typescript {
extensions.insert(0, rcstr!(".ts")); extensions.insert(0, rcstr!(".ts"));
} }
let prune_rules = match prune {
Some((base, glob)) => vec![ModuleRule::new(
RuleCondition::ResourcePathGlob {
base,
glob: glob.await?,
},
vec![ModuleRuleEffect::Ignore],
)],
None => vec![],
};
let resolve_options = ResolveOptionsContext { let resolve_options = ResolveOptionsContext {
custom_extensions: Some(extensions), custom_extensions: Some(extensions),
emulate_environment: Some(compile_time_info.await?.environment), emulate_environment: Some(compile_time_info.await?.environment),
...@@ -957,6 +972,7 @@ pub async fn externals_tracing_module_context( ...@@ -957,6 +972,7 @@ pub async fn externals_tracing_module_context(
// node-file-trace. // node-file-trace.
environment: None, environment: None,
analyze_mode: AnalyzeMode::Tracing, analyze_mode: AnalyzeMode::Tracing,
module_rules: prune_rules,
// Disable tree shaking. Even side-effect-free imports need to be traced, as they will // Disable tree shaking. Even side-effect-free imports need to be traced, as they will
// execute at runtime. // execute at runtime.
..Default::default() ..Default::default()
...@@ -1112,6 +1128,7 @@ impl AssetContext for ModuleAssetContext { ...@@ -1112,6 +1128,7 @@ impl AssetContext for ModuleAssetContext {
Vc::upcast(externals_tracing_module_context( Vc::upcast(externals_tracing_module_context(
*options.compile_time_info, *options.compile_time_info,
false, false,
None,
)), )),
// If target is specified, a symlink will be created to // If target is specified, a symlink will be created to
// make the folder // make the folder
......
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