parsenv 0.1.0

Utilities for easy definition and parsing of environment variables
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
//! Library for common environment variable parsing functionality and types.

use std::{
    any::Any, borrow::Cow, env, error::Error as StdError, marker::PhantomData, str::FromStr,
    time::Duration,
};

use chrono::TimeDelta;

/// An abstraction around environment variable parsing.
///
/// Construct an env var using EnvVar::new("variable_name").
///
/// All env vars must have a parser, to go from an env var string to a value.
///
/// If the value has a `FromStr` implementation, you can use `.with_from_str_parser()`
/// to set the parser.
///
/// Alternatively, a custom parser instance may be passed to `.with_custom_parser()`.
/// The parser must implement `EnvVarParser`.
///
/// A default may be set on an env var with a configured parser, using `.with_default()`.
///
/// EnvVars may be parsed with either `.parse_required()`, which returns an error
/// if the variable is absent, or `.parse_optional()`, which returns None if the
/// variable is absent.
///
/// EnvVars that have configured defaults may also be parsed with `.parse_or_default()`,
/// which will return the provided default if the variable is absent.
pub struct EnvVar<P, D> {
    variable: Cow<'static, str>,
    parser: P,
    default: D,
}

/// Implementation for uninitialized type.
impl EnvVar<EnvVarNoParser, EnvVarNoDefault> {
    /// Construct a new EnvVar.
    ///
    /// Must specify a parser in order to parse.
    pub fn new(variable: impl Into<Cow<'static, str>>) -> Self {
        Self {
            variable: variable.into(),
            parser: EnvVarNoParser,
            default: EnvVarNoDefault,
        }
    }

    pub fn const_new(variable: &'static str) -> Self {
        Self {
            variable: Cow::Borrowed(variable),
            parser: EnvVarNoParser,
            default: EnvVarNoDefault,
        }
    }
}

/// Implementation on a type with an uninitialized parser.
impl<D> EnvVar<EnvVarNoParser, D> {
    /// Configure the EnvVar to use destination type's FromStr impl to parse
    /// the variable value.
    pub fn with_from_str_parser<T>(self) -> EnvVar<EnvVarFromStrParser<T>, D>
    where
        T: FromStr,
        T::Err: StdError + Send + Sync + 'static,
    {
        EnvVar {
            variable: self.variable,
            parser: EnvVarFromStrParser(PhantomData::<T>),
            default: self.default,
        }
    }

    pub fn with_bool_parser(self) -> EnvVar<EnvVarCustomParser<BoolEnvVarParser>, D> {
        EnvVar {
            variable: self.variable,
            parser: EnvVarCustomParser(BoolEnvVarParser),
            default: self.default,
        }
    }

    /// Configure the EnvVar to use the provided parser to parse the variable value.
    pub fn with_custom_parser<T>(self, parser: T) -> EnvVar<EnvVarCustomParser<T>, D>
    where
        T: EnvVarParser,
    {
        EnvVar {
            variable: self.variable,
            parser: EnvVarCustomParser(parser),
            default: self.default,
        }
    }
}

/// Implementation on a type with an uninitialized Default, which has already
/// configured a Parser.
impl<P> EnvVar<P, EnvVarNoDefault>
where
    Self: ParseEnvVarValue,
    <Self as ParseEnvVarValue>::Value: Clone,
{
    pub fn with_default(
        self,
        // insist that our default value be the same as our parser value
        value: <Self as ParseEnvVarValue>::Value,
    ) -> EnvVar<P, EnvVarDefault<<Self as ParseEnvVarValue>::Value>> {
        EnvVar {
            variable: self.variable,
            parser: self.parser,
            default: EnvVarDefault { value },
        }
    }

    pub fn use_default(self) -> EnvVar<P, EnvVarDefault<<Self as ParseEnvVarValue>::Value>>
    where
        <Self as ParseEnvVarValue>::Value: Default,
    {
        EnvVar {
            variable: self.variable,
            parser: self.parser,
            default: EnvVarDefault {
                value: <Self as ParseEnvVarValue>::Value::default(),
            },
        }
    }
}

/// Marker type for an EnvVar that has not configured a parser.
pub struct EnvVarNoParser;

/// Marker type for an EnvVar that has not configured a default.
pub struct EnvVarNoDefault;

/// An env var default value
pub struct EnvVarDefault<T> {
    value: T,
}

/// A marker type indicating the EnvVar should use T's FromStr implementation as
/// a parser.
pub struct EnvVarFromStrParser<T>(PhantomData<T>)
where
    T: FromStr,
    T::Err: StdError + Send + Sync + 'static;

/// A custom parser for an EnvVar.
pub struct EnvVarCustomParser<T>(T)
where
    T: EnvVarParser;

