footing 0.6.3

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. Enabling the
//! `time` feature also provides deterministic UTC wall-clock support 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)).unwrap();
//! 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)
}

/// A manual clock value would exceed the supported time range.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockOverflow;

impl fmt::Display for ClockOverflow {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("clock value exceeds the supported time range")
    }
}

impl std::error::Error for ClockOverflow {}

/// 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`.
    /// Returns an error without changing the clock if the result is out of range.
    pub fn advance(&self, duration: Duration) -> Result<(), ClockOverflow> {
        let mut instant = lock_clock(&self.instant);
        *instant = instant.checked_add(duration).ok_or(ClockOverflow)?;
        Ok(())
    }

    /// 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 {
            now: Arc::new(Mutex::new(OffsetDateTime::now_utc())),
        }
    }

    /// Creates a manual UTC clock at a specific timestamp, normalizing its offset to UTC.
    /// Returns an error if the timestamp is outside the supported UTC range.
    pub fn at(now: OffsetDateTime) -> Result<Self, ClockOverflow> {
        let now = now
            .checked_to_offset(time::UtcOffset::UTC)
            .ok_or(ClockOverflow)?;
        Ok(Self {
            now: Arc::new(Mutex::new(now)),
        })
    }

    /// Advances the UTC timestamp by `duration`.
    /// Returns an error without changing the clock if the result is out of range.
    pub fn advance(&self, duration: Duration) -> Result<(), ClockOverflow> {
        let duration = time::Duration::try_from(duration).map_err(|_| ClockOverflow)?;
        let mut now = lock_clock(&self.now);
        *now = now.checked_add(duration).ok_or(ClockOverflow)?;
        Ok(())
    }

    /// Sets the timestamp, normalizing its offset to UTC.
    /// Returns an error without changing the clock if the UTC timestamp is out of range.
    pub fn set(&self, now: OffsetDateTime) -> Result<(), ClockOverflow> {
        let now = now
            .checked_to_offset(time::UtcOffset::UTC)
            .ok_or(ClockOverflow)?;
        *lock_clock(&self.now) = now;
        Ok(())
    }

    /// 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)).unwrap();

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

    #[test]
    fn manual_clock_reports_overflow_without_changing_time() {
        let clock = ManualClock::new();
        let start = clock.now();
        assert_eq!(clock.advance(Duration::MAX), Err(ClockOverflow));
        assert_eq!(clock.now(), start);
    }

    #[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).unwrap();

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

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

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_normalizes_offsets_without_changing_the_instant() {
        use time::{Date, Month, UtcOffset};

        let local = Date::from_calendar_date(2025, Month::January, 1)
            .unwrap()
            .with_hms(2, 30, 0)
            .unwrap()
            .assume_offset(UtcOffset::from_hms(8, 0, 0).unwrap());
        let clock = ManualUtcClock::at(local).unwrap();
        let utc = clock.now_utc();
        assert_eq!(utc.offset(), UtcOffset::UTC);
        assert_eq!(utc.to_calendar_date(), (2024, Month::December, 31));
        assert_eq!(utc.to_hms(), (18, 30, 0));
        assert_eq!(utc.unix_timestamp_nanos(), local.unix_timestamp_nanos());

        let local = local
            .replace_time(time::Time::from_hms(23, 45, 0).unwrap())
            .replace_offset(UtcOffset::from_hms(-5, 0, 0).unwrap());
        clock.set(local).unwrap();
        let utc = clock.now_utc();
        assert_eq!(utc.offset(), UtcOffset::UTC);
        assert_eq!(utc.to_calendar_date(), (2025, Month::January, 2));
        assert_eq!(utc.to_hms(), (4, 45, 0));
        assert_eq!(utc.unix_timestamp_nanos(), local.unix_timestamp_nanos());
    }

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_rejects_offsets_outside_the_utc_range() {
        let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
        for timestamp in [
            time::Date::MIN
                .midnight()
                .assume_offset(time::UtcOffset::from_hms(1, 0, 0).unwrap()),
            time::Date::MAX
                .with_time(time::Time::MAX)
                .assume_offset(time::UtcOffset::from_hms(-1, 0, 0).unwrap()),
        ] {
            assert!(matches!(ManualUtcClock::at(timestamp), Err(ClockOverflow)));
            assert_eq!(clock.set(timestamp), Err(ClockOverflow));
            assert_eq!(clock.now_utc(), OffsetDateTime::UNIX_EPOCH);
            assert_eq!(clock.now_utc().offset(), time::UtcOffset::UTC);
        }
    }

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_reports_conversion_and_timestamp_overflow() {
        let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
        assert_eq!(clock.advance(Duration::MAX), Err(ClockOverflow));
        assert_eq!(clock.now_utc(), OffsetDateTime::UNIX_EPOCH);

        let end = time::Date::MAX.with_time(time::Time::MAX).assume_utc();
        clock.set(end).unwrap();
        assert_eq!(clock.advance(Duration::from_nanos(1)), Err(ClockOverflow));
        assert_eq!(clock.now_utc(), end);
    }

    #[cfg(feature = "time")]
    #[test]
    fn manual_utc_clock_recovers_from_poisoned_lock() {
        let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
        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).unwrap();

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