init4-bin-base 0.19.1

Internal utilities for binaries produced by the init4 team
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
use core::{
    fmt::{self, Display, Formatter},
    str::FromStr,
};
use signet_constants::{
    HostConstants, RollupConstants, SignetConstants, SignetEnvironmentConstants,
    SignetSystemConstants,
};
use std::env::VarError;
use tracing_core::metadata::ParseLevelError;

use crate::utils::calc::SlotCalculator;
/// The `derive(FromEnv)` macro.
///
/// This macro generates a [`FromEnv`] implementation for the struct it is
/// applied to. It will generate a `from_env` function that loads the struct
/// from the environment. It will also generate an `inventory` function that
/// returns a list of all environment variables that are required to load the
/// struct.
///
/// The macro also generates a `____EnvError` type that captures errors that can
/// occur when trying to create an instance of the struct from environment
/// variables. This error type is used in the `FromEnv` trait implementation.
///
/// ## [`FromEnv`] vs [`FromEnvVar`]
///
/// While [`FromEnvVar`] deals with loading simple types from the environment,
/// [`FromEnv`] is for loading complex types. It builds a struct from the
/// environment, usually be delegating each field to a [`FromEnvVar`] or
/// [`FromEnv`] implementation.
///
/// When using the derive macro, the props of the struct must implement
/// [`FromEnv`] or [`FromEnvVar`]. Props that implement [`FromEnv`] contain all
/// the information needed to load the struct from the environment. Props
/// that implement [`FromEnvVar`] need additional information via attributes.
///
/// ## Attributes
///
/// The macro supports the following attributes:
/// - `var = ""`: The name of the environment variable. **This is required if
///   the prop implements [`FromEnvVar`] and forbidden if the prop implements
///   [`FromEnv`].**
/// - `desc = ""`: A description of the environment variable. **This is required
///   if the prop implements [`FromEnvVar`] and forbidden if the prop
///   implements [`FromEnv`].**
/// - `optional`: Marks the prop as optional. This is currently only used in the
///   generated `fn inventory`, and is informational.
/// - `infallible`: Marks the prop as infallible. This means that the prop
///   cannot fail to be parsed after the environment variable is loaded.
/// - `skip`: Marks the prop as skipped. This means that the prop will not be
///   loaded from the environment, and will be generated via
///   `Default::default()` instead.
///
/// ## Conditions of use
///
/// There are a few usage requirements:
///
/// - Struct props MUST implement either [`FromEnvVar`] or [`FromEnv`].
/// - If the prop implements [`FromEnvVar`], it must be tagged as follows:
///     - `var = "ENV_VAR_NAME"`: The environment variable name to load.
///     - `desc = "description"`: A description of the environment variable.
/// - If the prop is an [`Option<T>`], it must be tagged as follows:
///     - `optional`
/// - If the prop's associated error type is [`Infallible`], it must be tagged
///   as follows:
///     - `infallible`
/// - If used within this crate (`init4_bin_base`), the entire struct must be
///   tagged with `#[from_env(crate)]` (see the [`SlotCalculator`] for an
///   example).
///
/// # Examples
///
/// The following example shows how to use the macro:
///
/// ```
/// # // I am unsure why we need this, as identical code works in
/// # // integration tests. However, compile test fails without it.
/// # #![allow(proc_macro_derive_resolution_fallback)]
/// use init4_bin_base::utils::from_env::{FromEnv};
///
/// #[derive(Debug, FromEnv)]
/// pub struct MyCfg {
///     #[from_env(var = "COOL_DUDE", desc = "Some u8 we like :o)")]
///     pub my_cool_u8: u8,
///
///     #[from_env(var = "CHUCK", desc = "Charles is a u64")]
///     pub charles: u64,
///
///     #[from_env(
///         var = "PERFECT",
///         desc = "A bold and neat string",
///         infallible,
///     )]
///     pub strings_cannot_fail: String,
///
///     #[from_env(
///         var = "MAYBE_NOT_NEEDED",
///         desc = "This is an optional string",
///         optional,
///         infallible,
///     )]
///     maybe_not_needed: Option<String>,
/// }
///
/// #[derive(Debug, FromEnv)]
/// pub struct MyBiggerCfg {
///     #[from_env(var = "BIGGGG_CONFIGGGG", desc = "A big config", infallible)]
///     pub big_config: String,
///
///     // Note that becuase `MyCfg` implements `FromEnv`, we do not need to
///     // specify the `var` and `desc` attributes.
///     pub little_config: MyCfg,
/// }
///
/// // The [`FromEnv`] trait is implemented for the struct, and the struct can
/// // be loaded from the environment.
/// # fn use_it() {
/// if let Err(missing) = MyBiggerCfg::check_inventory() {
///     println!("Missing environment variables:");
///     for var in missing {
///         println!("{}: {}", var.var, var.description);
///     }
/// }
/// # }
/// ```
///
/// This will generate a [`FromEnv`] implementation for the struct, and a
/// `MyCfgEnvError` type that is used to represent errors that can occur when
/// loading from the environment. The error generated will look like this:
///
/// ```ignore
/// pub enum MyCfgEnvError {
///     MyCoolU8(<u8 as FromEnvVar>::Error),
///     Charles(<u64 as FromEnvVar>::Error),
///     // No variants for infallible errors.
/// }
/// ```
///
/// [`Infallible`]: std::convert::Infallible
/// [`SlotCalculator`]: crate::utils::SlotCalculator
/// [`FromEnv`]: crate::utils::from_env::FromEnv
/// [`FromEnvVar`]: crate::utils::from_env::FromEnvVar
pub use init4_from_env_derive::FromEnv;

