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
use Error as StdError;
pub use ;
/// Raw bytes for one configuration entry, with its declaring [`Source`].
///
/// A loader returns one `Payload` per entry it finds. Fields:
///
/// - `source` — the concrete resource this entry came from. When one [`Source`] expands to
/// several entries (e.g. a directory of files), set this to the *specific* resource loaded,
/// not the original directory — clone the incoming source and narrow it with
/// [`Source::with_resource`]. Downstream stages surface it in diagnostics.
/// - `maybe_name` — the entry's name, or `None` for an unnamed payload. All `None`-named
/// payloads merge together into the root; distinct names stay separate. Named entries with the
/// same name also merge.
/// - `maybe_format` — a hint for the parser stage selecting the parser (`json`, `env`, …), or
/// `None` to let the parser infer/default. It is a hint, not a guarantee.
/// - `content` — the unparsed bytes, passed through verbatim to the parser.
///
/// **Lowercase convention:** built-in loaders lower-case `maybe_name` and `maybe_format` when
/// their Source `lowercase` option is `true` (the default). Custom loaders are encouraged to
/// follow the same convention so entry names merge predictably across sources.
/// Errors a [`Load`] implementation can return.
///
/// Each variant carries a `loader` field (set to your [`Load::name`]) so messages identify the
/// source. See [`Load`]'s "Choosing an error" section for guidance on which to pick.
/// Loads raw configuration bytes from a declared source.
///
/// Implement this to add a new source kind (protocol, service, database, …). This is the first
/// stage of the pipeline: it only *fetches bytes*, it does not parse them — [`Payload::content`]
/// is handed to the parser stage unchanged.
///
/// # Contract
///
/// - [`load`](Load::load) takes ownership of one [`Source`] and returns one [`Payload`] per
/// configuration entry found. A single source may expand to many entries (e.g. every file in a
/// directory) → return many payloads; finding nothing is `Ok(vec![])`, not an error.
/// - Set [`Payload::source`] on each entry to the *concrete* resource loaded, not the original
/// source — clone it and narrow with [`Source::with_resource`]. This keeps diagnostics precise.
/// - Use [`Payload::maybe_name`] for the entry name (`None` merges into the root with all other
/// unnamed entries) and [`Payload::maybe_format`] as a parser hint (e.g. `json`).
/// - Follow the lowercase convention: when your `lowercase` option is `true` (recommended
/// default), lower-case names and formats so entries merge predictably across sources.
///
/// # Reading options
///
/// Options declared on the source (e.g. `file(ignore=[not-found])`) are available via
/// [`Source::options`]. Look each up with [`Options::get`], convert with the typed accessors
/// ([`OptionValue::as_bool`], [`OptionValue::as_string`], [`OptionValue::as_list`], …), and on a
/// type mismatch build the `reason` from [`OptionValue::type_name`]. It is good practice to reject
/// unknown keys by iterating [`Options::keys`] and returning [`Error::InvalidOption`] — see the
/// `file` loader's `load` for a complete worked pattern.
///
/// # Choosing an error
///
/// - [`Error::InvalidResource`] — the resource string is empty/malformed for this loader.
/// - [`Error::InvalidOption`] — an option is unknown, or has the wrong type/value.
/// - [`Error::NotFound`] — the resource/entry doesn't exist (and isn't being ignored).
/// - [`Error::NoAccess`] — permission denied by the backend.
/// - [`Error::Timeout`] — a deadline was exceeded.
/// - [`Error::Duplicate`] — two entries collide on the same name with different formats.
/// - [`Error::Load`] — any other backend failure (`description` completes "could not …").
/// - [`Error::Other`] — bridge for an opaque error via `?`.
///
/// # Registering
///
/// Pass an instance to `tanzim::Config::with_loader`. The pipeline dispatches each source to the
/// first loader whose [`supported_source_list`](Load::supported_source_list) contains the source
/// string, so it may advertise several (e.g. `["http", "https"]`). For a one-off loader you don't
/// want to define a type for, use [`closure::Closure`] instead of implementing this trait.
///
/// # Example — collecting specific environment variables
///
/// A loader that reads the variable names listed in its `keys` option and returns them as one
/// `env`-format payload. It shows the whole contract: reading a typed option, mapping failures to
/// the right [`Error`] variant, and building a [`Payload`].
///
/// ```rust
/// use std::env;
/// use tanzim_load::{Error, Load, Payload, Source};
///
/// struct SelectedEnv;
///
/// impl Load for SelectedEnv {
/// fn name(&self) -> &str { "selected-env" }
/// fn supported_source_list(&self) -> Vec<String> { vec!["selected-env".into()] }
///
/// fn load(&self, source: Source) -> Result<Vec<Payload>, Error> {
/// // Read the `keys` option — a required list of variable names.
/// let value = source.options().get("keys").ok_or_else(|| Error::InvalidOption {
/// loader: self.name().into(),
/// key: "keys".into(),
/// reason: "required".into(),
/// })?;
/// let keys = value.as_list().ok_or_else(|| Error::InvalidOption {
/// loader: self.name().into(),
/// key: "keys".into(),
/// reason: format!("expected list, found {}", value.type_name()),
/// })?;
///
/// // Collect each requested variable into a `KEY="value"` line.
/// let mut lines = Vec::new();
/// for item in keys {
/// let key = item.as_string().ok_or_else(|| Error::InvalidOption {
/// loader: self.name().into(),
/// key: "keys".into(),
/// reason: format!("expected string, found {}", item.type_name()),
/// })?;
/// let val = env::var(key).map_err(|_| Error::NotFound {
/// loader: self.name().into(),
/// resource: source.resource().into(),
/// item: format!("environment variable `{key}`"),
/// })?;
/// lines.push(format!("{key}={val:?}"));
/// }
///
/// Ok(vec![Payload {
/// source,
/// maybe_name: None, // unnamed → merges into the config root
/// maybe_format: Some("env".into()), // parsed by the `env` parser
/// content: lines.join("\n").into_bytes(),
/// }])
/// }
/// }
///
/// // SAFETY: example-only; single-threaded doctest env vars.
/// unsafe {
/// env::set_var("DB_HOST", "localhost");
/// env::set_var("DB_PORT", "5432");
/// }
///
/// let source = Source::parse("selected-env(keys=[DB_HOST,DB_PORT])").unwrap();
///
/// let payloads = SelectedEnv.load(source).unwrap();
/// let content = String::from_utf8_lossy(&payloads[0].content);
/// assert!(content.contains(r#"DB_HOST="localhost""#));
/// assert!(content.contains(r#"DB_PORT="5432""#));
/// ```