h3x 0.6.1

Peer-to-peer DHTTP/3 transport over QUIC
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
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
//! Generic HTTP/3 endpoint.
//!
//! [`H3Endpoint`] combines a QUIC transport `Q` with a selected connection
//! type `C`, providing raw HTTP/3 connection pooling and request serving.
//! Client connection access requires `Q: quic::Connect<Connection = C>`;
//! server request serving requires `Q: quic::Listen<Connection = C>`.
//!
//! [`ConnectionBuilder`]: crate::connection::ConnectionBuilder

use std::{any::Any, error::Error, sync::Arc};

use bon::bon;
use http::uri::Authority;
use snafu::ResultExt;
use tower_service::Service;
use tracing::Instrument;

use crate::{
    connection::{Connection as H3Connection, ConnectionBuilder, ConnectionState},
    dhttp::message::{MessageReader, MessageWriter},
    pool::{self, Pool},
    quic::{self, GetStreamIdExt},
    stream_id::StreamId,
};

#[cfg(feature = "hyper")]
pub mod hyper;

/// Generic HTTP/3 endpoint parameterized over a QUIC transport `Q` and a
/// connection type `C`.
///
/// `Q` carries no struct-level constraint — abilities are encoded at the
/// method level:
///
/// | Capability | Bound |
/// |---|---|
/// | Client connection access (connect)    | `Q: quic::Connect<Connection = C>` |
/// | Server (listen, listen_owned)          | `Q: quic::Listen<Connection = C>`  |
pub struct H3Endpoint<Q, C: quic::Connection> {
    pub(crate) quic: Q,
    pub(crate) builder: Arc<ConnectionBuilder<C>>,
    pub(crate) pool: Pool<C>,
}

/// RAII guard for mutable access to [`H3Endpoint`]'s QUIC transport.
///
/// On drop, clears the endpoint's connection pool via [`Pool::clear`],
/// ensuring no stale connections remain after QUIC configuration changes.
pub struct QuicMutGuard<'a, Q, C: quic::Connection> {
    quic: &'a mut Q,
    pool: &'a Pool<C>,
}

/// A request that has just been accepted on a QUIC stream but whose HTTP/3
/// header frame has not yet been interpreted by a higher-level HTTP API.
pub struct UnresolvedRequest {
    /// QUIC stream identifier for this request.
    pub stream_id: StreamId,
    /// Incoming request stream.
    pub read_stream: MessageReader,
    /// Outgoing response stream.
    pub write_stream: MessageWriter,
    /// Owning H3 connection.
    pub connection: Arc<ConnectionState<dyn quic::DynConnection>>,
}

#[derive(Debug, snafu::Snafu)]
#[snafu(module)]
pub enum AcceptError<E: Error + 'static> {
    #[snafu(display("failed to accept QUIC connection"))]
    Accept { source: E },
    #[snafu(display("failed to initialize H3 connection"))]
    Build { source: quic::ConnectionError },
}

impl<Q, C: quic::Connection> std::ops::Deref for QuicMutGuard<'_, Q, C> {
    type Target = Q;
    fn deref(&self) -> &Self::Target {
        self.quic
    }
}

impl<Q, C: quic::Connection> std::ops::DerefMut for QuicMutGuard<'_, Q, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.quic
    }
}

impl<Q, C: quic::Connection> Drop for QuicMutGuard<'_, Q, C> {
    fn drop(&mut self) {
        self.pool.clear();
    }
}

#[bon]
impl<Q, C: quic::Connection> H3Endpoint<Q, C> {
    /// Construct a new HTTP/3 endpoint.
    #[builder]
    pub fn new(quic: Q, #[builder(default)] builder: Arc<ConnectionBuilder<C>>) -> Self {
        Self {
            quic,
            builder,
            pool: Pool::empty(),
        }
    }
}

impl<Q, C: quic::Connection> H3Endpoint<Q, C>
where
    Q: quic::Connect<Connection = C>,
{
    /// Construct a new HTTP/3 endpoint with default pool and builder.
    pub fn new(quic: Q) -> Self {
        H3Endpoint::builder().quic(quic).build()
    }
}

impl<Q, C: quic::Connection> H3Endpoint<Q, C> {
    /// Obtain a mutable guard for the QUIC transport.
    ///
    /// The guard implements [`DerefMut`](std::ops::DerefMut) targeting `Q`.
    /// On drop, the connection pool is cleared via [`Pool::clear`].
    pub fn quic_mut(&mut self) -> QuicMutGuard<'_, Q, C> {
        QuicMutGuard {
            quic: &mut self.quic,
            pool: &self.pool,
        }
    }

    /// Shared reference to the underlying QUIC transport.
    pub fn quic(&self) -> &Q {
        &self.quic
    }

    /// Consume the endpoint and return the underlying QUIC transport.
    pub fn into_quic(self) -> Q {
        self.quic
    }

    /// Clear all cached client connections.
    ///
    /// This is useful when an external network transition invalidates paths
    /// without mutating the QUIC transport configuration itself.
    pub fn clear_pool(&self) {
        self.pool.clear();
    }

    /// Number of cached client connection entries.
    pub fn pool_len(&self) -> usize {
        self.pool.len()
    }
}

impl<Q, C: quic::Connection> H3Endpoint<Q, C>
where
    Q: quic::Connect<Connection = C>,
{
    /// Obtain (or reuse) an HTTP/3 connection to `server` from the pool.
    pub async fn connect(
        &self,
        server: Authority,
    ) -> Result<Arc<H3Connection<C>>, pool::ConnectError<Q::Error>> {
        self.pool
            .reuse_or_connect_with(&self.quic, self.builder.clone(), server)
            .await
    }
}

impl<Q, C: quic::Connection> H3Endpoint<Q, C>
where
    Q: quic::Listen<Connection = C>,
{
    /// Accept one QUIC connection and initialize it as an HTTP/3 connection.
    pub async fn accept(&mut self) -> Result<Arc<H3Connection<C>>, AcceptError<Q::Error>> {
        let quic_conn = self
            .quic
            .accept()
            .await
            .context(accept_error::AcceptSnafu)?;
        let h3_conn = self
            .builder
            .build(quic_conn)
            .await
            .context(accept_error::BuildSnafu)?;
        Ok(Arc::new(h3_conn))
    }

    /// Accept one HTTP/3 connection from a shared endpoint handle.
    ///
    /// Rust does not support overloading inherent methods by receiver type, so
    /// the shared-handle variant uses the same `*_owned` convention as
    /// [`H3Endpoint::listen_owned`].
    pub fn accept_owned<E>(
        self: &Arc<Self>,
    ) -> impl Future<Output = Result<Arc<H3Connection<C>>, AcceptError<E>>> + use<E, Q, C>
    where
        E: Error + Any,
        for<'a> &'a Q: quic::Listen<Connection = C, Error = E>,
    {
        let this = Arc::clone(self);
        let builder = this.builder.clone();
        let pool = this.pool.clone();
        async move {
            let mut ref_ep = H3Endpoint {
                quic: &this.quic,
                builder,
                pool,
            };
            ref_ep.accept().await
        }
    }
}

impl<Q, C> quic::Connect for H3Endpoint<Q, C>
where
    Q: quic::Connect<Connection = C>,
    C: quic::Connection,
{
    type Connection = C;
    type Error = Q::Error;

    fn connect<'a>(
        &'a self,
        server: &'a Authority,
    ) -> impl Future<Output = Result<Arc<Self::Connection>, Self::Error>> + Send + 'a {
        self.quic.connect(server)
    }
}

impl<Q, C> quic::Listen for H3Endpoint<Q, C>
where
    Q: quic::Listen<Connection = C>,
    C: quic::Connection,
{
    type Connection = C;
    type Error = Q::Error;

    fn accept(
        &mut self,
    ) -> impl Future<Output = Result<Arc<Self::Connection>, Self::Error>> + Send + '_ {
        self.quic.accept()
    }

    fn shutdown(&self) -> impl Future<Output = Result<(), Self::Error>> + Send + '_ {
        self.quic.shutdown()
    }
}

