ntex 4.0.0-beta.17

Framework for composable network services
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
//! HTTP/1 protocol dispatcher
use std::{future, io, mem, pin::Pin, rc::Rc, task::Context, task::Poll, task::ready};

use crate::io::{Decoded, Filter, Io, IoStatusUpdate, RecvError};
use crate::service::pipeline::{Pipeline, PipelineCall};
use crate::{channel::bstream, util::clone_io_error};

use crate::http::body::{Body, MessageBody, ResponseBody};
use crate::http::error::{DispatchError, PayloadError, ResponseError};
use crate::http::message::CurrentIo;
use crate::http::{
    self, StatusCode, config::DispatcherConfig, request::Request, response::Response,
};

use super::control::{Control, ControlAck, ControlResult, ServiceDisconnectReason};
use super::decoder::{PayloadDecoder, PayloadItem, PayloadType};
use super::payload::{Payload, PayloadSender};
use super::{Message, ProtocolError, codec::Codec, timer::Timer, timer::Timers};

pin_project_lite::pin_project! {
    /// Dispatcher for HTTP/1.1 protocol
    pub struct Dispatcher<F, B, Err> {
        st: State<F, B, Err>,
        inner: DispatcherInner<F, B, Err>,
    }
}

#[derive(Debug)]
enum State<F, B, Err> {
    CallPublish {
        fut: PipelineCall<Request, Response<B>, Err>,
    },
    CallControl {
        fut: PipelineCall<Control<F, Err>, ControlAck<F>, DispatchError>,
    },
    ReadRequest,
    ReadPayload,
    SendPayload {
        body: ResponseBody<B>,
    },
    Stop,
}

/// Request payload failure
#[derive(Debug)]
enum PayloadFailure {
    /// Protocol error or payload read timeout
    Protocol(ProtocolError),
    /// Peer is gone or write backpressure timeout
    PeerGone(Option<io::Error>),
}

/// Control service disconnect state
#[derive(Debug)]
enum Disconnect {
    None,
    /// Disconnect reason to send once the current response is written
    Pending(ServiceDisconnectReason),
    /// Disconnect control message has been sent
    Sent,
}

struct DispatcherInner<F, B, Err> {
    io: Rc<Io<F>>,
    codec: Codec,
    timers: Timers,
    config: DispatcherConfig,
    disconnect: Disconnect,
    service: Pipeline<Request, Response<B>, Err>,
    control: Option<Pipeline<Control<F, Err>, ControlAck<F>, DispatchError>>,
    payload: Option<(PayloadDecoder, PayloadSender)>,
    pending_payload_error: Option<PayloadFailure>,
    /// The response head is sent and its body is not complete
    response_started: bool,
}

impl<F, B, Err> Dispatcher<F, B, Err>
where
    F: Filter,
    B: MessageBody,
    Err: ResponseError + 'static,
{
    /// Construct new `Dispatcher` instance with outgoing messages stream.
    ///
    /// Without a control service the default action is applied to every
    /// control message.
    pub(in crate::http) fn new(
        id: usize,
        io: Io<F>,
        service: Pipeline<Request, Response<B>, Err>,
        control: Option<Pipeline<Control<F, Err>, ControlAck<F>, DispatchError>>,
        config: DispatcherConfig,
    ) -> Self {
        let codec = Codec::new(id, io.shared().get());

        // slow-request timer
        let timers = Timers::new(&io, codec.cfg.headers_read_rate);

        Dispatcher {
            st: State::ReadRequest,
            inner: DispatcherInner {
                codec,
                timers,
                config,
                service,
                control,
                io: Rc::new(io),
                payload: None,
                pending_payload_error: None,
                response_started: false,
                disconnect: Disconnect::None,
            },
        }
    }
}

impl<F, B, Err> future::Future for Dispatcher<F, B, Err>
where
    F: Filter,
    B: MessageBody,
    Err: ResponseError + 'static,
{
    type Output = Result<(), DispatchError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let inner = this.inner;

        loop {
            *this.st = match this.st {
                // handle publish service responses
                State::CallPublish { fut } => match Pin::new(fut).poll(cx) {
                    Poll::Ready(Ok(res)) => {
                        let (res, body) = res.into_parts();
                        inner.send_response(res, body)
                    }
                    Poll::Ready(Err(err)) => inner.ctl_error(err),
                    Poll::Pending => {
                        // state changed because of error
                        // otherwise .poll_request() returns Poll::Pending
                        let st = ready!(inner.poll_request(cx));

                        // spawn current publish future to runtime
                        // so it could complete error handling
                        if let State::CallPublish { fut } =
                            mem::replace(&mut *this.st, State::ReadRequest)
                        {
                            crate::rt::spawn(fut);
                        }
                        st
                    }
                },
                // handle control service responses
                State::CallControl { fut } => {
                    let result = match Pin::new(fut).poll(cx) {
                        Poll::Ready(result) => result,
                        Poll::Pending => {
                            // Check for payload errors while waiting for the control
                            // service, but preserve the in-flight control call.
                            if inner.pending_payload_error.is_none()
                                && let Poll::Ready(Err(err)) = inner.poll_request_payload_inner(cx)
                            {
                                inner.pending_payload_error = Some(err);
                            }
                            return Poll::Pending;
                        }
                    };

                    match result {
                        Ok(ControlAck { result }) => inner.control_result(result),
                        Err(err) => {
                            log::error!("{}: Control plain error: {}", inner.io.tag(), err);
                            return Poll::Ready(Err(err));
                        }
                    }
                }
                // read request and call service
                State::ReadRequest => {
                    if let Some(st) = inner.check_disconnect() {
                        st
                    } else {
                        ready!(inner.poll_read_request(cx))
                    }
                }
                // consume request's payload
                State::ReadPayload => {
                    let result = inner.poll_request_payload(cx);
                    if let Some(st) = inner.check_disconnect() {
                        st
                    } else {
                        // a partially decoded payload keeps reading the payload
                        ready!(result).unwrap_or_else(|| {
                            if inner.payload.is_some() {
                                State::ReadPayload
                            } else {
                                inner.next_request()
                            }
                        })
                    }
                }
                // send response body
                State::SendPayload { body } => {
                    ready!(inner.poll_send_payload(cx, body))
                }
                // shutdown io
                State::Stop => {
                    let _ = ready!(inner.io.poll_shutdown(cx));
                    return Poll::Ready(Ok(()));
                }
            }
        }
    }
}

impl<F, B, Err> Drop for DispatcherInner<F, B, Err> {
    fn drop(&mut self) {
        // a detached service call must not wait for the rest of the payload
        if let Some((_, sender)) = self.payload.take() {
            sender.set_error(PayloadError::Incomplete(None));
        }
    }
}

