Skip to main content

cbcl_core/
clock.rs

1//! Pluggable clock abstraction for time-aware agent state (REQ-305 TTL).
2//!
3//! Cbcl-core is `no_std + alloc`-compatible, so the agent can't reach for
4//! `std::time::SystemTime` directly. Instead, callers inject a [`Clock`]
5//! that yields the current second-since-epoch when the agent needs to
6//! stamp a buffered entry or run TTL eviction.
7//!
8//! Two implementations ship in-tree:
9//!
10//! - [`NoClock`] — always returns [`u64::MAX`]. Buffered entries stamped
11//!   with this value never expire under
12//!   [`PendingQueue::expire`](crate::policy::PendingQueue::expire), giving
13//!   a "no TTL" semantic by default. This is what [`Agent::new`] uses.
14//! - [`SystemClock`] (gated on the `std` feature) — wraps
15//!   `SystemTime::now()` and emits seconds since the Unix epoch.
16//!
17//! Custom clocks are useful for tests (a mock that ticks deterministically),
18//! for embedded targets that have a custom time source, or when wiring the
19//! agent into a larger system that already owns a clock.
20
21#![forbid(unsafe_code)]
22
23/// A monotonic-ish source of "seconds since epoch" used by the agent for
24/// pending-queue timestamps. Implementations must be `Debug + Send + Sync`
25/// so the agent (which derives `Debug` and may move across threads) can
26/// hold an `Arc<dyn Clock>`.
27pub trait Clock: core::fmt::Debug + Send + Sync {
28    /// Return the current time in seconds. The exact epoch is up to the
29    /// implementation as long as it is consistent across calls — the agent
30    /// only ever compares values from the same clock against each other
31    /// (e.g. `now.saturating_sub(inserted_at) >= ttl`).
32    fn now(&self) -> u64;
33}
34
35/// A clock that always reports [`u64::MAX`]. Entries stamped with this
36/// value are never reaped by TTL expiry — the agent's default behaviour.
37#[derive(Debug, Clone, Copy, Default)]
38pub struct NoClock;
39
40impl Clock for NoClock {
41    fn now(&self) -> u64 {
42        u64::MAX
43    }
44}
45
46/// A clock backed by `std::time::SystemTime::now()`, returning seconds
47/// since the Unix epoch. Available only when the `std` feature is on.
48#[cfg(feature = "std")]
49#[derive(Debug, Clone, Copy, Default)]
50pub struct SystemClock;
51
52#[cfg(feature = "std")]
53impl Clock for SystemClock {
54    /// Returns seconds since `UNIX_EPOCH`. If the system clock is set to a
55    /// time *before* `UNIX_EPOCH` (effectively impossible on a sane host
56    /// but a `Result::Err` on `duration_since`), falls back to
57    /// [`u64::MAX`] — the same value [`NoClock`] uses — so a misbehaving
58    /// clock errs toward "don't expire anything" rather than the
59    /// alternative of "expire everything immediately".
60    fn now(&self) -> u64 {
61        std::time::SystemTime::now()
62            .duration_since(std::time::UNIX_EPOCH)
63            .map(|d| d.as_secs())
64            .unwrap_or(u64::MAX)
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn no_clock_returns_u64_max() {
74        assert_eq!(NoClock.now(), u64::MAX);
75    }
76
77    #[cfg(feature = "std")]
78    #[test]
79    fn system_clock_is_recent() {
80        let now = SystemClock.now();
81        // Sanity bounds — between 2020 and year 3000.
82        assert!(now > 1_577_836_800, "clock before 2020: {now}");
83        assert!(now < 32_503_680_000, "clock after year 3000: {now}");
84    }
85}