Skip to main content

veilid_tools/
process_watchdog.rs

1#![cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
2
3use super::*;
4use std::sync::mpsc;
5
6/// A plain OS thread that sleeps on a fixed period and reports when it wakes late.
7///
8/// Async tick lag cannot tell an overloaded executor from a process the OS is not
9/// scheduling. This thread touches no executor, so its lateness is the OS's alone:
10/// when it matches the async lag, the whole process was held (App Nap, sleep, CPU
11/// starvation); when it stays punctual while tasks lag, the executor or a pool is the
12/// bottleneck. Dropping the handle stops the thread at its next wakeup.
13pub struct ProcessWatchdog {
14    _stop: mpsc::Sender<()>,
15}
16
17impl ProcessWatchdog {
18    /// Start the thread. `on_late(late_us, now_us)` runs on the watchdog thread whenever
19    /// a wakeup is at least `late_threshold_ms` past its period.
20    #[must_use]
21    pub fn start(
22        period_ms: u64,
23        late_threshold_ms: u64,
24        on_late: impl Fn(u64, u64) + Send + 'static,
25    ) -> Self {
26        let (stop, wake) = mpsc::channel::<()>();
27        let period = Duration::from_millis(period_ms);
28        let late_threshold_us = late_threshold_ms * 1000;
29        let thread = std::thread::Builder::new()
30            .name("veilid-watchdog".to_owned())
31            .spawn(move || loop {
32                let before = get_raw_timestamp();
33                match wake.recv_timeout(period) {
34                    Err(mpsc::RecvTimeoutError::Timeout) => {}
35                    Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
36                }
37                let now = get_raw_timestamp();
38                let late_us = now.saturating_sub(before).saturating_sub(period_ms * 1000);
39                if late_us >= late_threshold_us {
40                    on_late(late_us, now);
41                }
42            });
43        match thread {
44            Ok(_) => debug!("process watchdog started: period {}ms", period_ms),
45            Err(e) => warn!("process watchdog thread not started: {}", e),
46        }
47        Self { _stop: stop }
48    }
49}