1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use dashmap::DashMap;
use std::fmt::Debug;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time;
use crate::RResult;
use crate::ResolverError;
#[derive(Default, Debug)]
pub struct CacheFile {
duration: time::Duration,
cached_file: DashMap<PathBuf, (Arc<String>, time::SystemTime)>,
}
impl CacheFile {
pub fn new(duration: u64) -> Self {
CacheFile {
duration: time::Duration::from_millis(duration),
cached_file: Default::default(),
}
}
fn get_last_modified_time_from_file<P: AsRef<Path> + Debug>(
path: P,
) -> RResult<time::SystemTime> {
fs::metadata(path.as_ref())
.map_err(ResolverError::Io)?
.modified()
.map_err(ResolverError::Io)
}
#[tracing::instrument]
pub fn need_update<P: AsRef<Path> + Debug>(&self, path: P) -> RResult<bool> {
if !path.as_ref().is_file() {
return Ok(false);
}
self.cached_file
.get(path.as_ref())
.map(|value| value.1)
.map(|stored_last_modify_time| -> RResult<bool> {
let duration = Self::get_last_modified_time_from_file(path.as_ref())?
.duration_since(stored_last_modify_time)
.map_err(|_| {
ResolverError::UnexpectedValue(format!(
"Compare SystemTime failed in {}",
path.as_ref().display()
))
})?;
Ok(duration >= self.duration)
})
.map_or(Ok(true), |val| val)
}
#[tracing::instrument]
pub fn read_to_string<P: AsRef<Path> + Debug>(&self, path: P) -> RResult<Arc<String>> {
let str = Arc::new(fs::read_to_string(path.as_ref()).map_err(ResolverError::Io)?);
let last_modified_time = Self::get_last_modified_time_from_file(path.as_ref())?;
self.cached_file.insert(
path.as_ref().to_path_buf(),
(str.clone(), last_modified_time),
);
Ok(str)
}
}