aioduct 0.2.0

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
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
use super::*;
use crate::body::RequestBodySend;
use crate::runtime::TokioRuntime;
use crate::runtime::tokio_rt::TokioIo;

/// Helper: perform an HTTP/1.1 handshake over a duplex stream and return
/// the resulting `PooledConnection`.
async fn make_h1_conn() -> PooledConnection<RequestBodySend> {
    let (client_io, mut server_io) = tokio::io::duplex(1024);

    // Spawn a task that reads from the server side so the connection stays
    // alive and the sender reports `is_ready() == true`.
    tokio::spawn(async move {
        use tokio::io::AsyncReadExt;
        let mut buf = [0u8; 1024];
        loop {
            match server_io.read(&mut buf).await {
                Ok(0) | Err(_) => break,
                _ => {}
            }
        }
    });

    let io = TokioIo::new(client_io);
    let (sender, conn) = hyper::client::conn::http1::handshake(io)
        .await
        .expect("h1 handshake should succeed on duplex");

    // Drive the connection in the background.
    tokio::spawn(async move {
        let _ = conn.await;
    });

    PooledConnection::new_h1(sender)
}

fn key(host: &str) -> PoolKey {
    PoolKey::new(
        Scheme::HTTP,
        host.parse::<Authority>().expect("valid authority"),
    )
}

#[test]
fn checkout_returns_none_on_empty_pool() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    assert!(pool.checkout(&key("example.com:80")).is_none());
}

#[tokio::test]
async fn checkin_then_checkout_returns_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    let out = pool.checkout(&k);
    assert!(
        out.is_some(),
        "checkout should return the checked-in connection"
    );
}

#[tokio::test]
async fn checkout_with_different_key_returns_none() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));

    let conn = make_h1_conn().await;
    pool.checkin(key("a.example.com:80"), conn);

    tokio::task::yield_now().await;

    assert!(
        pool.checkout(&key("b.example.com:80")).is_none(),
        "checkout with a different key should return None"
    );
}

#[tokio::test]
async fn pool_respects_max_idle_per_host() {
    let max_idle = 2;
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(max_idle)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    for _ in 0..3 {
        let conn = make_h1_conn().await;
        pool.checkin(k.clone(), conn);
    }

    tokio::task::yield_now().await;

    assert!(pool.checkout(&k).is_some(), "1st checkout should succeed");
    assert!(pool.checkout(&k).is_some(), "2nd checkout should succeed");
    assert!(
        pool.checkout(&k).is_none(),
        "3rd checkout should return None (capacity was 2)"
    );
}

#[tokio::test]
async fn checkin_checkout_is_lifo() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let conn1 = make_h1_conn().await;
    let addr1 = std::net::SocketAddr::from(([1, 1, 1, 1], 80));
    let mut conn1 = conn1;
    conn1.remote_addr = Some(addr1);
    pool.checkin(k.clone(), conn1);

    let conn2 = make_h1_conn().await;
    let addr2 = std::net::SocketAddr::from(([2, 2, 2, 2], 80));
    let mut conn2 = conn2;
    conn2.remote_addr = Some(addr2);
    pool.checkin(k.clone(), conn2);

    tokio::task::yield_now().await;

    let out = pool.checkout(&k).expect("should get a connection");
    assert_eq!(
        out.remote_addr,
        Some(addr2),
        "LIFO: most recent connection first"
    );
}

#[tokio::test]
async fn checkout_expired_connection_returns_none() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_millis(50));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::time::sleep(Duration::from_millis(100)).await;

    assert!(
        pool.checkout(&k).is_none(),
        "expired connection should be discarded"
    );
}

#[tokio::test]
async fn checkout_connection_past_max_lifetime_returns_none() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_lifetime(Duration::from_millis(50));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::time::sleep(Duration::from_millis(100)).await;

    assert!(
        pool.checkout(&k).is_none(),
        "connection older than max lifetime should be discarded"
    );
}

#[tokio::test]
async fn checkin_connection_past_max_lifetime_drops_it() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_lifetime(Duration::ZERO);
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    assert!(
        pool.checkout(&k).is_none(),
        "expired connection should not be inserted into the pool"
    );
}

#[tokio::test]
async fn reaper_removes_expired_connections() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_millis(50));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::time::sleep(Duration::from_millis(150)).await;

    assert!(
        pool.checkout(&k).is_none(),
        "reaper should have removed the expired connection"
    );
}

#[tokio::test]
async fn reaper_removes_connections_past_max_lifetime() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_lifetime(Duration::from_millis(50));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::time::sleep(Duration::from_millis(150)).await;

    assert!(
        pool.checkout(&k).is_none(),
        "reaper should remove connections older than max lifetime"
    );
}

// --- Connection coalescing tests ---

use std::net::IpAddr;

