nmbrs-metrics 0.7.4

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.
//!
//! Where an activation recorded the family itself, its own series is
//! the answer for that activation, whatever the mode: it covers the
//! activation exactly.

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 (own, hosts): (Vec<Stored>, Vec<Stored>) = source
        .fetch(conn, &named, start_ms, end_ms)?
        .into_iter()
        .partition(|s| s.series.labels.iter().any(|(k, _)| k == "phase"));
    if own.is_empty() && 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 passes = |labels: &[(String, String)]| applied.iter().all(|m| m.matches(labels));
    let mut out: Vec<Series> = Vec::new();
    for activation in &activations {
        // A series the activation recorded itself is the activation's
        // already, whole: it is given as it is, and the session's is
        // not read over this activation as well.
        let recorded: Vec<&Stored> = own
            .iter()
            .filter(|s| {
                activation
                    .series
                    .labels
                    .iter()
                    .filter(|(key, _)| key != "__name__")
                    .all(|pair| s.series.labels.contains(pair))
            })
            .collect();
        if !recorded.is_empty() {
            for stored in recorded {
                let known = out.iter().any(|s| s.labels == stored.series.labels);
                if !known && passes(&stored.series.labels) && !stored.series.samples.is_empty() {
                    out.push(stored.series.clone());
                }
            }
            continue;
        }
        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 !passes(&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)
}