whatwg_streams 0.1.0-alpha.11

whatwg_streams for rust
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
use super::super::{CountQueuingStrategy, Locked, QueuingStrategy, Unlocked};
use super::error::StreamError;
use super::shared::{StreamResult, WakerSet};
use crate::platform::{MaybeSend, SharedPtr};
use futures::FutureExt;
use futures::channel::mpsc::{UnboundedSender, unbounded};
use futures::channel::oneshot;
use futures::future::poll_fn;
use futures::{AsyncWrite, SinkExt, StreamExt, future};
use futures::{channel::mpsc::UnboundedReceiver, task::AtomicWaker};
use parking_lot::RwLock;
use pin_project::pin_project;
use std::collections::VecDeque;
use std::future::Future;
use std::io::{Error as IoError, ErrorKind};
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::task::{Context, Poll, Waker};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StreamState {
    Writable,
    Closed,
    Errored,
}

struct PendingWrite<T> {
    chunk: T,
    completion_tx: Option<oneshot::Sender<StreamResult<()>>>,
}

/// Commands sent to stream task for state mutation
enum StreamCommand<T> {
    Write {
        chunk: T,
        completion: oneshot::Sender<StreamResult<()>>,
    },
    WriteFireAndForget {
        chunk: T,
    },
    Flush {
        completion: oneshot::Sender<StreamResult<()>>,
    },
    Close {
        completion: oneshot::Sender<StreamResult<()>>,
    },
    Abort {
        reason: Option<String>,
        completion: oneshot::Sender<StreamResult<()>>,
    },
    RegisterReadyWaker {
        waker: Waker,
    },
    RegisterClosedWaker {
        waker: Waker,
    },
}

#[pin_project]
pub struct WritableStream<T: MaybeSend + 'static, Sink, S = Unlocked> {
    command_tx: UnboundedSender<StreamCommand<T>>,
    backpressure: SharedPtr<AtomicBool>,
    closed: SharedPtr<AtomicBool>,
    errored: SharedPtr<AtomicBool>,
    locked: SharedPtr<AtomicBool>,
    queue_total_size: SharedPtr<AtomicUsize>,
    high_water_mark: SharedPtr<AtomicUsize>,
    stored_error: SharedPtr<RwLock<Option<StreamError>>>,
    _sink: PhantomData<Sink>,
    _state: PhantomData<S>,
    #[pin]
    flush_receiver: Option<oneshot::Receiver<StreamResult<()>>>,
    #[pin]
    close_receiver: Option<oneshot::Receiver<Result<(), StreamError>>>,
    #[pin]
    write_receiver: Option<oneshot::Receiver<Result<(), StreamError>>>,
    pending_write_len: Option<usize>,
    pub(crate) controller: SharedPtr<WritableStreamDefaultController>,
}

impl<T: MaybeSend, Sink, S> WritableStream<T, Sink, S> {
    pub fn locked(&self) -> bool {
        self.locked.load(Ordering::Acquire)
    }

    fn get_stored_error(&self) -> StreamError {
        self.stored_error
            .read()
            .clone()
            .unwrap_or_else(|| "Stream is errored".into())
    }
}

impl<T, Sink> WritableStream<T, Sink, Unlocked>
where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    /// Abort the stream, signaling that no more data will be written.
    /// This rejects all pending writes and errors the stream.
    /// Matches WritableStream.abort() in WHATWG spec.
    pub async fn abort(&self, reason: Option<String>) -> StreamResult<()> {
        let (tx, rx) = oneshot::channel();

        // Send the Abort command to the stream task
        self.command_tx
            .clone()
            .send(StreamCommand::Abort {
                reason,
                completion: tx,
            })
            .await
            .map_err(|_| StreamError::TaskDropped)?;

        // Await the completion of the abort operation
        rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
    }

    pub async fn close(&self) -> StreamResult<()> {
        let (tx, rx) = oneshot::channel();

        self.command_tx
            .clone()
            .send(StreamCommand::Close { completion: tx })
            .await
            .map_err(|_| StreamError::TaskDropped)?;

        rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
    }
}

impl<T, Sink> WritableStream<T, Sink, Unlocked>
where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    pub fn get_writer(
        &self,
    ) -> Result<
        (
            WritableStream<T, Sink, Locked>,
            WritableStreamDefaultWriter<T, Sink>,
        ),
        StreamError,
    > {
        // Attempt to atomically acquire the lock:
        if self
            .locked
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return Err("Stream already locked".into());
        }

        let locked = WritableStream {
            command_tx: self.command_tx.clone(),
            backpressure: SharedPtr::clone(&self.backpressure),
            closed: SharedPtr::clone(&self.closed),
            errored: SharedPtr::clone(&self.errored),
            locked: SharedPtr::clone(&self.locked),
            queue_total_size: SharedPtr::clone(&self.queue_total_size),
            high_water_mark: SharedPtr::clone(&self.high_water_mark),
            stored_error: SharedPtr::clone(&self.stored_error),
            _sink: PhantomData,
            _state: PhantomData::<Locked>,
            flush_receiver: None,
            close_receiver: None,
            write_receiver: None,
            pending_write_len: None,
            controller: self.controller.clone(),
        };

        Ok((locked.clone(), WritableStreamDefaultWriter::new(locked)))
    }
}

impl<T: MaybeSend + 'static, Sink> WritableStream<T, Sink>
where
    Sink: WritableSink<T> + 'static,
{
    /// Common constructor logic shared between spawn variants
    pub(crate) fn new_inner(
        sink: Sink,
        strategy: crate::platform::BoxedStrategy<T>,
    ) -> (Self, impl Future<Output = ()>) {
        let (command_tx, command_rx) = futures::channel::mpsc::unbounded();
        let high_water_mark = SharedPtr::new(AtomicUsize::new(strategy.high_water_mark()));
        let stored_error = SharedPtr::new(RwLock::new(None));

        // Spec: backpressure is set at construction from the initial desiredSize
        // (HWM − 0). A HWM of 0 means desiredSize 0, so the stream applies
        // backpressure immediately and ready() is pending until a write drains.
        let initial_backpressure = strategy.high_water_mark() == 0;

        let inner = WritableStreamInner {
            state: StreamState::Writable,
            queue: VecDeque::new(),
            queue_total_size: 0,
            strategy,
            sink: Some(sink),
            backpressure: initial_backpressure,
            close_requested: false,
            close_completions: Vec::new(),
            abort_reason: None,
            abort_requested: false,
            abort_completions: Vec::new(),
            stored_error: SharedPtr::clone(&stored_error),
            ready_wakers: WakerSet::new(),
            closed_wakers: WakerSet::new(),
            flush_completions: Vec::new(),
            pending_flush_commands: Vec::new(),
        };

        let backpressure = SharedPtr::new(AtomicBool::new(initial_backpressure));
        let closed = SharedPtr::new(AtomicBool::new(false));
        let errored = SharedPtr::new(AtomicBool::new(false));
        let locked = SharedPtr::new(AtomicBool::new(false));
        let queue_total_size = SharedPtr::new(AtomicUsize::new(0));

        let (ctrl_tx, ctrl_rx): (
            UnboundedSender<ControllerMsg>,
            UnboundedReceiver<ControllerMsg>,
        ) = unbounded();
        let controller = WritableStreamDefaultController::new(ctrl_tx.clone());

        let fut = stream_task(
            command_rx,
            inner,
            SharedPtr::clone(&backpressure),
            SharedPtr::clone(&closed),
            SharedPtr::clone(&errored),
            SharedPtr::clone(&queue_total_size),
            controller.clone(),
            ctrl_rx,
        );

        let stream = Self {
            command_tx,
            backpressure,
            closed,
            errored,
            locked,
            queue_total_size,
            high_water_mark,
            stored_error,
            _sink: PhantomData,
            _state: PhantomData,
            flush_receiver: None,
            close_receiver: None,
            write_receiver: None,
            pending_write_len: None,
            controller: controller.into(),
        };

        (stream, fut)
    }
}

impl<T, Sink, S> WritableStream<T, Sink, S>
where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    // private helper
    fn desired_size(&self) -> Option<usize> {
        // Spec: errored → null (None); closed → 0 (Some(0)); otherwise HWM − queued
        if self.errored.load(Ordering::Acquire) {
            return None;
        }
        if self.closed.load(Ordering::Acquire) {
            return Some(0);
        }

        let queue_size = self.queue_total_size.load(Ordering::Acquire);
        let hwm = self.high_water_mark.load(Ordering::Acquire);

        if queue_size >= hwm {
            Some(0)
        } else {
            Some(hwm - queue_size)
        }
    }
}

impl<T: MaybeSend + 'static, Sink> Clone for WritableStream<T, Sink, Locked> {
    fn clone(&self) -> Self {
        Self {
            command_tx: self.command_tx.clone(),
            backpressure: SharedPtr::clone(&self.backpressure),
            closed: SharedPtr::clone(&self.closed),
            errored: SharedPtr::clone(&self.errored),
            locked: SharedPtr::clone(&self.locked),
            queue_total_size: SharedPtr::clone(&self.queue_total_size),
            high_water_mark: SharedPtr::clone(&self.high_water_mark),
            stored_error: SharedPtr::clone(&self.stored_error),
            _sink: PhantomData,
            _state: PhantomData,
            flush_receiver: None,
            close_receiver: None,
            write_receiver: None,
            pending_write_len: None,
            controller: self.controller.clone(),
        }
    }
}

