day-part-http 0.6.1

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The portable client (docs/http.md "Client").
//!
//! A [`Client`] owns the policy that must behave the same on every backend: following redirects,
//! answering 401 and 407 challenges, the cookie jar, public-key pins, multipart bodies, total-time
//! limits, and backpressure on response bodies. Beneath it a [`Transport`] performs one exchange
//! at a time through the platform's own stack, which keeps TLS, trust stores, proxies, HTTP/2 and
//! 3, and NTLM with the OS.
//!
//! Every asynchronous operation has a callback form (`*_async`) and a future form (`*_future`),
//! per docs/async.md rule 3. Callbacks run on the thread the platform reports on; dropping a
//! future, a [`Body`] or a [`WebSocket`] cancels what it stands for.

use std::collections::VecDeque;
use std::future::Future;
use std::io::{Cursor, Read};
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use day_async::TimerId;
use sha2::{Digest, Sha256};

use crate::{HttpError, Method, Request, Response};

// ---------------------------------------------------------------------------
// Client
// ---------------------------------------------------------------------------

/// Body chunks (or WebSocket messages) a reader keeps in hand, queued plus granted, before it
/// stops asking the transport for more. A slow reader therefore slows the socket.
const WINDOW: u32 = 4;
/// The idle bound when neither the request nor the client sets one.
pub(crate) const DEFAULT_IDLE: Duration = Duration::from_secs(30);
const DEFAULT_QUESTION_TIMEOUT: Duration = Duration::from_secs(120);
/// Credentials offered to one request before its 401 is delivered as the response.
const MAX_AUTH_ATTEMPTS: u32 = 3;

/// Lock, riding out poisoning: every state here is plain data whose invariants a panicking
/// holder cannot break halfway.
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|p| p.into_inner())
}

/// A request body, as the builder recorded it.
#[derive(Clone, Debug, Default)]
pub(crate) enum Payload {
    #[default]
    Empty,
    Bytes(Arc<Vec<u8>>),
    File(PathBuf),
    Stream(SharedReader, Option<u64>),
    Form(Form),
}

/// An upload progress observer: `(bytes sent, total)`.
#[derive(Clone)]
pub(crate) struct ProgressFn(pub(crate) Arc<dyn Fn(u64, Option<u64>) + Send + Sync>);

impl std::fmt::Debug for ProgressFn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ProgressFn")
    }
}

/// Whether a client follows redirects.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Redirects {
    /// Follow at most this many, then fail with [`HttpError::TooManyRedirects`].
    Follow(u32),
    /// Deliver each redirect response as the response.
    Never,
}

impl Default for Redirects {
    fn default() -> Self {
        Redirects::Follow(10)
    }
}

/// A redirect the client is about to follow, as [`ClientBuilder::on_redirect`] sees it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hop {
    pub status: u16,
    pub from: String,
    pub to: String,
    /// The method the next request uses: a 303 turns anything but HEAD into GET, and a 301 or
    /// 302 turns a POST into a GET.
    pub method: String,
    /// Redirects already followed on the way here.
    pub followed: u32,
}

/// An HTTP authentication challenge, as [`ClientBuilder::on_challenge`] sees it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Challenge {
    pub url: String,
    pub host: String,
    pub port: u16,
    pub realm: Option<String>,
    pub scheme: Scheme,
    /// A proxy asked (407), not the origin server.
    pub proxy: bool,
    /// Credentials this request already offered that the server refused.
    pub previous_failures: u32,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Resolution {
    Default,
    Follow,
    Stop,
    Credential { user: String, password: String },
    Bearer(String),
    Cancel,
    Accept,
    Reject,
}

/// The half of a question a handler answers. Dropping it unanswered takes the default.
struct ReplyGrip {
    flight: Weak<Flight>,
    ask: u64,
    answered: bool,
}

impl ReplyGrip {
    fn answer(mut self, resolution: Resolution) {
        self.answered = true;
        if let Some(flight) = self.flight.upgrade() {
            flight.resolve(self.ask, resolution);
        }
    }
}

impl Drop for ReplyGrip {
    fn drop(&mut self) {
        if let (false, Some(flight)) = (self.answered, self.flight.upgrade()) {
            flight.resolve(self.ask, Resolution::Default);
        }
    }
}

/// Answers a redirect question. Dropping it unanswered follows the redirect. It is `Send`, so a
/// handler may keep it and answer later from any thread; the exchange waits meanwhile, up to the
/// client's question timeout.
pub struct RedirectReply(ReplyGrip);

impl RedirectReply {
    /// Follow the redirect.
    pub fn follow(self) {
        self.0.answer(Resolution::Follow)
    }

    /// Do not follow: the redirect response is the response.
    pub fn stop(self) {
        self.0.answer(Resolution::Stop)
    }

    /// Abandon the request; it fails with [`HttpError::Cancelled`].
    pub fn cancel(self) {
        self.0.answer(Resolution::Cancel)
    }
}

impl std::fmt::Debug for RedirectReply {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("RedirectReply")
    }
}

/// Answers a challenge. Dropping it unanswered delivers the 401 (or 407) as the response.
pub struct ChallengeReply(ReplyGrip);

impl ChallengeReply {
    /// Answer with a user name and password. The client writes Basic or Digest to match the
    /// challenge; a platform stack answering NTLM or Negotiate itself takes them as they are.
    pub fn credential(self, user: impl Into<String>, password: impl Into<String>) {
        self.0.answer(Resolution::Credential {
            user: user.into(),
            password: password.into(),
        })
    }

    /// Answer with a bearer token.
    pub fn bearer(self, token: impl Into<String>) {
        self.0.answer(Resolution::Bearer(token.into()))
    }

    /// Offer nothing: the challenge response is the response.
    pub fn default_handling(self) {
        self.0.answer(Resolution::Default)
    }

    /// Abandon the request; it fails with [`HttpError::Cancelled`].
    pub fn cancel(self) {
        self.0.answer(Resolution::Cancel)
    }
}

impl std::fmt::Debug for ChallengeReply {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ChallengeReply")
    }
}

/// Answers a server trust question. Dropping it unanswered keeps the platform's verdict.
pub struct TrustReply(ReplyGrip);

impl TrustReply {
    /// Trust the server, whatever the platform concluded.
    pub fn accept(self) {
        self.0.answer(Resolution::Accept)
    }

    /// Refuse the server; the request fails with [`HttpError::Tls`].
    pub fn reject(self) {
        self.0.answer(Resolution::Reject)
    }

    /// Keep the platform's verdict.
    pub fn default_handling(self) {
        self.0.answer(Resolution::Default)
    }
}

impl std::fmt::Debug for TrustReply {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("TrustReply")
    }
}

type RedirectHandler = dyn Fn(&Hop, RedirectReply) + Send + Sync;
type ChallengeHandler = dyn Fn(&Challenge, ChallengeReply) + Send + Sync;
type TrustHandler = dyn Fn(&ServerTrust, TrustReply) + Send + Sync;

/// Which servers a client trusts beyond the platform's own evaluation.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Trust {
    pins: Vec<(String, Option<[u8; 32]>)>,
}

impl Trust {
    /// The platform's evaluation alone.
    pub fn system() -> Trust {
        Trust::default()
    }

    /// Require `host`'s certificate chain to hold a key whose SHA-256 is `pin`, written
    /// `sha256/<base64>` as [`ServerTrust::pins`] prints it. `*.example.com` covers every
    /// subdomain. Several pins for one host accept any of them, which is how a key rotation
    /// ships. A malformed pin matches nothing, so its host fails closed.
    pub fn pin(mut self, host: impl Into<String>, pin: &str) -> Trust {
        self.pins
            .push((host.into().to_ascii_lowercase(), parse_pin(pin)));
        self
    }

    /// Whether any pin is configured.
    pub fn is_empty(&self) -> bool {
        self.pins.is_empty()
    }

    fn pins_for(&self, host: &str) -> Option<Vec<Option<[u8; 32]>>> {
        let host = host.to_ascii_lowercase();
        let pins: Vec<_> = self
            .pins
            .iter()
            .filter(|(pattern, _)| host_matches(pattern, &host))
            .map(|(_, pin)| *pin)
            .collect();
        (!pins.is_empty()).then_some(pins)
    }
}

fn host_matches(pattern: &str, host: &str) -> bool {
    match pattern.strip_prefix("*.") {
        Some(base) => {
            host.len() > base.len() + 1
                && host.ends_with(base)
                && host.as_bytes()[host.len() - base.len() - 1] == b'.'
        }
        None => pattern == host,
    }
}

/// A client certificate identity, presented when a server asks for one.
#[derive(Clone)]
pub struct Identity {
    pub(crate) pkcs12: Arc<Vec<u8>>,
    pub(crate) password: String,
}

impl Identity {
    /// A PKCS#12 archive (`.p12`, `.pfx`) holding the certificate and its private key.
    pub fn pkcs12(der: Vec<u8>, password: impl Into<String>) -> Identity {
        Identity {
            pkcs12: Arc::new(der),
            password: password.into(),
        }
    }
}

impl std::fmt::Debug for Identity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Identity")
            .field("pkcs12_bytes", &self.pkcs12.len())
            .finish_non_exhaustive()
    }
}

/// Where a client keeps cookies.
#[derive(Clone, Debug)]
pub enum Cookies {
    /// The platform's store: `HTTPCookieStorage` on Apple, the browser's jar on the web. Where
    /// the platform offers none to share ([`Capabilities::platform_cookies`]), an in-memory
    /// [`CookieJar`].
    Platform,
    /// This jar, which the client reads and writes itself.
    Jar(Arc<CookieJar>),
    /// Send none and keep none.
    Off,
}

impl Cookies {
    /// A fresh in-memory jar.
    pub fn jar() -> Cookies {
        Cookies::Jar(Arc::new(CookieJar::new()))
    }

    /// A jar persisted to `file`: cookies with an expiry survive a relaunch.
    pub fn jar_at(file: impl Into<PathBuf>) -> Cookies {
        Cookies::Jar(Arc::new(CookieJar::open(file)))
    }
}

impl Default for Cookies {
    /// The platform store on Apple and the web, an in-memory jar elsewhere.
    fn default() -> Self {
        if cfg!(any(
            target_os = "macos",
            target_os = "ios",
            target_arch = "wasm32"
        )) {
            Cookies::Platform
        } else {
            Cookies::jar()
        }
    }
}

/// Whether a client keeps an HTTP cache.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cache {
    /// The platform's cache with these capacities in bytes, where it has one
    /// ([`Capabilities::platform_cache`]).
    Platform { memory: u64, disk: u64 },
    /// No cache.
    Off,
}

impl Cache {
    /// The platform cache at 8 MiB in memory and 64 MiB on disk.
    pub fn platform() -> Cache {
        Cache::Platform {
            memory: 8 << 20,
            disk: 64 << 20,
        }
    }
}

impl Default for Cache {
    fn default() -> Self {
        Cache::platform()
    }
}

/// Configures a [`Client`].
pub struct ClientBuilder {
    timeout_idle: Duration,
    timeout_total: Option<Duration>,
    redirects: Redirects,
    on_redirect: Option<Arc<RedirectHandler>>,
    on_challenge: Option<Arc<ChallengeHandler>>,
    on_server_trust: Option<Arc<TrustHandler>>,
    trust: Trust,
    identity: Option<Identity>,
    cookies: Cookies,
    cache: Cache,
    headers: Vec<(String, String)>,
    max_per_host: Option<u32>,
    wait_for_connectivity: bool,
    question_timeout: Duration,
    transport: Option<Arc<dyn Transport>>,
    session: Option<crate::Session>,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        ClientBuilder {
            timeout_idle: DEFAULT_IDLE,
            timeout_total: None,
            redirects: Redirects::default(),
            on_redirect: None,
            on_challenge: None,
            on_server_trust: None,
            trust: Trust::system(),
            identity: None,
            cookies: Cookies::default(),
            cache: Cache::default(),
            headers: Vec::new(),
            max_per_host: None,
            wait_for_connectivity: false,
            question_timeout: DEFAULT_QUESTION_TIMEOUT,
            transport: None,
            session: None,
        }
    }
}

impl std::fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("redirects", &self.redirects)
            .field("cookies", &self.cookies)
            .field("cache", &self.cache)
            .finish_non_exhaustive()
    }
}

impl ClientBuilder {
    /// How long an exchange may sit without progress, for requests that set no
    /// [`Request::timeout`]. Default 30 s.
    pub fn timeout_idle(mut self, limit: Duration) -> Self {
        self.timeout_idle = limit;
        self
    }

    /// How long a whole request may take, redirects, challenges and body included. Default
    /// none. A request's own [`Request::timeout_total`] wins.
    pub fn timeout_total(mut self, limit: Duration) -> Self {
        self.timeout_total = Some(limit);
        self
    }

    /// Whether to follow redirects. Default [`Redirects::Follow`]`(10)`.
    pub fn redirects(mut self, redirects: Redirects) -> Self {
        self.redirects = redirects;
        self
    }

    /// Ask before following each redirect. Needs [`Capabilities::manual_redirects`]; where the
    /// platform follows redirects itself, requests from this client fail with
    /// [`HttpError::Unsupported`].
    pub fn on_redirect(
        mut self,
        handler: impl Fn(&Hop, RedirectReply) + Send + Sync + 'static,
    ) -> Self {
        self.on_redirect = Some(Arc::new(handler));
        self
    }

    /// Answer authentication challenges. Without a handler a 401 or 407 is delivered as the
    /// response.
    pub fn on_challenge(
        mut self,
        handler: impl Fn(&Challenge, ChallengeReply) + Send + Sync + 'static,
    ) -> Self {
        self.on_challenge = Some(Arc::new(handler));
        self
    }

    /// Public-key pins, checked on top of the platform's evaluation.
    pub fn trust(mut self, trust: Trust) -> Self {
        self.trust = trust;
        self
    }

    /// Decide on servers the platform does not trust, or confirm the ones it does. Needs
    /// [`Capabilities::server_trust`].
    pub fn on_server_trust(
        mut self,
        handler: impl Fn(&ServerTrust, TrustReply) + Send + Sync + 'static,
    ) -> Self {
        self.on_server_trust = Some(Arc::new(handler));
        self
    }

    /// Present this identity when a server asks for a client certificate. Needs
    /// [`Capabilities::client_identity`].
    pub fn identity(mut self, identity: Identity) -> Self {
        self.identity = Some(identity);
        self
    }

    /// Where to keep cookies. Default [`Cookies::default`].
    pub fn cookies(mut self, cookies: Cookies) -> Self {
        self.cookies = cookies;
        self
    }

    /// Whether to keep an HTTP cache. Default [`Cache::platform`].
    pub fn cache(mut self, cache: Cache) -> Self {
        self.cache = cache;
        self
    }

    /// A header sent with every request that does not set it itself.
    pub fn header(mut self, name: &str, value: &str) -> Self {
        self.headers.push((name.to_string(), value.to_string()));
        self
    }

    /// The `User-Agent` sent with every request.
    pub fn user_agent(self, agent: &str) -> Self {
        self.header("User-Agent", agent)
    }

    /// At most this many connections to one host, where the platform lets an app choose.
    pub fn max_per_host(mut self, limit: u32) -> Self {
        self.max_per_host = Some(limit.max(1));
        self
    }

    /// Wait for a usable network instead of failing at once, where the platform can
    /// ([`Capabilities::wait_for_connectivity`]).
    pub fn wait_for_connectivity(mut self, wait: bool) -> Self {
        self.wait_for_connectivity = wait;
        self
    }

    /// How long a handler may hold a question before its default answer is taken. Default two
    /// minutes.
    pub fn question_timeout(mut self, limit: Duration) -> Self {
        self.question_timeout = limit;
        self
    }

    /// Route through an isolated session. By default clients follow Session::global().
    /// An explicit `transport` overrides provider/interception selection for this client.
    pub fn session(mut self, session: crate::Session) -> Self {
        self.session = Some(session);
        self
    }

    /// Perform exchanges through this transport instead of the platform's: a test double, or
    /// an app's own stack.
    pub fn transport(mut self, transport: impl Transport) -> Self {
        self.transport = Some(Arc::new(transport));
        self
    }

    /// The client.
    pub fn build(self) -> Client {
        let caps = match &self.transport {
            Some(t) => t.capabilities(),
            None => crate::platform_capabilities(),
        };
        let cookies = match self.cookies {
            Cookies::Platform if !caps.platform_cookies => Cookies::jar(),
            other => other,
        };
        let config = TransportConfig {
            timeout_idle: self.timeout_idle,
            timeout_total: self.timeout_total,
            platform_cookies: matches!(cookies, Cookies::Platform),
            platform_cache: match self.cache {
                Cache::Platform { memory, disk } => Some((memory, disk)),
                Cache::Off => None,
            },
            redirects: self.redirects,
            ask_auth: self.on_challenge.is_some(),
            ask_trust: self.on_server_trust.is_some() || !self.trust.is_empty(),
            identity: self.identity,
            max_per_host: self.max_per_host,
            wait_for_connectivity: self.wait_for_connectivity,
        };
        let session = if self.transport.is_some() {
            None
        } else {
            Some(self.session.unwrap_or_else(crate::Session::global))
        };
        let transport = match self.transport {
            Some(t) => t,
            None => crate::platform_transport(&config),
        };
        Client {
            inner: Arc::new(ClientInner {
                session,
                config,
                clock: None,
                provider_cache: Arc::new(Mutex::new(None)),
                fallback_cookies: Cookies::jar(),
                caps: transport.capabilities(),
                transport,
                timeout_idle: self.timeout_idle,
                timeout_total: self.timeout_total,
                redirects: self.redirects,
                on_redirect: self.on_redirect,
                on_challenge: self.on_challenge,
                on_server_trust: self.on_server_trust,
                trust: self.trust,
                cookies,
                headers: self.headers,
                question_timeout: self.question_timeout,
                credentials: Arc::new(Mutex::new(Vec::new())),
            }),
        }
    }
}

