ntex-io 4.2.1

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

use ntex_bytes::{BytePageSize, BytesMut};
use ntex_codec::{Decoder, Encoder};
use ntex_service::cfg::{Cfg, SharedCfg};
use ntex_util::{future::Either, task::LocalWaker, time::Sleep};

use crate::buf::Stack;
use crate::cfg::IoConfig;
use crate::ctx::IoContext;
use crate::filter::{Base, Filter, Layer};
use crate::filterptr::FilterPtr;
use crate::flags::Flags;
use crate::ops::{Id, IoManager, TimerHandle};
use crate::seal::{IoBoxed, Sealed};
use crate::utils::{Extensions, WriteDeadline, write_timed_out};
use crate::waiters::{TAG_WRITE, WriteGuard};
use crate::{Decoded, FilterLayer, Handle, IoStatusUpdate, IoStream, RecvError};

/// Buffered, filterable interface to an underlying I/O stream.
///
/// `Io` is the main handle for a connection. The runtime fills its read buffer
/// and drains its write buffer, while protocol code uses this handle to decode
/// requests and encode responses.
///
/// Reads and writes go through buffers rather than directly to the socket.
/// When the read buffer grows too large, ntex pauses the transport.
/// [`read_more`](Self::read_more) can resume it, so calling that method asks
/// for more input; it does more than check whether data is already available.
///
/// If the peer cleanly closes its read side, any buffered input remains
/// available and responses can still be written. [`shutdown`](Self::shutdown)
/// closes the connection gracefully and waits for the runtime to finish.
/// [`terminate`](IoRef::terminate) closes it immediately.
///
/// The `F` parameter keeps track of the installed filters. Adding or mapping a
/// filter changes the type. Use [`seal`](Self::seal) or [`boxed`](Self::boxed)
/// when the concrete filter type does not need to be exposed.
///
/// Use [`get_ref`](Self::get_ref) to share access to the connection. The
/// returned [`IoRef`] points to the same buffers and state; it does not create
/// another connection. Dropping `Io` terminates the connection even if an
/// `IoRef` is still alive.
pub struct Io<F = Base>(UnsafeCell<IoRef>, marker::PhantomData<F>);

/// A cheap, cloneable handle to an [`Io`] connection.
///
/// All clones point to the same connection. Changes to its buffers,
/// configuration, timers, errors, or shutdown state are visible through every
/// clone. Cloning `IoRef` never clones the socket.
///
/// Use it to inspect the connection, access its buffers, queue output, or start
/// graceful or immediate shutdown. These methods are also available directly
/// on `Io`, which dereferences to `IoRef`.
///
/// Keeping an `IoRef` alive does not keep the connection open after its `Io`
/// owner is dropped. Like `Io`, it stays on the local runtime thread and is
/// neither `Send` nor `Sync`.
#[derive(Clone)]
pub struct IoRef(pub(super) Rc<IoState>);

pub(crate) struct IoState {
    filter: FilterPtr,
    pub(super) id: Cell<Id>,
    pub(super) cfg: Cfg<IoConfig>,
    pub(super) flags: Flags,
    pub(super) error: Cell<Option<io::Error>>,
    pub(super) read_task: LocalWaker,
    pub(super) write_task: LocalWaker,
    dispatch_task: LocalWaker,
    pub(super) buffer: Stack,
    pub(super) handle: Cell<Option<Box<dyn Handle>>>,
    pub(super) timeout: Cell<TimerHandle>,
    pub(super) shutdown_timeout: Cell<Option<Sleep>>,
    /// Bytes handed to the transport that have not reached the peer yet.
    ///
    /// Completion based transports take ownership of write pages and keep them
    /// until the operation completes, so those bytes are no longer in
    /// `buffer`. They are still outstanding output and must be accounted for.
    pub(super) wr_inflight: Cell<u32>,
    pub(super) extensions: Extensions,
}

impl IoState {
    pub(super) fn id(&self) -> Id {
        self.id.get()
    }

    pub(super) fn tag(&self) -> &'static str {
        self.cfg.tag()
    }

    /// Checks whether the `Io` that owned the filter chain has been dropped.
    pub(super) fn is_io_dropped(&self) -> bool {
        !self.filter.is_set()
    }

    pub(super) fn filter(&self) -> &dyn Filter {
        self.filter.get()
    }

    pub(super) fn notify_timeout(&self) {
        if self.flags.check_dispatcher_timeout_unset() {
            self.wake_dispatch_task();
            log::trace!("{}: Timer, notify dispatcher", self.cfg.tag());
        }
    }

    /// Wakes the disconnect waiters and all public waker slots.
    pub(super) fn notify_disconnect(&self) {
        self.extensions.wake_all();
    }

    /// Get the current I/O error.
    pub(super) fn error(&self) -> Option<io::Error> {
        if let Some(err) = self.error.take() {
            let cloned = if let Some(code) = err.raw_os_error() {
                io::Error::from_raw_os_error(code)
            } else {
                io::Error::new(err.kind(), format!("{err}"))
            };
            self.error.set(Some(cloned));
            Some(err)
        } else {
            None
        }
    }

    /// Returns the current I/O error, or creates a `NotConnected` error.
    pub(super) fn error_or_disconnected(&self) -> io::Error {
        self.error()
            .unwrap_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "Disconnected"))
    }

    pub(super) fn filters_stopped(&self) {
        // the shutdown deadline carries over into the transport shutdown
        // phase, so that a single `shutdown_timeout` bounds both phases
        self.wake_read_task();
        self.wake_write_task();
        self.wake_dispatch_task();
        self.wake_write_waiters();
        self.flags.enter_transport_shutdown();
    }

    fn set_error(&self, err: Option<io::Error>) {
        if let Some(err) = err {
            if let Some(current) = self.error.take() {
                self.error.set(Some(current));
            } else {
                self.error.set(Some(err));
            }
        }
    }

    pub(super) fn set_shutdown_error(&self, err: io::Error) {
        self.set_error(Some(err));
    }

    /// Force-closes the connection, aborting it instead of closing gracefully.
    ///
    /// This is the only path that makes the transport report
    /// [`Readiness::Terminate`](crate::Readiness::Terminate). Terminations that
    /// come from a failure rather than from an explicit request go through
    /// [`terminate_connection`](Self::terminate_connection) and let the
    /// transport close the connection gracefully.
    pub(super) fn force_close_connection(&self) {
        self.begin_terminate(None, true);
    }

    pub(super) fn terminate_connection(&self, err: Option<io::Error>) {
        self.begin_terminate(err, false);
    }

    /// Moves the connection onto the termination path and runs the teardown
    /// work, which only the first call to get here performs.
    fn begin_terminate(&self, err: Option<io::Error>, force: bool) {
        self.set_error(err);
        if self.flags.begin_terminate(force) {
            log::trace!("{}: Terminate io", self.cfg.tag());
            // buffers held by the transport are gone with it
            self.wr_inflight.set(0);
            self.wake_read_task();
            self.wake_write_task();
            self.wake_dispatch_task();
            self.wake_write_waiters();
            self.handle.take();
        }
    }

    pub(super) fn stop_connection(&self, err: Option<io::Error>) {
        if !self.flags.is_closed() {
            log::trace!("{}: Stop io with error {:?}", self.cfg.tag(), err);
            self.set_error(err);
            self.flags.set_stopped();
            // buffers held by the transport are gone with it
            self.wr_inflight.set(0);
            self.wake_read_task();
            self.wake_write_task();
            self.wake_dispatch_task();
            self.wake_write_waiters();
            self.notify_disconnect();
            self.handle.take();
        }
    }

    /// Gracefully shuts down the read and write I/O tasks.
    pub(super) fn start_shutdown(&self) {
        if self.flags.is_active() {
            log::trace!("{}: Initiate io shutdown {:?}", self.cfg.tag(), self.flags);
            self.flags.enter_filters_stopping();
            self.wake_read_task();
            self.wake_write_task();
        }
    }

    pub(super) fn get_read_buf(&self) -> BytesMut {
        self.cfg.read_buf().get()
    }

    pub(super) fn is_rd_backpressure_needed(&self, size: usize) -> bool {
        size >= self.cfg.read_buf().high
    }

    pub(super) fn is_wr_backpressure_needed(&self, size: usize) -> bool {
        size >= self.cfg.write_buf().high
    }

    pub(super) fn should_disable_rd_backpressure(&self, size: usize) -> bool {
        size <= self.cfg.read_buf().half
    }

    pub(super) fn should_disable_wr_backpressure(&self, size: usize) -> bool {
        size <= self.cfg.write_buf().half
    }

    /// Total output that has not reached the peer yet.
    ///
    /// This is the buffered output plus whatever the transport has taken
    /// ownership of but not written out. Flush completion, write
    /// back-pressure and the shutdown drain are all decided on this value,
    /// because until it reaches zero the peer has not seen everything.
    pub(super) fn write_outstanding(&self) -> usize {
        self.buffer.write_buf_size() + self.wr_inflight.get() as usize
    }

    /// Output that has reached the transport-facing buffer but not the peer.
    ///
    /// Output a filter holds back, for example application data during a TLS
    /// renegotiation, is excluded. It can not drain until more input is read,
    /// so it must not keep reads paused.
    pub(super) fn transport_outstanding(&self) -> usize {
        self.buffer.write_dst_size() + self.wr_inflight.get() as usize
    }

    /// Records bytes taken by, or returned from, the transport.
    pub(super) fn track_wr_inflight(&self, before: usize, after: usize) {
        let inflight = self.wr_inflight.get();
        if after < before {
            self.wr_inflight
                .set(inflight.saturating_add(as_u32(before - after)));
        } else {
            // the transport returned unwritten output to the buffer
            self.wr_inflight
                .set(inflight.saturating_sub(as_u32(after - before)));
        }
    }

    /// Records output that reached the peer.
    pub(super) fn wr_inflight_written(&self, written: usize) {
        self.wr_inflight
            .set(self.wr_inflight.get().saturating_sub(as_u32(written)));
    }

    pub(super) fn wake_read_task(&self) {
        self.read_task.wake();
    }

    pub(super) fn wake_write_task(&self) {
        #[cfg(feature = "trace")]
        log::trace!("{}: Wake write task, flags:{:?}", self.tag(), self.flags);
        self.write_task.wake();
    }

    pub(super) fn wake_dispatch_task(&self) {
        self.dispatch_task.wake();
    }

    pub(super) fn wake_write_waiters(&self) {
        self.extensions.wake(TAG_WRITE);
    }

    /// Returns `Some` once more output can be written or the connection is gone.
    pub(super) fn check_write_ready(&self) -> Option<io::Result<()>> {
        if self.flags.is_peer_gone() {
            Some(Err(self.error_or_disconnected()))
        } else if !self.flags.is_wr_backpressure()
            || self.should_disable_wr_backpressure(self.write_outstanding())
        {
            Some(Ok(()))
        } else {
            None
        }
    }

    pub(super) async fn write_ready(&self) -> io::Result<()> {
        if let Some(res) = self.check_write_ready() {
            return res;
        }

        let waiter = WriteGuard::new(&self.extensions);
        let mut deadline = WriteDeadline::new(self.cfg.write_timeout());
        poll_fn(|cx| {
            if let Some(res) = self.check_write_ready() {
                Poll::Ready(res)
            } else if deadline.poll_expired(cx) {
                Poll::Ready(Err(write_timed_out()))
            } else {
                // a woken waiter registers the waker again
                waiter.register(cx);
                Poll::Pending
            }
        })
        .await
    }

    /// Waits for `f`, bounded by the configured write timeout.
    pub(super) async fn with_write_timeout<T, F>(&self, mut f: F) -> io::Result<T>
    where
        F: FnMut(&mut Context<'_>) -> Poll<io::Result<T>>,
    {
        let mut deadline = WriteDeadline::new(self.cfg.write_timeout());
        poll_fn(|cx| match f(cx) {
            Poll::Ready(res) => Poll::Ready(res),
            Poll::Pending if deadline.poll_expired(cx) => Poll::Ready(Err(write_timed_out())),
            Poll::Pending => Poll::Pending,
        })
        .await
    }
}

impl Eq for IoState {}

impl PartialEq for IoState {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ptr::eq(self, other)
    }
}

impl hash::Hash for IoState {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (ptr::from_ref(self) as usize).hash(state);
    }
}

impl fmt::Debug for IoState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let err = self.error.take();
        let res = f
            .debug_struct("IoState")
            .field("id", &self.id)
            .field("flags", &self.flags)
            .field("filter", &self.filter.is_set())
            .field("timeout", &self.timeout)
            .field("error", &err)
            .field("buffer", &self.buffer)
            .field("cfg", &self.cfg)
            .finish();
        self.error.set(err);
        res
    }
}

impl Io {
    /// Creates a new `Io` instance.
    pub fn new<I: IoStream, T: Into<SharedCfg>>(io: I, cfg: T) -> Self {
        let cfg = cfg.into().get::<IoConfig>();
        let size = cfg.write_page_size();
        let flags = Flags::new(cfg.write_buf_threshold() > 0);

        let inner = Rc::new(IoState {
            cfg,
            flags,
            id: Cell::new(Id::default()),
            filter: FilterPtr::null(),
            error: Cell::new(None),
            dispatch_task: LocalWaker::new(),
            read_task: LocalWaker::new(),
            write_task: LocalWaker::new(),
            buffer: Stack::new(size),
            handle: Cell::new(None),
            timeout: Cell::new(TimerHandle::default()),
            shutdown_timeout: Cell::new(None),
            wr_inflight: Cell::new(0),
            extensions: Extensions::default(),
        });
        inner.filter.set(Base::new(IoRef(inner.clone())));

        let ioref = IoRef(inner);
        ioref.0.id.set(IoManager::register(&ioref));

        // start io tasks
        let hnd = io.start(IoContext::new(ioref.clone()));
        ioref.0.handle.set(Some(hnd));

        Io(UnsafeCell::new(ioref), marker::PhantomData)
    }
}

impl<I: IoStream> From<I> for Io {
    #[inline]
    fn from(io: I) -> Io {
        Io::new(io, SharedCfg::default())
    }
}

impl IoRef {
    fn create_empty() -> IoRef {
        IoRef(Rc::new(IoState {
            id: Cell::new(Id::default()),
            cfg: SharedCfg::default().get::<IoConfig>(),
            filter: FilterPtr::null(),
            flags: Flags::new_stopped(),
            error: Cell::new(None),
            dispatch_task: LocalWaker::new(),
            read_task: LocalWaker::new(),
            write_task: LocalWaker::new(),
            buffer: Stack::new(BytePageSize::Size16),
            handle: Cell::new(None),
            timeout: Cell::new(TimerHandle::default()),
            shutdown_timeout: Cell::new(None),
            wr_inflight: Cell::new(0),
            extensions: Extensions::default(),
        }))
    }
}

impl<F> Io<F> {
    #[inline]
    /// Returns a cloneable reference to this connection's shared state.
    pub fn get_ref(&self) -> IoRef {
        self.io_ref().clone()
    }

    #[inline]
    #[must_use]
    /// Transfers the live connection state into a new `Io` object.
    ///
    /// This does not clone the connection. `self` is replaced with a stopped
    /// placeholder and should no longer be used for I/O.
    ///
    /// # Safety
    ///
    /// No reference derived from `self` may be alive across this call, the
    /// filter returned by [`Io::filter`], the `IoRef` it dereferences to and
    /// the config returned by [`IoRef::cfg`] all borrow the transferred state,
    /// which is dropped together with the returned `Io`.
    pub unsafe fn take(&self) -> Self {
        Self(UnsafeCell::new(self.take_io_ref()), marker::PhantomData)
    }

    fn take_io_ref(&self) -> IoRef {
        unsafe { mem::replace(&mut *self.0.get(), IoRef::create_empty()) }
    }

    /// Panics if the filter chain is in use, it cannot be changed then.
    #[track_caller]
    fn check_not_borrowed(&self) {
        if self.st().buffer.is_borrowed() {
            let tag = self.tag();
            // the state is leaked, dropping `self` while unwinding would
            // drop the filter that is in use
            mem::forget(self.take_io_ref());
            panic!("{tag}: filter chain is changed while it is in use");
        }
    }

