From 9529138c36e3ffe63699527760af8e9f93f8d9f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Mon, 6 Feb 2023 16:20:20 +0100 Subject: [PATCH] refactor(npm): use per-thread package.json cache (#17644) This commit adds a per-thread cache for `package.json` files. It's similar to what Node.js is doing. --- ext/node/package_json.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/ext/node/package_json.rs b/ext/node/package_json.rs index 5894b88313..e40448930b 100644 --- a/ext/node/package_json.rs +++ b/ext/node/package_json.rs @@ -11,9 +11,15 @@ use deno_core::serde_json; use deno_core::serde_json::Map; use deno_core::serde_json::Value; use serde::Serialize; +use std::cell::RefCell; +use std::collections::HashMap; use std::io::ErrorKind; use std::path::PathBuf; +thread_local! { + static CACHE: RefCell> = RefCell::new(HashMap::new()); +} + #[derive(Clone, Debug, Serialize)] pub struct PackageJson { pub exists: bool, @@ -58,6 +64,12 @@ impl PackageJson { pub fn load_skip_read_permission( path: PathBuf, ) -> Result { + assert!(path.is_absolute()); + + if CACHE.with(|cache| cache.borrow().contains_key(&path)) { + return Ok(CACHE.with(|cache| cache.borrow()[&path].clone())); + } + let source = match std::fs::read_to_string(&path) { Ok(source) => source, Err(err) if err.kind() == ErrorKind::NotFound => { @@ -136,6 +148,12 @@ impl PackageJson { imports, bin, }; + + CACHE.with(|cache| { + cache + .borrow_mut() + .insert(package_json.path.clone(), package_json.clone()); + }); Ok(package_json) }