/// Trait defining parse methods available whether or not an EnvVar is configured
/// with a default value.
pub trait ParseBase: ParseEnvVarValue {
    fn parse_required(&self) -> Result<Self::Value, EnvVarError>;

    fn parse_optional(&self) -> Result<Option<Self::Value>, EnvVarError>;
}

/// Implementation of ParseBase for any EnvVar where we can parse the env var value.
impl<T, U> ParseBase for EnvVar<T, U>
where
    Self: ParseEnvVarValue,
{
    fn parse_required(&self) -> Result<Self::Value, EnvVarError> {
        let raw = env::var(self.variable.as_ref())
            .map_err(|e| EnvVarError::new(self.variable.clone(), e))?;

        self.parse(&raw)
    }

    fn parse_optional(&self) -> Result<Option<Self::Value>, EnvVarError> {
        env::var(self.variable.as_ref())
            .map(Some)
            .or_else(|e| match e {
                env::VarError::NotPresent => Ok(None),
                env::VarError::NotUnicode(..) => Err(EnvVarError::new(self.variable.clone(), e)),
            })?
            // empty strings are treated as absent values
            .filter(|v| !v.is_empty())
            .map(|v| self.parse(&v))
            .transpose()
    }
}

/// Trait for EnvVars that have a configured default.
pub trait ParseOrDefault: ParseEnvVarValue {
    fn parse_or_default(&self) -> Result<Self::Value, EnvVarError>;
}

/// Trait to retrieve an EnvVar's default value.
pub trait GetDefault {
    type Value;

    fn default(&self) -> Self::Value;
}

/// Implementation of GetDefault for an EnvVar with a configured default.
///
/// Note that this trait is what what allows us to add a bound that the default
/// value must be of the same type as is returned by the parser.
impl<T, U> GetDefault for EnvVar<T, EnvVarDefault<U>>
where
    U: Clone,
{
    type Value = U;

    fn default(&self) -> Self::Value {
        self.default.value.clone()
    }
}

impl<T, U> ParseOrDefault for EnvVar<T, EnvVarDefault<U>>
where
    Self: ParseEnvVarValue,
    Self: ParseBase,
    Self: GetDefault<Value = <Self as ParseEnvVarValue>::Value>,
{
    fn parse_or_default(&self) -> Result<Self::Value, EnvVarError> {
        Ok(self.parse_optional()?.unwrap_or(self.default()))
    }
}

/// A trait indicating that an EnvVar can parse the value of its referenced
/// environment variable.
pub trait ParseEnvVarValue {
    type Value;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarError>;
}

/// Implementation for the FromStr parser, which uses... FromStr.
impl<T, U> ParseEnvVarValue for EnvVar<EnvVarFromStrParser<T>, U>
where
    T: FromStr + 'static,
    T::Err: StdError + Send + Sync + 'static,
{
    type Value = T;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarError> {
        val.parse()
            .map_err(|e| EnvVarError::parse_error::<Self::Value>(self.variable.clone(), val, e))
    }
}

/// Implementation for a custom parser, using that parser.
impl<T, U> ParseEnvVarValue for EnvVar<EnvVarCustomParser<T>, U>
where
    T: EnvVarParser,
{
    type Value = <T as EnvVarParser>::Value;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarError> {
        self.parser
            .0
            .parse(val)
            .map_err(|e| EnvVarError::new(self.variable.clone(), e))
    }
}

/// A trait indicating that a type can parse an environment variable value
/// into some other type.
pub trait EnvVarParser: Sized + 'static {
    type Value;

    /// Parse the value.
    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarErrorKind>;

    /// Convenience constructor
    fn err_invalid_value(val: &str) -> EnvVarErrorKind {
        EnvVarErrorKind::invalid_value::<Self>(val)
    }
}

/// Custom parser for Boolean env vars, allowing 1 and 0 in addition to true and false.
pub struct BoolEnvVarParser;

impl EnvVarParser for BoolEnvVarParser {
    type Value = bool;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarErrorKind> {
        match val.to_lowercase().as_str() {
            "1" | "true" => Ok(true),
            "0" | "false" => Ok(false),
            _ => Err(Self::err_invalid_value(val)),
        }
    }
}

/// Parser for integer Duration env vars, specifying what unit to expect.
#[repr(transparent)]
#[derive(Debug, Copy, Clone)]
pub struct DurationEnvVarParser {
    unit: DurationEnvVarUnit,
}
impl DurationEnvVarParser {
    pub const SECONDS: Self = DurationEnvVarParser::new(DurationEnvVarUnit::Seconds);

