diff --git a/crates/shared/cli-utils/README.md b/crates/shared/cli-utils/README.md index 3252be4e..4691c5e6 100644 --- a/crates/shared/cli-utils/README.md +++ b/crates/shared/cli-utils/README.md @@ -20,8 +20,7 @@ base-cli-utils = { git = "https://github.com/base/node-reth" } ``` ```rust,ignore -use base_cli_utils::{GlobalArgs, Version}; -use base_cli_utils::runtime::{build_runtime, run_until_ctrl_c}; +use base_cli_utils::{GlobalArgs, RuntimeManager, Version}; use clap::Parser; #[derive(Parser)] @@ -32,10 +31,12 @@ struct MyCli { fn main() -> eyre::Result<()> { Version::init(); - let cli = MyCli::parse(); + let _cli = MyCli::parse(); - let runtime = build_runtime()?; - runtime.block_on(run_until_ctrl_c(async { /* ... */ })) + RuntimeManager::run_until_ctrl_c(async { + // ... your async code ... + Ok(()) + }) } ``` diff --git a/crates/shared/cli-utils/src/runtime.rs b/crates/shared/cli-utils/src/runtime.rs index f8af5368..1b6d45b2 100644 --- a/crates/shared/cli-utils/src/runtime.rs +++ b/crates/shared/cli-utils/src/runtime.rs @@ -7,43 +7,27 @@ use std::future::Future; pub struct RuntimeManager; impl RuntimeManager { - /// Builds a multi-threaded Tokio runtime with all features enabled. - pub fn build_runtime() -> eyre::Result { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .map_err(|e| eyre::eyre!("Failed to build tokio runtime: {}", e)) + /// Creates a new default tokio multi-thread [Runtime](tokio::runtime::Runtime) with all + /// features enabled. + pub fn tokio_runtime() -> Result { + tokio::runtime::Builder::new_multi_thread().enable_all().build() } - /// Runs a future to completion, returning early on Ctrl+C. - pub async fn run_until_ctrl_c(fut: F) -> eyre::Result<()> - where - F: Future, - { - let ctrl_c = async { - tokio::signal::ctrl_c().await.expect("Failed to install Ctrl+C handler"); - }; - - tokio::select! { - biased; - () = ctrl_c => Ok(()), - () = fut => Ok(()), - } - } - - /// Runs a fallible future to completion, returning early on Ctrl+C. - pub async fn run_until_ctrl_c_fallible(fut: F) -> eyre::Result<()> + /// Run a fallible future until ctrl-c is pressed. + pub fn run_until_ctrl_c(fut: F) -> eyre::Result<()> where F: Future>, { - let ctrl_c = async { - tokio::signal::ctrl_c().await.expect("Failed to install Ctrl+C handler"); - }; - - tokio::select! { - biased; - () = ctrl_c => Ok(()), - result = fut => result, - } + let rt = Self::tokio_runtime().map_err(|e| eyre::eyre!(e))?; + rt.block_on(async move { + tokio::select! { + biased; + _ = tokio::signal::ctrl_c() => { + tracing::info!(target: "cli", "Received Ctrl-C, shutting down..."); + Ok(()) + } + res = fut => res, + } + }) } }