Skip to main content

hyperi_rustlib/
shutdown.rs

1// Project:   hyperi-rustlib
2// File:      src/shutdown.rs
3// Purpose:   Unified graceful shutdown with global CancellationToken
4// Language:  Rust
5//
6// License:   FSL-1.1-ALv2
7// Copyright: (c) 2026 HYPERI PTY LIMITED
8
9//! Unified graceful shutdown manager.
10//!
11//! Provides a global [`CancellationToken`] that all modules can listen on
12//! for coordinated graceful shutdown. One place handles SIGTERM/SIGINT,
13//! all modules drain gracefully.
14//!
15//! ## Usage
16//!
17//! ```rust,no_run
18//! use hyperi_rustlib::shutdown;
19//!
20//! #[tokio::main]
21//! async fn main() {
22//!     // Install the signal handler once at startup
23//!     let token = shutdown::install_signal_handler();
24//!
25//!     // Pass token to workers, or they can call shutdown::token() directly
26//!     tokio::spawn(async move {
27//!         loop {
28//!             tokio::select! {
29//!                 _ = token.cancelled() => {
30//!                     // drain and exit
31//!                     break;
32//!                 }
33//!                 _ = do_work() => {}
34//!             }
35//!         }
36//!     });
37//! }
38//!
39//! async fn do_work() {
40//!     tokio::time::sleep(std::time::Duration::from_secs(1)).await;
41//! }
42//! ```
43
44use std::sync::OnceLock;
45use tokio_util::sync::CancellationToken;
46
47static TOKEN: OnceLock<CancellationToken> = OnceLock::new();
48
49/// Get the global shutdown token.
50///
51/// All modules should clone this token and listen for cancellation
52/// in their main loops via `token.cancelled().await`.
53///
54/// The token is created lazily on first access.
55pub fn token() -> CancellationToken {
56    TOKEN.get_or_init(CancellationToken::new).clone()
57}
58
59/// Check if shutdown has been requested.
60pub fn is_shutdown() -> bool {
61    TOKEN.get().is_some_and(CancellationToken::is_cancelled)
62}
63
64/// Trigger shutdown programmatically.
65///
66/// Cancels the global token. All modules listening on it will
67/// begin their drain/cleanup sequence.
68pub fn trigger() {
69    if let Some(t) = TOKEN.get() {
70        t.cancel();
71    }
72}
73
74/// Wait for SIGTERM or SIGINT, then trigger shutdown.
75///
76/// Call this once at application startup. It spawns a background
77/// task that waits for the OS signal, then cancels the global token.
78///
79/// **K8s pre-stop compliance:** When running in Kubernetes (detected via
80/// [`crate::env::runtime_context`]), sleeps for `PRESTOP_DELAY_SECS`
81/// (default 5) before cancelling the token. This gives K8s time to
82/// remove the pod from Service endpoints before the app starts draining.
83/// On bare metal / Docker, the delay is 0 (immediate shutdown).
84///
85/// Returns the token for use in `tokio::select!` or other async
86/// shutdown coordination.
87#[must_use]
88pub fn install_signal_handler() -> CancellationToken {
89    let t = token();
90    let cancel = t.clone();
91
92    tokio::spawn(async move {
93        wait_for_signal().await;
94
95        // K8s pre-stop: delay before draining to allow endpoint removal.
96        // Without this, K8s routes traffic to a pod that's already shutting down.
97        let prestop_delay = prestop_delay_secs();
98        if prestop_delay > 0 {
99            #[cfg(feature = "logger")]
100            tracing::info!(
101                delay_secs = prestop_delay,
102                "Pre-stop delay: waiting for K8s endpoint removal"
103            );
104            tokio::time::sleep(std::time::Duration::from_secs(prestop_delay)).await;
105        }
106
107        cancel.cancel();
108
109        #[cfg(feature = "logger")]
110        tracing::info!("Shutdown signal received, cancelling all tasks");
111    });
112
113    t
114}
115
116/// Determine the pre-stop delay in seconds.
117///
118/// - `PRESTOP_DELAY_SECS` env var overrides (for tuning in deployment manifests)
119/// - K8s detected: default 5 seconds
120/// - Bare metal / Docker: default 0 (no delay)
121fn prestop_delay_secs() -> u64 {
122    if let Ok(val) = std::env::var("PRESTOP_DELAY_SECS")
123        && let Ok(secs) = val.parse::<u64>()
124    {
125        return secs;
126    }
127    if crate::env::runtime_context().is_kubernetes() {
128        5
129    } else {
130        0
131    }
132}
133
134/// Wait for SIGTERM or SIGINT.
135async fn wait_for_signal() {
136    let ctrl_c = async {
137        if let Err(e) = tokio::signal::ctrl_c().await {
138            tracing::error!(error = %e, "Failed to install Ctrl+C handler");
139            std::future::pending::<()>().await;
140        }
141    };
142
143    #[cfg(unix)]
144    let terminate = async {
145        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
146            Ok(mut sig) => {
147                sig.recv().await;
148            }
149            Err(e) => {
150                tracing::error!(
151                    error = %e,
152                    "Failed to install SIGTERM handler, only Ctrl+C will trigger shutdown"
153                );
154                std::future::pending::<()>().await;
155            }
156        }
157    };
158
159    #[cfg(unix)]
160    tokio::select! {
161        () = ctrl_c => {},
162        () = terminate => {},
163    }
164
165    #[cfg(not(unix))]
166    ctrl_c.await;
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn token_is_not_cancelled_initially() {
175        // Use a fresh token (not the global) to avoid test pollution
176        let t = CancellationToken::new();
177        assert!(!t.is_cancelled());
178    }
179
180    #[test]
181    fn trigger_cancels_token() {
182        let t = CancellationToken::new();
183        assert!(!t.is_cancelled());
184        t.cancel();
185        assert!(t.is_cancelled());
186    }
187
188    #[test]
189    fn token_is_cloneable_and_shared() {
190        let t = CancellationToken::new();
191        let c1 = t.clone();
192        let c2 = t.clone();
193
194        assert!(!c1.is_cancelled());
195        assert!(!c2.is_cancelled());
196
197        t.cancel();
198
199        assert!(c1.is_cancelled());
200        assert!(c2.is_cancelled());
201    }
202
203    #[test]
204    fn multiple_triggers_are_idempotent() {
205        let t = CancellationToken::new();
206        t.cancel();
207        t.cancel(); // second cancel should not panic
208        assert!(t.is_cancelled());
209    }
210
211    #[tokio::test]
212    async fn cancelled_future_resolves_after_cancel() {
213        let t = CancellationToken::new();
214        let c = t.clone();
215
216        tokio::spawn(async move {
217            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
218            c.cancel();
219        });
220
221        // This should resolve once the token is cancelled
222        t.cancelled().await;
223        assert!(t.is_cancelled());
224    }
225
226    #[tokio::test]
227    async fn child_token_cancelled_by_parent() {
228        let parent = CancellationToken::new();
229        let child = parent.child_token();
230
231        assert!(!child.is_cancelled());
232        parent.cancel();
233        assert!(child.is_cancelled());
234    }
235}