use super::outcome::{Exchange, Outcome};
use axum::http::StatusCode;
use std::sync::{Arc, Mutex};
const BOUNDS: [u64; 12] = [
1000, 5000, 10000, 25000, 50000, 100000, 250000, 500000, 1000000, 5000000, 10000000, 30000000,
];
#[derive(Clone, Default)]
struct Counts {
admitted: u64,
active: u64,
outcomes: [u64; 4],
rejected: u64,
admission_rejected: u64,
transport_errors: u64,
elapsed_micros: u64,
responses: [u64; 5],
buckets: [u64; 12],
}
pub(crate) struct Metrics {
counts: Mutex<Counts>,
}
impl Metrics {
pub(crate) fn new() -> Self {
Self {
counts: Mutex::new(Counts::default()),
}
}
pub(crate) fn begin(self: &Arc<Self>) -> Exchange {
self.update(|counts| {
counts.admitted += 1;
counts.active += 1;
});
Exchange::new(self.clone())
}
pub(super) fn finish(&self, micros: u64, outcome: Outcome) {
self.update(|counts| {
counts.active -= 1;
counts.outcomes[outcome.index()] += 1;
counts.elapsed_micros = counts.elapsed_micros.saturating_add(micros);
for (bound, count) in BOUNDS.iter().zip(&mut counts.buckets) {
if micros <= *bound {
*count += 1;
}
}
});
}
fn update(&self, update: impl FnOnce(&mut Counts)) {
update(&mut self.counts.lock().unwrap_or_else(|e| e.into_inner()));
}
pub(crate) fn rejected(&self, admission: bool) {
self.update(|counts| {
counts.admission_rejected += u64::from(admission);
counts.rejected += 1;
});
}
pub(crate) fn transport_failure(&self) {
self.update(|counts| counts.transport_errors += 1);
}
pub(crate) fn response(&self, status: StatusCode) {
self.update(|counts| {
counts.responses[(status.as_u16() / 100).clamp(1, 5) as usize - 1] += 1
});
}
pub(crate) fn render(&self) -> String {
let counts = self
.counts
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let finished: u64 = counts.outcomes.iter().sum();
let mut output = String::new();
for (name, kind, value) in [
(
"servlet_exchanges_admitted_total",
"counter",
counts.admitted,
),
("servlet_exchanges_active", "gauge", counts.active),
("servlet_exchanges_finished_total", "counter", finished),
(
"servlet_admission_rejections_total",
"counter",
counts.admission_rejected,
),
(
"servlet_runtime_rejections_total",
"counter",
counts.rejected,
),
(
"servlet_transport_errors_total",
"counter",
counts.transport_errors,
),
(
"servlet_exchange_duration_microseconds_total",
"counter",
counts.elapsed_micros,
),
] {
output.push_str(&format!("# TYPE {name} {kind}\n{name} {value}\n"));
}
output.push_str("# TYPE servlet_exchanges_outcomes_total counter\n");
for outcome in [
Outcome::Completed,
Outcome::Failed,
Outcome::TimedOut,
Outcome::Cancelled,
] {
output.push_str(&format!(
"servlet_exchanges_outcomes_total{{outcome=\"{}\"}} {}\n",
outcome.name(),
counts.outcomes[outcome.index()]
));
}
output.push_str("# TYPE servlet_responses_total counter\n");
for (index, count) in counts.responses.iter().enumerate() {
output.push_str(&format!(
"servlet_responses_total{{class=\"{}xx\"}} {count}\n",
index + 1
));
}
output.push_str("# TYPE servlet_exchange_duration_seconds histogram\n");
for (bound, count) in BOUNDS.iter().zip(counts.buckets) {
output.push_str(&format!(
"servlet_exchange_duration_seconds_bucket{{le=\"{}\"}} {count}\n",
*bound as f64 / 1_000_000.0
));
}
output.push_str(&format!("servlet_exchange_duration_seconds_bucket{{le=\"+Inf\"}} {finished}\nservlet_exchange_duration_seconds_count {finished}\nservlet_exchange_duration_seconds_sum {}\n", counts.elapsed_micros as f64 / 1_000_000.0));
output
}
}
#[cfg(test)]
#[path = "metrics_test.rs"]
mod metrics_test;