/// Details about an environment variable. This is used to generate
/// documentation for the environment variables and by the [`FromEnv`] trait to
/// check if necessary environment variables are present.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EnvItemInfo {
    /// The environment variable name.
    pub var: &'static str,
    /// A description of the environment variable function in the CFG.
    pub description: &'static str,
    /// Whether the environment variable is optional or not.
    pub optional: bool,
}

/// Error type for loading from the environment. See the [`FromEnv`] trait for
/// more information.
#[derive(Debug, thiserror::Error)]
pub enum FromEnvErr {
    /// The environment variable is missing.
    #[error("error reading variable {0}: {1}")]
    EnvError(String, VarError),
    /// The environment variable is empty.
    #[error("environment variable {0} is empty")]
    Empty(String),
    /// The environment variable is present, but the value could not be parsed.
    #[error("failed to parse environment variable {0}: {1}")]
    ParseError(String, #[source] Box<dyn core::error::Error + Send + Sync>),
}

impl FromEnvErr {
    /// Convert the error into another error type.
    pub fn infallible_into(self) -> FromEnvErr {
        match self {
            Self::EnvError(s, e) => FromEnvErr::EnvError(s, e),
            Self::Empty(s) => FromEnvErr::Empty(s),
            Self::ParseError(..) => unreachable!(),
        }
    }
}

impl FromEnvErr {
    /// Missing env var.
    pub fn env_err(var: &str, e: VarError) -> Self {
        Self::EnvError(var.to_string(), e)
    }

    /// Empty env var.
    pub fn empty(var: &str) -> Self {
        Self::Empty(var.to_string())
    }

