oomtop-config 0.2.1

oomtop configuration: layered config, themes, keymaps, JSON Schema, comment-preserving writes
Documentation
//! Semantic validation of a [`Config`]: the ranges, names and formats that the types alone cannot express.
//!
//! This is the **one** place those rules live. It is used by
//! - the loader ([`crate::layered`]): a layer, env var or flag that breaks a rule is rejected like a type
//!   error (file:line, last good values stay in effect);
//! - `oomtop config set` and the settings screen (through [`crate::write::set_value`]): nothing invalid is
//!   ever written;
//! - `oomtop config validate` ([`crate::validate`]);
//! - the JSON Schema ([`crate::schema`]), which carries the same minimum/maximum/enum values.
//!
//! [`problems`] is pure. [`fs_problems`] adds the checks that need the config directory (the selected theme
//! and layout must exist).

use crate::model::Config;
use crate::paths::ConfigPaths;

/// Smallest `general.refresh_ms` / `general.host_refresh_ms` (perf budget, SPEC §14).
pub const MIN_REFRESH_MS: u64 = 250;
/// Largest `format.decimals` (three decimals of a GiB is a MiB; more is noise).
pub const MAX_DECIMALS: u8 = 3;
/// Bounds of `adapters.timeout_ms`: exactly what the adapters clamp to (`oomtop_adapters::MIN_TIMEOUT` /
/// `MAX_TIMEOUT`, 10 ms … 2 s), so a value that is accepted is the value that is used. The upper bound keeps a
/// hung local endpoint from stalling sampling.
pub const MIN_ADAPTER_TIMEOUT_MS: u64 = 10;
pub const MAX_ADAPTER_TIMEOUT_MS: u64 = 2000;
/// Bounds of `headroom.margin_pct` (% of RAM).
pub const MAX_MARGIN_PCT: f64 = 100.0;
/// Upper bound of `headroom.pressure_boost_pct`.
pub const MAX_PRESSURE_BOOST_PCT: f64 = 1000.0;
/// Names accepted in `appearance.header`.
pub const HEADER_ROWS: &[&str] = &["meters", "headline", "memory", "swap", "accelerators", "thermal"];

/// One broken rule: the dotted key and a message that starts with it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
    pub key: String,
    pub message: String,
}

fn problem(key: &str, what: impl AsRef<str>) -> Problem {
    Problem {
        key: key.to_string(),
        message: format!("{key}: {}", what.as_ref()),
    }
}

/// `host:port` as `oomtop serve` accepts it: a socket address (`127.0.0.1:9469`, `[::1]:9469`) or a host
/// name with a port (`localhost:9469`).
pub fn valid_listen(s: &str) -> bool {
    if s.parse::<std::net::SocketAddr>().is_ok() {
        return true;
    }
    match s.rsplit_once(':') {
        Some((host, port)) => {
            port.parse::<u16>().is_ok()
                && !host.is_empty()
                && !host.starts_with(['-', '.'])
                && host
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
        }
        None => false,
    }
}

/// A layout name is a file stem under `layouts/` (same rule as theme names) — never a path.
pub fn valid_layout_name(name: &str) -> bool {
    crate::theme::valid_theme_name(name)
}

