1#![doc(
4 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10
11use reth_tasks::{PanickedTaskError, TaskExecutor};
14use std::{
15 future::Future,
16 pin::{pin, Pin},
17 sync::mpsc,
18 time::Duration,
19};
20use tokio::task::JoinHandle;
21use tracing::{debug, error, info};
22
23#[derive(Debug)]
27pub struct CliRunner {
28 config: CliRunnerConfig,
29 runtime: reth_tasks::Runtime,
30}
31
32impl CliRunner {
33 pub fn try_default_runtime() -> Result<Self, reth_tasks::RuntimeBuildError> {
38 Self::try_with_runtime_config(reth_tasks::RuntimeConfig::default())
39 }
40
41 pub fn try_with_runtime_config(
43 config: reth_tasks::RuntimeConfig,
44 ) -> Result<Self, reth_tasks::RuntimeBuildError> {
45 let runtime = reth_tasks::RuntimeBuilder::new(config).build()?;
46 Ok(Self { config: CliRunnerConfig::default(), runtime })
47 }
48
49 pub const fn with_config(mut self, config: CliRunnerConfig) -> Self {
51 self.config = config;
52 self
53 }
54
55 pub fn runtime(&self) -> reth_tasks::Runtime {
57 self.runtime.clone()
58 }
59
60 pub fn block_on<F, T>(&self, fut: F) -> T
62 where
63 F: Future<Output = T>,
64 {
65 self.runtime.handle().block_on(Box::pin(fut) as Pin<Box<dyn Future<Output = T> + '_>>)
66 }
67
68 pub fn run_command_until_exit<F, E>(
75 self,
76 command: impl FnOnce(CliContext) -> F,
77 ) -> Result<(), E>
78 where
79 F: Future<Output = Result<(), E>>,
80 E: Send
81 + Sync
82 + std::fmt::Display
83 + From<std::io::Error>
84 + From<reth_tasks::PanickedTaskError>
85 + 'static,
86 {
87 let (context, task_manager_handle) = cli_context(&self.runtime);
88 self.run_until_exit(task_manager_handle, Box::pin(command(context)))
89 }
90
91 fn run_until_exit<E>(
93 self,
94 task_manager_handle: JoinHandle<Result<(), PanickedTaskError>>,
95 command: Pin<Box<dyn Future<Output = Result<(), E>> + '_>>,
96 ) -> Result<(), E>
97 where
98 E: Send
99 + Sync
100 + std::fmt::Display
101 + From<std::io::Error>
102 + From<reth_tasks::PanickedTaskError>
103 + 'static,
104 {
105 let command_res = self.runtime.handle().block_on(run_to_completion_or_panic(
107 task_manager_handle,
108 run_until_ctrl_c_if(self.config.handle_signals, command),
109 ));
110
111 if let Err(err) = &command_res {
112 error!(target: "reth::cli", %err, "shutting down due to error");
113 } else {
114 debug!(target: "reth::cli", "shutting down gracefully");
115 self.runtime.graceful_shutdown_with_timeout(self.config.graceful_shutdown_timeout);
119 }
120
121 runtime_shutdown(self.runtime, true);
122
123 command_res
124 }
125
126 pub fn run_blocking_command_until_exit<F, E>(
130 self,
131 command: impl FnOnce(CliContext) -> F + Send + 'static,
132 ) -> Result<(), E>
133 where
134 F: Future<Output = Result<(), E>> + Send + 'static,
135 E: Send
136 + Sync
137 + std::fmt::Display
138 + From<std::io::Error>
139 + From<reth_tasks::PanickedTaskError>
140 + 'static,
141 {
142 self.run_blocking_until_exit(Box::new(move |context| Box::pin(command(context))))
143 }
144
145 fn run_blocking_until_exit<E>(
148 self,
149 command: Box<dyn FnOnce(CliContext) -> BoxedCommand<E> + Send>,
150 ) -> Result<(), E>
151 where
152 E: Send
153 + Sync
154 + std::fmt::Display
155 + From<std::io::Error>
156 + From<reth_tasks::PanickedTaskError>
157 + 'static,
158 {
159 let (context, task_manager_handle) = cli_context(&self.runtime);
160
161 let handle = self.runtime.handle().clone();
163 let command_handle = self.runtime.spawn_blocking(move || handle.block_on(command(context)));
164
165 let command_res = self.runtime.handle().block_on(run_to_completion_or_panic(
167 task_manager_handle,
168 run_until_ctrl_c_if(self.config.handle_signals, async move {
169 command_handle.await.expect("Failed to join blocking task")
170 }),
171 ));
172
173 if let Err(err) = &command_res {
174 error!(target: "reth::cli", %err, "shutting down due to error");
175 } else {
176 debug!(target: "reth::cli", "shutting down gracefully");
177 self.runtime.graceful_shutdown_with_timeout(self.config.graceful_shutdown_timeout);
178 }
179
180 runtime_shutdown(self.runtime, true);
181
182 command_res
183 }
184
185 pub fn run_until_ctrl_c<F, E>(self, fut: F) -> Result<(), E>
187 where
188 F: Future<Output = Result<(), E>>,
189 E: Send + Sync + From<std::io::Error> + 'static,
190 {
191 self.runtime.handle().block_on(run_until_ctrl_c(
192 Box::pin(fut) as Pin<Box<dyn Future<Output = Result<(), E>> + '_>>
193 ))?;
194 Ok(())
195 }
196
197 pub fn run_blocking_until_ctrl_c<F, E>(self, fut: F) -> Result<(), E>
202 where
203 F: Future<Output = Result<(), E>> + Send + 'static,
204 E: Send + Sync + From<std::io::Error> + 'static,
205 {
206 self.run_blocking_until_ctrl_c_boxed(Box::pin(fut))
207 }
208
209 fn run_blocking_until_ctrl_c_boxed<E>(self, fut: BoxedCommand<E>) -> Result<(), E>
210 where
211 E: Send + Sync + From<std::io::Error> + 'static,
212 {
213 let handle = self.runtime.handle().clone();
214 let fut = self.runtime.spawn_blocking(move || handle.block_on(fut));
215 self.runtime
216 .handle()
217 .block_on(run_until_ctrl_c(async move { fut.await.expect("Failed to join task") }))?;
218
219 runtime_shutdown(self.runtime, false);
220
221 Ok(())
222 }
223}
224
225type BoxedCommand<E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send>>;
227
228fn cli_context(
230 runtime: &reth_tasks::Runtime,
231) -> (CliContext, JoinHandle<Result<(), PanickedTaskError>>) {
232 let handle =
233 runtime.take_task_manager_handle().expect("Runtime must contain a TaskManager handle");
234 let context = CliContext { task_executor: runtime.clone() };
235 (context, handle)
236}
237
238#[derive(Debug)]
240pub struct CliContext {
241 pub task_executor: TaskExecutor,
243}
244
245const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
247
248#[derive(Debug, Clone)]
250pub struct CliRunnerConfig {
251 pub graceful_shutdown_timeout: Duration,
256 pub handle_signals: bool,
263}
264
265impl Default for CliRunnerConfig {
266 fn default() -> Self {
267 Self::new()
268 }
269}
270
271impl CliRunnerConfig {
272 pub const fn new() -> Self {
274 Self { graceful_shutdown_timeout: DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT, handle_signals: true }
275 }
276
277 pub const fn with_graceful_shutdown_timeout(mut self, timeout: Duration) -> Self {
279 self.graceful_shutdown_timeout = timeout;
280 self
281 }
282
283 pub const fn with_signal_handling(mut self, handle_signals: bool) -> Self {
287 self.handle_signals = handle_signals;
288 self
289 }
290}
291
292async fn run_to_completion_or_panic<F, E>(
296 task_manager_handle: JoinHandle<Result<(), PanickedTaskError>>,
297 fut: F,
298) -> Result<(), E>
299where
300 F: Future<Output = Result<(), E>>,
301 E: Send + Sync + From<reth_tasks::PanickedTaskError> + 'static,
302{
303 let fut = pin!(fut);
304 tokio::select! {
305 task_manager_result = task_manager_handle => {
306 if let Ok(Err(panicked_error)) = task_manager_result {
307 return Err(panicked_error.into());
308 }
309 },
310 res = fut => res?,
311 }
312 Ok(())
313}
314
315async fn run_until_ctrl_c_if<F, E>(handle_signals: bool, fut: F) -> Result<(), E>
318where
319 F: Future<Output = Result<(), E>>,
320 E: Send + Sync + 'static + From<std::io::Error>,
321{
322 if handle_signals {
323 run_until_ctrl_c(fut).await
324 } else {
325 fut.await
326 }
327}
328
329async fn run_until_ctrl_c<F, E>(fut: F) -> Result<(), E>
333where
334 F: Future<Output = Result<(), E>>,
335 E: Send + Sync + 'static + From<std::io::Error>,
336{
337 let ctrl_c = tokio::signal::ctrl_c();
338
339 #[cfg(unix)]
340 {
341 let mut stream = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
342 let sigterm = stream.recv();
343 let sigterm = pin!(sigterm);
344 let ctrl_c = pin!(ctrl_c);
345 let fut = pin!(fut);
346
347 tokio::select! {
348 _ = ctrl_c => {
349 info!(target: "reth::cli", "Received ctrl-c");
350 },
351 _ = sigterm => {
352 info!(target: "reth::cli", "Received SIGTERM");
353 },
354 res = fut => res?,
355 }
356 }
357
358 #[cfg(not(unix))]
359 {
360 let ctrl_c = pin!(ctrl_c);
361 let fut = pin!(fut);
362
363 tokio::select! {
364 _ = ctrl_c => {
365 info!(target: "reth::cli", "Received ctrl-c");
366 },
367 res = fut => res?,
368 }
369 }
370
371 Ok(())
372}
373
374const DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
376
377fn runtime_shutdown(rt: reth_tasks::Runtime, wait: bool) {
382 let (tx, rx) = mpsc::channel();
383 std::thread::Builder::new()
384 .name("rt-shutdown".to_string())
385 .spawn(move || {
386 rt.shutdown_timeout(DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT);
387 let _ = tx.send(());
388 })
389 .unwrap();
390
391 if wait {
392 let _ = rx.recv_timeout(DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT).inspect_err(|err| {
393 tracing::warn!(target: "reth::cli", %err, "runtime shutdown timed out");
394 });
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use super::*;
401
402 #[test]
403 fn runtime_shutdown_stops_tasks_with_live_runtime_clones() {
404 let runtime = reth_tasks::Runtime::test();
405 let retained = runtime.clone();
406 let task_runtime = runtime.clone();
407 let (started, ready) = mpsc::channel();
408 let task = runtime.handle().spawn(async move {
409 let _runtime = task_runtime;
410 started.send(()).unwrap();
411 std::future::pending::<()>().await;
412 });
413 ready.recv_timeout(Duration::from_secs(5)).unwrap();
414
415 runtime_shutdown(runtime, true);
416
417 assert!(task.is_finished(), "shutdown returned while a task still owned the runtime");
418 assert!(retained.handle().block_on(task).unwrap_err().is_cancelled());
419 }
420
421 #[cfg(unix)]
422 #[test]
423 fn command_outlives_signal_without_signal_handling() {
424 let runner = CliRunner::try_default_runtime()
425 .unwrap()
426 .with_config(CliRunnerConfig::new().with_signal_handling(false));
427 let mut ran_after_signal = false;
428 let res: Result<(), Box<dyn std::error::Error + Send + Sync>> = runner
429 .run_command_until_exit(|_| async {
430 let mut sigterm =
431 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
432 assert_eq!(unsafe { libc::raise(libc::SIGTERM) }, 0);
434 sigterm.recv().await;
435 tokio::time::sleep(Duration::from_millis(100)).await;
437 ran_after_signal = true;
438 Ok(())
439 });
440 res.unwrap();
441 assert!(ran_after_signal, "runner stopped the command on SIGTERM");
442 }
443}