footing 0.1.5

Feature-gated foundations for Rust backend services
Documentation
//! Clock abstraction for runtime code and deterministic tests.
//!
//! Production code normally uses [`SystemClock`]. Tests can use
//! [`ManualClock`] to advance monotonic time without sleeping. With the `time`
//! feature enabled, [`SystemUtcClock`] and [`ManualUtcClock`] provide
//! deterministic UTC wall-clock timestamps for business decisions.
//!
//! ```rust
//! use std::time::Duration;
//! use footing::clock::{Clock, ManualClock};
//!
//! let clock = ManualClock::new();
//! let start = clock.now();
//! clock.advance(Duration::from_secs(5));
//! assert_eq!(clock.now().duration_since(start), Duration::from_secs(5));
//! ```
//!
use std::{
    fmt,
    sync::{Arc, Mutex, MutexGuard},
    time::{Duration, Instant},
};

#[cfg(feature = "time")]
use time::OffsetDateTime;

/// Read-only clock used by runtime components.
pub trait Clock: Send + Sync + 'static {
    /// Returns the current monotonic instant.
    fn now(&self) -> Instant;
}

/// Shared clock handle.
pub type SharedClock = Arc<dyn Clock>;

/// Read-only UTC wall clock used by business components.
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub trait UtcClock: Send + Sync + 'static {
    /// Returns the current UTC wall-clock timestamp.
    fn now_utc(&self) -> OffsetDateTime;
}

/// Shared UTC wall-clock handle.
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub type SharedUtcClock = Arc<dyn UtcClock>;

/// Returns a shared system clock.
#[must_use]
pub fn system_clock() -> SharedClock {
    Arc::new(SystemClock)
}

/// Returns a shared system UTC wall clock.
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[must_use]
pub fn system_utc_clock() -> SharedUtcClock {
    Arc::new(SystemUtcClock)
}

fn lock_clock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Monotonic clock backed by [`Instant::now`].
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;

impl Clock for SystemClock {
    fn now(&self) -> Instant {
        Instant::now()
    }
}

/// UTC wall clock backed by [`OffsetDateTime::now_utc`].
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemUtcClock;

#[cfg(feature = "time")]
impl UtcClock for SystemUtcClock {
    fn now_utc(&self) -> OffsetDateTime {
        OffsetDateTime::now_utc()
    }
}

/// Deterministic clock for tests and simulations.
#[derive(Clone)]
pub struct ManualClock {
    instant: Arc<Mutex<Instant>>,
}

impl ManualClock {
    /// Creates a manual clock starting at [`Instant::now`].
    #[must_use]
    pub fn new() -> Self {
        Self::at(Instant::now())
    }

    /// Creates a manual clock at a specific instant.
    #[must_use]
    pub fn at(instant: Instant) -> Self {
        Self {
            instant: Arc::new(Mutex::new(instant)),
        }
    }

    /// Advances the clock by `duration`.
    pub fn advance(&self, duration: Duration) {
        let mut instant = lock_clock(&self.instant);
        *instant = instant.checked_add(duration).unwrap_or(*instant);
    }

    /// Sets the current instant.
    pub fn set(&self, instant: Instant) {
        *lock_clock(&self.instant) = instant;
    }

    /// Returns this clock as a shared trait object.
    #[must_use]
    pub fn shared(&self) -> SharedClock {
        Arc::new(self.clone())
    }
}

impl Default for ManualClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for ManualClock {
    fn now(&self) -> Instant {
        *lock_clock(&self.instant)
    }
}

impl fmt::Debug for ManualClock {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ManualClock")
            .field("instant", &self.now())
            .finish()
    }
}

/// Deterministic UTC wall clock for tests and simulations.
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[derive(Clone)]
pub struct ManualUtcClock {
    now: Arc<Mutex<OffsetDateTime>>,
}

#[cfg(feature = "time")]
impl ManualUtcClock {
    /// Creates a manual UTC clock starting at the current system timestamp.
    #[must_use]
    pub fn new() -> Self {
        Self::at(OffsetDateTime::now_utc())
    }

    /// Creates a manual UTC clock at a specific timestamp.
    #[must_use]
    pub fn at(now: OffsetDateTime) -> Self {
        Self {
            now: Arc::new(Mutex::new(now)),
        }
    }

    /// Advances the UTC timestamp by `duration`.
    pub fn advance(&self, duration: Duration) {
        let Ok(duration) = time::Duration::try_from(duration) else {
            return;
        };
        let mut now = lock_clock(&self.now);
        *now = now.checked_add(duration).unwrap_or(*now);
    }

    /// Sets the UTC timestamp.
    pub fn set(&self, now: OffsetDateTime) {
        *lock_clock(&self.now) = now;
    }

    /// Returns this clock as a shared trait object.
    #[must_use]
    pub fn shared(&self) -> SharedUtcClock {
        Arc::new(self.clone())
    }
}

#[cfg(feature = "time")]
impl Default for ManualUtcClock {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "time")]
impl UtcClock for ManualUtcClock {
    fn now_utc(&self) -> OffsetDateTime {
        *lock_clock(&self.now)
    }
}

#[cfg(feature = "time")]
impl fmt::Debug for ManualUtcClock {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ManualUtcClock")
            .field("now", &self.now_utc())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn manual_clock_advances_monotonic_time() {
        let clock = ManualClock::new();
        let start = clock.now();

        clock.advance(Duration::from_secs(5));

        assert_eq!(clock.now().duration_since(start), Duration::from_secs(5));
    }

    #[test]
    fn manual_clock_recovers_from_poisoned_lock() {
        let clock = ManualClock::new();
        let poisoned = clock.clone();
        let _ = std::thread::spawn(move || {
            let _guard = poisoned.instant.lock().expect("test lock should acquire");
            panic!("poison manual clock lock");
        })
        .join();

        let expected = Instant::now();
        clock.set(expected);

        assert_eq!(clock.now(), expected);
    }

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_advances_wall_time() {
        let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH);

        clock.advance(Duration::from_secs(90));

        assert_eq!(
            clock.now_utc(),
            OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(90)
        );
    }

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_recovers_from_poisoned_lock() {
        let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH);
        let poisoned = clock.clone();
        let _ = std::thread::spawn(move || {
            let _guard = poisoned.now.lock().expect("test lock should acquire");
            panic!("poison manual UTC clock lock");
        })
        .join();

        let expected = OffsetDateTime::UNIX_EPOCH + time::Duration::days(1);
        clock.set(expected);

        assert_eq!(clock.now_utc(), expected);
    }
}