    /// Error while parsing.
    pub fn parse_error<E>(var: &str, err: E) -> Self
    where
        E: core::error::Error + Send + Sync + 'static,
    {
        Self::ParseError(var.to_string(), Box::new(err))
    }
}

/// Convenience function for parsing a value from the environment, if present
/// and non-empty.
pub fn parse_env_if_present<T>(env_var: &str) -> Result<T, FromEnvErr>
where
    T: FromStr,
    T::Err: core::error::Error + Send + Sync + 'static,
{
    let s = std::env::var(env_var).map_err(|e| FromEnvErr::env_err(env_var, e))?;

    if s.is_empty() {
        Err(FromEnvErr::empty(env_var))
    } else {
        s.parse()
            .map_err(|error| FromEnvErr::ParseError(env_var.to_owned(), Box::new(error)))
    }
}

/// Trait for loading from the environment.
///
/// This trait is for structs or other complex objects, that need to be loaded
/// from the environment. It expects that
///
/// - The struct is [`Sized`] and `'static`.
/// - The struct elements can be parsed from strings.
/// - Struct elements are at fixed env vars, known by the type at compile time.
///
/// As such, unless the env is modified, these are essentially static runtime
/// values. We do not recommend using dynamic env vars.
///
/// ## [`FromEnv`] vs [`FromEnvVar`]
///
/// While [`FromEnvVar`] deals with loading simple types from the environment,
/// [`FromEnv`] is for loading complex types. It builds a struct from the
/// environment, usually be delegating each field to a [`FromEnvVar`] or
/// [`FromEnv`] implementation. [`FromEnv`] effectively defines a singleton
/// configuration object, which is produced by loading many env vars, while
/// [`FromEnvVar`] defines a procedure for loading data from a single
/// environment variable.
///
/// ## Implementing [`FromEnv`]
///
/// Please use the [`FromEnv`](macro@FromEnv) derive macro to implement this
/// trait.
///
/// ## Note on error types
///
/// [`FromEnv`] and [`FromEnvVar`] are often deeply nested. This means that
/// error types are often nested as well. To avoid this, we use a single error
/// type [`FromEnvErr`] that wraps an inner error type. This allows us to
/// ensure that env-related errors (e.g. missing env vars) are not lost in the
/// recursive structure of parsing errors. Environment errors are always at the
/// top level, and should never be nested.
pub trait FromEnv: fmt::Debug + Sized + 'static {
    /// Get the required environment variable names for this type.
    ///
    /// ## Note
    ///
    /// This MUST include the environment variable names for all fields in the
    /// struct, including optional vars.
    fn inventory() -> Vec<&'static EnvItemInfo>;

    /// Get a list of missing environment variables.
    ///
    /// This will check all environment variables in the inventory, and return
    /// a list of those that are non-optional and missing. This is useful for
    /// reporting missing environment variables.
    fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> {
        let mut missing = Vec::new();
        for var in Self::inventory() {
            match std::env::var(var.var) {
                Ok(s) if s.is_empty() && !var.optional => missing.push(var),
                Err(VarError::NotPresent) if !var.optional => missing.push(var),
                _ => {}
            }
        }
        if missing.is_empty() {
            Ok(())
        } else {
            Err(missing)
        }
    }

    /// Load from the environment.
    fn from_env() -> Result<Self, FromEnvErr>;
}

impl<T> FromEnv for Option<T>
where
    T: FromEnv,
{
    fn inventory() -> Vec<&'static EnvItemInfo> {
        T::inventory()
    }

    fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> {
        T::check_inventory()
    }

    fn from_env() -> Result<Self, FromEnvErr> {
        match T::from_env() {
            Ok(v) => Ok(Some(v)),
            Err(FromEnvErr::Empty(_)) | Err(FromEnvErr::EnvError(_, _)) => Ok(None),
            Err(e) => Err(e),
        }
    }
}

impl<T> FromEnv for Box<T>
where
    T: FromEnv,
{
    fn inventory() -> Vec<&'static EnvItemInfo> {
        T::inventory()
    }

    fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> {
        T::check_inventory()
    }

    fn from_env() -> Result<Self, FromEnvErr> {
        T::from_env().map(Box::new)
    }
}

impl<T> FromEnv for std::sync::Arc<T>
where
    T: FromEnv,
{
    fn inventory() -> Vec<&'static EnvItemInfo> {
        T::inventory()
    }

    fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> {
        T::check_inventory()
    }

    fn from_env() -> Result<Self, FromEnvErr> {
        T::from_env().map(std::sync::Arc::new)
    }
}

impl<T, U> FromEnv for std::borrow::Cow<'static, U>
where
    T: FromEnv,
    U: std::borrow::ToOwned<Owned = T> + core::fmt::Debug + ?Sized,
{
    fn inventory() -> Vec<&'static EnvItemInfo> {
        T::inventory()
    }

    fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> {
        T::check_inventory()
    }

    fn from_env() -> Result<Self, FromEnvErr> {
        T::from_env().map(std::borrow::Cow::Owned)
    }
}

