ntex 4.9.0

Framework for composable network services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
use std::sync::{Arc, Mutex, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
use std::{cell::Cell, convert::Infallible, future::poll_fn, rc::Rc, task::Poll};
use std::{future::ready, io, io::Read, io::Write, net};

use futures_util::{future::FutureExt, stream::StreamExt, stream::once};
use regex::Regex;

use ntex::http::header::{self, HeaderName, HeaderValue};
use ntex::http::{
    HttpService, HttpServiceConfig, KeepAlive, Method, Request, Response, StatusCode, Version,
};
use ntex::http::{body, h1, h1::Control, test, test::server as test_server};
use ntex::service::{BindCtx, Ctx, ReadyNotifier};
use ntex::time::{Millis, Seconds, sleep};
use ntex::{SharedCfg, channel::oneshot, fn_service, rt, util::Bytes, web::error};

/// Upper limit for blocking socket reads, a correct server answers much sooner.
const TEN_SECONDS: std::time::Duration = std::time::Duration::from_secs(10);

/// Waits until `check` returns `true`, checking it every 10 milliseconds.
///
/// Returns an error if it does not happen within five seconds.
async fn wait_for(check: impl Fn() -> bool) -> Result<(), &'static str> {
    for _ in 0..500 {
        if check() {
            return Ok(());
        }
        sleep(Millis(10)).await;
    }
    Err("the expected condition is not met in time")
}

/// STATEMENT: `HttpService::h1` serves requests with the peer address available.
///
/// HOW:
/// - Start an HTTP/1 service with a header read deadline and keep-alive disabled.
/// - Send a `GET`, assert the handler sees a peer address, and verify a successful response.
#[ntex::test]
async fn test_h1() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::h1(async |req: Request| {
                assert!(req.peer_addr().is_some());
                Ok::<_, io::Error>(Response::Ok().build())
            })
        },
        SharedCfg::new("SRV").add(
            HttpServiceConfig::new()
                .set_headers_read_rate(Seconds(1), Seconds::ZERO, 256)
                .set_keepalive(KeepAlive::Disabled),
        ),
    );

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());
}

/// Counts shutdowns of the wrapped service.
struct ShutdownCount<S> {
    svc: S,
    shutdowns: Arc<AtomicUsize>,
}

impl<St, Req, S: ntex::Service<St, Req>> ntex::Service<St, Req> for ShutdownCount<S> {
    type Res = S::Res;
    type Error = S::Error;

    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, S::Error> {
        ctx.call(&self.svc, req).await
    }

    async fn shutdown(&self, _: Ctx<'_, Self, St>) {
        self.shutdowns.fetch_add(1, Ordering::Relaxed);
    }
}

/// STATEMENT: HTTP/1 shuts down the per-connection application and control services
/// when the connection ends.
///
/// HOW:
/// - Wrap the application and control services with shutdown counters.
/// - Serve one request with keep-alive disabled.
/// - Wait until each counter reaches one.
#[ntex::test]
async fn test_h1_shuts_down_connection_services() {
    let app = Arc::new(AtomicUsize::new(0));
    let ctl = Arc::new(AtomicUsize::new(0));
    let (app2, ctl2) = (app.clone(), ctl.clone());

    let srv = test::server_with_config(
        async move |_| {
            let (app, ctl) = (app2.clone(), ctl2.clone());
            HttpService::h1(ntex::service::fn_factory(async move |_: &_| {
                Ok::<_, io::Error>(ShutdownCount {
                    svc: fn_service(async |_: Request| Ok::<_, io::Error>(Response::Ok().build())),
                    shutdowns: app.clone(),
                })
            }))
            .control(ntex::service::fn_factory(async move |_: &_| {
                Ok::<_, io::Error>(ShutdownCount {
                    svc: fn_service(async |msg: Control<_, _>| Ok::<_, io::Error>(msg.ack())),
                    shutdowns: ctl.clone(),
                })
            }))
        },
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled)),
    );

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());
    wait_for(|| app.load(Ordering::Relaxed) == 1 && ctl.load(Ordering::Relaxed) == 1)
        .await
        .unwrap();
}

/// STATEMENT: `HttpService` instantiates its application factory per connection,
/// while the server factory that builds the `HttpService` runs once per worker.
///
/// HOW:
/// - Count server factory calls and application `ServiceFactory::create` calls.
/// - Send two requests with keep-alive disabled, so each uses a new connection.
/// - Check the application was created twice and the server factory ran once.
#[ntex::test]
async fn test_http_service_factory_per_connection() {
    let workers = Arc::new(AtomicUsize::new(0));
    let creates = Arc::new(AtomicUsize::new(0));
    let (workers2, creates2) = (workers.clone(), creates.clone());

    let srv = test::server_with_config(
        async move |_| {
            workers2.fetch_add(1, Ordering::Relaxed);
            let creates = creates2.clone();
            HttpService::new(ntex::service::fn_factory(async move |_: &_| {
                creates.fetch_add(1, Ordering::Relaxed);
                Ok::<_, io::Error>(fn_service(async |_: Request| {
                    Ok::<_, io::Error>(Response::Ok().build())
                }))
            }))
        },
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled)),
    );

    for _ in 0..2 {
        let response = srv.request(Method::GET, "/").send().await.unwrap();
        assert!(response.status().is_success());
    }
    assert_eq!(creates.load(Ordering::Relaxed), 2);
    assert_eq!(workers.load(Ordering::Relaxed), 1);
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TargetMode {
    Raw,
    Validate,
    Normalize,
}

fn target_config(mode: TargetMode) -> HttpServiceConfig {
    match mode {
        TargetMode::Raw => HttpServiceConfig::new(),
        TargetMode::Validate => HttpServiceConfig::new().set_request_target_validation(true),
        TargetMode::Normalize => HttpServiceConfig::new().set_request_target_normalization(true),
    }
}

/// STATEMENT: Opt-in HTTP/1 decoding normalizes targets before application filters and routing.
///
/// HOW:
/// - Send raw, absolute and double-slash targets with target processing disabled,
///   validation-only or normalization enabled.
/// - Check filters, guards and handlers agree on the expected target and routing path.
#[ntex::test]
async fn test_h1_request_target_normalization() {
    use ntex::web::{self, App, HttpRequest, WebRequest};

    for (target, mode, expected) in [
        (
            "/old/../%74est?q=%7e",
            TargetMode::Raw,
            "/old/../%74est?q=%7e",
        ),
        (
            "/old/../%74est?q=%7e",
            TargetMode::Validate,
            "/old/../%74est?q=%7e",
        ),
        ("/old/../%74est?q=%7e", TargetMode::Normalize, "/test?q=~"),
        ("//test", TargetMode::Normalize, "//test"),
        ("/.//test", TargetMode::Normalize, "//test"),
        ("/.//%74est", TargetMode::Normalize, "//test"),
        (
            "HTTPS://Example.COM:00443/old/../%74est?q=%7e",
            TargetMode::Normalize,
            "/test?q=~",
        ),
    ] {
        let cfg = target_config(mode);
        let srv = test::server_with_config(
            async move |_| {
                HttpService::h1(
                    App::default()
                        .filter(async move |req: WebRequest<()>| {
                            assert_eq!(req.uri().path_and_query(), expected);
                            if req.uri().authority().is_some() {
                                assert_eq!(req.connection_info().host(), "example.com");
                                assert_eq!(req.connection_info().scheme(), "https");
                            }
                            Ok::<_, Infallible>(req)
                        })
                        .service(
                            web::resource(["/test", "/old/../test", "//test"])
                                .guard(web::guard::fn_guard(move |head| {
                                    head.uri.path_and_query() == expected
                                }))
                                .to(async |req: HttpRequest| {
                                    assert_eq!(req.match_info().get_ref().path(), req.path());
                                    req.uri().path_and_query().as_str().to_owned()
                                }),
                        ),
                )
            },
            SharedCfg::new("SRV").add(cfg),
        );
        let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
        stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
        stream.set_write_timeout(Some(TEN_SECONDS)).unwrap();
        write!(
            stream,
            "GET {target} HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n"
        )
        .unwrap();
        let mut response = String::new();
        stream.read_to_string(&mut response).unwrap();
        assert!(response.starts_with("HTTP/1.1 200 OK\r\n"), "{response}");
        assert_eq!(response.split_once("\r\n\r\n").unwrap().1, expected);
    }
}

/// STATEMENT: HTTP/1 target and Host-header validation are independently opt-in.
///
/// HOW:
/// - Send malformed escapes, fragments, authorities and asterisk forms over raw TCP.
/// - Require successful fallback responses by default and `400` with validation-only
///   or normalization enabled; `GET *` is always rejected with `400`.
/// - Check rejected requests never enter application middleware.
/// - Send an invalid Host header with either target setting and require `400` only
///   when transport Host validation is enabled.
#[ntex::test]
async fn test_h1_request_target_validation() {
    use ntex::web::{App, WebRequest, middleware::DefaultHeaders};

    for (mode, validate_host) in [
        (TargetMode::Raw, false),
        (TargetMode::Raw, true),
        (TargetMode::Validate, false),
        (TargetMode::Validate, true),
        (TargetMode::Normalize, false),
        (TargetMode::Normalize, true),
    ] {
        let cfg = target_config(mode);
        let cfg = if validate_host {
            cfg.set_host_validation(true)
        } else {
            cfg
        };
        let srv = test::server_with_config(
            async move |_| {
                HttpService::h1(
                    App::default()
                        .middleware(DefaultHeaders::new().header("x-app", "called"))
                        .default_service(async |req: WebRequest<()>| {
                            Ok::<_, Infallible>(req.into_response(Response::Ok()))
                        }),
                )
            },
            SharedCfg::new("SRV").add(cfg),
        );
        for (target, host) in [
            ("/bad%zz", "localhost"),
            ("/a#fragment", "localhost"),
            ("http://host:bad/path", "localhost"),
            ("*", "localhost"),
            ("/", "invalid/host"),
        ] {
            let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
            stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
            stream.set_write_timeout(Some(TEN_SECONDS)).unwrap();
            write!(
                stream,
                "GET {target} HTTP/1.1\r\nhost: {host}\r\nconnection: close\r\n\r\n"
            )
            .unwrap();
            let mut response = String::new();
            // a rejected request is closed with its headers unread, so the
            // peer may reset the connection after sending the response
            if let Err(e) = stream.read_to_string(&mut response) {
                assert!(
                    e.kind() == io::ErrorKind::ConnectionReset && response.contains("\r\n\r\n"),
                    "{target}: {e}"
                );
            }
            let rejected = if host == "invalid/host" {
                validate_host
            } else if target == "*" {
                true
            } else {
                mode != TargetMode::Raw
            };
            let status = if rejected { 400 } else { 200 };
            assert!(
                response.starts_with(&format!("HTTP/1.1 {status} ")),
                "{target}: {response}"
            );
            assert_eq!(
                response.contains("\r\nx-app: called\r\n"),
                !rejected,
                "{response}"
            );
        }
    }
}

/// STATEMENT: Opt-in HTTP/2 decoding normalizes targets before application filters and routing.
///
/// HOW:
/// - Send unnormalized `:path` values with target processing disabled, validation-only
///   or normalization enabled.
/// - Check that application filters and handlers receive the raw or canonical path/query.
#[ntex::test]
async fn test_h2_request_target_normalization() {
    use ntex::http::HeaderMap;
    use ntex::time::timeout;
    use ntex::web::{self, App, HttpRequest, WebRequest};
    use ntex_h2::{MessageKind, StreamEof, client::SimpleClient};

    for (target, mode, expected) in [
        (
            "/old/../%74est?q=%7e",
            TargetMode::Raw,
            "/old/../%74est?q=%7e",
        ),
        (
            "/old/../%74est?q=%7e",
            TargetMode::Validate,
            "/old/../%74est?q=%7e",
        ),
        ("/old/../%74est?q=%7e", TargetMode::Normalize, "/test?q=~"),
        ("/.//%74est", TargetMode::Normalize, "//test"),
    ] {
        let cfg = target_config(mode);
        let srv = test::server_with_config(
            async move |_| {
                HttpService::h2(
                    App::default()
                        .filter(async move |req: WebRequest<()>| {
                            assert_eq!(req.uri().path_and_query(), expected);
                            Ok::<_, Infallible>(req)
                        })
                        .service(web::resource(["/test", "/old/../test", "//test"]).to(
                            async |req: HttpRequest| {
                                assert_eq!(req.match_info().get_ref().path(), req.path());
                                req.uri().path_and_query().as_str().to_owned()
                            },
                        )),
                )
            },
            SharedCfg::new("SRV").add(cfg),
        );
        let io = ntex::connect::connect(srv.addr()).await.unwrap();
        let client = SimpleClient::new(io, false, "localhost".into());
        let (_snd, rcv) = client
            .send(Method::GET, target.into(), HeaderMap::default(), true)
            .await
            .unwrap();
        let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Headers { ref pseudo, .. }
                if pseudo.status == Some(StatusCode::OK)),
            "{msg:?}"
        );
        let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Eof(StreamEof::Data(ref data, _)) if data == expected),
            "{msg:?}"
        );
    }
}

