use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stale {
pub age: Duration,
pub ttl: Duration,
}
impl std::fmt::Display for Stale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "stale: age {:?} exceeds ttl {:?}", self.age, self.ttl)
}
}
impl std::error::Error for Stale {}
#[derive(Debug)]
pub struct StaleValue<T> {
pub value: T,
pub stale: Stale,
}
impl<T> std::fmt::Display for StaleValue<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.stale.fmt(f)
}
}
impl<T: std::fmt::Debug> std::error::Error for StaleValue<T> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidFetchTime {
pub ahead_by: Duration,
}
impl std::fmt::Display for InvalidFetchTime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"fetch time is {:?} ahead of the current monotonic clock",
self.ahead_by
)
}
}
impl std::error::Error for InvalidFetchTime {}
#[must_use = "the fetched value should be read or passed to another operation"]
#[derive(Debug)]
pub struct Fresh<T> {
val: T,
fetched: Instant,
ttl: Duration,
}
impl<T> Fresh<T> {
pub fn fetch(val: T, ttl: Duration) -> Self {
Fresh {
val,
fetched: Instant::now(),
ttl,
}
}
pub fn fetched_at(val: T, fetched: Instant, ttl: Duration) -> Result<Self, InvalidFetchTime> {
let now = Instant::now();
if fetched <= now {
Ok(Fresh { val, fetched, ttl })
} else {
Err(InvalidFetchTime {
ahead_by: fetched.duration_since(now),
})
}
}
pub fn get(&self) -> Result<&T, Stale> {
let age = self.age();
if age <= self.ttl {
Ok(&self.val)
} else {
Err(Stale { age, ttl: self.ttl })
}
}
pub fn into_inner(self) -> Result<T, StaleValue<T>> {
let age = self.age();
if age <= self.ttl {
Ok(self.val)
} else {
Err(StaleValue {
value: self.val,
stale: Stale { age, ttl: self.ttl },
})
}
}
pub fn remaining(&self) -> Duration {
self.ttl.saturating_sub(self.age())
}
fn age(&self) -> Duration {
Instant::now().saturating_duration_since(self.fetched)
}
}
pub mod scoped {
use core::marker::PhantomData;
type Invariant<'id> = PhantomData<fn(&'id ()) -> &'id ()>;
#[must_use = "the scoped value should be read during the closure"]
pub struct Live<'id, T> {
val: T,
_brand: Invariant<'id>,
}
impl<T> Live<'_, T> {
pub fn get(&self) -> &T {
&self.val
}
}
pub fn with_live<T, R>(val: T, f: impl for<'id> FnOnce(Live<'id, T>) -> R) -> R {
f(Live {
val,
_brand: PhantomData,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expired_value_reports_age_and_ttl() {
let ttl = Duration::from_secs(1);
let fetched = Instant::now() - Duration::from_secs(2);
let value = Fresh::fetched_at(7, fetched, ttl).unwrap();
let stale = value.get().unwrap_err();
assert!(stale.age >= Duration::from_secs(2));
assert_eq!(stale.ttl, ttl);
assert_eq!(value.remaining(), Duration::ZERO);
}
#[test]
fn fresh_non_clone_value_can_be_recovered() {
let value = Fresh::fetch(String::from("quote"), Duration::from_secs(1));
assert_eq!(value.into_inner().unwrap(), "quote");
}
#[test]
fn stale_non_clone_value_is_returned_with_the_error() {
let fetched = Instant::now() - Duration::from_secs(2);
let value =
Fresh::fetched_at(String::from("quote"), fetched, Duration::from_secs(1)).unwrap();
let error = value.into_inner().unwrap_err();
assert_eq!(error.value, "quote");
assert!(error.stale.age >= Duration::from_secs(2));
}
#[test]
fn future_fetch_time_is_rejected() {
let future = Instant::now() + Duration::from_secs(1);
let error = Fresh::fetched_at(7, future, Duration::from_secs(1)).unwrap_err();
assert!(error.ahead_by > Duration::ZERO);
}
}