ibapi 5.5.0

An unofficial Rust client for the Interactive Brokers TWS API: market data, orders, and account data, with async (Tokio) and blocking clients for TWS and IB Gateway.
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
//! Async transport routing tests.
//!
//! Mirror of `transport/sync/tests.rs` routing tests on the async stack.
//! `MemoryStream` lets tests push response frames freely and drive
//! `bus.read_and_route_message()` directly. Frames use the
//! binary-text-payload framing that `parse_raw_message` expects post-floor-213:
//! `[4-byte BE msg_id][NUL-delimited remaining fields]`, produced by `body()`.

use crate::client::handshake_state::{HandshakeState, ServerVersion};
use crate::common::test_utils::helpers::order_status_frame;
use crate::orders::OrderStatusKind;
use std::sync::Arc;
use std::time::Duration;

use super::*;
use crate::client::ids::{OrderId, RequestId};
use crate::common::test_utils::helpers;
use crate::common::test_utils::helpers::{
    binary_proto, body, error_frame, execution_data_frame, farm_ok_frame_42, farm_ok_frame_unrouted, handshake_frames, NoticeTestData, FARM_OK_MSG,
};
use crate::connection::common::ConnectionProtocol;
use crate::connection::r#async::AsyncConnection;
use crate::messages::{encode_raw_length, OutgoingMessages, TRANSPORT_RECONNECT_CODE};
use crate::server_versions;
use crate::testdata::builders::contracts::contract_data;
use crate::testdata::builders::orders::order_bound;
use crate::testdata::builders::ResponseProtoEncoder;
use crate::transport::common::poison_with;

/// The client id the test buses connect with. Order fixtures default to
/// client 100, so a frame for this client's own order sets it explicitly.
const CLIENT_ID: i32 = 28;

/// Wrap a fresh `MemoryStream` in a stubbed `AsyncTcpMessageBus`. Pins
/// `server_version` to the current floor so `parse_raw_message` produces
/// binary-text-payload frames from `body()` inputs.
fn make_bus() -> (MemoryStream, Arc<AsyncTcpMessageBus<MemoryStream>>) {
    let stream = MemoryStream::default();
    let connection = AsyncConnection::stubbed(stream.clone(), CLIENT_ID);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);
    let bus = Arc::new(AsyncTcpMessageBus::new(connection));
    (stream, bus)
}

const TICK: Duration = Duration::from_millis(100);

/// `with_channel_capacity` reaches the per-request channels: a capacity-2
/// channel holds at most 2 queued frames, evicting the oldest (#779).
#[tokio::test]
async fn with_channel_capacity_bounds_request_channels() {
    let stream = MemoryStream::default();
    let connection = AsyncConnection::stubbed(stream.clone(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);
    let bus = Arc::new(AsyncTcpMessageBus::with_channel_capacity(connection, 2));

    let _sub = bus.send_request(RequestId::nth(1), vec![]).await.unwrap();
    let sender = bus.requests.sender(&RequestId::nth(1)).unwrap();
    for _ in 0..3 {
        sender.send(RoutedItem::Error(Error::Cancelled)).unwrap();
    }
    assert_eq!(sender.len(), 2, "capacity-2 channel retains only the newest 2 frames");
}

/// Send `capacity + 1` items through `send`, then expect `subscription` to
/// report exactly one dropped frame with `class`'s lag notice: proof that its
/// channel holds `capacity` and that the subscription carries `class`.
async fn assert_capacity_and_class(name: &str, subscription: &mut AsyncInternalSubscription, send: impl Fn(), capacity: usize, class: ChannelClass) {
    for _ in 0..=capacity {
        send();
    }
    let expected = match class {
        ChannelClass::MarketData => crate::messages::subscription_lag_notice(1),
        ChannelClass::Order | ChannelClass::OrderStream => crate::messages::order_lag_notice(1),
    };
    match subscription.next_routed().await {
        Some(RoutedItem::Notice(notice)) => assert_eq!(notice, expected, "{name}"),
        other => panic!("{name}: expected a one-frame lag notice, got {other:?}"),
    }
}

/// A small `channel_capacity` sizes market-data channels but never shrinks
/// the order-class floors, and each subscription carries its channel's class
/// (#896).
#[tokio::test]
async fn channel_classes_under_small_channel_capacity() {
    let stream = MemoryStream::default();
    let connection = AsyncConnection::stubbed(stream.clone(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);
    let bus = Arc::new(AsyncTcpMessageBus::with_channel_capacity(connection, 1));
    let cancelled = || RoutedItem::Error(Error::Cancelled);

    let mut market = bus.send_request(RequestId::nth(1), vec![]).await.unwrap();
    let sender = bus.requests.sender(&RequestId::nth(1)).unwrap();
    let send = || drop(sender.send(cancelled()));
    assert_capacity_and_class("request", &mut market, send, 1, ChannelClass::MarketData).await;

    let mut executions = bus.send_executions_request(RequestId::nth(2), vec![]).await.unwrap();
    let sender = bus.requests.sender(&RequestId::nth(2)).unwrap();
    let send = || drop(sender.send(cancelled()));
    assert_capacity_and_class("executions", &mut executions, send, ORDER_CAPACITY, ChannelClass::Order).await;

    let mut order = bus.send_order_request(OrderId::new(3), vec![]).await.unwrap();
    let sender = bus.orders.sender(&OrderId::new(3)).unwrap();
    let send = || drop(sender.send(cancelled()));
    assert_capacity_and_class("order", &mut order, send, ORDER_CAPACITY, ChannelClass::Order).await;

    let mut updates = bus.create_order_update_subscription().await.unwrap();
    let sender = bus.order_taps.updates_sender().unwrap();
    let send = || drop(sender.send(cancelled()));
    assert_capacity_and_class(
        "order update stream",
        &mut updates,
        send,
        ORDER_STREAM_CAPACITY,
        ChannelClass::OrderStream,
    )
    .await;

    // Shared channels: `notify_all` reaches every allocated one, so each is
    // subscribed only when its turn comes.
    let notify = || bus.shared_channels.notify_all(cancelled);
    let mut positions = bus.send_shared_request(OutgoingMessages::RequestPositions, vec![]).await.unwrap();
    assert_capacity_and_class("positions", &mut positions, notify, 1, ChannelClass::MarketData).await;
    let mut open_orders = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();
    assert_capacity_and_class("open orders", &mut open_orders, notify, ORDER_STREAM_CAPACITY, ChannelClass::OrderStream).await;
}

/// A `channel_capacity` above a floor raises the order-class channels too.
#[test]
fn channel_class_capacity() {
    assert_eq!(ChannelClass::MarketData.capacity(4), 4);
    assert_eq!(ChannelClass::Order.capacity(4), ORDER_CAPACITY);
    assert_eq!(ChannelClass::OrderStream.capacity(4), ORDER_STREAM_CAPACITY);
    let large = ORDER_STREAM_CAPACITY * 2;
    assert_eq!(ChannelClass::Order.capacity(large), large);
    assert_eq!(ChannelClass::OrderStream.capacity(large), large);
}

#[test]
fn shared_order_channels_are_order_class() {
    for request in [
        OutgoingMessages::RequestOpenOrders,
        OutgoingMessages::RequestAllOpenOrders,
        OutgoingMessages::RequestAutoOpenOrders,
        OutgoingMessages::RequestCompletedOrders,
    ] {
        assert_eq!(ChannelClass::of_shared(request), ChannelClass::OrderStream, "{request:?}");
    }
    assert_eq!(ChannelClass::of_shared(OutgoingMessages::RequestPositions), ChannelClass::MarketData);
}

/// A lag on an order-class subscription surfaces the order lag notice, and
/// clones keep the class.
#[tokio::test]
async fn order_class_lag_surfaces_order_lag_notice() {
    let (sender, receiver) = broadcast::channel(1);
    let mut subscription = AsyncInternalSubscription::new(receiver).class(ChannelClass::Order);
    let mut clone = subscription.clone();
    for _ in 0..4 {
        sender.send(RoutedItem::Error(Error::Cancelled)).unwrap();
    }

    for sub in [&mut subscription, &mut clone] {
        match sub.next_routed().await {
            Some(RoutedItem::Notice(notice)) => assert_eq!(notice, crate::messages::order_lag_notice(3)),
            other => panic!("expected order lag notice, got {other:?}"),
        }
    }
}

/// Receive next message with a deadline; panics with context if the channel
/// times out, closes, or surfaces an error.
async fn next_message(sub: &mut AsyncInternalSubscription) -> ResponseMessage {
    tokio::time::timeout(TICK, sub.next())
        .await
        .expect("subscription got no message before timeout")
        .expect("subscription closed")
        .expect("subscription error")
}

/// Two in-flight `send_request` subscriptions: responses arrive in reverse order
/// and each subscription receives only its own message.
#[tokio::test]
async fn request_id_correlation_with_interleaved_responses() {
    let (stream, bus) = make_bus();

    let (id_a, id_b) = (RequestId::nth(100), RequestId::nth(200));
    let mut sub_a = bus.send_request(id_a, vec![]).await.unwrap();
    let mut sub_b = bus.send_request(id_b, vec![]).await.unwrap();

    // HistogramData (msg_id 89): request_id at field index 1.
    stream.push_inbound(body(&format!("89|{id_b}|payload-b|")));
    stream.push_inbound(body(&format!("89|{id_a}|payload-a|")));

    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    let msg_a = next_message(&mut sub_a).await;
    let msg_b = next_message(&mut sub_b).await;
    assert_eq!(msg_a.peek_int(1).unwrap(), id_a.raw());
    assert_eq!(msg_b.peek_int(1).unwrap(), id_b.raw());

    // No cross-talk.
    assert!(sub_a.try_next_routed().is_none(), "sub_a received an extra message");
    assert!(sub_b.try_next_routed().is_none(), "sub_b received an extra message");
}

/// Same shape as the request_id test but on the orders channel: two in-flight
/// `send_order_request` subscriptions, OrderStatus responses interleaved.
#[tokio::test]
async fn order_id_correlation_with_interleaved_responses() {
    let (stream, bus) = make_bus();

    let mut sub_a = bus.send_order_request(OrderId::from(11), vec![]).await.unwrap();
    let mut sub_b = bus.send_order_request(OrderId::from(22), vec![]).await.unwrap();

    // OrderStatus carries `order_id` at proto tag 1.
    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OrderStatus as i32,
        &crate::proto::OrderStatus {
            order_id: Some(22),
            status: Some("Filled".into()),
            ..Default::default()
        },
    ));
    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OrderStatus as i32,
        &crate::proto::OrderStatus {
            order_id: Some(11),
            status: Some("Submitted".into()),
            ..Default::default()
        },
    ));

    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    let msg_a = next_message(&mut sub_a).await;
    let msg_b = next_message(&mut sub_b).await;
    assert_eq!(msg_a.order_id(), Some(11));
    assert_eq!(msg_b.order_id(), Some(22));

    assert!(sub_a.try_next_routed().is_none(), "sub_a received an extra message");
    assert!(sub_b.try_next_routed().is_none(), "sub_b received an extra message");
}

/// Shared-channel fan-out: `RequestOpenOrders`, `RequestAllOpenOrders`, and
/// `RequestAutoOpenOrders` all map to `[OpenOrder, OrderStatus, OpenOrderEnd]`
/// in `CHANNEL_MAPPINGS`. The `OrderAndShared` strategy fans every `OpenOrder`
/// out to each shared subscriber, with or without an order id.
#[tokio::test]
async fn shared_channel_fan_out_for_open_orders() {
    let (stream, bus) = make_bus();

    let mut sub_open = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();
    let mut sub_all = bus.send_shared_request(OutgoingMessages::RequestAllOpenOrders, vec![]).await.unwrap();
    let mut sub_auto = bus.send_shared_request(OutgoingMessages::RequestAutoOpenOrders, vec![]).await.unwrap();

    for order_id in [Some(42), None] {
        stream.push_inbound(binary_proto(
            crate::messages::IncomingMessages::OpenOrder as i32,
            &crate::proto::OpenOrder {
                order_id,
                ..Default::default()
            },
        ));
        bus.read_and_route_message().await.unwrap();

        for (name, sub) in [("open", &mut sub_open), ("all", &mut sub_all), ("auto", &mut sub_auto)] {
            let msg = next_message(sub).await;
            assert_eq!(msg.message_type(), crate::messages::IncomingMessages::OpenOrder, "sub_{name}");
            assert_eq!(msg.order_id(), order_id, "sub_{name}");
        }
    }
}

/// An order with a live `send_order_request` route still answers an
/// open-orders request: `OpenOrder` and `OrderStatus` reach both (#1033).
#[tokio::test]
async fn routed_order_also_reaches_open_orders() {
    use crate::messages::IncomingMessages as M;
    let (stream, bus) = make_bus();

    let mut order = bus.send_order_request(OrderId::from(42), vec![]).await.unwrap();
    let mut open_orders = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();

    stream.push_inbound(binary_proto(
        M::OpenOrder as i32,
        &crate::proto::OpenOrder {
            order_id: Some(42),
            ..Default::default()
        },
    ));
    stream.push_inbound(binary_proto(
        M::OrderStatus as i32,
        &crate::proto::OrderStatus {
            order_id: Some(42),
            status: Some("Submitted".into()),
            ..Default::default()
        },
    ));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    for (name, sub) in [("order", &mut order), ("open orders", &mut open_orders)] {
        for expected in [M::OpenOrder, M::OrderStatus] {
            let msg = next_message(sub).await;
            assert_eq!(msg.message_type(), expected, "{name}");
            assert_eq!(msg.order_id(), Some(42), "{name}");
        }
        assert!(sub.try_next_routed().is_none(), "{name} received an extra message");
    }
}

/// Shared-channel routing: `send_shared_request` for `RequestCurrentTime`
/// receives the `CurrentTime` response via the channel mapping in
/// `shared_channel_configuration::CHANNEL_MAPPINGS`.
#[tokio::test]
async fn shared_channel_routing_current_time() {
    let (stream, bus) = make_bus();

    let mut sub = bus.send_shared_request(OutgoingMessages::RequestCurrentTime, vec![]).await.unwrap();

    stream.push_inbound(body("49|1|1700000000|"));
    bus.read_and_route_message().await.unwrap();

    let msg = next_message(&mut sub).await;
    assert_eq!(msg.peek_int(0).unwrap(), 49);
    assert_eq!(msg.peek_int(2).unwrap(), 1_700_000_000);
}

/// EOF on the stream surfaces from `read_and_route_message` as `Io(UnexpectedEof)`.
/// The bus does not silently spin on the closed queue. (The production
/// `process_messages` loop catches this error and triggers reconnect; here we
/// drive `read_and_route_message` once to verify the error is surfaced rather
/// than swallowed.)
#[tokio::test]
async fn read_and_route_surfaces_eof() {
    let (stream, bus) = make_bus();

    stream.hang_up();
    let err = bus.read_and_route_message().await.expect_err("dispatch should surface an error");
    assert!(
        matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::UnexpectedEof),
        "unexpected error: {err:?}"
    );
}

