Skip to main content

docsrs_cli/shutdown/
signals.rs

1//! OS signal capture and the double-interrupt force-exit escalation.
2//!
3//! Split from the cancellation primitives in the parent module: deciding *that*
4//! work should stop is portable state machinery, while learning that the OS
5//! asked for it is platform-specific and carries every `cfg(unix)` /
6//! `cfg(windows)` branch in the crate.
7
8use std::time::Duration;
9
10use super::{CancelKind, flush_stdio};
11use crate::error::EXIT_INTERRUPTED;
12
13/// Future that completes when a cancel signal arrives.
14///
15/// # Platform policy (one-shot)
16///
17/// - Unix: SIGINT → [`CancelKind::Interrupt`]; SIGTERM / SIGHUP → [`CancelKind::Terminate`]
18/// - Windows: Ctrl+C → Interrupt; Ctrl+Break / Ctrl+Close → Terminate
19/// - SIGHUP is terminate (no config reload on one-shot)
20pub async fn wait_for_cancel() -> CancelKind {
21    #[cfg(unix)]
22    {
23        use tokio::signal::unix::{SignalKind, signal};
24        let mut sigint = match signal(SignalKind::interrupt()) {
25            Ok(s) => s,
26            Err(_) => {
27                let _ = tokio::signal::ctrl_c().await;
28                return CancelKind::Interrupt;
29            }
30        };
31        let mut sigterm = match signal(SignalKind::terminate()) {
32            Ok(s) => s,
33            Err(_) => {
34                let _ = tokio::signal::ctrl_c().await;
35                return CancelKind::Interrupt;
36            }
37        };
38        let mut sighup = match signal(SignalKind::hangup()) {
39            Ok(s) => s,
40            Err(_) => {
41                // Hangup unavailable: fall through without a third arm.
42                tokio::select! {
43                    _ = sigint.recv() => return CancelKind::Interrupt,
44                    _ = sigterm.recv() => return CancelKind::Terminate,
45                }
46            }
47        };
48        tokio::select! {
49            _ = sigint.recv() => CancelKind::Interrupt,
50            _ = sigterm.recv() => CancelKind::Terminate,
51            _ = sighup.recv() => CancelKind::Terminate,
52        }
53    }
54    #[cfg(windows)]
55    {
56        use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close};
57        let mut c_c = match ctrl_c() {
58            Ok(s) => s,
59            Err(_) => {
60                let _ = tokio::signal::ctrl_c().await;
61                return CancelKind::Interrupt;
62            }
63        };
64        let mut c_break = match ctrl_break() {
65            Ok(s) => s,
66            Err(_) => {
67                // Break unavailable: wait only on Ctrl+C.
68                let _ = c_c.recv().await;
69                return CancelKind::Interrupt;
70            }
71        };
72        let mut c_close = match ctrl_close() {
73            Ok(s) => s,
74            Err(_) => {
75                tokio::select! {
76                    _ = c_c.recv() => return CancelKind::Interrupt,
77                    _ = c_break.recv() => return CancelKind::Terminate,
78                }
79            }
80        };
81        tokio::select! {
82            _ = c_c.recv() => CancelKind::Interrupt,
83            _ = c_break.recv() => CancelKind::Terminate,
84            _ = c_close.recv() => CancelKind::Terminate,
85        }
86    }
87    #[cfg(not(any(unix, windows)))]
88    {
89        // Unsupported platforms: portable Ctrl+C only.
90        let _ = tokio::signal::ctrl_c().await;
91        CancelKind::Interrupt
92    }
93}
94
95/// Window for second SIGINT to force-exit (Rules Rust: double Ctrl-C).
96pub const DOUBLE_INTERRUPT_FORCE_SECS: u64 = 5;
97
98/// Install a process-wide second-SIGINT force-exit watcher.
99///
100/// First SIGINT is handled cooperatively by [`wait_for_cancel`] / [`crate::shutdown::race_op_with_cancel_and_deadline`].
101/// A second SIGINT within [`DOUBLE_INTERRUPT_FORCE_SECS`] flushes stdio and exits 130.
102/// Returns a join handle so callers may abort it after a clean finish (optional).
103pub fn spawn_double_interrupt_force_exit() -> tokio::task::JoinHandle<()> {
104    tokio::spawn(async move {
105        #[cfg(unix)]
106        {
107            use tokio::signal::unix::{SignalKind, signal};
108            let mut sigint = match signal(SignalKind::interrupt()) {
109                Ok(s) => s,
110                Err(_) => return,
111            };
112            // Consume first SIGINT (cooperative path also receives it).
113            let _ = sigint.recv().await;
114            // The force window is enforced by `tokio::time::timeout` below, which
115            // owns its own deadline. A separate `Instant::now()` used to be taken
116            // here and then discarded with `let _ = first;` in the force branch —
117            // a stamp nothing read, kept alive only by the discard that silenced
118            // the unused warning it would otherwise have raised.
119            // Wait for a second SIGINT inside the force window.
120            let second = sigint.recv();
121            tokio::pin!(second);
122            match tokio::time::timeout(
123                Duration::from_secs(DOUBLE_INTERRUPT_FORCE_SECS),
124                &mut second,
125            )
126            .await
127            {
128                Ok(Some(())) => {
129                    let _ = writeln_force_hint();
130                    flush_stdio();
131                    // Force path only: cooperative cleanup already had a chance on first SIGINT.
132                    std::process::exit(i32::from(EXIT_INTERRUPTED));
133                }
134                Ok(None) => {
135                    // Signal stream ended; do not force-exit.
136                }
137                Err(_) => {
138                    // Window expired: no force-exit for a late second interrupt.
139                }
140            }
141        }
142        #[cfg(not(unix))]
143        {
144            portable_double_interrupt().await;
145        }
146    })
147}
148
149/// Portable double-interrupt watcher for targets without POSIX signals.
150///
151/// Compiled on every target (including Unix, where it is never called) so the
152/// body stays type-checked on the host. Attribute `cfg` is resolved during macro
153/// expansion, before type checking, so a body that only ever compiles elsewhere
154/// can carry errors into a release unnoticed.
155#[cfg_attr(unix, allow(dead_code))]
156async fn portable_double_interrupt() {
157    // Portable: first ctrl_c is cooperative (other task); second within window forces.
158    let _ = tokio::signal::ctrl_c().await;
159    // `timeout` returning `Ok` already proves the second interrupt landed inside
160    // the force window; an elapsed-time re-check would be vacuously true.
161    if let Ok(Ok(())) = tokio::time::timeout(
162        Duration::from_secs(DOUBLE_INTERRUPT_FORCE_SECS),
163        tokio::signal::ctrl_c(),
164    )
165    .await
166    {
167        let _ = writeln_force_hint();
168        flush_stdio();
169        // Force path only: cooperative cleanup already had a chance on first ctrl_c.
170        std::process::exit(i32::from(EXIT_INTERRUPTED));
171    }
172}
173
174fn writeln_force_hint() -> std::io::Result<()> {
175    use std::io::Write;
176    let mut err = std::io::stderr();
177    writeln!(
178        err,
179        "docsrs-cli: second interrupt within {DOUBLE_INTERRUPT_FORCE_SECS}s; forcing exit {EXIT_INTERRUPTED}"
180    )?;
181    err.flush()
182}