impl<Q, C: quic::Connection> H3Endpoint<Q, C>
where
    Q: quic::Listen<Connection = C>,
{
    /// Accept and serve HTTP/3 connections in a loop.
    #[doc(alias = "serve")]
    pub async fn listen<S>(&mut self, service: S) -> Result<(), <Q as quic::Listen>::Error>
    where
        S: Service<UnresolvedRequest, Response = ()> + Clone + Send + Sync + 'static,
        S::Future: Send,
        S::Error: Into<Box<dyn Error + Send + Sync>>,
    {
        loop {
            let quic_conn = self.quic.accept().await?;
            let h3_conn = match self.builder.build(quic_conn).await {
                Ok(c) => Arc::new(c),
                Err(e) => {
                    let report = snafu::Report::from_error(&e);
                    tracing::debug!(error = %report, "failed to build H3 connection");
                    continue;
                }
            };
            // Inherent termination: spawned task exits when accept_raw_message_stream
            // returns an error (connection closed) or qpack is no longer available.
            tokio::spawn(listen_connection(h3_conn, service.clone()).in_current_span());
        }
    }

    /// Listen for HTTP/3 requests on an `Arc<H3Endpoint<Q, C>>`.
    ///
    /// The returned future does not capture `&self`, so it can be spawned:
    ///
    /// ```ignore
    /// let h3: Arc<H3Endpoint<QuicEndpoint, Connection>> = ...;
    /// tokio::spawn(h3.listen(router));
    /// ```
    #[doc(alias = "serve_owned")]
    pub fn listen_owned<S>(
        self: &Arc<Self>,
        service: S,
    ) -> impl Future<Output = Result<(), <Q as quic::Listen>::Error>> + use<S, Q, C>
    where
        S: Service<UnresolvedRequest, Response = ()> + Clone + Send + Sync + 'static,
        S::Future: Send,
        S::Error: Into<Box<dyn Error + Send + Sync>>,
        for<'a> &'a Q: quic::Listen<Connection = C, Error = <Q as quic::Listen>::Error>,
    {
        let this = Arc::clone(self);
        let pool = this.pool.clone();
        let builder = this.builder.clone();
        async move {
            let mut ref_ep = H3Endpoint {
                quic: &this.quic,
                builder,
                pool,
            };
            ref_ep.listen(service).await
        }
    }
}

/// Listen for requests from a single accepted H3 connection.
///
/// Inherent termination: returns when [`H3Connection::accept_raw_message_stream`]
/// produces an error (connection closed) or when the QPACK module is no longer
/// available.
async fn listen_connection<C, S>(h3_conn: Arc<H3Connection<C>>, mut service: S)
where
    C: quic::Connection,
    S: Service<UnresolvedRequest, Response = ()> + Clone + Send + 'static,
    S::Future: Send,
    S::Error: Into<Box<dyn Error + Send + Sync>>,
{
    let erased = Arc::new(h3_conn.erase());

    loop {
        let (mut reader, writer) = match h3_conn.accept_raw_message_stream().await {
            Ok(s) => s,
            Err(e) => {
                let report = snafu::Report::from_error(&e);
                tracing::debug!(error = %report, "stopping request handler for connection");
                return;
            }
        };
        let stream_id = match GetStreamIdExt::stream_id(&mut reader).await {
            Ok(id) => id,
            Err(e) => {
                let report = snafu::Report::from_error(&e);
                tracing::debug!(error = %report, "failed to get stream id, skipping request");
                continue;
            }
        };
        let qpack = match h3_conn.qpack() {
            Ok(q) => q,
            Err(e) => {
                let report = snafu::Report::from_error(&e);
                tracing::debug!(error = %report, "qpack unavailable, stopping handler");
                return;
            }
        };
        let read_stream =
            MessageReader::new(stream_id, reader, qpack.decoder.clone(), (*erased).clone());
        let write_stream = MessageWriter::new(writer, qpack.encoder.clone(), (*erased).clone());

        let request = UnresolvedRequest {
            stream_id: StreamId(stream_id),
            read_stream,
            write_stream,
            connection: erased.clone(),
        };

        // Inherent termination: the spawned task exits when the service future resolves.
        tokio::spawn(listen_request(&mut service, request).in_current_span());
    }
}