/// `AsyncMessageBus::send_message` writes through to the connection.
#[tokio::test]
async fn send_message_writes_through() {
    let (stream, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    mb.send_message(b"global-cancel-bytes".to_vec()).await.unwrap();

    let captured = stream.captured();
    assert!(captured.windows(b"global-cancel-bytes".len()).any(|w| w == b"global-cancel-bytes"));
}

/// `AsyncMessageBus::create_order_update_subscription` returns
/// `AlreadySubscribed` on duplicate calls.
#[tokio::test]
async fn create_order_update_subscription_is_unique() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    let _first = mb.create_order_update_subscription().await.unwrap();
    let err = mb.create_order_update_subscription().await.err().expect("duplicate fails");
    assert!(matches!(err, Error::AlreadySubscribed), "got: {err:?}");
}

/// After shutdown, a new order-update stream is refused rather than stored
/// as a sender nothing will ever drop (#871).
#[tokio::test]
async fn create_order_update_subscription_after_shutdown_fails() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();
    mb.ensure_shutdown().await;

    let err = mb.create_order_update_subscription().await.err().expect("subscribe after shutdown");
    assert!(matches!(err, Error::Shutdown), "got: {err:?}");
    assert!(bus.order_taps.updates_lease().is_none());
}

/// Shutdown ends a live notice stream, and one opened afterwards is already
/// ended. Before, the connection kept the only sender alive and both waited
/// forever (#871).
#[tokio::test]
async fn notice_stream_ends_on_shutdown() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();
    let mut live = mb.notice_subscribe();

    mb.ensure_shutdown().await;

    let ended = tokio::time::timeout(Duration::from_millis(500), live.next()).await;
    assert!(matches!(ended, Ok(None)), "live stream: {ended:?}");

    let mut late = mb.notice_subscribe();
    bus.connection.notice_broadcaster.broadcast(Notice::synthesized(-1, "late".into()));
    let ended = tokio::time::timeout(Duration::from_millis(500), late.next()).await;
    assert!(matches!(ended, Ok(None)), "late stream: {ended:?}");
}

/// `request_shutdown_sync` (the `Drop` path) ends notice streams too.
#[tokio::test]
async fn notice_stream_ends_on_request_shutdown_sync() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();
    let mut live = mb.notice_subscribe();

    mb.request_shutdown_sync();

    let ended = tokio::time::timeout(Duration::from_millis(500), live.next()).await;
    assert!(matches!(ended, Ok(None)), "live stream: {ended:?}");
}

/// `Client::drop` calls `request_shutdown_sync`, which must end a live
/// order-update stream (whose subscription holds the bus).
#[tokio::test]
async fn order_update_stream_ends_on_request_shutdown_sync() {
    let (_, bus) = make_bus();
    bus.clone().process_messages().expect("process_messages");
    let mut updates = bus.create_order_update_subscription().await.unwrap();

    bus.request_shutdown_sync();

    let drained = tokio::time::timeout(Duration::from_millis(500), async { while updates.next().await.is_some() {} }).await;
    assert!(drained.is_ok(), "order-update stream did not end");
}

/// Like the sync bus, shutdown fails every kind of subscription with
/// `Error::Shutdown` before ending it, so a reader can tell shutdown from a
/// stream that simply closed. Through `request_shutdown_sync`, the
/// `Client::drop` path, with no dispatcher to finish it.
#[tokio::test]
async fn shutdown_fails_every_subscription_then_ends_it() {
    let (_, bus) = make_bus();
    let subscriptions = [
        ("request", bus.send_request(RequestId::nth(1), vec![]).await.unwrap()),
        ("order", bus.send_order_request(OrderId::from(7), vec![]).await.unwrap()),
        (
            "shared",
            bus.send_shared_request(OutgoingMessages::RequestPositions, vec![]).await.unwrap(),
        ),
        ("order update", bus.create_order_update_subscription().await.unwrap()),
    ];

    bus.request_shutdown_sync();

    for (name, mut subscription) in subscriptions {
        let first = tokio::time::timeout(TICK, subscription.next_routed()).await.expect(name);
        assert!(matches!(first, Some(RoutedItem::Error(Error::Shutdown))), "{name}: {first:?}");
        let end = tokio::time::timeout(TICK, subscription.next_routed()).await.expect(name);
        assert!(end.is_none(), "{name} did not end: {end:?}");
    }
}

/// A `place_order` or `executions` subscription that has received an
/// execution is also held in the execution-id map, so the commission report
/// that follows can reach it. Shutdown must drop that alias too: a sender left
/// there kept the channel open, and the subscription's reader waited forever
/// after `Client::drop`.
#[tokio::test]
async fn subscriptions_with_executions_end_on_request_shutdown_sync() {
    let (stream, bus) = make_bus();
    let mut order = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    let mut executions = bus.send_request(RequestId::nth(99), vec![]).await.unwrap();

    // Mapped by order id, and by request id where no order channel matches.
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 7, "exec-order"));
    stream.push_inbound(execution_data_frame(CLIENT_ID, RequestId::nth(99).raw(), 0, "exec-request"));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();
    for (name, sub) in [("order", &mut order), ("executions", &mut executions)] {
        let message = next_message(sub).await;
        assert_eq!(message.message_type(), crate::messages::IncomingMessages::ExecutionData, "{name}");
    }
    assert_eq!(bus.executions.len(), 2, "both executions mapped");

    bus.clone().process_messages().expect("process_messages");
    bus.request_shutdown_sync();

    for (name, sub) in [("order", &mut order), ("executions", &mut executions)] {
        let drained = tokio::time::timeout(Duration::from_millis(500), async { while sub.next().await.is_some() {} }).await;
        assert!(drained.is_ok(), "{name} subscription with an execution did not end");
    }
    assert!(bus.executions.is_empty());
}

/// A frame with message id `-2` is `IncomingMessages::Shutdown`: the router
/// shuts the bus down and the dispatcher exits. Like `Client::drop`, that path
/// reaches `request_shutdown` with no reconnect reset before it, so it must
/// drop execution-id aliases as well.
#[tokio::test]
async fn shutdown_frame_ends_subscriptions_with_executions() {
    let (stream, bus) = make_bus();
    let mut order = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 7, "exec-order"));
    bus.read_and_route_message().await.unwrap();
    let message = next_message(&mut order).await;
    assert_eq!(message.message_type(), crate::messages::IncomingMessages::ExecutionData);

    bus.clone().process_messages().expect("process_messages");
    stream.push_inbound((crate::messages::IncomingMessages::Shutdown as i32).to_be_bytes().to_vec());

    let drained = tokio::time::timeout(Duration::from_millis(500), async { while order.next().await.is_some() {} }).await;
    assert!(drained.is_ok(), "order subscription with an execution did not end");
    assert!(!bus.is_connected());
    assert!(bus.executions.is_empty());
}

/// An order-update stream dropped while its cleanup signal is still queued
/// leaves a sender with no receivers behind. An order frame arriving in that
/// window fails the order-update send, and routing carries on: the frame still
/// reaches the order's own subscription.
#[tokio::test]
async fn order_frame_routes_while_a_dropped_order_update_stream_awaits_cleanup() {
    let (stream, bus) = make_bus();
    let mut order = bus.send_order_request(OrderId::from(22), vec![]).await.unwrap();
    let updates = bus.create_order_update_subscription().await.unwrap();

    // Stall the cleanup task, so the stream's cleanup signal cannot run
    // before the frame is routed.
    let cleanup_gate = bus.cleanup_gate.lock().await;
    drop(updates);
    assert!(bus.order_taps.updates_lease().is_some(), "the dropped stream is still registered");

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OrderStatus as i32,
        &crate::proto::OrderStatus {
            order_id: Some(22),
            status: Some("Filled".into()),
            ..Default::default()
        },
    ));
    tokio::time::timeout(Duration::from_millis(500), bus.read_and_route_message())
        .await
        .expect("routing blocked")
        .unwrap();

    assert_eq!(next_message(&mut order).await.order_id(), Some(22));
    drop(cleanup_gate);
}

/// `AsyncMessageBus::is_connected` reflects the bus state — true initially,
/// false after `request_shutdown_sync` flips the flag.
#[tokio::test]
async fn is_connected_reflects_shutdown_flag() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    assert!(mb.is_connected());
    mb.request_shutdown_sync();
    assert!(!mb.is_connected());
}

/// Receive next routed envelope with a deadline.
async fn next_routed(sub: &mut AsyncInternalSubscription) -> RoutedItem {
    tokio::time::timeout(TICK, sub.next_routed())
        .await
        .expect("subscription got no item before timeout")
        .expect("subscription closed")
}

/// Warning code (2104) bound to a real request_id is delivered as a
/// `RoutedItem::Notice` to the owning subscription — stream stays open.
#[tokio::test]
async fn warning_with_request_id_delivers_notice() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(42);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(error_frame(request_id.raw(), 2104, FARM_OK_MSG));
    bus.read_and_route_message().await.unwrap();

    let item = next_routed(&mut sub).await;
    match item {
        RoutedItem::Notice(notice) => {
            assert_eq!(notice.request_id, Some(request_id.raw()));
            assert_eq!(notice.code, 2104);
            assert_eq!(notice.message, "Market data farm connection is OK:usfarm");
        }
        other => panic!("expected RoutedItem::Notice, got {other:?}"),
    }

    // Stream stays open: a follow-up data message is delivered.
    stream.push_inbound(body(&format!("89|{request_id}|payload|")));
    bus.read_and_route_message().await.unwrap();
    let item = next_routed(&mut sub).await;
    assert!(matches!(item, RoutedItem::Response(_)), "got: {item:?}");
}

/// Data advisory (code 10167) bound to a real request_id is informational:
/// TWS proceeds with delayed data, so it is delivered as a `RoutedItem::Notice`
/// and the stream stays open for the follow-up data — not routed as an error
/// that would terminate the subscription.
#[tokio::test]
async fn data_advisory_with_request_id_keeps_stream_open() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(42);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    let code = 10167; // data advisory: "Displaying delayed market data."
    stream.push_inbound(error_frame(request_id.raw(), code, "Displaying delayed market data."));
    bus.read_and_route_message().await.unwrap();

    let item = next_routed(&mut sub).await;
    match item {
        RoutedItem::Notice(notice) => {
            assert_eq!(notice.code, code);
            assert!(notice.is_data_advisory());
        }
        other => panic!("expected RoutedItem::Notice, got {other:?}"),
    }

    // Stream stays open: the delayed data the advisory promised arrives.
    stream.push_inbound(body(&format!("89|{request_id}|payload|")));
    bus.read_and_route_message().await.unwrap();
    let item = next_routed(&mut sub).await;
    assert!(matches!(item, RoutedItem::Response(_)), "got: {item:?}");
}

/// Hard error (code 200) bound to a real request_id is delivered as a
/// `RoutedItem::Error` to the owning subscription.
#[tokio::test]
async fn hard_error_with_request_id_terminates_subscription() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(42);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(error_frame(request_id.raw(), 200, "No security definition found"));
    bus.read_and_route_message().await.unwrap();

    let item = next_routed(&mut sub).await;
    match item {
        RoutedItem::Error(Error::Notice(notice)) => {
            assert_eq!(notice.request_id, Some(request_id.raw()));
            assert_eq!(notice.code, 200);
            assert_eq!(notice.message, "No security definition found");
        }
        other => panic!("expected RoutedItem::Error(Notice), got {other:?}"),
    }
}

/// Warning with `UNSPECIFIED_REQUEST_ID` has no owner — log only, no channel
/// write to an in-flight subscription.
#[tokio::test]
async fn warning_with_unspecified_id_is_log_only() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_request(RequestId::nth(42), vec![]).await.unwrap();

    stream.push_inbound(error_frame(-1, 2104, FARM_OK_MSG));
    bus.read_and_route_message().await.unwrap();

    assert!(sub.try_next_routed().is_none(), "unrouted notice must not be delivered to a subscription");
}

/// Request-less hard error (id = -1) is uncorrelatable, so it fails every
/// in-flight *one-shot* shared request fast (`RequestIds` here) while leaving
/// *streaming* shared requests (`RequestPositions`) untouched — and still fans
/// out to the global notice stream. Regression for #694 (callers hung forever).
#[tokio::test]
async fn request_less_hard_error_fails_one_shot_and_spares_stream() {
    let (stream, bus) = make_bus();
    let mut notice_stream = bus.notice_subscribe();
    let mut one_shot = bus.send_shared_request(OutgoingMessages::RequestIds, vec![]).await.unwrap();
    let mut streaming = bus.send_shared_request(OutgoingMessages::RequestPositions, vec![]).await.unwrap();

    // 321 "read-only mode" is the live-reproduced case; non-warning, id = -1.
    stream.push_inbound(error_frame(-1, 321, READ_ONLY_MSG));
    bus.read_and_route_message().await.unwrap();

    // One-shot caller fails fast with the real error instead of hanging. Read via
    // the legacy `next()` projection — the same path `next_valid_order_id` and the
    // `one_shot_shared` helper consume — so a `Some(Err(..))` surfaces to callers.
    let item = tokio::time::timeout(TICK, one_shot.next())
        .await
        .expect("one-shot got no error before timeout")
        .expect("subscription closed");
    match item {
        Err(Error::Notice(notice)) => {
            assert_eq!(notice.code, 321);
            assert_eq!(notice.message, READ_ONLY_MSG);
        }
        other => panic!("expected Err(Notice), got {other:?}"),
    }
    // Streaming shared subscription is not terminated by the unrelated error.
    assert!(
        streaming.try_next_routed().is_none(),
        "streaming shared sub must not receive the request-less error"
    );
    // Global notice stream still observes it.
    let notice = tokio::time::timeout(TICK, notice_stream.next()).await.unwrap().unwrap();
    assert_eq!(notice.request_id, None);
    assert_eq!(notice.code, 321);
}

/// A request-less *warning* stays notice-only: it must not fail an in-flight
/// one-shot shared request (only non-warning hard errors trip fail-fast).
#[tokio::test]
async fn request_less_warning_does_not_fail_one_shot() {
    let (stream, bus) = make_bus();
    let mut one_shot = bus.send_shared_request(OutgoingMessages::RequestIds, vec![]).await.unwrap();

    stream.push_inbound(error_frame(-1, 2104, FARM_OK_MSG));
    bus.read_and_route_message().await.unwrap();

    assert!(one_shot.try_next_routed().is_none(), "warning must not fail a one-shot shared request");
}

