eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
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
//! HTTP/3 transport over QUIC (Quinn + h3).
//!
//! This module is only compiled when the `http3` feature is enabled.
//! HTTP/3 uses QUIC instead of TCP, so it has its own connection lifecycle,
//! TLS configuration, and stream multiplexing model.
//!
//! # Lifecycle
//!
//! Each origin (`host:port`) moves through:
//!
//! `Vacant -> Connecting -> Ready -> Failed/Closed -> Evicted -> Reconnectable`
//!
//! - Only one connection attempt per origin is in flight at a time. The
//!   per-origin [`tokio::sync::OnceCell`] serializes establishment;
//!   concurrent waiters share the same attempt (including DNS, QUIC
//!   handshake, and h3 initialization).
//! - A failed initialization does not poison the origin. `OnceCell`
//!   caches only success; `Err` leaves the cell empty so the next request
//!   retries establishment.
//! - A connection that becomes unusable is evicted from the cache so a
//!   subsequent request reconnects. Eviction removes only cache ownership:
//!   in-flight streams hold their own `SendRequest` clone and the detached
//!   driver task keeps driving until those streams complete.
//! - Client drop releases cache ownership and the QUIC endpoint. Detached
//!   driver tasks terminate when their connections close; in-flight response
//!   bodies hold their QUIC streams and remain valid until consumed or
//!   dropped.
//! - The cache is bounded ([`H3_CACHE_MAX_ENTRIES`]). Eviction drops an
//!   arbitrary idle entry; the next request to an evicted origin reconnects
//!   lazily. In-flight responses survive unrelated eviction.
//!
//! # Policy mapping
//!
//! - `Timeout.connect` bounds DNS + QUIC handshake + h3 initialization as one
//!   connect budget shared across address fallback attempts. `Timeout.total`
//!   remains the outer logical deadline enforced by the pipeline and is never
//!   restarted per address or reconnect.
//! - `Timeout.read` currently applies to response-body progress at the
//!   documented response boundary (post-transport wrapper); response-header
//!   waiting remains total-bounded on this experimental transport.
//!   `Timeout.write` applies to
//!   streamed request-body progress via the pre-transport wrapper installed
//!   before dispatch.
//! - QUIC idle lifetime derives from `PoolConfig::idle_timeout`
//!   (`Limits::keepalive_expiry`). `Timeout.pool` is an acquisition budget
//!   and never controls idle lifetime. Without explicit configuration the
//!   default is [`H3_DEFAULT_IDLE_TIMEOUT`] for compatibility.
//! - Logical request concurrency is enforced by the pool (one permit per
//!   request). QUIC stream limits are physical transport settings kept
//!   separate: `max_concurrent_bidi_streams` derives from
//!   `PoolConfig::max_connections_per_host` when configured, otherwise
//!   [`H3_DEFAULT_MAX_BIDI_STREAMS`]. The logical limit remains the upper
//!   bound on concurrent H3 streams because each stream holds a permit.
//!
//! # Failure handling
//!
//! The transport never retries internally. On a terminal connection-level
//! failure the stale cache entry is evicted and the original error is
//! returned. Replayable idempotent requests reconnect only through the
//! existing retry machinery on a subsequent attempt; one-shot bodies are
//! never duplicated by the transport.
//!
//! # Alt-Svc discovery (separate cache)
//!
//! Alt-Svc state lives in [`super::alt_svc::AltSvcCache`], owned by the
//! client and logically separate from the QUIC `sender_cache` here. An
//! origin may advertise an alternative with no QUIC session, and evicting a
//! failed QUIC session never erases the advertised route. Alternative
//! authorities affect only UDP routing; SNI, `Host`, cookies, auth, and
//! certificate validation always use the logical origin.
//!
//! # Draining (GOAWAY)
//!
//! GOAWAY is observed through the pinned `h3` 0.0.8 API only:
//! `SendRequest::send_request` fails with `StreamError::RemoteClosing` once
//! the shared `closing` flag is set by `process_goaway`, and the driver
//! `poll_close` terminal carries the HTTP/3 application close code
//! (`ApplicationClose { error_code }`, e.g. `H3_NO_ERROR`). Draining marks
//! the cached generation so no new streams are assigned to it; in-flight
//! streams keep their sender clones and the detached driver until they
//! complete. Reconnect creates a new generation. No upstream bug is worked
//! around by normalizing close errors into success.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Duration;

use bytes::Buf;

use crate::body::{RequestBody, ResponseBody};
use crate::error::{Error, Result};
use crate::pool::PoolConfig;
use crate::response::Response;
use crate::timeout::TimeoutPhase;
use crate::transport::datagram::{DatagramDialer, RouteUdpSocket, ROUTE_IO_ERROR_CODE, ROUTE_MTU};
use crate::transport::dialer::{DialError, DialErrorKind};
use crate::transport::metrics::{H3CloseKind, H3CloseSummary, H3ConnectionDiagnostic, H3RouteKind};

/// Upper bound on cached H3 origin entries.
///
/// Matches the spirit of the SNI (256) and SOCKS (64) client caches without a
/// new LRU dependency. QUIC connections each own a UDP flow, TLS session, and
/// background driver task, so the bound is conservative like SOCKS rather than
/// as generous as SNI. Eviction is arbitrary-entry (hash order) and removes
/// only cache ownership; in-flight streams keep their connection alive.
pub(crate) const H3_CACHE_MAX_ENTRIES: usize = 64;

/// Default QUIC idle timeout when no `keepalive_expiry` is configured.
///
/// Preserves the pre-hardening 30-second behavior as the conservative default.
pub(crate) const H3_DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(30);

/// Default maximum concurrent bidirectional QUIC streams per connection.
///
/// H3 request/response cycles use bidirectional streams. Unidirectional
/// streams carry control traffic and stay at this default.
pub(crate) const H3_DEFAULT_MAX_BIDI_STREAMS: u32 = 100;

/// Default maximum concurrent unidirectional QUIC streams per connection.
pub(crate) const H3_DEFAULT_MAX_UNI_STREAMS: u32 = 100;

/// Type alias for the h3 request sender, parameterised over the
/// h3-quinn connection and bytes body type.
type H3Sender = h3::client::SendRequest<h3_quinn::OpenStreams, bytes::Bytes>;

/// Cached h3 sender and its background driver for a single origin.
///
/// The `SendRequest` is clonable; clones share the same h3 connection.
/// When all clones (including the one stored here) are dropped the h3
/// connection is closed with `HTTP_NO_ERROR`. Dropping the cached entry
/// (eviction) detaches the driver task (`JoinHandle` drop does not abort);
/// the task keeps driving until in-flight streams complete and the
/// connection closes.
///
/// `draining` is set when GOAWAY is observed (`RemoteClosing` on new
/// streams) or when the driver `poll_close` resolves. New requests must not
/// be assigned to a draining generation. `close_reason` preserves the
/// upstream HTTP/3 application close code for diagnostics (never
/// synthesized).
struct CachedH3Sender {
    sender: H3Sender,
    _driver: tokio::task::JoinHandle<()>,
    draining: Arc<AtomicBool>,
    #[allow(
        dead_code,
        reason = "preserved upstream close code for diagnostics via test hook"
    )]
    close_reason: Arc<std::sync::Mutex<Option<String>>>,
    /// Alt-Svc generation this session was built for (`None` = explicit
    /// `Http3Only` direct route, no discovery).
    alt_generation: Option<u64>,
    /// Route-owned QUIC endpoint for a caller-routed generation.
    ///
    /// Held purely for ownership: dropping it releases the abstract endpoint,
    /// which releases the caller's [`DatagramRoute`] and aborts the two bridge
    /// worker tasks. `None` for direct generations, which share the connector's
    /// single long-lived endpoint.
    _route_endpoint: Option<quinn::Endpoint>,
    /// Bridge handle for a caller-routed generation, used to read typed route
    /// failure evidence after the QUIC layer has already reported a symptom.
    route_socket: Option<Arc<RouteUdpSocket>>,
}

/// Explicit H3 dispatch failure.
///
/// Carries whether any request body bytes may have been committed so the
/// pipeline can decide safe fallback without inferring from error strings.
/// `body_committed=false` means no application data was sent (connect,
/// handshake, or pre-send drain); only then may `Auto` fall back for
/// replayable bodies.
#[derive(Debug, Clone)]
pub(crate) struct H3DispatchError {
    /// Underlying transport error.
    pub(crate) error: crate::error::Error,
    /// `true` once request body bytes may have been delivered.
    pub(crate) body_committed: bool,
    /// `true` when the peer indicated graceful drain (GOAWAY).
    pub(crate) draining: bool,
    /// Failure class for suppression (variant-derived, never strings).
    pub(crate) failure_class: super::alt_svc::H3FailureClass,
}

impl H3DispatchError {
    fn new(error: crate::error::Error, body_committed: bool, draining: bool) -> Self {
        let failure_class = super::alt_svc::H3FailureClass::from_error(&error);
        Self {
            error,
            body_committed,
            draining,
            failure_class,
        }
    }

