pingly 0.2.0

TLS and HTTP/1/2/3 fingerprint analysis server and Rust library
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! Axum routes served through coordinated HTTP/1, HTTP/2, and HTTP/3 listeners.
//!
//! Axum owns routing and middleware. Hyper serves TCP connections, while h3 and Quinn serve QUIC
//! connections. Pingora runtime scheduling is kept in [`runtime`].

mod accept;
mod certificate;
mod handle;
mod tls;
mod tracker;

pub(crate) mod routes;
pub(crate) mod runtime;

use std::{convert::Infallible, io, net::SocketAddr, time::Duration};

use axum::{body::Body, http::Request, response::Response, Router};
use pingora_runtime::current_handle;
use socket2::{Domain, Protocol, Socket, Type};
use tokio::{
    io::{AsyncRead, AsyncWrite},
    net::{TcpListener, TcpStream},
    task::JoinError,
};
use tower::Service;

use self::{
    accept::{Accept, DefaultAcceptor},
    tcp::ConnectInfoService,
};
pub(crate) use self::{
    handle::Handle,
    tls::{acme::AcmeRuntime, rustls::RustlsAcceptor},
    tracker::accept::TrackAcceptor,
};
use crate::Result;

const MAX_HEADER_LIST_SIZE: usize = 8 * 1024;
const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_millis(50);

/// Coordinates the TCP HTTP/1 and HTTP/2 listener with an optional UDP HTTP/3 listener.
pub(crate) struct HttpServer<A = RustlsAcceptor> {
    /// TCP listener accepting HTTP/1 and HTTP/2 connections.
    tcp_listener: TcpListener,
    /// Application routes shared by every HTTP version.
    router: Router,
    /// Adapter responsible for plain TCP or TLS setup and request inspection.
    acceptor: A,
    /// Hyper connection settings shared by accepted TCP streams.
    tcp_builder: tcp::ConnectionBuilder,
    /// Whether one response should gracefully close its underlying connection.
    close_after_first_request: bool,
    /// Optional QUIC endpoint serving HTTP/3 on the matching port.
    quic_endpoint: Option<quinn::Endpoint>,
}

enum ListenerExit {
    Tcp(std::result::Result<(), JoinError>),
    Quic(std::result::Result<Result<()>, JoinError>),
}

impl HttpServer<RustlsAcceptor> {
    /// Construct a new [`HttpServer<RustlsAcceptor>`].
    pub(crate) async fn new(
        bind: SocketAddr,
        keep_alive_timeout: u64,
        concurrent_limit: usize,
        acceptor: RustlsAcceptor,
        router: Router,
    ) -> Result<Self> {
        let rustls = acceptor.default_config();
        let mut server = Self::bind_tcp(bind, router, keep_alive_timeout, acceptor).await?;
        server.quic_endpoint = Some(quic::bind(
            server.tcp_listener.local_addr()?,
            rustls,
            concurrent_limit,
            server.close_after_first_request,
        )?);
        Ok(server)
    }

    /// Construct a new [`HttpServer<DefaultAcceptor>`].
    pub(crate) async fn new_plain(
        bind: SocketAddr,
        router: Router,
        keep_alive_timeout: u64,
    ) -> Result<HttpServer<DefaultAcceptor>> {
        HttpServer::bind_tcp(bind, router, keep_alive_timeout, DefaultAcceptor).await
    }
}

impl<A> HttpServer<A> {
    async fn bind_tcp(
        bind: SocketAddr,
        router: Router,
        keep_alive_timeout: u64,
        acceptor: A,
    ) -> Result<Self> {
        let (tcp_builder, close_after_first_request) = tcp::connection_builder(keep_alive_timeout);
        let tcp_listener = bind_tcp_listener(bind).await?;
        Ok(Self {
            tcp_listener,
            router,
            acceptor,
            tcp_builder,
            close_after_first_request,
            quic_endpoint: None,
        })
    }

    pub(crate) fn map_acceptor<B>(self, map: impl FnOnce(A) -> B) -> HttpServer<B> {
        HttpServer {
            tcp_listener: self.tcp_listener,
            router: self.router,
            acceptor: map(self.acceptor),
            tcp_builder: self.tcp_builder,
            close_after_first_request: self.close_after_first_request,
            quic_endpoint: self.quic_endpoint,
        }
    }
}

async fn bind_tcp_listener(bind: SocketAddr) -> Result<TcpListener> {
    if bind.is_ipv4() {
        return Ok(TcpListener::bind(bind).await?);
    }

    bind_ipv6_tcp(bind).map_err(Into::into)
}

/// The IPv6 wildcard opts into IPv4-mapped connections; concrete addresses do not.
///
/// https://www.rfc-editor.org/rfc/rfc3493#section-5.3
fn bind_ipv6_tcp(bind: SocketAddr) -> io::Result<TcpListener> {
    let socket = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))?;
    socket.set_only_v6(!bind.ip().is_unspecified())?;
    socket.bind(&bind.into())?;
    socket.listen(1024)?;
    socket.set_nonblocking(true)?;

    let listener: std::net::TcpListener = socket.into();
    TcpListener::from_std(listener)
}

