astrs_cli/command/signals.rs
1//! The one place this binary decides what "stop" means when it arrives as a
2//! signal rather than as an argument.
3//!
4//! ```text
5//! SIGINT ─┐
6//! ├─► Signals::next() ─► the verb's own graceful path
7//! SIGTERM ─┘ (cancel a run, unsubscribe a tail,
8//! shut a server's listener down)
9//! ```
10//!
11//! # Why `SIGTERM` and not only `SIGINT`
12//!
13//! Ctrl-C in a terminal sends `SIGINT`, and that is the case every user
14//! meets. But every long-running verb in this binary also runs *under a
15//! supervisor* — `astrs run` inside a CI step or a container, `astrs
16//! coordinator`/`astrs daemon` under systemd or under `astrs up`'s own
17//! `astrs down` — and a supervisor terminates rather than interrupts. A
18//! process that handled only `SIGINT` would be killed outright by its
19//! supervisor's default `SIGTERM` disposition, leaving the graph it was
20//! supervising to be reaped by the orphan guard instead of stopped
21//! gracefully. Both signals therefore mean exactly one thing here: begin the
22//! same graceful stop.
23//!
24//! # Degrading rather than failing
25//!
26//! Installing a handler can fail (a process may have exhausted its signal
27//! resources, or run somewhere the syscall is refused). A verb that refused
28//! to start because a handler could not be installed would be strictly worse
29//! than one that runs and cannot be interrupted — the graph is what the user
30//! came for. [`Signals::install`] therefore keeps whichever handler it got
31//! and, if it got none, simply never resolves.
32
33/// The signals that mean "stop what you are doing, gracefully".
34#[derive(Debug)]
35pub struct Signals {
36 /// The `SIGINT` stream, absent if it could not be installed.
37 interrupt: Option<tokio::signal::unix::Signal>,
38 /// The `SIGTERM` stream, absent if it could not be installed.
39 terminate: Option<tokio::signal::unix::Signal>,
40}
41
42impl Signals {
43 /// Installs both handlers, degrading to "no handler" rather than
44 /// failing the caller.
45 ///
46 /// Must be called from inside a tokio runtime (every caller in this
47 /// crate is already inside its verb's own `block_on`).
48 #[must_use]
49 pub fn install() -> Self {
50 use tokio::signal::unix::{SignalKind, signal};
51 Self {
52 interrupt: signal(SignalKind::interrupt()).ok(),
53 terminate: signal(SignalKind::terminate()).ok(),
54 }
55 }
56
57 /// Whether any handler at all is installed — false only when the
58 /// process could not have one, in which case [`Signals::next`] never
59 /// resolves.
60 #[must_use]
61 pub const fn is_armed(&self) -> bool {
62 self.interrupt.is_some() || self.terminate.is_some()
63 }
64
65 /// Resolves on the next signal of either kind.
66 ///
67 /// Cancel-safe: both underlying streams are, so this is safe to use as a
68 /// `tokio::select!` arm that loses the race.
69 pub async fn next(&mut self) {
70 match (self.interrupt.as_mut(), self.terminate.as_mut()) {
71 (Some(interrupt), Some(terminate)) => {
72 tokio::select! {
73 _ = interrupt.recv() => {}
74 _ = terminate.recv() => {}
75 }
76 }
77 (Some(one), None) | (None, Some(one)) => {
78 let _ = one.recv().await;
79 }
80 (None, None) => std::future::pending().await,
81 }
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
88
89 use super::*;
90 use std::time::Duration;
91
92 #[tokio::test]
93 async fn installing_twice_is_harmless_and_both_handlers_arm() {
94 let first = Signals::install();
95 let second = Signals::install();
96 assert!(first.is_armed());
97 assert!(second.is_armed());
98 }
99
100 #[tokio::test]
101 async fn a_real_signal_resolves_the_wait() {
102 let mut signals = Signals::install();
103 // Signalling this very process is the only honest test of a signal
104 // handler; `SIGINT`'s default disposition would end the test binary,
105 // which is exactly why the handler being installed first matters.
106 let pid = rustix::process::Pid::from_raw(std::process::id().cast_signed())
107 .expect("this process has a pid");
108 tokio::spawn(async move {
109 tokio::time::sleep(Duration::from_millis(20)).await;
110 let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT);
111 });
112 tokio::time::timeout(Duration::from_secs(5), signals.next())
113 .await
114 .expect("the handler must observe SIGINT");
115 }
116
117 #[tokio::test]
118 async fn a_wait_with_no_handlers_never_resolves() {
119 let mut signals = Signals {
120 interrupt: None,
121 terminate: None,
122 };
123 assert!(!signals.is_armed());
124 let timed_out = tokio::time::timeout(Duration::from_millis(30), signals.next())
125 .await
126 .is_err();
127 assert!(timed_out, "an unarmed wait must never resolve");
128 }
129}