footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! HTTP metrics for independently composed Axum/Tower services.
//!
//! Enable `http-metrics` to use this module, or `http-stack` to include it with
//! footing's complete middleware stack:
//!
//! ```toml
//! footing = { version = "0.6", default-features = false, features = ["http-metrics"] }
//! ```
//!
//! The feature uses the shared [`crate::observability`] metrics infrastructure.
//! It does not enable compression, CORS, pagination, or stack assembly. Routes
//! and middleware are installed explicitly by the application.
//! Log formatting and subscriber initialization are independent: use your own
//! subscriber or enable Footing's `logging` feature.
//!
//! Apply [`HttpMetricsLayer`] to a router after declaring its routes so labels
//! use matched patterns such as `/items/{id}`. Unmatched requests use
//! [`HTTP_METRICS_UNMATCHED_ROUTE`]; raw URLs and user identifiers are not labels.
//! The default metrics count responses and measure time until response headers
//! are ready. [`HttpMetricsLayer::with_response_body_metrics`] additionally
//! observes body consumption without buffering it.
//!
//! This example exports both Prometheus and OpenMetrics formats using `Accept`.
//! The export route is merged after applying the layer so scrapes do not count
//! as application requests. The host application controls access to that route.
//!
//! ```
//! use std::sync::Arc;
//! use axum::{
//!     Router, extract::State, http::{HeaderMap, StatusCode},
//!     response::Response, routing::get,
//! };
//! use footing::{
//!     http::{HttpMetricsLayer, MetricsResponse},
//!     observability::MetricRegistry,
//! };
//!
//! async fn export_metrics(
//!     State(registry): State<Arc<MetricRegistry>>,
//!     headers: HeaderMap,
//! ) -> Result<Response, StatusCode> {
//!     let snapshot = registry.snapshot().map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
//!     Ok(MetricsResponse(snapshot).negotiate(&headers))
//! }
//!
//! let (metrics, registry) = HttpMetricsLayer::in_memory();
//! let api = Router::new()
//!     .route("/items/{id}", get(|| async { "ok" }))
//!     .layer(metrics);
//! let monitoring = Router::new()
//!     .route("/metrics", get(export_metrics))
//!     .with_state(registry);
//! let app: Router = api.merge(monitoring);
//! ```

use std::{
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum::{extract::MatchedPath, http::Request, response::Response};
use tower::{Layer, Service};

use crate::{
    clock::{SharedClock, system_clock},
    observability::{
        MetricLabels, MetricRecorder, MetricRegistry, MetricsError, RecordingFailures,
        metric_labels, metric_names,
    },
};

mod body;
mod response;
pub use body::HttpMetricsBody;
pub use response::{MetricsResponse, OPENMETRICS_CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE};
/// HTTP metrics unmatched route.
pub const HTTP_METRICS_UNMATCHED_ROUTE: &str = "unmatched";

fn route_label<B>(request: &Request<B>) -> &str {
    request
        .extensions()
        .get::<MatchedPath>()
        .map(MatchedPath::as_str)
        .unwrap_or(HTTP_METRICS_UNMATCHED_ROUTE)
}

fn method_label(method: &str) -> &'static str {
    match method {
        "GET" => "GET",
        "HEAD" => "HEAD",
        "POST" => "POST",
        "PUT" => "PUT",
        "DELETE" => "DELETE",
        "CONNECT" => "CONNECT",
        "OPTIONS" => "OPTIONS",
        "TRACE" => "TRACE",
        "PATCH" => "PATCH",
        "QUERY" => "QUERY",
        _ => "_OTHER",
    }
}

#[derive(Clone)]
/// Records responses and latency up to response headers becoming available.
///
/// Enable [`Self::with_response_body_metrics`] to also observe response bodies.
pub struct HttpMetricsLayer {
    recorder: Arc<dyn MetricRecorder>,
    clock: SharedClock,
    failed_recordings: RecordingFailures,
    response_body_metrics: bool,
}

impl HttpMetricsLayer {
    #[must_use]
    /// Creates a new instance.
    pub fn new(recorder: Arc<dyn MetricRecorder>) -> Self {
        Self {
            recorder,
            clock: system_clock(),
            failed_recordings: RecordingFailures::default(),
            response_body_metrics: false,
        }
    }

    #[must_use]
    /// Creates in memory.
    pub fn in_memory() -> (Self, Arc<MetricRegistry>) {
        let registry = Arc::new(MetricRegistry::new());
        (Self::new(registry.clone()), registry)
    }

    #[must_use]
    /// Configures clock and returns the updated value.
    pub fn with_clock(mut self, clock: SharedClock) -> Self {
        self.clock = clock;
        self
    }