impl<A> HttpServer<A>
where
    A: Accept<TcpStream, ConnectInfoService> + Clone + Send + Sync + 'static,
    A::Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    A::Service:
        Service<Request<Body>, Response = Response, Error = Infallible> + Clone + Send + 'static,
    <A::Service as Service<Request<Body>>>::Future: Send + 'static,
    A::Future: Send,
{
    pub(crate) async fn serve(self, handle: Handle) -> Result<()> {
        let Self {
            tcp_listener,
            router,
            acceptor,
            tcp_builder,
            close_after_first_request,
            quic_endpoint,
        } = self;

        let Some(quic_endpoint) = quic_endpoint else {
            tcp::serve(
                tcp_listener,
                router,
                acceptor,
                tcp_builder,
                close_after_first_request,
                handle,
            )
            .await;
            return Ok(());
        };

        let mut tcp_task = current_handle().spawn(tcp::serve(
            tcp_listener,
            router.clone(),
            acceptor,
            tcp_builder,
            close_after_first_request,
            handle.clone(),
        ));

        let mut quic_task = current_handle().spawn(quic::serve(
            quic_endpoint,
            router,
            close_after_first_request,
            handle.clone(),
        ));

        let first_exit = tokio::select! {
            result = &mut tcp_task => ListenerExit::Tcp(result),
            result = &mut quic_task => ListenerExit::Quic(result),
        };

        // A listener stopping unexpectedly must also stop its sibling. This avoids continuing to
        // advertise HTTP/3 after the UDP endpoint has failed and gives both protocols time to
        // drain.
        handle.request_graceful_shutdown();
        let (tcp_result, quic_result) = match first_exit {
            ListenerExit::Tcp(result) => (result, quic_task.await),
            ListenerExit::Quic(result) => (tcp_task.await, result),
        };

        tcp_result?;
        quic_result??;
        Ok(())
    }
}

mod tcp {
    //! HTTP/1 and HTTP/2 service over TCP.

    use std::{convert::Infallible, io, net::SocketAddr, time::Duration};

    use axum::{
        body::Body,
        extract::ConnectInfo,
        http::{header, Method, Request, StatusCode},
        middleware::AddExtension,
        response::Response,
        Router,
    };
    use hyper::{body::Incoming, ext::Protocol};
    use hyper_util::{
        rt::{TokioExecutor, TokioIo, TokioTimer},
        server::conn::auto::Builder,
        service::TowerToHyperService,
    };
    use pingora_runtime::current_handle;
    use tokio::{
        io::{AsyncRead, AsyncWrite},
        net::{TcpListener, TcpStream},
        sync::watch,
        task::{JoinError, JoinSet},
        time::timeout,
    };
    use tower::{Service, ServiceExt};

    use super::{
        accept::{Accept, AcceptOutcome},
        Handle, ACCEPT_ERROR_BACKOFF, MAX_HEADER_LIST_SIZE,
    };