/// STATEMENT: `HttpService::new` recognizes HTTP/1.1 requests and supplies a nonzero date year.
///
/// HOW:
/// - Send a `GET` and assert the handler sees a peer address and `Version::HTTP_11`.
/// - Verify a successful response whose `Date` header does not start with a zero year.
#[ntex::test]
async fn test_h1_2() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::new(async |req: Request| {
                assert!(req.peer_addr().is_some());
                assert_eq!(req.version(), Version::HTTP_11);
                Ok::<_, io::Error>(Response::Ok().build())
            })
        },
        SharedCfg::new("SRV").add(
            HttpServiceConfig::new()
                .set_headers_read_rate(Seconds(1), Seconds::ZERO, 256)
                .set_keepalive(KeepAlive::Disabled),
        ),
    );

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());

    // check date
    let hdr = response.header(header::DATE).unwrap();
    assert!(!hdr.to_str().unwrap().starts_with("000"));
}

/// STATEMENT: HTTP/1 expectation control can reject a request or permit its body transmission.
///
/// HOW:
/// - Reject an `Expect: 100-continue` request without the accepted query and verify status `412`.
/// - Accept the query, verify `100 Continue`, then send the body and verify `200 OK`.
#[ntex::test]
async fn test_expect_continue() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::h1(async move |mut req: Request| {
                let _ = req.payload().next().await;
                Ok::<_, io::Error>(Response::Ok().build())
            })
            .control(async move |req: Control<_, _>| {
                sleep(Millis(20)).await;
                let ack = if let Control::Expect(exc) = req {
                    if exc
                        .get_ref()
                        .head()
                        .uri
                        .query()
                        .is_some_and(|q| q == "yes=")
                    {
                        exc.ack()
                    } else {
                        exc.fail(error::InternalError::default(
                            "error",
                            StatusCode::PRECONDITION_FAILED,
                        ))
                    }
                } else {
                    req.ack()
                };
                Ok::<_, std::convert::Infallible>(ack)
            })
        },
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled)),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ =
        stream.write_all(b"GET /test HTTP/1.1\r\nhost: localhost\r\nexpect: 100-continue\r\n\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 412 Precondition Failed\r\ncontent-length"));

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream
        .write_all(b"GET /test?yes= HTTP/1.1\r\nhost: localhost\r\ncontent-length:4\r\nexpect: 100-continue\r\n\r\n");
    let mut data = [0; 25];
    let _ = stream.read_exact(&mut data[..]);
    assert_eq!(&data, b"HTTP/1.1 100 Continue\r\n\r\n");

    let mut data = String::new();
    let _ = stream.write_all(b"test");
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 200 OK\r\n"));
}

/// STATEMENT: HTTP/1 chunked request decoding delivers the complete payload across chunk sizes.
///
/// HOW:
/// - Send random payload chunks of 32768, 32, and 32768 bytes followed by the terminating chunk.
/// - Sum decoded bytes in the handler and verify the response reports the total sent.
#[ntex::test]
async fn test_chunked_payload() {
    let chunk_sizes = [32768, 32, 32768];
    let total_size: usize = chunk_sizes.iter().sum();

    let srv = test_server(async |_| {
        HttpService::h1(fn_service(|mut request: Request| {
            request
                .take_payload()
                .map(|res| match res {
                    Ok(pl) => pl,
                    Err(e) => panic!("Error reading payload: {e}"),
                })
                .fold(0usize, async move |acc, chunk| acc + chunk.len())
                .map(|req_size| Ok::<_, io::Error>(Response::Ok().body(format!("size={req_size}"))))
        }))
    });

    let returned_size = {
        let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
        let _ = stream.write_all(
            b"POST /test HTTP/1.1\r\nhost: localhost\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n",
        );

        for chunk_size in chunk_sizes.iter() {
            let mut bytes = Vec::new();
            let random_bytes: Vec<u8> = (0..*chunk_size).map(|_| rand::random::<u8>()).collect();

            bytes.extend(format!("{chunk_size:X}\r\n").as_bytes());
            bytes.extend(&random_bytes[..]);
            bytes.extend(b"\r\n");
            let _ = stream.write_all(&bytes);
        }
        let _ = stream.write_all(b"0\r\n\r\n");

        let mut data = String::new();
        let _ = stream.read_to_string(&mut data);

        let re = Regex::new(r"size=([0-9]+)").unwrap();
        let size: usize = match re.captures(&data) {
            Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
            None => panic!("Failed to find size in HTTP Response: {data}"),
        };
        size
    };

    assert_eq!(returned_size, total_size);
}

/// STATEMENT: Incomplete HTTP/1 headers time out when progress stalls or the total budget expires.
///
/// HOW:
/// - Configure a one-second read period, a two-second budget, and a four-byte minimum rate.
/// - Keep an incomplete head above the minimum rate and verify it still receives `408`.
/// - Stall a second incomplete head below the minimum rate and verify another `408`.
#[ntex::test]
async fn test_slow_request() {
    const DATA: &[u8] = b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n";

    let srv = test::server_with_config(
        async |_| HttpService::new(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_headers_read_rate(
            Seconds(1),
            Seconds(2),
            4,
        )),
    );

    // reading the head above the rate extends the timeout, the cumulative
    // budget caps it, the head is never completed
    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let _ = stream.write_all(&DATA[..5]);

    let done = Arc::new(AtomicBool::new(false));
    let writer = {
        let mut stream = stream.try_clone().unwrap();
        let done = done.clone();
        // five bytes every 300 milliseconds is above the four bytes per
        // second rate, it keeps extending the timeout
        std::thread::spawn(move || {
            while !done.load(Ordering::Acquire) {
                if stream.write_all(b"aaaaa").is_err() {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(300));
            }
        })
    };

    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    done.store(true, Ordering::Release);
    writer.join().unwrap();
    assert!(data.starts_with("HTTP/1.1 408 Request Timeout"), "{data:?}");

    // a stalled head is not extended, the read rate is not reached
    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let _ = stream.write_all(&DATA[..4]);
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 408 Request Timeout"), "{data:?}");
}

/// STATEMENT: Header read deadlines apply to later requests on an HTTP/1 keep-alive connection.
///
/// HOW:
/// - Configure a single one-second header read period and complete an initial request.
/// - Verify `200 OK`, then send an incomplete second head and verify `408 Request Timeout`.
#[ntex::test]
async fn test_slow_request2() {
    const DATA: &[u8] = b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n";

    let srv = test::server_with_config(
        async |_| HttpService::new(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        // a single read rate period, extending it is covered by `test_slow_request`
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_headers_read_rate(
            Seconds(1),
            Seconds(1),
            4,
        )),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
    let _ = stream.write_all(DATA);
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 408 Request Timeout"), "{data:?}");
}

/// STATEMENT: Sufficient header progress extends the HTTP/1 read deadline.
///
/// HOW:
/// - Send five bytes with a four-byte minimum rate and a one-second initial read period.
/// - Complete the head after 1.1 seconds, within the total budget, and verify `200 OK`.
#[ntex::test]
async fn test_headers_read_rate_extends_timeout() {
    let srv = test::server_with_config(
        async |_| HttpService::new(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_headers_read_rate(
            Seconds(1),
            Seconds(3),
            4,
        )),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /");
    sleep(Millis(1100)).await;
    let _ = stream.write_all(b" HTTP/1.1\r\nhost: localhost\r\n\r\n");

    let mut data = vec![0; 1024];
    let len = stream.read(&mut data).unwrap();
    assert!(data[..len].starts_with(b"HTTP/1.1 200 OK\r\n"));
}

/// STATEMENT: Header read-rate accounting includes bytes already consumed by the HTTP/1 decoder.
///
/// HOW:
/// - Send a complete request line and a header, leaving only the final blank line outstanding.
/// - Wait beyond the initial read period and verify no response or connection close occurs.
/// - Finish the head within the extended budget and verify `200 OK`.
#[ntex::test]
async fn test_headers_read_rate_counts_parsed_bytes() {
    let srv = test::server_with_config(
        async |_| HttpService::new(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_headers_read_rate(
            Seconds(2),
            Seconds(5),
            4,
        )),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    // The complete request line is consumed by the decoder, leaving no bytes
    // buffered while the remainder of the header block is still pending.
    let _ = stream.write_all(b"GET / HTTP/1.1\r\nhost: localhost\r\n");
    sleep(Millis(3200)).await;

    stream.set_nonblocking(true).unwrap();
    let mut data = vec![0; 1024];
    match stream.read(&mut data) {
        Err(err) if err.kind() == io::ErrorKind::WouldBlock => (),
        Ok(len) => panic!(
            "server responded before the request head completed: {:?}",
            String::from_utf8_lossy(&data[..len])
        ),
        Err(err) => panic!("failed to inspect the connection: {err}"),
    }
    stream.set_nonblocking(false).unwrap();

    let _ = stream.write_all(b"\r\n");

    let len = stream.read(&mut data).unwrap();
    assert!(data[..len].starts_with(b"HTTP/1.1 200 OK\r\n"));
}

/// STATEMENT: Sufficient payload progress extends the HTTP/1 body read deadline.
///
/// HOW:
/// - Send half a ten-byte body with a four-byte minimum rate and a one-second read period.
/// - Send the remaining bytes after 1.1 seconds and verify the consuming handler returns `200 OK`.
#[ntex::test]
async fn test_payload_read_rate_extends_timeout() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::new(async |mut req: Request| {
                while req.payload().recv().await.is_some() {}
                Ok::<_, io::Error>(Response::Ok().build())
            })
        },
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_payload_read_rate(
            Seconds(1),
            Seconds(3),
            4,
        )),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ =
        stream.write_all(b"POST / HTTP/1.1\r\nhost: localhost\r\ncontent-length: 10\r\n\r\n12345");
    sleep(Millis(1100)).await;
    let _ = stream.write_all(b"67890");

    let mut data = vec![0; 1024];
    let len = stream.read(&mut data).unwrap();
    assert!(data[..len].starts_with(b"HTTP/1.1 200 OK\r\n"));
}

/// STATEMENT: HTTP/1 rejects a malformed protocol version in the request line.
///
/// HOW:
/// - Send a raw request line containing `HTTP1.1` instead of `HTTP/1.1`.
/// - Read the response and verify it starts with `400 Bad Request`.
#[ntex::test]
async fn test_http1_malformed_request() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP1.1\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 400 Bad Request"));
}

/// STATEMENT: HTTP/1.1 connections accept successive requests with default keep-alive settings.
///
/// HOW:
/// - Send a complete request over a raw TCP connection and verify `200 OK`.
/// - Reuse that connection for another request and verify a second `200 OK`.
#[ntex::test]
async fn test_http1_keepalive() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
}

/// STATEMENT: An idle HTTP/1 connection closes after its keep-alive timeout.
///
/// HOW:
/// - Configure a one-second keep-alive timeout and verify a request receives `200 OK`.
/// - Leave the connection idle and verify the next socket read returns EOF.
#[ntex::test]
async fn test_http1_keepalive_timeout() {
    let srv = test::server_with_config(
        async |_| HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(1)),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    // the connection is closed once the keep-alive timeout expires
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);
}