/// Helper: perform an HTTP/2 handshake over a duplex stream.
async fn make_h2_conn() -> PooledConnection<RequestBodySend> {
    let (client_io, server_io) = tokio::io::duplex(65536);

    // Spawn server-side h2 connection handler
    tokio::spawn(async move {
        use hyper::server::conn::http2::Builder;
        use hyper::service::service_fn;
        let io = TokioIo::new(server_io);
        let _ = Builder::new(crate::runtime::executor::poll_executor::<TokioRuntime>())
            .serve_connection(
                io,
                service_fn(|_req| async {
                    Ok::<_, std::convert::Infallible>(hyper::Response::new(
                        http_body_util::Empty::<bytes::Bytes>::new(),
                    ))
                }),
            )
            .await;
    });

    let io = TokioIo::new(client_io);
    let (sender, conn) = hyper::client::conn::http2::handshake(
        crate::runtime::executor::poll_executor::<TokioRuntime>(),
        io,
    )
    .await
    .expect("h2 handshake should succeed on duplex");

    tokio::spawn(async move {
        let _ = conn.await;
    });

    PooledConnection::new_h2(sender)
}

fn key_https(host: &str) -> PoolKey {
    PoolKey::new(
        Scheme::HTTPS,
        host.parse::<Authority>().expect("valid authority"),
    )
}

#[tokio::test]
async fn checkout_coalesced_finds_by_san() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "cdn.example.com".into(),
        "api.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(result.is_some(), "should find coalesced connection via SAN");
}

#[tokio::test]
async fn checkout_coalesced_rejects_h1() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h1_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(result.is_none(), "h1 connections should not be coalesced");
}

#[tokio::test]
async fn checkout_coalesced_rejects_different_ip() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let different_ip: IpAddr = [10, 0, 0, 2].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(different_ip));
    assert!(result.is_none(), "different IP should prevent coalescing");
}

#[tokio::test]
async fn checkout_coalesced_skips_expired() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_millis(50));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::time::sleep(Duration::from_millis(100)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(
        result.is_none(),
        "expired connection should not be returned"
    );
}

#[test]
fn checkout_coalesced_empty_pool_returns_none() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(result.is_none(), "empty pool should return None");
}

#[tokio::test]
async fn coalesced_checkout_skips_past_max_lifetime() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_lifetime(Duration::from_millis(1));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::time::sleep(Duration::from_millis(50)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(
        result.is_none(),
        "connection past max lifetime should not be returned"
    );
}

#[test]
fn mark_connecting_h2_returns_false_first_time() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");
    assert!(!pool.mark_connecting_h2(&k));
}

#[test]
fn mark_connecting_h2_returns_true_when_already_present() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");
    assert!(!pool.mark_connecting_h2(&k));
    assert!(pool.mark_connecting_h2(&k));
}

#[test]
fn unmark_connecting_h2_allows_re_mark() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");
    assert!(!pool.mark_connecting_h2(&k));
    pool.unmark_connecting_h2(&k);
    assert!(!pool.mark_connecting_h2(&k));
}

#[test]
fn pool_key_new_vs_with_hint_default() {
    let k1 = PoolKey::new(Scheme::HTTP, "example.com:80".parse().unwrap());
    let k2 = PoolKey::with_hint(
        Scheme::HTTP,
        "example.com:80".parse().unwrap(),
        ProtocolHint::Auto,
    );
    assert_eq!(k1, k2);
}

#[test]
fn pool_key_different_hints_not_equal() {
    let k1 = PoolKey::with_hint(
        Scheme::HTTP,
        "example.com:80".parse().unwrap(),
        ProtocolHint::Auto,
    );
    let k2 = PoolKey::with_hint(
        Scheme::HTTP,
        "example.com:80".parse().unwrap(),
        ProtocolHint::H2c,
    );
    assert_ne!(k1, k2);
}

#[test]
fn protocol_hint_debug() {
    assert_eq!(format!("{:?}", ProtocolHint::Auto), "Auto");
    assert_eq!(format!("{:?}", ProtocolHint::H2c), "H2c");
    assert_eq!(format!("{:?}", ProtocolHint::AdaptiveH2c), "AdaptiveH2c");
}

#[tokio::test]
async fn checkout_h2_clone_for_multiplex() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("example.com:443");

    let conn = make_h2_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    let out1 = pool.checkout(&k);
    assert!(out1.is_some(), "first checkout should succeed");

    let out2 = pool.checkout(&k);
    assert!(
        out2.is_some(),
        "second checkout should succeed (H2 multiplex clone)"
    );
}

#[tokio::test]
async fn checkout_h2_respects_max_active_streams_per_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_streams_per_connection(std::num::NonZeroUsize::new(1).unwrap());
    let k = key_https("example.com:443");

    let conn = make_h2_conn().await;
    pool.checkin(k.clone(), conn);

    let out1 = pool.checkout(&k).expect("first active stream");
    assert!(
        pool.checkout(&k).is_none(),
        "second checkout should hit this connection's active stream limit"
    );

    drop(out1);
    assert!(
        pool.checkout(&k).is_some(),
        "dropping the active clone should release stream capacity"
    );
}