/// Every rule a config breaks (empty = valid). Pure: no file access.
pub fn problems(cfg: &Config) -> Vec<Problem> {
    let mut out = Vec::new();
    let mut check = |key: &str, ok: bool, what: String| {
        if !ok {
            out.push(problem(key, what));
        }
    };
    let g = &cfg.general;
    for (key, v) in [
        ("general.refresh_ms", g.refresh_ms),
        ("general.host_refresh_ms", g.host_refresh_ms),
    ] {
        check(
            key,
            v >= MIN_REFRESH_MS,
            format!("must be ≥ {MIN_REFRESH_MS} ms (perf budget, SPEC §14)"),
        );
    }
    let t = &cfg.thresholds;
    check(
        "thresholds.idle_cpu_pct",
        t.idle_cpu_pct.is_finite() && t.idle_cpu_pct >= 0.0,
        "must be a number ≥ 0".into(),
    );
    check(
        "thresholds.stale_score",
        t.stale_score.is_finite() && (0.0..=1.0).contains(&t.stale_score),
        "must be between 0 and 1".into(),
    );
    let h = &cfg.headroom;
    check(
        "headroom.min_margin",
        oomtop_core::units::parse_bytes(&h.min_margin).is_ok(),
        "must be a size like \"1.5G\"".into(),
    );
    check(
        "headroom.margin_override",
        h.margin_override.trim().is_empty() || oomtop_core::units::parse_bytes(&h.margin_override).is_ok(),
        "must be empty or a size like \"2G\"".into(),
    );
    check(
        "headroom.margin_pct",
        h.margin_pct.is_finite() && (0.0..=MAX_MARGIN_PCT).contains(&h.margin_pct),
        format!("must be between 0 and {MAX_MARGIN_PCT}"),
    );
    check(
        "headroom.pressure_boost_pct",
        h.pressure_boost_pct.is_finite() && (0.0..=MAX_PRESSURE_BOOST_PCT).contains(&h.pressure_boost_pct),
        format!("must be between 0 and {MAX_PRESSURE_BOOST_PCT}"),
    );
    check(
        "adapters.timeout_ms",
        (MIN_ADAPTER_TIMEOUT_MS..=MAX_ADAPTER_TIMEOUT_MS).contains(&cfg.adapters.timeout_ms),
        format!("must be between {MIN_ADAPTER_TIMEOUT_MS} and {MAX_ADAPTER_TIMEOUT_MS} ms"),
    );
    check(
        "appearance.theme",
        crate::theme::valid_theme_name(&cfg.appearance.theme),
        format!(
            "{:?} is not a theme name (a built-in or a file stem in themes/)",
            cfg.appearance.theme
        ),
    );
    for row in &cfg.appearance.header {
        if !HEADER_ROWS.contains(&row.as_str()) {
            let hint = crate::layered::closest(row, HEADER_ROWS.iter().copied())
                .map(|c| format!(" — did you mean {c:?}?"))
                .unwrap_or_default();
            check(
                "appearance.header",
                false,
                format!("unknown row {row:?}{hint} (rows: {})", HEADER_ROWS.join(", ")),
            );
        }
    }
    check(
        "format.decimals",
        cfg.format.decimals <= MAX_DECIMALS,
        format!("must be between 0 and {MAX_DECIMALS}"),
    );
    check(
        "keys.preset",
        crate::keymap::PRESETS.contains(&cfg.keys.preset.as_str()),
        format!(
            "unknown key preset {:?} (presets: {})",
            cfg.keys.preset,
            crate::keymap::PRESETS.join(", ")
        ),
    );
    check(
        "layout.name",
        cfg.layout.name.is_empty() || valid_layout_name(&cfg.layout.name),
        format!(
            "{:?} is not a layout name (a file stem in layouts/)",
            cfg.layout.name
        ),
    );
    let p = &cfg.personalization;
    check(
        "personalization.half_life_days",
        p.half_life_days.is_finite() && p.half_life_days > 0.0,
        "must be > 0".into(),
    );
    check(
        "personalization.retention_days",
        p.retention_days >= 1,
        "must be ≥ 1 day".into(),
    );
    check(
        "personalization.log_max_mb",
        p.log_max_mb >= 1,
        "must be ≥ 1 MB".into(),
    );
    for (name, w) in [
        ("salience", p.weights.salience),
        ("affinity", p.weights.affinity),
        ("actionability", p.weights.actionability),
        ("query", p.weights.query),
        ("noise", p.weights.noise),
    ] {
        check(
            &format!("personalization.weights.{name}"),
            w.is_finite(),
            "must be a finite number".into(),
        );
    }
    check(
        "serve.listen",
        valid_listen(&cfg.serve.listen),
        "must be host:port, e.g. 127.0.0.1:9469".into(),
    );
    for (i, v) in cfg.views.iter().enumerate() {
        check(
            &format!("views.{i}.layout"),
            v.layout.is_empty() || valid_layout_name(&v.layout),
            format!("{:?} is not a layout name (a file stem in layouts/)", v.layout),
        );
    }
    out
}

