schedr_master/clock.rs
1//! Master time (B225, B228): the one clock every liveness decision of the cluster reads.
2//!
3//! The master is handed the wall clock (`now`) for what people see and what the database
4//! keeps: schedules, the times shown, retention. Whether a worker is lost, an assignment has
5//! waited too long, a parse or connection job overran, or a moved cleanup may start is decided
6//! on master time instead: the master's monotonic clock, which never steps. It is a
7//! [`Timestamp`] on a timeline of its own (the wall clock when the process first read it, plus
8//! the monotonic time since), so the code comparing times stays as it was; such times are never
9//! stored as wall-clock ones, nor compared with them. Workers read it from the clock every
10//! master message carries (`MasterClock`).
11//!
12//! A test hands the master its own times and these follow them ([`as_given`]), so a test moves
13//! master time by the `now` it passes.
14
15use std::sync::OnceLock;
16
17use jiff::{SignedDuration, Timestamp};
18
19/// How the master reads master time, from the wall-clock time it was handed.
20pub type Steady = fn(Timestamp) -> Timestamp;
21
22/// Master time as the time handed (tests: they move it with the `now` they pass).
23#[must_use]
24pub const fn as_given(now: Timestamp) -> Timestamp {
25 now
26}
27
28/// Master time from the monotonic clock (production): the wall clock at the process's first
29/// reading, plus the monotonic time since. `now` is ignored.
30#[must_use]
31pub fn monotonic(_now: Timestamp) -> Timestamp {
32 static ORIGIN: OnceLock<(Timestamp, std::time::Instant)> = OnceLock::new();
33 let (wall, mono) = *ORIGIN.get_or_init(|| (Timestamp::now(), std::time::Instant::now()));
34 let since = SignedDuration::try_from(mono.elapsed()).unwrap_or(SignedDuration::MAX);
35 wall.checked_add(since).unwrap_or(Timestamp::MAX)
36}
37
38/// This master process's timeline: master times of another process aren't comparable.
39#[must_use]
40pub fn timeline() -> u64 {
41 static TIMELINE: OnceLock<u64> = OnceLock::new();
42 *TIMELINE.get_or_init(|| {
43 // The low half of a UUIDv7, its random part: unique enough among a deployment's masters.
44 let bits = uuid::Uuid::now_v7().as_u128();
45 u64::try_from(bits & u128::from(u64::MAX))
46 .unwrap_or(1)
47 .max(1)
48 })
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn the_monotonic_clock_never_goes_back_and_given_times_pass_through() {
57 let first = monotonic(Timestamp::MIN);
58 let second = monotonic(Timestamp::MAX);
59 assert!(second >= first);
60 let given: Timestamp = "2026-11-11T03:00:00Z".parse().unwrap();
61 assert_eq!(as_given(given), given);
62 assert_eq!(timeline(), timeline());
63 assert_ne!(timeline(), 0);
64 }
65}