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
//! The crate's single error type.
//!
//! No backend error type is ever exposed: a `figment::Error` or a
//! `serde_json::Error` is translated into an [`Error`] at the boundary, so
//! switching backends never changes a caller's signatures.
use std::fmt;
use std::path::PathBuf;
/// Broad category of a configuration failure.
///
/// Matching on this is enough to decide how to react; the human-readable
/// detail lives in the [`Display`](fmt::Display) output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
/// A configured file exists but could not be read.
Io,
/// A file was read but is not valid in its format.
Parse,
/// A required value was not supplied by any source.
Missing,
/// A value was supplied but cannot become the requested type.
Type,
/// An environment variable could not be interpreted.
Env,
/// Every value parsed, but the configuration as a whole was rejected.
Invalid,
/// A remote store could not be read.
Remote,
/// An encrypted file could not be decrypted.
Decrypt,
/// The active backend failed for a reason of its own.
Backend,
}
impl ErrorKind {
/// A short, stable label. Useful for metrics and log fields.
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Io => "io",
Self::Parse => "parse",
Self::Missing => "missing",
Self::Type => "type",
Self::Env => "env",
Self::Invalid => "invalid",
Self::Remote => "remote",
Self::Decrypt => "decrypt",
Self::Backend => "backend",
}
}
}
/// Where a value came from.
///
/// Attached to errors so the first question of every configuration bug —
/// *which source set this?* — is answered by the message itself.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Origin {
/// A file on disk.
File(PathBuf),
/// An environment variable, named in full.
Env(String),
/// An in-memory source supplied by the caller.
Inline,
/// A remote store, as it described itself.
Remote(String),
/// A value set from code: `"default"` or `"override"`.
Runtime(&'static str),
/// Provenance could not be determined.
Unknown,
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::File(path) => write!(f, "in {}", path.display()),
Self::Env(name) => write!(f, "from {name}"),
Self::Inline => f.write_str("in an inline source"),
Self::Remote(store) => write!(f, "from {store}"),
Self::Runtime(layer) => write!(f, "set as {layer}"),
Self::Unknown => f.write_str("origin unknown"),
}
}
}
/// A configuration error.
///
/// Boxed internally so that `Result<T, Error>` stays small on the hot path —
/// `load` is called on every reload, and most calls succeed.
pub struct Error {
inner: Box<Inner>,
}
struct Inner {
kind: ErrorKind,
/// Key path from the config root, outermost segment first.
path: Vec<String>,
origin: Origin,
message: String,
}
impl Error {
/// Builds an error with no path and no known origin.
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
inner: Box::new(Inner {
kind,
path: Vec::new(),
origin: Origin::Unknown,
message: message.into(),
}),
}
}
/// A configuration that parsed but failed its own validation.
///
/// Called by the code `#[dynamic_config(.., validate)]` generates, from
/// whatever `validate` resolves to at the call site.
pub fn invalid<E: fmt::Display>(error: E) -> Self {
Self::new(ErrorKind::Invalid, error.to_string())
}
/// Maps a validation result into a load failure.
///
/// Takes the whole `Result` rather than the error, so the generated code is
/// one expression regardless of what `validate` returns.
///
/// # Errors
///
/// If `outcome` is `Err`.
pub fn ok_or_invalid<T, E: fmt::Display>(outcome: Result<T, E>) -> Result<(), Self> {
outcome.map(|_| ()).map_err(Self::invalid)
}
/// A remote store that could not be read.
///
/// For implementors of [`RemoteSource`](crate::RemoteSource), so a network
/// failure is categorised the same way whichever store it came from.
pub fn remote<E: fmt::Display>(error: E) -> Self {
Self::new(ErrorKind::Remote, error.to_string())
}
/// A failure decrypting an encrypted config file.
///
/// For [`Decryptor`](crate::Decryptor) implementations, so a scheme this
/// crate has never heard of still reports through the same category.
pub fn decrypt<E: fmt::Display>(error: E) -> Self {
Self::new(ErrorKind::Decrypt, error.to_string())
}
/// A path whose extension names no format this build can write.
#[must_use]
pub fn unsupported(path: &std::path::Path) -> Self {
Self::new(
ErrorKind::Backend,
"the extension names no supported format; expected `.json`, `.toml`, \
`.yaml` or `.yml`",
)
.with_origin(Origin::File(path.to_owned()))
}
/// The error's category.
#[must_use]
pub fn kind(&self) -> ErrorKind {
self.inner.kind
}
/// The dotted key path this error occurred at, empty at the root.
#[must_use]
pub fn path(&self) -> String {
self.inner.path.join(".")
}
/// Where the offending value came from.
#[must_use]
pub fn origin(&self) -> &Origin {
&self.inner.origin
}
/// The detail message, without the path or origin decoration.
#[must_use]
pub fn message(&self) -> &str {
&self.inner.message
}
/// Pushes a key onto the front of the path.
///
/// Deserialization unwinds from the innermost field outwards, so each
/// enclosing map prepends its own key and the path assembles itself in the
/// right order without any of them knowing the full path.
pub(crate) fn prepend_key(mut self, key: impl Into<String>) -> Self {
self.inner.path.insert(0, key.into());
self
}
/// Records provenance, unless something more specific is already known.
pub(crate) fn with_origin(mut self, origin: Origin) -> Self {
if self.inner.origin == Origin::Unknown {
self.inner.origin = origin;
}
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.inner.path.is_empty() {
f.write_str(&self.inner.message)?;
} else {
write!(f, "{}: {}", self.path(), self.inner.message)?;
}
if self.inner.origin != Origin::Unknown {
write!(f, " ({})", self.inner.origin)?;
}
Ok(())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("kind", &self.inner.kind)
.field("path", &self.path())
.field("origin", &self.inner.origin)
.field("message", &self.inner.message)
.finish()
}
}
impl std::error::Error for Error {}
impl serde::de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Self::new(ErrorKind::Type, msg.to_string())
}
fn missing_field(field: &'static str) -> Self {
Self::new(ErrorKind::Missing, "missing value").prepend_key(field)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::de::Error as _;
#[test]
fn prepend_key_assembles_the_path_outermost_first() {
let error = Error::new(ErrorKind::Type, "boom")
.prepend_key("max")
.prepend_key("pool")
.prepend_key("db");
assert_eq!(error.path(), "db.pool.max");
}
#[test]
fn display_includes_the_path_and_the_origin() {
let error = Error::new(ErrorKind::Type, "invalid type")
.prepend_key("port")
.with_origin(Origin::Env("APP_DB_PORT".to_owned()));
assert_eq!(error.to_string(), "port: invalid type (from APP_DB_PORT)");
}
#[test]
fn display_omits_both_decorations_when_they_are_absent() {
let error = Error::new(ErrorKind::Parse, "unexpected end of input");
assert_eq!(error.to_string(), "unexpected end of input");
}
#[test]
fn the_first_origin_recorded_wins() {
let error = Error::new(ErrorKind::Type, "boom")
.with_origin(Origin::Inline)
.with_origin(Origin::Env("APP_X".to_owned()));
assert_eq!(error.origin(), &Origin::Inline);
}
#[test]
fn a_missing_field_carries_its_name_and_kind() {
let error = Error::missing_field("host");
assert_eq!(error.kind(), ErrorKind::Missing);
assert_eq!(error.path(), "host");
}
}