rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! The configuration: the file, overridden by environment variables.
//!
//! ```toml
//! access_id = "…"
//! base_url = "https://www.rmv.de/hapi/"
//! timeout_seconds = 20
//! retries = 2
//! delay_threshold_minutes = 2
//! ```
//!
//! The file is `config.toml` in the directory of [`dirs::config`], or the
//! one `RMV_CONFIG` names. `RMV_ACCESS_ID` and `RMV_BASE_URL` override the
//! file.
//!
//! The access key is a secret: [`Settings`] and [`Config`] never show it in
//! their `Debug` output, and [`Settings::get`] returns [`REDACTED`] for it.

use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::dirs;

pub use hafas::REDACTED;

/// The production server of RMV, dialect version 2.39.
pub const DEFAULT_BASE_URL: &str = "https://www.rmv.de/hapi/";
pub const DEFAULT_TIMEOUT_SECONDS: u64 = 20;
/// How often a request is repeated after a transient error.
pub const DEFAULT_RETRIES: u32 = 2;
/// The most repetitions the setting allows. Every repetition counts against
/// the quota of the access key.
pub const MAX_RETRIES: u32 = 5;
/// From how many minutes late an arrival counts as delayed.
pub const DEFAULT_DELAY_THRESHOLD_MINUTES: u32 = 2;

/// The configuration file could not be read or written, or a value is
/// invalid.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("cannot read {}", path.display())]
    Read { path: PathBuf, source: io::Error },
    // The diagnostic of the parser is left out: it quotes the line, which
    // can hold the access key.
    #[error("{} is not a valid configuration", path.display())]
    Parse { path: PathBuf },
    #[error("cannot write {}", path.display())]
    Write { path: PathBuf, source: io::Error },
    #[error("unknown setting {0}, known are: {keys}", keys = Settings::KEYS.join(", "))]
    UnknownKey(String),
    #[error("invalid value for {key}: {reason}")]
    InvalidValue { key: String, reason: String },
}

/// The contents of the configuration file. Unset values take their default.
#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Settings {
    /// The access key of the RMV Open Data API. Required for every request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retries: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delay_threshold_minutes: Option<u32>,
}

impl fmt::Debug for Settings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Settings")
            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
            .field("base_url", &self.base_url)
            .field("timeout_seconds", &self.timeout_seconds)
            .field("retries", &self.retries)
            .field("delay_threshold_minutes", &self.delay_threshold_minutes)
            .finish()
    }
}

impl Settings {
    /// The names of the settings, as in the file.
    pub const KEYS: &[&str] = &[
        "access_id",
        "base_url",
        "timeout_seconds",
        "retries",
        "delay_threshold_minutes",
    ];

    /// The file `RMV_CONFIG` names, else `config.toml` in [`dirs::config`].
    /// `None` if the home directory is unknown.
    pub fn path(env: &impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
        variable(env, "RMV_CONFIG")
            .map(PathBuf::from)
            .or_else(|| dirs::config().map(|dir| dir.join("config.toml")))
    }

    /// Reads the file, or returns empty settings if it does not exist.
    pub fn load(path: &Path) -> Result<Self, Error> {
        let text = match std::fs::read_to_string(path) {
            Ok(text) => text,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
            Err(source) => {
                return Err(Error::Read {
                    path: path.to_owned(),
                    source,
                });
            }
        };
        toml::from_str(&text).map_err(|_| Error::Parse {
            path: path.to_owned(),
        })
    }

    /// Writes the file, creating its directory if needed. Replaces the file
    /// at once, so a failed write leaves the old one intact. On Unix only
    /// the owner can read it, as it holds the access key.
    pub fn save(&self, path: &Path) -> Result<(), Error> {
        let write = |source| Error::Write {
            path: path.to_owned(),
            source,
        };
        let text = toml::to_string(self)
            .map_err(io::Error::other)
            .map_err(write)?;
        // A relative file name has an empty parent, which needs no creation.
        std::fs::create_dir_all(path.parent().unwrap_or(Path::new(""))).map_err(write)?;
        let temporary = path.with_extension("toml.tmp");
        write_private(&temporary, &text).map_err(write)?;
        std::fs::rename(&temporary, path).map_err(write)
    }

    /// The value of a setting, as text. `None` if unset. The access key is
    /// never returned: it shows as [`REDACTED`].
    pub fn get(&self, key: &str) -> Result<Option<String>, Error> {
        Ok(match key {
            "access_id" => self.access_id.as_ref().map(|_| REDACTED.to_owned()),
            "base_url" => self.base_url.clone(),
            "timeout_seconds" => self.timeout_seconds.map(|v| v.to_string()),
            "retries" => self.retries.map(|v| v.to_string()),
            "delay_threshold_minutes" => self.delay_threshold_minutes.map(|v| v.to_string()),
            _ => return Err(Error::UnknownKey(key.to_owned())),
        })
    }

