90 lines
2.9 KiB
Rust
90 lines
2.9 KiB
Rust
use std::time::Instant;
|
|
|
|
use axum::{
|
|
extract::{MatchedPath, Request},
|
|
middleware::Next,
|
|
response::Response,
|
|
};
|
|
use crank_metrics::{
|
|
DbPoolState, ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass, InFlightGuard,
|
|
};
|
|
use metrics::Unit;
|
|
|
|
use crate::{MetricKind, MetricUnit};
|
|
|
|
pub async fn record_http_request(request: Request, next: Next) -> Response {
|
|
let route = request
|
|
.extensions()
|
|
.get::<MatchedPath>()
|
|
.map_or(HttpRoute::unmatched(), |path| {
|
|
HttpRoute::from_matched_path(path.as_str())
|
|
});
|
|
let method = HttpMethod::classify(request.method().as_str());
|
|
let started_at = Instant::now();
|
|
let _inflight = InFlightGuard::http();
|
|
|
|
let response = next.run(request).await;
|
|
let exemplar = response.extensions().get::<ExemplarTraceId>().copied();
|
|
crank_metrics::record_http_request_with_exemplar(
|
|
route,
|
|
method,
|
|
HttpStatusClass::from_status(response.status().as_u16()),
|
|
started_at.elapsed(),
|
|
exemplar,
|
|
);
|
|
|
|
response
|
|
}
|
|
|
|
pub fn record_db_pool_connections(total: u32, idle: usize) {
|
|
let idle = u32::try_from(idle.min(total as usize)).unwrap_or(total);
|
|
crank_metrics::set_db_pool_connections(DbPoolState::Idle, idle);
|
|
crank_metrics::set_db_pool_connections(DbPoolState::Used, total.saturating_sub(idle));
|
|
}
|
|
|
|
pub(crate) fn register_metric_schema(service: crank_metrics::MetricService) {
|
|
for definition in crank_metrics::metric_schema_for_service(service) {
|
|
let unit = match definition.unit {
|
|
MetricUnit::Count => Unit::Count,
|
|
MetricUnit::Seconds => Unit::Seconds,
|
|
};
|
|
match definition.kind {
|
|
MetricKind::Counter => {
|
|
metrics::describe_counter!(definition.name, unit, definition.description);
|
|
}
|
|
MetricKind::Gauge => {
|
|
metrics::describe_gauge!(definition.name, unit, definition.description);
|
|
}
|
|
MetricKind::Histogram => {
|
|
metrics::describe_histogram!(definition.name, unit, definition.description);
|
|
}
|
|
}
|
|
}
|
|
|
|
crank_metrics::initialize_gauges(service);
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crank_metrics::{HttpMethod, HttpRoute, HttpStatusClass};
|
|
|
|
#[test]
|
|
fn normalizes_unbounded_http_values() {
|
|
assert_eq!(HttpMethod::classify("GET"), HttpMethod::Get);
|
|
assert_eq!(
|
|
HttpMethod::classify("CUSTOM-user-controlled"),
|
|
HttpMethod::Other
|
|
);
|
|
assert_eq!(HttpStatusClass::from_status(204), HttpStatusClass::Success);
|
|
assert_eq!(
|
|
HttpStatusClass::from_status(429),
|
|
HttpStatusClass::ClientError
|
|
);
|
|
assert_eq!(HttpStatusClass::from_status(999), HttpStatusClass::Other);
|
|
assert_eq!(
|
|
HttpRoute::from_matched_path("/documents/{document_id}"),
|
|
HttpRoute::unmatched()
|
|
);
|
|
}
|
|
}
|