/// A request-less *system message* (1102, connectivity restored with data
/// maintained) reports a connection-wide state change, not a failed request.
/// It must reach the notice stream without failing in-flight one-shot shared
/// requests - `managed_accounts`, `server_time`, `next_valid_order_id`.
#[tokio::test]
async fn request_less_system_message_does_not_fail_one_shot() {
    let (stream, bus) = make_bus();
    let mut notice_stream = bus.notice_subscribe();
    let mut one_shot = bus.send_shared_request(OutgoingMessages::RequestIds, vec![]).await.unwrap();

    let code = crate::messages::CONNECTIVITY_RESTORED_DATA_MAINTAINED_CODE;
    stream.push_inbound(error_frame(-1, code, CONNECTIVITY_RESTORED_MSG));
    bus.read_and_route_message().await.unwrap();

    assert!(
        one_shot.try_next_routed().is_none(),
        "system message must not fail a one-shot shared request"
    );

    let notice = tokio::time::timeout(TICK, notice_stream.next()).await.unwrap().unwrap();
    assert_eq!(notice.code, code);
    assert!(notice.is_system_message());
}

/// A notice bound to an id below the request floor is an order's: it goes to
/// the order subscription for that id.
#[tokio::test]
async fn warning_with_order_id_routes_to_order_channel() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();

    stream.push_inbound(error_frame(7, 2104, "Order warning"));
    bus.read_and_route_message().await.unwrap();

    let item = next_routed(&mut sub).await;
    match item {
        RoutedItem::Notice(notice) => {
            assert_eq!(notice.code, 2104);
            assert_eq!(notice.message, "Order warning");
        }
        other => panic!("expected RoutedItem::Notice, got {other:?}"),
    }
}

// ---- end-to-end Subscription consumer tests for Notice delivery ----
//
// Mirror the dispatcher routing tests above, one layer up: drive bytes through
// the production dispatcher and assert via the public async `Subscription<T>`
// API that the consumer sees `SubscriptionItem::Notice` / `Err(_)` / `None` as
// expected.

use crate::subscriptions::r#async::Subscription;
use crate::subscriptions::{DecoderContext, StreamDecoder, SubscriptionItem, SubscriptionItemStreamExt};
use futures::StreamExt;

const CONNECTIVITY_RESTORED_MSG: &str = "Connectivity between IB and TWS has been restored - data maintained.";
const READ_ONLY_MSG: &str = "The API interface is currently in Read-Only mode.";

async fn make_request_subscription(request_id: RequestId) -> (MemoryStream, Arc<AsyncTcpMessageBus<MemoryStream>>, Subscription<NoticeTestData>) {
    let (stream, bus) = make_bus();
    let internal = bus.send_request(request_id, vec![]).await.unwrap();
    let sub = Subscription::new_from_internal(internal, bus.clone(), Some(request_id.raw()), None, DecoderContext::default());
    (stream, bus, sub)
}

async fn make_order_subscription(order_id: OrderId) -> (MemoryStream, Arc<AsyncTcpMessageBus<MemoryStream>>, Subscription<NoticeTestData>) {
    let (stream, bus) = make_bus();
    let internal = bus.send_order_request(order_id, vec![]).await.unwrap();
    let sub = Subscription::new_from_internal(internal, bus.clone(), None, Some(order_id.value()), DecoderContext::default());
    (stream, bus, sub)
}

/// Number of length-prefixed frames in `captured` whose payload is `payload`.
fn count_frames(captured: &[u8], payload: &[u8]) -> usize {
    let mut rest = captured;
    let mut count = 0;
    while rest.len() >= 4 {
        let len = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
        let (frame, tail) = rest[4..].split_at(len);
        count += usize::from(frame == payload);
        rest = tail;
    }
    count
}

/// Wait until `captured` holds `expected` frames equal to `payload`, or the
/// deadline passes. Async `Drop` spawns the cancel send, so a count can only
/// be asserted after that task has had a chance to run.
async fn wait_for_frames(stream: &MemoryStream, payload: &[u8], expected: usize) -> usize {
    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    loop {
        let count = count_frames(&stream.captured(), payload);
        if count >= expected || std::time::Instant::now() >= deadline {
            return count;
        }
        tokio::time::sleep(Duration::from_millis(1)).await;
    }
}

/// TWS keeps one positions stream per client (`CancelPositions` carries no id),
/// so with two live `RequestPositions` subscriptions the first drop must not
/// write the cancel, the survivor must keep receiving, and the last drop writes
/// exactly one cancel. Subscriptions are built through the production
/// `SubscriptionBuilder::send_shared`.
#[tokio::test]
async fn shared_subscription_cancel_waits_for_last_subscriber() {
    use crate::accounts::PositionUpdate;
    use crate::client::builders::r#async::SubscriptionBuilder;

    let (stream, bus) = make_bus();
    let cancel = <PositionUpdate as StreamDecoder<PositionUpdate>>::cancel_message(0, None, None).unwrap();

    let make = || async {
        let message_bus: Arc<dyn AsyncMessageBus> = bus.clone();
        SubscriptionBuilder::<PositionUpdate>::new_with_components(DecoderContext::default(), message_bus)
            .send_shared(OutgoingMessages::RequestPositions, b"positions".to_vec())
            .await
            .unwrap()
    };
    let first = make().await;
    let mut second = make().await;

    drop(first);
    // Give a wrongly spawned cancel time to land before asserting its absence.
    tokio::time::sleep(Duration::from_millis(20)).await;
    assert_eq!(
        count_frames(&stream.captured(), &cancel),
        0,
        "cancel written while a subscription is still live"
    );

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::PositionEnd as i32,
        &crate::proto::PositionEnd {},
    ));
    bus.read_and_route_message().await.unwrap();
    let item = next_item(&mut second).await.expect("survivor received nothing").unwrap();
    assert!(matches!(item, SubscriptionItem::Data(PositionUpdate::PositionEnd)), "got: {item:?}");

    drop(second);
    assert_eq!(wait_for_frames(&stream, &cancel, 1).await, 1, "last drop must write exactly one cancel");
}

/// `Orders` has no cancel message, so its drop writes nothing; the count for
/// its request type must still return to zero, or a later cancel for the
/// type would be withheld. The release runs in the task `Drop` spawns.
///
/// Built the way `open_orders()` builds it: `send_shared_request` then
/// `new_from_internal_simple`, with nothing naming the request type. The
/// drop can only reach the count because the subscription derives the type
/// from the internal subscription's cleanup signal.
#[tokio::test]
async fn shared_subscription_without_cancel_message_releases_count() {
    use crate::orders::Orders;

    let (stream, bus) = make_bus();
    let count = || async { bus.shared_channels.live(OutgoingMessages::RequestOpenOrders).await };

    let internal = bus
        .send_shared_request(OutgoingMessages::RequestOpenOrders, b"open-orders".to_vec())
        .await
        .unwrap();
    let sub = Subscription::<Orders>::new_from_internal_simple(internal, bus.clone(), DecoderContext::default());
    assert_eq!(count().await, 1);

    drop(sub);
    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    while count().await != 0 && std::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(1)).await;
    }
    assert_eq!(count().await, 0, "count leaked for a type with no cancel message");
    assert_eq!(count_frames(&stream.captured(), b"open-orders"), 1, "only the request was written");
}

/// A shared subscription that reads its end marker still releases its count on
/// drop: the cancel-after-end guard applies only to request-id subscriptions.
#[tokio::test]
async fn shared_subscription_ended_natively_still_releases_count() {
    use crate::orders::Orders;

    let (stream, bus) = make_bus();
    let count = || async { bus.shared_channels.live(OutgoingMessages::RequestOpenOrders).await };

    let internal = bus
        .send_shared_request(OutgoingMessages::RequestOpenOrders, b"open-orders".to_vec())
        .await
        .unwrap();
    let mut sub = Subscription::<Orders>::new_from_internal_simple(internal, bus.clone(), DecoderContext::default());

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OpenOrderEnd as i32,
        &crate::proto::OpenOrdersEnd {},
    ));
    bus.read_and_route_message().await.unwrap();
    assert!(next_item(&mut sub).await.is_none(), "OpenOrderEnd ends the stream");
    assert!(sub.ended_natively());

    drop(sub);
    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    while count().await != 0 && std::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(1)).await;
    }
    assert_eq!(count().await, 0, "count leaked after a natural end");
}

type PositionsSubscription = Subscription<crate::accounts::PositionUpdate>;

async fn positions_subscription(bus: &Arc<AsyncTcpMessageBus<MemoryStream>>) -> PositionsSubscription {
    let internal = bus
        .send_shared_request(OutgoingMessages::RequestPositions, b"positions".to_vec())
        .await
        .unwrap();
    Subscription::new_from_internal(internal, bus.clone(), None, None, DecoderContext::default())
}

fn positions_cancel() -> Vec<u8> {
    <crate::accounts::PositionUpdate as StreamDecoder<crate::accounts::PositionUpdate>>::cancel_message(0, None, None).unwrap()
}

async fn positions_live(bus: &Arc<AsyncTcpMessageBus<MemoryStream>>) -> usize {
    bus.shared_channels.live(OutgoingMessages::RequestPositions).await
}

/// Wait until the count for `RequestPositions` reaches `expected`, or the
/// deadline passes; the release runs in the task `Drop` spawns.
async fn wait_for_positions_live(bus: &Arc<AsyncTcpMessageBus<MemoryStream>>, expected: usize) -> usize {
    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    loop {
        let live = positions_live(bus).await;
        if live == expected || std::time::Instant::now() >= deadline {
            return live;
        }
        tokio::time::sleep(Duration::from_millis(1)).await;
    }
}

/// A shared subscription dropped on a thread with no runtime still writes its
/// cancel and releases its count, so the next subscription of the type can
/// cancel too (#848). Before, the count leaked and every later drop of the
/// type withheld its cancel until the next reconnect.
#[tokio::test]
async fn shared_subscription_dropped_outside_runtime_cancels() {
    let (stream, bus) = make_bus();
    let cancel = positions_cancel();

    let sub = positions_subscription(&bus).await;
    std::thread::spawn(move || drop(sub)).join().expect("drop outside a runtime panicked");
    assert_eq!(wait_for_frames(&stream, &cancel, 1).await, 1, "off-runtime drop must write the cancel");

    drop(positions_subscription(&bus).await);
    assert_eq!(
        wait_for_frames(&stream, &cancel, 2).await,
        2,
        "count leaked: next drop withheld its cancel"
    );
}

/// A reset ends every shared subscription, so the count restarts at zero for
/// the new session: a resubscription made after the reset is the only live one
/// and its drop writes the cancel even while the dead handle is still held.
#[tokio::test]
async fn shared_count_restarts_after_reset() {
    let (stream, bus) = make_bus();
    let cancel = positions_cancel();

    let old = positions_subscription(&bus).await;
    bus.reset_channels().await;
    assert_eq!(positions_live(&bus).await, 0);

    let new = positions_subscription(&bus).await;
    drop(new);
    assert_eq!(wait_for_frames(&stream, &cancel, 1).await, 1, "cancel withheld by a dead handle");

    drop(old);
    tokio::time::sleep(Duration::from_millis(20)).await;
    assert_eq!(count_frames(&stream.captured(), &cancel), 1, "dead handle wrote a cancel");
}

/// A handle from before the reset is dead: its drop must neither cancel on the
/// new session, which has no such stream, nor touch the new session's count.
#[tokio::test]
async fn stale_shared_handle_neither_cancels_nor_decrements() {
    let (stream, bus) = make_bus();
    let cancel = positions_cancel();

    let old = positions_subscription(&bus).await;
    bus.reset_channels().await;
    let new = positions_subscription(&bus).await;

    drop(old);
    tokio::time::sleep(Duration::from_millis(20)).await;
    assert_eq!(count_frames(&stream.captured(), &cancel), 0, "dead handle wrote a cancel");
    assert_eq!(positions_live(&bus).await, 1);

    drop(new);
    assert_eq!(wait_for_frames(&stream, &cancel, 1).await, 1);
    assert_eq!(wait_for_positions_live(&bus, 0).await, 0);
}

/// The open-orders channel maps three response types. A reset that walked the
/// channels by response type failed it three times; it must fail it once.
#[tokio::test]
async fn reset_fails_a_shared_channel_once() {
    let (_stream, bus) = make_bus();
    let mut open_orders = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();

    bus.reset_channels().await;

    let items: Vec<_> = std::iter::from_fn(|| open_orders.try_next_routed()).collect();
    assert!(matches!(items.as_slice(), [RoutedItem::Error(Error::ConnectionReset)]), "{items:?}");
}

type AccountUpdatesSubscription = Subscription<crate::accounts::AccountUpdate>;

fn account(name: &str) -> crate::accounts::types::AccountId {
    crate::accounts::types::AccountId(name.to_string())
}

// The request bytes name the account so each account's writes can be counted.
fn account_updates_request(name: &str) -> Vec<u8> {
    format!("account-updates {name}").into_bytes()
}

async fn account_updates_subscription(bus: &Arc<AsyncTcpMessageBus<MemoryStream>>, name: &str) -> Result<AccountUpdatesSubscription, Error> {
    let internal = bus.send_account_updates_request(&account(name), account_updates_request(name)).await?;
    Ok(Subscription::new_from_internal(
        internal,
        bus.clone(),
        None,
        None,
        DecoderContext::default(),
    ))
}

fn account_updates_cancel() -> Vec<u8> {
    <crate::accounts::AccountUpdate as StreamDecoder<crate::accounts::AccountUpdate>>::cancel_message(0, None, None).unwrap()
}

async fn account_updates_slot(bus: &AsyncTcpMessageBus<MemoryStream>) -> Option<crate::accounts::types::AccountId> {
    bus.shared_channels.account_updates().await
}

/// The same account again shares the one TWS stream: both requests go out,
/// and only the last cancel frees the slot.
#[tokio::test]
async fn account_updates_same_account_shares() {
    let (stream, bus) = make_bus();
    let cancel = account_updates_cancel();

    let first = account_updates_subscription(&bus, "DU1").await.unwrap();
    let second = account_updates_subscription(&bus, "DU1").await.unwrap();
    assert_eq!(count_frames(&stream.captured(), &account_updates_request("DU1")), 2);
    assert_eq!(bus.shared_channels.live(OutgoingMessages::RequestAccountData).await, 2);

    first.cancel().await;
    assert_eq!(
        count_frames(&stream.captured(), &cancel),
        0,
        "cancel written while a subscription is still live"
    );
    assert_eq!(account_updates_slot(&bus).await, Some(account("DU1")));

    second.cancel().await;
    assert_eq!(count_frames(&stream.captured(), &cancel), 1);
    assert_eq!(account_updates_slot(&bus).await, None);
}

