mabi-core 1.6.2

Mabinogion - Core abstractions and utilities for industrial protocol simulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Environment variable override system.
//!
//! This module provides hierarchical environment variable support for configuration
//! with type-safe parsing and customizable prefix.
//!
//! # Naming Convention
//!
//! Environment variables follow a hierarchical pattern:
//! `{PREFIX}_{SECTION}_{FIELD}` where:
//! - `PREFIX`: Application prefix (default: `TRAP_SIM`)
//! - `SECTION`: Configuration section (e.g., `ENGINE`, `MODBUS`)
//! - `FIELD`: Specific field name in SCREAMING_SNAKE_CASE
//!
//! # Examples
//!
//! ```text
//! TRAP_SIM_ENGINE_MAX_DEVICES=50000
//! TRAP_SIM_ENGINE_TICK_INTERVAL_MS=50
//! TRAP_SIM_MODBUS_TCP_BIND_ADDRESS=0.0.0.0:5502
//! TRAP_SIM_LOG_LEVEL=debug
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use mabi_core::config::env::EnvOverrides;
//!
//! let overrides = EnvOverrides::with_prefix("TRAP_SIM")
//!     .add_rule("ENGINE_MAX_DEVICES", |c, v| {
//!         c.max_devices = v.parse().ok()?;
//!         Some(())
//!     })
//!     .build();
//!
//! overrides.apply(&mut config)?;
//! ```

use std::collections::HashMap;
use std::env;
use std::fmt;
use std::marker::PhantomData;
use std::str::FromStr;

use crate::error::{Error, ValidationErrors};
use crate::Result;

/// Default environment variable prefix.
pub const DEFAULT_PREFIX: &str = "TRAP_SIM";

/// Environment variable override result.
#[derive(Debug, Clone)]
pub struct EnvApplyResult {
    /// Number of overrides successfully applied.
    pub applied: usize,
    /// Fields that were overridden.
    pub overridden_fields: Vec<String>,
    /// Errors encountered during application.
    pub errors: Vec<EnvOverrideError>,
}

impl EnvApplyResult {
    /// Check if any overrides were applied.
    pub fn has_changes(&self) -> bool {
        self.applied > 0
    }

    /// Check if there were any errors.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Convert to Result, failing if there were errors.
    pub fn into_result(self) -> Result<Self> {
        if self.errors.is_empty() {
            Ok(self)
        } else {
            let mut validation = ValidationErrors::new();
            for err in &self.errors {
                validation.add(&err.env_var, &err.message);
            }
            Err(Error::validation(validation))
        }
    }
}

/// Error that occurred while applying an environment override.
#[derive(Debug, Clone)]
pub struct EnvOverrideError {
    /// Environment variable name.
    pub env_var: String,
    /// Field path being overridden.
    pub field: String,
    /// Error message.
    pub message: String,
}

impl fmt::Display for EnvOverrideError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Failed to apply {} to {}: {}",
            self.env_var, self.field, self.message
        )
    }
}

/// Type for override application functions.
pub type OverrideFn<T> = Box<dyn Fn(&mut T, &str) -> std::result::Result<(), String> + Send + Sync>;

/// Rule for applying an environment variable override.
pub struct EnvRule<T> {
    /// Environment variable suffix (without prefix).
    pub suffix: String,
    /// Target field path for documentation.
    pub field_path: String,
    /// Description of what this override does.
    pub description: String,
    /// Function to apply the override.
    pub apply: OverrideFn<T>,
}

impl<T> fmt::Debug for EnvRule<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvRule")
            .field("suffix", &self.suffix)
            .field("field_path", &self.field_path)
            .field("description", &self.description)
            .finish()
    }
}

/// Builder for creating environment override rules.
pub struct EnvRuleBuilder<T> {
    suffix: String,
    field_path: String,
    description: String,
    _phantom: PhantomData<T>,
}

impl<T> EnvRuleBuilder<T> {
    /// Create a new rule builder.
    pub fn new(suffix: impl Into<String>) -> Self {
        let suffix = suffix.into();
        Self {
            field_path: suffix.to_lowercase().replace('_', "."),
            suffix,
            description: String::new(),
            _phantom: PhantomData,
        }
    }

