mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Stored settings, and the one order in which a value is decided.
//!
//! A setting is resolved in exactly three layers and never in four:
//!
//! 1. a mark on the command line,
//! 2. a value written into the settings file,
//! 3. the value built into this build.
//!
//! The process environment is deliberately absent from that list. A value that
//! changes with the surrounding shell is not a stored setting: it makes the
//! same command behave differently in two terminals, and it hides the reason
//! from whoever reads the command afterwards. No code in this module reads the
//! environment, and adding such a read is a defect rather than a feature.

pub mod doctor;
pub mod keys;
pub mod paths;
pub mod secret;
pub mod store;
pub mod vault;

pub use keys::{Domain, Fallback, KeySpec, Value};
pub use secret::Secret;

use crate::error::Result;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Which layer decided a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
    /// A mark on the command line.
    Flag,
    /// A value written into the settings file.
    Stored,
    /// The value built into this build.
    Default,
}

impl Origin {
    /// The stable identifier emitted on the wire.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Flag => "flag",
            Self::Stored => "stored",
            Self::Default => "default",
        }
    }
}

/// One resolved setting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    /// The value in force, when this build carries one at all.
    ///
    /// Absent means the value is decided elsewhere: by the server, by the host,
    /// or by nothing at all. Reporting that plainly beats inventing a number.
    pub value: Option<Value>,
    /// Which layer decided it.
    pub origin: Origin,
}

/// The settings in force for one invocation.
///
/// Holding no credential of its own, this may be rendered in a diagnostic
/// safely; a credential lives in [`Secret`], which redacts itself.
#[derive(Debug)]
pub struct Config {
    file: PathBuf,
    stored: store::Stored,
    flags: BTreeMap<&'static str, Value>,
}

impl Config {
    /// Loads the stored settings from the given location.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the location cannot be determined
    /// or the file exists and cannot be read.
    pub fn load(override_dir: Option<&Path>) -> Result<Self> {
        let file = paths::config_file(override_dir)?;
        let stored = store::load(&file)?;
        Ok(Self {
            file,
            stored,
            flags: BTreeMap::new(),
        })
    }

    /// The settings as they stand when the stored file cannot be read at all.
    ///
    /// Every setting falls back to its built-in value, which is the same place
    /// [`Self::load`] lands when nothing was ever stored. The difference is why
    /// it landed there, and that difference belongs to the caller: this is only
    /// correct for work whose subject IS the unreadable file, and wrong for
    /// everything else, which would silently run against values the caller
    /// never chose.
    ///
    /// It exists because `config doctor` is that work. Reporting an unreadable
    /// file is the reason that command was written, so refusing to serve it
    /// until the file can be read is refusing to serve it exactly when it is
    /// needed.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the location itself cannot be
    /// determined. That is a different condition from an unreadable file: there
    /// is no path to report on, so there is nothing to diagnose either.
    pub fn with_nothing_stored(override_dir: Option<&Path>) -> Result<Self> {
        Ok(Self {
            file: paths::config_file(override_dir)?,
            stored: store::Stored::new(),
            flags: BTreeMap::new(),
        })
    }

    /// Records one mark from the command line, which outranks everything else.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the name is unknown or the text
    /// falls outside the setting's domain.
    pub fn with_flag(mut self, name: &str, raw: &str) -> Result<Self> {
        let value = keys::validate(name, raw)?;
        let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
        self.flags.insert(entry.name, value);
        Ok(self)
    }

    /// Where the settings file lives for this invocation.
    #[must_use]
    pub fn file(&self) -> &Path {
        &self.file
    }

    /// Whether a value was written into the file for this setting.
    #[must_use]
    pub fn is_stored(&self, name: &str) -> bool {
        self.stored.contains_key(name)
    }

