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