docsrs_cli/shutdown/mod.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
23mod signals;
24
25#[cfg(test)]
26mod tests;
27
28pub use signals::{
29 DOUBLE_INTERRUPT_FORCE_SECS, spawn_double_interrupt_force_exit, wait_for_cancel,
30};
31
32use std::future::Future;
33use std::pin::Pin;
34use std::sync::Arc;
35use std::sync::atomic::{AtomicU8, Ordering};
36use std::task::{Context, Poll};
37use std::time::Duration;
38
39use tokio::time::{Instant, timeout};
40
41use crate::error::{AppError, AppResult, ErrorDetail};
42
43/// Which OS signal cancelled the process.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum CancelKind {
46 /// SIGINT / Ctrl-C.
47 Interrupt,
48 /// SIGTERM, SIGHUP, Ctrl+Break, or Ctrl+Close (one-shot terminate).
49 Terminate,
50}
51
52const FLAG_NONE: u8 = 0;
53const FLAG_INTERRUPT: u8 = 1;
54const FLAG_TERMINATE: u8 = 2;
55
56/// Shared cancel flag checked by HTTP retries between attempts.
57///
58/// Stores the first observed [`CancelKind`] so cooperative checks can surface
59/// exit 130 vs 143 correctly (first cancel wins).
60///
61/// # Interior mutability
62///
63/// Cross-task flag (`Arc<AtomicU8>`): signal waiter, wall-clock path, and HTTP
64/// pollers share one flag. An atomic is the right primitive (not `Mutex<u8>` /
65/// `Cell` — multi-task, single primitive, no compound invariant).
66///
67/// Ordering is [`Ordering::SeqCst`] on every load/store/CAS so first-writer-wins
68/// is totally ordered against cooperative `check` without a separate fence story.
69#[derive(Debug, Clone, Default)]
70pub struct CancelFlag {
71 state: Arc<AtomicU8>,
72}
73
74impl CancelFlag {
75 /// Creates a fresh, non-cancelled flag.
76 pub fn new() -> Self {
77 Self {
78 state: Arc::new(AtomicU8::new(FLAG_NONE)),
79 }
80 }
81
82 /// Marks the flag as cancelled with [`CancelKind::Terminate`] (generic cancel).
83 pub fn cancel(&self) {
84 self.cancel_with(CancelKind::Terminate);
85 }
86
87 /// Marks the flag as cancelled with an explicit signal kind.
88 ///
89 /// First writer wins; subsequent calls are no-ops (idempotent).
90 /// CAS uses `SeqCst` success/failure orderings (see type docs).
91 pub fn cancel_with(&self, kind: CancelKind) {
92 let v = match kind {
93 CancelKind::Interrupt => FLAG_INTERRUPT,
94 CancelKind::Terminate => FLAG_TERMINATE,
95 };
96 // SeqCst: publish first cancel kind with a total order vs loads in `check`.
97 let _ = self
98 .state
99 .compare_exchange(FLAG_NONE, v, Ordering::SeqCst, Ordering::SeqCst);
100 }
101
102 /// Returns whether cancellation was requested.
103 pub fn is_cancelled(&self) -> bool {
104 // SeqCst: observe any prior `cancel_with` from another task.
105 self.state.load(Ordering::SeqCst) != FLAG_NONE
106 }
107
108 /// Returns the stored kind when cancelled.
109 pub fn kind(&self) -> Option<CancelKind> {
110 // SeqCst: pair with `cancel_with` CAS (see type docs).
111 match self.state.load(Ordering::SeqCst) {
112 FLAG_INTERRUPT => Some(CancelKind::Interrupt),
113 FLAG_TERMINATE => Some(CancelKind::Terminate),
114 _ => None,
115 }
116 }
117
118 /// Returns [`AppError::interrupted`] or [`AppError::terminated`] when cancelled.
119 ///
120 /// # Errors
121 ///
122 /// Returns [`crate::error::ErrorKind::Interrupted`] or [`crate::error::ErrorKind::Terminated`] when the flag is set.
123 pub fn check(&self) -> AppResult<()> {
124 match self.kind() {
125 None => Ok(()),
126 Some(CancelKind::Interrupt) => Err(AppError::interrupted()),
127 Some(CancelKind::Terminate) => Err(AppError::terminated()),
128 }
129 }
130}
131
132/// Run a future with a wall-clock deadline.
133///
134/// # Errors
135///
136/// Returns [`crate::error::ErrorKind::Timeout`] when `deadline` elapses before `fut` completes.
137/// Propagates any error returned by `fut` itself.
138pub async fn with_wall_clock<T, F, Fut>(deadline: Duration, fut: F) -> AppResult<T>
139where
140 F: FnOnce() -> Fut,
141 Fut: Future<Output = AppResult<T>>,
142{
143 match timeout(deadline, fut()).await {
144 Ok(inner) => inner,
145 Err(_) => Err(AppError::of(ErrorDetail::WallClockTimeout {
146 secs: deadline.as_secs(),
147 })),
148 }
149}
150
151/// Race an operation against cancel signals and an optional wall-clock deadline.
152///
153/// # Cancel safety (`select!`)
154///
155/// - Cancel arm: `wait_for_cancel` only awaits signal `recv` / `ctrl_c` (Tokio
156/// signal futures are cancel-safe; losing a poll does not drop OS registration).
157/// - Op arm: dropping `op` mid-flight aborts the in-flight HTTP future; partial
158/// body buffers are dropped with the task (one-shot CLI — no shared mutable
159/// request state beyond `CancelFlag`, which is written only on cancel/timeout).
160/// - `biased` prefers the cancel arm so a ready signal is not starved by a ready `op`.
161///
162/// # Errors
163///
164/// Returns [`crate::error::ErrorKind::Timeout`] when `deadline` elapses first.
165/// Returns [`crate::error::ErrorKind::Interrupted`] on SIGINT / Ctrl-C.
166/// Returns [`crate::error::ErrorKind::Terminated`] on SIGTERM / SIGHUP / Ctrl+Break / Ctrl+Close.
167/// Propagates any error returned by `op`.
168pub async fn race_op_with_cancel_and_deadline<T, Fut>(
169 deadline: Duration,
170 cancel_flag: CancelFlag,
171 op: Fut,
172) -> AppResult<T>
173where
174 Fut: Future<Output = AppResult<T>>,
175{
176 tokio::pin!(op);
177 let cancel = wait_for_cancel();
178 tokio::pin!(cancel);
179
180 let timed = timeout(deadline, async {
181 tokio::select! {
182 biased;
183 kind = &mut cancel => {
184 cancel_flag.cancel_with(kind);
185 match kind {
186 CancelKind::Interrupt => Err(AppError::interrupted()),
187 CancelKind::Terminate => Err(AppError::terminated()),
188 }
189 }
190 res = &mut op => res,
191 }
192 });
193
194 match timed.await {
195 Ok(inner) => inner,
196 Err(_) => {
197 cancel_flag.cancel_with(CancelKind::Terminate);
198 Err(AppError::of(ErrorDetail::WallClockTimeout {
199 secs: deadline.as_secs(),
200 }))
201 }
202 }
203}
204
205/// Elapsed milliseconds since start.
206pub fn duration_ms(start: Instant) -> u64 {
207 start.elapsed().as_millis() as u64
208}
209
210/// Flush stdout and stderr best-effort (FINALIZE).
211pub fn flush_stdio() {
212 use std::io::Write;
213 let _ = std::io::stdout().flush();
214 let _ = std::io::stderr().flush();
215}
216
217/// Progress reporter: after `delay`, emit one localized line to stderr if still running.
218///
219/// `done` is an [`AtomicBool`](std::sync::atomic::AtomicBool) shared with a background task (not `Mutex<bool>`).
220/// Stores/loads use [`Ordering::SeqCst`] so `finish` is visible before the delayed
221/// write without relying on abort alone.
222///
223/// # Drop / non-orphan tasks
224///
225/// Tokio's [`JoinHandle`](tokio::task::JoinHandle) **detaches** the task on drop (does not abort). This guard
226/// implements [`Drop`] so early `?` returns and cancel races still abort the timer
227/// (Rules Rust: no orphan critical tasks; fixed fan-out of at most one progress task).
228pub struct ProgressGuard {
229 done: Arc<std::sync::atomic::AtomicBool>,
230 handle: Option<tokio::task::JoinHandle<()>>,
231}
232
233impl ProgressGuard {
234 /// Starts a delayed stderr progress line unless `quiet` is set.
235 pub fn start(quiet: bool, delay: Duration, message: String) -> Self {
236 let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
237 if quiet {
238 return Self { done, handle: None };
239 }
240 let flag = Arc::clone(&done);
241 let handle = tokio::spawn(async move {
242 tokio::time::sleep(delay).await;
243 // SeqCst: see `finish` / `Drop` store from the owner task.
244 if !flag.load(Ordering::SeqCst) {
245 use std::io::Write;
246 let _ = writeln!(std::io::stderr(), "{message}");
247 let _ = std::io::stderr().flush();
248 }
249 });
250 Self {
251 done,
252 handle: Some(handle),
253 }
254 }
255
256 /// Cancels the pending progress line and aborts the background task.
257 pub fn finish(mut self) {
258 self.shutdown();
259 }
260
261 fn shutdown(&mut self) {
262 // SeqCst: publish "done" before abort so a racing timer load never prints.
263 self.done.store(true, Ordering::SeqCst);
264 if let Some(h) = self.handle.take() {
265 h.abort();
266 }
267 }
268}
269
270impl Drop for ProgressGuard {
271 fn drop(&mut self) {
272 self.shutdown();
273 }
274}
275
276/// Helper future that polls cancel between retries (used by tests).
277pub struct CancelPoll<'a> {
278 flag: &'a CancelFlag,
279}
280
281impl Future for CancelPoll<'_> {
282 type Output = AppResult<()>;
283 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
284 Poll::Ready(self.flag.check())
285 }
286}