webserver-base 0.4.6

A Rust library which contains shared logic for all of my webserver projects.
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Request ids and Prometheus metrics, on for every server.

use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::OnceLock;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use axum::Router;
use axum::body::{Body, Bytes};
use axum::extract::{MatchedPath, Request};
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderName, HeaderValue, Method};
use axum::middleware::Next;
use axum::response::Response;
use axum::routing::get;
use http_body::{Frame, SizeHint};
use metrics_exporter_prometheus::{
    Matcher, PrometheusBuilder, PrometheusHandle, PrometheusRecorder,
};
use tokio::net::TcpListener;
use tower_http::request_id::{MakeRequestId, MakeRequestUuid, RequestId};
use tracing::{error, info};

use super::shutdown::Shutdown;
use crate::traces::HTTP_SERVER_OP;

/// The port `/metrics` is served on, inside the container, in production only.
///
/// Fixed on purpose: every container has its own network namespace, so the same
/// port never collides, and it is never published, so only the scraper on the
/// host (the container's bridge address) can reach it. Not served locally, where
/// two projects running at once would collide.
pub const METRICS_PORT: u16 = 9000;

/// The request id header: reused when nginx sent one, generated otherwise, and
/// echoed on the response.
pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id");

/// Upper bound on an incoming request id. nginx's `$request_id` is 32 hex
/// characters; anything longer or stranger is replaced rather than logged.
const MAX_REQUEST_ID_LEN: usize = 64;

/// Seconds: the OpenTelemetry default boundaries, so dashboards and
/// cross-project comparisons line up.
const DURATION_BUCKETS: [f64; 14] = [
    0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0,
];

/// Bytes: 256 B to 4 MiB, for request and response bodies.
const SIZE_BUCKETS: [f64; 8] = [
    256.0,
    1024.0,
    4096.0,
    16384.0,
    65536.0,
    262_144.0,
    1_048_576.0,
    4_194_304.0,
];

const DURATION_METRICS: [&str; 2] = [
    "http_request_duration_seconds",
    "http_client_request_duration_seconds",
];

const SIZE_METRICS: [&str; 4] = [
    "http_request_body_size_bytes",
    "http_response_body_size_bytes",
    "http_client_request_body_size_bytes",
    "http_client_response_body_size_bytes",
];

/// Histograms are only drained into their buckets by upkeep.
const UPKEEP_INTERVAL: Duration = Duration::from_secs(5);

static RELEASE: OnceLock<String> = OnceLock::new();
static HANDLE: OnceLock<PrometheusHandle> = OnceLock::new();

/// Records the application's release (`name@version`) for `build_info`.
pub(crate) fn set_release(release: &str) {
    let _ = RELEASE.set(release.to_owned());
}

/// The process-wide recorder, installed on first use.
///
/// A second server in the same process (tests) shares it rather than fighting
/// over the one global recorder slot.
pub(crate) fn handle() -> &'static PrometheusHandle {
    HANDLE.get_or_init(|| {
        let mut builder: PrometheusBuilder = PrometheusBuilder::new();
        for (names, buckets) in [
            (DURATION_METRICS.as_slice(), DURATION_BUCKETS.as_slice()),
            (SIZE_METRICS.as_slice(), SIZE_BUCKETS.as_slice()),
        ] {
            for name in names {
                builder = builder
                    .set_buckets_for_metric(Matcher::Full((*name).to_owned()), buckets)
                    .expect("the buckets are non-empty");
            }
        }
        let recorder: PrometheusRecorder = builder.build_recorder();
        let handle: PrometheusHandle = recorder.handle();
        let _ = metrics::set_global_recorder(recorder);
        let release: String = RELEASE.get().cloned().unwrap_or_default();
        metrics::gauge!(
            "build_info",
            "release" => release,
            "webserver_base" => env!("CARGO_PKG_VERSION")
        )
        .set(1.0);
        // Registered at 0, so the series exist before the first failure.
        for listener in ["app", "metrics"] {
            metrics::counter!("http_accept_errors_total", "listener" => listener).increment(0);
        }
        handle
    })
}