/// TWS has one account-updates slot: a second account would switch the live
/// subscription to its data. It is refused before anything is written, and
/// the live subscription keeps its data.
#[tokio::test]
async fn account_updates_other_account_refused() {
    use crate::accounts::AccountUpdate;

    let (stream, bus) = make_bus();
    let mut first = account_updates_subscription(&bus, "DU1").await.unwrap();

    let refused = account_updates_subscription(&bus, "DU2").await.map(|_| ());
    assert!(
        matches!(&refused, Err(Error::AccountUpdatesInUse { active, requested }) if *active == account("DU1") && *requested == account("DU2")),
        "got: {refused:?}"
    );
    assert_eq!(
        count_frames(&stream.captured(), &account_updates_request("DU2")),
        0,
        "refused request was written"
    );
    assert_eq!(bus.shared_channels.live(OutgoingMessages::RequestAccountData).await, 1);

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::AccountDownloadEnd as i32,
        &crate::proto::AccountDataEnd {
            account_name: Some("DU1".to_string()),
        },
    ));
    bus.read_and_route_message().await.unwrap();
    let item = next_item(&mut first).await.expect("live subscription received nothing").unwrap();
    assert!(matches!(item, SubscriptionItem::Data(AccountUpdate::End)), "got: {item:?}");
}

/// Once the last subscription of an account is cancelled, another account is
/// accepted. `cancel().await` releases before it returns; a plain drop
/// releases in a spawned task, so it is not used to switch.
#[tokio::test]
async fn account_updates_other_account_after_cancel() {
    let (stream, bus) = make_bus();

    let first = account_updates_subscription(&bus, "DU1").await.unwrap();
    first.cancel().await;
    assert_eq!(count_frames(&stream.captured(), &account_updates_cancel()), 1);

    let _second = account_updates_subscription(&bus, "DU2").await.unwrap();
    assert_eq!(count_frames(&stream.captured(), &account_updates_request("DU2")), 1);
    assert_eq!(account_updates_slot(&bus).await, Some(account("DU2")));
}

/// A reset ends every subscription, so the slot is free on the new session,
/// and a dead handle's drop must not free the new account's slot.
#[tokio::test]
async fn account_updates_slot_restarts_after_reset() {
    let (stream, bus) = make_bus();

    let old = account_updates_subscription(&bus, "DU1").await.unwrap();
    bus.reset_channels().await;
    let _new = account_updates_subscription(&bus, "DU2").await.unwrap();

    drop(old);
    tokio::time::sleep(Duration::from_millis(20)).await;
    assert_eq!(
        count_frames(&stream.captured(), &account_updates_cancel()),
        0,
        "dead handle wrote a cancel"
    );
    assert_eq!(account_updates_slot(&bus).await, Some(account("DU2")));
}

/// Bound a `Subscription::next()` await with the test tick so a missing item
/// surfaces as a panic rather than hanging the test thread.
async fn next_item<T: StreamDecoder<T> + Send + 'static>(sub: &mut Subscription<T>) -> Option<Result<SubscriptionItem<T>, Error>> {
    tokio::time::timeout(TICK, sub.next())
        .await
        .expect("subscription got no item before timeout")
}

/// Code 2104 on a request id surfaces as `SubscriptionItem::Notice` without
/// terminating; a follow-up data message arrives normally on the same stream.
#[tokio::test]
async fn subscription_notice_delivery_request_keyed() {
    let (stream, bus, mut subscription) = make_request_subscription(RequestId::nth(42)).await;

    stream.push_inbound(farm_ok_frame_42());
    bus.read_and_route_message().await.unwrap();

    match next_item(&mut subscription).await {
        Some(Ok(SubscriptionItem::Notice(notice))) => {
            assert_eq!(notice.code, 2104);
            assert_eq!(notice.message, FARM_OK_MSG);
        }
        other => panic!("expected SubscriptionItem::Notice, got {other:?}"),
    }

    stream.push_inbound(body(&format!("89|{}|payload|", RequestId::nth(42))));
    bus.read_and_route_message().await.unwrap();
    match next_item(&mut subscription).await {
        Some(Ok(SubscriptionItem::Data(_))) => {}
        other => panic!("expected SubscriptionItem::Data, got {other:?}"),
    }
}

/// Partial entitlement can precede delayed Greeks on the same request.
#[tokio::test]
async fn subscription_10091_preserves_later_option_computation() {
    use crate::contracts::tick_types::TickType;
    use crate::market_data::realtime::TickTypes;
    use crate::testdata::builders::{market_data::tick_option_computation, ResponseProtoEncoder};

    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(42);
    let internal = bus.send_request(request_id, vec![]).await.unwrap();
    let mut subscription = Subscription::new_from_internal(internal, bus.clone(), Some(request_id.raw()), None, DecoderContext::default());
    let computation = tick_option_computation()
        .request_id(request_id.raw())
        .tick_type(TickType::DelayedModelOption as i32)
        .tick_attrib(0)
        .delta(0.5)
        .to_proto();

    // Both frames are dispatched before polling: the error must not hide
    // an already-queued computation on the same request.
    stream.push_inbound(error_frame(request_id.raw(), 10091, "Synthetic partial-entitlement advisory"));
    stream.push_inbound(binary_proto(IncomingMessages::TickOptionComputation as i32, &computation));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    match next_item(&mut subscription).await {
        Some(Ok(SubscriptionItem::Notice(notice))) => {
            assert_eq!(notice.request_id, Some(request_id.raw()));
            assert_eq!(notice.code, 10091);
            assert_eq!(notice.message, "Synthetic partial-entitlement advisory");
            assert!(notice.is_data_advisory());
        }
        other => panic!("expected nonterminal 10091 notice, got {other:?}"),
    }
    match next_item(&mut subscription).await {
        Some(Ok(SubscriptionItem::Data(TickTypes::OptionComputation(greeks)))) => {
            assert_eq!(greeks.field, TickType::DelayedModelOption);
            assert_eq!(greeks.tick_attribute, Some(0));
            assert_eq!(greeks.delta, Some(0.5));
            assert_eq!(greeks.implied_volatility, None);
        }
        other => panic!("option computation after 10091 lost: {other:?}"),
    }
}

/// A depth-book reset (317) precedes the rows that rebuild it on the same
/// request. It must not end the depth stream (#806), and arrives as
/// `MarketDepths::Reset` so `filter_data()` keeps it (#899).
#[tokio::test]
async fn subscription_317_yields_reset_then_rows() {
    use crate::market_data::realtime::MarketDepths;
    use crate::testdata::builders::{market_data::market_depth_response, ResponseProtoEncoder};

    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(42);
    let internal = bus.send_request(request_id, vec![]).await.unwrap();
    let subscription: Subscription<MarketDepths> =
        Subscription::new_from_internal(internal, bus.clone(), Some(request_id.raw()), None, DecoderContext::default());
    let row = market_depth_response()
        .request_id(request_id.raw())
        .position(0)
        .operation(0)
        .side(1)
        .price(101.5)
        .size(3.0)
        .to_proto();

    // Both frames are dispatched before polling: the reset must not hide the
    // first row of the rebuilt book.
    stream.push_inbound(error_frame(
        request_id.raw(),
        317,
        "Market depth data has been RESET. Please empty deep book contents before applying any new entries.",
    ));
    stream.push_inbound(binary_proto(IncomingMessages::MarketDepth as i32, &row));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    let mut depths = subscription.filter_data();
    match depths.next().await {
        Some(Ok(MarketDepths::Reset)) => {}
        other => panic!("expected MarketDepths::Reset, got {other:?}"),
    }
    match depths.next().await {
        Some(Ok(MarketDepths::MarketDepth(depth))) => {
            assert_eq!(depth.position, 0);
            assert_eq!(depth.operation, 0);
            assert_eq!(depth.side, 1);
            assert_eq!(depth.price, 101.5);
            assert_eq!(depth.size, 3.0);
        }
        other => panic!("market depth row after 317 lost: {other:?}"),
    }
}

/// Hard error (code 200) surfaces as `Some(Err(_))`; subsequent reads return `None`.
#[tokio::test]
async fn subscription_hard_error_terminates_stream() {
    let (stream, bus, mut subscription) = make_request_subscription(RequestId::nth(42)).await;

    let request_id = RequestId::nth(42);
    stream.push_inbound(error_frame(request_id.raw(), 200, "No security definition found"));
    stream.push_inbound(body(&format!("89|{request_id}|payload|")));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    match next_item(&mut subscription).await {
        Some(Err(Error::Notice(notice))) => {
            assert_eq!(notice.code, 200);
            assert_eq!(notice.message, "No security definition found");
        }
        other => panic!("expected Some(Err(Error::Notice)), got {other:?}"),
    }

    assert!(next_item(&mut subscription).await.is_none(), "terminal error must hide even queued data");
}

/// Order-keyed notice: an id below the request floor reaches the order subscription.
#[tokio::test]
async fn subscription_notice_delivery_order_keyed() {
    let (stream, bus, mut subscription) = make_order_subscription(OrderId::from(7)).await;

    stream.push_inbound(error_frame(7, 2109, "Outside RTH order warning"));
    bus.read_and_route_message().await.unwrap();

    match next_item(&mut subscription).await {
        Some(Ok(SubscriptionItem::Notice(notice))) => {
            assert_eq!(notice.code, 2109);
            assert_eq!(notice.message, "Outside RTH order warning");
        }
        other => panic!("expected SubscriptionItem::Notice, got {other:?}"),
    }
}

/// Unrouted notice (UNSPECIFIED request_id) is log-only; no channel write.
#[tokio::test]
async fn subscription_unspecified_notice_not_delivered() {
    let (stream, bus, mut subscription) = make_request_subscription(RequestId::nth(42)).await;

    stream.push_inbound(farm_ok_frame_unrouted());
    bus.read_and_route_message().await.unwrap();

    let item = tokio::time::timeout(TICK, subscription.next()).await;
    assert!(item.is_err(), "unrouted notice must not be delivered to a subscription, got {item:?}");
}

/// `data_stream()` filters `SubscriptionItem::Notice` and yields only data.
#[tokio::test]
async fn subscription_data_stream_filters_notices() {
    let (stream, bus, subscription) = make_request_subscription(RequestId::nth(42)).await;

    let request_id = RequestId::nth(42);
    stream.push_inbound(body(&format!("89|{request_id}|first|")));
    stream.push_inbound(farm_ok_frame_42());
    stream.push_inbound(body(&format!("89|{request_id}|second|")));
    for _ in 0..3 {
        bus.read_and_route_message().await.unwrap();
    }

    let collected: Vec<_> = subscription.filter_data().take(2).collect().await;
    assert_eq!(collected.len(), 2, "filter_data() must yield the two data items");
    for item in collected {
        assert!(matches!(item, Ok(NoticeTestData)), "unexpected stream item");
    }
}

// ---- end-to-end NoticeStream tests (PR 5) ----
//
// Mirror of the sync `notice_stream` dispatcher tests on the async stack.

/// An unrouted warning is delivered to a `notice_stream` subscriber.
#[tokio::test]
async fn notice_stream_receives_unrouted_warning() {
    let (stream, bus) = make_bus();
    let mut notice_stream = bus.notice_subscribe();

    stream.push_inbound(farm_ok_frame_unrouted());
    bus.read_and_route_message().await.unwrap();

    let notice = tokio::time::timeout(TICK, notice_stream.next())
        .await
        .expect("notice not delivered before timeout")
        .expect("stream closed early");
    assert_eq!(notice.code, 2104);
    assert_eq!(notice.message, FARM_OK_MSG);
}

/// Two `notice_subscribe` calls each receive every unrouted notice.
#[tokio::test]
async fn notice_stream_fans_out_to_multiple_subscribers() {
    let (stream, bus) = make_bus();
    let mut s1 = bus.notice_subscribe();
    let mut s2 = bus.notice_subscribe();

    stream.push_inbound(farm_ok_frame_unrouted());
    bus.read_and_route_message().await.unwrap();

    let n1 = tokio::time::timeout(TICK, s1.next()).await.unwrap().unwrap();
    let n2 = tokio::time::timeout(TICK, s2.next()).await.unwrap().unwrap();
    assert_eq!(n1.code, 2104);
    assert_eq!(n2.code, 2104);
}

/// Severity-agnostic: an unrouted hard error also fans out.
#[tokio::test]
async fn notice_stream_receives_unrouted_hard_error() {
    let (stream, bus) = make_bus();
    let mut notice_stream = bus.notice_subscribe();

    stream.push_inbound(error_frame(-1, 504, "Not connected"));
    bus.read_and_route_message().await.unwrap();

    let notice = tokio::time::timeout(TICK, notice_stream.next()).await.unwrap().unwrap();
    assert_eq!(notice.code, 504);
}

/// A routed notice (real `request_id`) goes to the owning subscription, NOT
/// to the global notice stream.
#[tokio::test]
async fn notice_stream_skips_routed_notices() {
    let (stream, bus, mut subscription) = make_request_subscription(RequestId::nth(42)).await;
    let mut notice_stream = bus.notice_subscribe();

    stream.push_inbound(farm_ok_frame_42());
    bus.read_and_route_message().await.unwrap();

    // Routed to the owner.
    let item = tokio::time::timeout(TICK, subscription.next()).await.unwrap();
    assert!(matches!(item, Some(Ok(SubscriptionItem::Notice(_)))), "owner missed notice");

    // NOT delivered to the global stream.
    let leaked = tokio::time::timeout(TICK, notice_stream.next()).await;
    assert!(leaked.is_err(), "routed notice leaked to global stream");
}

/// Late subscribers don't see prior notices (no replay buffer on broadcast).
#[tokio::test]
async fn notice_stream_late_subscriber_misses_prior() {
    let (stream, bus) = make_bus();

    stream.push_inbound(farm_ok_frame_unrouted());
    bus.read_and_route_message().await.unwrap();

    // Subscribe AFTER the broadcast.
    let mut late = bus.notice_subscribe();
    let leaked = tokio::time::timeout(TICK, late.next()).await;
    assert!(leaked.is_err(), "late subscriber should not see prior notices");
}

// ---- order-routing strategy tests ----
//
// Mirror of the sync-side `process_orders` strategy tests. `route_to_order_channel`
// dispatches by `order_routing_strategy(message_type)`; each strategy has a
// different fallback order (order_id → request_id, by execution_id, shared-only).

#[tokio::test]
async fn execution_data_routes_to_order_channel() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();

    stream.push_inbound(execution_data_frame(CLIENT_ID, RequestId::nth(99).raw(), 7, "exec-1"));
    bus.read_and_route_message().await.unwrap();

    let msg = next_message(&mut sub).await;
    assert_eq!(msg.order_id(), Some(7));
}

#[tokio::test]
async fn execution_data_falls_back_to_request_channel() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(99);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(execution_data_frame(CLIENT_ID, request_id.raw(), 7, "exec-1"));
    bus.read_and_route_message().await.unwrap();

    let msg = next_message(&mut sub).await;
    assert_eq!(msg.request_id(), Some(request_id.raw()));
}