/// An HTTP client: policy shared by every request it sends, over the platform's transport.
/// Cloning is cheap and shares the policy, the cookies and the connections.
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
}

type ProviderCache = Arc<Mutex<Option<(u64, Arc<dyn Transport>)>>>;
type Credentials = Arc<Mutex<Vec<(String, Option<String>, Resolution)>>>;

#[derive(Clone)]
struct ClientInner {
    session: Option<crate::Session>,
    config: TransportConfig,
    clock: Option<Arc<dyn crate::simulation::Clock>>,
    provider_cache: ProviderCache,
    fallback_cookies: Cookies,
    transport: Arc<dyn Transport>,
    caps: Capabilities,
    timeout_idle: Duration,
    timeout_total: Option<Duration>,
    redirects: Redirects,
    on_redirect: Option<Arc<RedirectHandler>>,
    on_challenge: Option<Arc<ChallengeHandler>>,
    on_server_trust: Option<Arc<TrustHandler>>,
    trust: Trust,
    cookies: Cookies,
    headers: Vec<(String, String)>,
    question_timeout: Duration,
    /// Credentials that worked, by origin and realm, offered again without asking.
    credentials: Credentials,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("capabilities", &self.inner.caps)
            .field("redirects", &self.inner.redirects)
            .field("cookies", &self.inner.cookies)
            .finish_non_exhaustive()
    }
}

impl Default for Client {
    fn default() -> Self {
        Client::new()
    }
}

impl Client {
    /// A client with the default policy over the platform's transport.
    pub fn new() -> Client {
        ClientBuilder::default().build()
    }

    /// Configure a client.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// What this client's transport can do.
    pub fn capabilities(&self) -> Capabilities {
        self.inner.current_transport().capabilities()
    }

    /// Send `request`; `on_head` receives the response head with its unread [`Body`], or the
    /// failure. It runs on the thread the platform reports on.
    pub fn send_async(
        &self,
        request: Request,
        on_head: impl FnOnce(Result<Streaming, HttpError>) + Send + 'static,
    ) -> InFlight {
        InFlight(Arc::downgrade(&Flight::start(
            &self.inner,
            request,
            Box::new(on_head),
        )))
    }

    /// Send `request` and await the response head. Dropping the future cancels the request.
    pub fn send_future(&self, request: Request) -> Sending {
        let (tx, rx) = day_async::oneshot();
        let flight = Flight::start(&self.inner, request, Box::new(move |r| tx.send(r)));
        Sending {
            flight,
            rx,
            done: false,
        }
    }

    /// Buffer at most `max_bytes`, cancelling if either Content-Length or the actual streamed
    /// body exceeds it. The bound applies to decoded response bytes delivered by the transport.
    pub async fn fetch_limited_future(
        &self,
        request: Request,
        max_bytes: usize,
    ) -> Result<Response, HttpError> {
        self.fetch_limited_with_progress_future(request, max_bytes, |_, _| {})
            .await
    }

    /// Bounded download with `(received, total)` observations on the polling thread.
    /// Unknown or encoded representation lengths report None, never a guessed fraction.
    /// Observer calls occur at connection start, response headers, and each body chunk;
    /// UI consumers should throttle their presentation updates.
    pub async fn fetch_limited_with_progress_future(
        &self,
        request: Request,
        max_bytes: usize,
        mut progress: impl FnMut(u64, Option<u64>),
    ) -> Result<Response, HttpError> {
        progress(0, None);
        let is_head = matches!(request.method, Method::Head);
        let streaming = self.send_future(request).await?;
        // HEAD/304 can advertise the representation size despite carrying no body.
        let bodyless = is_head || matches!(streaming.status(), 204 | 304);
        if !bodyless
            && streaming
                .expected_length()
                .is_some_and(|n| n > max_bytes as u64)
        {
            return Err(HttpError::BodyTooLarge { limit: max_bytes });
        }
        let (head, mut body) = streaming.into_parts();
        let encoded = head.headers.iter().any(|(k, v)| {
            k.eq_ignore_ascii_case("content-encoding") && !v.eq_ignore_ascii_case("identity")
        });
        let total = if bodyless || encoded {
            None
        } else {
            head.expected_length.filter(|n| *n > 0)
        };
        progress(0, total);
        let mut bytes = Vec::new();
        while let Some(chunk) = body.next().await {
            let chunk = chunk?;
            if bytes.len().saturating_add(chunk.len()) > max_bytes {
                return Err(HttpError::BodyTooLarge { limit: max_bytes });
            }
            bytes.extend_from_slice(&chunk);
            let received = bytes.len() as u64;
            progress(received, total.filter(|n| received <= *n));
        }
        Ok(Response::assemble(head, bytes, body.metrics()))
    }

    /// Send `request` and read its whole body into memory. For large bodies use
    /// [`Client::send_async`] and read the [`Body`] in chunks.
    pub fn fetch_async(
        &self,
        request: Request,
        on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static,
    ) -> InFlight {
        InFlight(Arc::downgrade(&Flight::start(
            &self.inner,
            request,
            Box::new(move |head| match head {
                Ok(streaming) => streaming.collect_async(on_done),
                Err(e) => on_done(Err(e)),
            }),
        )))
    }

    /// Send `request` and await the whole response. Dropping the future cancels the request.
    pub fn fetch_future(&self, request: Request) -> Fetching {
        let (tx, rx) = day_async::oneshot();
        let flight = Flight::start(
            &self.inner,
            request,
            Box::new(move |head| match head {
                Ok(streaming) => streaming.collect_async(move |r| tx.send(r)),
                Err(e) => tx.send(Err(e)),
            }),
        );
        Fetching {
            flight,
            rx,
            done: false,
        }
    }

    /// [`Client::fetch_async`], with a closure that cancels the request.
    #[cfg_attr(target_os = "windows", allow(dead_code))]
    pub(crate) fn fetch_cancellable(
        &self,
        request: Request,
        on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static,
    ) -> Box<dyn FnOnce() + Send> {
        let flight = Flight::start(
            &self.inner,
            request,
            Box::new(move |head| match head {
                Ok(streaming) => streaming.collect_async(on_done),
                Err(e) => on_done(Err(e)),
            }),
        );
        Box::new(move || flight.cancel())
    }

    /// Open a WebSocket (`ws://` or `wss://`); `on_open` receives it after the handshake, or the
    /// failure.
    pub fn websocket_async(
        &self,
        request: Request,
        on_open: impl FnOnce(Result<WebSocket, HttpError>) + Send + 'static,
    ) {
        WsShared::open(&self.inner, request, Box::new(on_open));
    }

    /// Open a WebSocket and await the handshake. Dropping the future abandons the connection.
    pub fn websocket_future(&self, request: Request) -> Connecting {
        let (tx, rx) = day_async::oneshot();
        let shared = WsShared::open(&self.inner, request, Box::new(move |r| tx.send(r)));
        Connecting {
            shared,
            rx,
            done: false,
        }
    }

    /// The cookies this client would send, from its jar or the platform's store.
    pub fn cookies(&self) -> Vec<Cookie> {
        match &self.inner.cookies {
            Cookies::Jar(jar) => jar.cookies(),
            Cookies::Platform => {
                let transport = self.inner.current_transport();
                if transport.capabilities().platform_cookies {
                    transport.cookies()
                } else if let Cookies::Jar(jar) = &self.inner.fallback_cookies {
                    jar.cookies()
                } else {
                    Vec::new()
                }
            }
            Cookies::Off => Vec::new(),
        }
    }

    /// Forget every cookie in this client's jar or the platform's store.
    pub fn clear_cookies(&self) {
        match &self.inner.cookies {
            Cookies::Jar(jar) => jar.clear(),
            Cookies::Platform => {
                self.inner.current_transport().clear_cookies();
                if let Cookies::Jar(jar) = &self.inner.fallback_cookies {
                    jar.clear();
                }
            }
            Cookies::Off => {}
        }
    }

    /// Empty the platform cache this client uses.
    pub fn clear_cache(&self) {
        self.inner.current_transport().clear_cache();
    }
}

impl ClientInner {
    fn current_transport(&self) -> Arc<dyn Transport> {
        self.session
            .as_ref()
            .map(|s| s.provider_transport(&self.config, &self.provider_cache))
            .unwrap_or_else(|| self.transport.clone())
    }

    fn snapshot(&self, request: &Request) -> Arc<Self> {
        let mut inner = self.clone();
        match &self.session {
            Some(session) => {
                let selected = session.resolve(
                    &self.config,
                    &self.provider_cache,
                    &request.url,
                    request.method.as_str(),
                );
                inner.transport = selected.transport;
                inner.clock = selected.clock;
            }
            None => inner.transport = crate::Session::global().observe(self.transport.clone()),
        }
        inner.caps = inner.transport.capabilities();
        if matches!(inner.cookies, Cookies::Platform) && !inner.caps.platform_cookies {
            inner.cookies = self.fallback_cookies.clone();
        }
        Arc::new(inner)
    }
    fn prepare(&self, request: &Request, websocket: bool) -> Result<Prepared, HttpError> {
        let bad = || HttpError::BadUrl(request.url.clone());
        let written = request.url.trim();
        let url = match url::Url::parse(written) {
            Ok(url) => Some(url),
            // A page resolves a relative reference against its own address, which only the
            // browser knows, so the request goes out as written.
            #[cfg(target_arch = "wasm32")]
            Err(url::ParseError::RelativeUrlWithoutBase) if !written.is_empty() => None,
            Err(_) => return Err(bad()),
        };
        if let Some(url) = &url {
            let scheme_ok = if websocket {
                matches!(url.scheme(), "ws" | "wss")
            } else {
                matches!(url.scheme(), "http" | "https")
            };
            if !scheme_ok || url.host_str().is_none() {
                return Err(bad());
            }
        }
        let mut headers: Vec<(String, String)> = self
            .headers
            .iter()
            .filter(|(k, _)| !has_header(&request.headers, k))
            .cloned()
            .collect();
        headers.extend(request.headers.iter().cloned());
        if let Cookies::Jar(jar) = &self.cookies
            && let Some(url) = &url
            && !has_header(&headers, "cookie")
            && let Some(cookie) = jar.header_for(url)
        {
            headers.push(("Cookie".into(), cookie));
        }
        let body = prepare_body(&request.payload, &mut headers)?;
        Ok(Prepared {
            method: request.method.as_str().to_string(),
            url: url.map_or_else(|| written.to_string(), |url| url.to_string()),
            headers,
            body,
            timeout_idle: request.timeout.unwrap_or(self.timeout_idle),
            allow_expensive: request.allow_expensive,
            allow_constrained: request.allow_constrained,
            cache: request.cache,
            priority: request.priority,
            protocols: request.protocols.clone(),
        })
    }

    fn cached_credential(&self, origin: &str, realm: &Option<String>) -> Option<Resolution> {
        lock(&self.credentials)
            .iter()
            .find(|(o, r, _)| o == origin && r == realm)
            .map(|(_, _, c)| c.clone())
    }
}

fn has_header(headers: &[(String, String)], name: &str) -> bool {
    headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(name))
}

fn prepare_body(
    payload: &Payload,
    headers: &mut Vec<(String, String)>,
) -> Result<PreparedBody, HttpError> {
    let io = |e: std::io::Error| HttpError::Io(e.to_string());
    Ok(match payload {
        Payload::Empty => PreparedBody::Empty,
        Payload::Bytes(bytes) => PreparedBody::Bytes(bytes.clone()),
        Payload::File(path) => PreparedBody::File {
            len: std::fs::metadata(path).map_err(io)?.len(),
            path: path.clone(),
        },
        Payload::Stream(reader, len) => PreparedBody::Stream {
            reader: reader.clone(),
            len: *len,
        },
        Payload::Form(form) => {
            let (reader, len) = form.reader().map_err(io)?;
            if !has_header(headers, "content-type") {
                headers.push(("Content-Type".into(), form.content_type()));
            }
            PreparedBody::Stream {
                reader: SharedReader::new(reader),
                len: Some(len),
            }
        }
    })
}

/// The request that follows a redirect (RFC 9110 §15.4): the method rewrite, and no credentials
/// or cookies carried to another origin.
fn redirect_request(previous: &Request, status: u16, from: &url::Url, to: &url::Url) -> Request {
    let mut next = previous.clone();
    next.url = to.to_string();
    let rewrite = (status == 303 && previous.method != Method::Head)
        || (matches!(status, 301 | 302) && previous.method == Method::Post);
    if rewrite {
        next.method = Method::Get;
        next.payload = Payload::Empty;
        next.headers.retain(|(k, _)| {
            !k.eq_ignore_ascii_case("content-type") && !k.eq_ignore_ascii_case("content-length")
        });
    }
    if from.origin() != to.origin() {
        next.headers.retain(|(k, _)| {
            !k.eq_ignore_ascii_case("authorization")
                && !k.eq_ignore_ascii_case("proxy-authorization")
                && !k.eq_ignore_ascii_case("cookie")
        });
    }
    next
}

fn origin_of(url: &url::Url) -> String {
    url.origin().ascii_serialization()
}

type HeadCallback = Box<dyn FnOnce(Result<Streaming, HttpError>) + Send>;
type ItemCallback<T> = Box<dyn FnMut(Option<Result<T, HttpError>>) -> bool + Send>;

/// A queue between a transport and one reader, granting demand as the reader takes items.
struct Inbox<T> {
    queue: VecDeque<T>,
    /// Demand granted and not yet used.
    outstanding: u32,
    /// The terminal outcome, delivered once the queue is empty.
    finished: Option<Result<(), HttpError>>,
    /// The terminal outcome was delivered.
    taken: bool,
    paused: bool,
    waker: Option<Waker>,
    callback: Option<ItemCallback<T>>,
    /// A thread holds the callback and is delivering.
    draining: bool,
}

enum Notify {
    Wake(Waker),
    Drain,
}

impl<T> Inbox<T> {
    fn new() -> Self {
        Inbox {
            queue: VecDeque::new(),
            outstanding: 0,
            finished: None,
            taken: false,
            paused: false,
            waker: None,
            callback: None,
            draining: false,
        }
    }

    fn notify(&mut self) -> Option<Notify> {
        if self.callback.is_some() {
            Some(Notify::Drain)
        } else {
            self.waker.take().map(Notify::Wake)
        }
    }

    fn push(&mut self, item: T) -> Option<Notify> {
        self.outstanding = self.outstanding.saturating_sub(1);
        self.queue.push_back(item);
        self.notify()
    }

    fn finish(&mut self, outcome: Result<(), HttpError>) -> Option<Notify> {
        if self.finished.is_none() && !self.taken {
            self.finished = Some(outcome);
        }
        self.notify()
    }

    /// The next item to deliver: `Some(None)` is the clean end, `None` is nothing yet.
    fn take(&mut self) -> Option<Option<Result<T, HttpError>>> {
        if let Some(item) = self.queue.pop_front() {
            return Some(Some(Ok(item)));
        }
        if let Some(outcome) = self.finished.take() {
            self.taken = true;
            return Some(outcome.err().map(Err));
        }
        if self.taken {
            return Some(None);
        }
        None
    }