/// STATEMENT: Keep-alive expiration does not interrupt an active HTTP/1 response.
///
/// HOW:
/// - Configure a one-second keep-alive timeout and serve a fast request.
/// - Reuse the connection for a handler delayed by 1.2 seconds and verify both responses are `200`.
#[ntex::test]
async fn test_http1_no_keepalive_during_response() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::h1(async |req: Request| {
                // the second request is processed while the keep-alive timer
                // of the previous wait is left armed
                if req.uri().path() == "/slow" {
                    sleep(Millis(1200)).await;
                }
                Ok::<_, io::Error>(Response::Ok().build())
            })
        },
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(1)),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    for path in ["/fast", "/slow"] {
        let _ =
            stream.write_all(format!("GET {path} HTTP/1.1\r\nhost: localhost\r\n\r\n").as_bytes());
        let mut data = vec![0; 1024];
        let _ = stream.read(&mut data);
        assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
    }
}

/// STATEMENT: Idle HTTP/1 closure after a response reports a keep-alive disconnect.
///
/// HOW:
/// - Enable header read deadlines and a one-second keep-alive timeout.
/// - Verify a request succeeds, then wait for socket EOF.
/// - Assert the control service observed `Control::Disconnect` with `Reason::KeepAlive`.
#[ntex::test]
async fn test_http1_keepalive_after_response() {
    let ka = Arc::new(AtomicBool::new(false));
    let ka2 = ka.clone();
    let srv = test::server_with_config(
        async move |_| {
            let ka = ka2.clone();
            HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build())).control(
                async move |req: Control<_, _>| {
                    if let Control::Disconnect(h1::control::Reason::KeepAlive(_)) = &req {
                        ka.store(true, Ordering::Release);
                    }
                    Ok::<_, std::convert::Infallible>(req.ack())
                },
            )
        },
        SharedCfg::new("SRV").add(
            HttpServiceConfig::new()
                .set_headers_read_rate(Seconds(1), Seconds(2), 4)
                .set_keepalive(1),
        ),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    // the connection is closed once the keep-alive timeout expires
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let mut data = vec![0; 1024];
    let len = stream.read(&mut data).unwrap();
    assert_eq!(len, 0);
    assert!(ka.load(Ordering::Relaxed));
}

/// STATEMENT: HTTP/1.1 honors a request's `Connection: close` directive.
///
/// HOW:
/// - Send a raw request containing `Connection: close` and verify `200 OK`.
/// - Verify the following socket read returns EOF.
#[ntex::test]
async fn test_http1_keepalive_close() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(
        b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n",
    );
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);
}

/// STATEMENT: HTTP/1.0 requests close by default even when the response uses HTTP/1.1.
///
/// HOW:
/// - Send an HTTP/1.0 request without a connection directive.
/// - Verify an HTTP/1.1 `200 OK` with `Connection: close`, followed by socket EOF.
#[ntex::test]
async fn test_http10_keepalive_default_close() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n");
    let mut data = vec![0; 1024];
    let n = stream.read(&mut data).unwrap();
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
    // an HTTP/1.1 response is persistent by default
    assert!(data[..n].windows(19).any(|w| w == b"connection: close\r\n"));

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);
}

/// STATEMENT: HTTP/1.0 connection headers reflect explicit keep-alive or default closure.
///
/// HOW:
/// - Send an HTTP/1.0 request with `Connection: keep-alive` and verify the response echoes it.
/// - On another connection, omit that directive and verify `Connection: close` followed by EOF.
#[ntex::test]
async fn test_http10_keepalive() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n");
    let mut data = vec![0; 1024];
    let n = stream.read(&mut data).unwrap();
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
    assert!(
        data[..n]
            .windows(24)
            .any(|w| w == b"connection: keep-alive\r\n")
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n");
    let mut data = vec![0; 1024];
    let n = stream.read(&mut data).unwrap();
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
    // an HTTP/1.1 response is persistent by default
    assert!(data[..n].windows(19).any(|w| w == b"connection: close\r\n"));

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);
}

/// STATEMENT: Disabling keep-alive closes HTTP/1.1 connections after their response.
///
/// HOW:
/// - Configure `KeepAlive::Disabled` and send a request without `Connection: close`.
/// - Verify `200 OK` followed by socket EOF.
#[ntex::test]
async fn test_http1_keepalive_disabled() {
    let srv = test::server_with_config(
        async |_| HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled)),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);
}

/// STATEMENT: A completed HTTP/1 payload no longer triggers its read deadline.
///
/// HOW:
/// - Configure a one-second payload deadline and deliver the head and body in separate reads.
/// - Read the body in the handler, delay the response by 1.5 seconds, and verify `200 OK`.
#[ntex::test]
async fn test_http1_disable_payload_timer_after_whole_pl_has_been_read() {
    let srv = test::server_with_config(
        async |_| {
            HttpService::h1(async move |mut req: Request| {
                req.payload().recv().await;
                sleep(Millis(1500)).await;
                Ok::<_, io::Error>(Response::Ok().build())
            })
            .control(async |msg: Control<_, _>| Ok::<_, io::Error>(msg.ack()))
        },
        SharedCfg::new("SRV").add(
            HttpServiceConfig::new()
                .set_headers_read_rate(Seconds(1), Seconds(1), 128)
                .set_payload_read_rate(Seconds(1), Seconds(1), 512)
                .set_keepalive(1),
        ),
    );

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream
        .write_all(b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n");
    // the head and the payload arrive as separate reads, so payload timing
    // starts for an incomplete payload
    sleep(Millis(100)).await;
    let _ = stream.write_all(b"\r\n");
    sleep(Millis(100)).await;
    let _ = stream.write_all(b"1234");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
}

/// STATEMENT: An HTTP/1 handler may respond without consuming a delayed request payload.
///
/// HOW:
/// - Install a handler that ignores the body and a control service that panics on protocol errors.
/// - Send headers declaring a four-byte body, deliver it after a delay, and verify `200 OK`.
#[cfg(unix)]
#[ntex::test]
async fn test_http1_handle_not_consumed_payload() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().build())).control(
            async |msg: Control<_, _>| {
                if matches!(
                    msg,
                    Control::Disconnect(ntex::http::h1::control::Reason::ProtocolError(_))
                ) {
                    panic!()
                }
                Ok::<_, io::Error>(msg.ack())
            },
        )
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(
        b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\ncontent-length: 4\r\n\r\n",
    );
    sleep(Millis(250)).await;
    let _ = stream.write_all(b"1234");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
}

/// STATEMENT: Disconnecting an HTTP/1 client reports an error to its pending payload reader.
///
/// HOW:
/// - Declare a large body without sending it and wait until the handler starts reading.
/// - Drop the client connection and verify the handler records one payload error.
#[ntex::test]
async fn test_http1_handle_payload_errors() {
    let started = Arc::new(AtomicUsize::new(0));
    let started2 = started.clone();
    let count = Arc::new(AtomicUsize::new(0));
    let count2 = count.clone();

    let srv = test_server(async move |_| {
        let started = started2.clone();
        let count = count2.clone();
        HttpService::h1(move |mut req: Request| {
            let started = started.clone();
            let count = count.clone();
            async move {
                let mut pl = req.take_payload();
                started.fetch_add(1, Ordering::Release);
                let result = pl.recv().await;
                if result.unwrap().is_err() {
                    count.fetch_add(1, Ordering::Relaxed);
                }
                Ok::<_, io::Error>(Response::Ok().build())
            }
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(
        b"GET /test/tests/test HTTP/1.1\r\nhost: localhost\r\ncontent-length: 99999\r\n\r\n",
    );
    // the request is dropped while the handler waits for the payload
    wait_for(|| started.load(Ordering::Acquire) == 1)
        .await
        .expect("request is not received");
    drop(stream);
    wait_for(|| count.load(Ordering::Acquire) == 1)
        .await
        .expect("payload error is not reported");
}

/// STATEMENT: HTTP/1 response framing respects status-specific content-length rules.
///
/// HOW:
/// - Return `100` and `102` for `GET` and `HEAD`; verify replacement `500` responses with length zero.
/// - Return `204` and `101` for both methods and verify no `Content-Length` header is sent.
/// - Return empty `200` and `404` responses to `GET` and verify `Content-Length: 0`.
#[ntex::test]
async fn test_content_length() {
    let srv = test_server(async |_| {
        HttpService::h1(async |req: Request| {
            let indx: usize = req.uri().path().as_str()[1..].parse().unwrap();
            let statuses = [
                StatusCode::NO_CONTENT,
                StatusCode::CONTINUE,
                StatusCode::SWITCHING_PROTOCOLS,
                StatusCode::PROCESSING,
                StatusCode::OK,
                StatusCode::NOT_FOUND,
            ];
            Ok::<_, io::Error>(Response::new(statuses[indx]))
        })
    });

    let header = HeaderName::from_static("content-length");
    let value = HeaderValue::from_static("0");

    {
        // interim `1xx` responses cannot be final, they are replaced with 500
        for i in [1, 3] {
            for method in ["GET", "HEAD"] {
                let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
                let _ = stream.write_all(
                    format!("{method} /{i} HTTP/1.1\r\nhost: localhost\r\n\r\n").as_bytes(),
                );
                let mut data = vec![0; 1024];
                let n = stream.read(&mut data).unwrap();
                let data = String::from_utf8_lossy(&data[..n]).to_lowercase();
                assert!(data.starts_with("http/1.1 500"), "{data:?}");
                assert!(data.contains("content-length: 0\r\n"), "{data:?}");
            }
        }

        for i in [0, 2] {
            let req = srv.request(Method::GET, format!("/{i}"));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), None);

            let req = srv.request(Method::HEAD, format!("/{i}"));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), None);
        }

        for i in 4..6 {
            let req = srv.request(Method::GET, format!("/{i}"));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), Some(&value));
        }
    }
}

/// STATEMENT: Large HTTP/1 response headers do not corrupt the response body.
///
/// HOW:
/// - Return twenty long custom headers together with a body containing ten copies of `STR`.
/// - Verify success and compare the fully received body with the original bytes.
#[ntex::test]
async fn test_h1_headers() {
    let data = STR.repeat(10);
    let data2 = data.clone();

    let srv = test_server(async move |_| {
        let data = data.clone();
        HttpService::h1(async move |_| {
            let mut builder = Response::Ok();
            for idx in 0..20 {
                builder.header(
                    format!("X-TEST-{idx}").as_str(),
                    "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
                );
            }
            Ok::<_, io::Error>(builder.body(data.clone()))
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from(data2));
}

const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World";

/// STATEMENT: HTTP/1 delivers a fixed response body unchanged.
///
/// HOW:
/// - Return `STR` from the request handler and send a `GET`.
/// - Verify success and compare the complete received body with `STR`.
#[ntex::test]
async fn test_h1_body() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().body(STR)))
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}

/// STATEMENT: HTTP/1 `HEAD` responses retain the computed body length without sending body bytes.
///
/// HOW:
/// - Return `STR` without an explicit length and send a `HEAD` request.
/// - Verify success, `Content-Length` equal to `STR.len()`, and an empty received body.
#[ntex::test]
async fn test_h1_head_empty() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().body(STR)))
    });

    let response = srv.request(Method::HEAD, "/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert!(bytes.is_empty());
}

/// STATEMENT: HTTP/1 `HEAD` preserves an explicit content length while suppressing the body.
///
/// HOW:
/// - Return `STR` with an explicitly configured content length and send a `HEAD`.
/// - Verify success, the configured `Content-Length`, and an empty received body.
#[ntex::test]
async fn test_h1_head_binary() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            Ok::<_, io::Error>(Response::Ok().content_length(STR.len() as u64).body(STR))
        })
    });

    let response = srv.request(Method::HEAD, "/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert!(bytes.is_empty());
}

/// STATEMENT: HTTP/1 computes the content length for a fixed-body `HEAD` response.
///
/// HOW:
/// - Return `STR` without explicitly configuring a length and send a `HEAD`.
/// - Verify success and a `Content-Length` equal to `STR.len()`.
#[ntex::test]
async fn test_h1_head_binary2() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| Ok::<_, io::Error>(Response::Ok().body(STR)))
    });

    let response = srv.request(Method::HEAD, "/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }
}

/// STATEMENT: HTTP/1 delivers the complete contents of a sized response stream.
///
/// HOW:
/// - Wrap one chunk containing `STR` in a `body::SizedStream` with the matching length.
/// - Send a `GET`, verify success, and compare the received body with `STR`.
#[ntex::test]
async fn test_h1_body_length() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            let body = once(ready(Ok(Bytes::from_static(STR.as_ref()))));
            Ok::<_, io::Error>(Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)))
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}

