nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The sampler's gauges (SRD-118 §4): which families each category
//! publishes, and writing a sample to them.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use nmbrs_metrics::component::Component;
use nmbrs_metrics::instruments::gauge::ValueGauge;

use super::{Categories, SysmonSample};

/// One gauge family the sampler publishes.
pub struct Family {
    pub name: &'static str,
    /// True when the category that publishes it is enabled.
    enabled: fn(&Categories) -> bool,
    /// The label its series are told apart by, for a family with one
    /// series per device, core, mount, interface or process. `None`
    /// for a family that describes the host as a whole.
    pub subject: Option<&'static str>,
}

const fn host(name: &'static str, enabled: fn(&Categories) -> bool) -> Family {
    Family {
        name,
        enabled,
        subject: None,
    }
}

const fn per(
    name: &'static str,
    subject: &'static str,
    enabled: fn(&Categories) -> bool,
) -> Family {
    Family {
        name,
        enabled,
        subject: Some(subject),
    }
}

/// Every family, by category. This table is what is registered, and
/// SRD-118 §4 lists the same families.
pub const FAMILIES: &[Family] = &[
    host("sysmon_cpu_util", |c| c.cpu),
    host("sysmon_cpu_core_p25", |c| c.cpu),
    host("sysmon_cpu_core_p50", |c| c.cpu),
    host("sysmon_cpu_core_p75", |c| c.cpu),
    per("sysmon_cpu_core_max", "core", |c| c.cpu),
    per("sysmon_io_util", "device", |c| c.io),
    per("sysmon_io_read_bytes_per_s", "device", |c| c.io),
    per("sysmon_io_write_bytes_per_s", "device", |c| c.io),
    per("sysmon_io_read_ops_per_s", "device", |c| c.io),
    per("sysmon_io_write_ops_per_s", "device", |c| c.io),
    host("sysmon_ram_util", |c| c.ram),
    host("sysmon_ram_util_cached", |c| c.ram),
    host("sysmon_rambw_util", |c| c.rambw),
    per("sysmon_storage_util", "mount", |c| c.storage),
    per("sysmon_net_rx_bytes_per_s", "iface", |c| c.net),
    per("sysmon_net_tx_bytes_per_s", "iface", |c| c.net),
    host("sysmon_pressure_cpu", |c| c.pressure),
    host("sysmon_pressure_mem", |c| c.pressure),
    host("sysmon_pressure_mem_full", |c| c.pressure),
    host("sysmon_pressure_io", |c| c.pressure),
    host("sysmon_pressure_io_full", |c| c.pressure),
    per("sysmon_proc_cpu_cores", "proc", |c| c.proc),
    per("sysmon_proc_rss_bytes", "proc", |c| c.proc),
    per("sysmon_proc_threads", "proc", |c| c.proc),
    per("sysmon_proc_read_bytes_per_s", "proc", |c| c.proc),
    per("sysmon_proc_write_bytes_per_s", "proc", |c| c.proc),
];

/// A gauge family whose series are one-per-SUBJECT — the device, core, or
/// mount the measurement is about. Each distinct subject value materialises
/// a dimensional cell under the session component
/// ([`nmbrs_metrics::cells::resolve_under`]) and registers the family there
/// once; after that a sample is a hash lookup and a `set`.
///
/// This is what "submitted to metrics with the appropriate dimensional
/// labels, keyed by the session component" means concretely:
/// `sysmon_io_util{session="…",device="nvme1n1"}` — the subject is a label,
/// the cell refines the session's identity, and a sweep that shifts between
/// devices yields one honestly-labeled series per device rather than one
/// anonymous series whose subject silently changes.
struct SubjectGauge {
    family: &'static str,
    /// The dimension this family's subject occupies (`device`, `core`,
    /// `mount`).
    label_key: &'static str,
    parent: Arc<RwLock<Component>>,
    /// Instruments already materialised, by subject value.
    instances: std::collections::HashMap<String, Arc<ValueGauge>>,
}

impl SubjectGauge {
    fn new(family: &'static str, label_key: &'static str, parent: Arc<RwLock<Component>>) -> Self {
        Self {
            family,
            label_key,
            parent,
            instances: Default::default(),
        }
    }

