self_update 1.3.1

Self updates for standalone executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
/*!
Collection of modules supporting various release distribution backends
*/

use crate::errors::{Error, Result};
use crate::http_client;

pub(crate) mod common;
pub mod custom;
#[cfg(feature = "gitea")]
pub mod gitea;
#[cfg(feature = "gitee")]
pub mod gitee;
#[cfg(feature = "github")]
pub mod github;
#[cfg(feature = "gitlab")]
pub mod gitlab;
#[cfg(feature = "manifest")]
pub mod manifest;
#[cfg(feature = "s3")]
pub mod s3;

/// Search for the first "rel" link-header uri in a full link header string.
/// Seems like reqwest/hyper threw away their link-header parser implementation...
///
/// ex:
/// `Link: <https://api.github.com/resource?page=2>; rel="next"`
/// `Link: <https://gitlab.com/api/v4/projects/13083/releases?id=13083&page=2&per_page=20>; rel="next"`
///
/// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
/// header values may contain multiple values separated by commas
/// `Link: <https://place.com>; rel="next", <https://wow.com>; rel="next"`
// Only the forge backends walk Link-header pagination; the attribute keeps builds without any of
// them (custom/s3-only) warning-free without cfg-gating shared code out of existence.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee"
    )),
    allow(dead_code)
)]
pub(crate) fn find_rel_next_link(link_str: &str) -> Option<&str> {
    for link in link_str.split(',') {
        let mut uri = None;
        let mut is_rel_next = false;
        for part in link.split(';') {
            let part = part.trim();
            if part.starts_with('<') && part.ends_with('>') {
                uri = Some(part.trim_start_matches('<').trim_end_matches('>'));
            } else if part.starts_with("rel=") {
                let part = part
                    .trim_start_matches("rel=")
                    .trim_end_matches('"')
                    .trim_start_matches('"');
                if part == "next" {
                    is_rel_next = true;
                }
            }

            if is_rel_next && uri.is_some() {
                return uri;
            }
        }
    }
    None
}

/// Maximum number of `Link: rel="next"` pages walked when listing releases — a safety bound
/// against pathological release histories.
// The pagination machinery below is used by the listing backends (github/gitlab/gitea/s3); the
// attributes keep a backend-less build (custom only) warning-free.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) const MAX_RELEASE_PAGES: usize = 100;

/// Maximum number of bytes buffered for a single listing-page body. A per-page COUNT bound
/// ([`MAX_RELEASE_PAGES`]) was already present; this per-page SIZE bound prevents a pathological
/// or misconfigured endpoint from forcing unbounded memory use. Real GitHub/GitLab/Gitea release
/// listing pages with 100 entries and many assets are well under 1 MiB; 4 MiB is a generous cap.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) const MAX_LISTING_BODY_BYTES: usize = 4 * 1024 * 1024; // 4 MiB

/// A sans-io description of a single page request: *what* to fetch (`url` + `headers`) and *how*
/// to parse the response body into items, the next page (if any), and an early-stop signal — with
/// no transport. The two drivers ([`run_paginated`] / [`run_paginated_async`]) perform the IO by
/// sending this via the shared `send`/`send_async` + `retry` machinery, then call `parse`.
///
/// `parse` is `+ Send` so [`run_paginated_async`]'s future stays `Send` (it is held across the
/// await in the async driver).
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) struct PageRequest<T> {
    pub url: String,
    pub headers: http_client::HeaderMap,
    /// Pure parser: `(body bytes, response headers) -> this page's items + next page + early-stop`.
    #[allow(clippy::type_complexity)]
    pub parse: Box<dyn FnOnce(&[u8], &http_client::HeaderMap) -> Result<Page<T>> + Send>,
}

/// The parsed result of one [`PageRequest`]: the page's `items`, the optional `next` page request,
/// and an early-`stop` flag. The driver appends `items`, then stops if `stop` is set, `next` is
/// `None`, or the [`MAX_RELEASE_PAGES`] bound is hit.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) struct Page<T> {
    pub items: Vec<T>,
    pub next: Option<PageRequest<T>>,
    pub stop: bool,
}

impl<T> Page<T> {
    /// A terminal single-page result: these `items`, no next page, no early stop.
    // Only the forge backends' single-release plans build terminal pages; s3 follows
    // continuation tokens via `next` instead.
    #[cfg_attr(
        not(any(
            feature = "github",
            feature = "gitlab",
            feature = "gitea",
            feature = "gitee"
        )),
        allow(dead_code)
    )]
    pub(crate) fn last(items: Vec<T>) -> Self {
        Self {
            items,
            next: None,
            stop: false,
        }
    }
}

/// Drive a sans-io [`PageRequest`] chain to completion over the sync transport.
///
/// Loops: send the request via [`send`] (reusing its retry/backoff machinery), read the body bytes
/// once, call `parse`, extend the accumulator, then stop if `page.stop`, `page.next` is `None`, or
/// the [`MAX_RELEASE_PAGES`] bound is reached (logging a warning if a further page was still
/// advertised at the bound).
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) fn run_paginated<T>(
    first: PageRequest<T>,
    config: &common::RequestConfig,
) -> Result<Vec<T>> {
    let mut out = Vec::new();
    let mut next = Some(first);
    let mut pages = 0usize;
    while let Some(request) = next {
        let PageRequest {
            url,
            headers,
            parse,
        } = request;
        let resp = send(&url, headers, config)?;
        let resp_headers = resp.headers().clone();
        let mut body = Vec::new();
        let reader = resp.body();
        // S5: cap the per-page body size so a malicious or misconfigured endpoint cannot force
        // unbounded memory use. Read one byte past the cap to distinguish "exactly at the cap"
        // (fine) from "over the cap" (error).
        let mut limited = {
            use std::io::Read as _;
            reader.take((MAX_LISTING_BODY_BYTES + 1) as u64)
        };
        std::io::Read::read_to_end(&mut limited, &mut body)?;
        if body.len() > MAX_LISTING_BODY_BYTES {
            return Err(Error::InvalidResponse {
                source: Box::new(crate::errors::MessageError(format!(
                    "listing page body exceeded the {MAX_LISTING_BODY_BYTES}-byte cap; \
                     real release listing pages are much smaller"
                ))),
            });
        }
        let page = parse(&body, &resp_headers)?;
        out.extend(page.items);
        pages += 1;
        if page.stop {
            break;
        }
        if pages >= MAX_RELEASE_PAGES {
            if page.next.is_some() {
                log::warn!(
                    "self_update: stopped paginating releases after {MAX_RELEASE_PAGES} pages; \
                     older releases may be omitted"
                );
            }
            break;
        }
        next = page.next;
    }
    Ok(out)
}

/// Async sibling of [`run_paginated`]: drive a sans-io [`PageRequest`] chain over the async
/// transport. Reuses [`send_async`]'s retry/backoff machinery; reads the body bytes via the async
/// response trait, then calls the same `parse` closure.
#[cfg(feature = "async")]
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3"
    )),
    allow(dead_code)
)]
pub(crate) async fn run_paginated_async<T>(
    first: PageRequest<T>,
    config: &common::RequestConfig,
) -> Result<Vec<T>> {
    use futures_util::StreamExt;

    let mut out = Vec::new();
    let mut next = Some(first);
    let mut pages = 0usize;
    while let Some(request) = next {
        let PageRequest {
            url,
            headers,
            parse,
        } = request;
        let resp = send_async(&url, headers, config).await?;
        let resp_headers = resp.headers().clone();
        // Drain the streamed body into a single buffer (one full read, honoring the I7 intent of
        // not double-buffering: the bytes stream feeds the buffer directly).
        let mut stream = resp.bytes_stream();
        let mut body = Vec::new();
        while let Some(chunk) = stream.next().await {
            body.extend_from_slice(&chunk?);
            // S5: cap the per-page body size (same bound as the sync driver).
            if body.len() > MAX_LISTING_BODY_BYTES {
                return Err(Error::InvalidResponse {
                    source: Box::new(crate::errors::MessageError(format!(
                        "listing page body exceeded the {MAX_LISTING_BODY_BYTES}-byte cap; \
                         real release listing pages are much smaller"
                    ))),
                });
            }
        }
        let page = parse(&body, &resp_headers)?;
        out.extend(page.items);
        pages += 1;
        if page.stop {
            break;
        }
        if pages >= MAX_RELEASE_PAGES {
            if page.next.is_some() {
                log::warn!(
                    "self_update: stopped paginating releases after {MAX_RELEASE_PAGES} pages; \
                     older releases may be omitted"
                );
            }
            break;
        }
        next = page.next;
    }
    Ok(out)
}

