Skip to main content

toolkit/
config.rs

1//! Configuration gear for typed gear configuration access.
2//!
3//! This gear provides two distinct mechanisms for loading gear configuration:
4//!
5//! 1. **Lenient loading** (default): Falls back to `T::default()` when configuration is missing.
6//!    - Used by `gear_config_or_default`
7//!    - Allows gears to exist without configuration sections in the main config file
8//!
9//! 2. **Strict loading**: Requires configuration to be present and valid.
10//!    - Used by `gear_config_required`
11//!    - Returns errors when configuration is missing or invalid
12//!
13//! Both loaders hide the framework-owned [`GTS_PUBLICATION_CONFIG_KEY`] entry of the
14//! `config` section from the gear's typed configuration, so a gear config with
15//! `#[serde(deny_unknown_fields)]` accepts it; the runtime reads it from the raw
16//! [`ConfigProvider`]. Every other key, unknown business fields included, still reaches
17//! the gear's deserializer.
18
19use serde::de::DeserializeOwned;
20
21/// `gears.<gear>.config.gts_publication`: the gear's GTS publication policy, owned by
22/// the runtime ([`crate::gts_publication::GtsPublicationOptions`]) and removed from the
23/// typed gear configuration.
24pub const GTS_PUBLICATION_CONFIG_KEY: &str = "gts_publication";
25
26/// Deserialize a gear's `config` section without the framework-owned keys.
27fn typed_config<T: DeserializeOwned>(
28    gear_name: &str,
29    config_section: &serde_json::Value,
30) -> Result<T, ConfigError> {
31    let mut section = config_section.clone();
32    if let Some(obj) = section.as_object_mut() {
33        obj.remove(GTS_PUBLICATION_CONFIG_KEY);
34    }
35    serde_json::from_value(section).map_err(|e| ConfigError::InvalidConfig {
36        gear: gear_name.to_owned(),
37        cause: e,
38    })
39}
40
41/// Configuration error for typed config operations
42#[derive(thiserror::Error, Debug)]
43pub enum ConfigError {
44    #[error("gear '{gear}' not found")]
45    GearNotFound { gear: String },
46    #[error("gear '{gear}' config must be an object")]
47    InvalidGearStructure { gear: String },
48    #[error("missing 'config' section in gear '{gear}'")]
49    MissingConfigSection { gear: String },
50    // Intentionally not named `source`; doing so would duplicate chained error output.
51    #[error("invalid config for gear '{gear}': {cause}")]
52    InvalidConfig {
53        gear: String,
54        cause: serde_json::Error,
55    },
56    #[error("variable expansion failed for gear '{gear}': {cause}")]
57    VarExpand {
58        gear: String,
59        cause: toolkit_utils::var_expand::ExpandVarsError,
60    },
61}
62
63/// Provider of gear-specific configuration (raw JSON sections only).
64pub trait ConfigProvider: Send + Sync {
65    /// Returns raw JSON section for the gear, if any.
66    fn get_gear_config(&self, gear_name: &str) -> Option<&serde_json::Value>;
67}
68
69/// Lenient configuration loader that falls back to defaults.
70///
71/// This function provides forgiving behavior for gears that don't require configuration:
72/// - If the gear is not present in config → returns `Ok(T::default())`
73/// - If the gear value is not an object → returns `Ok(T::default())`
74/// - If the gear has no "config" field → returns `Ok(T::default())`
75/// - If "config" is present but invalid → returns `Err(ConfigError::InvalidConfig)`
76/// - The framework-owned `config.gts_publication` entry is not part of `T`
77///
78/// Use this for gears that can operate with default configuration.
79///
80/// # Errors
81/// Returns `ConfigError::InvalidConfig` if the config section exists but cannot be deserialized.
82pub fn gear_config_or_default<T: DeserializeOwned + Default>(
83    provider: &dyn ConfigProvider,
84    gear_name: &str,
85) -> Result<T, ConfigError> {
86    // If gear not found, use defaults
87    let Some(gear_raw) = provider.get_gear_config(gear_name) else {
88        return Ok(T::default());
89    };
90
91    // If gear is not an object, use defaults
92    let Some(obj) = gear_raw.as_object() else {
93        return Ok(T::default());
94    };
95
96    // If no config section, use defaults
97    let Some(config_section) = obj.get("config") else {
98        return Ok(T::default());
99    };
100
101    // Config section exists, try to parse it
102    typed_config(gear_name, config_section)
103}
104
105/// Strict configuration loader that requires configuration to be present.
106///
107/// This function enforces that configuration must exist and be valid:
108/// - If the gear is not present → returns `Err(ConfigError::GearNotFound)`
109/// - If the gear value is not an object → returns `Err(ConfigError::InvalidGearStructure)`
110/// - If the gear has no "config" field → returns `Err(ConfigError::MissingConfigSection)`
111/// - If "config" is present but invalid → returns `Err(ConfigError::InvalidConfig)`
112/// - The framework-owned `config.gts_publication` entry is not part of `T`
113///
114/// Use this for gears that cannot operate without explicit configuration.
115///
116/// # Errors
117/// Returns `ConfigError` if the gear is not found, has invalid structure, or config is invalid.
118pub fn gear_config_required<T: DeserializeOwned>(
119    provider: &dyn ConfigProvider,
120    gear_name: &str,
121) -> Result<T, ConfigError> {
122    let gear_raw =
123        provider
124            .get_gear_config(gear_name)
125            .ok_or_else(|| ConfigError::GearNotFound {
126                gear: gear_name.to_owned(),
127            })?;
128
129    // Extract config section from: gears.<name> = { database: ..., config: ... }
130    let obj = gear_raw
131        .as_object()
132        .ok_or_else(|| ConfigError::InvalidGearStructure {
133            gear: gear_name.to_owned(),
134        })?;
135
136    let config_section = obj
137        .get("config")
138        .ok_or_else(|| ConfigError::MissingConfigSection {
139            gear: gear_name.to_owned(),
140        })?;
141
142    typed_config(gear_name, config_section)
143}
144
145#[cfg(test)]
146#[cfg_attr(coverage_nightly, coverage(off))]
147mod tests {
148    use super::*;
149    use serde::Deserialize;
150    use serde_json::json;
151    use std::collections::HashMap;
152
153    #[derive(Debug, PartialEq, Deserialize, Default)]
154    struct TestConfig {
155        #[serde(default)]
156        api_key: String,
157        #[serde(default)]
158        timeout_ms: u64,
159        #[serde(default)]
160        enabled: bool,
161    }
162
163    struct MockConfigProvider {
164        gears: HashMap<String, serde_json::Value>,
165    }
166
167    impl MockConfigProvider {
168        fn new() -> Self {
169            let mut gears = HashMap::new();
170
171            // Valid gear config
172            gears.insert(
173                "test_gear".to_owned(),
174                json!({
175                    "database": {
176                        "url": "postgres://localhost/test"
177                    },
178                    "config": {
179                        "api_key": "secret123",
180                        "timeout_ms": 5000,
181                        "enabled": true
182                    }
183                }),
184            );
185
186            // Gear without config section
187            gears.insert(
188                "no_config_gear".to_owned(),
189                json!({
190                    "database": {
191                        "url": "postgres://localhost/test"
192                    }
193                }),
194            );
195
196            // Gear with invalid structure (not an object)
197            gears.insert("invalid_gear".to_owned(), json!("not an object"));
198
199            Self { gears }
200        }
201    }
202
203    impl ConfigProvider for MockConfigProvider {
204        fn get_gear_config(&self, gear_name: &str) -> Option<&serde_json::Value> {
205            self.gears.get(gear_name)
206        }
207    }
208
209    // ========== Tests for lenient loading (gear_config_or_default) ==========
210
211    #[test]
212    fn test_lenient_success() {
213        let provider = MockConfigProvider::new();
214        let result: Result<TestConfig, ConfigError> =
215            gear_config_or_default(&provider, "test_gear");
216
217        assert!(result.is_ok());
218        let config = result.unwrap();
219        assert_eq!(config.api_key, "secret123");
220        assert_eq!(config.timeout_ms, 5000);
221        assert!(config.enabled);
222    }
223
224    #[test]
225    fn test_lenient_gear_not_found_returns_default() {
226        let provider = MockConfigProvider::new();
227        let result: Result<TestConfig, ConfigError> =
228            gear_config_or_default(&provider, "nonexistent");
229
230        assert!(result.is_ok());
231        let config = result.unwrap();
232        assert_eq!(config, TestConfig::default());
233    }
234
235    #[test]
236    fn test_lenient_missing_config_section_returns_default() {
237        let provider = MockConfigProvider::new();
238        let result: Result<TestConfig, ConfigError> =
239            gear_config_or_default(&provider, "no_config_gear");
240
241        assert!(result.is_ok());
242        let config = result.unwrap();
243        assert_eq!(config, TestConfig::default());
244    }
245
246    #[test]
247    fn test_lenient_invalid_structure_returns_default() {
248        let provider = MockConfigProvider::new();
249        let result: Result<TestConfig, ConfigError> =
250            gear_config_or_default(&provider, "invalid_gear");
251
252        assert!(result.is_ok());
253        let config = result.unwrap();
254        assert_eq!(config, TestConfig::default());
255    }
256
257    #[test]
258    fn test_lenient_invalid_config_returns_error() {
259        let mut provider = MockConfigProvider::new();
260        // Add gear with invalid config structure
261        provider.gears.insert(
262            "bad_config_gear".to_owned(),
263            json!({
264                "config": {
265                    "api_key": "secret123",
266                    "timeout_ms": "not_a_number", // Should be u64
267                    "enabled": true
268                }
269            }),
270        );
271
272        let result: Result<TestConfig, ConfigError> =
273            gear_config_or_default(&provider, "bad_config_gear");
274
275        assert!(matches!(result, Err(ConfigError::InvalidConfig { .. })));
276        if let Err(ConfigError::InvalidConfig { gear, .. }) = result {
277            assert_eq!(gear, "bad_config_gear");
278        }
279    }
280
281    #[test]
282    fn test_lenient_helper_with_multiple_scenarios() {
283        let provider = MockConfigProvider::new();
284
285        // Gear not found should return default
286        let result: Result<TestConfig, ConfigError> =
287            gear_config_or_default(&provider, "nonexistent");
288        assert!(result.is_ok());
289        assert_eq!(result.unwrap(), TestConfig::default());
290
291        // Valid config should parse correctly
292        let result: Result<TestConfig, ConfigError> =
293            gear_config_or_default(&provider, "test_gear");
294        assert!(result.is_ok());
295        let config = result.unwrap();
296        assert_eq!(config.api_key, "secret123");
297    }
298
299    // ========== Tests for strict loading (gear_config_required) ==========
300
301    #[test]
302    fn test_strict_success() {
303        let provider = MockConfigProvider::new();
304        let result: Result<TestConfig, ConfigError> = gear_config_required(&provider, "test_gear");
305
306        assert!(result.is_ok());
307        let config = result.unwrap();
308        assert_eq!(config.api_key, "secret123");
309        assert_eq!(config.timeout_ms, 5000);
310        assert!(config.enabled);
311    }
312
313    #[test]
314    fn test_strict_gear_not_found() {
315        let provider = MockConfigProvider::new();
316        let result: Result<TestConfig, ConfigError> =
317            gear_config_required(&provider, "nonexistent");
318
319        assert!(matches!(result, Err(ConfigError::GearNotFound { .. })));
320        if let Err(ConfigError::GearNotFound { gear }) = result {
321            assert_eq!(gear, "nonexistent");
322        }
323    }
324
325    #[test]
326    fn test_strict_missing_config_section() {
327        let provider = MockConfigProvider::new();
328        let result: Result<TestConfig, ConfigError> =
329            gear_config_required(&provider, "no_config_gear");
330
331        assert!(matches!(
332            result,
333            Err(ConfigError::MissingConfigSection { .. })
334        ));
335        if let Err(ConfigError::MissingConfigSection { gear }) = result {
336            assert_eq!(gear, "no_config_gear");
337        }
338    }
339
340    #[test]
341    fn test_strict_invalid_structure() {
342        let provider = MockConfigProvider::new();
343        let result: Result<TestConfig, ConfigError> =
344            gear_config_required(&provider, "invalid_gear");
345
346        assert!(matches!(
347            result,
348            Err(ConfigError::InvalidGearStructure { .. })
349        ));
350        if let Err(ConfigError::InvalidGearStructure { gear }) = result {
351            assert_eq!(gear, "invalid_gear");
352        }
353    }
354
355    #[test]
356    fn test_strict_invalid_config() {
357        let mut provider = MockConfigProvider::new();
358        // Add gear with invalid config structure
359        provider.gears.insert(
360            "bad_config_gear".to_owned(),
361            json!({
362                "config": {
363                    "api_key": "secret123",
364                    "timeout_ms": "not_a_number", // Should be u64
365                    "enabled": true
366                }
367            }),
368        );
369
370        let result: Result<TestConfig, ConfigError> =
371            gear_config_required(&provider, "bad_config_gear");
372
373        assert!(matches!(result, Err(ConfigError::InvalidConfig { .. })));
374        if let Err(ConfigError::InvalidConfig { gear, .. }) = result {
375            assert_eq!(gear, "bad_config_gear");
376        }
377    }
378
379    // ========== The framework-owned `gts_publication` entry ==========
380
381    /// A gear config as strict as the real resolver/plugin/AM configs.
382    #[derive(Debug, PartialEq, Deserialize, Default)]
383    #[serde(deny_unknown_fields)]
384    struct StrictConfig {
385        #[serde(default)]
386        vendor: String,
387    }
388
389    fn strict_provider(config: &serde_json::Value) -> MockConfigProvider {
390        let mut provider = MockConfigProvider::new();
391        provider
392            .gears
393            .insert("strict_gear".to_owned(), json!({ "config": config }));
394        provider
395    }
396
397    #[test]
398    fn strict_gear_config_accepts_the_gts_publication_section() {
399        let provider = strict_provider(&json!({
400            "vendor": "acme",
401            "gts_publication": { "timeout": "5s", "batch_size": 3 },
402        }));
403        let required: StrictConfig = gear_config_required(&provider, "strict_gear").unwrap();
404        let lenient: StrictConfig = gear_config_or_default(&provider, "strict_gear").unwrap();
405        assert_eq!(required.vendor, "acme");
406        assert_eq!(lenient.vendor, "acme");
407        // The runtime still reads the section from the raw provider.
408        assert_eq!(
409            provider.get_gear_config("strict_gear").unwrap()["config"][GTS_PUBLICATION_CONFIG_KEY]
410                ["batch_size"],
411            3
412        );
413    }
414
415    #[test]
416    fn strict_gear_config_still_rejects_an_unknown_business_field() {
417        let provider = strict_provider(&json!({
418            "vendor": "acme",
419            "gts_publication": { "batch_size": 3 },
420            "vendro": "typo",
421        }));
422        for result in [
423            gear_config_required::<StrictConfig>(&provider, "strict_gear"),
424            gear_config_or_default::<StrictConfig>(&provider, "strict_gear"),
425        ] {
426            let err = result.unwrap_err();
427            assert!(
428                matches!(&err, ConfigError::InvalidConfig { gear, cause }
429                    if gear == "strict_gear" && cause.to_string().contains("unknown field `vendro`")),
430                "{err}"
431            );
432        }
433    }
434
435    #[test]
436    fn only_the_gts_publication_key_is_hidden() {
437        // Any other key keeps reaching the gear's deserializer.
438        let provider = strict_provider(&json!({ "publication": {} }));
439        let err = gear_config_required::<StrictConfig>(&provider, "strict_gear").unwrap_err();
440        assert!(
441            err.to_string().contains("unknown field `publication`"),
442            "{err}"
443        );
444    }
445
446    // ========== Tests for ConfigError display messages ==========
447
448    #[test]
449    fn test_config_error_messages() {
450        let gear_not_found = ConfigError::GearNotFound {
451            gear: "test".to_owned(),
452        };
453        assert_eq!(gear_not_found.to_string(), "gear 'test' not found");
454
455        let invalid_structure = ConfigError::InvalidGearStructure {
456            gear: "test".to_owned(),
457        };
458        assert_eq!(
459            invalid_structure.to_string(),
460            "gear 'test' config must be an object"
461        );
462
463        let missing_config = ConfigError::MissingConfigSection {
464            gear: "test".to_owned(),
465        };
466        assert_eq!(
467            missing_config.to_string(),
468            "missing 'config' section in gear 'test'"
469        );
470    }
471
472    #[test]
473    fn test_invalid_config_message_is_not_duplicated_by_source_chain() {
474        let mut provider = MockConfigProvider::new();
475        provider.gears.insert(
476            "bad_config_gear".to_owned(),
477            json!({
478                "config": {
479                    "api_key": "secret123",
480                    "timeout_ms": "not_a_number",
481                    "enabled": true
482                }
483            }),
484        );
485        let result: Result<TestConfig, ConfigError> =
486            gear_config_required(&provider, "bad_config_gear");
487        let err = result.unwrap_err();
488
489        assert_eq!(
490            err.to_string(),
491            "invalid config for gear 'bad_config_gear': invalid type: string \"not_a_number\", expected u64"
492        );
493
494        assert!(std::error::Error::source(&err).is_none());
495        let anyhow_err: anyhow::Error = err.into();
496        assert_eq!(
497            format!("{anyhow_err:#}"),
498            "invalid config for gear 'bad_config_gear': invalid type: string \"not_a_number\", expected u64"
499        );
500    }
501
502    #[test]
503    fn test_var_expand_message_is_not_duplicated_by_source_chain() {
504        let err = ConfigError::VarExpand {
505            gear: "test".to_owned(),
506            cause: toolkit_utils::var_expand::ExpandVarsError::Regex("boom".to_owned()),
507        };
508
509        assert_eq!(
510            err.to_string(),
511            "variable expansion failed for gear 'test': env expansion regex error: boom"
512        );
513        assert!(std::error::Error::source(&err).is_none());
514    }
515}