adk_core/clock.rs
1//! Time sources for stores whose behaviour depends on the current time.
2//!
3//! Spend ledgers read the time from a [`Clock`] to pick period windows and to expire
4//! reservations. Production code uses [`SystemClock`]; tests and conformance suites
5//! use [`ManualClock`] to cross a day or month boundary without waiting for it.
6
7use std::fmt;
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11use chrono::{DateTime, Utc};
12
13/// Source of the current UTC time.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_core::{Clock, SystemClock};
19///
20/// let before = chrono::Utc::now();
21/// assert!(SystemClock.now() >= before);
22/// ```
23pub trait Clock: fmt::Debug + Send + Sync {
24 /// Returns the current time.
25 fn now(&self) -> DateTime<Utc>;
26}
27
28/// The operating system's wall clock.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
30pub struct SystemClock;
31
32impl Clock for SystemClock {
33 fn now(&self) -> DateTime<Utc> {
34 Utc::now()
35 }
36}
37
38/// A clock that reads a time the caller sets and moves only when told to.
39///
40/// Clones share the same time, so a test can hand one clone to a store and advance
41/// another.
42///
43/// # Example
44///
45/// ```rust
46/// use adk_core::{Clock, ManualClock};
47/// use chrono::{TimeZone, Utc};
48/// use std::time::Duration;
49///
50/// let clock = ManualClock::new(Utc.with_ymd_and_hms(2026, 10, 31, 23, 59, 0).unwrap());
51/// clock.advance(Duration::from_secs(120));
52/// assert_eq!(clock.now(), Utc.with_ymd_and_hms(2026, 11, 1, 0, 1, 0).unwrap());
53/// ```
54#[derive(Debug, Clone)]
55pub struct ManualClock {
56 now: Arc<Mutex<DateTime<Utc>>>,
57}
58
59impl ManualClock {
60 /// Creates a clock that reads `at`.
61 pub fn new(at: DateTime<Utc>) -> Self {
62 Self { now: Arc::new(Mutex::new(at)) }
63 }
64
65 /// Sets the time the clock reads.
66 pub fn set(&self, at: DateTime<Utc>) {
67 *self.now.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = at;
68 }
69
70 /// Moves the clock forward by `by`.
71 pub fn advance(&self, by: Duration) {
72 let by = chrono::Duration::from_std(by).unwrap_or(chrono::Duration::MAX);
73 let mut now = self.now.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
74 *now = now.checked_add_signed(by).unwrap_or(DateTime::<Utc>::MAX_UTC);
75 }
76}
77
78impl Clock for ManualClock {
79 fn now(&self) -> DateTime<Utc> {
80 *self.now.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
81 }
82}