    /// Set the field path for documentation.
    pub fn field_path(mut self, path: impl Into<String>) -> Self {
        self.field_path = path.into();
        self
    }

    /// Set the description.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Build with a parsing function for types that implement FromStr.
    pub fn parse_into<F, V>(self, setter: F) -> EnvRule<T>
    where
        F: Fn(&mut T, V) + Send + Sync + 'static,
        V: FromStr,
        V::Err: fmt::Display,
    {
        EnvRule {
            suffix: self.suffix,
            field_path: self.field_path,
            description: self.description,
            apply: Box::new(move |config, value| {
                let parsed = value
                    .parse::<V>()
                    .map_err(|e| format!("Failed to parse: {}", e))?;
                setter(config, parsed);
                Ok(())
            }),
        }
    }

    /// Build with a custom application function.
    pub fn apply_with<F>(self, f: F) -> EnvRule<T>
    where
        F: Fn(&mut T, &str) -> std::result::Result<(), String> + Send + Sync + 'static,
    {
        EnvRule {
            suffix: self.suffix,
            field_path: self.field_path,
            description: self.description,
            apply: Box::new(f),
        }
    }

    /// Build for string fields (no parsing needed).
    pub fn as_string<F>(self, setter: F) -> EnvRule<T>
    where
        F: Fn(&mut T, String) + Send + Sync + 'static,
    {
        EnvRule {
            suffix: self.suffix,
            field_path: self.field_path,
            description: self.description,
            apply: Box::new(move |config, value| {
                setter(config, value.to_string());
                Ok(())
            }),
        }
    }

    /// Build for boolean fields with flexible parsing.
    pub fn as_bool<F>(self, setter: F) -> EnvRule<T>
    where
        F: Fn(&mut T, bool) + Send + Sync + 'static,
    {
        EnvRule {
            suffix: self.suffix,
            field_path: self.field_path,
            description: self.description,
            apply: Box::new(move |config, value| {
                let parsed =
                    parse_bool(value).ok_or_else(|| format!("Invalid boolean value: {}", value))?;
                setter(config, parsed);
                Ok(())
            }),
        }
    }
}

/// Parse a boolean from various string representations.
fn parse_bool(s: &str) -> Option<bool> {
    match s.to_lowercase().as_str() {
        "true" | "1" | "yes" | "on" | "enabled" => Some(true),
        "false" | "0" | "no" | "off" | "disabled" => Some(false),
        _ => None,
    }
}

/// Environment variable overrides configuration.
pub struct EnvOverrides<T> {
    /// Prefix for all environment variables.
    prefix: String,
    /// Override rules.
    rules: Vec<EnvRule<T>>,
    /// Whether to ignore missing environment variables.
    ignore_missing: bool,
    /// Whether to fail on parse errors.
    fail_on_error: bool,
}

impl<T> fmt::Debug for EnvOverrides<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvOverrides")
            .field("prefix", &self.prefix)
            .field("rules_count", &self.rules.len())
            .field("ignore_missing", &self.ignore_missing)
            .field("fail_on_error", &self.fail_on_error)
            .finish()
    }
}

impl<T> EnvOverrides<T> {
    /// Create a new environment overrides handler with default prefix.
    pub fn new() -> Self {
        Self::with_prefix(DEFAULT_PREFIX)
    }

