Skip to main content

appcore_log/
clock.rs

1// =============================================================================
2//        #######
3//     ###       ###     F: clock.rs
4//    ##   ## ##   ##    P: AppCore-Runtime
5//         ## ##
6//                       C: working-tree by dnettoRaw
7//    ##   ## ##   ##    U: working-tree by dnettoRaw
8//      ###########      S: 1.0.2-rc
9// =============================================================================
10
11//! Explicit clocks keep event timestamps deterministic at test boundaries.
12
13/// Supplies Unix timestamps in milliseconds at an application boundary.
14pub trait LogClock: Send + Sync {
15    /// Returns the current Unix timestamp in milliseconds.
16    fn now_ms(&self) -> u64;
17}
18
19/// Production wall-clock implementation with a controlled pre-epoch fallback.
20#[derive(Debug, Default, Clone, Copy)]
21pub struct SystemLogClock;
22
23impl LogClock for SystemLogClock {
24    fn now_ms(&self) -> u64 {
25        std::time::SystemTime::now()
26            .duration_since(std::time::UNIX_EPOCH)
27            .map(|duration| duration.as_millis().try_into().unwrap_or(u64::MAX))
28            .unwrap_or_default()
29    }
30}
31
32/// Deterministic clock for tests and reproducible examples.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct FixedLogClock(u64);
35
36impl FixedLogClock {
37    /// Creates a clock returning exactly `timestamp_ms`.
38    pub const fn new(timestamp_ms: u64) -> Self {
39        Self(timestamp_ms)
40    }
41}
42
43impl LogClock for FixedLogClock {
44    fn now_ms(&self) -> u64 {
45        self.0
46    }
47}