qubit-config 0.11.2

Powerful type-safe configuration management with multi-value properties, variable substitution, and rich data type support
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/

#![allow(private_bounds)]

use qubit_value::MultiValues;
use qubit_value::multi_values::{MultiValuesFirstGetter, MultiValuesGetter};
use serde::de::DeserializeOwned;

use crate::config_prefix_view::ConfigPrefixView;
use crate::field::ConfigField;
use crate::from::{FromConfig, is_effectively_missing, parse_property_from_reader};
use crate::options::ConfigReadOptions;
use crate::{Config, ConfigError, ConfigResult, Property};

/// Read-only configuration interface.
///
/// This trait allows consumers to read configuration values without requiring
/// ownership of a [`crate::Config`]. Both [`crate::Config`] and
/// [`crate::ConfigPrefixView`] implement it.
///
/// Its required methods mirror the read-only surface of [`crate::Config`]
/// (metadata, raw properties, iteration, subtree extraction, and serde
/// deserialization), with prefix views resolving keys relative to their
/// logical prefix.
///
pub trait ConfigReader {
    /// Returns whether `${...}` variable substitution is applied when reading
    /// string values.
    ///
    /// # Returns
    ///
    /// `true` if substitution is enabled for this reader.
    fn is_enable_variable_substitution(&self) -> bool;

    /// Returns the maximum recursion depth allowed when resolving nested
    /// `${...}` references.
    ///
    /// # Returns
    ///
    /// Maximum substitution depth (see
    /// `DEFAULT_MAX_SUBSTITUTION_DEPTH` for the default used by
    /// [`crate::Config`]).
    fn max_substitution_depth(&self) -> usize;

    /// Returns the optional human-readable description attached to this
    /// configuration (the whole document; prefix views expose the same value
    /// as the underlying [`crate::Config`]).
    fn description(&self) -> Option<&str>;

    /// Returns a reference to the raw [`Property`] for `name`, if present.
    ///
    /// For a [`ConfigPrefixView`], `name` is resolved relative to the view
    /// prefix (same rules as [`Self::get`]).
    fn get_property(&self, name: &str) -> Option<&Property>;

    /// Number of configuration entries visible to this reader (all keys for
    /// [`crate::Config`]; relative keys only for a [`ConfigPrefixView`]).
    fn len(&self) -> usize;

    /// Returns `true` when [`Self::len`] is zero.
    fn is_empty(&self) -> bool;

    /// All keys visible to this reader (relative keys for a prefix view).
    fn keys(&self) -> Vec<String>;

    /// Returns whether a property exists for the given key.
    ///
    /// # Parameters
    ///
    /// * `name` - Full configuration key (for [`crate::ConfigPrefixView`],
    ///   relative keys are resolved against the view prefix).
    ///
    /// # Returns
    ///
    /// `true` if the key is present.
    fn contains(&self, name: &str) -> bool;

