use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use crate::MetricValue;
pub fn render_snapshot(
descriptors: &[&crate::MetricDescriptor],
samples: &[crate::MetricSample],
output: &mut String,
) {
use std::fmt::Write;
for descriptor in descriptors {
let _ = writeln!(output, "# HELP {} {}", descriptor.name, descriptor.help);
let _ = writeln!(
output,
"# TYPE {} {}",
descriptor.name,
descriptor.kind.prometheus_type()
);
for sample in samples
.iter()
.filter(|sample| sample.name == descriptor.name)
{
sample.render_prometheus(output);
}
}
}
pub const LATENCY_SECONDS: &[f64] = &[
0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0,
];
pub const STREAM_LIFETIME_SECONDS: &[f64] = &[
0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 900.0, 3600.0,
];
pub fn add(counter: &AtomicU64, amount: u64) {
let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
Some(value.saturating_add(amount))
});
}
pub struct AtomicHistogram {
bounds: &'static [f64],
buckets: [AtomicU64; 16],
micros: AtomicU64,
}
impl AtomicHistogram {
pub const fn new(bounds: &'static [f64]) -> Self {
assert!(bounds.len() < 16);
let mut index = 0;
while index < bounds.len() {
assert!(bounds[index] > 0.0 && bounds[index] < f64::INFINITY);
assert!(index == 0 || bounds[index - 1] < bounds[index]);
index += 1;
}
Self {
bounds,
buckets: [const { AtomicU64::new(0) }; 16],
micros: AtomicU64::new(0),
}
}
pub fn observe(&self, duration: Duration) {
let seconds = duration.as_secs_f64();
let bucket = self.bounds.partition_point(|bound| *bound < seconds);
add(
&self.micros,
duration.as_micros().min(u64::MAX as u128) as u64,
);
add(&self.buckets[bucket], 1);
}
pub fn snapshot(&self) -> MetricValue {
let buckets: Vec<u64> = self.buckets[..=self.bounds.len()]
.iter()
.map(|cell| cell.load(Ordering::Relaxed))
.collect();
let count = buckets.iter().copied().fold(0u64, u64::saturating_add);
MetricValue::Histogram {
bounds: self.bounds,
buckets,
sum: self.micros.load(Ordering::Relaxed) as f64 / 1_000_000.0,
count,
}
}
}