#[tokio::test]
async fn checkout_h2_active_stream_limit_is_per_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_streams_per_connection(std::num::NonZeroUsize::new(1).unwrap());
    let k = key_https("example.com:443");

    pool.checkin(k.clone(), make_h2_conn().await);
    pool.checkin(k.clone(), make_h2_conn().await);

    let _out1 = pool.checkout(&k).expect("first connection stream");
    let _out2 = pool.checkout(&k).expect("second connection stream");
}

#[tokio::test]
async fn max_active_streams_per_connection_does_not_change_h1_checkout() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_streams_per_connection(std::num::NonZeroUsize::new(1).unwrap());
    let k = key("example.com:80");

    pool.checkin(k.clone(), make_h1_conn().await);
    pool.checkin(k.clone(), make_h1_conn().await);

    tokio::task::yield_now().await;

    assert!(pool.checkout(&k).is_some(), "first h1 checkout");
    assert!(pool.checkout(&k).is_some(), "second h1 checkout");
}

#[tokio::test]
async fn checkout_coalesced_respects_max_active_streams_per_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_streams_per_connection(std::num::NonZeroUsize::new(1).unwrap());
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    let ip: IpAddr = [10, 0, 0, 1].into();
    let out1 = pool
        .checkout_coalesced("cdn.example.com", Some(ip))
        .expect("first coalesced stream");
    assert!(
        pool.checkout_coalesced("cdn.example.com", Some(ip))
            .is_none(),
        "second coalesced checkout should hit this connection's active stream limit"
    );

    drop(out1);
    assert!(
        pool.checkout_coalesced("cdn.example.com", Some(ip))
            .is_some(),
        "dropping the active clone should release coalesced stream capacity"
    );
}

#[tokio::test]
async fn checkout_coalesced_without_ip_check() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let result = pool.checkout_coalesced("cdn.example.com", None);
    assert!(
        result.is_some(),
        "should find coalesced connection when resolved_ip is None"
    );
}

#[tokio::test]
async fn checkout_coalesced_san_not_found() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("unknown.example.com", Some(ip));
    assert!(result.is_none(), "SAN not in cert should return None");
}

// --- Reaper task body tests ---

#[tokio::test]
async fn reaper_cleans_san_index_for_expired_connections() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_millis(50));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    // Wait for idle timeout + reaper cycle
    tokio::time::sleep(Duration::from_millis(150)).await;

    // SAN index should be cleaned up, so coalesced lookup should fail
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(
        result.is_none(),
        "reaper should have cleaned expired connections and SAN index"
    );
}

#[tokio::test]
async fn reaper_retains_live_connections() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(4)
        .with_idle_timeout(Duration::from_secs(10));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    // Sleep less than the idle timeout but enough for reaper to fire
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Connection should still be available
    let result = pool.checkout(&k);
    assert!(
        result.is_some(),
        "reaper should retain connections that haven't expired"
    );
}

// --- PooledConnection fields/methods tests ---

#[tokio::test]
async fn pooled_connection_new_h1_defaults() {
    let conn = make_h1_conn().await;
    assert!(conn.remote_addr.is_none());
    assert!(conn.tls_info.is_none());
    assert!(conn.tls_handshake_duration.is_none());
    assert!(conn.sans.is_empty());
    assert_eq!(conn.requests_served(), 0);
    assert_eq!(conn.bytes_sent(), 0);
    assert_eq!(conn.bytes_received(), 0);
    assert!(!conn.is_multiplex_clone);
    assert!(!conn.is_h2_or_h3());
    // Note: is_ready() for h1 depends on the background connection driver timing;
    // tested transitively via checkin_then_checkout_returns_connection.
}

#[tokio::test]
async fn pooled_connection_new_h2_defaults() {
    let conn = make_h2_conn().await;
    assert!(conn.remote_addr.is_none());
    assert!(conn.tls_info.is_none());
    assert!(conn.tls_handshake_duration.is_none());
    assert!(conn.sans.is_empty());
    assert_eq!(conn.requests_served(), 0);
    assert_eq!(conn.bytes_sent(), 0);
    assert_eq!(conn.bytes_received(), 0);
    assert!(!conn.is_multiplex_clone);
    assert!(conn.is_h2_or_h3());
    assert!(conn.is_ready());
}

#[tokio::test]
async fn clone_for_multiplex_returns_none_for_h1() {
    let conn = make_h1_conn().await;
    assert!(conn.clone_for_multiplex().is_none());
}

#[tokio::test]
async fn clone_for_multiplex_returns_some_for_h2() {
    let mut conn = make_h2_conn().await;
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    conn.record_request(1024);
    conn.record_bytes_received(4096);

    let cloned = conn.clone_for_multiplex();
    assert!(cloned.is_some());

    let cloned = cloned.unwrap();
    assert!(cloned.is_multiplex_clone);
    assert_eq!(
        cloned.remote_addr,
        Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)))
    );
    // Cloned handle shares transport-cumulative metrics
    assert_eq!(cloned.requests_served(), 1);
    assert_eq!(cloned.bytes_sent(), 1024);
    assert_eq!(cloned.bytes_received(), 4096);
    assert!(cloned.is_h2_or_h3());
}

