//! The clock, injected — because every stamp this crate writes is read back by //! a test. //! //! `AGENTS.md`: fake timers and an explicit system time, never the wall clock. //! Nothing below calls `Utc::now()` except [`SystemClock`], and nothing in //! `tests/` constructs one. use std::sync::Mutex; /// What time it is, to whoever is asking. pub trait Clock: Send + Sync { /// RFC 3339, UTC, second precision — the one spelling a stamp takes. fn now_rfc3339(&self) -> String; } /// The wall clock. The only implementation that reads it. #[derive(Debug, Clone, Copy, Default)] pub struct SystemClock; impl Clock for SystemClock { fn now_rfc3339(&self) -> String { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) } } /// A clock a test sets by hand, and advances by hand. #[derive(Debug)] pub struct FixedClock(Mutex); impl FixedClock { /// A clock stopped at `at`. pub fn at(at: &str) -> Self { Self(Mutex::new(at.to_string())) } /// Move it. There is no "advance by a duration": a test that wants a /// second instant says which one it wants. pub fn set(&self, at: &str) { *self.0.lock().expect("the fixed clock's lock") = at.to_string(); } } impl Clock for FixedClock { fn now_rfc3339(&self) -> String { self.0.lock().expect("the fixed clock's lock").clone() } }