tanzim 0.5.0

Configuration pipeline facade (load, parse, merge)
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
#![doc = include_str!("../README.md")]
#![doc(test(no_crate_inject))]

//! # tanzim
//!
//! Load, parse, and merge configuration from declarative configuration sources.
//!
//! Workspace crates:
//!
//! - [`source`] — [`tanzim_source`] ([`tanzim_source::Source`])
//! - [`loader`] — [`tanzim_load`] ([`tanzim_load::Load`])
//! - [`parser`] — [`tanzim_parse`] ([`tanzim_parse::Deserialize`])
//! - [`merge`] — [`tanzim_merge`] ([`tanzim_merge::Merge`])

pub use tanzim_load as loader;
pub use tanzim_merge as merge;
pub use tanzim_parse as parser;
pub use tanzim_source as source;

#[doc(inline)]
pub use tanzim_source::Source;

pub mod ext {
    //! Re-exported dependency crates.

    pub extern crate tanzim_load;
    pub extern crate tanzim_merge;
    pub extern crate tanzim_parse;
    pub extern crate tanzim_source;
}

mod logging;

use cfg_if::cfg_if;

/// A loaded payload paired with the value tree produced by parsing it.
pub type Parsed = (loader::Payload, parser::LocatedValue);

/// Merged configuration keyed by entry name.
///
/// Identical to [`merge::Merged`]; re-aliased here for the facade's public API.
pub type Merged = merge::Merged;

fn source_display(cs: &Source) -> String {
    let mut s = cs.source().to_string();
    if cs.skip_errors() {
        s.push('?');
    }
    if cs.resource_colon() || !cs.resource().is_empty() {
        s.push(':');
        s.push_str(cs.resource());
    }
    s
}

/// Errors produced by [`Config`] and [`ConfigBuilder`].
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Source(source::ParseError),
    #[error(transparent)]
    Load(loader::Error),
    #[error(transparent)]
    Parse(tanzim_value::Error),
    #[error(transparent)]
    Merge(merge::Error),
    #[error("no loader found for `{at}`")]
    NoLoader { at: String },
    #[error("no parser found for format `{format}` in `{at}`")]
    NoParser { format: String, at: String },
}

/// Builds a [`Config`] with a fluent API.
///
/// The default merger is [`merge::LastWins`].
pub struct ConfigBuilder {
    sources: Vec<Source>,
    loaders: Vec<Box<dyn loader::Load>>,
    parsers: Vec<Box<dyn parser::Deserialize>>,
    merger: Box<dyn merge::Merge>,
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self {
            sources: Vec::new(),
            loaders: Vec::new(),
            parsers: Vec::new(),
            merger: Box::new(merge::LastWins),
        }
    }
}

impl ConfigBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_source<S>(mut self, source: S) -> Result<Self, Error>
    where
        S: TryInto<Source, Error = source::ParseError>,
    {
        match source.try_into() {
            Ok(src) => {
                self.sources.push(src);
                Ok(self)
            }
            Err(e) => Err(Error::Source(e)),
        }
    }

    pub fn with_loader(mut self, loader: impl loader::Load + 'static) -> Self {
        self.loaders.push(Box::new(loader));
        self
    }

    pub fn with_parser(mut self, parser: impl parser::Deserialize + 'static) -> Self {
        self.parsers.push(Box::new(parser));
        self
    }

    pub fn with_merger(mut self, merger: impl merge::Merge + 'static) -> Self {
        self.merger = Box::new(merger);
        self
    }

    pub fn build(self) -> Config {
        Config {
            sources: self.sources,
            loaders: self.loaders,
            parsers: self.parsers,
            merger: self.merger,
        }
    }
}

/// Runs the load → parse → merge pipeline for configuration.
///
/// Construct via [`ConfigBuilder`] or add/modify components with the `with_*` setters.
pub struct Config {
    sources: Vec<Source>,
    loaders: Vec<Box<dyn loader::Load>>,
    parsers: Vec<Box<dyn parser::Deserialize>>,
    merger: Box<dyn merge::Merge>,
}

impl Config {
    // ── Getters ──────────────────────────────────────────────────────────────

    pub fn sources(&self) -> &[Source] {
        &self.sources
    }

    pub fn sources_mut(&mut self) -> &mut Vec<Source> {
        &mut self.sources
    }

