Skip to main content

hyperi_rustlib/cli/
app.rs

1// Project:   hyperi-rustlib
2// File:      src/cli/app.rs
3// Purpose:   DfeApp trait and standard lifecycle runner
4// Language:  Rust
5//
6// License:   FSL-1.1-ALv2
7// Copyright: (c) 2026 HYPERI PTY LIMITED
8
9//! Application trait and lifecycle runner for DFE services.
10//!
11//! Provides the standard startup sequence: parse → log → config → dispatch.
12//!
13//! ## Example
14//!
15//! ```rust,ignore
16//! use hyperi_rustlib::cli::{CommonArgs, DfeApp, CliError, VersionInfo, run_app};
17//!
18//! struct MyApp { common: CommonArgs }
19//!
20//! impl DfeApp for MyApp {
21//!     type Config = MyConfig;
22//!
23//!     fn name(&self) -> &str { "my-service" }
24//!     fn env_prefix(&self) -> &str { "MY_SERVICE" }
25//!     fn version_info(&self) -> VersionInfo {
26//!         VersionInfo::new("my-service", env!("CARGO_PKG_VERSION"))
27//!     }
28//!     fn common_args(&self) -> &CommonArgs { &self.common }
29//!     fn load_config(&self, path: Option<&str>) -> Result<MyConfig, CliError> { todo!() }
30//!     async fn run_service(&self, config: MyConfig) -> Result<(), CliError> { todo!() }
31//! }
32//! ```
33
34use std::fmt::Debug;
35
36use serde::de::DeserializeOwned;
37
38use super::error::CliError;
39use super::version::VersionInfo;
40use super::{CommonArgs, StandardCommand, output};
41
42/// Trait for DFE service applications.
43///
44/// Implement this trait to get the standard CLI lifecycle for free.
45/// The 80% common behaviour (logging, config, metrics, version) is handled
46/// by `run_app()`. Your app provides the 20% (config type, service logic).
47pub trait DfeApp: Sized {
48    /// Application-specific configuration type.
49    type Config: DeserializeOwned + Debug + Send + Sync;
50
51    /// Service name (e.g. "dfe-loader").
52    fn name(&self) -> &str;
53
54    /// Environment variable prefix for config cascade (e.g. "DFE_LOADER").
55    fn env_prefix(&self) -> &str;
56
57    /// Version information for this service.
58    fn version_info(&self) -> VersionInfo;
59
60    /// Access the common CLI arguments.
61    fn common_args(&self) -> &CommonArgs;
62
63    /// Resolve the active subcommand.
64    ///
65    /// Returns `None` to default to `StandardCommand::Run`.
66    fn command(&self) -> Option<&StandardCommand> {
67        None
68    }
69
70    /// Load application configuration from the given path (or defaults).
71    ///
72    /// # Errors
73    ///
74    /// Returns `CliError` if configuration cannot be loaded or parsed.
75    fn load_config(&self, path: Option<&str>) -> Result<Self::Config, CliError>;
76
77    /// Run the main service loop.
78    ///
79    /// Called after logging, config, and [`ServiceRuntime`](super::ServiceRuntime)
80    /// are initialised. The runtime contains all common infrastructure (metrics,
81    /// memory guard, shutdown token, worker pool, scaling pressure). Apps just
82    /// use it -- no boilerplate needed.
83    ///
84    /// # Errors
85    ///
86    /// Returns `CliError` if the service encounters a fatal error.
87    fn run_service(
88        &self,
89        config: Self::Config,
90        runtime: super::ServiceRuntime,
91    ) -> impl std::future::Future<Output = Result<(), CliError>> + Send;
92
93    /// Provide scaling pressure components for KEDA autoscaling.
94    ///
95    /// Override to register app-specific scaling signals (buffer depth,
96    /// consumer lag, error rate, etc.). The default returns an empty vec.
97    #[cfg(feature = "scaling")]
98    fn scaling_components(&self, _config: &Self::Config) -> Vec<crate::ScalingComponent> {
99        vec![]
100    }
101
102    /// Register all metrics for this service.
103    ///
104    /// Called by `metrics-manifest` and `generate-artefacts` subcommands to
105    /// capture the full metric catalogue without starting the service.
106    /// The default implementation is a no-op. Override to register
107    /// `DfeMetrics`, metric groups, and app-specific metrics.
108    #[cfg(any(feature = "metrics", feature = "otel-metrics"))]
109    fn register_metrics(&self, _manager: &crate::metrics::MetricsManager) {}
110
111    /// Build the deployment contract for this service.
112    ///
113    /// Called by `generate-artefacts` to produce container specs, health
114    /// endpoints, KEDA config, and metrics manifest. The default returns
115    /// `None`. Override to provide a contract.
116    #[cfg(feature = "deployment")]
117    fn deployment_contract(&self) -> Option<crate::deployment::DeploymentContract> {
118        None
119    }
120}
121
122/// Drive the standard DFE service lifecycle.
123///
124/// Handles subcommand dispatch:
125/// - `run` (default): init logger → load config → run service
126/// - `version`: print version info and exit
127/// - `config-check`: load config, validate, print summary
128///
129/// # Errors
130///
131/// Returns `CliError` if any lifecycle step fails.
132pub async fn run_app<A: DfeApp>(app: A) -> Result<(), CliError> {
133    let command = app.command().cloned().unwrap_or(StandardCommand::Run);
134    let args = app.common_args();
135
136    match command {
137        StandardCommand::Version => {
138            let info = app.version_info();
139            println!("{info}");
140            Ok(())
141        }
142
143        StandardCommand::ConfigCheck => {
144            // Initialise logger for config-check output
145            init_logger(args)?;
146
147            let config_path = args.config.as_deref();
148            match app.load_config(config_path) {
149                Ok(config) => {
150                    output::print_success("configuration is valid");
151                    if !args.quiet {
152                        eprintln!();
153                        output::print_kv("service", &app.name());
154                        output::print_kv("config", &config_path.unwrap_or("(defaults)"));
155                        output::print_kv("log_level", &args.effective_log_level());
156                        output::print_kv("log_format", &args.log_format);
157                        output::print_kv("metrics_addr", &args.metrics_addr);
158                        eprintln!();
159                        // Run the Debug dump through the logger's
160                        // sensitive-field masker before printing. Consumer
161                        // configs commonly hold ENV-sourced secrets in
162                        // plain `String` fields (the canonical K8s
163                        // secret-store -> K8s Secret -> ENV path) -- without
164                        // masking, `{config:#?}` happily prints them in
165                        // clear text. The masker recognises the standard
166                        // sensitive field names (password, token, api_key,
167                        // secret, bearer, etc.) and replaces the value
168                        // with `[REDACTED]`.
169                        //
170                        // The masker lives in the logger module; if the
171                        // consumer hasn't enabled the `logger` feature
172                        // they're already opting out of every other
173                        // sensitive-field defence (log masking, etc.), so
174                        // an unmasked Debug print here is consistent with
175                        // the rest of their stance.
176                        let raw = format!("{config:#?}");
177                        #[cfg(feature = "logger")]
178                        let masked = {
179                            let default_fields = crate::logger::default_sensitive_fields();
180                            let patterns: Vec<&str> =
181                                default_fields.iter().map(String::as_str).collect();
182                            crate::logger::mask_sensitive_string(&raw, &patterns)
183                        };
184                        #[cfg(not(feature = "logger"))]
185                        let masked = raw;
186                        eprintln!("  config: {masked}");
187                    }
188                    Ok(())
189                }
190                Err(e) => {
191                    output::print_error(&format!("configuration invalid: {e}"));
192                    Err(e)
193                }
194            }
195        }
196
197        #[cfg(any(feature = "metrics", feature = "otel-metrics"))]
198        StandardCommand::MetricsManifest => {
199            let mgr = crate::metrics::MetricsManager::new(app.name());
200            app.register_metrics(&mgr);
201            let manifest = mgr.registry().manifest();
202            println!(
203                "{}",
204                serde_json::to_string_pretty(&manifest)
205                    .map_err(|e| CliError::Service(format!("JSON serialisation failed: {e}")))?
206            );
207            Ok(())
208        }
209        #[cfg(not(any(feature = "metrics", feature = "otel-metrics")))]
210        StandardCommand::MetricsManifest => {
211            output::print_error("metrics feature not enabled -- no manifest available");
212            Err(CliError::Service("metrics feature not enabled".into()))
213        }
214
215        StandardCommand::GenerateArtefacts(ref artefact_args) => {
216            generate_artefacts(&app, artefact_args)?;
217            Ok(())
218        }
219
220        StandardCommand::Run => {
221            let version_info = app.version_info();
222            init_logger_for_service(args, app.name(), &version_info.version)?;
223
224            tracing::info!(
225                service = app.name(),
226                version = version_info.version,
227                "starting service"
228            );
229
230            let config_path = args.config.as_deref();
231            let config = app.load_config(config_path)?;
232
233            tracing::debug!(?config, "configuration loaded");
234
235            // Build ServiceRuntime -- all common infrastructure for free
236            let commit = option_env!("GIT_COMMIT").unwrap_or("unknown");
237            let runtime = super::ServiceRuntime::build(
238                app.name(),
239                app.env_prefix(),
240                &args.metrics_addr,
241                &version_info.version,
242                commit,
243                #[cfg(feature = "scaling")]
244                app.scaling_components(&config),
245            )
246            .await?;
247
248            app.run_service(config, runtime).await
249        }
250
251        #[cfg(feature = "top")]
252        StandardCommand::Top(ref top_args) => {
253            let top_config = crate::top::TopConfig::from_args(top_args);
254            crate::top::run_top(&top_config).map_err(|e| CliError::Service(e.to_string()))
255        }
256    }
257}
258
259/// Initialise the logger from CLI arguments.
260#[cfg(feature = "logger")]
261fn init_logger(args: &CommonArgs) -> Result<(), CliError> {
262    let opts = args.to_logger_options()?;
263    crate::logger::setup(opts)?;
264    Ok(())
265}
266
267/// Initialise the logger with service name and version injected into JSON output.
268#[cfg(feature = "logger")]
269fn init_logger_for_service(
270    args: &CommonArgs,
271    service_name: &str,
272    service_version: &str,
273) -> Result<(), CliError> {
274    let opts = args.to_logger_options()?;
275    crate::logger::setup(crate::logger::LoggerOptions {
276        service_name: Some(service_name.to_string()),
277        service_version: Some(service_version.to_string()),
278        ..opts
279    })?;
280    Ok(())
281}
282
283/// Initialise the logger from CLI arguments (no-op without logger feature).
284#[cfg(not(feature = "logger"))]
285fn init_logger(_args: &CommonArgs) -> Result<(), CliError> {
286    Ok(())
287}
288
289/// Initialise the logger with service name and version (no-op without logger feature).
290#[cfg(not(feature = "logger"))]
291fn init_logger_for_service(
292    _args: &CommonArgs,
293    _service_name: &str,
294    _service_version: &str,
295) -> Result<(), CliError> {
296    Ok(())
297}
298
299/// Generate all CI artefacts for this service.
300///
301/// Produces metrics manifest, deployment contract, and container spec
302/// in the output directory. Files are deterministic -- running twice produces
303/// identical output (no timestamps that change between runs).
304fn generate_artefacts<A: DfeApp>(
305    app: &A,
306    args: &super::commands::GenerateArtefactsArgs,
307) -> Result<(), CliError> {
308    let output_dir = std::path::Path::new(&args.output_dir);
309    std::fs::create_dir_all(output_dir)
310        .map_err(|e| CliError::Service(format!("failed to create output dir: {e}")))?;
311
312    let mut generated: Vec<String> = Vec::new();
313
314    // Metrics manifest
315    #[cfg(any(feature = "metrics", feature = "otel-metrics"))]
316    {
317        let mgr = crate::metrics::MetricsManager::new(app.name());
318        app.register_metrics(&mgr);
319        let manifest = mgr.registry().manifest();
320        let path = output_dir.join("metrics-manifest.json");
321        let json = serde_json::to_string_pretty(&manifest)
322            .map_err(|e| CliError::Service(format!("metrics manifest JSON failed: {e}")))?;
323        std::fs::write(&path, &json)
324            .map_err(|e| CliError::Service(format!("failed to write {}: {e}", path.display())))?;
325        generated.push(format!(
326            "metrics-manifest.json ({} metrics)",
327            manifest.metrics.len()
328        ));
329    }
330
331    // Deployment contract + container manifest
332    #[cfg(feature = "deployment")]
333    let deployment_contract = app.deployment_contract();
334    #[cfg(feature = "deployment")]
335    if deployment_contract.is_none() {
336        output::print_warn(&format!(
337            "DfeApp::deployment_contract() returned None for `{}` -- \
338             only metrics-manifest.json will be generated. \
339             Implement the trait hook to emit deployment-contract.json, \
340             container-manifest.json, and Dockerfile.runtime.",
341            app.name()
342        ));
343    }
344    #[cfg(feature = "deployment")]
345    if let Some(contract) = deployment_contract {
346        // Full deployment contract (secrets, KEDA, Helm, everything)
347        let path = output_dir.join("deployment-contract.json");
348        let json = serde_json::to_string_pretty(&contract)
349            .map_err(|e| CliError::Service(format!("deployment contract JSON failed: {e}")))?;
350        std::fs::write(&path, &json)
351            .map_err(|e| CliError::Service(format!("failed to write {}: {e}", path.display())))?;
352        generated.push("deployment-contract.json".to_string());
353
354        // Container manifest (minimal subset for CI image builds)
355        let cm_path = output_dir.join("container-manifest.json");
356        let cm_json = crate::deployment::generate::generate_container_manifest(&contract)
357            .map_err(|e| CliError::Service(format!("container manifest failed: {e}")))?;
358        std::fs::write(&cm_path, &cm_json).map_err(|e| {
359            CliError::Service(format!("failed to write {}: {e}", cm_path.display()))
360        })?;
361        generated.push("container-manifest.json".to_string());
362
363        // Runtime stage Dockerfile fragment (for CI composition)
364        let rt_path = output_dir.join("Dockerfile.runtime");
365        let rt_content = crate::deployment::generate::generate_runtime_stage(&contract);
366        std::fs::write(&rt_path, &rt_content).map_err(|e| {
367            CliError::Service(format!("failed to write {}: {e}", rt_path.display()))
368        })?;
369        generated.push("Dockerfile.runtime".to_string());
370
371        // ArgoCD Application CR (default generation -- ArgoCD is the
372        // standard CD tool across the fleet).
373        let argo_path = output_dir.join("argocd-application.yaml");
374        let argo_cfg = crate::deployment::ArgocdConfig {
375            repo_url: crate::deployment::argocd_repo_url_from_cascade(&contract.app_name),
376            ..Default::default()
377        };
378        let argo_content =
379            crate::deployment::generate::generate_argocd_application(&contract, &argo_cfg, None);
380        std::fs::write(&argo_path, &argo_content).map_err(|e| {
381            CliError::Service(format!("failed to write {}: {e}", argo_path.display()))
382        })?;
383        generated.push("argocd-application.yaml".to_string());
384    }
385
386    if generated.is_empty() {
387        output::print_warn("no artefacts generated (no metrics or deployment features enabled)");
388    } else {
389        output::print_success(&format!(
390            "generated {} artefact(s) in {}",
391            generated.len(),
392            output_dir.display()
393        ));
394        for name in &generated {
395            output::print_kv("  wrote", name);
396        }
397    }
398
399    Ok(())
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn test_standard_command_default_is_run() {
408        // When command() returns None, run_app defaults to Run
409        let cmd = StandardCommand::Run;
410        assert!(matches!(cmd, StandardCommand::Run));
411    }
412}