This commit is contained in:
JMARyA 2024-05-10 07:51:30 +02:00
parent e5a18ae047
commit fd581bf9d9
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
2 changed files with 14 additions and 8 deletions

View file

@ -12,7 +12,7 @@ pub struct Config {
/// Regex for which paths should never use cache /// Regex for which paths should never use cache
pub no_cache: String, pub no_cache: String,
/// Time-to-live (TTL) duration for cached data in minutes /// Time-to-live (TTL) duration for cached data in minutes
pub ttl: usize, pub ttl: Option<usize>,
/// Regex for allowing only specific path requests /// Regex for allowing only specific path requests
pub only_allow: Option<String>, pub only_allow: Option<String>,
} }

View file

@ -73,18 +73,22 @@ impl Mirror {
/// ///
/// * `true` if the cached data is invalid (older than TTL), `false` otherwise. /// * `true` if the cached data is invalid (older than TTL), `false` otherwise.
pub fn is_cache_invalid(&self, p: &Path) -> bool { pub fn is_cache_invalid(&self, p: &Path) -> bool {
if self.config.ttl.is_none() {
return false;
}
let try_is_cache_invalid = || { let try_is_cache_invalid = || {
let modified = p.metadata().ok()?.modified().ok()?; let modified = p.metadata().ok()?.modified().ok()?;
let current_time = std::time::SystemTime::now(); let current_time = std::time::SystemTime::now();
let elapsed_time = current_time.duration_since(modified).ok()?; let elapsed_time = current_time.duration_since(modified).ok()?;
let threshold_duration = let threshold_duration =
std::time::Duration::from_secs((self.config.ttl * 60).try_into().unwrap()); std::time::Duration::from_secs((self.config.ttl.unwrap() * 60).try_into().unwrap());
if elapsed_time > threshold_duration { if elapsed_time > threshold_duration {
log::info!( log::info!(
"Cached file is {} minutes old. Older than TTL {}.", "Cached file is {} minutes old. Older than TTL {}.",
(elapsed_time.as_secs() / 60), (elapsed_time.as_secs() / 60),
self.config.ttl self.config.ttl.unwrap()
); );
Some(true) Some(true)
} else { } else {
@ -123,11 +127,13 @@ impl Mirror {
// check if cache should be used // check if cache should be used
Self::create_cache_dir(p.parent().unwrap()); Self::create_cache_dir(p.parent().unwrap());
if !self.no_cache.is_match(path) || !self.is_cache_invalid(&p) { if !self.no_cache.is_match(path) {
// use cache if present if !self.is_cache_invalid(&p) {
if let Some(resp) = self.fetch_cache(&p, req).await { // use cache if present
log::info!("Returning {path} from cache"); if let Some(resp) = self.fetch_cache(&p, req).await {
return Some(resp); log::info!("Returning {path} from cache");
return Some(resp);
}
} }
} }