fn is_valid_request_id(value: &HeaderValue) -> bool {
    let bytes: &[u8] = value.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= MAX_REQUEST_ID_LEN
        && bytes
            .iter()
            .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-' || *byte == b'_')
}

/// The `op` of a request that is not traced. The sampler gives every `op` but
/// [`HTTP_SERVER_OP`] a rate of zero.
const UNTRACED_OP: &str = "http.server.untraced";

/// Which routes become Sentry transactions.
///
/// A request is traced only if it matched a route of the site's own. Never
/// traced: what no one reads a trace of and would drown the quota (static
/// assets and the project's own nested services, icons, well-known documents,
/// feeds, trailing-slash redirects, the health check, the analytics and Sentry
/// proxies) and what matched nothing (a 404 is a scanner).
#[derive(Debug, Clone)]
pub(crate) struct TraceRoutes {
    untraced: Vec<String>,
    /// Patterns matched whole, never as a prefix (a trailing-slash redirect
    /// `/docs` must not untrace the page `/docs/{slug}`).
    untraced_exact: Vec<String>,
}

impl TraceRoutes {
    /// Everything except `untraced` (route patterns, or the prefix a service is
    /// nested under).
    pub(crate) const fn new(untraced: Vec<String>) -> Self {
        Self {
            untraced,
            untraced_exact: Vec::new(),
        }
    }

    /// Also never traces these route patterns, matched exactly.
    #[must_use]
    pub(crate) fn with_untraced_exact(mut self, untraced_exact: Vec<String>) -> Self {
        self.untraced_exact = untraced_exact;
        self
    }

    /// Whether a request that matched `route` (`None`: matched nothing) is
    /// traced.
    pub(crate) fn is_traced(&self, route: Option<&str>) -> bool {
        route.is_some_and(|route: &str| {
            !self
                .untraced_exact
                .iter()
                .any(|exact: &String| route == exact)
                && !self.untraced.iter().any(|untraced: &String| {
                    route == untraced
                        || route
                            .strip_prefix(untraced.as_str())
                            .is_some_and(|rest: &str| rest.starts_with('/'))
                })
        })
    }

    /// The request's `tracing` span, which `sentry-tracing` turns into the
    /// transaction. `sentry.*` fields are its convention for the transaction's
    /// name, `op` and incoming `sentry-trace`.
    ///
    /// Named by route pattern (`GET /blog/{slug}`), never the raw path, so
    /// transactions group. `sentry-trace` is passed on only to continue the
    /// browser's trace id; the sampler ignores its sampled flag.
    pub(crate) fn span(&self, request: &Request) -> tracing::Span {
        let request_id: &str = request
            .headers()
            .get(&REQUEST_ID_HEADER)
            .and_then(|value: &HeaderValue| value.to_str().ok())
            .unwrap_or_default();
        let route: Option<&str> = request
            .extensions()
            .get::<MatchedPath>()
            .map(MatchedPath::as_str);
        let traced: bool = self.is_traced(route);
        let name: String = format!("{} {}", request.method(), route.unwrap_or("unmatched"));
        let incoming: Option<&str> = traced
            .then(|| request.headers().get("sentry-trace"))
            .flatten()
            .and_then(|value: &HeaderValue| value.to_str().ok());
        // `path`, not the URI: query strings can carry one-time codes and
        // tokens. `request_id` joins these lines to nginx's access log. At
        // INFO: under an INFO filter a DEBUG span is never created, and every
        // request would log a status with no route.
        tracing::info_span!(
            "request",
            "sentry.name" = name.as_str(),
            "sentry.op" = if traced { HTTP_SERVER_OP } else { UNTRACED_OP },
            "sentry.trace" = incoming,
            method = %request.method(),
            path = %request.uri().path(),
            version = ?request.version(),
            request_id,
        )
    }
}

