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