    /// Enables separate response-body duration and outcome metrics; disabled by default.
    ///
    /// Observes bodies as they are polled, without buffering or reading ahead.
    /// Durations start when response headers are ready and include consumer wait
    /// time. Outcomes are `completed`, `error`, or `incomplete` (dropped before
    /// completion). They describe body consumption, not delivery over the network
    /// or the reason for cancellation. Existing request metrics keep their meaning.
    ///
    /// Place body timeout middleware inside this layer to observe its errors.
    /// Apply this layer after routing so metric labels use matched route patterns.
    ///
    /// ```
    /// use axum::{Router, routing::get};
    /// use footing::http::HttpMetricsLayer;
    ///
    /// let (metrics, registry) = HttpMetricsLayer::in_memory();
    /// let app: Router = Router::new()
    ///     .route("/items/{id}", get(|| async { "body" }))
    ///     .layer(metrics.with_response_body_metrics(true));
    /// ```
    #[must_use]
    pub const fn with_response_body_metrics(mut self, enabled: bool) -> Self {
        self.response_body_metrics = enabled;
        self
    }

    /// Whether response-body duration and outcome metrics are enabled.
    #[must_use]
    pub const fn response_body_metrics_enabled(&self) -> bool {
        self.response_body_metrics
    }

    #[must_use]
    /// Returns the recorder.
    pub fn recorder(&self) -> &Arc<dyn MetricRecorder> {
        &self.recorder
    }

    /// Failed recording attempts across all services and clones of this layer.
    /// Includes invalid labels and recorder errors; a request's counter may
    /// succeed before its histogram fails. This is not a count of HTTP errors.
    /// Stored independently of the recorder so capacity exhaustion remains visible.
    #[must_use]
    pub fn failed_recordings(&self) -> u64 {
        self.failed_recordings.count()
    }

    #[must_use]
    /// Returns the clock.
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }
}

impl fmt::Debug for HttpMetricsLayer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HttpMetricsLayer")
            .field("response_body_metrics", &self.response_body_metrics)
            .finish_non_exhaustive()
    }
}

impl<S> Layer<S> for HttpMetricsLayer {
    type Service = HttpMetricsService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        HttpMetricsService {
            inner,
            recorder: self.recorder.clone(),
            clock: self.clock.clone(),
            failed_recordings: self.failed_recordings.clone(),
            response_body_metrics: self.response_body_metrics,
        }
    }
}

#[derive(Clone)]
/// Service for HTTP metrics.
pub struct HttpMetricsService<S> {
    inner: S,
    recorder: Arc<dyn MetricRecorder>,
    clock: SharedClock,
    failed_recordings: RecordingFailures,
    response_body_metrics: bool,
}

impl<S> fmt::Debug for HttpMetricsService<S>
where
    S: fmt::Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HttpMetricsService")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for HttpMetricsService<S>
where
    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
    S::Future: Send + 'static,
    ResBody: http_body::Body,
{
    type Response = Response<HttpMetricsBody<ResBody>>;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(context)
    }

    fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
        let start = self.clock.now();
        let recorder = self.recorder.clone();
        let clock = self.clock.clone();
        let failed_recordings = self.failed_recordings.clone();
        let response_body_metrics = self.response_body_metrics;
        let method = method_label(request.method().as_str());
        let route = route_label(&request).to_owned();
        let future = self.inner.call(request);

        Box::pin(async move {
            let result = future.await;
            let recording = match &result {
                Ok(response) => record_http_metrics(
                    recorder.as_ref(),
                    method,
                    &route,
                    response.status().as_u16(),
                    clock.now().saturating_duration_since(start),
                ),
                Err(_) => MetricLabels::new([
                    (metric_labels::METHOD, method),
                    (metric_labels::ROUTE, route.as_str()),
                    (metric_labels::ERROR, "service"),
                ])
                .and_then(|labels| {
                    recorder.increment_counter(metric_names::HTTP_SERVER_ERRORS_TOTAL, 1, labels)
                }),
            };
            failed_recordings.record(recording, "http");
            result.map(|response| {
                body::observe_response(
                    response,
                    recorder,
                    clock,
                    failed_recordings,
                    method,
                    route,
                    response_body_metrics,
                )
            })
        })
    }
}

/// Records HTTP metrics with strict labels, returning validation or recorder errors.
/// The counter is written before the histogram; writes are not transactional.
/// `elapsed` covers the service call through response headers, not body consumption.
pub fn record_http_metrics(
    recorder: &dyn MetricRecorder,
    method: &str,
    route: &str,
    status: u16,
    elapsed: Duration,
) -> Result<(), MetricsError> {
    let status = status.to_string();
    let labels = MetricLabels::new([
        (metric_labels::METHOD, method_label(method)),
        (metric_labels::ROUTE, route),
        (metric_labels::STATUS, status.as_str()),
    ])?;
    recorder.increment_counter(metric_names::HTTP_SERVER_REQUESTS_TOTAL, 1, labels.clone())?;
    recorder.observe_histogram(
        metric_names::HTTP_SERVER_REQUEST_DURATION_SECONDS,
        elapsed.as_secs_f64(),
        labels,
    )
}