    /// Total-deadline expiry for an H3 attempt (pre-commit, request-scoped).
    ///
    /// Classified `Other` so it never triggers broken-route suppression;
    /// the outer deadline is monotonic and never restarted by fallback.
    pub(crate) fn for_total_timeout(elapsed: Duration) -> Self {
        Self::new(
            crate::error::Error::Timeout {
                phase: crate::timeout::TimeoutPhase::Total,
                elapsed,
            },
            false,
            false,
        )
    }

    /// Returns `true` when `Auto` may safely fall back to H2/H1 within the
    /// same logical attempt: pre-commit failure only. The caller must also
    /// check body replayability and `Http3Only` strictness.
    pub(crate) fn safe_for_fallback(&self) -> bool {
        // Draining before commit is safe to reconnect, but fallback to H1/H2
        // is also safe (no bytes committed). Draining is handled as
        // reconnect-first by the connector; pipeline fallback uses the same
        // gate. Post-commit failures (including post-commit drains) are never
        // safe to silently replay.
        !self.body_committed
    }
}

/// Alternative endpoint for one H3 attempt.
///
/// `alt_host/alt_port` is the UDP destination; `sni_host` is always the
/// logical origin host for TLS authentication (never the alternative).
#[derive(Debug, Clone)]
pub(crate) struct H3AltTarget {
    /// UDP destination host (resolved via DNS).
    pub(crate) alt_host: String,
    /// UDP destination port.
    pub(crate) alt_port: u16,
    /// Logical origin host for SNI and certificate validation.
    pub(crate) sni_host: String,
    /// Alt-Svc generation (for suppression scoping).
    pub(crate) generation: Option<u64>,
}

/// Per-origin cache cell. The [`tokio::sync::OnceCell`] guarantees only
/// one caller per origin establishes the QUIC connection; concurrent
/// requests to the same origin await the same initialization instead of
/// racing get-then-insert (which duplicated connections and orphaned the
/// loser's driver task). Failures are not cached: `get_or_try_init` leaves
/// the cell empty on `Err`, so the origin stays reconnectable.
type CachedH3SenderCell = Arc<tokio::sync::OnceCell<CachedH3Sender>>;

/// A shared QUIC endpoint for HTTP/3 connections.
///
/// The endpoint is cloneable and manages the underlying UDP socket.
/// h3 senders are cached per origin so that the same h3 connection
/// (and therefore the same QUIC connection) is reused for subsequent
/// requests to the same host:port.
/// Per-origin H3 sender cache.
///
/// Standard-library `RwLock` around a plain map; locks are short-lived and
/// never held across `.await` or I/O. Poisoning is recovered via
/// `into_inner` (same rationale as `CookieJar`/`AltSvcCache`): the map has
/// no cross-entry invariants, so a panicked holder cannot leave it
/// structurally inconsistent.
type H3SenderCache = Arc<RwLock<HashMap<String, CachedH3SenderCell>>>;

fn h3_cache_get(cache: &H3SenderCache, key: &str) -> Option<CachedH3SenderCell> {
    cache
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(key)
        .cloned()
}

fn h3_cache_insert(cache: &H3SenderCache, key: String, cell: CachedH3SenderCell) {
    cache
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(key, cell);
}

fn h3_cache_remove(cache: &H3SenderCache, key: &str) {
    cache
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(key);
}

fn h3_cache_get_or_insert_default(cache: &H3SenderCache, key: String) -> CachedH3SenderCell {
    // Fast read path first to avoid write contention on hot origins.
    if let Some(cell) = h3_cache_get(cache, &key) {
        return cell;
    }
    let mut table = cache
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(cell) = table.get(&key).cloned() {
        return cell;
    }
    let cell: CachedH3SenderCell = Arc::new(tokio::sync::OnceCell::new());
    table.insert(key, cell.clone());
    cell
}

#[derive(Clone)]
pub(crate) struct H3Connector {
    /// Shared direct QUIC endpoint. `None` when a caller-owned datagram dialer
    /// is configured: routed generations never share a direct endpoint and
    /// configuring a dialer must not open a direct UDP socket at all.
    endpoint: Option<quinn::Endpoint>,
    /// Caller-owned datagram dialer, when configured.
    datagram_dialer: Option<Arc<dyn DatagramDialer>>,
    tls_config: Option<crate::tls::TlsConfig>,
    sender_cache: H3SenderCache,
    /// Effective QUIC idle timeout derived from pool keepalive configuration.
    quinn_idle_timeout: Duration,
    /// Effective maximum concurrent bidirectional streams per QUIC connection.
    max_bidi_streams: u32,
    /// Shared transport observability counters. `None` disables metering.
    metrics: Option<Arc<crate::transport::metrics::TransportMetrics>>,
}

/// Derive the QUIC idle timeout from pool configuration.
///
/// Maps `PoolConfig::idle_timeout` (`Limits::keepalive_expiry`) to the QUIC
/// transport timeout. `Timeout.pool` is deliberately not consulted: it is a
/// permit-acquisition budget, not a connection lifetime. Quinn requires a
/// protocol transport timeout that cannot exactly equal Hyper's pool idle
/// policy (QUIC idles on packet activity, Hyper idles on pool checkout), so
/// the mapping is documented here rather than claimed as identical.
fn derive_quinn_idle_timeout(pool_config: &PoolConfig) -> Duration {
    pool_config.idle_timeout.unwrap_or(H3_DEFAULT_IDLE_TIMEOUT)
}

/// Derive the QUIC bidirectional stream limit from pool configuration.
///
/// Keeps the physical transport limit separate from logical request
/// concurrency while ensuring the transport does not contradict configured
/// policy: when the effective per-origin in-flight limit
/// (`max_in_flight_requests_per_origin` or alias
/// `max_connections_per_host`) is set, the QUIC connection admits at
/// least that many concurrent request streams. Without explicit
/// configuration the conservative default applies. The global limit spans
/// origins and does not size a single connection's streams.
fn derive_max_bidi_streams(pool_config: &PoolConfig) -> u32 {
    match pool_config.effective_max_in_flight_per_origin() {
        Some(n) => u32::try_from(n).unwrap_or(u32::MAX).max(1),
        None => H3_DEFAULT_MAX_BIDI_STREAMS,
    }
}

/// Remaining budget under an optional connect deadline.
fn remaining_connect_budget(deadline: Option<std::time::Instant>) -> Option<Duration> {
    deadline.map(|d| d.saturating_duration_since(std::time::Instant::now()))
}

/// Convert an upstream QUIC close into a bounded, reason-free diagnostic.
fn h3_close_summary(error: &quinn::ConnectionError, graceful: bool) -> H3CloseSummary {
    let (kind, code) = match error {
        quinn::ConnectionError::VersionMismatch => (H3CloseKind::VersionMismatch, None),
        quinn::ConnectionError::TransportError(error) => {
            (H3CloseKind::TransportError, Some(error.code.into()))
        }
        quinn::ConnectionError::ConnectionClosed(close) => {
            (H3CloseKind::ConnectionClosed, Some(close.error_code.into()))
        }
        quinn::ConnectionError::ApplicationClosed(close) => (
            H3CloseKind::ApplicationClosed,
            Some(close.error_code.into()),
        ),
        quinn::ConnectionError::Reset => (H3CloseKind::Reset, None),
        quinn::ConnectionError::TimedOut => (H3CloseKind::TimedOut, None),
        quinn::ConnectionError::LocallyClosed => (H3CloseKind::LocallyClosed, None),
        quinn::ConnectionError::CidsExhausted => (H3CloseKind::CidsExhausted, None),
    };
    H3CloseSummary {
        kind,
        code,
        graceful,
    }
}

/// Snapshot Quinn state without retaining the connection handle in metrics.
fn h3_connection_diagnostic(
    connection: &quinn::Connection,
    route: H3RouteKind,
    alt_svc_generation: Option<u64>,
    close: Option<&quinn::ConnectionError>,
    graceful: bool,
) -> H3ConnectionDiagnostic {
    let stats = connection.stats();
    H3ConnectionDiagnostic {
        stable_id: connection.stable_id(),
        remote_address: connection.remote_address(),
        local_ip: connection.local_ip(),
        route,
        alt_svc_generation,
        rtt: connection.rtt(),
        sent_packets: stats.path.sent_packets,
        received_datagrams: stats.udp_rx.datagrams,
        lost_packets: stats.path.lost_packets,
        sent_bytes: stats.udp_tx.bytes,
        received_bytes: stats.udp_rx.bytes,
        lost_bytes: stats.path.lost_bytes,
        close: close.map(|error| h3_close_summary(error, graceful)),
        open_streams: None,
    }
}

/// A reason-free close label retained only for the existing test hook.
fn h3_close_label(error: &quinn::ConnectionError, graceful: bool) -> String {
    let summary = h3_close_summary(error, graceful);
    match summary.code {
        Some(code) => format!("{:?}:{code}", summary.kind),
        None => format!("{:?}", summary.kind),
    }
}

/// Closes the QUIC connection because its caller-owned route terminated.
///
/// `h3_quinn::Connection` takes ownership of the `quinn::Connection`, so the
/// driver task cannot reach it directly; a clone taken before the h3 session
/// was built can.
fn route_close(conn: Option<&quinn::Connection>) {
    if let Some(conn) = conn {
        conn.close(
            quinn::VarInt::from_u32(ROUTE_IO_ERROR_CODE),
            b"datagram route",
        );
    }
}