    const CONNECTION_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);

    pub(super) type ConnectionBuilder = Builder<TokioExecutor>;
    pub(super) type ConnectInfoService = AddExtension<Router, ConnectInfo<SocketAddr>>;

    /// Builds the shared Hyper settings for HTTP/1 and HTTP/2 connections.
    pub(super) fn connection_builder(keep_alive_timeout: u64) -> (ConnectionBuilder, bool) {
        let mut builder = Builder::new(TokioExecutor::new());
        let keep_alive_interval = Duration::from_secs(keep_alive_timeout);
        let close_after_first_request = keep_alive_interval.is_zero();

        builder
            .http1()
            .timer(TokioTimer::new())
            // The connection policy closes ordinary requests. Hyper must keep protocol
            // switching enabled so WebSocket and other upgrades can take over the stream.
            .keep_alive(true)
            .max_buf_size(MAX_HEADER_LIST_SIZE);

        let mut http2 = builder.http2();
        http2
            .timer(TokioTimer::new())
            .auto_date_header(true)
            .max_header_list_size(MAX_HEADER_LIST_SIZE as _);

        if close_after_first_request {
            http2.keep_alive_interval(None).max_concurrent_streams(1);
        } else {
            http2
                .keep_alive_interval(Some(keep_alive_interval))
                .keep_alive_timeout(keep_alive_interval);
        }

        (builder, close_after_first_request)
    }

    /// Waits for the next TCP connection.
    ///
    /// Transient listener errors are logged and retried after a short backoff, matching the
    /// approach used by axum-server. This keeps a temporary accept failure from stopping the
    /// whole server; shutdown is handled by the serve select loop that polls this future.
    async fn accept(listener: &TcpListener) -> (TcpStream, SocketAddr) {
        loop {
            match listener.accept().await {
                Ok(stream) => return stream,
                Err(error) => {
                    // axum-server retries transient listener accept errors after a short backoff.
                    // https://docs.rs/axum-server/0.8.0/src/axum_server/server.rs.html#370-376
                    tracing::warn!(%error, "failed to accept TCP connection");
                    tokio::time::sleep(ACCEPT_ERROR_BACKOFF).await;
                }
            }
        }
    }

    /// Runs the HTTP/1 and HTTP/2 accept loop until graceful shutdown starts.
    pub(super) async fn serve<A>(
        listener: TcpListener,
        router: Router,
        acceptor: A,
        builder: ConnectionBuilder,
        close_after_first_request: bool,
        handle: Handle,
    ) where
        A: Accept<TcpStream, ConnectInfoService> + Clone + Send + Sync + 'static,
        A::Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static,
        A::Service: Service<Request<Body>, Response = Response, Error = Infallible>
            + Clone
            + Send
            + 'static,
        <A::Service as Service<Request<Body>>>::Future: Send + 'static,
        A::Future: Send,
    {
        let mut connections = JoinSet::new();

        loop {
            tokio::select! {
                _ = handle.wait_graceful_shutdown() => break,
                finished = connections.join_next(), if !connections.is_empty() => {
                    if let Some(result) = finished {
                        log_connection_task(result);
                    }
                }
                accepted = accept(&listener) => {
                    let (stream, remote_addr) = accepted;
                    if let Err(error) = stream.set_nodelay(true) {
                        tracing::warn!(%error, %remote_addr, "failed to enable TCP_NODELAY");
                    }

                    let acceptor = acceptor.clone();
                    let builder = builder.clone();
                    let router = router.clone();
                    let connection_handle = handle.clone();

                    // Pingora strategy: inside a no-steal runtime, `current_handle()` randomly
                    // selects a worker from the runtime pool.
                    // https://docs.rs/pingora-runtime/0.8.1/src/pingora_runtime/lib.rs.html#88-102
                    connections.spawn_on(async move {
                        let service = router
                            .into_make_service_with_connect_info::<SocketAddr>()
                            .oneshot(remote_addr)
                            .await
                            .unwrap_or_else(|error| match error {});

                        match acceptor.accept(stream, service).await {
                            Ok(AcceptOutcome::Serve { stream, service }) => {
                                if let Err(error) = serve_connection(
                                    builder,
                                    stream,
                                    service,
                                    connection_handle,
                                    close_after_first_request,
                                )
                                .await
                                {
                                    tracing::debug!(%error, %remote_addr, "failed to serve connection stream");
                                }
                            }
                            Ok(AcceptOutcome::Handled) => {}
                            Err(error) => {
                                tracing::debug!(%error, %remote_addr, "failed to accept connection stream");
                            }
                        }
                    }, &current_handle());
                }
            }
        }

        if timeout(
            CONNECTION_DRAIN_TIMEOUT,
            drain_connection_tasks(&mut connections),
        )
        .await
        .is_err()
        {
            tracing::debug!("HTTP/1 and HTTP/2 connection drain timed out");
            connections.abort_all();
            drain_connection_tasks(&mut connections).await;
        }
    }

    async fn serve_connection<I, S>(
        builder: Builder<TokioExecutor>,
        stream: I,
        service: S,
        handle: Handle,
        close_after_first_request: bool,
    ) -> io::Result<()>
    where
        I: AsyncRead + AsyncWrite + Unpin + Send + 'static,
        S: Service<Request<Body>, Response = Response, Error = Infallible> + Clone + Send + 'static,
        S::Future: Send + 'static,
    {
        let (close_tx, mut close_rx) = if close_after_first_request {
            let (sender, receiver) = watch::channel(false);
            (Some(sender), Some(receiver))
        } else {
            (None, None)
        };
        let service = tower::service_fn(move |request: Request<Incoming>| {
            let service = service.clone();
            let close_tx = close_tx.clone();
            async move {
                let protocol_switch = ProtocolSwitch::from_request(&request);
                let response = service.oneshot(request.map(Body::new)).await?;

                if let Some(sender) = close_tx
                    .as_ref()
                    .filter(|_| !protocol_switch.succeeded(&response))
                {
                    sender.send_replace(true);
                }

                Ok::<_, Infallible>(response)
            }
        });
        let service = TowerToHyperService::new(service);
        let connection = builder.serve_connection_with_upgrades(TokioIo::new(stream), service);
        tokio::pin!(connection);
        let mut shutting_down = false;

        loop {
            tokio::select! {
                result = connection.as_mut() => {
                    return result.map_err(io::Error::other);
                }
                _ = handle.wait_graceful_shutdown(), if !shutting_down => {
                    shutting_down = true;
                    connection.as_mut().graceful_shutdown();
                }
                _ = wait_for_close_signal(&mut close_rx),
                    if close_after_first_request && !shutting_down =>
                {
                    shutting_down = true;
                    connection.as_mut().graceful_shutdown();
                }
            }
        }
    }

    async fn wait_for_close_signal(receiver: &mut Option<watch::Receiver<bool>>) {
        let Some(receiver) = receiver.as_mut() else {
            std::future::pending::<()>().await;
            return;
        };

        let close_requested = *receiver.borrow_and_update();
        if !close_requested {
            let _ = receiver.changed().await;
        }
    }

    #[derive(Clone, Copy)]
    enum ProtocolSwitch {
        None,
        Http1Upgrade,
        ExtendedConnect,
    }

    impl ProtocolSwitch {
        fn from_request<B>(request: &Request<B>) -> Self {
            if request.method() == Method::CONNECT
                && request.extensions().get::<Protocol>().is_some()
            {
                return Self::ExtendedConnect;
            }

            let connection_upgrade = request
                .headers()
                .get_all(header::CONNECTION)
                .iter()
                .filter_map(|value| value.to_str().ok())
                .flat_map(|value| value.split(','))
                .any(|token| token.trim().eq_ignore_ascii_case("upgrade"));

            if connection_upgrade && request.headers().contains_key(header::UPGRADE) {
                Self::Http1Upgrade
            } else {
                Self::None
            }
        }

        fn succeeded(self, response: &Response) -> bool {
            match self {
                Self::Http1Upgrade => response.status() == StatusCode::SWITCHING_PROTOCOLS,
                Self::ExtendedConnect => response.status().is_success(),
                Self::None => false,
            }
        }
    }

    async fn drain_connection_tasks(connections: &mut JoinSet<()>) {
        while let Some(result) = connections.join_next().await {
            log_connection_task(result);
        }
    }

    fn log_connection_task(result: std::result::Result<(), JoinError>) {
        if let Err(error) = result {
            if !error.is_cancelled() {
                tracing::debug!(%error, "HTTP/1 or HTTP/2 connection task failed");
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use axum::{
            body::Body,
            http::{header, Method, Request, StatusCode},
            response::Response,
        };
        use hyper::ext::Protocol;

        use super::ProtocolSwitch;

        const LATENCY_PATH: &str = "/api/latency";
        const WEBSOCKET_PROTOCOL: &str = "websocket";

        #[test]
        fn ordinary_requests_close_when_keep_alive_is_disabled() {
            let request = Request::get("/").body(()).unwrap();
            let response = Response::new(Body::empty());

            assert!(!ProtocolSwitch::from_request(&request).succeeded(&response));
        }

        #[test]
        fn successful_protocol_upgrades_remain_open() {
            let request = Request::get(LATENCY_PATH)
                .header(header::CONNECTION, "keep-alive, Upgrade")
                .header(header::UPGRADE, WEBSOCKET_PROTOCOL)
                .body(())
                .unwrap();
            let response = Response::builder()
                .status(StatusCode::SWITCHING_PROTOCOLS)
                .body(Body::empty())
                .unwrap();

            assert!(ProtocolSwitch::from_request(&request).succeeded(&response));
        }

        #[test]
        fn rejected_protocol_upgrades_close() {
            let request = Request::get("/not-found")
                .header(header::CONNECTION, "Upgrade")
                .header(header::UPGRADE, "nonsense")
                .body(())
                .unwrap();
            let response = Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::empty())
                .unwrap();

            assert!(!ProtocolSwitch::from_request(&request).succeeded(&response));
        }

        #[test]
        fn extended_connect_streams_remain_open() {
            let mut request = Request::builder()
                .method(Method::CONNECT)
                .uri(LATENCY_PATH)
                .body(())
                .unwrap();
            request
                .extensions_mut()
                .insert(Protocol::from_static(WEBSOCKET_PROTOCOL));
            let response = Response::new(Body::empty());

            assert!(ProtocolSwitch::from_request(&request).succeeded(&response));
        }

        #[test]
        fn rejected_extended_connect_streams_close() {
            let mut request = Request::builder()
                .method(Method::CONNECT)
                .uri(LATENCY_PATH)
                .body(())
                .unwrap();
            request
                .extensions_mut()
                .insert(Protocol::from_static(WEBSOCKET_PROTOCOL));
            let response = Response::builder()
                .status(StatusCode::FORBIDDEN)
                .body(Body::empty())
                .unwrap();

            assert!(!ProtocolSwitch::from_request(&request).succeeded(&response));
        }

        #[test]
        fn ordinary_connect_requests_still_close() {
            let request = Request::builder()
                .method(Method::CONNECT)
                .uri(LATENCY_PATH)
                .body(())
                .unwrap();
            let response = Response::new(Body::empty());

            assert!(!ProtocolSwitch::from_request(&request).succeeded(&response));
        }
    }
}

