Skip to main content

ash_domain/
clock.rs

1//! The [`Clock`] seam — where record timestamps come from.
2//!
3//! Timestamps (e.g. `inserted_at` / `updated_at` attributes the domain stamps
4//! automatically) are read from a `Clock`, so they can come from the OS wall
5//! clock ([`SystemClock`]) or — behind the `hlc` feature — the `ash-time`
6//! Hybrid Logical Clock (`AshTimeClock`) for causal ordering across nodes.
7//!
8//! Only [`SystemClock`] is unconditional: `ash-time` is an optional dependency,
9//! so a default build has the seam and the wall clock and links no HLC.
10
11#[cfg(feature = "hlc")]
12use ash_time::HlcClock;
13
14/// A source of the current time, in milliseconds since the Unix epoch.
15pub trait Clock: Send + Sync {
16    /// Milliseconds since the Unix epoch.
17    fn now_millis(&self) -> i64;
18}
19
20/// A [`Clock`] backed by the OS wall clock.
21#[derive(Clone, Copy, Debug, Default)]
22pub struct SystemClock;
23
24impl Clock for SystemClock {
25    fn now_millis(&self) -> i64 {
26        std::time::SystemTime::now()
27            .duration_since(std::time::UNIX_EPOCH)
28            .map(|d| d.as_millis() as i64)
29            .unwrap_or(0)
30    }
31}
32
33/// A [`Clock`] backed by the `ash-time` Hybrid Logical Clock, staying close to
34/// wall time while remaining strictly monotone.
35///
36/// Requires the `hlc` feature.
37#[cfg(feature = "hlc")]
38#[derive(Default)]
39pub struct AshTimeClock {
40    inner: HlcClock,
41}
42
43#[cfg(feature = "hlc")]
44impl AshTimeClock {
45    /// Create a clock with a fresh HLC.
46    pub fn new() -> Self {
47        Self {
48            inner: HlcClock::new(),
49        }
50    }
51}
52
53#[cfg(feature = "hlc")]
54impl Clock for AshTimeClock {
55    fn now_millis(&self) -> i64 {
56        // HlcTimestamp.physical is nanoseconds since the Unix epoch.
57        let ts = self.inner.now().unwrap_or_else(|_| self.inner.last());
58        (ts.physical / 1_000_000) as i64
59    }
60}