    /// More demand to grant, when the reader's hand runs low.
    fn refill(&mut self) -> Option<u32> {
        if self.paused || self.finished.is_some() || self.taken {
            return None;
        }
        let held = self.queue.len() as u32 + self.outstanding;
        if held > WINDOW / 2 {
            return None;
        }
        let more = WINDOW - held;
        self.outstanding += more;
        Some(more)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stage {
    Head,
    Body,
    Done,
}

enum Asked {
    Redirect {
        head: Head,
        next: Request,
    },
    Challenge {
        head: Head,
        parsed: ParsedChallenge,
        challenge: Challenge,
        url: url::Url,
    },
    NativeAuth(QuestionId),
    Trust(QuestionId),
}

enum PendingOp {
    Demand(u32),
    Answer(QuestionId, Answer),
}

enum Action {
    Demand(Arc<dyn Transfer>, u32),
    Answer(Arc<dyn Transfer>, QuestionId, Answer),
    Cancel(Arc<dyn Transfer>),
    StartHop,
    DeliverHead(HeadCallback, Box<Head>),
    HeadFailed(HeadCallback, HttpError),
    Wake(Waker),
    Drain,
    AskRedirect(Arc<RedirectHandler>, Hop, u64),
    AskChallenge(Arc<ChallengeHandler>, Challenge, u64),
    AskTrust(Arc<TrustHandler>, ServerTrust, u64),
    CancelTimer(TimerId),
    Progress(ProgressFn, u64, Option<u64>),
}

impl From<Notify> for Action {
    fn from(n: Notify) -> Action {
        match n {
            Notify::Wake(w) => Action::Wake(w),
            Notify::Drain => Action::Drain,
        }
    }
}

/// One request across its redirects and challenges.
struct Flight {
    client: Arc<ClientInner>,
    state: Mutex<FlightState>,
}

struct FlightState {
    request: Request,
    stage: Stage,
    /// Bumped for each new exchange, so late events from an abandoned one are ignored.
    generation: u64,
    transfer: Option<Arc<dyn Transfer>>,
    /// The current exchange reported its terminal event.
    exchange_over: bool,
    pending: Vec<PendingOp>,
    on_head: Option<HeadCallback>,
    inbox: Inbox<Vec<u8>>,
    received: u64,
    expected: Option<u64>,
    metrics: Option<Metrics>,
    redirects_followed: u32,
    auth_failures: u32,
    /// The handler declined a challenge the transport raised, so its 401 is the response.
    native_auth_declined: bool,
    /// Credentials offered on the current exchange, remembered once they work.
    offered: Option<(String, Option<String>, Resolution)>,
    asks: Vec<(u64, Asked, Option<TimerId>)>,
    next_ask: u64,
    total_timer: Option<TimerId>,
}

impl Flight {
    fn start(client: &Arc<ClientInner>, request: Request, on_head: HeadCallback) -> Arc<Flight> {
        let client = client.snapshot(&request);
        let total = request.timeout_total.or(client.timeout_total);
        // A handler the stack cannot consult, or pins it cannot check, must not be silently
        // skipped: such a request fails instead.
        let unsupported = (client.on_redirect.is_some()
            && !client.caps.manual_redirects
            && client.redirects != Redirects::Never)
            || ((!client.trust.is_empty() || client.on_server_trust.is_some())
                && !client.caps.server_trust)
            || (client.config.identity.is_some() && !client.caps.client_identity);
        let flight = Arc::new(Flight {
            client: client.clone(),
            state: Mutex::new(FlightState {
                request,
                stage: Stage::Head,
                generation: 0,
                transfer: None,
                exchange_over: false,
                pending: Vec::new(),
                on_head: Some(on_head),
                inbox: Inbox::new(),
                received: 0,
                expected: None,
                metrics: None,
                redirects_followed: 0,
                auth_failures: 0,
                native_auth_declined: false,
                offered: None,
                asks: Vec::new(),
                next_ask: 1,
                total_timer: None,
            }),
        });
        if unsupported {
            flight.fail_now(HttpError::Unsupported);
            return flight;
        }
        if let Some(total) = total {
            let weak = Arc::downgrade(&flight);
            let job = move || {
                if let Some(flight) = weak.upgrade() {
                    flight.fail_now(HttpError::Timeout);
                }
            };
            if let Some(clock) = &client.clock {
                clock.schedule(total, Box::new(job));
            } else {
                let timer = day_async::schedule(total, job);
                lock(&flight.state).total_timer = Some(timer);
            }
        }
        flight.start_exchange();
        flight
    }

    fn start_exchange(self: &Arc<Self>) {
        let (request, generation) = {
            let st = lock(&self.state);
            if st.stage == Stage::Done {
                return;
            }
            (st.request.clone(), st.generation)
        };
        let prepared = match self.client.prepare(&request, false) {
            Ok(p) => p,
            Err(e) => return self.fail_now(e),
        };
        let this = self.clone();
        let events: Events = Arc::new(move |event| this.on_event(generation, event));
        let transfer = self.client.transport.start(prepared, events);
        let mut actions = Vec::new();
        {
            let mut st = lock(&self.state);
            if st.generation == generation && !st.exchange_over && st.stage != Stage::Done {
                for op in std::mem::take(&mut st.pending) {
                    actions.push(match op {
                        PendingOp::Demand(n) => Action::Demand(transfer.clone(), n),
                        PendingOp::Answer(id, a) => Action::Answer(transfer.clone(), id, a),
                    });
                }
                st.transfer = Some(transfer);
            } else {
                actions.push(Action::Cancel(transfer));
            }
        }
        self.run(actions);
    }

    fn on_event(self: &Arc<Self>, generation: u64, event: Event) {
        let mut actions = Vec::new();
        {
            let mut st = lock(&self.state);
            if generation != st.generation || st.stage == Stage::Done {
                return;
            }
            match event {
                Event::Head(head) => self.head_arrived(&mut st, head, &mut actions),
                Event::Chunk(bytes) => {
                    // A head waiting on a redirect or challenge answer keeps its body too, in
                    // case the answer makes that response the response.
                    if st.stage == Stage::Body || parked(&st) {
                        st.received += bytes.len() as u64;
                        if let Some(n) = st.inbox.push(bytes) {
                            actions.push(n.into());
                        }
                    }
                }
                Event::Sent { sent, total } => {
                    if let Some(progress) = st.request.upload_progress.clone() {
                        actions.push(Action::Progress(progress, sent, total));
                    }
                }
                Event::Question(id, question) => self.question(&mut st, id, question, &mut actions),
                Event::Metrics(mut metrics) => {
                    metrics.redirects = st.redirects_followed;
                    st.metrics = Some(metrics);
                }
                Event::End => {
                    st.exchange_over = true;
                    st.transfer = None;
                    match st.stage {
                        Stage::Body => {
                            if let Some(n) = st.inbox.finish(Ok(())) {
                                actions.push(n.into());
                            }
                        }
                        // An empty body can end while its head waits on an answer.
                        Stage::Head if parked(&st) => {}
                        Stage::Head => fail(
                            &mut st,
                            HttpError::Io("the exchange ended without a response".into()),
                            &mut actions,
                        ),
                        Stage::Done => {}
                    }
                }
                Event::Failed(error) => {
                    st.exchange_over = true;
                    st.transfer = None;
                    fail(&mut st, error, &mut actions);
                }
            }
        }
        self.run(actions);
    }

    fn head_arrived(&self, st: &mut FlightState, head: Head, actions: &mut Vec<Action>) {
        let client = &self.client;
        let base = url::Url::parse(&head.url)
            .or_else(|_| url::Url::parse(&st.request.url))
            .ok();
        if let (Cookies::Jar(jar), Some(url)) = (&client.cookies, &base) {
            jar.store_all(url, head.headers_named("set-cookie"));
        }
        let status = head.status;

        if client.caps.manual_redirects
            && matches!(status, 301 | 302 | 303 | 307 | 308)
            && let Redirects::Follow(max) = client.redirects
            && let Some(from) = &base
            && let Some(to) = head.header("location").and_then(|l| from.join(l).ok())
            && matches!(to.scheme(), "http" | "https")
        {
            if st.redirects_followed >= max {
                return fail(st, HttpError::TooManyRedirects, actions);
            }
            let next = redirect_request(&st.request, status, from, &to);
            if let Some(handler) = client.on_redirect.clone() {
                let hop = Hop {
                    status,
                    from: from.to_string(),
                    to: to.to_string(),
                    method: next.method.as_str().to_string(),
                    followed: st.redirects_followed,
                };
                let ask = register(st, Asked::Redirect { head, next });
                actions.push(Action::AskRedirect(handler, hop, ask));
                return;
            }
            st.redirects_followed += 1;
            return replace_exchange(st, next, actions);
        }

        if matches!(status, 401 | 407)
            && !st.native_auth_declined
            && st.auth_failures < MAX_AUTH_ATTEMPTS
            && let Some(url) = base.clone()
        {
            let proxy = status == 407;
            let native = client.caps.auth_questions;
            let chosen = parse_challenges(&head.headers, proxy)
                .into_iter()
                .filter(|c| !(native && c.scheme.raised_natively()))
                .max_by_key(|c| match c.scheme {
                    Scheme::Digest => 3,
                    Scheme::Basic => 2,
                    Scheme::Bearer => 1,
                    _ => 0,
                });
            if let Some(parsed) = chosen {
                let realm = parsed.param("realm").map(str::to_string);
                let challenge = Challenge {
                    url: url.to_string(),
                    host: url.host_str().unwrap_or_default().to_string(),
                    port: url.port_or_known_default().unwrap_or(0),
                    realm: realm.clone(),
                    scheme: parsed.scheme.clone(),
                    proxy,
                    previous_failures: st.auth_failures,
                };
                if st.auth_failures == 0
                    && let Some(known) = client.cached_credential(&origin_of(&url), &realm)
                {
                    return answer_challenge(st, &parsed, &challenge, &url, known, head, actions);
                }
                if let Some(handler) = client.on_challenge.clone() {
                    let ask = register(
                        st,
                        Asked::Challenge {
                            head,
                            parsed,
                            challenge: challenge.clone(),
                            url,
                        },
                    );
                    actions.push(Action::AskChallenge(handler, challenge, ask));
                    return;
                }
            }
        }

        if let Some(offered) = st.offered.take()
            && !matches!(status, 401 | 407)
        {
            let mut known = lock(&client.credentials);
            known.retain(|(o, r, _)| !(o == &offered.0 && r == &offered.1));
            known.push(offered);
        }
        begin_body(st, head, actions);
    }

    fn question(
        &self,
        st: &mut FlightState,
        id: QuestionId,
        question: Question,
        actions: &mut Vec<Action>,
    ) {
        let client = &self.client;
        match question {
            Question::Auth(asked) => match client.on_challenge.clone() {
                Some(handler) if asked.previous_failures < MAX_AUTH_ATTEMPTS => {
                    let challenge = Challenge {
                        url: st.request.url.clone(),
                        host: asked.host,
                        port: asked.port,
                        realm: asked.realm,
                        scheme: asked.scheme,
                        proxy: asked.proxy,
                        previous_failures: asked.previous_failures,
                    };
                    let ask = register(st, Asked::NativeAuth(id));
                    actions.push(Action::AskChallenge(handler, challenge, ask));
                }
                _ => {
                    st.native_auth_declined = true;
                    answer(st, id, Answer::DefaultHandling, actions);
                }
            },
            Question::ServerTrust(trust) => {
                if let Some(pins) = client.trust.pins_for(&trust.host) {
                    let chain: Vec<[u8; 32]> =
                        trust.chain.iter().filter_map(|c| spki_sha256(c)).collect();
                    if !pins.iter().flatten().any(|p| chain.contains(p)) {
                        return answer(st, id, Answer::Reject, actions);
                    }
                    if trust.system_trusted {
                        return answer(st, id, Answer::Accept, actions);
                    }
                }
                match client.on_server_trust.clone() {
                    Some(handler) => {
                        let ask = register(st, Asked::Trust(id));
                        actions.push(Action::AskTrust(handler, trust, ask));
                    }
                    None => answer(st, id, Answer::DefaultHandling, actions),
                }
            }
        }
    }

    fn resolve(self: &Arc<Self>, ask: u64, resolution: Resolution) {
        let mut actions = Vec::new();
        {
            let mut st = lock(&self.state);
            let Some(index) = st.asks.iter().position(|(a, _, _)| *a == ask) else {
                return;
            };
            let (_, asked, timer) = st.asks.remove(index);
            if let Some(timer) = timer {
                actions.push(Action::CancelTimer(timer));
            }
            if st.stage != Stage::Done {
                self.apply(&mut st, asked, resolution, &mut actions);
            }
        }
        self.run(actions);
    }

    fn apply(
        &self,
        st: &mut FlightState,
        asked: Asked,
        resolution: Resolution,
        actions: &mut Vec<Action>,
    ) {
        match asked {
            Asked::Redirect { head, next } => match resolution {
                Resolution::Stop => begin_body(st, head, actions),
                Resolution::Cancel => fail(st, HttpError::Cancelled, actions),
                _ => {
                    st.redirects_followed += 1;
                    replace_exchange(st, next, actions);
                }
            },
            Asked::Challenge {
                head,
                parsed,
                challenge,
                url,
            } => answer_challenge(st, &parsed, &challenge, &url, resolution, head, actions),
            Asked::NativeAuth(id) => {
                let answer_with = match resolution {
                    Resolution::Credential { user, password } => {
                        Answer::Credential { user, password }
                    }
                    Resolution::Cancel => Answer::Cancel,
                    _ => {
                        st.native_auth_declined = true;
                        Answer::DefaultHandling
                    }
                };
                answer(st, id, answer_with, actions);
            }
            Asked::Trust(id) => {
                let answer_with = match resolution {
                    Resolution::Accept => Answer::Accept,
                    Resolution::Reject | Resolution::Cancel => Answer::Reject,
                    _ => Answer::DefaultHandling,
                };
                answer(st, id, answer_with, actions);
            }
        }
    }

    fn fail_now(self: &Arc<Self>, error: HttpError) {
        let mut actions = Vec::new();
        fail(&mut lock(&self.state), error, &mut actions);
        self.run(actions);
    }

    /// Abandon the request from the reader's side: nothing more is delivered.
    fn cancel(self: &Arc<Self>) {
        let mut actions = Vec::new();
        let (on_head, callback) = {
            let mut st = lock(&self.state);
            if st.stage == Stage::Done {
                return;
            }
            st.stage = Stage::Done;
            st.inbox.taken = true;
            st.inbox.finished = None;
            st.inbox.queue.clear();
            st.inbox.waker = None;
            teardown(&mut st, &mut actions);
            (st.on_head.take(), st.inbox.callback.take())
        };
        drop((on_head, callback));
        self.run(actions);
    }

    fn register_timer(self: &Arc<Self>, ask: u64) {
        let weak = Arc::downgrade(self);
        let timer = day_async::schedule(self.client.question_timeout, move || {
            if let Some(flight) = weak.upgrade() {
                flight.resolve(ask, Resolution::Default);
            }
        });
        let mut st = lock(&self.state);
        match st.asks.iter_mut().find(|(a, _, _)| *a == ask) {
            Some(entry) => entry.2 = Some(timer),
            None => day_async::unschedule(timer),
        }
    }

    fn grip(self: &Arc<Self>, ask: u64) -> ReplyGrip {
        ReplyGrip {
            flight: Arc::downgrade(self),
            ask,
            answered: false,
        }
    }

    fn run(self: &Arc<Self>, actions: Vec<Action>) {
        for action in actions {
            match action {
                Action::Demand(transfer, n) => transfer.demand(n),
                Action::Answer(transfer, id, answer) => transfer.answer(id, answer),
                Action::Cancel(transfer) => transfer.cancel(),
                Action::StartHop => self.start_exchange(),
                Action::DeliverHead(on_head, head) => on_head(Ok(Streaming {
                    head: *head,
                    body: Body {
                        flight: self.clone(),
                        handed_off: false,
                    },
                })),
                Action::HeadFailed(on_head, error) => on_head(Err(error)),
                Action::Wake(waker) => waker.wake(),
                Action::Drain => self.drain(),
                Action::AskRedirect(handler, hop, ask) => {
                    self.register_timer(ask);
                    handler(&hop, RedirectReply(self.grip(ask)));
                }
                Action::AskChallenge(handler, challenge, ask) => {
                    self.register_timer(ask);
                    handler(&challenge, ChallengeReply(self.grip(ask)));
                }
                Action::AskTrust(handler, trust, ask) => {
                    self.register_timer(ask);
                    handler(&trust, TrustReply(self.grip(ask)));
                }
                Action::CancelTimer(timer) => day_async::unschedule(timer),
                Action::Progress(progress, sent, total) => (progress.0)(sent, total),
            }
        }
    }

    /// Deliver queued chunks to the body's callback, one thread at a time and in order.
    fn drain(self: &Arc<Self>) {
        loop {
            let mut actions = Vec::new();
            let (item, mut callback) = {
                let mut st = lock(&self.state);
                if st.inbox.draining {
                    return;
                }
                let Some(callback) = st.inbox.callback.take() else {
                    return;
                };
                let Some(item) = st.inbox.take() else {
                    st.inbox.callback = Some(callback);
                    return;
                };
                if let Some(n) = st.inbox.refill() {
                    demand(&mut st, n, &mut actions);
                }
                st.inbox.draining = true;
                (item, callback)
            };
            self.run(actions);
            let terminal = !matches!(item, Some(Ok(_)));
            if terminal {
                self.finish_body();
            }
            let keep = callback(item);
            let mut st = lock(&self.state);
            st.inbox.draining = false;
            if terminal {
                return;
            }
            if keep {
                st.inbox.callback = Some(callback);
            } else {
                drop(st);
                drop(callback);
                return self.cancel();
            }
        }
    }

    /// The body's terminal outcome went to the reader: stop the clocks.
    fn finish_body(self: &Arc<Self>) {
        let mut actions = Vec::new();
        {
            let mut st = lock(&self.state);
            if st.stage != Stage::Done {
                st.stage = Stage::Done;
                teardown(&mut st, &mut actions);
            }
        }
        self.run(actions);
    }
}

/// A response head is waiting on a redirect or challenge answer.
fn parked(st: &FlightState) -> bool {
    st.asks
        .iter()
        .any(|(_, asked, _)| matches!(asked, Asked::Redirect { .. } | Asked::Challenge { .. }))
}

fn register(st: &mut FlightState, asked: Asked) -> u64 {
    let ask = st.next_ask;
    st.next_ask += 1;
    st.asks.push((ask, asked, None));
    ask
}

fn demand(st: &mut FlightState, n: u32, actions: &mut Vec<Action>) {
    match &st.transfer {
        Some(t) => actions.push(Action::Demand(t.clone(), n)),
        None if !st.exchange_over => st.pending.push(PendingOp::Demand(n)),
        None => {}
    }
}

fn answer(st: &mut FlightState, id: QuestionId, answer: Answer, actions: &mut Vec<Action>) {
    match &st.transfer {
        Some(t) => actions.push(Action::Answer(t.clone(), id, answer)),
        None if !st.exchange_over => st.pending.push(PendingOp::Answer(id, answer)),
        None => {}
    }
}

/// Stop the current exchange and send `next` in its place.
fn replace_exchange(st: &mut FlightState, next: Request, actions: &mut Vec<Action>) {
    if let Some(t) = st.transfer.take() {
        actions.push(Action::Cancel(t));
    }
    st.generation += 1;
    st.exchange_over = false;
    st.pending.clear();
    st.inbox.queue.clear();
    st.inbox.outstanding = 0;
    st.inbox.finished = None;
    st.received = 0;
    st.request = next;
    st.stage = Stage::Head;
    actions.push(Action::StartHop);
}

fn answer_challenge(
    st: &mut FlightState,
    parsed: &ParsedChallenge,
    challenge: &Challenge,
    url: &url::Url,
    resolution: Resolution,
    head: Head,
    actions: &mut Vec<Action>,
) {
    let value = match &resolution {
        Resolution::Credential { user, password } => match parsed.scheme {
            Scheme::Digest => {
                let mut uri = url.path().to_string();
                if let Some(q) = url.query() {
                    uri.push('?');
                    uri.push_str(q);
                }
                digest_authorization(parsed, user, password, st.request.method.as_str(), &uri)
            }
            _ => Some(basic_authorization(user, password)),
        },
        Resolution::Bearer(token) => Some(format!("Bearer {token}")),
        Resolution::Cancel => return fail(st, HttpError::Cancelled, actions),
        _ => None,
    };
    let Some(value) = value else {
        return begin_body(st, head, actions);
    };
    let name = if challenge.proxy {
        "Proxy-Authorization"
    } else {
        "Authorization"
    };
    let mut next = st.request.clone();
    next.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
    next.headers.push((name.to_string(), value));
    st.auth_failures += 1;
    st.offered = Some((origin_of(url), challenge.realm.clone(), resolution));
    replace_exchange(st, next, actions);
}

/// The final response head: hand it to the reader and start granting demand.
fn begin_body(st: &mut FlightState, head: Head, actions: &mut Vec<Action>) {
    st.stage = Stage::Body;
    st.expected = head.expected_length;
    if let Some(on_head) = st.on_head.take() {
        actions.push(Action::DeliverHead(on_head, Box::new(head)));
    }
    if let Some(n) = st.inbox.refill() {
        demand(st, n, actions);
    }
    // The exchange already ended while its head waited on an answer.
    if st.exchange_over
        && let Some(n) = st.inbox.finish(Ok(()))
    {
        actions.push(n.into());
    }
}

fn fail(st: &mut FlightState, error: HttpError, actions: &mut Vec<Action>) {
    match st.stage {
        Stage::Head => {
            st.stage = Stage::Done;
            // Tear the exchange down before the caller hears of the failure, as the body arm
            // does: a caller told "timed out" who retries at once must not have the old exchange
            // still running beside the new one. The `Failed(Cancelled)` a transport may raise
            // from inside `cancel` finds the flight `Done` and is dropped.
            teardown(st, actions);
            if let Some(on_head) = st.on_head.take() {
                actions.push(Action::HeadFailed(on_head, error));
            }
        }
        Stage::Body => {
            if let Some(t) = st.transfer.take() {
                actions.push(Action::Cancel(t));
            }
            if let Some(n) = st.inbox.finish(Err(error)) {
                actions.push(n.into());
            }
        }
        Stage::Done => {}
    }
}

fn teardown(st: &mut FlightState, actions: &mut Vec<Action>) {
    if let Some(t) = st.transfer.take() {
        actions.push(Action::Cancel(t));
    }
    st.pending.clear();
    for (_, _, timer) in st.asks.drain(..) {
        if let Some(timer) = timer {
            actions.push(Action::CancelTimer(timer));
        }
    }
    if let Some(timer) = st.total_timer.take() {
        actions.push(Action::CancelTimer(timer));
    }
}

/// A response head with its unread body.
#[derive(Debug)]
pub struct Streaming {
    head: Head,
    body: Body,
}

impl Streaming {
    /// The status code.
    pub fn status(&self) -> u16 {
        self.head.status
    }

    /// The headers, in arrival order.
    pub fn headers(&self) -> &[(String, String)] {
        &self.head.headers
    }

    /// The first header with this name, ASCII case-insensitive.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.head.header(name)
    }

    /// The URL that answered, after redirects.
    pub fn url(&self) -> &str {
        &self.head.url
    }

    /// `Content-Length`, when the response declared one.
    pub fn expected_length(&self) -> Option<u64> {
        self.head.expected_length
    }

    /// The whole head.
    pub fn head(&self) -> &Head {
        &self.head
    }

    /// The body, unread.
    pub fn into_body(self) -> Body {
        self.body
    }

    /// The head and the body, apart.
    pub fn into_parts(self) -> (Head, Body) {
        (self.head, self.body)
    }

    /// Read the whole body into memory; `on_done` receives the response.
    pub fn collect_async(self, on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static) {
        let Streaming { head, body } = self;
        let flight = Arc::downgrade(&body.flight);
        let capacity = head.expected_length.unwrap_or(0).min(16 << 20) as usize;
        let mut bytes = Vec::with_capacity(capacity);
        let mut on_done = Some(on_done);
        let mut head = Some(head);
        body.read_async(move |item| {
            match item {
                Some(Ok(chunk)) => {
                    bytes.extend_from_slice(&chunk);
                    return true;
                }
                Some(Err(e)) => {
                    if let Some(f) = on_done.take() {
                        f(Err(e));
                    }
                }
                None => {
                    if let (Some(f), Some(h)) = (on_done.take(), head.take()) {
                        let metrics = flight
                            .upgrade()
                            .and_then(|f| lock(&f.state).metrics.clone());
                        f(Ok(Response::assemble(
                            h,
                            std::mem::take(&mut bytes),
                            metrics,
                        )));
                    }
                }
            }
            false
        });
    }

    /// Read the whole body into memory and await the response.
    pub fn collect_future(self) -> Collecting {
        let flight = self.body.flight.clone();
        let (tx, rx) = day_async::oneshot();
        self.collect_async(move |r| tx.send(r));
        Collecting {
            flight,
            rx,
            done: false,
        }
    }
}

/// A response body, read in the chunks the platform delivers. The body pulls from the network
/// only while its reader keeps up. Dropping it before the end cancels the request.
pub struct Body {
    flight: Arc<Flight>,
    handed_off: bool,
}

impl std::fmt::Debug for Body {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Body")
            .field("received", &self.received())
            .finish_non_exhaustive()
    }
}

