pub fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
pub fn is_within_ttl(modified_unix: u64, ttl_secs: i64) -> bool {
match ttl_secs {
..=-1 => true,
0 => false,
ttl => now_unix().saturating_sub(modified_unix) < ttl as u64,
}
}
pub fn mutable_ref_fresh(has_upstream: bool, metadata_ttl: i64, modified: Option<u64>) -> bool {
if !has_upstream {
return true;
}
metadata_ttl > 0
&& modified
.map(|m| is_within_ttl(m, metadata_ttl))
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
#[test]
fn ttl_minus_one_always_fresh() {
assert!(is_within_ttl(0, -1));
assert!(is_within_ttl(1_000_000, -1));
}
#[test]
fn ttl_zero_always_stale() {
assert!(!is_within_ttl(now_secs(), 0));
assert!(!is_within_ttl(now_secs() + 100, 0));
}
#[test]
fn ttl_positive_fresh() {
assert!(is_within_ttl(now_secs() - 10, 300));
}
#[test]
fn ttl_positive_stale() {
assert!(!is_within_ttl(now_secs() - 600, 300));
}
#[test]
fn ttl_positive_boundary() {
let now = now_secs();
assert!(!is_within_ttl(now - 300, 300));
assert!(is_within_ttl(now - 299, 300));
}
#[test]
fn mutable_ref_fresh_hosted_and_proxied() {
let now = now_secs();
assert!(mutable_ref_fresh(false, -1, Some(now)));
assert!(mutable_ref_fresh(false, 0, None));
assert!(!mutable_ref_fresh(true, -1, Some(now)));
assert!(!mutable_ref_fresh(true, 0, Some(now)));
assert!(mutable_ref_fresh(true, 300, Some(now - 10)));
assert!(!mutable_ref_fresh(true, 300, Some(now - 600)));
assert!(!mutable_ref_fresh(true, 300, None));
}
}