footing 0.1.18

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
use std::{
    fmt,
    future::Future,
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    task::{Context, Poll},
    time::Duration,
};

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

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

/// OpenMetrics content type.
pub const OPENMETRICS_CONTENT_TYPE: &str = OpenMetricsExporter::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)]
/// Tower layer that applies HTTP metrics.
pub struct HttpMetricsLayer {
    recorder: Arc<dyn MetricRecorder>,
    clock: SharedClock,
    failed_recordings: Arc<AtomicU64>,
}

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

    #[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
    }

    #[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.load(Ordering::Relaxed)
    }

    #[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")
            .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(),
        }
    }
}

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

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,
    S::Error: Send + 'static,
{
    type Response = Response<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 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)
                }),
            };
            if let Err(error) = recording {
                let previous = failed_recordings
                    .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
                        Some(value.saturating_add(1))
                    })
                    .unwrap_or_else(|value| value);
                let failures = previous.saturating_add(1);
                // Log the first failure and powers of two, never metric label values.
                if failures.is_power_of_two() {
                    tracing::warn!(failures, error = %error, "HTTP metric recording failed");
                }
            }
            result
        })
    }
}

/// A response containing metrics.
pub struct MetricsResponse(pub MetricsSnapshot);

impl IntoResponse for MetricsResponse {
    fn into_response(self) -> Response {
        let export = match OpenMetricsExporter.export(&self.0) {
            Ok(export) => export,
            Err(never) => match never {},
        };
        let mut response = export.into_body().into_response();
        response.headers_mut().insert(
            CONTENT_TYPE,
            axum::http::HeaderValue::from_static(OPENMETRICS_CONTENT_TYPE),
        );
        response
    }
}

/// Records HTTP metrics with strict labels, returning validation or recorder errors.
/// The counter is written before the histogram; writes are not transactional.
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,
        routing::get,
    };
    use tower::ServiceExt;

    use super::*;

    #[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<()>, _>("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 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"),
        ]))
        .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"));
    }
}