impl<T, SinkType> futures::Sink<T> for WritableStream<T, SinkType, Unlocked>
where
    T: MaybeSend + 'static,
    SinkType: WritableSink<T> + 'static,
{
    type Error = StreamError;
    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        // Check if stream is in an error state
        if self.errored.load(Ordering::Acquire) {
            return Poll::Ready(Err(self.get_stored_error()));
        }

        // Check if stream is closed
        if self.closed.load(Ordering::Acquire) {
            return Poll::Ready(Err(StreamError::Closed));
        }

        // Check if there's backpressure
        if !self.backpressure.load(Ordering::Acquire) {
            Poll::Ready(Ok(()))
        } else {
            // Register waker to get notified when backpressure clears:
            let waker = cx.waker().clone();
            let _ = self
                .command_tx
                .unbounded_send(StreamCommand::RegisterReadyWaker { waker });

            // Double-check backpressure after registering waker to avoid race conditions
            if !self.backpressure.load(Ordering::Acquire) {
                Poll::Ready(Ok(()))
            } else {
                Poll::Pending
            }
        }
    }

    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
        // Pre-flight checks before sending
        if self.errored.load(Ordering::Acquire) {
            return Err(self.get_stored_error());
        }

        if self.closed.load(Ordering::Acquire) {
            return Err(StreamError::Closed);
        }

        // Check if backpressure is active - Sink contract says start_send should only
        // be called after poll_ready returns Ready(Ok(()))
        if self.backpressure.load(Ordering::Acquire) {
            return Err(
                "start_send called while backpressure is active - call poll_ready first".into(),
            );
        }

        self.command_tx
            .unbounded_send(StreamCommand::WriteFireAndForget { chunk: item })
            .map_err(|_| StreamError::TaskDropped)?;

        // For the Sink trait, we return immediately after enqueueing.
        // The actual write completion is handled asynchronously by the stream task.
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        // Project the pinned fields
        let mut this = self.project();

        // Check for errors
        if this.errored.load(Ordering::Acquire) {
            let error = this
                .stored_error
                .read()
                .clone()
                .unwrap_or_else(|| "Stream is errored".into());
            return Poll::Ready(Err(error));
        }

        // If there's no flush_receiver yet, initiate a flush and store the receiver
        if this.flush_receiver.is_none() {
            let (tx, rx) = oneshot::channel();
            if this
                .command_tx
                .unbounded_send(StreamCommand::Flush { completion: tx })
                .is_err()
            {
                return Poll::Ready(Err("Stream task dropped".into()));
            }

            *this.flush_receiver = Some(rx);
        }

        // Poll the flush_receiver
        if let Some(rx) = this.flush_receiver.as_mut().as_pin_mut() {
            match rx.poll(cx) {
                Poll::Ready(Ok(result)) => {
                    *this.flush_receiver = None;
                    Poll::Ready(result)
                }
                Poll::Ready(Err(_)) => {
                    *this.flush_receiver = None;
                    Poll::Ready(Err("Flush operation canceled".into()))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            Poll::Ready(Err("Flush receiver missing".into()))
        }
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        // Project the pinned fields
        let mut this = self.project();

        // Already closed?
        if this.closed.load(Ordering::Acquire) {
            return Poll::Ready(Ok(()));
        }

        // If errored, return error
        if this.errored.load(Ordering::Acquire) {
            let error = this
                .stored_error
                .read()
                .clone()
                .unwrap_or_else(|| "Stream is errored".into());
            return Poll::Ready(Err(error));
        }

        // Initiate close if not already started
        if this.close_receiver.is_none() {
            let (tx, rx) = oneshot::channel();
            if this
                .command_tx
                .unbounded_send(StreamCommand::Close { completion: tx })
                .is_err()
            {
                return Poll::Ready(Err("Stream task dropped".into()));
            }
            *this.close_receiver = Some(rx);
        }

        // Poll the close_receiver future
        if let Some(rx) = this.close_receiver.as_mut().as_pin_mut() {
            match rx.poll(cx) {
                Poll::Ready(Ok(result)) => {
                    *this.close_receiver = None;
                    Poll::Ready(result)
                }
                Poll::Ready(Err(_)) => {
                    *this.close_receiver = None;
                    Poll::Ready(Err("Close operation canceled".into()))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            Poll::Ready(Err("Close receiver missing".into()))
        }
    }
}

impl<T, Sink> AsyncWrite for WritableStream<T, Sink, Unlocked>
where
    T: for<'a> From<&'a [u8]> + MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, IoError>> {
        let mut this = self.project();

        // Early return for empty writes
        if buf.is_empty() {
            return Poll::Ready(Ok(0));
        }

        // Check error state
        if this.errored.load(Ordering::Acquire) {
            let error_msg = this
                .stored_error
                .read()
                .as_ref()
                .map(|e| e.to_string())
                .unwrap_or_else(|| "Stream is errored".into());
            return Poll::Ready(Err(IoError::new(ErrorKind::Other, error_msg)));
        }

        // Check closed state
        if this.closed.load(Ordering::Acquire) {
            return Poll::Ready(Err(IoError::new(ErrorKind::BrokenPipe, "Stream is closed")));
        }

        // Backpressure check
        if this.backpressure.load(Ordering::Acquire) {
            let waker = cx.waker().clone();
            let _ = this
                .command_tx
                .unbounded_send(StreamCommand::RegisterReadyWaker { waker });

            if this.backpressure.load(Ordering::Acquire) {
                return Poll::Pending;
            }
        }

        // If no write in progress, start one
        if this.write_receiver.is_none() {
            let chunk: T = T::from(buf);
            let (tx, rx) = oneshot::channel();

            if this
                .command_tx
                .unbounded_send(StreamCommand::Write {
                    chunk,
                    completion: tx,
                })
                .is_err()
            {
                return Poll::Ready(Err(IoError::new(
                    ErrorKind::BrokenPipe,
                    "Stream task dropped",
                )));
            }

            this.write_receiver.set(Some(rx));
            *this.pending_write_len = Some(buf.len());
        }

        // Poll the stored write receiver
        if let Some(rx) = this.write_receiver.as_mut().as_pin_mut() {
            match rx.poll(cx) {
                Poll::Ready(Ok(Ok(()))) => {
                    let written = this.pending_write_len.take().unwrap_or(0);
                    this.write_receiver.set(None);
                    Poll::Ready(Ok(written))
                }
                Poll::Ready(Ok(Err(stream_err))) => {
                    this.write_receiver.set(None);
                    this.pending_write_len.take();
                    let io_err = match stream_err {
                        StreamError::Canceled => {
                            IoError::new(ErrorKind::Interrupted, "Write canceled")
                        }
                        StreamError::Aborted(_) => {
                            IoError::new(ErrorKind::Interrupted, stream_err.to_string())
                        }
                        StreamError::Closing => {
                            IoError::new(ErrorKind::BrokenPipe, "Stream is closing")
                        }
                        StreamError::Closed => {
                            IoError::new(ErrorKind::BrokenPipe, "Stream is closed")
                        }
                        StreamError::TaskDropped => {
                            IoError::new(ErrorKind::BrokenPipe, "Stream task dropped")
                        }
                        StreamError::Other(_) => {
                            IoError::new(ErrorKind::Other, stream_err.to_string())
                        }
                    };
                    Poll::Ready(Err(io_err))
                }
                Poll::Ready(Err(_)) => {
                    this.write_receiver.set(None);
                    this.pending_write_len.take();
                    Poll::Ready(Err(IoError::new(
                        ErrorKind::Interrupted,
                        "Write completion channel canceled",
                    )))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            Poll::Ready(Err(IoError::new(
                ErrorKind::Other,
                "Write receiver missing",
            )))
        }
    }

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

        if this.errored.load(Ordering::Acquire) {
            let error_msg = this
                .stored_error
                .read()
                .as_ref()
                .map(|e| e.to_string())
                .unwrap_or_else(|| "Stream is errored".into());
            return Poll::Ready(Err(IoError::new(ErrorKind::Other, error_msg)));
        }

        // Create flush future if needed
        if this.flush_receiver.is_none() {
            let (tx, rx) = oneshot::channel();
            if this
                .command_tx
                .unbounded_send(StreamCommand::Flush { completion: tx })
                .is_err()
            {
                return Poll::Ready(Err(IoError::new(
                    ErrorKind::BrokenPipe,
                    "Stream task dropped",
                )));
            }
            *this.flush_receiver = Some(rx);
        }

        // Poll the stored flush receiver
        if let Some(rx) = this.flush_receiver.as_mut().as_pin_mut() {
            match rx.poll(cx) {
                Poll::Ready(Ok(result)) => {
                    this.flush_receiver.set(None); // clear the receiver
                    match result {
                        Ok(()) => Poll::Ready(Ok(())),
                        Err(e) => {
                            Poll::Ready(Err(IoError::new(ErrorKind::Other, format!("{}", e))))
                        }
                    }
                }
                Poll::Ready(Err(_)) => {
                    this.flush_receiver.set(None);
                    Poll::Ready(Err(IoError::new(
                        ErrorKind::Other,
                        "Flush operation canceled",
                    )))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            Poll::Ready(Err(IoError::new(
                ErrorKind::Other,
                "Flush receiver missing",
            )))
        }
    }

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

        // If already closed, return success
        if this.closed.load(Ordering::Acquire) {
            return Poll::Ready(Ok(()));
        }

        // If errored, return the error
        if this.errored.load(Ordering::Acquire) {
            let error_msg = this
                .stored_error
                .read()
                .as_ref()
                .map(|e| e.to_string())
                .unwrap_or_else(|| "Stream is errored".into());
            return Poll::Ready(Err(IoError::new(ErrorKind::Other, error_msg)));
        }

        // Create the close receiver if not already created
        if this.close_receiver.is_none() {
            let (tx, rx) = oneshot::channel();
            if this
                .command_tx
                .unbounded_send(StreamCommand::Close { completion: tx })
                .is_err()
            {
                return Poll::Ready(Err(IoError::new(
                    ErrorKind::BrokenPipe,
                    "Stream task dropped",
                )));
            }
            this.close_receiver.set(Some(rx));
        }

        // Poll the stored close receiver
        if let Some(rx) = this.close_receiver.as_mut().as_pin_mut() {
            match rx.poll(cx) {
                Poll::Ready(Ok(result)) => {
                    this.close_receiver.set(None);
                    match result {
                        Ok(()) => Poll::Ready(Ok(())),
                        Err(e) => {
                            Poll::Ready(Err(IoError::new(ErrorKind::Other, format!("{}", e))))
                        }
                    }
                }
                Poll::Ready(Err(_)) => {
                    this.close_receiver.set(None);
                    Poll::Ready(Err(IoError::new(
                        ErrorKind::Other,
                        "Close operation canceled",
                    )))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            // Should never happen
            Poll::Ready(Err(IoError::new(
                ErrorKind::Other,
                "Close receiver missing",
            )))
        }
    }
}

/// The underlying destination for a [`WritableStream`]: the sink receives each
/// chunk and is told when the stream finishes or is torn down.
///
/// # Teardown and the close/abort relationship
///
/// `close` takes `self` by value — closing consumes the sink, which is convenient
/// when finishing means turning accumulated state into a final result. A consequence
/// of owned-close is that **`abort` is not called once `close` is in flight**: by the
/// time an abort arrives during a pending close, the sink has already been moved into
/// the close operation. (The stream's promises still behave per spec — the close
/// rejects with the abort reason and the abort resolves — only the sink-side `abort`
/// callback is skipped in that interleaving.)
///
/// For cleanup that must run no matter how the stream ends — normal close, abort, or
/// an interrupted close — implement [`Drop`] on the sink rather than relying on
/// `abort`. The sink is always dropped when the stream finishes, so `Drop` is the
/// reliable teardown hook; `abort` is best used for the *reason*-carrying side effects
/// of an explicit abort.
pub trait WritableSink<T: MaybeSend + 'static>: MaybeSend + Sized + 'static {
    /// Called once before the first write, to set up the sink.
    fn start(
        &mut self,
        #[allow(unused)] controller: &mut WritableStreamDefaultController,
    ) -> impl Future<Output = StreamResult<()>> + MaybeSend {
        future::ready(Ok(())) // default no-op
    }

    /// Called for each chunk written to the stream. Returning the future unresolved
    /// applies backpressure: the writer's `write` does not resolve until this does.
    fn write(
        &mut self,
        chunk: T,
        controller: &mut WritableStreamDefaultController,
    ) -> impl std::future::Future<Output = StreamResult<()>> + MaybeSend;

    /// Called once after all writes complete, when the writer closes the stream.
    ///
    /// Takes `self` by value so the sink can consume its accumulated state to produce
    /// a final result. Not called if the stream is aborted instead of closed. See the
    /// trait docs for why teardown that must always run belongs in [`Drop`].
    fn close(self) -> impl Future<Output = StreamResult<()>> + MaybeSend {
        future::ready(Ok(())) // default no-op
    }

    /// Called when the stream is aborted with the abort reason, for reason-carrying
    /// cleanup. Not called once `close` is already in flight — see the trait docs.
    fn abort(
        &mut self,
        reason: Option<String>,
    ) -> impl Future<Output = StreamResult<()>> + MaybeSend {
        let _ = reason;
        future::ready(Ok(())) // default no-op
    }
}

// Helper to process each command. Break out to keep task flat.
fn process_command<T, Sink>(
    cmd: StreamCommand<T>,
    inner: &mut WritableStreamInner<T, Sink>,
    backpressure: &SharedPtr<AtomicBool>,
    closed: &SharedPtr<AtomicBool>,
    errored: &SharedPtr<AtomicBool>,
    queue_total_size: &SharedPtr<AtomicUsize>,
    _cx: &mut Context<'_>,
) where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    match cmd {
        StreamCommand::Write { chunk, completion } => {
            if inner.state == StreamState::Errored {
                let _ = completion.send(Err(inner.get_stored_error()));
                return;
            }
            if inner.state == StreamState::Closed {
                let _ = completion.send(Err(StreamError::Closed));
                return;
            }
            if inner.close_requested {
                let _ = completion.send(Err(StreamError::Closing));
                return;
            }
            let chunk_size = inner.strategy.size(&chunk);
            inner.queue.push_back(PendingWrite {
                chunk,
                completion_tx: Some(completion),
            });
            inner.queue_total_size += chunk_size;
            inner.update_backpressure();
            update_atomic_counters(inner, queue_total_size);
            update_flags(&inner, backpressure, closed, errored);
        }
        StreamCommand::WriteFireAndForget { chunk } => {
            if inner.state == StreamState::Errored
                || inner.state == StreamState::Closed
                || inner.close_requested
            {
                return;
            }
            let chunk_size = inner.strategy.size(&chunk);
            inner.queue.push_back(PendingWrite {
                chunk,
                completion_tx: None,
            });
            inner.queue_total_size += chunk_size;
            inner.update_backpressure();
            update_atomic_counters(inner, queue_total_size);
            update_flags(&inner, backpressure, closed, errored);
        }
        StreamCommand::Close { completion } => {
            if inner.state == StreamState::Errored {
                let _ = completion.send(Err(inner.get_stored_error()));
                return;
            }
            // Already closed or a close is already in-flight — reject per spec
            if inner.state == StreamState::Closed || inner.close_requested {
                let _ = completion.send(Err(StreamError::from("stream is already closing or closed")));
                return;
            }
            inner.close_requested = true;
            inner.close_completions.push(completion);
            update_atomic_counters(&inner, &queue_total_size);
            update_flags(&inner, backpressure, closed, errored);
        }
        StreamCommand::Abort { reason, completion } => {
            if inner.state == StreamState::Closed || inner.state == StreamState::Errored {
                let _ = completion.send(Ok(()));
                return;
            }

            if inner.abort_requested {
                // Abort already requested: queue completion
                inner.abort_completions.push(completion);
            } else {
                // First abort request: set reason BEFORE state transition
                inner.abort_reason = reason;
                inner.abort_requested = true;
                inner.abort_completions.push(completion);

                {
                    let mut stored_err_guard = inner.stored_error.write();
                    *stored_err_guard = Some(StreamError::Aborted(inner.abort_reason.clone()));
                }
                inner.state = StreamState::Errored;

                // Immediately reject all pending queued writes
                while let Some(pw) = inner.queue.pop_front() {
                    if let Some(tx) = pw.completion_tx {
                        let error = StreamError::Aborted(inner.abort_reason.clone());
                        let _ = tx.send(Err(error));
                    }
                }
            }
            update_atomic_counters(&inner, &queue_total_size);
            update_flags(&inner, backpressure, closed, errored);
        }
        StreamCommand::Flush { completion } => {
            if inner.state == StreamState::Errored {
                let _ = completion.send(Err(inner.get_stored_error()));
                return;
            }

            inner.pending_flush_commands.push(completion);
        }
        StreamCommand::RegisterReadyWaker { waker } => {
            inner.ready_wakers.register(&waker);
            // Immediately check if this waker should be woken
            // Immediately wake if already ready to prevent race conditions
            if !inner.backpressure {
                inner.ready_wakers.wake_all();
            }
        }
        StreamCommand::RegisterClosedWaker { waker } => {
            inner.closed_wakers.register(&waker);
            // Immediately check if this waker should be woken
            // Immediately wake if already closed/errored to prevent race conditions
            if inner.state == StreamState::Closed || inner.state == StreamState::Errored {
                inner.closed_wakers.wake_all();
            }
        }
    }
}

// Inflight operations being driven
enum InFlight<Sink> {
    Write {
        fut: crate::platform::PlatformBoxFutureStatic<(Sink, StreamResult<()>)>,
        completion: Option<oneshot::Sender<StreamResult<()>>>,
        // Held so queue_total_size can be decremented when the write completes,
        // not when it moves from queue to inflight.
        chunk_size: usize,
    },
    Close {
        fut: crate::platform::PlatformBoxFutureStatic<StreamResult<()>>,
        completions: Vec<oneshot::Sender<StreamResult<()>>>,
    },
    Abort {
        fut: crate::platform::PlatformBoxFutureStatic<StreamResult<()>>,
        completions: Vec<oneshot::Sender<StreamResult<()>>>,
    },
}

async fn stream_task<T, Sink>(
    mut command_rx: UnboundedReceiver<StreamCommand<T>>,
    mut inner: WritableStreamInner<T, Sink>,
    backpressure: SharedPtr<AtomicBool>,
    closed: SharedPtr<AtomicBool>,
    errored: SharedPtr<AtomicBool>,
    queue_total_size: SharedPtr<AtomicUsize>,
    mut controller: WritableStreamDefaultController,
    mut ctrl_rx: UnboundedReceiver<ControllerMsg>,
) where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    let mut inflight: Option<InFlight<Sink>> = None;

    if let Some(mut sink) = inner.sink.take() {
        let start_result = sink.start(&mut controller).await;

        match start_result {
            Ok(()) => {
                // Success: restore the sink to inner
                inner.sink = Some(sink);
            }
            Err(error) => {
                // Failed to start: mark errored state
                inner.state = StreamState::Errored;
                inner.set_stored_error(error);
                inner.sink = None; // Drop the sink on failure
                // Optionally you may want to wake closed and ready wakers here
                update_flags(&inner, &backpressure, &closed, &errored);
                // Since start failed, allow the loop to run and reject commands naturally as they would check for the error state.
            }
        }
    }

    poll_fn(|cx| {
        process_controller_msgs(&mut inner, &mut ctrl_rx, cx);
        update_atomic_counters(&inner, &queue_total_size);
        // Dual-layer waker management to handle race conditions in concurrent scenarios:
        //
        // 1. Immediate wake in RegisterWaker command arms (in process_command):
        //    Prevents race where wakers register when condition is already true
        //
        // 2. Batch wake via update_flags() below: Ensures all waiting wakers get
        //    notified when state changes during command processing
        //
        // Both mechanisms are required - stress testing (800-iteration loops) showed:
        // - Only immediate wake in command arms: failures around iteration 119
        // - Only update_flags() wake: failures around iteration 710
        // - Both together: no failures across multiple test runs
        update_flags(&inner, &backpressure, &closed, &errored);

        // Drain all commands, admin and work commands
        loop {
            match command_rx.poll_next_unpin(cx) {
                Poll::Ready(Some(cmd)) => {
                    process_command(
                        cmd,
                        &mut inner,
                        &backpressure,
                        &closed,
                        &errored,
                        &queue_total_size,
                        cx,
                    );
                    while let Some(completion) = inner.pending_flush_commands.pop() {
                        process_flush_command(completion, &mut inner, &inflight);
                    }
                }
                Poll::Ready(None) => return Poll::Ready(()),
                Poll::Pending => break,
            }
        }

        // cancel inflight writes/closes if abort requested but not yet started
        if inner.abort_requested {
            controller.request_abort(inner.abort_reason.clone()); // Signal to any running writes
            // Cancel inflight write or close operations immediately
            if let Some(inflight_op) = &mut inflight {
                match inflight_op {
                    // The in-flight write is left to finish with its own result (spec
                    // WritableStreamFinishInFlightWrite[WithError]); its promise must carry the
                    // write's own outcome, not the abort error, and the abort proceeds once it
                    // settles (handled in the Poll::Ready arm below). Only the stored error that
                    // closed() sees becomes the abort reason, pinned first-wins when abort was
                    // requested.
                    InFlight::Write { .. } => {}
                    InFlight::Close { completions, .. } => {
                        // Reject the in-flight close completions.
                        let abort_reason = inner.abort_reason.take();
                        let abort_err = StreamError::Aborted(abort_reason);
                        for sender in completions.drain(..) {
                            let _ = sender.send(Err(abort_err.clone()));
                        }
                        // Error the stream immediately with the abort reason.
                        // Per spec: sink.abort() is NOT called once sink.close() has started.
                        // Resolve abort completions with Ok so abort() callers don't hang.
                        inner.state = StreamState::Errored;
                        inner.set_stored_error(abort_err);
                        update_flags(&inner, &backpressure, &closed, &errored);
                        inner.abort_requested = false;
                        for sender in inner.abort_completions.drain(..) {
                            let _ = sender.send(Ok(()));
                        }
                        // The close future keeps running; Poll::Ready will see Errored state
                        // and skip the normal close-success path.
                    }
                    _ => {}
                }
            }
        }

        // 2. ---- If not currently working, handle one "work" command ----
        if inflight.is_none() {
            if inner.close_requested {
                // Only start close after all queued writes are done
                if inner.queue.is_empty() {
                    if let Some(sink) = inner.sink.take() {
                        let fut = Box::pin(async move { sink.close().await });
                        let completions = std::mem::take(&mut inner.close_completions);
                        inflight = Some(InFlight::Close { fut, completions });
                    } else {
                        // Update state BEFORE sending completions
                        inner.state = StreamState::Closed;
                        inner.close_requested = false;

                        update_flags(&inner, &backpressure, &closed, &errored);

                        // THEN send completions
                        for c in inner.close_completions.drain(..) {
                            let _ = c.send(Ok(()));
                        }
                    }
                }
            } else if inner.abort_requested {
                if let Some(mut sink) = inner.sink.take() {
                    let reason = inner.abort_reason.take();
                    let fut = Box::pin(async move { sink.abort(reason).await });
                    let completions = std::mem::take(&mut inner.abort_completions);
                    inflight = Some(InFlight::Abort { fut, completions });
                } else {
                    inner.abort_requested = false;
                    update_flags(&inner, &backpressure, &closed, &errored);

                    // THEN send completions
                    for c in inner.abort_completions.drain(..) {
                        let _ = c.send(Ok(()));
                    }
                }
            }
        }

        // 3. ---- Start a pending Write if possible ----
        if inflight.is_none() && inner.state == StreamState::Writable {
            if let Some(pw) = inner.queue.pop_front() {
                let chunk_size = inner.strategy.size(&pw.chunk);
                // Do NOT decrement queue_total_size here — keep the write counted
                // against backpressure until sink.write() completes (spec §4.5.2).
                // The decrement happens in the Poll::Ready arm below.

                if let Some(mut sink) = inner.sink.take() {
                    let mut ctrl = controller.clone();
                    let chunk = pw.chunk;
                    let completion = pw.completion_tx;

                    inflight = Some(InFlight::Write {
                        fut: Box::pin(async move {
                            let result = sink.write(chunk, &mut ctrl).await;
                            (sink, result)
                        }),
                        completion,
                        chunk_size,
                    });
                } else {
                    // Sink missing — undo queue accounting and error the stream
                    inner.queue_total_size -= chunk_size;
                    update_atomic_counters(&inner, &queue_total_size);
                    if let Some(tx) = pw.completion_tx {
                        let _ = tx.send(Err("Sink missing".into()));
                    }
                    inner.state = StreamState::Errored;
                }
            }
        }

        // 4. ---- Poll the in-flight future if present ----
        if let Some(inflight_op) = &mut inflight {
            match inflight_op {
                InFlight::Write {
                    fut, completion, chunk_size,
                } => {
                    match fut.as_mut().poll(cx) {
                        Poll::Ready((mut sink, result)) => {
                            // Decrement here — write is done, release backpressure now.
                            // Use saturating_sub: the stream may have been errored mid-write
                            // (e.g. terminate() inside transform()), which zeroes queue_total_size.
                            inner.queue_total_size = inner.queue_total_size.saturating_sub(*chunk_size);
                            decrement_flush_counters(&mut inner);

                            if inner.abort_requested {
                                // Transition to abort with recovered sink
                                let reason = inner.abort_reason.take();
                                let abort_fut = Box::pin(async move { sink.abort(reason).await });
                                let completions = std::mem::take(&mut inner.abort_completions);

                                // The in-flight write finishes with its own outcome even though an
                                // abort is pending: its promise carries the write's result, not the
                                // abort error (spec WritableStreamFinishInFlightWrite[WithError]).
                                // The abort error stays the stream's stored error (closed()), set
                                // first-wins when the abort was requested.
                                if let Some(sender) = completion.take() {
                                    let _ = sender.send(result);
                                }

                                inflight = Some(InFlight::Abort {
                                    fut: abort_fut,
                                    completions,
                                });
                                // Wake so InFlight::Abort is polled in the next pass
                                cx.waker().wake_by_ref();
                            } else {
                                // A controller.error() raised inside this write's sink body was
                                // sent to ctrl_rx while the future ran; drain it now so it — not
                                // this write's own rejection — becomes the (first-wins) stored
                                // error, matching the spec's synchronous ordering.
                                process_controller_msgs(&mut inner, &mut ctrl_rx, cx);

                                // Normal case: restore sink
                                if result.is_err() {
                                    if let Err(e) = result.clone() {
                                        inner.set_stored_error(e);
                                    }
                                    inner.state = StreamState::Errored;
                                } else if inner.state != StreamState::Errored {
                                    inner.sink = Some(sink);
                                }

                                inner.update_backpressure();
                                update_atomic_counters(&inner, &queue_total_size);
                                update_flags(&inner, &backpressure, &closed, &errored);

                                if let Some(sender) = completion.take() {
                                    let _ = sender.send(result);
                                }

                                // A write failure errors the whole stream: reject the
                                // writes and close still queued behind it, or they hang.
                                if inner.state == StreamState::Errored {
                                    inner.reject_pending_after_error();
                                    update_atomic_counters(&inner, &queue_total_size);
                                    update_flags(&inner, &backpressure, &closed, &errored);
                                }

                                inflight = None;
                                cx.waker().wake_by_ref();
                            }
                        }
                        Poll::Pending => {}
                    }
                }
                InFlight::Close { fut, completions } => match fut.as_mut().poll(cx) {
                    Poll::Ready(res) => {
                        // completions.is_empty() means they were already drained by the abort
                        // handler.  If they're still present we must send them now (normal close
                        // or close that errored via controller.error() / terminate()).
                        if completions.is_empty() && inner.state == StreamState::Errored {
                            // Aborted during close — state and completions already handled.
                        } else {
                            match &res {
                                Ok(()) => inner.state = StreamState::Closed,
                                Err(err) => {
                                    inner.state = StreamState::Errored;
                                    inner.set_stored_error(err.clone());
                                }
                            }
                            for sender in completions.drain(..) {
                                let _ = sender.send(res.clone());
                            }
                        }

                        inner.close_requested = false;
                        inner.queue.clear();
                        inner.queue_total_size = 0;
                        inner.backpressure = false;

                        update_atomic_counters(&inner, &queue_total_size);
                        update_flags(&inner, &backpressure, &closed, &errored);

                        inflight = None;
                        cx.waker().wake_by_ref();
                    }
                    Poll::Pending => {}
                },
                InFlight::Abort { fut, completions } => match fut.as_mut().poll(cx) {
                    Poll::Ready(sink_abort_result) => {
                        let notify_result = match sink_abort_result {
                            Ok(()) => Ok(()),
                            Err(sink_error) => {
                                // Sink abort failed - error the stream with this error (sink error)
                                inner.set_stored_error(sink_error.clone());
                                Err(sink_error)
                            }
                        };

                        inner.abort_requested = false;
                        // Clear remaining state
                        // Queue should already be empty (it was cleared when abort was requested)
                        inner.queue.clear();
                        inner.queue_total_size = 0;
                        inner.backpressure = false;

                        update_atomic_counters(&inner, &queue_total_size);
                        update_flags(&inner, &backpressure, &closed, &errored);

                        for sender in completions.drain(..) {
                            let _ = sender.send(notify_result.clone());
                        }

                        inflight = None;
                        cx.waker().wake_by_ref();
                    }
                    Poll::Pending => {}
                },
            }
        }

        Poll::Pending
    })
    .await;
}

fn update_flags<T, Sink>(
    inner: &WritableStreamInner<T, Sink>,
    backpressure: &AtomicBool,
    closed: &AtomicBool,
    errored: &AtomicBool,
) {
    let new_state = inner.state;

    backpressure.store(inner.backpressure, Ordering::Release);
    closed.store(new_state == StreamState::Closed, Ordering::Release);
    errored.store(new_state == StreamState::Errored, Ordering::Release);

    // Wake closed wakers if we're in a final state
    if new_state == StreamState::Closed || new_state == StreamState::Errored {
        inner.closed_wakers.wake_all();
    }

    // Wake ready wakers if no backpressure
    if !inner.backpressure {
        inner.ready_wakers.wake_all();
    }
}

pub struct WritableStreamDefaultWriter<T: MaybeSend + 'static, Sink> {
    stream: WritableStream<T, Sink, Locked>,
    // Refcounted lock guard. The writer is Clone — ready()/closed()/write() clone
    // it internally to build 'static futures — so releasing on the first clone's
    // Drop would free the stream's writer lock while the original handle is still
    // live, letting a second get_writer() wrongly succeed mid-use. The lock clears
    // only when the last handle (this guard's final refcount) drops.
    lock: SharedPtr<WriterLockGuard>,
}

struct WriterLockGuard {
    locked: SharedPtr<AtomicBool>,
}

impl Drop for WriterLockGuard {
    fn drop(&mut self) {
        self.locked.store(false, Ordering::Release);
    }
}

impl<T: MaybeSend + 'static, Sink> WritableStreamDefaultWriter<T, Sink>
where
    Sink: WritableSink<T> + 'static,
{
    /// Create a new writer linked to the stream
    fn new(stream: WritableStream<T, Sink, Locked>) -> Self {
        let lock = SharedPtr::new(WriterLockGuard {
            locked: SharedPtr::clone(&stream.locked),
        });
        Self { stream, lock }
    }

    /// Write a chunk to the stream by immediately enqueueing it for writing.
    ///
    /// This method sends the chunk to the stream's internal queue immediately and returns
    /// a future that resolves when the write has been fully processed by the sink.
    /// Awaiting this method ensures the write completes before proceeding.
    ///
    /// # Important
    ///
    /// Calling `write()` repeatedly *without* awaiting or *without* awaiting `ready()` (i.e without
    /// respecting backpressure) can cause unbounded growth of the internal queue,
    /// leading to increased memory usage and potential performance degradation.
    ///
    /// To avoid excessive buffering, it is recommended to either:
    /// - Await each `write()` call or
    /// - Await `ready()` before calling `write()` to respect backpressure signals, or
    /// - Use the [`enqueue_when_ready()`] helper method which does this automatically.
    ///
    /// # Specification Compliance
    ///
    /// This method closely corresponds to the WHATWG Streams specification's default
    /// writer `write()` method. The responsibility for backpressure handling lies with
    /// the caller.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Await ready before writing to avoid queue buildup:
    /// writer.stream.ready().await?;
    /// writer.write(chunk).await?;
    /// ```
    ///
    /// For high throughput scenarios without awaiting each write completion,
    /// call `write()` without awaiting, but this disables backpressure and risks
    /// unbounded queue growth.
    ///
    /// [`enqueue_when_ready()`]: Self::enqueue_when_ready
    pub fn write(&self, chunk: T) -> impl std::future::Future<Output = StreamResult<()>> {
        let (tx, rx) = oneshot::channel();

        let enqueue_result = self
            .stream
            .command_tx
            .unbounded_send(StreamCommand::Write {
                chunk,
                completion: tx,
            })
            .map_err(|_| StreamError::TaskDropped);

        // Return a future that handles the completion waiting
        async move {
            // First check if enqueueing failed
            enqueue_result?;

            // Then wait for the write to complete
            rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
        }
    }

    /// Waits for the stream to be ready (i.e., no backpressure) before performing a write.
    ///
    /// This method asynchronously waits until the stream signals it can accept more data,
    /// via the `ready()` future, before enqueuing the write operation. This helps avoid
    /// excessive queue buildup and memory usage, resulting in better throughput when
    /// producing data at a high rate.
    ///
    /// **Note:** This method is *not* part of the WHATWG Streams specification, but is
    /// provided as a convenient helper to implement efficient backpressure-aware writing.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Write data only when the stream is ready to accept it
    /// writer.enqueue_when_ready(chunk).await?;
    /// ```
    ///
    /// # Behavior
    ///
    /// - Awaits the stream becoming ready (no backpressure).
    /// - Then enqueues the write but doesn't await its completion (like `write()`).
    ///
    /// This approach balances throughput and memory by respecting the stream’s backpressure
    /// signals before each write.
    ///
    /// # Caveats
    ///
    /// Users who want maximum throughput without waiting should call `write()` directly,
    /// and optionally use `ready()` separately to monitor backpressure.
    ///
    /// This helper simplifies the common pattern of waiting on `ready()` before writing,
    /// but callers should choose based on desired flow control characteristics.
    pub async fn enqueue_when_ready(&self, chunk: T) -> StreamResult<()> {
        self.ready().await?;

        // Enqueue the write but don't await completion
        let _write_future = self.write(chunk);

        Ok(())
    }

    /// Immediately enqueue a chunk for writing without waiting for completion.
    ///
    /// This method adds the chunk to the stream's internal write queue and returns
    /// immediately. Unlike [`write()`], it does not wait for the write operation
    /// to complete or return a future for tracking completion.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the chunk was successfully enqueued, or `Err` if
    /// enqueueing fails due to the stream being closed, errored, or the
    /// stream task being dropped.
    ///
    /// # Behavior
    ///
    /// - **Does not wait** for the chunk to be written to the underlying sink
    /// - **Does not provide** completion notification or error handling for the write itself
    /// - **Does not respect backpressure** - chunks are queued regardless of current queue size
    /// - **Fire-and-forget** - suitable for high-throughput scenarios where individual
    ///   write completion tracking isn't needed
    ///
    /// # Memory Considerations
    ///
    /// Since this method doesn't respect backpressure signals, repeated calls without
    /// awaiting [`ready()`] can lead to unbounded queue growth and increased memory usage.
    /// Consider using [`write()`] or [`enqueue_when_ready()`] for backpressure-aware writing.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Fire-and-forget writing
    /// writer.enqueue(chunk1)?;
    /// writer.enqueue(chunk2)?;
    ///
    /// // Later, ensure all writes complete
    /// writer.close().await?;
    /// ```
    ///
    /// [`write()`]: Self::write
    /// [`ready()`]: Self::ready
    /// [`enqueue_when_ready()`]: Self::enqueue_when_ready
    pub fn enqueue(&self, chunk: T) -> StreamResult<()> {
        if self.stream.errored.load(Ordering::Acquire) {
            return Err(self.stream.get_stored_error());
        }
        if self.stream.closed.load(Ordering::Acquire) {
            return Err(StreamError::Closed);
        }

        self.stream
            .command_tx
            .unbounded_send(StreamCommand::WriteFireAndForget { chunk })
            .map_err(|_| StreamError::TaskDropped)
    }

    /// Close the stream asynchronously
    pub async fn close(&self) -> StreamResult<()> {
        let (tx, rx) = oneshot::channel();

        self.stream
            .command_tx
            .clone()
            .send(StreamCommand::Close { completion: tx })
            .await
            .map_err(|_| StreamError::TaskDropped)?;

        rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
    }

    /// Wait until every chunk currently enqueued (and any chunk in-flight) has been
    /// processed by the underlying sink.
    ///
    /// Unlike [`close()`], this does not tear the stream down — the writer remains
    /// usable after `flush` returns. Use this when a long-lived producer needs a
    /// mid-life barrier: "everything I've handed off so far is now in the sink."
    ///
    /// [`ready()`] does not answer the same question: it signals that the stream can
    /// accept more data, not that prior writes have landed.
    ///
    /// **Not part of the WHATWG Streams specification.** The spec exposes only
    /// `close()` on the writer. This helper is provided for the same reason as
    /// [`enqueue_when_ready()`] — convenience that the spec intentionally omits but
    /// Rust callers routinely need.
    ///
    /// [`close()`]: Self::close
    /// [`ready()`]: Self::ready
    /// [`enqueue_when_ready()`]: Self::enqueue_when_ready
    pub async fn flush(&self) -> StreamResult<()> {
        let (tx, rx) = oneshot::channel();
        self.stream
            .command_tx
            .unbounded_send(StreamCommand::Flush { completion: tx })
            .map_err(|_| StreamError::TaskDropped)?;
        rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
    }

    /// Abort the stream asynchronously with an optional reason
    pub async fn abort(&self, reason: Option<String>) -> StreamResult<()> {
        let (tx, rx) = oneshot::channel();

        self.stream
            .command_tx
            .clone()
            .send(StreamCommand::Abort {
                reason,
                completion: tx,
            })
            .await
            .map_err(|_| StreamError::TaskDropped)?;

        rx.await.unwrap_or_else(|_| Err(StreamError::TaskDropped))
    }

    /// Get the desired size synchronously (how much data the stream can accept)
    /// Returns None if the stream is closed or errored
    pub fn desired_size(&self) -> Option<usize> {
        self.stream.desired_size()
    }

    pub fn ready(&self) -> impl Future<Output = StreamResult<()>> {
        let writer = self.clone();
        poll_fn(move |cx| {
            if writer.stream.errored.load(Ordering::Acquire) {
                return Poll::Ready(Err(writer.stream.get_stored_error()));
            }
            if writer.stream.closed.load(Ordering::Acquire) {
                return Poll::Ready(Ok(()));
            }
            if !writer.stream.backpressure.load(Ordering::Acquire) {
                return Poll::Ready(Ok(()));
            }
            // Not ready, register waker:
            let waker = cx.waker().clone();
            let _ = writer
                .stream
                .command_tx
                .unbounded_send(StreamCommand::RegisterReadyWaker { waker });
            // If the channel is full or busy, that's okay—the next poll will try again.
            // Re-check backpressure after registration
            if !writer.stream.backpressure.load(Ordering::Acquire) {
                return Poll::Ready(Ok(()));
            }
            Poll::Pending
        })
    }

    pub fn closed(&self) -> impl Future<Output = StreamResult<()>> {
        let writer = self.clone();
        poll_fn(move |cx| {
            if writer.stream.errored.load(Ordering::Acquire) {
                return Poll::Ready(Err(writer.stream.get_stored_error()));
            }
            if writer.stream.closed.load(Ordering::Acquire) {
                return Poll::Ready(Ok(()));
            }
            let waker = cx.waker().clone();
            let _ = writer
                .stream
                .command_tx
                .unbounded_send(StreamCommand::RegisterClosedWaker { waker });
            // Re-check closed after registration
            if writer.stream.closed.load(Ordering::Acquire) {
                return Poll::Ready(Ok(()));
            }
            Poll::Pending
        })
    }
}

// Update the stream task to maintain the atomic counters
// this is meant to be called when queue or inflight size is modified before waking wakers i.e before calling `update_flags`
fn update_atomic_counters<T, Sink>(
    inner: &WritableStreamInner<T, Sink>,
    queue_total_size: &SharedPtr<AtomicUsize>,
) {
    queue_total_size.store(inner.queue_total_size, Ordering::Release);
}

impl<T: MaybeSend + 'static, Sink> WritableStreamDefaultWriter<T, Sink>
where
    Sink: WritableSink<T> + 'static,
{
    pub fn release_lock(self) -> StreamResult<()> {
        // Dropping self releases this handle's share of the lock guard. The lock
        // clears once the last writer handle — including any held by in-flight
        // ready()/closed() futures — is gone.
        drop(self);
        Ok(())
    }
}

impl<T: MaybeSend + 'static, Sink> Clone for WritableStreamDefaultWriter<T, Sink> {
    fn clone(&self) -> Self {
        Self {
            stream: self.stream.clone(),
            lock: SharedPtr::clone(&self.lock),
        }
    }
}

struct WritableStreamInner<T, Sink> {
    state: StreamState,
    queue: VecDeque<PendingWrite<T>>,
    queue_total_size: usize,
    strategy: crate::platform::BoxedStrategyStatic<T>,
    sink: Option<Sink>,

    backpressure: bool,
    /// `close()` in progress flag and completions waiting for close
    close_requested: bool,
    close_completions: Vec<oneshot::Sender<StreamResult<()>>>,

    abort_reason: Option<String>,
    /// `abort()` in progress flag and completions waiting for abort
    abort_requested: bool,
    abort_completions: Vec<oneshot::Sender<StreamResult<()>>>,

    stored_error: SharedPtr<RwLock<Option<StreamError>>>,

    ready_wakers: WakerSet,
    closed_wakers: WakerSet,

    /// Track flush operations waiting for specific write counts
    flush_completions: Vec<(oneshot::Sender<StreamResult<()>>, usize)>,
    pending_flush_commands: Vec<oneshot::Sender<StreamResult<()>>>,
}

impl<T: MaybeSend + 'static, Sink> WritableStreamInner<T, Sink> {
    /// Update the stream's backpressure flag to reflect the current load.
    fn update_backpressure(&mut self) {
        let prev = self.backpressure;
        self.backpressure = self.queue_total_size >= self.strategy.high_water_mark();
        if prev && !self.backpressure {
            self.ready_wakers.wake_all();
        }
    }

    fn get_stored_error(&self) -> StreamError {
        self.stored_error
            .read()
            .clone()
            .unwrap_or_else(|| "Stream is errored".into())
    }

    /// Record the stream's stored error, first-wins. The spec fixes `[[storedError]]` when the
    /// stream first leaves the "writable" state (`WritableStreamStartErroring`); every later error
    /// source is a no-op for it. Each write/close/abort *promise* still carries its own error
    /// through its own completion channel — only this shared stored error is pinned to the first.
    fn set_stored_error(&self, err: StreamError) {
        let mut guard = self.stored_error.write();
        if guard.is_none() {
            *guard = Some(err);
        }
    }

    /// Reject every request still waiting on the stream with the stored error.
    ///
    /// When a `sink.write()` failure transitions the stream to Errored, the spec's
    /// erroring procedure clears *all* pending write requests plus the close
    /// request — not only the write whose sink call failed. Without this, a write
    /// queued behind the failing one (and a close queued behind that) would wait on
    /// a completion that is never sent. `close_requested` is cleared too, so the
    /// post-error poll does not mistake the drained close queue for a clean close.
    fn reject_pending_after_error(&mut self) {
        let error = self.get_stored_error();
        while let Some(pw) = self.queue.pop_front() {
            if let Some(tx) = pw.completion_tx {
                let _ = tx.send(Err(error.clone()));
            }
        }
        self.queue_total_size = 0;
        self.close_requested = false;
        for c in self.close_completions.drain(..) {
            let _ = c.send(Err(error.clone()));
        }
        for (c, _) in self.flush_completions.drain(..) {
            let _ = c.send(Err(error.clone()));
        }
    }
}

