spin_common/
sloth.rs

1//! Warn on slow operations
2
3use tokio::task::JoinHandle;
4use tokio::time::{sleep, Duration};
5
6/// Print a warning message after the given duration unless the returned
7/// [`SlothGuard`] is dropped first.
8pub fn warn_if_slothful(warn_after_ms: u64, message: impl Into<String>) -> SlothGuard {
9    let message = message.into();
10    let warning = tokio::spawn(async move {
11        sleep(Duration::from_millis(warn_after_ms)).await;
12        eprintln!("{message}");
13    });
14    SlothGuard { warning }
15}
16
17/// Returned by [`warn_if_slothful`]; cancels the warning when dropped.
18#[must_use]
19pub struct SlothGuard {
20    warning: JoinHandle<()>,
21}
22
23impl Drop for SlothGuard {
24    fn drop(&mut self) {
25        self.warning.abort()
26    }
27}