Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: node resolution cache #27838

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions cli/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use deno_runtime::deno_web::BlobStore;
use deno_runtime::inspector_server::InspectorServer;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use node_resolver::analyze::NodeCodeTranslator;
use node_resolver::cache::NodeResolutionThreadLocalCache;
use once_cell::sync::OnceCell;
use sys_traits::EnvCurrentDir;

Expand Down Expand Up @@ -643,6 +644,7 @@ impl CliFactory {
self.workspace_factory()?.clone(),
ResolverFactoryOptions {
conditions_from_resolution_mode: Default::default(),
node_resolution_cache: Some(Arc::new(NodeResolutionThreadLocalCache)),
no_sloppy_imports_cache: false,
npm_system_info: self.flags.subcommand.npm_system_info(),
specified_import_map: Some(Box::new(CliSpecifiedImportMapProvider {
Expand Down
34 changes: 24 additions & 10 deletions cli/lib/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use std::sync::Arc;

use deno_core::error::JsError;
use deno_node::NodeRequireLoaderRc;
use deno_path_util::url_from_file_path;
use deno_path_util::url_to_file_path;
use deno_resolver::npm::DenoInNpmPackageChecker;
use deno_resolver::npm::NpmResolver;
use deno_runtime::colors;
Expand Down Expand Up @@ -44,6 +46,7 @@ use deno_runtime::WorkerExecutionMode;
use deno_runtime::WorkerLogLevel;
use deno_runtime::UNSTABLE_GRANULAR_FLAGS;
use node_resolver::errors::ResolvePkgJsonBinExportError;
use node_resolver::UrlOrPath;
use url::Url;

use crate::args::has_trace_permissions_enabled;
Expand Down Expand Up @@ -135,6 +138,9 @@ pub fn create_isolate_create_params() -> Option<v8::CreateParams> {

#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum ResolveNpmBinaryEntrypointError {
#[class(inherit)]
#[error(transparent)]
PathToUrl(#[from] deno_path_util::PathToUrlError),
#[class(inherit)]
#[error(transparent)]
ResolvePkgJsonBinExport(ResolvePkgJsonBinExportError),
Expand All @@ -153,7 +159,7 @@ pub enum ResolveNpmBinaryEntrypointFallbackError {
PackageSubpathResolve(node_resolver::errors::PackageSubpathResolveError),
#[class(generic)]
#[error("Cannot find module '{0}'")]
ModuleNotFound(Url),
ModuleNotFound(UrlOrPath),
}

pub struct LibMainWorkerOptions {
Expand Down Expand Up @@ -525,13 +531,13 @@ impl<TSys: DenoLibSys> LibMainWorkerFactory<TSys> {
.node_resolver
.resolve_binary_export(package_folder, sub_path)
{
Ok(specifier) => Ok(specifier),
Ok(path) => Ok(url_from_file_path(&path)?),
Err(original_err) => {
// if the binary entrypoint was not found, fallback to regular node resolution
let result =
self.resolve_binary_entrypoint_fallback(package_folder, sub_path);
match result {
Ok(Some(specifier)) => Ok(specifier),
Ok(Some(path)) => Ok(url_from_file_path(&path)?),
Ok(None) => {
Err(ResolveNpmBinaryEntrypointError::ResolvePkgJsonBinExport(
original_err,
Expand All @@ -551,7 +557,7 @@ impl<TSys: DenoLibSys> LibMainWorkerFactory<TSys> {
&self,
package_folder: &Path,
sub_path: Option<&str>,
) -> Result<Option<Url>, ResolveNpmBinaryEntrypointFallbackError> {
) -> Result<Option<PathBuf>, ResolveNpmBinaryEntrypointFallbackError> {
// only fallback if the user specified a sub path
if sub_path.is_none() {
// it's confusing to users if the package doesn't have any binary
Expand All @@ -573,14 +579,22 @@ impl<TSys: DenoLibSys> LibMainWorkerFactory<TSys> {
.map_err(
ResolveNpmBinaryEntrypointFallbackError::PackageSubpathResolve,
)?;
if deno_path_util::url_to_file_path(&specifier)
.map(|p| self.shared.sys.fs_exists_no_err(p))
.unwrap_or(false)
{
Ok(Some(specifier))
let path = match specifier {
UrlOrPath::Url(ref url) => match url_to_file_path(url) {
Ok(path) => path,
Err(_) => {
return Err(ResolveNpmBinaryEntrypointFallbackError::ModuleNotFound(
specifier,
));
}
},
UrlOrPath::Path(path) => path,
};
if self.shared.sys.fs_exists_no_err(&path) {
Ok(Some(path))
} else {
Err(ResolveNpmBinaryEntrypointFallbackError::ModuleNotFound(
specifier,
UrlOrPath::Path(path),
))
}
}
Expand Down
4 changes: 1 addition & 3 deletions cli/lsp/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,9 +449,7 @@ impl<'a> TsResponseImportMapper<'a> {
.pkg_json_resolver(specifier)
// the specifier might have a closer package.json, but we
// want the root of the package's package.json
.get_closest_package_json_from_file_path(
&package_root_folder.join("package.json"),
)
.get_closest_package_json(&package_root_folder.join("package.json"))
.ok()
.flatten()?;
let root_folder = package_json.path.parent()?;
Expand Down
17 changes: 14 additions & 3 deletions cli/lsp/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ use deno_semver::npm::NpmPackageReqReference;
use deno_semver::package::PackageNv;
use deno_semver::package::PackageReq;
use indexmap::IndexMap;
use node_resolver::cache::NodeResolutionSys;
use node_resolver::cache::NodeResolutionThreadLocalCache;
use node_resolver::DenoIsBuiltInNodeModuleChecker;
use node_resolver::NodeResolutionKind;
use node_resolver::PackageJsonThreadLocalCache;
Expand Down Expand Up @@ -207,6 +209,8 @@ impl LspScopeResolver {
NodeResolutionKind::Execution,
)
})
.ok()?
.into_url()
.ok()?,
))
.0;
Expand Down Expand Up @@ -257,7 +261,7 @@ impl LspScopeResolver {
root_node_modules_dir: byonm_npm_resolver
.root_node_modules_path()
.map(|p| p.to_path_buf()),
sys: CliSys::default(),
sys: factory.node_resolution_sys.clone(),
pkg_json_resolver: self.pkg_json_resolver.clone(),
},
)
Expand Down Expand Up @@ -522,6 +526,8 @@ impl LspResolver {
resolution_mode,
NodeResolutionKind::Types,
)
.ok()?
.into_url()
.ok()?,
)))
}
Expand Down Expand Up @@ -669,6 +675,7 @@ struct ResolverFactoryServices {
struct ResolverFactory<'a> {
config_data: Option<&'a Arc<ConfigData>>,
pkg_json_resolver: Arc<CliPackageJsonResolver>,
node_resolution_sys: NodeResolutionSys<CliSys>,
sys: CliSys,
services: ResolverFactoryServices,
}
Expand All @@ -684,6 +691,10 @@ impl<'a> ResolverFactory<'a> {
Self {
config_data,
pkg_json_resolver,
node_resolution_sys: NodeResolutionSys::new(
sys.clone(),
Some(Arc::new(NodeResolutionThreadLocalCache)),
),
sys,
services: Default::default(),
}
Expand All @@ -702,7 +713,7 @@ impl<'a> ResolverFactory<'a> {
let sys = CliSys::default();
let options = if enable_byonm {
CliNpmResolverCreateOptions::Byonm(CliByonmNpmResolverCreateOptions {
sys,
sys: self.node_resolution_sys.clone(),
pkg_json_resolver: self.pkg_json_resolver.clone(),
root_node_modules_dir: self.config_data.and_then(|config_data| {
config_data.node_modules_dir.clone().or_else(|| {
Expand Down Expand Up @@ -926,7 +937,7 @@ impl<'a> ResolverFactory<'a> {
DenoIsBuiltInNodeModuleChecker,
npm_resolver.clone(),
self.pkg_json_resolver.clone(),
self.sys.clone(),
self.node_resolution_sys.clone(),
node_resolver::ConditionsFromResolutionMode::default(),
)))
})
Expand Down
3 changes: 3 additions & 0 deletions cli/lsp/tsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ use indexmap::IndexMap;
use indexmap::IndexSet;
use lazy_regex::lazy_regex;
use log::error;
use node_resolver::cache::NodeResolutionThreadLocalCache;
use node_resolver::ResolutionMode;
use once_cell::sync::Lazy;
use regex::Captures;
Expand Down Expand Up @@ -4622,6 +4623,7 @@ fn op_resolve_inner(
let state = state.borrow_mut::<State>();
let mark = state.performance.mark_with_args("tsc.op.op_resolve", &args);
let referrer = state.specifier_map.normalize(&args.base)?;
NodeResolutionThreadLocalCache::clear();
let specifiers = state
.state_snapshot
.documents
Expand All @@ -4640,6 +4642,7 @@ fn op_resolve_inner(
})
})
.collect();
NodeResolutionThreadLocalCache::clear();
Copy link
Member Author

@dsherret dsherret Jan 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should improve this to be smarter. Right now I just have it clearing before and after each op_resolve.

state.performance.measure(mark);
Ok(specifiers)
}
Expand Down
9 changes: 8 additions & 1 deletion cli/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,12 @@ impl<TGraphContainer: ModuleGraphContainer>
ResolutionMode::Import,
NodeResolutionKind::Execution,
)
.map_err(|e| JsErrorBox::from_err(e).into());
.map_err(|e| JsErrorBox::from_err(e).into())
.and_then(|url_or_path| {
url_or_path
.into_url()
.map_err(|e| JsErrorBox::from_err(e).into())
});
}
}

Expand Down Expand Up @@ -696,6 +701,8 @@ impl<TGraphContainer: ModuleGraphContainer>
source,
})
})?
.into_url()
.map_err(JsErrorBox::from_err)?
}
Some(Module::Node(module)) => module.specifier.clone(),
Some(Module::Js(module)) => module.specifier.clone(),
Expand Down
Loading
Loading