#[tokio::test]
async fn multiplex_clone_releases_active_stream_count_on_drop() {
    let conn = make_h2_conn().await;
    assert_eq!(conn.active_multiplex_streams(), Some(0));

    let cloned = conn.clone_for_multiplex().expect("h2 should clone");
    assert_eq!(conn.active_multiplex_streams(), Some(1));

    drop(cloned);
    assert_eq!(conn.active_multiplex_streams(), Some(0));
}

// --- PoolKey Debug tests ---

#[test]
fn pool_key_debug_format() {
    let k = PoolKey::new(Scheme::HTTPS, "example.com:443".parse().unwrap());
    let debug = format!("{:?}", k);
    assert!(debug.contains("example.com:443"));
    assert!(debug.contains("Auto"));
}

#[test]
fn pool_key_with_hint_h2c_debug() {
    let k = PoolKey::with_hint(
        Scheme::HTTP,
        "example.com:80".parse().unwrap(),
        ProtocolHint::H2c,
    );
    let debug = format!("{:?}", k);
    assert!(debug.contains("H2c"));
}

#[test]
fn pool_key_with_hint_adaptive_debug() {
    let k = PoolKey::with_hint(
        Scheme::HTTP,
        "example.com:80".parse().unwrap(),
        ProtocolHint::AdaptiveH2c,
    );
    let debug = format!("{:?}", k);
    assert!(debug.contains("AdaptiveH2c"));
}

// --- ConnectionPool clone test ---

#[tokio::test]
async fn pool_clone_shares_state() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let pool2 = pool.clone();
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    // Checkout from clone should see the connection
    let out = pool2.checkout(&k);
    assert!(out.is_some(), "cloned pool should share internal state");
}

// --- Checkin eviction test ---

#[tokio::test]
async fn checkin_evicts_oldest_when_at_capacity() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let mut conn1 = make_h1_conn().await;
    conn1.remote_addr = Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)));
    pool.checkin(k.clone(), conn1);

    let mut conn2 = make_h1_conn().await;
    conn2.remote_addr = Some(std::net::SocketAddr::from(([2, 2, 2, 2], 80)));
    pool.checkin(k.clone(), conn2);

    tokio::task::yield_now().await;

    // Only the second connection should remain (capacity is 1)
    let out = pool.checkout(&k).expect("should have a connection");
    assert_eq!(
        out.remote_addr,
        Some(std::net::SocketAddr::from(([2, 2, 2, 2], 80))),
        "should get the newer connection after eviction"
    );
    assert!(
        pool.checkout(&k).is_none(),
        "only one connection should remain"
    );
}

// --- SAN index population on checkin ---

#[tokio::test]
async fn checkin_populates_san_index() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "alt.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    // Should find via SAN index
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("alt.example.com", Some(ip));
    assert!(result.is_some(), "SAN index should be populated on checkin");
}

// --- checkout_coalesced with IP address in SAN ---

#[tokio::test]
async fn checkout_coalesced_multiple_sans_finds_any() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "first.example.com".into(),
        "second.example.com".into(),
        "third.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // Should find for any SAN
    assert!(
        pool.checkout_coalesced("first.example.com", Some(ip))
            .is_some()
    );
    assert!(
        pool.checkout_coalesced("second.example.com", Some(ip))
            .is_some()
    );
    assert!(
        pool.checkout_coalesced("third.example.com", Some(ip))
            .is_some()
    );
}

// --- mark/unmark connecting_h2 with different keys ---

#[test]
fn mark_connecting_h2_independent_keys() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k1 = key("a.example.com:80");
    let k2 = key("b.example.com:80");

    assert!(!pool.mark_connecting_h2(&k1));
    assert!(!pool.mark_connecting_h2(&k2));
    // k1 is already marked
    assert!(pool.mark_connecting_h2(&k1));
    // k2 is also already marked
    assert!(pool.mark_connecting_h2(&k2));

    pool.unmark_connecting_h2(&k1);
    assert!(!pool.mark_connecting_h2(&k1));
    // k2 is still marked
    assert!(pool.mark_connecting_h2(&k2));
}

// --- checkout_coalesced cleans stale san_index ---

#[tokio::test]
async fn checkout_coalesced_cleans_stale_san_index() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_millis(50));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "stale.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    // Wait for expiration
    tokio::time::sleep(Duration::from_millis(100)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // This triggers cleanup of stale index entries
    let result = pool.checkout_coalesced("stale.example.com", Some(ip));
    assert!(
        result.is_none(),
        "expired connection should not be returned"
    );

    // After the cleanup, a subsequent lookup should also return None quickly
    let result2 = pool.checkout_coalesced("stale.example.com", Some(ip));
    assert!(result2.is_none());
}