impl Body {
    /// The next chunk; `None` after the last.
    // Awaited (`body.next().await`), so it is not `Iterator::next`.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> NextChunk<'_> {
        NextChunk { body: self }
    }

    /// Wait for the next chunk on this thread. Never call it on the UI thread.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn next_blocking(&mut self) -> Option<Result<Vec<u8>, HttpError>> {
        wait(self.next())
    }

    /// A grip that cancels this body's request from any thread, also after
    /// [`Body::read_async`] took the body.
    pub fn in_flight(&self) -> InFlight {
        InFlight(Arc::downgrade(&self.flight))
    }

    /// Bytes received so far, including chunks not read yet.
    pub fn received(&self) -> u64 {
        lock(&self.flight.state).received
    }

    /// `Content-Length`, when the response declared one.
    pub fn expected_length(&self) -> Option<u64> {
        lock(&self.flight.state).expected
    }

    /// Transfer metrics, once the platform reported them (usually just before the end).
    pub fn metrics(&self) -> Option<Metrics> {
        lock(&self.flight.state).metrics.clone()
    }

    /// Stop pulling from the network. Chunks already on their way still arrive.
    pub fn pause(&self) {
        lock(&self.flight.state).inbox.paused = true;
    }

    /// Pull from the network again after [`Body::pause`].
    pub fn resume(&self) {
        let mut actions = Vec::new();
        {
            let mut st = lock(&self.flight.state);
            st.inbox.paused = false;
            if let Some(n) = st.inbox.refill() {
                demand(&mut st, n, &mut actions);
            }
            if let Some(n) = st.inbox.notify() {
                actions.push(n.into());
            }
        }
        self.flight.run(actions);
    }

    /// Hand each chunk to `on_chunk` as it arrives, then `None` at the end or `Some(Err)` on
    /// failure. The body pulls the next chunk only after `on_chunk` returns; returning `false`
    /// cancels the request.
    pub fn read_async(
        mut self,
        on_chunk: impl FnMut(Option<Result<Vec<u8>, HttpError>>) -> bool + Send + 'static,
    ) {
        self.handed_off = true;
        lock(&self.flight.state).inbox.callback = Some(Box::new(on_chunk));
        self.flight.drain();
    }
}

impl Drop for Body {
    fn drop(&mut self) {
        if !self.handed_off {
            self.flight.cancel();
        }
    }
}

/// The future [`Body::next`] returns.
pub struct NextChunk<'a> {
    body: &'a mut Body,
}

impl Future for NextChunk<'_> {
    type Output = Option<Result<Vec<u8>, HttpError>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let flight = self.body.flight.clone();
        let mut actions = Vec::new();
        let (out, terminal) = {
            let mut st = lock(&flight.state);
            let item = st.inbox.take();
            if let Some(n) = st.inbox.refill() {
                demand(&mut st, n, &mut actions);
            }
            match item {
                Some(item) => {
                    let terminal = !matches!(item, Some(Ok(_)));
                    (Poll::Ready(item), terminal)
                }
                None => {
                    st.inbox.waker = Some(cx.waker().clone());
                    (Poll::Pending, false)
                }
            }
        };
        flight.run(actions);
        if terminal {
            flight.finish_body();
        }
        out
    }
}

/// A grip on a request started with a callback: cancel it from any thread, at any stage. Holding
/// it does not keep the request alive, and cancelling a finished request does nothing.
#[derive(Clone, Debug)]
pub struct InFlight(Weak<Flight>);

impl InFlight {
    /// Cancel the request. Its callback is not called again.
    pub fn cancel(&self) {
        if let Some(flight) = self.0.upgrade() {
            flight.cancel();
        }
    }
}

impl std::fmt::Debug for Flight {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Flight")
    }
}

/// The future [`Client::send_future`] returns.
pub struct Sending {
    flight: Arc<Flight>,
    rx: day_async::Oneshot<Result<Streaming, HttpError>>,
    done: bool,
}

impl Future for Sending {
    type Output = Result<Streaming, HttpError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.rx).poll(cx) {
            Poll::Ready(result) => {
                self.done = true;
                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for Sending {
    fn drop(&mut self) {
        if !self.done {
            self.flight.cancel();
        }
    }
}

/// The future [`Client::fetch_future`] returns.
pub struct Fetching {
    flight: Arc<Flight>,
    rx: day_async::Oneshot<Result<Response, HttpError>>,
    done: bool,
}

impl Future for Fetching {
    type Output = Result<Response, HttpError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.rx).poll(cx) {
            Poll::Ready(result) => {
                self.done = true;
                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for Fetching {
    fn drop(&mut self) {
        if !self.done {
            self.flight.cancel();
        }
    }
}

/// The future [`Streaming::collect_future`] returns.
pub struct Collecting {
    flight: Arc<Flight>,
    rx: day_async::Oneshot<Result<Response, HttpError>>,
    done: bool,
}

impl Future for Collecting {
    type Output = Result<Response, HttpError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.rx).poll(cx) {
            Poll::Ready(result) => {
                self.done = true;
                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for Collecting {
    fn drop(&mut self) {
        if !self.done {
            self.flight.cancel();
        }
    }
}

/// Run a future to completion on this thread, parking between polls.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn wait<F: Future>(future: F) -> F::Output {
    struct Unpark(std::thread::Thread);
    impl std::task::Wake for Unpark {
        fn wake(self: Arc<Self>) {
            self.0.unpark();
        }
        fn wake_by_ref(self: &Arc<Self>) {
            self.0.unpark();
        }
    }
    let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
    let mut cx = Context::from_waker(&waker);
    let mut future = std::pin::pin!(future);
    loop {
        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
            return value;
        }
        std::thread::park();
    }
}

// ---------------------------------------------------------------------------
// WebSockets
// ---------------------------------------------------------------------------

type OpenCallback = Box<dyn FnOnce(Result<WebSocket, HttpError>) + Send>;

struct WsShared {
    state: Mutex<WsState>,
}

struct WsState {
    socket: Option<Arc<dyn Socket>>,
    open: bool,
    over: bool,
    on_open: Option<OpenCallback>,
    protocol: Option<String>,
    inbox: Inbox<Message>,
    pending_demand: u32,
    /// Sends and a close requested before the transport handed back its socket.
    pending_sends: Vec<(Message, Completion)>,
    pending_close: Option<(u16, String)>,
}

impl WsShared {
    fn open(client: &Arc<ClientInner>, request: Request, on_open: OpenCallback) -> Arc<WsShared> {
        let client = client.snapshot(&request);
        let shared = Arc::new(WsShared {
            state: Mutex::new(WsState {
                socket: None,
                open: false,
                over: false,
                on_open: None,
                protocol: None,
                inbox: Inbox::new(),
                pending_demand: 0,
                pending_sends: Vec::new(),
                pending_close: None,
            }),
        });
        // Pins are checked through a transport's trust questions, which a WebSocket handshake
        // does not raise: a pinned client fails closed rather than connecting unpinned.
        let prepared = match client.prepare(&request, true).and_then(|p| {
            if client.trust.is_empty()
                && client.config.identity.is_none()
                && client.on_server_trust.is_none()
            {
                Ok(p)
            } else {
                Err(HttpError::Unsupported)
            }
        }) {
            Ok(p) => p,
            Err(e) => {
                lock(&shared.state).over = true;
                on_open(Err(e));
                return shared;
            }
        };
        lock(&shared.state).on_open = Some(on_open);
        let this = shared.clone();
        let events: WsEvents = Arc::new(move |event| this.on_event(event));
        let socket = client.transport.websocket(prepared, events);
        let (keep, demand, sends, close) = {
            let mut st = lock(&shared.state);
            let keep = !st.over;
            if keep {
                st.socket = Some(socket.clone());
            }
            (
                keep,
                std::mem::take(&mut st.pending_demand),
                std::mem::take(&mut st.pending_sends),
                st.pending_close.take(),
            )
        };
        if !keep {
            for (_, done) in sends {
                done(Err(HttpError::Io("the WebSocket is closed".into())));
            }
            let (code, reason) = close.unwrap_or((1000, String::new()));
            socket.close(code, &reason);
            return shared;
        }
        if demand > 0 {
            socket.demand(demand);
        }
        for (message, done) in sends {
            socket.send(message, done);
        }
        if let Some((code, reason)) = close {
            socket.close(code, &reason);
        }
        shared
    }

    fn on_event(self: &Arc<Self>, event: WsEvent) {
        let mut notify = None;
        let mut opened = None;
        let mut failed_open = None;
        let mut grant = None;
        {
            let mut st = lock(&self.state);
            if st.over && !matches!(event, WsEvent::Closed { .. }) {
                return;
            }
            match event {
                WsEvent::Open { protocol } => {
                    st.open = true;
                    st.protocol = protocol;
                    opened = st.on_open.take();
                    grant = st.inbox.refill().map(|n| ws_demand(&mut st, n));
                }
                WsEvent::Message(message) => notify = st.inbox.push(message),
                WsEvent::Closed { code, reason } => {
                    if st.over {
                        return;
                    }
                    st.over = true;
                    st.socket = None;
                    if st.open {
                        st.inbox.queue.push_back(Message::Close { code, reason });
                        notify = st.inbox.finish(Ok(()));
                    } else {
                        failed_open = st.on_open.take().map(|f| {
                            (
                                f,
                                HttpError::Io(format!("closed during the handshake ({code})")),
                            )
                        });
                    }
                }
                WsEvent::Failed(error) => {
                    st.over = true;
                    st.socket = None;
                    if st.open {
                        notify = st.inbox.finish(Err(error));
                    } else {
                        failed_open = st.on_open.take().map(|f| (f, error));
                    }
                }
            }
        }
        if let Some(Some((socket, n))) = grant {
            socket.demand(n);
        }
        if let Some(on_open) = opened {
            on_open(Ok(WebSocket {
                shared: self.clone(),
                handed_off: false,
            }));
        }
        if let Some((on_open, error)) = failed_open {
            on_open(Err(error));
        }
        match notify {
            Some(Notify::Wake(w)) => w.wake(),
            Some(Notify::Drain) => self.drain(),
            None => {}
        }
    }

    fn socket(&self) -> Option<Arc<dyn Socket>> {
        lock(&self.state).socket.clone()
    }

    fn drain(self: &Arc<Self>) {
        loop {
            let mut grant = None;
            let (item, mut callback) = {
                let mut st = lock(&self.state);
                if st.inbox.draining {
                    return;
                }
                let Some(callback) = st.inbox.callback.take() else {
                    return;
                };
                let Some(item) = st.inbox.take() else {
                    st.inbox.callback = Some(callback);
                    return;
                };
                if let Some(n) = st.inbox.refill() {
                    grant = ws_demand(&mut st, n);
                }
                st.inbox.draining = true;
                (item, callback)
            };
            if let Some((socket, n)) = grant {
                socket.demand(n);
            }
            let terminal = !matches!(item, Some(Ok(_)));
            let keep = callback(item);
            let mut st = lock(&self.state);
            st.inbox.draining = false;
            if terminal {
                return;
            }
            if keep {
                st.inbox.callback = Some(callback);
            } else {
                let socket = st.socket.take();
                st.over = true;
                drop(st);
                drop(callback);
                if let Some(socket) = socket {
                    socket.close(1000, "");
                }
                return;
            }
        }
    }
}

fn ws_demand(st: &mut WsState, n: u32) -> Option<(Arc<dyn Socket>, u32)> {
    match &st.socket {
        Some(socket) => Some((socket.clone(), n)),
        None => {
            st.pending_demand += n;
            None
        }
    }
}

/// An open WebSocket. Read it with [`WebSocket::next`] or [`WebSocket::read_async`], and send
/// through it or a [`WsSender`]. Dropping it closes the connection with code 1000.
pub struct WebSocket {
    shared: Arc<WsShared>,
    handed_off: bool,
}

impl std::fmt::Debug for WebSocket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebSocket")
            .field("protocol", &self.protocol())
            .finish_non_exhaustive()
    }
}

impl WebSocket {
    /// The subprotocol the server chose.
    pub fn protocol(&self) -> Option<String> {
        lock(&self.shared.state).protocol.clone()
    }

    /// A sending half to give to other code: it can send, ping and close.
    pub fn sender(&self) -> WsSender {
        WsSender {
            shared: self.shared.clone(),
        }
    }

    /// Send a message; `done` reports when the platform took it.
    pub fn send_async(
        &self,
        message: Message,
        done: impl FnOnce(Result<(), HttpError>) + Send + 'static,
    ) {
        self.sender().send_async(message, done)
    }

    /// Send a message and await the platform taking it.
    pub fn send_future(&self, message: Message) -> day_async::Oneshot<Result<(), HttpError>> {
        self.sender().send_future(message)
    }

    /// Close with `code` and `reason`.
    pub fn close(&self, code: u16, reason: &str) {
        self.sender().close(code, reason)
    }

    /// The next message; the last is a [`Message::Close`], then `None`.
    // Awaited (`socket.next().await`), so it is not `Iterator::next`.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> NextMessage<'_> {
        NextMessage { socket: self }
    }

    /// Hand each message to `on_message` as it arrives, then `None` at the end or `Some(Err)` on
    /// failure. Returning `false` closes the connection.
    pub fn read_async(
        mut self,
        on_message: impl FnMut(Option<Result<Message, HttpError>>) -> bool + Send + 'static,
    ) {
        self.handed_off = true;
        lock(&self.shared.state).inbox.callback = Some(Box::new(on_message));
        self.shared.drain();
    }
}

impl Drop for WebSocket {
    fn drop(&mut self) {
        if !self.handed_off {
            let socket = {
                let mut st = lock(&self.shared.state);
                st.over = true;
                st.socket.take()
            };
            if let Some(socket) = socket {
                socket.close(1000, "");
            }
        }
    }
}

/// The sending half of a [`WebSocket`].
#[derive(Clone)]
pub struct WsSender {
    shared: Arc<WsShared>,
}

impl std::fmt::Debug for WsSender {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("WsSender")
    }
}