    fn set(&mut self, subject: &str, value: f64) {
        if let Some(g) = self.instances.get(subject) {
            g.set(value);
            return;
        }
        let coord = nmbrs_metrics::labels::Labels::of(self.label_key, subject);
        let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
        let labels = {
            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
            guard.effective_labels().clone()
        };
        let g = Arc::new(ValueGauge::new(labels.with("family", self.family)));
        let registered = cell
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .register_instrument(
                self.family,
                nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
            );
        if let Err(e) = registered {
            // One cell, one family: a second registration here is a
            // programming error worth hearing about once, not per sample.
            crate::diag!(
                crate::observer::LogLevel::Warn,
                "sysmon: {family} cell {subject}: {e}",
                family = self.family
            );
        }
        g.set(value);
        self.instances.insert(subject.to_string(), g);
    }
}

/// The gauges of the enabled categories.
pub(super) struct Gauges {
    /// Host-scalar measures — no subject, so they live on the session root
    /// itself and carry exactly its labels.
    host: HashMap<&'static str, Arc<ValueGauge>>,
    /// Subject-dimensioned measures — one cell per device / core / mount /
    /// interface / process.
    subject: HashMap<&'static str, SubjectGauge>,
}

impl Gauges {
    /// Register gauges for the ENABLED categories on the session component.
    /// Direct registration on the session root — no child component, no new
    /// labels: the samples describe the whole host, which is exactly the
    /// session's dimensional cell.
    ///
    /// Subject-dimensioned families register per cell at first sight of
    /// each subject, NOT here — registering on the root as well would claim
    /// the family for the un-refined identity and collide with the first
    /// cell.
    pub fn register(component: &Arc<RwLock<Component>>, cats: Categories) -> Result<Self, String> {
        let mut gauges = Self {
            host: HashMap::new(),
            subject: HashMap::new(),
        };
        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
        let labels = guard.effective_labels().clone();
        for family in FAMILIES.iter().filter(|f| (f.enabled)(&cats)) {
            match family.subject {
                Some(label_key) => {
                    gauges.subject.insert(
                        family.name,
                        SubjectGauge::new(family.name, label_key, component.clone()),
                    );
                }
                None => {
                    let g = Arc::new(ValueGauge::new(labels.with("family", family.name)));
                    guard.register_instrument(
                        family.name,
                        nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
                    )?;
                    gauges.host.insert(family.name, g);
                }
            }
        }
        Ok(gauges)
    }

    /// Set a host-wide gauge. A family whose category is off has no
    /// gauge, and nothing is done.
    fn set(&self, family: &str, value: f64) {
        if let Some(g) = self.host.get(family) {
            g.set(value);
        }
    }

    /// Set one subject's gauge, likewise.
    fn set_for(&mut self, family: &str, subject: &str, value: f64) {
        if let Some(g) = self.subject.get_mut(family) {
            g.set(subject, value);
        }
    }

