requisite 0.1.0

Data-handling requirements encoded in Rust types.
Documentation
//! TTL-checked and operation-scoped values.
//!
//! [`Fresh<T>`] records when a value was fetched and checks its TTL on each
//! read. [`scoped`] binds a value to one closure and passes explicitly derived
//! results to later work.

use std::time::{Duration, Instant};

/// Returned when you read a [`Fresh`] value after its TTL has passed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stale {
    /// How old the value was when you tried to read it.
    pub age: Duration,
    /// The TTL it was given.
    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 {}

/// A consumed [`Fresh`] value whose TTL has elapsed.
#[derive(Debug)]
pub struct StaleValue<T> {
    /// The expired value.
    pub value: T,
    /// Timing information from the freshness check.
    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> {}

/// Returned when [`Fresh::fetched_at`] receives a future timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidFetchTime {
    /// How far the timestamp was ahead of the current monotonic clock.
    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 {}

/// A value with its fetch time and TTL.
///
/// [`Fresh::get`] evaluates elapsed monotonic time and returns [`Stale`] after
/// the TTL.
#[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> {
    /// Record a fetched value and its TTL.
    pub fn fetch(val: T, ttl: Duration) -> Self {
        Fresh {
            val,
            fetched: Instant::now(),
            ttl,
        }
    }

    /// Record a value with its fetch time and TTL.
    ///
    /// This supports data sources that already track fetch time and makes stale
    /// handling deterministic in tests. Future timestamps return
    /// [`InvalidFetchTime`].
    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),
            })
        }
    }

    /// Read the value while its age remains within the TTL.
    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 })
        }
    }

    /// Consume the wrapper and return the value while it remains fresh.
    ///
    /// A stale result returns both the value and its timing information in
    /// [`StaleValue`].
    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 },
            })
        }
    }

    /// Return the remaining TTL, saturating at zero.
    pub fn remaining(&self) -> Duration {
        self.ttl.saturating_sub(self.age())
    }

    fn age(&self) -> Duration {
        Instant::now().saturating_duration_since(self.fetched)
    }
}

/// Values bound to the operation that receives them.
///
/// [`with_live`](scoped::with_live) passes a branded
/// [`Live<'id, T>`](scoped::Live) to a closure. The brand ties the value to that
/// invocation while allowing the closure to return derived owned data.
pub mod scoped {
    use core::marker::PhantomData;

    /// Makes each [`with_live`] scope invariant over its brand.
    type Invariant<'id> = PhantomData<fn(&'id ()) -> &'id ()>;

    /// A value tied to one [`with_live`] invocation.
    #[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> {
        /// Borrow the value inside its scope.
        pub fn get(&self) -> &T {
            &self.val
        }
    }

    /// Run `f` with a value branded for this invocation.
    ///
    /// The `for<'id>` bound creates the scope and keeps values carrying its
    /// brand within the closure. The return type `R` is independent of `'id`,
    /// so returning or storing a [`Live`] value produces a lifetime error.
    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);
    }
}