impl WsSender {
    /// Send a message; `done` reports when the platform took it.
    pub fn send_async(
        &self,
        message: Message,
        done: impl FnOnce(Result<(), HttpError>) + Send + 'static,
    ) {
        let socket = {
            let mut st = lock(&self.shared.state);
            if let Some(socket) = st.socket.clone() {
                Some(socket)
            } else if !st.over {
                st.pending_sends.push((message, Box::new(done)));
                return;
            } else {
                None
            }
        };
        match socket {
            Some(socket) => socket.send(message, Box::new(done)),
            None => done(Err(HttpError::Io("the WebSocket is closed".into()))),
        }
    }

    /// Send a message and await the platform taking it.
    pub fn send_future(&self, message: Message) -> day_async::Oneshot<Result<(), HttpError>> {
        let (tx, rx) = day_async::oneshot();
        self.send_async(message, move |r| tx.send(r));
        rx
    }

    /// Send a ping; `done` reports the pong. Needs [`Capabilities::websocket_ping`].
    pub fn ping_async(&self, done: impl FnOnce(Result<(), HttpError>) + Send + 'static) {
        match self.shared.socket() {
            Some(socket) => socket.ping(Box::new(done)),
            None => done(Err(HttpError::Io("the WebSocket is closed".into()))),
        }
    }

    /// Send a ping and await the pong.
    pub fn ping_future(&self) -> day_async::Oneshot<Result<(), HttpError>> {
        let (tx, rx) = day_async::oneshot();
        self.ping_async(move |r| tx.send(r));
        rx
    }

    /// Close with `code` and `reason`. The peer's reply arrives as the last message.
    pub fn close(&self, code: u16, reason: &str) {
        let socket = {
            let mut st = lock(&self.shared.state);
            if st.socket.is_none() && !st.over {
                st.pending_close = Some((code, reason.to_string()));
            }
            st.socket.clone()
        };
        if let Some(socket) = socket {
            socket.close(code, reason);
        }
    }
}

/// The future [`WebSocket::next`] returns.
pub struct NextMessage<'a> {
    socket: &'a mut WebSocket,
}

impl Future for NextMessage<'_> {
    type Output = Option<Result<Message, HttpError>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let shared = self.socket.shared.clone();
        let mut grant = None;
        let out = {
            let mut st = lock(&shared.state);
            let item = st.inbox.take();
            if let Some(n) = st.inbox.refill() {
                grant = ws_demand(&mut st, n);
            }
            match item {
                Some(item) => Poll::Ready(item),
                None => {
                    st.inbox.waker = Some(cx.waker().clone());
                    Poll::Pending
                }
            }
        };
        if let Some((socket, n)) = grant {
            socket.demand(n);
        }
        out
    }
}

/// The future [`Client::websocket_future`] returns.
pub struct Connecting {
    shared: Arc<WsShared>,
    rx: day_async::Oneshot<Result<WebSocket, HttpError>>,
    done: bool,
}

impl Future for Connecting {
    type Output = Result<WebSocket, HttpError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.rx).poll(cx) {
            Poll::Ready(result) => {
                self.done = true;
                Poll::Ready(result.unwrap_or(Err(HttpError::Cancelled)))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Drop for Connecting {
    fn drop(&mut self) {
        if !self.done {
            let socket = {
                let mut st = lock(&self.shared.state);
                st.over = true;
                st.on_open = None;
                st.socket.take()
            };
            if let Some(socket) = socket {
                socket.close(1000, "");
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Cookies (RFC 6265)
// ---------------------------------------------------------------------------

/// A cookie, as a jar or the platform's store holds it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cookie {
    pub name: String,
    pub value: String,
    pub domain: String,
    pub path: String,
    /// `None` for a session cookie.
    pub expires: Option<SystemTime>,
    pub secure: bool,
    pub http_only: bool,
    /// Sent only to the host that set it, which named no `Domain`.
    pub host_only: bool,
}

/// A cookie store the client reads and writes itself: parsing, matching and expiry follow RFC
/// 6265, and a `Domain` that names a public suffix is refused.
#[derive(Debug, Default)]
pub struct CookieJar {
    cookies: Mutex<Vec<(Cookie, u64)>>,
    created: AtomicU64,
    file: Option<PathBuf>,
}

impl CookieJar {
    /// An empty jar in memory.
    pub fn new() -> CookieJar {
        CookieJar::default()
    }

    /// A jar persisted to `file`, loading what it holds. Session cookies are never written.
    pub fn open(file: impl Into<PathBuf>) -> CookieJar {
        let file = file.into();
        let jar = CookieJar {
            file: Some(file.clone()),
            ..CookieJar::default()
        };
        if let Ok(text) = std::fs::read_to_string(&file) {
            let now = now();
            let mut cookies = lock(&jar.cookies);
            for line in text.lines() {
                if let Some(cookie) = decode_cookie_line(line)
                    && cookie.expires.is_some_and(|e| e > now)
                {
                    let seq = jar.created.fetch_add(1, Ordering::Relaxed);
                    cookies.push((cookie, seq));
                }
            }
        }
        jar
    }

    /// Every unexpired cookie.
    pub fn cookies(&self) -> Vec<Cookie> {
        let now = now();
        lock(&self.cookies)
            .iter()
            .filter(|(c, _)| c.expires.is_none_or(|e| e > now))
            .map(|(c, _)| c.clone())
            .collect()
    }

    /// Forget every cookie.
    pub fn clear(&self) {
        lock(&self.cookies).clear();
        self.save();
    }

    /// Store the `Set-Cookie` values a response from `url` carried.
    pub fn store<'a>(&self, url: &str, set_cookie: impl IntoIterator<Item = &'a str>) {
        if let Ok(url) = url::Url::parse(url) {
            self.store_all(&url, set_cookie);
        }
    }

    /// The `Cookie` header for a request to `url`.
    pub fn header(&self, url: &str) -> Option<String> {
        url::Url::parse(url).ok().and_then(|u| self.header_for(&u))
    }

    fn store_all<'a>(&self, url: &url::Url, set_cookie: impl IntoIterator<Item = &'a str>) {
        let now = now();
        let mut changed = false;
        {
            let mut cookies = lock(&self.cookies);
            for value in set_cookie {
                let Some(cookie) = parse_set_cookie(url, value, now) else {
                    continue;
                };
                let existing = cookies.iter().position(|(c, _)| {
                    c.name == cookie.name && c.domain == cookie.domain && c.path == cookie.path
                });
                let seq = match existing {
                    Some(i) => cookies.remove(i).1,
                    None => self.created.fetch_add(1, Ordering::Relaxed),
                };
                if cookie.expires.is_none_or(|e| e > now) {
                    cookies.push((cookie, seq));
                }
                changed = true;
            }
            cookies.retain(|(c, _)| c.expires.is_none_or(|e| e > now));
        }
        if changed {
            self.save();
        }
    }

    fn header_for(&self, url: &url::Url) -> Option<String> {
        let host = url.host_str()?.to_ascii_lowercase();
        let secure = matches!(url.scheme(), "https" | "wss");
        let path = url.path();
        let now = now();
        let cookies = lock(&self.cookies);
        let mut matching: Vec<&(Cookie, u64)> = cookies
            .iter()
            .filter(|(c, _)| {
                c.expires.is_none_or(|e| e > now)
                    && (!c.secure || secure)
                    && if c.host_only {
                        c.domain == host
                    } else {
                        domain_matches(&host, &c.domain)
                    }
                    && path_matches(path, &c.path)
            })
            .collect();
        if matching.is_empty() {
            return None;
        }
        matching.sort_by(|(a, sa), (b, sb)| b.path.len().cmp(&a.path.len()).then(sa.cmp(sb)));
        Some(
            matching
                .iter()
                .map(|(c, _)| format!("{}={}", c.name, c.value))
                .collect::<Vec<_>>()
                .join("; "),
        )
    }

    fn save(&self) {
        let Some(file) = &self.file else {
            return;
        };
        let mut text = String::new();
        for (cookie, _) in lock(&self.cookies).iter() {
            if let Some(line) = encode_cookie_line(cookie) {
                text.push_str(&line);
                text.push('\n');
            }
        }
        if let Some(dir) = file.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        let partial = file.with_extension("partial");
        if std::fs::write(&partial, text).is_ok() {
            let _ = std::fs::rename(&partial, file);
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn now() -> SystemTime {
    SystemTime::now()
}

/// The browser keeps its own cookies, and `SystemTime::now` does not exist on wasm32.
#[cfg(target_arch = "wasm32")]
fn now() -> SystemTime {
    UNIX_EPOCH
}

fn domain_matches(host: &str, domain: &str) -> bool {
    host == domain
        || (host.len() > domain.len()
            && host.ends_with(domain)
            && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
            && host.parse::<std::net::IpAddr>().is_err())
}

fn path_matches(request: &str, cookie: &str) -> bool {
    request == cookie
        || (request.starts_with(cookie)
            && (cookie.ends_with('/') || request.as_bytes().get(cookie.len()) == Some(&b'/')))
}

fn default_cookie_path(url: &url::Url) -> String {
    let path = url.path();
    match path.rfind('/') {
        Some(0) | None => "/".to_string(),
        Some(i) => path[..i].to_string(),
    }
}

fn parse_cookie_date(text: &str) -> Option<SystemTime> {
    httpdate::parse_http_date(text)
        .ok()
        .or_else(|| httpdate::parse_http_date(&text.replace('-', " ")).ok())
}

fn parse_set_cookie(url: &url::Url, header: &str, now: SystemTime) -> Option<Cookie> {
    let mut parts = header.split(';');
    let (name, value) = parts.next()?.split_once('=')?;
    let name = name.trim();
    if name.is_empty() {
        return None;
    }
    let host = url.host_str()?.to_ascii_lowercase();
    let mut cookie = Cookie {
        name: name.to_string(),
        value: value.trim().to_string(),
        domain: host.clone(),
        path: default_cookie_path(url),
        expires: None,
        secure: false,
        http_only: false,
        host_only: true,
    };
    let mut max_age = None;
    let mut expires = None;
    let mut domain = None;
    for attribute in parts {
        let (key, value) = match attribute.split_once('=') {
            Some((k, v)) => (k.trim(), v.trim()),
            None => (attribute.trim(), ""),
        };
        match key.to_ascii_lowercase().as_str() {
            "expires" => expires = parse_cookie_date(value),
            "max-age" => max_age = value.parse::<i64>().ok(),
            "domain" => {
                let d = value.trim_start_matches('.').to_ascii_lowercase();
                if !d.is_empty() {
                    domain = Some(d);
                }
            }
            "path" if value.starts_with('/') => cookie.path = value.to_string(),
            "secure" => cookie.secure = true,
            "httponly" => cookie.http_only = true,
            _ => {}
        }
    }
    if let Some(domain) = domain {
        if domain != host && psl::suffix_str(&domain) == Some(domain.as_str()) {
            return None;
        }
        if !domain_matches(&host, &domain) {
            return None;
        }
        cookie.domain = domain;
        cookie.host_only = false;
    }
    cookie.expires = match max_age {
        Some(seconds) if seconds <= 0 => Some(UNIX_EPOCH),
        Some(seconds) => now.checked_add(Duration::from_secs(seconds as u64)),
        None => expires,
    };
    if cookie.secure && !matches!(url.scheme(), "https" | "wss") {
        return None;
    }
    Some(cookie)
}

fn encode_cookie_line(c: &Cookie) -> Option<String> {
    let expires = c.expires?.duration_since(UNIX_EPOCH).ok()?.as_secs();
    let fields = [&c.name, &c.value, &c.domain, &c.path];
    if fields.iter().any(|f| f.contains(['\t', '\n', '\r'])) {
        return None;
    }
    let flags: String = [(c.secure, 's'), (c.http_only, 'h'), (c.host_only, 'o')]
        .iter()
        .filter(|(on, _)| *on)
        .map(|(_, f)| *f)
        .collect();
    Some(format!(
        "{}\t{}\t{}\t{}\t{expires}\t{flags}",
        c.name, c.value, c.domain, c.path
    ))
}

fn decode_cookie_line(line: &str) -> Option<Cookie> {
    let mut fields = line.split('\t');
    let name = fields.next()?.to_string();
    let value = fields.next()?.to_string();
    let domain = fields.next()?.to_string();
    let path = fields.next()?.to_string();
    let expires = UNIX_EPOCH.checked_add(Duration::from_secs(fields.next()?.parse().ok()?))?;
    let flags = fields.next().unwrap_or("");
    Some(Cookie {
        name,
        value,
        domain,
        path,
        expires: Some(expires),
        secure: flags.contains('s'),
        http_only: flags.contains('h'),
        host_only: flags.contains('o'),
    })
}

// ---------------------------------------------------------------------------
// Transports
// ---------------------------------------------------------------------------

// The transport contract beneath [`crate::Client`] (docs/http.md "Transports").
//
// A transport performs one exchange: it sends a prepared request and reports what the platform
// stack saw, as [`Event`]s, in order. Policy (following a redirect, retrying a challenge,
// attaching cookies, deciding trust) belongs to the client above it, so every backend applies the
// same rules. Where a stack insists on deciding something itself (URLSession asks its delegate
// about redirects and challenges), the transport turns that into a [`Question`] and waits for the
// client's [`Answer`].
//
// Apps implement [`Transport`] only to install a test double through `ClientBuilder::transport`.

/// What a backend can do. The client consults it to decide what it must do itself, and apps can
/// read it (`day_part_http::capabilities()`) to say what a platform offers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Capabilities {
    /// Response bodies arrive in chunks, pulled on demand.
    pub streaming: bool,
    /// A request body can be sent from a reader without buffering it first.
    pub upload_streaming: bool,
    /// Upload progress is reported while a body is sent.
    pub upload_progress: bool,
    /// The stack hands back redirect responses, so the client can follow and approve each hop.
    pub manual_redirects: bool,
    /// The stack asks about HTTP challenges itself ([`Question::Auth`]).
    pub auth_questions: bool,
    /// NTLM and Negotiate are answered by the stack.
    pub native_auth_schemes: bool,
    /// The stack reports each server certificate chain for evaluation ([`Question::ServerTrust`]).
    pub server_trust: bool,
    /// A client certificate identity can be presented.
    pub client_identity: bool,
    /// The platform's own cookie store is available.
    pub platform_cookies: bool,
    /// The platform's own HTTP cache is available.
    pub platform_cache: bool,
    /// Transfer metrics are reported.
    pub metrics: bool,
    /// WebSockets are available.
    pub websockets: bool,
    /// A WebSocket can send an explicit ping.
    pub websocket_ping: bool,
    /// A WebSocket handshake can carry custom request headers.
    pub websocket_headers: bool,
    /// Requests can wait for connectivity instead of failing at once.
    pub wait_for_connectivity: bool,
}

/// How a request may use the platform's cache.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CachePolicy {
    /// Follow the response's cache headers.
    #[default]
    Default,
    /// Always load from the network, ignoring cached data.
    Reload,
    /// Use cached data when present, whatever its age; load otherwise.
    PreferCache,
}

/// A request body reader shared between clones of a request. A stream can be sent once: a retry
/// or a 307 redirect that needs the body again finds it taken and fails.
#[derive(Clone)]
pub struct SharedReader(Arc<Mutex<Option<Box<dyn Read + Send>>>>);

impl SharedReader {
    /// Wrap a reader.
    pub fn new(reader: impl Read + Send + 'static) -> Self {
        Self(Arc::new(Mutex::new(Some(Box::new(reader)))))
    }

    /// Take the reader; `None` once it was taken.
    pub fn take(&self) -> Option<Box<dyn Read + Send>> {
        self.0.lock().unwrap_or_else(|p| p.into_inner()).take()
    }
}

impl std::fmt::Debug for SharedReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("SharedReader")
    }
}

/// The body a transport sends.
#[derive(Debug)]
pub enum PreparedBody {
    Empty,
    Bytes(Arc<Vec<u8>>),
    File {
        path: PathBuf,
        len: u64,
    },
    Stream {
        reader: SharedReader,
        len: Option<u64>,
    },
}

/// One request, ready for a transport: headers merged, cookies and credentials attached.
#[derive(Debug)]
pub struct Prepared {
    pub method: String,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: PreparedBody,
    /// The idle bound: connecting, awaiting the head, and gaps in the body.
    pub timeout_idle: Duration,
    pub allow_expensive: bool,
    pub allow_constrained: bool,
    pub cache: CachePolicy,
    pub priority: Option<f32>,
    /// WebSocket subprotocols, in preference order.
    pub protocols: Vec<String>,
}

/// Per-client settings a transport applies when it is created.
#[derive(Clone, Debug)]
pub struct TransportConfig {
    pub timeout_idle: Duration,
    pub timeout_total: Option<Duration>,
    pub platform_cookies: bool,
    /// `(memory bytes, disk bytes)` for the platform cache; `None` = no cache.
    pub platform_cache: Option<(u64, u64)>,
    /// A stack with [`Capabilities::manual_redirects`] hands back every redirect whatever this
    /// says, and the client applies it; the others follow natively up to the limit, or refuse.
    pub redirects: Redirects,
    /// The client wants challenges as questions.
    pub ask_auth: bool,
    /// The client evaluates server trust (pins or a handler).
    pub ask_trust: bool,
    pub identity: Option<Identity>,
    pub max_per_host: Option<u32>,
    pub wait_for_connectivity: bool,
}

/// The response head.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Head {
    pub status: u16,
    /// In arrival order, duplicates preserved.
    pub headers: Vec<(String, String)>,
    /// The URL that answered, after any redirects the stack followed itself.
    pub url: String,
    /// `Content-Length`, when the response declared one.
    pub expected_length: Option<u64>,
}

impl Head {
    /// The first header with this name, ASCII case-insensitive.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// Every header with this name, in order.
    pub fn headers_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
        self.headers
            .iter()
            .filter(move |(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
}

/// Timings and facts about one completed transfer. Every field a platform does not report is
/// `None`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Metrics {
    /// Resolving the host name.
    pub dns: Option<Duration>,
    /// Establishing the connection, TLS included.
    pub connect: Option<Duration>,
    /// The TLS handshake.
    pub tls: Option<Duration>,
    /// From the start of the request to its first response byte.
    pub first_byte: Option<Duration>,
    /// From the start of the request to its last response byte.
    pub total: Option<Duration>,
    /// `http/1.1`, `h2`, `h3`.
    pub protocol: Option<String>,
    pub reused_connection: Option<bool>,
    pub proxy: Option<bool>,
    pub remote_address: Option<String>,
    pub tls_version: Option<String>,
    /// The response came from the local cache.
    pub from_cache: bool,
    pub bytes_sent: Option<u64>,
    pub bytes_received: Option<u64>,
    /// Redirects followed on the way to this response.
    pub redirects: u32,
}

/// An HTTP authentication scheme.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Scheme {
    Basic,
    Bearer,
    Digest,
    Ntlm,
    Negotiate,
    Other(String),
}

impl Scheme {
    pub(crate) fn parse(token: &str) -> Scheme {
        match token.to_ascii_lowercase().as_str() {
            "basic" => Scheme::Basic,
            "bearer" => Scheme::Bearer,
            "digest" => Scheme::Digest,
            "ntlm" => Scheme::Ntlm,
            "negotiate" => Scheme::Negotiate,
            _ => Scheme::Other(token.to_string()),
        }
    }

    /// Schemes a stack with native challenge handling (URLSession) raises as questions itself.
    pub(crate) fn raised_natively(&self) -> bool {
        matches!(
            self,
            Scheme::Basic | Scheme::Digest | Scheme::Ntlm | Scheme::Negotiate
        )
    }
}

/// The certificate chain a server presented, with the platform's own verdict on it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerTrust {
    pub host: String,
    /// DER certificates, leaf first.
    pub chain: Vec<Vec<u8>>,
    /// The platform's trust evaluation passed.
    pub system_trusted: bool,
    /// Why it failed, when it did.
    pub system_error: Option<String>,
}