mod quic {
    //! HTTP/3 service over Quinn with decrypted-stream fingerprint capture.

    pub mod crypto;
    pub mod inspect;

    use std::{
        convert::Infallible,
        error::Error as StdError,
        io,
        net::{SocketAddr, UdpSocket},
        sync::{Arc, OnceLock},
        time::Duration,
    };

    use axum::{
        body::Body,
        http::{Request, Response},
        Router,
    };
    use bytes::Bytes;
    use h3::error::Code;
    use http_body_util::BodyExt;
    use pingly::tls::ClientHelloHandshakeBuffer;
    use pingora_runtime::current_handle;
    use socket2::{Domain, Protocol, Socket, Type};
    use tokio::{
        task::{JoinError, JoinSet},
        time::timeout,
    };
    use tokio_rustls::rustls::{ProtocolVersion, ServerConfig};
    use tower::{Service, ServiceExt};

    use self::{
        crypto::HandshakeData,
        inspect::{Http3Capture, InspectedBidiStream, InspectedConnection},
    };
    use super::{tracker::info::ConnectionTrack, Handle, MAX_HEADER_LIST_SIZE};
    use crate::Result;

    type Http3Connection = h3::server::Connection<InspectedConnection, Bytes>;
    type RequestStream = h3::server::RequestStream<InspectedBidiStream<Bytes>, Bytes>;
    type RequestResolver = h3::server::RequestResolver<InspectedConnection, Bytes>;
    type BoxError = Box<dyn StdError + Send + Sync>;

