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