Skip to main content

mariadb_cli/config/
mod.rs

1//! Stored settings, and the one order in which a value is decided.
2//!
3//! A setting is resolved in exactly three layers and never in four:
4//!
5//! 1. a mark on the command line,
6//! 2. a value written into the settings file,
7//! 3. the value built into this build.
8//!
9//! The process environment is deliberately absent from that list. A value that
10//! changes with the surrounding shell is not a stored setting: it makes the
11//! same command behave differently in two terminals, and it hides the reason
12//! from whoever reads the command afterwards. No code in this module reads the
13//! environment, and adding such a read is a defect rather than a feature.
14
15pub mod doctor;
16pub mod keys;
17pub mod paths;
18pub mod secret;
19pub mod store;
20pub mod vault;
21
22pub use keys::{Domain, Fallback, KeySpec, Value};
23pub use secret::Secret;
24
25use crate::error::Result;
26use std::collections::BTreeMap;
27use std::path::{Path, PathBuf};
28
29/// Which layer decided a value.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
31#[serde(rename_all = "snake_case")]
32pub enum Origin {
33    /// A mark on the command line.
34    Flag,
35    /// A value written into the settings file.
36    Stored,
37    /// The value built into this build.
38    Default,
39}
40
41impl Origin {
42    /// The stable identifier emitted on the wire.
43    #[must_use]
44    pub const fn as_str(self) -> &'static str {
45        match self {
46            Self::Flag => "flag",
47            Self::Stored => "stored",
48            Self::Default => "default",
49        }
50    }
51}
52
53/// One resolved setting.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Resolved {
56    /// The value in force, when this build carries one at all.
57    ///
58    /// Absent means the value is decided elsewhere: by the server, by the host,
59    /// or by nothing at all. Reporting that plainly beats inventing a number.
60    pub value: Option<Value>,
61    /// Which layer decided it.
62    pub origin: Origin,
63}
64
65/// The settings in force for one invocation.
66///
67/// Holding no credential of its own, this may be rendered in a diagnostic
68/// safely; a credential lives in [`Secret`], which redacts itself.
69#[derive(Debug)]
70pub struct Config {
71    file: PathBuf,
72    stored: store::Stored,
73    flags: BTreeMap<&'static str, Value>,
74}
75
76impl Config {
77    /// Loads the stored settings from the given location.
78    ///
79    /// # Errors
80    ///
81    /// Returns a configuration failure when the location cannot be determined
82    /// or the file exists and cannot be read.
83    pub fn load(override_dir: Option<&Path>) -> Result<Self> {
84        let file = paths::config_file(override_dir)?;
85        let stored = store::load(&file)?;
86        Ok(Self {
87            file,
88            stored,
89            flags: BTreeMap::new(),
90        })
91    }
92
93    /// The settings as they stand when the stored file cannot be read at all.
94    ///
95    /// Every setting falls back to its built-in value, which is the same place
96    /// [`Self::load`] lands when nothing was ever stored. The difference is why
97    /// it landed there, and that difference belongs to the caller: this is only
98    /// correct for work whose subject IS the unreadable file, and wrong for
99    /// everything else, which would silently run against values the caller
100    /// never chose.
101    ///
102    /// It exists because `config doctor` is that work. Reporting an unreadable
103    /// file is the reason that command was written, so refusing to serve it
104    /// until the file can be read is refusing to serve it exactly when it is
105    /// needed.
106    ///
107    /// # Errors
108    ///
109    /// Returns a configuration failure when the location itself cannot be
110    /// determined. That is a different condition from an unreadable file: there
111    /// is no path to report on, so there is nothing to diagnose either.
112    pub fn with_nothing_stored(override_dir: Option<&Path>) -> Result<Self> {
113        Ok(Self {
114            file: paths::config_file(override_dir)?,
115            stored: store::Stored::new(),
116            flags: BTreeMap::new(),
117        })
118    }
119
120    /// Records one mark from the command line, which outranks everything else.
121    ///
122    /// # Errors
123    ///
124    /// Returns a configuration failure when the name is unknown or the text
125    /// falls outside the setting's domain.
126    pub fn with_flag(mut self, name: &str, raw: &str) -> Result<Self> {
127        let value = keys::validate(name, raw)?;
128        let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
129        self.flags.insert(entry.name, value);
130        Ok(self)
131    }
132
133    /// Where the settings file lives for this invocation.
134    #[must_use]
135    pub fn file(&self) -> &Path {
136        &self.file
137    }
138
139    /// Whether a value was written into the file for this setting.
140    #[must_use]
141    pub fn is_stored(&self, name: &str) -> bool {
142        self.stored.contains_key(name)
143    }
144
145    /// The value in force for one setting, and the layer that decided it.
146    ///
147    /// # Errors
148    ///
149    /// Returns a configuration failure when the name is unknown, or when a
150    /// value written into the file falls outside the setting's domain.
151    pub fn resolve(&self, name: &str) -> Result<Resolved> {
152        let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
153
154        if let Some(value) = self.flags.get(entry.name) {
155            return Ok(Resolved {
156                value: Some(value.clone()),
157                origin: Origin::Flag,
158            });
159        }
160
161        if let Some(raw) = self.stored.get(entry.name) {
162            return Ok(Resolved {
163                value: Some(keys::validate(entry.name, raw)?),
164                origin: Origin::Stored,
165            });
166        }
167
168        Ok(Resolved {
169            value: entry.default_value()?,
170            origin: Origin::Default,
171        })
172    }
173
174    /// Every published setting with the value in force and its origin.
175    ///
176    /// A setting whose stored value no longer passes its domain is carried as
177    /// a failure rather than skipped, so a broken file is impossible to miss.
178    pub fn resolve_all(&self) -> impl Iterator<Item = (&'static KeySpec, Result<Resolved>)> + '_ {
179        keys::all()
180            .iter()
181            .map(|entry| (entry, self.resolve(entry.name)))
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    fn scratch() -> tempfile::TempDir {
190        tempfile::tempdir().expect("scratch directory")
191    }
192
193    #[test]
194    fn nothing_stored_means_the_builtin_value_is_in_force() {
195        let dir = scratch();
196        let config = Config::load(Some(dir.path())).expect("loads");
197        let resolved = config.resolve("output.format").expect("published");
198        assert_eq!(resolved.origin, Origin::Default);
199        assert_eq!(resolved.value, Some(Value::Enumeration("json")));
200    }
201
202    #[test]
203    fn a_stored_value_beats_the_builtin_one() {
204        let dir = scratch();
205        let file = paths::config_file(Some(dir.path())).expect("location");
206        store::store(&file, "output.format", "tsv").expect("writes");
207
208        let config = Config::load(Some(dir.path())).expect("loads");
209        let resolved = config.resolve("output.format").expect("published");
210        assert_eq!(resolved.origin, Origin::Stored);
211        assert_eq!(resolved.value, Some(Value::Enumeration("tsv")));
212    }
213
214    #[test]
215    fn a_flag_beats_a_stored_value() {
216        let dir = scratch();
217        let file = paths::config_file(Some(dir.path())).expect("location");
218        store::store(&file, "output.format", "tsv").expect("writes");
219
220        let config = Config::load(Some(dir.path()))
221            .expect("loads")
222            .with_flag("output.format", "ndjson")
223            .expect("accepted");
224        let resolved = config.resolve("output.format").expect("published");
225        assert_eq!(resolved.origin, Origin::Flag);
226        assert_eq!(resolved.value, Some(Value::Enumeration("ndjson")));
227    }
228
229    #[test]
230    fn a_flag_outside_the_domain_is_refused_before_anything_is_decided() {
231        let dir = scratch();
232        let failure = Config::load(Some(dir.path()))
233            .expect("loads")
234            .with_flag("limits.retries", "many")
235            .expect_err("must refuse");
236        assert_eq!(failure.code(), "config.value_outside_domain");
237    }
238
239    #[test]
240    fn a_stored_value_outside_its_domain_is_reported_rather_than_ignored() {
241        let dir = scratch();
242        let file = paths::config_file(Some(dir.path())).expect("location");
243        // Written straight to the file, as an older build or a hand edit would.
244        std::fs::create_dir_all(dir.path()).expect("directory");
245        std::fs::write(&file, "\"output.format\" = \"yaml\"\n").expect("writes");
246
247        let config = Config::load(Some(dir.path())).expect("loads");
248        let failure = config.resolve("output.format").expect_err("must report");
249        assert_eq!(failure.code(), "config.value_outside_domain");
250    }
251
252    #[test]
253    fn a_setting_decided_by_the_server_carries_no_value_and_says_so() {
254        let dir = scratch();
255        let config = Config::load(Some(dir.path())).expect("loads");
256        let resolved = config.resolve("conn.timezone").expect("published");
257        assert_eq!(resolved.origin, Origin::Default);
258        assert_eq!(resolved.value, None);
259    }
260
261    #[test]
262    fn an_unknown_name_is_refused_at_every_entry_point() {
263        let dir = scratch();
264        let config = Config::load(Some(dir.path())).expect("loads");
265        assert_eq!(
266            config
267                .resolve("output.nonsense")
268                .expect_err("must refuse")
269                .code(),
270            "config.unknown_key"
271        );
272    }
273
274    #[test]
275    fn every_published_setting_is_listed_once() {
276        let dir = scratch();
277        let config = Config::load(Some(dir.path())).expect("loads");
278        assert_eq!(config.resolve_all().count(), keys::all().len());
279    }
280}