    pub fn loaders(&self) -> &[Box<dyn loader::Load>] {
        &self.loaders
    }

    pub fn loaders_mut(&mut self) -> &mut Vec<Box<dyn loader::Load>> {
        &mut self.loaders
    }

    pub fn parsers(&self) -> &[Box<dyn parser::Deserialize>] {
        &self.parsers
    }

    pub fn parsers_mut(&mut self) -> &mut Vec<Box<dyn parser::Deserialize>> {
        &mut self.parsers
    }

    pub fn merger(&self) -> &dyn merge::Merge {
        &*self.merger
    }

    pub fn merger_mut(&mut self) -> &mut Box<dyn merge::Merge> {
        &mut self.merger
    }

    // ── Setters (return Self) ─────────────────────────────────────────────────

    pub fn with_source<S>(mut self, source: S) -> Result<Self, Error>
    where
        S: TryInto<Source, Error = source::ParseError>,
    {
        match source.try_into() {
            Ok(src) => {
                self.sources.push(src);
                Ok(self)
            }
            Err(e) => Err(Error::Source(e)),
        }
    }

    pub fn with_loader(mut self, loader: impl loader::Load + 'static) -> Self {
        self.loaders.push(Box::new(loader));
        self
    }

    pub fn with_parser(mut self, parser: impl parser::Deserialize + 'static) -> Self {
        self.parsers.push(Box::new(parser));
        self
    }

    pub fn with_merger(mut self, merger: impl merge::Merge + 'static) -> Self {
        self.merger = Box::new(merger);
        self
    }

    // ── Pipeline ──────────────────────────────────────────────────────────────

