footing 0.1.12

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

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

use crate::{
    clock::{SharedClock, system_clock},
    observability::{
        MetricLabels, MetricRecorder, MetricRegistry, 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,
}

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

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

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

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

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> Service<Request<Body>> for HttpMetricsService<S>
where
    S: Service<Request<Body>, Response = Response>,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    type Response = Response;
    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<Body>) -> Self::Future {
        let start = self.clock.now();
        let recorder = self.recorder.clone();
        let clock = self.clock.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;
            match &result {
                Ok(response) => {
                    record_http_metrics(
                        recorder.as_ref(),
                        method,
                        &route,
                        response.status().as_u16(),
                        clock.now().saturating_duration_since(start),
                    );
                }
                Err(_) => {
                    let _ = recorder.increment_counter(
                        metric_names::HTTP_SERVER_ERRORS_TOTAL,
                        1,
                        MetricLabels::from_lossy([
                            (metric_labels::METHOD, method),
                            (metric_labels::ROUTE, route.as_str()),
                            (metric_labels::ERROR, "service"),
                        ]),
                    );
                }
            }
            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.
pub fn record_http_metrics(
    recorder: &dyn MetricRecorder,
    method: &str,
    route: &str,
    status: u16,
    elapsed: Duration,
) {
    let status = status.to_string();
    let labels = MetricLabels::from_lossy([
        (metric_labels::METHOD, method_label(method)),
        (metric_labels::ROUTE, route),
        (metric_labels::STATUS, status.as_str()),
    ]);
    let _ = recorder.increment_counter(metric_names::HTTP_SERVER_REQUESTS_TOTAL, 1, labels.clone());
    let _ = recorder.observe_histogram(
        metric_names::HTTP_SERVER_REQUEST_DURATION_SECONDS,
        elapsed.as_secs_f64(),
        labels,
    );
}

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

    use super::*;

    #[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"));
    }
}