#[tokio::test]
async fn execution_data_orphan_dropped() {
    let (stream, bus) = make_bus();
    let mut unrelated = bus.send_request(RequestId::nth(42), vec![]).await.unwrap();

    stream.push_inbound(execution_data_frame(CLIENT_ID, RequestId::nth(99).raw(), 7, "exec-1"));
    bus.read_and_route_message().await.unwrap();

    assert!(unrelated.try_next_routed().is_none(), "unrelated sub got an orphan message");
}

#[tokio::test]
async fn execution_data_end_routes_to_order_channel() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::ExecutionDataEnd as i32,
        &crate::proto::ExecutionDetailsEnd { req_id: Some(7) },
    ));
    bus.read_and_route_message().await.unwrap();

    next_message(&mut sub).await;
}

/// ExecutionDataEnd's `req_id` doubles as the order_id key for the router; a
/// request-range id misses the order channel and falls back to the request
/// channel.
#[tokio::test]
async fn execution_data_end_falls_back_to_request_channel() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(7);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::ExecutionDataEnd as i32,
        &crate::proto::ExecutionDetailsEnd {
            req_id: Some(request_id.raw()),
        },
    ));
    bus.read_and_route_message().await.unwrap();

    next_message(&mut sub).await;
}

#[tokio::test]
async fn execution_data_end_orphan_dropped() {
    let (stream, bus) = make_bus();
    let mut unrelated = bus.send_request(RequestId::nth(42), vec![]).await.unwrap();

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::ExecutionDataEnd as i32,
        &crate::proto::ExecutionDetailsEnd {
            req_id: Some(RequestId::nth(999).raw()),
        },
    ));
    bus.read_and_route_message().await.unwrap();

    assert!(unrelated.try_next_routed().is_none(), "unrelated sub got an orphan end");
}

/// `ByExecutionId`: the prior ExecutionData stores `exec-abc → order_id 7`'s
/// sender, and the CommissionsReport rides that mapping back to the same sub.
#[tokio::test]
async fn commission_report_routes_via_execution_id_mapping() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();

    stream.push_inbound(execution_data_frame(CLIENT_ID, RequestId::nth(99).raw(), 7, "exec-abc"));
    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::CommissionsReport as i32,
        &crate::proto::CommissionAndFeesReport {
            exec_id: Some("exec-abc".into()),
            ..Default::default()
        },
    ));

    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    let exec_msg = next_message(&mut sub).await;
    assert_eq!(exec_msg.message_type(), crate::messages::IncomingMessages::ExecutionData);
    let commission = next_message(&mut sub).await;
    assert_eq!(commission.message_type(), crate::messages::IncomingMessages::CommissionsReport);
}

#[tokio::test]
async fn commission_report_without_mapping_dropped() {
    let (stream, bus) = make_bus();
    let mut unrelated = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::CommissionsReport as i32,
        &crate::proto::CommissionAndFeesReport {
            exec_id: Some("exec-not-mapped".into()),
            ..Default::default()
        },
    ));
    bus.read_and_route_message().await.unwrap();

    assert!(unrelated.try_next_routed().is_none(), "unrelated sub got an unmapped commission");
}

/// #880: an execution-id alias holds a sender clone, so it must go when the
/// order or request subscription that owns it is dropped.
#[tokio::test]
async fn execution_aliases_pruned_when_subscriptions_drop() {
    let (stream, bus) = make_bus();
    let order = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    let executions = bus.send_request(RequestId::nth(99), vec![]).await.unwrap();
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 7, "exec-order"));
    stream.push_inbound(execution_data_frame(CLIENT_ID, RequestId::nth(99).raw(), 0, "exec-request"));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();
    assert_eq!(bus.executions.len(), 2, "both executions mapped");

    drop(order);
    drain_cleanup_signals(&bus).await;
    assert!(!bus.executions.contains(&"exec-order".to_string()), "order alias leaked");
    assert!(bus.executions.contains(&"exec-request".to_string()), "live request alias pruned");

    drop(executions);
    drain_cleanup_signals(&bus).await;
    assert!(bus.executions.is_empty(), "request alias leaked");
}

/// Each clone sends its own cleanup signal; the alias stays while any clone
/// can still read the channel and goes with the last one.
#[tokio::test]
async fn execution_alias_kept_while_a_clone_is_alive() {
    let (stream, bus) = make_bus();
    let order = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 7, "exec-order"));
    bus.read_and_route_message().await.unwrap();

    let clone = order.clone();
    drop(order);
    drain_cleanup_signals(&bus).await;
    assert!(bus.executions.contains(&"exec-order".to_string()), "alias pruned while a clone is alive");

    drop(clone);
    drain_cleanup_signals(&bus).await;
    assert!(bus.executions.is_empty(), "alias leaked");
}

/// A stale drop signal releases the old subscription's aliases and keeps those
/// of a newer registration under the same order id.
#[tokio::test]
async fn stale_cleanup_keeps_newer_execution_aliases() {
    let (stream, bus) = make_bus();
    let sub_a = bus.send_order_request(OrderId::from(42), vec![]).await.unwrap();
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 42, "exec-a"));
    bus.read_and_route_message().await.unwrap();
    let sub_b = bus.send_order_request(OrderId::from(42), vec![]).await.unwrap();
    stream.push_inbound(execution_data_frame(CLIENT_ID, 0, 42, "exec-b"));
    bus.read_and_route_message().await.unwrap();

    drop(sub_a);
    drain_cleanup_signals(&bus).await;
    assert!(!bus.executions.contains(&"exec-a".to_string()), "stale subscription's alias leaked");
    assert!(bus.executions.contains(&"exec-b".to_string()), "newer subscription's alias pruned");

    drop(sub_b);
    drain_cleanup_signals(&bus).await;
    assert!(bus.executions.is_empty());
}

#[tokio::test]
async fn completed_order_routes_to_shared_channel() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_shared_request(OutgoingMessages::RequestCompletedOrders, vec![]).await.unwrap();

    stream.push_inbound(body("101|265598|AAPL|STK|"));
    bus.read_and_route_message().await.unwrap();

    let msg = next_message(&mut sub).await;
    assert_eq!(msg.peek_int(0).unwrap(), 101);
}

#[tokio::test]
async fn completed_orders_end_routes_to_shared_channel() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_shared_request(OutgoingMessages::RequestCompletedOrders, vec![]).await.unwrap();

    stream.push_inbound(body("102|"));
    bus.read_and_route_message().await.unwrap();

    let msg = next_message(&mut sub).await;
    assert_eq!(msg.peek_int(0).unwrap(), 102);
}

// ---- order-update stream + lifecycle tests ----

/// `send_order_update` fan-out: an OpenOrder reaches both an order subscription
/// and the order-update stream when both are registered for the same order.
#[tokio::test]
async fn order_update_stream_receives_open_order() {
    let (stream, bus) = make_bus();
    let mut order_sub = bus.send_order_request(OrderId::from(42), vec![]).await.unwrap();
    let mut stream_sub = bus.create_order_update_subscription().await.unwrap();

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OpenOrder as i32,
        &crate::proto::OpenOrder {
            order_id: Some(42),
            ..Default::default()
        },
    ));
    bus.read_and_route_message().await.unwrap();

    next_message(&mut order_sub).await;
    next_message(&mut stream_sub).await;
}

/// A targeted hard error reaches the order-update stream as a notice so the
/// stream can continue with later order updates.
#[tokio::test]
async fn order_update_stream_receives_order_error_as_notice() {
    let (stream, bus) = make_bus();
    let mut stream_sub = bus.create_order_update_subscription().await.unwrap();

    stream.push_inbound(error_frame(42, 201, "Order rejected"));
    bus.read_and_route_message().await.unwrap();

    match next_routed(&mut stream_sub).await {
        RoutedItem::Notice(notice) => {
            assert_eq!(notice.request_id, Some(42));
            assert_eq!(notice.code, 201);
            assert_eq!(notice.message, "Order rejected");
        }
        other => panic!("expected RoutedItem::Notice, received {other:?}"),
    }

    stream.push_inbound(binary_proto(
        crate::messages::IncomingMessages::OpenOrder as i32,
        &crate::proto::OpenOrder {
            order_id: Some(42),
            ..Default::default()
        },
    ));
    bus.read_and_route_message().await.unwrap();

    assert!(matches!(next_routed(&mut stream_sub).await, RoutedItem::Response(_)));
}

/// An error with a request-range id stays on that request's subscription:
/// the order-update stream must not receive a copy.
#[tokio::test]
async fn order_update_stream_skips_data_request_error() {
    let (stream, bus) = make_bus();
    let mut stream_sub = bus.create_order_update_subscription().await.unwrap();
    let request_id = RequestId::nth(42);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(error_frame(request_id.raw(), 200, "No security definition found"));
    bus.read_and_route_message().await.unwrap();

    let item = next_routed(&mut sub).await;
    assert!(matches!(item, RoutedItem::Error(Error::Notice(_))), "got: {item:?}");
    assert!(
        stream_sub.try_next_routed().is_none(),
        "order-update stream must not receive a data-request error"
    );
}

/// #789: an order-range error id reaches the order subscription and the
/// order-update stream, never a request. A range-routing guard: the request
/// below sits at the same small number plus the floor, so the ids cannot
/// collide; the collision itself is what the floor rules out.
#[tokio::test]
async fn issue_789_order_error_reaches_order_side() {
    let (stream, bus) = make_bus();
    let order_id = OrderId::from(7);
    let mut request = bus.send_request(RequestId::nth(order_id.value()), vec![]).await.unwrap();
    let mut order = bus.send_order_request(order_id, vec![]).await.unwrap();
    let mut updates = bus.create_order_update_subscription().await.unwrap();

    stream.push_inbound(error_frame(order_id.value(), 202, "Order Canceled"));
    stream.push_inbound(error_frame(order_id.value(), 201, "Order rejected"));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    match next_routed(&mut order).await {
        RoutedItem::Notice(notice) => assert_eq!(notice.code, 202),
        other => panic!("expected the 202 notice, got {other:?}"),
    }
    match next_routed(&mut order).await {
        RoutedItem::Error(Error::Notice(notice)) => assert_eq!(notice.code, 201),
        other => panic!("expected the 201 error, got {other:?}"),
    }
    for code in [202, 201] {
        match next_routed(&mut updates).await {
            RoutedItem::Notice(notice) => {
                assert_eq!(notice.request_id, Some(order_id.value()));
                assert_eq!(notice.code, code);
            }
            other => panic!("expected the {code} notice on the order-update stream, got {other:?}"),
        }
    }
    assert!(request.try_next_routed().is_none(), "request received an order's error");
}

/// #789: an error for a request that is gone is not published as order-bound.
#[tokio::test]
async fn issue_789_late_request_error_stays_off_order_stream() {
    let (stream, bus) = make_bus();
    let request_id = RequestId::nth(5);
    drop(bus.send_request(request_id, vec![]).await.unwrap());
    drain_cleanup_signals(&bus).await;
    let mut updates = bus.create_order_update_subscription().await.unwrap();

    stream.push_inbound(error_frame(request_id.raw(), 200, "No security definition found"));
    bus.read_and_route_message().await.unwrap();

    assert!(
        try_next_routed(&mut updates).await.is_none(),
        "late request error reached the order-update stream"
    );
}

/// Routed-but-orphan notice (real request_id, no matching sub) takes the
/// `log_orphan` path, NOT the global notice stream.
#[tokio::test]
async fn warning_with_orphan_request_id_logs() {
    let (stream, bus) = make_bus();
    let mut unrelated = bus.send_request(RequestId::nth(42), vec![]).await.unwrap();
    let mut notice_stream = bus.notice_subscribe();

    stream.push_inbound(error_frame(RequestId::nth(99).raw(), 2104, "orphan warning"));
    bus.read_and_route_message().await.unwrap();

    assert!(unrelated.try_next_routed().is_none(), "unrelated sub got the notice");
    let leaked = tokio::time::timeout(TICK, notice_stream.next()).await;
    assert!(leaked.is_err(), "global notice stream got a routed-but-orphan notice");
}

/// Queue a marker cleanup signal behind everything already queued and wait
/// until the cleanup task has processed it. Signals are processed FIFO by a
/// single task, so once the marker's registration is gone, every signal sent
/// before it has been handled too.
pub(super) async fn drain_cleanup_signals<S: AsyncStream>(bus: &Arc<AsyncTcpMessageBus<S>>) {
    const MARKER_REQUEST_ID: RequestId = RequestId::nth(987_654);
    let marker = bus.send_request(MARKER_REQUEST_ID, vec![]).await.unwrap();
    drop(marker);

    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    while std::time::Instant::now() < deadline {
        if !bus.requests.contains(&MARKER_REQUEST_ID) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(1)).await;
    }
    panic!("cleanup task did not process the marker signal");
}

/// Regression test for #773: dropping an old order subscription must not
/// unregister a newer subscription under the same order id (place then cancel
/// on one id). The stale signal has to find the replacement live and skip it.
#[tokio::test]
async fn stale_order_cleanup_preserves_newer_subscription() {
    let (_, bus) = make_bus();

    let order_id = OrderId::from(42);
    let sub_a = bus.send_order_request(order_id, vec![]).await.unwrap();
    let mut sub_b = bus.send_order_request(order_id, vec![]).await.unwrap();
    drop(sub_a);

    drain_cleanup_signals(&bus).await;

    let sender = bus.orders.sender(&order_id).expect("stale cleanup removed the newer subscription");
    sender
        .send(RoutedItem::Error(Error::Cancelled))
        .expect("registered channel has no receivers");
    let item = tokio::time::timeout(TICK, sub_b.next_routed()).await.expect("sub_b got nothing");
    assert!(matches!(item, Some(RoutedItem::Error(Error::Cancelled))), "{item:?}");
    drop(sender);

    // The replacement's own drop still cleans up.
    drop(sub_b);
    drain_cleanup_signals(&bus).await;
    assert!(!bus.orders.contains(&order_id), "order channel leaked");
}

/// Dropping a clone must not unregister the channel while a sibling is still
/// consuming it; the registration goes away with the last holder.
#[tokio::test]
async fn dropping_clone_keeps_order_channel_registered() {
    let (_, bus) = make_bus();

    let order_id = OrderId::from(7);
    let sub = bus.send_order_request(order_id, vec![]).await.unwrap();
    let clone = sub.clone();
    drop(clone);

    drain_cleanup_signals(&bus).await;
    assert!(bus.orders.contains(&order_id), "clone drop unregistered a live subscription");

    drop(sub);
    drain_cleanup_signals(&bus).await;
    assert!(!bus.orders.contains(&order_id), "order channel leaked");
}