    /// The value in force for one setting, and the layer that decided it.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the name is unknown, or when a
    /// value written into the file falls outside the setting's domain.
    pub fn resolve(&self, name: &str) -> Result<Resolved> {
        let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;

        if let Some(value) = self.flags.get(entry.name) {
            return Ok(Resolved {
                value: Some(value.clone()),
                origin: Origin::Flag,
            });
        }

        if let Some(raw) = self.stored.get(entry.name) {
            return Ok(Resolved {
                value: Some(keys::validate(entry.name, raw)?),
                origin: Origin::Stored,
            });
        }

        Ok(Resolved {
            value: entry.default_value()?,
            origin: Origin::Default,
        })
    }

    /// Every published setting with the value in force and its origin.
    ///
    /// A setting whose stored value no longer passes its domain is carried as
    /// a failure rather than skipped, so a broken file is impossible to miss.
    pub fn resolve_all(&self) -> impl Iterator<Item = (&'static KeySpec, Result<Resolved>)> + '_ {
        keys::all()
            .iter()
            .map(|entry| (entry, self.resolve(entry.name)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scratch() -> tempfile::TempDir {
        tempfile::tempdir().expect("scratch directory")
    }

    #[test]
    fn nothing_stored_means_the_builtin_value_is_in_force() {
        let dir = scratch();
        let config = Config::load(Some(dir.path())).expect("loads");
        let resolved = config.resolve("output.format").expect("published");
        assert_eq!(resolved.origin, Origin::Default);
        assert_eq!(resolved.value, Some(Value::Enumeration("json")));
    }

    #[test]
    fn a_stored_value_beats_the_builtin_one() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        store::store(&file, "output.format", "tsv").expect("writes");

        let config = Config::load(Some(dir.path())).expect("loads");
        let resolved = config.resolve("output.format").expect("published");
        assert_eq!(resolved.origin, Origin::Stored);
        assert_eq!(resolved.value, Some(Value::Enumeration("tsv")));
    }

    #[test]
    fn a_flag_beats_a_stored_value() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        store::store(&file, "output.format", "tsv").expect("writes");

        let config = Config::load(Some(dir.path()))
            .expect("loads")
            .with_flag("output.format", "ndjson")
            .expect("accepted");
        let resolved = config.resolve("output.format").expect("published");
        assert_eq!(resolved.origin, Origin::Flag);
        assert_eq!(resolved.value, Some(Value::Enumeration("ndjson")));
    }

    #[test]
    fn a_flag_outside_the_domain_is_refused_before_anything_is_decided() {
        let dir = scratch();
        let failure = Config::load(Some(dir.path()))
            .expect("loads")
            .with_flag("limits.retries", "many")
            .expect_err("must refuse");
        assert_eq!(failure.code(), "config.value_outside_domain");
    }

    #[test]
    fn a_stored_value_outside_its_domain_is_reported_rather_than_ignored() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        // Written straight to the file, as an older build or a hand edit would.
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(&file, "\"output.format\" = \"yaml\"\n").expect("writes");

        let config = Config::load(Some(dir.path())).expect("loads");
        let failure = config.resolve("output.format").expect_err("must report");
        assert_eq!(failure.code(), "config.value_outside_domain");
    }

    #[test]
    fn a_setting_decided_by_the_server_carries_no_value_and_says_so() {
        let dir = scratch();
        let config = Config::load(Some(dir.path())).expect("loads");
        let resolved = config.resolve("conn.timezone").expect("published");
        assert_eq!(resolved.origin, Origin::Default);
        assert_eq!(resolved.value, None);
    }

    #[test]
    fn an_unknown_name_is_refused_at_every_entry_point() {
        let dir = scratch();
        let config = Config::load(Some(dir.path())).expect("loads");
        assert_eq!(
            config
                .resolve("output.nonsense")
                .expect_err("must refuse")
                .code(),
            "config.unknown_key"
        );
    }

    #[test]
    fn every_published_setting_is_listed_once() {
        let dir = scratch();
        let config = Config::load(Some(dir.path())).expect("loads");
        assert_eq!(config.resolve_all().count(), keys::all().len());
    }
}