Skip to content

Commit 134f7ce

Browse files
andholpil
authored andcommitted
feat(dependencies): cache package info from hexpm to reduce duplicate calls ✨
1 parent efefcb4 commit 134f7ce

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

compiler-cli/src/dependencies.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::{
2+
cell::RefCell,
23
collections::{HashMap, HashSet},
34
process::Command,
45
time::Instant,
@@ -1249,17 +1250,27 @@ async fn lookup_package(
12491250
}
12501251

12511252
struct PackageFetcher {
1253+
runtime_cache: RefCell<HashMap<String, hexpm::Package>>,
12521254
runtime: tokio::runtime::Handle,
12531255
http: HttpClient,
12541256
}
12551257

12561258
impl PackageFetcher {
12571259
pub fn boxed(runtime: tokio::runtime::Handle) -> Box<Self> {
12581260
Box::new(Self {
1261+
runtime_cache: RefCell::new(HashMap::new()),
12591262
runtime,
12601263
http: HttpClient::new(),
12611264
})
12621265
}
1266+
1267+
/// Caches the result so subsequent calls to `get_dependencies` so that we don't need to make a
1268+
/// network request. Currently dependencies are fetched during initial version resolution, and
1269+
/// then during check for major version availability.
1270+
fn cache_package(&self, package: &str, result: hexpm::Package) {
1271+
let mut runtime_cache = self.runtime_cache.borrow_mut();
1272+
let _ = runtime_cache.insert(package.to_string(), result);
1273+
}
12631274
}
12641275

12651276
#[derive(Debug)]
@@ -1293,6 +1304,15 @@ impl dependency::PackageFetcher for PackageFetcher {
12931304
&self,
12941305
package: &str,
12951306
) -> Result<hexpm::Package, Box<dyn std::error::Error>> {
1307+
{
1308+
let runtime_cache = self.runtime_cache.borrow();
1309+
let result = runtime_cache.get(package);
1310+
1311+
if let Some(result) = result {
1312+
return Ok(result.clone());
1313+
}
1314+
}
1315+
12961316
tracing::debug!(package = package, "looking_up_hex_package");
12971317
let config = hexpm::Config::new();
12981318
let request = hexpm::get_package_request(package, None, &config);
@@ -1302,7 +1322,10 @@ impl dependency::PackageFetcher for PackageFetcher {
13021322
.map_err(Box::new)?;
13031323

13041324
match hexpm::get_package_response(response, HEXPM_PUBLIC_KEY) {
1305-
Ok(a) => Ok(a),
1325+
Ok(a) => {
1326+
self.cache_package(package, a.clone());
1327+
Ok(a)
1328+
}
13061329
Err(e) => match e {
13071330
hexpm::ApiError::NotFound => {
13081331
Err(format!("I couldn't find a package called `{}`", package).into())

0 commit comments

Comments
 (0)