Skip to main content

reddb_file/
clock.rs

1//! Pluggable wall-clock abstraction for lease, term-fencing, and election timing.
2//!
3//! Production code always uses `SystemClock`. Tests inject `SimClock`, whose
4//! time only moves when the test explicitly calls `advance_ms` or `set_ms`,
5//! making timing fully deterministic and seed-reproducible.
6
7use std::sync::atomic::{AtomicU64, Ordering};
8
9/// Abstraction over the wall clock used by lease and fencing logic.
10///
11/// Implementors must be `Send + Sync` so they can be shared across tasks.
12pub trait Clock: Send + Sync {
13    /// Returns the current time as milliseconds since the Unix epoch.
14    fn now_unix_millis(&self) -> u64;
15}
16
17/// Production clock: delegates to `SystemTime::now()`.
18pub struct SystemClock;
19
20impl Clock for SystemClock {
21    #[inline]
22    fn now_unix_millis(&self) -> u64 {
23        std::time::SystemTime::now()
24            .duration_since(std::time::UNIX_EPOCH)
25            .unwrap_or_default()
26            .as_millis() as u64
27    }
28}
29
30/// Deterministic simulation clock for tests.
31///
32/// Time is frozen at `seed_ms` until the test calls [`SimClock::advance_ms`]
33/// or [`SimClock::set_ms`].  All operations on the internal counter use
34/// relaxed atomics — `SimClock` is not intended for concurrent mutation, only
35/// for sequential test control.
36pub struct SimClock {
37    now_ms: AtomicU64,
38}
39
40impl SimClock {
41    /// Create a clock frozen at `seed_ms` milliseconds since the Unix epoch.
42    pub fn from_seed(seed_ms: u64) -> Self {
43        Self {
44            now_ms: AtomicU64::new(seed_ms),
45        }
46    }
47
48    /// Move the clock forward by `delta_ms` milliseconds.
49    pub fn advance_ms(&self, delta_ms: u64) {
50        self.now_ms.fetch_add(delta_ms, Ordering::Relaxed);
51    }
52
53    /// Jump the clock to an absolute time (milliseconds since Unix epoch).
54    pub fn set_ms(&self, ms: u64) {
55        self.now_ms.store(ms, Ordering::Relaxed);
56    }
57}
58
59impl Clock for SimClock {
60    #[inline]
61    fn now_unix_millis(&self) -> u64 {
62        self.now_ms.load(Ordering::Relaxed)
63    }
64}