Skip to main content

docsrs_cli/
shutdown.rs

1//! Wall-clock timeout, signal awareness, and cancel racing for one-shot runs.
2//!
3//! # Workload classification (Rules Rust — parallelism)
4//!
5//! - **Class:** signal/deadline coordination on the multi-thread one-shot runtime
6//!   (see `src/main.rs` and [`crate::concurrency`]).
7//! - **Fan-out bound:** fixed auxiliary tasks — at most one double-interrupt
8//!   watcher and one [`ProgressGuard`] timer per command (abort-on-drop). Product
9//!   CPU/HTTP admission lives in [`crate::concurrency::ConcurrencyBudget`].
10//! - **Shared state:** `CancelFlag` and progress `done` use `Arc<Atomic*>` (SeqCst),
11//!   never `Mutex` across `.await`.
12//!
13//! # Shutdown model (CLI one-shot)
14//!
15//! Product policy is **minimum + pipeline-critical** shutdown, not daemon coordination:
16//! detect (signals / deadline) → signal (`CancelFlag`) → await (race + flush) → DIE.
17//!
18//! - Unix: SIGINT → interrupt (130); SIGTERM / SIGHUP → terminate (143)
19//! - Windows: Ctrl+C → interrupt; Ctrl+Break / Ctrl+Close → terminate
20//! - Second SIGINT / Ctrl+C within [`DOUBLE_INTERRUPT_FORCE_SECS`] force-exits 130 after flush
21//! - stdout `BrokenPipe` is mapped by callers to exit 141 (Rust ignores SIGPIPE by default)
22
23use std::future::Future;
24use std::pin::Pin;
25use std::sync::Arc;
26use std::sync::atomic::{AtomicU8, Ordering};
27use std::task::{Context, Poll};
28use std::time::Duration;
29
30use tokio::time::{Instant, timeout};
31
32use crate::error::{AppError, AppResult, EXIT_INTERRUPTED, ErrorKind};
33
34/// Which OS signal cancelled the process.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum CancelKind {
37    /// SIGINT / Ctrl-C.
38    Interrupt,
39    /// SIGTERM, SIGHUP, Ctrl+Break, or Ctrl+Close (one-shot terminate).
40    Terminate,
41}
42
43const FLAG_NONE: u8 = 0;
44const FLAG_INTERRUPT: u8 = 1;
45const FLAG_TERMINATE: u8 = 2;
46
47/// Shared cancel flag checked by HTTP retries between attempts.
48///
49/// Stores the first observed [`CancelKind`] so cooperative checks can surface
50/// exit 130 vs 143 correctly (first cancel wins).
51///
52/// # Interior mutability
53///
54/// Cross-task flag (`Arc<AtomicU8>`): signal waiter, wall-clock path, and HTTP
55/// pollers share one flag. An atomic is the right primitive (not `Mutex<u8>` /
56/// `Cell` — multi-task, single primitive, no compound invariant).
57///
58/// Ordering is [`Ordering::SeqCst`] on every load/store/CAS so first-writer-wins
59/// is totally ordered against cooperative `check` without a separate fence story.
60#[derive(Debug, Clone, Default)]
61pub struct CancelFlag {
62    state: Arc<AtomicU8>,
63}
64
65impl CancelFlag {
66    /// Creates a fresh, non-cancelled flag.
67    pub fn new() -> Self {
68        Self {
69            state: Arc::new(AtomicU8::new(FLAG_NONE)),
70        }
71    }
72
73    /// Marks the flag as cancelled with [`CancelKind::Terminate`] (generic cancel).
74    pub fn cancel(&self) {
75        self.cancel_with(CancelKind::Terminate);
76    }
77
78    /// Marks the flag as cancelled with an explicit signal kind.
79    ///
80    /// First writer wins; subsequent calls are no-ops (idempotent).
81    /// CAS uses `SeqCst` success/failure orderings (see type docs).
82    pub fn cancel_with(&self, kind: CancelKind) {
83        let v = match kind {
84            CancelKind::Interrupt => FLAG_INTERRUPT,
85            CancelKind::Terminate => FLAG_TERMINATE,
86        };
87        // SeqCst: publish first cancel kind with a total order vs loads in `check`.
88        let _ = self
89            .state
90            .compare_exchange(FLAG_NONE, v, Ordering::SeqCst, Ordering::SeqCst);
91    }
92
93    /// Returns whether cancellation was requested.
94    pub fn is_cancelled(&self) -> bool {
95        // SeqCst: observe any prior `cancel_with` from another task.
96        self.state.load(Ordering::SeqCst) != FLAG_NONE
97    }
98
99    /// Returns the stored kind when cancelled.
100    pub fn kind(&self) -> Option<CancelKind> {
101        // SeqCst: pair with `cancel_with` CAS (see type docs).
102        match self.state.load(Ordering::SeqCst) {
103            FLAG_INTERRUPT => Some(CancelKind::Interrupt),
104            FLAG_TERMINATE => Some(CancelKind::Terminate),
105            _ => None,
106        }
107    }
108
109    /// Returns [`AppError::interrupted`] or [`AppError::terminated`] when cancelled.
110    ///
111    /// # Errors
112    ///
113    /// Returns [`ErrorKind::Interrupted`] or [`ErrorKind::Terminated`] when the flag is set.
114    pub fn check(&self) -> AppResult<()> {
115        match self.kind() {
116            None => Ok(()),
117            Some(CancelKind::Interrupt) => Err(AppError::interrupted()),
118            Some(CancelKind::Terminate) => Err(AppError::terminated()),
119        }
120    }
121}
122
123/// Run a future with a wall-clock deadline.
124///
125/// # Errors
126///
127/// Returns [`ErrorKind::Timeout`] when `deadline` elapses before `fut` completes.
128/// Propagates any error returned by `fut` itself.
129pub async fn with_wall_clock<T, F, Fut>(deadline: Duration, fut: F) -> AppResult<T>
130where
131    F: FnOnce() -> Fut,
132    Fut: Future<Output = AppResult<T>>,
133{
134    match timeout(deadline, fut()).await {
135        Ok(inner) => inner,
136        Err(_) => Err(AppError::new(
137            ErrorKind::Timeout,
138            format!("wall-clock timeout after {}s", deadline.as_secs()),
139        )),
140    }
141}
142
143/// Race an operation against cancel signals and an optional wall-clock deadline.
144///
145/// # Cancel safety (`select!`)
146///
147/// - Cancel arm: `wait_for_cancel` only awaits signal `recv` / `ctrl_c` (Tokio
148///   signal futures are cancel-safe; losing a poll does not drop OS registration).
149/// - Op arm: dropping `op` mid-flight aborts the in-flight HTTP future; partial
150///   body buffers are dropped with the task (one-shot CLI — no shared mutable
151///   request state beyond `CancelFlag`, which is written only on cancel/timeout).
152/// - `biased` prefers the cancel arm so a ready signal is not starved by a ready `op`.
153///
154/// # Errors
155///
156/// Returns [`ErrorKind::Timeout`] when `deadline` elapses first.
157/// Returns [`ErrorKind::Interrupted`] on SIGINT / Ctrl-C.
158/// Returns [`ErrorKind::Terminated`] on SIGTERM / SIGHUP / Ctrl+Break / Ctrl+Close.
159/// Propagates any error returned by `op`.
160pub async fn race_op_with_cancel_and_deadline<T, Fut>(
161    deadline: Duration,
162    cancel_flag: CancelFlag,
163    op: Fut,
164) -> AppResult<T>
165where
166    Fut: Future<Output = AppResult<T>>,
167{
168    tokio::pin!(op);
169    let cancel = wait_for_cancel();
170    tokio::pin!(cancel);
171
172    let timed = timeout(deadline, async {
173        tokio::select! {
174            biased;
175            kind = &mut cancel => {
176                cancel_flag.cancel_with(kind);
177                match kind {
178                    CancelKind::Interrupt => Err(AppError::interrupted()),
179                    CancelKind::Terminate => Err(AppError::terminated()),
180                }
181            }
182            res = &mut op => res,
183        }
184    });
185
186    match timed.await {
187        Ok(inner) => inner,
188        Err(_) => {
189            cancel_flag.cancel_with(CancelKind::Terminate);
190            Err(AppError::new(
191                ErrorKind::Timeout,
192                format!("wall-clock timeout after {}s", deadline.as_secs()),
193            ))
194        }
195    }
196}
197
198/// Elapsed milliseconds since start.
199pub fn duration_ms(start: Instant) -> u64 {
200    start.elapsed().as_millis() as u64
201}
202
203/// Flush stdout and stderr best-effort (FINALIZE).
204pub fn flush_stdio() {
205    use std::io::Write;
206    let _ = std::io::stdout().flush();
207    let _ = std::io::stderr().flush();
208}
209
210/// Future that completes when a cancel signal arrives.
211///
212/// # Platform policy (one-shot)
213///
214/// - Unix: SIGINT → [`CancelKind::Interrupt`]; SIGTERM / SIGHUP → [`CancelKind::Terminate`]
215/// - Windows: Ctrl+C → Interrupt; Ctrl+Break / Ctrl+Close → Terminate
216/// - SIGHUP is terminate (no config reload on one-shot)
217pub async fn wait_for_cancel() -> CancelKind {
218    #[cfg(unix)]
219    {
220        use tokio::signal::unix::{SignalKind, signal};
221        let mut sigint = match signal(SignalKind::interrupt()) {
222            Ok(s) => s,
223            Err(_) => {
224                let _ = tokio::signal::ctrl_c().await;
225                return CancelKind::Interrupt;
226            }
227        };
228        let mut sigterm = match signal(SignalKind::terminate()) {
229            Ok(s) => s,
230            Err(_) => {
231                let _ = tokio::signal::ctrl_c().await;
232                return CancelKind::Interrupt;
233            }
234        };
235        let mut sighup = match signal(SignalKind::hangup()) {
236            Ok(s) => s,
237            Err(_) => {
238                // Hangup unavailable: fall through without a third arm.
239                tokio::select! {
240                    _ = sigint.recv() => return CancelKind::Interrupt,
241                    _ = sigterm.recv() => return CancelKind::Terminate,
242                }
243            }
244        };
245        tokio::select! {
246            _ = sigint.recv() => CancelKind::Interrupt,
247            _ = sigterm.recv() => CancelKind::Terminate,
248            _ = sighup.recv() => CancelKind::Terminate,
249        }
250    }
251    #[cfg(windows)]
252    {
253        use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close};
254        let mut c_c = match ctrl_c() {
255            Ok(s) => s,
256            Err(_) => {
257                let _ = tokio::signal::ctrl_c().await;
258                return CancelKind::Interrupt;
259            }
260        };
261        let mut c_break = match ctrl_break() {
262            Ok(s) => s,
263            Err(_) => {
264                // Break unavailable: wait only on Ctrl+C.
265                let _ = c_c.recv().await;
266                return CancelKind::Interrupt;
267            }
268        };
269        let mut c_close = match ctrl_close() {
270            Ok(s) => s,
271            Err(_) => {
272                tokio::select! {
273                    _ = c_c.recv() => return CancelKind::Interrupt,
274                    _ = c_break.recv() => return CancelKind::Terminate,
275                }
276            }
277        };
278        tokio::select! {
279            _ = c_c.recv() => CancelKind::Interrupt,
280            _ = c_break.recv() => CancelKind::Terminate,
281            _ = c_close.recv() => CancelKind::Terminate,
282        }
283    }
284    #[cfg(not(any(unix, windows)))]
285    {
286        // Unsupported platforms: portable Ctrl+C only.
287        let _ = tokio::signal::ctrl_c().await;
288        CancelKind::Interrupt
289    }
290}
291
292/// Window for second SIGINT to force-exit (Rules Rust: double Ctrl-C).
293pub const DOUBLE_INTERRUPT_FORCE_SECS: u64 = 5;
294
295/// Install a process-wide second-SIGINT force-exit watcher.
296///
297/// First SIGINT is handled cooperatively by [`wait_for_cancel`] / [`race_op_with_cancel_and_deadline`].
298/// A second SIGINT within [`DOUBLE_INTERRUPT_FORCE_SECS`] flushes stdio and exits 130.
299/// Returns a join handle so callers may abort it after a clean finish (optional).
300pub fn spawn_double_interrupt_force_exit() -> tokio::task::JoinHandle<()> {
301    tokio::spawn(async move {
302        #[cfg(unix)]
303        {
304            use tokio::signal::unix::{SignalKind, signal};
305            let mut sigint = match signal(SignalKind::interrupt()) {
306                Ok(s) => s,
307                Err(_) => return,
308            };
309            // Consume first SIGINT (cooperative path also receives it).
310            let _ = sigint.recv().await;
311            let first = Instant::now();
312            // Wait for a second SIGINT inside the force window.
313            let second = sigint.recv();
314            tokio::pin!(second);
315            match tokio::time::timeout(
316                Duration::from_secs(DOUBLE_INTERRUPT_FORCE_SECS),
317                &mut second,
318            )
319            .await
320            {
321                Ok(Some(())) => {
322                    let _ = first;
323                    let _ = writeln_force_hint();
324                    flush_stdio();
325                    // Force path only: cooperative cleanup already had a chance on first SIGINT.
326                    std::process::exit(i32::from(EXIT_INTERRUPTED));
327                }
328                Ok(None) => {
329                    // Signal stream ended; do not force-exit.
330                }
331                Err(_) => {
332                    // Window expired: no force-exit for a late second interrupt.
333                }
334            }
335        }
336        #[cfg(not(unix))]
337        {
338            // Portable: first ctrl_c is cooperative (other task); second within window forces.
339            let _ = tokio::signal::ctrl_c().await;
340            let first = Instant::now();
341            match tokio::time::timeout(
342                Duration::from_secs(DOUBLE_INTERRUPT_FORCE_SECS),
343                tokio::signal::ctrl_c(),
344            )
345            .await
346            {
347                Ok(Ok(())) => {
348                    if first.elapsed() <= Duration::from_secs(DOUBLE_INTERRUPT_FORCE_SECS) {
349                        let _ = writeln_force_hint();
350                        flush_stdio();
351                        std::process::exit(i32::from(EXIT_INTERRUPTED));
352                    }
353                }
354                _ => {}
355            }
356        }
357    })
358}
359
360fn writeln_force_hint() -> std::io::Result<()> {
361    use std::io::Write;
362    let mut err = std::io::stderr();
363    writeln!(
364        err,
365        "docsrs-cli: second interrupt within {DOUBLE_INTERRUPT_FORCE_SECS}s; forcing exit {EXIT_INTERRUPTED}"
366    )?;
367    err.flush()
368}
369
370/// Progress reporter: after `delay`, emit one localized line to stderr if still running.
371///
372/// `done` is an [`AtomicBool`] shared with a background task (not `Mutex<bool>`).
373/// Stores/loads use [`Ordering::SeqCst`] so `finish` is visible before the delayed
374/// write without relying on abort alone.
375///
376/// # Drop / non-orphan tasks
377///
378/// Tokio's [`JoinHandle`] **detaches** the task on drop (does not abort). This guard
379/// implements [`Drop`] so early `?` returns and cancel races still abort the timer
380/// (Rules Rust: no orphan critical tasks; fixed fan-out of at most one progress task).
381pub struct ProgressGuard {
382    done: Arc<std::sync::atomic::AtomicBool>,
383    handle: Option<tokio::task::JoinHandle<()>>,
384}
385
386impl ProgressGuard {
387    /// Starts a delayed stderr progress line unless `quiet` is set.
388    pub fn start(quiet: bool, delay: Duration, message: String) -> Self {
389        let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
390        if quiet {
391            return Self { done, handle: None };
392        }
393        let flag = Arc::clone(&done);
394        let handle = tokio::spawn(async move {
395            tokio::time::sleep(delay).await;
396            // SeqCst: see `finish` / `Drop` store from the owner task.
397            if !flag.load(Ordering::SeqCst) {
398                use std::io::Write;
399                let _ = writeln!(std::io::stderr(), "{message}");
400                let _ = std::io::stderr().flush();
401            }
402        });
403        Self {
404            done,
405            handle: Some(handle),
406        }
407    }
408
409    /// Cancels the pending progress line and aborts the background task.
410    pub fn finish(mut self) {
411        self.shutdown();
412    }
413
414    fn shutdown(&mut self) {
415        // SeqCst: publish "done" before abort so a racing timer load never prints.
416        self.done.store(true, Ordering::SeqCst);
417        if let Some(h) = self.handle.take() {
418            h.abort();
419        }
420    }
421}
422
423impl Drop for ProgressGuard {
424    fn drop(&mut self) {
425        self.shutdown();
426    }
427}
428
429/// Helper future that polls cancel between retries (used by tests).
430pub struct CancelPoll<'a> {
431    flag: &'a CancelFlag,
432}
433
434impl Future for CancelPoll<'_> {
435    type Output = AppResult<()>;
436    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
437        Poll::Ready(self.flag.check())
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    #[tokio::test]
446    async fn wall_clock_timeout() {
447        let err = with_wall_clock(Duration::from_millis(20), || async {
448            tokio::time::sleep(Duration::from_millis(200)).await;
449            Ok::<(), AppError>(())
450        })
451        .await
452        .unwrap_err();
453        assert_eq!(err.kind(), ErrorKind::Timeout);
454    }
455
456    #[tokio::test]
457    async fn cancel_flag_check_defaults_to_terminated() {
458        let f = CancelFlag::new();
459        assert!(f.check().is_ok());
460        f.cancel();
461        assert_eq!(f.check().unwrap_err().kind(), ErrorKind::Terminated);
462        assert_eq!(f.kind(), Some(CancelKind::Terminate));
463    }
464
465    #[tokio::test]
466    async fn cancel_flag_preserves_interrupt_kind() {
467        let f = CancelFlag::new();
468        f.cancel_with(CancelKind::Interrupt);
469        assert_eq!(f.check().unwrap_err().kind(), ErrorKind::Interrupted);
470        // First cancel wins: later terminate must not overwrite interrupt.
471        f.cancel_with(CancelKind::Terminate);
472        assert_eq!(f.check().unwrap_err().kind(), ErrorKind::Interrupted);
473    }
474
475    #[test]
476    fn duration_ms_non_zero_after_sleep() {
477        let start = Instant::now();
478        std::thread::sleep(Duration::from_millis(5));
479        assert!(duration_ms(start) >= 1);
480    }
481
482    #[tokio::test]
483    async fn race_deadline_wins() {
484        let flag = CancelFlag::new();
485        let err = race_op_with_cancel_and_deadline(Duration::from_millis(15), flag, async {
486            tokio::time::sleep(Duration::from_millis(200)).await;
487            Ok::<(), AppError>(())
488        })
489        .await
490        .unwrap_err();
491        assert_eq!(err.kind(), ErrorKind::Timeout);
492    }
493
494    #[tokio::test]
495    async fn progress_guard_quiet_is_noop() {
496        let g = ProgressGuard::start(true, Duration::from_millis(1), "x".into());
497        g.finish();
498    }
499
500    #[tokio::test]
501    async fn progress_guard_drop_aborts_without_finish() {
502        // Drop must abort (JoinHandle drop alone would detach the task).
503        let g = ProgressGuard::start(false, Duration::from_secs(60), "must-not-print".into());
504        drop(g);
505    }
506
507    #[test]
508    fn flush_stdio_does_not_panic() {
509        flush_stdio();
510    }
511
512    #[test]
513    fn double_interrupt_window_is_five_seconds() {
514        assert_eq!(DOUBLE_INTERRUPT_FORCE_SECS, 5);
515    }
516
517    #[tokio::test]
518    async fn spawn_double_interrupt_handle_aborts_cleanly() {
519        let h = spawn_double_interrupt_force_exit();
520        h.abort();
521        let _ = h.await;
522    }
523}