lockedenv 0.3.0

Type-safe, freeze-on-load environment variable management
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
//! Type-safe, freeze-on-load environment variable management.
//! Read and parse your environment once at startup into a generated struct.

#[cfg(feature = "dotenv")]
pub mod dotenv;
pub mod error;
pub mod lock;
pub mod parse;
#[cfg(feature = "watch")]
pub mod watcher;

// Re-export commonly used items
pub use error::EnvLockError;
pub use parse::{FromEnvStr, Secret};

#[doc(hidden)]
#[cfg(feature = "serde")]
pub use serde;
#[doc(hidden)]
#[cfg(feature = "tracing")]
pub use tracing;

// ── public macros ─────────────────────────────────────────────────────────────

/// Define a named, publicly accessible configuration struct with built-in
/// `load`, `try_load`, `from_map`, and `try_from_map` associated functions.
///
/// Unlike the anonymous structs produced by [`load!`], the struct defined here
/// has a real name and can be stored, returned from functions, and used as a
/// type in other signatures.
///
/// # Syntax
///
/// ```rust,no_run
/// lockedenv::env_struct! {
///     pub struct AppConfig {
///         HOST: String,
///         PORT: u16 = 8080,
///         TOKEN: lockedenv::Secret<String>,
///         LABEL: Option<String>,
///     }
/// }
///
/// fn main() {
///     let cfg = AppConfig::load();    // panics on error
///     println!("{}", cfg.HOST);
/// }
/// ```
///
/// A `prefix` can be supplied to strip a common namespace:
///
/// ```rust,no_run
/// lockedenv::env_struct! {
///     pub struct SvcConfig {
///         prefix = "SVC_",
///         HOST: String,
///         PORT: u16,
///     }
/// }
/// // reads SVC_HOST and SVC_PORT from the environment
/// ```
#[macro_export]
macro_rules! env_struct {
    // With prefix
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            prefix = $prefix:literal,
            $($key:ident : $ty:ty $(= $def:expr)?),* $(,)?
        }
    ) => {
        $crate::__env_struct_impl! { $(#[$meta])* $vis $name $prefix [ $($key : $ty $(= $def)?),* ] }
    };
    // Without prefix
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $($key:ident : $ty:ty $(= $def:expr)?),* $(,)?
        }
    ) => {
        $crate::__env_struct_impl! { $(#[$meta])* $vis $name "" [ $($key : $ty $(= $def)?),* ] }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __env_struct_impl {
    (
        $(#[$meta:meta])* $vis:vis $name:ident $prefix:literal [ $($key:ident : $ty:ty $(= $def:expr)?),* $(,)? ]
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq)]
        #[cfg_attr(feature = "serde", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
        $vis struct $name {
            $(pub $key: $ty,)*
        }

        impl $name {
            /// Load from OS environment variables; panics on any error.
            pub fn load() -> Self {
                Self::try_load().unwrap_or_else(|e| panic!("{}", e))
            }

            /// Load from OS environment variables; returns `Result`.
            pub fn try_load() -> Result<Self, $crate::EnvLockError> {
                $(
                    #[allow(non_snake_case)]
                    let $key: $ty = $crate::load_internal!(
                        @read_field $ty, concat!($prefix, stringify!($key)) $(, $def)?
                    );
                )*
                #[cfg(feature = "tracing")]
                {
                    let __result = Self { $($key: $key.clone()),* };
                    $crate::tracing::info!(config = ?__result, "lockedenv loaded");
                }
                Ok(Self { $($key),* })
            }

            /// Load from a `HashMap`; panics on any error.
            pub fn from_map(__map: &std::collections::HashMap<String, String>) -> Self {
                Self::try_from_map(__map).unwrap_or_else(|e| panic!("{}", e))
            }

            /// Load from a `HashMap`; returns `Result`.
            pub fn try_from_map(
                __map: &std::collections::HashMap<String, String>,
            ) -> Result<Self, $crate::EnvLockError> {
                $(
                    #[allow(non_snake_case)]
                    let $key: $ty = {
                        let __full_key = concat!($prefix, stringify!($key));
                        match __map.get(__full_key) {
                            Some(__val) => {
                                <$ty as $crate::parse::FromEnvStr>::from_env_str(__val)
                                    .map_err(|e| {
                                        let __found = if <$ty as $crate::parse::FromEnvStr>::REDACT_IN_ERRORS {
                                            "[REDACTED]".into()
                                        } else {
                                            __val.to_string()
                                        };
                                        $crate::EnvLockError::parse_error(
                                            __full_key.into(),
                                            __found,
                                            e,
                                        )
                                    })?
                            }
                            None => $crate::load_internal!(@map_none $ty, __full_key $(, $def)?),
                        }
                    };
                )*
                Ok(Self { $($key),* })
            }
        }
    };
}

/// Like `load!` but returns a `Result<_, EnvLockError>` instead of panicking.
#[macro_export]
macro_rules! try_load {
    { prefix = $prefix:literal, $($rest:tt)* } => {
        $crate::load_internal!(@env $prefix, $($rest)* )
    };
    { $($rest:tt)* } => {
        $crate::load_internal!(@env "", $($rest)* )
    };
}

/// Parse the environment and panic on error; returns the generated struct.
#[macro_export]
macro_rules! load {
    { $($rest:tt)* } => {
        $crate::try_load! { $($rest)* }.unwrap_or_else(|e| panic!("{}", e))
    };
}

/// Like `try_load!` but parses from a provided `HashMap` instead of the OS env.
#[macro_export]
macro_rules! try_from_map {
    (map: $map:expr, prefix = $prefix:literal, $($rest:tt)*) => {
        $crate::load_internal!(@map $map, $prefix, $($rest)*)
    };
    (map: $map:expr, $($rest:tt)*) => {
        $crate::load_internal!(@map $map, "", $($rest)*)
    };
}

/// `try_from_map!` variant that panics on failure.
#[macro_export]
macro_rules! from_map {
    (map: $map:expr, $($rest:tt)*) => {
        $crate::try_from_map!(map: $map, $($rest)*).unwrap_or_else(|e| panic!("{}", e))
    };
}

/// Like [`try_load!`] but collects **all** parse/missing errors instead of stopping
/// at the first one.  Returns `Ok(config)` when every field parsed successfully,
/// or `Err(Vec<EnvLockError>)` listing every problem found.
///
/// Also accepts a `map:` argument for HashMap injection (useful in tests):
///
/// ```rust,no_run
/// match lockedenv::try_check! { HOST: String, PORT: u16, DB: String } {
///     Ok(cfg)  => { /* use cfg */ }
///     Err(errs) => {
///         for e in &errs { eprintln!("{e}"); }
///         std::process::exit(1);
///     }
/// }
/// ```
#[macro_export]
macro_rules! try_check {
    // map — with prefix (must precede env rules; `map:` literal distinguishes them)
    { map: $map:expr, prefix = $prefix:literal, $($rest:tt)* } => {
        $crate::__check_internal!(@map $map, $prefix, $($rest)*)
    };
    // map — no prefix
    { map: $map:expr, $($key:ident : $ty:ty $(= $def:expr)?),* $(,)? } => {
        $crate::__check_internal!(@map $map, "", $($key: $ty $(= $def)?),*)
    };
    // env — with prefix
    { prefix = $prefix:literal, $($rest:tt)* } => {
        $crate::__check_internal!(@env $prefix, $($rest)*)
    };
    // env — no prefix
    { $($key:ident : $ty:ty $(= $def:expr)?),* $(,)? } => {
        $crate::__check_internal!(@env "", $($key: $ty $(= $def)?),*)
    };
}

/// Like [`load!`] but panics with **all** errors listed, not just the first.
/// Accepts the same syntax as [`try_check!`].
#[macro_export]
macro_rules! check {
    // map — with prefix
    { map: $map:expr, prefix = $prefix:literal, $($rest:tt)* } => {
        $crate::try_check! { map: $map, prefix = $prefix, $($rest)* }
            .unwrap_or_else(|__errs| {
                let __msg = __errs.iter()
                    .map(|e| format!("  - {}", e))
                    .collect::<Vec<_>>()
                    .join("\n");
                panic!("{} configuration error(s):\n{}", __errs.len(), __msg)
            })
    };
    // map — no prefix
    { map: $map:expr, $($rest:tt)* } => {
        $crate::try_check! { map: $map, $($rest)* }
            .unwrap_or_else(|__errs| {
                let __msg = __errs.iter()
                    .map(|e| format!("  - {}", e))
                    .collect::<Vec<_>>()
                    .join("\n");
                panic!("{} configuration error(s):\n{}", __errs.len(), __msg)
            })
    };
    // env
    { $($rest:tt)* } => {
        $crate::try_check! { $($rest)* }
            .unwrap_or_else(|__errs| {
                let __msg = __errs.iter()
                    .map(|e| format!("  - {}", e))
                    .collect::<Vec<_>>()
                    .join("\n");
                panic!("{} configuration error(s):\n{}", __errs.len(), __msg)
            })
    };
}

// Hidden helper macros for check!/try_check!

#[doc(hidden)]
#[macro_export]
macro_rules! __check_internal {
    // ── env variant ──────────────────────────────────────────────────────────
    (@env $prefix:expr, $($key:ident : $ty:ty $(= $def:expr)?),* $(,)?) => {{
        #[allow(non_snake_case)]
        #[derive(Debug, Clone, PartialEq)]
        #[cfg_attr(feature = "serde", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
        struct __CheckConfig { $($key: $ty,)* }

        let mut __errors: Vec<$crate::EnvLockError> = Vec::new();

        $(
            #[allow(non_snake_case)]
            let $key: Result<$ty, $crate::EnvLockError> =
                $crate::__check_read_env!($ty, concat!($prefix, stringify!($key)) $(, $def)?);
            if let Err(ref __e) = $key {
                __errors.push(__e.clone());
            }
        )*

        if __errors.is_empty() {
            // All Ok — unwrap is safe: each $key is Ok when __errors is empty.
            #[allow(clippy::unwrap_used)]
            Ok(__CheckConfig { $($key: $key.unwrap()),* })
        } else {
            Err(__errors)
        }
    }};

    // ── map variant ──────────────────────────────────────────────────────────
    (@map $map:expr, $prefix:expr, $($key:ident : $ty:ty $(= $def:expr)?),* $(,)?) => {{
        #[allow(non_snake_case)]
        #[derive(Debug, Clone, PartialEq)]
        #[cfg_attr(feature = "serde", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
        struct __CheckConfig { $($key: $ty,)* }

        let __check_map = &$map;
        let mut __errors: Vec<$crate::EnvLockError> = Vec::new();

        $(
            #[allow(non_snake_case)]
            let $key: Result<$ty, $crate::EnvLockError> = {
                let __full_key = concat!($prefix, stringify!($key));
                match __check_map.get(__full_key) {
                    Some(__val) => {
                        <$ty as $crate::parse::FromEnvStr>::from_env_str(__val)
                            .map_err(|e| {
                                let __found = if <$ty as $crate::parse::FromEnvStr>::REDACT_IN_ERRORS {
                                    "[REDACTED]".into()
                                } else {
                                    __val.to_string()
                                };
                                $crate::EnvLockError::parse_error(__full_key.into(), __found, e)
                            })
                    }
                    None => $crate::__check_map_none!($ty, __full_key $(, $def)?),
                }
            };
            if let Err(ref __e) = $key {
                __errors.push(__e.clone());
            }
        )*

        if __errors.is_empty() {
            #[allow(clippy::unwrap_used)]
            Ok(__CheckConfig { $($key: $key.unwrap()),* })
        } else {
            Err(__errors)
        }
    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __check_read_env {
    ($ty:ty, $key:expr, $def:expr) => {
        $crate::lock::__read_default::<$ty>($key, $def)
    };
    ($ty:ty, $key:expr) => {
        $crate::lock::__read_required::<$ty>($key)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __check_map_none {
    ($ty:ty, $key:expr, $def:expr) => {
        Ok::<$ty, $crate::EnvLockError>($def)
    };
    ($ty:ty, $key:expr) => {
        $crate::lock::__missing_value::<$ty>($key)
    };
}

// Internal implementation macro — not part of the public API.
// Exported only because Rust macros require cross-crate visibility.
#[doc(hidden)]
#[macro_export]
macro_rules! load_internal {
    // env-loading case
    (@env $prefix:expr,
        $($key:ident : $ty:ty $(= $def:expr)?),* $(,)? ) => {
        {
            #[allow(non_snake_case)]
            #[derive(Debug, Clone, PartialEq)]
            #[cfg_attr(feature = "serde", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
            struct __EnvLockConfig {
                $( $key: $ty, )*
            }

            let cfg = (|| -> Result<__EnvLockConfig, $crate::EnvLockError> {
                $(
                    #[allow(non_snake_case)]
                    let $key: $ty = $crate::load_internal!(@read_field $ty, concat!($prefix, stringify!($key)) $(, $def)? );
                )*
                let result = __EnvLockConfig { $( $key ),* };
                $crate::load_internal!(@log result);
                Ok(result)
            })();
            cfg
        }
    };

    // from-map case
    (@map $map:expr, $prefix:expr,
        $($key:ident : $ty:ty $(= $def:expr)?),* $(,)? ) => {
        {
            #[allow(non_snake_case)]
            #[derive(Debug, Clone, PartialEq)]
            #[cfg_attr(feature = "serde", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
            struct __EnvLockConfig {
                $( $key: $ty, )*
            }
            let __env_lock_map = &$map;
            let cfg = (|| -> Result<__EnvLockConfig, $crate::EnvLockError> {
                $(
                    #[allow(non_snake_case)]
                    let $key: $ty = {
                        let full_key = concat!($prefix, stringify!($key));
                        let v_opt = __env_lock_map.get(full_key);
                        match v_opt {
                            Some(val) => {
                                <$ty as $crate::parse::FromEnvStr>::from_env_str(val)
                                    .map_err(|e| {
                                        let found = if <$ty as $crate::parse::FromEnvStr>::REDACT_IN_ERRORS {
                                            "[REDACTED]".into()
                                        } else {
                                            val.to_string()
                                        };
                                        $crate::EnvLockError::parse_error(full_key.into(), found, e)
                                    })?
                            }
                            None => $crate::load_internal!(@map_none $ty, full_key $(, $def)?),
                        }
                    };
                )*
                let result = __EnvLockConfig { $( $key ),* };
                $crate::load_internal!(@log result);
                Ok(result)
            })();
            cfg
        }
    };

    (@log $cfg:ident) => {
        #[cfg(feature = "tracing")]
        $crate::tracing::info!(config = ?$cfg, "lockedenv loaded");
    };

    // None branch without default: use missing_value (Option<T> → Ok(None), others → Err)
    (@map_none $ty:ty, $key:expr) => {
        $crate::lock::__missing_value::<$ty>($key)?
    };
    // None branch with explicit default
    (@map_none $ty:ty, $key:expr, $def:expr) => {
        $def
    };

    // helper to read single field from env, with/without default
    (@read_field $ty:ty, $key:expr, $def:expr) => {
        $crate::lock::__read_default::<$ty>($key, $def)?
    };
    (@read_field $ty:ty, $key:expr) => {
        $crate::lock::__read_required::<$ty>($key)?
    };

}

// --- feature: dotenv ---

/// Load a `.env` file into the process environment, then read variables.
/// Panics if the file exists but cannot be parsed.
/// A missing file is silently ignored.
/// Requires feature `dotenv`.
///
/// ```rust,no_run
/// let config = lockedenv::load_dotenv! {
///     path: ".env",
///     PORT: u16,
///     DATABASE_URL: String,
/// };
/// ```
#[cfg(feature = "dotenv")]
#[macro_export]
macro_rules! load_dotenv {
    (path: $path:expr, $($rest:tt)*) => {
        {
            $crate::dotenv::load_file($path).unwrap_or_else(|e| panic!("{}", e));
            $crate::load! { $($rest)* }
        }
    };
}

/// Load a `.env` file into the process environment, then read variables,
/// returning `Result`.
/// Requires feature `dotenv`.
///
/// ```rust,no_run
/// fn main() -> Result<(), lockedenv::EnvLockError> {
///     let config = lockedenv::try_load_dotenv! { path: ".env.local", PORT: u16 }?;
///     Ok(())
/// }
/// ```
#[cfg(feature = "dotenv")]
#[macro_export]
macro_rules! try_load_dotenv {
    (path: $path:expr, $($rest:tt)*) => {
        {
            $crate::dotenv::load_file($path)?;
            $crate::try_load! { $($rest)* }
        }
    };
}

// --- feature: watch ---

/// Start a background drift-detection watcher for a specific set of keys.
///
/// Returns a [`watcher::WatchHandle`]; drop it (or call `.stop()`) to
/// terminate the thread gracefully.
///
/// Only variables listed in `keys` are monitored.  On each tick the watcher
/// reads exactly those keys via [`std::env::var`] — O(watched vars) instead
/// of O(all env vars).
///
/// `on_drift` receives `(key: &str, old: &str, new: &str)` on each change.
/// `"<removed>"` is passed as `new` when a variable disappears;
/// `"<missing>"` is passed as `old` when a variable is newly added.
///
/// Requires feature `watch`.
///
/// ```rust,no_run
/// let _handle = lockedenv::watch!(
///     keys = ["PORT", "DATABASE_URL"],
///     interval_secs = 60,
///     on_drift = |key, _old, _new| {
///         eprintln!("env drift detected: {}", key);
///     }
/// );
/// // Drop _handle to stop the watcher gracefully.
/// ```
#[cfg(feature = "watch")]
#[macro_export]
macro_rules! watch {
    (keys = [$($key:expr),* $(,)?], interval_secs = $secs:expr, on_drift = $cb:expr) => {
        $crate::watcher::start(
            vec![$($key.to_string()),*],
            std::time::Duration::from_secs($secs),
            $cb,
        )
    };
    (keys = [$($key:expr),* $(,)?], interval_ms = $ms:expr, on_drift = $cb:expr) => {
        $crate::watcher::start(
            vec![$($key.to_string()),*],
            std::time::Duration::from_millis($ms),
            $cb,
        )
    };
    (keys = [$($key:expr),* $(,)?], on_drift = $cb:expr) => {
        $crate::watcher::start(
            vec![$($key.to_string()),*],
            std::time::Duration::from_secs(5),
            $cb,
        )
    };
}