confik 0.15.12

Compose configuration from multiple sources without giving up type safety
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
//! Utilities for manual implementations of [`Configuration`].
//!
//! Where possible, the derive should be prefered, but sometimes a manual implementation is
//! required.

use std::{fmt::Display, marker::PhantomData};

use serde::{de::DeserializeOwned, Deserialize};

use crate::{Configuration, ConfigurationBuilder, Error, MissingValue, UnexpectedSecret};

/// Type alias for easier usage of [`Configuration`] in complex generic statements
pub type BuilderOf<T> = <T as Configuration>::Builder;

/// Type alias for easier usage of [`KeyedContainerBuilder`] and [`UnkeyedContainerBuilder`] in complex generic statements
pub type ItemOf<C> = <C as IntoIterator>::Item;

/// Type alias for easier usage of [`KeyedContainerBuilder`] in complex generic statements
pub type KeyOf<C> = <C as KeyedContainer>::Key;

/// Type alias for easier usage of [`ConfigurationBuilder`] in complex generic statements
pub type TargetOf<B> = <B as ConfigurationBuilder>::Target;

/// Type alias for easier usage of [`KeyedContainerBuilder`] in complex generic statements
pub type ValueOf<C> = <C as KeyedContainer>::Value;

/// Builder type for unkeyed containers such as [`Vec`] (as opposed to keyed containers like
/// [`HashMap`](std::collections::HashMap)).
///
/// This is not required to be used, but is a convient shortcut for unkeyed container types'
/// implementations.
///
/// For keyed containers, see [`KeyedContainerBuilder`].
///
/// Example usage:
/// ```rust
/// use confik::{
///     helpers::{BuilderOf, UnkeyedContainerBuilder},
///     Configuration,
/// };
/// use serde::Deserialize;
///
/// struct MyVec<T> {
///     // ...
/// #   __: Vec<T>,
/// }
///
/// impl<'de, T> Deserialize<'de> for MyVec<T> {
///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
///     where
///         D: serde::Deserializer<'de>,
///     {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<T> Default for MyVec<T> {
///     fn default() -> Self {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<T> IntoIterator for MyVec<T> {
///     type Item = T;
///
///     type IntoIter = // ...
/// #       <Vec<T> as IntoIterator>::IntoIter;
///
///     fn into_iter(self) -> Self::IntoIter {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<'a, T> IntoIterator for &'a MyVec<T> {
///     type Item = &'a T;
///
///     type IntoIter = // ...
/// #       <&'a [T] as IntoIterator>::IntoIter;
///
///     fn into_iter(self) -> Self::IntoIter {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<T> FromIterator<T> for MyVec<T> {
///     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<T> Configuration for MyVec<T>
/// where
///     T: Configuration,
///     BuilderOf<T>: 'static,
/// {
///     type Builder = UnkeyedContainerBuilder<MyVec<BuilderOf<T>>, Self>;
/// }
/// ```
#[derive(Debug, Default, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord)]
#[serde(from = "Container")]
pub enum UnkeyedContainerBuilder<Container, Target> {
    /// No data has been provided yet.
    ///
    /// Default to `None` but allow overwriting by later [`merge`][ConfigurationBuilder::merge]s.
    #[default]
    Unspecified,

    /// Data has been provided.
    ///
    /// Will not be overwritten by later [`merge`][ConfigurationBuilder::merge]s.
    Some(Container),

    /// Never instantiated, used to hold the [`Target`][ConfigurationBuilder::Target] type.
    _PhantomData(PhantomData<fn() -> Target>),
}

impl<Container, Target> From<Container> for UnkeyedContainerBuilder<Container, Target> {
    fn from(value: Container) -> Self {
        Self::Some(value)
    }
}

impl<Container, Target> ConfigurationBuilder for UnkeyedContainerBuilder<Container, Target>
where
    Self: DeserializeOwned,
    Container: IntoIterator + 'static,
    ItemOf<Container>: ConfigurationBuilder,
    Target: Default + FromIterator<TargetOf<ItemOf<Container>>>,
    for<'a> &'a Container: IntoIterator<Item = &'a ItemOf<Container>>,
{
    type Target = Target;

    fn merge(self, other: Self) -> Self {
        if matches!(self, Self::Unspecified) {
            other
        } else {
            self
        }
    }

    fn try_build(self) -> Result<Self::Target, Error> {
        match self {
            Self::Unspecified => Err(Error::MissingValue(MissingValue::default())),
            Self::Some(val) => val
                .into_iter()
                .map(ConfigurationBuilder::try_build)
                .collect(),
            Self::_PhantomData(_) => unreachable!("PhantomData is never instantiated"),
        }
    }

    fn contains_non_secret_data(&self) -> Result<bool, UnexpectedSecret> {
        match self {
            Self::Unspecified => Ok(false),

            // An explicit empty container is counted as as data, overriding any default.
            // If this branch is ever reached, then there is some data, even if it is empty.
            // So always return either an error or `true`.
            Self::Some(val) => val
                .into_iter()
                .map(ConfigurationBuilder::contains_non_secret_data)
                .enumerate()
                .find(|(_index, result)| result.is_err())
                .map(|(index, result)| result.map_err(|err| err.prepend(index.to_string())))
                .unwrap_or(Ok(true)),

            Self::_PhantomData(_) => unreachable!("PhantomData is never instantiated"),
        }
    }
}