/// The lease is released before the cleanup signal is sent, not by the field
/// drops after it: otherwise a concurrently processed signal could find the
/// registration still live and skip the removal, leaking it.
#[tokio::test]
async fn cleanup_signal_follows_lease_release() {
    let (_, bus) = make_bus();
    let request_id = RequestId::nth(5);
    let mut sub = bus.send_request(request_id, vec![]).await.unwrap();
    let is_live = || bus.requests.with_route(&request_id, |route| route.lease.is_live());
    assert_eq!(is_live(), Some(true));

    sub.send_cleanup_signal();
    assert_eq!(is_live(), Some(false), "signal sent while the handle still held the lease");

    drain_cleanup_signals(&bus).await;
    assert!(!bus.requests.contains(&request_id), "request channel leaked");
    drop(sub);
}

/// Regression test for #778: drop then immediately recreate the order update
/// stream. The dead registration is replaced without waiting for the cleanup
/// task, and the old stream's stale signal must not clear the replacement.
#[tokio::test]
async fn drop_then_recreate_order_update_stream() {
    let (_, bus) = make_bus();

    let s1 = bus.create_order_update_subscription().await.unwrap();
    drop(s1);

    // No yielding: recreation must succeed even before the stale signal is
    // processed.
    let mut s2 = bus.create_order_update_subscription().await.expect("immediate recreation failed");

    // Process s1's stale OrderUpdateStream signal; s2's registration survives.
    drain_cleanup_signals(&bus).await;
    let sender = bus.order_taps.updates_sender().expect("stale cleanup cleared the replacement stream");
    sender
        .send(RoutedItem::Error(Error::Cancelled))
        .expect("replacement stream has no receivers");
    let item = tokio::time::timeout(TICK, s2.next_routed()).await.expect("s2 got nothing");
    assert!(matches!(item, Some(RoutedItem::Error(Error::Cancelled))), "{item:?}");
    drop(sender);

    drop(s2);
    drain_cleanup_signals(&bus).await;
    assert!(bus.order_taps.updates_lease().is_none(), "order update stream leaked");
}

/// `reset_channels` after reconnect: every in-flight request and order
/// subscription receives `Error::ConnectionReset`, then the channel maps are
/// cleared.
#[tokio::test]
async fn reset_channels_notifies_in_flight_subscriptions() {
    let (_, bus) = make_bus();

    let mut req = bus.send_request(RequestId::nth(100), vec![]).await.unwrap();
    let mut order = bus.send_order_request(OrderId::from(200), vec![]).await.unwrap();
    // Streaming shared subscription — the population that hung forever when
    // reset skipped shared channels (#776).
    let mut shared = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();

    bus.reset_channels().await;

    for (name, sub) in [("request", &mut req), ("order", &mut order), ("shared", &mut shared)] {
        let item = tokio::time::timeout(TICK, sub.next_routed())
            .await
            .unwrap_or_else(|_| panic!("{name} got no notification"))
            .unwrap_or_else(|| panic!("{name} channel closed early"));
        assert!(matches!(item, RoutedItem::Error(Error::ConnectionReset)), "{name}: {item:?}");
    }

    assert!(bus.requests.is_empty());
    assert!(bus.orders.is_empty());
    assert!(bus.executions.is_empty());

    // A shared subscription created after the reset resubscribes at the
    // channel's current tail: it must not read the stale ConnectionReset.
    let mut late = bus.send_shared_request(OutgoingMessages::RequestOpenOrders, vec![]).await.unwrap();
    assert!(late.try_next_routed().is_none(), "post-reset shared subscription read a stale reset");
}

/// A finished reconnect publishes the reconnect notice to the notice stream:
/// a connection-state consumer subscribed there learns the socket generation
/// changed even with no live subscription to carry a `ConnectionReset`. TWS
/// never replays 1101/1102 on the new connection, so this notice is the only
/// signal that un-strands state recorded from the previous one (a held 1100).
/// It is published once the session is live again - the channel reset runs
/// before the reconnect, so the notice cannot ride on it - and a consumer
/// that resubscribes on it lands on the new session.
#[tokio::test]
async fn reconnect_publishes_reconnect_notice_to_notice_stream() {
    let stream = MemoryStream::default();
    let connection = AsyncConnection::stubbed(stream.clone(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);

    // First read is a body too short for the message id: InvalidFrame, which
    // the processing loop classifies as connection lost, so this also guards
    // the #891 short-body path end to end (it used to panic the dispatcher).
    // Then the frames the reconnect handshake consumes.
    stream.push_inbound(b"xx".to_vec());
    for frame in handshake_frames(server_versions::PROTOBUF_REST_MESSAGES_3, "EST", 5000) {
        stream.push_inbound(frame);
    }

    let bus = Arc::new(AsyncTcpMessageBus::new(connection));
    let mut notices = bus.connection.notice_broadcaster.subscribe();

    bus.clone().process_messages().expect("process_messages");

    let notice = tokio::time::timeout(Duration::from_secs(2), notices.recv())
        .await
        .expect("no reconnect notice on the notice stream")
        .expect("notice stream closed");
    assert_eq!(notice.code, TRANSPORT_RECONNECT_CODE, "{notice:?}");
    assert!(bus.is_connected(), "the notice must follow the session going live");
}

/// A market data type sent through the bus is re-sent by the reconnect, on
/// the wire before the reconnect notice: a consumer acting on the notice
/// already sees the new session with the type applied.
#[tokio::test]
async fn reconnect_replays_market_data_type_before_notice() {
    let (stream, bus) = make_bus();
    let mut notices = bus.connection.notice_broadcaster.subscribe();

    let packet = crate::market_data::realtime::common::encode_request_market_data_type(crate::market_data::MarketDataType::Delayed).unwrap();
    bus.send_market_data_type(packet.clone()).await.unwrap();

    stream.push_inbound(b"xx".to_vec());
    for frame in handshake_frames(server_versions::PROTOBUF_REST_MESSAGES_3, "EST", 5000) {
        stream.push_inbound(frame);
    }

    bus.clone().process_messages().expect("process_messages");

    let notice = tokio::time::timeout(Duration::from_secs(2), notices.recv())
        .await
        .expect("no reconnect notice on the notice stream")
        .expect("notice stream closed");
    assert_eq!(notice.code, TRANSPORT_RECONNECT_CODE, "{notice:?}");

    let handler = &bus.connection.connection_handler;
    let expected = [
        encode_raw_length(&packet),
        handler.format_handshake(),
        encode_raw_length(&handler.format_start_api(28)),
        encode_raw_length(&packet),
    ]
    .concat();
    assert_eq!(
        stream.captured(),
        expected,
        "the replay must be on the wire by the time the notice is published"
    );
}

/// `ensure_shutdown` joins the running message-processing task and reports
/// `is_connected() == false` afterwards. The handle is in place as soon as
/// `process_messages` returns.
#[tokio::test]
async fn ensure_shutdown_joins_processing_task() {
    let (_, bus) = make_bus();
    bus.clone().process_messages().expect("process_messages");
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    assert!(lock(&bus.process_task).is_some(), "process_task installed by process_messages");

    mb.ensure_shutdown().await;
    assert!(!mb.is_connected());
}

/// A successful automatic reconnect replays the handshake, whose
/// `NextValidId` is a fresh server floor for order IDs, and it may negotiate a
/// different server version (the gateway restarted on another build). The
/// bus must refresh both on the client: before this, only the initial
/// connection set them (#1105).
#[tokio::test]
async fn reconnect_refreshes_handshake_state() {
    let stream = MemoryStream::default();
    let connection = AsyncConnection::stubbed(stream.clone(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);

    // First read fails as InvalidFrame (a body too short to hold a message
    // id), which the processing loop classifies as connection lost.
    stream.push_inbound(b"xx".to_vec());
    // Frames the reconnect handshake consumes, in order.
    let new_version = server_versions::CONDITIONS_INCLUDE_OVERNIGHT;
    for frame in handshake_frames(new_version, "EST", 5000) {
        stream.push_inbound(frame);
    }

    let bus = Arc::new(AsyncTcpMessageBus::new(connection));
    let order_ids = Arc::new(crate::client::id_generator::ClientIdManager::new(100).unwrap());
    let server_version = Arc::new(ServerVersion::new(server_versions::PROTOBUF_REST_MESSAGES_3));
    bus.set_handshake_state(HandshakeState {
        order_ids: order_ids.clone(),
        server_version: server_version.clone(),
    });

    bus.clone().process_messages().expect("process_messages");

    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while order_ids.current_order_id() < 5000 {
        assert!(
            tokio::time::Instant::now() < deadline,
            "order-id generator was never raised from the reconnect handshake"
        );
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    // Refreshed in the same step as the order ids.
    assert_eq!(server_version.get(), new_version, "server version should be the reconnect handshake's");
}

#[tokio::test]
async fn send_shared_request_unsupported_returns_error() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    match mb.send_shared_request(OutgoingMessages::PlaceOrder, b"x".to_vec()).await {
        Err(Error::InvalidArgument(_)) => {}
        other => panic!("expected Error::InvalidArgument, got {:?}", other.err()),
    }
}

/// An unknown message id must reach the notice stream, not vanish. This is the
/// observable form of a framing desync: before this, `route_to_shared_channel`
/// dropped anything no channel claimed without a log or an error, so a
/// desynchronized stream was indistinguishable from an idle one.
#[tokio::test]
async fn unknown_message_id_reaches_the_notice_stream() {
    let (stream, bus) = make_bus();
    let mut notice_stream = bus.notice_subscribe();

    stream.push_inbound(crate::common::test_utils::helpers::unknown_message_frame());

    bus.read_and_route_message().await.unwrap();

    let notice = tokio::time::timeout(TICK, notice_stream.next())
        .await
        .expect("unknown frame must raise a notice")
        .expect("notice stream closed");
    assert_eq!(notice.code, crate::messages::UNKNOWN_MESSAGE_TYPE_CODE);
    // The id survives the protobuf path, where `kind` alone would have lost it.
    assert!(
        notice.message.contains(&helpers::UNKNOWN_MESSAGE_ID.to_string()),
        "notice must name the offending id, got {:?}",
        notice.message
    );
}

/// Every send is refused while the session is down: nothing reaches the socket
/// the reconnect is replacing, and nothing is registered on a channel no reset
/// would clear again.
#[tokio::test]
async fn sends_are_refused_while_disconnected() {
    let (stream, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    bus.connection_state.set_disconnected();

    assert!(matches!(
        mb.send_request(RequestId::nth(100), b"req-bytes".to_vec()).await,
        Err(Error::ConnectionReset)
    ));
    assert!(matches!(
        mb.send_order_request(OrderId::from(42), b"order-bytes".to_vec()).await,
        Err(Error::ConnectionReset)
    ));
    assert!(matches!(
        mb.send_shared_request(OutgoingMessages::RequestManagedAccounts, b"shared-bytes".to_vec())
            .await,
        Err(Error::ConnectionReset)
    ));
    assert!(matches!(mb.send_message(b"message-bytes".to_vec()).await, Err(Error::ConnectionReset)));

    assert!(bus.requests.is_empty(), "a refused request must register nothing");
    assert!(bus.orders.is_empty(), "a refused order request must register nothing");
    assert!(stream.captured().is_empty(), "a refused send must not reach the socket");

    // The same send goes through once the handshake has put the session back.
    bus.connection_state.set_connected();
    assert!(mb.send_request(RequestId::nth(100), b"req-bytes".to_vec()).await.is_ok());
    assert!(!stream.captured().is_empty());
}

/// `wait_connected` holds the one-shot retry until the session is back, and a
/// shutdown releases it rather than leaving the caller there for good.
#[tokio::test]
async fn wait_connected_returns_shutdown_when_the_bus_shuts_down() {
    let (_stream, bus) = make_bus();
    bus.connection_state.set_disconnected();

    let closer = Arc::clone(&bus);
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(20)).await;
        closer.request_shutdown_sync();
    });

    let result = tokio::time::timeout(Duration::from_secs(5), bus.wait_connected())
        .await
        .expect("wait_connected did not return on shutdown");
    assert!(matches!(result, Err(Error::Shutdown)), "got: {result:?}");
}

/// Writes fail, reads delegate to a `MemoryStream`. Stands in for the window
/// the send gate cannot close: the write is refused after the registration
/// went in.
#[derive(Clone, Debug, Default)]
struct FailingWriteStream(MemoryStream);

#[async_trait::async_trait]
impl AsyncIo for FailingWriteStream {
    async fn read_message(&self) -> Result<Vec<u8>, Error> {
        self.0.read_message().await
    }

    async fn write_all(&self, _buf: &[u8]) -> Result<(), Error> {
        Err(Error::ConnectionReset)
    }

    async fn close(&self) {
        self.0.close().await;
    }
}

#[async_trait::async_trait]
impl AsyncReconnect for FailingWriteStream {
    async fn reconnect(&self) -> Result<(), Error> {
        self.0.reconnect().await
    }

    async fn sleep(&self, duration: Duration, shutdown: &ShutdownSignal) {
        self.0.sleep(duration, shutdown).await
    }
}

impl AsyncStream for FailingWriteStream {}

/// A send whose write fails takes its registration with it, so no channel is
/// left waiting on a response that was never requested. Covers the window the
/// `ensure_connected` check cannot close, where the session goes down between
/// the check and the write.
#[tokio::test]
async fn failed_write_leaves_no_registration() {
    let connection = AsyncConnection::stubbed(FailingWriteStream::default(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);
    let bus = Arc::new(AsyncTcpMessageBus::new(connection));
    let mb: &dyn AsyncMessageBus = bus.as_ref();

    assert!(mb.send_request(RequestId::nth(100), b"req-bytes".to_vec()).await.is_err());
    assert!(bus.requests.is_empty(), "a failed write must leave no request registered");

    assert!(mb.send_order_request(OrderId::from(42), b"order-bytes".to_vec()).await.is_err());
    assert!(bus.orders.is_empty(), "a failed write must leave no order registered");
}

#[tokio::test]
async fn order_binding_reaches_updates_without_using_raw_order_id() {
    let (stream, bus) = make_bus();
    let mut order_sub = bus.send_order_request(OrderId::from(42), vec![]).await.unwrap();
    let mut update_sub = bus.create_order_update_subscription().await.unwrap();
    stream.push_inbound(binary_proto(
        IncomingMessages::OrderBound as i32,
        &order_bound().client_id(CLIENT_ID).to_proto(),
    ));
    bus.read_and_route_message().await.unwrap();
    let message = next_message(&mut update_sub).await;
    assert_eq!(message.message_type(), IncomingMessages::OrderBound);
    assert!(tokio::time::timeout(TICK, order_sub.next()).await.is_err());
}

// ---- buffer_limit: bounded request routes ------------------------------------

/// A cap of `limit`, ending on `ContractDataEnd`.
pub(super) fn bound(limit: usize) -> BufferBound {
    BufferBound {
        limit,
        end: &[IncomingMessages::ContractDataEnd],
    }
}

/// The request id `contract_row` and `contract_end` frames carry.
const CONTRACT_REQUEST_ID: RequestId = RequestId::nth(0);

fn contract_row(contract_id: i32) -> Vec<u8> {
    binary_proto(
        IncomingMessages::ContractData as i32,
        &contract_data().request_id(CONTRACT_REQUEST_ID.raw()).contract_id(contract_id).to_proto(),
    )
}

fn contract_end() -> Vec<u8> {
    binary_proto(
        IncomingMessages::ContractDataEnd as i32,
        &crate::proto::ContractDataEnd {
            req_id: Some(CONTRACT_REQUEST_ID.raw()),
        },
    )
}

async fn route_histograms(stream: &MemoryStream, bus: &AsyncTcpMessageBus<MemoryStream>, frames: usize, request_id: RequestId) {
    for n in 0..frames {
        // HistogramData (msg_id 89): request_id at field index 1, `n` at 2.
        stream.push_inbound(body(&format!("89|{request_id}|{n}|")));
        bus.read_and_route_message().await.unwrap();
    }
}

/// The next routed item, or `None` if nothing arrives within `TICK`.
async fn try_next_routed(sub: &mut AsyncInternalSubscription) -> Option<RoutedItem> {
    tokio::time::timeout(TICK, sub.next_routed()).await.ok().flatten()
}

#[tokio::test]
async fn bounded_request_fails_after_limit_unread() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_request_capped(RequestId::nth(100), vec![], Some(bound(2))).await.unwrap();

    route_histograms(&stream, &bus, 4, RequestId::nth(100)).await;

    // The first frame was not evicted: the overflow error took the reserved slot.
    match try_next_routed(&mut sub).await {
        Some(RoutedItem::Response(message)) => assert_eq!(message.peek_int(2).unwrap(), 0),
        other => panic!("expected the first row, got {other:?}"),
    }
    assert!(matches!(try_next_routed(&mut sub).await, Some(RoutedItem::Response(_))));
    assert!(matches!(
        try_next_routed(&mut sub).await,
        Some(RoutedItem::Error(Error::BufferLimitExceeded { limit: 2 }))
    ));
    assert!(
        try_next_routed(&mut sub).await.is_none(),
        "no lag notice, and frames after the overflow are discarded"
    );
}

