miden_node_utils/
shutdown.rs1use std::fmt::{self, Display, Formatter};
2use std::future::Future;
3use std::time::Duration;
4
5use anyhow::Context;
6use miden_node_tracing::{error, info};
7pub use tokio_util::sync::CancellationToken;
8
9pub const GRACE_PERIOD: Duration = Duration::from_secs(10);
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ShutdownSignal {
15 Interrupt,
16 Terminate,
17}
18
19impl Display for ShutdownSignal {
20 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
21 match self {
22 Self::Interrupt => f.write_str("SIGINT"),
23 Self::Terminate => f.write_str("SIGTERM"),
24 }
25 }
26}
27
28pub async fn run_with_shutdown<F, Fut>(service_name: &'static str, run: F) -> anyhow::Result<()>
34where
35 F: FnOnce(CancellationToken) -> Fut,
36 Fut: Future<Output = anyhow::Result<()>>,
37{
38 run_with_shutdown_signal(service_name, run, shutdown_signal()).await
39}
40
41async fn run_with_shutdown_signal<F, Fut, Signal>(
42 service_name: &'static str,
43 run: F,
44 signal: Signal,
45) -> anyhow::Result<()>
46where
47 F: FnOnce(CancellationToken) -> Fut,
48 Fut: Future<Output = anyhow::Result<()>>,
49 Signal: Future<Output = anyhow::Result<ShutdownSignal>>,
50{
51 let token = CancellationToken::new();
52 let service = run(token.clone());
53 tokio::pin!(service);
54 tokio::pin!(signal);
55
56 tokio::select! {
57 result = &mut service => result,
58 result = &mut signal => {
59 let signal = result?;
60 info!(target: "miden::process",
61 "Shutdown requested",
62 service.name = service_name,
63 shutdown.signal = signal.to_string()
64 );
65 token.cancel();
66
67 let Ok(result) = tokio::time::timeout(GRACE_PERIOD, &mut service).await else {
68 error!(
69 anyhow::anyhow!("graceful shutdown timed out"),
70 target: "miden::process",
71 "Graceful shutdown timed out; exiting process",
72 service.name = service_name,
73 shutdown.grace_period_ms = GRACE_PERIOD
74 );
75 std::process::exit(1);
76 };
77
78 result?;
79 info!(target: "miden::process","Shutdown complete", service.name = service_name);
80 Ok(())
81 },
82 }
83}
84
85pub async fn shutdown_signal() -> anyhow::Result<ShutdownSignal> {
87 #[cfg(unix)]
88 {
89 let mut terminate =
90 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
91 .context("failed to install SIGTERM handler")?;
92
93 tokio::select! {
94 _ = terminate.recv() => Ok(ShutdownSignal::Terminate),
95 result = tokio::signal::ctrl_c() => {
96 result
97 .context("failed to install Ctrl-C handler")
98 .map(|()| ShutdownSignal::Interrupt)
99 },
100 }
101 }
102
103 #[cfg(not(unix))]
104 {
105 tokio::signal::ctrl_c()
106 .await
107 .context("failed to install Ctrl-C handler")
108 .map(|()| ShutdownSignal::Interrupt)
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use std::sync::Arc;
115 use std::sync::atomic::{AtomicBool, Ordering};
116
117 use super::*;
118
119 #[tokio::test]
120 async fn signal_cancels_and_waits_for_service() {
121 let cancelled = Arc::new(AtomicBool::new(false));
122 let service_cancelled = Arc::clone(&cancelled);
123
124 run_with_shutdown_signal(
125 "test-service",
126 move |shutdown| async move {
127 shutdown.cancelled().await;
128 service_cancelled.store(true, Ordering::Relaxed);
129 Ok(())
130 },
131 std::future::ready(Ok(ShutdownSignal::Interrupt)),
132 )
133 .await
134 .expect("clean shutdown should succeed");
135
136 assert!(cancelled.load(Ordering::Relaxed));
137 }
138
139 #[tokio::test]
140 async fn signal_handler_error_is_propagated() {
141 let err = run_with_shutdown_signal(
142 "test-service",
143 |shutdown| async move {
144 shutdown.cancelled().await;
145 Ok(())
146 },
147 std::future::ready(Err(anyhow::anyhow!("signal handler failed"))),
148 )
149 .await
150 .expect_err("signal error should be returned");
151
152 assert_eq!(err.to_string(), "signal handler failed");
153 }
154}