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 /// [`Clock::elapsed`] as the agent's minimum interval measures it.
50 ///
51 /// The same reading on every clock but [`SystemClock`] in the real-print
52 /// suite's own build, where it also counts the time that suite's replay
53 /// jumps between recorded events: the agent's changes to the machine at two
54 /// events recorded an hour apart are an hour apart. Every other duration stays
55 /// on [`Clock::elapsed`], because what it spaces — the detector's reads above
56 /// all — the server takes on its own schedule in real time.
57 fn paced(&self) -> Duration {
58 self.elapsed()
59 }
60}
61
62/// The system's own clock, which is what a running supervisor is given.
63#[derive(Debug, Clone, Copy, Default)]
64pub struct SystemClock;
65
66impl Clock for SystemClock {
67 fn now(&self) -> Timestamp {
68 Timestamp::now()
69 }
70
71 fn elapsed(&self) -> Duration {
72 static ORIGIN: OnceLock<Instant> = OnceLock::new();
73 ORIGIN.get_or_init(Instant::now).elapsed()
74 }
75
76 fn paced(&self) -> Duration {
77 Timestamp::on_replay_clock(self.elapsed())
78 }
79}
80
81/// Both of a clock's readings, taken together.
82///
83/// The one translation between them: where an absolute instant falls on the
84/// clock nothing steps, as seen from the moment this was read. It is taken
85/// once per instant translated, and never again, so that a later step of the
86/// wall clock cannot move a wait already being counted down.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct ClockReading {
89 /// What the wall clock read.
90 pub wall: Timestamp,
91 /// What the clock nothing steps read at the same moment.
92 pub elapsed: Duration,
93}
94
95impl ClockReading {
96 /// Read both of one clock's readings now.
97 #[must_use]
98 pub fn of(clock: &dyn Clock) -> Self {
99 Self {
100 wall: clock.now(),
101 elapsed: clock.elapsed(),
102 }
103 }
104
105 /// Where `instant` falls on [`Clock::elapsed`], as this reading sees it:
106 /// as far after this reading's own `elapsed` as `instant` is after its
107 /// `wall`, and as far before it — down to the clock's origin — as `instant`
108 /// is before.
109 #[must_use]
110 pub fn elapsed_at(&self, instant: Timestamp) -> Duration {
111 let later = instant.as_utc() >= self.wall.as_utc();
112 let offset = instant
113 .as_utc()
114 .signed_duration_since(*self.wall.as_utc())
115 .num_microseconds()
116 .unwrap_or(if later { i64::MAX } else { i64::MIN });
117 let apart = Duration::from_micros(offset.unsigned_abs());
118 if later {
119 self.elapsed.saturating_add(apart)
120 } else {
121 self.elapsed.saturating_sub(apart)
122 }
123 }
124}
125
126/// The instant `seconds` after `instant`.
127///
128/// Sub-second precision is kept: a bounded change asked to stand for a minute
129/// stands for a minute, rather than for a minute less however far into a second
130/// it happened to be made.
131///
132/// # Errors
133///
134/// Returns the timestamp crate's own error when the sum denotes no
135/// representable instant.
136pub fn plus_seconds(
137 instant: Timestamp,
138 seconds: i64,
139) -> Result<Timestamp, printobserver_types::TimestampError> {
140 instant.plus_seconds(seconds)
141}
142
143/// How many whole seconds `later` is after `earlier`, saturating.
144#[must_use]
145pub fn seconds_between(earlier: Timestamp, later: Timestamp) -> i64 {
146 unix_seconds(later).saturating_sub(unix_seconds(earlier))
147}
148
149/// One instant as whole seconds after the Unix epoch.
150#[must_use]
151pub fn unix_seconds(instant: Timestamp) -> i64 {
152 instant.as_utc().timestamp()
153}