Skip to main content

synd_support/time/
clock.rs

1use chrono::{DateTime, Utc};
2
3/// Source of wall-clock time for components that must observe real time.
4pub trait Clock: Send + Sync + 'static {
5    fn now(&self) -> DateTime<Utc>;
6}
7
8/// Clock backed by the system wall clock.
9#[derive(Debug, Clone, Copy, Default)]
10pub struct SystemClock;
11
12impl Clock for SystemClock {
13    fn now(&self) -> DateTime<Utc> {
14        Utc::now()
15    }
16}
17
18#[cfg(any(test, feature = "mock"))]
19mod fake {
20    use std::sync::{Arc, Mutex};
21
22    use chrono::{DateTime, Utc};
23
24    use super::Clock;
25
26    /// Test clock whose current time is controlled by the caller.
27    #[derive(Debug, Clone)]
28    pub struct FakeClock {
29        now: Arc<Mutex<DateTime<Utc>>>,
30    }
31
32    impl FakeClock {
33        pub fn new(now: DateTime<Utc>) -> Self {
34            Self {
35                now: Arc::new(Mutex::new(now)),
36            }
37        }
38
39        pub fn set(&self, now: DateTime<Utc>) {
40            *self.now.lock().expect("fake clock mutex poisoned") = now;
41        }
42    }
43
44    impl Clock for FakeClock {
45        fn now(&self) -> DateTime<Utc> {
46            *self.now.lock().expect("fake clock mutex poisoned")
47        }
48    }
49}
50
51#[cfg(any(test, feature = "mock"))]
52pub use fake::FakeClock;