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) }; } pub fn pin(ts: &str) -> Option { CLOCK.with(|c| { let mut slot = c.borrow_mut(); (*slot).replace(ts.to_string()) }) } 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)) } // ---- waiting ---- /// 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::advance(d) { 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::advance(d) { return; } std::thread::sleep(d); } /// Wrap a closure about to be spawned so the child thread inherits this one's /// clock setting. Without it a control loop spawned by a test runs on wall time /// while the test itself runs on the virtual clock, and the two disagree. pub fn inherit(f: F) -> impl FnOnce() -> T where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { clock::wrap(f) } #[cfg(feature = "test-support")] pub fn virtualize() -> clock::VirtualClock { clock::virtualize() } #[cfg(feature = "test-support")] pub fn virtual_now() -> Option> { clock::now() } #[cfg(feature = "test-support")] mod clock { use super::*; 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 struct VirtualClock { _owner: MutexGuard<'static, ()>, } pub fn virtualize() -> VirtualClock { let owner = OWNER.lock().unwrap_or_else(|e| e.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(|e| e.into_inner()) } pub fn now() -> Option> { if !ON.get() { return None; } *lock(&AT) } /// Returns true when the wait was virtual: the clock moved, no wall time did. pub fn advance(d: Duration) -> bool { if !ON.get() { return false; } let mut at = lock(&AT); if let Some(t) = *at { let step = chrono::TimeDelta::from_std(d).unwrap_or_else(|_| chrono::TimeDelta::zero()); *at = Some(t + step); } // A control loop that never blocks still needs to let its caller run. std::thread::yield_now(); true } pub 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 { use super::*; #[inline(always)] pub fn advance(_d: Duration) -> bool { false } #[inline(always)] pub fn wrap(f: F) -> F where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { f } }