/// Puts a request id on every request and response.
///
/// Runs outside the trace layer, so the request span (and so every log line of
/// the request) carries the same id as nginx's access log line.
pub(crate) async fn request_id(mut request: Request, next: Next) -> Response {
    let id: HeaderValue = match request.headers().get(&REQUEST_ID_HEADER) {
        Some(value) if is_valid_request_id(value) => value.clone(),
        _ => MakeRequestUuid
            .make_request_id(&request)
            .map(RequestId::into_header_value)
            .expect("a UUID always makes a request id"),
    };
    request.headers_mut().insert(REQUEST_ID_HEADER, id.clone());
    let mut response: Response = next.run(request).await;
    response.headers_mut().insert(REQUEST_ID_HEADER, id);
    response
}

/// Methods outside the standard set share one label, so a client cannot grow
/// the series count.
fn method_label(method: &Method) -> &'static str {
    match *method {
        Method::GET => "GET",
        Method::HEAD => "HEAD",
        Method::POST => "POST",
        Method::PUT => "PUT",
        Method::PATCH => "PATCH",
        Method::DELETE => "DELETE",
        Method::OPTIONS => "OPTIONS",
        _ => "other",
    }
}

/// A byte count as a histogram sample.
#[expect(
    clippy::cast_precision_loss,
    reason = "a size past 2^53 bytes only loses precision inside a histogram bucket"
)]
pub(super) const fn byte_sample(bytes: u64) -> f64 {
    bytes as f64
}

/// Passes a body through untouched, counting its bytes as they stream (never
/// buffering), and records the total to a size histogram when dropped: at the
/// end of the stream, or early if the peer disconnects or the handler stops
/// reading. So a request size is the bytes the app read.
struct CountedBody {
    inner: Body,
    bytes: u64,
    metric: &'static str,
    method: &'static str,
    route: String,
}

impl CountedBody {
    fn wrap(body: Body, metric: &'static str, method: &'static str, route: &str) -> Body {
        Body::new(Self {
            inner: body,
            bytes: 0,
            metric,
            method,
            route: route.to_owned(),
        })
    }
}

impl http_body::Body for CountedBody {
    type Data = Bytes;
    type Error = axum::Error;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
        let polled: Poll<Option<Result<Frame<Bytes>, axum::Error>>> =
            Pin::new(&mut self.inner).poll_frame(context);
        if let Poll::Ready(Some(Ok(frame))) = &polled
            && let Some(data) = frame.data_ref()
        {
            self.bytes += data.len() as u64;
        }
        polled
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.inner.size_hint()
    }
}

impl Drop for CountedBody {
    fn drop(&mut self) {
        metrics::histogram!(
            self.metric,
            "method" => self.method,
            "route" => std::mem::take(&mut self.route)
        )
        .record(byte_sample(self.bytes));
    }
}

/// A server-sent-events response never ends on its own, so its size is not
/// sampled: one huge value per stream, all at once when a deploy closes them.
fn is_event_stream(response: &Response) -> bool {
    response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value: &HeaderValue| value.to_str().ok())
        .is_some_and(|value: &str| {
            value.split(';').next().is_some_and(|essence: &str| {
                essence.trim().eq_ignore_ascii_case("text/event-stream")
            })
        })
}

/// `http_requests_total`, `http_request_duration_seconds`,
/// `http_request_body_size_bytes`, `http_response_body_size_bytes` and
/// `http_requests_in_flight`, labelled by route pattern (`/blog/{slug}`, never
/// the raw path) so the series count stays bounded. Unmatched paths share
/// `unmatched`.
///
/// Sits inside compression, so the response size is the bytes before it. A
/// `text/event-stream` response records no size, and its duration is the time
/// to the response headers.
pub(crate) async fn http_metrics(request: Request, next: Next) -> Response {
    let method: &'static str = method_label(request.method());
    let route: String = request.extensions().get::<MatchedPath>().map_or_else(
        || String::from("unmatched"),
        |path| path.as_str().to_owned(),
    );
    let started: Instant = Instant::now();

    let (parts, body) = request.into_parts();
    let request: Request = Request::from_parts(
        parts,
        CountedBody::wrap(body, "http_request_body_size_bytes", method, &route),
    );

    metrics::gauge!("http_requests_in_flight").increment(1.0);
    let response: Response = next.run(request).await;
    metrics::gauge!("http_requests_in_flight").decrement(1.0);
    let response: Response = if is_event_stream(&response) {
        response
    } else {
        response.map(|body: Body| {
            CountedBody::wrap(body, "http_response_body_size_bytes", method, &route)
        })
    };

    let status: String = response.status().as_u16().to_string();
    metrics::counter!(
        "http_requests_total",
        "method" => method,
        "route" => route.clone(),
        "status" => status
    )
    .increment(1);
    metrics::histogram!("http_request_duration_seconds", "method" => method, "route" => route)
        .record(started.elapsed().as_secs_f64());
    response
}