// --- checkout_coalesced with not-ready connection (covers lines 260-270, 278, 284-289) ---

/// Creates an H2 connection and a channel to shut down the server side.
async fn make_h2_conn_with_shutdown() -> (
    PooledConnection<RequestBodySend>,
    tokio::sync::oneshot::Sender<()>,
) {
    let (client_io, server_io) = tokio::io::duplex(65536);
    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

    // Spawn server-side h2 connection handler that stops on shutdown signal
    tokio::spawn(async move {
        use hyper::server::conn::http2::Builder;
        use hyper::service::service_fn;
        let io = TokioIo::new(server_io);
        let conn = Builder::new(crate::runtime::executor::poll_executor::<TokioRuntime>())
            .serve_connection(
                io,
                service_fn(|_req| async {
                    Ok::<_, std::convert::Infallible>(hyper::Response::new(
                        http_body_util::Empty::<bytes::Bytes>::new(),
                    ))
                }),
            );
        tokio::select! {
            _ = conn => {},
            _ = shutdown_rx => {},
        }
    });

    let io = TokioIo::new(client_io);
    let (sender, conn) = hyper::client::conn::http2::handshake(
        crate::runtime::executor::poll_executor::<TokioRuntime>(),
        io,
    )
    .await
    .expect("h2 handshake should succeed on duplex");

    tokio::spawn(async move {
        let _ = conn.await;
    });

    (PooledConnection::new_h2(sender), shutdown_tx)
}

#[tokio::test]
async fn checkout_coalesced_removes_not_ready_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let (mut conn, shutdown_tx) = make_h2_conn_with_shutdown().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    // Shut down the server side to make the connection not-ready
    let _ = shutdown_tx.send(());
    // Give the connection driver time to detect the close
    tokio::time::sleep(Duration::from_millis(50)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // Connection should be found by SAN but be not-ready, triggering the remove path
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    // The not-ready connection gets removed from the pool, None is returned
    assert!(
        result.is_none(),
        "not-ready connection should be removed and return None"
    );
}

#[tokio::test]
async fn checkout_coalesced_cleans_san_index_when_no_connections_remain() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let (mut conn, shutdown_tx) = make_h2_conn_with_shutdown().await;
    conn.sans = std::sync::Arc::from(vec!["origin.example.com".into(), "cdn.example.com".into()]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    // Shut down the server side
    let _ = shutdown_tx.send(());
    tokio::time::sleep(Duration::from_millis(50)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // First checkout_coalesced: removes not-ready connection, cleans up
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(result.is_none());

    // Second lookup should also be None (SAN index was cleaned)
    let result2 = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(result2.is_none());

    // The pool key queue should be empty now
    assert!(
        pool.checkout(&k).is_none(),
        "pool should have no connections left"
    );
}

#[tokio::test]
async fn checkout_coalesced_san_index_stale_entry_continue_on_missing_queue() {
    // Test the path where san_index has a key but idle map doesn't (line 231: continue).
    // This happens when two different keys map to the same SAN: the first key's
    // idle queue might be empty/removed, so checkout_coalesced continues to the next key.
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k1 = key_https("origin1.example.com:443");
    let k2 = key_https("origin2.example.com:443");

    // Add a connection under k1 that shares SANs with k2, then make it not-ready
    let (mut conn1, shutdown1) = make_h2_conn_with_shutdown().await;
    conn1.sans = std::sync::Arc::from(vec!["origin1.example.com".into(), "cdn.example.com".into()]);
    conn1.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k1.clone(), conn1);

    // Add a healthy connection under k2 that also has the same SAN
    let mut conn2 = make_h2_conn().await;
    conn2.sans = std::sync::Arc::from(vec!["origin2.example.com".into(), "cdn.example.com".into()]);
    conn2.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k2.clone(), conn2);

    // Shut down k1's connection to make it not-ready
    let _ = shutdown1.send(());
    tokio::time::sleep(Duration::from_millis(50)).await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // checkout_coalesced should skip k1 (not-ready) and find k2
    let result = pool.checkout_coalesced("cdn.example.com", Some(ip));
    assert!(
        result.is_some(),
        "should find the second healthy connection even if first is not-ready"
    );
}

// --- pool with zero max_idle_per_host ---

#[tokio::test]
async fn pool_zero_max_idle_always_evicts() {
    // Edge case: max_idle_per_host = 0 means nothing stays pooled
    // (In practice the pool stores at least 1 because pop_front happens before push_back)
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    // Should be able to checkout the one connection
    assert!(pool.checkout(&k).is_some());
    assert!(pool.checkout(&k).is_none());
}

#[tokio::test]
async fn max_idle_per_host_zero_drops_on_checkin() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(0)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    assert!(
        pool.checkout(&k).is_none(),
        "connection should be dropped when max_idle_per_host is 0"
    );
}

