Skip to main content

toolkit/bootstrap/config/
mod.rs

1//! Configuration gear for toolkit-bootstrap
2//!
3//! This gear provides configuration types and utilities for both host and `OoP` gears.
4
5mod dump;
6
7use anyhow::{Context, Result, ensure};
8// Use DB config types from toolkit-db
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::path::{Path, PathBuf};
13pub use toolkit_db::{DbConnConfig, GlobalDatabaseConfig, PoolCfg};
14use tracing::Level;
15
16use crate::ConfigProvider;
17use crate::telemetry::OpenTelemetryConfig;
18use url::Url;
19
20/// Normalize a path to use forward slashes (for cross-platform YAML/DSN compatibility).
21fn normalize_path(path: &Path) -> String {
22    path.to_string_lossy().replace('\\', "/")
23}
24
25/// Error type for vendor configuration access.
26#[derive(thiserror::Error, Debug)]
27pub enum VendorConfigError {
28    #[error("vendor '{vendor}' not found in configuration")]
29    NotFound { vendor: String },
30    // Intentionally not named `source`; doing so would duplicate chained error output.
31    #[error("invalid config for vendor '{vendor}': {cause}")]
32    InvalidConfig {
33        vendor: String,
34        cause: serde_json::Error,
35    },
36}
37
38// Re-export dump functions
39pub use dump::{
40    dump_effective_gears_config_json, dump_effective_gears_config_yaml, list_gear_names,
41    redact_dsn_password, render_effective_gears_config,
42};
43
44/// Small typed view to parse each gear entry.
45#[derive(Debug, Clone, Deserialize)]
46#[serde(deny_unknown_fields)]
47pub struct GearConfig {
48    #[serde(default)]
49    pub database: Option<DbConnConfig>,
50    #[serde(default)]
51    pub config: serde_json::Value,
52    #[serde(default)]
53    pub runtime: Option<GearRuntime>,
54    #[serde(default)] // Used by the CLI
55    pub metadata: serde_json::Value,
56}
57
58/// Runtime configuration for a gear (local vs out-of-process).
59#[derive(Debug, Clone, Deserialize, Serialize, Default)]
60#[serde(deny_unknown_fields)]
61pub struct GearRuntime {
62    #[serde(default, rename = "type")]
63    pub mod_type: RuntimeKind,
64    /// Execution configuration for `OoP` gears.
65    #[serde(default)]
66    pub execution: Option<ExecutionConfig>,
67}
68
69/// Execution configuration for out-of-process gears.
70#[derive(Debug, Clone, Deserialize, Serialize, Default)]
71#[serde(deny_unknown_fields)]
72pub struct ExecutionConfig {
73    /// Path to the executable. Supports absolute paths or `~` expansion.
74    pub executable_path: String,
75    /// Command-line arguments to pass to the executable.
76    #[serde(default)]
77    pub args: Vec<String>,
78    /// Working directory for the process (optional, defaults to current dir).
79    #[serde(default)]
80    pub working_directory: Option<String>,
81    /// Environment variables to set for the process.
82    #[serde(default)]
83    pub environment: HashMap<String, String>,
84}
85
86/// Gear runtime kind.
87#[derive(Debug, Clone, Default, Deserialize, Serialize)]
88#[serde(rename_all = "lowercase")]
89pub enum RuntimeKind {
90    #[default]
91    Local,
92    Oop,
93}
94
95/// Main application configuration with strongly-typed global sections
96/// and a flexible per-gear configuration bag.
97#[derive(Debug, Clone, Deserialize, Serialize)]
98#[serde(deny_unknown_fields)]
99pub struct AppConfig {
100    /// Core server configuration.
101    pub server: ServerConfig,
102    /// New typed database configuration (optional).
103    pub database: Option<GlobalDatabaseConfig>,
104    /// Logging configuration
105    #[serde(default = "default_logging_config")]
106    pub logging: LoggingConfig,
107    /// OpenTelemetry configuration (resource, tracing, metrics).
108    #[serde(default)]
109    pub opentelemetry: OpenTelemetryConfig,
110    /// Directory containing per-gear YAML files (optional).
111    #[serde(default)]
112    pub gears_dir: Option<String>,
113    /// Per-gear configuration bag: `gear_name` → arbitrary JSON/YAML value.
114    #[serde(default)]
115    pub gears: HashMap<String, serde_json::Value>,
116    /// Per-vendor configuration bag: `vendor_name` → arbitrary JSON/YAML value.
117    /// Allows vendors to add their own typed configuration sections.
118    #[serde(default)]
119    pub vendor: VendorConfig,
120    /// Out-of-process HTTP server configuration.
121    ///
122    /// When present, an `OoP` gear starts an Axum HTTP server (probes,
123    /// gear routes, self-registration, dependency resolution, graceful drain)
124    /// instead of the legacy gRPC-only lifecycle (`cpt-cf-component-oop-bootstrap`).
125    #[serde(default)]
126    pub oop_http: Option<OopHttpConfig>,
127}
128
129impl Default for AppConfig {
130    fn default() -> Self {
131        let server = ServerConfig::default();
132        Self {
133            server,
134            database: None,
135            logging: default_logging_config(),
136            opentelemetry: OpenTelemetryConfig::default(),
137            gears_dir: None,
138            gears: HashMap::new(),
139            vendor: VendorConfig::new(),
140            oop_http: None,
141        }
142    }
143}
144
145/// Out-of-process HTTP server configuration (`cpt-cf-component-oop-bootstrap`).
146#[derive(Debug, Clone, Deserialize, Serialize)]
147#[serde(deny_unknown_fields)]
148pub struct OopHttpConfig {
149    /// Address the main HTTP server binds to (gear routes + probes),
150    /// e.g. `"0.0.0.0:8080"`.
151    pub listen_addr: String,
152    /// Optional separate bind address for probe endpoints (sidecar port).
153    /// When set, `/healthz` and `/readyz` are also served here.
154    #[serde(default)]
155    pub probe_bind_addr: Option<String>,
156    /// Maximum seconds to wait for in-flight requests to drain on shutdown.
157    #[serde(default = "default_drain_timeout_secs")]
158    pub drain_timeout_secs: u64,
159    /// Per-check timeout (ms) for readiness healthchecks on `/readyz`; raise for
160    /// slow dependencies. Mirrors the `api-gateway` `healthcheck_timeout_ms`.
161    #[serde(default = "default_healthcheck_timeout_ms")]
162    pub healthcheck_timeout_ms: u64,
163    /// Base URL other services use to reach this instance (registered as the
164    /// instance's REST endpoint). Defaults to `http://<listen_addr>` with an
165    /// unspecified host (`0.0.0.0`) rewritten to `127.0.0.1`.
166    #[serde(default)]
167    pub advertise_uri: Option<String>,
168    /// Allow a loopback / unspecified `advertise_uri` (`127.0.0.1`, `::1`,
169    /// `localhost`, `0.0.0.0`, `[::]`). Off by default: such an endpoint is
170    /// registered-but-unreachable in multi-host Profile 2 / Profile 3, so
171    /// bootstrap fails fast (`cpt-cf-adr-instance-addressable-discovery`).
172    /// Set `true` only for single-host / local-dev.
173    #[serde(default)]
174    pub allow_loopback_advertise: bool,
175    /// Development only: serve without a tenant authenticator. Non-platform routes
176    /// run with the default tenant `SecurityContext`, as `api-gateway`'s
177    /// `auth_disabled` does; platform routes still need a validated internal token.
178    /// An installed tenant authenticator still wins. Off by default: a worker serving
179    /// tenant operations without an authenticator refuses to start.
180    #[serde(default)]
181    pub auth_disabled: bool,
182    /// Platform-plane (`InternalAuthenticator`) configuration. When present it
183    /// drives both the *inbound* HTTP validator on the gear's own routes and
184    /// the *outbound* credential attached to the gear's `DirectoryService`
185    /// calls. The `shared_secret` provider works out of the box; the `kube`
186    /// provider's inbound `TokenReview` validator requires the `k8s-auth`
187    /// feature.
188    #[serde(default)]
189    pub internal_auth: Option<toolkit_security::InternalAuthConfig>,
190    /// Stable addressing labels (k8s `matchLabels` style) advertised with this
191    /// instance's directory registration, for label-based instance selection
192    /// (`DirectoryClient::resolve_by_labels`).
193    ///
194    /// Sourced from config (`oop_http.labels.<key>`) or the environment
195    /// (`APP__OOP_HTTP__LABELS__<KEY>`). A bare-numeric env *value* (e.g. a
196    /// `StatefulSet` ordinal injected as `APP__OOP_HTTP__LABELS__SHARD=7`) is
197    /// coerced to a string here rather than aborting the config load. Note:
198    /// environment-sourced keys are still lower-cased by the config loader, so
199    /// keys that must preserve case or contain `.`/`-` should be set in the
200    /// config file rather than via env.
201    #[serde(default, deserialize_with = "de_labels_scalar_to_string")]
202    pub labels: std::collections::BTreeMap<String, String>,
203}
204
205fn default_drain_timeout_secs() -> u64 {
206    30
207}
208
209fn default_healthcheck_timeout_ms() -> u64 {
210    500
211}
212
213/// Deserialize a label map, coercing scalar values (numbers, booleans) to
214/// strings.
215///
216/// The environment layer parses a bare-numeric value like
217/// `APP__OOP_HTTP__LABELS__SHARD=7` into an integer, which would otherwise fail
218/// to deserialize into a `String` and abort the entire `AppConfig::load_layered`
219/// — precisely on the path a k8s `StatefulSet` ordinal is injected. Accepting the
220/// scalar and rendering it as a string keeps that value load-able as a label.
221fn de_labels_scalar_to_string<'de, D>(
222    deserializer: D,
223) -> Result<std::collections::BTreeMap<String, String>, D::Error>
224where
225    D: serde::Deserializer<'de>,
226{
227    use serde::Deserialize;
228
229    // Ordering matters for `untagged`: a string input matches `Str`; an integer
230    // matches `I64`/`U64` before `F64`, so `7` renders as `"7"` not `"7.0"`.
231    #[derive(Deserialize)]
232    #[serde(untagged)]
233    enum Scalar {
234        Str(String),
235        Bool(bool),
236        I64(i64),
237        U64(u64),
238        F64(f64),
239    }
240
241    let raw = std::collections::BTreeMap::<String, Scalar>::deserialize(deserializer)?;
242    Ok(raw
243        .into_iter()
244        .map(|(k, v)| {
245            let value = match v {
246                Scalar::Str(s) => s,
247                Scalar::Bool(b) => b.to_string(),
248                Scalar::I64(i) => i.to_string(),
249                Scalar::U64(u) => u.to_string(),
250                Scalar::F64(f) => f.to_string(),
251            };
252            (k, value)
253        })
254        .collect())
255}
256
257impl ConfigProvider for AppConfig {
258    fn get_gear_config(&self, gear_name: &str) -> Option<&serde_json::Value> {
259        self.gears.get(gear_name)
260    }
261}
262
263#[derive(Debug, Clone, Deserialize, Serialize)]
264#[serde(deny_unknown_fields)]
265pub struct ServerConfig {
266    #[serde(default = "default_server_name")]
267    pub name: String,
268    #[serde(default = "default_home_dir")]
269    pub home_dir: PathBuf, // will be normalized to absolute path
270    /// Per-gear deadline for context construction + `init()` (seconds); absent
271    /// keeps [`DEFAULT_INIT_DEADLINE`](crate::runtime::DEFAULT_INIT_DEADLINE).
272    #[serde(default)]
273    pub init_deadline_secs: Option<u64>,
274    /// Per-gear graceful-shutdown deadline before hard-stop (seconds); absent
275    /// keeps [`DEFAULT_SHUTDOWN_DEADLINE`](crate::runtime::DEFAULT_SHUTDOWN_DEADLINE).
276    #[serde(default)]
277    pub shutdown_deadline_secs: Option<u64>,
278}
279
280impl ServerConfig {
281    /// Configured per-gear init deadline, if set.
282    #[must_use]
283    pub fn init_deadline(&self) -> Option<std::time::Duration> {
284        self.init_deadline_secs.map(std::time::Duration::from_secs)
285    }
286
287    /// Configured per-gear graceful-shutdown deadline, if set.
288    #[must_use]
289    pub fn shutdown_deadline(&self) -> Option<std::time::Duration> {
290        self.shutdown_deadline_secs
291            .map(std::time::Duration::from_secs)
292    }
293}
294
295fn default_server_name() -> String {
296    "cf-gears".to_owned()
297}
298
299fn default_home_dir() -> PathBuf {
300    super::host::paths::default_home_dir().join(".cf-gears")
301}
302
303impl Default for ServerConfig {
304    fn default() -> Self {
305        Self {
306            name: default_server_name(),
307            home_dir: default_home_dir(),
308            init_deadline_secs: None,
309            shutdown_deadline_secs: None,
310        }
311    }
312}
313
314impl ServerConfig {
315    fn normalize_home_dir_inplace(&mut self) -> Result<()> {
316        self.home_dir = super::host::normalize_path(
317            self.home_dir
318                .to_str()
319                .context("home directory configuration is not a valid path")?,
320        )
321        .context("home_dir normalization failed")?;
322
323        std::fs::create_dir_all(&self.home_dir).context("Failed to create home_dir")?;
324
325        Ok(())
326    }
327}
328
329/// Console output format for the logging layer.
330#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
331#[serde(rename_all = "lowercase")]
332pub enum ConsoleFormat {
333    /// Human-readable text output (default).
334    #[default]
335    Text,
336    /// Structured JSON output (useful for container log collectors).
337    Json,
338}
339
340/// Logging configuration - maps subsystem names to their logging settings.
341/// Key "default" is the catch-all for logs that don't match explicit subsystems.
342pub type LoggingConfig = HashMap<String, Section>;
343
344/// Per-vendor configuration bag: vendor name → arbitrary JSON/YAML value.
345/// Each vendor's section can be deserialized into a typed struct via
346/// [`AppConfig::vendor_config`] or [`AppConfig::vendor_config_or_default`].
347pub type VendorConfig = HashMap<String, serde_json::Value>;
348
349// ================= Custom serde gear for optional Level (supports "off") =================
350mod optional_level_serde {
351    use serde::{Deserialize, Deserializer, Serializer};
352    use tracing::Level;
353
354    #[allow(clippy::ref_option, clippy::trivially_copy_pass_by_ref)]
355    pub fn serialize<S>(level: &Option<Level>, serializer: S) -> Result<S::Ok, S::Error>
356    where
357        S: Serializer,
358    {
359        match level {
360            Some(l) => serializer.serialize_str(l.as_str()),
361            None => serializer.serialize_str("off"),
362        }
363    }
364
365    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Level>, D::Error>
366    where
367        D: Deserializer<'de>,
368    {
369        let s = String::deserialize(deserializer)?;
370        match s.to_lowercase().as_str() {
371            "trace" => Ok(Some(Level::TRACE)),
372            "debug" => Ok(Some(Level::DEBUG)),
373            "info" => Ok(Some(Level::INFO)),
374            "warn" => Ok(Some(Level::WARN)),
375            "error" => Ok(Some(Level::ERROR)),
376            "off" | "none" => Ok(None),
377            _ => Err(serde::de::Error::custom(format!("invalid level: {s}"))),
378        }
379    }
380
381    #[allow(clippy::unnecessary_wraps)]
382    pub fn default() -> Option<Level> {
383        Some(Level::INFO)
384    }
385}
386
387#[derive(Debug, Serialize, Deserialize, Clone)]
388pub struct SectionFile {
389    pub file: String,
390    #[serde(
391        default = "optional_level_serde::default",
392        with = "optional_level_serde"
393    )]
394    pub file_level: Option<Level>,
395}
396
397#[derive(Debug, Serialize, Deserialize, Clone)]
398pub struct Section {
399    #[serde(default)]
400    pub console_format: ConsoleFormat,
401    #[serde(
402        default = "optional_level_serde::default",
403        with = "optional_level_serde"
404    )]
405    pub console_level: Option<Level>,
406    #[serde(flatten)]
407    pub section_file: Option<SectionFile>,
408    pub max_age_days: Option<u32>, // Not implemented yet
409    #[serde(default)]
410    pub max_backups: Option<usize>, // How many files to keep
411    #[serde(default)]
412    pub max_size_mb: Option<u64>, // Max size of the file in MB
413}
414
415impl Section {
416    #[must_use]
417    pub fn file(&self) -> Option<&str> {
418        self.section_file
419            .as_ref()
420            .map(|f| f.file.as_str())
421            .filter(|s| !s.is_empty())
422    }
423
424    #[must_use]
425    pub fn file_level(&self) -> Option<Level> {
426        self.section_file.as_ref().and_then(|f| f.file_level)
427    }
428}
429
430/// Create a default logging configuration.
431#[must_use]
432pub fn default_logging_config() -> LoggingConfig {
433    let mut logging = HashMap::new();
434    logging.insert(
435        "default".to_owned(),
436        Section {
437            console_level: Some(Level::INFO),
438            section_file: Some(SectionFile {
439                file: "logs/cf-gears.log".to_owned(),
440                file_level: Some(Level::DEBUG),
441            }),
442            console_format: ConsoleFormat::default(),
443            max_age_days: Some(7),
444            max_backups: Some(3),
445            max_size_mb: Some(100),
446        },
447    );
448    logging
449}
450
451/// Remap a split, `APP__`-prefixed environment key into a figment config path.
452///
453/// k8s env var names must be `C_IDENTIFIERs` (no dashes), but gear names are
454/// kebab-case. Under the `gears` branch we therefore remap `_` -> `-` in the
455/// gear-name segment only (the one right after `gears`). Nested field names
456/// (e.g. `max_age_days`) and other branches (e.g. `vendor`) are left alone; the
457/// dash form is unaffected since remapping `-` is a no-op.
458///
459/// Safe because gear names are guaranteed kebab-case by `validate_kebab_case`
460/// (`#[toolkit::gear]` macro + `make validate-gear-names`).
461pub(crate) fn remap_gear_env_key(key: &str) -> String {
462    // Lowercase so the match is independent of figment's own (later) lowercasing.
463    let lower = key.to_ascii_lowercase();
464    let mut parts: Vec<&str> = lower.split('.').collect();
465    if parts.first() == Some(&"gears") && parts.len() >= 2 {
466        let gear = parts[1].replace('_', "-");
467        parts[1] = gear.as_str();
468        parts.join(".")
469    } else {
470        lower
471    }
472}
473
474/// Reject the pre-2026-03 top-level `tracing:` section with a migration hint.
475///
476/// The section moved under `opentelemetry:` in `8c2187bc4`, which also put
477/// `deny_unknown_fields` on [`AppConfig`] — so an unmigrated config already
478/// fails, but with a bare "unknown field" that says nothing about where the
479/// settings went. This turns that into an actionable error.
480///
481/// One check covers both shapes the old documentation taught: `Env::prefixed`
482/// splits on `__`, so `APP__TRACING__EXPORTER__ENDPOINT` lands on the same
483/// `tracing.*` path as the YAML block.
484///
485/// The nested `opentelemetry.tracing` is untouched — `find_value` resolves from
486/// the root — and `AppConfig::default()` contributes no `tracing` key.
487///
488/// # Errors
489/// Returns an error when a root-level `tracing` key is present.
490fn reject_legacy_tracing_key(figment: &figment::Figment) -> Result<()> {
491    if figment.find_value("tracing").is_err() {
492        return Ok(());
493    }
494
495    anyhow::bail!(
496        "the top-level `tracing:` section was replaced by `opentelemetry:`; \
497         move the settings across:\n\
498         \n\
499         \x20 tracing.enabled       -> opentelemetry.tracing.enabled\n\
500         \x20 tracing.service_name  -> opentelemetry.resource.service_name\n\
501         \x20 tracing.resource      -> opentelemetry.resource.attributes\n\
502         \x20 tracing.metrics       -> opentelemetry.metrics\n\
503         \x20 tracing.exporter      -> opentelemetry.exporter (shared) or \
504         opentelemetry.tracing.exporter\n\
505         \x20 tracing.sampler, .logs_correlation -> opentelemetry.tracing.*\n\
506         \x20 tracing.propagation, .http        -> (removed; never read by code)\n\
507         \n\
508         Environment overrides use the same path, so APP__TRACING__* becomes \
509         APP__OPENTELEMETRY__*. See docs/TRACING_SETUP.md."
510    );
511}
512
513impl AppConfig {
514    /// Load configuration with layered loading: defaults → YAML file → environment variables.
515    /// Also normalizes `server.home_dir` into an absolute path and creates the directory.
516    ///
517    /// # Errors
518    /// Returns an error if configuration loading or `home_dir` resolution fails.
519    pub fn load_layered(config_path: &PathBuf) -> Result<Self> {
520        use figment::{
521            Figment,
522            providers::{Env, Format, Serialized},
523        };
524
525        // For layered loading, start from AppConfig::default() which provides logging
526        // defaults (via default_logging_config()); other optional sections (database,
527        // opentelemetry, gears_dir) remain None unless overridden by YAML/ENV.
528        let figment = Figment::new()
529            .merge(Serialized::defaults(AppConfig::default()))
530            .merge(StrictYaml::file(config_path))
531            // Example: APP__SERVER__PORT=8087 maps to server.port.
532            .merge(
533                Env::prefixed("APP__")
534                    .split("__")
535                    .map(|key| remap_gear_env_key(key.as_str()).into()),
536            );
537
538        reject_legacy_tracing_key(&figment)?;
539
540        let mut config: AppConfig = figment
541            .extract()
542            .with_context(|| "Failed to extract config from figment".to_owned())?;
543
544        // Normalize + create home_dir immediately.
545        config
546            .server
547            .normalize_home_dir_inplace()
548            .context("Failed to resolve server.home_dir")?;
549
550        // Merge gear files if gears_dir is specified.
551        if let Some(dir) = config.gears_dir.as_ref() {
552            merge_gear_files(&mut config.gears, dir)?;
553        }
554
555        Ok(config)
556    }
557
558    /// Load configuration from file or create with default values.
559    /// Also normalizes `server.home_dir` into an absolute path and creates the directory.
560    ///
561    /// # Errors
562    /// Returns an error if configuration loading or `home_dir` resolution fails.
563    pub fn load_or_default(config_path: Option<&PathBuf>) -> Result<Self> {
564        if let Some(path) = config_path {
565            ensure!(
566                path.is_file(),
567                "config file does not exist: {}",
568                path.to_string_lossy()
569            );
570            Self::load_layered(path)
571        } else {
572            let mut c = Self::default();
573            c.server
574                .normalize_home_dir_inplace()
575                .context("Failed to resolve server.home_dir (defaults)")?;
576            Ok(c)
577        }
578    }
579
580    /// Serialize configuration to YAML.
581    ///
582    /// # Errors
583    /// Returns an error if serialization fails.
584    pub fn to_yaml(&self) -> Result<String> {
585        serde_saphyr::to_string(self).context("Failed to serialize config to YAML")
586    }
587
588    /// Deserialize a vendor configuration section into a typed struct.
589    ///
590    /// # Errors
591    /// Returns `VendorConfigError::NotFound` if the vendor is not present,
592    /// or `VendorConfigError::InvalidConfig` if deserialization fails.
593    pub fn vendor_config<T: DeserializeOwned>(
594        &self,
595        vendor_name: &str,
596    ) -> Result<T, VendorConfigError> {
597        let raw = self
598            .vendor
599            .get(vendor_name)
600            .ok_or_else(|| VendorConfigError::NotFound {
601                vendor: vendor_name.to_owned(),
602            })?;
603        T::deserialize(raw).map_err(|e| VendorConfigError::InvalidConfig {
604            vendor: vendor_name.to_owned(),
605            cause: e,
606        })
607    }
608
609    /// Deserialize a vendor configuration section, returning `T::default()` if absent.
610    ///
611    /// # Errors
612    /// Returns `VendorConfigError::InvalidConfig` if the section exists but cannot be
613    /// deserialized into `T`.
614    pub fn vendor_config_or_default<T: DeserializeOwned + Default>(
615        &self,
616        vendor_name: &str,
617    ) -> Result<T, VendorConfigError> {
618        let Some(raw) = self.vendor.get(vendor_name) else {
619            return Ok(T::default());
620        };
621        T::deserialize(raw).map_err(|e| VendorConfigError::InvalidConfig {
622            vendor: vendor_name.to_owned(),
623            cause: e,
624        })
625    }
626
627    /// Apply overrides from command line arguments.
628    pub fn apply_cli_overrides(&mut self, verbose: u8) {
629        // Set logging level based on verbose flags for "default" section.
630        if let Some(default_section) = self.logging.get_mut("default") {
631            default_section.console_level = match verbose {
632                0 => default_section.console_level, // keep
633                1 => Some(Level::DEBUG),
634                _ => Some(Level::TRACE),
635            };
636        }
637    }
638}
639
640/// Command line arguments structure.
641#[derive(Debug, Clone)]
642pub struct CliArgs {
643    pub config: Option<String>,
644    pub print_config: bool,
645    pub verbose: u8,
646    pub mock: bool,
647}
648
649/// Parse YAML with duplicate-key rejection.
650fn strict_yaml_parse<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, serde_saphyr::Error> {
651    // `Options` is `#[non_exhaustive]`, so it cannot be built with a struct literal from
652    // outside the crate — `options!` is what serde-saphyr provides instead.
653    let opts = serde_saphyr::options! {
654        duplicate_keys: serde_saphyr::DuplicateKeyPolicy::Error,
655    };
656    serde_saphyr::from_str_with_options(s, opts)
657}
658
659/// YAML [`Format`](figment::providers::Format) provider that rejects duplicate
660/// mapping keys instead of silently keeping the last value.
661///
662/// Drop-in replacement for figment's built-in `Yaml` — use
663/// `StrictYaml::file(path)` wherever you would use `Yaml::file(path)`.
664struct StrictYaml;
665
666impl figment::providers::Format for StrictYaml {
667    type Error = serde_saphyr::Error;
668
669    const NAME: &'static str = "YAML";
670
671    fn from_str<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, Self::Error> {
672        strict_yaml_parse(s)
673    }
674}
675
676fn merge_gear_files(
677    bag: &mut HashMap<String, serde_json::Value>,
678    dir: impl AsRef<Path>,
679) -> Result<()> {
680    use std::fs;
681    let dir = dir.as_ref();
682    if !dir.exists() {
683        return Ok(());
684    }
685    for entry in fs::read_dir(dir)? {
686        let entry = entry?;
687        let path = entry.path();
688        if !path.is_file() {
689            continue;
690        }
691        let ext = path
692            .extension()
693            .and_then(|s| s.to_str())
694            .unwrap_or("")
695            .to_ascii_lowercase();
696        if ext != "yml" && ext != "yaml" {
697            continue;
698        }
699        let name = path
700            .file_stem()
701            .and_then(|s| s.to_str())
702            .unwrap_or("")
703            .to_owned();
704        let raw = fs::read_to_string(&path)?;
705        let json: serde_json::Value = strict_yaml_parse(&raw)
706            .with_context(|| format!("failed to parse gear file: {}", path.display()))?;
707        bag.insert(name, json);
708    }
709    Ok(())
710}
711
712// ---- New ToolKit DB Handling Functions ----
713
714/// Expands environment variables in a DSN string.
715/// Replaces `${VARNAME}` with the actual environment variable value.
716///
717/// # Errors
718/// Returns an error if any referenced env var is missing.
719pub fn expand_env_in_dsn(dsn: &str) -> Result<String> {
720    toolkit_utils::var_expand::expand_env_vars(dsn).map_err(|e| anyhow::anyhow!("{e}"))
721}
722
723/// Resolves password: if it contains ${VAR}, expands from environment variable; otherwise returns as-is.
724///
725/// # Errors
726/// Returns an error if the referenced environment variable is not found.
727pub fn resolve_password(password: Option<&str>) -> Result<Option<String>> {
728    if let Some(pwd) = password {
729        if pwd.starts_with("${") && pwd.ends_with('}') {
730            // Extract variable name from ${VAR_NAME}
731            let var_name = &pwd[2..pwd.len() - 1];
732            let resolved = std::env::var(var_name).with_context(|| {
733                format!("Environment variable '{var_name}' not found for password")
734            })?;
735            Ok(Some(resolved))
736        } else {
737            // Return literal password as-is
738            Ok(Some(pwd.to_owned()))
739        }
740    } else {
741        Ok(None)
742    }
743}
744
745/// Validates that a DSN string is parseable by the dsn crate.
746/// Note: `SQLite` DSNs have special formats that dsn crate doesn't recognize, so we skip validation for them.
747///
748/// # Errors
749/// Returns an error if the DSN is invalid.
750pub fn validate_dsn(dsn: &str) -> Result<()> {
751    // Skip validation for SQLite DSNs as they use special syntax not recognized by dsn crate
752    if dsn.starts_with("sqlite:") {
753        return Ok(());
754    }
755
756    let _parsed = dsn::parse(dsn).map_err(|e| anyhow::anyhow!("Invalid DSN '{dsn}': {e}"))?;
757
758    Ok(())
759}
760
761/// Resolves `SQLite` @`file()` syntax in DSN to actual file paths.
762/// - `sqlite://@file(users.sqlite)` → `$HOME/.cf-gears/<gear>/users.sqlite`
763/// - `sqlite://@file(/abs/path/file.db)` → use absolute path
764/// - `sqlite://` or `sqlite:///` → `$HOME/.cf-gears/<gear>/<gear>.sqlite`
765fn resolve_sqlite_dsn(
766    dsn: &str,
767    home_dir: &Path,
768    gear_name: &str,
769    dry_run: bool,
770) -> Result<String> {
771    if dsn.contains("@file(") {
772        // Extract the file path from @file(...)
773        if let Some(start) = dsn.find("@file(")
774            && let Some(end) = dsn[start..].find(')')
775        {
776            let file_path = &dsn[start + 6..start + end]; // +6 for "@file("
777
778            let resolved_path = if file_path.starts_with('/')
779                || (file_path.len() > 1 && file_path.chars().nth(1) == Some(':'))
780            {
781                // Absolute path (Unix or Windows)
782                PathBuf::from(file_path)
783            } else {
784                // Relative path - resolve under gear directory
785                let gear_dir = home_dir.join(gear_name);
786                if !dry_run {
787                    std::fs::create_dir_all(&gear_dir).with_context(|| {
788                        format!("Failed to create gear directory: {}", gear_dir.display())
789                    })?;
790                }
791                gear_dir.join(file_path)
792            };
793
794            let normalized_path = normalize_path(&resolved_path);
795            // For Windows absolute paths (C:/...), use sqlite:path format
796            // For Unix absolute paths (/...), use sqlite://path format
797            if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
798                // Windows absolute path like C:/...
799                return Ok(format!("sqlite:{normalized_path}"));
800            }
801            // Unix absolute path or relative path
802            return Ok(format!("sqlite://{normalized_path}"));
803        }
804        return Err(anyhow::anyhow!(
805            "Invalid @file() syntax in SQLite DSN: {dsn}"
806        ));
807    }
808
809    // Handle empty DSN or just sqlite:// - default to gear.sqlite
810    if dsn == "sqlite://" || dsn == "sqlite:///" || dsn == "sqlite:" {
811        let gear_dir = home_dir.join(gear_name);
812        if !dry_run {
813            std::fs::create_dir_all(&gear_dir).with_context(|| {
814                format!("Failed to create gear directory: {}", gear_dir.display())
815            })?;
816        }
817        let db_path = gear_dir.join(format!("{gear_name}.sqlite"));
818        let normalized_path = normalize_path(&db_path);
819        // For Windows absolute paths (C:/...), use sqlite:path format
820        // For Unix absolute paths (/...), use sqlite://path format
821        if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
822            // Windows absolute path like C:/...
823            return Ok(format!("sqlite:{normalized_path}"));
824        }
825        // Unix absolute path or relative path
826        return Ok(format!("sqlite://{normalized_path}"));
827    }
828
829    // Return DSN as-is for normal cases
830    Ok(dsn.to_owned())
831}
832
833/// Builds a server-based DSN from individual fields.
834/// Used when no base DSN is provided or when overriding DSN components.
835/// Uses `url::Url` to properly handle percent-encoding of special characters.
836fn build_server_dsn(
837    scheme: &str,
838    host: Option<&str>,
839    port: Option<u16>,
840    user: Option<&str>,
841    password: Option<&str>,
842    dbname: Option<&str>,
843    params: &HashMap<String, String>,
844) -> Result<String> {
845    let host = host.unwrap_or("localhost");
846    let user = user.unwrap_or("postgres"); // reasonable default for server-based DBs
847
848    // Start with base URL
849    let mut url = Url::parse(&format!("{scheme}://dummy/"))
850        .with_context(|| format!("Invalid scheme: {scheme}"))?;
851
852    // Set host (required)
853    url.set_host(Some(host))
854        .with_context(|| format!("Invalid host: {host}"))?;
855
856    // Set port if provided
857    if let Some(port) = port {
858        url.set_port(Some(port))
859            .map_err(|()| anyhow::anyhow!("Invalid port: {port}"))?;
860    }
861
862    // Set username
863    url.set_username(user)
864        .map_err(|()| anyhow::anyhow!("Failed to set username: {user}"))?;
865
866    // Set password if provided
867    if let Some(password) = password {
868        url.set_password(Some(password))
869            .map_err(|()| anyhow::anyhow!("Failed to set password"))?;
870    }
871
872    // Set database name as path (with leading slash)
873    if let Some(dbname) = dbname {
874        // Manually encode the dbname to handle special characters
875        let encoded_dbname = urlencoding::encode(dbname);
876        url.set_path(&format!("/{encoded_dbname}"));
877    } else {
878        url.set_path("/");
879    }
880
881    // Set query parameters
882    if !params.is_empty() {
883        // Use url::Url::query_pairs_mut() to properly handle encoding
884        let mut query_pairs = url.query_pairs_mut();
885        for (key, value) in params {
886            query_pairs.append_pair(key, value);
887        }
888    }
889
890    Ok(url.to_string())
891}
892
893/// Builds a `SQLite` DSN by replacing the database file path while preserving query parameters.
894fn build_sqlite_dsn_with_dbname_override(
895    original_dsn: &str,
896    dbname: &str,
897    gear_name: &str,
898    home_dir: &Path,
899    dry_run: bool,
900) -> Result<String> {
901    // Parse the original DSN to extract query parameters
902    let query_params = if let Some(query_start) = original_dsn.find('?') {
903        &original_dsn[query_start..]
904    } else {
905        ""
906    };
907
908    // Build the correct path for the database file
909    let gear_dir = home_dir.join(gear_name);
910    if !dry_run {
911        std::fs::create_dir_all(&gear_dir)
912            .with_context(|| format!("Failed to create gear directory: {}", gear_dir.display()))?;
913    }
914    let db_path = gear_dir.join(dbname);
915    let normalized_path = normalize_path(&db_path);
916
917    // Build the new DSN with correct format for the platform
918    let dsn_base = if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
919        // Windows absolute path like C:/...
920        format!("sqlite:{normalized_path}")
921    } else {
922        // Unix absolute path or relative path
923        format!("sqlite://{normalized_path}")
924    };
925
926    Ok(format!("{dsn_base}{query_params}"))
927}
928
929/// Builds a `SQLite` DSN from file/path or validates existing DSN.
930/// If dbname is provided, it overrides the database file in the DSN.
931///
932/// # Arguments
933/// * `dry_run` - If true, skip directory creation (for read-only inspection)
934fn build_sqlite_dsn(
935    dsn: Option<&str>,
936    file: Option<&str>,
937    path: Option<&PathBuf>,
938    dbname: Option<&str>,
939    gear_name: &str,
940    home_dir: &Path,
941    dry_run: bool,
942) -> Result<String> {
943    // If full DSN provided, resolve @file() syntax and validate
944    if let Some(dsn) = dsn {
945        let resolved_dsn = resolve_sqlite_dsn(dsn, home_dir, gear_name, dry_run)?;
946
947        // If dbname is provided, we need to replace the database file path while preserving query params
948        if let Some(dbname) = dbname {
949            return build_sqlite_dsn_with_dbname_override(
950                &resolved_dsn,
951                dbname,
952                gear_name,
953                home_dir,
954                dry_run,
955            );
956        }
957
958        validate_dsn(&resolved_dsn)?;
959        return Ok(resolved_dsn);
960    }
961
962    // Build from path (absolute)
963    if let Some(path) = path {
964        let absolute_path = if path.is_absolute() {
965            path.clone()
966        } else {
967            home_dir.join(path)
968        };
969        let normalized_path = normalize_path(&absolute_path);
970        // For Windows absolute paths (C:/...), use sqlite:path format
971        // For Unix absolute paths (/...), use sqlite://path format
972        if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
973            // Windows absolute path like C:/...
974            return Ok(format!("sqlite:{normalized_path}"));
975        }
976        // Unix absolute path or relative path
977        return Ok(format!("sqlite://{normalized_path}"));
978    }
979
980    // Build from file (relative under gear dir)
981    if let Some(file) = file {
982        let gear_dir = home_dir.join(gear_name);
983        if !dry_run {
984            std::fs::create_dir_all(&gear_dir).with_context(|| {
985                format!("Failed to create gear directory: {}", gear_dir.display())
986            })?;
987        }
988        let db_path = gear_dir.join(file);
989        let normalized_path = normalize_path(&db_path);
990        // For Windows absolute paths (C:/...), use sqlite:path format
991        // For Unix absolute paths (/...), use sqlite://path format
992        if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
993            // Windows absolute path like C:/...
994            return Ok(format!("sqlite:{normalized_path}"));
995        }
996        // Unix absolute path or relative path
997        return Ok(format!("sqlite://{normalized_path}"));
998    }
999
1000    // Default to gear.sqlite
1001    let gear_dir = home_dir.join(gear_name);
1002    if !dry_run {
1003        std::fs::create_dir_all(&gear_dir)
1004            .with_context(|| format!("Failed to create gear directory: {}", gear_dir.display()))?;
1005    }
1006    let db_path = gear_dir.join(format!("{gear_name}.sqlite"));
1007    let normalized_path = normalize_path(&db_path);
1008    // For Windows absolute paths (C:/...), use sqlite:path format
1009    // For Unix absolute paths (/...), use sqlite://path format
1010    if normalized_path.len() > 1 && normalized_path.chars().nth(1) == Some(':') {
1011        // Windows absolute path like C:/...
1012        Ok(format!("sqlite:{normalized_path}"))
1013    } else {
1014        // Unix absolute path or relative path
1015        Ok(format!("sqlite://{normalized_path}"))
1016    }
1017}
1018
1019/// Type alias for the complex return type of `build_final_db_for_gear`
1020type DbConfigResult = Result<Option<(String /* final_dsn */, PoolCfg)>>;
1021
1022/// Builder for accumulating database configuration from multiple sources
1023#[derive(Default)]
1024struct DbConfigBuilder {
1025    dsn: Option<String>,
1026    host: Option<String>,
1027    port: Option<u16>,
1028    user: Option<String>,
1029    password: Option<String>,
1030    dbname: Option<String>,
1031    params: HashMap<String, String>,
1032    pool: PoolCfg,
1033}
1034
1035impl DbConfigBuilder {
1036    fn new() -> Self {
1037        Self::default()
1038    }
1039
1040    /// Apply global server configuration
1041    fn apply_global_server(
1042        &mut self,
1043        global_server: &DbConnConfig,
1044        home_dir: &Path,
1045        gear_name: &str,
1046        dry_run: bool,
1047    ) -> Result<()> {
1048        // Apply global server DSN
1049        if let Some(global_dsn) = &global_server.dsn {
1050            let expanded_dsn = expand_env_in_dsn(global_dsn.expose())?;
1051            // For SQLite, resolve @file() syntax before validation
1052            let resolved_dsn = if expanded_dsn.starts_with("sqlite") {
1053                resolve_sqlite_dsn(&expanded_dsn, home_dir, gear_name, dry_run)?
1054            } else {
1055                expanded_dsn
1056            };
1057            validate_dsn(&resolved_dsn)?;
1058            self.dsn = Some(resolved_dsn);
1059        }
1060
1061        // Apply global server fields (override DSN parts)
1062        if let Some(host) = &global_server.host {
1063            self.host = Some(host.clone());
1064        }
1065        if let Some(port) = global_server.port {
1066            self.port = Some(port);
1067        }
1068        if let Some(user) = &global_server.user {
1069            self.user = Some(user.clone());
1070        }
1071        if let Some(password) = resolve_password(
1072            global_server
1073                .password
1074                .as_ref()
1075                .map(toolkit_utils::SecretString::expose),
1076        )? {
1077            self.password = Some(password);
1078        }
1079        if let Some(dbname) = &global_server.dbname {
1080            self.dbname = Some(dbname.clone());
1081        }
1082        if let Some(params) = &global_server.params {
1083            self.params.extend(params.clone());
1084        }
1085        if let Some(pool) = &global_server.pool {
1086            self.pool = pool.clone();
1087        }
1088
1089        Ok(())
1090    }
1091
1092    /// Apply gear DSN (overrides global DSN)
1093    fn apply_gear_dsn(
1094        &mut self,
1095        gear_dsn: &str,
1096        home_dir: &Path,
1097        gear_name: &str,
1098        dry_run: bool,
1099    ) -> Result<()> {
1100        // For SQLite, resolve @file() syntax before validation
1101        let resolved_dsn = if gear_dsn.starts_with("sqlite") {
1102            resolve_sqlite_dsn(gear_dsn, home_dir, gear_name, dry_run)?
1103        } else {
1104            gear_dsn.to_owned()
1105        };
1106        validate_dsn(&resolved_dsn)?;
1107        self.dsn = Some(resolved_dsn);
1108        Ok(())
1109    }
1110
1111    /// Apply gear fields (override everything)
1112    fn apply_gear_fields(&mut self, gear_db_config: &DbConnConfig) -> Result<()> {
1113        if let Some(host) = &gear_db_config.host {
1114            self.host = Some(host.clone());
1115        }
1116        if let Some(port) = gear_db_config.port {
1117            self.port = Some(port);
1118        }
1119        if let Some(user) = &gear_db_config.user {
1120            self.user = Some(user.clone());
1121        }
1122        if let Some(password) = resolve_password(
1123            gear_db_config
1124                .password
1125                .as_ref()
1126                .map(toolkit_utils::SecretString::expose),
1127        )? {
1128            self.password = Some(password);
1129        }
1130        if let Some(dbname) = &gear_db_config.dbname {
1131            self.dbname = Some(dbname.clone());
1132        }
1133        if let Some(params) = &gear_db_config.params {
1134            self.params.extend(params.clone());
1135        }
1136        if let Some(pool) = &gear_db_config.pool {
1137            // Gear pool settings override global ones
1138            if let Some(max_conns) = pool.max_conns {
1139                self.pool.max_conns = Some(max_conns);
1140            }
1141            if let Some(acquire_timeout) = pool.acquire_timeout {
1142                self.pool.acquire_timeout = Some(acquire_timeout);
1143            }
1144        }
1145        Ok(())
1146    }
1147
1148    /// Check if we have any field overrides that require rebuilding the DSN
1149    fn has_field_overrides(&self) -> bool {
1150        self.host.is_some()
1151            || self.port.is_some()
1152            || self.user.is_some()
1153            || self.password.is_some()
1154            || !self.params.is_empty()
1155    }
1156}
1157
1158/// Determines the database backend type (`SQLite` or server-based)
1159fn decide_backend(builder: &DbConfigBuilder, gear_db_config: &DbConnConfig) -> bool {
1160    // Always treat as SQLite if DSN starts with "sqlite", regardless of server reference
1161    // Also treat as SQLite if no server reference and no explicit DSN (default case)
1162    gear_db_config.file.is_some()
1163        || gear_db_config.path.is_some()
1164        || builder
1165            .dsn
1166            .as_ref()
1167            .is_some_and(|dsn| dsn.starts_with("sqlite"))
1168        || (gear_db_config.server.is_none() && builder.dsn.is_none())
1169}
1170
1171/// Finalize `SQLite` DSN from builder state
1172fn finalize_sqlite_dsn(
1173    builder: &DbConfigBuilder,
1174    gear_db_config: &DbConnConfig,
1175    gear_name: &str,
1176    home_dir: &Path,
1177    dry_run: bool,
1178) -> Result<String> {
1179    build_sqlite_dsn(
1180        builder.dsn.as_deref(),
1181        gear_db_config.file.as_deref(),
1182        gear_db_config.path.as_ref(),
1183        builder.dbname.as_deref(),
1184        gear_name,
1185        home_dir,
1186        dry_run,
1187    )
1188}
1189
1190/// Finalize server-based DSN from builder state
1191fn finalize_server_dsn(builder: &DbConfigBuilder, gear_name: &str) -> Result<String> {
1192    // Extract dbname from DSN if not provided separately
1193    let dbname = if let Some(dbname) = builder.dbname.as_deref() {
1194        dbname.to_owned()
1195    } else if let Some(dsn) = builder.dsn.as_ref() {
1196        // Try to extract dbname from DSN path
1197        if let Ok(parsed) = url::Url::parse(dsn) {
1198            let path = parsed.path();
1199            if path.len() > 1 {
1200                // Remove leading slash and return the path as dbname
1201                path[1..].to_string()
1202            } else {
1203                return Err(anyhow::anyhow!(
1204                    "Server-based database config for gear '{gear_name}' missing required 'dbname'"
1205                ));
1206            }
1207        } else {
1208            return Err(anyhow::anyhow!(
1209                "Server-based database config for gear '{gear_name}' missing required 'dbname'"
1210            ));
1211        }
1212    } else {
1213        return Err(anyhow::anyhow!(
1214            "Server-based database config for gear '{gear_name}' missing required 'dbname'"
1215        ));
1216    };
1217
1218    if builder.has_field_overrides() || builder.dsn.is_none() {
1219        // Build DSN from fields when we have overrides or no original DSN
1220        let scheme = if let Some(dsn) = &builder.dsn {
1221            let parsed = Url::parse(dsn)?;
1222            parsed.scheme().to_owned()
1223        } else {
1224            "postgresql".to_owned() // default
1225        };
1226
1227        build_server_dsn(
1228            &scheme,
1229            builder.host.as_deref(),
1230            builder.port,
1231            builder.user.as_deref(),
1232            builder.password.as_deref(),
1233            Some(&dbname),
1234            &builder.params,
1235        )
1236    } else if let Some(original_dsn) = &builder.dsn {
1237        // Use original DSN when no field overrides (but update dbname if needed)
1238        if let Ok(mut parsed) = Url::parse(original_dsn) {
1239            // Update the path with the final dbname if it's different
1240            let original_dbname = parsed.path().trim_start_matches('/');
1241            if original_dbname != dbname {
1242                parsed.set_path(&format!("/{dbname}"));
1243            }
1244            Ok(parsed.to_string())
1245        } else {
1246            // Fallback to building from fields if URL parsing fails
1247            build_server_dsn(
1248                "postgresql",
1249                builder.host.as_deref(),
1250                builder.port,
1251                builder.user.as_deref(),
1252                builder.password.as_deref(),
1253                Some(&dbname),
1254                &builder.params,
1255            )
1256        }
1257    } else {
1258        // This branch should not be reachable due to the condition above
1259        unreachable!("final_dsn should not be None when has_field_overrides is false")
1260    }
1261}
1262
1263/// Redacts password from DSN for logging
1264fn redact_dsn_for_logging(dsn: &str) -> Result<String> {
1265    if dsn.contains('@') {
1266        let parsed = Url::parse(dsn)?;
1267        let mut log_url = parsed;
1268        if log_url.password().is_some() {
1269            log_url.set_password(Some("***")).ok();
1270        }
1271        Ok(log_url.to_string())
1272    } else {
1273        Ok(dsn.to_owned())
1274    }
1275}
1276
1277// ---- OoP Gear Configuration Support ----
1278
1279/// Environment variable name for passing rendered gear config to `OoP` gears.
1280pub const TOOLKIT_MODULE_CONFIG_ENV: &str = "TOOLKIT_MODULE_CONFIG";
1281
1282/// Rendered database configuration for `OoP` gears.
1283/// Contains both global server templates and gear-specific config.
1284#[derive(Debug, Clone, Serialize, Deserialize)]
1285pub struct RenderedDbConfig {
1286    /// Global database configuration with server templates.
1287    /// `OoP` gear can use these servers for reference.
1288    #[serde(skip_serializing_if = "Option::is_none")]
1289    pub global: Option<GlobalDatabaseConfig>,
1290    /// Gear-specific database configuration (already merged with server reference in master).
1291    /// This is the `gears.<name>.database` section after server merge.
1292    #[serde(skip_serializing_if = "Option::is_none")]
1293    pub gear: Option<DbConnConfig>,
1294}
1295
1296impl RenderedDbConfig {
1297    /// Create a new `RenderedDbConfig` from global and gear database configurations.
1298    #[must_use]
1299    pub fn new(global: Option<GlobalDatabaseConfig>, gear: Option<DbConnConfig>) -> Self {
1300        Self { global, gear }
1301    }
1302}
1303
1304/// Rendered gear configuration passed to `OoP` gears via environment variable.
1305///
1306/// This struct contains everything an `OoP` gear needs to initialize:
1307/// - Database configuration (structured, for field-by-field merge in `OoP`)
1308/// - Gear config section
1309/// - Logging configuration (for key-by-key merge in `OoP`)
1310/// - OpenTelemetry configuration (resource, tracing, metrics)
1311///
1312/// The runtime section is excluded as it's only relevant for the master host.
1313#[derive(Debug, Clone, Serialize, Deserialize)]
1314pub struct RenderedGearConfig {
1315    /// Rendered database configuration (structured, not resolved DSN).
1316    /// `OoP` gear will merge this with local --config using field-by-field merge.
1317    #[serde(skip_serializing_if = "Option::is_none")]
1318    pub database: Option<RenderedDbConfig>,
1319    /// Gear-specific config section (passed as-is)
1320    #[serde(default)]
1321    pub config: serde_json::Value,
1322    /// Logging configuration from master host.
1323    /// `OoP` gear will merge this with local --config (local keys override master keys).
1324    #[serde(skip_serializing_if = "Option::is_none")]
1325    pub logging: Option<LoggingConfig>,
1326    /// OpenTelemetry configuration from master host (resource, tracing, metrics).
1327    #[serde(skip_serializing_if = "Option::is_none")]
1328    pub opentelemetry: Option<OpenTelemetryConfig>,
1329}
1330
1331impl RenderedGearConfig {
1332    /// Deserialize from JSON string (used when reading from env var).
1333    ///
1334    /// # Errors
1335    /// Returns an error if JSON parsing fails.
1336    pub fn from_json(json: &str) -> Result<Self> {
1337        serde_json::from_str(json).context("Failed to parse RenderedGearConfig from JSON")
1338    }
1339
1340    /// Serialize to JSON string (used when passing to `OoP` gears via env var).
1341    ///
1342    /// # Errors
1343    /// Returns an error if serialization fails.
1344    pub fn to_json(&self) -> Result<String> {
1345        serde_json::to_string(self).context("Failed to serialize RenderedGearConfig to JSON")
1346    }
1347}
1348
1349/// Render gear configuration for passing to `OoP` gear via environment variable.
1350///
1351/// This function prepares a structured configuration that an `OoP` gear can use
1352/// to initialize itself. The configuration includes:
1353/// - Database configuration (structured, for field-by-field merge in `OoP`)
1354/// - Gear config section
1355/// - Logging configuration (for key-by-key merge in `OoP`)
1356/// - Tracing configuration for OTEL
1357///
1358/// The runtime section is excluded as it's only relevant for the master host.
1359///
1360/// `OoP` gears receive this via `TOOLKIT_MODULE_CONFIG` env var and can override
1361/// any section with their local --config file.
1362///
1363/// # Errors
1364/// Returns an error if gear configuration parsing fails.
1365pub fn render_gear_config_for_oop(
1366    app: &AppConfig,
1367    gear_name: &str,
1368    _home_dir: &std::path::Path,
1369) -> Result<RenderedGearConfig> {
1370    // Get gear's database config (with server reference, but NOT resolved to DSN).
1371    // OoP gear will use DbManager to resolve this with its local overrides.
1372    let gear_db_config = parse_gear_config(app, gear_name)
1373        .ok()
1374        .and_then(|entry| entry.database);
1375
1376    // Build database config with global servers and gear config (structured, not resolved)
1377    let database = if gear_db_config.is_some() || app.database.is_some() {
1378        Some(RenderedDbConfig::new(app.database.clone(), gear_db_config))
1379    } else {
1380        None
1381    };
1382
1383    // Get the gear's config section (excluding database and runtime)
1384    let config = parse_gear_config(app, gear_name)
1385        .map(|entry| entry.config)
1386        .unwrap_or_default();
1387
1388    // Pass logging config from master host so OoP gears can merge with their local config
1389    let logging = app.logging.clone();
1390
1391    // Pass OpenTelemetry config from master host so OoP gears use the same settings
1392    let opentelemetry = if app.opentelemetry.tracing.enabled || app.opentelemetry.metrics.enabled {
1393        Some(app.opentelemetry.clone())
1394    } else {
1395        None
1396    };
1397
1398    Ok(RenderedGearConfig {
1399        database,
1400        config,
1401        logging: Some(logging),
1402        opentelemetry,
1403    })
1404}
1405
1406/// Parse a gear config from the config bag.
1407///
1408/// # Errors
1409/// Returns an error if the gear is not found or config parsing fails.
1410pub fn parse_gear_config(app: &AppConfig, gear_name: &str) -> Result<GearConfig> {
1411    let gear_raw = app
1412        .gears
1413        .get(gear_name)
1414        .cloned()
1415        .ok_or_else(|| anyhow::anyhow!("Gear '{gear_name}' not found in config"))?;
1416
1417    let gear_config: GearConfig = serde_json::from_value(gear_raw)?;
1418    Ok(gear_config)
1419}
1420
1421/// Helper to get runtime config for a gear (if present).
1422///
1423/// # Errors
1424/// Returns an error if gear config parsing fails.
1425pub fn get_gear_runtime_config(app: &AppConfig, gear_name: &str) -> Result<Option<GearRuntime>> {
1426    let entry = parse_gear_config(app, gear_name)?;
1427    Ok(entry.runtime)
1428}
1429
1430/// Merges global + gear DB configs into a final, validated DSN and pool config.
1431/// Precedence: Global DSN -> Global fields -> Gear DSN -> Gear fields (fields always win).
1432/// For server-based, returns error if final dbname is missing.
1433/// For `SQLite`, builds/normalizes sqlite DSN from file/path or uses a full DSN as-is.
1434///
1435/// # Arguments
1436/// * `dry_run` - If true, skip directory creation (for read-only inspection)
1437///
1438/// # Errors
1439/// Returns an error if database configuration is invalid or resolution fails.
1440pub fn build_final_db_for_gear(
1441    app: &AppConfig,
1442    gear_name: &str,
1443    home_dir: &Path,
1444    dry_run: bool,
1445) -> DbConfigResult {
1446    // Parse gear entry from raw JSON
1447    let Some(gear_raw) = app.gears.get(gear_name) else {
1448        return Ok(None); // No gear config
1449    };
1450
1451    let gear_entry: GearConfig = serde_json::from_value(gear_raw.clone())
1452        .with_context(|| format!("Invalid gear config structure for '{gear_name}'"))?;
1453
1454    let Some(gear_db_config) = gear_entry.database else {
1455        tracing::warn!(
1456            "Gear '{}' has no database configuration; DB capability disabled",
1457            gear_name
1458        );
1459        return Ok(None);
1460    };
1461
1462    // Global database config
1463    let global_db_config = app.database.as_ref();
1464
1465    // Build configuration using the builder pattern
1466    let mut builder = DbConfigBuilder::new();
1467
1468    // Step 1: Apply global server config if referenced
1469    if let Some(server_name) = &gear_db_config.server {
1470        let global_server = global_db_config
1471            .and_then(|gc| gc.servers.get(server_name))
1472            .ok_or_else(|| {
1473                anyhow::anyhow!("Referenced server '{server_name}' not found in global config")
1474            })?;
1475
1476        builder.apply_global_server(global_server, home_dir, gear_name, dry_run)?;
1477    }
1478
1479    // Step 2: Apply gear DSN (override global)
1480    if let Some(gear_dsn) = &gear_db_config.dsn {
1481        builder.apply_gear_dsn(gear_dsn.expose(), home_dir, gear_name, dry_run)?;
1482    }
1483
1484    // Step 3: Apply gear fields (override everything)
1485    builder.apply_gear_fields(&gear_db_config)?;
1486
1487    // Determine backend type and finalize DSN
1488    let is_sqlite = decide_backend(&builder, &gear_db_config);
1489
1490    let result_dsn = if is_sqlite {
1491        finalize_sqlite_dsn(&builder, &gear_db_config, gear_name, home_dir, dry_run)?
1492    } else {
1493        finalize_server_dsn(&builder, gear_name)?
1494    };
1495
1496    // Validate final DSN
1497    validate_dsn(&result_dsn)?;
1498
1499    // Redact password for logging
1500    let log_dsn = redact_dsn_for_logging(&result_dsn)?;
1501
1502    tracing::info!(
1503        "Built final DB config for gear '{}': {}",
1504        gear_name,
1505        log_dsn
1506    );
1507
1508    Ok(Some((result_dsn, builder.pool)))
1509}
1510
1511/// Helper function to get gear database configuration from `AppConfig`.
1512/// Returns the `DbConnConfig` for a gear, or None if the gear has no database config.
1513#[must_use]
1514pub fn get_gear_db_config(app: &AppConfig, gear_name: &str) -> Option<DbConnConfig> {
1515    let gear_raw = app.gears.get(gear_name)?;
1516    let gear_entry: GearConfig = serde_json::from_value(gear_raw.clone()).ok()?;
1517    gear_entry.database
1518}
1519
1520/// Helper function to resolve gear home directory.
1521/// Returns the path where gear-specific files (like `SQLite` databases) should be stored.
1522#[must_use]
1523pub fn gear_home(app: &AppConfig, gear_name: &str) -> PathBuf {
1524    PathBuf::from(&app.server.home_dir).join(gear_name)
1525}
1526
1527#[cfg(test)]
1528#[cfg_attr(coverage_nightly, coverage(off))]
1529mod tests {
1530    use super::*;
1531    use serial_test::serial;
1532    use std::fs;
1533    use temp_env::with_var;
1534    use tempfile::tempdir;
1535
1536    /// Helper: a normalized `home_dir` should be absolute and not start with '~'.
1537    fn is_normalized_path(p: &Path) -> bool {
1538        p.is_absolute() && !p.starts_with("~")
1539    }
1540
1541    /// Helper: platform default subdirectory name.
1542    fn default_subdir() -> &'static str {
1543        ".cf-gears"
1544    }
1545
1546    #[test]
1547    fn test_remap_gear_env_key() {
1548        // (input, expected) — input keys are the dot-joined segments figment
1549        // produces after `split("__")`, before its own lowercasing.
1550        let cases = [
1551            // Gear-name segment: underscores -> dashes.
1552            ("gears.my_gear.port", "gears.my-gear.port"),
1553            // Only the gear-name segment is remapped; nested fields keep '_'.
1554            ("gears.my_gear.max_age_days", "gears.my-gear.max_age_days"),
1555            // Multiple underscores in the gear name are all remapped.
1556            ("gears.a_b_c.field", "gears.a-b-c.field"),
1557            // Already-kebab gear name is unaffected (remapping '-' is a no-op).
1558            ("gears.my-gear.port", "gears.my-gear.port"),
1559            // Non-gears branches are left alone.
1560            ("vendor.my_vendor.key", "vendor.my_vendor.key"),
1561            ("server.home_dir", "server.home_dir"),
1562            // `gears` with no gear-name segment is left as-is.
1563            ("gears", "gears"),
1564            // Uppercase input is lowercased.
1565            ("GEARS.MY_GEAR.PORT", "gears.my-gear.port"),
1566            // Bare key without dots.
1567            ("server", "server"),
1568        ];
1569
1570        for (input, expected) in cases {
1571            assert_eq!(
1572                remap_gear_env_key(input),
1573                expected,
1574                "remap_gear_env_key({input:?})"
1575            );
1576        }
1577    }
1578
1579    #[test]
1580    fn test_default_config_structure() {
1581        let config = AppConfig::default();
1582
1583        // Database defaults (simplified structure)
1584        assert!(config.database.is_none());
1585
1586        // Logging defaults
1587        let logging = config.logging;
1588        assert!(logging.contains_key("default"));
1589
1590        let default_section = &logging["default"];
1591        assert_eq!(default_section.console_level, Some(Level::INFO));
1592        assert_eq!(default_section.file().unwrap(), "logs/cf-gears.log");
1593
1594        // Gears bag is empty by default
1595        assert!(config.gears.is_empty());
1596    }
1597
1598    #[test]
1599    fn oop_http_labels_coerce_numeric_and_bool_values_to_strings() {
1600        // A bare-numeric env value (e.g. `APP__OOP_HTTP__LABELS__SHARD=7`) is
1601        // parsed as an integer by the env layer; it must load as a string
1602        // label rather than aborting the config parse.
1603        let cfg: OopHttpConfig = serde_json::from_value(serde_json::json!({
1604            "listen_addr": "0.0.0.0:8080",
1605            "labels": {
1606                "shard": 7,
1607                "role": "ingest",
1608                "canary": true,
1609            }
1610        }))
1611        .expect("numeric/bool label values must deserialize");
1612
1613        assert_eq!(cfg.labels.get("shard").map(String::as_str), Some("7"));
1614        assert_eq!(cfg.labels.get("role").map(String::as_str), Some("ingest"));
1615        assert_eq!(cfg.labels.get("canary").map(String::as_str), Some("true"));
1616    }
1617
1618    // `#[serial]`: calls load_layered, which reads the APP__ env layer; serialize
1619    // against the env-override tests that mutate process-global APP__* vars.
1620    #[test]
1621    #[serial]
1622    fn test_load_layered_normalizes_home_dir() {
1623        let tmp = tempdir().unwrap();
1624        let cfg_path = tmp.path().join("cfg.yaml");
1625
1626        // Provide a user path with "~" to ensure expansion and normalization.
1627        let yaml = r#"
1628server:
1629  home_dir: "~/.test_cfgears"
1630
1631database:
1632  servers:
1633    test_postgres:
1634      dsn: "postgres://user:pass@localhost/db"
1635      pool:
1636        max_conns: 20
1637
1638logging:
1639  default:
1640    console_level: debug
1641    file: "logs/default.log"
1642"#;
1643        fs::write(&cfg_path, yaml).unwrap();
1644
1645        let config = AppConfig::load_layered(&cfg_path).unwrap();
1646
1647        // home_dir should be normalized immediately
1648        assert!(is_normalized_path(&config.server.home_dir));
1649        assert!(config.server.home_dir.ends_with(".test_cfgears"));
1650
1651        // database parsed (TODO: update test to use new config format)
1652        // For now, since this test uses old format YAML, we skip DB assertions
1653        // let db = config.database.as_ref().unwrap();
1654
1655        // logging parsed
1656        let logging = &config.logging;
1657        let def = &logging["default"];
1658        assert_eq!(def.console_level, Some(Level::DEBUG));
1659        assert_eq!(def.section_file.as_ref().unwrap().file, "logs/default.log");
1660    }
1661
1662    #[test]
1663    fn test_load_or_default_normalizes_home_dir_when_none() {
1664        // No external file => defaults, but home_dir must be normalized.
1665        // Ensure platform env is present for home resolution in CI.
1666        let tmp = tempdir().unwrap();
1667        let env_var = if cfg!(target_os = "windows") {
1668            "APPDATA"
1669        } else {
1670            "HOME"
1671        };
1672        with_var(env_var, Some(tmp.path().to_str().unwrap()), || {
1673            let config = AppConfig::load_or_default(None).unwrap();
1674            assert!(is_normalized_path(&config.server.home_dir));
1675            assert!(config.server.home_dir.ends_with(default_subdir()));
1676        });
1677    }
1678
1679    // `#[serial]`: load_layered reads the APP__ env layer, so `gears.is_empty()`
1680    // would race with the (also `#[serial]`) env-override tests that set APP__GEARS__*.
1681    #[test]
1682    #[serial]
1683    fn test_minimal_yaml_config() {
1684        let tmp = tempdir().unwrap();
1685        let cfg_path = tmp.path().join("cfg.yaml");
1686
1687        let yaml = r#"
1688server:
1689  home_dir: "~/.minimal"
1690"#;
1691        fs::write(&cfg_path, yaml).unwrap();
1692
1693        let config = AppConfig::load_layered(&cfg_path).unwrap();
1694
1695        // Required fields are parsed; home_dir normalized
1696        assert!(is_normalized_path(&config.server.home_dir));
1697        assert!(config.server.home_dir.ends_with(".minimal"));
1698
1699        // Optional sections default to None
1700        assert!(config.database.is_none());
1701        assert!(config.gears.is_empty());
1702    }
1703
1704    #[test]
1705    fn test_cli_overrides() {
1706        let mut config = AppConfig::default();
1707
1708        let args = CliArgs {
1709            config: None,
1710            print_config: false,
1711            verbose: 2, // trace
1712            mock: false,
1713        };
1714
1715        config.apply_cli_overrides(args.verbose);
1716
1717        // Port override
1718
1719        // Verbose override affects logging
1720        let logging = &config.logging;
1721        let default_section = &logging["default"];
1722        assert_eq!(default_section.console_level, Some(Level::TRACE));
1723    }
1724
1725    #[test]
1726    fn test_cli_verbose_levels_matrix() {
1727        for (verbose_level, expected_log_level) in [
1728            (0, Some(Level::INFO)), // unchanged from default
1729            (1, Some(Level::DEBUG)),
1730            (2, Some(Level::TRACE)),
1731            (3, Some(Level::TRACE)), // cap at trace
1732        ] {
1733            let mut config = AppConfig::default();
1734            let args = CliArgs {
1735                config: None,
1736                print_config: false,
1737                verbose: verbose_level,
1738                mock: false,
1739            };
1740
1741            config.apply_cli_overrides(args.verbose);
1742
1743            let logging = &config.logging;
1744            let default_section = &logging["default"];
1745
1746            if verbose_level == 0 {
1747                assert_eq!(default_section.console_level, Some(Level::INFO));
1748            } else {
1749                assert_eq!(default_section.console_level, expected_log_level);
1750            }
1751        }
1752    }
1753
1754    // `#[serial]`: calls load_layered (reads APP__ env layer) and asserts on the
1755    // gears map, which the env-override tests mutate via APP__GEARS__*.
1756    #[test]
1757    #[serial]
1758    fn test_layered_config_loading_with_gears_dir() {
1759        let tmp = tempdir().unwrap();
1760        let cfg_path = tmp.path().join("gears_dir.yaml");
1761        let gears_dir = tmp.path().join("gears");
1762
1763        fs::create_dir_all(&gears_dir).unwrap();
1764        let gear_cfg = gears_dir.join("test_gear.yaml");
1765        fs::write(
1766            &gear_cfg,
1767            r#"
1768setting1: "value1"
1769setting2: 42
1770"#,
1771        )
1772        .unwrap();
1773
1774        // Convert Windows paths to forward slashes for YAML compatibility
1775        let gears_dir_str = normalize_path(&gears_dir);
1776        let yaml = format!(
1777            r#"
1778server:
1779  home_dir: "~/.gears_test"
1780
1781gears_dir: "{gears_dir_str}"
1782
1783gears:
1784  existing_gear:
1785    key: "value"
1786"#
1787        );
1788
1789        fs::write(&cfg_path, yaml).unwrap();
1790
1791        let config = AppConfig::load_layered(&cfg_path).unwrap();
1792
1793        // Should have loaded the existing gear from gears section
1794        assert!(config.gears.contains_key("existing_gear"));
1795
1796        // Should have also loaded the gear from gears_dir
1797        assert!(config.gears.contains_key("test_gear"));
1798
1799        // Check the loaded gear config
1800        let test_gear = &config.gears["test_gear"];
1801        assert_eq!(test_gear["setting1"], "value1");
1802        assert_eq!(test_gear["setting2"], 42);
1803    }
1804
1805    // `#[serial]`: calls load_layered, which reads the APP__ env layer; serialize
1806    // against the env-override tests that mutate process-global APP__* vars.
1807    #[test]
1808    #[serial]
1809    fn test_load_and_init_logging_smoke() {
1810        // Just verifies structure is acceptable for logging init path.
1811        let tmp = tempdir().unwrap();
1812        let cfg_path = tmp.path().join("logging.yaml");
1813        let yaml = r#"
1814server:
1815  home_dir: "~/.logging_test"
1816
1817logging:
1818  default:
1819    console_level: debug
1820    file: ""
1821    file_level: info
1822"#;
1823        fs::write(&cfg_path, yaml).unwrap();
1824
1825        let config = AppConfig::load_layered(&cfg_path).unwrap();
1826        let logging = &config.logging;
1827        assert!(logging.contains_key("default"));
1828
1829        let default_section = &logging["default"];
1830        assert_eq!(default_section.console_level, Some(Level::DEBUG));
1831        assert_eq!(default_section.file_level(), Some(Level::INFO));
1832        // not calling init to avoid side effects in tests
1833    }
1834
1835    // ===================== DB Configuration Precedence Tests =====================
1836
1837    /// Helper function to create `AppConfig` with database server configuration
1838    fn create_app_with_server(server_name: &str, db_config: DbConnConfig) -> AppConfig {
1839        let mut servers = HashMap::new();
1840        servers.insert(server_name.to_owned(), db_config);
1841
1842        AppConfig {
1843            database: Some(GlobalDatabaseConfig {
1844                servers,
1845                auto_provision: None,
1846            }),
1847            ..Default::default()
1848        }
1849    }
1850
1851    /// Helper function to add a gear to `AppConfig`
1852    fn add_gear_to_app(app: &mut AppConfig, gear_name: &str, database_config: &serde_json::Value) {
1853        app.gears.insert(
1854            gear_name.to_owned(),
1855            serde_json::json!({
1856                "database": database_config,
1857                "config": {}
1858            }),
1859        );
1860    }
1861
1862    /// Helper function to add a gear with custom config to `AppConfig`
1863    fn add_gear_with_config(app: &mut AppConfig, gear_name: &str, config: &serde_json::Value) {
1864        app.gears.insert(
1865            gear_name.to_owned(),
1866            serde_json::json!({
1867                "database": {},
1868                "config": config
1869            }),
1870        );
1871    }
1872
1873    /// Helper function to create a minimal `AppConfig` for testing
1874    fn create_minimal_app() -> AppConfig {
1875        AppConfig {
1876            database: None,
1877            gears: HashMap::new(),
1878            ..Default::default()
1879        }
1880    }
1881
1882    #[test]
1883    fn test_precedence_global_dsn_only() {
1884        let tmp = tempdir().unwrap();
1885        let home_dir = tmp.path();
1886
1887        let mut app = create_app_with_server(
1888            "test_server",
1889            DbConnConfig {
1890                dsn: Some(toolkit_utils::SecretString::new(
1891                    "postgresql://global_user:global_pass@global_host:5432/global_db",
1892                )),
1893                ..Default::default()
1894            },
1895        );
1896
1897        // Gear references global server
1898        add_gear_to_app(
1899            &mut app,
1900            "test_gear",
1901            &serde_json::json!({
1902                "server": "test_server"
1903            }),
1904        );
1905
1906        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
1907        assert!(result.is_some());
1908
1909        let (dsn, _pool) = result.unwrap();
1910        assert!(dsn.contains("global_user"));
1911        assert!(dsn.contains("global_host"));
1912        assert!(dsn.contains("global_db"));
1913    }
1914
1915    #[test]
1916    fn test_precedence_global_fields_only() {
1917        let tmp = tempdir().unwrap();
1918        let home_dir = tmp.path();
1919
1920        let mut app = create_app_with_server(
1921            "test_server",
1922            DbConnConfig {
1923                host: Some("field_host".to_owned()),
1924                port: Some(5433),
1925                user: Some("field_user".to_owned()),
1926                dbname: Some("field_db".to_owned()),
1927                ..Default::default()
1928            },
1929        );
1930
1931        // Gear references global server
1932        add_gear_to_app(
1933            &mut app,
1934            "test_gear",
1935            &serde_json::json!({
1936                "server": "test_server"
1937            }),
1938        );
1939
1940        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
1941        assert!(result.is_some());
1942
1943        let (dsn, _pool) = result.unwrap();
1944        assert!(dsn.contains("field_host"));
1945        assert!(dsn.contains("5433"));
1946        assert!(dsn.contains("field_user"));
1947        assert!(dsn.contains("field_db"));
1948    }
1949
1950    #[test]
1951    fn test_precedence_gear_dsn_only() {
1952        let tmp = tempdir().unwrap();
1953        let home_dir = tmp.path();
1954
1955        let app = AppConfig {
1956            gears: {
1957                let mut gears = HashMap::new();
1958                gears.insert(
1959                    "test_gear".to_owned(),
1960                    serde_json::json!({
1961                        "database": {
1962                            "dsn": "sqlite://gear_test.db?wal=true&synchronous=NORMAL"
1963                        },
1964                        "config": {}
1965                    }),
1966                );
1967                gears
1968            },
1969            ..Default::default()
1970        };
1971
1972        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
1973        assert!(result.is_some());
1974
1975        let (dsn, _pool) = result.unwrap();
1976        assert!(dsn.contains("gear_test.db"));
1977        assert!(dsn.contains("wal=true"));
1978    }
1979
1980    #[test]
1981    fn test_precedence_gear_fields_only() {
1982        let tmp = tempdir().unwrap();
1983        let home_dir = tmp.path();
1984
1985        let app = AppConfig {
1986            gears: {
1987                let mut gears = HashMap::new();
1988                gears.insert(
1989                    "test_gear".to_owned(),
1990                    serde_json::json!({
1991                        "database": {
1992                            "file": "gear_fields.db"
1993                        },
1994                        "config": {}
1995                    }),
1996                );
1997                gears
1998            },
1999            ..Default::default()
2000        };
2001
2002        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2003        assert!(result.is_some());
2004
2005        let (dsn, _pool) = result.unwrap();
2006        assert!(dsn.contains("gear_fields.db"));
2007        // Platform-specific DSN format check
2008        #[cfg(windows)]
2009        assert!(dsn.starts_with("sqlite:") && !dsn.starts_with("sqlite://"));
2010        #[cfg(unix)]
2011        assert!(dsn.starts_with("sqlite://"));
2012    }
2013
2014    #[test]
2015    fn test_precedence_fields_override_dsn() {
2016        let tmp = tempdir().unwrap();
2017        let home_dir = tmp.path();
2018
2019        let mut app = create_app_with_server(
2020            "test_server",
2021            DbConnConfig {
2022                dsn: Some(toolkit_utils::SecretString::new(
2023                    "postgresql://old_user:old_pass@old_host:5432/old_db",
2024                )),
2025                host: Some("new_host".to_owned()), // This should override DSN host
2026                port: Some(5433),                  // This should override DSN port
2027                user: Some("new_user".to_owned()), // This should override DSN user
2028                dbname: Some("new_db".to_owned()), // This should override DSN dbname
2029                ..Default::default()
2030            },
2031        );
2032
2033        // Gear also overrides some fields
2034        add_gear_to_app(
2035            &mut app,
2036            "test_gear",
2037            &serde_json::json!({
2038                "server": "test_server",
2039                "port": 5434  // Gear field should override global field
2040            }),
2041        );
2042
2043        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2044        assert!(result.is_some());
2045
2046        let (dsn, _pool) = result.unwrap();
2047        // Fields should override DSN parts
2048        assert!(dsn.contains("new_host"));
2049        assert!(dsn.contains("5434")); // Gear override should win
2050        assert!(dsn.contains("new_user"));
2051        assert!(dsn.contains("new_db"));
2052        // Old DSN values should not appear
2053        assert!(!dsn.contains("old_host"));
2054        assert!(!dsn.contains("5432"));
2055        assert!(!dsn.contains("old_user"));
2056        assert!(!dsn.contains("old_db"));
2057    }
2058
2059    #[test]
2060    fn test_env_expansion_password() {
2061        let tmp = tempdir().unwrap();
2062        let home_dir = tmp.path();
2063
2064        with_var("TEST_DB_PASSWORD", Some("secret123"), || {
2065            let mut app = create_app_with_server(
2066                "test_server",
2067                DbConnConfig {
2068                    host: Some("localhost".to_owned()),
2069                    port: Some(5432),
2070                    user: Some("testuser".to_owned()),
2071                    password: Some(toolkit_utils::SecretString::new("${TEST_DB_PASSWORD}")), // Should expand to "secret123"
2072                    dbname: Some("testdb".to_owned()),
2073                    ..Default::default()
2074                },
2075            );
2076
2077            add_gear_to_app(
2078                &mut app,
2079                "test_gear",
2080                &serde_json::json!({
2081                    "server": "test_server"
2082                }),
2083            );
2084
2085            let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2086            assert!(result.is_some());
2087
2088            let (dsn, _pool) = result.unwrap();
2089            assert!(dsn.contains("secret123"));
2090        });
2091    }
2092
2093    #[test]
2094    fn test_env_expansion_in_dsn() {
2095        let tmp = tempdir().unwrap();
2096        let home_dir = tmp.path();
2097
2098        temp_env::with_vars(
2099            [
2100                ("DB_HOST", Some("test-server")),
2101                ("DB_PASSWORD", Some("env_secret")),
2102            ],
2103            || {
2104                let mut app = create_app_with_server(
2105                    "test_server",
2106                    DbConnConfig {
2107                        dsn: Some(toolkit_utils::SecretString::new(
2108                            "postgresql://user:${DB_PASSWORD}@${DB_HOST}:5432/mydb",
2109                        )),
2110                        ..Default::default()
2111                    },
2112                );
2113
2114                add_gear_to_app(
2115                    &mut app,
2116                    "test_gear",
2117                    &serde_json::json!({
2118                        "server": "test_server"
2119                    }),
2120                );
2121
2122                let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2123                assert!(result.is_some());
2124
2125                let (dsn, _pool) = result.unwrap();
2126                assert!(dsn.contains("test-server"));
2127                assert!(dsn.contains("env_secret"));
2128                // ${} placeholders should be replaced
2129                assert!(!dsn.contains("${DB_HOST}"));
2130                assert!(!dsn.contains("${DB_PASSWORD}"));
2131            },
2132        );
2133    }
2134
2135    #[test]
2136    fn test_sqlite_file_path_resolution() {
2137        let tmp = tempdir().unwrap();
2138        let home_dir = tmp.path();
2139
2140        // Test 1: file (relative to home_dir/gear_name/)
2141        let app1 = AppConfig {
2142            gears: {
2143                let mut gears = HashMap::new();
2144                gears.insert(
2145                    "test_gear".to_owned(),
2146                    serde_json::json!({
2147                        "database": {
2148                            "file": "test.db"
2149                        },
2150                        "config": {}
2151                    }),
2152                );
2153                gears
2154            },
2155            ..Default::default()
2156        };
2157
2158        let result1 = build_final_db_for_gear(&app1, "test_gear", home_dir, false).unwrap();
2159        assert!(result1.is_some());
2160        let (dsn1, _) = result1.unwrap();
2161        assert!(dsn1.contains("test_gear"));
2162        assert!(dsn1.contains("test.db"));
2163
2164        // Test 2: path (absolute path)
2165        let abs_path = tmp.path().join("absolute.db");
2166        let app2 = AppConfig {
2167            gears: {
2168                let mut gears = HashMap::new();
2169                gears.insert(
2170                    "test_gear".to_owned(),
2171                    serde_json::json!({
2172                        "database": {
2173                            "path": abs_path.to_string_lossy()
2174                        },
2175                        "config": {}
2176                    }),
2177                );
2178                gears
2179            },
2180            ..Default::default()
2181        };
2182
2183        let result2 = build_final_db_for_gear(&app2, "test_gear", home_dir, false).unwrap();
2184        assert!(result2.is_some());
2185        let (dsn2, _) = result2.unwrap();
2186        assert!(dsn2.contains("absolute.db"));
2187
2188        // Test 3: no file or path (should default to gear_name.sqlite)
2189        let app3 = AppConfig {
2190            gears: {
2191                let mut gears = HashMap::new();
2192                gears.insert(
2193                    "test_gear".to_owned(),
2194                    serde_json::json!({
2195                        "database": {},
2196                        "config": {}
2197                    }),
2198                );
2199                gears
2200            },
2201            ..Default::default()
2202        };
2203
2204        let result3 = build_final_db_for_gear(&app3, "test_gear", home_dir, false).unwrap();
2205        assert!(result3.is_some());
2206        let (dsn3, _) = result3.unwrap();
2207        assert!(dsn3.contains("test_gear.sqlite"));
2208    }
2209
2210    #[cfg(windows)]
2211    #[test]
2212    fn test_sqlite_path_resolution_windows() {
2213        let tmp = tempdir().unwrap();
2214        let home_dir = tmp.path();
2215
2216        let app = AppConfig {
2217            gears: {
2218                let mut gears = HashMap::new();
2219                gears.insert(
2220                    "test_gear".to_owned(),
2221                    serde_json::json!({
2222                        "database": {
2223                            "file": "test.db"
2224                        },
2225                        "config": {}
2226                    }),
2227                );
2228                gears
2229            },
2230            ..Default::default()
2231        };
2232
2233        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2234        assert!(result.is_some());
2235        let (dsn, _) = result.unwrap();
2236
2237        // On Windows, paths should be normalized to forward slashes in DSN
2238        assert!(!dsn.contains('\\'));
2239        assert!(dsn.contains('/'));
2240    }
2241
2242    #[test]
2243    fn test_sqlite_dsn_with_server_reference_and_dbname_override() {
2244        let tmp = tempdir().unwrap();
2245        let home_dir = tmp.path();
2246
2247        let mut app = AppConfig::default();
2248
2249        // Global server with SQLite DSN and query params
2250        let mut servers = HashMap::new();
2251        servers.insert(
2252            "sqlite_users".to_owned(),
2253            DbConnConfig {
2254                engine: None,
2255                dsn: Some(toolkit_utils::SecretString::new(
2256                    "sqlite://users_info.db?WAL=true&synchronous=NORMAL&busy_timeout=5000",
2257                )),
2258                host: None,
2259                port: None,
2260                user: None,
2261                password: None,
2262                dbname: None,
2263                params: None,
2264                pool: None,
2265                file: None,
2266                path: None,
2267                lock_keepalive: None,
2268                server: None,
2269            },
2270        );
2271
2272        app.database = Some(GlobalDatabaseConfig {
2273            servers,
2274            auto_provision: None,
2275        });
2276
2277        // Gear that references the server but overrides the dbname
2278        app.gears.insert(
2279            "users_info".to_owned(),
2280            serde_json::json!({
2281                "database": {
2282                    "server": "sqlite_users",
2283                    "dbname": "users_info.db"
2284                },
2285                "config": {}
2286            }),
2287        );
2288
2289        let result = build_final_db_for_gear(&app, "users_info", home_dir, false).unwrap();
2290        assert!(result.is_some());
2291        let (dsn, _) = result.unwrap();
2292
2293        // Should be an absolute path with preserved query parameters
2294        assert!(dsn.contains("?WAL=true&synchronous=NORMAL&busy_timeout=5000"));
2295        assert!(dsn.contains("users_info/users_info.db"));
2296
2297        // Platform-specific path format
2298        #[cfg(windows)]
2299        {
2300            // Windows should use sqlite:C:/path format
2301            assert!(dsn.starts_with("sqlite:"));
2302            assert!(!dsn.starts_with("sqlite://"));
2303        }
2304
2305        #[cfg(unix)]
2306        {
2307            // Unix should use sqlite://path format
2308            assert!(dsn.starts_with("sqlite://"));
2309        }
2310    }
2311
2312    #[cfg(unix)]
2313    #[test]
2314    fn test_sqlite_path_resolution_unix() {
2315        let tmp = tempdir().unwrap();
2316        let home_dir = tmp.path();
2317
2318        let app = AppConfig {
2319            gears: {
2320                let mut gears = HashMap::new();
2321                gears.insert(
2322                    "test_gear".to_owned(),
2323                    serde_json::json!({
2324                        "database": {
2325                            "file": "test.db"
2326                        },
2327                        "config": {}
2328                    }),
2329                );
2330                gears
2331            },
2332            ..Default::default()
2333        };
2334
2335        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2336        assert!(result.is_some());
2337        let (dsn, _) = result.unwrap();
2338
2339        // On Unix, paths should be absolute
2340        assert!(dsn.starts_with("sqlite://"));
2341        assert!(dsn.contains("/test_gear/test.db"));
2342    }
2343
2344    #[test]
2345    fn test_server_based_db_missing_dbname_error() {
2346        let tmp = tempdir().unwrap();
2347        let home_dir = tmp.path();
2348
2349        let mut app = create_app_with_server(
2350            "test_server",
2351            DbConnConfig {
2352                host: Some("localhost".to_owned()),
2353                port: Some(5432),
2354                user: Some("testuser".to_owned()),
2355                // Missing dbname for server-based DB
2356                ..Default::default()
2357            },
2358        );
2359
2360        add_gear_to_app(
2361            &mut app,
2362            "test_gear",
2363            &serde_json::json!({
2364                "server": "test_server"
2365            }),
2366        );
2367
2368        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false);
2369        assert!(result.is_err());
2370        let error_msg = result.unwrap_err().to_string();
2371        assert!(error_msg.contains("missing required 'dbname'"));
2372    }
2373
2374    #[test]
2375    fn test_gear_no_database_config() {
2376        let tmp = tempdir().unwrap();
2377        let home_dir = tmp.path();
2378
2379        // Gear with no database section
2380        let app = AppConfig {
2381            gears: {
2382                let mut gears = HashMap::new();
2383                gears.insert(
2384                    "no_db_gear".to_owned(),
2385                    serde_json::json!({
2386                        "config": {
2387                            "some_setting": "value"
2388                        }
2389                    }),
2390                );
2391                gears
2392            },
2393            ..Default::default()
2394        };
2395
2396        let result = build_final_db_for_gear(&app, "no_db_gear", home_dir, false).unwrap();
2397        assert!(result.is_none());
2398    }
2399
2400    #[test]
2401    fn test_gear_empty_database_config() {
2402        let tmp = tempdir().unwrap();
2403        let home_dir = tmp.path();
2404
2405        // Gear with empty database section
2406        let app = AppConfig {
2407            gears: {
2408                let mut gears = HashMap::new();
2409                gears.insert(
2410                    "empty_db_gear".to_owned(),
2411                    serde_json::json!({
2412                        "database": null,
2413                        "config": {}
2414                    }),
2415                );
2416                gears
2417            },
2418            ..Default::default()
2419        };
2420
2421        let result = build_final_db_for_gear(&app, "empty_db_gear", home_dir, false).unwrap();
2422        assert!(result.is_none());
2423    }
2424
2425    #[test]
2426    fn test_referenced_server_not_found() {
2427        let tmp = tempdir().unwrap();
2428        let home_dir = tmp.path();
2429
2430        let app = AppConfig {
2431            gears: {
2432                let mut gears = HashMap::new();
2433                gears.insert(
2434                    "test_gear".to_owned(),
2435                    serde_json::json!({
2436                        "database": {
2437                            "server": "nonexistent_server"
2438                        },
2439                        "config": {}
2440                    }),
2441                );
2442                gears
2443            },
2444            ..Default::default()
2445        };
2446
2447        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false);
2448        assert!(result.is_err());
2449        let error_msg = result.unwrap_err().to_string();
2450        assert!(error_msg.contains("Referenced server 'nonexistent_server' not found"));
2451    }
2452
2453    #[test]
2454    fn test_dsn_validation_invalid_url() {
2455        let tmp = tempdir().unwrap();
2456        let home_dir = tmp.path();
2457
2458        let app = AppConfig {
2459            gears: {
2460                let mut gears = HashMap::new();
2461                gears.insert(
2462                    "test_gear".to_owned(),
2463                    serde_json::json!({
2464                        "database": {
2465                            "dsn": "invalid://not-a-valid[url"
2466                        },
2467                        "config": {}
2468                    }),
2469                );
2470                gears
2471            },
2472            ..Default::default()
2473        };
2474
2475        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false);
2476        assert!(result.is_err());
2477    }
2478
2479    #[test]
2480    fn test_env_variable_not_found() {
2481        let tmp = tempdir().unwrap();
2482        let home_dir = tmp.path();
2483
2484        // Use with_var with None to ensure the env var doesn't exist
2485        with_var("NONEXISTENT_PASSWORD", None::<&str>, || {
2486            let mut app = create_app_with_server(
2487                "test_server",
2488                DbConnConfig {
2489                    host: Some("localhost".to_owned()),
2490                    password: Some(toolkit_utils::SecretString::new("${NONEXISTENT_PASSWORD}")),
2491                    dbname: Some("testdb".to_owned()),
2492                    ..Default::default()
2493                },
2494            );
2495
2496            add_gear_to_app(
2497                &mut app,
2498                "test_gear",
2499                &serde_json::json!({
2500                    "server": "test_server"
2501                }),
2502            );
2503
2504            let result = build_final_db_for_gear(&app, "test_gear", home_dir, false);
2505            assert!(result.is_err());
2506            let error_msg = result.unwrap_err().to_string();
2507            assert!(error_msg.contains("NONEXISTENT_PASSWORD"));
2508        });
2509    }
2510
2511    #[test]
2512    fn test_sqlite_at_file_relative_path() {
2513        let tmp = tempdir().unwrap();
2514        let home_dir = tmp.path();
2515
2516        let app = AppConfig {
2517            gears: {
2518                let mut gears = HashMap::new();
2519                gears.insert(
2520                    "test_gear".to_owned(),
2521                    serde_json::json!({
2522                        "database": {
2523                            "dsn": "sqlite://@file(users.db)"
2524                        },
2525                        "config": {}
2526                    }),
2527                );
2528                gears
2529            },
2530            ..Default::default()
2531        };
2532
2533        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2534        assert!(result.is_some());
2535
2536        let (dsn, _pool) = result.unwrap();
2537        assert!(dsn.contains("test_gear"));
2538        assert!(dsn.contains("users.db"));
2539        // Platform-specific DSN format check
2540        #[cfg(windows)]
2541        assert!(dsn.starts_with("sqlite:") && !dsn.starts_with("sqlite://"));
2542        #[cfg(unix)]
2543        assert!(dsn.starts_with("sqlite:///"));
2544    }
2545
2546    #[test]
2547    fn test_sqlite_at_file_absolute_path() {
2548        let tmp = tempdir().unwrap();
2549        let home_dir = tmp.path();
2550        let abs_path = tmp.path().join("absolute_db.sqlite");
2551
2552        let app = AppConfig {
2553            gears: {
2554                let mut gears = HashMap::new();
2555                gears.insert(
2556                    "test_gear".to_owned(),
2557                    serde_json::json!({
2558                        "database": {
2559                            "dsn": format!("sqlite://@file({})", abs_path.to_string_lossy())
2560                        },
2561                        "config": {}
2562                    }),
2563                );
2564                gears
2565            },
2566            ..Default::default()
2567        };
2568
2569        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2570        assert!(result.is_some());
2571
2572        let (dsn, _pool) = result.unwrap();
2573        assert!(dsn.contains("absolute_db.sqlite"));
2574        // Platform-specific DSN format check
2575        #[cfg(windows)]
2576        assert!(dsn.starts_with("sqlite:") && !dsn.starts_with("sqlite://"));
2577        #[cfg(unix)]
2578        assert!(dsn.starts_with("sqlite:///"));
2579    }
2580
2581    #[test]
2582    fn test_sqlite_empty_dsn_default() {
2583        let tmp = tempdir().unwrap();
2584        let home_dir = tmp.path();
2585
2586        let app = AppConfig {
2587            gears: {
2588                let mut gears = HashMap::new();
2589                gears.insert(
2590                    "test_gear".to_owned(),
2591                    serde_json::json!({
2592                        "database": {
2593                            "dsn": "sqlite://"
2594                        },
2595                        "config": {}
2596                    }),
2597                );
2598                gears
2599            },
2600            ..Default::default()
2601        };
2602
2603        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2604        assert!(result.is_some());
2605
2606        let (dsn, _pool) = result.unwrap();
2607        assert!(dsn.contains("test_gear"));
2608        assert!(dsn.contains("test_gear.sqlite"));
2609        // Platform-specific DSN format check
2610        #[cfg(windows)]
2611        assert!(dsn.starts_with("sqlite:") && !dsn.starts_with("sqlite://"));
2612        #[cfg(unix)]
2613        assert!(dsn.starts_with("sqlite:///"));
2614    }
2615
2616    #[test]
2617    fn test_sqlite_at_file_invalid_syntax() {
2618        let tmp = tempdir().unwrap();
2619        let home_dir = tmp.path();
2620
2621        let app = AppConfig {
2622            gears: {
2623                let mut gears = HashMap::new();
2624                gears.insert(
2625                    "test_gear".to_owned(),
2626                    serde_json::json!({
2627                        "database": {
2628                            "dsn": "sqlite://@file(missing_closing_paren"
2629                        },
2630                        "config": {}
2631                    }),
2632                );
2633                gears
2634            },
2635            ..Default::default()
2636        };
2637
2638        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false);
2639        assert!(result.is_err());
2640        let error_msg = result.unwrap_err().to_string();
2641        assert!(error_msg.contains("Invalid @file() syntax"));
2642    }
2643
2644    #[test]
2645    fn test_dsn_special_characters_in_credentials() {
2646        let tmp = tempdir().unwrap();
2647        let home_dir = tmp.path();
2648
2649        // Test with special characters in username and password
2650        let mut app = create_app_with_server(
2651            "test_server",
2652            DbConnConfig {
2653                host: Some("localhost".to_owned()),
2654                port: Some(5432),
2655                user: Some("user@domain".to_owned()),
2656                password: Some(toolkit_utils::SecretString::new(
2657                    "pa@ss:w0rd/with%special&chars",
2658                )),
2659                dbname: Some("test/db".to_owned()),
2660                ..Default::default()
2661            },
2662        );
2663
2664        add_gear_to_app(
2665            &mut app,
2666            "test_gear",
2667            &serde_json::json!({
2668                "server": "test_server"
2669            }),
2670        );
2671
2672        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2673        assert!(result.is_some());
2674
2675        let (dsn, _pool) = result.unwrap();
2676
2677        // Verify DSN is properly encoded
2678        assert!(dsn.starts_with("postgresql://"));
2679        assert!(dsn.contains("user%40domain")); // @ encoded as %40
2680        assert!(dsn.contains("/test%2Fdb")); // / in dbname encoded as %2F
2681
2682        // Verify DSN is parseable and contains expected user
2683        validate_dsn(&dsn).expect("DSN with special characters should be valid");
2684
2685        // Parse the DSN to verify it contains the correct components
2686        let parsed_dsn = dsn::parse(&dsn).expect("DSN should be parseable");
2687        assert_eq!(parsed_dsn.username.as_deref(), Some("user@domain"));
2688        assert_eq!(
2689            parsed_dsn.password.as_deref(),
2690            Some("pa@ss:w0rd/with%special&chars")
2691        );
2692        // Note: dsn crate may have limitations with path parsing - just verify the main DSN works
2693        // The important thing is that the DSN is valid and contains the right components
2694    }
2695
2696    #[test]
2697    #[allow(clippy::non_ascii_literal)]
2698    fn test_dsn_unicode_characters() {
2699        let tmp = tempdir().unwrap();
2700        let home_dir = tmp.path();
2701
2702        // Test with Unicode characters
2703        let mut app = create_app_with_server(
2704            "test_server",
2705            DbConnConfig {
2706                host: Some("localhost".to_owned()),
2707                user: Some("ユーザー".to_owned()), // Japanese characters
2708                dbname: Some("unicode_db".to_owned()),
2709                ..Default::default()
2710            },
2711        );
2712
2713        add_gear_to_app(
2714            &mut app,
2715            "test_gear",
2716            &serde_json::json!({
2717                "server": "test_server"
2718            }),
2719        );
2720
2721        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2722        assert!(result.is_some());
2723
2724        let (dsn, _pool) = result.unwrap();
2725
2726        // Verify DSN is properly encoded with Unicode
2727        assert!(dsn.starts_with("postgresql://"));
2728        // Unicode characters should be percent-encoded
2729        assert!(dsn.contains('%')); // Should contain encoded characters
2730
2731        // Verify DSN is parseable
2732        validate_dsn(&dsn).expect("DSN with Unicode characters should be valid");
2733    }
2734
2735    #[test]
2736    fn test_dsn_query_parameters_encoding() {
2737        let tmp = tempdir().unwrap();
2738        let home_dir = tmp.path();
2739
2740        let mut params = HashMap::new();
2741        params.insert("ssl mode".to_owned(), "require & verify".to_owned());
2742        params.insert("application_name".to_owned(), "my-app/v1.0".to_owned());
2743
2744        let mut app = create_app_with_server(
2745            "test_server",
2746            DbConnConfig {
2747                host: Some("localhost".to_owned()),
2748                user: Some("testuser".to_owned()),
2749                dbname: Some("testdb".to_owned()),
2750                params: Some(params),
2751                ..Default::default()
2752            },
2753        );
2754
2755        add_gear_to_app(
2756            &mut app,
2757            "test_gear",
2758            &serde_json::json!({
2759                "server": "test_server"
2760            }),
2761        );
2762
2763        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2764        assert!(result.is_some());
2765
2766        let (dsn, _pool) = result.unwrap();
2767
2768        // Verify query parameters are properly encoded (spaces become +, & becomes %26)
2769        assert!(dsn.contains("ssl+mode=require+%26+verify"));
2770        assert!(dsn.contains("application_name=my-app%2Fv1.0"));
2771
2772        // Verify DSN is parseable
2773        validate_dsn(&dsn).expect("DSN with encoded query parameters should be valid");
2774    }
2775
2776    #[test]
2777    fn test_pool_config_merging() {
2778        use std::time::Duration;
2779
2780        let tmp = tempdir().unwrap();
2781        let home_dir = tmp.path();
2782
2783        // Global server with pool config
2784        let mut app = create_app_with_server(
2785            "test_server",
2786            DbConnConfig {
2787                host: Some("localhost".to_owned()),
2788                dbname: Some("testdb".to_owned()),
2789                pool: Some(PoolCfg {
2790                    max_conns: Some(10),
2791                    min_conns: None,
2792                    acquire_timeout: Some(Duration::from_secs(5)),
2793                    idle_timeout: None,
2794                    max_lifetime: None,
2795                    test_before_acquire: None,
2796                }),
2797                ..Default::default()
2798            },
2799        );
2800
2801        // Gear overrides only max_conns
2802        add_gear_to_app(
2803            &mut app,
2804            "test_gear",
2805            &serde_json::json!({
2806                "server": "test_server",
2807                "pool": {
2808                    "max_conns": 20
2809                }
2810            }),
2811        );
2812
2813        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2814        assert!(result.is_some());
2815
2816        let (_dsn, pool) = result.unwrap();
2817        assert_eq!(pool.max_conns, Some(20)); // Gear override wins
2818        assert_eq!(pool.acquire_timeout, Some(Duration::from_secs(5))); // Global value preserved
2819    }
2820
2821    #[test]
2822    fn test_pool_config_gear_overrides_all() {
2823        use std::time::Duration;
2824
2825        let tmp = tempdir().unwrap();
2826        let home_dir = tmp.path();
2827
2828        // Global server with pool config
2829        let mut app = create_app_with_server(
2830            "test_server",
2831            DbConnConfig {
2832                host: Some("localhost".to_owned()),
2833                dbname: Some("testdb".to_owned()),
2834                pool: Some(PoolCfg {
2835                    max_conns: Some(10),
2836                    min_conns: None,
2837                    acquire_timeout: Some(Duration::from_secs(5)),
2838                    idle_timeout: None,
2839                    max_lifetime: None,
2840                    test_before_acquire: None,
2841                }),
2842                ..Default::default()
2843            },
2844        );
2845
2846        // Gear overrides both pool settings
2847        add_gear_to_app(
2848            &mut app,
2849            "test_gear",
2850            &serde_json::json!({
2851                "server": "test_server",
2852                "pool": {
2853                    "max_conns": 30,
2854                    "acquire_timeout": "10s"
2855                }
2856            }),
2857        );
2858
2859        let result = build_final_db_for_gear(&app, "test_gear", home_dir, false).unwrap();
2860        assert!(result.is_some());
2861
2862        let (_dsn, pool) = result.unwrap();
2863        assert_eq!(pool.max_conns, Some(30));
2864        assert_eq!(pool.acquire_timeout, Some(Duration::from_secs(10)));
2865    }
2866
2867    #[test]
2868    fn test_list_gear_names() {
2869        let mut app = create_minimal_app();
2870        add_gear_with_config(&mut app, "zebra_gear", &serde_json::json!({}));
2871        add_gear_with_config(&mut app, "alpha_gear", &serde_json::json!({}));
2872        add_gear_with_config(&mut app, "beta_gear", &serde_json::json!({}));
2873
2874        let gear_names = list_gear_names(&app);
2875
2876        // Should be sorted alphabetically
2877        assert_eq!(gear_names.len(), 3);
2878        assert_eq!(gear_names[0], "alpha_gear");
2879        assert_eq!(gear_names[1], "beta_gear");
2880        assert_eq!(gear_names[2], "zebra_gear");
2881    }
2882
2883    #[test]
2884    fn test_list_gear_names_empty() {
2885        let app = create_minimal_app();
2886        let gear_names = list_gear_names(&app);
2887        assert_eq!(gear_names.len(), 0);
2888    }
2889
2890    #[test]
2891    fn test_redact_dsn_password_postgres() {
2892        let dsn = "postgres://user:secretpass@localhost:5432/mydb";
2893        let redacted = redact_dsn_password(dsn).unwrap();
2894        assert_eq!(
2895            redacted,
2896            "postgres://user:***REDACTED***@localhost:5432/mydb"
2897        );
2898    }
2899
2900    #[test]
2901    fn test_redact_dsn_password_no_password() {
2902        let dsn = "postgres://user@localhost:5432/mydb";
2903        let redacted = redact_dsn_password(dsn).unwrap();
2904        // No password means no redaction needed
2905        assert_eq!(redacted, "postgres://user@localhost:5432/mydb");
2906    }
2907
2908    #[test]
2909    fn test_redact_dsn_password_special_chars() {
2910        let dsn = "postgres://user:p@ss%40word@localhost:5432/mydb";
2911        let redacted = redact_dsn_password(dsn).unwrap();
2912        assert_eq!(
2913            redacted,
2914            "postgres://user:***REDACTED***@localhost:5432/mydb"
2915        );
2916    }
2917
2918    #[test]
2919    fn test_render_effective_gears_config() {
2920        let mut app = create_minimal_app();
2921        add_gear_with_config(
2922            &mut app,
2923            "test_gear",
2924            &serde_json::json!({
2925                "my_setting": "my_value",
2926                "enabled": true
2927            }),
2928        );
2929
2930        let result = render_effective_gears_config(&app).unwrap();
2931
2932        // Check structure
2933        assert!(result.is_object());
2934        let gears = result.as_object().unwrap();
2935        assert!(gears.contains_key("test_gear"));
2936
2937        let test_gear = gears.get("test_gear").unwrap();
2938        assert!(test_gear.is_object());
2939        let test_gear_obj = test_gear.as_object().unwrap();
2940
2941        // Should have config section
2942        assert!(test_gear_obj.contains_key("config"));
2943
2944        // Check config section
2945        let config = test_gear_obj.get("config").unwrap();
2946        assert_eq!(config.get("my_setting").unwrap(), "my_value");
2947        assert_eq!(config.get("enabled").unwrap(), true);
2948    }
2949
2950    #[test]
2951    fn test_render_effective_gears_config_with_database() {
2952        let mut app = create_app_with_server(
2953            "test_server",
2954            DbConnConfig {
2955                host: Some("localhost".to_owned()),
2956                port: Some(5432),
2957                user: Some("user".to_owned()),
2958                password: Some(toolkit_utils::SecretString::new("pass")),
2959                dbname: Some("db".to_owned()),
2960                ..Default::default()
2961            },
2962        );
2963
2964        // Gear with database config
2965        add_gear_to_app(
2966            &mut app,
2967            "test_gear",
2968            &serde_json::json!({
2969                "server": "test_server"
2970            }),
2971        );
2972
2973        let result = render_effective_gears_config(&app).unwrap();
2974        let gears = result.as_object().unwrap();
2975        let test_gear = gears.get("test_gear").unwrap().as_object().unwrap();
2976
2977        // Should have database section
2978        assert!(test_gear.contains_key("database"));
2979        let database = test_gear.get("database").unwrap().as_object().unwrap();
2980        assert!(database.contains_key("dsn"));
2981
2982        // DSN should be redacted
2983        let dsn = database.get("dsn").unwrap().as_str().unwrap();
2984        assert!(dsn.contains("***REDACTED***"));
2985        assert!(!dsn.contains("pass"));
2986    }
2987
2988    #[test]
2989    fn test_render_effective_gears_config_minimal() {
2990        // Test that gears with minimal/no config can be rendered
2991        let mut app = create_minimal_app();
2992
2993        // Manually add a gear with no database or config sections
2994        app.gears
2995            .insert("minimal_gear".to_owned(), serde_json::json!({}));
2996
2997        let result = render_effective_gears_config(&app).unwrap();
2998
2999        // Gear should be present in output (or excluded if truly empty)
3000        // Either way, rendering should succeed
3001        assert!(result.is_object());
3002    }
3003
3004    #[test]
3005    fn test_dump_effective_gears_config_yaml() {
3006        let mut app = create_minimal_app();
3007        add_gear_with_config(
3008            &mut app,
3009            "test_gear",
3010            &serde_json::json!({
3011                "setting": "value"
3012            }),
3013        );
3014
3015        let yaml = dump_effective_gears_config_yaml(&app).unwrap();
3016
3017        // Should be valid YAML
3018        assert!(yaml.contains("test_gear:"));
3019        assert!(yaml.contains("config:"));
3020        assert!(yaml.contains("setting: value"));
3021    }
3022
3023    #[test]
3024    fn test_dump_effective_gears_config_json() {
3025        let mut app = create_minimal_app();
3026        add_gear_with_config(
3027            &mut app,
3028            "test_gear",
3029            &serde_json::json!({
3030                "setting": "value"
3031            }),
3032        );
3033
3034        let json = dump_effective_gears_config_json(&app).unwrap();
3035
3036        // Should be valid JSON
3037        assert!(json.contains("\"test_gear\""));
3038        assert!(json.contains("\"config\""));
3039        assert!(json.contains("\"setting\""));
3040        assert!(json.contains("\"value\""));
3041
3042        // Verify it's parseable
3043        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
3044        assert!(parsed.is_object());
3045    }
3046
3047    #[test]
3048    fn test_render_multiple_gears() {
3049        let mut app = create_minimal_app();
3050        add_gear_with_config(&mut app, "gear_a", &serde_json::json!({"a": 1}));
3051        add_gear_with_config(&mut app, "gear_b", &serde_json::json!({"b": 2}));
3052        add_gear_with_config(&mut app, "gear_c", &serde_json::json!({"c": 3}));
3053
3054        let result = render_effective_gears_config(&app).unwrap();
3055        let gears = result.as_object().unwrap();
3056
3057        assert_eq!(gears.len(), 3);
3058        assert!(gears.contains_key("gear_a"));
3059        assert!(gears.contains_key("gear_b"));
3060        assert!(gears.contains_key("gear_c"));
3061    }
3062
3063    // ========== Vendor configuration tests ==========
3064
3065    #[derive(Debug, Deserialize, Default, PartialEq)]
3066    struct TestVendorConfig {
3067        #[serde(default)]
3068        api_token: String,
3069        #[serde(default)]
3070        api_url: String,
3071    }
3072
3073    #[test]
3074    fn test_vendor_section_parses_from_yaml() {
3075        let yaml = r#"
3076server:
3077  home_dir: "~/.test_vendor"
3078vendor:
3079  acme:
3080    api_token: "acme-token-123"
3081    api_url: "https://acme.example.com"
3082  other_corp:
3083    api_token: "other-token-789"
3084    api_url: "https://other.example.com"
3085"#;
3086        let config: AppConfig = serde_saphyr::from_str(yaml).unwrap();
3087        assert_eq!(config.vendor.len(), 2);
3088        assert!(config.vendor.contains_key("acme"));
3089        assert!(config.vendor.contains_key("other_corp"));
3090
3091        let acme: TestVendorConfig = config.vendor_config("acme").unwrap();
3092        assert_eq!(acme.api_token, "acme-token-123");
3093        assert_eq!(acme.api_url, "https://acme.example.com");
3094
3095        let other: TestVendorConfig = config.vendor_config("other_corp").unwrap();
3096        assert_eq!(other.api_token, "other-token-789");
3097        assert_eq!(other.api_url, "https://other.example.com");
3098    }
3099
3100    #[test]
3101    fn test_vendor_section_defaults_to_empty() {
3102        let config = AppConfig::default();
3103        assert!(config.vendor.is_empty());
3104    }
3105
3106    #[test]
3107    fn test_vendor_config_typed_access() {
3108        let mut config = AppConfig::default();
3109        config.vendor.insert(
3110            "acme".to_owned(),
3111            serde_json::json!({
3112                "api_token": "acme-token-123",
3113                "api_url": "https://acme.example.com"
3114            }),
3115        );
3116
3117        let acme: TestVendorConfig = config.vendor_config("acme").unwrap();
3118        assert_eq!(acme.api_token, "acme-token-123");
3119        assert_eq!(acme.api_url, "https://acme.example.com");
3120    }
3121
3122    #[test]
3123    fn test_vendor_config_not_found() {
3124        let config = AppConfig::default();
3125        let result: Result<TestVendorConfig, _> = config.vendor_config("nonexistent");
3126        assert!(matches!(
3127            result,
3128            Err(VendorConfigError::NotFound { ref vendor }) if vendor == "nonexistent"
3129        ));
3130    }
3131
3132    #[test]
3133    fn test_vendor_config_invalid_structure() {
3134        let mut config = AppConfig::default();
3135        config
3136            .vendor
3137            .insert("bad".to_owned(), serde_json::json!("not an object"));
3138
3139        let result: Result<TestVendorConfig, _> = config.vendor_config("bad");
3140        assert!(matches!(
3141            result,
3142            Err(VendorConfigError::InvalidConfig { ref vendor, .. }) if vendor == "bad"
3143        ));
3144    }
3145
3146    #[test]
3147    fn test_vendor_config_or_default_missing() {
3148        let config = AppConfig::default();
3149        let acme: TestVendorConfig = config.vendor_config_or_default("acme").unwrap();
3150        assert_eq!(acme, TestVendorConfig::default());
3151    }
3152
3153    #[test]
3154    fn test_vendor_config_or_default_present() {
3155        let mut config = AppConfig::default();
3156        config.vendor.insert(
3157            "acme".to_owned(),
3158            serde_json::json!({ "api_token": "acme-token-123" }),
3159        );
3160
3161        let acme: TestVendorConfig = config.vendor_config_or_default("acme").unwrap();
3162        assert_eq!(acme.api_token, "acme-token-123");
3163    }
3164
3165    #[test]
3166    #[serial]
3167    fn test_vendor_config_env_override() {
3168        let tmp = tempdir().unwrap();
3169        let cfg_path = tmp.path().join("cfg.yaml");
3170        let yaml = r#"
3171server:
3172  home_dir: "~/.test_vendor"
3173vendor:
3174  env_test_vendor:
3175    api_token: "from_yaml"
3176"#;
3177        fs::write(&cfg_path, yaml).unwrap();
3178
3179        with_var(
3180            "APP__VENDOR__ENV_TEST_VENDOR__API_TOKEN",
3181            Some("from_env"),
3182            || {
3183                let config = AppConfig::load_layered(&cfg_path).unwrap();
3184                let v: TestVendorConfig = config.vendor_config("env_test_vendor").unwrap();
3185                assert_eq!(v.api_token, "from_env");
3186            },
3187        );
3188    }
3189
3190    #[test]
3191    #[serial]
3192    fn test_oop_http_labels_from_yaml_and_env() {
3193        let tmp = tempdir().unwrap();
3194        let cfg_path = tmp.path().join("cfg.yaml");
3195        let yaml = r#"
3196server:
3197  home_dir: "~/.test_oop_labels"
3198oop_http:
3199  listen_addr: "0.0.0.0:8080"
3200  labels:
3201    role: "ingest"
3202"#;
3203        fs::write(&cfg_path, yaml).unwrap();
3204
3205        // Env layer adds a second label. Env keys are lower-cased by the loader,
3206        // so `ZONE` lands as `zone`.
3207        with_var("APP__OOP_HTTP__LABELS__ZONE", Some("us-east-1"), || {
3208            let config = AppConfig::load_layered(&cfg_path).unwrap();
3209            let oop = config.oop_http.expect("oop_http present");
3210            assert_eq!(oop.labels.get("role"), Some(&"ingest".to_owned()));
3211            assert_eq!(
3212                oop.labels.get("zone"),
3213                Some(&"us-east-1".to_owned()),
3214                "APP__OOP_HTTP__LABELS__ZONE should populate labels[zone]"
3215            );
3216        });
3217
3218        // A bare-numeric env value (e.g. a StatefulSet ordinal injected as
3219        // `APP__OOP_HTTP__LABELS__SHARD=7`) is coerced to its string
3220        // representation by `de_labels_scalar_to_string` rather than failing the
3221        // config load, so numeric-looking labels can be set via the environment.
3222        with_var("APP__OOP_HTTP__LABELS__SHARD", Some("7"), || {
3223            let config = AppConfig::load_layered(&cfg_path).unwrap();
3224            let oop = config.oop_http.expect("oop_http present");
3225            assert_eq!(
3226                oop.labels.get("shard"),
3227                Some(&"7".to_owned()),
3228                "a bare-numeric env label value should be coerced to the string \"7\""
3229            );
3230        });
3231    }
3232
3233    #[test]
3234    #[serial]
3235    fn test_gear_config_env_override_underscore_gear_name() {
3236        // k8s-friendly form: gear name uses underscores in the env var name,
3237        // which should be remapped to the kebab-case gear key.
3238        let tmp = tempdir().unwrap();
3239        let cfg_path = tmp.path().join("cfg.yaml");
3240        let yaml = r#"
3241server:
3242  home_dir: "~/.test_gear_env_underscore"
3243gears:
3244  static-authz-plugin:
3245    config:
3246      vendor: "from_yaml"
3247"#;
3248        fs::write(&cfg_path, yaml).unwrap();
3249
3250        with_var(
3251            "APP__GEARS__STATIC_AUTHZ_PLUGIN__CONFIG__VENDOR",
3252            Some("acme"),
3253            || {
3254                let config = AppConfig::load_layered(&cfg_path).unwrap();
3255                let gear = config.gears.get("static-authz-plugin").unwrap();
3256                assert_eq!(gear["config"]["vendor"], serde_json::json!("acme"));
3257            },
3258        );
3259    }
3260
3261    #[test]
3262    #[serial]
3263    fn test_gear_config_env_override_dash_gear_name_backcompat() {
3264        // Back-compat: the existing dash form must still work.
3265        let tmp = tempdir().unwrap();
3266        let cfg_path = tmp.path().join("cfg.yaml");
3267        let yaml = r#"
3268server:
3269  home_dir: "~/.test_gear_env_dash"
3270gears:
3271  static-authz-plugin:
3272    config:
3273      vendor: "from_yaml"
3274"#;
3275        fs::write(&cfg_path, yaml).unwrap();
3276
3277        with_var(
3278            "APP__GEARS__static-authz-plugin__CONFIG__VENDOR",
3279            Some("acme"),
3280            || {
3281                let config = AppConfig::load_layered(&cfg_path).unwrap();
3282                let gear = config.gears.get("static-authz-plugin").unwrap();
3283                assert_eq!(gear["config"]["vendor"], serde_json::json!("acme"));
3284            },
3285        );
3286    }
3287
3288    #[test]
3289    #[serial]
3290    fn test_gear_config_env_override_preserves_field_underscores() {
3291        // Underscores in nested config field names must NOT be remapped.
3292        let tmp = tempdir().unwrap();
3293        let cfg_path = tmp.path().join("cfg.yaml");
3294        let yaml = r#"
3295server:
3296  home_dir: "~/.test_gear_env_field"
3297gears:
3298  static-authz-plugin:
3299    config:
3300      some_field: "from_yaml"
3301"#;
3302        fs::write(&cfg_path, yaml).unwrap();
3303
3304        with_var(
3305            "APP__GEARS__STATIC_AUTHZ_PLUGIN__CONFIG__SOME_FIELD",
3306            Some("from_env"),
3307            || {
3308                let config = AppConfig::load_layered(&cfg_path).unwrap();
3309                let gear = config.gears.get("static-authz-plugin").unwrap();
3310                assert_eq!(gear["config"]["some_field"], serde_json::json!("from_env"));
3311            },
3312        );
3313    }
3314
3315    #[test]
3316    #[serial]
3317    fn test_vendor_config_env_override_unaffected_by_gear_remap() {
3318        // Isolation invariant: the gear-name `_`->`-` remap must NOT touch the
3319        // `vendor` branch. The underscore vendor name is the canary — if the
3320        // remap leaked, the env override would land under a dashed
3321        // `env-test-vendor` key and the underscore lookup would miss it.
3322        let tmp = tempdir().unwrap();
3323        let cfg_path = tmp.path().join("cfg.yaml");
3324        let yaml = r#"
3325server:
3326  home_dir: "~/.test_vendor_unaffected"
3327vendor:
3328  env_test_vendor:
3329    api_token: "from_yaml"
3330"#;
3331        fs::write(&cfg_path, yaml).unwrap();
3332
3333        with_var(
3334            "APP__VENDOR__ENV_TEST_VENDOR__API_TOKEN",
3335            Some("from_env"),
3336            || {
3337                let config = AppConfig::load_layered(&cfg_path).unwrap();
3338
3339                // The override applied to the underscore key, not a remapped one.
3340                let v: TestVendorConfig = config.vendor_config("env_test_vendor").unwrap();
3341                assert_eq!(v.api_token, "from_env");
3342
3343                // Distinguishing assertion vs. test_vendor_config_env_override:
3344                // no dashed key was synthesized in the vendor branch.
3345                assert!(
3346                    config.vendor.contains_key("env_test_vendor"),
3347                    "underscore vendor key must be preserved"
3348                );
3349                assert!(
3350                    !config.vendor.contains_key("env-test-vendor"),
3351                    "gear remap leaked into the vendor branch"
3352                );
3353            },
3354        );
3355    }
3356
3357    #[test]
3358    fn test_vendor_multiple_vendors_typed_access() {
3359        let mut config = AppConfig::default();
3360        config.vendor.insert(
3361            "acme".to_owned(),
3362            serde_json::json!({ "api_token": "acme-token", "api_url": "https://acme.com" }),
3363        );
3364        config.vendor.insert(
3365            "other_corp".to_owned(),
3366            serde_json::json!({ "api_token": "other-token", "api_url": "https://other.com" }),
3367        );
3368
3369        let acme: TestVendorConfig = config.vendor_config("acme").unwrap();
3370        let other: TestVendorConfig = config.vendor_config("other_corp").unwrap();
3371
3372        assert_eq!(acme.api_token, "acme-token");
3373        assert_eq!(other.api_token, "other-token");
3374        assert_eq!(acme.api_url, "https://acme.com");
3375        assert_eq!(other.api_url, "https://other.com");
3376    }
3377
3378    #[test]
3379    fn test_vendor_nested_config() {
3380        #[derive(Debug, Deserialize, PartialEq)]
3381        struct NestedVendorConfig {
3382            api_url: String,
3383            feature_flags: FeatureFlags,
3384        }
3385
3386        #[derive(Debug, Deserialize, PartialEq)]
3387        struct FeatureFlags {
3388            beta_mode: bool,
3389            max_retries: u32,
3390        }
3391
3392        let mut config = AppConfig::default();
3393        config.vendor.insert(
3394            "acme".to_owned(),
3395            serde_json::json!({
3396                "api_url": "https://acme.com",
3397                "feature_flags": {
3398                    "beta_mode": true,
3399                    "max_retries": 3
3400                }
3401            }),
3402        );
3403
3404        let acme: NestedVendorConfig = config.vendor_config("acme").unwrap();
3405        assert_eq!(acme.api_url, "https://acme.com");
3406        assert!(acme.feature_flags.beta_mode);
3407        assert_eq!(acme.feature_flags.max_retries, 3);
3408    }
3409
3410    #[test]
3411    fn test_vendor_config_or_default_invalid_returns_error() {
3412        let mut config = AppConfig::default();
3413        config
3414            .vendor
3415            .insert("bad".to_owned(), serde_json::json!("not an object"));
3416
3417        let result: Result<TestVendorConfig, _> = config.vendor_config_or_default("bad");
3418        assert!(matches!(
3419            result,
3420            Err(VendorConfigError::InvalidConfig { ref vendor, .. }) if vendor == "bad"
3421        ));
3422    }
3423
3424    #[test]
3425    fn test_vendor_config_yaml_roundtrip() {
3426        let mut config = AppConfig::default();
3427        config.vendor.insert(
3428            "acme".to_owned(),
3429            serde_json::json!({ "api_token": "acme-token-123" }),
3430        );
3431
3432        let yaml = config.to_yaml().unwrap();
3433        assert!(yaml.contains("vendor"));
3434        assert!(yaml.contains("acme"));
3435        assert!(yaml.contains("acme-token-123"));
3436    }
3437
3438    #[test]
3439    fn test_vendor_coexists_with_gears() {
3440        let mut config = AppConfig::default();
3441        config.gears.insert(
3442            "my_gear".to_owned(),
3443            serde_json::json!({ "config": { "some_setting": true } }),
3444        );
3445        config.vendor.insert(
3446            "acme".to_owned(),
3447            serde_json::json!({ "api_token": "acme-token-123" }),
3448        );
3449
3450        assert!(config.gears.contains_key("my_gear"));
3451        assert!(config.vendor.contains_key("acme"));
3452
3453        let acme: TestVendorConfig = config.vendor_config("acme").unwrap();
3454        assert_eq!(acme.api_token, "acme-token-123");
3455    }
3456
3457    #[test]
3458    fn test_vendor_error_display_messages() {
3459        let not_found = VendorConfigError::NotFound {
3460            vendor: "acme".to_owned(),
3461        };
3462        assert_eq!(
3463            not_found.to_string(),
3464            "vendor 'acme' not found in configuration"
3465        );
3466
3467        let invalid = VendorConfigError::InvalidConfig {
3468            vendor: "bad".to_owned(),
3469            cause: serde_json::from_str::<TestVendorConfig>("invalid").unwrap_err(),
3470        };
3471        let msg = invalid.to_string();
3472        assert!(msg.starts_with("invalid config for vendor 'bad':"));
3473        assert!(std::error::Error::source(&invalid).is_none());
3474    }
3475
3476    #[test]
3477    fn test_vendor_empty_object_in_yaml() {
3478        let yaml = r#"
3479server:
3480  home_dir: "~/.test_vendor"
3481vendor: {}
3482"#;
3483        let config: AppConfig = serde_saphyr::from_str(yaml).unwrap();
3484        assert!(config.vendor.is_empty());
3485    }
3486
3487    // ========== Legacy `tracing:` section ==========
3488
3489    /// The pre-2026-03 shape must fail with a migration hint, not a bare
3490    /// `unknown field` from `deny_unknown_fields`.
3491    // `#[serial]`: sets `APP__TRACING__*` below (via the sibling env-override
3492    // test), which lands on the same root-level `tracing` path this test
3493    // asserts is absent; serialize against it and the other APP__-mutating tests.
3494    #[test]
3495    #[serial]
3496    fn test_legacy_tracing_section_reports_migration() {
3497        let tmp = tempdir().unwrap();
3498        let cfg_path = tmp.path().join("cfg.yaml");
3499        let yaml = r#"
3500server:
3501  home_dir: "~/.test_legacy_tracing"
3502tracing:
3503  enabled: true
3504  service_name: "cf-gears-api"
3505  exporter:
3506    kind: "otlp_grpc"
3507    endpoint: "http://127.0.0.1:4317"
3508"#;
3509        fs::write(&cfg_path, yaml).unwrap();
3510
3511        let result = AppConfig::load_layered(&cfg_path);
3512        assert!(result.is_err(), "legacy `tracing:` should be rejected");
3513        let msg = format!("{:?}", result.unwrap_err());
3514
3515        for expected in [
3516            "opentelemetry",
3517            "opentelemetry.resource.service_name",
3518            "docs/TRACING_SETUP.md",
3519        ] {
3520            assert!(msg.contains(expected), "missing {expected:?} in: {msg}");
3521        }
3522    }
3523
3524    /// The nested `opentelemetry.tracing` must not trip the root-level guard.
3525    // `#[serial]`: see rationale on `test_legacy_tracing_section_reports_migration`.
3526    #[test]
3527    #[serial]
3528    fn test_nested_opentelemetry_tracing_is_accepted() {
3529        let tmp = tempdir().unwrap();
3530        let cfg_path = tmp.path().join("cfg.yaml");
3531        let yaml = r#"
3532server:
3533  home_dir: "~/.test_nested_tracing"
3534opentelemetry:
3535  resource:
3536    service_name: "cf-gears-api"
3537  tracing:
3538    enabled: true
3539  metrics:
3540    enabled: false
3541"#;
3542        fs::write(&cfg_path, yaml).unwrap();
3543
3544        let config = AppConfig::load_layered(&cfg_path).expect("nested form should load");
3545        assert!(config.opentelemetry.tracing.enabled);
3546        assert_eq!(config.opentelemetry.resource.service_name, "cf-gears-api");
3547    }
3548
3549    /// `reject_legacy_tracing_key` must also catch the legacy shape when it
3550    /// arrives through the `APP__` env layer rather than the YAML file —
3551    /// `Env::prefixed` splits `APP__TRACING__ENABLED` onto the same
3552    /// `tracing.enabled` path as the old YAML block.
3553    // `#[serial]`: mutates the process-global `APP__TRACING__*` var.
3554    #[test]
3555    #[serial]
3556    fn test_legacy_tracing_env_override_reports_migration() {
3557        let tmp = tempdir().unwrap();
3558        let cfg_path = tmp.path().join("cfg.yaml");
3559        let yaml = r#"
3560server:
3561  home_dir: "~/.test_legacy_tracing_env"
3562opentelemetry:
3563  resource:
3564    service_name: "cf-gears-api"
3565"#;
3566        fs::write(&cfg_path, yaml).unwrap();
3567
3568        with_var("APP__TRACING__ENABLED", Some("true"), || {
3569            let result = AppConfig::load_layered(&cfg_path);
3570            assert!(
3571                result.is_err(),
3572                "legacy `APP__TRACING__*` override should be rejected"
3573            );
3574            let msg = format!("{:?}", result.unwrap_err());
3575            assert!(
3576                msg.contains("opentelemetry"),
3577                "missing migration hint in: {msg}"
3578            );
3579        });
3580    }
3581
3582    // ========== Duplicate YAML key rejection tests ==========
3583
3584    // `#[serial]`: these call `load_layered`, which reads the process-global
3585    // `APP__` env layer; serialize against the env-override tests that mutate
3586    // `APP__*` vars via `with_var`.
3587    #[test]
3588    #[serial]
3589    fn test_reject_duplicate_gear_names() {
3590        let tmp = tempdir().unwrap();
3591        let cfg_path = tmp.path().join("cfg.yaml");
3592        let yaml = r#"
3593server:
3594  home_dir: "~/.test_dup"
3595gears:
3596  gear1:
3597    config: {}
3598  gear2:
3599    config: {}
3600  gear1:
3601    config: {}
3602"#;
3603        fs::write(&cfg_path, yaml).unwrap();
3604
3605        let result = AppConfig::load_layered(&cfg_path);
3606        assert!(result.is_err(), "duplicate gear names should be rejected");
3607        let msg = format!("{:?}", result.unwrap_err());
3608        assert!(
3609            msg.contains("duplicate") || msg.contains("Duplicate"),
3610            "error should mention duplicates: {msg}"
3611        );
3612    }
3613
3614    #[test]
3615    #[serial]
3616    fn test_reject_duplicate_keys_in_gear_file() {
3617        let tmp = tempdir().unwrap();
3618        let gears_dir = tmp.path().join("gears.d");
3619        fs::create_dir_all(&gears_dir).unwrap();
3620
3621        // Gear file with duplicate "config:" key
3622        let gear_yaml = r#"
3623config:
3624  key1: "value1"
3625config:
3626  key2: "value2"
3627"#;
3628        fs::write(gears_dir.join("bad_gear.yaml"), gear_yaml).unwrap();
3629
3630        let cfg_yaml = format!(
3631            r#"
3632server:
3633  home_dir: "~/.test_dup_modfile"
3634gears_dir: "{}"
3635"#,
3636            normalize_path(&gears_dir)
3637        );
3638        let cfg_path = tmp.path().join("cfg.yaml");
3639        fs::write(&cfg_path, cfg_yaml).unwrap();
3640
3641        let result = AppConfig::load_layered(&cfg_path);
3642        assert!(
3643            result.is_err(),
3644            "duplicate keys in a gear file should be rejected"
3645        );
3646        let msg = format!("{:?}", result.unwrap_err());
3647        assert!(
3648            msg.contains("duplicate") || msg.contains("Duplicate"),
3649            "error should mention duplicates: {msg}"
3650        );
3651    }
3652
3653    #[test]
3654    #[serial]
3655    fn test_no_false_positive_on_unique_gears() {
3656        let tmp = tempdir().unwrap();
3657        let cfg_path = tmp.path().join("cfg.yaml");
3658        let yaml = r#"
3659server:
3660  home_dir: "~/.test_ok"
3661gears:
3662  gear1:
3663    config: {}
3664  gear2:
3665    config: {}
3666  gear3:
3667    config: {}
3668"#;
3669        fs::write(&cfg_path, yaml).unwrap();
3670
3671        let result = AppConfig::load_layered(&cfg_path);
3672        assert!(
3673            result.is_ok(),
3674            "unique gear names should be accepted: {:?}",
3675            result.unwrap_err()
3676        );
3677    }
3678}
3679
3680// Note: DB trait implementations and helper functions removed since we now use DbManager