    fn st(&self) -> &IoState {
        unsafe { &(*self.0.get()).0 }
    }

    fn io_ref(&self) -> &IoRef {
        unsafe { &*self.0.get() }
    }

    #[inline]
    /// Replaces this connection's shared I/O configuration.
    ///
    /// The write-buffer page size and eager-write enablement are updated
    /// immediately. Existing allocated buffers and an already registered timer
    /// are not recreated.
    ///
    /// # Safety
    ///
    /// No reference obtained from [`IoRef::cfg`] for this connection may be
    /// live when this method is called or used afterward. Replacing the
    /// configuration may release the allocation backing those references.
    pub unsafe fn set_config<T: Into<SharedCfg>>(&self, cfg: T) {
        let cfg = cfg.into().get::<IoConfig>();
        let page_size = cfg.write_page_size();
        if self.cfg().write_page_size() != page_size {
            self.st().buffer.set_page_size(page_size);
        }
        self.st()
            .flags
            .set_direct_wr_enabled(cfg.write_buf_threshold() > 0);
        unsafe {
            self.st().cfg.replace(cfg);
        }
    }
}

impl<F: FilterLayer, T: Filter> Io<Layer<F, T>> {
    #[inline]
    /// Returns a reference to a filter.
    pub fn filter(&self) -> &F {
        &self.st().filter.filter::<Layer<F, T>>().0
    }
}

impl<F: Filter> Io<F> {
    #[inline]
    /// Converts the current I/O stream into a sealed version.
    ///
    /// # Panics
    ///
    /// Panics if called while the connection's filters or buffers are in use,
    /// for example from a closure, codec or filter invoked by this connection.
    pub fn seal(self) -> Io<Sealed> {
        self.check_not_borrowed();
        let state = self.take_io_ref();
        state.0.filter.seal::<F>();

        Io(UnsafeCell::new(state), marker::PhantomData)
    }

    #[inline]
    /// Converts the current I/O stream into a boxed version.
    pub fn boxed(self) -> IoBoxed {
        self.seal().into()
    }

    #[inline]
    /// Adds a new processing layer to the current filter chain.
    ///
    /// # Panics
    ///
    /// Panics if called while the connection's filters or buffers are in use,
    /// for example from a closure, codec or filter invoked by this connection.
    pub fn add_filter<U>(self, nf: U) -> Io<Layer<U, F>>
    where
        U: FilterLayer,
    {
        self.check_not_borrowed();
        self.with_callbacks(|cb| cb.before_processing(&self));

        // Write buffer processing may be delayed,
        // call the filter chain to process pending writes
        if let Err(e) = self.st().buffer.process_write_buf_no_cb(&self) {
            self.st().terminate_connection(Some(e));
        }

        let state = self.take_io_ref();

        // Add the buffers layer
        state.0.buffer.add_layer(state.0.cfg.write_page_size());

        // Replace current filter
        state.0.filter.add_filter::<F, U>(nf);

        let io = Io(UnsafeCell::new(state), marker::PhantomData);

        // push read data into new filter
        if let Err(e) = io.st().buffer.process_read_buf_no_cb(&io) {
            io.st().terminate_connection(Some(e));
        }
        io.with_callbacks(|cb| cb.after_processing(&io));

        io
    }

    #[allow(clippy::items_after_statements)]
    /// Wraps the current layer with a wrapper.
    ///
    /// # Panics
    ///
    /// Panics if called while the connection's filters or buffers are in use,
    /// for example from a closure, codec or filter invoked by this connection.
    pub fn map_filter<U, R>(self, f: U) -> Io<R>
    where
        U: FnOnce(F) -> R,
        R: Filter,
    {
        self.check_not_borrowed();
        self.with_callbacks(|cb| cb.before_processing(&self));

        // Write buffer processing may be delayed,
        // call the filter chain to process pending writes
        if let Err(e) = self.st().buffer.process_write_buf(&self) {
            self.st().terminate_connection(Some(e));
        }

        // `f` owns the filter, if it unwinds the filter chain is gone and the
        // connection must be torn down here, `Drop for Io` skips it without
        // a filter
        struct Guard<'a>(&'a IoRef);

        impl Drop for Guard<'_> {
            fn drop(&mut self) {
                let st = &self.0.0;
                st.force_close_connection();
                st.buffer.release(self.0.cfg());
                drop(st.extensions.take_callbacks());
            }
        }

        let guard = Guard(self.io_ref());
        self.st().filter.map_filter::<F, U, R>(f);
        mem::forget(guard);

        let state = self.take_io_ref();
        let io = Io(UnsafeCell::new(state), marker::PhantomData);
        io.with_callbacks(|cb| cb.after_processing(&io));
        io
    }
}

impl<F> Io<F> {
    /// Reads and decodes the next item from the incoming stream.
    ///
    /// Returns `Ok(None)` when the connection closed before another item could
    /// be decoded and nothing was left undecoded, whether the peer
    /// disconnected or the shutdown was started locally.
    ///
    /// If the peer closed its write half while the codec still held a partial
    /// item, the stream was truncated and this returns
    /// [`io::ErrorKind::UnexpectedEof`] in [`Either::Right`] rather than
    /// `Ok(None)`, so that a cut-off frame is not mistaken for a clean end of
    /// stream. Undecodable bytes left after a locally started shutdown are not
    /// treated as truncation.
    ///
    /// Codec errors are returned in [`Either::Left`]; transport errors and
    /// dispatcher timeouts are returned in [`Either::Right`].
    ///
    /// If write backpressure prevents further reads, this method first waits
    /// for the write buffer to fall below its configured threshold. A
    /// dispatcher timeout that fires during this wait is returned as well.
    pub async fn recv<U>(&self, codec: &U) -> Result<Option<U::Item>, Either<U::Error, io::Error>>
    where
        U: Decoder,
    {
        loop {
            return match poll_fn(|cx| self.poll_recv(codec, cx)).await {
                Ok(item) => Ok(Some(item)),
                Err(RecvError::Timeout) => Err(Either::Right(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "Timeout",
                ))),
                Err(RecvError::WriteBackpressure) => {
                    let timed_out = poll_fn(|cx| {
                        if self.st().flags.check_dispatcher_timeout() {
                            Poll::Ready(Ok(true))
                        } else {
                            self.poll_flush(cx, false).map_ok(|()| false)
                        }
                    })
                    .await
                    .map_err(Either::Right)?;

                    if timed_out {
                        Err(Either::Right(io::Error::new(
                            io::ErrorKind::TimedOut,
                            "Timeout",
                        )))
                    } else {
                        continue;
                    }
                }
                Err(RecvError::Decoder(err)) => Err(Either::Left(err)),
                Err(RecvError::PeerGone(Some(err))) => Err(Either::Right(err)),
                Err(RecvError::PeerGone(None)) => {
                    let st = self.st();
                    if st.flags.is_read_eof() && st.buffer.read_dst_size() != 0 {
                        Err(Either::Right(io::Error::new(
                            io::ErrorKind::UnexpectedEof,
                            "bytes remaining on stream",
                        )))
                    } else {
                        Ok(None)
                    }
                }
            };
        }
    }

    /// Reads exactly enough bytes from this I/O stream to fill `dst`.
    ///
    /// If there is not enough data available, waits for incoming data.
    /// If clean EOF or an error-free shutdown occurs before `dst` is filled,
    /// this returns [`io::ErrorKind::UnexpectedEof`]. Transport errors are
    /// passed through unchanged.
    ///
    /// Each wait goes through [`read_more`](Self::read_more), so this releases
    /// read backpressure unconditionally rather than waiting for the read
    /// buffer to drain to half the high watermark.
    pub async fn read_exact(&self, dst: &mut [u8]) -> io::Result<()> {
        loop {
            let completed = self.with_read_dst(|buf| {
                if buf.len() >= dst.len() {
                    let _ = io::Read::read(buf, dst).expect("Cannot fail");
                    true
                } else {
                    false
                }
            });
            if completed {
                return Ok(());
            }
            // No more bytes will arrive after clean EOF or shutdown.
            if self.read_more().await?.is_none() {
                return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Disconnected"));
            }
        }
    }

    #[inline]
    /// Waits until application-facing data is available and allows the
    /// transport to read more data.
    ///
    /// If reads are paused or under backpressure, calling this method resumes
    /// the read task. This is not a passive check of the current buffer, and
    /// read backpressure is released however much data is still buffered.
    ///
    /// Returns `Ok(Some(()))` when input that has not been reported yet is
    /// available, `Ok(None)` when no further input will be reported, and `Err`
    /// if the transport failed. See [`poll_read_more`](Self::poll_read_more)
    /// for what `None` means after a clean EOF.
    pub async fn read_more(&self) -> io::Result<Option<()>> {
        poll_fn(|cx| self.poll_read_more(cx)).await
    }

    #[inline]
    /// Waits for the next read from the transport.
    ///
    /// Use this when a filter needs more source bytes. Unlike
    /// [`read_more`](Self::read_more), data already waiting in the application
    /// buffer does not complete this wait. If the read task is paused, this
    /// method wakes it.
    ///
    /// Returns `Some(())` when the transport provides more input. If clean EOF
    /// leaves final data in the application buffer, it returns `Some(())` once
    /// and `None` afterward. A transport error is returned unchanged.
    pub async fn read_notify(&self) -> io::Result<Option<()>> {
        poll_fn(|cx| self.poll_read_notify(cx)).await
    }

    #[inline]
    /// Encodes an item and sends it to the peer, fully flushing the write buffer.
    ///
    /// The flush is bounded by the
    /// [write timeout](crate::IoConfig::set_write_timeout), if one is set;
    /// when it expires this returns [`io::ErrorKind::TimedOut`] in
    /// [`Either::Right`].
    pub async fn send<U>(&self, item: U::Item, codec: &U) -> Result<(), Either<U::Error, io::Error>>
    where
        U: Encoder,
    {
        self.encode(item, codec).map_err(Either::Left)?;

        self.st()
            .with_write_timeout(|cx| self.poll_flush(cx, true))
            .await
            .map_err(Either::Right)?;

        Ok(())
    }

    #[inline]
    /// Wakes the write task and requests a flush of queued output.
    ///
    /// This is the asynchronous counterpart to `poll_flush`. A full flush
    /// completes once all output has reached the peer, including output a
    /// transport has taken ownership of but not yet written.
    ///
    /// The wait is bounded by the
    /// [write timeout](crate::IoConfig::set_write_timeout), if one is set;
    /// when it expires this returns [`io::ErrorKind::TimedOut`].
    pub async fn flush(&self, full: bool) -> io::Result<()> {
        self.st()
            .with_write_timeout(|cx| self.poll_flush(cx, full))
            .await
    }

    #[inline]
    /// Gracefully shuts down the I/O stream.
    ///
    /// Shutdown runs in two phases, bounded together by a single
    /// [`IoConfig::set_shutdown_timeout`]. First the filters shut down while
    /// both directions stay open, so a filter can emit its closing data and
    /// read the peer's. Then the transport drains the remaining output, pauses
    /// the read side, and closes the connection.
    ///
    /// This completes once the transport backend has finished its shutdown
    /// operation, not merely once the output has been drained.
    ///
    /// [`IoConfig::set_shutdown_timeout`]: crate::IoConfig::set_shutdown_timeout
    pub async fn shutdown(&self) -> io::Result<()> {
        poll_fn(|cx| self.poll_shutdown(cx)).await
    }

    #[inline]
    /// Polls for application-facing data and allows the transport to read more.
    ///
    /// If reads are paused or under backpressure, this resumes the read task.
    /// It therefore changes the read state and should not be used as a passive
    /// buffer check.
    ///
    /// The release is unconditional: unlike consumption through
    /// [`IoRef::decode`], [`IoRef::with_buf`], [`IoRef::with_read_src`] or
    /// [`IoRef::with_read_dst`], which waits for the read buffer to fall to at
    /// most half the high watermark, this releases read backpressure however
    /// much data is still buffered. Asking for more input
    /// is taken as the dispatcher declaring itself able to accept it. This
    /// also resumes reads paused because output produced by reading, for
    /// example replies to peer pings, has not drained yet.
    ///
    /// # Returns
    ///
    /// - `Poll::Pending` while waiting for more data.
    /// - `Poll::Ready(Ok(Some(())))` when input that has not been reported yet
    ///   is available.
    /// - `Poll::Ready(Ok(None))` when no further input will be reported: after
    ///   a clean EOF once the available input has been reported, or when the
    ///   stream closes without an error. Clean EOF leaves the write half open.
    ///
    ///   This reports arrivals, not buffer contents. Input that has already
    ///   been reported stays in the read buffer and remains decodable through
    ///   [`IoRef::decode`] and [`IoRef::with_read_dst`], so `None` does not
    ///   imply that the read buffer is empty.
    /// - `Poll::Ready(Err(e))` if the transport failed.
    pub fn poll_read_more(&self, cx: &mut Context<'_>) -> Poll<io::Result<Option<()>>> {
        let st = self.st();

        if st.flags.is_peer_gone() {
            if let Some(err) = st.error() {
                Poll::Ready(Err(err))
            } else {
                Poll::Ready(Ok(None))
            }
        } else {
            let ready = st.flags.is_read_ready();

            if st.flags.is_read_eof() && !ready {
                return Poll::Ready(Ok(None));
            }

            // If the dispatcher requests more data but no read occurs,
            // restart the read task.
            if st.flags.is_read_paused_or_backpressure() || st.flags.is_read_wr_backpressure() {
                st.flags.unset_read_ready_and_backpressure();
                st.flags.unset_read_paused();
                st.flags.unset_read_wr_backpressure();
                st.wake_read_task();
                if ready {
                    Poll::Ready(Ok(Some(())))
                } else {
                    st.dispatch_task.register(cx.waker());
                    Poll::Pending
                }
            } else if ready {
                Poll::Ready(Ok(Some(())))
            } else {
                st.dispatch_task.register(cx.waker());
                Poll::Pending
            }
        }
    }

    #[inline]
    /// Polls for the next read from the transport.
    ///
    /// This is the polling version of [`read_notify`](Self::read_notify).
    /// Existing application data does not make it ready. When another transport
    /// read is needed, this wakes the read task and registers the current waker.
    ///
    /// `Some(())` means that more input arrived. Clean EOF may produce one last
    /// `Some(())` when filters leave final application data; later polls return
    /// `None`. Transport errors are returned unchanged.
    ///
    /// Paused or back-pressured reads are resumed through
    /// [`poll_read_more`](Self::poll_read_more), which releases read
    /// backpressure unconditionally.
    pub fn poll_read_notify(&self, cx: &mut Context<'_>) -> Poll<io::Result<Option<()>>> {
        let st = self.st();
        if st.flags.is_stopping_or_terminating() {
            if let Some(err) = st.error() {
                Poll::Ready(Err(err))
            } else {
                Poll::Ready(Ok(None))
            }
        } else if st.flags.is_read_eof() {
            let notified = st.flags.take_read_notified();
            if notified && st.flags.is_read_ready() {
                Poll::Ready(Ok(Some(())))
            } else {
                Poll::Ready(Ok(None))
            }
        } else if st.flags.take_read_notified() {
            Poll::Ready(Ok(Some(())))
        } else {
            st.flags.set_read_notify();
            // Resumes the read task if reads are paused. The result is
            // discarded on purpose: buffered application data does not
            // complete this wait, and the eof and closed cases are handled
            // by the branches above.
            let _ = self.poll_read_more(cx);
            st.dispatch_task.register(cx.waker());
            Poll::Pending
        }
    }

    #[inline]
    /// Decodes the next item from the incoming byte stream.
    ///
    /// Returns `Poll::Pending` when the codec needs more input, after going
    /// through [`poll_read_more`](Self::poll_read_more), which wakes the read
    /// task and releases read backpressure unconditionally.
    ///
    /// An error return does not register the waker.
    pub fn poll_recv<U>(
        &self,
        codec: &U,
        cx: &mut Context<'_>,
    ) -> Poll<Result<U::Item, RecvError<U>>>
    where
        U: Decoder,
    {
        let decoded = self.poll_recv_decode(codec, cx)?;

        if let Some(item) = decoded.item {
            Poll::Ready(Ok(item))
        } else {
            Poll::Pending
        }
    }

    #[inline]
    /// Attempts to decode an item and reports buffer progress.
    ///
    /// `Decoded::consumed` is the number of bytes consumed by this decode
    /// attempt and `Decoded::remains` is the number left in the
    /// application-facing read buffer. If the codec needs more input, this
    /// returns `Ok` with `item` set to `None` after arranging for `cx` to be
    /// woken when progress is possible.
    ///
    /// An error return does not register the waker. While the connection is
    /// open, an expired dispatcher timer and then active write backpressure are
    /// reported before the read buffer is decoded, so an error never follows a
    /// decode attempt and `Decoded` is never lost. The caller decides whether
    /// input received together with a timeout is decoded first, see
    /// [`IoRef::decode_item`](crate::IoRef::decode_item). Once the connection
    /// is closing neither is reported, the buffered input is decoded and
    /// `RecvError::PeerGone` is returned when no item is left.
    ///
    /// When the codec needs more input this goes through
    /// [`poll_read_more`](Self::poll_read_more), which releases read
    /// backpressure unconditionally.
    pub fn poll_recv_decode<U>(
        &self,
        codec: &U,
        cx: &mut Context<'_>,
    ) -> Result<Decoded<U::Item>, RecvError<U>>
    where
        U: Decoder,
    {
        let st = self.st();
        st.flags.unset_read_ready();

        let closed = st.flags.is_stopping() || st.flags.is_terminating();
        if !closed {
            if st.flags.check_dispatcher_timeout() {
                return Err(RecvError::Timeout);
            } else if st.flags.is_wr_backpressure() {
                return Err(RecvError::WriteBackpressure);
            }
        }

        let decoded = self
            .decode_item(codec)
            .map_err(|err| RecvError::Decoder(err))?;

        if decoded.item.is_some() {
            Ok(decoded)
        } else if st.flags.is_stopping() || st.flags.is_terminating() {
            Err(RecvError::PeerGone(st.error()))
        } else {
            match self.poll_read_more(cx) {
                Poll::Pending | Poll::Ready(Ok(Some(()))) => {
                    #[cfg(feature = "trace")]
                    if decoded.remains != 0 {
                        log::trace!("{}: Not enough data to decode next frame", self.tag());
                    }
                    Ok(decoded)
                }
                Poll::Ready(Err(e)) => Err(RecvError::PeerGone(Some(e))),
                Poll::Ready(Ok(None)) => Err(RecvError::PeerGone(None)),
            }
        }
    }

    #[inline]
    /// Wakes the write task and instructs it to flush data.
    ///
    /// A full flush waits until all output has reached the peer.
    ///
    /// Otherwise this returns immediately while the outstanding size is below
    /// the configured high watermark. Reaching that watermark enables write
    /// backpressure, and the call then waits until the outstanding size falls
    /// to half of it.
    ///
    /// Output that a completion based transport has taken ownership of counts
    /// as outstanding until it reaches the peer, so a full flush does not
    /// complete while a write is still in flight.
    pub fn poll_flush(&self, cx: &mut Context<'_>, full: bool) -> Poll<io::Result<()>> {
        let st = self.st();

        // flush filter state
        st.buffer.process_write_buf_force(self)?;
        self.consolidate_write_state(false)?;

        let len = st.write_outstanding();
        if len > 0 {
            if st.flags.is_peer_gone() {
                return Poll::Ready(Err(st.error_or_disconnected()));
            } else if full {
                st.flags.set_wants_write_flush();
                st.dispatch_task.register(cx.waker());
                return Poll::Pending;
            } else if st.flags.is_wr_backpressure() {
                if !st.should_disable_wr_backpressure(len) {
                    st.dispatch_task.register(cx.waker());
                    return Poll::Pending;
                }
            } else if st.is_wr_backpressure_needed(len) {
                st.flags.set_wr_backpressure();
                st.dispatch_task.register(cx.waker());
                return Poll::Pending;
            }
        }
        if st.flags.is_peer_gone() && !st.flags.is_write_flush() {
            Poll::Ready(Err(st.error_or_disconnected()))
        } else {
            st.flags.unset_wr_backpressure_and_flush();
            Poll::Ready(Ok(()))
        }
    }

    #[inline]
    /// Polls graceful shutdown through transport completion.
    ///
    /// `Poll::Ready` is returned only after the transport backend marks the
    /// connection stopped, not merely when filter shutdown and flushing finish.
    pub fn poll_shutdown(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let st = self.st();

        if st.flags.is_closed() {
            if let Some(err) = st.error() {
                Poll::Ready(Err(err))
            } else {
                Poll::Ready(Ok(()))
            }
        } else {
            if !st.flags.is_terminating() && !st.flags.is_stopping_filters() {
                st.start_shutdown();
            }
            // Reads must keep running during shutdown so that the transport can
            // observe a peer EOF and filters can complete their shutdown
            // handshake. `BUF_R_READY` is deliberately left alone: it marks
            // input the dispatcher has not consumed yet.
            //
            // Only the pause is cleared. Backpressure means the read buffer is
            // full, which the shutdown must still respect: clearing it on every
            // poll would let a peer that keeps sending grow the buffer without
            // bound, and would hide the blocked shutdown detection in
            // `poll_filters_shutdown`, which tests for exactly that flag.
            //
            // The tasks are woken only when this changes their state:
            // `start_shutdown` wakes both. Waking them on every poll would let
            // a caller that is polled spuriously keep the runtime busy with
            // wakeups; compio then never polls for I/O completions.
            if st.flags.is_read_paused() {
                st.flags.unset_read_paused();
                st.wake_read_task();
            }
            st.dispatch_task.register(cx.waker());
            Poll::Pending
        }
    }

    #[inline]
    /// Pauses the read task and polls for a status update.
    ///
    /// The transport stops reading until the pause is cancelled. There is no
    /// explicit resume: the pause is cancelled implicitly by any operation that
    /// touches the read buffer or asks for more input, namely
    /// [`read_more`](Self::read_more), [`poll_read_more`](Self::poll_read_more),
    /// [`IoRef::decode`], [`IoRef::decode_item`], and [`IoRef::with_read_dst`].
    /// Releasing read backpressure cancels it as well. Because those methods
    /// are available through every [`IoRef`] clone, the pause holds only while
    /// no other holder touches the read buffer.
    ///
    /// See [`poll_status_update`](Self::poll_status_update) for the reported
    /// updates.
    pub fn poll_read_pause(&self, cx: &mut Context<'_>) -> Poll<IoStatusUpdate> {
        let st = self.st();
        if !st.flags.is_read_paused() {
            st.wake_read_task();
            st.flags.set_read_paused();
        }
        self.poll_status_update(cx)
    }

    #[inline]
    /// Polls for available status updates.
    ///
    /// `Timeout` consumes the pending dispatcher-timeout notification.
    /// `WriteBackpressure` is reported while backpressure is active. The poll
    /// that observes the write buffer falling below its release threshold
    /// releases backpressure and reports no status update, matching
    /// [`poll_flush`](Self::poll_flush). `PeerGone` is returned once the
    /// connection has closed, whether the peer disconnected, the transport
    /// failed, or the shutdown was started locally.
    pub fn poll_status_update(&self, cx: &mut Context<'_>) -> Poll<IoStatusUpdate> {
        let st = self.st();
        st.dispatch_task.register(cx.waker());
        if st.flags.is_peer_gone() {
            Poll::Ready(IoStatusUpdate::PeerGone(st.error()))
        } else if st.flags.check_dispatcher_timeout() {
            Poll::Ready(IoStatusUpdate::Timeout)
        } else if st.flags.is_wr_backpressure() {
            // write backpressure is enabled and outstanding output is smaller than half
            if st.should_disable_wr_backpressure(st.write_outstanding()) {
                st.flags.unset_wr_backpressure();
                Poll::Pending
            } else {
                Poll::Ready(IoStatusUpdate::WriteBackpressure)
            }
        } else {
            Poll::Pending
        }
    }

    #[inline]
    /// Registers a dispatch task.
    pub fn register_dispatch(&self, cx: &mut Context<'_>) {
        self.st().dispatch_task.register(cx.waker());
    }
}