// Stream task processing for flush - count writes at this moment!
fn process_flush_command<T: MaybeSend + 'static, Sink>(
    completion: oneshot::Sender<StreamResult<()>>,
    inner: &mut WritableStreamInner<T, Sink>,
    inflight: &Option<InFlight<Sink>>,
) {
    if inner.state == StreamState::Errored {
        let _ = completion.send(Err(inner.get_stored_error()));
        return;
    }

    // Count writes that exist RIGHT NOW when flush is called
    let inflight_writes = match inflight {
        Some(InFlight::Write { .. }) => 1,
        _ => 0,
    };
    let writes_to_wait_for = inner.queue.len() + inflight_writes;

    if writes_to_wait_for == 0 {
        // No writes to wait for - flush complete immediately!
        let _ = completion.send(Ok(()));
    } else {
        // Queue this flush to wait for exactly this many write completions
        inner
            .flush_completions
            .push((completion, writes_to_wait_for));
    }
}

// When ANY write completes, decrement ALL pending flush counters
fn decrement_flush_counters<T, Sink>(inner: &mut WritableStreamInner<T, Sink>) {
    let mut i = 0;
    while i < inner.flush_completions.len() {
        let (_, count) = &mut inner.flush_completions[i];
        *count -= 1;

        if *count == 0 {
            // This flush is complete!
            let (sender, _) = inner.flush_completions.swap_remove(i);
            let _ = sender.send(Ok(()));
            // Don't increment i since we removed an element
        } else {
            i += 1;
        }
    }
}