/// Trait governing access to keyed containers like [`HashMap`](std::collections::HashMap) (as
/// opposed to unkeyed containers like [`Vec`]).
///
/// This trait purely exists to allow for simple usage of [`KeyedContainerBuilder`]. See the docs
/// there for details.
pub trait KeyedContainer {
    type Key;
    type Value;

    fn insert(&mut self, k: Self::Key, v: Self::Value);
    fn remove(&mut self, k: &Self::Key) -> Option<Self::Value>;
}

/// Builder type for keyed containers, such as [`HashMap`](std::collections::HashMap) (as opposed
/// to unkeyed containers like [`Vec`]). This is not required to be used, but is a convient
/// shortcut for map types' implementations.
///
/// Types using this as their builder must implement [`KeyedContainer`].
///
/// For unkeyed containers, see [`UnkeyedContainerBuilder`].
///
/// Example usage:
/// ```rust
/// use std::fmt::Display;
///
/// use confik::{
///     helpers::{BuilderOf, KeyedContainer, KeyedContainerBuilder},
///     Configuration,
/// };
/// use serde::Deserialize;
///
/// struct MyMap<K, V> {
///     // ...
/// #   __: Vec<(K, V)>,
/// }
///
/// impl<'de, K, V> Deserialize<'de> for MyMap<K, V> {
///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
///     where
///         D: serde::Deserializer<'de>,
///     {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<K, V> Default for MyMap<K, V> {
///     fn default() -> Self {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<K, V> IntoIterator for MyMap<K, V> {
///     type Item = (K, V);
///
///     type IntoIter = // ...
/// #       <Vec<(K, V)> as IntoIterator>::IntoIter;
///
///     fn into_iter(self) -> Self::IntoIter {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<'a, K, V> IntoIterator for &'a MyMap<K, V> {
///     type Item = (&'a K, &'a V);
///
///     type IntoIter = // ...
/// #       <&'a std::collections::HashMap<K, V> as IntoIterator>::IntoIter;
///
///     fn into_iter(self) -> Self::IntoIter {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<K, V> FromIterator<(K, V)> for MyMap<K, V> {
///     fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
///         // ...
/// #        unimplemented!()
///     }
/// }
///
/// impl<K, V> KeyedContainer for MyMap<K, V> {
///     type Key = K;
///
///     type Value = V;
///
///     fn insert(&mut self, k: Self::Key, v: Self::Value) {
///         // ...
/// #        unimplemented!()
///     }
///
///     fn remove(&mut self, k: &Self::Key) -> Option<Self::Value> {
///         // ...
/// #       unimplemented!()
///     }
/// }
///
/// impl<K, V> Configuration for MyMap<K, V>
/// where
///     K: Display + 'static,
///     V: Configuration,
///     BuilderOf<V>: 'static,
/// {
///     type Builder = KeyedContainerBuilder<MyMap<K, BuilderOf<V>>, Self>;
/// }
/// ```
#[derive(Debug, Default, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord)]
#[serde(from = "Container")]
pub enum KeyedContainerBuilder<Container, Target> {
    /// No data has been provided yet.
    ///
    /// Default to `None` but allow overwriting by later [`merge`][ConfigurationBuilder::merge]s.
    #[default]
    Unspecified,

    /// Data has been provided.
    ///
    /// Will not be overwritten by later [`merge`][ConfigurationBuilder::merge]s.
    Some(Container),

    /// Never instantiated, used to hold the [`Target`][ConfigurationBuilder::Target] type.
    _PhantomData(PhantomData<fn() -> Target>),
}

impl<Container, Target> From<Container> for KeyedContainerBuilder<Container, Target> {
    fn from(value: Container) -> Self {
        Self::Some(value)
    }
}