/// Spawn a task to process a single request through `service`.
///
/// Inherent termination: the spawned task exits when the service future resolves.
fn listen_request<S>(
    service: &mut S,
    request: UnresolvedRequest,
) -> impl Future<Output = ()> + use<S>
where
    S: Service<UnresolvedRequest, Response = ()> + Send + 'static,
    S::Future: Send,
    S::Error: Into<Box<dyn Error + Send + Sync>>,
{
    let fut = service.call(request);
    async move {
        if let Err(error) = fut.await {
            let boxed: Box<dyn Error + Send + Sync> = error.into();
            let report = snafu::Report::from_error(boxed.as_ref());
            tracing::debug!(error = %report, "request handler returned error");
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::VecDeque,
        fmt,
        future::{Ready, pending, ready},
        pin::Pin,
        sync::{
            Arc, Mutex,
            atomic::{AtomicUsize, Ordering},
        },
        task::{Context, Poll},
    };

    use bytes::Bytes;
    use dhttp_identity::identity;
    use futures::{SinkExt, Stream, StreamExt};
    use http::uri::Authority;
    use tokio::{
        sync::watch,
        time::{Duration, timeout},
    };
    use tower_service::Service;

    use super::*;
    use crate::{
        codec::{
            BoxPeekableStreamReader, BoxStreamWriter, PeekableStreamReader, SinkWriter,
            StreamReader,
        },
        connection::{
            ConnectionState,
            tests::{
                MockConnection, TestLocalAuthority, TestReadStream, TestRemoteAuthority,
                TestWriteStream,
            },
        },
        dhttp::{
            message::guard::{GuardQuicReader, GuardQuicWriter},
            protocol::DHttpProtocol,
        },
        pool::ReuseableConnection,
        protocol::{Protocol, Protocols, StreamVerdict},
        qpack::protocol::QPackProtocolFactory,
        quic::{BoxQuicStreamReader, BoxQuicStreamWriter, GetStreamIdExt, StopStreamExt},
        varint::VarInt,
    };

    /// Minimal quic::Connect implementation for testing QuicMutGuard.
    struct MockConnect;

    impl quic::Connect for MockConnect {
        type Connection = MockConnection;
        type Error = quic::ConnectionError;

        async fn connect<'a>(
            &'a self,
            _server: &'a Authority,
        ) -> Result<Arc<Self::Connection>, Self::Error> {
            unreachable!("connect is not called in guard tests")
        }
    }

    struct MutableTransport {
        generation: usize,
    }

    #[derive(Debug)]
    struct BuildableConnection;

    impl quic::ManageStream for BuildableConnection {
        type StreamReader = TestReadStream;
        type StreamWriter = TestWriteStream;

        async fn open_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn open_uni(&self) -> Result<Self::StreamWriter, quic::ConnectionError> {
            Ok(TestWriteStream)
        }

        async fn accept_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn accept_uni(&self) -> Result<Self::StreamReader, quic::ConnectionError> {
            pending().await
        }
    }

    impl quic::WithLocalAuthority for BuildableConnection {
        type LocalAuthority = TestLocalAuthority;

        async fn local_authority(
            &self,
        ) -> Result<Option<Self::LocalAuthority>, quic::ConnectionError> {
            Ok(None)
        }
    }

    impl quic::WithRemoteAuthority for BuildableConnection {
        type RemoteAuthority = TestRemoteAuthority;

        async fn remote_authority(
            &self,
        ) -> Result<Option<Self::RemoteAuthority>, quic::ConnectionError> {
            Ok(None)
        }
    }

    impl quic::Lifecycle for BuildableConnection {
        fn close(&self, _code: crate::error::Code, _reason: std::borrow::Cow<'static, str>) {}

        fn check(&self) -> Result<(), quic::ConnectionError> {
            Ok(())
        }

        async fn closed(&self) -> quic::ConnectionError {
            pending().await
        }
    }

    #[derive(Debug, Clone)]
    struct NamedRemoteAuthority {
        name: &'static str,
    }

    impl identity::RemoteAuthority for NamedRemoteAuthority {
        fn name(&self) -> &str {
            self.name
        }

        fn cert_chain(&self) -> &[rustls::pki_types::CertificateDer<'static>] {
            &[]
        }
    }

    #[derive(Debug)]
    struct IdentifiedConnection {
        remote_name: &'static str,
    }

    impl IdentifiedConnection {
        fn new(remote_name: &'static str) -> Self {
            Self { remote_name }
        }
    }

    impl quic::ManageStream for IdentifiedConnection {
        type StreamReader = TestReadStream;
        type StreamWriter = TestWriteStream;

        async fn open_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn open_uni(&self) -> Result<Self::StreamWriter, quic::ConnectionError> {
            Ok(TestWriteStream)
        }

        async fn accept_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn accept_uni(&self) -> Result<Self::StreamReader, quic::ConnectionError> {
            pending().await
        }
    }

    impl quic::WithLocalAuthority for IdentifiedConnection {
        type LocalAuthority = TestLocalAuthority;

        async fn local_authority(
            &self,
        ) -> Result<Option<Self::LocalAuthority>, quic::ConnectionError> {
            Ok(None)
        }
    }

    impl quic::WithRemoteAuthority for IdentifiedConnection {
        type RemoteAuthority = NamedRemoteAuthority;

        async fn remote_authority(
            &self,
        ) -> Result<Option<Self::RemoteAuthority>, quic::ConnectionError> {
            Ok(Some(NamedRemoteAuthority {
                name: self.remote_name,
            }))
        }
    }

    impl quic::Lifecycle for IdentifiedConnection {
        fn close(&self, _code: crate::error::Code, _reason: std::borrow::Cow<'static, str>) {}

        fn check(&self) -> Result<(), quic::ConnectionError> {
            Ok(())
        }

        async fn closed(&self) -> quic::ConnectionError {
            pending().await
        }
    }

    fn test_connection_error(reason: &'static str) -> quic::ConnectionError {
        quic::ConnectionError::Transport {
            source: quic::TransportError {
                kind: VarInt::from_u32(0x01),
                frame_type: VarInt::from_u32(0x00),
                reason: reason.into(),
            },
        }
    }

    type ConnectionResultQueue<C> = Arc<Mutex<VecDeque<Result<Arc<C>, quic::ConnectionError>>>>;

    #[derive(Clone)]
    struct CountingConnect<C: quic::Connection> {
        calls: Arc<AtomicUsize>,
        servers: Arc<Mutex<Vec<Authority>>>,
        result: Arc<Mutex<Result<Arc<C>, quic::ConnectionError>>>,
    }

    impl<C: quic::Connection> CountingConnect<C> {
        fn succeed(connection: C) -> Self {
            Self {
                calls: Arc::default(),
                servers: Arc::default(),
                result: Arc::new(Mutex::new(Ok(Arc::new(connection)))),
            }
        }

        fn fail(error: quic::ConnectionError) -> Self {
            Self {
                calls: Arc::default(),
                servers: Arc::default(),
                result: Arc::new(Mutex::new(Err(error))),
            }
        }
    }

    impl<C: quic::Connection> quic::Connect for CountingConnect<C> {
        type Connection = C;
        type Error = quic::ConnectionError;

        async fn connect<'a>(
            &'a self,
            server: &'a Authority,
        ) -> Result<Arc<Self::Connection>, Self::Error> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            self.servers
                .lock()
                .expect("server log mutex should not be poisoned")
                .push(server.clone());
            self.result
                .lock()
                .expect("result mutex should not be poisoned")
                .clone()
        }
    }

    #[derive(Clone)]
    struct SequencedConnect<C: quic::Connection> {
        calls: Arc<AtomicUsize>,
        results: ConnectionResultQueue<C>,
    }

    impl<C: quic::Connection> SequencedConnect<C> {
        fn new(results: impl IntoIterator<Item = Result<Arc<C>, quic::ConnectionError>>) -> Self {
            Self {
                calls: Arc::default(),
                results: Arc::new(Mutex::new(results.into_iter().collect())),
            }
        }
    }

    impl<C: quic::Connection> quic::Connect for SequencedConnect<C> {
        type Connection = C;
        type Error = quic::ConnectionError;

        async fn connect<'a>(
            &'a self,
            _server: &'a Authority,
        ) -> Result<Arc<Self::Connection>, Self::Error> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            self.results
                .lock()
                .expect("result queue mutex should not be poisoned")
                .pop_front()
                .expect("connect result queue should contain an entry")
        }
    }

    #[derive(Default)]
    struct MockListen {
        accepted: Arc<AtomicUsize>,
        shutdowns: Arc<AtomicUsize>,
    }

    impl quic::Listen for MockListen {
        type Connection = BuildableConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            self.accepted.fetch_add(1, Ordering::Relaxed);
            Ok(Arc::new(BuildableConnection))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            self.shutdowns.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }
    }

    impl quic::Listen for &MockListen {
        type Connection = BuildableConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            self.accepted.fetch_add(1, Ordering::Relaxed);
            Ok(Arc::new(BuildableConnection))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            self.shutdowns.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }
    }

    struct FailingListen;

    impl quic::Listen for FailingListen {
        type Connection = BuildableConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            Err(test_connection_error("accept failed"))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Err(test_connection_error("shutdown failed"))
        }
    }

    impl quic::Listen for &FailingListen {
        type Connection = BuildableConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            Err(test_connection_error("shared accept failed"))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Err(test_connection_error("shared shutdown failed"))
        }
    }

    struct UnbuildableListen;

    impl quic::Listen for UnbuildableListen {
        type Connection = MockConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            Ok(Arc::new(MockConnection::new()))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    impl quic::Listen for &UnbuildableListen {
        type Connection = MockConnection;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            Ok(Arc::new(MockConnection::new()))
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    #[derive(Clone)]
    struct SequencedListen<C: quic::Connection> {
        accepted: Arc<AtomicUsize>,
        results: ConnectionResultQueue<C>,
    }

    impl<C: quic::Connection> SequencedListen<C> {
        fn new(results: impl IntoIterator<Item = Result<Arc<C>, quic::ConnectionError>>) -> Self {
            Self {
                accepted: Arc::default(),
                results: Arc::new(Mutex::new(results.into_iter().collect())),
            }
        }
    }

    impl<C: quic::Connection> quic::Listen for SequencedListen<C> {
        type Connection = C;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            self.accepted.fetch_add(1, Ordering::Relaxed);
            self.results
                .lock()
                .expect("listen result queue mutex should not be poisoned")
                .pop_front()
                .expect("listen result queue should contain an entry")
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    impl<C: quic::Connection> quic::Listen for &SequencedListen<C> {
        type Connection = C;
        type Error = quic::ConnectionError;

        async fn accept(&mut self) -> Result<Arc<Self::Connection>, Self::Error> {
            self.accepted.fetch_add(1, Ordering::Relaxed);
            self.results
                .lock()
                .expect("listen result queue mutex should not be poisoned")
                .pop_front()
                .expect("listen result queue should contain an entry")
        }

        async fn shutdown(&self) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    #[derive(Clone)]
    struct NoopService;

    impl Service<UnresolvedRequest> for NoopService {
        type Response = ();
        type Error = quic::ConnectionError;
        type Future = Ready<Result<(), Self::Error>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _request: UnresolvedRequest) -> Self::Future {
            ready(Ok(()))
        }
    }

    #[derive(Debug)]
    struct CloseLatch {
        closed_tx: watch::Sender<bool>,
        closed_rx: watch::Receiver<bool>,
    }

    impl Default for CloseLatch {
        fn default() -> Self {
            let (closed_tx, closed_rx) = watch::channel(false);
            Self {
                closed_tx,
                closed_rx,
            }
        }
    }

    impl CloseLatch {
        fn close(&self) {
            let _ = self.closed_tx.send(true);
        }

        async fn wait(&self) {
            let mut closed_rx = self.closed_rx.clone();
            while !*closed_rx.borrow_and_update() {
                if closed_rx.changed().await.is_err() {
                    break;
                }
            }
        }
    }

    #[derive(Debug, Clone)]
    struct ControlledConnection {
        close_latch: Arc<CloseLatch>,
        close_error: quic::ConnectionError,
    }

    impl ControlledConnection {
        fn new(reason: &'static str) -> Self {
            Self {
                close_latch: Arc::new(CloseLatch::default()),
                close_error: test_connection_error(reason),
            }
        }

        fn trigger_close(&self) {
            self.close_latch.close();
        }
    }

    impl quic::ManageStream for ControlledConnection {
        type StreamReader = TestReadStream;
        type StreamWriter = TestWriteStream;

        async fn open_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn open_uni(&self) -> Result<Self::StreamWriter, quic::ConnectionError> {
            Ok(TestWriteStream)
        }

        async fn accept_bi(
            &self,
        ) -> Result<(Self::StreamReader, Self::StreamWriter), quic::ConnectionError> {
            pending().await
        }

        async fn accept_uni(&self) -> Result<Self::StreamReader, quic::ConnectionError> {
            pending().await
        }
    }

    impl quic::WithLocalAuthority for ControlledConnection {
        type LocalAuthority = TestLocalAuthority;

        async fn local_authority(
            &self,
        ) -> Result<Option<Self::LocalAuthority>, quic::ConnectionError> {
            Ok(None)
        }
    }

    impl quic::WithRemoteAuthority for ControlledConnection {
        type RemoteAuthority = TestRemoteAuthority;

        async fn remote_authority(
            &self,
        ) -> Result<Option<Self::RemoteAuthority>, quic::ConnectionError> {
            Ok(None)
        }
    }

    impl quic::Lifecycle for ControlledConnection {
        fn close(&self, _code: crate::error::Code, _reason: std::borrow::Cow<'static, str>) {
            self.trigger_close();
        }

        fn check(&self) -> Result<(), quic::ConnectionError> {
            Ok(())
        }

        async fn closed(&self) -> quic::ConnectionError {
            self.close_latch.wait().await;
            self.close_error.clone()
        }
    }

    fn state_without_qpack(
        quic: Arc<ControlledConnection>,
    ) -> ConnectionState<ControlledConnection> {
        let erased: Arc<dyn quic::DynConnection> = quic.clone();
        let mut protocols = Protocols::new();
        protocols.insert(DHttpProtocol::new_for_test(erased));
        ConnectionState::new_for_test(quic, Arc::new(protocols))
    }

    async fn state_with_qpack(
        quic: Arc<ControlledConnection>,
    ) -> ConnectionState<ControlledConnection> {
        let erased: Arc<dyn quic::DynConnection> = quic.clone();
        let mut protocols = Protocols::new();
        protocols.insert(DHttpProtocol::new_for_test(erased));
        let qpack = QPackProtocolFactory::new()
            .init(&quic, &protocols)
            .await
            .expect("qpack protocol should initialize for endpoint tests");
        protocols.insert(qpack);
        ConnectionState::new_for_test(quic, Arc::new(protocols))
    }

    async fn http3_request_stream(stream_id: u32) -> (BoxPeekableStreamReader, BoxStreamWriter) {
        let stream_id = VarInt::from_u32(stream_id);
        let (reader, mut write_side) = quic::test::mock_stream_pair(stream_id);
        write_side
            .send(Bytes::from_static(&[0x01]))
            .await
            .expect("write test HEADERS frame type");
        write_side
            .close()
            .await
            .expect("close test request read side");

        let (_read_side, writer) = quic::test::mock_stream_pair(stream_id);
        (
            PeekableStreamReader::new(StreamReader::new(Box::pin(reader) as BoxQuicStreamReader)),
            SinkWriter::new(Box::pin(writer) as BoxQuicStreamWriter),
        )
    }

    async fn enqueue_http3_request(
        state: &ConnectionState<ControlledConnection>,
        stream: (BoxPeekableStreamReader, BoxStreamWriter),
    ) {
        let verdict = Protocol::accept_bi(state.dhttp(), stream)
            .await
            .expect("test request stream should be classified");
        assert!(matches!(verdict, StreamVerdict::Accepted));
    }

    #[derive(Debug)]
    struct StreamIdErrorReadStream {
        first_chunk: Option<Bytes>,
        close_latch: Option<Arc<CloseLatch>>,
        first_stream_id: Option<VarInt>,
    }

    impl StreamIdErrorReadStream {
        fn new(close_latch: Arc<CloseLatch>) -> Self {
            Self {
                first_chunk: Some(Bytes::from_static(&[0x01])),
                close_latch: Some(close_latch),
                first_stream_id: None,
            }
        }

        fn fail_after_first_success(stream_id: VarInt) -> Self {
            Self {
                first_chunk: Some(Bytes::from_static(&[0x01])),
                close_latch: None,
                first_stream_id: Some(stream_id),
            }
        }
    }

    impl quic::GetStreamId for StreamIdErrorReadStream {
        fn poll_stream_id(
            self: Pin<&mut Self>,
            _cx: &mut Context,
        ) -> Poll<Result<VarInt, quic::StreamError>> {
            let this = self.get_mut();
            if let Some(stream_id) = this.first_stream_id.take() {
                return Poll::Ready(Ok(stream_id));
            }
            if let Some(close_latch) = &this.close_latch {
                close_latch.close();
            }
            Poll::Ready(Err(quic::StreamError::Reset {
                code: VarInt::from_u32(0x11),
            }))
        }
    }

    impl quic::StopStream for StreamIdErrorReadStream {
        fn poll_stop(
            self: Pin<&mut Self>,
            _cx: &mut Context,
            _code: VarInt,
        ) -> Poll<Result<(), quic::StreamError>> {
            let _ = self;
            Poll::Ready(Ok(()))
        }
    }

    impl Stream for StreamIdErrorReadStream {
        type Item = Result<Bytes, quic::StreamError>;

        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            let this = self.get_mut();
            Poll::Ready(this.first_chunk.take().map(Ok))
        }
    }

    fn stream_id_error_request_stream(
        stream_id: u32,
        close_latch: Arc<CloseLatch>,
    ) -> (BoxPeekableStreamReader, BoxStreamWriter) {
        let stream_id = VarInt::from_u32(stream_id);
        let reader = PeekableStreamReader::new(StreamReader::new(Box::pin(
            StreamIdErrorReadStream::new(close_latch),
        ) as BoxQuicStreamReader));
        let (_unused_reader, writer) = quic::test::mock_stream_pair(stream_id);
        (
            reader,
            SinkWriter::new(Box::pin(writer) as BoxQuicStreamWriter),
        )
    }

    fn second_stream_id_error_request_stream(
        stream_id: u32,
    ) -> (BoxPeekableStreamReader, BoxStreamWriter) {
        let stream_id = VarInt::from_u32(stream_id);
        let reader = PeekableStreamReader::new(StreamReader::new(Box::pin(
            StreamIdErrorReadStream::fail_after_first_success(stream_id),
        ) as BoxQuicStreamReader));
        let (_unused_reader, writer) = quic::test::mock_stream_pair(stream_id);
        (
            reader,
            SinkWriter::new(Box::pin(writer) as BoxQuicStreamWriter),
        )
    }

    #[derive(Debug, Clone)]
    struct RecordingService {
        seen_streams: Arc<Mutex<Vec<StreamId>>>,
        close_latch: Arc<CloseLatch>,
    }

    impl Service<UnresolvedRequest> for RecordingService {
        type Response = ();
        type Error = quic::ConnectionError;
        type Future = Ready<Result<(), Self::Error>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, request: UnresolvedRequest) -> Self::Future {
            self.seen_streams
                .lock()
                .expect("recording service mutex should not be poisoned")
                .push(request.stream_id);
            self.close_latch.close();
            ready(Ok(()))
        }
    }

    #[derive(Debug, Clone)]
    struct TestServiceError;

    impl fmt::Display for TestServiceError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("test service failure")
        }
    }

    impl Error for TestServiceError {}

    #[derive(Debug, Clone)]
    struct FailingService {
        calls: Arc<AtomicUsize>,
        close_latch: Arc<CloseLatch>,
    }

    impl Service<UnresolvedRequest> for FailingService {
        type Response = ();
        type Error = TestServiceError;
        type Future = Ready<Result<(), Self::Error>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _request: UnresolvedRequest) -> Self::Future {
            self.calls.fetch_add(1, Ordering::Relaxed);
            self.close_latch.close();
            ready(Err(TestServiceError))
        }
    }

    #[test]
    fn h3_endpoint_implements_quic_connect_when_transport_connects() {
        fn assert_connect<T: quic::Connect<Connection = MockConnection>>() {}

        assert_connect::<H3Endpoint<MockConnect, MockConnection>>();
        assert_connect::<Arc<H3Endpoint<MockConnect, MockConnection>>>();
    }

    #[test]
    fn h3_endpoint_implements_quic_listen_when_transport_listens() {
        fn assert_listen<T: quic::Listen<Connection = BuildableConnection>>() {}

        assert_listen::<H3Endpoint<MockListen, BuildableConnection>>();
    }

    #[test]
    fn builder_preserves_custom_builder_and_quic_accessor_returns_transport() {
        let listen = MockListen::default();
        let accepted = listen.accepted.clone();
        let builder: Arc<ConnectionBuilder<BuildableConnection>> =
            Arc::new(ConnectionBuilder::new(Arc::default()));
        let endpoint = H3Endpoint::builder()
            .quic(listen)
            .builder(builder.clone())
            .build();

        assert!(Arc::ptr_eq(&builder, &endpoint.builder));
        assert!(Arc::ptr_eq(&accepted, &endpoint.quic().accepted));
        assert_eq!(endpoint.pool_len(), 0);
    }

    #[test]
    fn builder_without_explicit_builder_uses_default_connection_builder() {
        let endpoint: H3Endpoint<_, BuildableConnection> =
            H3Endpoint::builder().quic(MockListen::default()).build();

        assert_eq!(*endpoint.builder, ConnectionBuilder::default());
        assert_eq!(endpoint.pool_len(), 0);
    }

    #[test]
    fn into_quic_returns_owned_transport() {
        let listen = MockListen::default();
        let accepted = listen.accepted.clone();
        let endpoint: H3Endpoint<_, BuildableConnection> =
            H3Endpoint::builder().quic(listen).build();

        let listen = endpoint.into_quic();

        assert!(Arc::ptr_eq(&accepted, &listen.accepted));
    }

    #[test]
    fn accept_error_display_describes_current_layer_and_preserves_source() {
        let accept = AcceptError::Accept {
            source: test_connection_error("accept display source"),
        };
        let build = AcceptError::<quic::ConnectionError>::Build {
            source: test_connection_error("build display source"),
        };

        assert_eq!(accept.to_string(), "failed to accept QUIC connection");
        assert!(Error::source(&accept).is_some());
        assert_eq!(build.to_string(), "failed to initialize H3 connection");
        assert!(Error::source(&build).is_some());
    }

    #[tokio::test]
    async fn inherent_connect_builds_and_reuses_pooled_h3_connection() {
        let connector = CountingConnect::succeed(IdentifiedConnection::new("test-remote"));
        let calls = connector.calls.clone();
        let servers = connector.servers.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "test-remote:443".parse().unwrap();

        let first = endpoint
            .connect(server.clone())
            .await
            .expect("first connect should build H3");
        let second = endpoint
            .connect(server.clone())
            .await
            .expect("second connect should reuse H3");

        assert!(Arc::ptr_eq(&first, &second));
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        assert_eq!(
            servers
                .lock()
                .expect("server log mutex should not be poisoned")
                .as_slice(),
            &[server],
        );
        assert_eq!(endpoint.pool_len(), 1);
    }

    #[tokio::test]
    async fn inherent_connect_preserves_authority_without_port() {
        let connector = CountingConnect::succeed(IdentifiedConnection::new("test-remote"));
        let servers = connector.servers.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "test-remote".parse().unwrap();

        endpoint
            .connect(server.clone())
            .await
            .expect("connection should build");

        assert_eq!(
            servers
                .lock()
                .expect("server log mutex should not be poisoned")
                .as_slice(),
            &[server],
        );
    }

    #[tokio::test]
    async fn inherent_connect_returns_connector_error() {
        let endpoint = H3Endpoint::<_, IdentifiedConnection>::new(CountingConnect::fail(
            test_connection_error("connector failed"),
        ));
        let server: Authority = "test-remote:443".parse().unwrap();

        let error = endpoint
            .connect(server)
            .await
            .expect_err("connector error should be returned");

        assert!(matches!(error, pool::ConnectError::Connector { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn inherent_connect_returns_h3_build_error() {
        let endpoint =
            H3Endpoint::<_, MockConnection>::new(CountingConnect::succeed(MockConnection::new()));
        let server: Authority = "test-remote:443".parse().unwrap();

        let error = endpoint
            .connect(server)
            .await
            .expect_err("H3 builder error should be returned");

        assert!(matches!(error, pool::ConnectError::H3 { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn inherent_connect_rejects_peer_identity_mismatch() {
        let connector = CountingConnect::succeed(IdentifiedConnection::new("actual.example"));
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "expected.example:443".parse().unwrap();

        let error = endpoint
            .connect(server)
            .await
            .expect_err("identity mismatch should be returned");

        assert!(matches!(
            error,
            pool::ConnectError::IncorrectIdentity { expected, actual }
                if expected == "expected.example" && actual.as_deref() == Some("actual.example")
        ));
    }

    #[tokio::test]
    async fn quic_connect_impl_delegates_to_inner_transport() {
        let connector = CountingConnect::succeed(IdentifiedConnection::new("delegated.example"));
        let calls = connector.calls.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "delegated.example:443".parse().unwrap();

        let connection = quic::Connect::connect(&endpoint, &server)
            .await
            .expect("delegated connect should return raw QUIC connection");

        assert_eq!(connection.remote_name, "delegated.example");
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        assert_eq!(endpoint.pool_len(), 0);
    }

    #[tokio::test]
    async fn quic_connect_impl_returns_inner_transport_error_without_pooling() {
        let connector =
            CountingConnect::<IdentifiedConnection>::fail(test_connection_error("delegate failed"));
        let calls = connector.calls.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "delegated.example:443".parse().unwrap();

        let error = quic::Connect::connect(&endpoint, &server)
            .await
            .expect_err("delegated connect should return raw QUIC errors");

        assert!(error.is_transport());
        assert_eq!(calls.load(Ordering::Relaxed), 1);
        assert_eq!(endpoint.pool_len(), 0);
    }

    #[tokio::test]
    async fn accept_builds_h3_connection_from_accepted_quic_connection() {
        let listen = MockListen::default();
        let accepted = listen.accepted.clone();
        let mut endpoint = H3Endpoint::builder().quic(listen).build();

        let connection = endpoint.accept().await.expect("accept should build H3");

        assert_eq!(accepted.load(Ordering::Relaxed), 1);
        connection.qpack().expect("qpack should be initialized");
    }

    #[tokio::test]
    async fn quic_listen_impl_returns_inner_accept_and_shutdown_errors() {
        let mut endpoint = H3Endpoint::builder().quic(FailingListen).build();

        let accept_error = quic::Listen::accept(&mut endpoint)
            .await
            .expect_err("listen impl should return raw accept errors");
        let shutdown_error = quic::Listen::shutdown(&endpoint)
            .await
            .expect_err("listen impl should return raw shutdown errors");

        assert!(accept_error.is_transport());
        assert!(shutdown_error.is_transport());
    }

    #[tokio::test]
    async fn accept_returns_quic_accept_error() {
        let mut endpoint = H3Endpoint::builder().quic(FailingListen).build();

        let error = endpoint
            .accept()
            .await
            .expect_err("accept error should be returned");

        assert!(matches!(error, AcceptError::Accept { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn accept_returns_h3_build_error() {
        let mut endpoint = H3Endpoint::builder().quic(UnbuildableListen).build();

        let error = endpoint
            .accept()
            .await
            .expect_err("build error should be returned");

        assert!(matches!(error, AcceptError::Build { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn accept_owned_builds_h3_connection_from_shared_endpoint() {
        let listen = MockListen::default();
        let accepted = listen.accepted.clone();
        let endpoint = Arc::new(H3Endpoint::builder().quic(listen).build());

        let connection = endpoint
            .accept_owned()
            .await
            .expect("accept_owned should build H3");

        assert_eq!(accepted.load(Ordering::Relaxed), 1);
        connection.qpack().expect("qpack should be initialized");
    }

    #[tokio::test]
    async fn accept_owned_returns_h3_build_error_from_shared_endpoint() {
        let endpoint = Arc::new(H3Endpoint::builder().quic(UnbuildableListen).build());

        let error = endpoint
            .accept_owned()
            .await
            .expect_err("shared build error should be returned");

        assert!(matches!(error, AcceptError::Build { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn accept_owned_returns_quic_accept_error_from_shared_endpoint() {
        let endpoint = Arc::new(H3Endpoint::builder().quic(FailingListen).build());

        let error = endpoint
            .accept_owned()
            .await
            .expect_err("shared accept error should be returned");

        assert!(matches!(error, AcceptError::Accept { source } if source.is_transport()));
    }

    #[tokio::test]
    async fn quic_listen_impl_delegates_accept_and_shutdown_to_inner_transport() {
        let listen = MockListen::default();
        let accepted = listen.accepted.clone();
        let shutdowns = listen.shutdowns.clone();
        let mut endpoint = H3Endpoint::builder().quic(listen).build();

        let _connection = quic::Listen::accept(&mut endpoint)
            .await
            .expect("listen impl should return raw QUIC connection");
        quic::Listen::shutdown(&endpoint)
            .await
            .expect("listen impl should delegate shutdown");

        assert_eq!(accepted.load(Ordering::Relaxed), 1);
        assert_eq!(shutdowns.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn listen_returns_quic_accept_error() {
        let mut endpoint = H3Endpoint::builder().quic(FailingListen).build();

        let error = endpoint
            .listen(NoopService)
            .await
            .expect_err("listen should return listener accept error");

        assert!(error.is_transport());
    }

    #[tokio::test]
    async fn listen_skips_build_errors_and_returns_later_accept_error() {
        let listen = SequencedListen::new([
            Ok(Arc::new(MockConnection::new())),
            Err(test_connection_error("accept failed after build retry")),
        ]);
        let accepted = listen.accepted.clone();
        let mut endpoint = H3Endpoint::builder().quic(listen).build();

        let error = endpoint
            .listen(NoopService)
            .await
            .expect_err("listen should continue past build errors and return accept error");

        assert!(error.is_transport());
        assert_eq!(accepted.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn listen_spawns_for_buildable_connections_and_returns_later_accept_error() {
        let listen = SequencedListen::new([
            Ok(Arc::new(BuildableConnection)),
            Err(test_connection_error(
                "accept failed after serving one connection",
            )),
        ]);
        let accepted = listen.accepted.clone();
        let mut endpoint = H3Endpoint::builder().quic(listen).build();

        let error = endpoint
            .listen(NoopService)
            .await
            .expect_err("listen should return the later listener error");

        assert!(error.is_transport());
        assert_eq!(accepted.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn listen_owned_returns_quic_accept_error_from_shared_endpoint() {
        let endpoint = Arc::new(H3Endpoint::builder().quic(FailingListen).build());

        let error = endpoint
            .listen_owned(NoopService)
            .await
            .expect_err("listen_owned should return shared listener accept error");

        assert!(error.is_transport());
    }

    #[tokio::test]
    async fn listen_owned_skips_build_errors_and_returns_later_accept_error() {
        let listen = SequencedListen::new([
            Ok(Arc::new(MockConnection::new())),
            Err(test_connection_error(
                "shared accept failed after build retry",
            )),
        ]);
        let accepted = listen.accepted.clone();
        let endpoint = Arc::new(H3Endpoint::builder().quic(listen).build());

        let error = endpoint
            .listen_owned(NoopService)
            .await
            .expect_err("listen_owned should continue past build errors and return accept error");

        assert!(error.is_transport());
        assert_eq!(accepted.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn listen_owned_spawns_for_buildable_connections_and_returns_later_accept_error() {
        let listen = SequencedListen::new([
            Ok(Arc::new(BuildableConnection)),
            Err(test_connection_error(
                "shared accept failed after serving one connection",
            )),
        ]);
        let accepted = listen.accepted.clone();
        let endpoint = Arc::new(H3Endpoint::builder().quic(listen).build());

        let error = endpoint
            .listen_owned(NoopService)
            .await
            .expect_err("listen_owned should return the later listener error");

        assert!(error.is_transport());
        assert_eq!(accepted.load(Ordering::Relaxed), 2);
    }

    /// Verify that QuicMutGuard provides mutable access to the inner QUIC transport.
    #[test]
    fn test_quic_mut_guard_deref_mut() {
        let mut quic = MockConnect;
        let pool = Pool::<MockConnection>::empty();
        let mut guard = QuicMutGuard {
            quic: &mut quic,
            pool: &pool,
        };

        // Verify Deref produces &MockConnect
        let _reference: &MockConnect = &guard;
        let _ = _reference;

        // Verify DerefMut produces &mut MockConnect
        let _mut_reference: &mut MockConnect = &mut guard;
        let _ = _mut_reference;

        drop(guard);
    }

    /// Verify that dropping QuicMutGuard clears the connection pool.
    #[test]
    fn test_quic_mut_guard_drop_clears_pool() {
        let mut quic = MockConnect;
        let pool = Pool::<MockConnection>::empty();

        // Insert an entry into the pool to verify clearing
        let auth: Authority = "example.com:443".parse().unwrap();
        pool.connections
            .entry(auth)
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()));

        assert_eq!(pool.len(), 1);

        {
            let guard = QuicMutGuard {
                quic: &mut quic,
                pool: &pool,
            };
            // Guard holds reference; pool still has entries
            assert_eq!(pool.len(), 1);
            drop(guard);
        } // guard dropped, pool.clear() called

        assert_eq!(pool.len(), 0);
    }

    /// Verify that H3Endpoint::quic_mut provides mutable access to the inner
    /// QUIC transport.
    #[test]
    fn test_quic_mut_access() {
        let mut h3 = H3Endpoint::new(MockConnect);

        let guard = h3.quic_mut();
        let _: &MockConnect = &guard; // verify Deref works
        drop(guard);
    }

    /// Verify that dropping the guard from H3Endpoint::quic_mut clears the
    /// connection pool.
    #[test]
    fn test_quic_mut_drop_clears_pool() {
        let mut h3 = H3Endpoint::new(MockConnect);

        // Insert an entry into the pool
        let auth: Authority = "example.com:443".parse().unwrap();
        h3.pool
            .connections
            .entry(auth)
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()));

        assert_eq!(h3.pool.len(), 1);

        {
            let _guard = h3.quic_mut();
        } // guard dropped, pool.clear() called

        assert_eq!(h3.pool.len(), 0);
    }

    #[test]
    fn quic_mut_allows_mutating_transport_before_clearing_pool_on_drop() {
        let mut endpoint: H3Endpoint<_, BuildableConnection> = H3Endpoint::builder()
            .quic(MutableTransport { generation: 0 })
            .build();
        let pool = endpoint.pool.clone();
        let auth: Authority = "example.com:443".parse().unwrap();
        endpoint
            .pool
            .connections
            .entry(auth)
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()));

        {
            let mut guard = endpoint.quic_mut();
            guard.generation = 1;
            assert_eq!(guard.generation, 1);
            assert_eq!(pool.len(), 1);
        }

        assert_eq!(endpoint.quic().generation, 1);
        assert_eq!(endpoint.pool_len(), 0);
    }

    #[test]
    fn test_clear_pool_clears_endpoint_connections() {
        let h3 = H3Endpoint::new(MockConnect);

        let auth: Authority = "example.com:443".parse().unwrap();
        h3.pool
            .connections
            .entry(auth)
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()));

        assert_eq!(h3.pool_len(), 1);

        h3.clear_pool();

        assert_eq!(h3.pool_len(), 0);
    }

    #[tokio::test]
    async fn clear_pool_forces_next_connect_to_rebuild_connection() {
        let connector = CountingConnect::succeed(IdentifiedConnection::new("reconnect.example"));
        let calls = connector.calls.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "reconnect.example:443".parse().unwrap();

        let first = endpoint
            .connect(server.clone())
            .await
            .expect("first connect should build H3");
        endpoint.clear_pool();
        let second = endpoint
            .connect(server)
            .await
            .expect("second connect should rebuild H3 after clearing pool");

        assert_eq!(calls.load(Ordering::Relaxed), 2);
        assert!(!Arc::ptr_eq(&first, &second));
        assert_eq!(endpoint.pool_len(), 1);
    }

    #[tokio::test]
    async fn dropping_quic_mut_guard_forces_next_connect_to_rebuild_connection() {
        let connector =
            CountingConnect::succeed(IdentifiedConnection::new("guard-reconnect.example"));
        let calls = connector.calls.clone();
        let mut endpoint = H3Endpoint::new(connector);
        let server: Authority = "guard-reconnect.example:443".parse().unwrap();

        let first = endpoint
            .connect(server.clone())
            .await
            .expect("first connect should build H3");
        drop(endpoint.quic_mut());
        let second = endpoint
            .connect(server)
            .await
            .expect("second connect should rebuild H3 after guard drop");

        assert_eq!(calls.load(Ordering::Relaxed), 2);
        assert!(!Arc::ptr_eq(&first, &second));
        assert_eq!(endpoint.pool_len(), 1);
    }

    #[tokio::test]
    async fn connector_errors_are_not_cached_and_later_connect_can_succeed() {
        let connector = SequencedConnect::new([
            Err(test_connection_error("connector failed once")),
            Ok(Arc::new(IdentifiedConnection::new("recover.example"))),
        ]);
        let calls = connector.calls.clone();
        let endpoint = H3Endpoint::new(connector);
        let server: Authority = "recover.example:443".parse().unwrap();

        let first = endpoint
            .connect(server.clone())
            .await
            .expect_err("first connect should fail at the connector");
        let second = endpoint
            .connect(server)
            .await
            .expect("second connect should retry after connector failure");

        assert!(matches!(first, pool::ConnectError::Connector { source } if source.is_transport()));
        assert_eq!(calls.load(Ordering::Relaxed), 2);
        assert_eq!(
            second
                .remote_authority()
                .await
                .expect("remote authority lookup should succeed")
                .as_ref()
                .map(|agent| agent.name()),
            Some("recover.example"),
        );
        assert_eq!(endpoint.pool_len(), 1);
    }

    #[tokio::test]
    async fn listen_connection_returns_when_accepting_request_streams_fails() {
        let quic = Arc::new(ControlledConnection::new("listen connection closed"));
        let state = state_without_qpack(quic.clone());
        let connection = Arc::new(H3Connection::from_state_for_test(state));

        quic.trigger_close();

        timeout(
            Duration::from_millis(100),
            listen_connection(connection, NoopService),
        )
        .await
        .expect("listen_connection should stop when accepting streams fails");
    }

    #[tokio::test]
    async fn listen_connection_skips_requests_when_stream_id_lookup_fails() {
        let quic = Arc::new(ControlledConnection::new("stream id failed"));
        let state = state_without_qpack(quic.clone());
        enqueue_http3_request(
            &state,
            stream_id_error_request_stream(21, quic.close_latch.clone()),
        )
        .await;
        let connection = Arc::new(H3Connection::from_state_for_test(state));
        let seen_streams = Arc::new(Mutex::new(Vec::new()));

        timeout(
            Duration::from_millis(100),
            listen_connection(
                connection,
                RecordingService {
                    seen_streams: seen_streams.clone(),
                    close_latch: Arc::new(CloseLatch::default()),
                },
            ),
        )
        .await
        .expect("listen_connection should stop after stream-id failure closes the connection");

        assert!(
            seen_streams
                .lock()
                .expect("recording service mutex should not be poisoned")
                .is_empty()
        );
    }

    #[tokio::test]
    async fn listen_connection_continues_after_stream_id_lookup_failure() {
        let quic = Arc::new(ControlledConnection::new("stream id failed then recovered"));
        let state = state_with_qpack(quic.clone()).await;
        enqueue_http3_request(&state, second_stream_id_error_request_stream(29)).await;
        enqueue_http3_request(&state, http3_request_stream(31).await).await;
        let connection = Arc::new(H3Connection::from_state_for_test(state));
        let seen_streams = Arc::new(Mutex::new(Vec::new()));

        timeout(
            Duration::from_millis(100),
            listen_connection(
                connection,
                RecordingService {
                    seen_streams: seen_streams.clone(),
                    close_latch: quic.close_latch.clone(),
                },
            ),
        )
        .await
        .expect("listen_connection should continue after stream-id failure");

        timeout(Duration::from_millis(100), async {
            loop {
                if seen_streams
                    .lock()
                    .expect("recording service mutex should not be poisoned")
                    .as_slice()
                    == [StreamId(VarInt::from_u32(31))]
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("valid request after stream-id failure should be served");
    }

    #[tokio::test]
    async fn listen_connection_returns_when_qpack_is_unavailable() {
        let quic = Arc::new(ControlledConnection::new("qpack unused"));
        let state = state_without_qpack(quic);
        enqueue_http3_request(&state, http3_request_stream(23).await).await;
        let connection = Arc::new(H3Connection::from_state_for_test(state));
        let seen_streams = Arc::new(Mutex::new(Vec::new()));

        timeout(
            Duration::from_millis(100),
            listen_connection(
                connection,
                RecordingService {
                    seen_streams: seen_streams.clone(),
                    close_latch: Arc::new(CloseLatch::default()),
                },
            ),
        )
        .await
        .expect("listen_connection should stop when qpack is unavailable");

        assert!(
            seen_streams
                .lock()
                .expect("recording service mutex should not be poisoned")
                .is_empty()
        );
    }

    #[tokio::test]
    async fn listen_connection_spawns_request_handling_for_valid_requests() {
        let quic = Arc::new(ControlledConnection::new("request served"));
        let state = state_with_qpack(quic.clone()).await;
        enqueue_http3_request(&state, http3_request_stream(25).await).await;
        let connection = Arc::new(H3Connection::from_state_for_test(state));
        let seen_streams = Arc::new(Mutex::new(Vec::new()));

        timeout(
            Duration::from_millis(100),
            listen_connection(
                connection,
                RecordingService {
                    seen_streams: seen_streams.clone(),
                    close_latch: quic.close_latch.clone(),
                },
            ),
        )
        .await
        .expect("listen_connection should stop after the test service closes the connection");

        timeout(Duration::from_millis(100), async {
            loop {
                if seen_streams
                    .lock()
                    .expect("recording service mutex should not be poisoned")
                    .as_slice()
                    == [StreamId(VarInt::from_u32(25))]
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("request handler task should record the accepted stream");
    }

    #[tokio::test]
    async fn listen_connection_keeps_running_when_request_handler_returns_error() {
        let quic = Arc::new(ControlledConnection::new("handler failed"));
        let state = state_with_qpack(quic.clone()).await;
        enqueue_http3_request(&state, http3_request_stream(27).await).await;
        let connection = Arc::new(H3Connection::from_state_for_test(state));
        let calls = Arc::new(AtomicUsize::new(0));

        timeout(
            Duration::from_millis(100),
            listen_connection(
                connection,
                FailingService {
                    calls: calls.clone(),
                    close_latch: quic.close_latch.clone(),
                },
            ),
        )
        .await
        .expect("listen_connection should stop after the failing handler closes the connection");

        timeout(Duration::from_millis(100), async {
            loop {
                if calls.load(Ordering::Relaxed) == 1 {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("failing request handler task should run once");

        // calls is incremented inside Service::call before the returned Ready future
        // is polled. Yield additional times so the spawned listen_request task observes
        // the ready error and runs the diagnostic logging branch before the runtime
        // is torn down.
        for _ in 0..16 {
            tokio::task::yield_now().await;
        }
    }

    #[tokio::test]
    async fn test_connection_helpers_expose_expected_pending_and_agent_paths() {
        let buildable = BuildableConnection;
        quic::Lifecycle::check(&buildable).expect("buildable connection is live");
        quic::Lifecycle::close(
            &buildable,
            crate::error::Code::H3_NO_ERROR,
            std::borrow::Cow::Borrowed("test close"),
        );
        assert!(
            quic::WithLocalAuthority::local_authority(&buildable)
                .await
                .expect("buildable local authority")
                .is_none()
        );
        assert!(
            quic::WithRemoteAuthority::remote_authority(&buildable)
                .await
                .expect("buildable remote authority")
                .is_none()
        );
        quic::ManageStream::open_uni(&buildable)
            .await
            .expect("buildable open_uni");
        timeout(
            Duration::from_millis(10),
            quic::ManageStream::open_bi(&buildable),
        )
        .await
        .expect_err("buildable open_bi stays pending");
        timeout(
            Duration::from_millis(10),
            quic::ManageStream::accept_bi(&buildable),
        )
        .await
        .expect_err("buildable accept_bi stays pending");
        timeout(
            Duration::from_millis(10),
            quic::ManageStream::accept_uni(&buildable),
        )
        .await
        .expect_err("buildable accept_uni stays pending");
        timeout(
            Duration::from_millis(10),
            quic::Lifecycle::closed(&buildable),
        )
        .await
        .expect_err("buildable closed stays pending");

        let identified = IdentifiedConnection::new("identified.example");
        quic::Lifecycle::check(&identified).expect("identified connection is live");
        assert!(
            quic::WithLocalAuthority::local_authority(&identified)
                .await
                .expect("identified local authority")
                .is_none()
        );
        let remote = quic::WithRemoteAuthority::remote_authority(&identified)
            .await
            .expect("identified remote authority")
            .expect("identified remote authority exists");
        assert_eq!(
            identity::RemoteAuthority::name(&remote),
            "identified.example"
        );
        assert!(identity::RemoteAuthority::cert_chain(&remote).is_empty());
        quic::ManageStream::open_uni(&identified)
            .await
            .expect("identified open_uni");
        timeout(
            Duration::from_millis(10),
            quic::ManageStream::open_bi(&identified),
        )
        .await
        .expect_err("identified open_bi stays pending");
        timeout(
            Duration::from_millis(10),
            quic::Lifecycle::closed(&identified),
        )
        .await
        .expect_err("identified closed stays pending");
    }

    #[tokio::test]
    async fn test_controlled_connection_and_stream_id_helpers_cover_remaining_traits() {
        let controlled = ControlledConnection::new("controlled terminal");
        quic::Lifecycle::check(&controlled).expect("controlled connection is live");
        assert!(
            quic::WithLocalAuthority::local_authority(&controlled)
                .await
                .expect("controlled local authority")
                .is_none()
        );
        assert!(
            quic::WithRemoteAuthority::remote_authority(&controlled)
                .await
                .expect("controlled remote authority")
                .is_none()
        );
        quic::ManageStream::open_uni(&controlled)
            .await
            .expect("controlled open_uni");
        timeout(
            Duration::from_millis(10),
            quic::ManageStream::open_bi(&controlled),
        )
        .await
        .expect_err("controlled open_bi stays pending");
        quic::Lifecycle::close(
            &controlled,
            crate::error::Code::H3_NO_ERROR,
            std::borrow::Cow::Borrowed("test close"),
        );
        let closed = quic::Lifecycle::closed(&controlled).await;
        assert!(matches!(closed, quic::ConnectionError::Transport { .. }));

        let close_latch = Arc::new(CloseLatch::default());
        let mut stream = StreamIdErrorReadStream::new(close_latch.clone());
        let stream_id_error = stream
            .stream_id()
            .await
            .expect_err("first stream-id helper reports reset");
        assert!(matches!(stream_id_error, quic::StreamError::Reset { .. }));
        close_latch.wait().await;
        stream
            .stop(VarInt::from_u32(0x33))
            .await
            .expect("stop helper is a no-op success");
        assert_eq!(
            Pin::new(&mut stream)
                .next()
                .await
                .expect("stream yields one chunk")
                .expect("chunk is ok"),
            Bytes::from_static(&[0x01])
        );
        assert!(
            Pin::new(&mut stream).next().await.is_none(),
            "stream helper ends after its single chunk"
        );

        let mut stream = StreamIdErrorReadStream::fail_after_first_success(VarInt::from_u32(99));
        assert_eq!(
            stream.stream_id().await.expect("first lookup succeeds"),
            VarInt::from_u32(99)
        );
        assert!(stream.stream_id().await.is_err());
    }

    #[tokio::test]
    async fn test_listener_and_service_helpers_cover_direct_paths() {
        let listen = MockListen::default();
        let shutdowns = listen.shutdowns.clone();
        let mut listen_ref = &listen;
        quic::Listen::shutdown(&listen_ref)
            .await
            .expect("shared mock shutdown succeeds");
        let _accepted = quic::Listen::accept(&mut listen_ref)
            .await
            .expect("shared mock accept succeeds");
        assert_eq!(shutdowns.load(Ordering::Relaxed), 1);
        assert_eq!(listen.accepted.load(Ordering::Relaxed), 1);

        let failing = FailingListen;
        let mut failing_ref = &failing;
        assert!(quic::Listen::accept(&mut failing_ref).await.is_err());
        assert!(quic::Listen::shutdown(&failing_ref).await.is_err());

        let unbuildable = UnbuildableListen;
        let mut unbuildable_ref = &unbuildable;
        let _ = quic::Listen::accept(&mut unbuildable_ref)
            .await
            .expect("shared unbuildable accept returns raw connection");
        quic::Listen::shutdown(&unbuildable_ref)
            .await
            .expect("shared unbuildable shutdown succeeds");

        let sequenced = SequencedListen::new([Ok(Arc::new(BuildableConnection))]);
        quic::Listen::shutdown(&sequenced)
            .await
            .expect("sequenced shutdown succeeds");
        let mut sequenced_ref = &sequenced;
        quic::Listen::shutdown(&sequenced_ref)
            .await
            .expect("shared sequenced shutdown succeeds");
        let _ = quic::Listen::accept(&mut sequenced_ref)
            .await
            .expect("shared sequenced accept consumes queued result");

        let quic = Arc::new(ControlledConnection::new("direct request connection"));
        let state = state_with_qpack(quic).await;
        let qpack = state.qpack().expect("qpack should be initialized");
        let erased = state.erase();
        let connection = Arc::new(erased.clone());
        let (request_reader, _request_write_side) =
            quic::test::mock_stream_pair(VarInt::from_u32(111));
        let (_response_read_side, response_writer) =
            quic::test::mock_stream_pair(VarInt::from_u32(111));
        let close_latch = Arc::new(CloseLatch::default());
        let request = UnresolvedRequest {
            stream_id: StreamId(VarInt::from_u32(111)),
            read_stream: MessageReader::new(
                VarInt::from_u32(111),
                StreamReader::new(GuardQuicReader::new(
                    Box::pin(request_reader) as BoxQuicStreamReader
                )),
                qpack.decoder.clone(),
                erased.clone(),
            ),
            write_stream: MessageWriter::new(
                SinkWriter::new(GuardQuicWriter::new(
                    Box::pin(response_writer) as BoxQuicStreamWriter
                )),
                qpack.encoder.clone(),
                erased,
            ),
            connection,
        };
        let mut service = RecordingService {
            seen_streams: Arc::new(Mutex::new(Vec::new())),
            close_latch,
        };
        listen_request(&mut service, request).await;
        assert_eq!(
            service
                .seen_streams
                .lock()
                .expect("recording service mutex should not be poisoned")
                .as_slice(),
            &[StreamId(VarInt::from_u32(111))]
        );
    }
}