Skip to main content

schedr_model/
beat.rs

1//! When a loop last turned, for liveness probes (see archive/PROJECT.md, Observability): the
2//! master's scheduling loop and the worker agent's event loop beat, and the ops port reads how long
3//! ago.
4//!
5//! The clock is monotonic (from when the process started), so a wall clock that steps never
6//! makes a loop look stuck or alive.
7
8use std::sync::Arc;
9use std::sync::OnceLock;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::{Duration, Instant};
12
13#[cfg(test)]
14mod tests;
15
16/// Never beaten.
17const NEVER: u64 = u64::MAX;
18
19/// When a loop last turned (cheap to clone; clones share it).
20#[derive(Debug, Clone)]
21pub struct Beat {
22    /// Milliseconds since [`origin`] at the last beat, or [`NEVER`].
23    last: Arc<AtomicU64>,
24}
25
26impl Default for Beat {
27    fn default() -> Self {
28        // The origin is set before any beat or question about one.
29        origin();
30        Self {
31            last: Arc::new(AtomicU64::new(NEVER)),
32        }
33    }
34}
35
36/// The process's monotonic origin.
37fn origin() -> Instant {
38    static ORIGIN: OnceLock<Instant> = OnceLock::new();
39    *ORIGIN.get_or_init(Instant::now)
40}
41
42fn millis(at: Instant) -> u64 {
43    u64::try_from(at.saturating_duration_since(origin()).as_millis()).unwrap_or(NEVER - 1)
44}
45
46impl Beat {
47    /// The loop turned now.
48    pub fn beat(&self) {
49        self.beat_at(Instant::now());
50    }
51
52    /// The loop turned at `at` (tests use their own times).
53    pub fn beat_at(&self, at: Instant) {
54        self.last.store(millis(at), Ordering::Relaxed);
55    }
56
57    /// How long before `now` the loop last turned; `None` if it never did.
58    #[must_use]
59    pub fn since(&self, now: Instant) -> Option<Duration> {
60        let last = self.last.load(Ordering::Relaxed);
61        (last != NEVER).then(|| Duration::from_millis(millis(now).saturating_sub(last)))
62    }
63}