// --- checkout_coalesced: SAN in index but connection SANs don't match target ---
// Covers line 247: `!entry.connection.sans.iter().any(|s| s == target_host)`

#[tokio::test]
async fn checkout_coalesced_san_index_has_entry_but_conn_sans_dont_match() {
    // This tests the scenario where the SAN index is populated via a shared SAN,
    // but the actual connection's SANs don't include the specific target_host
    // we're looking for from a different lookup path.
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    // Connection has SANs: origin.example.com, shared.example.com
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "shared.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    // Now manually insert a stale entry in the SAN index for a host
    // that isn't actually in the connection's SANs.
    // We simulate this by looking up "shared.example.com" (which IS in SANs) -
    // that should succeed:
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("shared.example.com", Some(ip));
    assert!(result.is_some(), "shared SAN should match");

    // And looking up a host NOT in the SANs should fail:
    let result = pool.checkout_coalesced("other.example.com", Some(ip));
    assert!(result.is_none(), "host not in SANs should not match");
}

// --- checkout_coalesced with H2 connection that has empty queue after removal ---
// Covers lines 265-266 (found_key path)

#[tokio::test]
async fn checkout_coalesced_last_connection_in_queue_triggers_removal() {
    // When the last connection in a queue is checkout out (non-multiplex path),
    // the queue becomes empty and found_key is set for removal.
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    // Add a single H1 connection with SANs (won't multiplex)
    let mut conn = make_h1_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "coalesced.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // H1 connections are rejected by is_h2_or_h3 check (line 243),
    // so this returns None and pool remains intact
    let result = pool.checkout_coalesced("coalesced.example.com", Some(ip));
    assert!(result.is_none(), "H1 should be rejected by coalescing");

    // Regular checkout should still work
    let result = pool.checkout(&k);
    assert!(result.is_some(), "H1 connection should still be in pool");
}

// --- ensure_reaper_local test (covers lines 350-371) ---

#[tokio::test]
async fn ensure_reaper_local_removes_expired() {
    // Use TokioRuntime as RuntimeLocal (it implements RuntimeLocal via spawn_local)
    // Actually TokioRuntime implements RuntimePoll, not RuntimeLocal.
    // The local reaper is tested in tests_compio.rs. Let's just verify the
    // send-path reaper cleans the SAN index properly.
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(1)
        .with_idle_timeout(Duration::from_millis(50));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "reaper-test.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    // Wait for idle timeout + reaper cycle to fire
    tokio::time::sleep(Duration::from_millis(150)).await;

    // Both regular checkout and coalesced checkout should fail
    assert!(
        pool.checkout(&k).is_none(),
        "reaper should have removed expired connection"
    );
    let ip: IpAddr = [10, 0, 0, 1].into();
    assert!(
        pool.checkout_coalesced("reaper-test.example.com", Some(ip))
            .is_none(),
        "reaper should have cleaned SAN index"
    );
}

// --- checkin with SANs populates index for all SANs ---

#[tokio::test]
async fn checkin_populates_san_index_for_all_sans() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "san1.example.com".into(),
        "san2.example.com".into(),
        "san3.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k, conn);

    tokio::task::yield_now().await;

    let ip: IpAddr = [10, 0, 0, 1].into();
    // All SANs should be findable via coalescing
    assert!(
        pool.checkout_coalesced("san1.example.com", Some(ip))
            .is_some()
    );
    assert!(
        pool.checkout_coalesced("san2.example.com", Some(ip))
            .is_some()
    );
    assert!(
        pool.checkout_coalesced("san3.example.com", Some(ip))
            .is_some()
    );
}

// --- checkout with not-ready H1 connection falls through ---

#[tokio::test]
async fn checkout_skips_not_ready_h1_connection() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let (mut conn, shutdown_tx) = make_h2_conn_with_shutdown().await;
    // Make it appear as H1 for this test by setting remote_addr
    conn.remote_addr = Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)));

    // Actually use an H1 connection for this
    let (client_io, server_io) = tokio::io::duplex(8192);
    // Drop server immediately to make connection not-ready
    drop(server_io);

    let io = TokioIo::new(client_io);
    let (sender, conn_task) = hyper::client::conn::http1::handshake(io)
        .await
        .expect("h1 handshake");

    tokio::spawn(async move {
        let _ = conn_task.await;
    });

    let mut h1_conn = PooledConnection::new_h1(sender);
    h1_conn.remote_addr = Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)));
    pool.checkin(k.clone(), h1_conn);

    // Give the connection driver time to detect the closed server
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Checkout should skip the not-ready connection
    let result = pool.checkout(&k);
    assert!(
        result.is_none(),
        "not-ready H1 connection should be skipped"
    );

    // Clean up the unused shutdown_tx
    let _ = shutdown_tx.send(());
}

// --- checkout_coalesced: san_index key exists but idle map has no entry (line 230-231) ---