/// STATEMENT: HTTP/1 supports an explicitly chunked streaming response.
///
/// HOW:
/// - Stream one chunk containing `STR` and explicitly set `Transfer-Encoding: chunked`.
/// - Verify success, the chunked encoding header, and a decoded body equal to `STR`.
#[ntex::test]
async fn test_h1_body_chunked_explicit() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            let body = once(ready(Ok::<_, io::Error>(Bytes::from_static(STR.as_ref()))));
            Ok::<_, io::Error>(
                Response::Ok()
                    .header(header::TRANSFER_ENCODING, "chunked")
                    .streaming(body),
            )
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());
    assert_eq!(
        response
            .headers()
            .get(header::TRANSFER_ENCODING)
            .unwrap()
            .to_str()
            .unwrap(),
        "chunked"
    );

    // read response
    let bytes = srv.load_body(response).await.unwrap();

    // decode
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}

/// STATEMENT: HTTP/1 automatically selects chunked encoding for an unsized response stream.
///
/// HOW:
/// - Stream one chunk containing `STR` without setting a transfer-encoding header.
/// - Verify success, an added `Transfer-Encoding: chunked`, and the complete decoded body.
#[ntex::test]
async fn test_h1_body_chunked_implicit() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            let body = once(ready(Ok::<_, io::Error>(Bytes::from_static(STR.as_ref()))));
            Ok::<_, io::Error>(Response::Ok().streaming(body))
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert!(response.status().is_success());
    assert_eq!(
        response
            .headers()
            .get(header::TRANSFER_ENCODING)
            .unwrap()
            .to_str()
            .unwrap(),
        "chunked"
    );

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}

/// STATEMENT: An unchunked HTTP/1 response stream is framed by its declared
/// `Content-Length`, so extra bytes cannot corrupt a keep-alive connection.
///
/// HOW:
/// - Respond with `no_chunking()`, `content_length(3)` and a stream yielding `ab`, `cd`.
/// - Pipeline two requests on one raw TCP connection.
/// - Check both responses arrive with body `abc`, and the first keeps the connection open.
#[ntex::test]
async fn test_h1_stream_declared_length() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            let body = futures_util::stream::iter(
                ["ab", "cd"].map(|c| Ok::<_, io::Error>(Bytes::from_static(c.as_bytes()))),
            );
            Ok::<_, io::Error>(
                Response::Ok()
                    .no_chunking()
                    .content_length(3)
                    .streaming(body),
            )
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    stream
        .write_all(
            b"GET / HTTP/1.1\r\nhost: localhost\r\n\r\n\
              GET / HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n",
        )
        .unwrap();
    let mut data = String::new();
    stream.read_to_string(&mut data).unwrap();

    let responses: Vec<_> = data.split("HTTP/1.1 200 OK\r\n").skip(1).collect();
    assert_eq!(responses.len(), 2, "{data:?}");
    for res in &responses {
        assert!(res.contains("content-length: 3\r\n"), "{data:?}");
        assert!(res.ends_with("\r\n\r\nabc"), "{data:?}");
    }
    assert!(!responses[0].contains("connection: close"), "{data:?}");
    assert!(data.starts_with("HTTP/1.1 200 OK\r\n"), "{data:?}");
}

/// STATEMENT: An invalid HTTP/1 response header becomes an internal-server-error response.
///
/// HOW:
/// - Build a response with a `Content-Type` value containing null bytes.
/// - Verify status `500` and the body `Invalid HTTP header value`.
#[ntex::test]
async fn test_h1_response_http_error_handling() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            let broken_header = Bytes::from_static(b"\0\0\0");
            Ok::<_, io::Error>(
                Response::Ok()
                    .header(header::CONTENT_TYPE, &broken_header[..])
                    .body(STR),
            )
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(b"Invalid HTTP header value"));
}

/// STATEMENT: HTTP/1 converts a service error into its configured response status and body.
///
/// HOW:
/// - Return an `InternalError` configured with `StatusCode::BAD_REQUEST` and the message `error`.
/// - Verify the client receives status `400` and that exact body.
#[ntex::test]
async fn test_h1_service_error() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_| {
            Err::<Response, _>(error::InternalError::default(
                "error",
                StatusCode::BAD_REQUEST,
            ))
        })
    });

    let response = srv.request(Method::GET, "/").send().await.unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(b"error"));
}

// /// STATEMENT: Dropping an HTTP/1 client request drops its pending server handler.
// ///
// /// HOW:
// /// - Delay the handler beyond the client timeout and attach a drop counter and notification.
// /// - Verify the request times out, await the drop notification, and assert one handler drop.
// #[ntex::test]
// async fn test_h1_client_drop() -> io::Result<()> {
// struct SetOnDrop(Arc<AtomicUsize>, Option<::oneshot::Sender<()>>);
// impl Drop for SetOnDrop {
//     fn drop(&mut self) {
//         self.0.fetch_add(1, Ordering::Relaxed);
//         let _ = self.1.take().unwrap().send(());
//     }
// }
//     let count = Arc::new(AtomicUsize::new(0));
//     let count2 = count.clone();
//     let (tx, rx) = ::oneshot::channel();
//     let tx = Arc::new(Mutex::new(Some(tx)));

//     let srv = test_server(async move |_| {
//         let tx = tx.clone();
//         let count = count2.clone();
//         HttpService::h1(async move |req: Request| {
//             let tx = tx.clone();
//             let count = count.clone();

//             let _st = SetOnDrop(count, tx.lock().unwrap().take());
//             assert!(req.peer_addr().is_some());
//             assert_eq!(req.version(), Version::HTTP_11);

//             // on connection close, server must drop pending handling future
//             sleep(Millis(150000)).await;
//             Ok::<_, io::Error>(Response::Ok().build())
//         })
//     });

//     let result = timeout(Millis(2500), srv.request(Method::GET, "/").send()).await;
//     assert!(result.is_err());
//     let _ = rx.await;
//     assert_eq!(count.load(Ordering::Relaxed), 1);
//     Ok(())
// }

/// STATEMENT: Graceful shutdown of `HttpService::h1` waits for active requests.
///
/// HOW:
/// - Hold two handlers on separate connections and start `srv.stop(true)`.
/// - Verify shutdown remains pending while both requests are active.
/// - Release the handlers, await shutdown completion, and verify the active count reaches zero.
#[ntex::test]
async fn test_h1_gracefull_shutdown() {
    let count = Arc::new(AtomicUsize::new(0));
    let count2 = count.clone();
    let release = Arc::new(AtomicBool::new(false));
    let release2 = release.clone();
    let (tx, rx) = ::oneshot::channel();
    let tx = Arc::new(Mutex::new(Some(tx)));

    let srv = test_server(async move |_| {
        let tx = tx.clone();
        let count = count2.clone();
        let release = release2.clone();
        HttpService::h1(async move |_: Request| {
            let count = count.clone();
            let release = release.clone();
            count.fetch_add(1, Ordering::Relaxed);
            if count.load(Ordering::Relaxed) == 2 {
                let _ = tx.lock().unwrap().take().unwrap().send(());
            }

            // the request stays in flight until the test releases it
            while !release.load(Ordering::Acquire) {
                sleep(Millis(10)).await;
            }
            count.fetch_sub(1, Ordering::Relaxed);
            Ok::<_, io::Error>(Response::Ok().build())
        })
    });

    let mut stream1 = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream1.write_all(b"GET /index.html HTTP/1.1\r\nhost: localhost\r\n\r\n");

    let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\nhost: localhost\r\n\r\n");

    let _ = rx.await;
    assert_eq!(count.load(Ordering::Relaxed), 2);

    let stopped = Arc::new(AtomicBool::new(false));
    let stopped2 = stopped.clone();
    let (tx, rx) = oneshot::channel();
    rt::spawn(async move {
        srv.stop(true).await;
        stopped2.store(true, Ordering::Release);
        let _ = tx.send(());
    });

    // shutdown does not complete while the requests are in flight
    sleep(Millis(300)).await;
    assert!(
        !stopped.load(Ordering::Acquire),
        "shutdown did not wait for in-flight requests"
    );
    assert_eq!(count.load(Ordering::Relaxed), 2);

    release.store(true, Ordering::Release);
    let _ = rx.await;
    assert_eq!(count.load(Ordering::Relaxed), 0);
}

struct FailingControl;

impl<St, F, E> ntex::ServiceFactory<St, Control<F, E>> for FailingControl
where
    F: ntex::io::Filter,
    E: ntex::http::ResponseError,
{
    type Res = h1::ControlAck<F>;
    type Error = io::Error;
    type Service = FailingControl;
    type InitError = io::Error;

    async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError> {
        Err(io::Error::other("control init failed"))
    }
}

impl<St, F, E> ntex::Service<St, Control<F, E>> for FailingControl
where
    F: ntex::io::Filter,
    E: ntex::http::ResponseError,
{
    type Res = h1::ControlAck<F>;
    type Error = io::Error;

    async fn call(
        &self,
        req: Control<F, E>,
        _: ntex::Ctx<'_, Self, St>,
    ) -> Result<Self::Res, Self::Error> {
        Ok(req.ack())
    }
}

