athena_rs 3.23.0

Hyper performant polyglot Database driver
Documentation
//! Prometheus text-format rendering helpers.
//!
//! This module owns escaping and output-line shaping helpers used by the
//! `/metrics` endpoint serialization path.

use std::fmt::{Display, Write};

use crate::features::metrics::types::{DURATION_BUCKETS_SECONDS, DurationSummary};

/// Escapes a label value for Prometheus exposition format.
pub(super) fn label_value(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

/// Writes Prometheus HELP/TYPE metadata lines for one metric name.
pub(super) fn write_help_and_type(body: &mut String, name: &str, help: &str, metric_type: &str) {
    let _ = writeln!(body, "# HELP {name} {help}");
    let _ = writeln!(body, "# TYPE {name} {metric_type}");
}

/// Writes one Prometheus sample line without labels.
pub(super) fn write_metric_value(body: &mut String, name: &str, value: impl Display) {
    let _ = writeln!(body, "{name} {value}");
}

/// Writes one Prometheus sample line with explicit label set.
pub(super) fn write_metric_with_labels(
    body: &mut String,
    name: &str,
    labels: &str,
    value: impl Display,
) {
    let _ = writeln!(body, "{name}{{{labels}}} {value}");
}

/// Writes histogram buckets/sum/count samples for one duration summary.
pub(super) fn write_histogram(
    body: &mut String,
    name: &str,
    labels: &str,
    summary: &DurationSummary,
) {
    for (index, upper_bound) in DURATION_BUCKETS_SECONDS.iter().enumerate() {
        write_metric_with_labels(
            body,
            &format!("{name}_bucket"),
            &format!("{labels},le=\"{upper_bound}\""),
            summary.buckets[index],
        );
    }
    write_metric_with_labels(
        body,
        &format!("{name}_bucket"),
        &format!("{labels},le=\"+Inf\""),
        summary.count,
    );
    write_metric_with_labels(
        body,
        &format!("{name}_sum"),
        labels,
        format!("{:.6}", summary.sum_seconds),
    );
    write_metric_with_labels(body, &format!("{name}_count"), labels, summary.count);
}