/// Trait for loading primitives from the environment. These are simple types
/// that should correspond to a single environment variable. It has been
/// implemented for common integer types, [`String`], [`url::Url`],
/// [`tracing::Level`], and [`std::time::Duration`].
///
/// It aims to make [`FromEnv`] implementations easier to write, by providing a
/// default implementation for common types.
///
/// ## Note on error types
///
/// [`FromEnv`] and [`FromEnvVar`] are often deeply nested. This means that
/// error types are often nested as well. To avoid this, we use a single error
/// type [`FromEnvErr`] that wraps an inner error type. This allows us to
/// ensure that env-related errors (e.g. missing env vars) are not lost in the
/// recursive structure of parsing errors. Environment errors are always at the
/// top level, and should never be nested.
///
/// ## Implementing [`FromEnv`]
///
/// [`FromEnvVar`] is a trait for loading simple types from the environment. It
/// represents a type that can be loaded from a single environment variable. It
/// is similar to [`FromStr`] and will usually be using an existing [`FromStr`]
/// impl.
///
/// ```
/// # use init4_bin_base::utils::from_env::{FromEnvVar, FromEnvErr};
/// # use std::str::FromStr;
/// # #[derive(Debug)]
/// # pub struct MyCoolType;
/// # impl std::str::FromStr for MyCoolType {
/// #    type Err = std::convert::Infallible;
/// #    fn from_str(s: &str) -> Result<Self, Self::Err> {
/// #        Ok(MyCoolType)
/// #    }
/// # }
///
/// // We can re-use the `FromStr` implementation for our `FromEnvVar` impl.
/// impl FromEnvVar for MyCoolType {
///     fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr>
///     {
///         Ok(String::from_env_var(env_var)?.parse().unwrap())
///     }
/// }
/// ```
pub trait FromEnvVar: core::fmt::Debug + Sized + 'static {
    /// Load the primitive from the environment at the given variable.
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr>;

    /// Load the primitive from the environment at the given variable. If the
    /// variable is unset or empty, return the default value.
    ///
    /// This function will return an error if the environment variable is set
    /// but cannot be parsed.
    fn from_env_var_or(env_var: &str, default: Self) -> Result<Self, FromEnvErr> {
        match Self::from_env_var(env_var) {
            Ok(v) => Ok(v),
            Err(FromEnvErr::Empty(_)) | Err(FromEnvErr::EnvError(_, _)) => Ok(default),
            Err(e) => Err(e),
        }
    }

    /// Load the primitive from the environment at the given variable. If the
    /// variable is unset or empty, call the provided function to get the
    /// default value.
    ///
    /// This function will return an error if the environment variable is set
    /// but cannot be parsed.
    fn from_env_var_or_else(
        env_var: &str,
        default: impl FnOnce() -> Self,
    ) -> Result<Self, FromEnvErr> {
        match Self::from_env_var(env_var) {
            Ok(v) => Ok(v),
            Err(FromEnvErr::Empty(_)) | Err(FromEnvErr::EnvError(_, _)) => Ok(default()),
            Err(e) => Err(e),
        }
    }

    /// Load the primitive from the environment at the given variable. If the
    /// variable is unset or empty, return the value generated by
    /// [`Default::default`].
    ///
    /// This function will return an error if the environment variable is set
    /// but cannot be parsed.
    fn from_env_var_or_default(env_var: &str) -> Result<Self, FromEnvErr>
    where
        Self: Default,
    {
        Self::from_env_var_or_else(env_var, Self::default)
    }
}

impl<T> FromEnvVar for Option<T>
where
    T: FromEnvVar,
{
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        match std::env::var(env_var) {
            Ok(s) if s.is_empty() => Ok(None),
            Ok(_) => T::from_env_var(env_var).map(Some),
            Err(VarError::NotPresent) => Ok(None),
            Err(error) => Err(FromEnvErr::parse_error(env_var, error)),
        }
    }
}

impl<T> FromEnvVar for Box<T>
where
    T: FromEnvVar,
{
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        T::from_env_var(env_var).map(Box::new)
    }
}

impl<T> FromEnvVar for std::sync::Arc<T>
where
    T: FromEnvVar,
{
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        T::from_env_var(env_var).map(std::sync::Arc::new)
    }
}