    const SETTINGS_CAPTURE_TIMEOUT: Duration = Duration::from_secs(5);
    const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
    const CONNECTION_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
    const CONNECTION_CLOSE_TIMEOUT: Duration = Duration::from_secs(2);
    const SERVER_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);

    const MAX_REQUEST_STREAMS_PER_CONNECTION: usize = 128;
    const MAX_UNIDIRECTIONAL_STREAMS_PER_CONNECTION: u32 = 16;
    const STREAM_RECEIVE_WINDOW: u32 = 64 * 1024;
    const CONNECTION_RECEIVE_WINDOW: u32 = 1024 * 1024;
    const CONNECTION_SEND_WINDOW: u64 = 1024 * 1024;

    // HTTP/3 application error codes are carried as QUIC variable-length integers.
    // https://www.rfc-editor.org/rfc/rfc9114#section-8.1
    const H3_NO_ERROR: quinn::VarInt = quinn::VarInt::from_u32(0x100);

    /// Binds a QUIC endpoint with H3 ALPN and ClientHello capture.
    pub(super) fn bind(
        bind: SocketAddr,
        rustls: Arc<ServerConfig>,
        concurrent_limit: usize,
        close_after_first_request: bool,
    ) -> Result<quinn::Endpoint> {
        let mut config = crypto::server_config((*rustls).clone())?;
        config.transport_config(transport_config(
            concurrent_limit,
            close_after_first_request,
        ));

        if bind.is_ipv6() {
            let socket = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?;
            socket.set_only_v6(!bind.ip().is_unspecified())?;
            socket.bind(&bind.into())?;
            socket.set_nonblocking(true)?;

            let socket: UdpSocket = socket.into();
            return Ok(quinn::Endpoint::new(
                quinn::EndpointConfig::default(),
                Some(config),
                socket,
                Arc::new(quinn::TokioRuntime),
            )?);
        }

        Ok(quinn::Endpoint::server(config, bind)?)
    }

    /// Builds QUIC flow-control and stream limits for incoming HTTP/3 connections.
    fn transport_config(
        concurrent_limit: usize,
        close_after_first_request: bool,
    ) -> Arc<quinn::TransportConfig> {
        let mut config = quinn::TransportConfig::default();

        // Each HTTP/3 request uses a client-initiated bidirectional stream. Capping these streams
        // also bounds request tasks retained by one connection.
        // https://www.rfc-editor.org/rfc/rfc9114#section-6.1
        config.max_concurrent_bidi_streams(request_stream_limit(
            concurrent_limit,
            close_after_first_request,
        ));

        // HTTP/3 needs control and QPACK streams, with spare capacity for GREASE and extensions.
        // https://www.rfc-editor.org/rfc/rfc9114#section-6.2
        config.max_concurrent_uni_streams(quinn::VarInt::from_u32(
            MAX_UNIDIRECTIONAL_STREAMS_PER_CONNECTION,
        ));

        // QUIC flow-control windows bound buffered request data per stream and connection.
        // https://www.rfc-editor.org/rfc/rfc9000#section-4.1
        config
            .stream_receive_window(quinn::VarInt::from_u32(STREAM_RECEIVE_WINDOW))
            .receive_window(quinn::VarInt::from_u32(CONNECTION_RECEIVE_WINDOW))
            .send_window(CONNECTION_SEND_WINDOW);

        Arc::new(config)
    }

    fn request_stream_limit(
        concurrent_limit: usize,
        close_after_first_request: bool,
    ) -> quinn::VarInt {
        let per_connection_limit = if close_after_first_request {
            concurrent_limit.min(1)
        } else {
            concurrent_limit.min(MAX_REQUEST_STREAMS_PER_CONNECTION)
        };
        let per_connection_limit = u32::try_from(per_connection_limit).unwrap_or(u32::MAX);
        quinn::VarInt::from_u32(per_connection_limit)
    }

    /// Builds the HTTP/3 SETTINGS and request field-section policy.
    fn connection_builder() -> h3::server::Builder {
        let mut builder = h3::server::builder();

        // SETTINGS_MAX_FIELD_SECTION_SIZE advertises and enforces the decoded request header
        // bound. RFC 9114 counts each field's name, value, and 32 bytes of overhead.
        // https://www.rfc-editor.org/rfc/rfc9114#section-4.1.1.3
        builder.max_field_section_size(MAX_HEADER_LIST_SIZE as u64);
        builder
    }

    /// Accepts QUIC connections until graceful shutdown starts.
    pub(super) async fn serve(
        endpoint: quinn::Endpoint,
        router: Router,
        close_after_first_request: bool,
        handle: Handle,
    ) -> Result<()> {
        let mut connections = JoinSet::new();

        let endpoint_closed = loop {
            tokio::select! {
                _ = handle.wait_graceful_shutdown() => break false,
                finished = connections.join_next(), if !connections.is_empty() => {
                    if let Some(result) = finished {
                        log_connection_task(result);
                    }
                }
                incoming = endpoint.accept() => {
                    let Some(incoming) = incoming else {
                        break true;
                    };
                    let remote_addr = incoming.remote_address();
                    let router = router.clone();
                    let connection_handle = handle.clone();

                    connections.spawn_on(async move {
                        let accepted = tokio::select! {
                            _ = connection_handle.wait_graceful_shutdown() => return,
                            accepted = incoming => accepted,
                        };

                        match accepted {
                            Ok(connection) => {
                                serve_connection(
                                    connection,
                                    remote_addr,
                                    router,
                                    connection_handle,
                                    close_after_first_request,
                                )
                                .await;
                            }
                            Err(error) => {
                                tracing::debug!(%error, %remote_addr, "failed to accept QUIC connection");
                            }
                        }
                    }, &current_handle());
                }
            }
        };

        if endpoint_closed {
            handle.request_graceful_shutdown();
        }

        endpoint.set_server_config(None);
        if timeout(
            SERVER_DRAIN_TIMEOUT,
            drain_connection_tasks(&mut connections),
        )
        .await
        .is_err()
        {
            tracing::debug!("HTTP/3 connection drain timed out");
            endpoint.close(H3_NO_ERROR, b"server shutdown timeout");
            connections.abort_all();
            drain_connection_tasks(&mut connections).await;
        } else {
            endpoint.close(H3_NO_ERROR, b"server shutdown");
        }
        endpoint.wait_idle().await;

        if endpoint_closed {
            return Err(io::Error::other("HTTP/3 endpoint closed unexpectedly").into());
        }
        Ok(())
    }

    async fn serve_connection(
        connection: quinn::Connection,
        remote_addr: SocketAddr,
        router: Router,
        handle: Handle,
        close_after_first_request: bool,
    ) {
        let transport = connection.clone();
        let client_hello = connection
            .handshake_data()
            .and_then(|data| data.downcast::<HandshakeData>().ok())
            .map(|data| data.client_hello());

        let capture = Http3Capture::new();
        let inspected =
            InspectedConnection::new(h3_quinn::Connection::new(connection), capture.clone());
        let connection = match connection_builder().build(inspected).await {
            Ok(connection) => connection,
            Err(error) => {
                tracing::debug!(%error, %remote_addr, "failed to initialize HTTP/3 connection");
                return;
            }
        };
        let service = router
            .into_make_service_with_connect_info::<SocketAddr>()
            .oneshot(remote_addr)
            .await
            .unwrap_or_else(|error| match error {});

        if close_after_first_request {
            serve_single_request_connection(
                connection,
                transport,
                remote_addr,
                service,
                capture,
                client_hello,
                handle,
            )
            .await;
        } else {
            serve_reusable_connection(
                connection,
                transport,
                remote_addr,
                service,
                capture,
                client_hello,
                handle,
            )
            .await;
        }
    }

    async fn serve_single_request_connection<S>(
        mut connection: Http3Connection,
        transport: quinn::Connection,
        remote_addr: SocketAddr,
        service: S,
        capture: Http3Capture,
        client_hello: Option<Arc<OnceLock<ClientHelloHandshakeBuffer>>>,
        handle: Handle,
    ) where
        S: Service<Request<Body>, Response = Response<Body>, Error = Infallible>
            + Clone
            + Send
            + 'static,
        S::Future: Send + 'static,
    {
        let accepted = tokio::select! {
            _ = handle.wait_graceful_shutdown() => {
                begin_connection_shutdown(&mut connection, remote_addr).await;
                wait_for_peer_close(&mut connection, &transport, remote_addr).await;
                return;
            }
            accepted = connection.accept() => accepted,
        };
        let resolver = match accepted {
            Ok(Some(resolver)) => resolver,
            Ok(None) => return,
            Err(error) => {
                tracing::debug!(%error, %remote_addr, "failed to accept HTTP/3 request");
                return;
            }
        };

        // GOAWAY identifies the first request stream that will not be processed. A zero grace count
        // keeps the accepted stream valid while rejecting every later request stream.
        // https://www.rfc-editor.org/rfc/rfc9114#section-5.2
        begin_connection_shutdown(&mut connection, remote_addr).await;

        let request = serve_request(resolver, remote_addr, service, capture, client_hello);
        tokio::pin!(request);

        loop {
            tokio::select! {
                _ = request.as_mut() => break,
                accepted = connection.accept() => {
                    match accepted {
                        Ok(Some(_)) => {
                            tracing::trace!(%remote_addr, "discarded HTTP/3 request after GOAWAY");
                        }
                        Ok(None) => {
                            request.as_mut().await;
                            break;
                        }
                        Err(error) => {
                            tracing::debug!(%error, %remote_addr, "HTTP/3 connection ended while serving request");
                            request.as_mut().await;
                            break;
                        }
                    }
                }
            }
        }

        wait_for_peer_close(&mut connection, &transport, remote_addr).await;
    }

    async fn serve_reusable_connection<S>(
        mut connection: Http3Connection,
        transport: quinn::Connection,
        remote_addr: SocketAddr,
        service: S,
        capture: Http3Capture,
        client_hello: Option<Arc<OnceLock<ClientHelloHandshakeBuffer>>>,
        handle: Handle,
    ) where
        S: Service<Request<Body>, Response = Response<Body>, Error = Infallible>
            + Clone
            + Send
            + 'static,
        S::Future: Send + 'static,
    {
        let mut requests = JoinSet::new();
        let graceful = loop {
            tokio::select! {
                _ = handle.wait_graceful_shutdown() => {
                    begin_connection_shutdown(&mut connection, remote_addr).await;
                    break true;
                }
                finished = requests.join_next(), if !requests.is_empty() => {
                    if let Some(result) = finished {
                        log_request_task(result, remote_addr);
                    }
                }
                accepted = connection.accept() => {
                    let resolver = match accepted {
                        Ok(Some(resolver)) => resolver,
                        Ok(None) => break false,
                        Err(error) => {
                            tracing::debug!(%error, %remote_addr, "failed to accept HTTP/3 request");
                            break false;
                        }
                    };

                    requests.spawn_on(
                        serve_request(
                            resolver,
                            remote_addr,
                            service.clone(),
                            capture.clone(),
                            client_hello.clone(),
                        ),
                        &current_handle(),
                    );
                }
            }
        };

        if graceful {
            if timeout(
                CONNECTION_DRAIN_TIMEOUT,
                drain_requests_while_driving(&mut connection, &mut requests, remote_addr),
            )
            .await
            .is_err()
            {
                tracing::debug!(%remote_addr, "HTTP/3 request drain timed out");
                requests.abort_all();
                drain_request_tasks(&mut requests, remote_addr).await;
            }

            wait_for_peer_close(&mut connection, &transport, remote_addr).await;
        } else {
            if timeout(
                CONNECTION_DRAIN_TIMEOUT,
                drain_request_tasks(&mut requests, remote_addr),
            )
            .await
            .is_err()
            {
                requests.abort_all();
                drain_request_tasks(&mut requests, remote_addr).await;
            }
        }
    }

    async fn begin_connection_shutdown(connection: &mut Http3Connection, remote_addr: SocketAddr) {
        // h3 adds this request count to the last accepted stream ID. Advancing once identifies the
        // first request stream that was not accepted, so the current response remains valid.
        // https://www.rfc-editor.org/rfc/rfc9114#section-5.2
        if let Err(error) = connection.shutdown(1).await {
            tracing::debug!(%error, %remote_addr, "failed to send HTTP/3 GOAWAY");
        }
    }

    async fn drain_requests_while_driving(
        connection: &mut Http3Connection,
        requests: &mut JoinSet<()>,
        remote_addr: SocketAddr,
    ) {
        while !requests.is_empty() {
            tokio::select! {
                finished = requests.join_next() => {
                    if let Some(result) = finished {
                        log_request_task(result, remote_addr);
                    }
                }
                accepted = connection.accept() => {
                    match accepted {
                        Ok(Some(_)) => {
                            tracing::trace!(%remote_addr, "discarded HTTP/3 request after GOAWAY");
                        }
                        Ok(None) => {
                            drain_request_tasks(requests, remote_addr).await;
                            return;
                        }
                        Err(error) => {
                            tracing::debug!(%error, %remote_addr, "HTTP/3 connection ended during drain");
                            drain_request_tasks(requests, remote_addr).await;
                            return;
                        }
                    }
                }
            }
        }
    }

    async fn wait_for_peer_close(
        connection: &mut Http3Connection,
        transport: &quinn::Connection,
        remote_addr: SocketAddr,
    ) {
        // Once accepted responses are complete, the endpoint can close with H3_NO_ERROR. The
        // timeout prevents a peer that keeps QUIC alive after GOAWAY from retaining this
        // connection forever. https://www.rfc-editor.org/rfc/rfc9114#section-5.2
        let closed = timeout(CONNECTION_CLOSE_TIMEOUT, async {
            loop {
                tokio::select! {
                    _ = transport.closed() => return,
                    accepted = connection.accept() => {
                        match accepted {
                            Ok(Some(_)) => {}
                            Ok(None) | Err(_) => return,
                        }
                    }
                }
            }
        })
        .await;

        if closed.is_err() {
            tracing::trace!(%remote_addr, "HTTP/3 peer close timed out");
        }

        if transport.close_reason().is_none() {
            transport.close(H3_NO_ERROR, b"HTTP/3 graceful shutdown");
        }
    }

    async fn serve_request<S>(
        resolver: RequestResolver,
        remote_addr: SocketAddr,
        service: S,
        capture: Http3Capture,
        client_hello: Option<Arc<OnceLock<ClientHelloHandshakeBuffer>>>,
    ) where
        S: Service<Request<Body>, Response = Response<Body>, Error = Infallible> + Send + 'static,
        S::Future: Send,
    {
        if timeout(
            REQUEST_TIMEOUT,
            serve_request_inner(resolver, remote_addr, service, capture, client_hello),
        )
        .await
        .is_err()
        {
            tracing::debug!(%remote_addr, "HTTP/3 request timed out");
        }
    }

    async fn serve_request_inner<S>(
        resolver: RequestResolver,
        remote_addr: SocketAddr,
        service: S,
        capture: Http3Capture,
        client_hello: Option<Arc<OnceLock<ClientHelloHandshakeBuffer>>>,
    ) where
        S: Service<Request<Body>, Response = Response<Body>, Error = Infallible> + Send + 'static,
        S::Future: Send,
    {
        let (request, stream) = match resolver.resolve_request().await {
            Ok(request) => request,
            Err(error) => {
                tracing::debug!(%error, %remote_addr, "failed to resolve HTTP/3 request");
                return;
            }
        };

        let mut track = ConnectionTrack::default();
        track.set_tls_version_negotiated(Some(ProtocolVersion::TLSv1_3));
        if let Some(client_hello) = client_hello {
            track.set_client_hello_handshake(client_hello);
        }

        if let Some(headers) = capture.take_headers(stream.id()) {
            let settings = capture.settings();

            // Control and request streams can arrive independently. Wait briefly for the mandatory
            // peer SETTINGS before response analysis rather than dropping HTTP/3 data due to
            // ordering. https://www.rfc-editor.org/rfc/rfc9114#section-7.2.4.2
            if timeout(SETTINGS_CAPTURE_TIMEOUT, settings.wait())
                .await
                .is_ok()
            {
                track.set_http3_capture(settings, headers);
            } else {
                tracing::debug!(%remote_addr, "HTTP/3 SETTINGS capture timed out");
            }
        }

        let mut request = request.map(|_| Body::empty());
        request.extensions_mut().insert(track);
        let response = service
            .oneshot(request)
            .await
            .unwrap_or_else(|error| match error {});

        if let Err(error) = send_response(stream, response).await {
            tracing::debug!(%error, %remote_addr, "failed to serve HTTP/3 response");
        }
    }

    async fn send_response(
        mut stream: RequestStream,
        response: Response<Body>,
    ) -> std::result::Result<(), BoxError> {
        // Analysis routes do not consume request bodies.
        stream.stop_sending(Code::H3_NO_ERROR);

        let (parts, body) = response.into_parts();
        stream
            .send_response(Response::from_parts(parts, ()))
            .await?;

        let mut body = body;
        while let Some(frame) = body.frame().await {
            let frame = frame?;
            match frame.into_data() {
                Ok(data) => stream.send_data(data).await?,
                Err(frame) => {
                    if let Ok(trailers) = frame.into_trailers() {
                        stream.send_trailers(trailers).await?;
                        break;
                    }
                }
            }
        }
        stream.finish().await?;
        Ok(())
    }

    async fn drain_connection_tasks(connections: &mut JoinSet<()>) {
        while let Some(result) = connections.join_next().await {
            log_connection_task(result);
        }
    }

    async fn drain_request_tasks(requests: &mut JoinSet<()>, remote_addr: SocketAddr) {
        while let Some(result) = requests.join_next().await {
            log_request_task(result, remote_addr);
        }
    }

    fn log_connection_task(result: std::result::Result<(), JoinError>) {
        if let Err(error) = result {
            if !error.is_cancelled() {
                tracing::debug!(%error, "HTTP/3 connection task failed");
            }
        }
    }

    fn log_request_task(result: std::result::Result<(), JoinError>, remote_addr: SocketAddr) {
        if let Err(error) = result {
            if !error.is_cancelled() {
                tracing::debug!(%error, %remote_addr, "HTTP/3 request task failed");
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::{request_stream_limit, MAX_REQUEST_STREAMS_PER_CONNECTION};

        #[test]
        fn request_stream_limit_follows_connection_policy() {
            assert_eq!(
                request_stream_limit(usize::MAX, false),
                quinn::VarInt::from_u32(MAX_REQUEST_STREAMS_PER_CONNECTION as u32)
            );
            assert_eq!(request_stream_limit(32, false), quinn::VarInt::from_u32(32));
            assert_eq!(request_stream_limit(32, true), quinn::VarInt::from_u32(1));
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        future::poll_fn,
        net::{Ipv4Addr, SocketAddr},
        sync::Arc,
        time::Duration,
    };

    use axum::http::{header::USER_AGENT, Request, StatusCode};
    use bytes::Buf;
    use quinn_proto::crypto::rustls::QuicClientConfig;
    use rcgen::{CertificateParams, KeyPair, SanType};
    use tokio::time::timeout;
    use tokio_rustls::rustls::{
        pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
        ClientConfig, RootCertStore, ServerConfig,
    };

    use super::{
        routes,
        tls::rustls::{self, RustlsConfig},
        Handle, HttpServer, RustlsAcceptor,
    };

    #[tokio::test]
    async fn http3_server_serves_analysis_and_shuts_down_cleanly() {
        timeout(Duration::from_secs(10), run_http3_server_test())
            .await
            .expect("HTTP/3 integration test timed out");
    }

    async fn run_http3_server_test() {
        let (acceptor, certificate) = test_acceptor();
        let server = HttpServer::new(
            SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
            0,
            1,
            acceptor,
            test_router(),
        )
        .await
        .expect("HTTP server should bind");
        let server_addr = server
            .tcp_listener
            .local_addr()
            .expect("bound server address should be available");
        let handle = Handle::new();
        let server_handle = handle.clone();
        let server_task = tokio::spawn(server.serve(server_handle));

        let mut endpoint = quinn::Endpoint::client(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
            .expect("QUIC client endpoint should bind");
        endpoint.set_default_client_config(test_client_config(certificate));
        let transport = endpoint
            .connect(server_addr, "localhost")
            .expect("QUIC connection should start")
            .await
            .expect("QUIC handshake should complete");
        let transport_handle = transport.clone();
        let (mut driver, mut send_request) = h3::client::new(h3_quinn::Connection::new(transport))
            .await
            .expect("HTTP/3 client should initialize");
        let driver_task = tokio::spawn(async move { poll_fn(|cx| driver.poll_close(cx)).await });

        let request = Request::get(format!(
            "https://localhost:{}/api/http3",
            server_addr.port()
        ))
        .header(USER_AGENT, "pingly-http3-integration")
        .body(())
        .expect("HTTP/3 request should build");
        let mut stream = send_request
            .send_request(request)
            .await
            .expect("HTTP/3 request should start");
        stream.finish().await.expect("HTTP/3 request should finish");

        let response = stream
            .recv_response()
            .await
            .expect("HTTP/3 response headers should arrive");
        assert_eq!(response.status(), StatusCode::OK);

        let mut body = Vec::new();
        while let Some(mut chunk) = stream
            .recv_data()
            .await
            .expect("HTTP/3 response body should be readable")
        {
            let remaining = chunk.remaining();
            body.extend_from_slice(&chunk.copy_to_bytes(remaining));
        }
        let analysis: serde_json::Value =
            serde_json::from_slice(&body).expect("analysis response should be JSON");

        assert_eq!(analysis["http_version"], "HTTP/3.0");
        assert_eq!(analysis["http3"]["settings"]["frame_type"], "Settings");
        assert_eq!(analysis["http3"]["headers"]["frame_type"], "Headers");
        assert!(analysis["http3"]["h3_text"].is_string());
        assert!(analysis["http3"]["headers"]["headers"]
            .as_array()
            .expect("captured headers should be an array")
            .iter()
            .any(|field| field["name"] == ":method" && field["value"] == "GET"));

        drop(stream);
        drop(send_request);
        handle.request_graceful_shutdown();
        transport_handle.close(quinn::VarInt::from_u32(0x100), b"test complete");

        timeout(Duration::from_secs(5), driver_task)
            .await
            .expect("HTTP/3 client driver should stop")
            .expect("HTTP/3 client driver task should not panic");
        timeout(Duration::from_secs(5), server_task)
            .await
            .expect("HTTP server should stop")
            .expect("HTTP server task should not panic")
            .expect("HTTP server should shut down cleanly");

        endpoint.close(quinn::VarInt::from_u32(0x100), b"test complete");
        endpoint.wait_idle().await;
    }

    fn test_acceptor() -> (RustlsAcceptor, CertificateDer<'static>) {
        let mut params = CertificateParams::default();
        params.subject_alt_names = vec![SanType::DnsName(
            "localhost".try_into().expect("valid DNS name"),
        )];
        let key_pair = KeyPair::generate().expect("key generation should succeed");
        let certificate = params
            .self_signed(&key_pair)
            .expect("certificate generation should succeed");
        let certificate_der = certificate.der().clone();
        let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));
        let mut config = ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(vec![certificate_der.clone()], private_key)
            .expect("server certificate should be valid");
        rustls::set_http_alpn_protocols(&mut config);
        let config = RustlsConfig::from_config(Arc::new(config));

        (RustlsAcceptor::new(config), certificate_der)
    }

    fn test_client_config(certificate: CertificateDer<'static>) -> quinn::ClientConfig {
        let mut roots = RootCertStore::empty();
        roots
            .add(certificate)
            .expect("server certificate should be trusted");
        let mut config = ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();
        config.alpn_protocols = vec![b"h3".to_vec()];
        let config = QuicClientConfig::try_from(config)
            .expect("rustls client configuration should support QUIC");

        quinn::ClientConfig::new(Arc::new(config))
    }

    fn test_router() -> axum::Router {
        #[cfg(target_os = "linux")]
        return routes::router(None);

        #[cfg(not(target_os = "linux"))]
        routes::router()
    }
}