    /// Reads the first stored value for `name` and converts it to `T`.
    ///
    /// # Type parameters
    ///
    /// * `T` - Target type parsed by [`FromConfig`].
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// The converted value on success, or a [`crate::ConfigError`] if the key
    /// is missing, empty, or not convertible.
    fn get<T>(&self, name: &str) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        let resolved = self.resolve_key(name);
        let property = self
            .get_property(name)
            .ok_or_else(|| ConfigError::PropertyNotFound(resolved.clone()))?;
        if !property.is_empty()
            && is_effectively_missing(self, &resolved, property, self.read_options())?
        {
            return Err(ConfigError::PropertyHasNoValue(resolved));
        }
        parse_property_from_reader(self, &resolved, property, self.read_options())
    }

    /// Reads the first stored value for `name` without cross-type conversion.
    ///
    /// # Type parameters
    ///
    /// * `T` - Exact target type; requires `MultiValues` to implement
    ///   `MultiValuesFirstGetter` for `T`.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// The exact stored value on success, or a [`crate::ConfigError`] if the
    /// key is missing, empty, or has a different stored type.
    fn get_strict<T>(&self, name: &str) -> ConfigResult<T>
    where
        MultiValues: MultiValuesFirstGetter<T>;

    /// Reads all stored values for `name` and converts each element to `T`.
    ///
    /// # Type parameters
    ///
    /// * `T` - Element type supported by the shared conversion layer.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// A vector of values on success, or a [`crate::ConfigError`] on failure.
    fn get_list<T>(&self, name: &str) -> ConfigResult<Vec<T>>
    where
        T: FromConfig;

    /// Reads all stored values for `name` without cross-type conversion.
    ///
    /// # Type parameters
    ///
    /// * `T` - Exact element type; requires `MultiValues` to implement
    ///   `MultiValuesGetter` for `T`.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// A vector of exact stored values on success, or a
    /// [`crate::ConfigError`] on failure.
    fn get_list_strict<T>(&self, name: &str) -> ConfigResult<Vec<T>>
    where
        MultiValues: MultiValuesGetter<T>;

    /// Gets a value or `default` if the key is missing or empty.
    ///
    /// Conversion and substitution errors are returned instead of being hidden by
    /// the default.
    #[inline]
    fn get_or<T>(&self, name: &str, default: T) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        self.get_optional(name)
            .map(|value| value.unwrap_or(default))
    }

    /// Gets an optional value with the same semantics as [`crate::Config::get_optional`].
    ///
    /// # Type parameters
    ///
    /// * `T` - Target type parsed by [`FromConfig`].
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key (relative for a prefix view).
    ///
    /// # Returns
    ///
    /// `Ok(Some(v))`, `Ok(None)` when missing or empty, or `Err` on conversion failure.
    fn get_optional<T>(&self, name: &str) -> ConfigResult<Option<T>>
    where
        T: FromConfig,
    {
        let resolved = self.resolve_key(name);
        match self.get_property(name) {
            None => Ok(None),
            Some(property)
                if is_effectively_missing(self, &resolved, property, self.read_options())? =>
            {
                Ok(None)
            }
            Some(property) => {
                parse_property_from_reader(self, &resolved, property, self.read_options()).map(Some)
            }
        }
    }

    /// Gets the read options active for this reader.
    ///
    /// # Returns
    ///
    /// Global read options inherited by field-less reads.
    fn read_options(&self) -> &ConfigReadOptions;

    /// Reads a value from the first present and non-empty key in `names`.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    ///
    /// # Returns
    ///
    /// Parsed value from the first configured key. Conversion errors stop the
    /// search and are returned directly.
    fn get_any<T>(&self, names: &[&str]) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        self.get_optional_any(names)?
            .ok_or_else(|| ConfigError::PropertyNotFound(format!("one of: {}", names.join(", "))))
    }

    /// Reads an optional value from the first present and non-empty key.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    ///
    /// # Returns
    ///
    /// `Ok(None)` only when all keys are missing or empty.
    fn get_optional_any<T>(&self, names: &[&str]) -> ConfigResult<Option<T>>
    where
        T: FromConfig,
    {
        self.get_optional_any_with_options(names, self.read_options())
    }

    /// Reads a value from any key, using `default` only when all keys are
    /// absent or empty.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    /// * `default` - Fallback when no candidate is configured.
    ///
    /// # Returns
    ///
    /// Parsed value or `default`; parsing errors are never swallowed.
    fn get_any_or<T>(&self, names: &[&str], default: T) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        self.get_optional_any(names)
            .map(|value| value.unwrap_or(default))
    }

    /// Reads a value from any key with explicit read options, using `default`
    /// only when all keys are absent or empty.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    /// * `default` - Fallback when no candidate is configured.
    /// * `read_options` - Parsing options for this read.
    ///
    /// # Returns
    ///
    /// Parsed value or `default`; parsing errors are never swallowed.
    fn get_any_or_with<T>(
        &self,
        names: &[&str],
        default: T,
        read_options: &ConfigReadOptions,
    ) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        self.get_optional_any_with_options(names, read_options)
            .map(|value| value.unwrap_or(default))
    }

    /// Reads a declared field.
    ///
    /// # Parameters
    ///
    /// * `field` - Field declaration containing name, aliases, defaults, and
    ///   optional field-level read options.
    ///
    /// # Returns
    ///
    /// Parsed field value or its default.
    fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>
    where
        T: FromConfig,
    {
        let ConfigField {
            name,
            aliases,
            default,
            read_options,
        } = field;
        let options = read_options.as_ref().unwrap_or_else(|| self.read_options());
        let mut names = Vec::with_capacity(1 + aliases.len());
        names.push(name.as_str());
        names.extend(aliases.iter().map(String::as_str));
        self.get_optional_any_with_options(&names, options)?
            .or(default)
            .ok_or_else(|| ConfigError::PropertyNotFound(format!("one of: {}", names.join(", "))))
    }

    /// Reads an optional declared field.
    ///
    /// # Parameters
    ///
    /// * `field` - Field declaration.
    ///
    /// # Returns
    ///
    /// Parsed field value, its default, or `None`.
    fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>
    where
        T: FromConfig,
    {
        let ConfigField {
            name,
            aliases,
            default,
            read_options,
        } = field;
        let options = read_options.as_ref().unwrap_or_else(|| self.read_options());
        let mut names = Vec::with_capacity(1 + aliases.len());
        names.push(name.as_str());
        names.extend(aliases.iter().map(String::as_str));
        self.get_optional_any_with_options(&names, options)
            .map(|value| value.or(default))
    }

    /// Shared implementation for field-level and global multi-key reads.
    fn get_optional_any_with_options<T>(
        &self,
        names: &[&str],
        options: &ConfigReadOptions,
    ) -> ConfigResult<Option<T>>
    where
        T: FromConfig,
    {
        for name in names {
            let Some(property) = self.get_property(name) else {
                continue;
            };
            let resolved = self.resolve_key(name);
            if is_effectively_missing(self, &resolved, property, options)? {
                continue;
            }
            return parse_property_from_reader(self, &resolved, property, options).map(Some);
        }
        Ok(None)
    }

    /// Gets an optional list with the same semantics as [`crate::Config::get_optional_list`].
    ///
    /// # Type parameters
    ///
    /// * `T` - Element type supported by the shared conversion layer.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// `Ok(Some(vec))`, `Ok(None)` when missing or empty, or `Err` on failure.
    fn get_optional_list<T>(&self, name: &str) -> ConfigResult<Option<Vec<T>>>
    where
        T: FromConfig;

    /// Returns whether any key visible to this reader starts with `prefix`.
    ///
    /// # Parameters
    ///
    /// * `prefix` - Key prefix to test (for a prefix view, keys are relative to
    ///   that view).
    ///
    /// # Returns
    ///
    /// `true` if at least one matching key exists.
    fn contains_prefix(&self, prefix: &str) -> bool;

    /// Iterates `(key, property)` pairs for keys that start with `prefix`.
    ///
    /// # Parameters
    ///
    /// * `prefix` - Key prefix filter.
    ///
    /// # Returns
    ///
    /// A boxed iterator over matching entries.
    fn iter_prefix<'a>(
        &'a self,
        prefix: &'a str,
    ) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>;

    /// Iterates all `(key, property)` pairs visible to this reader (same scope
    /// as [`Self::keys`]).
    fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>;

    /// Returns `true` if the key exists and the property has no values (same
    /// as [`crate::Config::is_null`]).
    fn is_null(&self, name: &str) -> bool;

    /// Extracts a subtree as a new [`Config`] (same semantics as
    /// [`crate::Config::subconfig`]; on a prefix view, `prefix` is relative to
    /// the view).
    fn subconfig(&self, prefix: &str, strip_prefix: bool) -> ConfigResult<Config>;

    /// Deserializes the subtree at `prefix` with serde (same as
    /// [`crate::Config::deserialize`]; on a prefix view, `prefix` is relative).
    fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>
    where
        T: DeserializeOwned;

    /// Creates a read-only prefix view; relative keys resolve under `prefix`.
    ///
    /// Semantics match [`crate::Config::prefix_view`] and
    /// [`crate::ConfigPrefixView::prefix_view`] (nested prefix when called on a
    /// view).
    ///
    /// # Parameters
    ///
    /// * `prefix` - Logical prefix; empty means the full configuration (same as
    ///   root).
    ///
    /// # Returns
    ///
    /// A [`ConfigPrefixView`] borrowing this reader's underlying
    /// [`crate::Config`].
    fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>;

    /// Resolves `name` into the canonical key path against the root
    /// [`crate::Config`].
    ///
    /// For a root [`crate::Config`], this returns `name` unchanged. For a
    /// [`crate::ConfigPrefixView`], this prepends the effective view prefix so
    /// callers can report root-relative key paths in diagnostics.
    ///
    /// # Parameters
    ///
    /// * `name` - Relative or absolute key in the current reader scope.
    ///
    /// # Returns
    ///
    /// Root-relative key path string.
    #[inline]
    fn resolve_key(&self, name: &str) -> String {
        name.to_string()
    }

    /// Gets a string value, applying variable substitution when enabled.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// The string after `${...}` resolution, or a [`crate::ConfigError`].
    fn get_string(&self, name: &str) -> ConfigResult<String> {
        self.get(name)
    }

    /// Gets a string value from the first present and non-empty key in `names`.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    ///
    /// # Returns
    ///
    /// The resolved string from the first configured key.
    #[inline]
    fn get_string_any(&self, names: &[&str]) -> ConfigResult<String> {
        self.get_any(names)
    }

    /// Gets an optional string value from the first present and non-empty key.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    ///
    /// # Returns
    ///
    /// `Ok(None)` only when all keys are missing or empty.
    #[inline]
    fn get_optional_string_any(&self, names: &[&str]) -> ConfigResult<Option<String>> {
        self.get_optional_any(names)
    }

    /// Gets a string from any key, or `default` when all keys are missing or
    /// empty.
    ///
    /// # Parameters
    ///
    /// * `names` - Candidate keys in priority order.
    /// * `default` - Fallback string used only when every key is missing or
    ///   empty.
    ///
    /// # Returns
    ///
    /// The resolved string or a clone of `default`; substitution errors are
    /// returned.
    #[inline]
    fn get_string_any_or(&self, names: &[&str], default: &str) -> ConfigResult<String> {
        self.get_any_or(names, default.to_string())
    }

    /// Gets a string value with substitution, or `default` if the key is
    /// missing or empty.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    /// * `default` - Fallback string used only when the key is missing or empty.
    ///
    /// # Returns
    ///
    /// The resolved string or a clone of `default`; parsing and substitution
    /// errors are returned.
    #[inline]
    fn get_string_or(&self, name: &str, default: &str) -> ConfigResult<String> {
        self.get_or(name, default.to_string())
    }

    /// Gets all string values for `name`, applying substitution to each element
    /// when enabled.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// A vector of resolved strings, or a [`crate::ConfigError`].
    fn get_string_list(&self, name: &str) -> ConfigResult<Vec<String>> {
        self.get(name)
    }

    /// Gets a string list with substitution, or copies `default` if the key is
    /// missing or empty.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    /// * `default` - Fallback string slices used only when the key is missing or
    ///   empty.
    ///
    /// # Returns
    ///
    /// The resolved list or `default` converted to owned `String`s`; parsing and
    /// substitution errors are returned.
    #[inline]
    fn get_string_list_or(&self, name: &str, default: &[&str]) -> ConfigResult<Vec<String>> {
        self.get_or(name, default.iter().map(|s| s.to_string()).collect())
    }

    /// Gets an optional string with the same three-way semantics as
    /// [`crate::Config::get_optional_string`].
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// `Ok(None)` if the key is missing or empty; `Ok(Some(s))` with
    /// substitution applied; or `Err` if the value exists but cannot be read as
    /// a string.
    #[inline]
    fn get_optional_string(&self, name: &str) -> ConfigResult<Option<String>> {
        match self.get_property(name) {
            None => Ok(None),
            Some(prop) if prop.is_empty() => Ok(None),
            Some(_) => self.get_string(name).map(Some),
        }
    }

    /// Gets an optional string list with per-element substitution when enabled.
    ///
    /// # Parameters
    ///
    /// * `name` - Configuration key.
    ///
    /// # Returns
    ///
    /// `Ok(None)` if the key is missing or empty; `Ok(Some(vec))` otherwise; or
    /// `Err` on conversion/substitution failure.
    #[inline]
    fn get_optional_string_list(&self, name: &str) -> ConfigResult<Option<Vec<String>>> {
        match self.get_property(name) {
            None => Ok(None),
            Some(prop) if prop.is_empty() => Ok(None),
            Some(_) => self.get_string_list(name).map(Some),
        }
    }
}