/// STATEMENT: HTTP/1 control-service initialization failure does not leak a shutdown blocker.
///
/// HOW:
/// - Use `FailingControl` to reject control-service creation and verify the connection sends no data.
/// - Request graceful shutdown and verify it completes within five seconds.
#[ntex::test]
async fn test_h1_control_init_error_does_not_block_shutdown() {
    let srv = test_server(async |_| {
        HttpService::new(async |_: Request| Ok::<_, io::Error>(Response::Ok().build()))
            .h1_control(FailingControl)
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /index.html HTTP/1.1\r\n\r\n");
    let mut data = Vec::new();
    let _ = stream.read_to_end(&mut data);
    assert!(data.is_empty());

    let res = ntex::time::timeout(Seconds(5), srv.stop(true)).await;
    assert!(
        res.is_ok(),
        "graceful shutdown waited for leaked connection"
    );
}

/// STATEMENT: Graceful shutdown of `HttpService::new` waits for active HTTP/1 requests.
///
/// HOW:
/// - Hold two HTTP/1 handlers on separate connections and start `srv.stop(true)`.
/// - Verify shutdown remains pending while both requests are active.
/// - Release the handlers, await shutdown completion, and verify the active count reaches zero.
#[ntex::test]
async fn test_h1_gracefull_shutdown_2() {
    let count = Arc::new(AtomicUsize::new(0));
    let count2 = count.clone();
    let release = Arc::new(AtomicBool::new(false));
    let release2 = release.clone();
    let (tx, rx) = ::oneshot::channel();
    let tx = Arc::new(Mutex::new(Some(tx)));

    let srv = test_server(async move |_| {
        let tx = tx.clone();
        let count = count2.clone();
        let release = release2.clone();
        HttpService::new(async move |_: Request| {
            let count = count.clone();
            let release = release.clone();
            count.fetch_add(1, Ordering::Relaxed);
            if count.load(Ordering::Relaxed) == 2 {
                let _ = tx.lock().unwrap().take().unwrap().send(());
            }

            // the request stays in flight until the test releases it
            while !release.load(Ordering::Acquire) {
                sleep(Millis(10)).await;
            }
            count.fetch_sub(1, Ordering::Relaxed);
            Ok::<_, io::Error>(Response::Ok().build())
        })
    });

    let mut stream1 = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream1.write_all(b"GET /index.html HTTP/1.1\r\nhost: localhost\r\n\r\n");

    let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\nhost: localhost\r\n\r\n");

    let _ = rx.await;
    assert_eq!(count.load(Ordering::Acquire), 2);

    let stopped = Arc::new(AtomicBool::new(false));
    let stopped2 = stopped.clone();
    let (tx, rx) = oneshot::channel();
    rt::spawn(async move {
        srv.stop(true).await;
        stopped2.store(true, Ordering::Release);
        let _ = tx.send(());
    });

    // shutdown does not complete while the requests are in flight
    sleep(Millis(300)).await;
    assert!(
        !stopped.load(Ordering::Acquire),
        "shutdown did not wait for in-flight requests"
    );
    assert_eq!(count.load(Ordering::Relaxed), 2);

    release.store(true, Ordering::Release);
    let _ = rx.await;
    assert_eq!(count.load(Ordering::Relaxed), 0);
}

struct HandlerReadinessGate {
    available: Cell<bool>,
    changed: ReadyNotifier,
    binds: Arc<AtomicUsize>,
    pending: Arc<AtomicBool>,
}

impl ntex::Service<(), ntex::web::WebRequest<()>> for HandlerReadinessGate {
    type Res = ntex::web::WebRequest<()>;
    type Error = Infallible;

    fn bind(&self, ctx: BindCtx<'_>) {
        self.binds.fetch_add(1, Ordering::Relaxed);
        ctx.subscribe(&self.changed);
    }

    async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), Infallible> {
        poll_fn(|_| {
            if self.available.get() {
                Poll::Ready(Ok(()))
            } else {
                self.pending.store(true, Ordering::Release);
                Poll::Pending
            }
        })
        .await
    }

    async fn call(
        &self,
        req: ntex::web::WebRequest<()>,
        _: Ctx<'_, Self>,
    ) -> Result<Self::Res, Infallible> {
        Ok(req)
    }
}

async fn h1_initialized_handler_readiness(path: &'static str) {
    use std::io::{BufRead, BufReader};

    use ntex::service::{apply_fn_factory, fn_factory};
    use ntex::web::{self, App, WebRequest};

    fn read_response(stream: &mut BufReader<net::TcpStream>) {
        let mut line = String::new();
        stream.read_line(&mut line).unwrap();
        assert_eq!(line, "HTTP/1.1 200 OK\r\n");
        loop {
            line.clear();
            assert_ne!(stream.read_line(&mut line).unwrap(), 0);
            if line == "\r\n" {
                break;
            }
        }
    }

    let calls = Arc::new(AtomicUsize::new(0));
    let heads = Arc::new(AtomicUsize::new(0));
    let binds = Arc::new(AtomicUsize::new(0));
    let blocked = Arc::new(AtomicBool::new(false));
    let pending = Arc::new(AtomicBool::new(false));
    let calls2 = calls.clone();
    let heads2 = heads.clone();
    let binds2 = binds.clone();
    let blocked2 = blocked.clone();
    let pending2 = pending.clone();
    let (block_tx, block_rx) = ::oneshot::channel();
    let (resume_tx, resume_rx) = ::oneshot::channel();
    let control = Arc::new(Mutex::new(Some((block_rx, resume_rx))));

    let srv = test_server(async move |_| {
        let gate = Rc::new(HandlerReadinessGate {
            available: Cell::new(true),
            changed: ReadyNotifier::new(),
            binds: binds2.clone(),
            pending: pending2.clone(),
        });
        let handler = ntex::factory(fn_factory({
            let gate = gate.clone();
            async move |(): &()| Ok::<_, Infallible>(gate.clone())
        }))
        .map(|req: WebRequest<()>| req.into_response(Response::Ok()));
        let app = App::new()
            .service(web::service("/blocked").build(handler.clone()))
            .service(web::resource("/ready").to(async || Response::Ok()))
            .service(
                web::resource("/resource")
                    .route(web::get().to(async || Response::Ok()))
                    .default_service(handler.clone()),
            )
            .default_service(handler);

        let blocked = blocked2.clone();
        let (block_rx, resume_rx) = control.lock().unwrap().take().unwrap();
        rt::spawn(async move {
            if block_rx.await.is_ok() {
                gate.available.set(false);
                gate.changed.notify();
                blocked.store(true, Ordering::Release);
                if resume_rx.await.is_ok() {
                    gate.available.set(true);
                    gate.changed.notify();
                }
            }
        });

        let calls = calls2.clone();
        let heads = heads2.clone();
        HttpService::h1(apply_fn_factory(app, async move |req: Request, ctx| {
            calls.fetch_add(1, Ordering::Relaxed);
            ctx.call(req).await
        }))
        .control(async move |event: Control<_, _>| {
            if matches!(event, Control::Request(_)) {
                heads.fetch_add(1, Ordering::Relaxed);
            }
            Ok::<_, Infallible>(event.ack())
        })
    });

    let stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream.set_read_timeout(Some(TEN_SECONDS)).unwrap();
    let mut stream = BufReader::new(stream);
    for path in ["/ready", path, "/ready"] {
        write!(
            stream.get_mut(),
            "GET {path} HTTP/1.1\r\nhost: localhost\r\n\r\n"
        )
        .unwrap();
        read_response(&mut stream);
    }
    assert_eq!(binds.load(Ordering::Relaxed), 1);
    assert_eq!(calls.load(Ordering::Relaxed), 3);
    assert_eq!(heads.load(Ordering::Relaxed), 3);

    block_tx.send(()).unwrap();
    wait_for(|| blocked.load(Ordering::Acquire)).await.unwrap();
    stream
        .get_mut()
        .write_all(
            b"GET /ready HTTP/1.1\r\nhost: localhost\r\n\r\n\
              GET /ready HTTP/1.1\r\nhost: localhost\r\n\r\n",
        )
        .unwrap();
    wait_for(|| pending.load(Ordering::Acquire))
        .await
        .expect("the dispatcher did not check the initialized handler's readiness");
    stream
        .get_ref()
        .set_read_timeout(Some(std::time::Duration::from_millis(100)))
        .unwrap();
    let result = stream.read(&mut [0; 1]);
    assert!(
        matches!(result, Err(ref err)
            if matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut)),
        "an unrelated request responded or disconnected while {path} was not ready: {result:?}"
    );
    assert_eq!(
        heads.load(Ordering::Relaxed),
        3,
        "the dispatcher decoded a new request while {path} was not ready"
    );
    assert_eq!(
        calls.load(Ordering::Relaxed),
        3,
        "the dispatcher entered the application while {path} was not ready"
    );

    resume_tx.send(()).unwrap();
    stream
        .get_ref()
        .set_read_timeout(Some(TEN_SECONDS))
        .unwrap();
    read_response(&mut stream);
    read_response(&mut stream);
    assert_eq!(heads.load(Ordering::Relaxed), 5);
    assert_eq!(calls.load(Ordering::Relaxed), 5);
    assert_eq!(binds.load(Ordering::Relaxed), 1);
}

/// STATEMENT: An initialized route's readiness gates HTTP/1 dispatch for other routes.
///
/// HOW:
/// - Initialize resource zero and a healthy route on one HTTP/1.1 connection, then cache readiness.
/// - Notify that resource zero is unavailable and pipeline two requests to the healthy route.
/// - Observe pending readiness with no response, new `Control::Request`, or application entry.
/// - Notify recovery and verify both queued requests complete without rebinding the handler.
#[ntex::test]
async fn test_h1_initialized_route_readiness_blocks_dispatch() {
    h1_initialized_handler_readiness("/blocked").await;
}

/// STATEMENT: An initialized default handler's readiness gates HTTP/1 dispatch to matching routes.
///
/// HOW:
/// - Initialize the fallback and a healthy route on one HTTP/1.1 connection, then cache readiness.
/// - Notify that the fallback is unavailable and pipeline two requests to the healthy route.
/// - Observe pending readiness with no response, new `Control::Request`, or application entry.
/// - Notify recovery and verify both queued requests complete without rebinding the handler.
#[ntex::test]
async fn test_h1_initialized_default_readiness_blocks_dispatch() {
    h1_initialized_handler_readiness("/missing").await;
}

/// STATEMENT: An initialized resource fallback gates HTTP/1 dispatch even when never selected.
///
/// HOW:
/// - Match a resource's `GET` route to initialize its fallback without invoking it.
/// - Mark that fallback unavailable and pipeline two requests to an unrelated healthy route.
/// - Observe pending readiness with no response, new `Control::Request`, or application entry.
/// - Notify recovery and verify both requests complete without rebinding the fallback.
#[ntex::test]
async fn test_h1_initialized_resource_fallback_readiness_blocks_dispatch() {
    h1_initialized_handler_readiness("/resource").await;
}

async fn h2_initialized_handler_readiness(path: &'static str) {
    use ntex::http::HeaderMap;
    use ntex::service::{apply_fn_factory, fn_factory};
    use ntex::time::timeout;
    use ntex::web::{self, App, WebRequest};
    use ntex_h2::{MessageKind, client::SimpleClient};

    let calls = Arc::new(AtomicUsize::new(0));
    let binds = Arc::new(AtomicUsize::new(0));
    let blocked = Arc::new(AtomicBool::new(false));
    let pending = Arc::new(AtomicBool::new(false));
    let calls2 = calls.clone();
    let binds2 = binds.clone();
    let blocked2 = blocked.clone();
    let pending2 = pending.clone();
    let (block_tx, block_rx) = ::oneshot::channel();
    let (resume_tx, resume_rx) = ::oneshot::channel();
    let control = Arc::new(Mutex::new(Some((block_rx, resume_rx))));

    let srv = test_server(async move |_| {
        let gate = Rc::new(HandlerReadinessGate {
            available: Cell::new(true),
            changed: ReadyNotifier::new(),
            binds: binds2.clone(),
            pending: pending2.clone(),
        });
        let handler = ntex::factory(fn_factory({
            let gate = gate.clone();
            async move |(): &()| Ok::<_, Infallible>(gate.clone())
        }))
        .map(|req: WebRequest<()>| req.into_response(Response::Ok()));
        let app = App::new()
            .service(web::service("/blocked").build(handler.clone()))
            .service(web::resource("/ready").to(async || Response::Ok()))
            .service(
                web::resource("/resource")
                    .route(web::get().to(async || Response::Ok()))
                    .default_service(handler.clone()),
            )
            .default_service(handler);

        let blocked = blocked2.clone();
        let (block_rx, resume_rx) = control.lock().unwrap().take().unwrap();
        rt::spawn(async move {
            if block_rx.await.is_ok() {
                gate.available.set(false);
                gate.changed.notify();
                blocked.store(true, Ordering::Release);
                if resume_rx.await.is_ok() {
                    gate.available.set(true);
                    gate.changed.notify();
                }
            }
        });

        let calls = calls2.clone();
        HttpService::h2(apply_fn_factory(app, async move |req: Request, ctx| {
            calls.fetch_add(1, Ordering::Relaxed);
            ctx.call(req).await
        }))
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    for path in ["/ready", path, "/ready"] {
        let (_snd, rcv) = client
            .send(Method::GET, path.into(), HeaderMap::default(), true)
            .await
            .unwrap();
        let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Headers { ref pseudo, eof: true, .. }
                if pseudo.status == Some(StatusCode::OK)),
            "{path}: {msg:?}"
        );
    }
    assert_eq!(binds.load(Ordering::Relaxed), 1);
    assert_eq!(calls.load(Ordering::Relaxed), 3);

    block_tx.send(()).unwrap();
    wait_for(|| blocked.load(Ordering::Acquire)).await.unwrap();
    let (_first, first) = client
        .send(Method::GET, "/ready".into(), HeaderMap::default(), true)
        .await
        .unwrap();
    wait_for(|| pending.load(Ordering::Acquire))
        .await
        .expect("the dispatcher did not check the initialized handler's readiness");
    let (_second, second) = client
        .send(Method::GET, "/ready".into(), HeaderMap::default(), true)
        .await
        .unwrap();
    for rcv in [&first, &second] {
        assert!(
            timeout(Millis(100), rcv.recv()).await.is_err(),
            "an unrelated request completed while {path} was not ready"
        );
    }
    assert_eq!(
        calls.load(Ordering::Relaxed),
        3,
        "the dispatcher entered the application while {path} was not ready"
    );

    resume_tx.send(()).unwrap();
    for rcv in [&first, &second] {
        let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Headers { ref pseudo, eof: true, .. }
                if pseudo.status == Some(StatusCode::OK)),
            "{msg:?}"
        );
    }
    assert_eq!(calls.load(Ordering::Relaxed), 5);
    assert_eq!(binds.load(Ordering::Relaxed), 1);
}

/// STATEMENT: An initialized route's readiness gates HTTP/2 application dispatch for other routes.
///
/// HOW:
/// - Initialize resource zero and a healthy route on one HTTP/2 connection, then cache readiness.
/// - Notify that resource zero is unavailable and send two requests to the healthy route.
/// - Observe pending readiness, no responses, and no application entry until recovery is notified.
/// - Verify both queued requests complete without rebinding the blocked handler.
#[ntex::test]
async fn test_h2_initialized_route_readiness_blocks_dispatch() {
    h2_initialized_handler_readiness("/blocked").await;
}