#[tokio::test]
async fn checkout_coalesced_san_index_key_but_idle_empty() {
    // Create a scenario where san_index maps a SAN to a key, but the idle map
    // no longer has that key (because we checked out the H1 connection via regular checkout).
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("origin.example.com:443");

    // Use H1 connection - regular checkout removes it completely from idle
    let mut conn = make_h1_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "origin.example.com".into(),
        "coalesce-target.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    // Regular checkout removes the H1 connection from the idle map entirely
    let out = pool.checkout(&k);
    assert!(out.is_some(), "regular checkout should succeed");

    // Now san_index still has "coalesce-target.example.com" -> k,
    // but idle map no longer has k. This hits the `None => continue` path (lines 230-231).
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("coalesce-target.example.com", Some(ip));
    assert!(
        result.is_none(),
        "should return None when idle map has no entry for the san_index key"
    );
}

// --- checkout_coalesced: san_index cleanup when idle map doesn't have key (lines 284-288) ---

#[tokio::test]
async fn checkout_coalesced_san_index_cleanup_removes_empty_set() {
    // Test that after checkout_coalesced finds no idle queue for a key,
    // it cleans up the san_index entry (lines 283-288).
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key_https("only-origin.example.com:443");

    // Use H1 connection so regular checkout fully removes from idle
    let mut conn = make_h1_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "only-origin.example.com".into(),
        "cleanup-target.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    tokio::task::yield_now().await;

    // Regular checkout removes from idle (H1, not multiplexed)
    let _ = pool.checkout(&k);

    // Now checkout_coalesced should find san_index entry but no idle entry,
    // triggering the cleanup that removes the key from san_index and then
    // removes the empty set.
    let ip: IpAddr = [10, 0, 0, 1].into();
    let result = pool.checkout_coalesced("cleanup-target.example.com", Some(ip));
    assert!(result.is_none());

    // Verify the SAN index was cleaned: a second call should also be None
    // (the san_index entry should have been removed entirely)
    let result2 = pool.checkout_coalesced("cleanup-target.example.com", Some(ip));
    assert!(
        result2.is_none(),
        "SAN index should have been fully cleaned"
    );
}

// --- spawn_reaper exercises the reaper loop body (lines 312-336) ---

#[tokio::test]
async fn reaper_loop_runs_multiple_cycles() {
    // Verify the reaper can run multiple cycles and correctly clean up connections
    // added at different times.
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(4)
        .with_idle_timeout(Duration::from_millis(30));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key("reaper-multi.example.com:80");

    // Add first connection
    let mut conn1 = make_h1_conn().await;
    conn1.remote_addr = Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)));
    pool.checkin(k.clone(), conn1);

    // Wait for first reaper cycle to expire it
    tokio::time::sleep(Duration::from_millis(80)).await;

    // First connection should be gone
    assert!(pool.checkout(&k).is_none(), "first conn should be reaped");

    // Add second connection
    let mut conn2 = make_h1_conn().await;
    conn2.remote_addr = Some(std::net::SocketAddr::from(([2, 2, 2, 2], 80)));
    pool.checkin(k.clone(), conn2);

    // Wait for second reaper cycle
    tokio::time::sleep(Duration::from_millis(80)).await;

    // Second connection should also be gone
    assert!(pool.checkout(&k).is_none(), "second conn should be reaped");
}

// --- reaper cleans san_index entries with keys no longer in idle (lines 330-334) ---

#[tokio::test]
async fn reaper_cleans_san_index_keys_not_in_idle() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .with_max_idle_per_host(4)
        .with_idle_timeout(Duration::from_millis(30));
    pool.ensure_reaper::<TokioRuntime>();
    let k = key_https("reaper-san.example.com:443");

    let mut conn = make_h2_conn().await;
    conn.sans = std::sync::Arc::from(vec![
        "reaper-san.example.com".into(),
        "reaper-alt.example.com".into(),
    ]);
    conn.remote_addr = Some(std::net::SocketAddr::from(([10, 0, 0, 1], 443)));
    pool.checkin(k.clone(), conn);

    // Wait for connection to expire and reaper to clean up
    tokio::time::sleep(Duration::from_millis(80)).await;

    // Both regular and coalesced lookups should fail
    assert!(pool.checkout(&k).is_none());
    let ip: IpAddr = [10, 0, 0, 1].into();
    assert!(
        pool.checkout_coalesced("reaper-alt.example.com", Some(ip))
            .is_none()
    );
}

// --- Multiple connections: checkout prefers the most-recently-added ready one ---

