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
//! Hot-reloadable, lock-free application configuration, built on
//! [figment](https://docs.rs/figment).
//!
//! Annotate a struct, call `init()` once, and read it from anywhere:
//!
//! ```
//! # #[cfg(feature = "json")] {
//! use dynamic_config::dynamic_config;
//! use serde::Deserialize;
//!
//! #[dynamic_config(files = ["config.json"], key = "server", env = "APP_")]
//! #[derive(Debug, Deserialize)]
//! struct ServerConfig {
//! #[serde(default = "default_host")]
//! host: String,
//! #[serde(default = "default_port")]
//! port: u16,
//! }
//!
//! # fn default_host() -> String { "0.0.0.0".into() }
//! # fn default_port() -> u16 { 8080 }
//! // `config.json` does not exist here, so every field falls back to its
//! // default — a missing file is skipped, not an error.
//! ServerConfig::init().expect("defaults cover every field");
//!
//! let config = ServerConfig::current();
//! println!("{}:{}", config.host, config.port);
//! # }
//! ```
//!
//! This page is the API reference. The guide — profiles, discovery, hot
//! reload, remote stores, encryption, testing — is
//! [**the book**](https://ctolon.github.io/dynamic-config/).
//!
//! # What the attribute generates
//!
//! The everyday core:
//!
//! | Method | Description |
//! |---|---|
//! | `load() -> Result<Self, Error>` | Read the sources and deserialize. Does not touch the snapshot. |
//! | `init() -> Result<(), Error>` | `load()` plus install as the initial snapshot. Call once at startup. |
//! | `replace(Self)` | Atomically swap in a new snapshot. |
//! | `current() -> Arc<Self>` | The current snapshot. Panics before `init()`. |
//! | `try_current() -> Option<Arc<Self>>` | The current snapshot, or `None` before `init()`. |
//! | `start_watch() -> io::Result<WatchHandle>` | With `watch`: reload on file changes until the handle is dropped. A second watch while one runs is `AlreadyExists`. |
//! | `on_reload(f)` | Run a callback on every later reload, for the life of the process. |
//! | `on_reload_scoped(f) -> HookGuard` | The same, until the guard is dropped. |
//! | `set_default(path, value)` | A fallback used only when nothing else supplies the key. |
//! | `set_override(path, value)` | A value that wins over every file and variable. |
//! | `clear_defaults()` / `clear_overrides()` | Drop them again. |
//! | `load_async()` / `init_async()` | With `async`: the same, off the async executor. |
//! | `changes()` | With `async`: a handle woken by every later reload. |
//!
//! The rest of the surface — introspection (`snapshot`, `source_of`, `is_set`,
//! `check`), persistence (`save`, `save_new`, `save_encrypted`), remote stores
//! (`set_remote`, `refresh_remote`, `apply_remote`), aliases, environment
//! bindings, flags, `bind_clap`, `schema` — is in [the book's attribute
//! reference](https://ctolon.github.io/dynamic-config/attribute-reference.html).
//!
//! # Precedence
//!
//! ```text
//! set_default < discovered < config.toml < secrets.json < remote < APP_DB_* < bind_env < set_flag < set_override
//! (runtime) (search path) (first) (last file) (etcd…) (environment) (by name) (CLI) (runtime)
//! ```
//!
//! Files merge left to right and tables merge key by key, so a small
//! `secrets.json` can override two fields of a large `config.toml` without
//! restating it.
//!
//! The two runtime layers bracket the rest. Defaults cover a fallback the
//! program can compute but a file need not state; overrides are what make a
//! test or a `--set key=value` flag authoritative without touching disk. Both
//! take effect on the next `load()`.
//!
//! # Reading configuration is lock-free
//!
//! `current()` hands out an `Arc` cloned from an `ArcSwap`, so a reload never
//! blocks a request handler. A reader that already holds an `Arc` keeps its own
//! generation — call `current()` once per request and reuse it, or a reload
//! landing mid-request will show you two different configurations.
//!
//! # Reloading cannot take the process down
//!
//! A reload re-runs `load()`. If the new configuration is invalid, or a file is
//! caught half-written, the error is reported and the previous snapshot stays
//! in place. A bad edit degrades to "no change".
//!
//! # Environment variables
//!
//! `env = "APP_"` with `key = "db"` reads `APP_DB_*`. A single underscore is
//! part of a field name; a doubled one introduces nesting:
//!
//! | Variable | Sets |
//! |---|---|
//! | `APP_DB_HOST` | `host` |
//! | `APP_DB_MAX_SIZE` | `max_size` |
//! | `APP_DB_POOL__MAX_SIZE` | `pool.max_size` |
//!
//! Values are interpreted by figment, which reads them loosely: `8080` reaches
//! a `u16`, `true` reaches a `bool`, and `[a, b, c]` reaches a `Vec<String>`.
//! A value that cannot become the field's type is an error naming the field.
//!
//! # Units
//!
//! `timeout = 30` is ambiguous and `max_body = 67108864` is unreadable, so both
//! are usually written with a unit — which no stock `Deserialize` accepts:
//!
//! ```
//! use std::time::Duration;
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Limits {
//! #[serde(with = "dynamic_config::duration")]
//! timeout: Duration, // "30s", "1h30m", "500ms", or a number of seconds
//! #[serde(with = "dynamic_config::bytes")]
//! max_body: u64, // "64MiB", "1GB", or a number of bytes
//! }
//! ```
//!
//! # Async
//!
//! With the `async` feature and the `async` argument, configuration loads
//! without blocking the executor, and tasks can await reloads instead of
//! polling. No runtime is named anywhere: `changes()` is a `Future`, so any
//! executor drives it.
//!
//! ```ignore
//! #[dynamic_config(files = ["config.json"], key = "db", watch, async)]
//! #[derive(Debug, Deserialize)]
//! struct DbConfig { pool_size: u32 }
//!
//! DbConfig::init_async().await?;
//! // Keep the handle: dropping it stops the watch.
//! let _watch = DbConfig::start_watch()?;
//!
//! let mut reloads = DbConfig::changes();
//!
//! spawn(async move {
//! loop {
//! let config = reloads.changed().await;
//! pool.resize(config.pool_size);
//! }
//! });
//! ```
//!
//! The watcher itself stays on a plain thread. `notify`'s channel is
//! synchronous, and keeping it off the runtime means file watching works
//! whether or not a runtime is running.
//!
//! # Features
//!
//! | Feature | Default | Effect |
//! |---|---|---|
//! | `json` | yes | `.json` sources |
//! | `toml` | no | `.toml` sources |
//! | `yaml` | no | `.yaml` / `.yml` sources |
//! | `watch` | no | `start_watch()` and the file watcher |
//! | `async` | no | `load_async`, `init_async`, `changes` — no runtime dependency |
//! | `tokio` | no | `async`, plus tokio's blocking pool instead of a thread per load |
//! | `clap` | no | `bind_clap`: named `clap` arguments as the flags layer |
//! | `schema` | no | `schema()`: a JSON Schema for the resolved configuration |
//! | `decrypt` | no | the [`Decryptor`]/[`Encryptor`] traits and `.age`-suffix handling |
//! | `age` | no | `decrypt`, plus the `age` module's implementation of it |
//! | `figment` | no | foreign figment providers as sources, via `Source::provider` |
//! | `dotenv` | no | `env_files = [".env"]`: `.env` files as the environment layer |
//! | `tracing` | no | Watcher diagnostics via `tracing` instead of stderr |
//! | `full` | no | all of the above |
//!
//! Using a format, `watch` or `async` whose feature is disabled is a compile
//! error naming the feature to add.
//!
//! # Without the macro
//!
//! [`load`], [`ConfigCell`] and [`LoadSpec`] are the whole engine and are
//! usable on their own:
//!
//! ```
//! # #[cfg(feature = "json")] {
//! use dynamic_config::{load, Format, LoadSpec, Source};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Db { host: String }
//!
//! let sources = [Source::inline(r#"{"db": {"host": "localhost"}}"#, Format::Json)];
//! let db: Db = load(&LoadSpec::new("db", &sources))
//! .expect("the inline document is well formed");
//!
//! assert_eq!(db.host, "localhost");
//! # }
//! ```
// A getter whose result is discarded is a mistake in a library like this one —
// `is_set`, `contains`, `document`, `describe` all answer a question and change
// nothing. Warned about rather than left to review, and CI denies warnings.
pub use ;
/// figment itself, re-exported.
///
/// So that writing a [`Source::provider`] needs no direct dependency, and no
/// second version of figment in the graph. This is the one place figment
/// appears in this crate's API, which is why it is behind a feature.
pub use figment;
pub use Aliases;
pub use EnvBindings;
pub use ;
pub use ;
pub use ;
pub use ;
pub use Search;
pub use ;
pub use ;
pub use Layer;
pub use Registry;
pub use AsyncRemoteSource;
pub use ;
pub use ;
pub use ;
pub use ;
pub use save_encrypted;
pub use ;
/// Turns a struct into a hot-reloadable configuration snapshot.
///
/// See the [crate documentation](crate) for the full guide.
///
/// # Arguments
///
/// | Argument | Form | Requires | Default |
/// |---|---|---|---|
/// | `files` | `files = ["a.toml"]` | one of `files` / `name`+`paths` | — |
/// | `name` | `name = "config"` | `paths` | — |
/// | `paths` | `paths = ["/etc/app", "."]` | `name` | — |
/// | `key` | `key = "db"` | always | — |
/// | `env` | `env = "APP_"` | | no environment layer |
/// | `nest` | `nest = "__"` | `env` | `"__"` |
/// | `allow_empty_env` | flag | `env` | off — `FOO=` is unset |
/// | `profile_env` | `profile_env = "APP_ENV"` | | no profile overlay |
/// | `watch` | flag | `watch` feature | off |
/// | `debounce` | `debounce = 250` | `watch` | 250 ms |
/// | `poll` / `poll_interval` | flag / `= 2000` | `watch` | native backend |
/// | `diff` | flag | | off |
/// | `validate` | flag | a `validate()` on the type | off |
/// | `save` | flag | `Self: Serialize` | off |
/// | `cache` | `cache = "last.json"` | | no cache — a bad start fails |
/// | `cache_mode` | `cache_mode = "redacted"` | `cache` | `"full"` |
/// | `env_files` | `env_files = [".env"]` | `dotenv` feature + `env` | none |
/// | `schema` | flag | `schema` feature + `Self: JsonSchema` | off |
/// | `async` | flag | `async` feature | off |
///
/// One field attribute: `#[config(secret)]` generates a `Debug` that prints
/// `***` for the marked fields, and forbids `#[derive(Debug)]` alongside it.
///
/// [The book's attribute reference](https://ctolon.github.io/dynamic-config/attribute-reference.html)
/// carries a section per argument, with an example and the reasoning behind
/// each default.
///
/// # Requirements
///
/// The annotated struct must implement `serde::Deserialize` and be
/// `Send + Sync + 'static`. Type and const parameters are supported — those go
/// through a `TypeId` registry rather than a `static`, at a measured cost of
/// roughly 10 ns per read. A **lifetime** parameter is rejected at compile
/// time: the snapshot outlives every borrow that could name one.
pub use dynamic_config;
use DeserializeOwned;
/// Reads and deserializes a configuration section.
///
/// This is what the generated `load()` calls. Missing files are skipped;
/// everything else — a parse failure, a missing required field, a value that
/// cannot become the requested type — is an [`Error`] naming the key path and
/// the source it came from.
///
/// # Errors
///
/// See [`ErrorKind`] for the categories.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "json")] {
/// use dynamic_config::{load, Format, LoadSpec, Source};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Server { port: u16 }
///
/// let sources = [Source::inline(r#"{"server": {"port": 8080}}"#, Format::Json)];
/// let server: Server = load(&LoadSpec::new("server", &sources).with_env("APP_"))
/// .expect("the inline document is well formed");
///
/// assert_eq!(server.port, 8080);
/// # }
/// ```
/// Resolves the section without deserializing it.
///
/// Two snapshots can be compared with [`Snapshot::diff`], which is how a reload
/// reports *which* keys changed rather than only that something did.
///
/// # Errors
///
/// If a source cannot be read or parsed — the same failures as [`load`].
/// Where the value at `path` would come from, if anything supplies it.
///
/// This is the answer to the question every configuration bug starts with:
/// *which layer set this?* It re-reads the sources, so it reports what the
/// **next** load would see rather than what the current snapshot holds.
///
/// `path` is dotted and relative to the section, as in `"pool.max_size"`.
///
/// # Errors
///
/// If a source cannot be read or parsed — the same failures as [`load`].
///
/// # Example
///
/// ```
/// # #[cfg(feature = "json")] {
/// use dynamic_config::{source_of, Format, LoadSpec, Origin, Source};
///
/// let sources = [Source::inline(r#"{"db": {"host": "localhost"}}"#, Format::Json)];
/// let spec = LoadSpec::new("db", &sources);
///
/// assert_eq!(source_of(&spec, "host").unwrap(), Some(Origin::Inline));
/// assert_eq!(source_of(&spec, "port").unwrap(), None);
/// # }
/// ```
/// Whether anything supplies `path`.
///
/// Distinguishes "absent" from "present but falsy", which
/// `#[serde(default)]` cannot.
///
/// # Errors
///
/// If a source cannot be read or parsed — the same failures as [`load`].
/// [`load`], moved off the async executor.
///
/// Reading configuration touches the filesystem, which would block the worker
/// it runs on. Where the work actually goes depends on what is available:
/// tokio's blocking pool with the `tokio` feature, an executor installed by
/// [`set_blocking_executor`], or a freshly spawned thread. A configuration load
/// happens at startup and on reload, so a thread per call is a real answer
/// rather than a placeholder.
///
/// `LoadSpec<'static>` is taken by value because the work outlives the call;
/// the spec the macro emits satisfies that for free.
///
/// # Errors
///
/// Same as [`load`], plus an [`ErrorKind::Backend`] error if the work never
/// produced a result — a panic inside it, or a runtime shutting down.
pub async
/// Runs blocking configuration work without blocking the caller's executor.
///
/// See [`load_async`] for where the work goes.
///
/// # Errors
///
/// Whatever `work` returns, plus [`ErrorKind::Backend`] if it never produced a
/// result.
pub async
// ---------------------------------------------------------------------------
// Support items used by the generated code. The redirect *macros* — the
// feature-gated `__*!` wall — live in `redirects`; the functions stay here
// because they are reached by path, and a path names the module it lives in.
// ---------------------------------------------------------------------------
/// Not public API. Lets the generated code name `serde` without the caller
/// having to depend on it under that exact name.
/// Not public API.
///
/// Writes the last configuration that worked, if one is configured. A failure
/// here is reported and swallowed: a cache that cannot be written is a worse
/// tomorrow, not a broken today.
/// Not public API.
///
/// The last configuration that worked, when a cold start could not read the
/// real one.
///
/// # Errors
///
/// If the cache exists but cannot be read. A missing cache is `Ok(None)`.
/// Not public API.
///
/// A reload a remote watch caused. Worded to name the trigger, because a
/// program watching both files and a store wants its log to say which one
/// moved.
/// Not public API.
///
/// A document the store pushed that this program cannot use. Logged as well as
/// returned: the loop that called this has nobody to hand an error to either,
/// and a store quietly serving a configuration nothing accepts is worth a line.
/// Not public API.
///
/// Renders the keys a reload changed, for the watcher to log. Returning a
/// string rather than logging keeps this out of the generated code's way and
/// leaves one log line per reload instead of two.
///
/// Always a string — "nothing to say" is not this function's case. The
/// caller's `Option` means "there was no previous snapshot to compare", and
/// that decision is made where the previous snapshot lives.