/// Builds the abstract Quinn endpoint that owns one caller-routed generation.
///
/// `max_udp_payload_size` is pinned to [`ROUTE_MTU`] so the stack never emits a
/// datagram larger than the IPv6 minimum and never attempts path-MTU discovery
/// over a carrier whose real MTU cannot be measured from here. The caller's
/// runtime requirement is resolved through Quinn's own runtime lookup, so the
/// timer half stays on the tokio runtime the request already runs on.
fn build_route_endpoint(socket: Arc<RouteUdpSocket>) -> std::io::Result<quinn::Endpoint> {
    let runtime = quinn::default_runtime().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "no QUIC runtime available for datagram route",
        )
    })?;
    let mut endpoint_config = quinn::EndpointConfig::default();
    // `max_udp_payload_size` is fallible because it validates the range; a
    // fixed 1200 is always in range, so an error here would be a Quinn
    // contract change rather than a runtime condition.
    endpoint_config
        .max_udp_payload_size(u16::try_from(ROUTE_MTU).unwrap_or(u16::MAX))
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
    quinn::Endpoint::new_with_abstract_socket(endpoint_config, None, socket, runtime)
}

/// Maps a typed caller dial error onto Eggfetch's error taxonomy.
///
/// The mapping preserves the caller's broad kind instead of collapsing it:
/// connect-class for transport failures so `Auto` fallback and Alt-Svc
/// suppression remain safe pre-commit, timeout class for provider-observed
/// timeouts, and the verbatim typed error for explicit rejection and
/// authentication so that evidence is never discarded.
fn route_dial_error(failure: DialError) -> Error {
    match failure.kind() {
        DialErrorKind::Connection => {
            Error::H3Connect(format!("QUIC handshake failed: {}", failure.message()))
        }
        DialErrorKind::Timeout => Error::Timeout {
            phase: TimeoutPhase::Connect,
            elapsed: Duration::ZERO,
        },
        DialErrorKind::Authentication | DialErrorKind::Rejected | DialErrorKind::Other => {
            Error::CustomTransport(Arc::new(failure))
        }
    }
}

/// The route-owned resource chain for one caller-routed generation.
///
/// Kept as a single value so the whole chain is created once, handed to the
/// h3 driver exactly once, and released as one unit when the generation is
/// evicted, terminates, or is dropped.
struct RouteOwnedChain {
    /// Bounded Quinn bridge over the caller's route.
    socket: Arc<RouteUdpSocket>,
    /// Abstract QUIC endpoint. Held for ownership: dropping it releases the
    /// bridge, the caller's [`crate::DatagramRoute`], and the two workers.
    endpoint: quinn::Endpoint,
    /// Terminal-state watcher handed to the h3 driver task.
    watcher: tokio::sync::watch::Receiver<bool>,
}