    pub const fn new(unit: DurationEnvVarUnit) -> Self {
        Self { unit }
    }
}
impl EnvVarParser for DurationEnvVarParser {
    type Value = Duration;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarErrorKind> {
        // type variable so we can specify it in parse_error() without it going
        // out of sync w/the rest of the funciton
        type T = u64;
        val.parse::<T>()
            .map_err(|e| EnvVarErrorKind::parse_error::<T>(val, e))
            .map(|v| match self.unit {
                DurationEnvVarUnit::Milliseconds => Duration::from_millis(v),
                DurationEnvVarUnit::Seconds => Duration::from_secs(v),
                DurationEnvVarUnit::Days => Duration::from_secs(v.saturating_mul(86400)),
            })
    }
}

#[derive(Debug, Copy, Clone)]
pub struct TimeDeltaEnvVarParser {
    unit: DurationEnvVarUnit,
}
impl TimeDeltaEnvVarParser {
    pub const fn new(unit: DurationEnvVarUnit) -> Self {
        Self { unit }
    }
}
impl EnvVarParser for TimeDeltaEnvVarParser {
    type Value = TimeDelta;

    fn parse(&self, val: &str) -> Result<Self::Value, EnvVarErrorKind> {
        // type variable so we can specify it in parse_error() without it going
        // out of sync w/the rest of the funciton
        type T = i64;
        val.parse::<T>()
            .map_err(|e| EnvVarErrorKind::parse_error::<T>(val, e))
            .map(|v| match self.unit {
                DurationEnvVarUnit::Milliseconds => TimeDelta::milliseconds(v),
                DurationEnvVarUnit::Seconds => TimeDelta::seconds(v),
                DurationEnvVarUnit::Days => TimeDelta::days(v),
            })
    }
}

#[derive(Debug, Copy, Clone)]
pub enum DurationEnvVarUnit {
    Milliseconds,
    Seconds,
    Days,
}

#[derive(Debug, thiserror::Error)]
#[error("env-var error: {var}: {kind}")]
pub struct EnvVarError {
    var: String,
    kind: EnvVarErrorKind,
}
impl EnvVarError {
    pub fn new(var: impl ToString, kind: impl Into<EnvVarErrorKind>) -> Self {
        Self {
            var: var.to_string(),
            kind: kind.into(),
        }
    }

    /// Invalid value errors for manual parsing, that don't have an underlying
    /// error instance.
    ///
    /// If there is an underlying error instance, use `.parse_error()`.
    pub fn invalid_value<T>(var: impl ToString, val: impl ToString) -> Self
    where
        T: Any,
    {
        Self {
            var: var.to_string(),
            kind: EnvVarErrorKind::InvalidValue {
                val: val.to_string(),
                ty: std::any::type_name::<T>(),
            },
        }
    }

    pub fn parse_error<T>(
        var: impl ToString,
        val: impl ToString,
        err: impl StdError + 'static + Send + Sync,
    ) -> Self
    where
        T: Any,
    {
        Self {
            var: var.to_string(),
            kind: EnvVarErrorKind::parse_error::<T>(val, err),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum EnvVarErrorKind {
    #[error("value contained invalid utf-8: {}", .0.err_with_source())]
    InvalidUtf8(#[source] std::env::VarError),
    #[error("invalid value for expected type: {val}, {ty}")]
    InvalidValue { val: String, ty: &'static str },
    #[error("{0}")]
    Other(String),
    #[error("invalid value for expected type: {val}, {ty}: {}", .parse_err.err_with_source())]
    ParseError {
        #[source]
        parse_err: Box<dyn StdError + 'static + Send + Sync>,
        val: String,
        ty: &'static str,
    },
    #[error("variable required but not found")]
    RequiredAbsent,
}
impl EnvVarErrorKind {
    pub fn invalid_value<T>(val: impl ToString) -> Self {
        Self::InvalidValue {
            val: val.to_string(),
            ty: std::any::type_name::<T>(),
        }
    }

    pub fn parse_error<T>(val: impl ToString, err: impl StdError + 'static + Send + Sync) -> Self
    where
        T: Any,
    {
        Self::ParseError {
            parse_err: Box::new(err),
            val: val.to_string(),
            ty: std::any::type_name::<T>(),
        }
    }
}
impl From<std::env::VarError> for EnvVarErrorKind {
    fn from(value: std::env::VarError) -> Self {
        match value {
            env::VarError::NotPresent => Self::RequiredAbsent,
            env::VarError::NotUnicode(..) => Self::InvalidUtf8(value),
        }
    }
}

pub trait ErrStringWithSource {
    fn err_with_source(&self) -> String;
}

impl<E> ErrStringWithSource for E
where
    E: std::error::Error,
    E: ?Sized,
{
    fn err_with_source(&self) -> String {
        format!(
            "{self}{}",
            if let Some(source) = self.source() {
                format!(": {source}")
            } else {
                String::from("")
            }
        )
    }
}