use std::{collections::BTreeMap, fmt::Display, sync::atomic::Ordering, time::Instant};
use metrics::Key;
use super::{
recorder::{read, Metrics},
summary::QUANTILES,
};
pub(super) fn render(metrics: &Metrics, now: Instant) -> String {
let descriptions = read(&metrics.descriptions);
let mut output = String::new();
{
let counters = read(&metrics.counters);
for (name, series) in by_name(counters.keys()) {
write_header(&mut output, &name, "counter", descriptions.get(&name));
for (labels, key) in series {
let value = counters[key].load(Ordering::Acquire);
write_line(&mut output, &name, "", &labels, None, &value);
}
output.push('\n');
}
}
{
let gauges = read(&metrics.gauges);
for (name, series) in by_name(gauges.keys()) {
write_header(&mut output, &name, "gauge", descriptions.get(&name));
for (labels, key) in series {
let value = f64::from_bits(gauges[key].load(Ordering::Acquire));
write_line(&mut output, &name, "", &labels, None, &value);
}
output.push('\n');
}
}
{
let histograms = read(&metrics.histograms);
for (name, series) in by_name(histograms.keys()) {
write_header(&mut output, &name, "summary", descriptions.get(&name));
for (labels, key) in series {
let (recent, sum, count) = histograms[key]
.with_summary(|summary| (summary.recent(now), summary.sum(), summary.count()));
for quantile in QUANTILES {
let value = recent.quantile(quantile).unwrap_or(0.0);
write_line(&mut output, &name, "", &labels, Some(quantile), &value);
}
write_line(&mut output, &name, "_sum", &labels, None, &sum);
write_line(&mut output, &name, "_count", &labels, None, &count);
}
output.push('\n');
}
}
output
}
fn by_name<'a>(keys: impl Iterator<Item = &'a Key>) -> BTreeMap<String, BTreeMap<String, &'a Key>> {
let mut by_name: BTreeMap<String, BTreeMap<String, &Key>> = BTreeMap::new();
for key in keys {
by_name
.entry(sanitize_metric_name(key.name()))
.or_default()
.insert(render_labels(key), key);
}
by_name
}
fn render_labels(key: &Key) -> String {
let mut labels: Vec<(&str, &str)> = Vec::new();
for label in key.labels() {
match labels.iter_mut().find(|(name, _)| *name == label.key()) {
Some((_, value)) => *value = label.value(),
None => labels.push((label.key(), label.value())),
}
}
labels
.iter()
.map(|(name, value)| {
format!(
"{}=\"{}\"",
sanitize_label_key(name),
sanitize_label_value(value)
)
})
.collect::<Vec<_>>()
.join(",")
}
fn write_header(
output: &mut String,
name: &str,
kind: &str,
description: Option<&impl AsRef<str>>,
) {
if let Some(description) = description {
output.push_str("# HELP ");
output.push_str(name);
output.push(' ');
output.push_str(&sanitize_description(description.as_ref()));
output.push('\n');
}
output.push_str("# TYPE ");
output.push_str(name);
output.push(' ');
output.push_str(kind);
output.push('\n');
}
fn write_line(
output: &mut String,
name: &str,
suffix: &str,
labels: &str,
quantile: Option<f64>,
value: &dyn Display,
) {
output.push_str(name);
output.push_str(suffix);
if !labels.is_empty() || quantile.is_some() {
output.push('{');
output.push_str(labels);
if let Some(quantile) = quantile {
if !labels.is_empty() {
output.push(',');
}
output.push_str(&format!("quantile=\"{quantile}\""));
}
output.push('}');
}
output.push(' ');
output.push_str(&value.to_string());
output.push('\n');
}
pub(super) fn sanitize_metric_name(name: &str) -> String {
sanitize_name(
name,
|c| c.is_ascii_alphabetic() || c == '_' || c == ':',
|c| c.is_ascii_alphanumeric() || c == '_' || c == ':',
)
}
pub(super) fn sanitize_label_key(key: &str) -> String {
sanitize_name(
key,
|c| c.is_ascii_alphabetic() || c == '_',
|c| c.is_ascii_alphanumeric() || c == '_',
)
}
fn sanitize_name(name: &str, valid_first: fn(char) -> bool, valid: fn(char) -> bool) -> String {
name.chars()
.enumerate()
.map(|(i, c)| {
let is_valid = if i == 0 { valid_first(c) } else { valid(c) };
if is_valid {
c
} else {
'_'
}
})
.collect()
}
pub(super) fn sanitize_label_value(value: &str) -> String {
escape(value, true)
}
pub(super) fn sanitize_description(description: &str) -> String {
escape(description, false)
}
fn escape(value: &str, escape_quotes: bool) -> String {
let mut escaped = String::with_capacity(value.len());
let mut previous_backslash = false;
for c in value.chars() {
match c {
'\n' => escaped.push_str("\\n"),
'"' if escape_quotes => {
previous_backslash = false;
escaped.push_str("\\\"");
}
'\\' => {
if previous_backslash {
escaped.push_str("\\\\");
}
previous_backslash = !previous_backslash;
}
c => {
if previous_backslash {
previous_backslash = false;
escaped.push_str("\\\\");
}
escaped.push(c);
}
}
}
if previous_backslash {
escaped.push_str("\\\\");
}
escaped
}