impl ServerTrust {
    /// Each certificate's public-key pin, `sha256/<base64>`, leaf first, the value
    /// `Trust::pin` takes.
    pub fn pins(&self) -> Vec<String> {
        self.chain
            .iter()
            .filter_map(|der| spki_sha256(der))
            .map(|h| pin_string(&h))
            .collect()
    }
}

/// A challenge a stack raised itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthQuestion {
    pub host: String,
    pub port: u16,
    pub realm: Option<String>,
    pub scheme: Scheme,
    pub proxy: bool,
    pub previous_failures: u32,
}

/// Something the stack waits on the client for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Question {
    Auth(AuthQuestion),
    ServerTrust(ServerTrust),
}

/// The identifier a transport pairs a question with its answer by.
pub type QuestionId = u64;

/// The client's answer to a [`Question`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Answer {
    Credential {
        user: String,
        password: String,
    },
    /// Let the stack decide: for a challenge, deliver the 401; for trust, the platform verdict.
    DefaultHandling,
    /// Abandon the request.
    Cancel,
    /// Trust the server despite the platform verdict.
    Accept,
    /// Refuse the server.
    Reject,
}

/// What a transport reports about one exchange, in order.
#[derive(Debug)]
pub enum Event {
    Head(Head),
    Chunk(Vec<u8>),
    Sent { sent: u64, total: Option<u64> },
    Question(QuestionId, Question),
    Metrics(Metrics),
    End,
    Failed(HttpError),
}

/// The sink a transport reports through.
pub type Events = Arc<dyn Fn(Event) + Send + Sync>;

/// The client's grip on one exchange.
pub trait Transfer: Send + Sync {
    /// Read up to `chunks` more body chunks.
    fn demand(&self, chunks: u32);
    /// Answer a question the transport raised.
    fn answer(&self, id: QuestionId, answer: Answer);
    /// Abandon the exchange. A transport still reports a terminal event afterwards.
    fn cancel(&self);
}

/// A WebSocket message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Message {
    Text(String),
    Binary(Vec<u8>),
    /// The peer closed the connection; nothing follows.
    Close {
        code: u16,
        reason: String,
    },
}

/// What a transport reports about one WebSocket.
#[derive(Debug)]
pub enum WsEvent {
    Open { protocol: Option<String> },
    Message(Message),
    Closed { code: u16, reason: String },
    Failed(HttpError),
}

/// The sink a WebSocket transport reports through.
pub type WsEvents = Arc<dyn Fn(WsEvent) + Send + Sync>;

/// A completion callback.
pub type Completion = Box<dyn FnOnce(Result<(), HttpError>) + Send>;

/// The client's grip on one WebSocket.
pub trait Socket: Send + Sync {
    fn send(&self, message: Message, done: Completion);
    fn ping(&self, done: Completion);
    fn close(&self, code: u16, reason: &str);
    /// Receive up to `messages` more messages.
    fn demand(&self, messages: u32);
}

/// One backend.
pub trait Transport: Send + Sync + 'static {
    fn capabilities(&self) -> Capabilities;
    /// Start an exchange. Events may arrive before this returns.
    fn start(&self, request: Prepared, events: Events) -> Arc<dyn Transfer>;
    /// Open a WebSocket.
    fn websocket(&self, request: Prepared, events: WsEvents) -> Arc<dyn Socket> {
        let _ = request;
        events(WsEvent::Failed(HttpError::Unsupported));
        Arc::new(NoSocket)
    }
    /// The platform store's cookies, for [`Cookies::Platform`].
    fn cookies(&self) -> Vec<Cookie> {
        Vec::new()
    }
    /// Forget the platform store's cookies.
    fn clear_cookies(&self) {}
    /// Empty the platform cache.
    fn clear_cache(&self) {}
}

struct NoSocket;

impl Socket for NoSocket {
    fn send(&self, _message: Message, done: Completion) {
        done(Err(HttpError::Unsupported));
    }
    fn ping(&self, done: Completion) {
        done(Err(HttpError::Unsupported));
    }
    fn close(&self, _code: u16, _reason: &str) {}
    fn demand(&self, _messages: u32) {}
}

// ---------------------------------------------------------------------------
// Pins
// ---------------------------------------------------------------------------

// Public-key pins (docs/http.md "Trust"): the SHA-256 of a certificate's SubjectPublicKeyInfo,
// written `sha256/<base64>`. Pinning the key rather than the certificate survives a renewal that
// keeps the key. The DER walk here reads exactly as far as the SPKI and no further.

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Standard base64 with padding.
pub(crate) fn base64_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        out.push(B64[(n >> 18) as usize & 63] as char);
        out.push(B64[(n >> 12) as usize & 63] as char);
        out.push(if chunk.len() > 1 {
            B64[(n >> 6) as usize & 63] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            B64[n as usize & 63] as char
        } else {
            '='
        });
    }
    out
}

/// Standard base64, padding optional, whitespace ignored. `None` on any other character.
pub(crate) fn base64_decode(text: &str) -> Option<Vec<u8>> {
    let mut acc = 0u32;
    let mut bits = 0u32;
    let mut out = Vec::with_capacity(text.len() * 3 / 4);
    for c in text.bytes() {
        let v = match c {
            b'A'..=b'Z' => c - b'A',
            b'a'..=b'z' => c - b'a' + 26,
            b'0'..=b'9' => c - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            b'=' => break,
            b' ' | b'\n' | b'\r' | b'\t' => continue,
            _ => return None,
        };
        acc = (acc << 6) | u32::from(v);
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
            acc &= (1 << bits) - 1;
        }
    }
    Some(out)
}

pub(crate) fn sha256(bytes: &[u8]) -> [u8; 32] {
    let digest = Sha256::digest(bytes);
    let mut out = [0u8; 32];
    out.copy_from_slice(digest.as_slice());
    out
}

pub(crate) fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// One DER element: `(tag, content, the whole element, what follows it)`.
type Tlv<'a> = (u8, &'a [u8], &'a [u8], &'a [u8]);

/// Read the DER element at the start of `data`.
fn read_tlv(data: &[u8]) -> Option<Tlv<'_>> {
    let tag = *data.first()?;
    let first = *data.get(1)?;
    let (len, header) = if first & 0x80 == 0 {
        (usize::from(first), 2)
    } else {
        let n = usize::from(first & 0x7f);
        if n == 0 || n > 4 {
            return None;
        }
        let mut len = 0usize;
        for i in 0..n {
            len = (len << 8) | usize::from(*data.get(2 + i)?);
        }
        (len, 2 + n)
    };
    let end = header.checked_add(len)?;
    if data.len() < end {
        return None;
    }
    Some((tag, &data[header..end], &data[..end], &data[end..]))
}

/// The SubjectPublicKeyInfo element of a DER certificate.
///
/// `Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signature }` and
/// `TBSCertificate ::= SEQUENCE { [0] version OPTIONAL, serialNumber, signature, issuer, validity,
/// subject, subjectPublicKeyInfo, … }`.
pub(crate) fn spki(cert: &[u8]) -> Option<&[u8]> {
    const SEQUENCE: u8 = 0x30;
    let (tag, certificate, _, _) = read_tlv(cert)?;
    if tag != SEQUENCE {
        return None;
    }
    let (tag, tbs, _, _) = read_tlv(certificate)?;
    if tag != SEQUENCE {
        return None;
    }
    let mut rest = tbs;
    let (tag, _, _, after) = read_tlv(rest)?;
    if tag == 0xa0 {
        rest = after;
    }
    for _ in 0..5 {
        let (_, _, _, after) = read_tlv(rest)?;
        rest = after;
    }
    let (tag, _, whole, _) = read_tlv(rest)?;
    (tag == SEQUENCE).then_some(whole)
}

/// The SHA-256 of a certificate's SPKI.
pub(crate) fn spki_sha256(cert: &[u8]) -> Option<[u8; 32]> {
    spki(cert).map(sha256)
}

/// `sha256/<base64>`.
pub(crate) fn pin_string(hash: &[u8; 32]) -> String {
    format!("sha256/{}", base64_encode(hash))
}

/// Parse `sha256/<base64>` (the prefix optional).
pub(crate) fn parse_pin(pin: &str) -> Option<[u8; 32]> {
    let text = pin.trim();
    let text = text.strip_prefix("sha256/").unwrap_or(text);
    let bytes = base64_decode(text)?;
    <[u8; 32]>::try_from(bytes.as_slice()).ok()
}

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

    fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
        let mut out = vec![tag];
        if content.len() < 0x80 {
            out.push(content.len() as u8);
        } else {
            out.push(0x82);
            out.extend_from_slice(&(content.len() as u16).to_be_bytes());
        }
        out.extend_from_slice(content);
        out
    }

    #[test]
    fn base64_round_trips() {
        // RFC 4648's vectors: each prefix of "foobar".
        let full = b"foobar";
        let expected = [
            "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy",
        ];
        for (n, want) in expected.iter().enumerate() {
            let sample = &full[..n];
            assert_eq!(base64_encode(sample), *want);
            assert_eq!(base64_decode(want).as_deref(), Some(sample));
        }
    }

    #[test]
    fn the_spki_is_found_after_the_optional_version() {
        let spki_elem = tlv(0x30, &[0x30, 0x00, 0x03, 0x02, 0x00, 0xAA]);
        let mut tbs = Vec::new();
        tbs.extend(tlv(0xa0, &tlv(0x02, &[2])));
        tbs.extend(tlv(0x02, &[1]));
        for _ in 0..4 {
            tbs.extend(tlv(0x30, &[]));
        }
        tbs.extend(spki_elem.clone());
        tbs.extend(tlv(0xa3, &[0x30, 0x00]));
        let mut cert = tlv(0x30, &tbs);
        cert.extend(tlv(0x30, &[]));
        let cert = tlv(0x30, &cert);
        assert_eq!(spki(&cert), Some(spki_elem.as_slice()));
        let pin = pin_string(&spki_sha256(&cert).unwrap());
        assert_eq!(parse_pin(&pin), Some(sha256(&spki_elem)));
    }

    #[test]
    fn a_malformed_certificate_has_no_spki() {
        assert_eq!(spki(&[0x30, 0x05, 0x30]), None);
        assert_eq!(spki(&[]), None);
    }
}

// ---------------------------------------------------------------------------
// Challenges
// ---------------------------------------------------------------------------

// HTTP authentication the client performs itself (docs/http.md "Challenges"): parsing
// `WWW-Authenticate` and `Proxy-Authenticate`, and writing Basic, Bearer and Digest credentials.
// NTLM and Negotiate are handshakes only an OS stack performs; those arrive as questions from a
// transport that can answer them.

/// One challenge: its scheme and parameters (names lowercased).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ParsedChallenge {
    pub scheme: Scheme,
    pub params: Vec<(String, String)>,
}

impl ParsedChallenge {
    pub(crate) fn param(&self, name: &str) -> Option<&str> {
        self.params
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.as_str())
    }
}

/// Every challenge in the response's `WWW-Authenticate` (or `Proxy-Authenticate`) headers, in
/// order.
pub(crate) fn parse_challenges(headers: &[(String, String)], proxy: bool) -> Vec<ParsedChallenge> {
    let name = if proxy {
        "proxy-authenticate"
    } else {
        "www-authenticate"
    };
    let mut out = Vec::new();
    for (_, value) in headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)) {
        parse_value(value, &mut out);
    }
    out
}

fn parse_value(value: &str, out: &mut Vec<ParsedChallenge>) {
    for item in split_outside_quotes(value) {
        let item = item.trim();
        if item.is_empty() {
            continue;
        }
        let (first, rest) = match item.find(char::is_whitespace) {
            Some(i) => (&item[..i], item[i..].trim()),
            None => (item, ""),
        };
        if first.contains('=') {
            push_param(out, item);
        } else {
            out.push(ParsedChallenge {
                scheme: Scheme::parse(first),
                params: Vec::new(),
            });
            if !rest.is_empty() {
                push_param(out, rest);
            }
        }
    }
}

fn push_param(out: &mut [ParsedChallenge], text: &str) {
    let Some(last) = out.last_mut() else {
        return;
    };
    match text.split_once('=') {
        Some((k, v)) if !k.trim().is_empty() => last
            .params
            .push((k.trim().to_ascii_lowercase(), unquote(v.trim()))),
        _ => last.params.push(("token68".into(), text.to_string())),
    }
}

fn split_outside_quotes(value: &str) -> Vec<String> {
    let mut items = Vec::new();
    let mut current = String::new();
    let mut quoted = false;
    let mut escaped = false;
    for c in value.chars() {
        if escaped {
            current.push(c);
            escaped = false;
            continue;
        }
        match c {
            '\\' if quoted => {
                current.push(c);
                escaped = true;
            }
            '"' => {
                quoted = !quoted;
                current.push(c);
            }
            ',' if !quoted => items.push(std::mem::take(&mut current)),
            _ => current.push(c),
        }
    }
    items.push(current);
    items
}

fn unquote(value: &str) -> String {
    let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) else {
        return value.to_string();
    };
    let mut out = String::with_capacity(inner.len());
    let mut escaped = false;
    for c in inner.chars() {
        if escaped {
            out.push(c);
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else {
            out.push(c);
        }
    }
    out
}

/// `Basic <base64(user:password)>`.
pub(crate) fn basic_authorization(user: &str, password: &str) -> String {
    format!(
        "Basic {}",
        base64_encode(format!("{user}:{password}").as_bytes())
    )
}

/// A fresh client nonce.
fn digest_cnonce() -> String {
    static CNONCES: AtomicU64 = AtomicU64::new(1);
    let n = CNONCES.fetch_add(1, Ordering::Relaxed);
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    hex(&sha256(format!("{n}:{now}").as_bytes())[..8])
}

fn md5_hex(text: &str) -> String {
    use md5::{Digest, Md5};
    let digest = Md5::digest(text.as_bytes());
    hex(digest.as_slice())
}