enum ControllerMsg {
    /// Trigger a stream error (controller.error(...))
    Error(StreamError),
}

/// Handle all controller-to-driver messages in a single step.
/// Call this in your poll_fn, before or after handling work.
fn process_controller_msgs<T, Sink>(
    inner: &mut WritableStreamInner<T, Sink>,
    ctrl_rx: &mut UnboundedReceiver<ControllerMsg>,
    cx: &mut Context<'_>,
) {
    // Poll (not try_next) so the task registers a waker on ctrl_rx: a controller.error() that
    // arrives while the task is otherwise idle (no commands, no in-flight write) must still wake
    // it, or the error sits unprocessed and closed()/ready() never settle.
    while let Poll::Ready(Some(msg)) = ctrl_rx.poll_next_unpin(cx) {
        match msg {
            ControllerMsg::Error(err) => {
                // controller.error() only takes effect while the stream is still "writable" (spec
                // WritableStreamDefaultControllerError). Once errored it is a surplus no-op (first
                // error wins); once closed it is a no-op; and while a close is in flight it is
                // discarded in favour of the close outcome — a successful close wins, matching
                // WritableStreamFinishInFlightClose clearing the stored error.
                if inner.state != StreamState::Writable || inner.close_requested {
                    continue;
                }
                *inner.stored_error.write() = Some(err.clone());
                inner.abort_reason = Some(format!("Controller error: {:?}", err));
                inner.state = StreamState::Errored;
                inner.queue.clear();
                inner.queue_total_size = 0;
                inner.ready_wakers.wake_all();
                inner.closed_wakers.wake_all();
            }
        }
    }
}

