1use crate::{
2 interface::{Commands, NoSubCmd},
3 Cli,
4};
5use clap::Subcommand;
6use eyre::{eyre, Result};
7use reth_chainspec::{ChainSpec, EthChainSpec, Hardforks};
8use reth_cli::chainspec::ChainSpecParser;
9use reth_cli_commands::{
10 common::{CliComponentsBuilder, CliNodeTypes, HeaderMut},
11 launcher::{FnLauncher, Launcher},
12};
13use reth_cli_runner::{CliRunner, CliRunnerConfig};
14use reth_db::DatabaseEnv;
15use reth_node_api::NodePrimitives;
16use reth_node_builder::{NodeBuilder, WithLaunchContext};
17use reth_node_ethereum::{consensus::EthBeaconConsensus, EthereumNode};
18use reth_node_metrics::recorder::install_prometheus_recorder;
19use reth_rpc_server_types::RpcModuleValidator;
20use reth_tasks::RayonConfig;
21use reth_tracing::{Layers, TracingGuards};
22use std::{fmt, sync::Arc};
23
24#[derive(Debug)]
26pub struct CliApp<
27 Spec: ChainSpecParser,
28 Ext: clap::Args + fmt::Debug,
29 Rpc: RpcModuleValidator,
30 SubCmd: Subcommand + fmt::Debug = NoSubCmd,
31> {
32 cli: Cli<Spec, Ext, Rpc, SubCmd>,
33 runner: Option<CliRunner>,
34 runner_config: Option<CliRunnerConfig>,
35 layers: Option<Layers>,
36 guard: Option<TracingGuards>,
37}
38
39impl<C, Ext, Rpc, SubCmd> CliApp<C, Ext, Rpc, SubCmd>
40where
41 C: ChainSpecParser,
42 Ext: clap::Args + fmt::Debug,
43 Rpc: RpcModuleValidator,
44 SubCmd: ExtendedCommand + Subcommand + fmt::Debug,
45{
46 pub(crate) fn new(cli: Cli<C, Ext, Rpc, SubCmd>) -> Self {
47 Self { cli, runner: None, runner_config: None, layers: Some(Layers::new()), guard: None }
48 }
49
50 pub fn set_runner(&mut self, runner: CliRunner) {
54 self.runner = Some(runner);
55 }
56
57 pub const fn set_runner_config(&mut self, config: CliRunnerConfig) {
63 self.runner_config = Some(config);
64 }
65
66 pub fn access_tracing_layers(&mut self) -> Result<&mut Layers> {
71 self.layers.as_mut().ok_or_else(|| eyre!("Tracing already initialized"))
72 }
73
74 pub fn run(self, launcher: impl Launcher<C, Ext>) -> Result<()>
79 where
80 C: ChainSpecParser<ChainSpec = ChainSpec>,
81 {
82 let jit_args = match &self.cli.command {
83 Commands::ReExecute(cmd) => cmd.jit.clone(),
84 _ => Default::default(),
85 };
86
87 let components = move |spec: Arc<ChainSpec>| {
88 let (evm_config, _) =
89 reth_node_ethereum::node::build_evm_config(spec.clone(), &jit_args, None)
90 .expect("failed to build EVM config");
91 (evm_config, Arc::new(EthBeaconConsensus::new(spec)))
92 };
93
94 self.run_with_components::<EthereumNode>(components, async move |builder, ext| {
95 launcher.entrypoint(builder, ext).await
96 })
97 }
98
99 pub fn run_with_components<N>(
105 mut self,
106 components: impl CliComponentsBuilder<N>,
107 launcher: impl AsyncFnOnce(
108 WithLaunchContext<NodeBuilder<DatabaseEnv, C::ChainSpec>>,
109 Ext,
110 ) -> Result<()>,
111 ) -> Result<()>
112 where
113 N: CliNodeTypes<Primitives: NodePrimitives<BlockHeader: HeaderMut>, ChainSpec: Hardforks>,
114 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
115 {
116 let runner = match self.runner.take() {
117 Some(runner) => runner,
118 None => {
119 let runtime_config = match &self.cli.command {
120 Commands::Node(command) => {
121 let config = reth_tasks::RuntimeConfig::default().with_rayon(RayonConfig {
122 reserved_cpu_cores: command.engine.reserved_cpu_cores,
123 proof_storage_worker_threads: command.engine.storage_worker_count,
124 proof_account_worker_threads: command.engine.account_worker_count,
125 prewarming_threads: command.engine.prewarming_threads,
126 ..Default::default()
127 });
128 if let Some(cpu_cores) = command.engine.cpu_cores {
129 config.with_cpu_cores(cpu_cores)
130 } else {
131 config
132 }
133 }
134 _ => reth_tasks::RuntimeConfig::default(),
135 };
136 let runner = CliRunner::try_with_runtime_config(runtime_config)?;
137 match self.runner_config.take() {
138 Some(config) => runner.with_config(config),
139 None => runner,
140 }
141 }
142 };
143
144 if let Some(chain_spec) = self.cli.command.chain_spec() {
146 self.cli.logs.log_file_directory =
147 self.cli.logs.log_file_directory.join(chain_spec.chain().to_string());
148 }
149
150 if matches!(self.cli.command, Commands::Node(_)) {
152 self.cli.logs.apply_node_defaults();
153 }
154
155 self.init_tracing(&runner)?;
156
157 reth_tasks::utils::deprioritize_background_threads();
159
160 let recorder = install_prometheus_recorder();
162 runner.block_on(async { recorder.spawn_upkeep() });
163
164 run_commands_with::<C, Ext, Rpc, N, SubCmd>(self.cli, runner, components, launcher)
165 }
166
167 pub fn init_tracing(&mut self, runner: &CliRunner) -> Result<()> {
171 if let Some(layers) = self.layers.take() {
172 self.guard = Some(self.cli.init_tracing(runner, layers)?);
173 }
174
175 Ok(())
176 }
177}
178
179pub(crate) fn run_commands_with<C, Ext, Rpc, N, SubCmd>(
182 cli: Cli<C, Ext, Rpc, SubCmd>,
183 runner: CliRunner,
184 components: impl CliComponentsBuilder<N>,
185 launcher: impl AsyncFnOnce(
186 WithLaunchContext<NodeBuilder<DatabaseEnv, C::ChainSpec>>,
187 Ext,
188 ) -> Result<()>,
189) -> Result<()>
190where
191 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
192 Ext: clap::Args + fmt::Debug,
193 Rpc: RpcModuleValidator,
194 N: CliNodeTypes<Primitives: NodePrimitives<BlockHeader: HeaderMut>, ChainSpec: Hardforks>,
195 SubCmd: ExtendedCommand + Subcommand + fmt::Debug,
196{
197 let rt = runner.runtime();
198
199 match cli.command {
200 Commands::Node(command) => {
201 if let Some(http_api) = &command.rpc.http_api {
203 Rpc::validate_selection(http_api, "http.api").map_err(|e| eyre!("{e}"))?;
204 }
205 if let Some(ws_api) = &command.rpc.ws_api {
206 Rpc::validate_selection(ws_api, "ws.api").map_err(|e| eyre!("{e}"))?;
207 }
208
209 runner.run_command_until_exit(|ctx| {
210 command.execute(ctx, FnLauncher::new::<C, Ext>(launcher))
211 })
212 }
213 Commands::Init(command) => runner.run_blocking_until_ctrl_c(command.execute::<N>(rt)),
214 Commands::InitState(command) => runner.run_blocking_until_ctrl_c(command.execute::<N>(rt)),
215 Commands::Import(command) => {
216 runner.run_blocking_until_ctrl_c(command.execute::<N, _>(components, rt))
217 }
218 Commands::ImportEra(command) => runner.run_blocking_until_ctrl_c(command.execute::<N>(rt)),
219 Commands::ExportEra(command) => runner.run_blocking_until_ctrl_c(command.execute::<N>(rt)),
220 Commands::DumpGenesis(command) => runner.run_blocking_until_ctrl_c(command.execute()),
221 Commands::Db(command) => {
222 runner.run_blocking_command_until_exit(|ctx| command.execute::<N>(ctx))
223 }
224 Commands::Download(command) => runner
225 .run_blocking_until_ctrl_c(async move { command.execute::<N>().await.map(|_| ()) }),
226 Commands::SnapshotManifest(command) => command.execute(),
227 Commands::Stage(command) => {
228 runner.run_command_until_exit(|ctx| command.execute::<N, _>(ctx, components))
229 }
230 Commands::P2P(command) => runner.run_until_ctrl_c(command.execute::<N>()),
231 Commands::Config(command) => runner.run_until_ctrl_c(command.execute()),
232 Commands::Prune(command) => runner.run_command_until_exit(|ctx| command.execute::<N>(ctx)),
233 #[cfg(feature = "dev")]
234 Commands::TestVectors(command) => runner.run_until_ctrl_c(command.execute()),
235 Commands::ReExecute(command) => {
236 runner.run_until_ctrl_c(command.execute::<N>(components, rt))
237 }
238 Commands::Ext(command) => command.execute(runner),
239 }
240}
241
242pub trait ExtendedCommand {
247 fn execute(self, runner: CliRunner) -> Result<()>;
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use crate::chainspec::EthereumChainSpecParser;
255 use clap::Parser;
256 use reth_cli_commands::node::NoArgs;
257
258 #[test]
259 fn test_cli_app_creation() {
260 let args = vec!["reth", "config"];
261 let cli = Cli::<EthereumChainSpecParser, NoArgs>::try_parse_from(args).unwrap();
262 let app = cli.configure();
263
264 assert!(app.runner.is_none());
266 assert!(app.layers.is_some());
267 assert!(app.guard.is_none());
268 }
269
270 #[test]
271 fn test_set_runner() {
272 let args = vec!["reth", "config"];
273 let cli = Cli::<EthereumChainSpecParser, NoArgs>::try_parse_from(args).unwrap();
274 let mut app = cli.configure();
275
276 if let Ok(runner) = CliRunner::try_default_runtime() {
278 app.set_runner(runner);
279 assert!(app.runner.is_some());
280 }
281 }
282
283 #[test]
284 fn test_access_tracing_layers() {
285 let args = vec!["reth", "config"];
286 let cli = Cli::<EthereumChainSpecParser, NoArgs>::try_parse_from(args).unwrap();
287 let mut app = cli.configure();
288
289 assert!(app.access_tracing_layers().is_ok());
291
292 app.layers = None;
294 assert!(app.access_tracing_layers().is_err());
295 }
296}