rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! The configuration file and the environment variables.

use std::collections::HashMap;
use std::time::Duration;

use rmv_core::config::{
    DEFAULT_BASE_URL, DEFAULT_DELAY_THRESHOLD_MINUTES, DEFAULT_RETRIES, DEFAULT_TIMEOUT_SECONDS,
    Error, MAX_RETRIES, REDACTED,
};
use rmv_core::{Config, Settings};

const KEY: &str = "secret-test-key";

fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
    let map: HashMap<String, String> = pairs
        .iter()
        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
        .collect();
    move |name| map.get(name).cloned()
}

#[test]
fn takes_the_defaults() {
    let config = Config::new(Settings::default(), &env(&[]));
    assert_eq!(config.access_id, None);
    assert_eq!(config.base_url, DEFAULT_BASE_URL);
    assert_eq!(config.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECONDS));
    assert_eq!(config.retries, DEFAULT_RETRIES);
    assert_eq!(
        config.delay_threshold_minutes,
        DEFAULT_DELAY_THRESHOLD_MINUTES
    );
}

#[test]
fn variables_override_the_file() {
    let settings = Settings {
        access_id: Some("from-file".into()),
        base_url: Some("https://file.example/".into()),
        timeout_seconds: Some(0),
        retries: Some(99),
        delay_threshold_minutes: Some(5),
    };
    let config = Config::new(
        settings.clone(),
        &env(&[
            ("RMV_ACCESS_ID", " from-env "),
            ("RMV_BASE_URL", "http://127.0.0.1:1/hapi/"),
        ]),
    );
    assert_eq!(config.access_id.as_deref(), Some("from-env"));
    assert_eq!(config.base_url, "http://127.0.0.1:1/hapi/");
    assert_eq!(config.timeout, Duration::from_secs(1));
    assert_eq!(config.retries, MAX_RETRIES);
    assert_eq!(config.delay_threshold_minutes, 5);
    // Empty variables count as unset.
    let config = Config::new(settings, &env(&[("RMV_ACCESS_ID", "  ")]));
    assert_eq!(config.access_id.as_deref(), Some("from-file"));
}

#[test]
fn never_shows_the_key() {
    let settings = Settings {
        access_id: Some(KEY.into()),
        ..Settings::default()
    };
    assert!(!format!("{settings:?}").contains(KEY));
    assert!(format!("{settings:?}").contains(REDACTED));
    assert_eq!(
        settings.get("access_id").unwrap().as_deref(),
        Some(REDACTED)
    );
    let config = Config::new(settings, &env(&[]));
    assert!(!format!("{config:?}").contains(KEY));
    assert_eq!(Settings::default().get("access_id").unwrap(), None);
}

#[test]
fn reads_and_writes_the_file() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("sub").join("config.toml");
    assert_eq!(Settings::load(&path).unwrap(), Settings::default());
    let mut settings = Settings::default();
    for (key, value) in [
        ("access_id", KEY),
        ("base_url", "http://127.0.0.1:1/hapi/"),
        ("timeout_seconds", "7"),
        ("retries", "0"),
        ("delay_threshold_minutes", "3"),
    ] {
        settings.set(key, Some(value)).unwrap();
        if key != "access_id" {
            assert_eq!(settings.get(key).unwrap().as_deref(), Some(value));
        }
    }
    settings.save(&path).unwrap();
    assert_eq!(Settings::load(&path).unwrap(), settings);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600);
    }
    // Saving again replaces the file.
    settings.set("retries", None).unwrap();
    settings.save(&path).unwrap();
    assert_eq!(Settings::load(&path).unwrap().retries, None);

    let config = Config::load(&env(&[("RMV_CONFIG", path.to_str().unwrap())])).unwrap();
    assert_eq!(config.access_id.as_deref(), Some(KEY));
    assert_eq!(config.timeout, Duration::from_secs(7));
}

#[test]
fn a_broken_file_does_not_quote_the_key() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    std::fs::write(&path, format!("access_id = \"{KEY}\"\nretries = \"x\"\n")).unwrap();
    let error = Settings::load(&path).unwrap_err();
    assert!(matches!(error, Error::Parse { .. }));
    assert!(!error.to_string().contains(KEY), "{error}");
    let error = rmv_core::Error::from(error);
    assert!(!format!("{error:?} {error}").contains(KEY));
    std::fs::write(&path, "unknown = 1\n").unwrap();
    assert!(matches!(Settings::load(&path), Err(Error::Parse { .. })));
}

#[test]
fn a_directory_cannot_be_read_or_written() {
    let dir = tempfile::tempdir().unwrap();
    assert!(matches!(
        Settings::load(dir.path()),
        Err(Error::Read { .. })
    ));
    assert!(matches!(
        Settings::default().save(dir.path()),
        Err(Error::Write { .. })
    ));
}

#[test]
fn checks_the_values() {
    let mut settings = Settings::default();
    let invalid = |result: Result<(), Error>| match result {
        Err(Error::InvalidValue { reason, .. }) => reason,
        other => panic!("{other:?}"),
    };
    assert!(invalid(settings.set("access_id", Some(" "))).contains("empty"));
    assert!(invalid(settings.set("access_id", Some("a b"))).contains("spaces"));
    assert!(invalid(settings.set("base_url", Some("ftp://x/"))).contains("http"));
    assert_ne!(invalid(settings.set("base_url", Some("not a url"))), "");
    assert!(invalid(settings.set("timeout_seconds", Some("0"))).contains("at least"));
    assert_ne!(invalid(settings.set("timeout_seconds", Some("x"))), "");
    assert!(invalid(settings.set("retries", Some("6"))).contains("at most"));
    assert_ne!(
        invalid(settings.set("delay_threshold_minutes", Some("-1"))),
        ""
    );
    assert!(matches!(
        settings.set("colour", Some("1")),
        Err(Error::UnknownKey(_))
    ));
    assert!(matches!(settings.get("colour"), Err(Error::UnknownKey(_))));
    settings.set("access_id", None).unwrap();
    settings.set("base_url", None).unwrap();
    assert_eq!(settings, Settings::default());
}

#[test]
fn finds_the_file() {
    assert_eq!(
        Settings::path(&env(&[("RMV_CONFIG", "/x/c.toml")])),
        Some("/x/c.toml".into())
    );
}

#[test]
fn falls_back_to_the_config_directory() {
    let path = Settings::path(&env(&[]));
    assert!(
        path.as_ref()
            .is_none_or(|path| path.ends_with("config.toml")),
        "{path:?}"
    );
}

#[test]
fn a_leftover_that_cannot_be_removed_fails_the_save() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let leftover = dir.path().join("config.toml.tmp");
    std::fs::create_dir(&leftover).unwrap();
    std::fs::write(leftover.join("x"), "").unwrap();
    assert!(matches!(
        Settings::default().save(&path),
        Err(Error::Write { .. })
    ));
}

#[test]
fn a_broken_file_fails_the_load() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    std::fs::write(&path, "retries = \"x\"\n").unwrap();
    let result = Config::load(&env(&[("RMV_CONFIG", path.to_str().unwrap())]));
    assert!(matches!(result, Err(Error::Parse { .. })));
}