monocle_agent/http.rs
1//! Axum HTTP integration: an inbound-request metrics middleware and
2//! [`request_span`], which names request spans `"<METHOD> <route>"`
3//! (e.g. `GET /render`).
4//!
5//! Only compiled with the `axum` feature (on by default).
6
7use std::sync::LazyLock;
8use std::time::{Duration, Instant};
9
10use axum::extract::{MatchedPath, Request};
11use axum::middleware::Next;
12use axum::response::Response;
13use opentelemetry::metrics::Histogram;
14use opentelemetry::KeyValue;
15use tracing::Span;
16
17/// Meter name for the instruments this crate owns.
18const METER_NAME: &str = "monocle-agent";
19
20/// `http.server.request.duration` — inbound HTTP request latency, in seconds.
21static HTTP_DURATION: LazyLock<Histogram<f64>> = LazyLock::new(|| {
22 opentelemetry::global::meter(METER_NAME)
23 .f64_histogram("http.server.request.duration")
24 .with_unit("s")
25 .with_description("Duration of inbound HTTP requests")
26 .build()
27});
28
29/// Record one HTTP request against `http.server.request.duration`.
30///
31/// `route` should be the low-cardinality matched path (e.g. `/items/{id}`),
32/// never the raw URI, to keep metric label cardinality bounded.
33pub fn record_http(route: &str, status: u16, dur: Duration) {
34 HTTP_DURATION.record(
35 dur.as_secs_f64(),
36 &[
37 KeyValue::new("http.route", route.to_string()),
38 KeyValue::new("http.response.status_code", status as i64),
39 ],
40 );
41}
42
43/// Axum middleware recording `http.server.request.duration` for every request.
44///
45/// Wire it after your routes so [`MatchedPath`] is populated:
46/// ```no_run
47/// # use axum::Router;
48/// # let router: Router = Router::new();
49/// let app = router.layer(axum::middleware::from_fn(monocle_agent::track_http_metrics));
50/// ```
51pub async fn track_http_metrics(req: Request, next: Next) -> Response {
52 // Prefer the matched route template; fall back to a constant so 404s / unmatched
53 // requests don't blow up label cardinality with arbitrary paths.
54 let route = req
55 .extensions()
56 .get::<MatchedPath>()
57 .map(|m| m.as_str().to_string())
58 .unwrap_or_else(|| "unmatched".to_string());
59 let start = Instant::now();
60 let resp = next.run(req).await;
61 record_http(&route, resp.status().as_u16(), start.elapsed());
62 resp
63}
64
65/// Build the per-request span, named `"<METHOD> <route>"` (e.g. `GET /render`)
66/// instead of tower-http's static `"request"`, so traces read clearly in Monocle.
67///
68/// Pass it straight to tower-http's `make_span_with`:
69///
70/// ```no_run
71/// # use tower_http::trace::TraceLayer;
72/// let layer = TraceLayer::new_for_http().make_span_with(monocle_agent::request_span);
73/// ```
74///
75/// It relies on tower-http's blanket `MakeSpan` implementation for
76/// `Fn(&Request) -> Span`, so this crate depends on **no** tower-http version —
77/// it works with whatever tower-http (0.5, 0.6, 0.7, …) your service already uses.
78///
79/// The span is created at INFO level (required so it passes the default filter
80/// and reaches the OTLP exporter) with `otel.kind = "server"` and the
81/// `http.request.method` / `http.route` semantic-convention fields. The dynamic
82/// name is carried via the special `otel.name` field understood by
83/// `tracing-opentelemetry`.
84pub fn request_span(request: &Request) -> Span {
85 let method = request.method().clone();
86 let route = request
87 .extensions()
88 .get::<MatchedPath>()
89 .map(|m| m.as_str().to_string())
90 .unwrap_or_else(|| request.uri().path().to_string());
91 let name = format!("{} {}", method.as_str(), route);
92 tracing::info_span!(
93 "http.request",
94 otel.name = %name,
95 otel.kind = "server",
96 http.request.method = %method,
97 http.route = %route,
98 )
99}