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
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
use super::*;
#[cfg(feature = "schema")]
use serde_json::Value;

#[cfg(feature = "schema")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct FieldValidationExport {
    pub(crate) levels: std::collections::BTreeMap<String, ValidationLevel>,
    pub(crate) messages: std::collections::BTreeMap<String, String>,
    pub(crate) tags: std::collections::BTreeMap<String, Vec<String>>,
}

impl FieldMetadata {
    /// Creates metadata for a single configuration path.
    #[must_use]
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: normalize_metadata_path(&path.into()),
            aliases: Vec::new(),
            secret: false,
            env: None,
            env_decode: None,
            doc: None,
            example: None,
            deprecated: None,
            has_default: false,
            merge: MergeStrategy::Merge,
            merge_explicit: false,
            allowed_sources: None,
            denied_sources: None,
            validations: Vec::new(),
            validation_configs: BTreeMap::new(),
        }
    }

    /// Adds an alternate serde path for this field.
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Marks this path as sensitive.
    #[must_use]
    pub fn secret(mut self) -> Self {
        self.secret = true;
        self
    }

    /// Overrides the environment variable name for this path.
    #[must_use]
    pub fn env(mut self, env: impl Into<String>) -> Self {
        self.env = Some(env.into());
        self
    }

    /// Decodes environment variables for this path with a built-in decoder.
    ///
    /// This can be used together with [`ConfigMetadata`] when metadata is
    /// built manually instead of derived.
    #[must_use]
    pub fn env_decoder(mut self, decoder: EnvDecoder) -> Self {
        self.env_decode = Some(decoder);
        self
    }

    /// Adds human-readable field documentation.
    #[must_use]
    pub fn doc(mut self, doc: impl Into<String>) -> Self {
        self.doc = Some(doc.into());
        self
    }

    /// Adds an example value used by generated docs.
    #[must_use]
    pub fn example(mut self, example: impl Into<String>) -> Self {
        self.example = Some(example.into());
        self
    }

    /// Marks the field as deprecated with an optional note.
    #[must_use]
    pub fn deprecated(mut self, note: impl Into<String>) -> Self {
        self.deprecated = Some(note.into());
        self
    }

    /// Marks the field as accepting omission via `serde(default)`.
    #[must_use]
    pub fn defaulted(mut self) -> Self {
        self.has_default = true;
        self
    }

    /// Sets the field-level merge strategy.
    #[must_use]
    pub fn merge_strategy(mut self, merge: MergeStrategy) -> Self {
        self.merge = merge;
        self.merge_explicit = true;
        self
    }

    /// Restricts the field to a specific set of source kinds.
    ///
    /// This is useful for fields that should only be loaded from selected
    /// layers, such as requiring secrets to come from environment variables or
    /// disallowing file-based overrides for a path.
    #[must_use]
    pub fn allow_sources<I>(mut self, sources: I) -> Self
    where
        I: IntoIterator<Item = SourceKind>,
    {
        self.allowed_sources = Some(sources.into_iter().collect());
        self
    }

    /// Explicitly denies a set of source kinds from overriding this field.
    #[must_use]
    pub fn deny_sources<I>(mut self, sources: I) -> Self
    where
        I: IntoIterator<Item = SourceKind>,
    {
        self.denied_sources = Some(sources.into_iter().collect());
        self
    }

    /// Appends a declarative validation rule.
    #[must_use]
    pub fn validate(mut self, rule: ValidationRule) -> Self {
        self.upsert_validation(rule);
        self
    }

    /// Overrides the human-readable message for a validation rule.
    #[must_use]
    pub fn validation_message(
        mut self,
        rule_code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        self.validation_configs
            .entry(rule_code.into())
            .or_default()
            .message = Some(message.into());
        self
    }

    /// Sets the runtime level for a validation rule.
    #[must_use]
    pub fn validation_level(
        mut self,
        rule_code: impl Into<String>,
        level: ValidationLevel,
    ) -> Self {
        self.validation_configs
            .entry(rule_code.into())
            .or_default()
            .level = level;
        self
    }

    /// Attaches machine-readable tags to a validation rule.
    #[must_use]
    pub fn validation_tags<I, S>(mut self, rule_code: impl Into<String>, tags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.validation_configs
            .entry(rule_code.into())
            .or_default()
            .tags = tags.into_iter().map(Into::into).collect();
        self
    }

    /// Requires the field to be non-empty.
    #[must_use]
    pub fn non_empty(self) -> Self {
        self.validate(ValidationRule::NonEmpty)
    }

    /// Requires the field to be greater than or equal to `min`.
    #[must_use]
    pub fn min(self, min: impl Into<ValidationNumber>) -> Self {
        self.validate(ValidationRule::Min(min.into()))
    }

    /// Requires the field to be less than or equal to `max`.
    #[must_use]
    pub fn max(self, max: impl Into<ValidationNumber>) -> Self {
        self.validate(ValidationRule::Max(max.into()))
    }

    /// Requires the field length to be greater than or equal to `min`.
    #[must_use]
    pub fn min_length(self, min: usize) -> Self {
        self.validate(ValidationRule::MinLength(min))
    }

    /// Requires the field length to be less than or equal to `max`.
    #[must_use]
    pub fn max_length(self, max: usize) -> Self {
        self.validate(ValidationRule::MaxLength(max))
    }

    /// Requires the field to be an array with at least `min` items.
    #[must_use]
    pub fn min_items(self, min: usize) -> Self {
        self.validate(ValidationRule::MinItems(min))
    }

    /// Requires the field to be an array with at most `max` items.
    #[must_use]
    pub fn max_items(self, max: usize) -> Self {
        self.validate(ValidationRule::MaxItems(max))
    }

    /// Requires the field to be an object with at least `min` properties.
    #[must_use]
    pub fn min_properties(self, min: usize) -> Self {
        self.validate(ValidationRule::MinProperties(min))
    }

    /// Requires the field to be an object with at most `max` properties.
    #[must_use]
    pub fn max_properties(self, max: usize) -> Self {
        self.validate(ValidationRule::MaxProperties(max))
    }

    /// Requires the field to be an exact multiple of `factor`.
    #[must_use]
    pub fn multiple_of(self, factor: impl Into<ValidationNumber>) -> Self {
        self.validate(ValidationRule::MultipleOf(factor.into()))
    }

    /// Requires the field to match a regular expression.
    #[must_use]
    pub fn pattern(self, pattern: impl Into<String>) -> Self {
        self.validate(ValidationRule::Pattern(pattern.into()))
    }

    /// Requires the field to be an array with unique items.
    #[must_use]
    pub fn unique_items(self) -> Self {
        self.validate(ValidationRule::UniqueItems)
    }

    /// Requires the field to match one of the provided scalar values.
    #[must_use]
    pub fn one_of<I, V>(self, values: I) -> Self
    where
        I: IntoIterator<Item = V>,
        V: Into<ValidationValue>,
    {
        self.validate(ValidationRule::OneOf(
            values.into_iter().map(Into::into).collect(),
        ))
    }

    /// Requires the field to be a valid hostname.
    #[must_use]
    pub fn hostname(self) -> Self {
        self.validate(ValidationRule::Hostname)
    }

    /// Requires the field to be a valid absolute URL string.
    #[must_use]
    pub fn url(self) -> Self {
        self.validate(ValidationRule::Url)
    }

    /// Requires the field to be a valid email address.
    #[must_use]
    pub fn email(self) -> Self {
        self.validate(ValidationRule::Email)
    }

    /// Requires the field to be a valid IP address.
    #[must_use]
    pub fn ip_addr(self) -> Self {
        self.validate(ValidationRule::IpAddr)
    }

    /// Requires the field to be a valid socket address.
    #[must_use]
    pub fn socket_addr(self) -> Self {
        self.validate(ValidationRule::SocketAddr)
    }

    /// Requires the field to be an absolute filesystem path.
    #[must_use]
    pub fn absolute_path(self) -> Self {
        self.validate(ValidationRule::AbsolutePath)
    }

    #[cfg(feature = "schema")]
    pub(crate) fn allowed_source_names(&self) -> Vec<String> {
        self.allowed_sources
            .as_ref()
            .map(|allowed_sources| allowed_sources.iter().copied().collect::<Vec<_>>())
            .unwrap_or_default()
            .into_iter()
            .map(|source| source.to_string())
            .collect()
    }

    #[cfg(feature = "schema")]
    pub(crate) fn denied_source_names(&self) -> Vec<String> {
        self.denied_sources
            .as_ref()
            .map(|denied_sources| denied_sources.iter().copied().collect::<Vec<_>>())
            .unwrap_or_default()
            .into_iter()
            .map(|source| source.to_string())
            .collect()
    }

    pub(crate) fn validation_config_for(
        &self,
        rule: &ValidationRule,
    ) -> Option<&ValidationRuleConfig> {
        self.validation_configs.get(rule.code())
    }

    pub(crate) fn validation_level_for(&self, rule: &ValidationRule) -> ValidationLevel {
        self.validation_config_for(rule)
            .map(|config| config.level)
            .unwrap_or(ValidationLevel::Error)
    }

    #[cfg(feature = "schema")]
    pub(crate) fn validation_export(&self) -> FieldValidationExport {
        let mut export = FieldValidationExport::default();
        for (rule_code, config) in &self.validation_configs {
            export.levels.insert(rule_code.clone(), config.level);
            if let Some(message) = &config.message {
                export.messages.insert(rule_code.clone(), message.clone());
            }
            if !config.tags.is_empty() {
                export.tags.insert(rule_code.clone(), config.tags.clone());
            }
        }
        export
    }

    #[cfg(feature = "schema")]
    pub(crate) fn validation_config_json(&self) -> Option<Value> {
        if self.validation_configs.is_empty() {
            None
        } else {
            Some(
                serde_json::to_value(&self.validation_configs)
                    .unwrap_or_else(|_| Value::Object(Default::default())),
            )
        }
    }

    pub(crate) fn decorate_validation_error(
        &self,
        rule: &ValidationRule,
        mut error: ValidationError,
    ) -> ValidationError {
        if let Some(config) = self.validation_config_for(rule) {
            if let Some(message) = &config.message {
                error.message = message.clone();
            }
            if !config.tags.is_empty() {
                error = error.with_tags(config.tags.clone());
            }
        }
        error
    }

    pub(super) fn merge_from(&mut self, other: Self) {
        self.aliases.extend(other.aliases);
        self.aliases.sort();
        self.aliases.dedup();
        self.secret |= other.secret;
        if let Some(env) = other.env {
            self.env = Some(env);
        }
        if let Some(env_decode) = other.env_decode {
            self.env_decode = Some(env_decode);
        }
        if let Some(doc) = other.doc {
            self.doc = Some(doc);
        }
        if let Some(example) = other.example {
            self.example = Some(example);
        }
        if let Some(deprecated) = other.deprecated {
            self.deprecated = Some(deprecated);
        }
        self.has_default |= other.has_default;
        if other.merge_explicit {
            self.merge = other.merge;
            self.merge_explicit = true;
        }
        if let Some(allowed_sources) = other.allowed_sources {
            self.allowed_sources = Some(allowed_sources);
        }
        if let Some(denied_sources) = other.denied_sources {
            self.denied_sources = Some(denied_sources);
        }
        for rule in other.validations {
            self.upsert_validation(rule);
        }
        for (rule_code, config) in other.validation_configs {
            self.validation_configs.insert(rule_code, config);
        }
    }

    fn upsert_validation(&mut self, rule: ValidationRule) {
        if let Some(existing) = self
            .validations
            .iter_mut()
            .find(|existing| existing.code() == rule.code())
        {
            *existing = rule;
        } else {
            self.validations.push(rule);
        }
    }

    pub(super) fn is_env_decoder_only(&self) -> bool {
        self.env_decode.is_some()
            && self.aliases.is_empty()
            && !self.secret
            && self.env.is_none()
            && self.doc.is_none()
            && self.example.is_none()
            && self.deprecated.is_none()
            && !self.has_default
            && !self.merge_explicit
            && self.allowed_sources.is_none()
            && self.denied_sources.is_none()
            && self.validations.is_empty()
            && self.validation_configs.is_empty()
    }
}