impl<F, B, Err> DispatcherInner<F, B, Err>
where
    F: Filter,
    B: MessageBody,
    Err: ResponseError + 'static,
{
    fn poll_read_request(&mut self, cx: &mut Context<'_>) -> Poll<State<F, B, Err>> {
        loop {
            // stop dispatcher
            if self.config.is_shutdown() {
                log::trace!("{}: Service is shutting down", self.io.tag());
                return Poll::Ready(self.ctl_svc_disconnect(ServiceDisconnectReason::Shutdown));
            }

            log::trace!("{}: Trying to read http message", self.io.tag());
            self.release_write_timer();
            if !self.io.is_read_filter_paused() {
                self.timers.resume_read(&self.io);
            }

            let (result, timeout) = match self.io.poll_recv_decode(&self.codec, cx) {
                // a request head received together with a read timer wins over
                // its expiry, the buffered input is decoded first
                Err(RecvError::Timeout)
                    if !self.timers.active.is_write() && self.timers.active != Timer::Idle =>
                {
                    let result = self.io.decode_item(&self.codec);
                    (result.map_err(RecvError::Decoder), true)
                }
                result => (result, false),
            };

            let result = match result {
                Ok(decoded) => {
                    self.timers.headers_decoded(
                        (decoded.consumed + decoded.remains) as u32,
                        decoded.remains as u32,
                    );
                    if timeout && decoded.item.is_none() {
                        match self.headers_timeout(&decoded) {
                            Ok(()) => continue,
                            Err(st) => return Poll::Ready(st),
                        }
                    }
                    if let Some(st) = self.update_hdrs_timer(&decoded) {
                        return Poll::Ready(st);
                    }
                    if let Some(item) = decoded.item {
                        Ok(item)
                    } else {
                        // the filter chain pauses reading, the peer is not
                        // charged for it
                        if self.io.is_read_filter_paused() {
                            self.timers.suspend_read(&self.io);
                        }
                        return Poll::Pending;
                    }
                }
                Err(err) => Err(err),
            };

            // decode incoming bytes stream
            let st = match result {
                Ok((mut req, pl)) => {
                    log::trace!(
                        "{}: Http message is received: {:?} and payload {:?}",
                        self.io.tag(),
                        req,
                        pl
                    );
                    req.head_mut().io = CurrentIo::Ref(self.io.get_ref());

                    // configure request payload
                    match pl {
                        PayloadType::None => (),
                        PayloadType::Payload(decoder) | PayloadType::Stream(decoder) => {
                            let (ps, pl) = Payload::create();
                            req.replace_payload(http::Payload::H1(pl));
                            self.payload = Some((decoder, ps));

                            // the client does not send the body before `100 Continue`
                            if !req.head().expect() {
                                self.start_payload_timer();
                            }
                        }
                    }
                    self.control(Control::request(req))
                }
                Err(RecvError::WriteBackpressure) => {
                    if let Err(err) = ready!(self.poll_flush_timed(cx)) {
                        log::trace!("{}: Peer is gone with {:?}", self.io.tag(), err);
                        self.ctl_peer_gone(Some(err))
                    } else {
                        continue;
                    }
                }
                Err(RecvError::Decoder(err)) => {
                    // Malformed requests, respond with 400
                    log::trace!("{}: Malformed request: {:?}", self.io.tag(), err);
                    self.ctl_proto_err(err.into())
                }
                Err(RecvError::PeerGone(err)) => {
                    log::trace!("{}: Peer is gone with {:?}", self.io.tag(), err);
                    self.ctl_peer_gone(err)
                }
                Err(RecvError::Timeout) => {
                    if self.timers.active.is_write() {
                        if let Err(err) = self.write_timer_expired() {
                            self.ctl_peer_gone(Some(err))
                        } else {
                            continue;
                        }
                    } else {
                        // expiry of the keep-alive timer left armed for the
                        // previous request
                        continue;
                    }
                }
            };

            return Poll::Ready(st);
        }
    }

    fn send_response(
        &mut self,
        mut msg: Response<()>,
        mut body: ResponseBody<B>,
    ) -> State<F, B, Err> {
        // an interim response cannot complete the request, the next response would
        // be taken as its final response, see RFC 9110 section 15.2
        let status = msg.status();
        if status.is_informational() && status != StatusCode::SWITCHING_PROTOCOLS {
            log::error!(
                "{}: Informational response {status} is not supported, sending 500",
                self.io.tag()
            );
            msg = Response::new(StatusCode::INTERNAL_SERVER_ERROR).drop_body();
            body = ResponseBody::Other(Body::Empty);
        }

        let size = body.size();
        log::trace!(
            "{}: Sending response: {:?} body: {:?}",
            self.io.tag(),
            msg,
            size
        );
        // close connection if payload stream is dropped and not consumed, or
        // the connection is going to be closed after the response
        if matches!(self.disconnect, Disconnect::Pending(_))
            || self
                .payload
                .as_ref()
                .is_some_and(|(_, snd)| snd.is_closed())
        {
            msg.head_mut()
                .set_connection_type(http::ConnectionType::Close);
        }

        // we don't need to process responses if socket is disconnected
        // but we still want to handle requests with app service
        // so we skip response processing for dropped connection
        if self.io.is_active() {
            let result = self
                .io
                .encode(Message::Item((msg, size)), &self.codec)
                .inspect_err(|_| {
                    if let Some(ref mut payload) = self.payload {
                        payload.1.set_error(PayloadError::Incomplete(None));
                    }
                });

            match result {
                // a response without body bytes, for example to a HEAD request,
                // is complete, the body is not polled
                Ok(()) if self.codec.is_body_complete() => self.response_done(),
                Ok(()) => {
                    self.response_started = true;
                    State::SendPayload { body }
                }
                Err(err) => self.ctl_proto_err(err.into()),
            }
        } else {
            self.ctl_peer_gone(None)
        }
    }

    fn poll_send_payload(
        &mut self,
        cx: &mut Context<'_>,
        body: &mut ResponseBody<B>,
    ) -> Poll<State<F, B, Err>> {
        let payload_err = if let Some(err) = self.pending_payload_error.take() {
            Some(err)
        } else if !self.io.is_active() {
            return Poll::Ready(self.ctl_peer_gone(None));
        } else if !matches!(self.disconnect, Disconnect::Pending(_))
            && let Poll::Ready(Err(err)) = self.poll_request_payload_inner(cx)
        {
            Some(err)
        } else {
            None
        };
        match payload_err {
            // peer is gone or write timeout, the response cannot be completed
            Some(PayloadFailure::PeerGone(err)) => return Poll::Ready(self.ctl_peer_gone(err)),
            // the response head is sent, an error response is not possible,
            // finish the response and then stop
            Some(PayloadFailure::Protocol(err)) => {
                log::trace!("{}: Request payload error: {:?}", self.io.tag(), err);
                self.disconnect = Disconnect::Sent;
            }
            None => (),
        }
        loop {
            // encoding is a no-op once the transport is closing, the body
            // would be polled without write backpressure
            if !self.io.is_active() {
                return Poll::Ready(self.ctl_peer_gone(None));
            }
            if self.io.is_wr_backpressure() {
                if let Err(err) = ready!(self.poll_flush_timed(cx)) {
                    return Poll::Ready(self.ctl_peer_gone(Some(err)));
                }
            } else {
                // encoding enables write backpressure once the output exceeds
                // the high watermark, otherwise flushing would not wait
                self.release_write_timer();
            }
            let Poll::Ready(item) = body.poll_next_chunk(cx) else {
                // the client half-closed the connection and has no pipelined
                // requests, an idle body would hold the connection until its
                // next chunk
                if !self.codec.cfg.half_close
                    && self.io.is_read_eof()
                    && self.io.read_dst_size() == 0
                {
                    return Poll::Ready(self.ctl_peer_gone(None));
                }
                // a peer disconnect must be observed while the body is pending
                self.io.register_dispatch(cx);
                return Poll::Pending;
            };

            let st = match item {
                // the declared length is sent or the response has no body,
                // the body is not polled further
                Some(Ok(_)) if self.codec.is_body_complete() => {
                    log::trace!("{}: Response body exceeds its length", self.io.tag());
                    self.response_done()
                }
                Some(Ok(item)) => {
                    log::trace!("{}: Got response chunk: {:?}", self.io.tag(), item.len());
                    match self.io.encode(Message::Chunk(Some(item)), &self.codec) {
                        // the declared length is sent, the body is not polled
                        // for its end, under write backpressure the output is
                        // flushed first
                        Ok(())
                            if self.codec.is_body_complete() && !self.io.is_wr_backpressure() =>
                        {
                            self.response_done()
                        }
                        Ok(()) => continue,
                        Err(err) => self.ctl_proto_err(err.into()),
                    }
                }
                None => {
                    log::trace!(
                        "{}: Response payload eof {:?}",
                        self.io.tag(),
                        self.disconnect
                    );
                    // the end of a body with a declared length encodes nothing
                    if self.codec.is_body_complete() {
                        self.response_done()
                    } else if let Err(err) = self.io.encode(Message::Chunk(None), &self.codec) {
                        self.ctl_proto_err(err.into())
                    } else {
                        self.response_done()
                    }
                }
                Some(Err(err)) => {
                    log::trace!(
                        "{}: Error during response body poll: {:?}",
                        self.io.tag(),
                        err
                    );
                    self.ctl_proto_err(ProtocolError::ResponsePayload(err))
                }
            };
            return Poll::Ready(st);
        }
    }

    /// we might need to read more data into a request payload
    /// (ie service future can wait for payload data)
    fn poll_request(&mut self, cx: &mut Context<'_>) -> Poll<State<F, B, Err>> {
        if self.payload.is_some() {
            if let Some(st) = ready!(self.poll_request_payload(cx)) {
                Poll::Ready(st)
            } else {
                Poll::Pending
            }
        } else if let Some(st) = self.take_payload_error() {
            Poll::Ready(st)
        } else {
            // check for io changes, it could be close while waiting for service call
            let Poll::Ready(status) = self.io.poll_status_update(cx) else {
                // write backpressure can be disabled by the status update
                self.release_write_timer();
                // suspends or resumes the write timer on a filter pause
                if self.timers.active.is_write() {
                    self.timers
                        .start_write(&self.io, self.codec.cfg.write_timeout);
                }
                return Poll::Pending;
            };
            match status {
                IoStatusUpdate::Timeout if self.timers.active.is_write() => {
                    if let Err(err) = self.write_timer_expired() {
                        Poll::Ready(self.ctl_peer_gone(Some(err)))
                    } else {
                        Poll::Pending
                    }
                }
                IoStatusUpdate::Timeout => Poll::Pending,
                IoStatusUpdate::WriteBackpressure => {
                    self.timers
                        .start_write(&self.io, self.codec.cfg.write_timeout);
                    Poll::Pending
                }
                IoStatusUpdate::PeerGone(e) => Poll::Ready(self.ctl_peer_gone(e)),
            }
        }
    }

    /// Fails the request payload, the payload stream ends with `err`.
    fn set_payload_error(&mut self, err: PayloadError) {
        if let Some((_, sender)) = self.payload.take() {
            sender.set_error(err);
        }
    }

    /// Process request's payload
    fn poll_request_payload(&mut self, cx: &mut Context<'_>) -> Poll<Option<State<F, B, Err>>> {
        let result = if let Some(err) = self.pending_payload_error.take() {
            Err(err)
        } else {
            ready!(self.poll_request_payload_inner(cx))
        };
        Poll::Ready(result.err().map(|err| self.ctl_payload_err(err)))
    }

    /// Process request's payload
    fn poll_request_payload_inner(
        &mut self,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), PayloadFailure>> {
        // check if payload data is required
        let Some((_, sender)) = &self.payload else {
            return Poll::Ready(Ok(()));
        };

        match sender.poll_ready(cx) {
            Poll::Ready(bstream::Status::Ready) => {
                // read request payload
                let mut updated = false;
                let mut pending = None;
                self.release_write_timer();
                while let Some((payload_codec, sender)) = self.payload.as_mut() {
                    let result = if pending.is_some() {
                        self.io
                            .decode_item(payload_codec)
                            .map_err(RecvError::Decoder)
                    } else {
                        self.io.poll_recv_decode(payload_codec, cx)
                    };
                    let result = match result {
                        // the request payload is read regardless of write
                        // backpressure, and payload received together with a
                        // read timer wins over its expiry, the buffered input
                        // is decoded first
                        Err(err @ RecvError::WriteBackpressure) => {
                            pending = Some(err);
                            continue;
                        }
                        Err(err @ RecvError::Timeout) if !self.timers.active.is_write() => {
                            pending = Some(err);
                            continue;
                        }
                        Ok(decoded) if decoded.item.is_none() && pending.is_some() => {
                            // the decode attempt can consume bytes without an item
                            self.timers.payload_consumed(decoded.consumed as u32);
                            Err(pending.take().unwrap())
                        }
                        result => result,
                    };

                    let err = match result {
                        Ok(decoded) => {
                            self.timers
                                .payload_decoded(&self.io, decoded.consumed as u32);
                            match decoded.item {
                                Some(PayloadItem::Chunk(chunk)) => {
                                    updated = true;
                                    sender.feed_data(chunk);
                                    continue;
                                }
                                Some(PayloadItem::Trailers(trailers)) => {
                                    sender.feed_trailers(trailers);
                                    continue;
                                }
                                Some(PayloadItem::Eof) => {
                                    updated = true;
                                    sender.feed_eof();
                                    self.timers.payload_done(&self.io);
                                    self.payload = None;
                                    break;
                                }
                                None => {
                                    // the filter chain pauses reading, the
                                    // peer is not charged for it
                                    if self.io.is_read_filter_paused() {
                                        self.timers.suspend_read(&self.io);
                                    }
                                    break;
                                }
                            }
                        }
                        Err(RecvError::WriteBackpressure) => match self.poll_flush_timed(cx) {
                            Poll::Ready(Ok(())) => continue,
                            Poll::Ready(Err(err)) => {
                                self.set_payload_error(PayloadError::Incomplete(Some(
                                    clone_io_error(&err),
                                )));
                                PayloadFailure::PeerGone(Some(err))
                            }
                            Poll::Pending => {
                                self.timers.pause_payload(&self.io);
                                break;
                            }
                        },
                        Err(RecvError::Timeout) if self.timers.active.is_write() => {
                            if let Err(err) = self.write_timer_expired() {
                                PayloadFailure::PeerGone(Some(err))
                            } else {
                                continue;
                            }
                        }
                        Err(RecvError::Timeout) => {
                            if let Err(err) = self.handle_timeout() {
                                PayloadFailure::Protocol(err)
                            } else {
                                continue;
                            }
                        }
                        Err(RecvError::PeerGone(err)) => {
                            self.set_payload_error(PayloadError::Incomplete(
                                err.as_ref().map(clone_io_error),
                            ));
                            PayloadFailure::PeerGone(err)
                        }
                        Err(RecvError::Decoder(e)) => {
                            self.set_payload_error(PayloadError::Decode(e));
                            PayloadFailure::Protocol(ProtocolError::Decode(e))
                        }
                    };
                    return Poll::Ready(Err(err));
                }
                if updated {
                    Poll::Ready(Ok(()))
                } else {
                    Poll::Pending
                }
            }
            Poll::Pending => {
                self.timers.pause_payload(&self.io);
                Poll::Pending
            }
            Poll::Ready(bstream::Status::Dropped | bstream::Status::Eof) => {
                // service call is not interested in payload
                // wait until future completes and then close
                // connection
                self.payload = None;
                self.set_disconnect(ServiceDisconnectReason::PayloadDropped);
                Poll::Pending
            }
        }
    }

    /// Flushes output during write backpressure, bounded by the write
    /// timeout.
    fn poll_flush_timed(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        loop {
            if let Poll::Ready(res) = self.io.poll_flush(cx, false) {
                self.timers.stop_write(&self.io);
                return Poll::Ready(res);
            }
            self.timers
                .start_write(&self.io, self.codec.cfg.write_timeout);
            if !self.timers.active.is_write() {
                return Poll::Pending;
            }
            // the timer is reported through the status update
            match self.io.poll_status_update(cx) {
                Poll::Ready(IoStatusUpdate::Timeout) => {
                    if let Err(err) = self.write_timer_expired() {
                        return Poll::Ready(Err(err));
                    }
                }
                Poll::Pending if !self.io.is_wr_backpressure() => (),
                _ => return Poll::Pending,
            }
        }
    }

    /// Handles expiry of the write timer.
    ///
    /// Fails the request payload and returns the write timeout error if
    /// write backpressure is still enabled, otherwise stops the timer.
    /// An expiry during a filter write pause suspends the timer.
    fn write_timer_expired(&mut self) -> io::Result<()> {
        if self.io.is_wr_backpressure() && self.io.is_write_filter_paused() {
            // the filter chain paused writing before the dispatcher noticed
            self.timers
                .start_write(&self.io, self.codec.cfg.write_timeout);
            Ok(())
        } else if self.io.is_wr_backpressure() {
            log::trace!("{}: Write backpressure timeout", self.io.tag());
            self.set_payload_error(PayloadError::Io(write_timeout_error()));
            Err(write_timeout_error())
        } else {
            self.timers.stop_write(&self.io);
            Ok(())
        }
    }

    /// Stops the write timer if write backpressure has been disabled.
    fn release_write_timer(&mut self) {
        if self.timers.active.is_write() && !self.io.is_wr_backpressure() {
            self.timers.stop_write(&self.io);
        }
    }

    fn handle_timeout(&mut self) -> Result<(), ProtocolError> {
        // check read rate
        let (cfg, payload) = match self.timers.active {
            Timer::Headers => (&self.codec.cfg.headers_read_rate, false),
            Timer::Payload => (&self.codec.cfg.payload_read_rate, true),
            _ => return Ok(()),
        };
        let Some(cfg) = *cfg else {
            return Ok(());
        };
        if self.timers.extend(&self.io, cfg) {
            return Ok(());
        }

        log::trace!(
            "{}: Timeout during reading, {:?}",
            self.io.tag(),
            self.timers.active
        );
        if payload {
            self.set_payload_error(PayloadError::Io(io::Error::new(
                io::ErrorKind::TimedOut,
                "Payload read timeout",
            )));
            Err(ProtocolError::SlowPayloadTimeout)
        } else {
            Err(ProtocolError::SlowRequestTimeout)
        }
    }

    /// Handles expiry of a read timer while a request head is awaited.
    ///
    /// `decoded` is the decode attempt of the input received together with
    /// the expiry, it did not produce a request head.
    fn headers_timeout(
        &mut self,
        decoded: &Decoded<(Request, PayloadType)>,
    ) -> Result<(), State<F, B, Err>> {
        if self.timers.active == Timer::Headers {
            self.handle_timeout().map_err(|err| {
                log::trace!("{}: Slow request timeout", self.io.tag());
                self.ctl_proto_err(err)
            })
        } else if self.start_headers_timer(
            self.codec.is_reading_hdrs(),
            (decoded.consumed + decoded.remains) as u32,
            decoded.remains as u32,
        ) {
            // a partial request head wins over keep-alive or client timeout
            Ok(())
        } else if self.timers.active == Timer::ClientTimeout {
            log::trace!("{}: Client timeout, no request", self.io.tag());
            Err(self.ctl_proto_err(ProtocolError::SlowRequestTimeout))
        } else {
            log::trace!("{}: Keep-alive timeout, close connection", self.io.tag());
            Err(self.ctl_keepalive(true))
        }
    }

    fn update_hdrs_timer(
        &mut self,
        decoded: &Decoded<(Request, PayloadType)>,
    ) -> Option<State<F, B, Err>> {
        let partial = self.codec.is_reading_hdrs() || decoded.remains != 0;
        let remains = decoded.remains as u32;

        if decoded.item.is_some() {
            // got parsed frame
            self.timers.reset(&self.io);
        } else if self.timers.active == Timer::Headers {
            // received new data but not enough for parsing complete frame
            self.timers.progress.remains = remains;
        } else if self.start_headers_timer(
            partial,
            (decoded.consumed as u32).saturating_add(remains),
            remains,
        ) {
            // the headers read rate bounds a partial request head, for the
            // first request it starts with the first received byte
        } else if self.timers.active == Timer::ClientTimeout {
            // only the headers read rate bounds the first request
        } else if partial || self.codec.keepalive() {
            // without a headers read rate the keep-alive timer bounds a
            // partial request head
            if self.codec.cfg.ka_enabled {
                self.timers
                    .start_keepalive(&self.io, self.codec.cfg.keep_alive);
            }
        } else {
            self.io.close();
            return Some(self.ctl_keepalive(false));
        }
        None
    }

    /// Starts request-head timing for a partial request head.
    ///
    /// Returns `false` if the head is not partial or no headers read rate
    /// is configured.
    fn start_headers_timer(&mut self, partial: bool, consumed: u32, remains: u32) -> bool {
        let rate = self.codec.cfg.headers_read_rate;
        if partial && rate.is_some() {
            self.timers.start_headers(&self.io, rate, consumed, remains);
            true
        } else {
            false
        }
    }

    /// Starts payload timing for the current request if it is not started
    /// yet, an expectation can be handled without `100 Continue`.
    fn start_payload_timer(&mut self) {
        if self.payload.is_some()
            && matches!(
                self.timers.active,
                Timer::Stopped | Timer::Idle | Timer::Write
            )
        {
            self.timers
                .start_payload(&self.io, self.codec.cfg.payload_read_rate);
        }
    }

    /// Handles a sent response: reports a pending disconnect, or reads
    /// the rest of the request payload, or the next request.
    fn response_done(&mut self) -> State<F, B, Err> {
        self.response_started = false;
        if let Some(st) = self.check_disconnect() {
            st
        } else if self.payload.is_some() {
            self.start_payload_timer();
            State::ReadPayload
        } else {
            self.next_request()
        }
    }

    /// Reads the next request, unless the last response closes the
    /// connection, then pipelined requests are not processed.
    fn next_request(&mut self) -> State<F, B, Err> {
        if self.codec.keepalive() {
            State::ReadRequest
        } else {
            log::trace!("{}: Connection is not persistent, close", self.io.tag());
            self.io.close();
            self.ctl_keepalive(false)
        }
    }

    fn publish(&mut self, req: Request) -> State<F, B, Err> {
        // payload failed while waiting for the control service
        if let Some(st) = self.take_payload_error() {
            return st;
        }
        self.start_payload_timer();
        State::CallPublish {
            fut: self.service.call_nowait(req),
        }
    }

    fn take_payload_error(&mut self) -> Option<State<F, B, Err>> {
        self.pending_payload_error
            .take()
            .map(|err| self.ctl_payload_err(err))
    }

    fn ctl_payload_err(&mut self, err: PayloadFailure) -> State<F, B, Err> {
        match err {
            PayloadFailure::Protocol(err) => self.ctl_proto_err(err),
            PayloadFailure::PeerGone(err) => self.ctl_peer_gone(err),
        }
    }

    /// Applies the control service acknowledgement.
    fn control_result(&mut self, result: ControlResult<F>) -> State<F, B, Err> {
        match result {
            ControlResult::Publish(req) => self.publish(req),
            // the response head is sent, an error response would be written
            // into the unfinished body
            ControlResult::ProtocolError(..) if self.response_started => {
                log::trace!("{}: Response is incomplete, close", self.io.tag());
                self.response_started = false;
                self.io.close();
                self.stop()
            }
            ControlResult::Response(res, body)
            | ControlResult::Error(res, body)
            | ControlResult::ProtocolError(res, body) => self.send_response(res, body.into()),
            ControlResult::Continue(req) => {
                let result = self.io.encode_slice(b"HTTP/1.1 100 Continue\r\n\r\n");
                if let Err(err) = result {
                    return self.ctl_peer_gone(Some(err));
                }
                self.start_payload_timer();
                if req.upgrade() {
                    self.ctl_upgrade(req)
                } else {
                    self.publish(req)
                }
            }
            ControlResult::Expect(req) => self.control(Control::expect(req)),
            ControlResult::ExpectFailed(res, body) => {
                self.set_disconnect(ServiceDisconnectReason::ExpectFailed);
                self.send_response(res, body.into())
            }
            ControlResult::Upgrade(req) => self.ctl_upgrade(req),
            ControlResult::UpgradeAck(req) => {
                self.set_disconnect(ServiceDisconnectReason::UpgradeHandled);
                self.publish(req)
            }
            ControlResult::UpgradeHandled => {
                self.ctl_svc_disconnect(ServiceDisconnectReason::UpgradeHandled)
            }
            ControlResult::UpgradeFailed(res, body) => {
                self.set_disconnect(ServiceDisconnectReason::UpgradeFailed);
                self.send_response(res, body.into())
            }
            ControlResult::Stop => self.stop(),
            ControlResult::Connect(_) => unreachable!(),
        }
    }

    /// Sends a control message, without a control service the default action
    /// is applied.
    fn control(&mut self, req: Control<F, Err>) -> State<F, B, Err> {
        if let Some(ctl) = &self.control {
            State::CallControl {
                fut: ctl.call_nowait(req),
            }
        } else {
            self.control_result(req.ack().result)
        }
    }

    fn ctl_upgrade(&mut self, req: Request) -> State<F, B, Err> {
        self.codec.reset_upgrade();
        self.control(Control::upgrade(req, self.io.clone(), self.codec.clone()))
    }

    fn ctl_keepalive(&mut self, enabled: bool) -> State<F, B, Err> {
        self.ctl_disconnect(Control::keepalive(enabled))
    }

    fn ctl_error(&mut self, err: Err) -> State<F, B, Err> {
        self.ctl_disconnect(Control::err(err))
    }

    fn ctl_proto_err(&mut self, err: ProtocolError) -> State<F, B, Err> {
        self.ctl_disconnect(Control::proto_err(err))
    }

    fn ctl_peer_gone(&mut self, err: Option<io::Error>) -> State<F, B, Err> {
        self.ctl_disconnect(Control::peer_gone(err))
    }

    fn ctl_svc_disconnect(&mut self, reason: ServiceDisconnectReason) -> State<F, B, Err> {
        self.ctl_disconnect(Control::svc_disconnect(reason))
    }

    /// Records a disconnect reason, unless a disconnect has been sent.
    fn set_disconnect(&mut self, reason: ServiceDisconnectReason) {
        if !matches!(self.disconnect, Disconnect::Sent) {
            self.disconnect = Disconnect::Pending(reason);
        }
    }

    fn ctl_disconnect(&mut self, req: Control<F, Err>) -> State<F, B, Err> {
        if matches!(
            mem::replace(&mut self.disconnect, Disconnect::Sent),
            Disconnect::Sent
        ) {
            self.stop()
        } else {
            self.control(req)
        }
    }

    fn check_disconnect(&mut self) -> Option<State<F, B, Err>> {
        match mem::replace(&mut self.disconnect, Disconnect::Sent) {
            Disconnect::None => {
                self.disconnect = Disconnect::None;
                None
            }
            Disconnect::Pending(reason) => Some(self.control(Control::svc_disconnect(reason))),
            Disconnect::Sent => Some(self.stop()),
        }
    }

    fn stop(&mut self) -> State<F, B, Err> {
        log::debug!("{}: Dispatcher is stopped", self.io.tag());

        self.timers.stop(&self.io);
        State::Stop
    }
}