impl H3Connector {
    /// Create a new H3 connector.
    ///
    /// Derives QUIC idle and stream policy from `pool_config` so the H3 path
    /// honors the same keepalive/concurrency configuration as the H1/H2
    /// paths. See the module-level policy mapping for the exact semantics.
    #[allow(
        dead_code,
        reason = "kept for unit tests without metrics; client paths use with_metrics"
    )]
    pub(crate) fn new(
        tls_config: Option<crate::tls::TlsConfig>,
        pool_config: &PoolConfig,
    ) -> Result<Self> {
        Self::with_metrics(tls_config, pool_config, None)
    }

    /// Create a new H3 connector with shared transport metrics.
    pub(crate) fn with_metrics(
        tls_config: Option<crate::tls::TlsConfig>,
        pool_config: &PoolConfig,
        metrics: Option<Arc<crate::transport::metrics::TransportMetrics>>,
    ) -> Result<Self> {
        Self::with_datagram_route(tls_config, pool_config, metrics, None)
    }

    /// Create a new H3 connector, optionally routing every QUIC generation
    /// through a caller-owned datagram dialer.
    ///
    /// When `datagram_dialer` is `Some`, no direct QUIC endpoint is created at
    /// all. That is the whole point of the seam: a route that fails or refuses
    /// must never be able to fall back to silently opening a direct UDP socket.
    pub(crate) fn with_datagram_route(
        tls_config: Option<crate::tls::TlsConfig>,
        pool_config: &PoolConfig,
        metrics: Option<Arc<crate::transport::metrics::TransportMetrics>>,
        datagram_dialer: Option<Arc<dyn DatagramDialer>>,
    ) -> Result<Self> {
        let endpoint = if datagram_dialer.is_some() {
            None
        } else {
            let bind_addr = "0.0.0.0:0"
                .parse()
                .map_err(|e| Error::Connect(format!("invalid QUIC bind address: {e}")))?;
            Some(
                quinn::Endpoint::client(bind_addr)
                    .map_err(|e| Error::Connect(format!("failed to create QUIC endpoint: {e}")))?,
            )
        };

        Ok(Self {
            endpoint,
            datagram_dialer,
            tls_config,
            sender_cache: Arc::new(RwLock::new(HashMap::new())),
            quinn_idle_timeout: derive_quinn_idle_timeout(pool_config),
            max_bidi_streams: derive_max_bidi_streams(pool_config),
            metrics,
        })
    }

    /// Number of cached origin entries.
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for bounded-cache assertions")]
    pub(crate) fn cache_len(&self) -> usize {
        self.sender_cache
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    /// Returns `true` when `origin_key` (`host:port`) has a cache entry.
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for eviction assertions")]
    pub(crate) fn contains_origin(&self, origin_key: &str) -> bool {
        self.sender_cache
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .contains_key(origin_key)
    }

    /// Effective QUIC idle timeout for this connector.
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for idle-policy assertions")]
    pub(crate) fn quinn_idle_timeout(&self) -> Duration {
        self.quinn_idle_timeout
    }

    /// Effective maximum bidirectional streams per QUIC connection.
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for stream-limit assertions")]
    pub(crate) fn max_bidi_streams(&self) -> u32 {
        self.max_bidi_streams
    }

    /// Cache key for an origin.
    fn cache_key(host: &str, port: u16) -> String {
        format!("{host}:{port}")
    }

    /// Ensure the cache stays bounded by evicting one arbitrary entry.
    ///
    /// Never evicts `except_key` (the origin currently being inserted), so a
    /// newly created entry cannot be removed immediately after creation.
    /// Eviction drops only cache ownership; in-flight streams hold their own
    /// sender clones and the detached driver keeps them alive.
    fn ensure_cache_bound(&self, except_key: &str) {
        let victim = {
            let table = self
                .sender_cache
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if table.len() < H3_CACHE_MAX_ENTRIES {
                return;
            }
            table.keys().find(|k| *k != except_key).cloned()
        };
        if let Some(victim) = victim {
            h3_cache_remove(&self.sender_cache, &victim);
            if let Some(ref m) = self.metrics {
                m.record_h3_eviction();
            }
        }
    }

    /// Remove a stale cache entry only when it is still the current cell.
    ///
    /// A concurrent reconnect may have already replaced the entry; blindly
    /// removing by key could drop the fresh connection. Pointer comparison
    /// keeps eviction scoped to the failed generation.
    fn evict_if_current(&self, key: &str, cell: &CachedH3SenderCell) {
        let is_current = h3_cache_get(&self.sender_cache, key)
            .is_some_and(|current| Arc::ptr_eq(&current, cell));
        if is_current {
            // Re-check under the write lock so a concurrent reconnect that
            // replaced the entry between the read and write cannot be
            // dropped. Removal is idempotent.
            let mut table = self
                .sender_cache
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if table
                .get(key)
                .is_some_and(|current| Arc::ptr_eq(current, cell))
            {
                table.remove(key);
                if let Some(ref m) = self.metrics {
                    m.record_h3_eviction();
                }
            }
        }
    }

    /// Resolve all socket addresses for an origin under the connect budget.
    async fn resolve_addrs(
        host: &str,
        port: u16,
        deadline: Option<std::time::Instant>,
        connect_budget: Option<Duration>,
        started: std::time::Instant,
    ) -> Result<Vec<SocketAddr>> {
        let lookup = tokio::net::lookup_host(format!("{host}:{port}"));
        let addrs: Vec<SocketAddr> = match remaining_connect_budget(deadline) {
            Some(remaining) => tokio::time::timeout(remaining, lookup)
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::Connect,
                    elapsed: started.elapsed(),
                })?
                .map_err(|e| Error::Connect(format!("DNS resolve: {e}")))?
                .collect(),
            None => lookup
                .await
                .map_err(|e| Error::Connect(format!("DNS resolve: {e}")))?
                .collect(),
        };
        if addrs.is_empty() {
            return Err(Error::Connect("no addresses resolved".into()));
        }
        let _ = connect_budget;
        Ok(addrs)
    }

    /// Attempt each resolved address in order under one connect deadline.
    ///
    /// Sequential bounded fallback: earlier candidates that fail yield to the
    /// next address without restarting the connect budget. Each attempt
    /// receives a fair share of the remaining budget (`remaining /
    /// addrs_left`) so a stalling candidate cannot starve later addresses;
    /// fast failures leave nearly the full budget for the next candidate.
    /// Cancellation drops the loop and aborts remaining attempts promptly.
    /// The final error preserves the connect/H3-connect taxonomy without
    /// leaking sensitive detail beyond the transport error itself.
    async fn connect_with_fallback(
        &self,
        endpoint: &quinn::Endpoint,
        addrs: &[SocketAddr],
        host: &str,
        deadline: Option<std::time::Instant>,
        started: std::time::Instant,
    ) -> Result<quinn::Connection> {
        let mut last_err: Option<Error> = None;
        for (idx, addr) in addrs.iter().enumerate() {
            let addrs_left = u32::try_from(addrs.len().saturating_sub(idx)).unwrap_or(u32::MAX);
            let remaining = remaining_connect_budget(deadline).map(|r| {
                let share = r.checked_div(addrs_left.max(1)).unwrap_or(r);
                // Never hand an attempt a zero budget while time remains;
                // the deadline check below reports exhaustion instead.
                share
            });
            if deadline.is_some_and(|d| std::time::Instant::now() >= d)
                || remaining.is_some_and(|r| r.is_zero())
            {
                return Err(last_err.unwrap_or(Error::Timeout {
                    phase: TimeoutPhase::Connect,
                    elapsed: started.elapsed(),
                }));
            }
            match self
                .connect_single(endpoint, *addr, host, remaining, started)
                .await
            {
                Ok(conn) => return Ok(conn),
                Err(e) => {
                    // Per-attempt timeouts fall through to the next address
                    // with its own share; only overall exhaustion (above) is
                    // terminal. This keeps a stalling candidate from
                    // consuming the entire shared budget.
                    last_err = Some(e);
                }
            }
        }
        Err(last_err.unwrap_or_else(|| Error::Connect("no addresses resolved".into())))
    }

    /// Establish a single QUIC connection under the remaining budget.
    async fn connect_single(
        &self,
        endpoint: &quinn::Endpoint,
        addr: SocketAddr,
        host: &str,
        remaining: Option<Duration>,
        started: std::time::Instant,
    ) -> Result<quinn::Connection> {
        let quic_config = build_quic_client_config(
            self.tls_config.as_ref(),
            self.quinn_idle_timeout,
            self.max_bidi_streams,
        )?;
        let connecting = endpoint
            .connect_with(quic_config, addr, host)
            .map_err(|e| Error::Connect(format!("QUIC connect: {e}")))?;
        let conn = match remaining {
            Some(budget) => tokio::time::timeout(budget, connecting)
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::Connect,
                    elapsed: started.elapsed(),
                })?
                .map_err(|e| Error::H3Connect(format!("QUIC handshake failed: {e}")))?,
            None => connecting
                .await
                .map_err(|e| Error::H3Connect(format!("QUIC handshake failed: {e}")))?,
        };
        Ok(conn)
    }

    /// Establish a complete caller-routed QUIC + h3 generation.
    ///
    /// The whole route-owned resource chain is created here and nowhere else:
    /// the caller's [`DatagramRoute`], the bounded Quinn bridge, the abstract
    /// endpoint, and the h3 driver. Everything is returned inside the
    /// [`CachedH3Sender`] so eviction, terminal close, and drop all release the
    /// same chain together.
    ///
    /// `sni_host` is always the logical origin, never the route's physical
    /// peer, so SNI and certificate validation stay bound to the origin even
    /// when the route is a relay.
    async fn establish_routed_generation(
        &self,
        target: crate::transport::dialer::DialTarget,
        sni_host: &str,
        deadline: Option<std::time::Instant>,
        started: std::time::Instant,
        alt_generation: Option<u64>,
        route_kind: H3RouteKind,
    ) -> Result<CachedH3Sender> {
        let dialer = self
            .datagram_dialer
            .as_ref()
            .ok_or_else(|| Error::Connect("no datagram dialer configured".into()))?;

        // Route establishment runs inside the request's own remaining connect
        // budget. A route that never completes is bounded by the caller rather
        // than becoming a hang, and the total deadline is never restarted.
        let route = match remaining_connect_budget(deadline) {
            Some(remaining) => tokio::time::timeout(remaining, dialer.connect(target))
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::Connect,
                    elapsed: started.elapsed(),
                })?,
            None => dialer.connect(target).await,
        }
        .map_err(route_dial_error)?;

        let socket = RouteUdpSocket::from_route(route);
        let watcher = socket.failure_watcher();
        let endpoint = build_route_endpoint(Arc::clone(&socket))
            .map_err(|e| Error::Connect(format!("datagram route endpoint: {e}")))?;
        let quic_config = build_quic_client_config(
            self.tls_config.as_ref(),
            self.quinn_idle_timeout,
            self.max_bidi_streams,
        )?;
        // Quinn always addresses the route's own peer; the bridge refuses any
        // other destination, so the connection cannot be redirected.
        let peer = socket.peer_addr();
        let connecting = endpoint
            .connect_with(quic_config, peer, sni_host)
            .map_err(|e| Error::Connect(format!("QUIC connect: {e}")))?;
        let conn = match remaining_connect_budget(deadline) {
            Some(remaining) => tokio::time::timeout(remaining, connecting)
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::Connect,
                    elapsed: started.elapsed(),
                })?
                .map_err(|e| Error::H3Connect(format!("QUIC handshake failed: {e}")))?,
            None => connecting
                .await
                .map_err(|e| Error::H3Connect(format!("QUIC handshake failed: {e}")))?,
        };

        let sender = Self::establish_h3_sender(
            conn,
            deadline,
            started,
            alt_generation,
            route_kind,
            self.metrics.clone(),
            Some(RouteOwnedChain {
                socket,
                endpoint,
                watcher,
            }),
        )
        .await?;
        Ok(sender)
    }

    /// Establish the h3 client session under the remaining connect budget.
    async fn establish_h3_sender(
        quinn_conn: quinn::Connection,
        deadline: Option<std::time::Instant>,
        started: std::time::Instant,
        alt_generation: Option<u64>,
        route: H3RouteKind,
        metrics: Option<Arc<crate::transport::metrics::TransportMetrics>>,
        route_chain: Option<RouteOwnedChain>,
    ) -> Result<CachedH3Sender> {
        let diagnostic_conn = quinn_conn.clone();
        let diagnostic_conn_for_route = quinn_conn.clone();
        // Direct generations get `None` for all three: they share the
        // connector's single endpoint and have no caller-owned chain to
        // release. Only a routed generation owns a chain.
        let route_socket: Option<Arc<RouteUdpSocket>> =
            route_chain.as_ref().map(|chain| Arc::clone(&chain.socket));
        let route_watcher: Option<tokio::sync::watch::Receiver<bool>> =
            route_chain.as_ref().map(|chain| chain.watcher.clone());
        let route_endpoint: Option<quinn::Endpoint> = route_chain.map(|chain| chain.endpoint);
        let init = async {
            let h3_conn = h3_quinn::Connection::new(quinn_conn);
            h3::client::new(h3_conn)
                .await
                .map_err(|e| Error::H3Protocol(format!("h3 client init: {e}")))
        };
        let (mut driver, sender) = match remaining_connect_budget(deadline) {
            Some(remaining) => {
                tokio::time::timeout(remaining, init)
                    .await
                    .map_err(|_| Error::Timeout {
                        phase: TimeoutPhase::Connect,
                        elapsed: started.elapsed(),
                    })??
            }
            None => init.await?,
        };
        let draining: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
        let close_reason: Arc<std::sync::Mutex<Option<String>>> =
            Arc::new(std::sync::Mutex::new(None));
        let draining_for_driver = draining.clone();
        let reason_for_driver = close_reason.clone();
        let metrics_for_driver = metrics.clone();
        if let Some(ref m) = metrics {
            m.record_h3_diagnostic(h3_connection_diagnostic(
                &diagnostic_conn,
                route,
                alt_generation,
                None,
                false,
            ));
        }
        let driver_handle = tokio::spawn(async move {
            use futures_util::future;
            // A dead route must not leave a request parked until the QUIC idle
            // timeout. The bridge already reports the I/O error to Quinn, so
            // this task's job is to make the connection terminal immediately:
            // close it with a transport error and then observe the ordinary
            // close path so metrics and drain state stay in one place.
            let close_err = match route_watcher {
                Some(mut watcher) => {
                    if *watcher.borrow() {
                        route_close(Some(&diagnostic_conn_for_route));
                    }
                    tokio::select! {
                        biased;
                        () = async {
                            // `watch` retains the last value, so a failure
                            // recorded before this branch was reached is
                            // observed here rather than lost.
                            while !*watcher.borrow_and_update() {
                                if watcher.changed().await.is_err() {
                                    return;
                                }
                            }
                        } => {
                            route_close(Some(&diagnostic_conn_for_route));
                            future::poll_fn(|cx| driver.poll_close(cx)).await
                        }
                        close_err = future::poll_fn(|cx| driver.poll_close(cx)) => close_err,
                    }
                }
                None => future::poll_fn(|cx| driver.poll_close(cx)).await,
            };
            draining_for_driver.store(true, Ordering::Relaxed);
            let graceful = close_err.is_h3_no_error();
            let quinn_close = diagnostic_conn.close_reason();
            if let Ok(mut guard) = reason_for_driver.lock() {
                *guard = quinn_close
                    .as_ref()
                    .map(|error| h3_close_label(error, graceful));
            }
            if let Some(m) = metrics_for_driver {
                if let Some(error) = quinn_close.as_ref() {
                    m.record_h3_diagnostic(h3_connection_diagnostic(
                        &diagnostic_conn,
                        route,
                        alt_generation,
                        Some(error),
                        graceful,
                    ));
                }
                m.record_h3_closed();
                // Graceful application close (`H3_NO_ERROR`) is a drain,
                // not a failure. Uses the public `is_h3_no_error()` API
                // (pinned h3 0.0.8); no variant matching, no strings.
                if graceful {
                    m.record_h3_drain();
                }
            }
        });
        Ok(CachedH3Sender {
            sender,
            _driver: driver_handle,
            draining,
            close_reason,
            alt_generation,
            _route_endpoint: route_endpoint,
            route_socket,
        })
    }

    /// Maps a QUIC-layer symptom to typed caller evidence when the generation
    /// runs over a caller-owned route.
    ///
    /// The QUIC error is a downstream symptom of the real cause, so this is the
    /// one place that replaces it. Every other classification decision stays
    /// variant-derived, and no `Display` text is ever parsed.
    fn route_error_override(route_socket: Option<&Arc<RouteUdpSocket>>, fallback: Error) -> Error {
        let Some(socket) = route_socket else {
            return fallback;
        };
        let Some(failure) = socket.route_failure() else {
            return fallback;
        };
        match failure.kind() {
            DialErrorKind::Connection => {
                Error::H3Connect(format!("QUIC handshake failed: {}", failure.message()))
            }
            DialErrorKind::Timeout => Error::Timeout {
                phase: TimeoutPhase::Connect,
                elapsed: Duration::ZERO,
            },
            // Rejection and authentication evidence is preserved verbatim as a
            // custom-transport error rather than being reclassified, because
            // Eggfetch has no evidence of its own about why the provider
            // refused. The kind survives in the typed source chain.
            DialErrorKind::Authentication | DialErrorKind::Rejected | DialErrorKind::Other => {
                Error::CustomTransport(Arc::new(failure))
            }
        }
    }

    /// Returns `true` when the cached cell is draining (GOAWAY observed or
    /// driver closed). Test hook for drain assertions.
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for drain assertions")]
    pub(crate) fn is_draining_key(&self, origin_key: &str) -> bool {
        h3_cache_get(&self.sender_cache, origin_key).is_some_and(|r| {
            r.get()
                .is_some_and(|cached| cached.draining.load(Ordering::Relaxed))
        })
    }

    /// Last driver close reason for `origin_key`, if any (preserved upstream
    /// close code, never synthesized).
    #[cfg(any(test, feature = "test-util"))]
    #[allow(dead_code, reason = "test hook for close-code assertions")]
    pub(crate) fn close_reason_key(&self, origin_key: &str) -> Option<String> {
        h3_cache_get(&self.sender_cache, origin_key).and_then(|r| {
            let cached = r.get()?;
            cached.close_reason.lock().ok()?.clone()
        })
    }

    /// Issue an HTTP/3 request and return a `Response` with a streaming body.
    ///
    /// `connect_timeout` bounds DNS + QUIC + h3 establishment as one budget
    /// shared across address fallback attempts. The outer pipeline enforces
    /// `Timeout.total`; this function never restarts that deadline. Read and
    /// write phase timeouts are enforced by the pipeline's body wrappers at
    /// the documented boundaries, so phase identity is preserved instead of
    /// collapsing into generic H3 protocol errors.
    ///
    /// `alt` carries an Alt-Svc-discovered UDP destination; SNI and
    /// certificate validation always use the logical origin host. `None`
    /// means explicit direct (`Http3Only`) routing.
    ///
    /// The transport performs no hidden retries except one draining
    /// reconnect (GOAWAY before commit): a draining generation is evicted
    /// and a single fresh generation is attempted within the same connect
    /// budget. All other connection-level failures evict the stale origin
    /// entry and return the original error; a later retry-policy attempt
    /// reconnects through the normal machinery. One-shot bodies are never
    /// replayed here. Failures report `body_committed` explicitly so the
    /// pipeline can gate safe fallback without string inference.
    #[allow(
        dead_code,
        reason = "kept for unit tests; pipeline uses send_request_with_alt"
    )]
    pub(crate) async fn send_request(
        &self,
        request: http::Request<RequestBody>,
        url: url::Url,
        connect_timeout: Option<Duration>,
    ) -> Result<Response> {
        self.send_request_inner(request, url, None, connect_timeout)
            .await
            .map_err(|e| e.error)
    }

    /// Detailed H3 dispatch with explicit commit/drain signalling for the
    /// pipeline fallback and suppression policy.
    pub(crate) async fn send_request_with_alt(
        &self,
        request: http::Request<RequestBody>,
        url: url::Url,
        alt: Option<H3AltTarget>,
        connect_timeout: Option<Duration>,
    ) -> std::result::Result<Response, H3DispatchError> {
        self.send_request_inner(request, url, alt, connect_timeout)
            .await
    }

    #[allow(
        clippy::too_many_lines,
        reason = "H3 dispatch centralizes connect/fallback/drain policy so transports do not reimplement it"
    )]
    async fn send_request_inner(
        &self,
        request: http::Request<RequestBody>,
        url: url::Url,
        alt: Option<H3AltTarget>,
        connect_timeout: Option<Duration>,
    ) -> std::result::Result<Response, H3DispatchError> {
        let map_err = |e: Error, committed: bool, draining: bool| {
            H3DispatchError::new(e, committed, draining)
        };
        let host = url
            .host_str()
            .ok_or_else(|| map_err(Error::InvalidUrl("missing host".into()), false, false))?;
        let port = url.port_or_known_default().unwrap_or(443);
        let cache_key = Self::cache_key(host, port);
        let host_owned = host.to_owned();
        // Alt-Svc routing: UDP destination may differ from the logical
        // origin. SNI and certificate validation always use the origin host.
        let (resolve_host, resolve_port, sni_host, alt_generation) = match &alt {
            Some(a) => (
                a.alt_host.clone(),
                a.alt_port,
                a.sni_host.clone(),
                a.generation,
            ),
            None => (host_owned.clone(), port, host_owned.clone(), None),
        };

        self.ensure_cache_bound(&cache_key);
        let mut cell = h3_cache_get_or_insert_default(&self.sender_cache, cache_key.clone());

        // Generation change (new advertisement) evicts the old QUIC session
        // so the new alternative is used immediately without waiting on
        // stale failure state. Draining generations are also evicted before
        // assigning new streams; in-flight streams survive via their clones.
        let mut was_reconnect = false;
        if let Some(cached) = cell.get() {
            let stale_generation = cached.alt_generation != alt_generation;
            let draining = cached.draining.load(Ordering::Relaxed);
            if stale_generation || draining {
                self.evict_if_current(&cache_key, &cell);
                let fresh: CachedH3SenderCell = Arc::new(tokio::sync::OnceCell::new());
                self.ensure_cache_bound(&cache_key);
                h3_cache_insert(&self.sender_cache, cache_key.clone(), fresh.clone());
                cell = fresh;
                // A fresh generation after eviction counts as a reconnect
                // once it establishes successfully below.
                was_reconnect = true;
            }
        }

        // Fast path: an established connection needs no DNS or handshake.
        // The slow path below shares DNS + QUIC + h3 init across concurrent
        // waiters through the same `OnceCell`.
        let cached = if let Some(cached) = cell.get() {
            cached
        } else {
            let started = std::time::Instant::now();
            let deadline = connect_timeout.map(|d| started + d);
            let endpoint_self = self.clone();
            let resolve_host_clone = resolve_host.clone();
            let sni_host_clone = sni_host.clone();
            let route_kind = if alt.is_some() {
                H3RouteKind::AltSvc
            } else {
                H3RouteKind::Explicit
            };
            let init_result: std::result::Result<&CachedH3Sender, Error> = cell
                .get_or_try_init(|| async {
                    let sender = if endpoint_self.datagram_dialer.is_some() {
                        // Caller-routed generation: no DNS and no direct
                        // endpoint at all. The dialer receives the original
                        // logical target, and SNI stays the origin host even
                        // when the route's physical peer is a relay.
                        endpoint_self
                            .establish_routed_generation(
                                crate::transport::dialer::DialTarget::new(
                                    &resolve_host_clone,
                                    resolve_port,
                                ),
                                &sni_host_clone,
                                deadline,
                                started,
                                alt_generation,
                                route_kind,
                            )
                            .await?
                    } else {
                        let endpoint = endpoint_self
                            .endpoint
                            .as_ref()
                            .ok_or_else(|| Error::Connect("no QUIC endpoint available".into()))?;
                        let addrs = Self::resolve_addrs(
                            &resolve_host_clone,
                            resolve_port,
                            deadline,
                            connect_timeout,
                            started,
                        )
                        .await?;
                        let quinn_conn = endpoint_self
                            .connect_with_fallback(
                                endpoint,
                                &addrs,
                                &sni_host_clone,
                                deadline,
                                started,
                            )
                            .await?;
                        Self::establish_h3_sender(
                            quinn_conn,
                            deadline,
                            started,
                            alt_generation,
                            route_kind,
                            endpoint_self.metrics.clone(),
                            None,
                        )
                        .await?
                    };
                    if let Some(ref m) = endpoint_self.metrics {
                        m.record_h3_created();
                        if was_reconnect {
                            m.record_h3_reconnected();
                        }
                    }
                    Ok(sender)
                })
                .await;
            match init_result {
                Ok(cached) => cached,
                Err(e) => {
                    // `OnceCell` caches only success, so the origin is already
                    // reconnectable. Propagate the connect-phase taxonomy
                    // (`Timeout{Connect}`, `Connect`, `H3Connect`) unchanged.
                    return Err(map_err(e.clone(), false, false));
                }
            }
        };
        let sender = cached.sender.clone();
        // Route evidence is resolved once per dispatch so a caller-routed
        // generation reports the caller's typed cause instead of the QUIC
        // symptom it produced.
        let route_socket = cached.route_socket.clone();
        let with_route_evidence =
            |error: Error| Self::route_error_override(route_socket.as_ref(), error);

        // Decompose the incoming request
        let (parts, body) = request.into_parts();

        // Build h3 request (body is always () for the h3 request frame)
        let mut h3_request = http::Request::builder()
            .method(parts.method)
            .uri(parts.uri)
            .version(parts.version);

        for (name, value) in &parts.headers {
            h3_request = h3_request.header(name, value);
        }

        let h3_request = h3_request
            .body(())
            .map_err(|e| map_err(Error::RequestBuild(e.to_string()), false, false))?;

        // Send the request headers. Pre-commit failures (including GOAWAY
        // drain signalled via shared closing state) evict the stale
        // generation so the next attempt reconnects. Draining is observed
        // through the public `h3::ConnectionState::is_closing()` API on the
        // pinned h3 0.0.8 sender (set by `process_goaway`); no variant
        // matching, no error strings.
        // No hidden retry happens here; the caller (retry/fallback policy)
        // decides whether to attempt again. In-flight streams keep their
        // clones and the detached driver.
        let mut request_stream = {
            let mut sender = sender;
            match sender.send_request(h3_request).await {
                Ok(stream) => stream,
                Err(e) => {
                    // GOAWAY sets shared `closing`; a send failure while
                    // closing is a graceful drain, not an arbitrary failure.
                    let draining = {
                        use h3::ConnectionState;
                        sender.is_closing()
                    };
                    // Mark the cached generation draining so no new streams
                    // are assigned to it; in-flight streams survive via
                    // their clones and the detached driver.
                    if draining {
                        if let Some(cached) = cell.get() {
                            cached.draining.store(true, Ordering::Relaxed);
                        }
                        if let Some(ref m) = self.metrics {
                            m.record_h3_drain();
                        }
                    }
                    self.evict_if_current(&cache_key, &cell);
                    if draining {
                        return Err(map_err(
                            Error::H3ConnectionClosed("peer draining (GOAWAY)".into()),
                            false,
                            true,
                        ));
                    }
                    return Err(map_err(
                        with_route_evidence(Error::H3Protocol(format!("send request: {e}"))),
                        false,
                        false,
                    ));
                }
            }
        };

        // Send request body. The pipeline wraps streamed bodies with the
        // write-phase timeout before dispatch, so a stalled producer surfaces
        // as `Timeout{Write}` here and must not evict the connection.
        // Body-phase failures are post-commit (bytes may have been
        // delivered) and never safe for silent fallback.
        let send_body_result = async {
            match body {
                RequestBody::Empty => Ok(()),
                RequestBody::Bytes(bytes) => request_stream
                    .send_data(bytes)
                    .await
                    .map_err(|e| Error::H3Protocol(format!("send data: {e}"))),
                RequestBody::Stream {
                    stream: body_stream,
                    ..
                } => {
                    use futures_util::StreamExt;
                    let mut body_stream = body_stream;
                    while let Some(chunk) = body_stream.next().await {
                        let bytes = chunk?;
                        request_stream
                            .send_data(bytes)
                            .await
                            .map_err(|e| Error::H3Protocol(format!("send data: {e}")))?;
                    }
                    Ok(())
                }
            }
        }
        .await;
        if let Err(e) = send_body_result {
            // Write-phase timeouts (`Timeout{Write}`) and body producer
            // errors are request scoped and must not evict the shared
            // connection. H3 transport failures evict so the next attempt
            // reconnects. All body-phase outcomes are post-commit for
            // fallback gating.
            let transport_failure = matches!(
                e,
                Error::H3Protocol(_)
                    | Error::H3ConnectionClosed(_)
                    | Error::H3Stream(_)
                    | Error::H3Connect(_)
            );
            if transport_failure {
                self.evict_if_current(&cache_key, &cell);
            }
            return Err(map_err(with_route_evidence(e), true, false));
        }

        // Signal end of request body (post-commit).
        if let Err(err) = request_stream.finish().await {
            self.evict_if_current(&cache_key, &cell);
            return Err(map_err(
                with_route_evidence(Error::H3Protocol(format!("finish stream: {err}"))),
                true,
                false,
            ));
        }

        // Receive response headers (post-commit: request was delivered).
        let response = match request_stream.recv_response().await {
            Ok(response) => response,
            Err(e) => {
                self.evict_if_current(&cache_key, &cell);
                return Err(map_err(
                    with_route_evidence(Error::H3Protocol(format!("recv response: {e}"))),
                    true,
                    false,
                ));
            }
        };

        let status = response.status();
        let resp_version = response.version();
        let mut resp_headers = http::HeaderMap::new();
        for (name, value) in response.headers() {
            resp_headers.insert(name.clone(), value.clone());
        }

        // Build a streaming response body from the h3 data frames.
        // recv_data() returns `impl Buf`; we convert to Bytes for compatibility
        // with our BoxBytesStream type. After data EOF, recv_trailers() is
        // attempted once and stored without buffering the body.
        //
        // The body stream holds only the request stream. The h3 sender and
        // driver are kept alive by the sender cache (or, after eviction, by
        // the detached driver plus in-flight sender clones), so the body does
        // not need to own them. On a body transport failure the stream evicts
        // the stale origin so the next request reconnects.
        let cache_for_body = self.sender_cache.clone();
        let key_for_body = cache_key.clone();
        let cell_for_body = cell.clone();
        let route_for_body = route_socket.clone();
        let trailers = crate::body::SharedTrailers::new();
        let trailers_for_body = trailers.clone();
        let body_stream = futures_util::stream::unfold(
            (request_stream, false),
            move |(mut stream, trailers_done)| {
                let cache_for_body = cache_for_body.clone();
                let key_for_body = key_for_body.clone();
                let cell_for_body = cell_for_body.clone();
                let trailers_for_body = trailers_for_body.clone();
                let route_for_body = route_for_body.clone();
                async move {
                    if trailers_done {
                        return None;
                    }
                    match stream.recv_data().await {
                        Ok(Some(mut data)) => {
                            let bytes = data.copy_to_bytes(data.remaining());
                            Some((Ok::<_, Error>(bytes), (stream, false)))
                        }
                        Ok(None) => {
                            // Data complete; attempt trailers once.
                            match stream.recv_trailers().await {
                                Ok(Some(headers)) => {
                                    trailers_for_body.store(headers);
                                }
                                Ok(None) => {}
                                Err(e) => {
                                    if h3_cache_get(&cache_for_body, &key_for_body).is_some_and(
                                        |current| Arc::ptr_eq(&current, &cell_for_body),
                                    ) {
                                        h3_cache_remove(&cache_for_body, &key_for_body);
                                    }
                                    return Some((
                                        Err(Self::route_error_override(
                                            route_for_body.as_ref(),
                                            Error::H3Protocol(format!("recv trailers: {e}")),
                                        )),
                                        (stream, true),
                                    ));
                                }
                            }
                            None
                        }
                        Err(e) => {
                            if h3_cache_get(&cache_for_body, &key_for_body)
                                .is_some_and(|current| Arc::ptr_eq(&current, &cell_for_body))
                            {
                                h3_cache_remove(&cache_for_body, &key_for_body);
                            }
                            Some((
                                Err(Self::route_error_override(
                                    route_for_body.as_ref(),
                                    Error::H3Protocol(format!("recv data: {e}")),
                                )),
                                (stream, true),
                            ))
                        }
                    }
                }
            },
        );

        let body = ResponseBody::streaming(Box::pin(body_stream));

        let mut core_response = Response::new(status, resp_version, resp_headers, url, body);
        core_response.set_trailers(trailers);
        Ok(core_response)
    }
}