#[tokio::test]
async fn checkout_tries_multiple_candidates_lifo() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    // Add two connections
    let mut conn1 = make_h1_conn().await;
    conn1.remote_addr = Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)));
    pool.checkin(k.clone(), conn1);

    let mut conn2 = make_h1_conn().await;
    conn2.remote_addr = Some(std::net::SocketAddr::from(([2, 2, 2, 2], 80)));
    pool.checkin(k.clone(), conn2);

    tokio::task::yield_now().await;

    // LIFO: should get conn2 first (most recently added)
    let out1 = pool.checkout(&k).expect("first checkout");
    assert_eq!(
        out1.remote_addr,
        Some(std::net::SocketAddr::from(([2, 2, 2, 2], 80)))
    );

    // Then conn1
    let out2 = pool.checkout(&k).expect("second checkout");
    assert_eq!(
        out2.remote_addr,
        Some(std::net::SocketAddr::from(([1, 1, 1, 1], 80)))
    );

    // Then empty
    assert!(pool.checkout(&k).is_none());
}

#[tokio::test]
async fn evict_removes_all_connections_for_key() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    let conn1 = make_h1_conn().await;
    pool.checkin(k.clone(), conn1);
    let conn2 = make_h1_conn().await;
    pool.checkin(k.clone(), conn2);

    tokio::task::yield_now().await;

    pool.evict(&k);
    assert!(
        pool.checkout(&k).is_none(),
        "evict should remove all connections for the key"
    );
}

#[tokio::test]
async fn evict_does_not_affect_other_keys() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k1 = key("a.example.com:80");
    let k2 = key("b.example.com:80");

    let conn1 = make_h1_conn().await;
    pool.checkin(k1.clone(), conn1);
    let conn2 = make_h1_conn().await;
    pool.checkin(k2.clone(), conn2);

    tokio::task::yield_now().await;

    pool.evict(&k1);
    assert!(pool.checkout(&k1).is_none());
    assert!(
        pool.checkout(&k2).is_some(),
        "evict should not affect other keys"
    );
}

// --- max_active_per_host tests ---

#[tokio::test]
async fn max_active_per_host_blocks_when_at_cap() {
    let max_active = std::num::NonZeroUsize::new(1).unwrap();
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_per_host(Some(max_active));
    let k = key("example.com:80");

    assert!(
        pool.can_connect(&k),
        "can_connect should return true initially"
    );

    // Checkin a connection, then checkout — active count becomes 1
    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);
    tokio::task::yield_now().await;

    let _out = pool.checkout(&k).expect("first checkout should succeed");
    assert!(
        !pool.can_connect(&k),
        "can_connect should return false when at cap"
    );
}

#[tokio::test]
async fn checkin_frees_active_slot() {
    let max_active = std::num::NonZeroUsize::new(1).unwrap();
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_per_host(Some(max_active));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);
    tokio::task::yield_now().await;

    let out = pool.checkout(&k).expect("first checkout");
    assert!(!pool.can_connect(&k), "at cap after checkout");

    // Return the connection — active slot is freed
    pool.checkin(k.clone(), out);
    assert!(
        pool.can_connect(&k),
        "can_connect should return true after checkin frees the slot"
    );

    // Should be able to checkout again
    let out2 = pool.checkout(&k);
    assert!(out2.is_some(), "should checkout after checkin freed slot");
}

#[tokio::test]
async fn drop_frees_active_slot() {
    let max_active = std::num::NonZeroUsize::new(1).unwrap();
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_per_host(Some(max_active));
    let k = key("example.com:80");

    let conn = make_h1_conn().await;
    pool.checkin(k.clone(), conn);
    tokio::task::yield_now().await;

    let out = pool.checkout(&k).expect("first checkout");
    assert!(!pool.can_connect(&k), "at cap after checkout");

    // Drop without checkin — the Drop impl decrements active count
    drop(out);
    assert!(
        pool.can_connect(&k),
        "can_connect should return true after drop frees the slot"
    );
}

#[test]
fn max_active_per_host_none_means_unlimited() {
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30));
    let k = key("example.com:80");

    // Default is unlimited — can always connect
    assert!(pool.can_connect(&k));
}

#[test]
fn max_active_per_host_zero_disables_cap() {
    // Passing 0 to the builder setter results in None (via NonZeroUsize::new(0))
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_per_host(None);
    let k = key("example.com:80");
    assert!(pool.can_connect(&k));
}

#[tokio::test]
async fn per_host_isolation() {
    let max_active = std::num::NonZeroUsize::new(1).unwrap();
    let pool = ConnectionPool::<RequestBodySend>::new()
        .without_reaper()
        .with_max_idle_per_host(8)
        .with_idle_timeout(Duration::from_secs(30))
        .with_max_active_per_host(Some(max_active));
    let k1 = key("a.example.com:80");
    let k2 = key("b.example.com:80");

    assert!(pool.can_connect(&k1));
    assert!(pool.can_connect(&k2));

    // Checkout for k1 puts it at cap
    let conn1 = make_h1_conn().await;
    pool.checkin(k1.clone(), conn1);
    tokio::task::yield_now().await;
    let _out1 = pool.checkout(&k1).expect("checkout k1");

    // k1 is at cap, k2 is not affected
    assert!(!pool.can_connect(&k1), "k1 should be at cap");
    assert!(
        pool.can_connect(&k2),
        "k2 should not be affected by k1's cap"
    );
}