brinkhaustools/
shutdown.rsuse std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
#[derive(Clone)]
pub struct ShutdownToken {
inner: Arc<ShutdownInner>,
}
impl ShutdownToken {
pub fn is_shutdown(&self) -> bool {
*self.inner.flag.lock().unwrap()
}
pub fn wait(&self) {
let mut flag = self.inner.flag.lock().unwrap();
while !*flag {
flag = self.inner.condvar.wait(flag).unwrap();
}
}
pub fn wait_timeout(&self, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
let mut flag = self.inner.flag.lock().unwrap();
while !*flag {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return false;
}
let (guard, _timeout_result) = self.inner.condvar.wait_timeout(flag, remaining).unwrap();
flag = guard;
}
true
}
}
struct ShutdownInner {
flag: Mutex<bool>,
condvar: Condvar,
#[allow(clippy::type_complexity)]
hooks: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
}
#[derive(Clone)]
pub struct ShutdownHandler {
inner: Arc<ShutdownInner>,
}
impl ShutdownHandler {
pub fn new() -> Self {
Self {
inner: Arc::new(ShutdownInner {
flag: Mutex::new(false),
condvar: Condvar::new(),
hooks: Mutex::new(Some(Vec::new())),
}),
}
}
#[cfg(feature = "signals")]
pub fn with_signal_handlers() -> Self {
let handler = Self::new();
let token = handler.token();
ctrlc::set_handler(move || {
token.inner.run_hooks_and_set(&token.inner);
})
.expect("Failed to install Ctrl+C handler");
handler
}
pub fn trigger(&self) {
self.inner.run_hooks_and_set(&self.inner);
}
pub fn trigger_delayed(&self, delay: Duration) {
let inner = self.inner.clone();
thread::spawn(move || {
thread::sleep(delay);
inner.run_hooks_and_set(&inner);
});
}
pub fn is_shutdown(&self) -> bool {
*self.inner.flag.lock().unwrap()
}
pub fn wait(&self) {
let mut flag = self.inner.flag.lock().unwrap();
while !*flag {
flag = self.inner.condvar.wait(flag).unwrap();
}
}
pub fn wait_timeout(&self, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
let mut flag = self.inner.flag.lock().unwrap();
while !*flag {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return false;
}
let (guard, _) = self.inner.condvar.wait_timeout(flag, remaining).unwrap();
flag = guard;
}
true
}
pub fn sleep(&self, duration: Duration) -> bool {
self.wait_timeout(duration)
}
pub fn register_hook<F: FnOnce() + Send + 'static>(&self, hook: F) {
let mut hooks_guard = self.inner.hooks.lock().unwrap();
if let Some(hooks) = hooks_guard.as_mut() {
hooks.push(Box::new(hook));
} else {
drop(hooks_guard);
hook();
}
}
pub fn token(&self) -> ShutdownToken {
ShutdownToken {
inner: self.inner.clone(),
}
}
pub fn reset_for_testing(&self) {
let mut flag = self.inner.flag.lock().unwrap();
*flag = false;
let mut hooks = self.inner.hooks.lock().unwrap();
*hooks = Some(Vec::new());
}
}
impl Default for ShutdownHandler {
fn default() -> Self {
Self::new()
}
}
impl ShutdownInner {
fn run_hooks_and_set(&self, _inner: &Arc<ShutdownInner>) {
let hooks = {
let mut hooks_guard = self.hooks.lock().unwrap();
hooks_guard.take()
};
if let Some(hooks) = hooks {
for hook in hooks {
hook();
}
}
let mut flag = self.flag.lock().unwrap();
*flag = true;
self.condvar.notify_all();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn test_initial_state() {
let h = ShutdownHandler::new();
assert!(!h.is_shutdown());
}
#[test]
fn test_trigger_immediate() {
let h = ShutdownHandler::new();
h.trigger();
assert!(h.is_shutdown());
}
#[test]
fn test_trigger_delayed() {
let h = ShutdownHandler::new();
h.trigger_delayed(Duration::from_millis(100));
assert!(!h.is_shutdown());
thread::sleep(Duration::from_millis(250));
assert!(h.is_shutdown());
}
#[test]
fn test_hook_called_on_shutdown() {
let h = ShutdownHandler::new();
let called = Arc::new(AtomicUsize::new(0));
let called_clone = called.clone();
h.register_hook(move || {
called_clone.fetch_add(1, Ordering::SeqCst);
});
h.trigger();
assert_eq!(called.load(Ordering::SeqCst), 1);
}
#[test]
fn test_hooks_execute_only_once() {
let h = ShutdownHandler::new();
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
h.register_hook(move || {
counter_clone.fetch_add(1, Ordering::SeqCst);
});
h.trigger();
h.trigger();
assert_eq!(counter.load(Ordering::SeqCst), 1);
}
#[test]
fn test_sleep_interrupted_by_shutdown() {
let h = ShutdownHandler::new();
let h2 = h.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(100));
h2.trigger();
});
let start = Instant::now();
let interrupted = h.sleep(Duration::from_secs(5));
let elapsed = start.elapsed();
assert!(interrupted);
assert!(elapsed < Duration::from_secs(1));
}
#[test]
fn test_sleep_completes_normally() {
let h = ShutdownHandler::new();
let interrupted = h.sleep(Duration::from_millis(50));
assert!(!interrupted);
}
#[test]
fn test_wait_blocks_until_shutdown() {
let h = ShutdownHandler::new();
let h2 = h.clone();
let done = Arc::new(AtomicUsize::new(0));
let done_clone = done.clone();
thread::spawn(move || {
h2.wait();
done_clone.fetch_add(1, Ordering::SeqCst);
});
thread::sleep(Duration::from_millis(50));
assert_eq!(done.load(Ordering::SeqCst), 0);
h.trigger();
thread::sleep(Duration::from_millis(50));
assert_eq!(done.load(Ordering::SeqCst), 1);
}
#[test]
fn test_wait_timeout_expires() {
let h = ShutdownHandler::new();
let result = h.wait_timeout(Duration::from_millis(100));
assert!(!result);
}
#[test]
fn test_wait_timeout_returns_true() {
let h = ShutdownHandler::new();
let h2 = h.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
h2.trigger();
});
let result = h.wait_timeout(Duration::from_secs(5));
assert!(result);
}
#[test]
fn test_multiple_hooks_all_called() {
let h = ShutdownHandler::new();
let counter = Arc::new(AtomicUsize::new(0));
for _ in 0..3 {
let c = counter.clone();
h.register_hook(move || {
c.fetch_add(1, Ordering::SeqCst);
});
}
h.trigger();
assert_eq!(counter.load(Ordering::SeqCst), 3);
}
#[test]
fn test_hook_registered_after_shutdown() {
let h = ShutdownHandler::new();
h.trigger();
let called = Arc::new(AtomicUsize::new(0));
let called_clone = called.clone();
h.register_hook(move || {
called_clone.fetch_add(1, Ordering::SeqCst);
});
assert_eq!(called.load(Ordering::SeqCst), 1);
}
#[test]
fn test_clone_token_shares_state() {
let h = ShutdownHandler::new();
let token = h.token();
assert!(!token.is_shutdown());
h.trigger();
assert!(token.is_shutdown());
}
#[test]
fn test_reset_for_testing() {
let h = ShutdownHandler::new();
h.trigger();
assert!(h.is_shutdown());
h.reset_for_testing();
assert!(!h.is_shutdown());
}
}