use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; pub fn now() -> String { #[cfg(feature = "test-support")] if let Some(t) = clock::now() { return fmt(t); } match pinned() { Some(pinned) => pinned, None => fmt(Utc::now()), } } fn base() -> DateTime { #[cfg(feature = "test-support")] if let Some(t) = clock::now() { return t; } match pinned().and_then(|p| parse(&p)) { Some(t) => t, None => Utc::now(), } } fn fmt(t: DateTime) -> String { t.to_rfc3339_opts(SecondsFormat::Secs, true) } fn pinned() -> Option { CLOCK.with(|c| c.borrow().clone()) } thread_local! { static CLOCK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } /// Freeze the clock for this thread, returning the previous pin if any. /// /// Gated with `unpin`: they are one capability, and gating half would leave a /// release binary able to freeze time and unable to release it. #[cfg(feature = "test-support")] pub fn pin(ts: &str) -> Option { CLOCK.with(|c| { let mut slot = c.borrow_mut(); (*slot).replace(ts.to_string()) }) } /// Release a pin set by `pin`. #[cfg(feature = "test-support")] pub fn unpin() { CLOCK.with(|c| *c.borrow_mut() = None); } pub fn parse(ts: &str) -> Option> { DateTime::parse_from_rfc3339(ts).ok().map(|d| d.with_timezone(&Utc)).or_else(|| { chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").ok().map(|n| Utc.from_utc_datetime(&n)) }) } pub fn delta_secs(a: &str, b: &str) -> Option { Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds()) } pub fn secs_ago(secs: i64) -> String { fmt(base() - chrono::Duration::seconds(secs)) } pub fn secs_ahead(secs: i64) -> String { fmt(base() + chrono::Duration::seconds(secs)) } /// Wait for `d`, checking `stop` every `slice`. Returns false if `stop` was set /// before the wait finished, so a control loop can leave instead of doing one /// more pass. pub fn wait(d: Duration, slice: Duration, stop: &AtomicBool) -> bool { if clock::virtual_sleep() { return !stop.load(Ordering::SeqCst); } let mut left = d; while !left.is_zero() { if stop.load(Ordering::SeqCst) { return false; } let step = slice.min(left); std::thread::sleep(step); left -= step; } true } pub fn sleep(d: Duration) { if clock::virtual_sleep() { return; } std::thread::sleep(d); } /// Wrap a closure about to be spawned so the child thread inherits this one's /// clock setting; a spawned control loop on wall time would disagree with a /// test on the virtual clock. pub fn inherit(f: F) -> impl FnOnce() -> T where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { clock::wrap(f) } /// The handle tests hold to keep the clock frozen; dropping it releases the /// clock, which is why `virtualize` hands one back rather than setting a global. #[cfg(feature = "test-support")] pub use clock::VirtualClock; #[cfg(feature = "test-support")] pub fn virtualize() -> clock::VirtualClock { clock::virtualize() } #[cfg(feature = "test-support")] mod clock { use super::{DateTime, Utc}; use std::cell::Cell; use std::sync::{Mutex, MutexGuard}; thread_local! { static ON: Cell = const { Cell::new(false) }; } static AT: Mutex>> = Mutex::new(None); static OWNER: Mutex<()> = Mutex::new(()); // `pub` only because the gated `virtualize()` that returns it is `pub`. pub struct VirtualClock { // Held, never read: owning the mutex *is* the virtual clock's lease, // and dropping this guard is what releases it. _owner: MutexGuard<'static, ()>, } pub fn virtualize() -> VirtualClock { let owner = OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); *lock(&AT) = Some(Utc::now()); ON.set(true); VirtualClock { _owner: owner } } impl Drop for VirtualClock { fn drop(&mut self) { ON.set(false); *lock(&AT) = None; } } fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } pub fn now() -> Option> { if !ON.get() { return None; } *lock(&AT) } /// Returns true when this thread is on the virtual clock: the wait cost a /// yield and no wall time. The clock does not move by itself - a test moves it /// with `advance`, so a frozen lease stays frozen however fast the loop runs. pub fn virtual_sleep() -> bool { if !ON.get() { return false; } // A control loop that never blocks still needs to let its caller run. std::thread::yield_now(); true } pub(super) fn wrap(f: F) -> impl FnOnce() -> T where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { let on = ON.get(); move || { ON.set(on); f() } } } #[cfg(not(feature = "test-support"))] mod clock { #[inline(always)] pub fn virtual_sleep() -> bool { false } #[inline(always)] pub(super) fn wrap(f: F) -> F where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { f } } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "test-support")] #[test] fn a_pinned_clock_moves_relative_arithmetic_with_it() { pin("2026-01-01T00:00:00Z"); assert_eq!(now(), "2026-01-01T00:00:00Z"); assert_eq!(secs_ahead(90), "2026-01-01T00:01:30Z"); assert_eq!(secs_ago(90), "2025-12-31T23:58:30Z"); unpin(); } #[test] fn an_unpinned_clock_is_the_real_one() { let n = now(); assert_eq!(delta_secs(&n, &secs_ahead(60)), Some(60)); assert_eq!(delta_secs(&n, &secs_ago(60)), Some(-60)); } }