diff --git a/sample.conf b/sample.conf index 96d11dd..6678722 100644 --- a/sample.conf +++ b/sample.conf @@ -9,7 +9,9 @@ mirrors = [ # Local cache directory cache_dir = "./data" -#ttl = "3h" + +# Time in minutes before a file is counted as out of date +ttl = "180" # Regex for paths which will never be served from cache no_cache = '.*(?:db|db\.sig)$' \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index f11a43c..f50582e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,10 +7,16 @@ pub struct Config { pub mirrors: Vec, pub cache_dir: String, pub no_cache: String, + pub ttl: usize, } impl Config { pub fn to_proxy(&self) -> Mirror { - Mirror::new(self.mirrors.clone(), &self.cache_dir, &self.no_cache) + Mirror::new( + self.mirrors.clone(), + &self.cache_dir, + &self.no_cache, + self.ttl, + ) } } diff --git a/src/proxy.rs b/src/proxy.rs index 8fc4d16..656ed36 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -8,15 +8,17 @@ use std::{ pub struct Mirror { mirrors: Vec>, data_dir: String, + ttl: usize, no_cache: regex::Regex, } impl Mirror { - pub fn new(mirrors: Vec, data_dir: &str, no_cache: &str) -> Self { + pub fn new(mirrors: Vec, data_dir: &str, no_cache: &str, ttl: usize) -> Self { Self { mirrors: mirrors.into_iter().map(Arc::new).collect(), data_dir: data_dir.to_string(), no_cache: regex::Regex::new(no_cache).unwrap(), + ttl, } } @@ -49,6 +51,29 @@ impl Mirror { } } + pub fn is_cache_invalid(&self, p: &Path) -> bool { + let try_is_cache_invalid = || { + let modified = p.metadata().ok()?.modified().ok()?; + let current_time = std::time::SystemTime::now(); + let elapsed_time = current_time.duration_since(modified).ok()?; + let threshold_duration = + std::time::Duration::from_secs((self.ttl * 60).try_into().unwrap()); + + if elapsed_time > threshold_duration { + log::info!( + "Cached file is {} minutes old. Older than TTL {}.", + (elapsed_time.as_secs() / 60), + self.ttl + ); + Some(true) + } else { + Some(false) + } + }; + + try_is_cache_invalid().unwrap_or(false) + } + /// Asynchronously retrieves content from the specified path, either from cache or mirrors. /// /// This function attempts to retrieve content from the specified `path`. If caching is enabled @@ -69,7 +94,7 @@ impl Mirror { let p = std::path::Path::new(&self.data_dir).join(p); // check if cache should be used - if !self.no_cache.is_match(path) { + if !self.no_cache.is_match(path) || !self.is_cache_invalid(&p) { Self::create_cache_dir(p.parent().unwrap()); // use cache if present @@ -90,7 +115,6 @@ impl Mirror { pub async fn fetch_cache(&self, p: &PathBuf, req: &HttpRequest) -> Option { if p.exists() { - // todo : refresh caches if p.is_dir() { return Some( actix_files::NamedFile::open_async(p.join("index"))