    /// Create with a custom prefix.
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            rules: Vec::new(),
            ignore_missing: true,
            fail_on_error: false,
        }
    }

    /// Get the full environment variable name for a suffix.
    pub fn full_var_name(&self, suffix: &str) -> String {
        format!("{}_{}", self.prefix, suffix)
    }

    /// Add a rule to the overrides.
    pub fn add_rule(mut self, rule: EnvRule<T>) -> Self {
        self.rules.push(rule);
        self
    }

    /// Set whether to ignore missing environment variables.
    pub fn ignore_missing(mut self, ignore: bool) -> Self {
        self.ignore_missing = ignore;
        self
    }

    /// Set whether to fail on parse errors.
    pub fn fail_on_error(mut self, fail: bool) -> Self {
        self.fail_on_error = fail;
        self
    }

    /// Apply all environment overrides to the configuration.
    pub fn apply(&self, config: &mut T) -> EnvApplyResult {
        let mut result = EnvApplyResult {
            applied: 0,
            overridden_fields: Vec::new(),
            errors: Vec::new(),
        };

        for rule in &self.rules {
            let var_name = self.full_var_name(&rule.suffix);

            match env::var(&var_name) {
                Ok(value) => match (rule.apply)(config, &value) {
                    Ok(()) => {
                        result.applied += 1;
                        result.overridden_fields.push(rule.field_path.clone());
                        tracing::debug!(
                            env_var = %var_name,
                            field = %rule.field_path,
                            "Applied environment override"
                        );
                    }
                    Err(msg) => {
                        result.errors.push(EnvOverrideError {
                            env_var: var_name,
                            field: rule.field_path.clone(),
                            message: msg,
                        });
                    }
                },
                Err(env::VarError::NotPresent) => {
                    // Variable not set, skip
                }
                Err(env::VarError::NotUnicode(_)) => {
                    result.errors.push(EnvOverrideError {
                        env_var: var_name,
                        field: rule.field_path.clone(),
                        message: "Value is not valid UTF-8".to_string(),
                    });
                }
            }
        }

        result
    }

    /// Apply and return Result based on fail_on_error setting.
    pub fn apply_checked(&self, config: &mut T) -> Result<EnvApplyResult> {
        let result = self.apply(config);
        if self.fail_on_error && result.has_errors() {
            result.into_result()
        } else {
            Ok(result)
        }
    }

    /// Get documentation for all registered rules.
    pub fn documentation(&self) -> Vec<EnvVarDoc> {
        self.rules
            .iter()
            .map(|rule| EnvVarDoc {
                var_name: self.full_var_name(&rule.suffix),
                field_path: rule.field_path.clone(),
                description: rule.description.clone(),
            })
            .collect()
    }

    /// Get the number of registered rules.
    pub fn rule_count(&self) -> usize {
        self.rules.len()
    }
}

impl<T> Default for EnvOverrides<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Documentation entry for an environment variable.
#[derive(Debug, Clone)]
pub struct EnvVarDoc {
    /// Full environment variable name.
    pub var_name: String,
    /// Configuration field path.
    pub field_path: String,
    /// Description.
    pub description: String,
}

impl fmt::Display for EnvVarDoc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {} - {}",
            self.var_name, self.field_path, self.description
        )
    }
}

/// Helper trait for creating typed environment rules.
pub trait EnvConfigurable: Sized {
    /// Create environment overrides for this type.
    fn env_overrides() -> EnvOverrides<Self>;
}

/// Convenience function to read and parse an environment variable.
pub fn get_env<T: FromStr>(name: &str) -> Option<T> {
    env::var(name).ok().and_then(|v| v.parse().ok())
}

/// Convenience function to read an environment variable with a default.
pub fn get_env_or<T: FromStr>(name: &str, default: T) -> T {
    get_env(name).unwrap_or(default)
}

/// Read an environment variable as a boolean with flexible parsing.
pub fn get_env_bool(name: &str) -> Option<bool> {
    env::var(name).ok().and_then(|v| parse_bool(&v))
}

/// Read an environment variable as a boolean with a default.
pub fn get_env_bool_or(name: &str, default: bool) -> bool {
    get_env_bool(name).unwrap_or(default)
}

/// A collection of environment variable values for testing.
#[derive(Debug, Default)]
pub struct EnvSnapshot {
    vars: HashMap<String, String>,
}

impl EnvSnapshot {
    /// Create a new empty snapshot.
    pub fn new() -> Self {
        Self::default()
    }

    /// Capture current environment variables with a specific prefix.
    pub fn capture(prefix: &str) -> Self {
        let vars = env::vars().filter(|(k, _)| k.starts_with(prefix)).collect();
        Self { vars }
    }