#[derive(Clone)]
pub struct WritableStreamDefaultController {
    tx: UnboundedSender<ControllerMsg>,
    abort_requested: SharedPtr<AtomicBool>,
    abort_reason: SharedPtr<RwLock<Option<String>>>,
    abort_waker: SharedPtr<AtomicWaker>,
}

impl WritableStreamDefaultController {
    fn new(sender: UnboundedSender<ControllerMsg>) -> Self {
        Self {
            tx: sender,
            abort_requested: SharedPtr::new(AtomicBool::new(false)),
            abort_reason: SharedPtr::new(RwLock::new(None)),
            abort_waker: SharedPtr::new(AtomicWaker::new()),
        }
    }

    /// Signal an error on the stream
    pub fn error(&self, error: StreamError) {
        // ignore send failure if receiver is dropped
        let _ = self.tx.unbounded_send(ControllerMsg::Error(error));
    }

    /// Returns `true` if the stream has been aborted.
    ///
    /// This is a synchronous check of the abort flag.
    pub fn is_aborted(&self) -> bool {
        self.abort_requested.load(Ordering::Acquire)
    }

    /// The reason the stream was aborted, if any.
    ///
    /// `None` until the stream is aborted, and `None` when it was aborted
    /// without a reason. A sink reacting to [`abort_future()`] or
    /// [`with_abort()`] can read this to learn *why* it was aborted.
    ///
    /// [`abort_future()`]: Self::abort_future
    /// [`with_abort()`]: Self::with_abort
    pub fn abort_reason(&self) -> Option<String> {
        self.abort_reason.read().clone()
    }

    /// Internal: request that the stream be aborted with an optional reason.
    ///
    /// Records the reason, sets the abort flag, and wakes any futures created
    /// by [`abort_future()`]. The reason is stored before the flag so a waiter
    /// that observes the flag also sees the reason.
    fn request_abort(&self, reason: Option<String>) {
        *self.abort_reason.write() = reason;
        self.abort_requested.store(true, Ordering::Release);
        self.abort_waker.wake();
    }

    /// Returns a future that resolves once the stream is aborted.
    ///
    /// # Usage
    ///
    /// Sink implementors should `select!` or `tokio::select!` on this future
    /// alongside their actual write work, so they can stop promptly if
    /// the stream aborts:
    ///
    /// ```ignore
    /// async fn write(
    ///     &mut self,
    ///     chunk: Vec<u8>,
    ///     controller: &mut WritableStreamDefaultController,
    /// ) -> StreamResult<()> {
    ///     tokio::select! {
    ///         _ = controller.abort_future() => {
    ///             Err(StreamError::Aborted(None))
    ///         }
    ///         _ = async {
    ///             // do actual I/O
    ///         } => {
    ///             Ok(())
    ///         }
    ///     }
    /// }
    /// ```
    pub fn abort_future(&self) -> impl std::future::Future<Output = ()> {
        let waker = self.abort_waker.clone();
        let flag = self.abort_requested.clone();
        poll_fn(move |cx| {
            if flag.load(Ordering::Acquire) {
                Poll::Ready(())
            } else {
                // register waker so it will be woken when request_abort() calls wake()
                waker.register(cx.waker());
                Poll::Pending
            }
        })
    }

    /// Races a future against the abort signal.
    ///
    /// If the abort fires first, returns `Err(StreamError::Aborted)`.
    /// Otherwise, returns the result of the future wrapped in `Ok`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// async fn write(
    ///     &mut self,
    ///     chunk: Vec<u8>,
    ///     controller: &mut WritableStreamDefaultController,
    /// ) -> StreamResult<()> {
    ///     controller.with_abort(async move {
    ///         // simulate slow write
    ///         tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    ///         Ok::<_, StreamError>(())
    ///     }).await
    /// }
    /// ```
    pub fn with_abort<F, T>(&self, fut: F) -> impl Future<Output = Result<T, StreamError>>
    where
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        let abort_fut = self.abort_future();

        // Box::pin makes it Unpin
        let fut = Box::pin(fut);
        let abort_fut = Box::pin(abort_fut);

        futures::future::select(fut, abort_fut).map(|either| match either {
            futures::future::Either::Left((value, _)) => Ok(value),
            futures::future::Either::Right((_unit, _)) => Err(StreamError::Aborted(None)),
        })
    }
}

pub struct WritableStreamBuilder<T, Sink>
where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    sink: Sink,
    strategy: crate::platform::BoxedStrategyStatic<T>,
    _phantom: PhantomData<fn() -> T>,
}