/// The `Authorization` value answering a Digest challenge (RFC 7616, `qop=auth`), or `None` when
/// the challenge lacks what it needs or names an algorithm this does not implement.
pub(crate) fn digest_authorization(
    challenge: &ParsedChallenge,
    user: &str,
    password: &str,
    method: &str,
    uri: &str,
) -> Option<String> {
    let realm = challenge.param("realm")?;
    let nonce = challenge.param("nonce")?;
    let algorithm = challenge.param("algorithm").unwrap_or("MD5");
    let hash = |text: String| -> Option<String> {
        match algorithm.to_ascii_uppercase().as_str() {
            "MD5" => Some(md5_hex(&text)),
            "SHA-256" => Some(hex(&sha256(text.as_bytes()))),
            _ => None,
        }
    };
    let ha1 = hash(format!("{user}:{realm}:{password}"))?;
    let ha2 = hash(format!("{method}:{uri}"))?;
    let auth_qop = challenge
        .param("qop")
        .is_some_and(|q| q.split(',').any(|t| t.trim() == "auth"));
    let mut value = format!(
        "Digest username=\"{user}\", realm=\"{realm}\", nonce=\"{nonce}\", uri=\"{uri}\", \
         algorithm={algorithm}"
    );
    if auth_qop {
        let nc = "00000001";
        let cnonce = digest_cnonce();
        let response = hash(format!("{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}"))?;
        value.push_str(&format!(
            ", response=\"{response}\", qop=auth, nc={nc}, cnonce=\"{cnonce}\""
        ));
    } else {
        let response = hash(format!("{ha1}:{nonce}:{ha2}"))?;
        value.push_str(&format!(", response=\"{response}\""));
    }
    if let Some(opaque) = challenge.param("opaque") {
        value.push_str(&format!(", opaque=\"{opaque}\""));
    }
    Some(value)
}

/// Check a Digest `Authorization` value against the expected credentials; the test server
/// verifies with it.
// The test server, its one caller, is native-only.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn verify_digest(authorization: &str, user: &str, password: &str, method: &str) -> bool {
    let Some(rest) = authorization.strip_prefix("Digest ") else {
        return false;
    };
    let mut parsed = Vec::new();
    parse_value(&format!("Digest {rest}"), &mut parsed);
    let Some(p) = parsed.first() else {
        return false;
    };
    let (Some(realm), Some(nonce), Some(uri), Some(response)) = (
        p.param("realm"),
        p.param("nonce"),
        p.param("uri"),
        p.param("response"),
    ) else {
        return false;
    };
    if p.param("username") != Some(user) {
        return false;
    }
    let ha1 = md5_hex(&format!("{user}:{realm}:{password}"));
    let ha2 = md5_hex(&format!("{method}:{uri}"));
    let expected = match (p.param("qop"), p.param("nc"), p.param("cnonce")) {
        (Some(qop), Some(nc), Some(cnonce)) => {
            md5_hex(&format!("{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}"))
        }
        _ => md5_hex(&format!("{ha1}:{nonce}:{ha2}")),
    };
    expected == response
}

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

    fn headers(values: &[&str]) -> Vec<(String, String)> {
        values
            .iter()
            .map(|v| ("WWW-Authenticate".to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn parses_several_challenges_with_quoted_commas() {
        let parsed = parse_challenges(
            &headers(&[
                r#"Basic realm="Day, test", charset="UTF-8""#,
                r#"Bearer realm="api", error="invalid_token""#,
            ]),
            false,
        );
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].scheme, Scheme::Basic);
        assert_eq!(parsed[0].param("realm"), Some("Day, test"));
        assert_eq!(parsed[0].param("charset"), Some("UTF-8"));
        assert_eq!(parsed[1].scheme, Scheme::Bearer);
        assert_eq!(parsed[1].param("error"), Some("invalid_token"));
    }

    #[test]
    fn parses_two_challenges_in_one_header() {
        let parsed = parse_challenges(
            &headers(&[r#"Negotiate, Digest realm="r", nonce="n", qop="auth""#]),
            false,
        );
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].scheme, Scheme::Negotiate);
        assert_eq!(parsed[1].scheme, Scheme::Digest);
        assert_eq!(parsed[1].param("nonce"), Some("n"));
    }

    #[test]
    fn basic_encodes_the_pair() {
        assert_eq!(
            basic_authorization("Aladdin", "open sesame"),
            "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
        );
    }

    #[test]
    fn a_digest_answer_verifies() {
        let challenge = parse_challenges(
            &headers(&[r#"Digest realm="Day test", nonce="abc", qop="auth", opaque="xyz""#]),
            false,
        )
        .remove(0);
        let value = digest_authorization(
            &challenge,
            "day",
            "sunrise",
            "GET",
            "/digest-auth/day/sunrise",
        )
        .expect("answer");
        assert!(value.contains("opaque=\"xyz\""), "{value}");
        assert!(verify_digest(&value, "day", "sunrise", "GET"));
        assert!(!verify_digest(&value, "day", "sunset", "GET"));
    }
}

// ---------------------------------------------------------------------------
// Multipart forms
// ---------------------------------------------------------------------------

// `multipart/form-data` bodies (docs/http.md "Uploads"), encoded as a stream: a file part is read
// from disk while it is sent, so a form carrying a large file never sits in memory.

#[derive(Clone, Debug)]
enum PartBody {
    Bytes(Vec<u8>),
    File(PathBuf),
}

#[derive(Clone, Debug)]
struct Part {
    name: String,
    filename: Option<String>,
    content_type: Option<String>,
    body: PartBody,
}

/// A multipart form. Build it, then hand it to `Request::form`.
#[derive(Clone, Debug)]
pub struct Form {
    boundary: String,
    parts: Vec<Part>,
}

impl Default for Form {
    fn default() -> Self {
        Self::new()
    }
}

impl Form {
    /// An empty form with a fresh boundary.
    pub fn new() -> Self {
        static BOUNDARIES: AtomicU64 = AtomicU64::new(1);
        let n = BOUNDARIES.fetch_add(1, Ordering::Relaxed);
        let seed = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let hash = sha256(format!("{n}:{seed}").as_bytes());
        Self {
            boundary: format!("day-{}", hex(&hash[..12])),
            parts: Vec::new(),
        }
    }

    /// A text field.
    pub fn text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.parts.push(Part {
            name: name.into(),
            filename: None,
            content_type: None,
            body: PartBody::Bytes(value.into().into_bytes()),
        });
        self
    }

    /// A file part from bytes in memory.
    pub fn bytes(
        mut self,
        name: impl Into<String>,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        bytes: Vec<u8>,
    ) -> Self {
        self.parts.push(Part {
            name: name.into(),
            filename: Some(filename.into()),
            content_type: Some(content_type.into()),
            body: PartBody::Bytes(bytes),
        });
        self
    }

    /// A file part read from disk while the form is sent.
    pub fn file(
        mut self,
        name: impl Into<String>,
        path: impl Into<PathBuf>,
        content_type: impl Into<String>,
    ) -> Self {
        let path = path.into();
        let filename = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "file".into());
        self.parts.push(Part {
            name: name.into(),
            filename: Some(filename),
            content_type: Some(content_type.into()),
            body: PartBody::File(path),
        });
        self
    }

    /// The `Content-Type` header value, boundary included.
    pub fn content_type(&self) -> String {
        format!("multipart/form-data; boundary={}", self.boundary)
    }

    fn part_header(&self, part: &Part) -> Vec<u8> {
        let escape = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
        let mut head = format!(
            "--{}\r\nContent-Disposition: form-data; name=\"{}\"",
            self.boundary,
            escape(&part.name)
        );
        if let Some(filename) = &part.filename {
            head.push_str(&format!("; filename=\"{}\"", escape(filename)));
        }
        head.push_str("\r\n");
        if let Some(ct) = &part.content_type {
            head.push_str(&format!("Content-Type: {ct}\r\n"));
        }
        head.push_str("\r\n");
        head.into_bytes()
    }

    /// The encoded body as a reader, with its exact length.
    pub(crate) fn reader(&self) -> std::io::Result<(Box<dyn Read + Send>, u64)> {
        let mut pieces: VecDeque<Box<dyn Read + Send>> = VecDeque::new();
        let mut len = 0u64;
        for part in &self.parts {
            let head = self.part_header(part);
            len += head.len() as u64;
            pieces.push_back(Box::new(Cursor::new(head)));
            match &part.body {
                PartBody::Bytes(bytes) => {
                    len += bytes.len() as u64;
                    pieces.push_back(Box::new(Cursor::new(bytes.clone())));
                }
                PartBody::File(path) => {
                    let file = std::fs::File::open(path)?;
                    len += file.metadata()?.len();
                    pieces.push_back(Box::new(file));
                }
            }
            len += 2;
            pieces.push_back(Box::new(Cursor::new(b"\r\n".to_vec())));
        }
        let tail = format!("--{}--\r\n", self.boundary).into_bytes();
        len += tail.len() as u64;
        pieces.push_back(Box::new(Cursor::new(tail)));
        Ok((Box::new(Chain { pieces }), len))
    }
}

struct Chain {
    pieces: VecDeque<Box<dyn Read + Send>>,
}