/// The rules that need the config directory: the selected theme and layout must exist.
pub fn fs_problems(cfg: &Config, paths: &ConfigPaths) -> Vec<Problem> {
    let mut out = Vec::new();
    let theme = &cfg.appearance.theme;
    if crate::theme::valid_theme_name(theme) {
        if let Err(e) = crate::theme::load_theme(theme, Some(&paths.themes)) {
            out.push(Problem {
                key: "appearance.theme".into(),
                message: e.to_string(),
            });
        }
    }
    let layout = &cfg.layout.name;
    if !layout.is_empty()
        && valid_layout_name(layout)
        && !crate::layout::list_layouts(&paths.layouts).contains(layout)
    {
        out.push(Problem {
            key: "layout.name".into(),
            message: format!("no layout {layout:?} in {}", paths.layouts.display()),
        });
    }
    out
}

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

    #[test]
    fn defaults_are_valid() {
        assert_eq!(problems(&Config::default()), Vec::new());
    }

    #[test]
    fn every_rule_fires() {
        let mut c = Config::default();
        c.general.refresh_ms = 0;
        c.general.host_refresh_ms = 249;
        c.thresholds.idle_cpu_pct = -1.0;
        c.headroom.min_margin = "banana".into();
        c.headroom.margin_override = "x".into();
        c.headroom.margin_pct = f64::NAN;
        c.headroom.pressure_boost_pct = -50.0;
        c.adapters.timeout_ms = 60_000;
        c.appearance.theme = String::new();
        c.appearance.header = vec!["meter".into(), "memory".into()];
        c.format.decimals = 200;
        c.keys.preset = "bogus".into();
        c.layout.name = "../../x".into();
        c.personalization.half_life_days = 0.0;
        c.personalization.retention_days = 0;
        c.personalization.log_max_mb = 0;
        c.personalization.weights.query = f64::INFINITY;
        c.serve.listen = "localhost".into();
        c.views.push(crate::model::SavedView {
            name: "v".into(),
            query: String::new(),
            layout: "/etc/x".into(),
        });
        let keys: Vec<String> = problems(&c).into_iter().map(|p| p.key).collect();
        for want in [
            "general.refresh_ms",
            "general.host_refresh_ms",
            "thresholds.idle_cpu_pct",
            "headroom.min_margin",
            "headroom.margin_override",
            "headroom.margin_pct",
            "headroom.pressure_boost_pct",
            "adapters.timeout_ms",
            "appearance.theme",
            "appearance.header",
            "format.decimals",
            "keys.preset",
            "layout.name",
            "personalization.half_life_days",
            "personalization.retention_days",
            "personalization.log_max_mb",
            "personalization.weights.query",
            "serve.listen",
            "views.0.layout",
        ] {
            assert!(keys.iter().any(|k| k == want), "{want} not reported: {keys:?}");
        }
        // the adapter timeout range is the adapters' own clamp: 10 ms … 2000 ms, inclusive
        for (ms, ok) in [
            (9, false),
            (10, true),
            (200, true),
            (2000, true),
            (2001, false),
            (5000, false),
        ] {
            let mut c = Config::default();
            c.adapters.timeout_ms = ms;
            assert_eq!(problems(&c).is_empty(), ok, "adapters.timeout_ms = {ms}");
        }
        let msg = &problems(&c)
            .into_iter()
            .find(|p| p.key == "appearance.header")
            .unwrap()
            .message;
        assert!(msg.contains("did you mean \"meters\"?"), "{msg}");
    }

    #[test]
    fn listen_accepts_what_the_server_binds() {
        // `oomtop serve` hands the string to a `ToSocketAddrs` bind, so host names work
        for ok in [
            "127.0.0.1:9469",
            "[::1]:9469",
            "localhost:9469",
            "my-box.lan:80",
            "0.0.0.0:1",
        ] {
            assert!(valid_listen(ok), "{ok}");
        }
        for bad in [
            "localhost",
            "localhost:",
            ":9469",
            "localhost:99999",
            "a b:1",
            "-x:1",
            "",
        ] {
            assert!(!valid_listen(bad), "{bad}");
        }
    }

    #[test]
    fn theme_and_layout_must_exist() {
        let d = tempfile::tempdir().unwrap();
        let paths = ConfigPaths::new(d.path());
        let mut c = Config::default();
        assert!(fs_problems(&c, &paths).is_empty());
        c.appearance.theme = "nightt".into();
        c.layout.name = "gone".into();
        let p = fs_problems(&c, &paths);
        assert_eq!(p.len(), 2, "{p:?}");
        assert!(p[0].message.contains("theme \"nightt\" not found"));
        assert!(p[1].message.contains("no layout \"gone\""));
    }
}