Skip to main content

printobserver_core/
clock.rs

1//! The one time source this crate reads.
2//!
3//! Core never calls the system clock. Every instant it stamps, and every
4//! comparison it makes against one, is read through a [`Clock`], so that a
5//! test drives time by advancing this one dependency alone.
6//!
7//! A clock has two readings, and they answer different questions. [`Clock::now`]
8//! is the wall clock: every instant this crate **records** — an action's
9//! request, an event's arrival, an intervention's persisted deadline — is
10//! stamped from it, so that the history reads in the absolute time it was
11//! written. [`Clock::elapsed`] is a clock nothing steps, and every **duration
12//! measured while the supervisor lives** is measured on it: a bounded
13//! intervention's expiry, the agent's minimum interval between changes to the
14//! machine, and the detector's resume grace. A host's wall clock is moved by
15//! time synchronisation, and a duration measured across one such step is cut
16//! short or drawn out by the step.
17//!
18//! The two meet only where a recorded instant has to become a live wait: an
19//! intervention's persisted deadline, or the instant the agent last acted, read
20//! back after a restart. Each is translated once, against a [`ClockReading`]
21//! that took both readings together, and is counted down on
22//! [`Clock::elapsed`] from then on.
23
24use std::sync::OnceLock;
25use std::time::{Duration, Instant};
26
27use printobserver_types::Timestamp;
28
29/// The instant core reads the current time from.
30///
31/// Shareable across threads, because the expiry driver reads it from a thread
32/// of its own while callers read it from theirs.
33pub trait Clock: Send + Sync {
34    /// The instant now.
35    fn now(&self) -> Timestamp;
36
37    /// How much time has passed since an origin of this clock's own, on a
38    /// clock nothing steps: two readings differ by the time that passed
39    /// between them, whatever the wall clock did meanwhile.
40    ///
41    /// The provided reading is [`Clock::now`]'s, as time since the Unix epoch,
42    /// which a step of the wall clock moves; a clock over a host's own time
43    /// answers its monotonic clock instead, as [`SystemClock`] does.
44    fn elapsed(&self) -> Duration {
45        let micros = self.now().as_utc().timestamp_micros();
46        Duration::from_micros(u64::try_from(micros).unwrap_or_default())
47    }
48}
49
50/// The system's own clock, which is what a running supervisor is given.
51#[derive(Debug, Clone, Copy, Default)]
52pub struct SystemClock;
53
54impl Clock for SystemClock {
55    fn now(&self) -> Timestamp {
56        Timestamp::now()
57    }
58
59    fn elapsed(&self) -> Duration {
60        static ORIGIN: OnceLock<Instant> = OnceLock::new();
61        ORIGIN.get_or_init(Instant::now).elapsed()
62    }
63}
64
65/// Both of a clock's readings, taken together.
66///
67/// The one translation between them: where an absolute instant falls on the
68/// clock nothing steps, as seen from the moment this was read. It is taken
69/// once per instant translated, and never again, so that a later step of the
70/// wall clock cannot move a wait already being counted down.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct ClockReading {
73    /// What the wall clock read.
74    pub wall: Timestamp,
75    /// What the clock nothing steps read at the same moment.
76    pub elapsed: Duration,
77}
78
79impl ClockReading {
80    /// Read both of one clock's readings now.
81    #[must_use]
82    pub fn of(clock: &dyn Clock) -> Self {
83        Self {
84            wall: clock.now(),
85            elapsed: clock.elapsed(),
86        }
87    }
88
89    /// Where `instant` falls on [`Clock::elapsed`], as this reading sees it:
90    /// as far after this reading's own `elapsed` as `instant` is after its
91    /// `wall`, and as far before it — down to the clock's origin — as `instant`
92    /// is before.
93    #[must_use]
94    pub fn elapsed_at(&self, instant: Timestamp) -> Duration {
95        let later = instant.as_utc() >= self.wall.as_utc();
96        let offset = instant
97            .as_utc()
98            .signed_duration_since(*self.wall.as_utc())
99            .num_microseconds()
100            .unwrap_or(if later { i64::MAX } else { i64::MIN });
101        let apart = Duration::from_micros(offset.unsigned_abs());
102        if later {
103            self.elapsed.saturating_add(apart)
104        } else {
105            self.elapsed.saturating_sub(apart)
106        }
107    }
108}
109
110/// The instant `seconds` after `instant`.
111///
112/// Sub-second precision is kept: a bounded change asked to stand for a minute
113/// stands for a minute, rather than for a minute less however far into a second
114/// it happened to be made.
115///
116/// # Errors
117///
118/// Returns the timestamp crate's own error when the sum denotes no
119/// representable instant.
120pub fn plus_seconds(
121    instant: Timestamp,
122    seconds: i64,
123) -> Result<Timestamp, printobserver_types::TimestampError> {
124    instant.plus_seconds(seconds)
125}
126
127/// How many whole seconds `later` is after `earlier`, saturating.
128#[must_use]
129pub fn seconds_between(earlier: Timestamp, later: Timestamp) -> i64 {
130    unix_seconds(later).saturating_sub(unix_seconds(earlier))
131}
132
133/// One instant as whole seconds after the Unix epoch.
134#[must_use]
135pub fn unix_seconds(instant: Timestamp) -> i64 {
136    instant.as_utc().timestamp()
137}