use std::borrow::Cow;
use std::time::Instant;
use axum::extract::{MatchedPath, Request};
use axum::http::Method;
use axum::middleware::Next;
use axum::response::Response;
pub const REQUESTS_TOTAL: &str = "seiva_http_requests_total";
pub const REQUEST_DURATION_SECONDS: &str = "seiva_http_request_duration_seconds";
pub const REQUESTS_IN_FLIGHT: &str = "seiva_http_requests_in_flight";
const UNMATCHED_ROUTE: &str = "<unmatched>";
fn status_class(status: u16) -> &'static str {
match status {
100..=199 => "1xx",
200..=299 => "2xx",
300..=399 => "3xx",
400..=499 => "4xx",
_ => "5xx",
}
}
fn method_label(method: &Method) -> &'static str {
match *method {
Method::GET => "GET",
Method::POST => "POST",
Method::PUT => "PUT",
Method::DELETE => "DELETE",
Method::PATCH => "PATCH",
Method::HEAD => "HEAD",
Method::OPTIONS => "OPTIONS",
Method::CONNECT => "CONNECT",
Method::TRACE => "TRACE",
_ => "OTHER",
}
}
struct InFlightGuard;
impl InFlightGuard {
fn enter() -> Self {
metrics::gauge!(REQUESTS_IN_FLIGHT).increment(1.0);
Self
}
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
metrics::gauge!(REQUESTS_IN_FLIGHT).decrement(1.0);
}
}
pub async fn track_metrics(request: Request, next: Next) -> Response {
if request.uri().path().starts_with("/health") {
return next.run(request).await;
}
let route: Cow<'static, str> = request
.extensions()
.get::<MatchedPath>()
.map(|p| Cow::Owned(p.as_str().to_owned()))
.unwrap_or(Cow::Borrowed(UNMATCHED_ROUTE));
let method = method_label(request.method());
let guard = InFlightGuard::enter();
let started = Instant::now();
let response = next.run(request).await;
let elapsed = started.elapsed().as_secs_f64();
drop(guard);
let status = status_class(response.status().as_u16());
metrics::counter!(
REQUESTS_TOTAL,
"method" => method,
"route" => route.clone(),
"status" => status,
)
.increment(1);
metrics::histogram!(
REQUEST_DURATION_SECONDS,
"method" => method,
"route" => route,
"status" => status,
)
.record(elapsed);
response
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_classes_collapse_to_five_buckets() {
assert_eq!(status_class(100), "1xx");
assert_eq!(status_class(200), "2xx");
assert_eq!(status_class(204), "2xx");
assert_eq!(status_class(301), "3xx");
assert_eq!(status_class(404), "4xx");
assert_eq!(status_class(503), "5xx");
assert_eq!(status_class(599), "5xx");
}
#[test]
fn standard_methods_are_static_and_custom_collapses_to_other() {
assert_eq!(method_label(&Method::GET), "GET");
assert_eq!(method_label(&Method::DELETE), "DELETE");
assert_eq!(method_label(&Method::PATCH), "PATCH");
let custom = Method::from_bytes(b"PURGE").unwrap();
assert_eq!(method_label(&custom), "OTHER");
}
}