/// STATEMENT: An initialized default handler's readiness gates HTTP/2 dispatch to matching routes.
///
/// HOW:
/// - Initialize the fallback and a healthy route on one HTTP/2 connection, then cache readiness.
/// - Notify that the fallback is unavailable and send two requests matching the healthy route.
/// - Observe pending readiness, no responses, and no application entry until recovery is notified.
/// - Verify both queued requests complete without rebinding the default handler.
#[ntex::test]
async fn test_h2_initialized_default_readiness_blocks_dispatch() {
    h2_initialized_handler_readiness("/missing").await;
}

/// STATEMENT: An initialized resource fallback gates HTTP/2 dispatch even when never selected.
///
/// HOW:
/// - Match a resource's `GET` route to initialize its fallback without invoking it.
/// - Mark that fallback unavailable and send two requests to an unrelated healthy route.
/// - Observe pending readiness, no responses, and no application entry until recovery is notified.
/// - Verify both queued requests complete without rebinding the fallback.
#[ntex::test]
async fn test_h2_initialized_resource_fallback_readiness_blocks_dispatch() {
    h2_initialized_handler_readiness("/resource").await;
}

/// STATEMENT: HTTP/2 keeps delivering request payloads while the application is at capacity.
///
/// HOW:
/// - Limit the request service to one in-flight call and wait for it to start reading a body.
/// - Send the body after the service consumes its slot and verify the handler receives it.
#[ntex::test]
async fn test_h2_request_readiness_does_not_block_payload() {
    use ntex::http::HeaderMap;
    use ntex::util::BytesMut;
    use ntex_h2::client::SimpleClient;
    use ntex_util::services::inflight::InFlight;

    let started = Arc::new(AtomicBool::new(false));
    let received = Arc::new(Mutex::new(None));
    let started2 = started.clone();
    let received2 = received.clone();
    let srv = test_server(async move |_| {
        let started = started2.clone();
        let received = received2.clone();
        HttpService::h2(
            ntex::factory(move |mut req: Request| {
                let started = started.clone();
                let received = received.clone();
                async move {
                    started.store(true, Ordering::Release);
                    let mut body = BytesMut::new();
                    while let Some(chunk) = req.payload().next().await {
                        body.extend_from_slice(&chunk.map_err(io::Error::other)?);
                    }
                    *received.lock().unwrap() = Some(body.freeze());
                    Ok::<_, io::Error>(Response::Ok().build())
                }
            })
            .apply(InFlight::new(1)),
        )
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let (snd, _rcv) = client
        .send(Method::POST, "/".into(), HeaderMap::default(), false)
        .await
        .unwrap();
    wait_for(|| started.load(Ordering::Acquire)).await.unwrap();
    snd.send_payload(Bytes::from_static(b"pay"), false)
        .await
        .unwrap();
    snd.send_payload(Bytes::from_static(b"load"), true)
        .await
        .unwrap();
    wait_for(|| received.lock().unwrap().is_some())
        .await
        .expect("application readiness blocked delivery of the active request's body");
    assert_eq!(
        received.lock().unwrap().take(),
        Some(Bytes::from_static(b"payload"))
    );
}

/// STATEMENT: Dropping an unfinished HTTP/2 request body after its response resets the stream.
///
/// HOW:
/// - Retain the request payload in a task, read a chunk, then drop it after a delay.
/// - Verify the response completes while the request body remains open.
/// - Attempt further payload writes and verify the request stream becomes unwritable.
#[ntex::test]
async fn test_h2_request_body_dropped_after_response_resets_stream() {
    use ntex::http::{HeaderMap, Payload};
    use ntex::util::stream_recv;
    use ntex_h2::{MessageKind, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |mut req: Request| {
            // the request body is held after the response and dropped later
            let mut pl: Payload = req.take_payload();
            rt::spawn(async move {
                let _ = stream_recv(&mut pl).await;
                sleep(Millis(200)).await;
                drop(pl);
            });
            Ok::<_, io::Error>(Response::Ok().body("ok"))
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let (snd, rcv) = client
        .send(Method::POST, "/".into(), HeaderMap::default(), false)
        .await
        .unwrap();
    snd.send_payload(Bytes::from_static(b"chunk"), false)
        .await
        .unwrap();

    // complete response, the request body is still open
    let mut eof = false;
    while let Some(msg) = rcv.recv().await {
        match msg.kind {
            MessageKind::Headers { eof: true, .. } | MessageKind::Eof(_) => {
                eof = true;
                break;
            }
            _ => (),
        }
    }
    assert!(eof);

    // no data frame follows, the stream is reset when the body is dropped
    let mut reset = false;
    for _ in 0..100 {
        if snd
            .send_payload(Bytes::from_static(b"chunk"), false)
            .await
            .is_err()
        {
            reset = true;
            break;
        }
        sleep(Millis(50)).await;
    }
    assert!(reset, "request stream is not reset");
}

/// STATEMENT: An HTTP/2 payload reports its stream reset once, then ends without hanging.
///
/// HOW:
/// - Keep reading the payload after the handler returns, send one chunk, and reset with `CANCEL`.
/// - Verify the reader finishes with exactly the chunk and the `CANCEL` error, without a timeout.
#[ntex::test]
async fn test_h2_request_payload_ends_after_error() {
    use ntex::http::HeaderMap;
    use ntex::util::stream_recv;
    use ntex_h2::client::SimpleClient;

    let result = Arc::new(Mutex::new(None));
    let result2 = result.clone();
    let srv = test_server(async move |_| {
        let result = result2.clone();
        HttpService::h2(move |mut req: Request| {
            let result = result.clone();
            async move {
                // the request body outlives the handler
                let mut pl = req.take_payload();
                rt::spawn(async move {
                    let mut items = Vec::new();
                    loop {
                        match ntex::time::timeout(Millis(500), stream_recv(&mut pl)).await {
                            Ok(Some(Ok(chunk))) => items.push(format!("{chunk:?}")),
                            Ok(Some(Err(e))) => items.push(format!("error: {e:?}")),
                            Ok(None) => break,
                            Err(()) => {
                                items.push("timeout".to_string());
                                break;
                            }
                        }
                    }
                    *result.lock().unwrap() = Some(items);
                });
                Ok::<_, io::Error>(Response::Ok().body("ok"))
            }
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let (snd, _rcv) = client
        .send(Method::POST, "/".into(), HeaderMap::default(), false)
        .await
        .unwrap();
    snd.send_payload(Bytes::from_static(b"chunk"), false)
        .await
        .unwrap();
    sleep(Millis(50)).await;
    snd.reset(ntex_h2::frame::Reason::CANCEL);

    let mut items = None;
    for _ in 0..100 {
        sleep(Millis(20)).await;
        items = result.lock().unwrap().take();
        if items.is_some() {
            break;
        }
    }
    // the stream reset error is reported, not a generic incomplete payload
    let items = items.expect("request body is not completed");
    assert_eq!(items.len(), 2, "{items:?}");
    assert_eq!(items[0], "b\"chunk\"");
    assert!(
        items[1].starts_with("error:") && items[1].contains("CANCEL"),
        "{items:?}"
    );
}

/// STATEMENT: Opt-in HTTP/2 target validation rejects malformed targets without closing connections.
///
/// HOW:
/// - Send malformed paths and authorities to a lower-level HTTP service with open/closed bodies.
/// - Require `400` only with validation-only or normalization enabled, including for
///   delimiters inside an authority.
/// - Check OPTIONS retains its asterisk path and valid requests still succeed on the same connection.
#[ntex::test]
async fn test_h2_malformed_request_uri() {
    use ntex::http::HeaderMap;
    use ntex::time::timeout;
    use ntex_h2::{MessageKind, client::SimpleClient};

    for mode in [TargetMode::Raw, TargetMode::Validate, TargetMode::Normalize] {
        let cfg = target_config(mode);
        let srv = test::server_with_config(
            async |_| {
                HttpService::h2(async |req: Request| {
                    if req.method() == Method::OPTIONS {
                        assert_eq!(req.path(), "*");
                    }
                    Ok::<_, io::Error>(Response::Ok().build())
                })
            },
            SharedCfg::new("SRV").add(cfg),
        );
        for authority in ["localhost", "host/path"] {
            let io = ntex::connect::connect(srv.addr()).await.unwrap();
            let client = SimpleClient::new(io, false, authority.into());
            for (method, path, eof) in [
                (Method::GET, "/a b", true),
                (Method::POST, "/bad%zz", false),
                (Method::GET, "relative", true),
                (Method::OPTIONS, "*", true),
                (Method::GET, "/", true),
            ] {
                let (_snd, rcv) = client
                    .send(method, path.into(), HeaderMap::default(), eof)
                    .await
                    .unwrap();
                let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
                let MessageKind::Headers { pseudo, eof, .. } = msg.kind else {
                    panic!("unexpected message: {msg:?}")
                };
                let valid = authority == "localhost" && matches!(path, "/" | "*");
                let expected = if mode != TargetMode::Raw && !valid {
                    StatusCode::BAD_REQUEST
                } else {
                    StatusCode::OK
                };
                assert_eq!(pseudo.status, Some(expected), "{authority}{path}");
                assert!(eof);
            }
            assert!(!client.is_closed());
        }
    }
}

/// STATEMENT: The `HttpServiceConfig` header limit rejects HTTP/2 streams without closing connections.
///
/// HOW:
/// - Configure `set_max_headers(2)` and send requests with two and three header fields,
///   where the three fields repeat one header name, with open and closed request bodies.
/// - Require `431` for three fields and `200` for two fields, all on one connection.
/// - For a rejected open request body, verify further payload writes fail because the
///   stream is reset.
/// - Check the connection is still open afterwards.
#[ntex::test]
async fn test_h2_max_headers() {
    use ntex::http::{HeaderMap, HttpServiceConfig, header};
    use ntex::time::timeout;
    use ntex_h2::{MessageKind, client::SimpleClient};

    let srv = test::server_with_config(
        async |_| HttpService::h2(async |_| Ok::<_, io::Error>(Response::Ok().build())),
        SharedCfg::new("SRV").add(HttpServiceConfig::new().set_max_headers(2)),
    );
    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    for (count, eof, expected) in [
        (3, true, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE),
        (2, true, StatusCode::OK),
        (3, false, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE),
        (2, false, StatusCode::OK),
    ] {
        let mut headers = HeaderMap::default();
        headers.insert(header::USER_AGENT, header::HeaderValue::from_static("test"));
        for value in ["a", "b"].into_iter().take(count - 1) {
            headers.append(header::ACCEPT, header::HeaderValue::from_static(value));
        }
        let (snd, rcv) = client
            .send(Method::POST, "/".into(), headers, eof)
            .await
            .unwrap();
        if !eof && expected == StatusCode::OK {
            snd.send_payload(Bytes::new(), true).await.unwrap();
        }
        let msg = timeout(Seconds(5), rcv.recv()).await.unwrap().unwrap();
        let MessageKind::Headers { pseudo, .. } = msg.kind else {
            panic!("unexpected message: {msg:?}")
        };
        assert_eq!(pseudo.status, Some(expected), "{count} {eof}");

        if !eof && expected != StatusCode::OK {
            let mut reset = false;
            for _ in 0..100 {
                if snd.send_payload(Bytes::new(), false).await.is_err() {
                    reset = true;
                    break;
                }
                sleep(Millis(50)).await;
            }
            assert!(reset, "request stream is not reset");
        }
    }
    assert!(!client.is_closed());
}

/// STATEMENT: An HTTP/2 response body error resets only the failing stream.
///
/// HOW:
/// - Start a delayed successful request and a request whose response stream returns an error.
/// - Verify the failing stream sends `200` headers followed by an `INTERNAL_ERROR` reset.
/// - Verify the other response completes with its expected body and the connection stays open.
#[ntex::test]
async fn test_h2_response_body_error_resets_stream() {
    use ntex::http::HeaderMap;
    use ntex_h2::{MessageKind, StreamEof, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |req: Request| {
            if req.path() == "/err" {
                Ok::<_, io::Error>(Response::Ok().streaming(Box::pin(once(async {
                    Err::<Bytes, _>(io::Error::other("body error"))
                }))))
            } else {
                // the response is sent after the other stream fails
                sleep(Millis(200)).await;
                Ok(Response::Ok().body("ok"))
            }
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let (_snd1, rcv1) = client
        .send(Method::GET, "/slow".into(), HeaderMap::default(), true)
        .await
        .unwrap();
    let (_snd2, rcv2) = client
        .send(Method::GET, "/err".into(), HeaderMap::default(), true)
        .await
        .unwrap();

    let msg = rcv2.recv().await.unwrap();
    let MessageKind::Headers { pseudo, eof, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::OK));
    assert!(!eof);
    let msg = rcv2.recv().await.unwrap();
    assert!(
        matches!(msg.kind, MessageKind::Eof(StreamEof::Error(ref e)) if format!("{e:?}").contains("INTERNAL_ERROR")),
        "{msg:?}"
    );

    // the other stream completes
    let msg = rcv1.recv().await.unwrap();
    let MessageKind::Headers { pseudo, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::OK));
    let msg = rcv1.recv().await.unwrap();
    assert!(
        matches!(msg.kind, MessageKind::Eof(StreamEof::Data(ref d, _)) if d == "ok"),
        "{msg:?}"
    );
    assert!(!client.is_closed());
}

/// STATEMENT: HTTP/2 `304 Not Modified` responses omit bodies and content-length headers.
///
/// HOW:
/// - Return `304` responses with empty, fixed, and streaming application bodies.
/// - Verify each response ends at its headers and contains no `Content-Length`.
#[ntex::test]
async fn test_h2_not_modified_has_no_body() {
    use ntex::http::HeaderMap;
    use ntex_h2::{MessageKind, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |req: Request| {
            let mut res = Response::builder(StatusCode::NOT_MODIFIED);
            Ok::<_, io::Error>(match req.path() {
                "/sized" => res.body("body"),
                "/stream" => res.streaming(Box::pin(once(async {
                    Ok::<_, io::Error>(Bytes::from_static(b"body"))
                }))),
                _ => res.build(),
            })
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    for path in ["/empty", "/sized", "/stream"] {
        let (_snd, rcv) = client
            .send(Method::GET, path.into(), HeaderMap::default(), true)
            .await
            .unwrap();
        let msg = rcv.recv().await.unwrap();
        let MessageKind::Headers {
            pseudo,
            headers,
            eof,
        } = msg.kind
        else {
            panic!("unexpected message: {msg:?}")
        };
        assert_eq!(pseudo.status, Some(StatusCode::NOT_MODIFIED), "{path}");
        assert!(eof, "{path}: body is sent");
        assert!(
            !headers.contains_key(header::CONTENT_LENGTH),
            "{path}: {headers:?}"
        );
    }
}

/// STATEMENT: HTTP/2 sized and unsized response bodies use their expected end-stream framing.
///
/// HOW:
/// - Return the same two chunks through a sized stream and an unsized stream.
/// - Verify successful headers with `Date`, and length six for the sized response.
/// - Verify the sized stream ends on its last chunk, while the unsized stream ends with empty data.
#[ntex::test]
async fn test_h2_response_body_end_stream() {
    use ntex::http::HeaderMap;
    use ntex_h2::{MessageKind, StreamEof, client::SimpleClient};

    fn chunks<E>() -> futures_util::stream::Iter<std::array::IntoIter<Result<Bytes, E>, 2>> {
        futures_util::stream::iter([
            Ok(Bytes::from_static(b"abc")),
            Ok(Bytes::from_static(b"def")),
        ])
    }

    let srv = test_server(async |_| {
        HttpService::h2(async |req: Request| {
            Ok::<_, io::Error>(if req.path() == "/sized" {
                Response::Ok().body(body::SizedStream::new(6, chunks()))
            } else {
                Response::Ok().streaming(chunks::<io::Error>())
            })
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    for (path, last) in [("/sized", "def"), ("/stream", "")] {
        let (_snd, rcv) = client
            .send(Method::GET, path.into(), HeaderMap::default(), true)
            .await
            .unwrap();
        let msg = rcv.recv().await.unwrap();
        let MessageKind::Headers {
            pseudo, headers, ..
        } = msg.kind
        else {
            panic!("unexpected message: {msg:?}")
        };
        assert_eq!(pseudo.status, Some(StatusCode::OK), "{path}");
        assert!(headers.contains_key(header::DATE), "{path}: {headers:?}");
        if path == "/sized" {
            assert_eq!(headers.get(header::CONTENT_LENGTH).unwrap(), "6");
        }

        let msg = rcv.recv().await.unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Data(ref d, _) if d == "abc"),
            "{path}: {msg:?}"
        );
        if path == "/stream" {
            let msg = rcv.recv().await.unwrap();
            assert!(
                matches!(msg.kind, MessageKind::Data(ref d, _) if d == "def"),
                "{path}: {msg:?}"
            );
        }
        let msg = rcv.recv().await.unwrap();
        assert!(
            matches!(msg.kind, MessageKind::Eof(StreamEof::Data(ref d, _)) if d == last),
            "{path}: {msg:?}"
        );
    }
}

/// Raw HTTP/2 connection preface and a `POST /` request without END_STREAM.
fn h2_raw_post() -> Vec<u8> {
    let mut buf = Vec::new();
    buf.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
    // SETTINGS
    buf.extend_from_slice(&[0, 0, 0, 4, 0, 0, 0, 0, 0]);
    // HEADERS, END_HEADERS: `:method POST`, `:scheme http`, `:path /`
    buf.extend_from_slice(&[0, 0, 3, 1, 4, 0, 0, 0, 1, 0x83, 0x86, 0x84]);
    buf
}

/// Raw HTTP/2 DATA frame for stream 1.
fn h2_raw_data(buf: &mut Vec<u8>, data: &[u8], eof: bool) {
    #[allow(clippy::cast_possible_truncation)]
    buf.extend_from_slice(&[0, 0, data.len() as u8, 0, u8::from(eof), 0, 0, 0, 1]);
    buf.extend_from_slice(data);
}

/// STATEMENT: HTTP/2 skips empty non-final data frames and resets their count after non-empty data.
///
/// HOW:
/// - Send two groups of nine empty frames, separated and followed by non-empty payload data.
/// - Verify the handler receives only `a` and `bc`, with no empty chunks.
/// - Verify the connection remains open and no `GOAWAY` is sent.
#[ntex::test]
async fn test_h2_empty_data_frames_are_not_queued() {
    use ntex::util::stream_recv;

    let chunks = Arc::new(Mutex::new(None));
    let chunks2 = chunks.clone();
    let srv = test_server(async move |_| {
        let chunks = chunks2.clone();
        HttpService::h2(move |mut req: Request| {
            let chunks = chunks.clone();
            async move {
                let mut pl = req.take_payload();
                let mut items = Vec::new();
                while let Some(chunk) = stream_recv(&mut pl).await {
                    items.push(chunk.unwrap());
                }
                *chunks.lock().unwrap() = Some(items);
                Ok::<_, io::Error>(Response::Ok().body("ok"))
            }
        })
    });

    // a non-empty DATA frame resets the count of consecutive empty frames
    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let mut buf = h2_raw_post();
    for _ in 0..9 {
        h2_raw_data(&mut buf, b"", false);
    }
    h2_raw_data(&mut buf, b"a", false);
    for _ in 0..9 {
        h2_raw_data(&mut buf, b"", false);
    }
    h2_raw_data(&mut buf, b"bc", true);
    stream.write_all(&buf).unwrap();

    wait_for(|| chunks.lock().unwrap().is_some())
        .await
        .expect("request is not completed");
    assert_eq!(
        chunks.lock().unwrap().take().unwrap(),
        vec![Bytes::from("a"), Bytes::from("bc")]
    );

    // the connection stays open
    let frames = h2_raw_read_frames(&mut stream);
    assert!(
        !frames.0.iter().any(|f| f.0 == 7),
        "GOAWAY is sent: {frames:?}"
    );
    assert!(!frames.1, "connection is closed");
}

/// STATEMENT: HTTP/2 exposes request trailers after the payload reaches EOF.
///
/// HOW:
/// - Send raw frames carrying `abc` followed by final headers containing `x-trailer: 1`.
/// - Drain the payload and verify the body plus exactly one trailer with the expected value.
#[ntex::test]
async fn test_h2_request_trailers() {
    use ntex::util::stream_recv;

    let result = Arc::new(Mutex::new(None));
    let result2 = result.clone();
    let srv = test_server(async move |_| {
        let result = result2.clone();
        HttpService::h2(move |mut req: Request| {
            let result = result.clone();
            async move {
                let mut pl = req.take_payload();
                let mut body = Vec::new();
                while let Some(chunk) = stream_recv(&mut pl).await {
                    body.extend_from_slice(&chunk.unwrap());
                }
                *result.lock().unwrap() = Some((body, pl.trailers()));
                Ok::<_, io::Error>(Response::Ok().body("ok"))
            }
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let mut buf = h2_raw_post();
    h2_raw_data(&mut buf, b"abc", false);
    // HEADERS, END_STREAM | END_HEADERS: `x-trailer: 1`
    buf.extend_from_slice(&[0, 0, 13, 1, 5, 0, 0, 0, 1, 0, 9]);
    buf.extend_from_slice(b"x-trailer");
    buf.extend_from_slice(&[1, b'1']);
    stream.write_all(&buf).unwrap();

    wait_for(|| result.lock().unwrap().is_some())
        .await
        .expect("request is not completed");
    let (body, trailers) = result.lock().unwrap().take().unwrap();
    assert_eq!(body, b"abc");
    let trailers = trailers.expect("trailers are not received");
    assert_eq!(trailers.len(), 1);
    assert_eq!(trailers.get("x-trailer").unwrap(), "1");
}

/// Reads frames until the connection is closed or idle for 500ms,
/// returns frame types with payloads and `true` if the connection is closed.
fn h2_raw_read_frames(stream: &mut net::TcpStream) -> (Vec<(u8, Vec<u8>)>, bool) {
    stream
        .set_read_timeout(Some(std::time::Duration::from_millis(500)))
        .unwrap();
    let mut data = Vec::new();
    let mut buf = [0; 1024];
    let closed = loop {
        match stream.read(&mut buf) {
            Ok(0) => break true,
            Ok(n) => data.extend_from_slice(&buf[..n]),
            Err(e) if e.kind() == io::ErrorKind::ConnectionReset => break true,
            Err(_) => break false,
        }
    };
    let mut frames = Vec::new();
    let mut pos = 0;
    while pos + 9 <= data.len() {
        let len = (usize::from(data[pos]) << 16)
            | (usize::from(data[pos + 1]) << 8)
            | usize::from(data[pos + 2]);
        let end = (pos + 9 + len).min(data.len());
        frames.push((data[pos + 3], data[pos + 9..end].to_vec()));
        pos += 9 + len;
    }
    (frames, closed)
}

/// STATEMENT: Ten consecutive empty non-final HTTP/2 data frames trigger connection closure.
///
/// HOW:
/// - Send ten empty frames followed by non-empty final data.
/// - Verify `GOAWAY` carries `ENHANCE_YOUR_CALM` and the connection closes.
/// - Verify the trailing data is not delivered as a successfully completed request body.
#[ntex::test]
async fn test_h2_empty_data_frames_limit() {
    use ntex::util::stream_recv;

    let body = Arc::new(Mutex::new(None));
    let body2 = body.clone();
    let srv = test_server(async move |_| {
        let body = body2.clone();
        HttpService::h2(move |mut req: Request| {
            let body = body.clone();
            async move {
                let mut pl = req.take_payload();
                let mut items = Vec::new();
                while let Some(chunk) = stream_recv(&mut pl).await {
                    items.push(chunk.map_err(|_| ()));
                }
                *body.lock().unwrap() = Some(items);
                Ok::<_, io::Error>(Response::Ok().body("ok"))
            }
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let mut buf = h2_raw_post();
    for _ in 0..10 {
        h2_raw_data(&mut buf, b"", false);
    }
    // frames after the limit are not delivered
    h2_raw_data(&mut buf, b"abc", true);
    stream.write_all(&buf).unwrap();

    // the server sends GOAWAY and closes the connection
    let (frames, closed) = h2_raw_read_frames(&mut stream);
    let goaway = frames
        .iter()
        .find(|f| f.0 == 7)
        .unwrap_or_else(|| panic!("GOAWAY is not sent: {frames:?}"));
    // error code is ENHANCE_YOUR_CALM
    assert_eq!(goaway.1[4..8], [0, 0, 0, 0xb], "GOAWAY: {goaway:?}");
    assert!(closed, "connection is not closed");
    sleep(Millis(100)).await;
    assert_ne!(
        body.lock().unwrap().take(),
        Some(vec![Ok(Bytes::from("abc"))]),
        "request body is delivered"
    );
}

/// STATEMENT: HTTP/2 expectation control can permit a body or send a final rejection.
///
/// HOW:
/// - Send `Expect: 100-Continue` and verify non-final `100` headers before transmitting the body.
/// - Verify the accepted request returns `200` and echoes the body through the final data frame.
/// - Reject another request and verify a final `417` without `100`, leaving the connection open.
#[ntex::test]
async fn test_h2_expect_continue() {
    use ntex::http::{HeaderMap, h2};
    use ntex::util::{BytesMut, stream_recv};
    use ntex_h2::{MessageKind, StreamEof, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |mut req: Request| {
            assert_eq!(req.path(), "/");
            let mut pl = req.take_payload();
            let mut body = BytesMut::new();
            while let Some(chunk) = stream_recv(&mut pl).await {
                body.extend_from_slice(&chunk.unwrap());
            }
            Ok::<_, io::Error>(Response::Ok().body(body.freeze()))
        })
        .control(async |msg: h2::Control<_>| {
            Ok::<_, io::Error>(match msg {
                h2::Control::Expect(expect)
                    if expect.pseudo().path.as_deref() == Some("/reject") =>
                {
                    expect.fail(StatusCode::EXPECTATION_FAILED, HeaderMap::new())
                }
                msg => msg.ack(),
            })
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let mut hdrs = HeaderMap::default();
    hdrs.insert(header::EXPECT, HeaderValue::from_static("100-Continue"));

    let (snd, rcv) = client
        .send(Method::POST, "/".into(), hdrs.clone(), false)
        .await
        .unwrap();
    let msg = rcv.recv().await.unwrap();
    let MessageKind::Headers { pseudo, eof, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::CONTINUE));
    assert!(!eof);

    snd.send_payload(Bytes::from_static(b"body"), true)
        .await
        .unwrap();
    let msg = rcv.recv().await.unwrap();
    let MessageKind::Headers { pseudo, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::OK));
    // the sized body ends the stream with its last data frame
    let msg = rcv.recv().await.unwrap();
    assert!(
        matches!(msg.kind, MessageKind::Eof(StreamEof::Data(ref d, _)) if d == "body"),
        "{msg:?}"
    );

    // the expectation is rejected, the final response is sent without `100 Continue`
    let (_snd, rcv) = client
        .send(Method::POST, "/reject".into(), hdrs, false)
        .await
        .unwrap();
    let msg = rcv.recv().await.unwrap();
    let MessageKind::Headers { pseudo, eof, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::EXPECTATION_FAILED));
    assert!(eof);
    assert!(!client.is_closed());
}

/// STATEMENT: HTTP/2 expectation-control failure resets its stream without losing the connection.
///
/// HOW:
/// - Return a control-service error for an `Expect: 100-Continue` request.
/// - Verify an `INTERNAL_ERROR` stream reset, then successfully send a `GET` on the same connection.
#[ntex::test]
async fn test_h2_expect_control_error() {
    use ntex::http::{HeaderMap, h2};
    use ntex_h2::{MessageKind, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |_: Request| Ok::<_, io::Error>(Response::Ok().build())).control(
            async |msg: h2::Control<_>| match msg {
                h2::Control::Expect(expect)
                    if expect.pseudo().path.as_deref() == Some("/error") =>
                {
                    Err(io::Error::other("control error"))
                }
                msg => Ok(msg.ack()),
            },
        )
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    let mut hdrs = HeaderMap::default();
    hdrs.insert(header::EXPECT, HeaderValue::from_static("100-Continue"));

    let (_snd, rcv) = client
        .send(Method::POST, "/error".into(), hdrs, false)
        .await
        .unwrap();
    let msg = rcv.recv().await.unwrap();
    let MessageKind::Eof(ntex_h2::StreamEof::Error(err)) = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert!(
        matches!(
            &*err,
            ntex_h2::StreamError::Reset(ntex_h2::frame::Reason::INTERNAL_ERROR)
        ),
        "{err:?}"
    );

    // the connection is still usable
    let (_snd, rcv) = client
        .send(Method::GET, "/".into(), HeaderMap::default(), true)
        .await
        .unwrap();
    let msg = rcv.recv().await.unwrap();
    let MessageKind::Headers { pseudo, .. } = msg.kind else {
        panic!("unexpected message: {msg:?}")
    };
    assert_eq!(pseudo.status, Some(StatusCode::OK));
}

/// STATEMENT: HTTP/2 replaces informational application responses with an internal server error.
///
/// HOW:
/// - Return `100 Continue` and `101 Switching Protocols` as application responses.
/// - Verify both requests receive `500 Internal Server Error` headers.
#[ntex::test]
async fn test_h2_informational_response_is_replaced() {
    use ntex::http::HeaderMap;
    use ntex_h2::{MessageKind, client::SimpleClient};

    let srv = test_server(async |_| {
        HttpService::h2(async |req: Request| {
            let status = if req.path() == "/101" {
                StatusCode::SWITCHING_PROTOCOLS
            } else {
                StatusCode::CONTINUE
            };
            Ok::<_, io::Error>(Response::new(status))
        })
    });

    let io = ntex::connect::connect(srv.addr()).await.unwrap();
    let client = SimpleClient::new(io, false, "localhost".into());
    for path in ["/100", "/101"] {
        let (_snd, rcv) = client
            .send(Method::GET, path.into(), HeaderMap::default(), true)
            .await
            .unwrap();
        let msg = rcv.recv().await.unwrap();
        let MessageKind::Headers { pseudo, .. } = msg.kind else {
            panic!("unexpected message: {msg:?}")
        };
        assert_eq!(pseudo.status, Some(StatusCode::INTERNAL_SERVER_ERROR));
    }
}

/// STATEMENT: HTTP/1 rejects request lines exceeding its size limit while accepting shorter ones.
///
/// HOW:
/// - Send a request with a path containing 16 KiB of repeated bytes and verify status `414`.
/// - Shorten the path by twenty bytes, include a host header, and verify status `200`.
#[ntex::test]
async fn test_h1_request_line_too_long() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_: Request| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let req = format!("GET /{} HTTP/1.1\r\n\r\n", "a".repeat(16 * 1024));
    let _ = stream.write_all(req.as_bytes());
    let mut data = vec![0; 1024];
    let n = stream.read(&mut data).unwrap();
    assert!(data[..n].starts_with(b"HTTP/1.1 414"));

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let req = format!(
        "GET /{} HTTP/1.1\r\nhost: a\r\n\r\n",
        "a".repeat(16 * 1024 - 20)
    );
    let _ = stream.write_all(req.as_bytes());
    let n = stream.read(&mut data).unwrap();
    assert!(data[..n].starts_with(b"HTTP/1.1 200"));
}

/// STATEMENT: HTTP/1 distinguishes unsupported transfer codings from malformed coding order.
///
/// HOW:
/// - Send `Transfer-Encoding: gzip, chunked` and verify status `501`.
/// - Send `Transfer-Encoding: chunked, gzip` and verify status `400`.
#[ntex::test]
async fn test_h1_unsupported_transfer_coding() {
    let srv = test_server(async |_| {
        HttpService::h1(async |_: Request| Ok::<_, io::Error>(Response::Ok().build()))
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(
        b"POST / HTTP/1.1\r\nhost: a\r\ntransfer-encoding: gzip, chunked\r\n\r\n0\r\n\r\n",
    );
    let mut data = vec![0; 1024];
    let n = stream.read(&mut data).unwrap();
    assert!(data[..n].starts_with(b"HTTP/1.1 501"), "{:?}", &data[..n]);

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(
        b"POST / HTTP/1.1\r\nhost: a\r\ntransfer-encoding: chunked, gzip\r\n\r\n0\r\n\r\n",
    );
    let n = stream.read(&mut data).unwrap();
    assert!(data[..n].starts_with(b"HTTP/1.1 400"), "{:?}", &data[..n]);
}

/// STATEMENT: HTTP/1 exposes chunked request trailers without leaking them to a pipelined request.
///
/// HOW:
/// - Pipeline two chunked requests, the first with `x-trailer: 1` and the second without trailers.
/// - Drain each payload and return its body and trailers in the response.
/// - Verify the responses contain `abc|x-trailer=1` and `de|`, respectively.
#[ntex::test]
async fn test_h1_request_trailers() {
    use ntex::util::stream_recv;

    let srv = test_server(async |_| {
        HttpService::h1(async |mut req: Request| {
            let mut pl = req.take_payload();
            let mut body = Vec::new();
            while let Some(chunk) = stream_recv(&mut pl).await {
                body.extend_from_slice(&chunk.unwrap());
            }
            let trailers = pl.trailers().map(|t| {
                t.iter()
                    .map(|(n, v)| format!("{n}={}", v.to_str().unwrap()))
                    .collect::<Vec<_>>()
                    .join(",")
            });
            Ok::<_, io::Error>(Response::Ok().body(format!(
                "{}|{}",
                String::from_utf8(body).unwrap(),
                trailers.unwrap_or_default()
            )))
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    stream
        .write_all(
            b"POST / HTTP/1.1\r\nhost: a\r\ntransfer-encoding: chunked\r\n\r\n\
              3\r\nabc\r\n0\r\nx-trailer: 1\r\n\r\n\
              POST / HTTP/1.1\r\nhost: a\r\ntransfer-encoding: chunked\r\n\r\n\
              2\r\nde\r\n0\r\n\r\n",
        )
        .unwrap();
    stream
        .set_read_timeout(Some(std::time::Duration::from_secs(5)))
        .unwrap();
    let mut data = Vec::new();
    let mut buf = [0; 1024];
    // read until both pipelined responses are received
    while !data.ends_with(b"\r\n\r\nde|") {
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => data.extend_from_slice(&buf[..n]),
        }
    }
    let data = String::from_utf8(data).unwrap();
    assert!(data.contains("\r\n\r\nabc|x-trailer=1"), "{data:?}");
    assert!(data.ends_with("\r\n\r\nde|"), "{data:?}");
}

/// STATEMENT: An HTTP/1 peer reset stops polling an always-ready response body.
///
/// HOW:
/// - Serve a body that counts polls and yields data until a large safety limit.
/// - Read part of the response, then close with unread data to reset the connection.
/// - Verify the poll count stabilizes below the safety limit and remains unchanged after a delay.
#[ntex::test]
async fn test_h1_body_not_polled_after_peer_reset() {
    use std::task::{Context, Poll};

    static DATA: [u8; 16 * 1024] = [b'a'; 16 * 1024];
    const MAX_POLLS: usize = 5_000_000;

    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, std::rc::Rc<dyn std::error::Error>>>> {
            if self.0.fetch_add(1, Ordering::Relaxed) >= MAX_POLLS {
                Poll::Ready(None)
            } else {
                Poll::Ready(Some(Ok(Bytes::from_static(&DATA))))
            }
        }
    }

    let polls = Arc::new(AtomicUsize::new(0));
    let polls2 = polls.clone();
    let srv = test_server(async move |_| {
        let polls = polls2.clone();
        HttpService::h1(move |_: Request| {
            let body = body::Body::from_message(Stream(polls.clone()));
            async move { Ok::<_, io::Error>(Response::Ok().body(body)) }
        })
    });

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
    let mut data = vec![0; 64 * 1024];
    let mut total = 0;
    while total < 16 * 1024 * 1024 {
        total += stream.read(&mut data).unwrap();
    }
    // closing with unread data resets the connection
    drop(stream);

    // the poll count stabilizes once the body is not polled anymore
    let mut polls1 = polls.load(Ordering::Relaxed);
    for _ in 0..80 {
        sleep(Millis(25)).await;
        let current = polls.load(Ordering::Relaxed);
        if current == polls1 {
            break;
        }
        polls1 = current;
    }
    sleep(Millis(300)).await;
    let polls2 = polls.load(Ordering::Relaxed);
    assert_eq!(polls1, polls2);
    assert!(polls2 < MAX_POLLS, "{polls2}");
}