impl<T, U> FromEnvVar for std::borrow::Cow<'static, U>
where
    T: FromEnvVar,
    U: ToOwned<Owned = T> + core::fmt::Debug + ?Sized,
{
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        T::from_env_var(env_var).map(std::borrow::Cow::Owned)
    }
}

impl FromEnvVar for String {
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        std::env::var(env_var).map_err(|_| FromEnvErr::empty(env_var))
    }
}

impl FromEnvVar for std::time::Duration {
    fn from_env_var(s: &str) -> Result<Self, FromEnvErr> {
        u64::from_env_var(s).map(Self::from_millis)
    }
}

impl<T> FromEnvVar for Vec<T>
where
    T: From<String> + core::fmt::Debug + 'static,
{
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        let s = std::env::var(env_var).map_err(|e| FromEnvErr::env_err(env_var, e))?;
        if s.is_empty() {
            return Ok(vec![]);
        }
        Ok(s.split(',')
            .map(str::to_string)
            .map(Into::into)
            .collect::<Vec<_>>())
    }
}

/// Generate an `Optional{Name}WithDefault` newtype that wraps `$inner` with a const generic
/// default. When the env var is missing or empty, the default is used. The `$parse` closure
/// controls how a non-empty string is converted to the inner type.
macro_rules! optional_with_default {
    (
        $(#[$meta:meta])*
        $name:ident, $inner:ty, |$var:ident, $s:ident| $parse:expr
    ) => {
        $(#[$meta])*
        #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Copy, Debug)]
        pub struct $name<const DEFAULT: $inner>($inner);

        impl<const DEFAULT: $inner> $name<DEFAULT> {
            /// Extract the inner value.
            pub const fn into_inner(self) -> $inner {
                self.0
            }
        }

        impl<const DEFAULT: $inner> Display for $name<DEFAULT> {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                <$inner as Display>::fmt(&self.0, f)
            }
        }

        impl<const DEFAULT: $inner> Default for $name<DEFAULT> {
            fn default() -> Self {
                Self(DEFAULT)
            }
        }

        impl<const DEFAULT: $inner> FromEnvVar for $name<DEFAULT> {
            fn from_env_var($var: &str) -> Result<Self, FromEnvErr> {
                match std::env::var($var) {
                    Ok($s) if $s.is_empty() => Ok(Self(DEFAULT)),
                    Ok($s) => $parse.map(Self),
                    Err(VarError::NotPresent) => Ok(Self(DEFAULT)),
                    Err(error) => Err(FromEnvErr::parse_error($var, error)),
                }
            }
        }
    };
}

optional_with_default! {
    /// An optional boolean with a const default, for use in config structs.
    /// A non-empty value is treated as `true`; missing or empty falls back to the default.
    OptionalBoolWithDefault, bool, |env_var, _s| Ok(true)
}

/// Helper for numeric `optional_with_default!` invocations: parse a non-empty string.
fn parse_or_err<T: FromStr>(env_var: &str, s: &str) -> Result<T, FromEnvErr>
where
    T::Err: core::error::Error + Send + Sync + 'static,
{
    s.parse::<T>()
        .map_err(|error| FromEnvErr::parse_error(env_var, error))
}

optional_with_default! {
    /// An optional `u8` with a const default, for use in config structs.
    OptionalU8WithDefault, u8, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `u16` with a const default, for use in config structs.
    OptionalU16WithDefault, u16, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `u32` with a const default, for use in config structs.
    OptionalU32WithDefault, u32, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `u64` with a const default, for use in config structs.
    OptionalU64WithDefault, u64, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `u128` with a const default, for use in config structs.
    OptionalU128WithDefault, u128, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `usize` with a const default, for use in config structs.
    OptionalUsizeWithDefault, usize, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `i8` with a const default, for use in config structs.
    OptionalI8WithDefault, i8, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `i16` with a const default, for use in config structs.
    OptionalI16WithDefault, i16, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `i32` with a const default, for use in config structs.
    OptionalI32WithDefault, i32, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `i64` with a const default, for use in config structs.
    OptionalI64WithDefault, i64, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `i128` with a const default, for use in config structs.
    OptionalI128WithDefault, i128, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `isize` with a const default, for use in config structs.
    OptionalIsizeWithDefault, isize, |env_var, s| parse_or_err(env_var, &s)
}
optional_with_default! {
    /// An optional `char` with a const default, for use in config structs.
    OptionalCharWithDefault, char, |env_var, s| parse_or_err(env_var, &s)
}

macro_rules! impl_for_parseable {
    ($($t:ty),*) => {
        $(
            impl FromEnvVar for $t {
                fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
                    parse_env_if_present(env_var)
                }
            }
        )*
    }
}

