tier 0.1.14

Rust configuration library for layered TOML, env, and CLI settings
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
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::{self, Display, Formatter};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crate::ConfigError;
use crate::error::ValidationError;
use crate::loader::SourceKind;
use crate::report::{canonicalize_path_with_aliases, normalize_path, path_matches_pattern};

mod config;
mod field;
mod paths;
mod prefix;
mod validation;

use self::paths::*;
pub use self::prefix::prefixed_metadata;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Structured metadata describing configuration fields.
///
/// `ConfigMetadata` is the manual metadata API behind `tier`'s higher-level
/// derive support. It can describe:
///
/// - field-level behavior such as env names, aliases, secret paths, examples,
///   merge policies, and declared validation rules
/// - cross-field validation checks such as mutually exclusive or required-if
///   relationships
///
/// # Examples
///
/// ```
/// use tier::{ConfigMetadata, FieldMetadata};
///
/// let metadata = ConfigMetadata::from_fields([
///     FieldMetadata::new("db.url").env("DATABASE_URL"),
///     FieldMetadata::new("db.password").secret(),
/// ])
/// .required_with("tls.enabled", ["tls.cert", "tls.key"]);
///
/// assert_eq!(
///     metadata
///         .env_overrides()
///         .expect("valid metadata")
///         .get("DATABASE_URL")
///         .map(String::as_str),
///     Some("db.url")
/// );
/// assert_eq!(metadata.secret_paths(), vec!["db.password".to_owned()]);
/// assert_eq!(metadata.checks().len(), 1);
/// ```
pub struct ConfigMetadata {
    fields: Vec<FieldMetadata>,
    checks: Vec<ValidationCheck>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MetadataMatchScore {
    segment_count: usize,
    specificity: usize,
    positional_specificity: Vec<bool>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Metadata for a single configuration path.
pub struct FieldMetadata {
    /// Dot-delimited configuration path.
    pub path: String,
    /// Alternate dot-delimited paths accepted by serde during deserialization.
    pub aliases: Vec<String>,
    /// Whether values at this path should be treated as sensitive.
    pub secret: bool,
    /// Exact environment variable name to map to this path.
    pub env: Option<String>,
    /// Decoder applied to environment variable values before deserialization.
    pub env_decode: Option<EnvDecoder>,
    /// Human-readable field documentation.
    pub doc: Option<String>,
    /// Example value rendered in generated docs.
    pub example: Option<String>,
    /// Deprecation note shown in generated docs and runtime warnings.
    pub deprecated: Option<String>,
    /// Whether the field accepts omission via `serde(default)`.
    pub has_default: bool,
    /// Strategy used when merging layered values into this field.
    pub merge: MergeStrategy,
    /// Whether the merge strategy was explicitly declared for this field.
    pub merge_explicit: bool,
    /// Source kinds allowed to override this field.
    ///
    /// When unset, the field accepts values from any source kind.
    pub allowed_sources: Option<BTreeSet<SourceKind>>,
    /// Source kinds explicitly denied from overriding this field.
    ///
    /// When unset, the field does not deny any source kinds.
    pub denied_sources: Option<BTreeSet<SourceKind>>,
    /// Declarative validation rules applied after normalization.
    pub validations: Vec<ValidationRule>,
    /// Per-rule configuration such as custom messages, warning levels, and tags.
    pub validation_configs: BTreeMap<String, ValidationRuleConfig>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct EffectiveSourcePolicy {
    pub(crate) allowed_sources: Option<BTreeSet<SourceKind>>,
    pub(crate) denied_sources: Option<BTreeSet<SourceKind>>,
}

pub(crate) struct EffectiveValidation {
    pub(crate) field: FieldMetadata,
    pub(crate) rule: ValidationRule,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Built-in decoders for structured environment variable values.
///
/// These decoders are intended for operational formats that are common in
/// deployments but inconvenient to express as JSON.
///
/// # Examples
///
/// ```
/// use tier::{ConfigMetadata, EnvDecoder, FieldMetadata};
///
/// let mut metadata = ConfigMetadata::new();
/// metadata.push(FieldMetadata::new("no_proxy").env_decoder(EnvDecoder::Csv));
/// metadata.push(FieldMetadata::new("labels").env_decoder(EnvDecoder::KeyValueMap));
///
/// assert_eq!(metadata.fields().len(), 2);
/// ```
pub enum EnvDecoder {
    /// Comma-separated values such as `a,b,c`.
    Csv,
    /// Platform-native path list syntax such as `PATH`.
    PathList,
    /// Comma-separated `key=value` pairs such as `a=1,b=2`.
    KeyValueMap,
    /// Whitespace-separated values such as `a b c`.
    Whitespace,
}

impl Display for EnvDecoder {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Csv => write!(f, "csv"),
            Self::PathList => write!(f, "path_list"),
            Self::KeyValueMap => write!(f, "key_value_map"),
            Self::Whitespace => write!(f, "whitespace"),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Strategy applied when multiple layers write to the same configuration path.
pub enum MergeStrategy {
    /// Recursively merge objects and replace non-object values.
    #[default]
    Merge,
    /// Replace the current value at this path with the overlay value.
    Replace,
    /// Append array overlays while still recursively merging nested objects.
    Append,
}

#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
/// Runtime severity applied to a declarative validation rule.
pub enum ValidationLevel {
    /// Reject the configuration when the rule fails.
    #[default]
    Error,
    /// Record a warning and continue loading when the rule fails.
    Warning,
}

impl Display for ValidationLevel {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Error => write!(f, "error"),
            Self::Warning => write!(f, "warning"),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Additional configuration attached to a declarative validation rule.
pub struct ValidationRuleConfig {
    /// Runtime severity for the rule.
    pub level: ValidationLevel,
    /// Optional custom message shown when the rule fails.
    pub message: Option<String>,
    /// Optional machine-readable tags for downstream consumers.
    pub tags: Vec<String>,
}

impl Display for MergeStrategy {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Merge => write!(f, "merge"),
            Self::Replace => write!(f, "replace"),
            Self::Append => write!(f, "append"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
/// Numeric bound used by declarative validation rules.
pub enum ValidationNumber {
    /// A finite JSON-compatible number.
    Finite(serde_json::Number),
    /// An invalid non-finite value such as `NaN` or `inf`.
    Invalid(String),
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
/// Scalar value used by declarative validation rules and conditions.
pub struct ValidationValue(pub serde_json::Value);

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Declarative validation rule applied to a single configuration path.
pub enum ValidationRule {
    /// The field must not be empty.
    NonEmpty,
    /// The field must be greater than or equal to the given numeric bound.
    Min(ValidationNumber),
    /// The field must be less than or equal to the given numeric bound.
    Max(ValidationNumber),
    /// The field length must be at least the given number of units.
    MinLength(usize),
    /// The field length must be at most the given number of units.
    MaxLength(usize),
    /// The field must be an array with at least the given number of items.
    MinItems(usize),
    /// The field must be an array with at most the given number of items.
    MaxItems(usize),
    /// The field must be an object with at least the given number of properties.
    MinProperties(usize),
    /// The field must be an object with at most the given number of properties.
    MaxProperties(usize),
    /// The field must be a numeric multiple of the given factor.
    MultipleOf(ValidationNumber),
    /// The field must match the given regular expression.
    Pattern(String),
    /// The field must be an array whose items are unique.
    UniqueItems,
    /// The field must equal one of the provided scalar values.
    OneOf(Vec<ValidationValue>),
    /// The field must be a valid hostname.
    Hostname,
    /// The field must be a valid absolute URL string.
    Url,
    /// The field must be a valid email address.
    Email,
    /// The field must be a valid IP address.
    IpAddr,
    /// The field must be a valid socket address.
    SocketAddr,
    /// The field must be an absolute filesystem path.
    AbsolutePath,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Cross-field declarative validation applied to the final normalized configuration.
pub enum ValidationCheck {
    /// Requires that at least one of the given paths is configured.
    AtLeastOneOf { paths: Vec<String> },
    /// Requires that exactly one of the given paths is configured.
    ExactlyOneOf { paths: Vec<String> },
    /// Requires that no more than one of the given paths is configured.
    MutuallyExclusive { paths: Vec<String> },
    /// Requires one or more paths whenever `path` is configured.
    RequiredWith { path: String, requires: Vec<String> },
    /// Requires one or more paths whenever `path` equals `equals`.
    RequiredIf {
        /// Path whose value is inspected.
        path: String,
        /// Value that triggers the requirement.
        equals: ValidationValue,
        /// Paths that must be configured when the condition matches.
        requires: Vec<String>,
    },
}

/// Metadata produced for a configuration type.
pub trait TierMetadata {
    /// Returns metadata for the configuration type.
    #[must_use]
    fn metadata() -> ConfigMetadata {
        ConfigMetadata::default()
    }

    /// Returns configuration paths that should be treated as secrets.
    #[must_use]
    fn secret_paths() -> Vec<String> {
        Self::metadata().secret_paths()
    }
}

impl<T> TierMetadata for super::Secret<T> {
    fn metadata() -> ConfigMetadata {
        ConfigMetadata::from_fields([FieldMetadata::new("").secret()])
    }
}
impl TierMetadata for String {}
impl TierMetadata for bool {}
impl TierMetadata for char {}
impl TierMetadata for u8 {}
impl TierMetadata for u16 {}
impl TierMetadata for u32 {}
impl TierMetadata for u64 {}
impl TierMetadata for u128 {}
impl TierMetadata for usize {}
impl TierMetadata for i8 {}
impl TierMetadata for i16 {}
impl TierMetadata for i32 {}
impl TierMetadata for i64 {}
impl TierMetadata for i128 {}
impl TierMetadata for isize {}
impl TierMetadata for f32 {}
impl TierMetadata for f64 {}
impl TierMetadata for Duration {}
impl TierMetadata for SystemTime {}
impl TierMetadata for PathBuf {}
impl TierMetadata for IpAddr {}
impl TierMetadata for Ipv4Addr {}
impl TierMetadata for Ipv6Addr {}
impl TierMetadata for SocketAddr {}
impl TierMetadata for SocketAddrV4 {}
impl TierMetadata for SocketAddrV6 {}

impl<T> TierMetadata for Option<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

impl<T> TierMetadata for Vec<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T, const N: usize> TierMetadata for [T; N]
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T> TierMetadata for BTreeSet<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T> TierMetadata for HashSet<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<K, V> TierMetadata for BTreeMap<K, V>
where
    V: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), V::metadata())
    }
}

impl<K, V, S> TierMetadata for HashMap<K, V, S>
where
    V: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), V::metadata())
    }
}

impl<T> TierMetadata for Box<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

impl<T> TierMetadata for Arc<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

impl IntoIterator for ConfigMetadata {
    type Item = FieldMetadata;
    type IntoIter = std::vec::IntoIter<FieldMetadata>;

    fn into_iter(self) -> Self::IntoIter {
        self.fields.into_iter()
    }
}