impl<T: MaybeSend + 'static, Sink> WritableStreamBuilder<T, Sink>
where
    Sink: WritableSink<T> + 'static,
{
    fn new(sink: Sink) -> Self {
        Self {
            sink,
            strategy: Box::new(CountQueuingStrategy::new(1)),
            _phantom: PhantomData,
        }
    }

    pub fn strategy<S: QueuingStrategy<T> + MaybeSend + 'static>(mut self, s: S) -> Self {
        self.strategy = Box::new(s);
        self
    }

    /// Return stream + future without spawning
    pub fn prepare(self) -> (WritableStream<T, Sink, Unlocked>, impl Future<Output = ()>) {
        WritableStream::new_inner(self.sink, self.strategy)
    }

    /// Spawn with an owned spawner function
    pub fn spawn<F, R>(self, spawn_fn: F) -> WritableStream<T, Sink, Unlocked>
    where
        F: FnOnce(crate::platform::PlatformFuture<'static, ()>) -> R,
    {
        let (stream, fut) = self.prepare();
        spawn_fn(Box::pin(fut));
        stream
    }

    /// Spawn using a static spawner function reference
    pub fn spawn_ref<F, R>(self, spawn_fn: &'static F) -> WritableStream<T, Sink, Unlocked>
    where
        F: Fn(crate::platform::PlatformFuture<'static, ()>) -> R,
    {
        let (stream, fut) = self.prepare();
        spawn_fn(Box::pin(fut));
        stream
    }
}

impl<T, Sink> WritableStream<T, Sink, Unlocked>
where
    T: MaybeSend + 'static,
    Sink: WritableSink<T> + 'static,
{
    /// Returns a builder for this writable stream
    pub fn builder(sink: Sink) -> WritableStreamBuilder<T, Sink> {
        WritableStreamBuilder::new(sink)
    }
}

#[cfg(test)]
mod tests {
    use super::super::super::CountQueuingStrategy;
    use super::*;
    use std::sync::Mutex;

    #[derive(Clone)]
    struct CountingSink {
        write_count: SharedPtr<Mutex<usize>>,
    }

    impl CountingSink {
        fn new() -> Self {
            CountingSink {
                write_count: SharedPtr::new(Mutex::new(0)),
            }
        }

        fn get_count(&self) -> usize {
            *self.write_count.lock().unwrap()
        }
    }

    impl WritableSink<Vec<u8>> for CountingSink {
        fn write(
            &mut self,
            _chunk: Vec<u8>,
            _controller: &mut WritableStreamDefaultController,
        ) -> impl std::future::Future<Output = StreamResult<()>> {
            let count = SharedPtr::clone(&self.write_count);
            async move {
                let mut guard = count.lock().unwrap();
                *guard += 1;
                Ok(())
            }
        }
    }

    #[tokio_localset_test::localset_test]
    async fn writes_chunks_to_underlying_sink() {
        let sink = CountingSink::new();
        let expected_writes = 2;
        let strategy = CountQueuingStrategy::new(2);

        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        writer
            .write(vec![1, 2, 3])
            .await
            .expect("first write failed");
        writer.write(vec![4, 5]).await.expect("second write failed");
        writer.close().await.expect("close failed");

        assert_eq!(sink.get_count(), expected_writes);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_basic_write_close_lifecycle() {
        #[derive(Clone)]
        struct TestSink {
            write_count: SharedPtr<Mutex<usize>>,
        }

        impl TestSink {
            fn new() -> Self {
                Self {
                    write_count: SharedPtr::new(Mutex::new(0)),
                }
            }

            fn get_count(&self) -> usize {
                *self.write_count.lock().unwrap()
            }
        }

        impl WritableSink<Vec<u8>> for TestSink {
            fn write(
                &mut self,
                _chunk: Vec<u8>,
                _controller: &mut WritableStreamDefaultController,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                let count = self.write_count.clone();
                async move {
                    let mut guard = count.lock().unwrap();
                    *guard += 1;
                    Ok(())
                }
            }
        }

        let sink = TestSink::new();
        let strategy = CountQueuingStrategy::new(10);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        writer.write(vec![1]).await.expect("write failed");
        writer.write(vec![2]).await.expect("write failed");
        writer.close().await.expect("close failed");

        assert_eq!(sink.get_count(), 2);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_close_and_abort_operations() {
        #[derive(Clone)]
        struct TestSink {
            closed: SharedPtr<Mutex<bool>>,
            aborted: SharedPtr<Mutex<Option<String>>>,
        }

        impl TestSink {
            fn new() -> Self {
                Self {
                    closed: SharedPtr::new(Mutex::new(false)),
                    aborted: SharedPtr::new(Mutex::new(None)),
                }
            }

            fn abort_reason(&self) -> Option<String> {
                self.aborted.lock().unwrap().clone()
            }
        }

        impl WritableSink<Vec<u8>> for TestSink {
            fn write(
                &mut self,
                _chunk: Vec<u8>,
                _controller: &mut WritableStreamDefaultController,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                async { Ok(()) }
            }

            fn close(self) -> impl std::future::Future<Output = StreamResult<()>> {
                let closed = self.closed.clone();
                async move {
                    *closed.lock().unwrap() = true;
                    Ok(())
                }
            }

            fn abort(
                &mut self,
                reason: Option<String>,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                let aborted = self.aborted.clone();
                async move {
                    *aborted.lock().unwrap() = reason;
                    Ok(())
                }
            }
        }

        let sink = TestSink::new();
        let strategy = CountQueuingStrategy::new(1);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        writer
            .abort(Some("test failure".to_string()))
            .await
            .expect("abort failed");

        assert_eq!(sink.abort_reason(), Some("test failure".to_string()));

        // Operations after abort should fail
        let write_result = writer.write(vec![1]).await;
        assert!(write_result.is_err(), "write after abort should fail");

        let close_result = writer.close().await;
        assert!(close_result.is_err(), "close after abort should fail");
    }

    #[tokio_localset_test::localset_test]
    async fn enforces_writer_lock_exclusivity() {
        let sink = CountingSink::new();
        let strategy = CountQueuingStrategy::new(10);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let (_locked_stream, writer1) = stream.get_writer().expect("first get_writer failed");

        // Second writer acquisition should fail
        let second_writer_result = stream.get_writer();
        assert!(
            second_writer_result.is_err(),
            "second get_writer should fail when locked"
        );

        writer1.release_lock().expect("release_lock failed");

        // Now acquisition should succeed
        let (_locked_stream2, _writer2) = stream
            .get_writer()
            .expect("get_writer after release failed");
    }

    #[tokio_localset_test::localset_test]
    async fn applies_backpressure_correctly() {
        struct SlowSink {
            calls: SharedPtr<Mutex<usize>>,
            unblock_notify: SharedPtr<tokio::sync::Notify>,
        }

        impl SlowSink {
            fn new() -> (Self, SharedPtr<tokio::sync::Notify>) {
                let notify = SharedPtr::new(tokio::sync::Notify::new());
                (
                    Self {
                        calls: SharedPtr::new(Mutex::new(0)),
                        unblock_notify: notify.clone(),
                    },
                    notify,
                )
            }
        }

        impl WritableSink<Vec<u8>> for SlowSink {
            fn write(
                &mut self,
                _chunk: Vec<u8>,
                _controller: &mut WritableStreamDefaultController,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                let calls_clone = self.calls.clone();
                let notify = self.unblock_notify.clone();

                async move {
                    {
                        let mut guard = calls_clone.lock().unwrap();
                        *guard += 1;
                    }
                    notify.notified().await;
                    Ok(())
                }
            }
        }

        let (sink, unblock_notify) = SlowSink::new();
        let strategy = CountQueuingStrategy::new(1);
        let stream = WritableStream::builder(sink)
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");
        let writer = SharedPtr::new(writer);

        // First write starts but blocks in sink.
        // With spec-correct inflight accounting, the in-flight write keeps
        // queue_total_size=1 (HWM=1), so backpressure is active immediately.
        let writer_clone = writer.clone();
        let write1 = tokio::task::spawn_local(async move { writer_clone.write(vec![1]).await });

        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        assert!(
            stream
                .backpressure
                .load(std::sync::atomic::Ordering::Acquire),
            "backpressure must be active while a write is in-flight (HWM=1)"
        );

        // Second write queues on top — backpressure remains active
        let writer_clone_2 = writer.clone();
        let write2 = tokio::task::spawn_local(async move { writer_clone_2.write(vec![2]).await });

        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        assert!(
            stream
                .backpressure
                .load(std::sync::atomic::Ordering::Acquire)
        );

        // Ready should be pending during backpressure
        let ready_fut = writer.ready();
        tokio::pin!(ready_fut);

        let waker = futures::task::noop_waker_ref();
        let mut cx = std::task::Context::from_waker(waker);
        assert!(matches!(
            ready_fut.as_mut().poll(&mut cx),
            std::task::Poll::Pending
        ));

        // Unblock writes
        unblock_notify.notify_one();
        write1
            .await
            .expect("write1 task failed")
            .expect("write1 failed");

        unblock_notify.notify_one();
        write2
            .await
            .expect("write2 task failed")
            .expect("write2 failed");

        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        assert!(
            !stream
                .backpressure
                .load(std::sync::atomic::Ordering::Acquire)
        );

        let ready_result = ready_fut.await;
        assert!(
            ready_result.is_ok(),
            "ready future should resolve after backpressure clears"
        );
    }

    #[derive(Clone, Default)]
    struct DummySink;

    impl WritableSink<Vec<u8>> for DummySink {
        fn write(
            &mut self,
            _chunk: Vec<u8>,
            _controller: &mut WritableStreamDefaultController,
        ) -> impl std::future::Future<Output = StreamResult<()>> {
            futures::future::ready(Ok(()))
        }
    }

    #[tokio_localset_test::localset_test]
    async fn desired_size_returns_none_when_closed_or_errored() {
        // closed → Some(0)
        {
            let stream = WritableStream::builder(DummySink::default())
                .spawn(tokio::task::spawn_local);
            let (_locked, writer) = stream.get_writer().expect("get writer");
            writer.close().await.expect("close");
            assert_eq!(
                writer.desired_size(),
                Some(0),
                "desired_size must be Some(0) when closed (not None)"
            );
        }

        // errored → None
        {
            #[derive(Clone, Default)]
            struct AlwaysFailSink;
            impl WritableSink<u32> for AlwaysFailSink {
                fn write(
                    &mut self,
                    _chunk: u32,
                    _controller: &mut WritableStreamDefaultController,
                ) -> impl std::future::Future<Output = StreamResult<()>> {
                    async { Err(StreamError::from("write failed")) }
                }
            }
            let stream = WritableStream::builder(AlwaysFailSink::default())
                .spawn(tokio::task::spawn_local);
            let (_locked, writer) = stream.get_writer().expect("get writer");
            let _ = writer.write(1u32).await; // force errored state
            assert_eq!(
                writer.desired_size(),
                None,
                "desired_size must be None when errored"
            );
        }
    }

    #[tokio_localset_test::localset_test]
    async fn propagates_sink_errors_to_stream() {
        #[derive(Clone)]
        struct FailingSink {
            error_flag: SharedPtr<Mutex<bool>>,
        }

        impl FailingSink {
            fn new() -> Self {
                Self {
                    error_flag: SharedPtr::new(Mutex::new(false)),
                }
            }

            fn did_error(&self) -> bool {
                *self.error_flag.lock().unwrap()
            }
        }

        impl WritableSink<Vec<u8>> for FailingSink {
            fn write(
                &mut self,
                _chunk: Vec<u8>,
                _ctrl: &mut WritableStreamDefaultController,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                let flag = self.error_flag.clone();
                async move {
                    *flag.lock().unwrap() = true;
                    Err("intentional write failure".into())
                }
            }
        }

        let sink = FailingSink::new();
        let strategy = CountQueuingStrategy::new(10);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        let write_result = writer.write(vec![1]).await;
        assert!(write_result.is_err(), "write should error on sink failure");
        assert!(sink.did_error(), "sink error flag should be set");

        assert!(stream.errored.load(std::sync::atomic::Ordering::Acquire));
        assert!(
            !stream
                .backpressure
                .load(std::sync::atomic::Ordering::Acquire)
        );

        let close_result = writer.close().await;
        assert!(
            close_result.is_err(),
            "close should error when stream errored"
        );

        let closed_future_result = writer.closed().await;
        assert!(
            closed_future_result.is_err(),
            "closed future should reject on error"
        );
    }

    #[tokio_localset_test::localset_test]
    async fn writer_enqueue_when_ready_respects_backpressure() {
        let sink = CountingSink::new();
        let strategy = CountQueuingStrategy::new(2);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        writer
            .enqueue_when_ready(vec![1, 2, 3])
            .await
            .expect("enqueue_when_ready failed");
        writer
            .enqueue_when_ready(vec![4, 5, 6])
            .await
            .expect("enqueue_when_ready failed");

        writer.close().await.expect("close failed");

        assert_eq!(sink.get_count(), 2);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_multiple_close_calls_idempotently() {
        let stream = WritableStream::builder(DummySink)
            .strategy(CountQueuingStrategy::new(10))
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        // Per spec: first close() succeeds; subsequent close() calls on an already-closed
        // or closing stream must reject (WPT close.any.js tests 24 and 25).
        writer.close().await.expect("first close failed");
        assert!(writer.close().await.is_err(), "second close() must reject after stream is closed");
        assert!(writer.close().await.is_err(), "third close() must reject after stream is closed");

        let closed_res = writer.closed().await;
        assert!(
            closed_res.is_ok(),
            "closed future should resolve after close"
        );
    }

    #[tokio_localset_test::localset_test]
    async fn rejects_operations_after_close() {
        let stream = WritableStream::builder(DummySink)
            .strategy(CountQueuingStrategy::new(10))
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");

        writer.close().await.expect("close failed");

        let write_err = writer.write(vec![1]).await;
        assert!(write_err.is_err(), "write after close must fail");
    }

    #[tokio_localset_test::localset_test]
    async fn ready_future_resolves_when_no_backpressure() {
        #[derive(Clone)]
        struct BlockSink {
            notify: SharedPtr<tokio::sync::Notify>,
            write_calls: SharedPtr<Mutex<usize>>,
        }

        impl BlockSink {
            fn new() -> (Self, SharedPtr<tokio::sync::Notify>) {
                let notify = SharedPtr::new(tokio::sync::Notify::new());
                (
                    Self {
                        notify: notify.clone(),
                        write_calls: SharedPtr::new(Mutex::new(0)),
                    },
                    notify,
                )
            }
        }

        impl WritableSink<Vec<u8>> for BlockSink {
            fn write(
                &mut self,
                _chunk: Vec<u8>,
                _ctrl: &mut WritableStreamDefaultController,
            ) -> impl std::future::Future<Output = StreamResult<()>> {
                let notify = self.notify.clone();
                let count_clone = self.write_calls.clone();
                async move {
                    *count_clone.lock().unwrap() += 1;
                    notify.notified().await;
                    Ok(())
                }
            }
        }

        let (sink, notify) = BlockSink::new();
        let strategy = CountQueuingStrategy::new(1usize);
        let stream = WritableStream::builder(sink)
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);
        let (_locked_stream, writer) = stream.get_writer().expect("failed to get writer");
        let writer = SharedPtr::new(writer);

        // Start first write
        let writer_clone = writer.clone();
        let write1 = tokio::task::spawn_local(async move { writer_clone.write(vec![1]).await });
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Queue more writes to trigger backpressure
        let writer_clone = writer.clone();
        let write2 = tokio::task::spawn_local(async move { writer_clone.write(vec![2]).await });
        let writer_clone = writer.clone();
        let write3 = tokio::task::spawn_local(async move { writer_clone.write(vec![3]).await });
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Ready should be pending during backpressure
        let mut ready = writer.ready();
        use futures::task::{Context, Poll};
        use std::pin::Pin;
        let waker = futures::task::noop_waker_ref();
        let mut cx = Context::from_waker(waker);
        let mut pinned = Pin::new(&mut ready);
        assert!(matches!(pinned.as_mut().poll(&mut cx), Poll::Pending));

        // Unblock writes
        notify.notify_waiters();
        write1
            .await
            .expect("write1 task failed")
            .expect("write1 failed");

        notify.notify_waiters();
        write2
            .await
            .expect("write2 task failed")
            .expect("write2 failed");

        notify.notify_waiters();
        write3
            .await
            .expect("write3 task failed")
            .expect("write3 failed");

        let ready_res = ready.await;
        assert!(
            ready_res.is_ok(),
            "ready future must resolve after backpressure clears"
        );
    }
}

#[cfg(test)]
mod sink_integration_tests {
    use super::*;
    use futures::{SinkExt, StreamExt, stream};
    use std::sync::Mutex;
    use std::time::Duration;

    #[derive(Debug, Clone)]
    struct TestSink {
        id: String,
        received_items: SharedPtr<Mutex<Vec<String>>>,
        write_delay: Option<Duration>,
        fail_on_write: Option<usize>,
        fail_on_close: bool,
        operation_log: SharedPtr<Mutex<Vec<String>>>,
    }

    impl TestSink {
        fn new(id: &str) -> Self {
            Self {
                id: id.to_string(),
                received_items: SharedPtr::new(Mutex::new(Vec::new())),
                write_delay: None,
                fail_on_write: None,
                fail_on_close: false,
                operation_log: SharedPtr::new(Mutex::new(Vec::new())),
            }
        }

        fn with_write_delay(mut self, delay: Duration) -> Self {
            self.write_delay = Some(delay);
            self
        }

        fn with_write_failure(mut self, fail_on_nth: usize) -> Self {
            self.fail_on_write = Some(fail_on_nth);
            self
        }

        fn with_close_failure(mut self) -> Self {
            self.fail_on_close = true;
            self
        }

        fn get_received_items(&self) -> Vec<String> {
            self.received_items.lock().unwrap().clone()
        }

        fn get_operation_log(&self) -> Vec<String> {
            self.operation_log.lock().unwrap().clone()
        }

        fn log_operation(&self, op: &str) {
            self.operation_log
                .lock()
                .unwrap()
                .push(format!("{}: {}", self.id, op));
        }
    }

    impl WritableSink<String> for TestSink {
        async fn start(
            &mut self,
            _controller: &mut WritableStreamDefaultController,
        ) -> StreamResult<()> {
            self.log_operation("start called");
            Ok(())
        }

        async fn write(
            &mut self,
            chunk: String,
            _controller: &mut WritableStreamDefaultController,
        ) -> StreamResult<()> {
            self.log_operation(&format!("write called with: {}", chunk));

            if let Some(delay) = self.write_delay {
                tokio::time::sleep(delay).await;
            }

            let current_count = self.received_items.lock().unwrap().len();
            if let Some(fail_on) = self.fail_on_write {
                if current_count >= fail_on {
                    self.log_operation(&format!("write failed on item {}", current_count + 1));
                    return Err(
                        format!("Intentional write failure on item {}", current_count + 1).into(),
                    );
                }
            }

            self.received_items.lock().unwrap().push(chunk.clone());
            self.log_operation(&format!("write completed: {}", chunk));
            Ok(())
        }

        async fn close(self) -> StreamResult<()> {
            self.log_operation("close called");

            if self.fail_on_close {
                self.log_operation("close failed");
                return Err("Intentional close failure".into());
            }

            self.log_operation("close completed");
            Ok(())
        }

        async fn abort(&mut self, reason: Option<String>) -> StreamResult<()> {
            let reason_str = reason.as_deref().unwrap_or("no reason");
            self.log_operation(&format!("abort called with reason: {}", reason_str));
            self.log_operation("abort completed");
            Ok(())
        }
    }

    struct TestQueuingStrategy {
        high_water_mark: usize,
    }

    impl TestQueuingStrategy {
        fn new(high_water_mark: usize) -> Self {
            Self { high_water_mark }
        }
    }

    impl QueuingStrategy<String> for TestQueuingStrategy {
        fn size(&self, _chunk: &String) -> usize {
            1
        }

        fn high_water_mark(&self) -> usize {
            self.high_water_mark
        }
    }

    #[tokio_localset_test::localset_test]
    async fn processes_sink_operations_in_order() {
        let sink = TestSink::new("basic");
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        assert!(
            sink_handle
                .poll_ready_unpin(&mut std::task::Context::from_waker(
                    &futures::task::noop_waker()
                ))
                .is_ready()
        );

        sink_handle.start_send_unpin("item1".to_string()).unwrap();
        sink_handle.start_send_unpin("item2".to_string()).unwrap();
        sink_handle.start_send_unpin("item3".to_string()).unwrap();

        sink_handle.flush().await.unwrap();

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1", "item2", "item3"]);

        sink_handle.close().await.unwrap();

        let log = sink.get_operation_log();
        assert!(log.contains(&"basic: start called".to_string()));
        assert!(log.contains(&"basic: write completed: item1".to_string()));
        assert!(log.contains(&"basic: close completed".to_string()));
    }

    #[tokio_localset_test::localset_test]
    async fn handles_backpressure_with_small_buffer() {
        let sink = TestSink::new("backpressure").with_write_delay(Duration::from_millis(10));
        let strategy = TestQueuingStrategy::new(2);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.start_send_unpin("item1".to_string()).unwrap();
        sink_handle.start_send_unpin("item2".to_string()).unwrap();

        let start = std::time::Instant::now();
        sink_handle.send("item3".to_string()).await.unwrap();

        assert!(start.elapsed() >= Duration::from_millis(10));
        sink_handle.close().await.unwrap();

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1", "item2", "item3"]);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_write_failures_appropriately() {
        let sink = TestSink::new("write_fail").with_write_failure(2);
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.send("item1".to_string()).await.unwrap();
        sink_handle.send("item2".to_string()).await.unwrap();

        let result = sink_handle.send("item3".to_string()).await;
        assert!(result.is_err(), "third write should fail");

        let ready_result = sink_handle.poll_ready_unpin(&mut std::task::Context::from_waker(
            &futures::task::noop_waker(),
        ));
        match ready_result {
            std::task::Poll::Ready(Err(_)) => {}
            other => panic!("Expected error state after write failure, got: {:?}", other),
        }

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1", "item2"]);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_close_failures() {
        let sink = TestSink::new("close_fail").with_close_failure();
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.send("item1".to_string()).await.unwrap();
        sink_handle.send("item2".to_string()).await.unwrap();

        let close_result = sink_handle.close().await;
        assert!(close_result.is_err(), "close should fail");

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1", "item2"]);
    }

    #[tokio_localset_test::localset_test]
    async fn rejects_operations_after_close() {
        let sink = TestSink::new("after_close");
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.send("item1".to_string()).await.unwrap();
        sink_handle.close().await.unwrap();

        let send_result = sink_handle.send("item2".to_string()).await;
        assert!(send_result.is_err(), "send after close should fail");

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1"]);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_abort_with_reason() {
        let sink = TestSink::new("abort_test");
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let (_locked_stream, writer) = stream.get_writer().unwrap();

        writer.write("item1".to_string()).await.unwrap();
        writer.write("item2".to_string()).await.unwrap();

        writer
            .abort(Some("Test abort reason".to_string()))
            .await
            .unwrap();

        let log = sink.get_operation_log();
        assert!(
            log.iter()
                .any(|entry| entry.contains("abort called with reason: Test abort reason"))
        );
        assert!(log.iter().any(|entry| entry.contains("abort completed")));

        let received = sink.get_received_items();
        assert_eq!(received, vec!["item1", "item2"]);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_multiple_close_calls_idempotently() {
        let sink = TestSink::new("multi_close");
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.send("item1".to_string()).await.unwrap();

        // Per spec: first close() succeeds; subsequent ones reject (WPT close.any.js tests 24/25)
        sink_handle.close().await.unwrap();
        assert!(sink_handle.close().await.is_err(), "second close() must reject");
        assert!(sink_handle.close().await.is_err(), "third close() must reject");

        let log = sink.get_operation_log();
        let close_count = log
            .iter()
            .filter(|entry| entry.contains("close called"))
            .count();
        assert_eq!(close_count, 1, "should only see one close operation");
    }

    #[tokio_localset_test::localset_test]
    async fn flush_waits_for_all_pending_writes() {
        let sink = TestSink::new("flush_test").with_write_delay(Duration::from_millis(50));
        let strategy = TestQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        sink_handle.start_send_unpin("item1".to_string()).unwrap();
        sink_handle.start_send_unpin("item2".to_string()).unwrap();
        sink_handle.start_send_unpin("item3".to_string()).unwrap();

        let start = std::time::Instant::now();
        sink_handle.flush().await.unwrap();
        let elapsed = start.elapsed();

        assert!(
            elapsed >= Duration::from_millis(30),
            "flush should wait for writes to complete"
        );

        let received_after_flush = sink.get_received_items();
        assert_eq!(received_after_flush, vec!["item1", "item2", "item3"]);

        sink_handle.close().await.unwrap();
    }

    #[tokio_localset_test::localset_test]
    async fn integrates_with_futures_stream() {
        let sink = TestSink::new("stream_integration");
        let strategy = TestQueuingStrategy::new(3);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        let mut items = stream::iter(vec!["a", "b", "c", "d", "e"])
            .map(|s| Ok::<String, StreamError>(s.to_string()));

        sink_handle.send_all(&mut items).await.unwrap();

        let received = sink.get_received_items();
        assert_eq!(received, vec!["a", "b", "c", "d", "e"]);
    }

    #[tokio_localset_test::localset_test]
    async fn handles_timeout_scenarios() {
        use tokio::time::timeout;

        let sink = TestSink::new("timeout_test").with_write_delay(Duration::from_millis(50));
        let strategy = TestQueuingStrategy::new(1);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let mut sink_handle = stream;

        let result = timeout(
            Duration::from_millis(10),
            sink_handle.send("slow_item".to_string()),
        )
        .await;
        assert!(result.is_err(), "operation should timeout");

        let _ = sink_handle.close().await;

        let received = sink.get_received_items();
        assert_eq!(
            received,
            vec!["slow_item"],
            "item should eventually be received"
        );
    }

    #[tokio_localset_test::localset_test]
    async fn handles_concurrent_operations() {
        use tokio::sync::Mutex;

        let sink = TestSink::new("concurrent");
        let strategy = TestQueuingStrategy::new(10);
        let stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let sink_handle = SharedPtr::new(Mutex::new(stream));
        let item_count = 100;
        let mut send_futures = Vec::new();

        for i in 0..item_count {
            let sink_clone = SharedPtr::clone(&sink_handle);
            let item = format!("item_{}", i);
            send_futures.push(tokio::task::spawn_local(async move {
                let mut sink = sink_clone.lock().await;
                sink.send(item).await
            }));
        }

        let results = futures::future::join_all(send_futures).await;
        for r in results {
            r.unwrap().unwrap();
        }

        sink_handle.lock().await.close().await.unwrap();

        let received = sink.get_received_items();
        assert_eq!(received.len(), item_count);

        for i in 0..item_count {
            let expected = format!("item_{}", i);
            assert!(received.contains(&expected), "Missing item: {}", expected);
        }
    }
}

#[cfg(test)]
mod async_write_integration_tests {
    use super::*;
    use futures::io::AsyncWriteExt;
    use std::io::ErrorKind;
    use std::sync::Mutex;
    use std::time::Duration;

    #[derive(Debug, Clone)]
    struct BytesSink {
        id: String,
        received_data: SharedPtr<Mutex<Vec<u8>>>,
        write_delay: Option<Duration>,
        fail_on_write: Option<usize>,
        fail_on_close: bool,
        operation_log: SharedPtr<Mutex<Vec<String>>>,
    }

    impl BytesSink {
        fn new(id: &str) -> Self {
            Self {
                id: id.to_string(),
                received_data: SharedPtr::new(Mutex::new(Vec::new())),
                write_delay: None,
                fail_on_write: None,
                fail_on_close: false,
                operation_log: SharedPtr::new(Mutex::new(Vec::new())),
            }
        }

        fn with_write_delay(mut self, delay: Duration) -> Self {
            self.write_delay = Some(delay);
            self
        }

        fn with_write_failure(mut self, fail_on_nth: usize) -> Self {
            self.fail_on_write = Some(fail_on_nth);
            self
        }

        fn get_received_data(&self) -> Vec<u8> {
            self.received_data.lock().unwrap().clone()
        }

        fn get_received_string(&self) -> String {
            String::from_utf8_lossy(&self.get_received_data()).to_string()
        }

        fn log_operation(&self, op: &str) {
            self.operation_log
                .lock()
                .unwrap()
                .push(format!("{}: {}", self.id, op));
        }
    }

    impl WritableSink<Vec<u8>> for BytesSink {
        async fn start(
            &mut self,
            _controller: &mut WritableStreamDefaultController,
        ) -> StreamResult<()> {
            self.log_operation("start called");
            Ok(())
        }

        async fn write(
            &mut self,
            chunk: Vec<u8>,
            _controller: &mut WritableStreamDefaultController,
        ) -> StreamResult<()> {
            self.log_operation(&format!("write called with {} bytes", chunk.len()));

            if let Some(delay) = self.write_delay {
                tokio::time::sleep(delay).await;
            }

            let current_writes = self
                .operation_log
                .lock()
                .unwrap()
                .iter()
                .filter(|entry| entry.contains("write called"))
                .count();

            if let Some(fail_on) = self.fail_on_write {
                if current_writes > fail_on {
                    self.log_operation("write failed");
                    return Err(
                        format!("Intentional write failure on write {}", current_writes).into(),
                    );
                }
            }

            self.received_data.lock().unwrap().extend_from_slice(&chunk);
            self.log_operation(&format!("write completed: {} bytes", chunk.len()));
            Ok(())
        }

        async fn close(self) -> StreamResult<()> {
            self.log_operation("close called");
            if self.fail_on_close {
                self.log_operation("close failed");
                return Err("Intentional close failure".into());
            }
            self.log_operation("close completed");
            Ok(())
        }

        async fn abort(&mut self, reason: Option<String>) -> StreamResult<()> {
            let reason_str = reason.as_deref().unwrap_or("no reason");
            self.log_operation(&format!("abort called with reason: {}", reason_str));
            self.log_operation("abort completed");
            Ok(())
        }
    }

    struct TestQueuingStrategy {
        high_water_mark: usize,
    }

    impl TestQueuingStrategy {
        fn new(high_water_mark: usize) -> Self {
            Self { high_water_mark }
        }
    }

    impl<T> QueuingStrategy<T> for TestQueuingStrategy {
        fn size(&self, _chunk: &T) -> usize {
            1
        }

        fn high_water_mark(&self) -> usize {
            self.high_water_mark
        }
    }

    #[tokio_localset_test::localset_test]
    async fn writes_bytes_through_async_write_interface() {
        let sink = BytesSink::new("basic");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let data1 = b"Hello, ";
        let data2 = b"World!";

        stream.write_all(data1).await.unwrap();
        stream.write_all(data2).await.unwrap();
        AsyncWriteExt::flush(&mut stream).await.unwrap();

        let received = sink.get_received_string();
        assert_eq!(received, "Hello, World!");

        stream.close().await.unwrap();
    }

    #[tokio_localset_test::localset_test]
    async fn handles_empty_writes_correctly() {
        let sink = BytesSink::new("empty");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let result = stream.write(&[]).await.unwrap();
        assert_eq!(result, 0, "empty write should return 0");

        stream.write_all(b"test").await.unwrap();
        stream.close().await.unwrap();

        let received = sink.get_received_string();
        assert_eq!(received, "test");
    }

    #[tokio_localset_test::localset_test]
    async fn handles_large_data_writes() {
        let sink = BytesSink::new("large");
        let strategy = TestQueuingStrategy::new(10);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let large_data = vec![b'X'; 10000];
        stream.write_all(&large_data).await.unwrap();
        AsyncWriteExt::flush(&mut stream).await.unwrap();

        let received = sink.get_received_data();
        assert_eq!(received.len(), 10000);
        assert!(received.iter().all(|&b| b == b'X'));

        stream.close().await.unwrap();
    }

    #[tokio_localset_test::localset_test]
    async fn processes_multiple_small_writes() {
        let sink = BytesSink::new("multi");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        for i in 0..10 {
            let data = format!("{}", i);
            stream.write_all(data.as_bytes()).await.unwrap();
        }
        AsyncWriteExt::flush(&mut stream).await.unwrap();

        let received = sink.get_received_string();
        assert_eq!(received, "0123456789");

        stream.close().await.unwrap();
    }

    #[tokio_localset_test::localset_test]
    async fn propagates_write_errors_correctly() {
        let sink = BytesSink::new("error").with_write_failure(2);
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        stream.write_all(b"write1").await.unwrap();
        stream.write_all(b"write2").await.unwrap();

        let result = stream.write_all(b"write3").await;
        assert!(result.is_err(), "third write should fail");

        let result = stream.write_all(b"write4").await;
        assert!(result.is_err(), "subsequent writes should also fail");

        let received = sink.get_received_string();
        assert_eq!(received, "write1write2");
    }

    #[tokio_localset_test::localset_test]
    async fn rejects_writes_after_close() {
        let sink = BytesSink::new("closed");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        stream.write_all(b"before_close").await.unwrap();
        stream.close().await.unwrap();

        let result = stream.write_all(b"after_close").await;
        assert!(result.is_err(), "write after close should fail");

        if let Err(e) = result {
            assert_eq!(e.kind(), ErrorKind::BrokenPipe);
        }

        let received = sink.get_received_string();
        assert_eq!(received, "before_close");
    }

    #[tokio_localset_test::localset_test]
    async fn applies_backpressure_correctly() {
        let sink = BytesSink::new("backpressure").with_write_delay(Duration::from_millis(50));
        let strategy = TestQueuingStrategy::new(2);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let start = std::time::Instant::now();

        for i in 0..5 {
            let data = format!("chunk{}", i);
            stream.write_all(data.as_bytes()).await.unwrap();
        }

        let elapsed = start.elapsed();
        assert!(
            elapsed >= Duration::from_millis(100),
            "should take time due to backpressure"
        );

        stream.close().await.unwrap();

        let received = sink.get_received_string();
        assert_eq!(received, "chunk0chunk1chunk2chunk3chunk4");
    }

    #[tokio_localset_test::localset_test]
    async fn handles_partial_writes() {
        let sink = BytesSink::new("partial");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let data = b"Hello, World!";

        let mut written = 0;
        while written < data.len() {
            let chunk_size = std::cmp::min(5, data.len() - written);
            let n = stream
                .write(&data[written..written + chunk_size])
                .await
                .unwrap();
            written += n;
            assert!(n > 0, "should make progress on each write");
        }

        AsyncWriteExt::flush(&mut stream).await.unwrap();
        stream.close().await.unwrap();

        let received = sink.get_received_string();
        assert_eq!(received, "Hello, World!");
    }

    #[tokio_localset_test::localset_test]
    async fn produces_appropriate_io_error_kinds() {
        // Test closed stream error
        {
            let sink = BytesSink::new("closed_error");
            let strategy = TestQueuingStrategy::new(5);
            let mut stream = WritableStream::builder(sink.clone())
                .strategy(strategy)
                .spawn(tokio::task::spawn_local);
            stream.close().await.unwrap();

            let result = stream.write_all(b"data").await;
            assert!(result.is_err());
            if let Err(e) = result {
                assert_eq!(e.kind(), ErrorKind::BrokenPipe);
            }
        }

        // Test error state
        {
            let sink = BytesSink::new("error_state").with_write_failure(0);
            let strategy = TestQueuingStrategy::new(5);
            let mut stream = WritableStream::builder(sink.clone())
                .strategy(strategy)
                .spawn(tokio::task::spawn_local);

            let _ = stream.write_all(b"data").await;

            let result = stream.write_all(b"more_data").await;
            assert!(result.is_err());
            if let Err(e) = result {
                assert_eq!(e.kind(), ErrorKind::Other);
            }
        }
    }

    #[tokio_localset_test::localset_test]
    async fn handles_binary_data_correctly() {
        let sink = BytesSink::new("binary");
        let strategy = TestQueuingStrategy::new(5);
        let mut stream = WritableStream::builder(sink.clone())
            .strategy(strategy)
            .spawn(tokio::task::spawn_local);

        let binary_data = vec![0u8, 1, 255, 128, 0, 42, 255];
        stream.write_all(&binary_data).await.unwrap();
        stream.close().await.unwrap();

        let received = sink.get_received_data();
        assert_eq!(received, binary_data);
    }
}

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

    #[cfg(feature = "send")]
    pub struct TestSink {
        pub written_data: crate::platform::SharedPtr<std::sync::Mutex<Vec<String>>>,
    }

    #[cfg(feature = "local")]
    pub struct TestSink {
        pub written_data: crate::platform::SharedPtr<std::cell::RefCell<Vec<String>>>,
    }

    impl TestSink {
        #[cfg(feature = "send")]
        pub fn new() -> Self {
            Self {
                written_data: crate::platform::SharedPtr::new(std::sync::Mutex::new(Vec::new())),
            }
        }

        #[cfg(feature = "local")]
        pub fn new() -> Self {
            Self {
                written_data: crate::platform::SharedPtr::new(std::cell::RefCell::new(Vec::new())),
            }
        }
    }

    // Helper to access written data regardless of feature
    #[cfg(feature = "send")]
    macro_rules! get_written_data {
        ($data:expr) => {
            $data.lock().unwrap()
        };
    }

    #[cfg(feature = "local")]
    macro_rules! get_written_data {
        ($data:expr) => {
            $data.borrow()
        };
    }

    impl WritableSink<String> for TestSink {
        #[cfg(feature = "send")]
        async fn write(
            &mut self,
            chunk: String,
            _controller: &mut super::WritableStreamDefaultController,
        ) -> Result<(), StreamError> {
            self.written_data.lock().unwrap().push(chunk);
            Ok(())
        }

        #[cfg(feature = "local")]
        async fn write(
            &mut self,
            chunk: String,
            _controller: &mut super::WritableStreamDefaultController,
        ) -> Result<(), StreamError> {
            self.written_data.borrow_mut().push(chunk);
            Ok(())
        }

        async fn close(self) -> Result<(), StreamError> {
            Ok(())
        }

        async fn abort(&mut self, _reason: Option<String>) -> Result<(), StreamError> {
            Ok(())
        }
    }

    #[tokio_localset_test::localset_test]
    async fn builder_spawn_creates_working_stream() {
        let sink = TestSink::new();
        let written_data = crate::platform::SharedPtr::clone(&sink.written_data);

        let stream = WritableStream::builder(sink).spawn(tokio::task::spawn_local);
        let (_, writer) = stream.get_writer().unwrap();

        writer.write("hello".to_string()).await.unwrap();
        writer.write("world".to_string()).await.unwrap();
        writer.close().await.unwrap();

        let data = get_written_data!(written_data);
        assert_eq!(*data, vec!["hello".to_string(), "world".to_string()]);
    }

    #[tokio_localset_test::localset_test]
    async fn builder_prepare_allows_manual_spawning() {
        let sink = TestSink::new();
        let written_data = crate::platform::SharedPtr::clone(&sink.written_data);

        let (stream, fut) = WritableStream::builder(sink).prepare();

        tokio::task::spawn_local(fut);

        let (_, writer) = stream.get_writer().unwrap();

        writer.write("test".to_string()).await.unwrap();
        writer.close().await.unwrap();

        let data = get_written_data!(written_data);
        assert_eq!(*data, vec!["test".to_string()]);
    }

    fn spawn_local_fn(fut: crate::platform::PlatformFuture<'static, ()>) {
        tokio::task::spawn_local(fut);
    }

    #[tokio_localset_test::localset_test]
    async fn builder_spawn_ref_works_with_function_pointer() {
        let sink = TestSink::new();
        let written_data = crate::platform::SharedPtr::clone(&sink.written_data);

        let stream = WritableStream::builder(sink).spawn_ref(&spawn_local_fn);
        let (_, writer) = stream.get_writer().unwrap();

        writer.write("reference".to_string()).await.unwrap();
        writer.close().await.unwrap();

        let data = get_written_data!(written_data);
        assert_eq!(*data, vec!["reference".to_string()]);
    }

    #[tokio_localset_test::localset_test]
    async fn builder_accepts_custom_strategy() {
        let sink = TestSink::new();
        let written_data = crate::platform::SharedPtr::clone(&sink.written_data);

        let custom_strategy = CountQueuingStrategy::new(5);
        let stream = WritableStream::builder(sink)
            .strategy(custom_strategy)
            .spawn(tokio::task::spawn_local);

        let (_, writer) = stream.get_writer().unwrap();

        writer.write("custom".to_string()).await.unwrap();
        writer.close().await.unwrap();

        let data = get_written_data!(written_data);
        assert_eq!(*data, vec!["custom".to_string()]);
    }
}