refactor
This commit is contained in:
parent
e5a18ae047
commit
fd581bf9d9
2 changed files with 14 additions and 8 deletions
|
@ -12,7 +12,7 @@ pub struct Config {
|
|||
/// Regex for which paths should never use cache
|
||||
pub no_cache: String,
|
||||
/// Time-to-live (TTL) duration for cached data in minutes
|
||||
pub ttl: usize,
|
||||
pub ttl: Option<usize>,
|
||||
/// Regex for allowing only specific path requests
|
||||
pub only_allow: Option<String>,
|
||||
}
|
||||
|
|
12
src/proxy.rs
12
src/proxy.rs
|
@ -73,18 +73,22 @@ impl Mirror {
|
|||
///
|
||||
/// * `true` if the cached data is invalid (older than TTL), `false` otherwise.
|
||||
pub fn is_cache_invalid(&self, p: &Path) -> bool {
|
||||
if self.config.ttl.is_none() {
|
||||
return false;
|
||||
}
|
||||
|
||||
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.config.ttl * 60).try_into().unwrap());
|
||||
std::time::Duration::from_secs((self.config.ttl.unwrap() * 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.config.ttl
|
||||
self.config.ttl.unwrap()
|
||||
);
|
||||
Some(true)
|
||||
} else {
|
||||
|
@ -123,13 +127,15 @@ impl Mirror {
|
|||
|
||||
// check if cache should be used
|
||||
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) {
|
||||
if !self.is_cache_invalid(&p) {
|
||||
// use cache if present
|
||||
if let Some(resp) = self.fetch_cache(&p, req).await {
|
||||
log::info!("Returning {path} from cache");
|
||||
return Some(resp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fetch from network, if no response (offline) then use cache
|
||||
if let Some(resp) = self.fetch_network(path, &p).await {
|
||||
|
|
Loading…
Add table
Reference in a new issue