impl Read for Chain {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        while let Some(front) = self.pieces.front_mut() {
            let n = front.read(buf)?;
            if n > 0 {
                return Ok(n);
            }
            self.pieces.pop_front();
        }
        Ok(0)
    }
}

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

    #[test]
    fn the_declared_length_is_the_encoded_length() {
        let form = Form::new().text("title", "Sunrise").bytes(
            "photo",
            "day.png",
            "image/png",
            vec![1, 2, 3, 4],
        );
        let (mut reader, len) = form.reader().expect("reader");
        let mut out = Vec::new();
        reader.read_to_end(&mut out).expect("read");
        assert_eq!(out.len() as u64, len);
        let text = String::from_utf8_lossy(&out);
        assert!(text.contains("name=\"title\"\r\n\r\nSunrise\r\n"), "{text}");
        assert!(
            text.contains("filename=\"day.png\"\r\nContent-Type: image/png"),
            "{text}"
        );
        assert!(text.ends_with(&format!("--{}--\r\n", form.boundary)));
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod client_tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;

    #[derive(Clone, Debug)]
    struct Seen {
        method: String,
        url: String,
        headers: Vec<(String, String)>,
    }

    impl Seen {
        fn header(&self, name: &str) -> Option<&str> {
            self.headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case(name))
                .map(|(_, v)| v.as_str())
        }
    }

    #[derive(Default)]
    struct Reply {
        status: u16,
        headers: Vec<(String, String)>,
        chunks: Vec<Vec<u8>>,
        question: Option<Question>,
        stall: bool,
        expected: Option<Option<u64>>,
    }

    impl Reply {
        fn new(status: u16) -> Reply {
            Reply {
                status,
                ..Reply::default()
            }
        }
        fn header(mut self, name: &str, value: &str) -> Reply {
            self.headers.push((name.into(), value.into()));
            self
        }
        fn body(mut self, text: &str) -> Reply {
            self.chunks = vec![text.as_bytes().to_vec()];
            self
        }
        fn chunks(mut self, n: u8) -> Reply {
            self.chunks = (0..n).map(|i| vec![i]).collect();
            self
        }
        fn question(mut self, question: Question) -> Reply {
            self.question = Some(question);
            self
        }
        fn stall(mut self) -> Reply {
            self.stall = true;
            self
        }
    }

    type Script = dyn Fn(&Seen) -> Reply + Send + Sync;

    /// A transport that answers each exchange from a script, pulled by demand.
    #[derive(Clone)]
    struct Scripted {
        caps: Capabilities,
        script: Arc<Script>,
        seen: Arc<Mutex<Vec<Seen>>>,
        granted: Arc<AtomicU64>,
        cancels: Arc<AtomicUsize>,
        answers: Arc<Mutex<Vec<Answer>>>,
    }

    impl Scripted {
        fn new(script: impl Fn(&Seen) -> Reply + Send + Sync + 'static) -> Scripted {
            Scripted {
                caps: Capabilities {
                    streaming: true,
                    manual_redirects: true,
                    server_trust: true,
                    websockets: true,
                    ..Capabilities::default()
                },
                script: Arc::new(script),
                seen: Arc::default(),
                granted: Arc::default(),
                cancels: Arc::default(),
                answers: Arc::default(),
            }
        }

        fn seen(&self) -> Vec<Seen> {
            lock(&self.seen).clone()
        }
    }

    struct ExchangeState {
        events: Option<Events>,
        head: Option<Head>,
        chunks: VecDeque<Vec<u8>>,
        demand: u32,
        waiting: bool,
        emitting: bool,
        /// Emits nothing but keeps its events until cancelled, like a real stalled exchange; that
        /// hold is what keeps a callback-started flight alive.
        stalled: bool,
    }

    struct ScriptedTransfer {
        owner: Scripted,
        state: Mutex<ExchangeState>,
    }

    impl ScriptedTransfer {
        fn pump(&self) {
            loop {
                let (events, event) = {
                    let mut st = lock(&self.state);
                    if st.emitting || st.waiting || st.stalled {
                        return;
                    }
                    let Some(events) = st.events.clone() else {
                        return;
                    };
                    let event = if let Some(head) = st.head.take() {
                        Event::Head(head)
                    } else if st.chunks.is_empty() {
                        st.events = None;
                        Event::End
                    } else if st.demand == 0 {
                        return;
                    } else {
                        st.demand -= 1;
                        Event::Chunk(st.chunks.pop_front().unwrap_or_default())
                    };
                    st.emitting = true;
                    (events, event)
                };
                events(event);
                lock(&self.state).emitting = false;
            }
        }
    }

    impl Transfer for ScriptedTransfer {
        fn demand(&self, chunks: u32) {
            self.owner
                .granted
                .fetch_add(u64::from(chunks), Ordering::SeqCst);
            lock(&self.state).demand += chunks;
            self.pump();
        }

        fn answer(&self, _id: QuestionId, answer: Answer) {
            lock(&self.owner.answers).push(answer.clone());
            let refused = {
                let mut st = lock(&self.state);
                st.waiting = false;
                if matches!(answer, Answer::Reject | Answer::Cancel) {
                    st.events.take()
                } else {
                    None
                }
            };
            match refused {
                Some(events) => events(Event::Failed(HttpError::Tls("refused".into()))),
                None => self.pump(),
            }
        }

        fn cancel(&self) {
            self.owner.cancels.fetch_add(1, Ordering::SeqCst);
            let events = lock(&self.state).events.take();
            if let Some(events) = events {
                events(Event::Failed(HttpError::Cancelled));
            }
        }
    }

    struct EchoState {
        events: Option<WsEvents>,
        queue: VecDeque<Message>,
        demand: u32,
    }

    struct EchoSocket(Mutex<EchoState>);

    impl EchoSocket {
        fn pump(&self) {
            loop {
                let (events, message) = {
                    let mut st = lock(&self.0);
                    if st.demand == 0 || st.queue.is_empty() {
                        return;
                    }
                    let Some(events) = st.events.clone() else {
                        return;
                    };
                    st.demand -= 1;
                    (events, st.queue.pop_front())
                };
                if let Some(message) = message {
                    events(WsEvent::Message(message));
                }
            }
        }
    }

    impl Socket for EchoSocket {
        fn send(&self, message: Message, done: Completion) {
            lock(&self.0).queue.push_back(message);
            done(Ok(()));
            self.pump();
        }
        fn ping(&self, done: Completion) {
            done(Ok(()));
        }
        fn close(&self, code: u16, reason: &str) {
            let events = lock(&self.0).events.take();
            if let Some(events) = events {
                events(WsEvent::Closed {
                    code,
                    reason: reason.to_string(),
                });
            }
        }
        fn demand(&self, messages: u32) {
            lock(&self.0).demand += messages;
            self.pump();
        }
    }

    impl Transport for Scripted {
        fn capabilities(&self) -> Capabilities {
            self.caps
        }

        fn start(&self, request: Prepared, events: Events) -> Arc<dyn Transfer> {
            let seen = Seen {
                method: request.method.clone(),
                url: request.url.clone(),
                headers: request.headers.clone(),
            };
            lock(&self.seen).push(seen.clone());
            let reply = (self.script)(&seen);
            let expected = reply.chunks.iter().map(|c| c.len() as u64).sum();
            let transfer = Arc::new(ScriptedTransfer {
                owner: self.clone(),
                state: Mutex::new(ExchangeState {
                    events: Some(events.clone()),
                    head: Some(Head {
                        status: reply.status,
                        headers: reply.headers,
                        url: request.url,
                        expected_length: reply.expected.unwrap_or(Some(expected)),
                    }),
                    chunks: reply.chunks.into(),
                    demand: 0,
                    waiting: reply.question.is_some(),
                    emitting: false,
                    stalled: reply.stall,
                }),
            });
            if let Some(question) = reply.question {
                events(Event::Question(7, question));
            }
            transfer.pump();
            transfer
        }

        fn websocket(&self, request: Prepared, events: WsEvents) -> Arc<dyn Socket> {
            let socket = Arc::new(EchoSocket(Mutex::new(EchoState {
                events: Some(events.clone()),
                queue: VecDeque::new(),
                demand: 0,
            })));
            events(WsEvent::Open {
                protocol: request.protocols.first().cloned(),
            });
            socket
        }
    }

    fn builder(t: &Scripted) -> ClientBuilder {
        Client::builder()
            .transport(t.clone())
            .cookies(Cookies::jar())
    }

    fn der(tag: u8, content: &[u8]) -> Vec<u8> {
        let mut out = vec![tag, content.len() as u8];
        out.extend_from_slice(content);
        out
    }

    fn fake_certificate(key: u8) -> Vec<u8> {
        let mut tbs = der(0x02, &[1]);
        for _ in 0..4 {
            tbs.extend(der(0x30, &[]));
        }
        tbs.extend(der(0x30, &[0x03, 0x02, 0x00, key]));
        der(0x30, &der(0x30, &tbs))
    }

    #[test]
    fn a_303_is_followed_as_a_get() {
        let t = Scripted::new(|seen| match seen.url.as_str() {
            "http://day.test/a" => Reply::new(303).header("Location", "/b"),
            _ => Reply::new(200).body("done"),
        });
        let client = builder(&t).build();
        let resp = wait(client.fetch_future(Request::post("http://day.test/a", b"x".to_vec())))
            .expect("response");
        assert_eq!(resp.text(), "done");
        assert_eq!(resp.url, "http://day.test/b");
        let methods: Vec<String> = t.seen().into_iter().map(|s| s.method).collect();
        assert_eq!(methods, ["POST", "GET"]);
    }

    #[test]
    fn credentials_and_cookies_stay_behind_on_another_origin() {
        let t = Scripted::new(|seen| match seen.url.as_str() {
            "http://one.test/" => Reply::new(302).header("Location", "http://two.test/"),
            _ => Reply::new(200),
        });
        let jar = Arc::new(CookieJar::new());
        jar.store("http://one.test/", ["id=1"]);
        let client = Client::builder()
            .transport(t.clone())
            .cookies(Cookies::Jar(jar))
            .build();
        wait(client.fetch_future(Request::get("http://one.test/").bearer("secret")))
            .expect("response");
        let seen = t.seen();
        assert_eq!(seen[0].header("authorization"), Some("Bearer secret"));
        assert_eq!(seen[0].header("cookie"), Some("id=1"));
        assert_eq!(seen[1].header("authorization"), None);
        assert_eq!(seen[1].header("cookie"), None);
    }

    #[test]
    fn the_redirect_limit_fails_the_request() {
        let t = Scripted::new(|_| Reply::new(302).header("Location", "/again"));
        let client = builder(&t).redirects(Redirects::Follow(3)).build();
        let err = wait(client.fetch_future(Request::get("http://day.test/"))).unwrap_err();
        assert_eq!(err, HttpError::TooManyRedirects);
        assert_eq!(t.seen().len(), 4);
    }

    #[test]
    fn never_delivers_the_redirect_itself() {
        let t = Scripted::new(|_| Reply::new(301).header("Location", "/moved").body("moved"));
        let client = builder(&t).redirects(Redirects::Never).build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
        assert_eq!((resp.status, resp.text().as_ref()), (301, "moved"));
    }

    #[test]
    fn a_redirect_handler_decides_each_hop() {
        let t = Scripted::new(|seen| match seen.url.as_str() {
            "http://day.test/1" => Reply::new(302).header("Location", "/2"),
            "http://day.test/2" => Reply::new(302)
                .header("Location", "/3")
                .body("stopped here"),
            _ => Reply::new(200),
        });
        let hops = Arc::new(Mutex::new(Vec::new()));
        let log = hops.clone();
        let client = builder(&t)
            .on_redirect(move |hop, reply| {
                lock(&log).push(hop.to.clone());
                if hop.followed == 0 {
                    drop(reply);
                } else {
                    reply.stop();
                }
            })
            .build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/1"))).expect("response");
        assert_eq!((resp.status, resp.text().as_ref()), (302, "stopped here"));
        assert_eq!(*lock(&hops), ["http://day.test/2", "http://day.test/3"]);
    }

    #[test]
    fn a_redirect_handler_needs_manual_redirects() {
        let mut t = Scripted::new(|_| Reply::new(200));
        t.caps.manual_redirects = false;
        let client = builder(&t).on_redirect(|_, reply| reply.follow()).build();
        let err = wait(client.fetch_future(Request::get("http://day.test/"))).unwrap_err();
        assert_eq!(err, HttpError::Unsupported);
    }

    #[test]
    fn a_basic_challenge_is_answered_once_and_remembered() {
        let t = Scripted::new(|seen| match seen.header("authorization") {
            Some(a) if a == basic_authorization("day", "sunrise") => Reply::new(200).body("in"),
            _ => Reply::new(401).header("WWW-Authenticate", "Basic realm=\"Day test\""),
        });
        let asked = Arc::new(AtomicUsize::new(0));
        let count = asked.clone();
        let client = builder(&t)
            .on_challenge(move |challenge, reply| {
                count.fetch_add(1, Ordering::SeqCst);
                assert_eq!(challenge.scheme, Scheme::Basic);
                assert_eq!(challenge.realm.as_deref(), Some("Day test"));
                reply.credential("day", "sunrise");
            })
            .build();
        for _ in 0..2 {
            let resp = wait(client.fetch_future(Request::get("http://day.test/private")))
                .expect("response");
            assert_eq!(resp.text(), "in");
        }
        assert_eq!(asked.load(Ordering::SeqCst), 1);
        assert_eq!(t.seen().len(), 4);
    }

    #[test]
    fn a_digest_challenge_is_answered() {
        let t = Scripted::new(|seen| match seen.header("authorization") {
            Some(a) if verify_digest(a, "day", "sunrise", &seen.method) => {
                Reply::new(200).body("in")
            }
            _ => Reply::new(401).header(
                "WWW-Authenticate",
                "Digest realm=\"Day test\", nonce=\"n1\", qop=\"auth\"",
            ),
        });
        let client = builder(&t)
            .on_challenge(|_, reply| reply.credential("day", "sunrise"))
            .build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/digest?x=1")))
            .expect("response");
        assert_eq!(resp.text(), "in");
    }

    #[test]
    fn refused_credentials_end_with_the_401() {
        let t = Scripted::new(|_| {
            Reply::new(401).header("WWW-Authenticate", "Basic realm=\"Day test\"")
        });
        let client = builder(&t)
            .on_challenge(|_, reply| reply.credential("day", "wrong"))
            .build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
        assert_eq!(resp.status, 401);
        assert_eq!(t.seen().len(), 1 + MAX_AUTH_ATTEMPTS as usize);
    }

    #[test]
    fn without_a_handler_the_401_is_the_response() {
        let t = Scripted::new(|_| Reply::new(401).header("WWW-Authenticate", "Bearer"));
        let client = builder(&t).build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
        assert_eq!(resp.status, 401);
        assert_eq!(t.seen().len(), 1);
    }

    #[test]
    fn cookies_set_during_a_redirect_reach_the_next_hop() {
        let t = Scripted::new(|seen| match seen.url.as_str() {
            "http://day.test/login" => Reply::new(302)
                .header("Location", "/home")
                .header("Set-Cookie", "session=abc; Path=/; HttpOnly"),
            _ => Reply::new(200),
        });
        let client = builder(&t).build();
        wait(client.fetch_future(Request::get("http://day.test/login"))).expect("response");
        assert_eq!(t.seen()[1].header("cookie"), Some("session=abc"));
        assert_eq!(client.cookies().len(), 1);
        client.clear_cookies();
        assert!(client.cookies().is_empty());
    }

    #[test]
    fn the_jar_follows_domain_path_and_secure_rules() {
        let jar = CookieJar::new();
        jar.store(
            "https://www.day.test/app/page",
            [
                "a=1",
                "b=2; Domain=day.test; Path=/",
                "c=3; Secure; Path=/",
                "d=4; Domain=test",
                "e=5; Max-Age=0",
                "f=6; Domain=other.test",
            ],
        );
        assert_eq!(
            jar.header("https://www.day.test/app/x").as_deref(),
            Some("a=1; b=2; c=3")
        );
        assert_eq!(
            jar.header("http://www.day.test/app/x").as_deref(),
            Some("a=1; b=2")
        );
        assert_eq!(jar.header("https://api.day.test/").as_deref(), Some("b=2"));
        assert_eq!(
            jar.header("https://www.day.test/other").as_deref(),
            Some("b=2; c=3")
        );
        jar.store(
            "https://www.day.test/",
            ["b=; Domain=day.test; Path=/; Max-Age=0"],
        );
        assert_eq!(
            jar.header("https://www.day.test/other").as_deref(),
            Some("c=3")
        );
    }

    #[test]
    fn a_persistent_jar_keeps_only_cookies_with_an_expiry() {
        let dir = std::env::temp_dir().join(format!("day-http-jar-{}", std::process::id()));
        let file = dir.join("cookies");
        let _ = std::fs::remove_file(&file);
        let jar = CookieJar::open(&file);
        jar.store(
            "https://day.test/",
            ["session=1", "remember=2; Max-Age=3600"],
        );
        let reopened = CookieJar::open(&file);
        assert_eq!(
            reopened.header("https://day.test/").as_deref(),
            Some("remember=2")
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn bounded_progress_distinguishes_known_unknown_and_encoded_bodies() {
        for (advertised, encoding, expected) in [
            (Some(4), "identity", Some(4)),
            (None, "identity", None),
            (Some(2), "gzip", None),
        ] {
            let t = Scripted::new(move |_| {
                let mut reply = Reply::new(200)
                    .chunks(4)
                    .header("Content-Encoding", encoding);
                reply.expected = Some(advertised);
                reply
            });
            let client = builder(&t).build();
            let mut observations = Vec::new();
            let response = wait(client.fetch_limited_with_progress_future(
                Request::get("http://day.test/progress"),
                10,
                |received, total| observations.push((received, total)),
            ))
            .unwrap();
            assert_eq!(response.body, vec![0, 1, 2, 3]);
            assert_eq!(observations.first(), Some(&(0, None)));
            assert_eq!(observations.last(), Some(&(4, expected)));
            assert!(observations.windows(2).all(|pair| pair[0].0 <= pair[1].0));
        }
    }

    #[test]
    fn bounded_downloads_check_both_headers_and_streamed_bytes() {
        for advertised in [Some(100), None, Some(1)] {
            let t = Scripted::new(move |_| {
                let mut reply = Reply::new(200).chunks(100);
                reply.expected = Some(advertised);
                reply
            });
            let client = builder(&t).build();
            assert!(matches!(
                wait(client.fetch_limited_future(Request::get("http://day.test/big"), 10)),
                Err(HttpError::BodyTooLarge { limit: 10 })
            ));
            assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
        }
        let t = Scripted::new(|_| Reply::new(200).body("exact"));
        let client = builder(&t).build();
        assert_eq!(
            wait(client.fetch_limited_future(Request::get("http://day.test/exact"), 5))
                .unwrap()
                .body,
            b"exact"
        );
    }

    #[test]
    fn bounded_bodyless_responses_ignore_representation_length() {
        for (method, status) in [(Method::Get, 304), (Method::Head, 200), (Method::Get, 204)] {
            let t = Scripted::new(move |_| {
                let mut reply = Reply::new(status);
                reply.expected = Some(Some(100_000));
                reply
            });
            let mut req = Request::get("http://day.test/unchanged");
            req.method = method;
            let response = wait(builder(&t).build().fetch_limited_future(req, 0)).unwrap();
            assert_eq!(response.status, status);
            assert!(response.body.is_empty());
        }
    }

    #[test]
    fn a_slow_reader_holds_the_transport_to_its_window() {
        let t = Scripted::new(|_| Reply::new(200).chunks(100));
        let client = builder(&t).build();
        let streaming =
            wait(client.send_future(Request::get("http://day.test/big"))).expect("head");
        assert_eq!(streaming.expected_length(), Some(100));
        let mut body = streaming.into_body();
        assert_eq!(wait(body.next()), Some(Ok(vec![0])));
        let granted = t.granted.load(Ordering::SeqCst);
        assert!(granted <= u64::from(WINDOW), "granted {granted}");
        let mut all = vec![0u8];
        while let Some(chunk) = wait(body.next()) {
            all.extend(chunk.expect("chunk"));
        }
        assert_eq!(all, (0..100).collect::<Vec<u8>>());
        assert_eq!(body.received(), 100);
    }

    #[test]
    fn dropping_an_unread_body_cancels_the_exchange() {
        let t = Scripted::new(|_| Reply::new(200).chunks(100));
        let client = builder(&t).build();
        let streaming =
            wait(client.send_future(Request::get("http://day.test/big"))).expect("head");
        drop(streaming);
        assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn dropping_the_send_future_cancels_the_exchange() {
        let t = Scripted::new(|_| Reply::new(200).stall());
        let client = builder(&t).build();
        drop(client.send_future(Request::get("http://day.test/")));
        assert_eq!(t.cancels.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn read_async_hands_over_every_chunk_then_the_end() {
        let t = Scripted::new(|_| Reply::new(200).chunks(10));
        let client = builder(&t).build();
        let (tx, rx) = std::sync::mpsc::channel();
        client.send_async(Request::get("http://day.test/"), move |head| {
            let body = head.expect("head").into_body();
            body.read_async(move |item| {
                let more = matches!(item, Some(Ok(_)));
                let _ = tx.send(item.map(|r| r.map(|c| c[0])));
                more
            });
        });
        let items: Vec<_> = rx.iter().take(11).collect();
        let expected: Vec<_> = (0..10).map(|i| Some(Ok(i))).collect();
        assert_eq!(&items[..10], &expected[..]);
        assert_eq!(items[10], None);
    }

    #[test]
    fn a_pin_that_matches_accepts_and_one_that_does_not_rejects() {
        let cert = fake_certificate(0xAA);
        let good = pin_string(&spki_sha256(&cert).expect("spki"));
        let asking = |cert: Vec<u8>| {
            move |_: &Seen| {
                Reply::new(200)
                    .body("secure")
                    .question(Question::ServerTrust(ServerTrust {
                        host: "day.test".into(),
                        chain: vec![cert.clone()],
                        system_trusted: true,
                        system_error: None,
                    }))
            }
        };
        let t = Scripted::new(asking(cert.clone()));
        let client = builder(&t)
            .trust(Trust::system().pin("day.test", &good))
            .build();
        let resp = wait(client.fetch_future(Request::get("https://day.test/"))).expect("response");
        assert_eq!(resp.text(), "secure");
        assert_eq!(*lock(&t.answers), [Answer::Accept]);

        let t = Scripted::new(asking(cert));
        let wrong = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
        let client = builder(&t)
            .trust(Trust::system().pin("*.test", wrong))
            .build();
        let err = wait(client.fetch_future(Request::get("https://day.test/"))).unwrap_err();
        assert!(matches!(err, HttpError::Tls(_)), "{err:?}");
        assert_eq!(*lock(&t.answers), [Answer::Reject]);
    }

    #[test]
    fn a_trust_handler_may_accept_what_the_platform_refused() {
        let t = Scripted::new(|_| {
            Reply::new(200).question(Question::ServerTrust(ServerTrust {
                host: "self-signed.test".into(),
                chain: Vec::new(),
                system_trusted: false,
                system_error: Some("self-signed".into()),
            }))
        });
        let client = builder(&t)
            .on_server_trust(|trust, reply| {
                if trust.host == "self-signed.test" {
                    reply.accept()
                } else {
                    reply.reject()
                }
            })
            .build();
        let resp =
            wait(client.fetch_future(Request::get("https://self-signed.test/"))).expect("response");
        assert_eq!(resp.status, 200);
        assert_eq!(*lock(&t.answers), [Answer::Accept]);
    }

    #[test]
    fn a_question_nobody_answers_takes_its_default_after_the_timeout() {
        static HELD: Mutex<Vec<ChallengeReply>> = Mutex::new(Vec::new());
        let t =
            Scripted::new(|_| Reply::new(401).header("WWW-Authenticate", "Bearer realm=\"api\""));
        let client = builder(&t)
            .question_timeout(Duration::from_millis(50))
            .on_challenge(|_, reply| lock(&HELD).push(reply))
            .build();
        let resp = wait(client.fetch_future(Request::get("http://day.test/"))).expect("response");
        assert_eq!(resp.status, 401);
        lock(&HELD).clear();
    }

    #[test]
    fn the_total_limit_fails_a_stalled_request() {
        let t = Scripted::new(|_| Reply::new(200).stall());
        let client = builder(&t).timeout_total(Duration::from_millis(50)).build();
        // The count is read inside the callback, where the caller first hears of the timeout:
        // the stalled exchange must be cancelled by then, not a moment later on the timer's
        // thread (reading it after a woken future raced that thread, and lost on Windows CI).
        let cancels = t.cancels.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let _flight = client.fetch_async(Request::get("http://day.test/"), move |result| {
            let _ = tx.send((result.err(), cancels.load(Ordering::SeqCst)));
        });
        let (err, cancelled) = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("the total limit fires");
        assert_eq!(err, Some(HttpError::Timeout));
        assert_eq!(cancelled, 1);
    }

    #[test]
    fn a_bad_url_fails_before_any_exchange() {
        let t = Scripted::new(|_| Reply::new(200));
        let client = builder(&t).build();
        let err = wait(client.fetch_future(Request::get("ftp://day.test/"))).unwrap_err();
        assert!(matches!(err, HttpError::BadUrl(_)), "{err:?}");
        assert!(t.seen().is_empty());
    }

    #[test]
    fn a_websocket_echoes_then_closes_with_a_code() {
        let t = Scripted::new(|_| Reply::new(200));
        let client = builder(&t).build();
        let mut socket =
            wait(client.websocket_future(Request::get("ws://day.test/echo").protocols(["chat"])))
                .expect("open");
        assert_eq!(socket.protocol().as_deref(), Some("chat"));
        wait(socket.send_future(Message::Text("hello".into())))
            .expect("delivered")
            .expect("sent");
        assert_eq!(wait(socket.next()), Some(Ok(Message::Text("hello".into()))));
        socket.close(4000, "done");
        assert_eq!(
            wait(socket.next()),
            Some(Ok(Message::Close {
                code: 4000,
                reason: "done".into()
            }))
        );
        assert_eq!(wait(socket.next()), None);
    }
}