    /// Write one sample window to the gauges.
    pub fn publish(&mut self, sample: &SysmonSample) {
        if let Some(cpu) = &sample.cpu {
            self.set("sysmon_cpu_util", cpu.mean);
            self.set("sysmon_cpu_core_p25", cpu.p25);
            self.set("sysmon_cpu_core_p50", cpu.p50);
            self.set("sysmon_cpu_core_p75", cpu.p75);
            self.set_for(
                "sysmon_cpu_core_max",
                &cpu.top_core.to_string(),
                cpu.max_core,
            );
        }
        if let Some((device, util)) = &sample.io {
            self.set_for("sysmon_io_util", device, *util);
        }
        for rate in &sample.io_rates {
            let device = rate.device.as_str();
            self.set_for("sysmon_io_read_bytes_per_s", device, rate.read_bytes_per_s);
            self.set_for(
                "sysmon_io_write_bytes_per_s",
                device,
                rate.write_bytes_per_s,
            );
            self.set_for("sysmon_io_read_ops_per_s", device, rate.read_ops_per_s);
            self.set_for("sysmon_io_write_ops_per_s", device, rate.write_ops_per_s);
        }
        if let Some((committed, cached)) = sample.ram {
            self.set("sysmon_ram_util", committed);
            self.set("sysmon_ram_util_cached", cached);
        }
        if let Some(util) = sample.rambw {
            self.set("sysmon_rambw_util", util);
        }
        if let Some((mount, util)) = &sample.storage {
            self.set_for("sysmon_storage_util", mount, *util);
        }
        for rate in &sample.net {
            self.set_for(
                "sysmon_net_rx_bytes_per_s",
                &rate.iface,
                rate.rx_bytes_per_s,
            );
            self.set_for(
                "sysmon_net_tx_bytes_per_s",
                &rate.iface,
                rate.tx_bytes_per_s,
            );
        }
        if let Some(p) = &sample.pressure {
            self.set("sysmon_pressure_cpu", p.cpu);
            self.set("sysmon_pressure_mem", p.mem);
            self.set("sysmon_pressure_mem_full", p.mem_full);
            self.set("sysmon_pressure_io", p.io);
            self.set("sysmon_pressure_io_full", p.io_full);
        }
        for p in &sample.procs {
            let name = p.name.as_str();
            self.set_for("sysmon_proc_cpu_cores", name, p.cpu_cores);
            self.set_for("sysmon_proc_rss_bytes", name, p.rss_bytes);
            self.set_for("sysmon_proc_threads", name, p.threads);
            if let Some((read, write)) = p.io_bytes_per_s {
                self.set_for("sysmon_proc_read_bytes_per_s", name, read);
                self.set_for("sysmon_proc_write_bytes_per_s", name, write);
            }
        }
    }
}

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

    /// A subject-dimensioned gauge materialises ONE cell per subject under
    /// the session component, each series carrying the subject as a label —
    /// and re-setting an existing subject attaches no twin.
    #[test]
    fn subject_gauges_dimension_by_cell_under_the_session_component() {
        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
            nmbrs_metrics::labels::Labels::of("session", "s1"),
            std::collections::HashMap::new(),
        )));
        let mut g = SubjectGauge::new("sysmon_io_util", "device", session.clone());
        g.set("nvme1n1", 0.97);
        g.set("nvme2n1", 0.40);
        g.set("nvme1n1", 0.98);

        let guard = session.read().unwrap();
        assert_eq!(
            guard.child_count(),
            2,
            "one cell per device, re-sets attach no twin"
        );
        drop(guard);
        assert_eq!(g.instances.len(), 2);
        // The series carries session + device + family — the session's
        // identity refined by the subject, never replaced.
        let labels = g.instances["nvme1n1"].labels().to_prometheus();
        for owned in ["session=", "device=\"nvme1n1\"", "family="] {
            assert!(labels.contains(owned), "{owned} missing from {labels}");
        }
    }

    /// Only the enabled categories' families are registered, and a
    /// sample for a category that is off is not written anywhere.
    #[test]
    fn only_enabled_categories_have_gauges() {
        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
            nmbrs_metrics::labels::Labels::of("session", "s1"),
            std::collections::HashMap::new(),
        )));
        let cats = Categories {
            ram: true,
            net: true,
            ..Categories::default()
        };
        let mut gauges = Gauges::register(&session, cats).unwrap();
        assert_eq!(gauges.host.len(), 2);
        assert_eq!(gauges.subject.len(), 2);
        gauges.publish(&SysmonSample {
            ram: Some((0.25, 0.5)),
            pressure: Some(Default::default()),
            net: vec![super::super::net::NetRate {
                iface: "eth0".into(),
                rx_bytes_per_s: 10.0,
                tx_bytes_per_s: 20.0,
            }],
            ..SysmonSample::default()
        });
        assert_eq!(gauges.host["sysmon_ram_util"].get(), 0.25);
        assert_eq!(
            gauges.subject["sysmon_net_tx_bytes_per_s"].instances["eth0"].get(),
            20.0
        );
    }

    /// A family name is given once, and each is under `sysmon_`.
    #[test]
    fn family_names_are_unique() {
        let mut names: Vec<&str> = FAMILIES.iter().map(|f| f.name).collect();
        assert!(names.iter().all(|n| n.starts_with("sysmon_")));
        names.sort_unstable();
        let total = names.len();
        names.dedup();
        assert_eq!(names.len(), total);
    }
}