Skip to content

Commit 48d5814

Browse files
committed
graph: Factor caching of files from IPFS into separate struct
1 parent a52bba6 commit 48d5814

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

graph/src/components/link_resolver/ipfs.rs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,39 @@ use crate::ipfs::IpfsClient;
2424
use crate::ipfs::RetryPolicy;
2525
use crate::prelude::{LinkResolver as LinkResolverTrait, *};
2626

27+
#[derive(Clone, CheapClone)]
28+
struct Cache {
29+
cache: Arc<Mutex<LruCache<ContentPath, Vec<u8>>>>,
30+
}
31+
32+
impl Cache {
33+
fn new(capacity: usize) -> Self {
34+
Self {
35+
cache: Arc::new(Mutex::new(LruCache::with_capacity(capacity))),
36+
}
37+
}
38+
39+
fn find(&self, path: &ContentPath) -> Option<Vec<u8>> {
40+
self.cache.lock().unwrap().get(path).cloned()
41+
}
42+
43+
fn insert(&self, path: ContentPath, data: Vec<u8>) {
44+
let mut cache = self.cache.lock().unwrap();
45+
46+
if !cache.contains_key(&path) {
47+
cache.insert(path.clone(), data.clone());
48+
}
49+
}
50+
}
51+
2752
#[derive(Clone, CheapClone, Derivative)]
2853
#[derivative(Debug)]
2954
pub struct IpfsResolver {
3055
#[derivative(Debug = "ignore")]
3156
client: Arc<dyn IpfsClient>,
3257

3358
#[derivative(Debug = "ignore")]
34-
cache: Arc<Mutex<LruCache<ContentPath, Vec<u8>>>>,
59+
cache: Cache,
3560

3661
timeout: Duration,
3762
max_file_size: usize,
@@ -48,9 +73,7 @@ impl IpfsResolver {
4873

4974
Self {
5075
client,
51-
cache: Arc::new(Mutex::new(LruCache::with_capacity(
52-
env.max_ipfs_cache_size as usize,
53-
))),
76+
cache: Cache::new(env.max_ipfs_cache_size as usize),
5477
timeout: env.ipfs_timeout,
5578
max_file_size: env.max_ipfs_file_bytes,
5679
max_map_file_size: env.max_ipfs_map_file_size,
@@ -80,7 +103,7 @@ impl LinkResolverTrait for IpfsResolver {
80103
let max_file_size = self.max_file_size;
81104
let max_cache_file_size = self.max_cache_file_size;
82105

83-
if let Some(data) = self.cache.lock().unwrap().get(&path) {
106+
if let Some(data) = self.cache.find(&path) {
84107
trace!(logger, "IPFS cat cache hit"; "hash" => path.to_string());
85108
return Ok(data.to_owned());
86109
}
@@ -101,11 +124,7 @@ impl LinkResolverTrait for IpfsResolver {
101124
.to_vec();
102125

103126
if data.len() <= max_cache_file_size {
104-
let mut cache = self.cache.lock().unwrap();
105-
106-
if !cache.contains_key(&path) {
107-
cache.insert(path.clone(), data.clone());
108-
}
127+
self.cache.insert(path.clone(), data.clone());
109128
} else {
110129
debug!(
111130
logger,

0 commit comments

Comments
 (0)