    /// Sets a setting from text, or unsets it with `None`. Checks the value.
    pub fn set(&mut self, key: &str, value: Option<&str>) -> Result<(), Error> {
        let invalid = |reason: String| Error::InvalidValue {
            key: key.to_owned(),
            reason,
        };
        match key {
            "access_id" => {
                let value = value.map(str::trim);
                if let Some(id) = value {
                    check_access_id(id).map_err(|reason| invalid(reason.to_owned()))?;
                }
                self.access_id = value.map(str::to_owned);
            }
            "base_url" => {
                if let Some(url) = value {
                    check_base_url(url).map_err(invalid)?;
                }
                self.base_url = value.map(str::to_owned);
            }
            "timeout_seconds" => {
                let seconds: Option<u64> = number(value).map_err(invalid)?;
                if seconds == Some(0) {
                    return Err(invalid("must be at least 1".to_owned()));
                }
                self.timeout_seconds = seconds;
            }
            "retries" => {
                let retries: Option<u32> = number(value).map_err(invalid)?;
                if retries.is_some_and(|n| n > MAX_RETRIES) {
                    return Err(invalid(format!("must be at most {MAX_RETRIES}")));
                }
                self.retries = retries;
            }
            "delay_threshold_minutes" => {
                self.delay_threshold_minutes = number(value).map_err(invalid)?;
            }
            _ => return Err(Error::UnknownKey(key.to_owned())),
        }
        Ok(())
    }
}

/// Checks the form of an access key, without saying anything about it.
fn check_access_id(id: &str) -> Result<(), &'static str> {
    if id.is_empty() {
        return Err("must not be empty");
    }
    if id.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err("must not contain spaces or control characters");
    }
    Ok(())
}

fn check_base_url(url: &str) -> Result<(), String> {
    let parsed = hafas::Url::parse(url).map_err(|e| e.to_string())?;
    if matches!(parsed.scheme(), "http" | "https") {
        Ok(())
    } else {
        Err("expected an http or https URL".to_owned())
    }
}

#[cfg(unix)]
fn write_private(path: &Path, text: &str) -> io::Result<()> {
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;
    // The mode applies only to a new file, so a leftover is removed first.
    if let Err(error) = std::fs::remove_file(path)
        && error.kind() != io::ErrorKind::NotFound
    {
        return Err(error);
    }
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(text.as_bytes())
}

#[cfg(not(unix))]
fn write_private(path: &Path, text: &str) -> io::Result<()> {
    std::fs::write(path, text)
}

fn number<T: std::str::FromStr<Err: fmt::Display>>(
    value: Option<&str>,
) -> Result<Option<T>, String> {
    value
        .map(|v| v.parse().map_err(|e| format!("{e}")))
        .transpose()
}

/// A non-empty environment variable.
fn variable(env: &impl Fn(&str) -> Option<String>, name: &str) -> Option<String> {
    env(name).filter(|value| !value.trim().is_empty())
}

/// The configuration in effect.
#[derive(Clone, PartialEq, Eq)]
pub struct Config {
    pub access_id: Option<String>,
    pub base_url: String,
    pub timeout: Duration,
    pub retries: u32,
    pub delay_threshold_minutes: u32,
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Config")
            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
            .field("base_url", &self.base_url)
            .field("timeout", &self.timeout)
            .field("retries", &self.retries)
            .field("delay_threshold_minutes", &self.delay_threshold_minutes)
            .finish()
    }
}

impl Config {
    /// Reads the file and applies the environment variables `env` returns.
    pub fn load(env: &impl Fn(&str) -> Option<String>) -> Result<Self, Error> {
        let settings = Settings::path(env)
            .map(|path| Settings::load(&path))
            .transpose()?
            .unwrap_or_default();
        Ok(Self::new(settings, env))
    }

    /// The settings with the environment variables `env` returns applied.
    pub fn new(settings: Settings, env: &impl Fn(&str) -> Option<String>) -> Self {
        Self {
            access_id: variable(env, "RMV_ACCESS_ID")
                .map(|id| id.trim().to_owned())
                .or(settings.access_id),
            base_url: variable(env, "RMV_BASE_URL")
                .or(settings.base_url)
                .unwrap_or_else(|| DEFAULT_BASE_URL.to_owned()),
            timeout: Duration::from_secs(
                settings
                    .timeout_seconds
                    .unwrap_or(DEFAULT_TIMEOUT_SECONDS)
                    .max(1),
            ),
            retries: settings.retries.unwrap_or(DEFAULT_RETRIES).min(MAX_RETRIES),
            delay_threshold_minutes: settings
                .delay_threshold_minutes
                .unwrap_or(DEFAULT_DELAY_THRESHOLD_MINUTES),
        }
    }
}