#[tokio::test]
async fn bounded_request_counts_unread_not_total() {
    let (stream, bus) = make_bus();
    let mut sub = bus.send_request_capped(RequestId::nth(100), vec![], Some(bound(2))).await.unwrap();

    for _ in 0..6 {
        route_histograms(&stream, &bus, 1, RequestId::nth(100)).await;
        assert!(
            matches!(try_next_routed(&mut sub).await, Some(RoutedItem::Response(_))),
            "a reader that keeps up never overflows"
        );
    }
}

#[tokio::test]
async fn reset_skips_overflowed_route() {
    let (stream, bus) = make_bus();
    let mut overflowed = bus.send_request_capped(RequestId::nth(100), vec![], Some(bound(1))).await.unwrap();
    let mut at_limit = bus.send_request_capped(RequestId::nth(200), vec![], Some(bound(1))).await.unwrap();

    route_histograms(&stream, &bus, 2, RequestId::nth(100)).await;
    route_histograms(&stream, &bus, 1, RequestId::nth(200)).await;
    bus.reset_channels().await;

    assert!(matches!(try_next_routed(&mut overflowed).await, Some(RoutedItem::Response(_))));
    assert!(matches!(
        try_next_routed(&mut overflowed).await,
        Some(RoutedItem::Error(Error::BufferLimitExceeded { .. }))
    ));
    assert!(try_next_routed(&mut overflowed).await.is_none(), "no second terminal error after reset");

    // At its limit but not overflowed: the reset error uses the reserved slot, evicting nothing.
    assert!(matches!(try_next_routed(&mut at_limit).await, Some(RoutedItem::Response(_))));
    assert!(matches!(
        try_next_routed(&mut at_limit).await,
        Some(RoutedItem::Error(Error::ConnectionReset))
    ));
}

#[tokio::test]
async fn overflowed_subscription_cancels_on_drop() {
    use crate::contracts::ContractDetails;

    let (stream, bus) = make_bus();
    let internal = bus.send_request_capped(CONTRACT_REQUEST_ID, vec![], Some(bound(1))).await.unwrap();
    let mut subscription: Subscription<ContractDetails> = Subscription::new_from_internal(
        internal,
        bus.clone(),
        Some(CONTRACT_REQUEST_ID.raw()),
        None,
        DecoderContext::new(server_versions::CANCEL_CONTRACT_DATA),
    );

    for contract_id in [1, 2] {
        stream.push_inbound(contract_row(contract_id));
        bus.read_and_route_message().await.unwrap();
    }

    assert!(matches!(next_item(&mut subscription).await, Some(Ok(_))));
    assert!(matches!(
        next_item(&mut subscription).await,
        Some(Err(Error::BufferLimitExceeded { limit: 1 }))
    ));
    drop(subscription);

    let cancel = <ContractDetails as StreamDecoder<ContractDetails>>::cancel_message(
        server_versions::CANCEL_CONTRACT_DATA,
        Some(CONTRACT_REQUEST_ID.raw()),
        None,
    )
    .unwrap();
    assert_eq!(wait_for_frames(&stream, &cancel, 1).await, 1, "overflow leaves the cancel to drop");
}

#[tokio::test]
async fn bounded_request_end_marker_at_limit_still_ends() {
    // A result exactly `limit` rows long, read late: the end marker takes the
    // spare slot, so the stream ends normally and nothing is evicted.
    let (stream, bus) = make_bus();
    let mut sub = bus.send_request_capped(CONTRACT_REQUEST_ID, vec![], Some(bound(1))).await.unwrap();

    for frame in [contract_row(1), contract_end(), contract_row(2)] {
        stream.push_inbound(frame);
        bus.read_and_route_message().await.unwrap();
    }

    match try_next_routed(&mut sub).await {
        Some(RoutedItem::Response(message)) => assert_eq!(message.message_type(), IncomingMessages::ContractData),
        other => panic!("expected the row, got {other:?}"),
    }
    match try_next_routed(&mut sub).await {
        Some(RoutedItem::Response(message)) => assert_eq!(message.message_type(), IncomingMessages::ContractDataEnd),
        other => panic!("expected the end marker, got {other:?}"),
    }
    assert!(try_next_routed(&mut sub).await.is_none(), "frames after the end marker are discarded");
}

/// Shutdown fails the request with `Error::Shutdown`; the drain reports it, as
/// the sync drain does.
#[tokio::test]
async fn drain_reports_shutdown() {
    use crate::contracts::ContractDetails;
    use crate::subscriptions::Drained;

    let (_stream, bus) = make_bus();
    let internal = bus.send_request(CONTRACT_REQUEST_ID, vec![]).await.unwrap();
    let subscription: Subscription<ContractDetails> = Subscription::new_from_internal(
        internal,
        bus.clone(),
        Some(CONTRACT_REQUEST_ID.raw()),
        None,
        DecoderContext::new(server_versions::CANCEL_CONTRACT_DATA),
    );

    let drain = tokio::spawn(subscription.cancel_and_drain(tokio::time::Instant::now() + Duration::from_secs(5)));
    tokio::time::sleep(Duration::from_millis(20)).await;
    bus.request_shutdown();

    let outcome: Result<Drained, Error> = drain.await.unwrap();
    assert!(matches!(outcome, Err(Error::Shutdown)), "got {outcome:?}");
}

/// A read woken by `close` ends dispatch cleanly: requests end with
/// `Shutdown`, not the `ConnectionReset` the reconnect path fails them with.
#[tokio::test]
async fn close_ends_dispatch_without_reconnecting() {
    let (stream, bus) = make_bus();
    let mut internal = bus.send_request(CONTRACT_REQUEST_ID, vec![]).await.unwrap();
    bus.clone().process_messages().unwrap();
    tokio::task::yield_now().await;

    stream.close().await;
    let item = tokio::time::timeout(Duration::from_secs(1), internal.next())
        .await
        .expect("request never ended");
    assert!(matches!(item, Some(Err(Error::Shutdown))), "got {item:?}");
}

use super::io::tests::assert_peer_sees_eof;

/// A client on a dispatching bus over loopback TCP, and the peer end.
async fn tcp_client_with_peer() -> (crate::Client, Arc<AsyncTcpMessageBus<AsyncTcpSocket>>, tokio::net::TcpStream) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap().to_string();
    let (socket, peer) = tokio::join!(AsyncTcpSocket::connect(&address, true), listener.accept());
    let bus = Arc::new(AsyncTcpMessageBus::new(AsyncConnection::stubbed(socket.unwrap(), CLIENT_ID)));
    bus.clone().process_messages().unwrap();
    let client = crate::Client::stubbed(bus.clone(), server_versions::PROTOBUF_REST_MESSAGES_3);
    (client, bus, peer.unwrap().0)
}

/// Retained clients and subscriptions cannot retain a disconnected physical socket.
#[tokio::test]
async fn disconnect_closes_tcp_with_retained_client_and_subscription() {
    let (client, _bus, peer) = tcp_client_with_peer().await;
    let _subscription = client.order_update_stream().await.unwrap();

    client.disconnect().await;
    assert_peer_sees_eof(peer).await;
    assert!(!client.is_connected());
    // A second disconnect on the closed socket is a no-op.
    client.disconnect().await;
}

/// Runtime-free Client::drop requests close; the dispatcher releases both halves.
#[tokio::test]
async fn client_drop_closes_tcp_with_retained_subscription() {
    let (client, bus, peer) = tcp_client_with_peer().await;
    let _subscription = client.order_update_stream().await.unwrap();

    drop(client);
    assert_peer_sees_eof(peer).await;
    assert!(!bus.is_connected());
}

// ---- wait_for_fill lookup on a cache miss (#1020) ----

async fn read_frame(peer: &mut tokio::net::TcpStream) {
    use tokio::io::AsyncReadExt;
    let len = peer.read_u32().await.unwrap();
    peer.read_exact(&mut vec![0u8; len as usize]).await.unwrap();
}

/// A length-prefixed protobuf frame, as TWS writes it.
fn tws_frame(message: IncomingMessages, proto: &impl prost::Message) -> Vec<u8> {
    encode_raw_length(&helpers::binary_proto(message as i32, proto))
}

fn open_orders_end_frame() -> Vec<u8> {
    tws_frame(
        IncomingMessages::OpenOrderEnd,
        &crate::testdata::builders::orders::open_order_end().to_proto(),
    )
}

fn completed_orders_end_frame() -> Vec<u8> {
    tws_frame(
        IncomingMessages::CompletedOrdersEnd,
        &crate::testdata::builders::orders::completed_orders_end().to_proto(),
    )
}

/// On a cache miss `wait_for_fill` asks for open orders, then completed
/// orders, and reads each reply to its end marker (sent late here), so the
/// caller's next request of either kind cannot end on it and come back empty.
#[tokio::test]
async fn wait_for_fill_lookup_ends_do_not_end_next_requests() {
    use crate::orders::Orders;
    use crate::testdata::builders::orders::{completed_order, open_order};
    use futures::StreamExt;
    use tokio::io::AsyncWriteExt;

    let order = tws_frame(IncomingMessages::OpenOrder, &open_order().order_id(7).to_proto());
    let completed = tws_frame(IncomingMessages::CompletedOrder, &completed_order().order_id(9).to_proto());

    let (client, _bus, mut peer) = tcp_client_with_peer().await;
    let tws = tokio::spawn(async move {
        read_frame(&mut peer).await; // the lookup's open orders
        tokio::time::sleep(Duration::from_millis(50)).await;
        peer.write_all(&open_orders_end_frame()).await.unwrap();
        read_frame(&mut peer).await; // the lookup's completed orders
        tokio::time::sleep(Duration::from_millis(50)).await;
        peer.write_all(&completed_orders_end_frame()).await.unwrap();
        read_frame(&mut peer).await; // the caller's completed_orders
        peer.write_all(&completed).await.unwrap();
        peer.write_all(&completed_orders_end_frame()).await.unwrap();
        read_frame(&mut peer).await; // the caller's open_orders
        peer.write_all(&order).await.unwrap();
        peer.write_all(&open_orders_end_frame()).await.unwrap();
        peer
    });

    let outcome = client.wait_for_fill(7, Duration::ZERO).await.unwrap();
    assert_eq!(outcome, crate::orders::OrderOutcome::TimedOut(None));
    let mut orders = client.completed_orders(false).await.unwrap();
    let first = tokio::time::timeout(Duration::from_secs(1), orders.next()).await.expect("no reply");
    assert!(
        matches!(&first, Some(Ok(SubscriptionItem::Data(Orders::OrderData(d)))) if d.order.order_id == 9),
        "{first:?}"
    );
    let mut orders = client.open_orders().await.unwrap();
    let first = tokio::time::timeout(Duration::from_secs(1), orders.next()).await.expect("no reply");
    assert!(
        matches!(&first, Some(Ok(SubscriptionItem::Data(Orders::OrderData(d)))) if d.order.order_id == 7),
        "{first:?}"
    );
    drop(tws.await.unwrap());
}

/// An order missing from open orders but among completed ones (e.g. it ended
/// before this connection) ends the wait at once, with no fill prices.
#[tokio::test]
async fn wait_for_fill_finds_order_among_completed() {
    use crate::orders::{OrderOutcome, OrderStatusKind};
    use crate::testdata::builders::orders::completed_order;
    use tokio::io::AsyncWriteExt;

    let (client, _bus, mut peer) = tcp_client_with_peer().await;
    let completed = tws_frame(
        IncomingMessages::CompletedOrder,
        &completed_order()
            .client_id(client.client_id())
            .order_id(7)
            .status(OrderStatusKind::Cancelled)
            .total_quantity(60.0)
            .filled_quantity(40.0)
            .to_proto(),
    );
    let tws = tokio::spawn(async move {
        read_frame(&mut peer).await;
        peer.write_all(&open_orders_end_frame()).await.unwrap();
        read_frame(&mut peer).await;
        peer.write_all(&completed).await.unwrap();
        peer.write_all(&completed_orders_end_frame()).await.unwrap();
        peer
    });

    let started = std::time::Instant::now();
    let outcome = client.wait_for_fill(7, Duration::from_secs(10)).await.unwrap();

    assert!(started.elapsed() < Duration::from_secs(5), "waited {:?}", started.elapsed());
    let OrderOutcome::Ended(status) = outcome else {
        panic!("{outcome:?}");
    };
    assert_eq!(status.status, OrderStatusKind::Cancelled);
    assert_eq!((status.filled, status.remaining), (40.0, 60.0));
    assert_eq!(status.average_fill_price, None);
    drop(tws.await.unwrap());
}