impl EffectiveSourcePolicy {
    pub(crate) fn apply_field(&mut self, field: &FieldMetadata) {
        if let Some(allowed_sources) = &field.allowed_sources {
            self.allowed_sources = Some(allowed_sources.clone());
        }
        if let Some(denied_sources) = &field.denied_sources {
            self.denied_sources = Some(denied_sources.clone());
        }
    }

    pub(crate) fn source_kind_allowed(&self, kind: SourceKind) -> bool {
        self.allowed_sources
            .as_ref()
            .is_none_or(|allowed_sources| allowed_sources.contains(&kind))
    }

    pub(crate) fn source_kind_denied(&self, kind: SourceKind) -> bool {
        self.denied_sources
            .as_ref()
            .is_some_and(|denied_sources| denied_sources.contains(&kind))
    }

    pub(crate) fn allowed_sources_vec(&self) -> Vec<SourceKind> {
        self.allowed_sources
            .as_ref()
            .map(|allowed_sources| allowed_sources.iter().copied().collect())
            .unwrap_or_default()
    }

    pub(crate) fn denied_sources_vec(&self) -> Vec<SourceKind> {
        self.denied_sources
            .as_ref()
            .map(|denied_sources| denied_sources.iter().copied().collect())
            .unwrap_or_default()
    }
}