Skip to main content

dynamic_config/builder/
mod.rs

1//! Configuring a load at runtime — the builder half of the attribute split.
2//!
3//! The attribute declares that a type *is* a configuration; the [`Builder`]
4//! owns the "where" — chosen at runtime, not compile time — and funnels
5//! into the same [`LoadSpec`] everything else reads, so the two surfaces
6//! cannot drift apart on semantics.
7//!
8//! ```no_run
9//! # #[cfg(feature = "json")] {
10//! use dynamic_config::Builder;
11//! use serde::Deserialize;
12//!
13//! #[derive(Debug, Deserialize)]
14//! struct Db { host: String }
15//!
16//! let db: Db = Builder::new("db")
17//!     .file("config.json")
18//!     .env("APP_")
19//!     .load()
20//!     .expect("the sources read cleanly");
21//! # }
22//! ```
23//!
24//! On a `#[dynamic_config]` type, the generated `builder()` goes further:
25//! its `init()` installs the result as the type's snapshot, so runtime-
26//! chosen sources feed the same `current()` everything already reads.
27//!
28//! One concern per file: this module holds the struct, the fluent surface
29//! and the one `with_spec` funnel; [`lifecycle`] loads, installs and
30//! recovers; [`diagnostics`] answers questions without installing;
31//! [`watching`] starts the file watcher; [`configured`] is the slot that
32//! remembers a builder at `init` so the type can answer later.
33
34mod configured;
35mod diagnostics;
36mod lifecycle;
37#[cfg(feature = "watch")]
38mod watching;
39
40pub use configured::Configured;
41
42use std::marker::PhantomData;
43use std::path::Path;
44
45use serde::de::DeserializeOwned;
46
47use crate::cache::CacheMode;
48use crate::error::Error;
49use crate::source::{Format, LoadSpec, Source};
50
51/// An application-level validation hook: deserialized, not yet installed.
52///
53/// A closure rather than a bare `fn`, because a validator that needs
54/// *context* — a policy object, a schema, a foreign runtime's validator —
55/// cannot be written as a function pointer, and that is the shape a
56/// language binding needs. The `Arc` is what keeps `Builder` cloneable;
57/// a plain `fn` still coerces, so every existing call site is unchanged.
58type Validator<T> = std::sync::Arc<dyn Fn(&T) -> Result<(), Error> + Send + Sync>;
59
60/// Where a load's outcome goes — the value on success, the news on failure.
61///
62/// Two known shapes rather than an `Arc<dyn Fn>`: the generated `builder()`
63/// points at a `static` cell through plain `fn`s — no allocation — while a
64/// [`Dynamic`](crate::Dynamic) instance owns its cell and shares it here.
65///
66/// The failure half is here rather than only in the caller because a failed
67/// reload is a fact about the *cell*: `status()` answers "how many have
68/// failed since one worked", and only the cell outlives the attempt. A
69/// generated type reaches its static cell through a `fn` for the same
70/// reason the install does.
71pub(crate) enum Installer<T> {
72    /// The generated path: `fn`s that reach the type's static cell.
73    Static {
74        /// Stores into the type's cell, stating why, and hands back what it
75        /// stored — so `init_and_current` returns the snapshot *this* call
76        /// installed rather than whatever a later reload made current.
77        install: fn(T, crate::ReloadReason) -> std::sync::Arc<T>,
78        /// Records a reload that installed nothing.
79        record_failure: fn(&Error),
80    },
81    /// The instance path: this builder installs into a shared cell.
82    Cell(std::sync::Arc<crate::cell::ConfigCell<T>>),
83}
84
85impl<T> Installer<T> {
86    pub(super) fn install(&self, value: T, reason: crate::ReloadReason) -> std::sync::Arc<T> {
87        match self {
88            Self::Static { install, .. } => install(value, reason),
89            Self::Cell(cell) => cell.store_with(value, reason),
90        }
91    }
92
93    pub(super) fn record_failure(&self, error: &Error) {
94        match self {
95            Self::Static { record_failure, .. } => record_failure(error),
96            Self::Cell(cell) => cell.record_failure(error),
97        }
98    }
99}
100
101impl<T> Clone for Installer<T> {
102    fn clone(&self) -> Self {
103        match self {
104            Self::Static {
105                install,
106                record_failure,
107            } => Self::Static {
108                install: *install,
109                record_failure: *record_failure,
110            },
111            Self::Cell(cell) => Self::Cell(std::sync::Arc::clone(cell)),
112        }
113    }
114}
115
116/// Runtime-chosen sources for one configuration section.
117///
118/// Methods take and return `self`, are infallible, and defer every check to
119/// [`load`](Self::load) — a missing file or an unsupported extension is a
120/// load-time answer, same as everywhere else in this crate.
121///
122/// What the builder configures in this stage is the source side: files,
123/// the environment layer, `.env` files, profiles. The runtime layers
124/// (`set_default`, `set_override`) and remote stores stay on the generated
125/// type, whose statics they live in.
126pub struct Builder<T> {
127    key: String,
128    files: Vec<(String, bool)>,
129    env: Option<String>,
130    nest: Option<String>,
131    allow_empty_env: bool,
132    strict_env: bool,
133    whole_document: bool,
134    env_files: Vec<String>,
135    secrets_dir: Option<String>,
136    allow_external_symlinks: bool,
137    profile_env: Option<String>,
138    search: Option<(String, Vec<String>)>,
139    cache: Option<(String, CacheMode)>,
140    /// `Some` routes the cache through this encryptor: written encrypted,
141    /// recovered through the installed [`Decryptor`](crate::Decryptor).
142    #[cfg(feature = "decrypt")]
143    cache_encryptor: Option<std::sync::Arc<dyn crate::Encryptor>>,
144    /// `Some` even when empty: knowing there are *no* secret fields is
145    /// knowledge, and only the generated `builder()` has it.
146    secrets: Option<Vec<String>>,
147    validate: Option<Validator<T>>,
148    fields: &'static [&'static str],
149    install: Option<Installer<T>>,
150    /// Remembers this builder as the type's configuration on a successful
151    /// `init`, so `source_of`, `check`, `prepare` and friends can answer
152    /// later without being handed the builder again.
153    register: Option<fn(&Self)>,
154    defaults: Option<&'static crate::Layer>,
155    overrides: Option<&'static crate::Layer>,
156    flags: Option<&'static crate::Layer>,
157    bindings: Option<&'static crate::EnvBindings>,
158    aliases: Option<&'static crate::Aliases>,
159    remote: Option<&'static crate::Remote>,
160    _marker: PhantomData<fn() -> T>,
161}
162
163impl<T> Clone for Builder<T> {
164    fn clone(&self) -> Self {
165        Self {
166            key: self.key.clone(),
167            files: self.files.clone(),
168            env: self.env.clone(),
169            nest: self.nest.clone(),
170            allow_empty_env: self.allow_empty_env,
171            strict_env: self.strict_env,
172            whole_document: self.whole_document,
173            env_files: self.env_files.clone(),
174            secrets_dir: self.secrets_dir.clone(),
175            allow_external_symlinks: self.allow_external_symlinks,
176            profile_env: self.profile_env.clone(),
177            search: self.search.clone(),
178            cache: self.cache.clone(),
179            #[cfg(feature = "decrypt")]
180            cache_encryptor: self.cache_encryptor.clone(),
181            secrets: self.secrets.clone(),
182            validate: self.validate.clone(),
183            fields: self.fields,
184            install: self.install.clone(),
185            register: self.register,
186            defaults: self.defaults,
187            overrides: self.overrides,
188            flags: self.flags,
189            bindings: self.bindings,
190            aliases: self.aliases,
191            remote: self.remote,
192            _marker: PhantomData,
193        }
194    }
195}
196
197impl<T: DeserializeOwned> Builder<T> {
198    /// A builder for the section `key`, tied to no config type's storage.
199    ///
200    /// [`load`](Self::load) works; [`init`](Self::init) needs somewhere to
201    /// install and is how the generated `builder()` differs from this.
202    #[must_use]
203    pub fn new(key: impl Into<String>) -> Self {
204        Self {
205            key: key.into(),
206            files: Vec::new(),
207            env: None,
208            nest: None,
209            allow_empty_env: false,
210            strict_env: false,
211            whole_document: false,
212            env_files: Vec::new(),
213            secrets_dir: None,
214            allow_external_symlinks: false,
215            profile_env: None,
216            search: None,
217            cache: None,
218            #[cfg(feature = "decrypt")]
219            cache_encryptor: None,
220            secrets: None,
221            validate: None,
222            fields: &[],
223            install: None,
224            register: None,
225            defaults: None,
226            overrides: None,
227            flags: None,
228            bindings: None,
229            aliases: None,
230            remote: None,
231            _marker: PhantomData,
232        }
233    }
234
235    /// The generated `builder()`: everything installs into the type's cell,
236    /// and every reload that installs nothing is recorded there too.
237    #[doc(hidden)]
238    #[must_use]
239    pub fn with_installer(
240        mut self,
241        install: fn(T, crate::ReloadReason) -> std::sync::Arc<T>,
242        record_failure: fn(&Error),
243    ) -> Self {
244        self.install = Some(Installer::Static {
245            install,
246            record_failure,
247        });
248        self
249    }
250
251    /// The instance path: this builder installs into `cell`. What
252    /// [`Dynamic::new`](crate::Dynamic::new) wires; not public API.
253    ///
254    /// The registration callback is severed along with the installer: a
255    /// generated builder's `register` points at the *type's* `Configured`
256    /// slot, and an instance-owned builder landing there would cross-wire
257    /// the type surface — `Config::reload()` installing into the
258    /// `Dynamic`'s cell while `Config::current()` reads a static nothing
259    /// writes.
260    pub(crate) fn with_cell(mut self, cell: std::sync::Arc<crate::cell::ConfigCell<T>>) -> Self {
261        self.install = Some(Installer::Cell(cell));
262        self.register = None;
263        self
264    }
265
266    /// The generated `builder()`: the type's `#[config(secret)]` fields, by
267    /// their serde names — what a redacted cache needs to know.
268    #[doc(hidden)]
269    #[must_use]
270    pub fn with_secrets(mut self, secrets: &[&str]) -> Self {
271        self.secrets = Some(secrets.iter().map(|name| (*name).to_owned()).collect());
272        self
273    }
274
275    /// Which paths hold secrets, stated by hand.
276    ///
277    /// `#[config(secret)]` is a *declaration*, and a configuration with no
278    /// struct has nowhere to make one — so a schemaless configuration
279    /// (`Builder::values`, or any bare [`Builder::new`]) starts with no
280    /// secret list at all, and every surface that redacts one has nothing
281    /// to redact. This is that list, supplied at the only place that knows
282    /// it. It buys exactly what the attribute buys:
283    ///
284    /// - [`explain`](Self::explain) returns `***` for a path that is, sits
285    ///   under, or contains one of these — the same three-way rule
286    ///   `#[config(secret)]` gets;
287    /// - [`CacheMode::Redacted`](crate::CacheMode::Redacted) and
288    ///   [`Fingerprint`](crate::CacheMode::Fingerprint) become usable —
289    ///   without a list they are **refused** at `init` rather than quietly
290    ///   writing a cache with the secrets in it.
291    ///
292    /// Paths are dotted and relative to the section, as in
293    /// `"credentials.password"`. Naming a table redacts everything below it.
294    ///
295    /// What it cannot buy is a redacting `Debug`: there is no type here to
296    /// generate one for. [`Value`](crate::Value)'s own `Debug` prints shape
297    /// and keys and never values, which is why that gap is a non-event.
298    ///
299    /// ```no_run
300    /// # #[cfg(feature = "json")] {
301    /// use dynamic_config::{Builder, CacheMode};
302    ///
303    /// let builder = Builder::values("db")
304    ///     .file("config.json")
305    ///     .secrets(&["password"])
306    ///     .cache("last-known-good.json", CacheMode::Redacted);
307    /// # let _ = builder;
308    /// # }
309    /// ```
310    #[must_use]
311    pub fn secrets(self, secrets: &[&str]) -> Self {
312        self.with_secrets(secrets)
313    }
314
315    /// The generated `builder()`: the type's runtime layers and remote
316    /// storage, which live in its statics.
317    #[doc(hidden)]
318    #[must_use]
319    #[allow(clippy::too_many_arguments)]
320    pub fn with_type_statics(
321        mut self,
322        defaults: &'static crate::Layer,
323        overrides: &'static crate::Layer,
324        flags: &'static crate::Layer,
325        bindings: &'static crate::EnvBindings,
326        aliases: &'static crate::Aliases,
327        remote: &'static crate::Remote,
328        register: fn(&Self),
329    ) -> Self {
330        self.defaults = Some(defaults);
331        self.overrides = Some(overrides);
332        self.flags = Some(flags);
333        self.bindings = Some(bindings);
334        self.aliases = Some(aliases);
335        self.remote = Some(remote);
336        self.register = Some(register);
337        self
338    }
339
340    /// The section key this builder reads.
341    #[must_use]
342    pub fn key(&self) -> &str {
343        &self.key
344    }
345
346    /// Application-level validation, run after deserializing and before
347    /// anything installs — on `init`, on every watch reload, and on a
348    /// recovery from the cache. The reload path keeps the previous snapshot
349    /// when this refuses, exactly like a parse failure.
350    #[must_use]
351    pub fn validate(
352        mut self,
353        check: impl Fn(&T) -> Result<(), Error> + Send + Sync + 'static,
354    ) -> Self {
355        self.validate = Some(std::sync::Arc::new(check));
356        self
357    }
358
359    /// Adds a configuration file. Merged in call order; later files win.
360    ///
361    /// The format comes from the extension at load time. A missing file is
362    /// skipped, which is what makes an optional `secrets.json` work.
363    #[must_use]
364    pub fn file(mut self, path: impl Into<String>) -> Self {
365        self.files.push((path.into(), false));
366        self
367    }
368
369    /// Adds an encrypted configuration file — `secrets.json.age`.
370    ///
371    /// The format comes from the extension *under* the suffix; the document
372    /// decrypts through the installed [`Decryptor`](crate::Decryptor).
373    #[cfg(feature = "decrypt")]
374    #[cfg_attr(docsrs, doc(cfg(feature = "decrypt")))]
375    #[must_use]
376    pub fn encrypted_file(mut self, path: impl Into<String>) -> Self {
377        self.files.push((path.into(), true));
378        self
379    }
380
381    /// The environment layer: `prefix` plus the key, as in `env = "APP_"`.
382    #[must_use]
383    pub fn env(mut self, prefix: impl Into<String>) -> Self {
384        self.env = Some(prefix.into());
385        self
386    }
387
388    /// The nesting separator inside variable names; `"__"` unless said.
389    #[must_use]
390    pub fn nest(mut self, separator: impl Into<String>) -> Self {
391        self.nest = Some(separator.into());
392        self
393    }
394
395    /// Treats `FOO=` as set-to-empty rather than unset.
396    #[must_use]
397    pub fn allow_empty_env(mut self) -> Self {
398        self.allow_empty_env = true;
399        self
400    }
401
402    /// Refuses ambiguous environment spellings; see
403    /// [`LoadSpec::with_strict_env`].
404    #[must_use]
405    pub fn strict_env(mut self) -> Self {
406        self.strict_env = true;
407        self
408    }
409
410    /// Reads each document as this section's values, with no section header.
411    ///
412    /// The default is one file, several sections — every top-level key names
413    /// one, and this builder's key says which is yours. That is what lets a
414    /// `config.toml` carry `[db]` and `[server]` for two configuration types
415    /// that know nothing about each other.
416    ///
417    /// Say this when the document is *only* this configuration:
418    ///
419    /// ```json
420    /// { "host": "0.0.0.0", "port": 8000 }
421    /// ```
422    ///
423    /// ```no_run
424    /// # #[cfg(feature = "json")] {
425    /// use dynamic_config::Builder;
426    /// # use serde::Deserialize;
427    /// # #[derive(Deserialize)]
428    /// # struct Server { host: String, port: u16 }
429    /// let server: Server = Builder::new("server")
430    ///     .whole_document()
431    ///     .file("server.json")
432    ///     .env("APP_")
433    ///     .load()
434    ///     .expect("the sources read cleanly");
435    /// # }
436    /// ```
437    ///
438    /// The key keeps every other job it has: `APP_SERVER_PORT` still reaches
439    /// `port`, the cache entry and the diagnostics are still named after it,
440    /// and `""` is allowed for a configuration with nothing to call itself —
441    /// the environment layer is then just the prefix, `APP_PORT`.
442    ///
443    /// Everything else is unchanged: profile variants
444    /// (`server.production.json`), defaults, flags, overrides, aliases, the
445    /// secrets directory and a remote store's document all behave exactly as
446    /// they do for a sectioned load. It applies to **every** document this
447    /// builder reads, because sources that disagreed about their own shape
448    /// would be a configuration nobody could reason about.
449    #[must_use]
450    pub fn whole_document(mut self) -> Self {
451        self.whole_document = true;
452        self
453    }
454
455    /// A `.env` file read as the environment layer, below the real thing.
456    #[must_use]
457    pub fn env_file(mut self, path: impl Into<String>) -> Self {
458        self.env_files.push(path.into());
459        self
460    }
461
462    /// A directory of single-value files: one file per key, the filename is
463    /// the key, the contents are the value.
464    ///
465    /// What Docker's `/run/secrets` and a Kubernetes secret volume look like.
466    /// Nesting is spelled in the filename with the same separator
467    /// [`nest`](Self::nest) sets, so `db__password` is `db.password`; one
468    /// trailing newline is removed, because every tool that writes a secret
469    /// writes one. The layer sits above the files and below `.env` and the
470    /// environment — a mounted secret is a deployment fact, and a variable
471    /// exported for this run is a more specific one.
472    ///
473    /// A directory that is not there is skipped, exactly like a missing
474    /// file; one that cannot be read is a load-time error naming it.
475    #[must_use]
476    pub fn secrets_dir(mut self, path: impl Into<String>) -> Self {
477        self.secrets_dir = Some(path.into());
478        self
479    }
480
481    /// Lets a symlink in the secrets directory resolve outside it.
482    ///
483    /// Off by default since 0.7.1: an escaping link is refused with an
484    /// error naming the entry, because a directory of mounted credentials
485    /// that silently reads an arbitrary path through a planted link is a
486    /// vulnerability, not a layout. Kubernetes' own `..data` indirection
487    /// stays inside the mount and keeps working untouched. Turn this on
488    /// only for a deliberate cross-mount arrangement — and say why in a
489    /// comment, because the next reader will ask.
490    #[must_use]
491    pub fn allow_external_symlinks(mut self, allow: bool) -> Self {
492        self.allow_external_symlinks = allow;
493        self
494    }
495
496    /// The environment variable naming the active profile.
497    #[must_use]
498    pub fn profile_env(mut self, variable: impl Into<String>) -> Self {
499        self.profile_env = Some(variable.into());
500        self
501    }
502
503    /// Discovery: look for `{name}.{ext}` in each of `paths`, below any
504    /// explicitly listed files — the same rule as the attribute's
505    /// `name` + `paths`.
506    #[must_use]
507    pub fn discover(
508        mut self,
509        name: impl Into<String>,
510        paths: impl IntoIterator<Item = impl Into<String>>,
511    ) -> Self {
512        self.search = Some((name.into(), paths.into_iter().map(Into::into).collect()));
513        self
514    }
515
516    /// A last-known-good cache: written after every clean [`init`](Self::init)
517    /// or watch reload, recovered from when the sources will not load.
518    ///
519    /// [`CacheMode::Redacted`] and [`CacheMode::Fingerprint`] need to know
520    /// which fields are secret, which only the generated `builder()` on a
521    /// `#[dynamic_config]` type carries — on a bare [`Builder::new`], those
522    /// modes are refused at `init` rather than silently caching everything.
523    #[must_use]
524    pub fn cache(mut self, path: impl Into<String>, mode: CacheMode) -> Self {
525        self.cache = Some((path.into(), mode));
526        // Last writer wins outright: a plaintext cache asked for after an
527        // encrypted one must not keep the encryptor and silently write a
528        // full encrypted document where redaction was requested.
529        #[cfg(feature = "decrypt")]
530        {
531            self.cache_encryptor = None;
532        }
533        self
534    }
535
536    /// A last-known-good cache, encrypted at rest.
537    ///
538    /// The fourth answer to the cache trade-off, and the one that collapses
539    /// it: full fidelity — recovery needs nothing from the live environment
540    /// — with nothing readable on disk. Written through `encryptor` after
541    /// every clean [`init`](Self::init) or watch reload; recovered through
542    /// the installed [`Decryptor`](crate::Decryptor), the same door
543    /// [`encrypted_file`](Self::encrypted_file) reads through, so one
544    /// `set_decryptor` covers both. The path carries the format under the
545    /// encryption suffix — `last.json.age` — exactly like an encrypted
546    /// source file.
547    ///
548    /// The recipient question that kept this out of the attribute era has
549    /// the builder's answer: the recipients live in the `encryptor` the
550    /// caller constructs, at the call site that owns them.
551    #[cfg(feature = "decrypt")]
552    #[cfg_attr(docsrs, doc(cfg(feature = "decrypt")))]
553    #[must_use]
554    pub fn cache_encrypted(
555        mut self,
556        path: impl Into<String>,
557        encryptor: impl crate::Encryptor + 'static,
558    ) -> Self {
559        self.cache = Some((path.into(), CacheMode::Full));
560        self.cache_encryptor = Some(std::sync::Arc::new(encryptor));
561        self
562    }
563
564    /// The generated `builder()`: the struct's field names, for unknown-key
565    /// detection in [`check`](Self::check).
566    #[doc(hidden)]
567    #[must_use]
568    pub fn with_fields(mut self, fields: &'static [&'static str]) -> Self {
569        self.fields = fields;
570        self
571    }
572
573    /// Runs `operation` with the [`LoadSpec`] this builder describes.
574    ///
575    /// The one funnel: everything the builder does goes through the same
576    /// spec the attribute generates, so the two surfaces cannot diverge.
577    fn with_spec<R>(
578        &self,
579        operation: impl FnOnce(&LoadSpec<'_>) -> Result<R, Error>,
580    ) -> Result<R, Error> {
581        let sources = self
582            .files
583            .iter()
584            .map(|(file, encrypted)| {
585                Format::from_path(Path::new(file)).map(|format| {
586                    if *encrypted {
587                        Source::encrypted(file, format)
588                    } else {
589                        Source::file(file, format)
590                    }
591                })
592            })
593            .collect::<Result<Vec<_>, _>>()?;
594        let env_files: Vec<&str> = self.env_files.iter().map(String::as_str).collect();
595
596        let mut spec = LoadSpec::new(&self.key, &sources)
597            .with_empty_env(self.allow_empty_env)
598            .with_strict_env(self.strict_env)
599            .with_whole_document(self.whole_document)
600            .with_env_files(&env_files);
601
602        if let Some(prefix) = &self.env {
603            spec = spec.with_env(prefix);
604        }
605        if let Some(separator) = &self.nest {
606            spec = spec.with_nest(separator);
607        }
608        if let Some(variable) = &self.profile_env {
609            spec = spec.with_profile_env(variable);
610        }
611        if let Some(directory) = &self.secrets_dir {
612            spec = spec.with_secrets_dir(directory);
613            spec = spec.with_allow_external_symlinks(self.allow_external_symlinks);
614        }
615
616        let search_paths: Vec<&str>;
617        if let Some((name, paths)) = &self.search {
618            search_paths = paths.iter().map(String::as_str).collect();
619            spec = spec.with_search(name, &search_paths);
620        }
621
622        if let Some(layer) = self.defaults {
623            spec = spec.with_defaults(layer);
624        }
625        if let Some(layer) = self.overrides {
626            spec = spec.with_overrides(layer);
627        }
628        if let Some(layer) = self.flags {
629            spec = spec.with_flags(layer);
630        }
631        if let Some(bindings) = self.bindings {
632            spec = spec.with_env_bindings(bindings);
633        }
634        if let Some(aliases) = self.aliases {
635            spec = spec.with_aliases(aliases);
636        }
637        if let Some(remote) = self.remote {
638            spec = spec.with_remote(remote);
639        }
640
641        operation(&spec)
642    }
643}
644
645impl Builder<crate::Value> {
646    /// A configuration with no struct: the resolved section as data.
647    ///
648    /// Sugar for `Builder::<Value>::new(key)`, and the entry point that
649    /// makes the schemaless shape findable — a plugin host, a feature-flag
650    /// table, a tool inspecting somebody else's configuration. Every source,
651    /// layer and diagnostic on this builder behaves exactly as it does for a
652    /// struct, because nothing in the engine ever needed one; what changes is
653    /// the reading, which is by path.
654    ///
655    /// ```
656    /// # #[cfg(feature = "json")] {
657    /// use dynamic_config::{Builder, Dynamic};
658    ///
659    /// # std::fs::create_dir_all("target/doctest").unwrap();
660    /// # std::fs::write("target/doctest/schemaless.json",
661    /// #     r#"{"db": {"host": "localhost", "pool": {"max_size": 32}}}"#).unwrap();
662    /// let config = Dynamic::new(
663    ///     Builder::values("db").file("target/doctest/schemaless.json"),
664    /// );
665    /// let values = config.init_and_current()?;
666    ///
667    /// // One atomic load above; a walk of the tree here. No struct, and no
668    /// // deserialize per read.
669    /// assert_eq!(values.get("host").and_then(|v| v.as_str()), Some("localhost"));
670    /// assert_eq!(values.get("pool.max_size").and_then(|v| v.as_i64()), Some(32));
671    /// # }
672    /// # Ok::<(), dynamic_config::Error>(())
673    /// ```
674    ///
675    /// # What it does not get
676    ///
677    /// A struct is a *declaration*, and four things follow from it that
678    /// nothing can reconstruct without one:
679    ///
680    /// | | With a struct | Here |
681    /// |---|---|---|
682    /// | Types | checked at the load | checked at each read |
683    /// | Unknown keys | [`check`](Self::check) names them | reported as **not checked** |
684    /// | Secrets | `#[config(secret)]` | [`secrets`](Self::secrets), by hand |
685    /// | Missing required values | the load fails | absent is `None` |
686    ///
687    /// Everything else — layering, profiles, discovery, `.env`,
688    /// `secrets_dir`, watching, the last-known-good cache, reload hooks,
689    /// `source_of` and `explain` — is unchanged. The exception is not
690    /// about schemas: remote stores and the runtime layers live in a
691    /// `#[dynamic_config]` type's statics, so no builder made with
692    /// [`new`](Self::new) or `values` reaches them, whatever `T` is.
693    #[must_use]
694    pub fn values(key: impl Into<String>) -> Self {
695        Self::new(key)
696    }
697}
698
699impl<T> std::fmt::Debug for Builder<T> {
700    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
701        f.debug_struct("Builder")
702            .field("key", &self.key)
703            .field("files", &self.files)
704            .field("env", &self.env)
705            .field("env_files", &self.env_files)
706            .field("strict_env", &self.strict_env)
707            .field("whole_document", &self.whole_document)
708            .field("installs", &self.install.is_some())
709            .finish_non_exhaustive()
710    }
711}