impl<F> AsRef<IoRef> for Io<F> {
    #[inline]
    fn as_ref(&self) -> &IoRef {
        self.io_ref()
    }
}

impl<F> Eq for Io<F> {}

impl<F> PartialEq for Io<F> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.io_ref().eq(other.io_ref())
    }
}

impl<F> hash::Hash for Io<F> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.io_ref().hash(state);
    }
}

impl<F> fmt::Debug for Io<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Io").field("state", self.st()).finish()
    }
}

impl<F> ops::Deref for Io<F> {
    type Target = IoRef;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.io_ref()
    }
}

impl<F> Drop for Io<F> {
    fn drop(&mut self) {
        let st = self.st();
        self.stop_timer();

        // code run by the filter chain dropped the `Io`, the filter is in use
        let in_use = st.filter.is_set() && st.buffer.is_borrowed();

        if st.filter.is_set() {
            if in_use {
                // the filter cannot be dropped, it is leaked
                st.force_close_connection();
                st.filter.leak();
            } else {
                // filter is unsafe and must be dropped explicitly,
                // and won't be dropped without special attention
                if !st.flags.is_closed() {
                    log::trace!("{}: Io is dropped, terminate connection", st.tag());
                }

                if st.write_outstanding() == 0 {
                    // Everything the application wrote has reached the transport,
                    // so the connection can end with a normal FIN and the peer
                    // sees a clean end of stream.
                    st.terminate_connection(None);
                } else {
                    // Output is still buffered and the filter chain is about to go
                    // away, so it can never be delivered. Abort instead, so that
                    // the peer cannot mistake a truncated stream for a complete
                    // one.
                    st.force_close_connection();
                }
                st.filter.drop_filter::<F>();
            }

            // Nothing can consume buffered input or deliver buffered output
            // anymore, but the state may outlive the `Io` for a while, held by
            // the transport while it closes or by other `IoRef` handles.
            st.buffer.release(self.io_ref().cfg());

            // Callbacks may hold an `IoRef` to this connection, which would keep
            // the state alive through a reference cycle. They are dropped outside
            // the extensions borrow, because their destructor may use the `IoRef`.
            drop(st.extensions.take_callbacks());
        }

        IoManager::unregister(self.io_ref());

        // a panic while unwinding would abort
        assert!(
            !in_use || std::thread::panicking(),
            "{}: Io is dropped while its filter is in use",
            st.tag()
        );
    }
}