impl_for_parseable!(
    u8,
    u16,
    u32,
    u64,
    u128,
    usize,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    url::Url,
    SignetConstants,
    SignetEnvironmentConstants,
    SignetSystemConstants,
    HostConstants,
    RollupConstants,
    SlotCalculator
);

#[cfg(feature = "alloy")]
impl_for_parseable!(
    alloy::primitives::Address,
    alloy::primitives::Bytes,
    alloy::primitives::U256
);

#[cfg(feature = "alloy")]
impl<const N: usize> FromEnvVar for alloy::primitives::FixedBytes<N> {
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        parse_env_if_present(env_var)
    }
}

impl FromEnvVar for bool {
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        let s: String = std::env::var(env_var).map_err(|e| FromEnvErr::env_err(env_var, e))?;
        Ok(!s.is_empty())
    }
}

/// Error type for parsing tracing levels from the environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("failed to parse tracing level from environment variable")]
pub struct LevelParseError;

impl From<ParseLevelError> for LevelParseError {
    fn from(_: ParseLevelError) -> Self {
        LevelParseError
    }
}

impl FromEnvVar for tracing::Level {
    fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr> {
        let s: String = std::env::var(env_var).map_err(|e| FromEnvErr::env_err(env_var, e))?;
        s.parse()
            .map_err(LevelParseError::from)
            .map_err(|error| FromEnvErr::parse_error(env_var, error))
    }
}

impl FromEnv for SignetSystemConstants {
    fn inventory() -> Vec<&'static EnvItemInfo> {
        vec![&EnvItemInfo {
            var: "CHAIN_NAME",
            description: "The name of the chain",
            optional: false,
        }]
    }

    fn from_env() -> Result<Self, FromEnvErr> {
        SignetSystemConstants::from_env_var("CHAIN_NAME")
    }
}

#[cfg(feature = "cold-sql")]
mod cold_sql {
    use super::{EnvItemInfo, FromEnv, FromEnvErr, FromEnvVar};

    const URL_VAR: &str = "SIGNET_COLD_SQL_URL";
    const MAX_CONNECTIONS_VAR: &str = "SIGNET_COLD_SQL_MAX_CONNECTIONS";
    const MIN_CONNECTIONS_VAR: &str = "SIGNET_COLD_SQL_MIN_CONNECTIONS";
    const ACQUIRE_TIMEOUT_SECS_VAR: &str = "SIGNET_COLD_SQL_ACQUIRE_TIMEOUT_SECS";
    const MAX_LIFETIME_SECS_VAR: &str = "SIGNET_COLD_SQL_MAX_LIFETIME_SECS";
    const IDLE_TIMEOUT_SECS_VAR: &str = "SIGNET_COLD_SQL_IDLE_TIMEOUT_SECS";

    const DEFAULT_MAX_CONNECTIONS: u32 = 100;
    const DEFAULT_MIN_CONNECTIONS: u32 = 5;
    const DEFAULT_ACQUIRE_TIMEOUT_SECS: u64 = 5;
    const DEFAULT_MAX_LIFETIME_SECS: u64 = 1800;
    const DEFAULT_IDLE_TIMEOUT_SECS: u64 = 600;

