use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; /// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`. pub fn now() -> String { match pinned() { Some(pinned) => pinned, None => fmt(Utc::now()), } } /// The instant relative arithmetic should use, which is what makes `secs_ago` /// and `secs_ahead` honest under a pinned clock (ยง6 m-1): a pinned test asking /// for a 90-second lease means 90 seconds after *the pinned instant*, not after /// the real one. fn base() -> DateTime { 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) }; } /// Pin the clock for the current thread (tests only). Returns the previous value. 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()) } /// A timestamp `secs` from [`base`], canonical format. 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)) }