/// An order open orders list is working: its status reaches the wait and no
/// completed-orders request follows.
#[tokio::test]
async fn wait_for_fill_skips_completed_when_order_is_open() {
    use crate::orders::{OrderOutcome, OrderStatusKind};
    use crate::testdata::builders::orders::open_order;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let order = tws_frame(IncomingMessages::OpenOrder, &open_order().order_id(7).to_proto());
    let status = encode_raw_length(&helpers::order_status_frame(CLIENT_ID, 7, OrderStatusKind::Submitted));

    let (client, _bus, mut peer) = tcp_client_with_peer().await;
    let tws = tokio::spawn(async move {
        read_frame(&mut peer).await;
        peer.write_all(&order).await.unwrap();
        peer.write_all(&status).await.unwrap();
        peer.write_all(&open_orders_end_frame()).await.unwrap();
        let next = tokio::time::timeout(Duration::from_millis(300), peer.read_u32()).await;
        assert!(next.is_err(), "unexpected request: {next:?}");
        peer
    });

    let outcome = client.wait_for_fill(7, Duration::from_millis(100)).await.unwrap();

    assert!(
        matches!(&outcome, OrderOutcome::TimedOut(Some(s)) if s.status == OrderStatusKind::Submitted),
        "{outcome:?}"
    );
    drop(tws.await.unwrap());
}

// ---- outbound rate limiter (#950) ----

/// A throttled send awaits rather than blocking the runtime: on a paused
/// clock, a ticker task keeps running while the sends wait out the limit.
#[tokio::test(start_paused = true)]
async fn rate_limiter_awaits_without_blocking_runtime() -> Result<(), Error> {
    let (stream, bus) = make_bus();
    // Burst of 1, then one every 500 ms.
    bus.set_rate_limiter(crate::RateLimiter::per_second(2));

    let ticks = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let ticker = {
        let ticks = ticks.clone();
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(Duration::from_millis(10)).await;
                ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
        })
    };

    let started = std::time::Instant::now();
    for _ in 0..4 {
        bus.send_message(b"request".to_vec()).await?;
    }
    ticker.abort();

    assert_eq!(count_frames(&stream.captured(), b"request"), 4);
    assert!(ticks.load(std::sync::atomic::Ordering::Relaxed) > 0, "runtime blocked while throttled");
    assert!(
        started.elapsed() < Duration::from_millis(500),
        "slept in real time: {:?}",
        started.elapsed()
    );
    Ok(())
}

/// A status that arrived before the stream opened — an order filled between
/// `submit()` and `wait_for_fill` — is the stream's first item.
#[tokio::test]
async fn order_status_stream_starts_with_earlier_status() {
    let (stream, bus) = make_bus();

    stream.push_inbound(order_status_frame(CLIENT_ID, 7, OrderStatusKind::Filled));
    bus.read_and_route_message().await.unwrap();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    assert_eq!(next_message(&mut statuses).await.order_id(), Some(7));
}

/// An order TWS refused with an error and no status (110) reaches a status
/// stream opened afterwards, so `submit()` then `wait_for_fill` cannot miss it.
#[tokio::test]
async fn order_status_stream_starts_with_earlier_rejection() {
    let (stream, bus) = make_bus();

    stream.push_inbound(helpers::error_frame(7, 110, "price off the tick"));
    bus.read_and_route_message().await.unwrap();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    let item = tokio::time::timeout(TICK, statuses.next_routed()).await.expect("no item");
    assert!(matches!(&item, Some(RoutedItem::Error(Error::Notice(n))) if n.code == 110), "{item:?}");
}

/// The stream gets a copy: the `place_order` subscription for the same order
/// and the order-update stream still receive the frame.
#[tokio::test]
async fn order_status_stream_takes_nothing_from_other_routes() {
    let (stream, bus) = make_bus();

    let mut order = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    let mut updates = bus.create_order_update_subscription().await.unwrap();
    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();

    stream.push_inbound(order_status_frame(CLIENT_ID, 7, OrderStatusKind::Submitted));
    bus.read_and_route_message().await.unwrap();

    assert_eq!(next_message(&mut statuses).await.order_id(), Some(7));
    assert_eq!(next_message(&mut order).await.order_id(), Some(7));
    assert_eq!(next_message(&mut updates).await.order_id(), Some(7));
}

/// A status for an order no route claims still reaches its status stream.
#[tokio::test]
async fn order_status_stream_sees_unrouted_status() {
    let (stream, bus) = make_bus();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    stream.push_inbound(order_status_frame(CLIENT_ID, 7, OrderStatusKind::Submitted));
    bus.read_and_route_message().await.unwrap();

    assert_eq!(next_message(&mut statuses).await.order_id(), Some(7));
}

/// Order ids are unique per client only: another client's order 7 (e.g.
/// from `all_open_orders`) is not this client's order 7.
#[tokio::test]
async fn order_status_stream_ignores_other_clients_status() {
    let (stream, bus) = make_bus();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    stream.push_inbound(order_status_frame(CLIENT_ID + 1, 7, OrderStatusKind::Filled));
    bus.read_and_route_message().await.unwrap();

    assert!(tokio::time::timeout(TICK, statuses.next_routed()).await.is_err(), "open stream got it");
    let mut later = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    assert!(
        tokio::time::timeout(TICK, later.next_routed()).await.is_err(),
        "later stream started with it"
    );
}

// ---- other clients' order frames (#1021) ----

fn foreign_open_order_frame(order_id: i32) -> Vec<u8> {
    let order = crate::testdata::builders::orders::open_order()
        .order_id(order_id)
        .client_id(CLIENT_ID + 1);
    binary_proto(IncomingMessages::OpenOrder as i32, &order.to_proto())
}

fn commission_frame(execution_id: &str) -> Vec<u8> {
    binary_proto(
        IncomingMessages::CommissionsReport as i32,
        &crate::proto::CommissionAndFeesReport {
            exec_id: Some(execution_id.into()),
            ..Default::default()
        },
    )
}

/// Order ids are unique per client only: another client's `OpenOrder` and
/// `OrderStatus` for an id this client also uses answer `all_open_orders`,
/// and reach neither this client's order route nor its update stream.
#[tokio::test]
async fn foreign_order_frames_reach_only_shared_channel() {
    let (stream, bus) = make_bus();
    let mut order_route = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    let mut updates = bus.create_order_update_subscription().await.unwrap();
    let mut all_open = bus.send_shared_request(OutgoingMessages::RequestAllOpenOrders, vec![]).await.unwrap();

    stream.push_inbound(foreign_open_order_frame(7));
    stream.push_inbound(order_status_frame(CLIENT_ID + 1, 7, OrderStatusKind::Submitted));
    bus.read_and_route_message().await.unwrap();
    bus.read_and_route_message().await.unwrap();

    assert_eq!(next_message(&mut all_open).await.message_type(), IncomingMessages::OpenOrder);
    assert_eq!(next_message(&mut all_open).await.message_type(), IncomingMessages::OrderStatus);
    assert!(tokio::time::timeout(TICK, order_route.next()).await.is_err(), "order route got it");
    assert!(tokio::time::timeout(TICK, updates.next()).await.is_err(), "update stream got it");
}

/// Another client's execution still answers an `executions()` request (its
/// filter can name that client), with its commission report; one TWS sends
/// unprompted reaches neither this client's order route nor its update stream.
#[tokio::test]
async fn foreign_execution_answers_requests_only() {
    let (stream, bus) = make_bus();
    let mut order_route = bus.send_order_request(OrderId::from(7), vec![]).await.unwrap();
    let mut updates = bus.create_order_update_subscription().await.unwrap();
    let request_id = RequestId::nth(99);
    let mut request = bus.send_request(request_id, vec![]).await.unwrap();

    stream.push_inbound(execution_data_frame(CLIENT_ID + 1, request_id.raw(), 7, "exec-1"));
    stream.push_inbound(commission_frame("exec-1"));
    stream.push_inbound(execution_data_frame(CLIENT_ID + 1, -1, 7, "exec-2"));
    for _ in 0..3 {
        bus.read_and_route_message().await.unwrap();
    }

    assert_eq!(next_message(&mut request).await.message_type(), IncomingMessages::ExecutionData);
    assert_eq!(next_message(&mut request).await.message_type(), IncomingMessages::CommissionsReport);
    assert!(
        tokio::time::timeout(TICK, request.next()).await.is_err(),
        "request got the unprompted one"
    );
    assert!(tokio::time::timeout(TICK, order_route.next()).await.is_err(), "order route got it");
    while let Ok(Some(item)) = tokio::time::timeout(TICK, updates.next()).await {
        let message_type = item.unwrap().message_type();
        assert_ne!(message_type, IncomingMessages::ExecutionData, "update stream got it");
    }
}

#[tokio::test]
async fn foreign_order_bound_is_ignored() {
    let (stream, bus) = make_bus();
    let mut updates = bus.create_order_update_subscription().await.unwrap();

    stream.push_inbound(binary_proto(
        IncomingMessages::OrderBound as i32,
        &order_bound().client_id(CLIENT_ID + 1).to_proto(),
    ));
    bus.read_and_route_message().await.unwrap();

    assert!(tokio::time::timeout(TICK, updates.next()).await.is_err());
}

/// The status in `wait_for_fill`'s open-orders snapshot reply reaches the
/// order's status stream as well as the snapshot.
#[tokio::test]
async fn order_status_stream_sees_snapshot_reply() {
    let (stream, bus) = make_bus();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    let _snapshot = bus
        .send_shared_request(OutgoingMessages::RequestOpenOrders, b"open-orders".to_vec())
        .await
        .unwrap();
    stream.push_inbound(order_status_frame(CLIENT_ID, 7, OrderStatusKind::Submitted));
    bus.read_and_route_message().await.unwrap();

    assert_eq!(next_message(&mut statuses).await.order_id(), Some(7));
}

#[tokio::test]
async fn order_status_stream_ends_on_reset_and_shutdown() {
    let (_stream, bus) = make_bus();

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    bus.reset_channels().await;
    let item = tokio::time::timeout(TICK, statuses.next_routed()).await.expect("no item");
    assert!(matches!(item, Some(RoutedItem::Error(Error::ConnectionReset))), "{item:?}");

    let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
    bus.request_shutdown();
    let item = tokio::time::timeout(TICK, statuses.next_routed()).await.expect("no item");
    assert!(matches!(item, Some(RoutedItem::Error(Error::Shutdown))), "{item:?}");
    assert!(matches!(
        bus.create_order_status_subscription(OrderId::from(7)).await,
        Err(Error::Shutdown)
    ));
}

/// A wait abandoned by its caller (an outer `timeout` or `select!` dropping
/// the future) releases its status stream, and the order's entry with it.
#[tokio::test]
async fn abandoned_order_status_wait_is_released() {
    let (_stream, bus) = make_bus();

    let wait = async {
        let mut statuses = bus.create_order_status_subscription(OrderId::from(7)).await.unwrap();
        statuses.next_routed().await
    };
    assert!(tokio::time::timeout(Duration::from_millis(20), wait).await.is_err(), "nothing was sent");
    drain_cleanup_signals(&bus).await;

    assert!(!bus.order_taps.has_status_entry(OrderId::from(7)), "status stream outlived its wait");
}

/// A panic under the broadcaster lock must not end notice delivery or panic
/// every later broadcast on the dispatcher task.
#[tokio::test]
async fn notice_broadcaster_recovers_from_a_poisoned_lock() {
    let broadcaster = NoticeBroadcaster::new(broadcast::channel(4).0);
    poison_with(|| broadcaster.sender.lock().unwrap());
    assert!(broadcaster.sender.is_poisoned());

    let mut receiver = broadcaster.subscribe();
    broadcaster.broadcast(Notice::synthesized(1, "after poison".into()));
    broadcaster.close();

    assert_eq!(receiver.recv().await.unwrap().message, "after poison");
    assert!(matches!(receiver.recv().await, Err(broadcast::error::RecvError::Closed)));
}

/// A reconnect that gives up leaves the session `Failed`, not shut down: a
/// later request and `wait_connected` both get `ConnectionFailed`, the
/// documented terminal error, so a retry loop can tell "reconnecting"
/// (`ConnectionReset`) from "gone" (#1052).
#[tokio::test]
async fn exhausted_reconnect_refuses_later_sends_with_connection_failed() {
    let stream = MemoryStream::default();
    let mut connection = AsyncConnection::stubbed(stream.clone(), 28);
    connection.set_server_version_for_test(server_versions::PROTOBUF_REST_MESSAGES_3);
    connection.max_reconnect_attempts = Some(1);
    stream.set_reconnect_failures(1);
    // Too short for a message id: InvalidFrame, which triggers the reconnect.
    stream.push_inbound(b"xx".to_vec());

    let bus = Arc::new(AsyncTcpMessageBus::new(connection));
    let mut in_flight = bus.send_request(RequestId::nth(100), vec![]).await.unwrap();
    bus.clone().process_messages().expect("process_messages");

    // The reset arrives after the session is marked down, so the wait below
    // cannot see the session as still connected.
    let item = tokio::time::timeout(Duration::from_secs(5), in_flight.next_routed())
        .await
        .expect("in-flight request got no notification")
        .expect("in-flight channel closed early");
    assert!(matches!(item, RoutedItem::Error(Error::ConnectionReset)), "in-flight: {item:?}");

    let waited = tokio::time::timeout(Duration::from_secs(5), bus.wait_connected())
        .await
        .expect("wait_connected did not return after the reconnect gave up");
    assert!(matches!(waited, Err(Error::ConnectionFailed)), "wait_connected: {waited:?}");

    let sent = bus.send_request(RequestId::nth(1), vec![]).await.err();
    assert!(matches!(sent, Some(Error::ConnectionFailed)), "send_request: {sent:?}");
    // Streams that skip the send gate report the same reason.
    let updates = bus.create_order_update_subscription().await.err();
    assert!(matches!(updates, Some(Error::ConnectionFailed)), "order updates: {updates:?}");
    let status = bus.create_order_status_subscription(OrderId::from(7)).await.err();
    assert!(matches!(status, Some(Error::ConnectionFailed)), "order status: {status:?}");
}

/// After shutdown, the send gate refuses with `Shutdown` - not the
/// `ConnectionReset` that means "reconnecting", which would invite a retry
/// against a client that is gone (#1052).
#[tokio::test]
async fn send_after_shutdown_fails_with_shutdown() {
    let (_, bus) = make_bus();
    let mb: &dyn AsyncMessageBus = bus.as_ref();
    mb.ensure_shutdown().await;

    let sent = bus.send_request(RequestId::nth(1), vec![]).await.err();
    assert!(matches!(sent, Some(Error::Shutdown)), "send_request: {sent:?}");
    let waited = bus.wait_connected().await;
    assert!(matches!(waited, Err(Error::Shutdown)), "wait_connected: {waited:?}");
}

/// A reset starts a new session generation, which subscriptions made before
/// it compare against to skip a cancel the new session couldn't place.
#[tokio::test]
async fn reset_channels_starts_new_session_generation() {
    let (_stream, bus) = make_bus();
    assert_eq!(bus.session_generation(), 0);

    bus.reset_channels().await;
    bus.reset_channels().await;

    assert_eq!(bus.session_generation(), 2);
}