Skip to main content

rusty_time_clock/
lib.rs

1//! rusty_time-clock — the platform seam.
2//!
3//! Three capabilities, each a trait so the daemon, the tests, and the TIMECORP
4//! simulator plug the same discipline loop into different worlds:
5//!
6//! * [`ClockRead`] — wall + monotonic time.
7//! * [`ClockDrive`] — execute [`ClockCommand`]s (slew / step).
8//! * [`VirtualDriver`] — the no-privilege fallback: applies commands to a
9//!   [`rusty_time_core::VirtualClock`] view instead of the OS clock.
10//!
11//! This is the only crate in the workspace where `unsafe` is permitted; every
12//! block names its invariant.
13
14use core::fmt;
15use rusty_time_core::ClockCommand;
16
17#[derive(Clone, Debug)]
18pub struct ClockError {
19    /// Which operation failed (static, greppable).
20    pub op: &'static str,
21    /// OS-level detail.
22    pub detail: String,
23}
24
25impl fmt::Display for ClockError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "clock {}: {}", self.op, self.detail)
28    }
29}
30
31impl std::error::Error for ClockError {}
32
33/// Read the platform clocks.
34pub trait ClockRead {
35    /// Wall-clock nanoseconds since the Unix epoch.
36    fn wall_ns(&self) -> Result<i128, ClockError>;
37    /// Monotonic seconds from an arbitrary origin, unaffected by steps.
38    fn mono_s(&self) -> Result<f64, ClockError>;
39
40    /// Wall clock as **(seconds, nanoseconds)** since the Unix epoch.
41    ///
42    /// This is the shape an NTP timestamp actually wants, and the shape the
43    /// OS already has: every platform's clock call returns a seconds/nanos
44    /// pair. Going through `wall_ns` multiplies those together into an `i128`
45    /// and the caller then divides them straight back apart — and a 128-bit
46    /// division is a *software* routine, not an instruction. On the server's
47    /// per-reply path callgrind attributed 5% of everything the server did to
48    /// `__divti3`, for a round trip that produces the numbers it started with.
49    ///
50    /// The default implementation keeps that round trip, so implementations
51    /// that only have nanoseconds still work; the platform clocks override it.
52    fn wall_parts(&self) -> Result<(i64, u32), ClockError> {
53        let ns = self.wall_ns()?;
54        let secs = ns.div_euclid(1_000_000_000) as i64;
55        let nanos = ns.rem_euclid(1_000_000_000) as u32;
56        Ok((secs, nanos))
57    }
58}
59
60/// Drive the platform clock.
61pub trait ClockDrive {
62    fn apply(&mut self, cmd: &ClockCommand) -> Result<(), ClockError>;
63}
64
65/// What this machine can actually do, probed without perturbing the clock.
66///
67/// Deliberately separates *reading* from *disciplining*: reading needs no
68/// privilege anywhere, disciplining needs it everywhere, and a daemon that
69/// cannot tell the difference reports "working" while silently never
70/// correcting anything. The smoke rigs assert on these fields.
71#[derive(Clone, Debug, PartialEq)]
72pub struct ClockCapabilities {
73    pub os: &'static str,
74    pub arch: &'static str,
75    /// Wall and monotonic clocks readable.
76    pub can_read: bool,
77    /// Whether this process holds what disciplining requires. Probed by
78    /// inspecting privileges, never by attempting an adjustment — a probe that
79    /// moves the clock to find out whether it may is not a probe.
80    pub can_discipline: bool,
81    /// What disciplining needs here, for the operator who has `false` above.
82    pub discipline_requirement: &'static str,
83    /// Granularity of the platform's frequency-adjustment knob, in ppm.
84    /// `None` where the platform exposes no frequency knob at all.
85    pub slew_resolution_ppm: Option<f64>,
86    /// Ceiling the platform imposes on frequency adjustment, in ppm.
87    pub max_slew_ppm: f64,
88    /// Whether receives are batched (one syscall for many datagrams).
89    pub batch_receive: bool,
90    /// Measured granularity of a monotonic clock read, nanoseconds.
91    pub mono_resolution_ns: Option<f64>,
92}
93
94impl ClockCapabilities {
95    /// Measure how finely the monotonic clock actually ticks, by finding the
96    /// smallest non-zero step across a burst of reads. A *measurement*, not the
97    /// value the platform advertises — those disagree often enough to matter.
98    pub fn measure_mono_resolution<C: ClockRead>(clock: &C) -> Option<f64> {
99        let mut smallest = f64::INFINITY;
100        let mut last = clock.mono_s().ok()?;
101        for _ in 0..20_000 {
102            let now = clock.mono_s().ok()?;
103            let delta = now - last;
104            if delta > 0.0 && delta < smallest {
105                smallest = delta;
106            }
107            last = now;
108        }
109        smallest.is_finite().then_some(smallest * 1e9)
110    }
111}
112
113#[cfg(target_os = "linux")]
114mod linux;
115#[cfg(target_os = "linux")]
116pub use linux::SystemClock;
117
118#[cfg(target_os = "macos")]
119mod macos;
120#[cfg(target_os = "macos")]
121pub use macos::SystemClock;
122
123#[cfg(windows)]
124mod windows;
125#[cfg(windows)]
126pub use windows::SystemClock;
127
128mod virtual_driver;
129pub use virtual_driver::VirtualDriver;
130
131/// Platform slew arithmetic, testable on every host (see the module docs for
132/// why that is not merely tidiness).
133pub mod slew;
134
135/// Reference-clock transports: gpsd shared memory, chrony's SOCK protocol,
136/// and PTP hardware clocks.
137#[cfg(any(unix, target_os = "linux"))]
138pub mod refclock;
139
140#[cfg(any(unix, windows))]
141pub mod net;
142
143/// SIGTERM and SIGINT, including as a PID namespace's init process.
144pub mod stop;
145
146/// Probe this machine's clock capabilities.
147pub fn capabilities() -> ClockCapabilities {
148    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
149    {
150        let mut caps = platform_capabilities();
151        let clock = SystemClock;
152        caps.can_read = clock.wall_ns().is_ok() && clock.mono_s().is_ok();
153        caps.mono_resolution_ns = ClockCapabilities::measure_mono_resolution(&clock);
154        caps
155    }
156    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
157    {
158        ClockCapabilities {
159            os: std::env::consts::OS,
160            arch: std::env::consts::ARCH,
161            can_read: false,
162            can_discipline: false,
163            discipline_requirement: "no platform driver for this target",
164            slew_resolution_ppm: None,
165            max_slew_ppm: 0.0,
166            batch_receive: false,
167            mono_resolution_ns: None,
168        }
169    }
170}
171
172#[cfg(target_os = "linux")]
173use linux::platform_capabilities;
174#[cfg(target_os = "macos")]
175use macos::platform_capabilities;
176#[cfg(windows)]
177use windows::platform_capabilities;
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn capabilities_are_self_consistent() {
185        let caps = capabilities();
186        assert_eq!(caps.os, std::env::consts::OS);
187        // Reading is unprivileged on every platform we support, so a build
188        // that cannot read its own clock is broken, not merely unprivileged.
189        assert!(caps.can_read, "clock must be readable without privilege");
190        assert!(
191            !caps.discipline_requirement.is_empty(),
192            "an operator who cannot discipline must be told what it needs"
193        );
194        // Resolution is a measurement; if present it must be sane.
195        if let Some(res) = caps.mono_resolution_ns {
196            assert!(
197                res > 0.0 && res < 1e9,
198                "implausible monotonic resolution {res} ns"
199            );
200        }
201        assert!(caps.max_slew_ppm > 0.0);
202    }
203
204    #[test]
205    fn batch_receive_matches_the_platform() {
206        // recvmmsg is Linux-only; claiming it elsewhere would make a smoke rig
207        // assert a capability that does not exist.
208        assert_eq!(capabilities().batch_receive, cfg!(target_os = "linux"));
209    }
210}