use std::sync::{
Arc, OnceLock,
atomic::{AtomicBool, Ordering},
};
use tokio::sync::watch;
pub const INTERRUPTED_EXIT_CODE: u8 = 130;
#[derive(Debug, Clone)]
pub struct Interrupt {
requested: Arc<AtomicBool>,
cleanup_in_flight: Arc<AtomicBool>,
fired: watch::Sender<bool>,
}
impl Interrupt {
fn install() -> Self {
let interrupt = Self {
requested: Arc::new(AtomicBool::new(false)),
cleanup_in_flight: Arc::new(AtomicBool::new(false)),
fired: watch::channel(false).0,
};
tokio::spawn(listen(interrupt.clone()));
interrupt
}
#[must_use]
pub fn requested(&self) -> bool {
self.requested.load(Ordering::Acquire)
}
#[must_use]
fn cleanup_in_flight(&self) -> bool {
self.cleanup_in_flight.load(Ordering::Acquire)
}
#[must_use]
pub fn cleanup_guard(&self) -> CleanupGuard {
self.cleanup_in_flight.store(true, Ordering::Release);
CleanupGuard {
cleanup_in_flight: Arc::clone(&self.cleanup_in_flight),
}
}
pub async fn fired(&self) {
if self.requested() {
return;
}
let mut receiver = self.fired.subscribe();
let _ = receiver.changed().await;
}
}
#[derive(Debug)]
pub struct CleanupGuard {
cleanup_in_flight: Arc<AtomicBool>,
}
impl Drop for CleanupGuard {
fn drop(&mut self) {
self.cleanup_in_flight.store(false, Ordering::Release);
}
}
pub fn interrupt() -> &'static Interrupt {
static INTERRUPT: OnceLock<Interrupt> = OnceLock::new();
INTERRUPT.get_or_init(Interrupt::install)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Course {
LetTheCloneCleanUp,
StopNow,
}
#[must_use]
const fn course(cleanup_in_flight: bool) -> Course {
if cleanup_in_flight {
Course::LetTheCloneCleanUp
} else {
Course::StopNow
}
}
async fn listen(interrupt: Interrupt) {
if tokio::signal::ctrl_c().await.is_err() {
return;
}
interrupt.requested.store(true, Ordering::Release);
interrupt.fired.send_replace(true);
match course(interrupt.cleanup_in_flight()) {
Course::LetTheCloneCleanUp => {}
Course::StopNow => std::process::exit(i32::from(INTERRUPTED_EXIT_CODE)),
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use super::{Course, Interrupt, course};
fn handle() -> Interrupt {
Interrupt {
requested: Arc::new(AtomicBool::new(false)),
cleanup_in_flight: Arc::new(AtomicBool::new(false)),
fired: tokio::sync::watch::channel(false).0,
}
}
#[test]
fn a_guard_is_held_only_while_it_exists() {
let interrupt = handle();
assert!(
!interrupt.cleanup_in_flight(),
"nothing is in flight before a clone starts"
);
let guard = interrupt.cleanup_guard();
assert!(
interrupt.cleanup_in_flight(),
"a running git always has a deletion behind it"
);
drop(guard);
assert!(
!interrupt.cleanup_in_flight(),
"a guard that outlived its clone would swallow every later Ctrl+C"
);
}
#[test]
fn an_interruption_during_a_cleanup_lets_the_cleanup_finish() {
assert_eq!(
course(true),
Course::LetTheCloneCleanUp,
"a deletion is under way, so the listener must not exit"
);
}
#[test]
fn an_interruption_with_nothing_pending_stops_at_once() {
assert_eq!(course(false), Course::StopNow);
}
#[test]
fn no_signal_has_been_requested_before_one_arrives() {
assert!(
!handle().requested(),
"the flag must start clear, or every clone would stop on its own"
);
}
#[tokio::test]
async fn a_signal_that_arrived_before_the_wait_resolves_at_once() {
let interrupt = handle();
let _guard = interrupt.cleanup_guard();
interrupt.requested.store(true, Ordering::Release);
interrupt.fired.send_replace(true);
tokio::time::timeout(Duration::from_secs(5), interrupt.fired())
.await
.expect("waiting on a signal that already arrived must not block");
}
#[tokio::test]
async fn a_signal_that_arrives_after_the_wait_is_still_seen() {
let interrupt = handle();
let _guard = interrupt.cleanup_guard();
let waiter = {
let interrupt = interrupt.clone();
tokio::spawn(async move { interrupt.fired().await })
};
tokio::task::yield_now().await;
interrupt.requested.store(true, Ordering::Release);
interrupt.fired.send_replace(true);
tokio::time::timeout(Duration::from_secs(5), waiter)
.await
.expect("a signal after subscribing must wake the waiter")
.expect("the waiter must not panic");
}
}