impl<Container, Target> ConfigurationBuilder for KeyedContainerBuilder<Container, Target>
where
    Self: DeserializeOwned,
    Container:
        KeyedContainer + IntoIterator<Item = (KeyOf<Container>, ValueOf<Container>)> + 'static,
    KeyOf<Container>: Display,
    ValueOf<Container>: ConfigurationBuilder + 'static,
    Target: Default + FromIterator<(KeyOf<Container>, TargetOf<ValueOf<Container>>)>,
    for<'a> &'a Container: IntoIterator<Item = (&'a KeyOf<Container>, &'a ValueOf<Container>)>,
{
    type Target = Target;

    fn merge(self, other: Self) -> Self {
        match (self, other) {
            (Self::_PhantomData(_), _) | (_, Self::_PhantomData(_)) => {
                unreachable!("PhantomData is never instantiated")
            }
            (Self::Unspecified, other) => other,
            (us, Self::Unspecified) => us,
            (Self::Some(mut us), Self::Some(other)) => {
                for (key, their_val) in other {
                    let val = if let Some(our_val) = us.remove(&key) {
                        our_val.merge(their_val)
                    } else {
                        their_val
                    };

                    us.insert(key, val);
                }

                Self::Some(us)
            }
        }
    }

    fn try_build(self) -> Result<Self::Target, Error> {
        match self {
            Self::Unspecified => Err(Error::MissingValue(MissingValue::default())),
            Self::Some(val) => val
                .into_iter()
                .map(|(key, value)| Ok((key, value.try_build()?)))
                .collect(),
            Self::_PhantomData(_) => unreachable!("PhantomData is never instantiated"),
        }
    }

    fn contains_non_secret_data(&self) -> Result<bool, UnexpectedSecret> {
        match self {
            Self::Unspecified => Ok(false),

            // An explicit empty container is counted as as data, overriding any default.
            // If this branch is ever reached, then there is some data, even if it is empty.
            // So always return either an error or `true`.
            Self::Some(val) => val
                .into_iter()
                .map(|(key, value)| (key, value.contains_non_secret_data()))
                .find(|(_key, result)| result.is_err())
                .map(|(key, result)| result.map_err(|err| err.prepend(key.to_string())))
                .unwrap_or(Ok(true)),

            Self::_PhantomData(_) => unreachable!("PhantomData is never instantiated"),
        }
    }
}

/// Implementation helper for building a type that supports merging in itself, but needs to represent unset.
///
/// See [`MergingWithUnset`] for more info.
#[derive(Debug, Default, Clone)]
pub enum MergingUnsetBuilder<T> {
    #[default]
    Unset,
    Set(T),
}

impl<'de, T> Deserialize<'de> for MergingUnsetBuilder<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        T::deserialize(deserializer).map(Self::Set)
    }
}

/// A helper trait for building [`Configuration`], with automated handling of unset merges and builds.
///
/// This trait duplicated the definitions of [Configuration], any set value(s) delegate to these functions, with unset values being handled by [`MergingUnsetBuilder`] itself.
///
/// For an example `AdditiveMerge` type, you would otherwise need to have a custom builder with `Option<usize>` inside, and then handle the `Option` yourself. This trait allows that to be delegated to [`MergingUnsetBuilder`].
/// ```
/// use confik::{
///     helpers::{MergingUnsetBuilder, MergingWithUnset},
///     Configuration, Error, UnexpectedSecret,
/// };
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct AdditiveMerge(usize);
///
/// impl Configuration for AdditiveMerge {
///     type Builder = MergingUnsetBuilder<Self>;
/// }
///
/// impl MergingWithUnset for AdditiveMerge {
///     type Target = Self;
///
///     fn merge(self, other: Self) -> Self {
///         Self(self.0 + other.0)
///     }
///
///     fn try_build(self) -> Result<Self::Target, Error> {
///         Ok(self)
///     }
///
///     fn contains_non_secret_data(&self) -> Result<bool, UnexpectedSecret> {
///         Ok(true)
///     }
/// }
/// ```
pub trait MergingWithUnset {
    type Target;

    fn merge(self, other: Self) -> Self;
    fn try_build(self) -> Result<Self::Target, Error>;
    fn contains_non_secret_data(&self) -> Result<bool, UnexpectedSecret>;
}

impl<T> ConfigurationBuilder for MergingUnsetBuilder<T>
where
    T: MergingWithUnset + DeserializeOwned,
{
    type Target = T::Target;

    fn merge(self, other: Self) -> Self {
        match (self, other) {
            (Self::Unset, merged) | (merged, Self::Unset) => merged,
            (Self::Set(s), Self::Set(o)) => Self::Set(s.merge(o)),
        }
    }

    fn try_build(self) -> Result<Self::Target, Error> {
        match self {
            Self::Unset => Err(Error::MissingValue(MissingValue::default())),
            Self::Set(s) => s.try_build(),
        }
    }

    fn contains_non_secret_data(&self) -> Result<bool, UnexpectedSecret> {
        match self {
            Self::Unset => Ok(false),
            Self::Set(s) => s.contains_non_secret_data(),
        }
    }
}