use std::{
fmt,
sync::{Arc, Mutex, MutexGuard},
time::{Duration, Instant},
};
#[cfg(feature = "time")]
use time::OffsetDateTime;
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
}
pub type SharedClock = Arc<dyn Clock>;
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub trait UtcClock: Send + Sync + 'static {
fn now_utc(&self) -> OffsetDateTime;
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub type SharedUtcClock = Arc<dyn UtcClock>;
#[must_use]
pub fn system_clock() -> SharedClock {
Arc::new(SystemClock)
}
#[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)
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
}
#[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()
}
}
#[derive(Clone)]
pub struct ManualClock {
instant: Arc<Mutex<Instant>>,
}
impl ManualClock {
#[must_use]
pub fn new() -> Self {
Self::at(Instant::now())
}
#[must_use]
pub fn at(instant: Instant) -> Self {
Self {
instant: Arc::new(Mutex::new(instant)),
}
}
pub fn advance(&self, duration: Duration) {
let mut instant = lock_clock(&self.instant);
*instant = instant.checked_add(duration).unwrap_or(*instant);
}
pub fn set(&self, instant: Instant) {
*lock_clock(&self.instant) = instant;
}
#[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()
}
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[derive(Clone)]
pub struct ManualUtcClock {
now: Arc<Mutex<OffsetDateTime>>,
}
#[cfg(feature = "time")]
impl ManualUtcClock {
#[must_use]
pub fn new() -> Self {
Self::at(OffsetDateTime::now_utc())
}
#[must_use]
pub fn at(now: OffsetDateTime) -> Self {
Self {
now: Arc::new(Mutex::new(now)),
}
}
pub fn advance(&self, duration: Duration) {
let Ok(duration) = time::Duration::try_from(duration) else {
return;
};
let mut now = lock_clock(&self.now);
*now = now.checked_add(duration).unwrap_or(*now);
}
pub fn set(&self, now: OffsetDateTime) {
*lock_clock(&self.now) = now;
}
#[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));
assert_eq!(clock.now().duration_since(start), Duration::from_secs(5));
}
#[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);
clock.advance(Duration::from_secs(90));
assert_eq!(
clock.now_utc(),
OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(90)
);
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_recovers_from_poisoned_lock() {
let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH);
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);
assert_eq!(clock.now_utc(), expected);
}
}