/// Build the first-page request URL, defaulting the page size to 100 — unless the base URL
/// already carries query parameters (e.g. a `Link`-header "next" URL), in which case it is used
/// verbatim so an existing `page`/`per_page` is not clobbered.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee"
    )),
    allow(dead_code)
)]
pub(crate) fn first_page_url(base_url: &str) -> String {
    if base_url.contains('?') {
        base_url.to_owned()
    } else {
        format!("{base_url}?per_page=100")
    }
}

/// Extract the `rel="next"` URL from a response's `Link` header(s), if present.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee"
    )),
    allow(dead_code)
)]
pub(crate) fn next_link(headers: &http_client::HeaderMap) -> Option<String> {
    headers
        .get_all(http_client::header::LINK)
        .iter()
        .filter_map(|link| link.to_str().ok().and_then(find_rel_next_link))
        .next()
        .map(str::to_owned)
}

/// Exponential backoff in milliseconds before retry `attempt` (0-based): `base`, `base*2`,
/// `base*4`, … doubling each attempt, clamped to never exceed `max`. With the defaults
/// (`base = 100ms`, `max = 3200ms`) this is the historical 100, 200, 400, … capped at ~3.2s
/// (attempt 5 and beyond).
pub(crate) fn retry_backoff_ms(
    attempt: u32,
    base: std::time::Duration,
    max: std::time::Duration,
) -> u64 {
    // I8: as_millis() returns u128; saturate to u64::MAX rather than silently truncating.
    let base_ms = u64::try_from(base.as_millis()).unwrap_or(u64::MAX);
    let max_ms = u64::try_from(max.as_millis()).unwrap_or(u64::MAX);
    // Double `base` `attempt` times with saturation, then clamp to `max`.
    let doubled = (0..attempt).fold(base_ms, |acc, _| acc.saturating_mul(2));
    doubled.min(max_ms)
}

/// Whether an error must not be retried. [`Error::RateLimited`] is never retried: the wait is the
/// server's to dictate (`Retry-After`, or the reset header), and it can be far longer than any
/// backoff this crate would apply, so the error is returned immediately and the decision to sleep,
/// reschedule, or give up stays with the caller instead of being spent inside the loop.
fn is_rate_limited(err: &Error) -> bool {
    matches!(err, Error::RateLimited { .. })
}

/// Run `attempt` until it succeeds or the retry budget is spent, invoking `on_retry(err, backoff)`
/// (which logs the failure and sleeps) between tries. With `retries == 0` the attempt runs exactly
/// once. The transport and the sleep are injected so the retry/backoff control flow can be
/// unit-tested without real requests or real delays.
///
/// [`Error::RateLimited`] is never retried: the wait is the server's to dictate (`Retry-After`, or
/// the reset header), and it can be far longer than any backoff this crate would apply, so the
/// error is returned immediately and the decision to sleep, reschedule, or give up stays with the
/// caller instead of being spent inside the loop.
pub(crate) fn retry<R>(
    retries: u32,
    base: std::time::Duration,
    max: std::time::Duration,
    mut attempt: impl FnMut() -> Result<R>,
    mut on_retry: impl FnMut(&Error, u64),
) -> Result<R> {
    let mut attempts = 0u32;
    loop {
        match attempt() {
            Ok(r) => return Ok(r),
            Err(e) => {
                if attempts >= retries || is_rate_limited(&e) {
                    return Err(e);
                }
                on_retry(&e, retry_backoff_ms(attempts, base, max));
                attempts += 1;
            }
        }
    }
}

/// Async sibling of [`retry`]: the same retry/backoff loop with an injected async transport and
/// async `sleep`. `log_retry` runs synchronously between tries (so the error is never held across
/// the await); `sleep` performs the backoff delay. [`Error::RateLimited`] short-circuits here too.
#[cfg(feature = "async")]
pub(crate) async fn retry_async<R, A, Fut, S, SFut>(
    retries: u32,
    base: std::time::Duration,
    max: std::time::Duration,
    mut attempt: A,
    mut log_retry: impl FnMut(&Error, u64),
    mut sleep: S,
) -> Result<R>
where
    A: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<R>>,
    S: FnMut(u64) -> SFut,
    SFut: std::future::Future<Output = ()>,
{
    let mut attempts = 0u32;
    loop {
        match attempt().await {
            Ok(r) => return Ok(r),
            Err(e) => {
                if attempts >= retries || is_rate_limited(&e) {
                    return Err(e);
                }
                let backoff = retry_backoff_ms(attempts, base, max);
                log_retry(&e, backoff);
                sleep(backoff).await;
                attempts += 1;
            }
        }
    }
}

/// Issue a GET request, merging the per-request transport `config` (extra headers + timeout)
/// on top of the supplied `base` headers, retrying a failed request up to `config.retries`
/// times with exponential backoff.
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3",
        feature = "manifest"
    )),
    allow(dead_code)
)]
pub(crate) fn send(
    url: &str,
    mut base: http_client::HeaderMap,
    config: &common::RequestConfig,
) -> Result<Box<dyn http_client::HttpResponse>> {
    // Apply the backend's derived Authorization first (scheme + token), unless the user set their
    // own Authorization via `request_header` (honored below when `config.headers` is merged). The
    // token is attached only for a same-host request, so a malicious `Link` next-page URL pointing
    // at another host does not receive it.
    config.apply_auth(url, &mut base)?;
    for (name, value) in &config.headers {
        // S2: gate a user-supplied Authorization header with the same host check that guards the
        // backend-derived token; drop it for any host that is not in the allow list.
        if name == http_client::header::AUTHORIZATION && !config.auth_allowed_for(url) {
            continue;
        }
        base.insert(name.clone(), value.clone());
    }
    // Dispatch through the injected client if present, else the crate's default per-call client.
    let default;
    let client: &dyn http_client::HttpClient = match config.client.as_deref() {
        Some(c) => c,
        None => {
            default = http_client::default_client();
            &*default
        }
    };
    retry(
        config.retries,
        config.retry_base_delay,
        config.retry_max_delay,
        || client.get(url, &base, config.timeout),
        |e, backoff| {
            // S1: redact presigned-URL credentials before logging.
            let safe_url = crate::errors::redact_url(url);
            log::warn!("self_update: request to {safe_url} failed ({e}); retrying in {backoff}ms");
            std::thread::sleep(std::time::Duration::from_millis(backoff));
        },
    )
}