    /// Load raw bytes from all sources using the registered loaders.
    ///
    /// Sources with `skip_errors` set swallow load failures silently.
    pub fn load(&self) -> Result<Vec<loader::Payload>, Error> {
        let mut result = Vec::new();
        for config_source in &self.sources {
            let source_name = config_source.source();
            cfg_if! {
                if #[cfg(feature = "tracing")] {
                    tracing::debug!(msg = "Loading configuration source", source = source_name, resource = config_source.resource());
                } else if #[cfg(feature = "logging")] {
                    log::debug!("msg=\"Loading configuration source\" source={source_name} resource={}", config_source.resource());
                }
            }
            let mut found_loader = None;
            for loader in &self.loaders {
                let supported = loader.supported_source_list();
                let mut matches = false;
                for s in &supported {
                    if s.as_str() == source_name {
                        matches = true;
                        break;
                    }
                }
                if matches {
                    found_loader = Some(loader);
                    break;
                }
            }
            let loader = match found_loader {
                Some(l) => l,
                None => {
                    return Err(Error::NoLoader {
                        at: source_display(config_source),
                    });
                }
            };
            cfg_if! {
                if #[cfg(feature = "tracing")] {
                    tracing::trace!(msg = "Found loader for configuration source", loader = loader.name(), source = source_name);
                } else if #[cfg(feature = "logging")] {
                    log::trace!("msg=\"Found loader for configuration source\" loader={} source={source_name}", loader.name());
                }
            }
            let payloads = match loader.load(config_source.clone()) {
                Ok(payloads) => payloads,
                Err(e) => {
                    if config_source.skip_errors() {
                        cfg_if! {
                            if #[cfg(feature = "tracing")] {
                                tracing::warn!(msg = "Skipped load error for source", source = source_display(config_source), error = ?e);
                            } else if #[cfg(feature = "logging")] {
                                let display = source_display(config_source);
                                log::warn!("msg=\"Skipped load error for source\" source={display} error={e:?}");
                            }
                        }
                        continue;
                    }
                    return Err(Error::Load(e));
                }
            };
            for payload in payloads {
                result.push(payload.normalize());
            }
        }
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Configuration load stage complete", payload_count = result.len());
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Configuration load stage complete\" payload_count={}", result.len());
            }
        }
        Ok(result)
    }

    /// Deserialize loaded bytes into [`parser::LocatedValue`] trees.
    ///
    /// Parser selection: if `payload.format` is set, the first parser that lists that
    /// format wins; otherwise parsers are probed via `is_format_supported`. Sources
    /// with `skip_errors` skip payloads that fail to parse.
    pub fn parse(&self, loaded: &[loader::Payload]) -> Result<Vec<Parsed>, Error> {
        let mut result = Vec::new();
        for payload in loaded {
            let config_source = &payload.source;
            let resource = match (&payload.name, &payload.format) {
                (Some(name), Some(format)) => format!("{name}.{format}"),
                _ => {
                    let r = config_source.resource();
                    if r.is_empty() {
                        config_source.to_string()
                    } else {
                        r.to_string()
                    }
                }
            };
            let source_name = config_source.source();
            cfg_if! {
                if #[cfg(feature = "tracing")] {
                    tracing::debug!(msg = "Parsing configuration payload", source = source_name, resource = resource, format = payload.format.as_deref().unwrap_or("auto"));
                } else if #[cfg(feature = "logging")] {
                    let fmt = payload.format.as_deref().unwrap_or("auto");
                    log::debug!("msg=\"Parsing configuration payload\" source={source_name} resource={resource} format={fmt}");
                }
            }
            let mut found_parser = None;
            if let Some(format) = &payload.format {
                for parser in &self.parsers {
                    let supported = parser.supported_format_list();
                    let mut matches = false;
                    for s in &supported {
                        if s.as_str() == format.as_str() {
                            matches = true;
                            break;
                        }
                    }
                    if matches {
                        found_parser = Some(parser);
                        break;
                    }
                }
            }
            if found_parser.is_none() {
                for parser in &self.parsers {
                    if let Some(true) = parser.is_format_supported(&payload.content) {
                        found_parser = Some(parser);
                        break;
                    }
                }
            }
            let parser = match found_parser {
                Some(p) => p,
                None => {
                    return Err(Error::NoParser {
                        format: payload.format.as_deref().unwrap_or("unknown").to_string(),
                        at: source_display(config_source),
                    });
                }
            };
            cfg_if! {
                if #[cfg(feature = "tracing")] {
                    tracing::trace!(msg = "Found parser for configuration payload", parser = parser.name(), resource = resource);
                } else if #[cfg(feature = "logging")] {
                    log::trace!("msg=\"Found parser for configuration payload\" parser={} resource={resource}", parser.name());
                }
            }
            let value = match parser.parse(source_name, &resource, &payload.content) {
                Ok(v) => v,
                Err(e) => {
                    if config_source.skip_errors() {
                        cfg_if! {
                            if #[cfg(feature = "tracing")] {
                                tracing::warn!(msg = "Skipped parse error for payload", source = source_display(config_source), resource = resource, error = ?e);
                            } else if #[cfg(feature = "logging")] {
                                let display = source_display(config_source);
                                log::warn!("msg=\"Skipped parse error for payload\" source={display} resource={resource} error={e:?}");
                            }
                        }
                        continue;
                    }
                    return Err(Error::Parse(e));
                }
            };
            result.push((payload.clone(), value));
        }
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Configuration parse stage complete", parsed_count = result.len());
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Configuration parse stage complete\" parsed_count={}", result.len());
            }
        }
        Ok(result)
    }

    /// Merge parsed values using the registered merger.
    ///
    /// Payloads with the same name are combined; `None`-named payloads share the `""` key.
    pub fn merge(&self, parsed: &[Parsed]) -> Result<Merged, Error> {
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Starting configuration merge stage", entry_count = parsed.len());
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Starting configuration merge stage\" entry_count={}", parsed.len());
            }
        }
        match self.merger.merge(parsed) {
            Ok(r) => {
                cfg_if! {
                    if #[cfg(feature = "tracing")] {
                        tracing::info!(msg = "Configuration merge stage complete", group_count = r.len());
                    } else if #[cfg(feature = "logging")] {
                        log::info!("msg=\"Configuration merge stage complete\" group_count={}", r.len());
                    }
                }
                Ok(r)
            }
            Err(e) => Err(Error::Merge(e)),
        }
    }

    /// Run load → parse → merge in sequence.
    pub fn run(&self) -> Result<Merged, Error> {
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Running configuration pipeline", source_count = self.sources.len(), loader_count = self.loaders.len(), parser_count = self.parsers.len());
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Running configuration pipeline\" source_count={} loader_count={} parser_count={}", self.sources.len(), self.loaders.len(), self.parsers.len());
            }
        }
        let loaded = self.load()?;
        let parsed = self.parse(&loaded)?;
        self.merge(&parsed)
    }
}