#[cfg(test)]
mod tests {
    use axum::{
        Router,
        body::{Body, to_bytes},
        http::{StatusCode, header::CONTENT_TYPE},
        response::IntoResponse,
        routing::get,
    };
    use tower::ServiceExt;

    use super::*;
    use crate::observability::MetricsSnapshot;

    #[tokio::test]
    async fn metrics_compose_with_request_and_response_body_wrappers() {
        use http_body_util::{BodyExt, Full};
        use tower_http::timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer, TimeoutBody};

        let (layer, registry) = HttpMetricsLayer::in_memory();
        let inner = tower::service_fn(|request: Request<TimeoutBody<Body>>| async move {
            let body = request.into_body().collect().await.unwrap().to_bytes();
            Ok::<_, std::convert::Infallible>(Response::new(Full::new(body)))
        });
        let service = RequestBodyTimeoutLayer::new(Duration::from_secs(1))
            .layer(layer.layer(ResponseBodyTimeoutLayer::new(Duration::from_secs(1)).layer(inner)));
        let response = service
            .oneshot(Request::new(Body::from("payload")))
            .await
            .unwrap();
        assert_eq!(
            response.into_body().collect().await.unwrap().to_bytes(),
            "payload"
        );
        assert_eq!(registry.snapshot().unwrap().samples().len(), 2);
        assert_eq!(layer.failed_recordings(), 0);
    }

    #[tokio::test]
    async fn recording_failures_are_shared_and_do_not_change_responses() {
        let registry = Arc::new(MetricRegistry::with_limits(
            crate::observability::MetricRegistryLimits::new(1, 1).unwrap(),
        ));
        let layer = HttpMetricsLayer::new(registry.clone());
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(layer.clone());
        for _ in 0..3 {
            let response = app
                .clone()
                .oneshot(Request::new(Body::empty()))
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
            assert_eq!(to_bytes(response.into_body(), 16).await.unwrap(), "ok");
        }
        // The counter succeeds; the histogram cannot allocate a second series.
        assert_eq!(layer.failed_recordings(), 3);
        assert_eq!(registry.snapshot().unwrap().samples()[0].value(), 3.0);

        let service = layer
            .clone()
            .layer(tower::service_fn(|_: Request<()>| async {
                Err::<Response<Body>, _>("service failed")
            }));
        assert_eq!(
            service.oneshot(Request::new(())).await.unwrap_err(),
            "service failed"
        );
        assert_eq!(layer.failed_recordings(), 4);
    }

    #[tokio::test]
    async fn oversized_routes_are_rejected_without_losing_the_route_label() {
        let route = format!("/{}", "x".repeat(300));
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let app = Router::new()
            .route(&route, get(|| async {}))
            .layer(layer.clone());
        let response = app
            .oneshot(Request::get(&route).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(layer.failed_recordings(), 1);
        assert!(registry.snapshot().unwrap().samples().is_empty());

        let larger = MetricRegistry::with_limits(
            crate::observability::MetricRegistryLimits::default()
                .with_max_label_value_length(1024)
                .unwrap(),
        );
        record_http_metrics(&larger, "GET", &route, 200, Duration::ZERO).unwrap();
        for sample in larger.snapshot().unwrap().samples() {
            assert!(
                sample
                    .labels()
                    .iter()
                    .any(|(key, value)| key == "route" && value == &route)
            );
        }

        assert_eq!(
            record_http_metrics(registry.as_ref(), "GET", "bad\nroute", 200, Duration::ZERO),
            Err(MetricsError::InvalidLabelValue)
        );
        assert!(registry.snapshot().unwrap().samples().is_empty());
    }

    #[tokio::test]
    async fn metrics_accept_non_clone_services_and_call_the_ready_instance() {
        struct ReadyService(bool);

        impl Service<Request<Body>> for ReadyService {
            type Response = Response;
            type Error = std::convert::Infallible;
            type Future = std::future::Ready<Result<Response, Self::Error>>;

            fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                self.0 = true;
                Poll::Ready(Ok(()))
            }

            fn call(&mut self, _: Request<Body>) -> Self::Future {
                assert!(
                    std::mem::take(&mut self.0),
                    "call must use the ready service"
                );
                std::future::ready(Ok("ok".into_response()))
            }
        }

        let (layer, registry) = HttpMetricsLayer::in_memory();
        let mut service = layer.layer(ReadyService(false));
        for _ in 0..2 {
            service
                .ready()
                .await
                .unwrap()
                .call(Request::new(Body::empty()))
                .await
                .unwrap();
        }
        let snapshot = registry.snapshot().unwrap();
        let requests = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .unwrap();
        assert_eq!(requests.value(), 2.0);
    }

    #[tokio::test]
    async fn metrics_preserve_non_send_service_errors_and_record_them() {
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let service = layer.layer(tower::service_fn(|_: Request<()>| async {
            tokio::task::yield_now().await;
            Err::<Response<Body>, _>(std::rc::Rc::new(String::from("local service failure")))
        }));
        let error = service
            .oneshot(Request::post("/jobs/42").body(()).unwrap())
            .await
            .unwrap_err();

        assert_eq!(error.as_str(), "local service failure");
        let snapshot = registry.snapshot().unwrap();
        assert_eq!(snapshot.samples().len(), 1);
        let sample = &snapshot.samples()[0];
        assert_eq!(sample.name(), metric_names::HTTP_SERVER_ERRORS_TOTAL);
        assert_eq!(sample.value(), 1.0);
        assert_eq!(sample.labels().len(), 3);
        for (name, value) in [
            (metric_labels::METHOD, "POST"),
            (metric_labels::ROUTE, HTTP_METRICS_UNMATCHED_ROUTE),
            (metric_labels::ERROR, "service"),
        ] {
            assert!(sample.labels().contains(&(name.into(), value.into())));
        }
        assert_eq!(layer.failed_recordings(), 0);
    }

    #[tokio::test]
    async fn unknown_methods_share_one_label_and_leave_room_for_normal_requests() {
        let registry = Arc::new(MetricRegistry::with_limits(
            crate::observability::MetricRegistryLimits::new(10, 2).unwrap(),
        ));
        let app = Router::new()
            .route("/health", get(|| async { "ok" }))
            .layer(HttpMetricsLayer::new(registry.clone()));
        for method in ["CUSTOM_A", "CUSTOM_B", "GET"] {
            app.clone()
                .oneshot(
                    Request::builder()
                        .uri("/health")
                        .method(method)
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
        }
        let snapshot = registry.snapshot().unwrap();
        let requests: Vec<_> = snapshot
            .samples()
            .iter()
            .filter(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .collect();
        assert_eq!(requests.len(), 2);
        for (method, count) in [("_OTHER", 2.0), ("GET", 1.0)] {
            assert!(requests.iter().any(|sample| sample.value() == count
                && sample.labels().contains(&("method".into(), method.into()))));
        }
    }

    #[tokio::test]
    async fn metrics_layer_records_requests() {
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let response = Router::new()
            .route("/health", get(|| async { "ok" }))
            .layer(layer)
            .oneshot(
                Request::get("/health")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");

        assert_eq!(response.status(), StatusCode::OK);
        let snapshot = registry.snapshot().expect("snapshot should build");
        let sample = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .expect("request counter should be recorded");
        assert_eq!(
            sample
                .labels()
                .iter()
                .find(|(name, _)| name == metric_labels::ROUTE)
                .map(|(_, value)| value.as_str()),
            Some("/health")
        );
    }

    #[tokio::test]
    async fn metrics_layer_uses_matched_route_instead_of_raw_identifier() {
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let response = Router::new()
            .route("/users/{id}", get(|| async { "ok" }))
            .layer(layer)
            .oneshot(
                Request::get("/users/123")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");

        assert_eq!(response.status(), StatusCode::OK);
        let snapshot = registry.snapshot().expect("snapshot should build");
        let sample = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .expect("request counter should be recorded");
        assert_eq!(
            sample
                .labels()
                .iter()
                .find(|(name, _)| name == metric_labels::ROUTE)
                .map(|(_, value)| value.as_str()),
            Some("/users/{id}")
        );
    }

    #[test]
    fn route_label_strategy_never_uses_raw_path_by_default() {
        let request = Request::get("/users/123")
            .body(Body::empty())
            .expect("request should build");

        assert_eq!(route_label(&request), HTTP_METRICS_UNMATCHED_ROUTE);
    }

    #[tokio::test]
    async fn metrics_response_uses_openmetrics_content_type() {
        let response = MetricsResponse(
            MetricsSnapshot::new(vec![
                crate::observability::MetricSample::counter("jobs_total", 1)
                    .expect("metric sample should build"),
            ])
            .unwrap(),
        )
        .into_response();

        assert_eq!(
            response
                .headers()
                .get(CONTENT_TYPE)
                .and_then(|value| value.to_str().ok()),
            Some(OPENMETRICS_CONTENT_TYPE)
        );
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should read");
        assert!(String::from_utf8_lossy(&body).contains("jobs_total"));
    }
}