/// Async sibling of [`send`]: issue a GET, merging the per-request transport `config` on top of
/// `base`, retrying up to `config.retries` times with `tokio::time::sleep` backoff.
#[cfg(feature = "async")]
#[cfg_attr(
    not(any(
        feature = "github",
        feature = "gitlab",
        feature = "gitea",
        feature = "gitee",
        feature = "s3",
        feature = "manifest"
    )),
    allow(dead_code)
)]
pub(crate) async fn send_async(
    url: &str,
    mut base: http_client::HeaderMap,
    config: &common::RequestConfig,
) -> Result<Box<dyn http_client::AsyncHttpResponse>> {
    config.apply_auth(url, &mut base)?;
    for (name, value) in &config.headers {
        // S2: same host gate as the sync `send` path (see comment there).
        if name == http_client::header::AUTHORIZATION && !config.auth_allowed_for(url) {
            continue;
        }
        base.insert(name.clone(), value.clone());
    }
    let default;
    let client: &dyn http_client::AsyncHttpClient = match config.async_client.as_deref() {
        Some(c) => c,
        None => {
            default = http_client::default_async_client();
            &*default
        }
    };
    retry_async(
        config.retries,
        config.retry_base_delay,
        config.retry_max_delay,
        || client.get(url, &base, config.timeout),
        |e, backoff| {
            // S1: redact presigned-URL credentials before logging.
            let safe_url = crate::errors::redact_url(url);
            log::warn!("self_update: request to {safe_url} failed ({e}); retrying in {backoff}ms");
        },
        |backoff| tokio::time::sleep(std::time::Duration::from_millis(backoff)),
    )
    .await
}

#[cfg(test)]
mod test {
    use crate::backends::common::RequestConfig;
    use crate::backends::find_rel_next_link;
    use crate::backends::{Page, PageRequest};
    use crate::http_client::HeaderMap;

    #[test]
    fn test_find_rel_link() {
        let val = r##" <https://api.github.com/resource?page=2>; rel="next" "##;
        let link = find_rel_next_link(val);
        assert_eq!(link, Some("https://api.github.com/resource?page=2"));

        let val = r##" <https://gitlab.com/api/v4/projects/13083/releases?id=13083&page=2&per_page=20>; rel="next" "##;
        let link = find_rel_next_link(val);
        assert_eq!(
            link,
            Some("https://gitlab.com/api/v4/projects/13083/releases?id=13083&page=2&per_page=20")
        );

        // returns the first one
        let val = r##" <https://place.com>; rel="next", <https://wow.com>; rel="next" "##;
        let link = find_rel_next_link(val);
        assert_eq!(link, Some("https://place.com"));

        // bad format, returns the second one
        let val = r##" https://bad-format.com; rel="next", <https://wow.com>; rel="next" "##;
        let link = find_rel_next_link(val);
        assert_eq!(link, Some("https://wow.com"));

        // all bad format, returns none
        let val = r##" https://bad-format.com; rel="next", <https://also-bad.com; rel="next" , <https://good.com>; rel="preconnect" "##;
        let link = find_rel_next_link(val);
        assert!(link.is_none());
    }

    // -----------------------------------------------------------------------
    // run_paginated: sans-io page-chain driver (over a loopback TCP stub)
    // -----------------------------------------------------------------------

    use std::io::{Read as _, Write as _};
    use std::net::TcpListener;

    /// A `PageRequest<i32>` that parses the body as a comma-separated list of ints and follows the
    /// `rel="next"` Link header (never setting the early-stop flag).
    fn int_page(url: String) -> PageRequest<i32> {
        PageRequest {
            url,
            headers: HeaderMap::new(),
            parse: Box::new(move |body, headers| {
                let text = std::str::from_utf8(body).unwrap_or("");
                let items: Vec<i32> = text
                    .split(',')
                    .filter(|s| !s.is_empty())
                    .map(|s| s.parse::<i32>().unwrap())
                    .collect();
                let next = crate::backends::next_link(headers).map(int_page);
                Ok(Page {
                    items,
                    next,
                    stop: false,
                })
            }),
        }
    }