fn write_timeout_error() -> io::Error {
    io::Error::new(io::ErrorKind::TimedOut, "Write backpressure timeout")
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::{error, future::Future, future::poll_fn, sync::Arc};

    use rand::Rng;

    use super::*;
    use crate::http::config::HttpServiceConfig;
    use crate::http::h1::control::Reason;
    use crate::http::{KeepAlive, ResponseHead, StatusCode, body};
    use crate::io::{self as nio, Base, testing::IoTest};
    use crate::service::{IntoService, Service, cfg::SharedCfg, fn_service};
    use crate::time::{Millis, Seconds, sleep, timeout};
    use crate::util::{Bytes, BytesMut, lazy, stream_recv};
    use crate::{client::ClientCodec, codec::Decoder};

    const BUFFER_SIZE: usize = 32_768;

    #[crate::rt_test]
    async fn test_payload_timer_resume_preserves_maximum() {
        let (_client, server) = IoTest::create();
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_payload_read_rate(Seconds(10), Seconds(15), 1))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        h1.inner.timers.stop(&h1.inner.io);
        h1.inner.payload = Some((PayloadDecoder::length(4), Payload::create().0));
        h1.inner.start_payload_timer();
        h1.inner.timers.payload_decoded(&h1.inner.io, 2);
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds(5));
        assert!(h1.inner.handle_timeout().is_ok());
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds::ZERO);
        assert_eq!(h1.inner.io.timer_handle().remains(), Seconds(5));

        h1.inner.timers.pause_payload(&h1.inner.io);
        assert_eq!(h1.inner.timers.active, Timer::PayloadPaused);
        assert_eq!(h1.inner.timers.progress.period, Seconds(5));
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds::ZERO);

        h1.inner.timers.payload_decoded(&h1.inner.io, 2);
        assert_ne!(h1.inner.timers.active, Timer::PayloadPaused);
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds::ZERO);
        assert_eq!(h1.inner.io.timer_handle().remains(), Seconds(5));
    }

    /// A sent disconnect absorbs pending and later disconnect reasons.
    #[crate::rt_test]
    async fn test_disconnect_state() {
        let (_client, server) = IoTest::create();
        let config: SharedCfg = SharedCfg::new("SVC").into();
        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        assert!(h1.inner.check_disconnect().is_none());
        assert!(matches!(h1.inner.disconnect, Disconnect::None));

        h1.inner
            .set_disconnect(ServiceDisconnectReason::ExpectFailed);
        assert!(matches!(
            h1.inner.disconnect,
            Disconnect::Pending(ServiceDisconnectReason::ExpectFailed)
        ));
        // without a control service the disconnect is acknowledged in place
        assert!(matches!(h1.inner.ctl_peer_gone(None), State::Stop));
        assert!(matches!(h1.inner.disconnect, Disconnect::Sent));

        h1.inner
            .set_disconnect(ServiceDisconnectReason::PayloadDropped);
        assert!(matches!(h1.inner.disconnect, Disconnect::Sent));
        assert!(matches!(h1.inner.check_disconnect(), Some(State::Stop)));
        assert!(matches!(h1.inner.ctl_peer_gone(None), State::Stop));
    }

    fn exhausted_payload_h1(
        server: IoTest,
        rate: u32,
    ) -> (Dispatcher<Base, body::Body, io::Error>, Payload) {
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_payload_read_rate(Seconds(1), Seconds(5), rate))
            .into();
        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );
        let (tx, rx) = Payload::create();
        h1.inner.payload = Some((PayloadDecoder::length(4), tx));
        h1.inner.timers.stop(&h1.inner.io);
        h1.inner.timers.active = Timer::PayloadPaused;
        h1.inner.timers.progress.max_timeout = Seconds::ZERO;
        (h1, rx)
    }

    /// A detached payload reader is woken with an error when the dispatcher
    /// is dropped before the payload is complete.
    #[crate::rt_test]
    async fn test_dropped_dispatcher_fails_detached_payload() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let result = Rc::new(RefCell::new(None));
        let result2 = result.clone();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::new("SVC")),
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| {
                    let result = result2.clone();
                    async move {
                        let mut pl = req.take_payload();
                        crate::rt::spawn(async move {
                            let mut last = None;
                            while let Some(item) = pl.recv().await {
                                last = Some(item);
                            }
                            *result.borrow_mut() = Some(last);
                        });
                        Ok::<_, io::Error>(Response::Ok().build())
                    }
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: a\r\ncontent-length: 10\r\n\r\npart");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(result.borrow().is_none());

        drop(h1);
        sleep(Millis(50)).await;
        let res = result.borrow_mut().take();
        assert!(
            matches!(res, Some(Some(Err(PayloadError::Incomplete(None))))),
            "{res:?}"
        );
    }

    /// Resuming without budget left decodes the buffered payload first.
    #[crate::rt_test]
    async fn test_exhausted_payload_budget_decodes_buffered_data() {
        let (client, server) = IoTest::create();
        let (mut h1, mut rx) = exhausted_payload_h1(server, 1);

        client.write("test");
        sleep(Millis(50)).await;
        let res = lazy(|cx| h1.inner.poll_request_payload_inner(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(()))));
        assert!(h1.inner.payload.is_none());
        assert_eq!(
            stream_recv(&mut rx).await.unwrap().unwrap(),
            Bytes::from("test")
        );
        assert!(stream_recv(&mut rx).await.is_none());

        let (client, server) = IoTest::create();
        let (mut h1, mut rx) = exhausted_payload_h1(server, 1);

        client.write("te");
        sleep(Millis(50)).await;
        let res = lazy(|cx| h1.inner.poll_request_payload_inner(cx)).await;
        assert!(matches!(
            res,
            Poll::Ready(Err(PayloadFailure::Protocol(
                ProtocolError::SlowPayloadTimeout
            )))
        ));
        assert_eq!(
            stream_recv(&mut rx).await.unwrap().unwrap(),
            Bytes::from("te")
        );
        assert!(stream_recv(&mut rx).await.unwrap().is_err());
    }

    /// Resuming continues the interrupted period instead of starting a new one.
    #[crate::rt_test]
    async fn test_payload_resume_continues_period() {
        let (client, server) = IoTest::create();
        let (mut h1, _rx) = exhausted_payload_h1(server, 1);
        h1.inner.timers.progress.period = Seconds(3);
        h1.inner.timers.progress.max_timeout = Seconds(2);

        client.write("te");
        sleep(Millis(50)).await;
        let res = lazy(|cx| h1.inner.poll_request_payload_inner(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(()))));
        assert!(h1.inner.payload.is_some());
        assert_eq!(h1.inner.timers.active, Timer::Payload);
        assert_eq!(h1.inner.io.timer_handle().remains(), Seconds(3));
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds(2));
    }

    /// A period that expired before pausing is checked on resume.
    #[crate::rt_test]
    async fn test_payload_resume_checks_expired_period() {
        let (client, server) = IoTest::create();
        let (mut h1, mut rx) = exhausted_payload_h1(server, 1000);
        h1.inner.timers.progress.max_timeout = Seconds(4);

        client.write("te");
        sleep(Millis(50)).await;
        let res = lazy(|cx| h1.inner.poll_request_payload_inner(cx)).await;
        assert!(matches!(
            res,
            Poll::Ready(Err(PayloadFailure::Protocol(
                ProtocolError::SlowPayloadTimeout
            )))
        ));
        assert_eq!(
            stream_recv(&mut rx).await.unwrap().unwrap(),
            Bytes::from("te")
        );

        // enough data was received, the next period starts
        let (client, server) = IoTest::create();
        let (mut h1, _rx) = exhausted_payload_h1(server, 1);
        h1.inner.timers.progress.max_timeout = Seconds(4);

        client.write("te");
        sleep(Millis(50)).await;
        let res = lazy(|cx| h1.inner.poll_request_payload_inner(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(()))));
        assert!(h1.inner.payload.is_some());
        assert_eq!(h1.inner.timers.active, Timer::Payload);
        assert_eq!(h1.inner.io.timer_handle().remains(), Seconds(1));
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds(3));
    }

    #[crate::rt_test]
    async fn test_header_timeout_does_not_leak_into_payload() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_headers_read_rate(Seconds(10), Seconds(10), 1)
                    .set_payload_read_rate(Seconds(10), Seconds(10), 1)
                    .set_keepalive(KeepAlive::Disabled),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |mut req: Request| {
                    while req.payload().recv().await.is_some() {}
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\n");
        sleep(Millis(50)).await;
        h1.inner.io.notify_timeout();
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.write("body");
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
    }

    #[crate::rt_test]
    async fn test_payload_timeout_does_not_leak_into_keepalive() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_headers_read_rate(Seconds(10), Seconds(10), 1)
                    .set_payload_read_rate(Seconds(10), Seconds(10), 1)
                    .set_keepalive(Seconds(10)),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |mut req: Request| {
                    while req.payload().recv().await.is_some() {}
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.write("body");
        sleep(Millis(50)).await;
        h1.inner.io.notify_timeout();
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);
        assert!(h1.inner.io.is_active());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    #[crate::rt_test]
    async fn test_partial_next_request_wins_keepalive_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_headers_read_rate(Seconds(10), Seconds(20), 1)
                    .set_keepalive(Seconds(10)),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("GET /first HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        let partial = "GET /next HTTP/1.1\r\nhost: example.com";
        client.write(partial);
        sleep(Millis(50)).await;
        h1.inner.io.notify_timeout();

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Headers);
        assert_ne!(h1.inner.timers.active, Timer::KeepAlive);
        assert_eq!(h1.inner.timers.progress.consumed, partial.len() as u32);
        assert!(h1.inner.io.is_active());

        client.write("\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    /// Bytes of a partial request head consumed by a decode attempt that ends
    /// with write backpressure count towards the headers read rate.
    #[crate::rt_test]
    async fn test_headers_rate_counts_bytes_decoded_during_write_backpressure() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(nio::IoConfig::new().set_write_buf(16))
            .add(
                HttpServiceConfig::new()
                    .set_headers_read_rate(Seconds(10), Seconds(20), 1)
                    .set_keepalive(Seconds(10)),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        // the response head of the first request exceeds the write watermark,
        // the decoder consumes the start line of the next request before
        // write backpressure is reported
        let partial = "GET /next HTTP/1.1\r\nhost: example.com";
        client.write(format!(
            "GET /first HTTP/1.1\r\nhost: localhost\r\n\r\n{partial}"
        ));
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_wr_backpressure());
        assert_ne!(h1.inner.timers.active, Timer::Headers);

        client.remote_buffer_cap(1024);
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(!h1.inner.io.is_wr_backpressure());
        assert_eq!(h1.inner.timers.active, Timer::Headers);
        assert_eq!(h1.inner.timers.progress.consumed, partial.len() as u32);

        client.write("\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    fn keepalive_h1(server: IoTest) -> Dispatcher<Base, body::Body, io::Error> {
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_client_timeout(Seconds::ZERO)
                    .set_keepalive(Seconds(1)),
            )
            .into();

        Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        )
    }

    /// Expiry of the keep-alive timer left armed while a request is processed
    /// does not close the connection.
    #[crate::rt_test]
    async fn test_idle_keepalive_expiry_is_ignored() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_client_timeout(Seconds::ZERO)
                    .set_keepalive(Seconds(1)),
            )
            .into();
        let mut h1 = Dispatcher::<_, body::Body, io::Error>::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |req: Request| {
                    if req.path() == "/slow" {
                        sleep(Millis(1300)).await;
                    }
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);

        client.write("GET /slow HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Idle);

        // the armed keep-alive timer expires while the service is busy
        sleep(Millis(1500)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
        assert!(h1.inner.io.is_active());
        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    /// Without request-head timing, waiting for the first request is not
    /// bounded by keep-alive, for an idle or a partially received request.
    #[crate::rt_test]
    async fn test_first_request_unbounded_without_header_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = keepalive_h1(server);

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::ClientTimeout);
        sleep(Millis(2200)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_active());

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::ClientTimeout);
        sleep(Millis(2200)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_active());

        client.write("\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    /// Without request-head timing, a partial next request does not stop the
    /// keep-alive timer.
    #[crate::rt_test]
    async fn test_partial_next_request_keepalive_without_header_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = keepalive_h1(server);

        client.write("GET /first HTTP/1.1\r\nhost: localhost\r\n\r\nGET /next HTTP/1.1\r\nhost: localhost\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);

        client.write("host: example.com");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::KeepAlive);

        let res = timeout(Millis(3000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.unwrap().is_ok());
        assert!(client.read_any().is_empty());
    }

    fn client_timeout_h1(server: IoTest) -> Dispatcher<Base, body::Body, io::Error> {
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_headers_read_rate(Seconds(1), Seconds(5), 1024)
                    .set_keepalive(KeepAlive::Disabled),
            )
            .into();

        Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        )
    }

    /// A new connection that sends nothing is bounded by the client timeout.
    #[crate::rt_test]
    async fn test_client_timeout_without_request() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = client_timeout_h1(server);

        assert_eq!(h1.inner.timers.active, Timer::ClientTimeout);
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::ClientTimeout);

        let res = timeout(Millis(3000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.unwrap().is_ok());
        assert!(
            client
                .read_any()
                .starts_with(b"HTTP/1.1 408 Request Timeout\r\n")
        );
    }

    /// The headers read rate starts with the first byte of the first request,
    /// with the complete cumulative budget.
    #[crate::rt_test]
    async fn test_headers_rate_starts_with_first_byte() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = client_timeout_h1(server);

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::ClientTimeout);

        let partial = "GET / HTTP/1.1\r\nhost: localhost\r\n";
        client.write(partial);
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Headers);
        assert_eq!(h1.inner.timers.progress.consumed, partial.len() as u32);
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds(4));

        client.write("\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"));
    }

    /// The first byte arriving together with the client timeout wins.
    #[crate::rt_test]
    async fn test_first_byte_wins_client_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = client_timeout_h1(server);

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n");
        sleep(Millis(50)).await;
        h1.inner.io.notify_timeout();

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Headers);
        assert!(h1.inner.io.is_active());
        assert!(client.read_any().is_empty());
    }

    #[crate::rt_test]
    async fn test_new_connection_without_header_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_client_timeout(Seconds::ZERO)
                    .set_keepalive(KeepAlive::Disabled),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_active());

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());

        let buf = client.read_any();
        assert!(buf.starts_with(b"HTTP/1.1 200 OK\r\n"));
    }

    /// Create http/1 dispatcher.
    pub(crate) fn h1<F, S, B>(stream: IoTest, s: F) -> Dispatcher<Base, B, S::Error>
    where
        F: IntoService<S, (), Request>,
        S: Service<(), Request> + 'static,
        S::Res: Into<Response<B>>,
        S::Error: ResponseError + 'static,
        B: MessageBody,
    {
        let cfg: SharedCfg = SharedCfg::new("DBG")
            .add(
                HttpServiceConfig::new()
                    .set_keepalive(Seconds(5))
                    .set_client_timeout(Seconds(1)),
            )
            .into();

        Dispatcher::new(
            0,
            nio::Io::new(stream, cfg.clone()),
            Pipeline::new((), s.into_service().map(Into::into)),
            None,
            DispatcherConfig::default(),
        )
    }

    pub(crate) fn spawn_h1<F, S, B>(stream: IoTest, s: F)
    where
        F: IntoService<S, (), Request>,
        S: Service<(), Request> + 'static,
        S::Res: Into<Response<B>>,
        S::Error: ResponseError,
        B: MessageBody + 'static,
    {
        let cfg: SharedCfg = SharedCfg::new("DBG")
            .add(
                HttpServiceConfig::new()
                    .set_keepalive(Seconds(5))
                    .set_client_timeout(Seconds(1)),
            )
            .into();

        crate::rt::spawn(Dispatcher::new(
            0,
            nio::Io::new(stream, cfg),
            Pipeline::new((), s.into_service().map(Into::into)),
            None,
            DispatcherConfig::default(),
        ));
    }

    fn load(decoder: &mut ClientCodec, buf: &mut BytesMut) -> ResponseHead {
        decoder.decode(buf).unwrap().unwrap()
    }

    #[crate::rt_test]
    async fn test_on_request() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        client.write("GET /test HTTP/1.0\r\n\r\n");

        let data = Rc::new(Cell::new(false));
        let data2 = data.clone();
        let config: SharedCfg = SharedCfg::new("DBG")
            .add(
                HttpServiceConfig::new()
                    .set_keepalive(Seconds(5))
                    .set_client_timeout(Seconds(1)),
            )
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new((), async |_| Ok::<_, io::Error>(Response::Ok().build())),
            Some(Pipeline::new(
                (),
                fn_service(async move |req: Control<_, _>| {
                    if let Control::Request(_) = req {
                        data2.set(true);
                    }
                    Ok::<_, DispatchError>(req.ack())
                }),
            )),
            DispatcherConfig::default(),
        );
        sleep(Millis(50)).await;
        let _ = lazy(|cx| Pin::new(&mut h1).poll(cx)).await;
        sleep(Millis(50)).await;

        client.local_buffer(|buf| assert_eq!(&buf[..15], b"HTTP/1.1 200 OK"));
        client.close().await;

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_ready());
        assert!(data.get());
    }

    #[crate::rt_test]
    async fn test_req_parse_err() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        client.write("GET /test HTTP/1\r\n\r\n");

        let mut h1 = h1(server, async |_| Ok::<_, io::Error>(Response::Ok().build()));
        sleep(Millis(50)).await;
        // required because io shutdown is async oper
        let _ = lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_ready();
        sleep(Millis(50)).await;

        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert!(!h1.inner.io.is_active());
        sleep(Millis(50)).await;

        client.local_buffer(|buf| assert_eq!(&buf[..26], b"HTTP/1.1 400 Bad Request\r\n"));

        client.close().await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_ready());
        assert!(!h1.inner.io.is_active());
    }

    #[crate::rt_test]
    async fn test_pipeline() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());
        spawn_h1(server, async |_| Ok::<_, io::Error>(Response::Ok().build()));

        client.write("GET /test1 HTTP/1.1\r\nhost: localhost\r\n\r\n");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(!client.is_server_dropped());

        client.write("GET /test2 HTTP/1.1\r\nhost: localhost\r\n\r\n");
        client.write("GET /test3 HTTP/1.1\r\nhost: localhost\r\n\r\n");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(decoder.decode(&mut buf).unwrap().is_none());
        assert!(!client.is_server_dropped());

        client.close().await;
        assert!(client.is_server_dropped());
    }

    #[crate::rt_test]
    async fn test_pipeline_after_close() {
        for (req, res) in [
            (
                "GET /test1 HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n",
                "HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n",
            ),
            (
                "GET /test1 HTTP/1.0\r\n\r\n",
                "HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n",
            ),
            (
                "POST /test1 HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\ncontent-length: 4\r\n\r\nbody",
                "HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n",
            ),
        ] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let calls = Rc::new(Cell::new(0));
            let calls2 = calls.clone();
            spawn_h1(server, move |mut req: Request| {
                calls2.set(calls2.get() + 1);
                async move {
                    let mut pl = req.take_payload();
                    while let Some(item) = crate::util::stream_recv(&mut pl).await {
                        item.unwrap();
                    }
                    Ok::<_, io::Error>(Response::Ok().build())
                }
            });

            // the next request is pipelined behind a non-persistent request
            client.write(format!(
                "{req}GET /test2 HTTP/1.1\r\nhost: localhost\r\n\r\n"
            ));
            sleep(Millis(100)).await;

            let buf = client.read_any();
            assert!(buf.starts_with(res.as_bytes()), "{req:?} {buf:?}");
            assert_eq!(
                buf.windows(7).filter(|w| w == b"HTTP/1.").count(),
                1,
                "{req:?}"
            );
            assert_eq!(calls.get(), 1, "{req:?}");
            assert!(client.is_server_dropped(), "{req:?}");
        }
    }

    #[crate::rt_test]
    async fn test_response_without_body_is_framed() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        spawn_h1(server, move |req: Request| async move {
            if req.path() == "/test1" {
                Ok::<_, io::Error>(Response::Ok().body(body::Body::None))
            } else {
                Ok(Response::Ok().body("next"))
            }
        });

        client.write(
            "GET /test1 HTTP/1.1\r\nhost: a\r\n\r\n\
             GET /test2 HTTP/1.1\r\nhost: a\r\n\r\n",
        );
        sleep(Millis(100)).await;

        let buf = client.read_any();
        let data = String::from_utf8(buf.to_vec()).unwrap();
        let (first, second) = data.split_at(data.rfind("HTTP/1.1 200 OK").unwrap());
        assert!(first.starts_with("HTTP/1.1 200 OK\r\n"), "{data:?}");
        assert!(first.contains("\r\ncontent-length: 0\r\n"), "{data:?}");
        assert!(first.ends_with("\r\n\r\n"), "{data:?}");
        assert!(second.contains("\r\ncontent-length: 4\r\n"), "{data:?}");
        assert!(second.ends_with("\r\n\r\nnext"), "{data:?}");
        assert!(!client.is_server_dropped());
    }

    #[crate::rt_test]
    async fn test_informational_response_is_replaced() {
        for status in [
            StatusCode::CONTINUE,
            StatusCode::PROCESSING,
            StatusCode::EARLY_HINTS,
        ] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            spawn_h1(server, move |req: Request| async move {
                if req.path() == "/test1" {
                    Ok::<_, io::Error>(Response::builder(status).body("interim"))
                } else {
                    Ok(Response::Ok().build())
                }
            });

            client.write(
                "GET /test1 HTTP/1.1\r\nhost: a\r\n\r\n\
                 GET /test2 HTTP/1.1\r\nhost: a\r\n\r\n",
            );
            sleep(Millis(100)).await;

            let buf = client.read_any();
            assert!(
                buf.starts_with(b"HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\n"),
                "{status} {buf:?}"
            );
            assert_eq!(
                buf.windows(9).filter(|w| w == b"HTTP/1.1 ").count(),
                2,
                "{status} {buf:?}"
            );
            assert!(!buf.windows(7).any(|w| w == b"interim"), "{status} {buf:?}");
            assert!(
                buf.windows(15).any(|w| w == b"HTTP/1.1 200 OK"),
                "{status} {buf:?}"
            );
        }
    }

    #[crate::rt_test]
    async fn test_upgrade_without_connection_option() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let seen = Rc::new(RefCell::new(Vec::new()));
        let seen2 = seen.clone();
        spawn_h1(server, move |req: Request| {
            seen2
                .borrow_mut()
                .push((req.path().to_string(), req.upgrade()));
            async { Ok::<_, io::Error>(Response::Ok().build()) }
        });

        client.write(
            "GET /test1 HTTP/1.1\r\nhost: a\r\nupgrade: websocket\r\n\r\n\
             GET /test2 HTTP/1.1\r\nhost: a\r\nconnection: upgrade\r\n\r\n\
             GET /test3 HTTP/1.1\r\nhost: a\r\n\r\n",
        );
        sleep(Millis(100)).await;

        let buf = client.read_any();
        assert_eq!(
            buf.windows(15).filter(|w| w == b"HTTP/1.1 200 OK").count(),
            3,
            "{buf:?}"
        );
        assert_eq!(
            *seen.borrow(),
            [
                ("/test1".to_string(), false),
                ("/test2".to_string(), false),
                ("/test3".to_string(), false)
            ]
        );
    }

    #[crate::rt_test]
    async fn test_http10_expect_and_upgrade_ignored() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let seen = Rc::new(RefCell::new(Vec::new()));
        let seen2 = seen.clone();
        spawn_h1(server, move |mut req: Request| {
            seen2
                .borrow_mut()
                .push((req.path().to_string(), req.upgrade()));
            async move {
                let mut pl = req.take_payload();
                while let Some(item) = crate::util::stream_recv(&mut pl).await {
                    item.unwrap();
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        });

        client.write(
            "POST /test1 HTTP/1.0\r\nconnection: keep-alive\r\n\
             expect: 100-continue\r\ncontent-length: 4\r\n\r\nbody\
             GET /test2 HTTP/1.0\r\nconnection: keep-alive, upgrade\r\n\
             upgrade: websocket\r\n\r\n\
             GET /test3 HTTP/1.0\r\n\r\n",
        );
        sleep(Millis(100)).await;

        let buf = client.read_any();
        // no interim response for an HTTP/1.0 client
        assert!(buf.starts_with(b"HTTP/1.1 200 OK\r\n"), "{buf:?}");
        assert!(!buf.windows(3).any(|w| w == b"100"), "{buf:?}");
        assert_eq!(
            *seen.borrow(),
            [
                ("/test1".to_string(), false),
                ("/test2".to_string(), false),
                ("/test3".to_string(), false)
            ]
        );
    }

    #[crate::rt_test]
    async fn test_invalid_host_rejected() {
        for req in [
            "GET /test HTTP/1.1\r\n\r\n",
            "GET /test HTTP/1.1\r\nhost: a\r\nhost: b\r\n\r\n",
            "GET /test HTTP/1.1\r\nhost: user@a\r\n\r\n",
        ] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let calls = Rc::new(Cell::new(0));
            let calls2 = calls.clone();
            spawn_h1(server, move |_| {
                calls2.set(calls2.get() + 1);
                async { Ok::<_, io::Error>(Response::Ok().build()) }
            });

            client.write(req);
            sleep(Millis(100)).await;

            let buf = client.read_any();
            assert!(
                buf.starts_with(b"HTTP/1.1 400 Bad Request\r\n"),
                "{req:?} {buf:?}"
            );
            assert_eq!(calls.get(), 0, "{req:?}");
            assert!(client.is_server_dropped(), "{req:?}");
        }
    }

    #[crate::rt_test]
    async fn test_pipeline_with_payload() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());

        spawn_h1(server, async move |mut req: Request| {
            let mut p = req.take_payload();
            while (stream_recv(&mut p).await).is_some() {}
            Ok::<_, io::Error>(Response::Ok().build())
        });

        client.write("GET /test1 HTTP/1.1\r\nhost: localhost\r\ncontent-length: 5\r\n\r\n");
        sleep(Millis(50)).await;
        client.write("xxxxx");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(!client.is_server_dropped());

        client.write("GET /test2 HTTP/1.1\r\nhost: localhost\r\n\r\n");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(decoder.decode(&mut buf).unwrap().is_none());
        assert!(!client.is_server_dropped());

        client.close().await;
        assert!(client.is_server_dropped());
    }

    #[crate::rt_test]
    /// The rest of a payload that is still held by the application after the
    /// response is sent must not be decoded as the next request.
    async fn test_payload_after_response_is_not_a_request() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let calls = Rc::new(Cell::new(0));
        let held = Rc::new(RefCell::new(None));
        let (calls2, held2) = (calls.clone(), held.clone());

        spawn_h1(server, move |mut req: Request| {
            calls2.set(calls2.get() + 1);
            *held2.borrow_mut() = Some(req.take_payload());
            async { Ok::<_, io::Error>(Response::Ok().build()) }
        });

        let smuggled = "GET /s HTTP/1.1\r\nhost: a\r\n\r\n";
        client.write(format!(
            "POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: {}\r\n\r\naaaaa",
            5 + smuggled.len()
        ));
        let _ = client.read().await.unwrap();
        sleep(Millis(50)).await;
        client.write(smuggled);
        sleep(Millis(100)).await;
        assert_eq!(calls.get(), 1, "payload bytes dispatched as a request");

        let mut pl = held.borrow_mut().take().unwrap();
        let mut body = BytesMut::new();
        while let Some(chunk) = stream_recv(&mut pl).await {
            body.extend_from_slice(&chunk.unwrap());
        }
        assert_eq!(&body[..], format!("aaaaa{smuggled}").as_bytes());

        client.write("GET /next HTTP/1.1\r\nhost: localhost\r\n\r\n");
        let _ = client.read().await.unwrap();
        assert_eq!(calls.get(), 2);
    }

    #[crate::rt_test]
    async fn test_pipeline_with_delay() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());
        spawn_h1(server, async |_| {
            sleep(Millis(100)).await;
            Ok::<_, io::Error>(Response::Ok().build())
        });

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(!client.is_server_dropped());

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(decoder.decode(&mut buf).unwrap().is_none());
        assert!(!client.is_server_dropped());

        buf.extend(client.read().await.unwrap());
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(decoder.decode(&mut buf).unwrap().is_none());
        assert!(!client.is_server_dropped());

        client.close().await;
        assert!(client.is_server_dropped());
    }

    #[crate::rt_test]
    /// A peer write-half close still allows all buffered requests to complete
    /// and their responses to be written.
    async fn test_write_disconnected() {
        let num = Arc::new(AtomicUsize::new(0));
        let num2 = num.clone();

        let (client, server) = IoTest::create();
        spawn_h1(server, async move |_| {
            num2.fetch_add(1, Ordering::Relaxed);
            Ok::<_, io::Error>(Response::Ok().build())
        });

        client.remote_buffer_cap(1024);
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        client.close().await;
        assert!(client.is_server_dropped());

        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());
        let mut buf = BytesMut::from(&client.read_any()[..]);
        for _ in 0..3 {
            assert!(load(&mut decoder, &mut buf).status.is_success());
        }
        assert!(decoder.decode(&mut buf).unwrap().is_none());
        assert_eq!(num.load(Ordering::Relaxed), 3);
    }

    /// max http message size is 32k (no payload)
    #[crate::rt_test]
    async fn test_read_large_message() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = h1(server, async |_| Ok::<_, io::Error>(Response::Ok().build()));
        // SAFETY: this test does not retain a reference returned by `io.cfg()`.
        unsafe {
            h1.inner.io.set_config(
                SharedCfg::new("TEST")
                    .add(
                        nio::IoConfig::new()
                            .set_read_buf(15 * 1024, 1024)
                            .set_write_buf(15 * 1024),
                    )
                    .add(HttpServiceConfig::new().set_max_buf_size(32 * 1024)),
            );
        }

        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());

        // generate large http message
        let data = rand::rng()
            .sample_iter(&rand::distr::Alphanumeric)
            .take(70_000)
            .map(char::from)
            .collect::<String>();
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\nContent-Length: ");
        client.write(data);
        sleep(Millis(50)).await;

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.unwrap();
        assert!(!h1.inner.io.is_active());

        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert_eq!(
            load(&mut decoder, &mut buf).status,
            StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
        );
    }

    #[crate::rt_test]
    async fn test_read_backpressure() {
        let mark = Arc::new(AtomicBool::new(false));
        let mark2 = mark.clone();

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        spawn_h1(server, async move |mut req: Request| {
            let m = mark2.clone();

            // read one chunk
            let mut pl = req.take_payload();
            let _ = stream_recv(&mut pl).await.unwrap().unwrap();
            m.store(true, Ordering::Relaxed);
            // sleep
            sleep(Millis(999_999_000)).await;
            Ok::<_, io::Error>(Response::Ok().build())
        });

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\nContent-Length: 1048576\r\n\r\n");
        sleep(Millis(50)).await;

        // buf must be consumed
        assert_eq!(client.remote_buffer(|buf| buf.len()), 0);

        // io should be drained only by no more than MAX_BUFFER_SIZE
        let random_bytes: Vec<u8> = (0..1_048_576).map(|_| rand::random::<u8>()).collect();
        client.write(random_bytes);

        sleep(Millis(50)).await;
        assert!(client.remote_buffer(|buf| buf.len()) > 1_048_576 - BUFFER_SIZE * 3);
        assert!(mark.load(Ordering::Relaxed));
    }

    fn write_timeout_h1(
        server: IoTest,
        cfg: HttpServiceConfig,
        payload: Rc<RefCell<Option<http::Payload>>>,
    ) -> Dispatcher<Base, body::Body, io::Error> {
        let config: SharedCfg = SharedCfg::new("SVC").add(cfg).into();
        Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| {
                    payload.borrow_mut().replace(req.take_payload());
                    async { Ok::<_, io::Error>(Response::Ok().body("x".repeat(128 * 1024))) }
                }),
            ),
            None,
            DispatcherConfig::default(),
        )
    }

    /// A client that stops reading the response is disconnected by the write
    /// timeout.
    #[crate::rt_test]
    async fn test_write_timeout_during_response() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let mut h1 = write_timeout_h1(
            server,
            HttpServiceConfig::new().set_write_timeout(Seconds(1)),
            Rc::default(),
        );

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_wr_backpressure());
        assert_eq!(h1.inner.timers.active, Timer::Write);

        let res = timeout(Millis(5000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.unwrap().is_ok());
        assert!(client.is_closed());
    }

    /// The write timeout stops the dispatcher while sending a response with
    /// an unfinished request payload.
    #[crate::rt_test]
    async fn test_write_timeout_with_unfinished_payload() {
        let payload = Rc::new(RefCell::new(None));
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let mut h1 = write_timeout_h1(
            server,
            HttpServiceConfig::new().set_write_timeout(Seconds(1)),
            payload.clone(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\nb");
        let res = timeout(Millis(5000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.unwrap().is_ok());

        let mut payload = payload.borrow_mut().take().unwrap();
        let mut timed_out = false;
        while let Some(item) = payload.recv().await {
            if let Err(PayloadError::Io(err)) = item {
                assert_eq!(err.kind(), io::ErrorKind::TimedOut);
                timed_out = true;
            }
        }
        assert!(timed_out);
    }

    /// A delayed protocol error does not interrupt a response whose head has
    /// been sent.
    #[crate::rt_test]
    async fn test_delayed_protocol_error_finishes_response() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let mut h1 = write_timeout_h1(server, HttpServiceConfig::new(), Rc::default());
        h1.inner.pending_payload_error =
            Some(PayloadFailure::Protocol(ProtocolError::SlowPayloadTimeout));

        let mut body = ResponseBody::from(body::Body::from("body"));
        let st = lazy(|cx| h1.inner.poll_send_payload(cx, &mut body)).await;
        assert!(matches!(st, Poll::Ready(State::Stop)));
        assert!(matches!(h1.inner.disconnect, Disconnect::Sent));
        assert!(h1.inner.pending_payload_error.is_none());
    }

    /// Without a write timeout, write backpressure is not bounded.
    #[crate::rt_test]
    async fn test_no_write_timeout_during_response() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let mut h1 = write_timeout_h1(server, HttpServiceConfig::new(), Rc::default());

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Stopped);

        let res = timeout(Millis(2500), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.is_err());
        assert!(!client.is_closed());
    }

    /// The write timer keeps paused payload timing and restores it once
    /// backpressure is disabled.
    #[crate::rt_test]
    async fn test_write_timer_restores_payload_timer() {
        let payload = Rc::new(RefCell::new(None));
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let mut h1 = write_timeout_h1(
            server,
            HttpServiceConfig::new()
                .set_write_timeout(Seconds(5))
                .set_payload_read_rate(Seconds(10), Seconds(20), 1),
            payload.clone(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\nb");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::WriteWithPayload);
        assert_eq!(h1.inner.timers.progress.period, Seconds(10));
        assert_eq!(h1.inner.timers.progress.max_timeout, Seconds(10));

        client.remote_buffer_cap(256 * 1024);
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Payload);

        payload.borrow_mut().take();
        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    #[crate::rt_test]
    async fn test_payload_timer_pauses_for_write_backpressure() {
        let payload = Rc::new(RefCell::new(None));
        let payload2 = payload.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);

        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_payload_read_rate(Seconds(10), Seconds(20), 1))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| {
                    payload2.borrow_mut().replace(req.take_payload());
                    async { Ok::<_, io::Error>(Response::Ok().body("x".repeat(128 * 1024))) }
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\nb");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Payload);
        assert!(h1.inner.io.is_wr_backpressure());

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::PayloadPaused);
        assert_ne!(h1.inner.timers.active, Timer::Payload);
        assert!(!h1.inner.io.timer_handle().is_set());

        client.remote_buffer_cap(256 * 1024);
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(h1.inner.timers.active, Timer::Payload);
        assert_ne!(h1.inner.timers.active, Timer::PayloadPaused);

        client.write("ody");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        payload.borrow_mut().take();
        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    /// The request payload is read while write backpressure is active.
    #[crate::rt_test]
    async fn test_payload_read_during_write_backpressure() {
        let body = Rc::new(RefCell::new(BytesMut::new()));
        let body2 = body.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::new("SVC")),
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| {
                    let body = body2.clone();
                    let mut pl = req.take_payload();
                    crate::rt::spawn(async move {
                        while let Some(Ok(chunk)) = stream_recv(&mut pl).await {
                            body.borrow_mut().extend_from_slice(&chunk);
                        }
                    });
                    async { Ok::<_, io::Error>(Response::Ok().body("x".repeat(128 * 1024))) }
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\nb");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_wr_backpressure());

        client.write("ody");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(h1.inner.io.is_wr_backpressure());
        assert_eq!(&body.borrow()[..], b"body");

        client.remote_buffer_cap(256 * 1024);
        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    #[crate::rt_test]
    #[allow(clippy::items_after_statements)]
    async fn test_write_backpressure() {
        let num = Arc::new(AtomicUsize::new(0));
        let num2 = num.clone();

        struct Stream(Arc<AtomicUsize>);

        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                body::BodySize::Stream
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                let data = rand::rng()
                    .sample_iter(&rand::distr::Alphanumeric)
                    .take(65_536)
                    .map(char::from)
                    .collect::<String>();
                self.0.fetch_add(data.len(), Ordering::Relaxed);

                Poll::Ready(Some(Ok(Bytes::from(data))))
            }
        }

        let (client, server) = IoTest::create();
        let mut h1 = h1(server, async move |_| {
            let n = num2.clone();
            Ok::<_, io::Error>(Response::Ok().message_body(Stream(n.clone())))
        });
        let state = h1.inner.io.get_ref();

        // do not allow to write to socket
        client.remote_buffer_cap(0);
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        // buf must be consumed
        assert_eq!(client.remote_buffer(|buf| buf.len()), 0);

        // amount of generated data
        assert_eq!(num.load(Ordering::Relaxed), 65_536);

        // response message + chunking encoding
        assert_eq!(state.with_write_src(|buf| buf.len()).unwrap(), 65629);

        client.remote_buffer_cap(65536);
        sleep(Millis(50)).await;
        assert_eq!(state.with_write_src(|buf| { buf.len() }).unwrap(), 93);

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert_eq!(num.load(Ordering::Relaxed), 65_536 * 2);
    }

    #[crate::rt_test]
    async fn test_disconnect_during_response_body_pending() {
        struct Stream(bool);

        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                body::BodySize::Sized(2048)
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                if self.0 {
                    Poll::Pending
                } else {
                    self.0 = true;
                    let data = rand::rng()
                        .sample_iter(&rand::distr::Alphanumeric)
                        .take(1024)
                        .map(char::from)
                        .collect::<String>();
                    Poll::Ready(Some(Ok(Bytes::from(data))))
                }
            }
        }

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let mut h1 = h1(server, async |_| {
            Ok::<_, io::Error>(Response::Ok().message_body(Stream(false)))
        });

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        // http message must be consumed
        assert_eq!(client.remote_buffer(|buf| buf.len()), 0);

        let mut decoder = ClientCodec::new(true, SharedCfg::default().get());
        let mut buf = BytesMut::from(&client.read().await.unwrap()[..]);
        assert!(load(&mut decoder, &mut buf).status.is_success());
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.close().await;
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
    }

    #[crate::rt_test]
    async fn test_partial_request_headers_clean_disconnect() {
        let requests = Arc::new(AtomicUsize::new(0));
        let requests2 = requests.clone();
        let disconnects = Arc::new(AtomicUsize::new(0));
        let disconnects2 = disconnects.clone();

        let (client, server) = IoTest::create();
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_client_timeout(Seconds(10)))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async move |_| {
                    requests2.fetch_add(1, Ordering::Relaxed);
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, _>| {
                    if let Control::Disconnect(Reason::PeerGone(err)) = &msg {
                        assert!(err.get_ref().is_none());
                        disconnects2.fetch_add(1, Ordering::Relaxed);
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write("GET /test HTTP/1.1\r\nHost: example.com");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert_eq!(requests.load(Ordering::Relaxed), 0);
        assert_eq!(disconnects.load(Ordering::Relaxed), 1);
        assert!(client.read_any().is_empty());
    }

    #[crate::rt_test]
    async fn test_partial_request_headers_read_error() {
        let requests = Arc::new(AtomicUsize::new(0));
        let requests2 = requests.clone();
        let disconnects = Arc::new(AtomicUsize::new(0));
        let disconnects2 = disconnects.clone();

        let (client, server) = IoTest::create();
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_client_timeout(Seconds(10)))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async move |_| {
                    requests2.fetch_add(1, Ordering::Relaxed);
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, _>| {
                    if let Control::Disconnect(Reason::PeerGone(err)) = &msg {
                        assert_eq!(
                            err.get_ref().map(io::Error::kind),
                            Some(io::ErrorKind::ConnectionReset)
                        );
                        disconnects2.fetch_add(1, Ordering::Relaxed);
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write("GET /test HTTP/1.1\r\nHost: example.com");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.read_error(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "connection reset",
        ));
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert_eq!(requests.load(Ordering::Relaxed), 0);
        assert_eq!(disconnects.load(Ordering::Relaxed), 1);
        assert!(client.read_any().is_empty());
    }

    #[crate::rt_test]
    async fn test_header_progress_available_when_timer_fires() {
        let (client, server) = IoTest::create();
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_headers_read_rate(Seconds(1), Seconds(2), 4))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            None,
            DispatcherConfig::default(),
        );

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        client.write("GET /");
        sleep(Millis(1100)).await;

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().is_empty());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    #[crate::rt_test]
    async fn test_payload_progress_available_when_timer_fires() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_payload_read_rate(Seconds(1), Seconds(2), 2))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |mut req: Request| {
                    while req.payload().recv().await.is_some() {}
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            None,
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ntransfer-encoding: chunked\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        // Chunk framing is consumed without producing a payload item.
        client.write("4\r\n");
        sleep(Millis(1100)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(client.read_any().is_empty());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
    }

    #[crate::rt_test]
    async fn test_payload_timer_waits_for_expect_continue() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_payload_read_rate(Seconds(1), Seconds(2), 1)
                    .set_keepalive(KeepAlive::Disabled),
            )
            .into();

        let h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |mut req: Request| {
                    let mut body = BytesMut::new();
                    while let Some(chunk) = req.payload().recv().await {
                        body.extend_from_slice(&chunk.unwrap());
                    }
                    assert_eq!(&body[..], b"test");
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async |req: Control<Base, io::Error>| {
                    if let Control::Expect(exc) = req {
                        // slower than the payload read-rate limits
                        sleep(Millis(3100)).await;
                        Ok::<_, DispatchError>(exc.ack())
                    } else {
                        Ok(req.ack())
                    }
                }),
            )),
            DispatcherConfig::default(),
        );
        crate::rt::spawn(h1);

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\nexpect: 100-continue\r\n\r\n");
        // an expired payload timer would respond with an error or close
        let buf = client.read().await.unwrap();
        assert_eq!(&buf[..], b"HTTP/1.1 100 Continue\r\n\r\n");

        client.write("test");
        let buf = client.read().await.unwrap();
        assert!(buf.starts_with(b"HTTP/1.1 200 OK\r\n"), "{buf:?}");
    }

    /// An expectation answered with a final response starts payload timing
    /// once the dispatcher reads the rest of the payload.
    #[crate::rt_test]
    async fn test_payload_timer_starts_after_expect_response() {
        let stash = Rc::new(RefCell::new(None));
        let stash2 = stash.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(HttpServiceConfig::new().set_payload_read_rate(Seconds(1), Seconds(2), 1))
            .into();

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| Ok::<_, io::Error>(Response::Ok().build())),
            ),
            Some(Pipeline::new(
                (),
                fn_service(move |req: Control<Base, io::Error>| {
                    let stash = stash2.clone();
                    async move {
                        if let Control::Request(mut req) = req {
                            // keep the payload stream alive
                            stash.borrow_mut().replace(req.get_mut().take_payload());
                            Ok::<_, DispatchError>(req.fail_with(Response::Forbidden().build()))
                        } else {
                            Ok(req.ack())
                        }
                    }
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\nexpect: 100-continue\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(client.read_any().starts_with(b"HTTP/1.1 403 Forbidden\r\n"));
        assert!(matches!(h1.st, State::ReadPayload));
        assert_eq!(h1.inner.timers.active, Timer::Payload);

        let res = timeout(Millis(3500), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.unwrap().is_ok());
        assert!(stash.borrow().is_some());
    }

    #[crate::rt_test]
    async fn test_payload_peer_gone_while_control_pending() {
        let requests = Arc::new(AtomicUsize::new(0));
        let requests2 = requests.clone();
        let disconnects = Arc::new(AtomicUsize::new(0));
        let disconnects2 = disconnects.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::default()),
            Pipeline::new(
                (),
                fn_service(async move |_| {
                    requests2.fetch_add(1, Ordering::Relaxed);
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, _>| {
                    match &msg {
                        Control::Request(_) => sleep(Millis(100)).await,
                        Control::Disconnect(Reason::PeerGone(_)) => {
                            disconnects2.fetch_add(1, Ordering::Relaxed);
                        }
                        _ => {}
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 10\r\n\r\nbody");
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert_eq!(requests.load(Ordering::Relaxed), 0);
        assert_eq!(disconnects.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    async fn test_payload_decode_error_while_control_pending() {
        let requests = Arc::new(AtomicUsize::new(0));
        let requests2 = requests.clone();
        let errors = Arc::new(AtomicUsize::new(0));
        let errors2 = errors.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::default()),
            Pipeline::new(
                (),
                fn_service(async move |_| {
                    requests2.fetch_add(1, Ordering::Relaxed);
                    Ok::<_, io::Error>(Response::Ok().build())
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, _>| {
                    match &msg {
                        Control::Request(_) => sleep(Millis(100)).await,
                        Control::Disconnect(Reason::ProtocolError(err))
                            if matches!(err.get_ref(), ProtocolError::Decode(_)) =>
                        {
                            errors2.fetch_add(1, Ordering::Relaxed);
                        }
                        _ => {}
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write(
            "POST / HTTP/1.1\r\nhost: localhost\r\ntransfer-encoding: chunked\r\n\r\ninvalid\r\n",
        );
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert_eq!(requests.load(Ordering::Relaxed), 0);
        assert_eq!(errors.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    async fn test_disconnect_notification_is_not_repeated() {
        let payload = Rc::new(RefCell::new(None));
        let payload2 = payload.clone();
        let disconnects = Arc::new(AtomicUsize::new(0));
        let disconnects2 = disconnects.clone();
        let peer_gone = Arc::new(AtomicUsize::new(0));
        let peer_gone2 = peer_gone.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::default()),
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| {
                    payload2.borrow_mut().replace(req.take_payload());
                    async { Err::<Response<()>, _>(io::Error::other("service error")) }
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, io::Error>| {
                    let wait = match &msg {
                        Control::Disconnect(Reason::Error(_)) => {
                            disconnects2.fetch_add(1, Ordering::Relaxed);
                            true
                        }
                        Control::Disconnect(Reason::PeerGone(_)) => {
                            disconnects2.fetch_add(1, Ordering::Relaxed);
                            peer_gone2.fetch_add(1, Ordering::Relaxed);
                            false
                        }
                        _ => false,
                    };
                    if wait {
                        sleep(Millis(100)).await;
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 10\r\n\r\nbody");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        assert_eq!(disconnects.load(Ordering::Relaxed), 1);
        assert_eq!(peer_gone.load(Ordering::Relaxed), 0);
    }

    #[crate::rt_test]
    async fn test_payload_peer_gone_reports_incomplete() {
        let mark = Arc::new(AtomicUsize::new(0));
        let mark2 = mark.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = h1(server, move |mut req: Request| {
            let mark = mark2.clone();
            async move {
                while let Some(item) = req.payload().recv().await {
                    if matches!(item, Err(PayloadError::Incomplete(None))) {
                        mark.fetch_add(1, Ordering::Relaxed);
                    }
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        });

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 10\r\n\r\nbody");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.close().await;
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        timeout(Millis(1000), async {
            while mark.load(Ordering::Relaxed) == 0 {
                sleep(Millis(10)).await;
            }
        })
        .await
        .expect("payload consumer did not receive incomplete error");
        assert_eq!(mark.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    async fn test_payload_read_error_reports_incomplete() {
        let mark = Arc::new(AtomicUsize::new(0));
        let mark2 = mark.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = h1(server, move |mut req: Request| {
            let mark = mark2.clone();
            async move {
                while let Some(item) = req.payload().recv().await {
                    if let Err(PayloadError::Incomplete(Some(err))) = item
                        && err.kind() == io::ErrorKind::ConnectionReset
                    {
                        mark.fetch_add(1, Ordering::Relaxed);
                    }
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        });

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 10\r\n\r\nbody");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());

        client.read_error(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "connection reset",
        ));
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        sleep(Millis(50)).await;
        assert_eq!(mark.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    async fn test_payload_decode_error_is_preserved() {
        let mark = Arc::new(AtomicUsize::new(0));
        let mark2 = mark.clone();
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let mut h1 = h1(server, move |mut req: Request| {
            let mark = mark2.clone();
            async move {
                while let Some(item) = req.payload().recv().await {
                    if matches!(item, Err(PayloadError::Decode(_))) {
                        mark.fetch_add(1, Ordering::Relaxed);
                    }
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        });

        client.write(
            "POST / HTTP/1.1\r\nhost: localhost\r\ntransfer-encoding: chunked\r\n\r\ninvalid\r\n",
        );
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());
        sleep(Millis(50)).await;
        assert_eq!(mark.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    async fn test_service_error() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\ncontent-length:512\r\n\r\n");

        let mut h1 = h1(server, |_| {
            Box::pin(async { Err::<Response<()>, _>(io::Error::other("error")) })
        });
        // required because io shutdown is async oper
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());

        assert!(!h1.inner.io.is_active());
        let buf = client.local_buffer(BytesMut::take);
        assert_eq!(&buf[..28], b"HTTP/1.1 500 Internal Server");
        assert_eq!(&buf[buf.len() - 5..], b"error");
    }

    #[crate::rt_test]
    async fn test_payload_timeout() {
        let mark = Arc::new(AtomicUsize::new(0));
        let mark2 = mark.clone();
        let err_mark = Arc::new(AtomicUsize::new(0));
        let err_mark2 = err_mark.clone();

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        let svc = move |mut req: Request| {
            let m = mark2.clone();
            async move {
                // read one chunk
                let mut pl = req.take_payload();
                while let Some(item) = stream_recv(&mut pl).await {
                    let size = m.load(Ordering::Relaxed);
                    if let Ok(buf) = item {
                        m.store(size + buf.len(), Ordering::Relaxed);
                    } else {
                        return Ok::<_, io::Error>(Response::Ok().build());
                    }
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        };

        let config: SharedCfg = SharedCfg::new("SVC")
            .add(
                HttpServiceConfig::new()
                    .set_keepalive(Seconds(5))
                    .set_client_timeout(Seconds(1))
                    .set_payload_read_rate(Seconds(1), Seconds(2), 512),
            )
            .into();

        let disp = Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new((), fn_service(svc)),
            Some(Pipeline::new(
                (),
                fn_service(async move |msg: Control<_, _>| {
                    if let Control::Disconnect(Reason::ProtocolError(ref err)) = msg
                        && matches!(err.get_ref(), ProtocolError::SlowPayloadTimeout)
                    {
                        err_mark2.store(err_mark2.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
                    }
                    Ok::<_, DispatchError>(msg.ack())
                }),
            )),
            DispatcherConfig::default(),
        );
        crate::rt::spawn(disp);

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\nContent-Length: 1048576\r\n\r\n");
        sleep(Millis(50)).await;

        // send partial data to server, 1200 bytes per second exceeds the
        // configured rate in every period
        for _ in 0..20 {
            let random_bytes: Vec<u8> = (0..300).map(|_| rand::random::<u8>()).collect();
            client.write(random_bytes);
            sleep(Millis(250)).await;
            if err_mark.load(Ordering::Relaxed) != 0 {
                break;
            }
        }
        // The first period exceeds the configured rate and earns one
        // extension; the two-second maximum then terminates the payload.
        // Each one-second period lasts about one and less than two seconds
        // (a timer may expire early by the age of the cached time), so the
        // payload ends after about 2 to 4 seconds. Without the extension it
        // would end after about one second, with at most 1500 bytes.
        let received = mark.load(Ordering::Relaxed);
        assert!((1800..=5400).contains(&received), "received: {received}");
        assert_eq!(err_mark.load(Ordering::Relaxed), 1);
    }

    #[crate::rt_test]
    /// A payload dropped while the service is running closes the connection,
    /// the response announces it.
    async fn test_payload_dropped_before_response_closes() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);

        spawn_h1(server, async |mut req: Request| {
            drop(req.take_payload());
            sleep(Millis(100)).await;
            Ok::<_, io::Error>(Response::Ok().body("TEST"))
        });

        client.write("POST /test HTTP/1.1\r\nhost: localhost\r\ncontent-length: 512\r\n\r\n");
        sleep(Millis(50)).await;
        client.write("aaaaa");

        let buf = client.read().await.unwrap();
        assert!(
            buf.starts_with(b"HTTP/1.1 200 OK\r\ncontent-length: 4\r\nconnection: close\r\n"),
            "{buf:?}"
        );
        sleep(Millis(50)).await;
        assert!(client.is_server_dropped());
    }

    #[crate::rt_test]
    /// A peer disconnect stops the dispatcher while the response body is
    /// pending, the body is dropped.
    async fn test_pending_body_dropped_on_peer_gone() {
        struct Stream(Rc<Cell<bool>>, bool);
        impl Drop for Stream {
            fn drop(&mut self) {
                self.0.set(true);
            }
        }
        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                body::BodySize::Stream
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                if self.1 {
                    Poll::Pending
                } else {
                    self.1 = true;
                    Poll::Ready(Some(Ok(Bytes::from_static(b"data"))))
                }
            }
        }

        for delay in [false, true] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let dropped = Rc::new(Cell::new(false));
            let dropped2 = dropped.clone();
            spawn_h1(server, move |_| {
                let d = dropped2.clone();
                async move {
                    if delay {
                        sleep(Millis(20)).await;
                    }
                    Ok::<_, io::Error>(Response::Ok().message_body(Stream(d, false)))
                }
            });
            client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
            let _ = client.read().await.unwrap();
            sleep(Millis(50)).await;
            client.read_error(io::Error::from(io::ErrorKind::ConnectionReset));
            sleep(Millis(100)).await;
            assert!(dropped.get(), "delay={delay}");
        }
    }

    /// A client half-close drops an idle response body, unless half-close is
    /// enabled or pipelined requests are still buffered.
    #[crate::rt_test]
    async fn test_pending_body_dropped_on_half_close() {
        struct Stream(Rc<Cell<bool>>, bool);
        impl Drop for Stream {
            fn drop(&mut self) {
                self.0.set(true);
            }
        }
        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                body::BodySize::Stream
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                if self.1 {
                    Poll::Pending
                } else {
                    self.1 = true;
                    Poll::Ready(Some(Ok(Bytes::from_static(b"data"))))
                }
            }
        }

        for (half_close, pipelined, delay) in [
            (false, false, false),
            (false, false, true),
            (true, false, false),
            (false, true, false),
        ] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let cfg: SharedCfg = SharedCfg::new("DBG")
                .add(HttpServiceConfig::new().set_half_close(half_close))
                .into();
            let dropped = Rc::new(Cell::new(false));
            let dropped2 = dropped.clone();
            let svc = move |_| {
                let d = dropped2.clone();
                async move {
                    if delay {
                        sleep(Millis(50)).await;
                    }
                    Ok::<_, io::Error>(Response::Ok().message_body(Stream(d, false)))
                }
            };
            crate::rt::spawn(Dispatcher::new(
                0,
                nio::Io::new(server, cfg),
                Pipeline::new((), fn_service(svc).map(Into::into)),
                None,
                DispatcherConfig::default(),
            ));

            client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
            if pipelined {
                client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
            }
            if !delay {
                let _ = client.read().await.unwrap();
            }
            client.close().await;
            sleep(Millis(150)).await;
            let case = format!("half_close={half_close} pipelined={pipelined} delay={delay}");
            if half_close || pipelined {
                assert!(!dropped.get(), "{case}");
                assert!(!client.is_server_dropped(), "{case}");
            } else {
                assert!(dropped.get(), "{case}");
                assert!(client.is_server_dropped(), "{case}");
            }
        }
    }

    /// A response body is not polled after its declared length is sent, or
    /// for a response without a body.
    #[crate::rt_test]
    async fn test_body_not_polled_after_length() {
        struct Stream(Rc<Cell<usize>>, body::BodySize);
        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                self.1
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                self.0.set(self.0.get() + 1);
                if self.0.get() > 10_000 {
                    Poll::Ready(None)
                } else {
                    Poll::Ready(Some(Ok(Bytes::from_static(b"data"))))
                }
            }
        }

        for (method, size, polls) in [
            ("GET", body::BodySize::Sized(6), 2),
            ("HEAD", body::BodySize::Sized(6), 0),
            ("HEAD", body::BodySize::Stream, 0),
        ] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(1024 * 1024);
            let count = Rc::new(Cell::new(0));
            let count2 = count.clone();
            spawn_h1(server, move |_| {
                let c = count2.clone();
                async move { Ok::<_, io::Error>(Response::Ok().message_body(Stream(c, size))) }
            });

            let req = format!("{method} /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
            client.write(&req);
            sleep(Millis(50)).await;
            let case = format!("{method} {size:?}");
            assert_eq!(count.get(), polls, "{case}");
            let buf = client.read_any();
            if method == "GET" {
                assert!(buf.ends_with(b"\r\n\r\ndatada"), "{case} {buf:?}");
            } else {
                assert!(buf.ends_with(b"\r\n\r\n"), "{case} {buf:?}");
            }

            // the connection stays persistent
            client.write(&req);
            sleep(Millis(50)).await;
            assert_eq!(count.get(), polls * 2, "{case}");
            assert!(
                client.read_any().starts_with(b"HTTP/1.1 200 OK\r\n"),
                "{case}"
            );
            assert!(!client.is_server_dropped(), "{case}");
        }
    }

    /// A response with a declared length is complete once its last byte is
    /// sent, the body is not polled for its end.
    #[crate::rt_test]
    async fn test_sized_body_complete_without_end() {
        struct Stream(bool);
        impl body::MessageBody for Stream {
            fn size(&self) -> body::BodySize {
                body::BodySize::Sized(4)
            }
            fn poll_next_chunk(
                &mut self,
                _: &mut Context<'_>,
            ) -> Poll<Option<Result<Bytes, Rc<dyn error::Error>>>> {
                // the stream never ends after its last chunk
                if self.0 {
                    Poll::Pending
                } else {
                    self.0 = true;
                    Poll::Ready(Some(Ok(Bytes::from_static(b"data"))))
                }
            }
        }

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024 * 1024);
        spawn_h1(server, async |_| {
            Ok::<_, io::Error>(Response::Ok().message_body(Stream(false)))
        });

        let req = "GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n";
        client.write(format!("{req}{req}"));
        sleep(Millis(100)).await;
        let buf = client.read_any();
        assert_eq!(
            buf.windows(4).filter(|w| w == b"data").count(),
            2,
            "{buf:?}"
        );
        assert!(!client.is_server_dropped());
    }

    /// The end of a chunked response body is encoded.
    #[crate::rt_test]
    async fn test_chunked_body_terminated() {
        use futures_util::stream;

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024 * 1024);
        spawn_h1(server, async |_| {
            Ok::<_, io::Error>(Response::Ok().streaming(stream::iter([Ok::<_, io::Error>(
                Bytes::from_static(b"data"),
            )])))
        });

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        let buf = client.read_any();
        assert!(buf.ends_with(b"\r\n\r\n4\r\ndata\r\n0\r\n\r\n"), "{buf:?}");
    }

    /// The last chunk of a response with a declared length is flushed before
    /// the connection is closed, it is not left to the shutdown timeout.
    #[crate::rt_test]
    async fn test_sized_body_flushed_before_close() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let config: SharedCfg = SharedCfg::new("SVC")
            .add(nio::IoConfig::new().set_shutdown_timeout(Seconds(1)))
            .into();
        crate::rt::spawn(Dispatcher::new(
            0,
            nio::Io::new(server, config),
            Pipeline::new(
                (),
                fn_service(async |_| {
                    Ok::<_, io::Error>(Response::Ok().body(Bytes::from(vec![b'x'; 128 * 1024])))
                }),
            ),
            None,
            DispatcherConfig::default(),
        ));

        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n");
        sleep(Millis(1500)).await;
        assert!(!client.is_server_dropped());

        client.remote_buffer_cap(1024 * 1024);
        let mut buf = BytesMut::new();
        loop {
            let data = client.read().await.unwrap();
            if data.is_empty() {
                break;
            }
            buf.extend_from_slice(&data);
        }
        assert!(buf.ends_with(&[b'x'; 1024]), "{}", buf.len());
        assert!(buf.len() > 128 * 1024);
    }

    #[crate::rt_test]
    async fn test_unconsumed_payload() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        client.write("GET /test HTTP/1.1\r\nhost: localhost\r\ncontent-length:512\r\n\r\n");

        let mut h1 = h1(server, async move |_| {
            Ok::<_, io::Error>(Response::Ok().body("TEST"))
        });
        // required because io shutdown is async oper
        assert!(poll_fn(|cx| Pin::new(&mut h1).poll(cx)).await.is_ok());

        assert!(!h1.inner.io.is_active());
        let buf = client.local_buffer(BytesMut::take);
        assert_eq!(
            &buf[..55],
            b"HTTP/1.1 200 OK\r\ncontent-length: 4\r\nconnection: close\r\n"
        );
    }

    type Events = Rc<RefCell<Vec<String>>>;

    /// Creates a dispatcher with a control service that records every event
    /// and answers it with `f`.
    fn ctl_h1<S, C>(
        server: IoTest,
        events: &Events,
        svc: S,
        ctl: C,
    ) -> Dispatcher<Base, body::Body, io::Error>
    where
        S: AsyncFn(Request) -> Result<Response, io::Error> + 'static,
        C: Fn(Control<Base, io::Error>) -> Result<ControlAck<Base>, DispatchError> + 'static,
    {
        let events = events.clone();
        let svc = Rc::new(svc);
        let ctl = Rc::new(ctl);
        Dispatcher::new(
            0,
            nio::Io::new(server, SharedCfg::default()),
            Pipeline::new(
                (),
                fn_service(move |req: Request| {
                    let svc = svc.clone();
                    async move { svc(req).await }
                }),
            ),
            Some(Pipeline::new(
                (),
                fn_service(move |msg: Control<Base, io::Error>| {
                    let name = match &msg {
                        Control::Connect(_) => "connect".to_string(),
                        Control::Request(_) => "request".to_string(),
                        Control::Upgrade(_) => "upgrade".to_string(),
                        Control::Expect(_) => "expect".to_string(),
                        Control::Disconnect(Reason::Service(r)) => {
                            format!("service:{:?}", r.reason())
                        }
                        Control::Disconnect(Reason::Error(_)) => "error".to_string(),
                        Control::Disconnect(Reason::ProtocolError(e)) => match e.get_ref() {
                            ProtocolError::ResponsePayload(_) => "response-payload".to_string(),
                            ProtocolError::Decode(_) => "decode".to_string(),
                            e => format!("protocol:{e}"),
                        },
                        Control::Disconnect(Reason::PeerGone(p)) => {
                            format!("peer-gone:{}", p.get_ref().is_some())
                        }
                        Control::Disconnect(Reason::KeepAlive(k)) => {
                            format!("keepalive:{}", k.is_enabled())
                        }
                    };
                    events.borrow_mut().push(name);
                    let res = ctl(msg);
                    async move { res }
                }),
            )),
            DispatcherConfig::default(),
        )
    }

    fn events(events: &Events) -> Vec<String> {
        events.borrow().clone()
    }

    /// A control service error stops the dispatcher with that error.
    #[crate::rt_test]
    async fn test_control_error_stops_dispatcher() {
        use crate::error::IntoFailure;

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let ev = Events::default();
        let calls = Rc::new(Cell::new(0));
        let calls2 = calls.clone();
        let mut h1 = ctl_h1(
            server,
            &ev,
            async move |_| {
                calls2.set(calls2.get() + 1);
                Ok(Response::Ok().build())
            },
            |msg| match msg {
                Control::Request(_) => Err(DispatchError::Control(io::Error::other("ctl").fail())),
                msg => Ok(msg.ack()),
            },
        );

        client.write("GET / HTTP/1.1\r\nhost: a\r\n\r\n");
        let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(matches!(res, Ok(Err(DispatchError::Control(_)))));
        assert_eq!(calls.get(), 0);
        assert_eq!(events(&ev), ["request"]);
    }

    /// A rejected upgrade sends the response and closes the connection.
    #[crate::rt_test]
    async fn test_upgrade_failed() {
        for with_err in [false, true] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let ev = Events::default();
            let calls = Rc::new(Cell::new(0));
            let calls2 = calls.clone();
            let mut h1 = ctl_h1(
                server,
                &ev,
                async move |_| {
                    calls2.set(calls2.get() + 1);
                    Ok(Response::Ok().build())
                },
                move |msg| match msg {
                    Control::Upgrade(mut upg) => {
                        assert_eq!(upg.get_ref().path(), "/ws");
                        assert_eq!(upg.get_mut().path(), "/ws");
                        assert!(!upg.io().is_closed());
                        if with_err {
                            Ok(upg.fail(io::Error::other("upgrade")))
                        } else {
                            Ok(upg.fail_with(Response::Forbidden().build()))
                        }
                    }
                    msg => Ok(msg.ack()),
                },
            );

            client.write(
                "GET /ws HTTP/1.1\r\nhost: a\r\nconnection: upgrade\r\n\
                 upgrade: websocket\r\n\r\nGET /next HTTP/1.1\r\nhost: a\r\n\r\n",
            );
            let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
            assert!(matches!(res, Ok(Ok(()))));

            let buf = client.read_any();
            let status: &[u8] = if with_err {
                b"HTTP/1.1 500 Internal Server Error\r\n"
            } else {
                b"HTTP/1.1 403 Forbidden\r\n"
            };
            assert!(buf.starts_with(status), "{buf:?}");
            // the pipelined request is not processed
            assert_eq!(
                buf.windows(9).filter(|w| w == b"HTTP/1.1 ").count(),
                1,
                "{buf:?}"
            );
            assert_eq!(calls.get(), 0);
            assert_eq!(events(&ev), ["request", "upgrade", "service:UpgradeFailed"]);
        }
    }

    /// The control service can replace the response for a service error.
    #[crate::rt_test]
    async fn test_service_error_response_replaced() {
        for with_err in [false, true] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let ev = Events::default();
            let mut h1 = ctl_h1(
                server,
                &ev,
                async |_| Err(io::Error::other("service")),
                move |msg| match msg {
                    Control::Disconnect(Reason::Error(mut err)) => {
                        assert_eq!(err.get_ref().to_string(), "service");
                        assert_eq!(err.get_mut().kind(), io::ErrorKind::Other);
                        if with_err {
                            Ok(err.fail(ProtocolError::Decode(
                                crate::http::error::DecodeError::Method,
                            )))
                        } else {
                            Ok(err.fail_with(Response::new(StatusCode::IM_A_TEAPOT)))
                        }
                    }
                    msg => Ok(msg.ack()),
                },
            );

            client.write("GET / HTTP/1.1\r\nhost: a\r\n\r\n");
            let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
            assert!(matches!(res, Ok(Ok(()))));

            let buf = client.read_any();
            let status: &[u8] = if with_err {
                b"HTTP/1.1 400 Bad Request\r\n"
            } else {
                b"HTTP/1.1 418 I'm a teapot\r\n"
            };
            assert!(buf.starts_with(status), "{buf:?}");
            assert_eq!(events(&ev), ["request", "error"]);
        }
    }

    /// The control service can replace the response for a protocol error.
    #[crate::rt_test]
    async fn test_protocol_error_response_replaced() {
        for with_err in [false, true] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let ev = Events::default();
            let mut h1 = ctl_h1(
                server,
                &ev,
                async |_| Ok(Response::Ok().build()),
                move |msg| match msg {
                    Control::Disconnect(Reason::ProtocolError(err)) => {
                        if with_err {
                            Ok(err.fail(io::Error::other("proto")))
                        } else {
                            Ok(err.fail_with(Response::new(StatusCode::IM_A_TEAPOT)))
                        }
                    }
                    msg => Ok(msg.ack()),
                },
            );

            client.write("GET / HTTP/1.1\r\nhost: a\r\ncontent-length: x\r\n\r\n");
            let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
            assert!(matches!(res, Ok(Ok(()))));

            let buf = client.read_any();
            let status: &[u8] = if with_err {
                b"HTTP/1.1 500 Internal Server Error\r\n"
            } else {
                b"HTTP/1.1 418 I'm a teapot\r\n"
            };
            assert!(buf.starts_with(status), "{buf:?}");
            assert_eq!(events(&ev), ["decode"]);
        }
    }

    /// A rejected expectation sends the response, skips the service and
    /// closes the connection.
    #[crate::rt_test]
    async fn test_expect_failed() {
        for with_err in [false, true] {
            let (client, server) = IoTest::create();
            client.remote_buffer_cap(4096);
            let ev = Events::default();
            let calls = Rc::new(Cell::new(0));
            let calls2 = calls.clone();
            let mut h1 = ctl_h1(
                server,
                &ev,
                async move |_| {
                    calls2.set(calls2.get() + 1);
                    Ok(Response::Ok().build())
                },
                move |msg| match msg {
                    Control::Expect(mut exp) => {
                        assert_eq!(exp.get_mut().path(), "/upload");
                        if with_err {
                            Ok(exp.fail(io::Error::other("expect")))
                        } else {
                            Ok(exp.fail_with(Response::ExpectationFailed().build()))
                        }
                    }
                    msg => Ok(msg.ack()),
                },
            );

            client.write(
                "POST /upload HTTP/1.1\r\nhost: a\r\ncontent-length: 4\r\n\
                 expect: 100-continue\r\n\r\n",
            );
            let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
            assert!(matches!(res, Ok(Ok(()))));

            let buf = client.read_any();
            let status: &[u8] = if with_err {
                b"HTTP/1.1 500 Internal Server Error\r\n"
            } else {
                b"HTTP/1.1 417 Expectation Failed\r\n"
            };
            assert!(buf.starts_with(status), "{buf:?}");
            assert!(!buf.windows(3).any(|w| w == b"100"), "{buf:?}");
            assert_eq!(calls.get(), 0);
            assert_eq!(events(&ev), ["request", "expect", "service:ExpectFailed"]);
        }
    }

    /// A response body error is reported as a protocol error and the
    /// connection is closed without completing the response.
    #[crate::rt_test]
    async fn test_response_body_error() {
        use futures_util::stream;

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let ev = Events::default();
        let mut h1 = ctl_h1(
            server,
            &ev,
            async |_| {
                Ok(Response::Ok().streaming(stream::iter([
                    Ok(Bytes::from_static(b"part")),
                    Err(io::Error::other("body")),
                ])))
            },
            |msg| Ok(msg.ack()),
        );

        client.write("GET / HTTP/1.1\r\nhost: a\r\n\r\nGET /next HTTP/1.1\r\nhost: a\r\n\r\n");
        let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(matches!(res, Ok(Ok(()))));

        let buf = client.read_any();
        assert!(buf.starts_with(b"HTTP/1.1 200 OK\r\n"), "{buf:?}");
        assert!(buf.windows(4).any(|w| w == b"part"), "{buf:?}");
        // the chunked body is not terminated and no second response follows
        assert!(!buf.ends_with(b"0\r\n\r\n"), "{buf:?}");
        assert_eq!(
            buf.windows(9).filter(|w| w == b"HTTP/1.1 ").count(),
            1,
            "{buf:?}"
        );
        assert_eq!(events(&ev), ["request", "response-payload"]);
    }

    /// A transport read error is reported with the error.
    #[crate::rt_test]
    async fn test_peer_gone_with_error() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(4096);
        let ev = Events::default();
        let taken = Rc::new(Cell::new(false));
        let taken2 = taken.clone();
        let mut h1 = ctl_h1(
            server,
            &ev,
            async |_| Ok(Response::Ok().build()),
            move |msg| match msg {
                Control::Disconnect(Reason::PeerGone(mut p)) => {
                    assert_eq!(p.get_mut().unwrap().kind(), io::ErrorKind::ConnectionReset);
                    taken2.set(p.take().is_some());
                    assert!(p.get_ref().is_none());
                    Ok(p.ack())
                }
                msg => Ok(msg.ack()),
            },
        );

        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        client.read_error(io::Error::from(io::ErrorKind::ConnectionReset));
        let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(matches!(res, Ok(Ok(()))));
        assert!(taken.get());
        assert_eq!(events(&ev), ["peer-gone:true"]);
    }

    #[derive(Default)]
    struct GateDir {
        blocked: Cell<bool>,
        waker: RefCell<Option<std::task::Waker>>,
    }

    impl GateDir {
        fn poll(&self, res: Poll<nio::Readiness>, cx: &Context<'_>) -> Poll<nio::Readiness> {
            match res {
                Poll::Ready(nio::Readiness::Ready) if self.blocked.get() => {
                    *self.waker.borrow_mut() = Some(cx.waker().clone());
                    Poll::Pending
                }
                res => res,
            }
        }

        fn set(&self, blocked: bool) {
            self.blocked.set(blocked);
            if !blocked && let Some(waker) = self.waker.borrow_mut().take() {
                waker.wake();
            }
        }
    }

    /// Gate control, a blocked filter chain is not ready for reads or writes.
    #[derive(Clone, Default)]
    struct GateCtl(Rc<(GateDir, GateDir)>);

    impl GateCtl {
        fn block_read(&self, blocked: bool) {
            self.0.0.set(blocked);
        }

        fn block_write(&self, blocked: bool) {
            self.0.1.set(blocked);
        }
    }

    struct GateFilter<F>(F, GateCtl);

    impl<F: Filter> Filter for GateFilter<F> {
        fn query(&self, id: std::any::TypeId) -> Option<Box<dyn std::any::Any>> {
            self.0.query(id)
        }

        fn process_read_buf(&self, ctx: &mut nio::FilterCtx<'_>) -> io::Result<()> {
            self.0.process_read_buf(ctx)
        }

        fn process_write_buf(&self, ctx: &mut nio::FilterCtx<'_>) -> io::Result<()> {
            self.0.process_write_buf(ctx)
        }

        fn shutdown(&self, ctx: &mut nio::FilterCtx<'_>) -> io::Result<Poll<()>> {
            self.0.shutdown(ctx)
        }

        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<nio::Readiness> {
            self.1.0.0.poll(self.0.poll_read_ready(cx), cx)
        }

        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<nio::Readiness> {
            self.1.0.1.poll(self.0.poll_write_ready(cx), cx)
        }
    }

    type GatedH1 = Dispatcher<GateFilter<Base>, body::Body, io::Error>;

    /// Dispatcher over a gated filter chain, the service reads the request
    /// payload and responds with a body of `size` bytes.
    fn gated_h1(server: IoTest, cfg: HttpServiceConfig, size: usize) -> (GateCtl, GatedH1) {
        let gate = GateCtl::default();
        let g = gate.clone();
        let config: SharedCfg = SharedCfg::new("SVC").add(cfg).into();
        let io = nio::Io::new(server, config).map_filter(move |f| GateFilter(f, g));
        let h1 = Dispatcher::new(
            0,
            io,
            Pipeline::new(
                (),
                fn_service(move |mut req: Request| async move {
                    let mut pl = req.take_payload();
                    while let Some(item) = pl.recv().await {
                        item.map_err(io::Error::other)?;
                    }
                    Ok::<_, io::Error>(Response::Ok().body("x".repeat(size)))
                }),
            ),
            None,
            DispatcherConfig::default(),
        );
        (gate, h1)
    }

    fn spawn_gated_h1(
        server: IoTest,
        cfg: HttpServiceConfig,
        size: usize,
    ) -> (GateCtl, nio::IoRef) {
        let (gate, h1) = gated_h1(server, cfg, size);
        let io = h1.inner.io.get_ref();
        crate::rt::spawn(async move {
            let _ = h1.await;
        });
        (gate, io)
    }

    /// Reads a response with a body of `size` bytes.
    async fn read_response(client: &IoTest, size: usize) -> Bytes {
        let mut buf = BytesMut::new();
        loop {
            if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n")
                && buf.len() - pos - 4 >= size
            {
                return buf.freeze();
            }
            buf.extend_from_slice(&client.read().await.unwrap());
        }
    }

    /// The keep-alive timer does not run while the filter chain pauses
    /// reading.
    #[crate::rt_test]
    async fn test_filter_pause_suspends_keepalive() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let (gate, io) = spawn_gated_h1(
            server,
            HttpServiceConfig::new()
                .set_client_timeout(Seconds::ZERO)
                .set_keepalive(Seconds(1)),
            1,
        );

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        assert!(
            read_response(&client, 1)
                .await
                .starts_with(b"HTTP/1.1 200 OK\r\n")
        );

        // the peer sends a request while the filter is not ready
        gate.block_read(true);
        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(100)).await;
        assert!(io.is_read_filter_paused());

        sleep(Millis(2000)).await;
        assert!(io.is_active());

        gate.block_read(false);
        assert!(
            read_response(&client, 1)
                .await
                .starts_with(b"HTTP/1.1 200 OK\r\n")
        );

        // keep-alive is armed again once reading resumes
        sleep(Millis(2500)).await;
        assert!(client.is_closed());
    }

    /// The request-head read timer does not run while the filter chain
    /// pauses reading.
    #[crate::rt_test]
    async fn test_filter_pause_suspends_headers_timer() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let (gate, io) = spawn_gated_h1(
            server,
            HttpServiceConfig::new()
                .set_headers_read_rate(Seconds(1), Seconds(2), 1024)
                .set_keepalive(KeepAlive::Disabled),
            1,
        );

        client.write("GET / HTTP/1.1\r\n");
        sleep(Millis(100)).await;

        gate.block_read(true);
        client.write("host: localhost\r\n");
        sleep(Millis(100)).await;
        assert!(io.is_read_filter_paused());

        sleep(Millis(3000)).await;
        assert!(io.is_active());

        // the timer resumes once reading resumes
        gate.block_read(false);
        sleep(Millis(100)).await;
        assert!(!io.is_read_filter_paused());
        assert!(io.is_active());
        sleep(Millis(2000)).await;
        assert!(!io.is_active());
        assert!(client.read_any().starts_with(b"HTTP/1.1 408"));
    }

    /// The payload read timer does not run while the filter chain pauses
    /// reading.
    #[crate::rt_test]
    async fn test_filter_pause_suspends_payload_timer() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let (gate, io) = spawn_gated_h1(
            server,
            HttpServiceConfig::new()
                .set_payload_read_rate(Seconds(1), Seconds(2), 1024)
                .set_keepalive(KeepAlive::Disabled),
            1,
        );

        client.write("POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\nab");
        sleep(Millis(100)).await;

        gate.block_read(true);
        client.write("cd");
        sleep(Millis(100)).await;
        assert!(io.is_read_filter_paused());

        sleep(Millis(3000)).await;
        assert!(io.is_active());

        gate.block_read(false);
        assert!(
            read_response(&client, 1)
                .await
                .starts_with(b"HTTP/1.1 200 OK\r\n")
        );
    }

    /// The write timer does not run while the filter chain pauses writing.
    #[crate::rt_test]
    async fn test_filter_pause_suspends_write_timeout() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1_048_576);
        let size = 128 * 1024;
        let (gate, io) = spawn_gated_h1(
            server,
            HttpServiceConfig::new().set_write_timeout(Seconds(1)),
            size,
        );

        // the response waits for the filter, write backpressure is enabled
        gate.block_write(true);
        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(100)).await;
        assert!(io.is_write_filter_paused());
        assert!(io.is_wr_backpressure());

        sleep(Millis(2500)).await;
        assert!(io.is_active());

        gate.block_write(false);
        let buf = read_response(&client, size).await;
        assert!(buf.starts_with(b"HTTP/1.1 200 OK\r\n"));
        assert!(!io.is_write_filter_paused());
    }

    /// The write timer starts over once the filter chain resumes writing.
    #[crate::rt_test]
    async fn test_write_timeout_restarts_after_filter_pause() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let (gate, io) = spawn_gated_h1(
            server,
            HttpServiceConfig::new().set_write_timeout(Seconds(1)),
            128 * 1024,
        );

        gate.block_write(true);
        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(1500)).await;
        assert!(io.is_write_filter_paused());
        assert!(io.is_active());

        // the peer does not read, the timeout starts over once writes resume
        gate.block_write(false);
        sleep(Millis(500)).await;
        assert!(!io.is_write_filter_paused());
        assert!(io.is_active());
        sleep(Millis(2000)).await;
        assert!(client.is_closed());
    }

    /// A write timer expiry before the dispatcher notices a filter write
    /// pause suspends the timer.
    #[crate::rt_test]
    async fn test_write_timer_expiry_during_filter_pause() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let (gate, mut h1) = gated_h1(
            server,
            HttpServiceConfig::new().set_write_timeout(Seconds(1)),
            128 * 1024,
        );

        client.write("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
        sleep(Millis(50)).await;
        assert!(lazy(|cx| Pin::new(&mut h1).poll(cx)).await.is_pending());
        assert!(h1.inner.io.is_wr_backpressure());
        assert_eq!(h1.inner.timers.active, Timer::Write);

        // a read event turns the io task, it notices the pause
        gate.block_write(true);
        client.write("G");
        sleep(Millis(50)).await;
        assert!(h1.inner.io.is_write_filter_paused());

        assert!(h1.inner.write_timer_expired().is_ok());
        assert_eq!(h1.inner.timers.active, Timer::Write);
        assert!(h1.inner.timers.write_suspended);
        assert!(!h1.inner.io.timer_handle().is_set());

        gate.block_write(false);
        client.remote_buffer_cap(1_048_576);
        let res = timeout(Millis(1000), poll_fn(|cx| Pin::new(&mut h1).poll(cx))).await;
        assert!(res.is_err());
        assert!(
            read_response(&client, 128 * 1024)
                .await
                .starts_with(b"HTTP/1.1 200 OK\r\n")
        );
    }
}