/// Saturating conversion used for the in-flight write counter.
fn as_u32(v: usize) -> u32 {
    u32::try_from(v).unwrap_or(u32::MAX)
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use ntex_bytes::{BufMut, BytePages, Bytes, BytesMut};
    use ntex_codec::BytesCodec;
    use ntex_util::{future::lazy, time::Millis, time::sleep, time::timeout};

    use super::*;
    use crate::waiters::{TAG_DISCONNECT, WaiterEntry};
    use crate::{
        FilterBuf, IoContext, IoTaskStatus, Readiness, Waiter, ops::Iops, testing::IoTest,
    };
    use std::pin::Pin;

    const BIN: &[u8] = b"GET /test HTTP/1\r\n\r\n";
    const TEXT: &str = "GET /test HTTP/1\r\n\r\n";
    const BIN2: &[u8] = b"12345678901234561234567890123456";

    #[ntex::test]
    async fn test_basics() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let server = Io::from(server);
        assert!(server.eq(&server));
        assert!(server.io_ref().eq(server.io_ref()));
    }

    #[ntex::test]
    async fn test_recv() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let server = Io::new(server, SharedCfg::new("SRV"));

        server.st().notify_timeout();
        let err = server.recv(&BytesCodec).await.err().unwrap();
        assert!(format!("{err:?}").contains("Timeout"));

        client.write(TEXT);
        server.st().flags.set_wr_backpressure();
        let item = server.recv(&BytesCodec).await.ok().unwrap().unwrap();
        assert_eq!(item, TEXT);
    }

    /// Callbacks that hold an `IoRef` must not keep the connection state alive
    /// after the `Io` is dropped.
    #[ntex::test]
    async fn test_drop_releases_callbacks() {
        struct Cb(#[allow(dead_code)] IoRef);
        impl crate::IoCallbacks for Cb {
            fn before_processing(&self, _: &IoRef) {}
            fn after_processing(&self, _: &IoRef) {}
        }

        let (client, server) = IoTest::create();
        let server = Io::new(server, SharedCfg::new("SRV"));
        server.register_filter_callbacks(Cb(server.get_ref()));
        let state = Rc::downgrade(&server.io_ref().0);

        drop(server);
        client.close().await;
        sleep(Millis(50)).await;
        assert!(state.upgrade().is_none());
    }

    /// Callbacks registered through a leftover `IoRef` once the `Io` is
    /// dropped, or the connection is closed, must not be stored.
    #[ntex::test]
    async fn test_callbacks_not_registered_after_drop_or_close() {
        struct Cb(#[allow(dead_code)] IoRef, Rc<Cell<usize>>);
        impl crate::IoCallbacks for Cb {
            fn before_processing(&self, _: &IoRef) {
                self.1.set(self.1.get() + 1);
            }
            fn after_processing(&self, _: &IoRef) {}
        }

        // dropped, teardown still in progress
        let (client, server) = IoTest::create();
        let server = Io::new(server, SharedCfg::new("SRV"));
        let io = server.get_ref();
        let state = Rc::downgrade(&io.0);
        drop(server);
        io.register_filter_callbacks(Cb(io.clone(), Rc::default()));
        drop(io);
        client.close().await;
        sleep(Millis(50)).await;
        assert!(state.upgrade().is_none());

        // closed, `Io` still alive
        let (client, server) = IoTest::create();
        let server = Io::new(server, SharedCfg::new("SRV"));
        client.close().await;
        server.close();
        let _ = server.shutdown().await;
        assert!(server.is_closed());
        let calls = Rc::new(Cell::new(0));
        server.register_filter_callbacks(Cb(server.get_ref(), calls.clone()));
        server.with_callbacks(|cb| cb.before_processing(&server));
        assert_eq!(calls.get(), 0);
    }

    #[ntex::test]
    async fn test_stop_timer_clears_timeout_notification() {
        let (_client, server) = IoTest::create();
        let server = Io::new(server, SharedCfg::new("SRV"));

        server.start_timer(ntex_util::time::Seconds(10));
        server.notify_timeout();
        server.stop_timer();

        assert!(lazy(|cx| server.poll_status_update(cx)).await.is_pending());
    }

    #[ntex::test]
    async fn test_read() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let server = Io::new(server, SharedCfg::new("SRV"));

        client.write(b"1234");
        let mut buf: [u8; 4] = [0, 0, 0, 0];
        server.read_exact(&mut buf).await.unwrap();
        assert_eq!(&buf, b"1234");

        // disconnect during read
        let fut = ntex_rt::spawn(async move {
            let mut buf: [u8; 4] = [0, 0, 0, 0];
            let err = server.read_exact(&mut buf).await.unwrap_err();
            (server, err)
        });
        client.close().await;
        let (server, err) = fut.await.unwrap();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);

        let err = server.read_exact(&mut [0]).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
    }

    #[ntex::test]
    async fn test_read_partial_eof() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let server = Io::new(server, SharedCfg::new("SRV"));

        client.write(b"12");
        client.close().await;

        let err = server.read_exact(&mut [0; 4]).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);

        let mut buf = [0; 2];
        server.read_exact(&mut buf).await.unwrap();
        assert_eq!(&buf, b"12");

        let err = server.read_exact(&mut [0]).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
    }

    #[ntex::test]
    async fn test_send() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let server = Io::from(server);
        assert!(server.eq(&server));

        server
            .send(Bytes::from_static(BIN), &BytesCodec)
            .await
            .ok()
            .unwrap();
        let item = client.read_any();
        assert_eq!(item, TEXT);
    }

    #[ntex::test]
    async fn read() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_read_buf(8, 4)),
        );
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        assert!(io.st().dispatch_task.is_set());

        let ctx = IoContext::new(io.get_ref());

        // Ready
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(io.st().read_task.is_set());
        assert!(!io.st().flags.is_read_ready());
        assert!(!io.st().flags.is_rd_backpressure());
        assert!(!io.is_rd_backpressure());
        assert!(!io.is_wr_backpressure());

        // == Enable backpressure
        ctx.release_read_buf(
            BytesMut::copy_from_slice(b"1234567890"),
            Poll::Ready(Ok(10)),
        );

        // dispatcher is woken
        assert!(!io.st().dispatch_task.is_set());
        // read task is paused
        assert!(io.st().flags.is_read_paused());
        // read buffer is ready
        assert!(io.st().flags.is_read_ready());
        // read backpressure is enabled
        assert!(io.st().flags.is_rd_backpressure());
        assert!(io.is_rd_backpressure());
        assert!(!io.is_wr_backpressure());
        // read task paused
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);

        // read one byte
        assert_eq!(io.with_read_dst(|buf| buf.split_to(1)), b"1");
        // read buffer is ready
        assert!(io.st().flags.is_read_ready());
        // read backpressure is enabled
        assert!(io.st().flags.is_rd_backpressure());

        // read task is set
        assert!(io.st().read_task.is_set());

        // read one more byte
        assert_eq!(io.with_read_dst(|buf| buf.split_to(1)), b"2");
        // read backpressure is enabled
        assert!(io.st().flags.is_rd_backpressure());

        // dropping below the high watermark does not release backpressure
        assert_eq!(io.with_read_dst(|buf| buf.split_to(1)), b"3");
        assert!(io.st().flags.is_rd_backpressure());
        assert!(io.st().flags.is_read_paused());

        // reaching half of the high watermark releases backpressure
        assert_eq!(io.with_read_dst(|buf| buf.split_to(3)), b"456");
        // read task is not paused anymore
        assert!(!io.st().flags.is_read_paused());
        // read buffer is not ready
        assert!(!io.st().flags.is_read_ready());
        // read backpressure is disabled
        assert!(!io.st().flags.is_rd_backpressure());
        // read task is woken
        assert!(!io.st().read_task.is_set());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // register dispatcher task
        lazy(|cx| io.register_dispatch(cx)).await;

        // == Enable backpressure, 4 bytes in buffer + 4 more
        ctx.release_read_buf(BytesMut::copy_from_slice(b"1234"), Poll::Ready(Ok(4)));

        // dispatcher is woken
        assert!(!io.st().dispatch_task.is_set());
        // read task is paused
        assert!(io.st().flags.is_read_paused());
        // read buffer is ready
        assert!(io.st().flags.is_read_ready());
        // read backpressure is enabled
        assert!(io.st().flags.is_rd_backpressure());
        // read task paused
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);

        // read 4 bytes. buf size is 4, less that half of high watermark
        assert_eq!(io.with_read_dst(|buf| buf.split_to(4)), b"7890");
        // read backpressure is disabled
        assert!(!io.st().flags.is_rd_backpressure());

        // register dispatcher task
        lazy(|cx| io.register_dispatch(cx)).await;

        // == No backpressure, 4 bytes in buffer + 3 more
        ctx.release_read_buf(BytesMut::copy_from_slice(b"567"), Poll::Ready(Ok(3)));

        // read task is paused
        assert!(!io.st().flags.is_read_paused());
        // read buffer is ready
        assert!(io.st().flags.is_read_ready());
        // read backpressure is enabled
        assert!(!io.st().flags.is_rd_backpressure());
        // read task ready
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // read 4 bytes. buf size is 4, less that half of high watermark
        assert_eq!(io.with_read_dst(BytesMut::take), b"1234567");
        // read task is paused
        assert!(!io.st().flags.is_read_paused());
        // read buffer is ready
        assert!(!io.st().flags.is_read_ready());
        // read task is not woken
        assert!(io.st().read_task.is_set());

        // == Terminate
        io.terminate();
        // read task is woken
        assert!(!io.st().read_task.is_set());
        // read task ready
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
    }

    #[ntex::test]
    async fn only_force_close_reports_terminate() {
        // a transport failure ends the connection, but it is closed gracefully
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ctx = IoContext::new(io.get_ref());
        ctx.stop(Some(io::Error::other("transport failed")));
        assert!(io.st().flags.is_terminating());
        assert!(!io.st().flags.is_force_closing());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );

        // a failure during the transport shutdown phase does not abort either
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ctx = IoContext::new(io.get_ref());
        io.close();
        io.st().filters_stopped();
        assert!(io.st().flags.is_stopping());
        ctx.stop(Some(io::Error::other("transport failed")));
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );

        // only an explicit force close aborts
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ctx = IoContext::new(io.get_ref());
        io.terminate();
        assert!(io.st().flags.is_force_closing());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
    }

    #[ntex::test]
    async fn drop_closes_gracefully_once_output_is_flushed() {
        // Nothing is left to deliver, so the transport ends the connection with
        // a normal FIN and the peer sees a clean end of stream.
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ioref = io.get_ref();
        let ctx = IoContext::new(io.get_ref());
        assert_eq!(io.st().write_outstanding(), 0);
        drop(io);
        assert!(!ioref.0.flags.is_force_closing());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );
    }

    #[ntex::test]
    async fn drop_aborts_when_output_would_be_lost() {
        // The filter chain goes away with the `Io`, so buffered output can
        // never be delivered. Aborting keeps a truncated stream distinguishable
        // from a complete one.
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ioref = io.get_ref();
        let ctx = IoContext::new(io.get_ref());
        io.encode_slice(b"not delivered").unwrap();
        assert_ne!(io.st().write_outstanding(), 0);
        drop(io);
        assert!(ioref.0.flags.is_force_closing());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
    }

    #[ntex::test]
    async fn drop_releases_buffers() {
        // The state can outlive the `Io`, held by the transport while it closes
        // or by other handles, but nothing can use its buffers anymore.
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ioref = io.get_ref();
        let ctx = IoContext::new(io.get_ref());
        ctx.release_read_buf(BytesMut::copy_from_slice(b"unread"), Poll::Ready(Ok(6)));
        io.encode_slice(b"not delivered").unwrap();
        assert_eq!(ioref.0.buffer.read_dst_size(), 6);
        assert_ne!(ioref.0.buffer.write_buf_size(), 0);

        drop(io);
        assert_eq!(ioref.0.buffer.read_dst_size(), 0);
        assert!(ioref.0.buffer.get_read_buf().is_none());
        assert_eq!(ioref.0.buffer.write_buf_size(), 0);

        // input of a read that was in flight is discarded
        ctx.release_read_buf(BytesMut::copy_from_slice(b"late"), Poll::Ready(Ok(4)));
        assert!(ioref.0.buffer.get_read_buf().is_none());
        ctx.with_read_buf(|buf| {
            buf.extend_from_slice(b"late");
            Poll::Ready(Ok(4))
        });
        assert!(ioref.0.buffer.get_read_buf().is_none());
        assert_eq!(ioref.0.buffer.read_dst_size(), 0);
    }

    #[ntex::test]
    async fn force_close_survives_filter_replacement() {
        // Dropping `Io` swaps the chain for `NullFilter`, which cannot see the
        // io state, so an explicit terminate must still be honoured afterwards.
        let io = Io::new(IoTest::create().0, SharedCfg::new("SRV"));
        let ctx = IoContext::new(io.get_ref());
        io.terminate();
        drop(io);
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
    }

    #[ntex::test]
    async fn read_notify() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_read_buf(8, 4)),
        );
        assert!(!io.st().flags.is_read_notify());
        assert!(lazy(|cx| io.poll_read_notify(cx)).await.is_pending());
        assert!(io.st().dispatch_task.is_set());
        assert!(io.st().flags.is_read_notify());

        let ctx = IoContext::new(io.get_ref());

        // incoming bytes
        ctx.release_read_buf(BytesMut::copy_from_slice(b"1"), Poll::Ready(Ok(1)));

        assert!(!io.st().dispatch_task.is_set());
        // rd buffer is ready
        assert!(io.st().flags.is_read_ready());
        assert!(io.st().flags.is_read_notify());
        // dispatcher is notified
        assert!(io.st().flags.is_read_notified());
        let res = lazy(|cx| io.poll_read_notify(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(Some(())))));

        // disapcher is not set
        assert!(!io.st().dispatch_task.is_set());
        // rd buffer is ready
        assert!(io.st().flags.is_read_ready());

        // == start notification process again
        assert!(lazy(|cx| io.poll_read_notify(cx)).await.is_pending());
        assert!(io.st().dispatch_task.is_set());
        assert!(io.st().flags.is_read_notify());
        assert!(io.st().flags.is_read_ready());
        // read task ready
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // == enable packpressure
        ctx.release_read_buf(BytesMut::copy_from_slice(b"2345678"), Poll::Ready(Ok(7)));
        // read backpressure is enabled
        assert!(io.st().flags.is_rd_backpressure());

        // rd buffer is ready
        assert!(io.st().flags.is_read_ready());
        assert!(io.st().flags.is_read_notify());
        // dispatcher is notified
        assert!(io.st().flags.is_read_notified());
        let res = lazy(|cx| io.poll_read_notify(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(Some(())))));
        // read task paused
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);
        // read task is set
        assert!(io.st().read_task.is_set());

        // == start notification process again
        assert!(lazy(|cx| io.poll_read_notify(cx)).await.is_pending());
        // read flags active
        assert!(!io.st().flags.is_rd_backpressure());
        assert!(!io.st().flags.is_read_ready());
        assert!(!io.st().flags.is_read_paused());
        // read task is woken
        assert!(!io.st().read_task.is_set());
        // read task ready
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // incoming bytes
        ctx.release_read_buf(BytesMut::copy_from_slice(b"1"), Poll::Ready(Ok(1)));
        assert!(!io.st().dispatch_task.is_set());
        // rd buffer is ready
        assert!(io.st().flags.is_read_ready());
        assert!(io.st().flags.is_read_notify());
        assert!(io.st().flags.is_read_paused());
        assert!(io.st().flags.is_rd_backpressure());
        // dispatcher is notified
        assert!(io.st().flags.is_read_notified());
        assert!(matches!(
            lazy(|cx| io.poll_read_notify(cx)).await,
            Poll::Ready(Ok(Some(())))
        ));

        // == Terminate
        io.terminate();
        let res = lazy(|cx| io.poll_read_notify(cx)).await;
        assert!(matches!(res, Poll::Ready(Ok(None))), "{res:?}");
    }

    #[ntex::test]
    async fn read_more() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);

        let io = Io::from(server);
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());

        client.write(TEXT);
        assert_eq!(io.read_more().await.unwrap(), Some(()));
        assert!(matches!(
            lazy(|cx| io.poll_read_more(cx)).await,
            Poll::Ready(Ok(Some(())))
        ));

        let item = io.with_read_dst(BytesMut::take);
        assert_eq!(item, Bytes::from_static(BIN));

        client.write(TEXT);
        sleep(Millis(50)).await;
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_ready());
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_ready());
    }

    #[ntex::test]
    async fn read_backpressure() {
        let (client, server) = IoTest::create();

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_read_buf(64, 32)),
        );
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());

        client.write(BIN2);
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_read_ready());
        assert!(io.flags().is_rd_backpressure());
        let _item = io.recv(&BytesCodec).await.ok().unwrap().unwrap();
        assert!(!io.flags().is_read_ready());
        assert!(!io.flags().is_rd_backpressure());

        client.write(BIN2);
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_read_ready());
        assert!(io.flags().is_rd_backpressure());
        assert_eq!(io.read_more().await.unwrap(), Some(()));
    }

    #[ntex::test]
    async fn read_src_releases_read_backpressure() {
        let (client, server) = IoTest::create();

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_read_buf(64, 32)),
        );
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());

        client.write(BIN2);
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_rd_backpressure());

        // On a filterless Io the transport-facing source aliases the
        // application-facing read destination.
        let len = io.get_ref().with_read_src(|buf| {
            let len = buf.len();
            buf.clear();
            len
        });
        assert!(len > 0);
        assert!(!io.flags().is_rd_backpressure());
        assert!(!io.flags().is_read_paused());

        // reads resume
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_read_ready());
    }

    #[ntex::test]
    async fn with_buf_releases_read_backpressure() {
        let (client, server) = IoTest::create();

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_read_buf(64, 32)),
        );
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());

        client.write(BIN2);
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_rd_backpressure());

        let len = io
            .get_ref()
            .with_buf(|buf| {
                buf.with_read_buffers(|_, dst| {
                    let len = dst.len();
                    dst.clear();
                    len
                })
            })
            .unwrap();
        assert!(len > 0);
        assert!(!io.flags().is_rd_backpressure());
        assert!(!io.flags().is_read_paused());

        // reads resume
        client.write(BIN2);
        sleep(Millis(50)).await;
        assert!(io.flags().is_read_ready());
    }

    #[ntex::test]
    async fn write() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
        assert!(io.st().dispatch_task.is_set());
        assert!(io.st().flags.is_direct_wr_enabled());

        let ctx = IoContext::new(io.get_ref());

        // == No write work
        assert_eq!(lazy(|cx| ctx.poll_write_ready(cx)).await, Poll::Pending);
        assert!(io.st().write_task.is_set());
        assert!(io.st().flags.is_write_paused());
        assert!(!io.st().flags.is_wr_backpressure());

        // write
        io.with_write_src(|buf| buf.put_slice(b"1234")).unwrap();
        assert_eq!(lazy(|cx| ctx.poll_write_ready(cx)).await, Poll::Pending);
        // write task is paused
        assert!(io.st().flags.is_write_paused());
        // send-buf op is scheduled
        assert!(io.st().flags.is_wr_send_scheduled());
        // back-pressure is not enabled
        assert!(!io.st().flags.is_wr_backpressure());
        // dispatch is not woken up
        assert!(io.st().dispatch_task.is_set());

        // == enable wr backpressure
        io.with_write_src(|buf| buf.put_slice(b"5678")).unwrap();
        // back-pressure is enabled
        assert!(io.st().flags.is_wr_backpressure());
        // dispatch is woken up
        assert!(!io.st().dispatch_task.is_set());
        // write task is set
        assert!(io.st().write_task.is_set());
        // dispatcher gets WriteBackpressure
        assert!(matches!(
            lazy(|cx| io.poll_status_update(cx)).await,
            Poll::Ready(IoStatusUpdate::WriteBackpressure)
        ));
        // flush write buffer
        assert!(lazy(|cx| io.poll_flush(cx, false)).await.is_pending());
        // full flush is not enabled
        assert!(!io.st().flags.is_write_flush());

        // run send-buf ops
        Iops::run();
        // send-buf op is not scheduled
        assert!(!io.st().flags.is_wr_send_scheduled());
        // write task is not paused
        assert!(!io.st().flags.is_write_paused());
        // write task has been woken up
        assert!(!io.st().write_task.is_set());
        // write task can proceed
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // wrote 4 bytes to io
        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(4).freeze()), b"1234");
        // continue to write
        assert_eq!(ctx.update_write_status(Ok(4)), IoTaskStatus::Io);
        // write task can proceed
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        // write task is not paused
        assert!(!io.st().flags.is_write_paused());
        // back-pressure is enabled
        assert!(io.st().flags.is_wr_backpressure());
        // the write buf dropped below the release threshold, back-pressure is
        // released and no further WriteBackpressure is reported
        assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
        // back-pressure is disabled
        assert!(!io.st().flags.is_wr_backpressure());
        assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
        // write buffer is flushed
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, false)).await,
            Poll::Ready(Ok(()))
        ));

        // full flush write buffer
        io.with_write_src(|buf| buf.put_slice(b"1234")).unwrap();
        assert!(lazy(|cx| io.poll_flush(cx, true)).await.is_pending());
        // full flush is enabled
        assert!(io.st().flags.is_write_flush());
        // back-pressure is enabled
        assert!(io.st().flags.is_wr_backpressure());

        // wrote all data
        Iops::run();
        assert_eq!(ctx.with_write_dst(BytePages::freeze), b"56781234");
        // write task is not paused, so send-buf op is not scheduled
        assert!(!io.st().flags.is_wr_send_scheduled());
        // update status, no more work
        assert_eq!(ctx.update_write_status(Ok(8)), IoTaskStatus::Pause);
        // write task is paused
        assert!(io.st().flags.is_write_paused());
        // flush is still enabled
        assert!(io.st().flags.is_write_flush());
        // back-pressure is still enabled
        assert!(io.st().flags.is_wr_backpressure());
        // dispatch is woken up
        assert!(!io.st().dispatch_task.is_set());

        // write buffer is flushed
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, false)).await,
            Poll::Ready(Ok(()))
        ));
        // full flush is disabled
        assert!(!io.st().flags.is_write_flush());
        // back-pressure is disabled
        assert!(!io.st().flags.is_wr_backpressure());

        // == Terminate
        io.terminate();
        // read task is woken
        assert!(!io.st().write_task.is_set());
        // write task ready
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Terminate)
        );
        // flush returns error
        let Poll::Ready(Err(err)) = lazy(|cx| io.poll_flush(cx, false)).await else {
            panic!()
        };
        assert_eq!(err.kind(), io::ErrorKind::NotConnected);
        // statis returns error
        assert!(matches!(
            lazy(|cx| io.poll_status_update(cx)).await,
            Poll::Ready(IoStatusUpdate::PeerGone(None))
        ));
    }

    #[ntex::test]
    async fn local_shutdown_reports_peer_gone_without_error() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::from(server);

        // purely local graceful shutdown, the peer does nothing
        io.shutdown().await.unwrap();

        assert!(!io.is_active());
        assert!(matches!(
            lazy(|cx| io.poll_status_update(cx)).await,
            Poll::Ready(IoStatusUpdate::PeerGone(None))
        ));
    }

    #[ntex::test]
    async fn set_config_updates_eager_write_support() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(0)),
        );
        assert!(!io.st().flags.is_direct_wr_enabled());

        // SAFETY: no reference returned by `io.cfg()` is retained.
        unsafe {
            io.set_config(SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(1024)));
        }
        assert!(io.st().flags.is_direct_wr_enabled());
        assert_eq!(io.cfg().write_buf_threshold(), 1024);

        // SAFETY: the previous `io.cfg()` reference was limited to the
        // assertion statement and is no longer live.
        unsafe {
            io.set_config(SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(0)));
        }
        assert!(!io.st().flags.is_direct_wr_enabled());
        assert_eq!(io.cfg().write_buf_threshold(), 0);
    }

    #[ntex::test]
    async fn eager_write_uses_updated_buffer_size() {
        #[derive(Debug)]
        struct DirectWrite;

        impl IoStream for DirectWrite {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DirectWrite {
            fn write(&self, ctx: &IoContext) {
                let n = ctx.with_write_dst(|buf| {
                    let n = buf.len();
                    buf.clear();
                    n
                });
                let _ = ctx.update_write_status(Ok(n));
            }
        }

        let io = Io::new(
            DirectWrite,
            SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(1).set_write_buf(8)),
        );

        io.encode_slice(BIN2).unwrap();

        assert_eq!(io.st().buffer.write_buf_size(), 0);
        assert!(io.flags().is_write_paused());
        assert!(!io.flags().is_wr_backpressure());
        assert!(!io.st().flags.is_wr_send_scheduled());
    }

    #[ntex::test]
    async fn eager_write_reports_transport_error() {
        #[derive(Debug)]
        struct FailedWrite;

        impl IoStream for FailedWrite {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for FailedWrite {
            fn write(&self, ctx: &IoContext) {
                ctx.update_write_status(Err(io::Error::new(
                    io::ErrorKind::ConnectionReset,
                    "connection reset",
                )));
            }
        }

        let io = Io::new(
            FailedWrite,
            SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(1)),
        );

        let err = io.encode_slice(BIN2).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");
        assert!(io.st().flags.is_terminating());
    }

    #[ntex::test]
    async fn terminate_during_eager_write_releases_transport() {
        #[derive(Debug)]
        struct FailedWrite(Rc<Cell<bool>>);

        impl Drop for FailedWrite {
            fn drop(&mut self) {
                self.0.set(true);
            }
        }

        impl IoStream for FailedWrite {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for FailedWrite {
            fn write(&self, ctx: &IoContext) {
                ctx.update_write_status(Err(io::Error::new(
                    io::ErrorKind::ConnectionReset,
                    "connection reset",
                )));
            }
        }

        let dropped = Rc::new(Cell::new(false));
        let io = Io::new(
            FailedWrite(dropped.clone()),
            SharedCfg::new("SRV").add(IoConfig::new().set_write_buf_threshold(1)),
        );

        io.encode_slice(BIN2).unwrap_err();
        assert!(io.st().flags.is_terminating());

        // the handle is taken for the duration of the direct write, so the
        // terminate it triggered could not release the transport itself
        assert!(dropped.get());
        assert!(io.st().handle.take().is_none());
    }

    #[ntex::test]
    async fn write_backpressure() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(16)),
        );
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        assert!(io.flags().is_write_paused());
        assert!(!io.flags().is_wr_backpressure());
        assert!(!io.is_wr_backpressure());

        io.encode_slice(BIN2).unwrap();
        assert!(Iops::is_registered(&io));
        assert!(io.flags().is_wr_backpressure());

        client.remote_buffer_cap(1024);
        let item = client.read().await.unwrap();
        assert_eq!(item, BIN2);
        assert!(io.flags().is_wr_backpressure());
        // the write buf drained, back-pressure is released and no status
        // update is reported, same as poll_flush() below
        assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
        assert!(!io.flags().is_wr_backpressure());
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, false)).await,
            Poll::Ready(Ok(()))
        ));
        assert!(!io.flags().is_wr_backpressure());
    }

    #[ntex::test]
    async fn partial_flush_keeps_write_backpressure_until_half_watermark() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let ctx = IoContext::new(io.get_ref());

        io.encode_slice(b"12345678").unwrap();
        assert!(io.flags().is_wr_backpressure());

        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(1).len()), 1);
        assert_eq!(ctx.update_write_status(Ok(1)), IoTaskStatus::Io);
        assert!(lazy(|cx| io.poll_flush(cx, false)).await.is_pending());
        assert!(io.flags().is_wr_backpressure());

        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(3).len()), 3);
        assert_eq!(ctx.update_write_status(Ok(3)), IoTaskStatus::Io);
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, false)).await,
            Poll::Ready(Ok(()))
        ));
        assert!(!io.flags().is_wr_backpressure());
    }

    #[ntex::test]
    async fn write_ready_waits_for_release_threshold() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let ctx = IoContext::new(io.get_ref());

        // no back-pressure
        assert!(io.write_ready().await.is_ok());

        io.encode_slice(b"12345678").unwrap();
        assert!(io.flags().is_wr_backpressure());

        // several producers wait at once
        let done = Rc::new(Cell::new(0));
        for _ in 0..2 {
            let (io, done) = (io.get_ref(), done.clone());
            ntex_util::spawn(async move {
                io.write_ready().await.unwrap();
                done.set(done.get() + 1);
            });
        }
        sleep(Millis(10)).await;
        assert_eq!(done.get(), 0);

        // above the release threshold
        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(1).len()), 1);
        assert_eq!(ctx.update_write_status(Ok(1)), IoTaskStatus::Io);
        sleep(Millis(10)).await;
        assert_eq!(done.get(), 0);

        // the write task wakes the producers, the dispatcher does not run
        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(3).len()), 3);
        assert_eq!(ctx.update_write_status(Ok(3)), IoTaskStatus::Io);
        sleep(Millis(10)).await;
        assert_eq!(done.get(), 2);
        assert!(io.flags().is_wr_backpressure());
        assert!(io.write_ready().await.is_ok());
    }

    #[ntex::test]
    async fn write_ready_released_during_full_flush() {
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let ctx = IoContext::new(io.get_ref());

        io.encode_slice(b"12345678").unwrap();
        assert!(lazy(|cx| io.poll_flush(cx, true)).await.is_pending());
        assert!(io.flags().is_write_flush());

        let done = Rc::new(Cell::new(false));
        let (io2, done2) = (io.get_ref(), done.clone());
        ntex_util::spawn(async move {
            io2.write_ready().await.unwrap();
            done2.set(true);
        });
        sleep(Millis(10)).await;
        assert!(!done.get());

        assert_eq!(ctx.with_write_dst(|buf| buf.split_to(4).len()), 4);
        assert_eq!(ctx.update_write_status(Ok(4)), IoTaskStatus::Io);
        sleep(Millis(10)).await;
        assert!(done.get());
    }

    #[ntex::test]
    async fn write_ready_fails_on_disconnect() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        io.encode_slice(b"12345678").unwrap();
        assert!(io.flags().is_wr_backpressure());

        let res = Rc::new(Cell::new(None));
        let (io2, res2) = (io.get_ref(), res.clone());
        ntex_util::spawn(async move {
            res2.set(Some(io2.write_ready().await.is_err()));
        });
        sleep(Millis(10)).await;
        assert_eq!(res.get(), None);

        io.terminate();
        sleep(Millis(10)).await;
        assert_eq!(res.get(), Some(true));
        assert!(io.write_ready().await.is_err());
    }

    #[ntex::test]
    async fn waiter() {
        let (client, server) = IoTest::create();
        let io = Io::from(server);
        let (mut s1, mut s2, mut s3) = (Waiter::new(&io, 7), Waiter::new(&io, 7), io.waiter(8));
        assert!(lazy(|cx| Pin::new(&mut s1).poll(cx)).await.is_pending());
        assert!(lazy(|cx| Pin::new(&mut s2).poll(cx)).await.is_pending());
        assert!(lazy(|cx| Pin::new(&mut s3).poll(cx)).await.is_pending());
        assert!(lazy(|cx| Pin::new(&mut s1).poll(cx)).await.is_pending());
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 3);

        io.wake(7);
        assert!(lazy(|cx| Pin::new(&mut s1).poll(cx)).await.is_ready());
        assert!(lazy(|cx| Pin::new(&mut s2).poll(cx)).await.is_ready());
        assert!(lazy(|cx| Pin::new(&mut s3).poll(cx)).await.is_pending());
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);

        drop(s3);
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 0);

        // a static waiter keeps the registration
        assert!(lazy(|cx| Pin::new(&mut s1).poll(cx)).await.is_pending());
        let mut s1 = s1.into_static();
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);

        // a cloned waiter is not registered
        let s4 = s1.clone();
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);
        drop(s4);
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);

        // a waiter is woken on disconnect
        let res = Rc::new(Cell::new(false));
        let res2 = res.clone();
        ntex_util::spawn(async move {
            (&mut s1).await;
            res2.set(true);
        });
        sleep(Millis(10)).await;
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);
        client.close().await;
        timeout(Millis(1000), io.shutdown())
            .await
            .expect("stream shutdown did not complete")
            .unwrap();
        sleep(Millis(10)).await;
        assert!(res.get(), "waiter was not woken on disconnect");
        (&mut s2).await;
        drop(s2);
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 0);
    }

    #[ntex::test]
    async fn waiter_poll_ready() {
        let (_client, server) = IoTest::create();
        let io = Io::from(server);
        let waiter = io.waiter(3);
        let ext = &io.get_ref().0.extensions;

        // not registered, the wake is missed
        io.wake(3);
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
        assert_eq!(ext.wakers_len(), 1);

        // a wake between polls is reported once, then the waiter registers again
        io.wake(3);
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_ready());
        assert_eq!(ext.wakers_len(), 0);
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
        assert_eq!(ext.wakers_len(), 1);

        io.wake(3);
        waiter.await;
        assert_eq!(ext.wakers_len(), 0);
    }

    #[ntex::test]
    async fn wake_reserved_tag_is_ignored() {
        let (_client, server) = IoTest::create();
        let io = Io::from(server);
        let mut waiter = io.on_disconnect();
        assert!(lazy(|cx| Pin::new(&mut waiter).poll(cx)).await.is_pending());
        io.wake(TAG_DISCONNECT);
        io.wake(TAG_WRITE);
        assert!(lazy(|cx| Pin::new(&mut waiter).poll(cx)).await.is_pending());
        assert_eq!(io.get_ref().0.extensions.wakers_len(), 1);
    }

    #[cfg(debug_assertions)]
    #[ntex::test]
    #[should_panic(expected = "reserved")]
    async fn waiter_reserved_tag() {
        let (_client, server) = IoTest::create();
        let io = Io::from(server);
        let _waiter = Waiter::new(&io, TAG_DISCONNECT);
    }

    #[cfg(debug_assertions)]
    #[ntex::test]
    #[should_panic(expected = "reserved")]
    async fn waiter_reserved_tag_ioref() {
        let (_client, server) = IoTest::create();
        let io = Io::from(server);
        let _waiter = io.waiter(TAG_WRITE);
    }

    #[ntex::test]
    async fn dropped_waiters_are_removed() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let ext = &io.get_ref().0.extensions;

        for _ in 0..4 {
            let waiter = io.on_disconnect();
            assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
            assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
            assert_eq!(ext.wakers_len(), 1);
        }
        assert_eq!(ext.wakers_len(), 0);

        io.encode_slice(b"12345678").unwrap();
        assert!(io.flags().is_wr_backpressure());
        for _ in 0..4 {
            let mut fut = std::pin::pin!(io.write_ready());
            assert!(lazy(|cx| fut.as_mut().poll(cx)).await.is_pending());
            assert!(lazy(|cx| fut.as_mut().poll(cx)).await.is_pending());
            assert_eq!(ext.wakers_len(), 1);
        }
        assert_eq!(ext.wakers_len(), 0);

        // woken waiters are removed
        let waiter = io.on_disconnect();
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());
        let mut fut = std::pin::pin!(io.write_ready());
        assert!(lazy(|cx| fut.as_mut().poll(cx)).await.is_pending());
        assert_eq!(ext.wakers_len(), 2);
        io.terminate();
        assert_eq!(ext.wakers_len(), 1);
        assert!(lazy(|cx| fut.as_mut().poll(cx)).await.is_ready());

        // the backend reports the teardown
        sleep(Millis(50)).await;
        assert_eq!(ext.wakers_len(), 0);
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_ready());
    }

    #[test]
    fn woken_waiter_slot_is_reused() {
        let ext = Extensions::default();
        let waker = std::task::Waker::noop();
        let (a, b) = (WaiterEntry::new(TAG_WRITE), WaiterEntry::new(TAG_WRITE));

        ext.register_waker(&a, waker);
        ext.wake(TAG_WRITE);

        // `b` reuses the slot of the woken `a`
        ext.register_waker(&b, waker);
        ext.register_waker(&a, waker);
        assert_eq!(ext.wakers_len(), 2);
        ext.remove_waker(&a);
        assert_eq!(ext.wakers_len(), 1);

        // the removed stale id of `a` does not touch `b`
        ext.wake(TAG_WRITE);
        ext.register_waker(&b, waker);
        ext.register_waker(&a, waker);
        ext.wake(TAG_WRITE);
        ext.register_waker(&b, waker);
        ext.remove_waker(&a);
        assert_eq!(ext.wakers_len(), 1);
        ext.remove_waker(&b);
        assert_eq!(ext.wakers_len(), 0);
    }

    #[ntex::test]
    async fn full_flush_waits_for_inflight_write() {
        // A completion based transport takes ownership of the write pages, so
        // the write buffer empties before the bytes reach the peer. A full
        // flush must not complete until they have.
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default()),
        );
        let ctx = IoContext::new(io.get_ref());

        io.encode_slice(b"12345678").unwrap();

        let page = ctx.with_write_dst(BytePages::take).unwrap();
        assert_eq!(page.len(), 8);
        // the buffer is empty, the output is in flight
        assert_eq!(io.st().buffer.write_buf_size(), 0);
        assert_eq!(io.st().write_outstanding(), 8);

        assert!(lazy(|cx| io.poll_flush(cx, true)).await.is_pending());

        // the transport reports the write
        assert_eq!(ctx.update_write_status(Ok(page.len())), IoTaskStatus::Pause);
        assert_eq!(io.st().write_outstanding(), 0);
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, true)).await,
            Poll::Ready(Ok(()))
        ));
    }

    #[ntex::test]
    async fn write_backpressure_counts_inflight_output() {
        // Output owned by the transport is still outstanding, so it keeps
        // back-pressure in place.
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let ctx = IoContext::new(io.get_ref());

        io.encode_slice(b"12345678").unwrap();
        assert!(io.flags().is_wr_backpressure());

        let page = ctx.with_write_dst(BytePages::take).unwrap();
        assert_eq!(io.st().buffer.write_buf_size(), 0);

        // nothing reached the peer yet, so back-pressure stays enabled
        assert!(lazy(|cx| io.poll_flush(cx, false)).await.is_pending());
        assert!(io.flags().is_wr_backpressure());

        assert_eq!(ctx.update_write_status(Ok(page.len())), IoTaskStatus::Pause);
        assert!(matches!(
            lazy(|cx| io.poll_flush(cx, false)).await,
            Poll::Ready(Ok(()))
        ));
        assert!(!io.flags().is_wr_backpressure());
    }

    #[ntex::test]
    async fn transport_shutdown_waits_for_inflight_write() {
        // The transport shutdown phase reports `Close` once the output has
        // been drained. Output the transport already owns has not been
        // drained until it is reported as written.
        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default()),
        );
        let ctx = IoContext::new(io.get_ref());

        io.encode_slice(b"12345678").unwrap();
        let page = ctx.with_write_dst(BytePages::take).unwrap();

        // enter the transport shutdown phase
        io.st().flags.enter_filters_stopping();
        io.st().filters_stopped();
        assert!(io.st().flags.is_stopping());

        // nothing left to submit, but the output is still in flight
        assert_eq!(lazy(|cx| ctx.poll_write_ready(cx)).await, Poll::Pending);

        assert_eq!(ctx.update_write_status(Ok(page.len())), IoTaskStatus::Pause);
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        );
    }

    #[ntex::test]
    async fn shutdown_flushes_write_buf_with_read_backpressure() {
        // Graceful shutdown must flush the pending write buffer even if
        // the peer keeps sending data (read backpressure is enabled).
        let (client, server) = IoTest::create();
        // remote side does not accept any data yet, write task stalls
        client.remote_buffer_cap(0);

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(8, 4)
                    .set_shutdown_timeout(ntex_util::time::Seconds(2)),
            ),
        );

        // queue response data; remote is stalled so it stays in the write buffer
        io.encode_slice(b"response-tail").unwrap();
        sleep(Millis(50)).await;
        assert_eq!(io.st().buffer.write_buf_size(), 13);

        // peer keeps sending, crossing the read high watermark,
        // read task gets paused with back-pressure enabled
        client.write("0123456789");
        sleep(Millis(50)).await;
        assert!(io.flags().is_read_paused());
        assert!(io.flags().is_rd_backpressure());
        assert_eq!(io.st().buffer.write_buf_size(), 13);

        // start graceful shutdown while the write buffer is not empty
        io.close();
        sleep(Millis(50)).await;

        // peer starts draining the connection
        client.remote_buffer_cap(1024);

        // all previously queued data must be written before io stream is closed.
        // Without the fix graceful shutdown completes immediately (read is paused
        // with back-pressure), dropping the buffered write data, so the read here
        // returns nothing instead of the queued response tail.
        let data = ntex_util::time::timeout(Millis(2000), client.read())
            .await
            .expect("write buffer was dropped during shutdown")
            .unwrap();
        assert_eq!(&data[..], b"response-tail");

        // the connection still closes gracefully afterwards (within the
        // shutdown timeout) instead of hanging
        ntex_util::time::timeout(Millis(4000), io.on_disconnect())
            .await
            .expect("io stream did not disconnect after flush");
    }

    #[ntex::test]
    async fn peer_eof_allows_response_before_shutdown() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::from(server);

        client.write("request");
        client.close().await;

        assert_eq!(
            timeout(Millis(1000), io.recv(&BytesCodec))
                .await
                .expect("request was not decoded")
                .unwrap(),
            Some(Bytes::from_static(b"request"))
        );
        assert!(
            timeout(Millis(1000), io.recv(&BytesCodec))
                .await
                .expect("EOF was not reported")
                .unwrap()
                .is_none()
        );
        assert!(!io.st().flags.is_closed());

        io.encode(Bytes::from_static(b"response"), &BytesCodec)
            .unwrap();
        timeout(Millis(1000), io.shutdown())
            .await
            .expect("shutdown did not complete")
            .unwrap();

        assert_eq!(
            timeout(Millis(1000), client.read())
                .await
                .expect("response was not flushed")
                .unwrap(),
            b"response"[..]
        );
    }

    #[ntex::test]
    async fn shutdown_waits_for_transport_stop() {
        #[derive(Debug)]
        struct DormantTransport;

        impl IoStream for DormantTransport {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DormantTransport {}

        let io = Io::from(DormantTransport);
        let ctx = IoContext::new(io.get_ref());
        let waiter = io.on_disconnect();
        io.st().flags.enter_transport_shutdown();

        assert!(lazy(|cx| io.poll_shutdown(cx)).await.is_pending());
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());

        ctx.stopped(None);
        assert!(matches!(
            lazy(|cx| io.poll_shutdown(cx)).await,
            Poll::Ready(Ok(()))
        ));
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_ready());
    }

    /// The transport can report the connection gone straight from the active
    /// state, so being stopped reports every earlier state as reached. That
    /// must not be mistaken for having gone through a graceful shutdown and
    /// discard input that arrived before the connection went away.
    #[ntex::test]
    async fn a_stopped_connection_keeps_its_buffered_input() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        client.write(TEXT);

        let io = Io::from(server);
        io.read_more().await.unwrap().unwrap();
        assert_eq!(io.with_read_dst(|buf| buf.len()), BIN.len());

        IoContext::new(io.get_ref()).stopped(None);
        assert!(io.is_closed() && !io.is_active());
        // the shutdown states report as reached even though none was run
        assert!(io.st().flags.is_stopping() && !io.st().flags.is_shutting_down_filters());
        assert_eq!(
            io.with_read_dst(|buf| buf.len()),
            BIN.len(),
            "input received before the transport went away was discarded"
        );
    }

    #[ntex::test]
    async fn transport_shutdown_drain_wakes_write_task() {
        #[derive(Debug)]
        struct DormantTransport;

        impl IoStream for DormantTransport {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DormantTransport {}

        let io = Io::from(DormantTransport);
        let ctx = IoContext::new(io.get_ref());

        // enter the transport shutdown phase with output still queued
        io.encode_slice(b"tail").unwrap();
        io.st().flags.enter_filters_stopping();
        io.st().flags.enter_transport_shutdown();
        assert_eq!(io.st().buffer.write_buf_size(), 4);

        // the write task is asked to drain it
        assert!(matches!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        ));
        assert!(io.st().write_task.is_set());

        // the transport writes everything out
        let res = ctx.with_write_dst(|buf| {
            let mut written = 0;
            while let Some(page) = buf.take() {
                written += page.len();
            }
            Ok(written)
        });
        assert_eq!(ctx.update_write_status(res), IoTaskStatus::Pause);
        assert_eq!(io.st().write_outstanding(), 0);

        // `poll_write_ready` reports `Close` only on another poll, so the
        // drain must have woken the write task for the shutdown to complete
        assert!(!io.st().write_task.is_set());
        assert!(matches!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Close)
        ));
    }

    #[ntex::test]
    async fn termination_waits_for_transport_stop() {
        #[derive(Debug)]
        struct DormantTransport;

        impl IoStream for DormantTransport {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DormantTransport {}

        let io = Io::from(DormantTransport);
        let ctx = IoContext::new(io.get_ref());
        let waiter = io.on_disconnect();
        ctx.stop(Some(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "connection reset",
        )));

        assert!(io.st().flags.is_terminating());
        assert!(!io.st().flags.is_closed());
        assert!(lazy(|cx| io.poll_shutdown(cx)).await.is_pending());
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_pending());

        ctx.stopped(None);
        let Poll::Ready(Err(err)) = lazy(|cx| io.poll_shutdown(cx)).await else {
            panic!("shutdown did not report termination error");
        };
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert!(lazy(|cx| waiter.poll_ready(cx)).await.is_ready());
    }

    #[ntex::test]
    async fn send_buf_retains_termination_error() {
        #[derive(Debug)]
        struct DormantTransport;

        impl IoStream for DormantTransport {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DormantTransport {}

        let io = Io::from(DormantTransport);
        let ctx = IoContext::new(io.get_ref());
        ctx.stop(Some(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "connection reset",
        )));

        let err = io.get_ref().send_buf().unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");

        ctx.stopped(None);
        let err = io.shutdown().await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");
    }

    #[ntex::test]
    async fn read_readiness_reports_termination_error() {
        #[derive(Debug)]
        struct DormantTransport;

        impl IoStream for DormantTransport {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for DormantTransport {}

        let io = Io::from(DormantTransport);
        let ctx = IoContext::new(io.get_ref());
        ctx.stop(Some(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "connection reset",
        )));

        let Poll::Ready(Err(err)) = lazy(|cx| io.poll_read_more(cx)).await else {
            panic!("read request did not report termination error");
        };
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");

        let Poll::Ready(Err(err)) = lazy(|cx| io.poll_read_notify(cx)).await else {
            panic!("read notification did not report termination error");
        };
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");

        let err = io.read_exact(&mut [0]).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::ConnectionReset);
        assert_eq!(err.to_string(), "connection reset");
    }

    /// Reads pause under back-pressure, so a filter shutdown that waits for
    /// input cannot complete while it holds, even once the dispatcher has
    /// taken the buffered input. Readiness must not ask for reads that would
    /// pause: a readiness based transport would then never re-arm read
    /// interest.
    #[ntex::test]
    async fn filter_shutdown_is_blocked_by_read_backpressure() {
        #[derive(Debug)]
        struct PendingShutdown;

        impl FilterLayer for PendingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Pending)
            }
        }

        let (_client, server) = IoTest::create();
        let io = Io::new(server, SharedCfg::new("SRV")).add_filter(PendingShutdown);

        // The dispatcher decoded part of the input: read readiness is cleared,
        // but the buffer is still above the back-pressure release mark.
        io.st().flags.set_read_ready_and_backpressure();
        io.st().flags.unset_read_ready();
        // shutdown clears the read pause and keeps the back-pressure
        assert!(lazy(|cx| io.poll_shutdown(cx)).await.is_pending());

        let ctx = IoContext::new(io.get_ref());
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);
        assert!(io.st().flags.is_stopping());
    }

    #[ntex::test]
    async fn intermediate_filter_output_reaches_transport() {
        // A filter that emits output while processing reads, the way a TLS
        // layer emits handshake records.
        #[derive(Debug)]
        struct Emit;

        impl FilterLayer for Emit {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_read_buffers(|src, dst| {
                    if let Some(src) = src {
                        dst.extend_from_slice(src);
                        src.clear();
                    }
                });
                buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"pong"));
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Ready(()))
            }
        }

        #[derive(Debug)]
        struct Passthrough;

        impl FilterLayer for Passthrough {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_read_buffers(|src, dst| {
                    if let Some(src) = src {
                        dst.extend_from_slice(src);
                        src.clear();
                    }
                });
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Ready(()))
            }
        }

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

        // Two layers, so the bytes `Emit` writes during read processing land in
        // an intermediate buffer that `Stack::write_buf_size()` does not count.
        // Only the forced write-chain pass moves them out to the transport.
        let io = Io::from(server).add_filter(Passthrough).add_filter(Emit);

        client.write("ping");
        let _ = io.recv(&BytesCodec).await.unwrap();
        sleep(Millis(50)).await;
        assert!(client.read_any().starts_with(b"pong"));
    }

    #[ntex::test]
    async fn read_pauses_while_read_output_is_not_drained() {
        // A filter that answers every input chunk itself, like WebSocket pong
        // replies, without passing anything to the application.
        #[derive(Debug)]
        struct Reply;

        impl FilterLayer for Reply {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                let data = buf.with_read_buffers(|src, _| src.as_mut().map(BytesMut::take));
                if let Some(data) = data {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(&data));
                }
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Ready(()))
            }
        }

        // The transport is driven by the test through `IoContext`.
        #[derive(Debug)]
        struct Manual;

        impl IoStream for Manual {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for Manual {}

        let io = Io::new(
            Manual,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        )
        .add_filter(Reply);
        let ctx = IoContext::new(io.get_ref());
        let read = |data: &'static [u8]| {
            ctx.with_read_buf(|buf| {
                buf.extend_from_slice(data);
                Poll::Ready(Ok(data.len()))
            })
        };

        // the replies are below the high watermark
        assert_eq!(read(b"ping"), IoTaskStatus::Io);
        assert!(!io.st().flags.is_read_wr_backpressure());

        // the replies reach the high watermark, reads pause
        assert_eq!(read(b"ping"), IoTaskStatus::Pause);
        assert!(io.st().flags.is_read_wr_backpressure());
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);
        assert!(io.st().read_task.is_set());

        // the transport takes the replies, in-flight output is not drained
        let _ = ctx.with_write_dst(|buf| buf.split_to(8));
        assert_eq!(io.st().write_outstanding(), 8);
        let _ = ctx.update_write_status(Ok(0));
        assert!(io.st().flags.is_read_wr_backpressure());

        // above half of the high watermark reads stay paused
        let _ = ctx.update_write_status(Ok(3));
        assert!(io.st().flags.is_read_wr_backpressure());
        assert!(io.st().read_task.is_set());

        // drained to half, reading resumes
        let _ = ctx.update_write_status(Ok(1));
        assert!(!io.st().flags.is_read_wr_backpressure());
        assert!(!io.st().read_task.is_set());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // output that was not produced by reading does not pause reads
        io.encode_slice(b"12345678").unwrap();
        assert!(io.st().write_outstanding() >= 8);
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(!io.st().flags.is_read_wr_backpressure());
    }

    #[ntex::test]
    async fn read_output_pause_ignores_held_back_output() {
        // Holds application output until a handshake completes, like TLS
        // during a renegotiation.
        #[derive(Debug, Default)]
        struct Reneg(Cell<bool>);

        impl FilterLayer for Reneg {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                let data = buf.with_read_buffers(|src, _| src.as_mut().map(BytesMut::take));
                match data.as_deref() {
                    Some(b"hello") => {
                        buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"handshake"));
                    }
                    Some(b"done") => {
                        self.0.set(true);
                        buf.with_write_buffers(BytePages::move_to);
                    }
                    _ => (),
                }
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                if self.0.get() {
                    buf.with_write_buffers(BytePages::move_to);
                }
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Ready(()))
            }
        }

        #[derive(Debug)]
        struct Manual;

        impl IoStream for Manual {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for Manual {}

        let io = Io::new(
            Manual,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        )
        .add_filter(Reneg::default());
        let ctx = IoContext::new(io.get_ref());
        let read = |data: &'static [u8]| {
            ctx.with_read_buf(|buf| {
                buf.extend_from_slice(data);
                Poll::Ready(Ok(data.len()))
            })
        };

        // application output is held back by the filter
        io.encode_slice(b"12345678").unwrap();
        assert_eq!(io.st().write_outstanding(), 8);

        // the handshake reply reaches the high watermark, reads pause
        assert_eq!(read(b"hello"), IoTaskStatus::Pause);
        assert!(io.st().flags.is_read_wr_backpressure());

        // the reply drains, the held back output does not keep reads paused
        let _ = ctx.with_write_dst(|buf| buf.split_to(9));
        let _ = ctx.update_write_status(Ok(9));
        assert_eq!(io.st().write_outstanding(), 8);
        assert!(!io.st().flags.is_read_wr_backpressure());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // the handshake completes and the held back output moves
        let _ = read(b"done");
        assert_eq!(ctx.with_write_dst(|buf| buf.len()), 8);
    }

    #[ntex::test]
    async fn read_more_lifts_read_output_pause() {
        #[derive(Debug)]
        struct Reply;

        impl FilterLayer for Reply {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                let data = buf.with_read_buffers(|src, _| src.as_mut().map(BytesMut::take));
                if let Some(data) = data {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(&data));
                }
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Ready(()))
            }
        }

        #[derive(Debug)]
        struct Manual;

        impl IoStream for Manual {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for Manual {}

        let io = Io::new(
            Manual,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        )
        .add_filter(Reply);
        let ctx = IoContext::new(io.get_ref());
        let read = |data: &'static [u8]| {
            ctx.with_read_buf(|buf| {
                buf.extend_from_slice(data);
                Poll::Ready(Ok(data.len()))
            })
        };

        // read_more
        assert_eq!(read(b"pingping"), IoTaskStatus::Pause);
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        assert!(!io.st().flags.is_read_wr_backpressure());
        assert!(!io.st().read_task.is_set());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );

        // read_notify
        assert_eq!(read(b"ping"), IoTaskStatus::Pause);
        assert_eq!(lazy(|cx| ctx.poll_read_ready(cx)).await, Poll::Pending);
        assert!(lazy(|cx| io.poll_read_notify(cx)).await.is_pending());
        assert!(!io.st().flags.is_read_wr_backpressure());
        assert!(!io.st().read_task.is_set());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
    }

    #[ntex::test]
    async fn read_pause_on_read_output_does_not_block_filter_shutdown() {
        #[derive(Debug)]
        struct Reply;

        impl FilterLayer for Reply {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                let data = buf.with_read_buffers(|src, _| src.as_mut().map(BytesMut::take));
                if let Some(data) = data {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(&data));
                }
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                // waits for input, like a TLS close_notify
                Ok(Poll::Pending)
            }
        }

        #[derive(Debug)]
        struct Manual;

        impl IoStream for Manual {
            fn start(self, _: IoContext) -> Box<dyn Handle> {
                Box::new(self)
            }
        }

        impl Handle for Manual {}

        let io = Io::new(
            Manual,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        )
        .add_filter(Reply);
        let ctx = IoContext::new(io.get_ref());
        let read = |data: &'static [u8]| {
            ctx.with_read_buf(|buf| {
                buf.extend_from_slice(data);
                Poll::Ready(Ok(data.len()))
            })
        };

        assert_eq!(read(b"pingping"), IoTaskStatus::Pause);
        assert!(io.st().flags.is_read_wr_backpressure());

        // the filters are shutting down and may need input to complete
        assert!(lazy(|cx| io.poll_shutdown(cx)).await.is_pending());
        assert!(io.st().flags.is_stopping_filters());
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert_eq!(read(b"ping"), IoTaskStatus::Io);
    }

    #[ntex::test]
    async fn peer_eof_completes_filter_shutdown() {
        #[derive(Debug)]
        struct PendingShutdown;

        impl FilterLayer for PendingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                // waits for input that can never arrive after a clean eof
                buf.with_write_buffers(BytePages::move_to);
                Ok(Poll::Pending)
            }
        }

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(
            server,
            SharedCfg::new("SRV")
                .add(IoConfig::default().set_shutdown_timeout(ntex_util::time::Seconds(30))),
        )
        .add_filter(PendingShutdown);

        io.encode_slice(b"bye").unwrap();

        // peer closes cleanly, no further input can arrive
        let peer = client.clone();
        drop(client);
        assert!(io.read_more().await.unwrap().is_none());
        assert!(io.st().flags.is_read_eof());

        // the shutdown completes without waiting for the shutdown timeout
        timeout(Millis(1000), io.shutdown())
            .await
            .expect("transport shutdown did not complete")
            .unwrap();
        assert!(io.st().flags.is_closed());

        // buffered output still reached the peer
        assert_eq!(peer.read_any(), Bytes::from_static(b"bye"));
    }

    /// A filter that forwards input and never finishes its own shutdown.
    #[derive(Debug)]
    struct StuckShutdown(Cell<bool>);

    impl FilterLayer for StuckShutdown {
        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_read_buffers(|src, dst| {
                if let Some(src) = src {
                    dst.extend_from_slice(src);
                    src.clear();
                }
            });
            Ok(())
        }

        fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_write_buffers(BytePages::move_to);
            Ok(())
        }

        fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
            self.0.set(true);
            Ok(Poll::Pending)
        }
    }

    #[ntex::test]
    async fn transport_shutdown_pauses_read_task() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        client.write("before");
        sleep(Millis(25)).await;
        assert_eq!(
            io.recv(&BytesCodec).await.unwrap().unwrap(),
            b"before".as_ref()
        );

        // stall the output so the transport shutdown phase does not complete
        client.remote_buffer_cap(0);
        io.get_ref().with_write_dst(|b| b.extend_from_slice(b"out"));

        // enter the transport shutdown phase
        io.st().flags.enter_filters_stopping();
        io.st().flags.enter_transport_shutdown();
        io.st().wake_read_task();

        // the filters are done, so input is left in the transport; it is
        // discarded by the transport itself right before it closes
        client.write("after");
        sleep(Millis(50)).await;
        assert!(!io.st().flags.is_closed());
        assert_eq!(client.remote_buffer(|buf| buf.len()), 5);
    }

    /// Counts the wakeups delivered through the waker it provides.
    #[derive(Default)]
    struct WakeCounter(std::sync::atomic::AtomicUsize);

    impl std::task::Wake for WakeCounter {
        fn wake(self: std::sync::Arc<Self>) {
            self.wake_by_ref();
        }

        fn wake_by_ref(self: &std::sync::Arc<Self>) {
            self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
    }

    impl WakeCounter {
        fn count(&self) -> usize {
            self.0.load(std::sync::atomic::Ordering::Relaxed)
        }
    }

    #[ntex::test]
    async fn repeated_shutdown_polls_do_not_wake_tasks() {
        use std::{sync::Arc, task::Waker};

        let (_client, server) = IoTest::create();
        let io = Io::new(server, SharedCfg::new("SRV")).add_filter(StuckShutdown(Cell::new(false)));

        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(io.poll_shutdown(&mut cx).is_pending());
        assert!(io.st().flags.is_stopping_filters());

        // Polling again without any state change must not wake the transport
        // tasks. A runtime that polls the caller spuriously, as compio does
        // for `block_on`, would otherwise be kept busy with wakeups.
        let rd = Arc::new(WakeCounter::default());
        let wr = Arc::new(WakeCounter::default());
        io.st().read_task.register(&Waker::from(rd.clone()));
        io.st().write_task.register(&Waker::from(wr.clone()));
        for _ in 0..3 {
            assert!(io.poll_shutdown(&mut cx).is_pending());
        }
        assert_eq!(rd.count(), 0);
        assert_eq!(wr.count(), 0);

        // Paused reads are resumed, the filter may need the input.
        io.st().flags.set_read_paused();
        assert!(io.poll_shutdown(&mut cx).is_pending());
        assert!(!io.st().flags.is_read_paused());
        assert_eq!(rd.count(), 1);
    }

    #[ntex::test]
    async fn filter_shutdown_applies_read_backpressure() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024 * 1024);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(1024, 256)
                    .set_shutdown_timeout(ntex_util::time::Seconds(30)),
            ),
        )
        .add_filter(StuckShutdown(Cell::new(false)));

        let ioref = io.get_ref();
        let high = 1024;
        ntex::rt::spawn(async move {
            let _ = io.shutdown().await;
        });
        sleep(Millis(50)).await;

        // The filter never completes, so the connection stays in the filter
        // shutdown phase while the peer keeps sending.
        for _ in 0..40 {
            client.write("A".repeat(1024));
            sleep(Millis(5)).await;
        }
        sleep(Millis(100)).await;

        // Reads are backpressured instead of draining the peer without bound.
        let buffered = ioref.with_read_dst(|buf| buf.len());
        assert!(
            buffered <= high * 2,
            "read buffer grew to {buffered} with a high watermark of {high}"
        );
        assert!(
            client.remote_buffer(|buf| !buf.is_empty()),
            "peer send buffer was drained despite read backpressure"
        );
    }

    #[ntex::test]
    async fn filter_shutdown_blocked_by_unconsumed_input() {
        // The dispatcher stops consuming with a full read buffer, so the filter
        // cannot receive the input it is waiting for. The shutdown gives up on
        // the filter handshake promptly instead of reading without bound until
        // the deadline.
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024 * 1024);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(1024, 256)
                    .set_shutdown_timeout(ntex_util::time::Seconds(30)),
            ),
        )
        .add_filter(StuckShutdown(Cell::new(false)));

        client.write("A".repeat(4096));
        sleep(Millis(50)).await;
        assert!(
            io.get_ref().is_rd_backpressure(),
            "read backpressure was not active before the shutdown"
        );

        // Completes well inside the 30 second deadline, so it is the blocked
        // detection that ends the phase rather than the timeout.
        let err = timeout(Millis(3000), io.shutdown())
            .await
            .expect("shutdown did not complete")
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
    }

    #[derive(Debug)]
    struct Passthrough;

    impl FilterLayer for Passthrough {
        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_read_buffers(|src, dst| {
                if let Some(src) = src {
                    dst.extend_from_slice(src);
                    src.clear();
                }
            });
            Ok(())
        }

        fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_write_buffers(BytePages::move_to);
            Ok(())
        }
    }

    /// A filter that sends "bye" on shutdown and waits for the peer's "ack".
    #[derive(Debug, Default)]
    struct AckShutdown {
        sent: Cell<bool>,
        acked: Cell<bool>,
    }

    impl FilterLayer for AckShutdown {
        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_read_buffers(|src, dst| {
                if let Some(src) = src {
                    if self.sent.get() && &src[..] == b"ack" {
                        self.acked.set(true);
                    } else {
                        dst.extend_from_slice(src);
                    }
                    src.clear();
                }
            });
            Ok(())
        }

        fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
            buf.with_write_buffers(BytePages::move_to);
            Ok(())
        }

        fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
            if !self.sent.replace(true) {
                buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"bye"));
            }
            Ok(if self.acked.get() {
                Poll::Ready(())
            } else {
                Poll::Pending
            })
        }
    }

    async fn filter_shutdown_waits_for_peer<F: Filter>(client: IoTest, io: Io<F>) {
        client.remote_buffer_cap(1024);
        let io = io.add_filter(AckShutdown::default());
        let done = Rc::new(Cell::new(false));
        let done2 = done.clone();
        ntex::rt::spawn(async move {
            io.shutdown().await.unwrap();
            done2.set(true);
        });
        sleep(Millis(50)).await;

        // the shutdown output reached the peer while the filter is pending
        assert_eq!(client.read_any(), Bytes::from_static(b"bye"));
        assert!(!done.get());

        // the peer's input completes the filter shutdown
        client.write("ack");
        sleep(Millis(50)).await;
        assert!(done.get());
    }

    #[ntex::test]
    async fn filter_shutdown_completes_on_peer_input() {
        let (client, server) = IoTest::create();
        let io = Io::new(server, SharedCfg::new("SRV"));
        filter_shutdown_waits_for_peer(client, io).await;
    }

    #[ntex::test]
    async fn filter_shutdown_output_passes_inner_filters() {
        let (client, server) = IoTest::create();
        let io = Io::new(server, SharedCfg::new("SRV")).add_filter(Passthrough);
        filter_shutdown_waits_for_peer(client, io).await;
    }

    #[ntex::test]
    async fn filter_failure_output_passes_inner_filters() {
        /// Answers any input with "err", closes and fails.
        #[derive(Debug)]
        struct FailOnInput;

        impl FilterLayer for FailOnInput {
            fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                if buf.with_read_src(|src| src.take().is_some()) {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"err"));
                    buf.io().close();
                    Err(io::Error::new(io::ErrorKind::InvalidData, "failed"))
                } else {
                    Ok(())
                }
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }
        }

        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"))
            .add_filter(Passthrough)
            .add_filter(FailOnInput);

        client.write("input");
        let err = io.recv(&BytesCodec).await.unwrap_err();
        assert_eq!(err.into_inner().kind(), io::ErrorKind::InvalidData);
        sleep(Millis(50)).await;

        assert_eq!(client.read_any(), Bytes::from_static(b"err"));
        assert!(io.is_closed());
    }

    #[ntex::test]
    async fn filter_shutdown_timeout_is_reported() {
        #[derive(Debug)]
        struct PendingShutdown;

        impl FilterLayer for PendingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Pending)
            }
        }

        let (_client, server) = IoTest::create();
        let io = Io::new(
            server,
            SharedCfg::new("SRV")
                .add(IoConfig::default().set_shutdown_timeout(ntex_util::time::Seconds(1))),
        )
        .add_filter(PendingShutdown);

        let err = timeout(Millis(3000), io.shutdown())
            .await
            .expect("transport shutdown did not complete")
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
        assert!(io.st().flags.is_closed());
        assert!(!io.st().flags.is_terminating());
    }

    #[ntex::test]
    async fn blocked_filter_shutdown_flushes_buffered_output() {
        #[derive(Debug)]
        struct ClosingShutdown(Cell<bool>);

        impl FilterLayer for ClosingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                // emit a closing record, like a tls close_notify
                if !self.0.replace(true) {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"bye"));
                }
                Ok(Poll::Pending)
            }
        }

        let (client, server) = IoTest::create();
        // the peer cannot accept the closing record yet
        client.remote_buffer_cap(0);

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(8, 4)
                    .set_shutdown_timeout(ntex_util::time::Seconds(10)),
            ),
        )
        .add_filter(ClosingShutdown(Cell::new(false)));

        io.st().flags.set_read_ready_and_backpressure();
        io.close();
        sleep(Millis(50)).await;

        // the filter shutdown is blocked, so the transport shutdown phase
        // starts right away and takes over draining the closing record
        assert!(io.st().flags.is_stopping());

        // let the peer accept the buffered bytes
        client.remote_buffer_cap(1024);
        assert_eq!(
            timeout(Millis(1000), client.read())
                .await
                .expect("closing record was not written")
                .unwrap(),
            Bytes::from_static(b"bye")
        );

        let err = timeout(Millis(1000), io.shutdown())
            .await
            .expect("transport shutdown did not complete")
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
    }

    #[ntex::test]
    async fn one_deadline_bounds_both_shutdown_phases() {
        #[derive(Debug)]
        struct ClosingShutdown(Cell<bool>);

        impl FilterLayer for ClosingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
                buf.with_write_buffers(BytePages::move_to);
                Ok(())
            }

            fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                if !self.0.replace(true) {
                    buf.with_write_buffers(|_, dst| dst.extend_from_slice(b"bye"));
                }
                Ok(Poll::Pending)
            }
        }

        let (client, server) = IoTest::create();
        // the peer never accepts the closing record, so neither the filter
        // shutdown nor the transport drain can ever complete
        client.remote_buffer_cap(0);

        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(8, 4)
                    .set_shutdown_timeout(ntex_util::time::Seconds(1)),
            ),
        )
        .add_filter(ClosingShutdown(Cell::new(false)));

        let start = std::time::Instant::now();
        io.close();

        timeout(Millis(5000), io.shutdown())
            .await
            .expect("transport shutdown did not complete")
            .unwrap_err();
        assert!(io.st().flags.is_closed());

        // both phases stall, yet a single shutdown timeout covers them: a
        // per-phase deadline would take twice as long
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(1600),
            "shutdown took {elapsed:?}, the deadline did not span both phases"
        );
    }

    #[ntex::test]
    async fn blocked_filter_shutdown_is_reported() {
        #[derive(Debug)]
        struct PendingShutdown;

        impl FilterLayer for PendingShutdown {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }

            fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
                Ok(Poll::Pending)
            }
        }

        let (_client, server) = IoTest::create();
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_read_buf(8, 4)
                    .set_shutdown_timeout(ntex_util::time::Seconds(10)),
            ),
        )
        .add_filter(PendingShutdown);

        io.st().flags.set_read_ready_and_backpressure();
        io.close();
        sleep(Millis(50)).await;

        let err = timeout(Millis(1000), io.shutdown())
            .await
            .expect("transport shutdown did not complete")
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert!(io.st().flags.is_closed());
        assert!(!io.st().flags.is_terminating());
    }

    #[ntex::test]
    async fn shutdown() {
        // layer drops all unprocessed data after filter shutdown
        #[derive(Debug)]
        struct F;

        impl FilterLayer for F {
            fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }
            fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
                Ok(())
            }
        }

        let io = Io::new(
            IoTest::create().0,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(8)),
        );
        let st = io.st();
        assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
        assert!(st.dispatch_task.is_set());
        assert!(!st.flags.is_peer_gone());
        assert!(!st.flags.is_stopping_filters());

        let ctx = IoContext::new(io.get_ref());

        // == init shutdown
        io.close();
        assert!(!st.flags.is_peer_gone());
        assert!(st.flags.is_stopping_filters());
        // encoding is not allowed in shutting down stage
        let err = io.with_write_src(|_| 1).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);

        let io = io.add_filter(F);
        let layer = Layer::new(F, Base::new(io.get_ref()));

        let st = io.st();
        st.buffer.with_write_src(|p| p.put_slice(b"123"));
        assert_eq!(st.buffer.write_buf_size(), 3);
        let res = st.buffer.with_filter(io.as_ref(), |f| layer.shutdown(f));
        assert!(matches!(res, Ok(Poll::Ready(()))));
        assert_eq!(st.buffer.write_buf_size(), 0);

        // == terminate
        ctx.stop(None);
        assert!(st.flags.is_peer_gone());
        assert!(st.flags.is_terminating());
        assert!(!st.flags.is_closed());
        assert!(st.flags.is_stopping_filters());

        let err = io.with_write_src(|_| 1).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotConnected);

        ctx.stopped(None);
        assert!(st.flags.is_closed());
    }

    struct FixedSize(usize);

    impl Decoder for FixedSize {
        type Item = Bytes;
        type Error = io::Error;

        fn decode(&self, src: &mut BytesMut) -> Result<Option<Bytes>, io::Error> {
            if src.len() < self.0 {
                Ok(None)
            } else {
                Ok(Some(src.split_to(self.0)))
            }
        }
    }

    #[ntex::test]
    async fn recv_reports_timeout_during_write_backpressure() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(16)),
        );
        io.encode_slice(BIN2).unwrap();
        assert!(io.flags().is_wr_backpressure());

        let ioref = io.get_ref();
        let (res, ()) =
            ntex_util::future::join(timeout(Millis(1000), io.recv(&BytesCodec)), async move {
                sleep(Millis(25)).await;
                ioref.0.notify_timeout();
            })
            .await;

        let Err(Either::Right(err)) = res.expect("recv ignored the timeout") else {
            panic!("expected a timeout error")
        };
        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
        assert!(io.flags().is_wr_backpressure());
    }

    #[ntex::test]
    async fn write_timeout_bounds_output_waits() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(
                IoConfig::default()
                    .set_write_buf(16)
                    .set_write_timeout(ntex_util::time::Seconds(1)),
            ),
        );
        io.encode_slice(BIN2).unwrap();
        assert!(io.flags().is_wr_backpressure());

        let ioref = io.get_ref();
        let ((send, flush), ready) = timeout(
            Millis(3000),
            ntex_util::future::join(
                ntex_util::future::join(
                    io.send(Bytes::from_static(b"item"), &BytesCodec),
                    io.flush(false),
                ),
                ioref.write_ready(),
            ),
        )
        .await
        .expect("output waits are not bounded by the write timeout");

        let Err(Either::Right(err)) = send else {
            panic!("expected a transport error")
        };
        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
        assert_eq!(flush.unwrap_err().kind(), io::ErrorKind::TimedOut);
        assert_eq!(ready.unwrap_err().kind(), io::ErrorKind::TimedOut);

        // the connection is left open, the caller decides
        assert!(!io.is_closed());
        client.remote_buffer_cap(1024);
        io.flush(true).await.unwrap();
    }

    #[ntex::test]
    async fn recv_reports_truncated_stream() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        // a partial item, then the peer goes away
        client.write("123");
        sleep(Millis(25)).await;
        client.close().await;

        let err = io.recv(&FixedSize(8)).await.err().unwrap();
        let Either::Right(err) = err else {
            panic!("expected a transport error")
        };
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);

        // the partial item is still buffered, it is not discarded
        assert_eq!(io.with_read_dst(|b| b.len()), 3);
    }

    #[ntex::test]
    async fn recv_reports_clean_eof() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        // a whole item, then the peer goes away
        client.write("12345678");
        sleep(Millis(25)).await;
        client.close().await;

        assert_eq!(io.recv(&FixedSize(8)).await.unwrap().unwrap(), "12345678");
        assert!(io.recv(&FixedSize(8)).await.unwrap().is_none());
    }

    /// Fixed size frames, the last frame may be shorter once at eof.
    struct FixedSizeEof(usize, std::cell::Cell<usize>);

    impl Decoder for FixedSizeEof {
        type Item = Bytes;
        type Error = io::Error;

        fn decode(&self, src: &mut BytesMut) -> Result<Option<Bytes>, io::Error> {
            FixedSize(self.0).decode(src)
        }

        fn decode_eof(&self, src: &mut BytesMut) -> Result<Option<Bytes>, io::Error> {
            self.1.set(self.1.get() + 1);
            if src.is_empty() {
                Ok(None)
            } else {
                let len = src.len().min(self.0);
                Ok(Some(src.split_to(len)))
            }
        }
    }

    #[ntex::test]
    async fn recv_uses_decode_eof_after_eof() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));
        let codec = FixedSizeEof(8, std::cell::Cell::new(0));

        client.write("12345678");
        sleep(Millis(25)).await;
        assert_eq!(io.recv(&codec).await.unwrap().unwrap(), "12345678");
        // not at eof yet
        assert_eq!(codec.1.get(), 0);

        // a partial frame, then the peer goes away
        client.write("123");
        sleep(Millis(25)).await;
        client.close().await;

        assert_eq!(io.recv(&codec).await.unwrap().unwrap(), "123");
        assert!(io.recv(&codec).await.unwrap().is_none());
        assert!(codec.1.get() >= 2);
        assert_eq!(io.with_read_dst(|b| b.len()), 0);
    }

    #[ntex::test]
    async fn recv_local_shutdown_is_not_truncation() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        // undecodable input is left buffered, but the peer never closed and
        // the shutdown is started locally, so this is not a truncated stream
        client.write("123");
        sleep(Millis(25)).await;
        io.close();
        sleep(Millis(25)).await;

        assert!(io.recv(&FixedSize(8)).await.unwrap().is_none());
        assert_eq!(io.with_read_dst(|b| b.len()), 3);
    }

    #[ntex::test]
    async fn read_pause_stops_transport_reads() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        assert!(lazy(|cx| io.poll_read_pause(cx)).await.is_pending());
        assert!(io.flags().is_read_paused());
        assert!(lazy(|cx| io.poll_read_pause(cx)).await.is_pending());

        // the transport does not read while paused
        client.write("data");
        sleep(Millis(25)).await;
        assert_eq!(io.st().buffer.read_dst_size(), 0);

        // status updates are still reported
        io.st().notify_timeout();
        assert!(matches!(
            lazy(|cx| io.poll_read_pause(cx)).await,
            Poll::Ready(IoStatusUpdate::Timeout)
        ));

        // waiting for input cancels the pause
        assert_eq!(io.read_notify().await.unwrap(), Some(()));
        assert!(!io.flags().is_read_paused());
        assert_eq!(io.with_read_dst(BytesMut::take), b"data");
    }

    /// Querying the read destination size leaves the read state in place.
    #[ntex::test]
    async fn read_dst_size_keeps_read_state() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        // an installed read pause is not cancelled
        assert!(lazy(|cx| io.poll_read_pause(cx)).await.is_pending());
        assert_eq!(io.read_dst_size(), 0);
        assert!(io.flags().is_read_paused());

        // read readiness is not cleared
        client.write("data");
        assert_eq!(io.read_notify().await.unwrap(), Some(()));
        io.st().flags.set_read_ready();
        assert_eq!(io.read_dst_size(), 4);
        assert!(io.flags().is_read_ready());
        assert_eq!(io.with_read_dst(BytesMut::take), b"data");
        assert!(!io.flags().is_read_ready());
    }

    struct Failing;

    impl Decoder for Failing {
        type Item = Bytes;
        type Error = &'static str;

        fn decode(&self, _: &mut BytesMut) -> Result<Option<Bytes>, &'static str> {
            Err("invalid frame")
        }
    }

    #[ntex::test]
    async fn recv_reports_decoder_error() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        client.write("data");
        let Err(Either::Left(err)) = io.recv(&Failing).await else {
            panic!("expected a decoder error")
        };
        assert_eq!(err, "invalid frame");
    }

    /// An expired timer is reported before decoding, the buffered input is
    /// left for the next attempt.
    #[ntex::test]
    async fn poll_recv_decode_reports_timeout_before_decoding() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        client.write("data");
        sleep(Millis(25)).await;
        io.st().notify_timeout();

        let res = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx)).await;
        assert!(matches!(res, Err(RecvError::Timeout)));
        assert_eq!(io.st().buffer.read_dst_size(), 4);

        let decoded = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx))
            .await
            .unwrap();
        assert_eq!(decoded.item.unwrap(), "data");
        assert_eq!((decoded.consumed, decoded.remains), (4, 0));
    }

    /// Write backpressure is reported before decoding, the buffered input is
    /// left for the next attempt.
    #[ntex::test]
    async fn poll_recv_decode_reports_write_backpressure_before_decoding() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        client.write("data");
        sleep(Millis(25)).await;
        io.st().flags.set_wr_backpressure();

        let res = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx)).await;
        assert!(matches!(res, Err(RecvError::WriteBackpressure)));
        assert_eq!(io.st().buffer.read_dst_size(), 4);

        io.flush(false).await.unwrap();
        let decoded = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx))
            .await
            .unwrap();
        assert_eq!(decoded.item.unwrap(), "data");
    }

    /// A closing connection reports neither an expired timer nor write
    /// backpressure, the buffered input is decoded before the disconnect.
    #[ntex::test]
    async fn poll_recv_decode_closing_decodes_buffered_input() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1024);
        let io = Io::new(server, SharedCfg::new("SRV"));

        client.write("data");
        sleep(Millis(25)).await;
        io.close();
        sleep(Millis(25)).await;
        io.st().notify_timeout();
        io.st().flags.set_wr_backpressure();

        let decoded = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx))
            .await
            .unwrap();
        assert_eq!(decoded.item.unwrap(), "data");

        let res = lazy(|cx| io.poll_recv_decode(&BytesCodec, cx)).await;
        assert!(matches!(res, Err(RecvError::PeerGone(None))));
    }

    #[ntex::test]
    async fn poll_flush_enables_write_backpressure() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(0);
        let io = Io::new(
            server,
            SharedCfg::new("SRV").add(IoConfig::default().set_write_buf(16)),
        );

        // output buffered without a state update
        io.with_write_dst(|buf| buf.extend_from_slice(BIN2));
        assert!(!io.flags().is_wr_backpressure());

        assert!(lazy(|cx| io.poll_flush(cx, false)).await.is_pending());
        assert!(io.flags().is_wr_backpressure());

        client.remote_buffer_cap(1024);
        assert_eq!(client.read().await.unwrap(), BIN2);
        io.flush(false).await.unwrap();
        assert!(!io.flags().is_wr_backpressure());
    }

    /// Filter chain wrapper that is not ready for reads or writes while
    /// blocked.
    struct Gate<F>(F, Rc<Cell<bool>>, Rc<Cell<bool>>);

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

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

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

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

        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
            match self.0.poll_read_ready(cx) {
                Poll::Ready(Readiness::Ready) if self.1.get() => Poll::Pending,
                res => res,
            }
        }

        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
            match self.0.poll_write_ready(cx) {
                Poll::Ready(Readiness::Ready) if self.2.get() => Poll::Pending,
                res => res,
            }
        }
    }

    #[derive(Debug)]
    struct GateTransport;

    impl IoStream for GateTransport {
        fn start(self, _: IoContext) -> Box<dyn Handle> {
            Box::new(self)
        }
    }

    impl Handle for GateTransport {}

    #[ntex::test]
    async fn filter_pause_pauses_reading() {
        let blocked = Rc::new(Cell::new(false));
        let b = blocked.clone();
        let io = Io::new(GateTransport, SharedCfg::default())
            .map_filter(move |f| Gate(f, b, Rc::default()));
        let ctx = IoContext::new(io.get_ref());

        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(!io.is_read_filter_paused());

        // the filter is not ready while the io state allows reads
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        blocked.set(true);
        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
        assert!(io.is_read_filter_paused());
        assert!(!io.st().dispatch_task.is_set(), "dispatcher is notified");

        // a continued pause does not notify again
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
        assert!(io.st().dispatch_task.is_set());

        // a read already in flight is accepted, but reading stays paused
        let mut buf = ctx.take_read_buf();
        buf.extend_from_slice(b"12");
        assert_eq!(
            ctx.release_read_buf(buf, Poll::Ready(Ok(2))),
            IoTaskStatus::Pause
        );
        assert_eq!(io.with_read_dst(BytesMut::take), b"12");
        assert_eq!(
            ctx.with_read_buf(|_| Poll::<io::Result<usize>>::Pending),
            IoTaskStatus::Pause
        );

        // the filter is ready again
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        blocked.set(false);
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(!io.is_read_filter_paused());
        assert!(!io.st().dispatch_task.is_set(), "dispatcher is notified");
        assert_eq!(
            ctx.with_read_buf(|_| Poll::<io::Result<usize>>::Pending),
            IoTaskStatus::Io
        );
    }

    #[ntex::test]
    async fn io_state_pause_is_not_filter_pause() {
        let blocked = Rc::new(Cell::new(true));
        let b = blocked.clone();
        let io = Io::new(GateTransport, SharedCfg::default())
            .map_filter(move |f| Gate(f, b, Rc::default()));
        let ctx = IoContext::new(io.get_ref());

        // the dispatcher paused reads, the filter pause is not reported
        io.st().flags.set_read_paused();
        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
        assert!(!io.is_read_filter_paused());

        // the dispatcher resumes reads while the filter is still not ready
        io.st().flags.unset_read_paused();
        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
        assert!(io.is_read_filter_paused());

        // the io state pauses reads again, the filter pause is kept
        io.st().flags.set_read_paused();
        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
        assert!(io.is_read_filter_paused());

        // a ready chain ends the filter pause
        blocked.set(false);
        io.st().flags.unset_read_paused();
        assert_eq!(
            lazy(|cx| ctx.poll_read_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(!io.is_read_filter_paused());
    }

    #[ntex::test]
    async fn filter_pause_pauses_writing() {
        let blocked = Rc::new(Cell::new(true));
        let b = blocked.clone();
        let io = Io::new(GateTransport, SharedCfg::default())
            .map_filter(move |f| Gate(f, Rc::default(), b));
        let ctx = IoContext::new(io.get_ref());

        // no output is waiting, the filter pause is not reported
        assert!(lazy(|cx| ctx.poll_write_ready(cx)).await.is_pending());
        assert!(!io.is_write_filter_paused());

        // output waits for the filter
        io.encode_slice(b"1234").unwrap();
        sleep(Millis(10)).await;
        assert!(!io.st().flags.is_write_paused());
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        assert!(lazy(|cx| ctx.poll_write_ready(cx)).await.is_pending());
        assert!(io.is_write_filter_paused());
        assert!(!io.st().dispatch_task.is_set(), "dispatcher is notified");

        // a write already in flight completes, writing stays paused
        ctx.with_write_dst(|dst| {
            let mut page = dst.take().unwrap();
            page.advance_to(2);
            dst.prepend(page);
        });
        assert_eq!(ctx.update_write_status(Ok(2)), IoTaskStatus::Pause);
        assert!(!io.st().flags.is_write_paused());
        assert_eq!(io.st().buffer.write_buf_size(), 2);

        // the filter is ready again
        assert!(lazy(|cx| io.poll_read_more(cx)).await.is_pending());
        blocked.set(false);
        assert_eq!(
            lazy(|cx| ctx.poll_write_ready(cx)).await,
            Poll::Ready(Readiness::Ready)
        );
        assert!(!io.is_write_filter_paused());
        assert!(!io.st().dispatch_task.is_set(), "dispatcher is notified");
        assert_eq!(ctx.update_write_status(Ok(0)), IoTaskStatus::Io);
    }
}