    impl FromEnv for signet_cold_sql::SqlConnector {
        fn inventory() -> Vec<&'static EnvItemInfo> {
            vec![
                &EnvItemInfo {
                    var: URL_VAR,
                    description: "SQL connection URL for cold storage (postgres:// or sqlite:)",
                    optional: false,
                },
                &EnvItemInfo {
                    var: MAX_CONNECTIONS_VAR,
                    description: "Max SQL pool connections [default: 100]",
                    optional: true,
                },
                &EnvItemInfo {
                    var: MIN_CONNECTIONS_VAR,
                    description: "Min SQL pool idle connections [default: 5]",
                    optional: true,
                },
                &EnvItemInfo {
                    var: ACQUIRE_TIMEOUT_SECS_VAR,
                    description: "SQL pool acquire timeout in seconds [default: 5]",
                    optional: true,
                },
                &EnvItemInfo {
                    var: MAX_LIFETIME_SECS_VAR,
                    description: "SQL pool max connection lifetime in seconds [default: 1800]",
                    optional: true,
                },
                &EnvItemInfo {
                    var: IDLE_TIMEOUT_SECS_VAR,
                    description: "SQL pool idle timeout in seconds [default: 600]",
                    optional: true,
                },
            ]
        }

        fn from_env() -> Result<Self, FromEnvErr> {
            let url = String::from_env_var(URL_VAR)?;
            let max_conns = u32::from_env_var_or(MAX_CONNECTIONS_VAR, DEFAULT_MAX_CONNECTIONS)?;
            let min_conns = u32::from_env_var_or(MIN_CONNECTIONS_VAR, DEFAULT_MIN_CONNECTIONS)?;
            let acquire_timeout =
                u64::from_env_var_or(ACQUIRE_TIMEOUT_SECS_VAR, DEFAULT_ACQUIRE_TIMEOUT_SECS)?;
            let max_lifetime =
                u64::from_env_var_or(MAX_LIFETIME_SECS_VAR, DEFAULT_MAX_LIFETIME_SECS)?;
            let idle_timeout =
                u64::from_env_var_or(IDLE_TIMEOUT_SECS_VAR, DEFAULT_IDLE_TIMEOUT_SECS)?;

            Ok(Self::new(url)
                .with_max_connections(max_conns)
                .with_min_connections(min_conns)
                .with_acquire_timeout(std::time::Duration::from_secs(acquire_timeout))
                .with_idle_timeout(Some(std::time::Duration::from_secs(idle_timeout)))
                .with_max_lifetime(Some(std::time::Duration::from_secs(max_lifetime))))
        }
    }
}

#[cfg(test)]
mod test {
    use std::{borrow::Cow, time::Duration};

    use super::*;

    fn set<T>(env: &str, val: &T)
    where
        T: ToString + ?Sized,
    {
        std::env::set_var(env, val.to_string());
    }

    fn test<T>(env: &str, val: T)
    where
        T: ToString + FromEnvVar + PartialEq + std::fmt::Debug,
    {
        set(env, &val);

        let res = T::from_env_var(env).unwrap();
        assert_eq!(res, val);
    }

    #[test]
    fn test_primitives() {
        test("U8", 42u8);
        test("U16", 42u16);
        test("U32", 42u32);
        test("U64", 42u64);
        test("U128", 42u128);
        test("Usize", 42usize);
        test("I8", 42i8);
        test("I8-NEG", -42i16);
        test("I16", 42i16);
        test("I32", 42i32);
        test("I64", 42i64);
        test("I128", 42i128);
        test("Isize", 42isize);
        test("String", "hello".to_string());
        test("Url", url::Url::parse("http://example.com").unwrap());
        test("Level", tracing::Level::INFO);
    }

    #[test]
    fn test_duration() {
        let amnt = 42;
        let val = Duration::from_millis(42);

        set("Duration", &amnt);
        let res = Duration::from_env_var("Duration").unwrap();

        assert_eq!(res, val);
    }

    #[test]
    fn test_a_few_errors() {
        set("U8_", &30000u16);
        let err = u8::from_env_var("U8_").unwrap_err();
        assert!(matches!(err, FromEnvErr::ParseError(ref var, _) if var == "U8_"));

        set("U8_", &"");
        let err = u8::from_env_var("U8_").unwrap_err();
        assert!(matches!(err, FromEnvErr::Empty(ref var) if var == "U8_"));
    }

    #[test]
    fn is_cow_str_from_env_var() {
        let s = "hello";
        set("COW", s);
        let res: Cow<'static, str> = Cow::from_env_var("COW").unwrap();
        assert_eq!(res, Cow::<'static, str>::Owned(s.to_owned()));
    }
}