nmbrs-metrics 0.7.3

Metrics collection and reporting for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! A session's series read over each phase, from the store (SRD-118
//! ยง5.1).
//!
//! The selector carries `phase_samples="<mode>"`. Each series it names
//! is read once for each activation of each phase, and returned as one
//! series per activation that carries the activation's labels beside
//! its own and only the samples the mode counts toward it.

use rusqlite::Connection;

use super::super::phase_samples::{ACTIVITY_FAMILY, LABEL, PhaseSamples, Window};
use super::{DataSourceError, Matcher, MatcherOp, Sample, Series, SqliteDataSource, Stored};

/// The windows a stored series' samples cover.
fn windows(stored: &Stored) -> Vec<Window> {
    stored
        .series
        .samples
        .iter()
        .zip(&stored.intervals)
        .map(|(sample, interval)| Window::of_sample(sample.timestamp_ms, *interval))
        .collect()
}

/// Answer a selector that carries the `phase_samples` matcher.
///
/// An activation is one series of [`ACTIVITY_FAMILY`], and its frames
/// are that series' sample windows. Every matcher but the reserved
/// one and `__name__` is applied to a series' labels together with an
/// activation's, so `phase="load"` picks the phase and any other label
/// picks among the series or the activations.
///
/// A series and an activation are matched by time alone. A series the
/// session records belongs to no one execution of it, and a frame is a
/// stretch of the clock, which only one execution was running in.
pub(super) fn select(
    source: &SqliteDataSource,
    conn: &Connection,
    matchers: &[Matcher],
    start_ms: i64,
    end_ms: i64,
    mode: PhaseSamples,
) -> Result<Vec<Series>, DataSourceError> {
    let keep = |label: &'static str| matchers.iter().filter(move |m| m.label == label).cloned();
    // The series: every one of the family, in the query's range. The
    // session's series carry no execution, so `exec_id` is not asked
    // of them here; it is applied below with the activation's labels.
    let named: Vec<Matcher> = keep("__name__").collect();
    let hosts = source.fetch(conn, &named, start_ms, end_ms)?;
    if let Some(recorded) = hosts
        .iter()
        .find(|h| h.series.labels.iter().any(|(k, _)| k == "phase"))
    {
        let family = recorded
            .series
            .labels
            .iter()
            .find(|(k, _)| k == "__name__")
            .map(|(_, v)| v.as_str())
            .unwrap_or("the family");
        return Err(DataSourceError::new(format!(
            "`{LABEL}` reads a series the session records over a phase, and {family} is \
             recorded by a phase: its series already carry `phase`. Remove `{LABEL}` from \
             the selector."
        )));
    }
    if hosts.is_empty() {
        return Ok(Vec::new());
    }
    // The activations: every phase's, over the whole of the store, so
    // that a frame is whole whatever the query's range. A `phase`
    // matcher can only be about an activation, and narrows the read.
    let activity: Vec<Matcher> = std::iter::once(Matcher::eq("__name__", ACTIVITY_FAMILY))
        .chain(keep("exec_id").filter(|m| m.op == MatcherOp::Eq))
        .chain(keep("phase"))
        .collect();
    let activations = source.fetch(conn, &activity, 0, i64::MAX)?;
    let applied: Vec<&Matcher> = matchers
        .iter()
        .filter(|m| m.label != LABEL && m.label != "__name__")
        .collect();

    let mut out = Vec::new();
    for activation in &activations {
        let frames = windows(activation);
        for host in &hosts {
            let mut labels = host.series.labels.clone();
            for (key, value) in &activation.series.labels {
                if key != "__name__" && !labels.iter().any(|(k, _)| k == key) {
                    labels.push((key.clone(), value.clone()));
                }
            }
            if !applied.iter().all(|m| m.matches(&labels)) {
                continue;
            }
            let covered = windows(host);
            let mut counted: Vec<usize> = frames
                .iter()
                .flat_map(|frame| mode.select(*frame, &covered))
                .collect();
            counted.sort_unstable();
            counted.dedup();
            if counted.is_empty() {
                continue;
            }
            let samples: Vec<Sample> = counted
                .into_iter()
                .map(|i| host.series.samples[i])
                .collect();
            out.push(Series { labels, samples });
        }
    }
    Ok(out)
}