/// Build a QUIC client configuration.
///
/// QUIC requires TLS 1.3 only. When a `TlsConfig` is provided, its trust
/// store, client identity, and verification settings are honoured. Otherwise
/// a default config with webpki roots is used.
///
/// `idle_timeout` is the effective QUIC idle lifetime derived from pool
/// keepalive configuration (see [`derive_quinn_idle_timeout`]).
/// `max_bidi_streams` is the effective per-connection bidirectional stream
/// limit derived from logical pool policy (see [`derive_max_bidi_streams`]).
fn build_quic_client_config(
    tls_config: Option<&crate::tls::TlsConfig>,
    idle_timeout: Duration,
    max_bidi_streams: u32,
) -> Result<quinn::ClientConfig> {
    let default_tls_config = crate::tls::TlsConfig::default();
    let tls_config = tls_config.unwrap_or(&default_tls_config);
    let rc = tls_config.build_quic_rustls_config()?;

    let quic_crypto = quinn::crypto::rustls::QuicClientConfig::try_from(rc)
        .map_err(|e| Error::Tls(format!("QUIC TLS config conversion: {e}")))?;

    let mut quic_config = quinn::ClientConfig::new(Arc::new(quic_crypto));

    // Configure transport parameters. The bidi limit is the physical QUIC
    // stream cap, kept separate from the logical pool permit model: every
    // in-flight H3 request holds a pool permit, so the logical per-origin
    // limit remains the upper bound on concurrent streams.
    let mut transport = quinn::TransportConfig::default();
    transport.max_concurrent_bidi_streams(max_bidi_streams.into());
    transport.max_concurrent_uni_streams(H3_DEFAULT_MAX_UNI_STREAMS.into());

    transport.max_idle_timeout(Some(
        quinn::IdleTimeout::try_from(idle_timeout)
            .map_err(|e| Error::Tls(format!("invalid idle timeout: {e}")))?,
    ));

    quic_config.transport_config(Arc::new(transport));

    Ok(quic_config)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pool_with(idle: Option<Duration>, per_host: Option<usize>) -> PoolConfig {
        PoolConfig {
            idle_timeout: idle,
            max_connections_per_host: per_host,
            ..PoolConfig::default()
        }
    }

    #[test]
    fn idle_defaults_to_thirty_seconds() {
        let derived = derive_quinn_idle_timeout(&pool_with(None, None));
        assert_eq!(derived, Duration::from_secs(30));
    }

    #[test]
    fn idle_follows_keepalive_expiry() {
        let derived = derive_quinn_idle_timeout(&pool_with(Some(Duration::from_secs(5)), None));
        assert_eq!(derived, Duration::from_secs(5));
    }

    #[test]
    fn bidi_defaults_to_one_hundred() {
        assert_eq!(derive_max_bidi_streams(&pool_with(None, None)), 100);
    }

    #[test]
    fn bidi_follows_per_host_limit() {
        assert_eq!(derive_max_bidi_streams(&pool_with(None, Some(10))), 10);
        // A large logical limit raises the physical cap so the transport does
        // not contradict configured concurrency.
        assert_eq!(derive_max_bidi_streams(&pool_with(None, Some(1000))), 1000);
    }

    #[test]
    fn cache_bound_is_sixty_four() {
        assert_eq!(H3_CACHE_MAX_ENTRIES, 64);
    }

    #[test]
    fn close_classification_is_sanitized_and_preserves_codes() {
        let graceful = quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose {
            error_code: quinn::VarInt::from_u32(0x100),
            reason: bytes::Bytes::from_static(b"peer reason must not escape"),
        });
        let summary = h3_close_summary(&graceful, true);
        assert_eq!(summary.kind, H3CloseKind::ApplicationClosed);
        assert_eq!(summary.code, Some(0x100));
        assert!(summary.graceful);
        assert!(!format!("{summary:?}").contains("peer reason"));

        let non_graceful = h3_close_summary(&quinn::ConnectionError::Reset, false);
        assert_eq!(non_graceful.kind, H3CloseKind::Reset);
        assert_eq!(non_graceful.code, None);
        assert!(!non_graceful.graceful);
    }
    #[test]
    fn quic_config_uses_derived_policy() {
        // `ClientConfig` exposes no transport getter; a successful build with
        // derived values plus the connector-level getter tests below pins the
        // mapping without reaching into Quinn internals.
        let _ = build_quic_client_config(None, Duration::from_secs(5), 10).expect("quic config");
        let _ = build_quic_client_config(None, Duration::from_secs(30), 100).expect("quic config");
    }

    #[cfg(any(test, feature = "test-util"))]
    #[tokio::test]
    async fn connector_derives_policy_from_pool() {
        let pool = pool_with(Some(Duration::from_secs(7)), Some(12));
        let connector = H3Connector::new(None, &pool).expect("connector");
        assert_eq!(connector.quinn_idle_timeout(), Duration::from_secs(7));
        assert_eq!(connector.max_bidi_streams(), 12);
    }

    #[cfg(any(test, feature = "test-util"))]
    #[tokio::test]
    async fn connector_defaults_match_legacy_behavior() {
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector");
        assert_eq!(connector.quinn_idle_timeout(), Duration::from_secs(30));
        assert_eq!(connector.max_bidi_streams(), 100);
        assert_eq!(connector.cache_len(), 0);
    }

    #[tokio::test]
    async fn cache_bound_evicts_without_losing_current_origin() {
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector builds");
        // Fill beyond capacity through the same bounded-insert path used by
        // `send_request` so the test pins the production eviction policy.
        for i in 0..(H3_CACHE_MAX_ENTRIES + 10) {
            let key = format!("host-{i}.example:443");
            connector.ensure_cache_bound(&key);
            h3_cache_get_or_insert_default(&connector.sender_cache, key);
        }
        assert!(
            connector.cache_len() <= H3_CACHE_MAX_ENTRIES,
            "cache must stay bounded, got {}",
            connector.cache_len()
        );
        // The most recently inserted origin survives its own insertion.
        let current = format!("host-{}.example:443", H3_CACHE_MAX_ENTRIES + 9);
        assert!(connector.contains_origin(&current));
    }

    #[tokio::test]
    async fn evictions_increment_transport_metrics() {
        let metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
        let connector =
            H3Connector::with_metrics(None, &PoolConfig::default(), Some(metrics.clone()))
                .expect("connector builds");
        for i in 0..(H3_CACHE_MAX_ENTRIES + 5) {
            let key = format!("host-{i}.example:443");
            connector.ensure_cache_bound(&key);
            h3_cache_get_or_insert_default(&connector.sender_cache, key);
        }
        let evictions = metrics
            .h3_cache_evictions
            .load(std::sync::atomic::Ordering::Relaxed);
        assert!(
            evictions >= 5,
            "bounded evictions must be counted, got {evictions}"
        );
    }

    #[test]
    fn bidi_follows_new_in_flight_name() {
        let pool = PoolConfig {
            max_in_flight_requests_per_origin: Some(9),
            ..PoolConfig::default()
        };
        assert_eq!(derive_max_bidi_streams(&pool), 9);
    }

    #[tokio::test]
    async fn evict_if_current_scopes_to_failed_generation() {
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector builds");
        let key = "example.com:443".to_owned();
        let first: CachedH3SenderCell = Arc::new(tokio::sync::OnceCell::new());
        h3_cache_insert(&connector.sender_cache, key.clone(), first.clone());
        // A stale generation must not drop a fresh replacement.
        let second: CachedH3SenderCell = Arc::new(tokio::sync::OnceCell::new());
        h3_cache_insert(&connector.sender_cache, key.clone(), second.clone());
        connector.evict_if_current(&key, &first);
        assert!(
            connector.contains_origin(&key),
            "eviction of a stale cell must not remove the current generation"
        );
        connector.evict_if_current(&key, &second);
        assert!(
            !connector.contains_origin(&key),
            "eviction of the current cell must remove the stale origin"
        );
    }

    #[test]
    fn remaining_budget_saturates_at_zero() {
        let past = std::time::Instant::now()
            .checked_sub(Duration::from_secs(1))
            .expect("recent instant");
        assert_eq!(
            remaining_connect_budget(Some(past)),
            Some(Duration::ZERO),
            "an expired deadline must yield zero, not panic"
        );
        assert!(remaining_connect_budget(None).is_none());
    }

    /// Minimal local QUIC+H3 server for deterministic lifecycle tests.
    ///
    /// Binds 127.0.0.1:0 with a self-signed cert, serves `body` on every
    /// request, and returns the bound address plus a shutdown sender. No
    /// public internet is used. Only compiled for tests with the `http3`
    /// feature (this module is already `http3`-gated).
    #[cfg(test)]
    struct LocalH3Server {
        addr: SocketAddr,
        shutdown: tokio::sync::watch::Sender<bool>,
    }

    #[cfg(test)]
    impl LocalH3Server {
        #[allow(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            reason = "kept async to match the integration-test fixture shape; the awaits live in the spawned task"
        )]
        async fn start(body: Vec<u8>) -> Self {
            use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
            let cert_key =
                rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("rcgen cert");
            let cert_der = CertificateDer::from(cert_key.cert.der().to_vec());
            let key_der =
                PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der()));
            let mut server_tls = rustls::ServerConfig::builder_with_provider(Arc::new(
                rustls::crypto::ring::default_provider(),
            ))
            .with_protocol_versions(&[&rustls::version::TLS13])
            .expect("TLS13")
            .with_no_client_auth()
            .with_single_cert(vec![cert_der], key_der)
            .expect("cert");
            server_tls.alpn_protocols = vec![b"h3".to_vec()];
            let quic_crypto = quinn::crypto::rustls::QuicServerConfig::try_from(server_tls)
                .expect("server crypto");
            let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_crypto));
            let mut transport = quinn::TransportConfig::default();
            transport.max_concurrent_bidi_streams(100u32.into());
            transport.max_concurrent_uni_streams(100u32.into());
            server_config.transport_config(Arc::new(transport));
            let endpoint = quinn::Endpoint::server(server_config, "127.0.0.1:0".parse().unwrap())
                .expect("bind server");
            let addr = endpoint.local_addr().expect("addr");
            let body = bytes::Bytes::from(body);
            let (tx, mut rx) = tokio::sync::watch::channel(false);
            tokio::spawn(async move {
                loop {
                    tokio::select! {
                        incoming = endpoint.accept() => {
                            let Some(incoming) = incoming else { break };
                            let body = body.clone();
                            tokio::spawn(async move {
                                let Ok(conn) = incoming.await else { return };
                                let h3_conn = h3_quinn::Connection::new(conn);
                                let Ok(mut server) =
                                    h3::server::Connection::<_, bytes::Bytes>::new(h3_conn).await
                                else {
                                    return;
                                };
                                loop {
                                    let Ok(Some(resolver)) = server.accept().await else { break };
                                    let body = body.clone();
                                    let Ok((_req, mut stream)) =
                                        resolver.resolve_request().await
                                    else {
                                        continue;
                                    };
                                    while stream.recv_data().await.ok().flatten().is_some() {}
                                    let resp = http::Response::builder()
                                        .status(200)
                                        .body(())
                                        .unwrap();
                                    if stream.send_response(resp).await.is_err() {
                                        break;
                                    }
                                    let _ = stream.send_data(body).await;
                                    let _ = stream.finish().await;
                                }
                            });
                        }
                        _ = rx.changed() => break,
                    }
                }
            });
            Self { addr, shutdown: tx }
        }
    }

    #[cfg(test)]
    impl Drop for LocalH3Server {
        fn drop(&mut self) {
            let _ = self.shutdown.send(true);
        }
    }

    /// A UDP blackhole: bound but never answered, so QUIC handshakes stall
    /// until the connect budget fires instead of failing fast with ICMP
    /// unreachable. Deterministic without public internet.
    #[cfg(test)]
    struct Blackhole {
        _socket: std::net::UdpSocket,
        addr: SocketAddr,
    }

    #[cfg(test)]
    impl Blackhole {
        fn bind() -> Self {
            let socket =
                std::net::UdpSocket::bind("127.0.0.1:0").expect("bind blackhole UDP socket");
            socket.set_nonblocking(true).expect("blackhole nonblocking");
            let addr = socket.local_addr().expect("blackhole addr");
            Self {
                _socket: socket,
                addr,
            }
        }
    }

    #[tokio::test]
    async fn failed_init_does_not_poison_origin() {
        // Connect to a closed localhost UDP port: no server answers, so with
        // a tight connect budget the attempt fails. The `OnceCell` must stay
        // uninitialized so a later attempt retries rather than replaying a
        // cached error.
        let blackhole = Blackhole::bind();
        // Use a neighboring closed port for the failure: unbind immediately
        // so nothing answers. (The blackhole itself is used by timeout tests
        // below; here we want a fast failure, so use a port we just freed.)
        let closed_port = {
            let s = std::net::UdpSocket::bind("127.0.0.1:0").expect("probe bind");
            s.local_addr().expect("probe addr").port()
        };
        let _ = &blackhole;
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector builds");
        let started = std::time::Instant::now();
        let deadline = Some(started + Duration::from_millis(300));
        let bad = vec![SocketAddr::from(([127, 0, 0, 1], closed_port))];
        let endpoint = connector
            .endpoint
            .as_ref()
            .expect("unit tests use a direct connector");
        let first = connector
            .connect_with_fallback(endpoint, &bad, "localhost", deadline, started)
            .await;
        assert!(first.is_err(), "expected handshake failure, got {first:?}");
        // No cache entry is created by `connect_with_fallback` itself; the
        // poison-freedom that matters is at the `OnceCell` layer, pinned by
        // `oncecell_failure_leaves_cell_empty` below.
    }

    #[tokio::test]
    async fn oncecell_failure_leaves_cell_empty() {
        // Pins the `Vacant -> Connecting -> Reconnectable` property that the
        // lifecycle depends on: `get_or_try_init` caches only success.
        let cell = tokio::sync::OnceCell::<u32>::new();
        let first: std::result::Result<&u32, &'static str> =
            cell.get_or_try_init(|| async { Err("boom") }).await;
        assert!(first.is_err());
        assert!(cell.get().is_none(), "failed init must not poison the cell");
        let second: std::result::Result<&u32, &'static str> =
            cell.get_or_try_init(|| async { Ok(7u32) }).await;
        assert_eq!(*second.expect("retry succeeds"), 7);
    }

    #[tokio::test]
    async fn fallback_skips_unreachable_address() {
        let server = LocalH3Server::start(b"fallback-ok".to_vec()).await;
        let closed_port = {
            let s = std::net::UdpSocket::bind("127.0.0.1:0").expect("probe bind");
            s.local_addr().expect("probe addr").port()
        };
        let tls = crate::tls::TlsConfig::builder()
            .danger_accept_invalid_certs(true)
            .build();
        let connector =
            H3Connector::new(Some(tls), &PoolConfig::default()).expect("connector builds");
        let started = std::time::Instant::now();
        // The closed port stalls (QUIC has no fast refuse); the fair-share
        // budget gives it half and reserves half for the reachable server.
        let deadline = Some(started + Duration::from_secs(8));
        let addrs = vec![SocketAddr::from(([127, 0, 0, 1], closed_port)), server.addr];
        let conn = tokio::time::timeout(
            Duration::from_secs(20),
            connector.connect_with_fallback(
                connector
                    .endpoint
                    .as_ref()
                    .expect("unit tests use a direct connector"),
                &addrs,
                "localhost",
                deadline,
                started,
            ),
        )
        .await
        .expect("fallback test must not hang")
        .expect("fallback to reachable address succeeds");
        assert_eq!(conn.remote_address(), server.addr);
    }

    #[tokio::test]
    async fn connect_budget_fires_connect_phase_timeout() {
        let blackhole = Blackhole::bind();
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector builds");
        let started = std::time::Instant::now();
        let budget = Duration::from_millis(200);
        let deadline = Some(started + budget);
        let err = connector
            .connect_with_fallback(
                connector
                    .endpoint
                    .as_ref()
                    .expect("unit tests use a direct connector"),
                std::slice::from_ref(&blackhole.addr),
                "localhost",
                deadline,
                started,
            )
            .await
            .expect_err("blackhole handshake must not succeed");
        match err {
            Error::Timeout {
                phase: TimeoutPhase::Connect,
                ..
            } => {}
            other => panic!("expected connect-phase timeout, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn fallback_cancellation_aborts_promptly() {
        let blackhole = Blackhole::bind();
        let connector = H3Connector::new(None, &PoolConfig::default()).expect("connector builds");
        let started = std::time::Instant::now();
        let deadline = Some(started + Duration::from_secs(30));
        // Abort well before the 30s budget: dropping the future must stop the
        // remaining attempts instead of stalling to the deadline.
        let pending = connector.connect_with_fallback(
            connector
                .endpoint
                .as_ref()
                .expect("unit tests use a direct connector"),
            std::slice::from_ref(&blackhole.addr),
            "localhost",
            deadline,
            started,
        );
        let aborted = tokio::time::timeout(Duration::from_millis(200), pending).await;
        assert!(
            aborted.is_err(),
            "cancellation must abort the pending connect promptly"
        );
    }

    #[tokio::test]
    async fn write_timeout_propagates_without_masking() {
        // A stalled producer wrapped with the pipeline's write timeout must
        // surface as `Timeout{Write}` through the H3 send path, not as a
        // generic H3 protocol error.
        let server = LocalH3Server::start(b"ok".to_vec()).await;
        let tls = crate::tls::TlsConfig::builder()
            .danger_accept_invalid_certs(true)
            .build();
        let connector =
            H3Connector::new(Some(tls), &PoolConfig::default()).expect("connector builds");
        let stalled = futures_util::stream::pending::<std::result::Result<bytes::Bytes, Error>>();
        let wrapped =
            crate::stream::write_timeout_stream(Box::pin(stalled), Duration::from_millis(100));
        let body = RequestBody::Stream {
            stream: wrapped,
            length: None,
        };
        let uri: http::Uri = format!("https://127.0.0.1:{}/", server.addr.port())
            .parse()
            .expect("uri");
        let http_req = http::Request::builder()
            .method(http::Method::POST)
            .uri(uri)
            .version(http::Version::HTTP_3)
            .body(body)
            .expect("request");
        let url =
            url::Url::parse(&format!("https://127.0.0.1:{}/", server.addr.port())).expect("url");
        // Borrow the wrapped stream progression: the first `next()` on the
        // body yields the write timeout; `send_request` must propagate it.
        let err = connector
            .send_request(http_req, url, Some(Duration::from_secs(10)))
            .await
            .expect_err("stalled body must fail");
        match err {
            Error::Timeout {
                phase: TimeoutPhase::Write,
                ..
            } => {}
            other => panic!("expected write-phase timeout, got {other:?}"),
        }
        // A write-phase failure is request scoped: the origin entry stays so
        // later requests are unaffected (no poison, no spurious eviction).
        let key = format!("127.0.0.1:{}", server.addr.port());
        assert!(
            connector.contains_origin(&key),
            "write timeout must not evict the shared connection"
        );
        let _ = server;
    }
}