/// Serves `/metrics` on [`METRICS_PORT`] until shutdown.
///
/// Never fails the site: a port that cannot be bound degrades metrics only, so
/// it is reported to Sentry and the site keeps serving.
pub(crate) async fn serve_metrics(shutdown: Shutdown) {
    let address: SocketAddr = SocketAddr::from(([0, 0, 0, 0], METRICS_PORT));
    let listener: TcpListener = match TcpListener::bind(address).await {
        Ok(listener) => listener,
        Err(source) => {
            error!(%address, error = %source, "metrics listener not started; the site still serves");
            return;
        }
    };
    let handle: &'static PrometheusHandle = handle();
    let router: Router =
        Router::new().route("/metrics", get(move || async move { handle.render() }));

    let upkeep_shutdown: Shutdown = shutdown.clone();
    tokio::spawn(async move {
        let mut interval: tokio::time::Interval = tokio::time::interval(UPKEEP_INTERVAL);
        loop {
            tokio::select! {
                _ = interval.tick() => handle.run_upkeep(),
                () = upkeep_shutdown.clone().recv() => break,
            }
        }
    });

    info!("metrics on http://{address}/metrics");
    super::connections::serve(
        "metrics",
        listener,
        router,
        super::connections::ConnectionLimits::new(),
        shutdown.recv(),
    )
    .await;
}

#[cfg(test)]
mod tests {
    use axum::Router;
    use axum::body::Body;
    use axum::http::{HeaderValue, Request, StatusCode};
    use axum::response::Response;
    use tower::ServiceExt;

    use super::{REQUEST_ID_HEADER, TraceRoutes, handle, is_valid_request_id};
    use crate::environment::Environment;
    use crate::webserver::{Shutdown, WebServer};

    fn sidecar() -> Router {
        WebServer::new("127.0.0.1", 0, Environment::Local)
            .into_router(Shutdown::manual())
            .expect("a sidecar always boots")
    }

    async fn get(path: &str, request_id: Option<&'static str>) -> Response {
        let mut request: Request<Body> = Request::get(path).body(Body::empty()).expect("valid");
        if let Some(id) = request_id {
            request
                .headers_mut()
                .insert(REQUEST_ID_HEADER, HeaderValue::from_static(id));
        }
        sidecar().oneshot(request).await.expect("infallible")
    }

    fn response_id(response: &Response) -> String {
        response.headers()[&REQUEST_ID_HEADER]
            .to_str()
            .expect("ascii")
            .to_owned()
    }

    #[test]
    fn an_nginx_request_id_is_kept() {
        assert!(is_valid_request_id(&HeaderValue::from_static(
            "c99301cd50023a854cbb00c56e7f3537"
        )));
    }

    #[test]
    fn a_long_or_odd_request_id_is_replaced_rather_than_logged() {
        for bad in ["", "has space", "semi;colon", &"a".repeat(65)] {
            let value: HeaderValue = HeaderValue::from_str(bad).expect("ascii");
            assert!(!is_valid_request_id(&value), "{bad:?}");
        }
    }

    #[tokio::test]
    async fn the_id_nginx_sent_comes_back_on_the_response() {
        let response: Response =
            get("/api/v1/health", Some("c99301cd50023a854cbb00c56e7f3537")).await;

        let expected: &str = "c99301cd50023a854cbb00c56e7f3537";
        assert_eq!(expected, response_id(&response));
    }

