Skip to main content

toolkit_http/layers/
metrics.rs

1//! Tower layer that records OpenTelemetry metrics for outbound HTTP requests.
2//!
3//! Emits a single instrument following [OpenTelemetry HTTP client semantic
4//! conventions][semconv]:
5//! - `http.client.request.duration` — histogram (seconds)
6//!
7//! Attributes: `http.request.method`, `http.route`, `server.address`,
8//! `server.port` (when the URI carries an explicit port), and
9//! `http.response.status_code` (on success) or `error.type` (on failure).
10//!
11//! Modeled after go-appkit's `MetricsRoundTripper`: one duration histogram plus
12//! a build-time request classifier that produces the bounded `http.route`
13//! label, preventing cardinality explosion from raw paths. Like the Go version,
14//! this layer sits outside the retry loop, so it observes one logical request
15//! regardless of transport-level retries.
16//!
17//! [semconv]: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
18
19use crate::error::HttpError;
20use crate::request::RequestType;
21use crate::response::ResponseBody;
22use bytes::Bytes;
23use http::{Request, Response};
24use http_body_util::Full;
25use opentelemetry::metrics::{Histogram, Meter};
26use opentelemetry::{KeyValue, global};
27use std::borrow::Cow;
28use std::future::Future;
29use std::pin::Pin;
30use std::sync::Arc;
31use std::task::{Context, Poll};
32use std::time::Instant;
33use tower::{Layer, Service};
34
35/// Classifies a request into a low-cardinality route label (the `http.route`
36/// attribute). Set once when the client is built; invoked on every request.
37///
38/// This is the Rust analogue of go-appkit's `ClassifyRequest` callback. It must
39/// return a *bounded* set of values (e.g. route templates like
40/// `GET /users/{id}`), never a raw path containing identifiers, otherwise the
41/// metric cardinality is unbounded.
42pub type ClassifyFn = Arc<dyn Fn(&Request<Full<Bytes>>) -> Cow<'static, str> + Send + Sync>;
43
44/// Explicit histogram bucket boundaries (seconds) for request duration.
45///
46/// The SDK's default boundaries are count-oriented (hundreds–thousands) and
47/// useless for a seconds-valued duration. These mirror go-appkit's buckets with
48/// finer low-end resolution, so client-side percentiles stay meaningful and
49/// comparable across the two implementations.
50const DURATION_BOUNDARIES_SECS: &[f64] = &[
51    0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 150.0, 300.0, 600.0,
52];
53
54/// Default classifier producing `"METHOD host"` (mirrors go-appkit's default
55/// `summary`). Never returns a raw path, so it cannot blow up cardinality.
56#[must_use]
57pub fn default_classify(req: &Request<Full<Bytes>>) -> Cow<'static, str> {
58    let host = req.uri().host().unwrap_or("unknown");
59    // Use the normalized method (`_OTHER` for unknown verbs) so the route label
60    // stays consistent with the `http.request.method` attribute and cannot be
61    // widened by arbitrary method strings.
62    Cow::Owned(format!("{} {}", normalize_method(req.method()), host))
63}
64
65/// Normalize HTTP method per [OTel semantic conventions][semconv].
66///
67/// Unknown methods map to `_OTHER` to bound attribute cardinality. Mirrors the
68/// server-side helper in `api-gateway`'s `http_metrics` middleware (duplicated
69/// here so `toolkit-http` stays free of a dependency on that gear).
70///
71/// [semconv]: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
72fn normalize_method(method: &http::Method) -> &'static str {
73    match *method {
74        http::Method::GET => "GET",
75        http::Method::POST => "POST",
76        http::Method::PUT => "PUT",
77        http::Method::DELETE => "DELETE",
78        http::Method::PATCH => "PATCH",
79        http::Method::HEAD => "HEAD",
80        http::Method::OPTIONS => "OPTIONS",
81        http::Method::CONNECT => "CONNECT",
82        http::Method::TRACE => "TRACE",
83        _ => "_OTHER",
84    }
85}
86
87/// Low-cardinality `error.type` value for a transport-level failure.
88///
89/// This layer sits outside the load-shed/retry layers (and inside the buffer),
90/// and the inner service returns `Ok(Response)` for all HTTP statuses (including
91/// 4xx/5xx). Only transport-class failures reach the `Err` arm here — the
92/// `OTel` analogue of go-appkit's `status="0"`. Because the layer is outside the
93/// concurrency limiter, a load-shed rejection reaches this arm too and is
94/// recorded as `"overloaded"`. A connect that fails at the outbound proxy is
95/// `"proxy"`. Everything else collapses to `"other"` rather
96/// than enumerating variants that cannot occur at this point.
97fn error_type(err: &HttpError) -> &'static str {
98    match err {
99        HttpError::Timeout(_) => "timeout",
100        HttpError::DeadlineExceeded(_) => "deadline_exceeded",
101        HttpError::Transport(_) => "transport",
102        HttpError::Tls(_) => "tls",
103        HttpError::Overloaded => "overloaded",
104        HttpError::Proxy { .. } => "proxy",
105        _ => "other",
106    }
107}
108
109/// Tower layer recording HTTP client request-duration metrics.
110#[derive(Clone)]
111pub struct MetricsLayer {
112    duration: Histogram<f64>,
113    classify: ClassifyFn,
114}
115
116impl MetricsLayer {
117    /// Create a metrics layer.
118    ///
119    /// `client_type` names the OpenTelemetry instrumentation scope (the meter),
120    /// mirroring go-appkit's `ClientType` and the server-side `gear_name`.
121    /// `classify` produces the bounded `http.route` attribute for each request.
122    #[must_use]
123    pub fn new(client_type: &str, classify: ClassifyFn) -> Self {
124        let scope = opentelemetry::InstrumentationScope::builder(client_type.to_owned()).build();
125        let meter = global::meter_with_scope(scope);
126        Self::with_meter(&meter, classify)
127    }
128
129    /// Create a metrics layer using a caller-provided [`Meter`].
130    ///
131    /// Use this to bind the instrument to a specific `MeterProvider` instead of
132    /// the global one (e.g. for tests or multi-provider setups). The instrument
133    /// name, unit, bucket boundaries, and behavior are identical to [`new`](Self::new).
134    #[must_use]
135    pub fn with_meter(meter: &Meter, classify: ClassifyFn) -> Self {
136        let duration = meter
137            .f64_histogram("http.client.request.duration")
138            .with_description("Duration of outbound HTTP client requests")
139            .with_unit("s")
140            .with_boundaries(DURATION_BOUNDARIES_SECS.to_vec())
141            .build();
142        Self { duration, classify }
143    }
144}
145
146impl<S> Layer<S> for MetricsLayer {
147    type Service = MetricsService<S>;
148
149    fn layer(&self, inner: S) -> Self::Service {
150        MetricsService {
151            inner,
152            duration: self.duration.clone(),
153            classify: self.classify.clone(),
154        }
155    }
156}
157
158/// Service that records a duration metric for each outbound request.
159#[derive(Clone)]
160pub struct MetricsService<S> {
161    inner: S,
162    duration: Histogram<f64>,
163    classify: ClassifyFn,
164}
165
166impl<S> Service<Request<Full<Bytes>>> for MetricsService<S>
167where
168    S: Service<Request<Full<Bytes>>, Response = Response<ResponseBody>, Error = HttpError>
169        + Clone
170        + Send
171        + 'static,
172    S::Future: Send,
173{
174    type Response = Response<ResponseBody>;
175    type Error = HttpError;
176    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
177
178    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
179        self.inner.poll_ready(cx)
180    }
181
182    fn call(&mut self, req: Request<Full<Bytes>>) -> Self::Future {
183        // Compute attributes from the request up front; the request itself is
184        // moved into the inner service.
185        let route = (self.classify)(&req).into_owned();
186        let method = normalize_method(req.method());
187        let server_address = req.uri().host().unwrap_or("unknown").to_owned();
188        let server_port = req.uri().port_u16();
189        // Read request_type set by RequestBuilder::with_request_type — mirrors
190        // go-appkit's GetRequestTypeFromContext.
191        let request_type = req
192            .extensions()
193            .get::<RequestType>()
194            .map(|rt| rt.0.clone().into_owned());
195        let duration = self.duration.clone();
196
197        // Swap so we call the instance that was poll_ready'd, leaving a fresh
198        // clone for the next poll_ready cycle (Tower Service contract).
199        let clone = self.inner.clone();
200        let mut inner = std::mem::replace(&mut self.inner, clone);
201
202        Box::pin(async move {
203            let start = Instant::now();
204            let result = inner.call(req).await;
205            let elapsed = start.elapsed().as_secs_f64();
206
207            let mut attrs = vec![
208                KeyValue::new("http.request.method", method),
209                KeyValue::new("http.route", route),
210                KeyValue::new("server.address", server_address),
211            ];
212            // OTel client semconv pairs server.address with server.port; only
213            // explicit ports are present in the URI (default 80/443 are elided).
214            if let Some(port) = server_port {
215                attrs.push(KeyValue::new("server.port", i64::from(port)));
216            }
217            if let Some(rt) = request_type {
218                attrs.push(KeyValue::new("request_type", rt));
219            }
220            match &result {
221                Ok(response) => attrs.push(KeyValue::new(
222                    "http.response.status_code",
223                    i64::from(response.status().as_u16()),
224                )),
225                Err(e) => attrs.push(KeyValue::new("error.type", error_type(e))),
226            }
227            duration.record(elapsed, &attrs);
228
229            result
230        })
231    }
232}
233
234#[cfg(test)]
235#[cfg_attr(coverage_nightly, coverage(off))]
236mod tests {
237    use super::*;
238    use crate::request::RequestType;
239    use http::StatusCode;
240    use http_body_util::{BodyExt, Empty};
241    use opentelemetry::metrics::MeterProvider;
242    use opentelemetry_sdk::metrics::data::{AggregatedMetrics, HistogramDataPoint, MetricData};
243    use opentelemetry_sdk::metrics::{InMemoryMetricExporter, SdkMeterProvider};
244    use std::convert::Infallible;
245    use tower::{ServiceBuilder, ServiceExt, service_fn};
246
247    fn empty_response(status: StatusCode) -> Response<ResponseBody> {
248        let body: ResponseBody = Empty::<Bytes>::new()
249            .map_err(|e: Infallible| -> Box<dyn std::error::Error + Send + Sync> { match e {} })
250            .boxed();
251        Response::builder().status(status).body(body).unwrap()
252    }
253
254    /// Collect the histogram data point for `http.client.request.duration` whose
255    /// attributes contain every `(key, value)` in `expected`. Returns `None` if
256    /// no matching point was exported.
257    fn find_duration_point(
258        exporter: &InMemoryMetricExporter,
259        expected: &[(&str, &str)],
260    ) -> Option<HistogramDataPoint<f64>> {
261        let batches = exporter.get_finished_metrics().unwrap();
262        for rm in &batches {
263            for sm in rm.scope_metrics() {
264                for metric in sm.metrics() {
265                    if metric.name() != "http.client.request.duration" {
266                        continue;
267                    }
268                    let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
269                        continue;
270                    };
271                    for dp in hist.data_points() {
272                        let matches = expected.iter().all(|(k, v)| {
273                            dp.attributes()
274                                .any(|kv| kv.key.as_str() == *k && kv.value.to_string() == *v)
275                        });
276                        if matches {
277                            return Some(dp.clone());
278                        }
279                    }
280                }
281            }
282        }
283        None
284    }
285
286    fn test_provider() -> (SdkMeterProvider, InMemoryMetricExporter) {
287        let exporter = InMemoryMetricExporter::default();
288        let provider = SdkMeterProvider::builder()
289            .with_periodic_exporter(exporter.clone())
290            .build();
291        (provider, exporter)
292    }
293
294    #[tokio::test]
295    async fn records_duration_with_attributes_on_success() {
296        let (provider, exporter) = test_provider();
297        let meter = provider.meter("test-client");
298        let classify: ClassifyFn = Arc::new(|_req| Cow::Borrowed("GET /users/{id}"));
299        let layer = MetricsLayer::with_meter(&meter, classify);
300
301        let inner = service_fn(|_req: Request<Full<Bytes>>| async {
302            Ok::<_, HttpError>(empty_response(StatusCode::OK))
303        });
304        let mut svc = ServiceBuilder::new().layer(layer).service(inner);
305        let req = Request::builder()
306            .method(http::Method::GET)
307            .uri("https://example.com:8443/users/123")
308            .body(Full::new(Bytes::new()))
309            .unwrap();
310
311        let resp = svc.ready().await.unwrap().call(req).await.unwrap();
312        assert_eq!(resp.status(), StatusCode::OK);
313
314        provider.force_flush().unwrap();
315        let point = find_duration_point(
316            &exporter,
317            &[
318                ("http.request.method", "GET"),
319                ("http.route", "GET /users/{id}"),
320                ("server.address", "example.com"),
321                ("server.port", "8443"),
322                ("http.response.status_code", "200"),
323            ],
324        )
325        .expect("a duration data point with the expected attributes should be exported");
326        assert_eq!(point.count(), 1, "exactly one observation recorded");
327    }
328
329    #[tokio::test]
330    async fn records_error_type_on_transport_failure() {
331        let (provider, exporter) = test_provider();
332        let meter = provider.meter("test-client");
333        let layer = MetricsLayer::with_meter(&meter, Arc::new(default_classify));
334
335        let inner = service_fn(|_req: Request<Full<Bytes>>| async {
336            Err::<Response<ResponseBody>, _>(HttpError::Timeout(std::time::Duration::from_secs(1)))
337        });
338        let mut svc = ServiceBuilder::new().layer(layer).service(inner);
339        let req = Request::builder()
340            .method(http::Method::GET)
341            .uri("https://example.com/")
342            .body(Full::new(Bytes::new()))
343            .unwrap();
344
345        let err = svc.ready().await.unwrap().call(req).await.unwrap_err();
346        assert!(matches!(err, HttpError::Timeout(_)));
347
348        provider.force_flush().unwrap();
349        let point = find_duration_point(&exporter, &[("error.type", "timeout")])
350            .expect("a duration data point tagged error.type=timeout should be exported");
351        assert_eq!(point.count(), 1);
352        // Failures must not carry a status code.
353        assert!(
354            point
355                .attributes()
356                .all(|kv| kv.key.as_str() != "http.response.status_code"),
357            "transport failures must not record http.response.status_code"
358        );
359    }
360
361    #[test]
362    fn default_classify_normalizes_method_and_drops_path() {
363        let req = Request::builder()
364            .method(http::Method::POST)
365            .uri("https://api.example.com/users/abc-123-uuid")
366            .body(Full::new(Bytes::new()))
367            .unwrap();
368        // Raw path with an identifier must never leak into the label.
369        assert_eq!(default_classify(&req), "POST api.example.com");
370
371        let exotic = Request::builder()
372            .method(http::Method::from_bytes(b"PROPFIND").unwrap())
373            .uri("https://api.example.com/dav")
374            .body(Full::new(Bytes::new()))
375            .unwrap();
376        assert_eq!(default_classify(&exotic), "_OTHER api.example.com");
377    }
378
379    #[test]
380    fn normalize_method_caps_unknown() {
381        assert_eq!(normalize_method(&http::Method::GET), "GET");
382        let custom = http::Method::from_bytes(b"PROPFIND").unwrap();
383        assert_eq!(normalize_method(&custom), "_OTHER");
384    }
385
386    #[tokio::test]
387    async fn records_request_type_attribute_when_set() {
388        let (provider, exporter) = test_provider();
389        let meter = provider.meter("test-client");
390        let layer = MetricsLayer::with_meter(&meter, Arc::new(default_classify));
391
392        let inner = service_fn(|_req: Request<Full<Bytes>>| async {
393            Ok::<_, HttpError>(empty_response(StatusCode::OK))
394        });
395        let mut svc = ServiceBuilder::new().layer(layer).service(inner);
396
397        let mut req = Request::builder()
398            .method(http::Method::GET)
399            .uri("https://example.com/tenants/123")
400            .body(Full::new(Bytes::new()))
401            .unwrap();
402        req.extensions_mut()
403            .insert(RequestType::new("tenants_resolve"));
404
405        svc.ready().await.unwrap().call(req).await.unwrap();
406
407        provider.force_flush().unwrap();
408        let point = find_duration_point(&exporter, &[("request_type", "tenants_resolve")])
409            .expect("request_type attribute should appear in exported metric");
410        assert_eq!(point.count(), 1);
411    }
412
413    #[tokio::test]
414    async fn omits_request_type_when_not_set() {
415        let (provider, exporter) = test_provider();
416        let meter = provider.meter("test-client");
417        let layer = MetricsLayer::with_meter(&meter, Arc::new(default_classify));
418
419        let inner = service_fn(|_req: Request<Full<Bytes>>| async {
420            Ok::<_, HttpError>(empty_response(StatusCode::OK))
421        });
422        let mut svc = ServiceBuilder::new().layer(layer).service(inner);
423
424        let req = Request::builder()
425            .method(http::Method::GET)
426            .uri("https://example.com/tenants/123")
427            .body(Full::new(Bytes::new()))
428            .unwrap();
429
430        svc.ready().await.unwrap().call(req).await.unwrap();
431
432        provider.force_flush().unwrap();
433        let dp = find_duration_point(&exporter, &[("http.request.method", "GET")])
434            .expect("a data point should be exported");
435        assert!(
436            dp.attributes().all(|kv| kv.key.as_str() != "request_type"),
437            "request_type must not appear when not set"
438        );
439    }
440
441    #[test]
442    fn error_type_maps_transport_class_failures() {
443        assert_eq!(
444            error_type(&HttpError::Timeout(std::time::Duration::from_secs(1))),
445            "timeout"
446        );
447        assert_eq!(
448            error_type(&HttpError::Transport("boom".into())),
449            "transport"
450        );
451        assert_eq!(error_type(&HttpError::Overloaded), "overloaded");
452        assert_eq!(
453            error_type(&HttpError::Proxy {
454                kind: crate::error::ProxyErrorKind::AuthRequired,
455                proxy: "http://proxy:3128".to_owned(),
456            }),
457            "proxy"
458        );
459    }
460
461    /// A load-shed rejection (`HttpError::Overloaded`) reaching this layer — as
462    /// it does in `build()`, where the concurrency limiter is inner to the
463    /// metrics layer — is recorded as `error.type = "overloaded"`, so shed
464    /// requests are counted rather than invisible.
465    #[tokio::test]
466    async fn records_error_type_overloaded_when_shed() {
467        let (provider, exporter) = test_provider();
468        let meter = provider.meter("test-client");
469        let layer = MetricsLayer::with_meter(&meter, Arc::new(default_classify));
470
471        let inner = service_fn(|_req: Request<Full<Bytes>>| async {
472            Err::<Response<ResponseBody>, _>(HttpError::Overloaded)
473        });
474        let mut svc = ServiceBuilder::new().layer(layer).service(inner);
475        let req = Request::builder()
476            .method(http::Method::GET)
477            .uri("https://example.com/")
478            .body(Full::new(Bytes::new()))
479            .unwrap();
480
481        let err = svc.ready().await.unwrap().call(req).await.unwrap_err();
482        assert!(matches!(err, HttpError::Overloaded));
483
484        provider.force_flush().unwrap();
485        let point = find_duration_point(&exporter, &[("error.type", "overloaded")])
486            .expect("a shed request should record error.type=overloaded");
487        assert_eq!(point.count(), 1);
488    }
489}