    /// Build a stub serving pages whose `Link` next-URLs are wired to the stub's own base via the
    /// supplied paths. `specs` is `(next_path, body)` per page; a `None` next_path is the last page.
    fn linked_stub(
        specs: Vec<(Option<&str>, &str)>,
    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        // Bind first so we know the base, then resolve the relative next-paths against it.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let pages: Vec<(Option<String>, String)> = specs
            .into_iter()
            .map(|(next, body)| (next.map(|p| format!("{base}{p}")), body.to_string()))
            .collect();
        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = captured.clone();
        std::thread::spawn(move || {
            for (link, body) in pages {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                let req = String::from_utf8_lossy(&buf[..n]).into_owned();
                sink.lock()
                    .unwrap()
                    .push(req.lines().next().unwrap_or("").to_string());
                let mut out = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n".to_string();
                if let Some(link) = link {
                    out.push_str(&format!("Link: <{link}>; rel=\"next\"\r\n"));
                }
                out.push_str(&format!(
                    "Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                ));
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        (base, captured)
    }

    #[test]
    fn run_paginated_accumulates_pages() {
        // Three pages, the first two advertising a `rel="next"` link to the next.
        let (base, captured) = linked_stub(vec![
            (Some("/p2"), "1,2"),
            (Some("/p3"), "3"),
            (None, "4,5"),
        ]);
        let got = crate::backends::run_paginated(
            int_page(format!("{base}/p1")),
            &RequestConfig::default(),
        )
        .unwrap();
        assert_eq!(got, vec![1, 2, 3, 4, 5]);
        let paths = captured.lock().unwrap();
        assert_eq!(paths.len(), 3, "exactly three pages were requested");
        assert!(paths[0].contains("/p1"));
        assert!(paths[1].contains("/p2"));
        assert!(paths[2].contains("/p3"));
    }

    #[test]
    fn run_paginated_single_page() {
        let (base, captured) = linked_stub(vec![(None, "7,8,9")]);
        let got = crate::backends::run_paginated(
            int_page(format!("{base}/only")),
            &RequestConfig::default(),
        )
        .unwrap();
        assert_eq!(got, vec![7, 8, 9]);
        assert_eq!(captured.lock().unwrap().len(), 1, "one request only");
    }

    #[test]
    fn run_paginated_stops_early_on_page_stop_flag() {
        // Page 1 advertises a next page but sets `stop=true`; the driver must NOT request page 2.
        let (base, captured) = linked_stub(vec![
            (Some("/never"), "1,2"),
            (None, "should-not-be-served"),
        ]);
        let stopping = PageRequest {
            url: format!("{base}/p1"),
            headers: HeaderMap::new(),
            parse: Box::new(|body: &[u8], _headers: &HeaderMap| {
                let text = std::str::from_utf8(body).unwrap_or("");
                let items: Vec<i32> = text.split(',').map(|s| s.parse().unwrap()).collect();
                // Pretend the server still advertises a next page but we stop early.
                Ok(Page {
                    items,
                    next: Some(int_page("http://unused.invalid/never".into())),
                    stop: true,
                })
            }),
        };
        let got = crate::backends::run_paginated(stopping, &RequestConfig::default()).unwrap();
        assert_eq!(got, vec![1, 2]);
        assert_eq!(
            captured.lock().unwrap().len(),
            1,
            "stop=true must halt after page 1; page 2 must never be requested"
        );
    }

    #[test]
    fn run_paginated_is_bounded_by_max_pages() {
        use crate::backends::MAX_RELEASE_PAGES;
        // A server that always advertises a next page (pointing back at itself) must not loop
        // forever — the driver is bounded by MAX_RELEASE_PAGES.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let base_for_thread = base.clone();
        std::thread::spawn(move || {
            loop {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let body = "0";
                let out = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nLink: <{base_for_thread}/n>; rel=\"next\"\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        let got = crate::backends::run_paginated(
            int_page(format!("{base}/start")),
            &RequestConfig::default(),
        )
        .unwrap();
        assert_eq!(
            got.len(),
            MAX_RELEASE_PAGES,
            "the walk is bounded at MAX_RELEASE_PAGES even when next is always advertised"
        );
    }

    // -----------------------------------------------------------------------
    // run_paginated_async: direct coverage of the async page-chain driver
    // (body-drain via bytes_stream + async early-stop), mirroring the sync tests.
    // -----------------------------------------------------------------------

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_accumulates_pages() {
        let (base, captured) = linked_stub(vec![
            (Some("/p2"), "1,2"),
            (Some("/p3"), "3"),
            (None, "4,5"),
        ]);
        let got = crate::backends::run_paginated_async(
            int_page(format!("{base}/p1")),
            &RequestConfig::default(),
        )
        .await
        .unwrap();
        assert_eq!(got, vec![1, 2, 3, 4, 5]);
        let paths = captured.lock().unwrap();
        assert_eq!(paths.len(), 3, "exactly three pages were requested");
        assert!(paths[0].contains("/p1"));
        assert!(paths[1].contains("/p2"));
        assert!(paths[2].contains("/p3"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_stops_early_on_page_stop_flag() {
        // Page 1 advertises a next page but sets `stop=true`; the async driver must NOT request
        // page 2 (same contract as the sync driver).
        let (base, captured) = linked_stub(vec![
            (Some("/never"), "1,2"),
            (None, "should-not-be-served"),
        ]);
        let stopping = PageRequest {
            url: format!("{base}/p1"),
            headers: HeaderMap::new(),
            parse: Box::new(|body: &[u8], _headers: &HeaderMap| {
                let text = std::str::from_utf8(body).unwrap_or("");
                let items: Vec<i32> = text.split(',').map(|s| s.parse().unwrap()).collect();
                Ok(Page {
                    items,
                    next: Some(int_page("http://unused.invalid/never".into())),
                    stop: true,
                })
            }),
        };
        let got = crate::backends::run_paginated_async(stopping, &RequestConfig::default())
            .await
            .unwrap();
        assert_eq!(got, vec![1, 2]);
        assert_eq!(
            captured.lock().unwrap().len(),
            1,
            "stop=true must halt after page 1; page 2 must never be requested (async)"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_is_bounded_by_max_pages() {
        use crate::backends::MAX_RELEASE_PAGES;
        // A server always advertising a next page (pointing back at itself) must not loop forever;
        // the async driver is bounded by MAX_RELEASE_PAGES just like the sync one.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let base_for_thread = base.clone();
        std::thread::spawn(move || {
            loop {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let body = "0";
                let out = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nLink: <{base_for_thread}/n>; rel=\"next\"\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        let got = crate::backends::run_paginated_async(
            int_page(format!("{base}/start")),
            &RequestConfig::default(),
        )
        .await
        .unwrap();
        assert_eq!(
            got.len(),
            MAX_RELEASE_PAGES,
            "the async walk is bounded at MAX_RELEASE_PAGES even when next is always advertised"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_propagates_fetch_error() {
        // A non-2xx status on the first page must propagate as the structured error over the async
        // transport, before any accumulation.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let body = "boom";
                let out = format!(
                    "HTTP/1.1 503 Service Unavailable\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        let res = crate::backends::run_paginated_async(
            int_page(format!("{base}/p1")),
            &RequestConfig::default(),
        )
        .await;
        assert!(matches!(
            res,
            Err(crate::errors::Error::HttpStatus { status: 503, .. })
        ));
    }

    #[test]
    fn run_paginated_propagates_fetch_error() {
        // A non-2xx status on the first page must propagate as the structured error.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let body = "boom";
                let out = format!(
                    "HTTP/1.1 503 Service Unavailable\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        let res = crate::backends::run_paginated(
            int_page(format!("{base}/p1")),
            &RequestConfig::default(),
        );
        assert!(matches!(
            res,
            Err(crate::errors::Error::HttpStatus { status: 503, .. })
        ));
    }

    #[test]
    fn retry_runs_once_on_immediate_success() {
        use crate::backends::retry;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            3,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Ok(7)
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert_eq!(res.unwrap(), 7);
        assert_eq!(calls.get(), 1);
        assert!(backoffs.borrow().is_empty());
    }

    #[test]
    fn retry_with_zero_budget_attempts_once_then_errors() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            0,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        assert_eq!(calls.get(), 1);
        assert!(backoffs.borrow().is_empty());
    }

    #[test]
    fn retry_exhausts_budget_then_returns_last_error() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            2,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        // initial attempt + 2 retries
        assert_eq!(calls.get(), 3);
        assert_eq!(*backoffs.borrow(), vec![100, 200]);
    }

    #[test]
    fn retry_returns_ok_when_a_later_attempt_succeeds() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                if calls.get() < 3 {
                    Err(Error::HttpStatus {
                        status: 503,
                        url: "u".into(),
                    })
                } else {
                    Ok(42)
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert_eq!(res.unwrap(), 42);
        assert_eq!(calls.get(), 3);
        assert_eq!(*backoffs.borrow(), vec![100, 200]);
    }

    #[test]
    fn retry_backoff_is_exponential_and_capped() {
        use crate::backends::common::{DEFAULT_RETRY_BASE_DELAY, DEFAULT_RETRY_MAX_DELAY};
        use crate::backends::retry_backoff_ms;
        // The default base/cap reproduce the historical 100, 200, 400, … capped at 3200ms.
        let ms =
            |attempt| retry_backoff_ms(attempt, DEFAULT_RETRY_BASE_DELAY, DEFAULT_RETRY_MAX_DELAY);
        assert_eq!(ms(0), 100);
        assert_eq!(ms(1), 200);
        assert_eq!(ms(2), 400);
        assert_eq!(ms(3), 800);
        assert_eq!(ms(4), 1600);
        assert_eq!(ms(5), 3200);
        // capped from attempt 5 onward
        assert_eq!(ms(6), 3200);
        assert_eq!(ms(100), 3200);
    }

    #[test]
    fn retry_backoff_honors_a_configured_base_and_cap() {
        use crate::backends::retry_backoff_ms;
        use std::time::Duration;
        // I4: a configured base/cap drives the backoff. base = 250ms doubles each attempt and is
        // clamped at the 1000ms cap.
        let base = Duration::from_millis(250);
        let max = Duration::from_millis(1000);
        assert_eq!(retry_backoff_ms(0, base, max), 250);
        assert_eq!(retry_backoff_ms(1, base, max), 500);
        assert_eq!(retry_backoff_ms(2, base, max), 1000);
        // clamped at the cap from here on (would be 2000, 4000, …).
        assert_eq!(retry_backoff_ms(3, base, max), 1000);
        assert_eq!(retry_backoff_ms(10, base, max), 1000);
        // A very large attempt index must saturate, not overflow/panic.
        assert_eq!(retry_backoff_ms(100, base, max), 1000);
    }

    #[test]
    fn retry_backoff_uses_the_request_config_defaults() {
        use crate::backends::common::RequestConfig;
        use std::time::Duration;
        // The defaults wired into RequestConfig match the historical 100ms base / 3.2s cap.
        let cfg = RequestConfig::default();
        assert_eq!(cfg.retry_base_delay, Duration::from_millis(100));
        assert_eq!(cfg.retry_max_delay, Duration::from_millis(3200));
    }

    #[test]
    fn retry_with_a_single_retry_attempts_twice() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            1,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        // initial attempt + 1 retry; the `>` vs `>=` budget boundary
        assert_eq!(calls.get(), 2);
        assert_eq!(*backoffs.borrow(), vec![100]);
    }

    #[test]
    fn retry_does_not_retry_a_rate_limited_error() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        // The quota is already spent, so retrying can only fire more requests against an exhausted
        // (and possibly shared) budget. Even with a budget of 5 the attempt must run exactly ONCE
        // and no backoff may be scheduled; the RateLimited error is returned unchanged.
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::RateLimited {
                    status: 403,
                    url: "u".into(),
                    reset_at: None,
                    retry_after: None,
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(
            matches!(res, Err(Error::RateLimited { status: 403, .. })),
            "the RateLimited error must be returned unchanged, got {:?}",
            res
        );
        assert_eq!(
            calls.get(),
            1,
            "a rate-limited attempt must not be retried, even with retries = 5"
        );
        assert!(
            backoffs.borrow().is_empty(),
            "no backoff may be scheduled for a rate-limited attempt"
        );
    }

    #[test]
    fn retry_still_consumes_the_budget_for_a_non_rate_limited_error() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        // Guard the other side of the RateLimited short-circuit: every other error still consumes
        // the whole budget (initial attempt + 5 retries) with the full backoff sequence.
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        assert_eq!(calls.get(), 6, "initial attempt + 5 retries");
        assert_eq!(*backoffs.borrow(), vec![100, 200, 400, 800, 1600]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn retry_async_does_not_retry_a_rate_limited_error() {
        use crate::backends::retry_async;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        // Async sibling of `retry_does_not_retry_a_rate_limited_error`: the async loop must
        // short-circuit the spent quota identically, so the two lanes cannot drift.
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let slept = Cell::new(0u32);
        let res: crate::errors::Result<i32> = retry_async(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                async {
                    Err(Error::RateLimited {
                        status: 429,
                        url: "u".into(),
                        reset_at: None,
                        retry_after: None,
                    })
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
            |_b| {
                slept.set(slept.get() + 1);
                async {}
            },
        )
        .await;
        assert!(
            matches!(res, Err(Error::RateLimited { status: 429, .. })),
            "the RateLimited error must be returned unchanged (async), got {:?}",
            res
        );
        assert_eq!(
            calls.get(),
            1,
            "a rate-limited attempt must not be retried (async), even with retries = 5"
        );
        assert!(backoffs.borrow().is_empty());
        assert_eq!(
            slept.get(),
            0,
            "no backoff sleep for a rate-limited attempt"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn retry_async_still_consumes_the_budget_for_a_non_rate_limited_error() {
        use crate::backends::retry_async;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        // The other side of the async short-circuit: a non-RateLimited error still spends the whole
        // budget and sleeps between each try.
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let slept = Cell::new(0u32);
        let res: crate::errors::Result<i32> = retry_async(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                async {
                    Err(Error::HttpStatus {
                        status: 503,
                        url: "u".into(),
                    })
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
            |_b| {
                slept.set(slept.get() + 1);
                async {}
            },
        )
        .await;
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        assert_eq!(calls.get(), 6, "initial attempt + 5 retries (async)");
        assert_eq!(*backoffs.borrow(), vec![100, 200, 400, 800, 1600]);
        assert_eq!(slept.get(), 5);
    }

    #[test]
    fn retry_backoff_sequence_through_the_loop_climbs_and_caps() {
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        // Six retries drive the in-loop attempt index from 0 through 5, so the recorded backoff
        // sequence must climb 100 -> 3200 and hit the cap at the final step — proving the loop
        // feeds the rising attempt index into `retry_backoff_ms`, not just index 0/1.
        let res: crate::errors::Result<i32> = retry(
            6,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                Err(Error::HttpStatus {
                    status: 503,
                    url: "u".into(),
                })
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        assert_eq!(calls.get(), 7);
        assert_eq!(*backoffs.borrow(), vec![100, 200, 400, 800, 1600, 3200]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn retry_async_exhausts_budget_then_returns_last_error() {
        use crate::backends::retry_async;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry_async(
            2,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                async {
                    Err(Error::HttpStatus {
                        status: 503,
                        url: "u".into(),
                    })
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
            |_b| async {},
        )
        .await;
        assert!(matches!(res, Err(Error::HttpStatus { .. })));
        assert_eq!(calls.get(), 3);
        assert_eq!(*backoffs.borrow(), vec![100, 200]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn retry_async_returns_ok_when_a_later_attempt_succeeds() {
        use crate::backends::retry_async;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry_async(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                let done = calls.get() >= 3;
                async move {
                    if done {
                        Ok(42)
                    } else {
                        Err(Error::HttpStatus {
                            status: 503,
                            url: "u".into(),
                        })
                    }
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
            |_b| async {},
        )
        .await;
        assert_eq!(res.unwrap(), 42);
        assert_eq!(calls.get(), 3);
        assert_eq!(*backoffs.borrow(), vec![100, 200]);
    }

    // -----------------------------------------------------------------------
    // send: the listing path applies the derived auth header AND honors a user
    // AUTHORIZATION override (B5), captured off a loopback TCP stub.
    // -----------------------------------------------------------------------

    /// Bind a loopback stub that accepts one request, captures its raw header lines, and replies
    /// with an empty 200. Returns the base URL and the captured-request handle.
    fn auth_capture_stub() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = captured.clone();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                let req = String::from_utf8_lossy(&buf[..n]).into_owned();
                let lines: Vec<String> = req.lines().map(|l| l.to_string()).collect();
                *sink.lock().unwrap() = lines;
                let body = "";
                let out = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        (base, captured)
    }

    /// Extract the `Authorization` header value the stub received, if any.
    fn captured_authorization(lines: &[String]) -> Option<String> {
        lines.iter().find_map(|l| {
            l.strip_prefix("Authorization: ")
                .or_else(|| l.strip_prefix("authorization: "))
                .map(|v| v.to_string())
        })
    }

    #[test]
    fn send_applies_derived_token_auth_on_listing_path() {
        use crate::backends::common::AuthScheme;
        let (base, captured) = auth_capture_stub();
        let config = RequestConfig {
            auth_scheme: AuthScheme::Token,
            auth_token: Some("secret".to_string()),
            auth_base_host: crate::backends::common::host_of(&base),
            ..Default::default()
        };
        let _ = crate::backends::send(&base, HeaderMap::new(), &config).unwrap();
        let lines = captured.lock().unwrap().clone();
        assert_eq!(
            captured_authorization(&lines),
            Some("token secret".to_string()),
            "the listing path must send the derived `token` auth header"
        );
    }

    #[test]
    fn send_applies_derived_bearer_auth_on_listing_path() {
        use crate::backends::common::AuthScheme;
        let (base, captured) = auth_capture_stub();
        let config = RequestConfig {
            auth_scheme: AuthScheme::Bearer,
            auth_token: Some("secret".to_string()),
            auth_base_host: crate::backends::common::host_of(&base),
            ..Default::default()
        };
        let _ = crate::backends::send(&base, HeaderMap::new(), &config).unwrap();
        let lines = captured.lock().unwrap().clone();
        assert_eq!(
            captured_authorization(&lines),
            Some("Bearer secret".to_string()),
            "the listing path must send the derived `Bearer` auth header"
        );
    }

    #[test]
    fn send_honors_user_authorization_override_on_listing_path() {
        use crate::backends::common::AuthScheme;
        use crate::http_client::header::AUTHORIZATION;
        // A backend token is configured AND the user supplies their own Authorization via
        // `request_header` (i.e. config.headers). The user override must win on the listing path
        // when the URL's host is in the allow list (S2: the same host gate applies to both the
        // derived token and the user-supplied Authorization).
        let (base, captured) = auth_capture_stub();
        let mut headers = HeaderMap::new();
        headers.insert(AUTHORIZATION, "Bearer user-override".parse().unwrap());
        let config = RequestConfig {
            auth_scheme: AuthScheme::Token,
            auth_token: Some("secret".to_string()),
            headers,
            // Allow the stub's loopback host so the user Authorization passes the S2 gate.
            auth_base_host: crate::backends::common::host_of(&base),
            ..Default::default()
        };
        let _ = crate::backends::send(&base, HeaderMap::new(), &config).unwrap();
        let lines = captured.lock().unwrap().clone();
        assert_eq!(
            captured_authorization(&lines),
            Some("Bearer user-override".to_string()),
            "a user AUTHORIZATION override must win over the backend token on the listing path"
        );
    }

    #[test]
    fn first_page_url_appends_per_page_only_when_no_query() {
        use crate::backends::first_page_url;
        assert_eq!(
            first_page_url("https://api.github.com/repos/o/r/releases"),
            "https://api.github.com/repos/o/r/releases?per_page=100"
        );
        // A URL that already has query params (e.g. a `Link` next URL) is left untouched.
        assert_eq!(
            first_page_url("https://api.github.com/repos/o/r/releases?page=2&per_page=20"),
            "https://api.github.com/repos/o/r/releases?page=2&per_page=20"
        );
    }

    #[test]
    fn next_link_extracts_rel_next_from_link_header() {
        use crate::backends::next_link;
        use crate::http_client::header::{HeaderMap, LINK};

        // No Link header -> None.
        assert_eq!(next_link(&HeaderMap::new()), None);

        // A single `rel="next"` link is returned.
        let mut headers = HeaderMap::new();
        headers.insert(
            LINK,
            "<https://api.example.com/r?page=2>; rel=\"next\""
                .parse()
                .unwrap(),
        );
        assert_eq!(
            next_link(&headers),
            Some("https://api.example.com/r?page=2".to_string())
        );

        // The `next` link is picked out from among other relations.
        let mut headers = HeaderMap::new();
        headers.insert(
            LINK,
            "<https://api.example.com/r?page=5>; rel=\"last\", <https://api.example.com/r?page=2>; rel=\"next\""
                .parse()
                .unwrap(),
        );
        assert_eq!(
            next_link(&headers),
            Some("https://api.example.com/r?page=2".to_string())
        );
    }

    // -----------------------------------------------------------------------
    // I8: retry_backoff_ms safe u128->u64 cast
    // -----------------------------------------------------------------------

    #[test]
    fn retry_backoff_ms_saturates_for_huge_duration() {
        use crate::backends::retry_backoff_ms;
        use std::time::Duration;
        // Duration::from_secs(u64::MAX) has as_millis() >> u64::MAX; the old `as u64` cast
        // silently truncated. The fix (u64::try_from(..).unwrap_or(u64::MAX)) must saturate.
        let huge = Duration::from_secs(u64::MAX);
        // Both base and max are huge; regardless of attempt, the result must be u64::MAX.
        assert_eq!(
            retry_backoff_ms(0, huge, huge),
            u64::MAX,
            "a Duration::from_secs(u64::MAX) base must not truncate: expected u64::MAX"
        );
        // A clamp against a huge max: the doubled base is still huge, capped to the huge max.
        assert_eq!(
            retry_backoff_ms(5, huge, huge),
            u64::MAX,
            "a huge duration at a non-zero attempt must also saturate to u64::MAX"
        );
    }

    // -----------------------------------------------------------------------
    // S1: retry log lines must not leak presigned-URL credentials
    // -----------------------------------------------------------------------

    #[test]
    fn retry_log_redacts_amz_signature_in_presigned_url() {
        // The retry on_retry closure in `send`/`send_async` must call `crate::errors::redact_url`
        // before formatting the log message (S1 fix). Construct the exact string the closure
        // produces and assert no raw credential value appears.
        let presigned_url = "https://bucket.s3.amazonaws.com/app.tar.gz\
            ?X-Amz-Credential=AKIAEXAMPLE\
            &X-Amz-Expires=300\
            &X-Amz-Signature=s3cr3tsig\
            &X-Amz-SignedHeaders=host";
        let safe = crate::errors::redact_url(presigned_url);
        // Format the message exactly as the on_retry closure does:
        let log_line = format!("self_update: request to {safe} failed (err); retrying in 100ms");
        assert!(
            !log_line.contains("s3cr3tsig"),
            "retry log line must not contain the raw X-Amz-Signature value: {log_line}"
        );
        assert!(
            log_line.contains("X-Amz-Signature=REDACTED"),
            "the parameter key must still appear as REDACTED in the log: {log_line}"
        );
        // Confirm that WITHOUT redaction the secret would have appeared (documents the fix intent).
        let without_fix =
            format!("self_update: request to {presigned_url} failed (err); retrying in 100ms");
        assert!(
            without_fix.contains("s3cr3tsig"),
            "sanity: the unfixed format string DOES contain the raw signature"
        );
    }

    // -----------------------------------------------------------------------
    // S2: user-supplied Authorization is gated by the same host check as the
    //     backend-derived token
    // -----------------------------------------------------------------------

    #[test]
    fn send_drops_user_authorization_for_disallowed_host() {
        // A user-supplied Authorization in config.headers must be dropped for a host that is not
        // in the allow list (S2 fix). auth_base_host=None means no host is allowed.
        use crate::http_client::header::AUTHORIZATION;
        let (base, captured) = auth_capture_stub();
        let mut extra = HeaderMap::new();
        extra.insert(AUTHORIZATION, "Bearer user-token".parse().unwrap());
        let config = RequestConfig {
            headers: extra,
            auth_base_host: None, // no host allowed → user Authorization must be dropped
            ..Default::default()
        };
        let _ = crate::backends::send(&base, HeaderMap::new(), &config).unwrap();
        let lines = captured.lock().unwrap().clone();
        assert_eq!(
            captured_authorization(&lines),
            None,
            "user Authorization must be dropped when auth_base_host is None (disallowed host)"
        );
    }

    #[test]
    fn send_keeps_user_authorization_for_allowed_host() {
        // A user-supplied Authorization must reach the server when the URL's host is in the allow
        // list (S2 regression guard: the gate must not over-restrict).
        use crate::http_client::header::AUTHORIZATION;
        let (base, captured) = auth_capture_stub();
        let stub_host = crate::backends::common::host_of(&base);
        let mut extra = HeaderMap::new();
        extra.insert(AUTHORIZATION, "Bearer user-token".parse().unwrap());
        let config = RequestConfig {
            headers: extra,
            auth_base_host: stub_host,
            ..Default::default()
        };
        let _ = crate::backends::send(&base, HeaderMap::new(), &config).unwrap();
        let lines = captured.lock().unwrap().clone();
        assert_eq!(
            captured_authorization(&lines),
            Some("Bearer user-token".to_string()),
            "user Authorization must be forwarded when the host is in the allow list"
        );
    }

    // -----------------------------------------------------------------------
    // S5: per-page body size cap
    // -----------------------------------------------------------------------

    #[test]
    fn run_paginated_errors_when_body_exceeds_cap() {
        use crate::backends::MAX_LISTING_BODY_BYTES;
        use std::io::{Read as _, Write as _};
        use std::net::TcpListener;

        // A body one byte over MAX_LISTING_BODY_BYTES must produce Error::InvalidResponse
        // before parse is ever called (S5: per-page body size cap).
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let over_cap = MAX_LISTING_BODY_BYTES + 1;
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let hdr = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {over_cap}\r\nConnection: close\r\n\r\n"
                );
                let _ = stream.write_all(hdr.as_bytes());
                let chunk = vec![b'x'; 8192];
                let mut remaining = over_cap;
                while remaining > 0 {
                    let n = remaining.min(chunk.len());
                    let _ = stream.write_all(&chunk[..n]);
                    remaining -= n;
                }
                let _ = stream.flush();
            }
        });
        let req = PageRequest::<i32> {
            url: format!("{base}/page"),
            headers: HeaderMap::new(),
            // Without the S5 fix, parse would be called with a huge body and return Aborted —
            // the assertion below would then fail (Aborted != InvalidResponse).
            parse: Box::new(|_body, _headers| Err(crate::errors::Error::Aborted)),
        };
        let res = crate::backends::run_paginated(req, &RequestConfig::default());
        assert!(
            matches!(res, Err(crate::errors::Error::InvalidResponse { .. })),
            "a body over the cap must error with InvalidResponse, got: {:?}",
            res
        );
    }

    #[test]
    fn run_paginated_normal_body_is_not_capped() {
        // A body well under MAX_LISTING_BODY_BYTES must parse normally (S5 regression guard).
        let (base, _) = linked_stub(vec![(None, "10,20,30")]);
        let got = crate::backends::run_paginated(
            int_page(format!("{base}/page")),
            &RequestConfig::default(),
        )
        .unwrap();
        assert_eq!(got, vec![10, 20, 30]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_errors_when_body_exceeds_cap() {
        use crate::backends::MAX_LISTING_BODY_BYTES;
        use std::io::{Read as _, Write as _};
        use std::net::TcpListener;

        // Async variant of run_paginated_errors_when_body_exceeds_cap.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let over_cap = MAX_LISTING_BODY_BYTES + 1;
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let hdr = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {over_cap}\r\nConnection: close\r\n\r\n"
                );
                let _ = stream.write_all(hdr.as_bytes());
                let chunk = vec![b'x'; 8192];
                let mut remaining = over_cap;
                while remaining > 0 {
                    let n = remaining.min(chunk.len());
                    let _ = stream.write_all(&chunk[..n]);
                    remaining -= n;
                }
                let _ = stream.flush();
            }
        });
        let req = PageRequest::<i32> {
            url: format!("{base}/page"),
            headers: HeaderMap::new(),
            parse: Box::new(|_body, _headers| Err(crate::errors::Error::Aborted)),
        };
        let res = crate::backends::run_paginated_async(req, &RequestConfig::default()).await;
        assert!(
            matches!(res, Err(crate::errors::Error::InvalidResponse { .. })),
            "async: a body over the cap must error with InvalidResponse, got: {:?}",
            res
        );
    }

    // -----------------------------------------------------------------------
    // AUTH-RL: a rate-limited response is never re-issued.
    //
    // The unit tests above drive `retry`/`retry_async` with a hand-built
    // `Error::RateLimited`. These tests close the loop end-to-end over the real
    // transport: a loopback stub that COUNTS the requests it served proves the
    // number of HTTP requests actually put on the wire, and each rate-limit case
    // is paired with a control that still spends the whole retry budget — so a
    // short-circuit that fired for EVERY error (or one keyed on the 403 status
    // rather than on the classified variant) could not pass this set.
    // -----------------------------------------------------------------------

    /// Bind a loopback stub that answers EVERY connection with the same fixed response and counts
    /// the requests it served. `status_line` is e.g. `"403 Forbidden"`; `extra_headers` is a block
    /// of CRLF-terminated header lines (possibly empty). Every response carries `Connection: close`,
    /// so one connection is one request and the counter is the exact number of requests the client
    /// issued. Unlike the one-shot stubs above it accepts in a loop, so a retried request is served
    /// (and counted) rather than hanging.
    fn counting_stub(
        status_line: &str,
        extra_headers: &str,
    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let hits = std::sync::Arc::new(AtomicUsize::new(0));
        let counter = hits.clone();
        let status_line = status_line.to_string();
        let extra_headers = extra_headers.to_string();
        std::thread::spawn(move || {
            loop {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                if n == 0 {
                    continue;
                }
                counter.fetch_add(1, Ordering::SeqCst);
                let body = "stub";
                let out = format!(
                    "HTTP/1.1 {status_line}\r\n{extra_headers}Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        (base, hits)
    }

    /// A `RequestConfig` with `retries` retries and a 1ms backoff, so a control test that really
    /// does spend its whole budget stays fast (the backoff *values* are covered by the
    /// `retry_backoff_*` tests; here only the request COUNT matters).
    fn fast_retry_config(retries: u32) -> RequestConfig {
        RequestConfig {
            retries,
            retry_base_delay: std::time::Duration::from_millis(1),
            retry_max_delay: std::time::Duration::from_millis(1),
            ..Default::default()
        }
    }

    fn hits_of(hits: &std::sync::Arc<std::sync::atomic::AtomicUsize>) -> usize {
        hits.load(std::sync::atomic::Ordering::SeqCst)
    }

    #[test]
    fn send_issues_exactly_one_request_for_a_rate_limited_response() {
        // End-to-end guard for the RateLimited short-circuit: a 403 reporting a spent quota must
        // put exactly ONE request on the wire even with retries = 3. Before the fix this issued 4
        // requests against an already-exhausted (and, behind a shared egress IP, shared) budget.
        let (base, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(3));
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::RateLimited { status: 403, .. })
            ),
            "a 403 with a spent quota must surface as RateLimited, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits_of(&hits),
            1,
            "a rate-limited response must not be retried: exactly one request may reach the server"
        );
    }

    #[test]
    fn send_spends_the_whole_budget_for_a_server_error() {
        // The control for the test above. A 500 is NOT rate limiting, so the retry budget is still
        // spent in full: 1 initial attempt + 3 retries = 4 requests on the wire. Without this pair,
        // a `retry` that short-circuited on EVERY error would pass the rate-limit test.
        let (base, hits) = counting_stub("500 Internal Server Error", "");
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(3));
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::HttpStatus { status: 500, .. })
            ),
            "a 500 must surface as HttpStatus, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits_of(&hits),
            4,
            "a non-rate-limited failure must still consume the retry budget (1 + 3 requests)"
        );
    }

    #[test]
    fn send_issues_exactly_one_request_for_a_bare_429() {
        // The second production path into `Error::RateLimited`: a bare 429 with no quota headers at
        // all (what proxies, CDNs and self-hosted forges return). It must short-circuit exactly like
        // the header-bearing 403 — the classification, not the header presence, drives the loop.
        let (base, hits) = counting_stub("429 Too Many Requests", "");
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(3));
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::RateLimited { status: 429, .. })
            ),
            "a bare 429 must surface as RateLimited, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits_of(&hits),
            1,
            "a 429 must not be retried, even with no quota headers on the response"
        );
    }

    #[test]
    fn send_issues_one_request_for_a_secondary_rate_limit_and_keeps_the_retry_after() {
        // GitHub's *secondary* rate limit: 403 + `Retry-After` while the primary quota is still
        // nonzero. It classifies as RateLimited, so it must short-circuit too — and the wait the
        // server asked for has to survive back to the caller, since the crate no longer retries on
        // the caller's behalf.
        let (base, hits) = counting_stub(
            "403 Forbidden",
            "x-ratelimit-remaining: 42\r\nretry-after: 1\r\n",
        );
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(3));
        match res {
            Err(crate::errors::Error::RateLimited { retry_after, .. }) => assert_eq!(
                retry_after,
                Some(std::time::Duration::from_secs(1)),
                "the server-supplied Retry-After must reach the caller"
            ),
            Err(other) => panic!("expected RateLimited for a 403 + Retry-After, got: {other:?}"),
            Ok(_) => panic!("expected RateLimited for a 403 + Retry-After, got a success"),
        }
        assert_eq!(
            hits_of(&hits),
            1,
            "a secondary rate limit (nonzero remaining + Retry-After) must not be retried"
        );
    }

    #[test]
    fn send_still_retries_a_plain_403_authorization_failure() {
        // The sharpest control: a *bare* 403 with no quota signal is an authorization failure
        // (`Unauthorized`), not a rate limit, and must still consume the retry budget. A
        // short-circuit keyed on the 403 STATUS instead of on the `RateLimited` variant would issue
        // one request here and fail this test.
        let (base, hits) = counting_stub("403 Forbidden", "");
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(3));
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::Unauthorized { status: 403, .. })
            ),
            "a bare 403 must stay Unauthorized, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits_of(&hits),
            4,
            "a plain 403 authorization failure is not rate limiting: the budget is still spent"
        );
    }

    #[test]
    fn send_with_zero_retries_is_unchanged_by_the_rate_limit_short_circuit() {
        // The `retries = 0` boundary: the short-circuit must be a no-op there (one request either
        // way), so the fix cannot have changed the default-configuration behavior.
        let (base, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let res = crate::backends::send(&base, HeaderMap::new(), &fast_retry_config(0));
        assert!(matches!(
            res,
            Err(crate::errors::Error::RateLimited { status: 403, .. })
        ));
        assert_eq!(
            hits_of(&hits),
            1,
            "retries = 0 still issues exactly one request"
        );
    }

    #[test]
    fn run_paginated_issues_one_request_for_a_rate_limited_first_page() {
        // The paginated driver reaches the transport through `send`, so the short-circuit must hold
        // for a listing walk too: a rate-limited first page ends the walk after one request.
        let (base, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let res =
            crate::backends::run_paginated(int_page(format!("{base}/p1")), &fast_retry_config(3));
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::RateLimited { status: 403, .. })
            ),
            "the paginated driver must surface RateLimited, got: {:?}",
            res.err()
        );
        assert_eq!(
            hits_of(&hits),
            1,
            "a rate-limited listing page must not be retried"
        );
    }

    #[test]
    fn run_paginated_spends_the_whole_budget_for_a_server_error() {
        // Control for the paginated rate-limit test: a 500 on the first page still retries.
        let (base, hits) = counting_stub("500 Internal Server Error", "");
        let res =
            crate::backends::run_paginated(int_page(format!("{base}/p1")), &fast_retry_config(3));
        assert!(matches!(
            res,
            Err(crate::errors::Error::HttpStatus { status: 500, .. })
        ));
        assert_eq!(
            hits_of(&hits),
            4,
            "a 500 listing page still consumes the retry budget (1 + 3 requests)"
        );
    }

    #[test]
    fn retry_short_circuits_mid_sequence_when_a_later_attempt_is_rate_limited() {
        // The short-circuit must also fire *after* the budget is partially spent: attempt 1 fails
        // with a retryable 503 (logged + backed off), attempt 2 comes back rate limited and must end
        // the loop immediately — 2 attempts and exactly 1 logged retry, not the full budget of 5.
        use crate::backends::retry;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let res: crate::errors::Result<i32> = retry(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                if calls.get() == 1 {
                    Err(Error::HttpStatus {
                        status: 503,
                        url: "u".into(),
                    })
                } else {
                    Err(Error::RateLimited {
                        status: 403,
                        url: "u".into(),
                        reset_at: None,
                        retry_after: None,
                    })
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
        );
        assert!(
            matches!(res, Err(Error::RateLimited { status: 403, .. })),
            "the rate-limit error from the second attempt must be the one returned, got {:?}",
            res
        );
        assert_eq!(
            calls.get(),
            2,
            "the loop must stop at the rate-limited attempt"
        );
        assert_eq!(
            *backoffs.borrow(),
            vec![100],
            "only the first (retryable) failure may log/schedule a retry; the rate-limited one must not"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn retry_async_short_circuits_mid_sequence_when_a_later_attempt_is_rate_limited() {
        // Async sibling of the mid-sequence test: one logged retry and one sleep for the 503, then
        // an immediate return on the rate-limited second attempt.
        use crate::backends::retry_async;
        use crate::errors::Error;
        use std::cell::{Cell, RefCell};
        let calls = Cell::new(0u32);
        let backoffs = RefCell::new(Vec::<u64>::new());
        let slept = Cell::new(0u32);
        let res: crate::errors::Result<i32> = retry_async(
            5,
            crate::backends::common::DEFAULT_RETRY_BASE_DELAY,
            crate::backends::common::DEFAULT_RETRY_MAX_DELAY,
            || {
                calls.set(calls.get() + 1);
                let first = calls.get() == 1;
                async move {
                    if first {
                        Err(Error::HttpStatus {
                            status: 503,
                            url: "u".into(),
                        })
                    } else {
                        Err(Error::RateLimited {
                            status: 429,
                            url: "u".into(),
                            reset_at: None,
                            retry_after: None,
                        })
                    }
                }
            },
            |_e, b| backoffs.borrow_mut().push(b),
            |_b| {
                slept.set(slept.get() + 1);
                async {}
            },
        )
        .await;
        assert!(
            matches!(res, Err(Error::RateLimited { status: 429, .. })),
            "the async loop must return the rate-limit error from the second attempt, got {:?}",
            res
        );
        assert_eq!(calls.get(), 2);
        assert_eq!(*backoffs.borrow(), vec![100]);
        assert_eq!(slept.get(), 1, "only the retryable failure may sleep");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn send_async_issues_exactly_one_request_for_a_rate_limited_response() {
        // Async sibling of `send_issues_exactly_one_request_for_a_rate_limited_response`: the async
        // lane must not re-issue a request against a spent quota either.
        let (base, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let res = crate::backends::send_async(&base, HeaderMap::new(), &fast_retry_config(3)).await;
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::RateLimited { status: 403, .. })
            ),
            "async: a 403 with a spent quota must surface as RateLimited"
        );
        assert_eq!(
            hits_of(&hits),
            1,
            "async: a rate-limited response must not be retried"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn send_async_spends_the_whole_budget_for_a_server_error() {
        // Async control: a 500 still spends the full budget (1 + 3 requests), so the async
        // short-circuit is proven to be rate-limit specific.
        let (base, hits) = counting_stub("500 Internal Server Error", "");
        let res = crate::backends::send_async(&base, HeaderMap::new(), &fast_retry_config(3)).await;
        assert!(matches!(
            res,
            Err(crate::errors::Error::HttpStatus { status: 500, .. })
        ));
        assert_eq!(
            hits_of(&hits),
            4,
            "async: a non-rate-limited failure must still consume the retry budget"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn send_async_still_retries_a_plain_403_authorization_failure() {
        // Async control on the status-vs-variant distinction: a bare 403 is `Unauthorized` and is
        // still retried.
        let (base, hits) = counting_stub("403 Forbidden", "");
        let res = crate::backends::send_async(&base, HeaderMap::new(), &fast_retry_config(3)).await;
        assert!(matches!(
            res,
            Err(crate::errors::Error::Unauthorized { status: 403, .. })
        ));
        assert_eq!(
            hits_of(&hits),
            4,
            "async: a plain 403 authorization failure still consumes the retry budget"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn run_paginated_async_issues_one_request_for_a_rate_limited_first_page() {
        // The async listing driver inherits the short-circuit through `send_async`.
        let (base, hits) = counting_stub("403 Forbidden", "x-ratelimit-remaining: 0\r\n");
        let res = crate::backends::run_paginated_async(
            int_page(format!("{base}/p1")),
            &fast_retry_config(3),
        )
        .await;
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::RateLimited { status: 403, .. })
            ),
            "async: the paginated driver must surface RateLimited"
        );
        assert_eq!(
            hits_of(&hits),
            1,
            "async: a rate-limited listing page must not be retried"
        );
    }
}