    #[tokio::test]
    async fn a_request_without_a_usable_id_gets_a_fresh_one() {
        for sent in [None, Some("has;semicolon")] {
            let response: Response = get("/api/v1/health", sent).await;
            let id: String = response_id(&response);

            assert_eq!(36, id.len(), "a UUID, not {id:?}");
            assert!(is_valid_request_id(
                &HeaderValue::from_str(&id).expect("ascii")
            ));
        }
    }

    #[tokio::test]
    async fn requests_are_counted_by_route_pattern_and_unknown_paths_share_one_label() {
        let _ = handle();
        let health: Response = get("/api/v1/health", None).await;
        let missing: Response = get("/no/such/page/12345", None).await;
        assert_eq!(StatusCode::OK, health.status());
        assert_eq!(StatusCode::NOT_FOUND, missing.status());

        let rendered: String = handle().render();
        assert!(
            rendered.contains(
                r#"http_requests_total{method="GET",route="/api/v1/health",status="200"}"#
            ),
            "{rendered}"
        );
        assert!(
            rendered
                .contains(r#"http_requests_total{method="GET",route="unmatched",status="404"}"#),
            "{rendered}"
        );
        assert!(!rendered.contains("12345"), "raw paths never become labels");
        assert!(
            rendered.contains("http_request_duration_seconds_bucket"),
            "a histogram, not a summary"
        );
        assert!(rendered.contains("build_info{"), "{rendered}");
    }

    #[test]
    fn accept_errors_are_zero_for_both_listeners_at_startup() {
        let rendered: String = handle().render();
        for listener in ["app", "metrics"] {
            let series: String = format!(r#"http_accept_errors_total{{listener="{listener}"}} 0"#);
            assert!(rendered.contains(&series), "{series} missing: {rendered}");
        }
    }

    async fn echo(body: String) -> String {
        body
    }

    #[tokio::test]
    async fn request_and_response_sizes_are_counted_under_the_route_pattern() {
        let _ = handle();
        let router: Router = Router::new()
            .route("/size_test/{id}", axum::routing::post(echo))
            .layer(axum::middleware::from_fn(super::http_metrics));
        let request: Request<Body> = Request::post("/size_test/98765")
            .body(Body::from("x".repeat(2000)))
            .expect("valid");
        let response: Response = router.oneshot(request).await.expect("infallible");
        let body: axum::body::Bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("readable");
        assert_eq!(2000, body.len());

        let rendered: String = handle().render();
        let labels: &str = r#"method="POST",route="/size_test/{id}""#;
        for metric in [
            "http_request_body_size_bytes",
            "http_response_body_size_bytes",
        ] {
            let count: String = format!("{metric}_count{{{labels}}} 1");
            assert!(rendered.contains(&count), "{count} missing: {rendered}");
            let sum: String = format!("{metric}_sum{{{labels}}} 2000");
            assert!(rendered.contains(&sum), "{sum} missing: {rendered}");
            let bucket: String = format!("{metric}_bucket{{{labels},le=\"4096\"}} 1");
            assert!(rendered.contains(&bucket), "{bucket} missing: {rendered}");
        }
        assert!(!rendered.contains("98765"), "raw paths never become labels");
    }

    fn status_only(status: StatusCode) -> Response {
        let mut response: Response = Response::new(Body::empty());
        *response.status_mut() = status;
        response
    }

    async fn events() -> Response {
        Response::builder()
            .header("content-type", "text/event-stream; charset=utf-8")
            .body(Body::from("data: hi\n\n"))
            .expect("valid")
    }

    fn metric_router() -> Router {
        Router::new()
            .route(
                "/empty_204",
                axum::routing::get(|| async { status_only(StatusCode::NO_CONTENT) }),
            )
            .route(
                "/empty_304",
                axum::routing::get(|| async { status_only(StatusCode::NOT_MODIFIED) }),
            )
            .route("/head_test", axum::routing::get(echo_static))
            .route("/sse_test", axum::routing::get(events))
            .route("/gone_test", axum::routing::post(echo))
            .layer(axum::middleware::from_fn(super::http_metrics))
    }

    async fn echo_static() -> &'static str {
        "hello"
    }

    async fn drain(response: Response) {
        let _ = axum::body::to_bytes(response.into_body(), usize::MAX).await;
    }

    #[tokio::test]
    async fn head_204_and_304_record_a_zero_response_size() {
        let _ = handle();
        for (request, route, method) in [
            (Request::head("/head_test"), "/head_test", "HEAD"),
            (Request::get("/empty_204"), "/empty_204", "GET"),
            (Request::get("/empty_304"), "/empty_304", "GET"),
        ] {
            let response: Response = metric_router()
                .oneshot(request.body(Body::empty()).expect("valid"))
                .await
                .expect("infallible");
            drain(response).await;

            let rendered: String = handle().render();
            let labels: String = format!(r#"method="{method}",route="{route}""#);
            for series in ["_count", "_sum"] {
                let line: String = format!(
                    "http_response_body_size_bytes{series}{{{labels}}} {}",
                    i32::from(series == "_count")
                );
                assert!(rendered.contains(&line), "{line} missing: {rendered}");
            }
        }
    }

    #[tokio::test]
    async fn an_event_stream_records_no_response_size() {
        let _ = handle();
        let response: Response = metric_router()
            .oneshot(
                Request::get("/sse_test")
                    .body(Body::empty())
                    .expect("valid"),
            )
            .await
            .expect("infallible");
        drain(response).await;

        let rendered: String = handle().render();
        assert!(
            !rendered
                .contains(r#"http_response_body_size_bytes_count{method="GET",route="/sse_test"}"#),
            "{rendered}"
        );
        assert!(
            rendered
                .contains(r#"http_requests_total{method="GET",route="/sse_test",status="200"}"#),
            "the request itself is still counted: {rendered}"
        );
    }

    #[tokio::test]
    async fn a_client_that_disconnects_early_still_records_once() {
        let _ = handle();
        let response: Response = metric_router()
            .oneshot(
                Request::post("/gone_test")
                    .body(Body::from("x".repeat(100)))
                    .expect("valid"),
            )
            .await
            .expect("infallible");
        // The client goes away without reading the body.
        drop(response);

        let rendered: String = handle().render();
        let line: &str =
            r#"http_response_body_size_bytes_count{method="POST",route="/gone_test"} 1"#;
        assert!(rendered.contains(line), "{line} missing: {rendered}");
    }

    #[test]
    fn the_duration_buckets_are_the_opentelemetry_defaults() {
        let _ = handle();
        metrics::histogram!("http_request_duration_seconds", "method" => "GET", "route" => "/bucket_test")
            .record(0.06);
        let rendered: String = handle().render();
        for le in [
            "0.005", "0.01", "0.025", "0.05", "0.075", "0.1", "0.25", "0.5", "0.75", "1", "2.5",
            "5", "7.5", "10", "+Inf",
        ] {
            let bucket: String = format!(r#"route="/bucket_test",le="{le}""#);
            assert!(rendered.contains(&bucket), "{bucket} missing: {rendered}");
        }
    }

    fn routes() -> TraceRoutes {
        TraceRoutes::new(vec![
            String::from("/static"),
            String::from("/api/v1/health"),
            String::from("/robots.txt"),
        ])
    }

    #[test]
    fn a_route_the_site_owns_is_traced() {
        assert!(routes().is_traced(Some("/")));
        assert!(routes().is_traced(Some("/blog/{slug}")));
        assert!(routes().is_traced(Some("/api/v1/things")));
    }

    #[test]
    fn a_route_nothing_matched_is_never_traced() {
        assert!(!routes().is_traced(None));
    }

    #[test]
    fn an_untraced_route_is_excluded_exactly_and_under_a_nested_prefix() {
        assert!(!routes().is_traced(Some("/api/v1/health")));
        assert!(!routes().is_traced(Some("/robots.txt")));
        assert!(!routes().is_traced(Some("/static")));
        assert!(!routes().is_traced(Some("/static/{*__private__axum_nest_tail_param}")));
    }

    #[test]
    fn a_site_route_that_merely_starts_like_an_untraced_one_is_still_traced() {
        assert!(routes().is_traced(Some("/statically")));
        assert!(routes().is_traced(Some("/robots.txt.html")));
        assert!(routes().is_traced(Some("/api/v1/health-report")));
    }
}