    /// Set a variable in this snapshot.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.vars.insert(key.into(), value.into());
    }

    /// Apply this snapshot to the environment.
    pub fn apply(&self) {
        for (key, value) in &self.vars {
            env::set_var(key, value);
        }
    }

    /// Clear variables from environment (for testing).
    pub fn clear_from_env(&self) {
        for key in self.vars.keys() {
            env::remove_var(key);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    #[derive(Debug, Default)]
    struct TestConfig {
        max_devices: usize,
        name: String,
        enabled: bool,
    }

    fn test_overrides() -> EnvOverrides<TestConfig> {
        EnvOverrides::with_prefix("TEST")
            .add_rule(
                EnvRuleBuilder::new("MAX_DEVICES")
                    .field_path("max_devices")
                    .description("Maximum device count")
                    .parse_into(|c: &mut TestConfig, v: usize| c.max_devices = v),
            )
            .add_rule(
                EnvRuleBuilder::new("NAME")
                    .field_path("name")
                    .description("Config name")
                    .as_string(|c: &mut TestConfig, v| c.name = v),
            )
            .add_rule(
                EnvRuleBuilder::new("ENABLED")
                    .field_path("enabled")
                    .description("Enable flag")
                    .as_bool(|c: &mut TestConfig, v| c.enabled = v),
            )
    }

    fn env_test_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    #[test]
    fn test_env_var_name() {
        let overrides: EnvOverrides<TestConfig> = EnvOverrides::with_prefix("TRAP_SIM");
        assert_eq!(
            overrides.full_var_name("ENGINE_MAX_DEVICES"),
            "TRAP_SIM_ENGINE_MAX_DEVICES"
        );
    }

    #[test]
    fn test_parse_bool() {
        assert_eq!(parse_bool("true"), Some(true));
        assert_eq!(parse_bool("True"), Some(true));
        assert_eq!(parse_bool("1"), Some(true));
        assert_eq!(parse_bool("yes"), Some(true));
        assert_eq!(parse_bool("on"), Some(true));
        assert_eq!(parse_bool("enabled"), Some(true));

        assert_eq!(parse_bool("false"), Some(false));
        assert_eq!(parse_bool("False"), Some(false));
        assert_eq!(parse_bool("0"), Some(false));
        assert_eq!(parse_bool("no"), Some(false));
        assert_eq!(parse_bool("off"), Some(false));
        assert_eq!(parse_bool("disabled"), Some(false));

        assert_eq!(parse_bool("invalid"), None);
    }

    #[test]
    fn test_apply_overrides() {
        let _guard = env_test_lock().lock().unwrap();

        // Set test environment variables
        env::set_var("TEST_MAX_DEVICES", "5000");
        env::set_var("TEST_NAME", "test-config");
        env::set_var("TEST_ENABLED", "true");

        let overrides = test_overrides();
        let mut config = TestConfig::default();

        let result = overrides.apply(&mut config);

        assert_eq!(result.applied, 3);
        assert_eq!(config.max_devices, 5000);
        assert_eq!(config.name, "test-config");
        assert!(config.enabled);

        // Cleanup
        env::remove_var("TEST_MAX_DEVICES");
        env::remove_var("TEST_NAME");
        env::remove_var("TEST_ENABLED");
    }

    #[test]
    fn test_parse_error() {
        let _guard = env_test_lock().lock().unwrap();

        env::set_var("TEST_MAX_DEVICES", "not_a_number");

        let overrides = test_overrides();
        let mut config = TestConfig::default();

        let result = overrides.apply(&mut config);

        assert!(result.has_errors());
        assert_eq!(result.errors.len(), 1);
        assert!(result.errors[0].message.contains("Failed to parse"));

        env::remove_var("TEST_MAX_DEVICES");
    }

    #[test]
    fn test_documentation() {
        let overrides = test_overrides();
        let docs = overrides.documentation();

        assert_eq!(docs.len(), 3);
        assert_eq!(docs[0].var_name, "TEST_MAX_DEVICES");
        assert_eq!(docs[0].field_path, "max_devices");
    }

    #[test]
    fn test_env_snapshot() {
        let _guard = env_test_lock().lock().unwrap();

        let mut snapshot = EnvSnapshot::new();
        snapshot.set("TEST_VAR", "value");
        snapshot.apply();

        assert_eq!(env::var("TEST_VAR").ok(), Some("value".to_string()));

        snapshot.clear_from_env();
        assert!(env::var("TEST_VAR").is_err());
    }
}