repe 10.0.0

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

/// Derive the `Sec-WebSocket-Accept` response header value from a client's
/// `Sec-WebSocket-Key`, per RFC 6455.
///
/// For an embedder answering the upgrade with its own HTTP stack before
/// handing the connection to [`SharedWebSocketServer::adopt_upgraded`].
/// This is the one piece of the handshake that is easy to get subtly
/// wrong, and getting it wrong is rejected by the *client*, not by this
/// crate.
///
/// A thin wrapper rather than a re-export of the transport's function, so
/// this signature is repe's to keep stable across a transport version
/// bump.
pub fn derive_accept_key(sec_websocket_key: &[u8]) -> String {
    tokio_tungstenite::tungstenite::handshake::derive_accept_key(sec_websocket_key)
}

type ConnectHook = Arc<dyn Fn(PeerHandle) + Send + Sync>;
type ConnectCtxHook = Arc<dyn Fn(&PeerHandle, &HandshakeContext) + Send + Sync>;
type DisconnectHook = Arc<dyn Fn(PeerId) + Send + Sync>;
type ErrorHook = Arc<dyn Fn(&ConnectionError) + Send + Sync>;

/// Default per-connection outbound channel capacity.
///
/// Each accepted connection allocates a bounded `tokio::sync::mpsc`
/// channel of this size for outbound messages (responses + pushed
/// notifies). A full channel surfaces back as
/// [`PeerSendError::Full`](crate::PeerSendError) on the next
/// [`PeerHandle::send_notify`] attempt. Override per server with
/// [`WebSocketServer::with_outbound_capacity`].
pub const DEFAULT_OUTBOUND_CAPACITY: usize = 256;

/// Default cap on concurrently-running off-reader handlers (registered
/// via `Router::with_*_blocking`) per connection. Bounds how many
/// blocking-pool threads one connection can occupy at once. Override
/// with [`WebSocketServer::with_offreader_limit`]; `0` removes the cap.
pub const DEFAULT_OFFREADER_LIMIT: usize = 16;

/// Upper bound on how long the writer task spends draining queued
/// messages after the connection's reader has exited. A slow or
/// unresponsive peer (where TCP has not yet errored) cannot pin the
/// connection task open past this deadline.
const SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);

/// A transport-level event reported to a [`WebSocketServer::on_error`]
/// callback.
///
/// These are the failures the server would otherwise print to stderr
/// (handshake / connection I/O / a caught handler panic) plus the
/// off-reader saturation rejection, surfaced as a typed value so an
/// embedder can route them into its own `log` / `tracing` pipeline,
/// filter by category, or branch on the wire [`ErrorCode`] that reached
/// the client. With no callback registered the server falls back to its
/// historical `eprintln!` behavior for the three logged categories and
/// stays silent for [`Saturation`](ConnectionError::Saturation), which
/// only ever produced a wire response.
///
/// The category split mirrors the wire-code split: a caught panic is an
/// [`ErrorCode::InternalError`] and a saturation rejection is an
/// [`ErrorCode::ResourceExhausted`] (see [`error_code`]). Handshake and
/// connection I/O failures tore the connection down before or after any
/// REPE response, so they carry no wire code.
///
/// [`error_code`]: ConnectionError::error_code
#[non_exhaustive]
#[derive(Debug)]
pub enum ConnectionError {
    /// The WebSocket upgrade handshake failed (bad path, malformed
    /// upgrade, I/O error during the upgrade). No connection was
    /// established.
    Handshake(RepeError),
    /// An established connection ended on a transport or protocol error
    /// (the peer vanished, a non-binary frame arrived, the socket
    /// errored). This is the value [`SharedWebSocketServer::serve_connection`]
    /// also returns to a co-hosting embedder.
    Connection(RepeError),
    /// An off-reader handler panicked. The panic was caught and mapped to
    /// an [`ErrorCode::InternalError`] response (for a request) or
    /// swallowed (for a notify); the connection was deliberately kept
    /// alive because it is shared with other concurrent transfers.
    HandlerPanic {
        /// The query path of the handler that panicked.
        method: String,
    },
    /// An outbound message exceeded the connection's
    /// [`assumed_peer_frame_limit`](crate::WebSocketLimits::assumed_peer_frame_limit)
    /// and was not sent.
    ///
    /// A response was replaced with an [`ErrorCode::InternalError`] response so
    /// the caller learns its request produced an undeliverable result; a notify
    /// was dropped, since it has no response to carry the failure. Either way
    /// the connection stays up, which is the point: sending the message would
    /// have made the peer's reader close it.
    OutboundTooLarge {
        /// The query path of the message that was too large.
        method: String,
        /// Serialized size of the message that was refused.
        size: usize,
        /// The configured assumption it exceeded.
        limit: usize,
    },
    /// An off-reader request was rejected because the connection's
    /// [`with_offreader_limit`](WebSocketServer::with_offreader_limit)
    /// cap was reached. The client received an
    /// [`ErrorCode::ResourceExhausted`] response and should retry.
    Saturation {
        /// The query path of the rejected request.
        method: String,
    },
}

impl ConnectionError {
    /// The REPE error code that reached (or would reach) the client for
    /// this event, if any. A caught panic surfaces as
    /// [`ErrorCode::InternalError`] and a saturation rejection as
    /// [`ErrorCode::ResourceExhausted`]; handshake and connection I/O
    /// failures carry no wire code because no REPE response was sent.
    pub fn error_code(&self) -> Option<ErrorCode> {
        match self {
            ConnectionError::HandlerPanic { .. } => Some(ErrorCode::InternalError),
            ConnectionError::Saturation { .. } => Some(ErrorCode::ResourceExhausted),
            // A refused response is substituted with an InternalError response;
            // a refused notify carries no code because notifies have none.
            ConnectionError::OutboundTooLarge { .. } => Some(ErrorCode::InternalError),
            ConnectionError::Handshake(_) | ConnectionError::Connection(_) => None,
        }
    }
}

impl std::fmt::Display for ConnectionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConnectionError::Handshake(err) => write!(f, "websocket handshake error: {err}"),
            ConnectionError::Connection(err) => write!(f, "websocket connection error: {err}"),
            ConnectionError::HandlerPanic { method } => {
                write!(
                    f,
                    "off-reader handler panicked for {method}; connection kept alive"
                )
            }
            ConnectionError::Saturation { method } => {
                write!(f, "off-reader dispatch limit reached for {method}; retry")
            }
            ConnectionError::OutboundTooLarge {
                method,
                size,
                limit,
            } => {
                write!(
                    f,
                    "outbound message for {method} is {size} bytes, over the {limit} byte assumed \
                     peer frame limit; not sent"
                )
            }
        }
    }
}

impl std::error::Error for ConnectionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ConnectionError::Handshake(err) | ConnectionError::Connection(err) => Some(err),
            ConnectionError::HandlerPanic { .. }
            | ConnectionError::Saturation { .. }
            | ConnectionError::OutboundTooLarge { .. } => None,
        }
    }
}

/// Read-only snapshot of the WebSocket upgrade request, captured during
/// the handshake and handed to an
/// [`on_peer_connect_with_handshake`](WebSocketServer::on_peer_connect_with_handshake)
/// hook.
///
/// An embedder whose canonical client identity rides in the upgrade
/// request — a token in the query string, an auth header — derives its
/// key from this context at connect time and attaches it to the
/// freshly-inserted peer with
/// [`PeerRegistry::alias`](crate::PeerRegistry::alias), so later targeted
/// pushes can address the peer by that key. The path, query, and headers
/// are captured as owned values, so the context outlives the handshake
/// and is cheap to clone.
///
/// If the embedder's key instead arrives in a request *body*, this hook
/// is unnecessary — the handler already has both the key and the peer via
/// [`CallContext::peer`](crate::CallContext::peer).
#[derive(Clone)]
pub struct HandshakeContext {
    path: String,
    query: Option<String>,
    headers: Vec<(String, String)>,
}

impl HandshakeContext {
    /// Capture the parts of an upgrade request an embedder may key on.
    ///
    /// Public for the embedder whose HTTP framework performed the upgrade
    /// itself and who is serving the result through
    /// [`SharedWebSocketServer::adopt_upgraded`]: repe never saw that
    /// request, so it cannot capture the context on its own. Such a
    /// handler is holding the whole request, which makes it the
    /// best-positioned caller in the crate for the identity-keying this
    /// type exists for. Pair it with
    /// [`SharedWebSocketServer::serve_connection_with_handshake`].
    ///
    /// Generic over the body type so it accepts any `http::Request`,
    /// whatever the framework parameterizes it with, and borrows rather
    /// than consumes so the caller can still answer the upgrade with it.
    /// The `http` version is the one this crate's transport is built
    /// against, reachable as
    /// `repe::tokio_tungstenite::tungstenite::http` if you need to name
    /// it.
    ///
    /// Connections repe upgrades itself get this for free — the built-in
    /// `serve*` loops and
    /// [`WebSocketServer::accept_with_handshake`](WebSocketServer::accept_with_handshake)
    /// capture it — so this is only for the adopted path.
    pub fn from_http_request<T>(request: &tungstenite::http::Request<T>) -> Self {
        let uri = request.uri();
        let headers = request
            .headers()
            .iter()
            .filter_map(|(name, value)| {
                // Keep only values that round-trip to clean text. The
                // documented use is keying off a token / auth header, so a
                // value that is not valid (visible ASCII) text is better
                // surfaced as an absent header (fail-closed: the embedder
                // sees `None` and can reject the connection) than captured
                // as a lossily-mangled string that no `get_by` lookup would
                // ever match.
                value
                    .to_str()
                    .ok()
                    .map(|v| (name.as_str().to_owned(), v.to_owned()))
            })
            .collect();
        Self {
            path: uri.path().to_owned(),
            query: uri.query().map(str::to_owned),
            headers,
        }
    }

    /// The request-target path of the upgrade (e.g. `/repe`). This is the
    /// same path [`WebSocketServer::accept`] validated against, normalized
    /// by the client; the query string is not included.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The raw query string of the upgrade request (the part after `?`),
    /// if present. Percent-decoding and key/value splitting are left to
    /// the embedder so repe pulls in no URL-parsing dependency.
    pub fn query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    /// The first value of the named header, matched case-insensitively
    /// (HTTP header names are case-insensitive). Returns `None` if the
    /// header was absent, or if its value was not valid (visible ASCII)
    /// text — such values are dropped at capture rather than mangled, so a
    /// token or auth header that cannot round-trip to a clean string reads
    /// as absent rather than as a corrupted key.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(n, _)| n.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// Iterate over every captured header as `(name, value)` pairs, in
    /// the order they arrived. Header names retain the case the client
    /// sent; use [`header`](Self::header) for a case-insensitive lookup.
    /// Headers whose value was not valid (visible ASCII) text are dropped
    /// at capture (see [`header`](Self::header)), so they do not appear
    /// here either.
    pub fn headers(&self) -> impl Iterator<Item = (&str, &str)> {
        self.headers
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
    }
}

impl std::fmt::Debug for HandshakeContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Hand-written rather than derived (mirroring `PeerHandle` and
        // `CallContext` in the peer module): the query string and header
        // values can carry credentials — the documented use keys off an
        // auth header or a token in the query — so a routine
        // `tracing::debug!(?ctx)` must not spill them into logs. The path
        // and header names are safe to show; values and the query are
        // redacted.
        f.debug_struct("HandshakeContext")
            .field("path", &self.path)
            .field("query", &self.query.as_ref().map(|_| "<redacted>"))
            .field(
                "headers",
                &self
                    .headers
                    .iter()
                    .map(|(name, _)| name.as_str())
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

/// An opaque, cloneable shutdown trigger for connections served under a
/// [`SharedWebSocketServer`].
///
/// A one-port co-hosting embedder owns its own accept loop, so it cannot
/// hand its listener to
/// [`serve_listener_with_graceful_drain`](WebSocketServer::serve_listener_with_graceful_drain).
/// Instead it creates one `ShutdownToken`, serves each connection with
/// [`serve_connection_with_cancel`](SharedWebSocketServer::serve_connection_with_cancel),
/// and calls [`cancel`](Self::cancel) on shutdown. Every off-reader
/// handler then observes the wind-down through
/// [`CallContext::is_cancelled`](crate::CallContext::is_cancelled) /
/// [`CallContext::cancelled`](crate::CallContext::cancelled), while the
/// embedder drains its own task set.
///
/// The backing `tokio_util` cancellation type is deliberately hidden so
/// the embedder is not coupled to that crate's version; the turnkey
/// [`serve_listener_with_graceful_drain`](WebSocketServer::serve_listener_with_graceful_drain)
/// uses the same machinery internally.
#[derive(Clone, Default)]
pub struct ShutdownToken {
    inner: CancellationToken,
}

impl ShutdownToken {
    /// Create a fresh, un-cancelled trigger.
    pub fn new() -> Self {
        Self::default()
    }

    /// Signal every connection served under this token to wind down.
    /// Idempotent: cancelling again is a no-op.
    pub fn cancel(&self) {
        self.inner.cancel();
    }

    /// Whether [`cancel`](Self::cancel) has fired.
    pub fn is_cancelled(&self) -> bool {
        self.inner.is_cancelled()
    }

    /// Resolves once [`cancel`](Self::cancel) fires, so an embedder can
    /// `select!` on the same shutdown signal it hands to the server.
    pub async fn cancelled(&self) {
        self.inner.cancelled().await;
    }

    /// Mint a per-connection child token. Cancelling this token cancels
    /// every child; a child can also be cancelled on its own (on
    /// disconnect) without affecting the parent or siblings.
    fn child_token(&self) -> CancellationToken {
        self.inner.child_token()
    }
}

impl std::fmt::Debug for ShutdownToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ShutdownToken")
            .field("cancelled", &self.is_cancelled())
            .finish()
    }
}

/// [`CancelSignal`] backed by a `tokio_util` [`CancellationToken`]. One
/// per off-reader dispatch (and one shared by the connection's inline
/// dispatch); cheap to build since it just wraps a token clone.
struct TokenSignal(CancellationToken);

impl CancelSignal for TokenSignal {
    fn is_cancelled(&self) -> bool {
        self.0.is_cancelled()
    }

    fn cancelled(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        Box::pin(self.0.cancelled())
    }
}

/// Awaits a spawned task, aborting it if this future is itself dropped
/// before it completes.
///
/// The connection handler wraps its writer task in this so that when a
/// server-level graceful drain aborts the connection task at its
/// deadline, the separately-spawned writer task is torn down with it
/// rather than left draining for up to `SHUTDOWN_DRAIN_TIMEOUT` longer.
/// On normal completion the abort fires on an already-finished handle,
/// which is a no-op.
struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);

impl<T> Drop for AbortOnDrop<T> {
    fn drop(&mut self) {
        self.0.abort();
    }
}

impl<T> Future for AbortOnDrop<T> {
    type Output = Result<T, tokio::task::JoinError>;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.get_mut().0).poll(cx)
    }
}

/// Route a transport-level event to the registered [`on_error`] hooks, or
/// fall back to the server's historical stderr behavior when none are
/// registered.
///
/// [`on_error`]: WebSocketServer::on_error
fn report_error(hooks: &[ErrorHook], err: ConnectionError) {
    if !hooks.is_empty() {
        for hook in hooks {
            hook(&err);
        }
        return;
    }
    // No hooks: preserve the historical stderr behavior for the
    // categories that logged before, and stay silent for saturation
    // (which never logged -- it only produced a wire error response).
    match &err {
        ConnectionError::Saturation { .. } => {}
        logged => eprintln!("[repe] {logged}"),
    }
}

pub struct WebSocketServer {
    router: Router,
    limits: crate::WebSocketLimits,
    outbound_capacity: usize,
    offreader_limit: Option<usize>,
    peer_id_counter: Arc<AtomicU64>,
    on_connect: Vec<ConnectHook>,
    on_connect_ctx: Vec<ConnectCtxHook>,
    on_disconnect: Vec<DisconnectHook>,
    on_error: Vec<ErrorHook>,
}

impl WebSocketServer {
    pub fn new(router: Router) -> Self {
        Self {
            router,
            limits: crate::WebSocketLimits::default(),
            outbound_capacity: DEFAULT_OUTBOUND_CAPACITY,
            offreader_limit: Some(DEFAULT_OFFREADER_LIMIT),
            peer_id_counter: Arc::new(AtomicU64::new(0)),
            on_connect: Vec::new(),
            on_connect_ctx: Vec::new(),
            on_disconnect: Vec::new(),
            on_error: Vec::new(),
        }
    }

    pub async fn listen<A: ToSocketAddrs>(addr: A) -> std::io::Result<TcpListener> {
        TcpListener::bind(addr).await
    }

    /// Per-connection outbound channel capacity. Defaults to
    /// [`DEFAULT_OUTBOUND_CAPACITY`]. A full channel returns
    /// [`PeerSendError::Full`](crate::PeerSendError) from
    /// [`PeerHandle::send_notify`]; the embedder decides whether to
    /// retry, drop, or prune.
    ///
    /// Panics if `capacity == 0` (bounded mpsc with zero capacity has
    /// surprising semantics; this is programmer error).
    pub fn with_outbound_capacity(mut self, capacity: usize) -> Self {
        assert!(
            capacity >= 1,
            "WebSocketServer outbound capacity must be >= 1"
        );
        self.outbound_capacity = capacity;
        self
    }

    /// Size limits for every connection this server accepts. Defaults to
    /// [`WebSocketLimits::default`](crate::WebSocketLimits::default).
    ///
    /// The inbound thresholds are applied during the handshake, so they reach
    /// only connections this server upgrades itself: [`serve`](Self::serve) and
    /// friends, plus [`accept_with_limits`](Self::accept_with_limits). A
    /// connection the embedder upgraded and handed to
    /// [`SharedWebSocketServer::serve_connection`] carries whatever inbound
    /// limits that upgrade was given, and cannot be retrofitted here: the
    /// underlying transport fixes them at construction and exposes no setter.
    /// The outbound guard, being repe's own, applies on every path.
    pub fn with_limits(mut self, limits: crate::WebSocketLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Cap on concurrently-running off-reader handlers (those registered
    /// via `Router::with_json_blocking` and friends) per connection.
    /// Defaults to [`DEFAULT_OFFREADER_LIMIT`].
    ///
    /// When the cap is reached, a further off-reader request gets an
    /// error response ([`ErrorCode::ResourceExhausted`]) and the client
    /// should retry; the request is never queued and the reader is never
    /// blocked waiting for a slot — blocking it would stall the very
    /// frames (ACKs, cancels) that in-flight transfers need to finish
    /// and free a slot. Pass `0` to remove the cap (unbounded), which
    /// matches a hand-rolled `spawn_blocking` and is only sensible if you
    /// have sized the runtime's blocking pool accordingly.
    pub fn with_offreader_limit(mut self, limit: usize) -> Self {
        self.offreader_limit = (limit > 0).then_some(limit);
        self
    }

    /// Attach a [`PeerRegistry`] so this server's accepted peers are
    /// inserted on connect and removed on disconnect. The registry is
    /// `Arc`-shared so background tasks can clone it and broadcast.
    ///
    /// Sugar over [`on_peer_connect`](Self::on_peer_connect) +
    /// [`on_peer_disconnect`](Self::on_peer_disconnect). Calling this
    /// does not exclude additional connect/disconnect callbacks; hooks
    /// fire in registration order.
    ///
    /// The server's `PeerId` allocator is swapped for the registry's,
    /// so two `WebSocketServer`s sharing one registry mint
    /// non-colliding ids. If you call `with_peer_registry` more than
    /// once on the same server, the most recent registry's counter
    /// wins.
    pub fn with_peer_registry(mut self, registry: PeerRegistry) -> Self {
        self.peer_id_counter = registry.id_counter();
        let insert_registry = registry.clone();
        let remove_registry = registry;
        self.on_peer_connect(move |peer| insert_registry.insert(peer))
            .on_peer_disconnect(move |id| {
                remove_registry.remove(id);
            })
    }

    /// Run `f` from the per-connection task on accept, just after the
    /// `PeerHandle` is built and *before* the reader/writer tasks
    /// start processing traffic. Notifies queued from `f` via
    /// `peer.send_notify(...)` are guaranteed to land on the wire
    /// before any response.
    ///
    /// The callback runs synchronously on the accept task and must not
    /// block; offload work to a channel or `tokio::spawn` if needed.
    pub fn on_peer_connect<F>(mut self, f: F) -> Self
    where
        F: Fn(PeerHandle) + Send + Sync + 'static,
    {
        self.on_connect.push(Arc::new(f));
        self
    }

    /// Like [`on_peer_connect`](Self::on_peer_connect), but the callback
    /// also receives the [`HandshakeContext`] of the upgrade request
    /// (path, query, headers). Use it when the embedder's client identity
    /// rides in the handshake: derive a key from the request and attach it
    /// to the just-inserted peer with
    /// [`PeerRegistry::alias`](crate::PeerRegistry::alias), so later
    /// targeted pushes can address the peer by that key.
    ///
    /// ```ignore
    /// let peers = PeerRegistry::new();
    /// let server = WebSocketServer::new(router)
    ///     .with_peer_registry(peers.clone())
    ///     .on_peer_connect_with_handshake({
    ///         let peers = peers.clone();
    ///         move |peer, hs| {
    ///             if let Some(token) = hs.header("authorization") {
    ///                 peers.alias(peer.peer_id(), token);
    ///             }
    ///         }
    ///     });
    /// ```
    ///
    /// These hooks fire **after** the plain
    /// [`on_peer_connect`](Self::on_peer_connect) hooks (so a
    /// [`with_peer_registry`](Self::with_peer_registry) insert has already
    /// run and the peer is present for `alias`), in registration order,
    /// and still before the connection processes any traffic. Like the
    /// plain hook the callback runs synchronously on the accept task and
    /// must not block.
    ///
    /// The context is available wherever the handshake is: the built-in
    /// `serve*` loops, and the co-hosting
    /// [`accept_with_handshake`](Self::accept_with_handshake) +
    /// [`serve_connection_with_handshake`](SharedWebSocketServer::serve_connection_with_handshake)
    /// path. A connection served through plain
    /// [`serve_connection`](SharedWebSocketServer::serve_connection)
    /// (which carries no captured handshake) does not fire these hooks.
    pub fn on_peer_connect_with_handshake<F>(mut self, f: F) -> Self
    where
        F: Fn(&PeerHandle, &HandshakeContext) + Send + Sync + 'static,
    {
        self.on_connect_ctx.push(Arc::new(f));
        self
    }

    /// Run `f` when the connection closes (any exit path: clean Close
    /// frame, transport error, handler panic). Fires exactly once per
    /// accepted connection.
    pub fn on_peer_disconnect<F>(mut self, f: F) -> Self
    where
        F: Fn(PeerId) + Send + Sync + 'static,
    {
        self.on_disconnect.push(Arc::new(f));
        self
    }

    /// Run `f` for each transport-level [`ConnectionError`]: a handshake
    /// or connection I/O failure (in the built-in accept loops), a caught
    /// off-reader handler panic, or an off-reader saturation rejection.
    /// Lets an embedder route these into its own `log` / `tracing`
    /// pipeline instead of the default raw `eprintln!`.
    ///
    /// Composes like [`on_peer_connect`](Self::on_peer_connect) /
    /// [`on_peer_disconnect`](Self::on_peer_disconnect): every registered
    /// callback fires in registration order. Registering at least one
    /// callback suppresses the default stderr logging entirely — the
    /// callbacks become the sole sink, so a callback that wants the old
    /// behavior should print it. With no callback registered the server
    /// keeps its historical stderr behavior (and stays silent on
    /// saturation, which never logged).
    ///
    /// The callback runs synchronously on the task that detected the
    /// error (an accept task, a connection's reader, or an off-reader
    /// blocking thread) and must not block.
    pub fn on_error<F>(mut self, f: F) -> Self
    where
        F: Fn(&ConnectionError) + Send + Sync + 'static,
    {
        self.on_error.push(Arc::new(f));
        self
    }

    pub async fn serve<A: ToSocketAddrs>(self, addr: A, path: &str) -> std::io::Result<()> {
        let listener = Self::listen(addr).await?;
        self.serve_listener(listener, path).await
    }

    /// Bind `addr` and serve REPE WebSocket connections until
    /// `shutdown` resolves, then stop accepting and return `Ok(())`.
    ///
    /// For embedders that run the server in-process and need a clean
    /// stop without tearing down the runtime. `shutdown` is any future:
    /// a [`tokio::sync::oneshot`] receiver, a `Notify`, a timer.
    ///
    /// Already-accepted connections are **not** awaited — each runs on
    /// its own detached task and continues until its peer disconnects
    /// or it errors; this call returns as soon as the accept loop
    /// stops. Track connection lifetimes yourself (e.g. via a
    /// [`PeerRegistry`]) if you need to drain them before exiting.
    ///
    /// Equivalent to [`serve`](Self::serve) when `shutdown` never
    /// resolves.
    pub async fn serve_with_shutdown<A: ToSocketAddrs>(
        self,
        addr: A,
        path: &str,
        shutdown: impl Future<Output = ()>,
    ) -> std::io::Result<()> {
        let listener = Self::listen(addr).await?;
        self.serve_listener_with_shutdown(listener, path, shutdown)
            .await
    }

    /// Serve an already-bound listener until the listener errors or the
    /// task is dropped. For a clean stop, use
    /// [`serve_listener_with_shutdown`](Self::serve_listener_with_shutdown).
    pub async fn serve_listener(self, listener: TcpListener, path: &str) -> std::io::Result<()> {
        self.serve_listener_with_shutdown(listener, path, std::future::pending::<()>())
            .await
    }

    /// Like [`serve_with_shutdown`](Self::serve_with_shutdown) but takes
    /// an already-bound [`TcpListener`] instead of an address, mirroring
    /// the [`serve`](Self::serve) / [`serve_listener`](Self::serve_listener)
    /// pair. This is the single accept loop the other `serve*` entry
    /// points delegate to; see
    /// [`serve_with_shutdown`](Self::serve_with_shutdown) for the
    /// shutdown semantics (already-accepted connections are not
    /// awaited).
    pub async fn serve_listener_with_shutdown(
        self,
        listener: TcpListener,
        path: &str,
        shutdown: impl Future<Output = ()>,
    ) -> std::io::Result<()> {
        let path = normalize_path(path);
        let shared = self.into_shared();

        tokio::pin!(shutdown);
        loop {
            tokio::select! {
                // `TcpListener::accept` is cancel-safe, so losing this
                // branch to `shutdown` cannot drop an accepted stream.
                accepted = listener.accept() => {
                    let (stream, _addr) = accepted?;
                    let path = path.clone();
                    let shared = shared.clone();
                    tokio::spawn(async move {
                        shared.accept_and_serve(stream, &path, None).await;
                    });
                }
                _ = &mut shutdown => break,
            }
        }
        Ok(())
    }

    /// Bind `addr` and serve REPE WebSocket connections until `shutdown`
    /// resolves, then stop accepting, signal in-flight off-reader
    /// handlers to cancel, and await already-accepted connections for up
    /// to `drain_timeout` before aborting whatever remains.
    ///
    /// The draining counterpart to
    /// [`serve_with_shutdown`](Self::serve_with_shutdown): where that one
    /// returns the instant the accept loop stops (connections detached),
    /// this one tracks every connection it spawns in a `JoinSet` and
    /// gives in-flight work a bounded window to finish. See
    /// [`serve_listener_with_graceful_drain`](Self::serve_listener_with_graceful_drain)
    /// for the full semantics.
    pub async fn serve_with_graceful_drain<A: ToSocketAddrs>(
        self,
        addr: A,
        path: &str,
        shutdown: impl Future<Output = ()>,
        drain_timeout: Duration,
    ) -> std::io::Result<()> {
        let listener = Self::listen(addr).await?;
        self.serve_listener_with_graceful_drain(listener, path, shutdown, drain_timeout)
            .await
    }

    /// Like [`serve_with_graceful_drain`](Self::serve_with_graceful_drain)
    /// but takes an already-bound [`TcpListener`].
    ///
    /// When `shutdown` resolves the loop stops accepting and:
    ///
    /// 1. signals every accepted connection to cancel — each off-reader
    ///    handler observes this through
    ///    [`CallContext::is_cancelled`](crate::CallContext::is_cancelled)
    ///    / [`CallContext::cancelled`](crate::CallContext::cancelled), and
    ///    each connection's reader stops accepting new requests;
    /// 2. awaits the connection tasks until `drain_timeout` elapses;
    /// 3. aborts any still-running connection tasks (which tears down
    ///    their writer tasks too, so this server-level deadline
    ///    supersedes the per-connection `SHUTDOWN_DRAIN_TIMEOUT` writer
    ///    drain).
    ///
    /// This is the turnkey audience's entry point: it owns the accept
    /// loop and the `JoinSet`. A one-port co-hosting embedder that owns
    /// its own accept loop instead pairs
    /// [`serve_connection_with_cancel`](SharedWebSocketServer::serve_connection_with_cancel)
    /// with its own [`ShutdownToken`] and `JoinSet`.
    ///
    /// A misbehaving off-reader handler that never polls its cancellation
    /// signal still holds its blocking-pool thread past `drain_timeout`
    /// (a blocking thread cannot be aborted); the abort tears down the
    /// connection's reader/writer, not such a handler. Pairing the drain
    /// with handlers that poll `is_cancelled()` is what makes the
    /// timeout a backstop rather than the common wait.
    pub async fn serve_listener_with_graceful_drain(
        self,
        listener: TcpListener,
        path: &str,
        shutdown: impl Future<Output = ()>,
        drain_timeout: Duration,
    ) -> std::io::Result<()> {
        let path = normalize_path(path);
        let shared = self.into_shared();
        // Parent of every connection's cancellation token. Cancelled once
        // on shutdown to wake all in-flight handlers at once.
        let parent = ShutdownToken::new();
        let mut conns: JoinSet<()> = JoinSet::new();

        tokio::pin!(shutdown);
        loop {
            tokio::select! {
                accepted = listener.accept() => {
                    let (stream, _addr) = accepted?;
                    let path = path.clone();
                    let shared = shared.clone();
                    let parent = parent.clone();
                    conns.spawn(async move {
                        shared.accept_and_serve(stream, &path, Some(&parent)).await;
                    });
                    // Reap finished connections so the JoinSet tracks only
                    // live ones rather than growing with every accept.
                    while conns.try_join_next().is_some() {}
                }
                _ = &mut shutdown => break,
            }
        }

        // Shutdown: wake in-flight handlers, then drain with a deadline.
        parent.cancel();
        let deadline = Instant::now() + drain_timeout;
        loop {
            match tokio::time::timeout_at(deadline, conns.join_next()).await {
                Ok(Some(_)) => {}  // a connection drained
                Ok(None) => break, // all connections drained
                Err(_) => {
                    // Deadline hit: abort the stragglers and await the
                    // aborts (prompt, since they unwind at await points).
                    conns.shutdown().await;
                    break;
                }
            }
        }
        Ok(())
    }

    /// Consume this builder into a cheap, cloneable
    /// [`SharedWebSocketServer`]. The per-connection configuration
    /// (router, hooks, capacities) is built exactly once here; each
    /// clone of the returned handle is an `Arc` clone.
    ///
    /// Use with [`accept`](Self::accept) and
    /// [`SharedWebSocketServer::serve_connection`] to serve connections
    /// the embedder accepts itself — e.g. peek the upgrade header on
    /// each accepted stream, route WebSocket upgrades to REPE and send
    /// everything else to an HTTP handler, all on one TCP port. The
    /// built-in [`serve`](Self::serve) loop is implemented on top of
    /// exactly this.
    pub fn into_shared(self) -> SharedWebSocketServer {
        SharedWebSocketServer {
            config: Arc::new(ConnectionConfig {
                router: self.router,
                limits: self.limits,
                outbound_capacity: self.outbound_capacity,
                offreader_limit: self.offreader_limit,
                peer_id_counter: self.peer_id_counter,
                on_connect: Arc::new(self.on_connect),
                on_connect_ctx: Arc::new(self.on_connect_ctx),
                on_disconnect: Arc::new(self.on_disconnect),
                on_error: Arc::new(self.on_error),
            }),
        }
    }

    /// Perform the REPE WebSocket handshake on an already-accepted
    /// `stream`, validating that the client requested `path`. Returns
    /// the upgraded [`WebSocketStream`] ready to hand to
    /// [`SharedWebSocketServer::serve_connection`].
    ///
    /// An associated function: it needs only the path, not the
    /// router/hooks, so it composes with any [`SharedWebSocketServer`].
    /// `path` is normalized exactly as [`serve`](Self::serve)
    /// normalizes it.
    pub async fn accept(
        stream: TcpStream,
        path: &str,
    ) -> Result<WebSocketStream<TcpStream>, RepeError> {
        Self::accept_with_limits(stream, path, crate::WebSocketLimits::default()).await
    }

    /// [`accept`](Self::accept) with explicit size limits.
    ///
    /// An associated function cannot see a builder-set
    /// [`with_limits`](Self::with_limits), and the inbound thresholds are fixed
    /// during the handshake, so an embedder driving its own accept must pass
    /// them here. Use the same value the server was built with, or the inbound
    /// limits will not match what the rest of the server expects.
    pub async fn accept_with_limits(
        stream: TcpStream,
        path: &str,
        limits: crate::WebSocketLimits,
    ) -> Result<WebSocketStream<TcpStream>, RepeError> {
        // No handshake capture: this path feeds `serve_connection`, which
        // does not fire handshake-aware hooks.
        accept_repe_websocket(stream, &normalize_path(path), false, limits)
            .await
            .map(|(ws, _handshake)| ws)
    }

    /// Like [`accept`](Self::accept), but also returns the
    /// [`HandshakeContext`] of the upgrade request so a co-hosting
    /// embedder can fire
    /// [`on_peer_connect_with_handshake`](Self::on_peer_connect_with_handshake)
    /// hooks. Pair the returned context with
    /// [`SharedWebSocketServer::serve_connection_with_handshake`] (or
    /// [`serve_connection_with_cancel_and_handshake`](SharedWebSocketServer::serve_connection_with_cancel_and_handshake)).
    ///
    /// The built-in `serve*` loops capture this context for you, so this
    /// pairing is only needed when the embedder owns its own accept loop
    /// (one-port co-hosting) *and* keys peers off the handshake.
    pub async fn accept_with_handshake(
        stream: TcpStream,
        path: &str,
    ) -> Result<(WebSocketStream<TcpStream>, HandshakeContext), RepeError> {
        Self::accept_with_handshake_and_limits(stream, path, crate::WebSocketLimits::default())
            .await
    }

    /// [`accept_with_handshake`](Self::accept_with_handshake) with explicit
    /// size limits. See [`accept_with_limits`](Self::accept_with_limits) for why
    /// an associated function cannot read them from the builder.
    pub async fn accept_with_handshake_and_limits(
        stream: TcpStream,
        path: &str,
        limits: crate::WebSocketLimits,
    ) -> Result<(WebSocketStream<TcpStream>, HandshakeContext), RepeError> {
        let (ws, handshake) =
            accept_repe_websocket(stream, &normalize_path(path), true, limits).await?;
        // `capture_handshake = true` always yields `Some` on the accept
        // path (the validator populates it before returning `Ok`).
        Ok((
            ws,
            handshake.expect("handshake captured when capture_handshake is set"),
        ))
    }
}

struct ConnectionConfig {
    router: Router,
    limits: crate::WebSocketLimits,
    outbound_capacity: usize,
    offreader_limit: Option<usize>,
    peer_id_counter: Arc<AtomicU64>,
    on_connect: Arc<Vec<ConnectHook>>,
    on_connect_ctx: Arc<Vec<ConnectCtxHook>>,
    on_disconnect: Arc<Vec<DisconnectHook>>,
    on_error: Arc<Vec<ErrorHook>>,
}

/// Cheap, cloneable handle to a [`WebSocketServer`]'s per-connection
/// configuration, produced by [`WebSocketServer::into_shared`].
///
/// `into_shared` builds the connection configuration (router, hooks,
/// capacities) exactly once; cloning a `SharedWebSocketServer` is an
/// `Arc` clone. The handle is `Send + Sync + 'static`, so it drops
/// straight into a per-connection
/// `tokio::spawn(async move { shared.serve_connection(ws).await })` —
/// the shape an embedder needs to share one TCP port between REPE
/// WebSocket upgrades and its own HTTP routes.
#[derive(Clone)]
pub struct SharedWebSocketServer {
    config: Arc<ConnectionConfig>,
}

impl SharedWebSocketServer {
    /// Perform the REPE WebSocket handshake using this server's configured
    /// [`WebSocketLimits`](crate::WebSocketLimits).
    ///
    /// Prefer this over the associated [`WebSocketServer::accept`] in an
    /// embedder-owned accept loop. That one takes no `self`, so it cannot see a
    /// builder-set [`with_limits`](WebSocketServer::with_limits) and accepts
    /// with the defaults instead: the limits would appear to be configured and
    /// silently not be.
    pub async fn accept(
        &self,
        stream: TcpStream,
        path: &str,
    ) -> Result<WebSocketStream<TcpStream>, RepeError> {
        WebSocketServer::accept_with_limits(stream, path, self.config.limits).await
    }

    /// [`accept`](Self::accept), also returning the upgrade's
    /// [`HandshakeContext`].
    pub async fn accept_with_handshake(
        &self,
        stream: TcpStream,
        path: &str,
    ) -> Result<(WebSocketStream<TcpStream>, HandshakeContext), RepeError> {
        WebSocketServer::accept_with_handshake_and_limits(stream, path, self.config.limits).await
    }

    /// This server's size limits, for an embedder that upgrades the stream
    /// through some path of its own and needs to configure it to match.
    pub fn limits(&self) -> crate::WebSocketLimits {
        self.config.limits
    }

    /// Wrap the raw IO of a connection **another HTTP stack already
    /// upgraded** into a server-role [`WebSocketStream`] carrying this
    /// server's configured [`WebSocketLimits`](crate::WebSocketLimits),
    /// ready for [`serve_connection`](Self::serve_connection).
    ///
    /// This is the seam for an embedder whose HTTP routes live in a
    /// framework (`axum`, `hyper`, `tower`) rather than in a hand-written
    /// accept loop. Such an embedder already owns a `Router` with its own
    /// paths on it and wants the REPE endpoint to be one more route,
    /// answering the 101 through the framework's own upgrade machinery.
    /// The peek-then-fork recipe (`is_websocket_upgrade` +
    /// [`accept`](Self::accept)) cannot serve that shape, because it
    /// requires repe to own the `TcpStream` before any HTTP is parsed.
    /// Here the framework keeps the socket, performs the handshake, and
    /// hands back the upgraded byte stream — which is what `io` is.
    ///
    /// The caller is responsible for the handshake itself: validating
    /// `Upgrade`/`Connection`/`Sec-WebSocket-Version` and answering `101`
    /// with the [`derive_accept_key`] of the client's `Sec-WebSocket-Key`.
    /// Frameworks that expose the upgrade as an extractor do that part;
    /// [`derive_accept_key`] is provided for those that hand back the raw
    /// request. Path validation is the caller's too — the framework
    /// already routed the request here, which is the counterpart to the
    /// `path` argument [`WebSocketServer::accept`] takes.
    ///
    /// Nothing is read from `io` before the first REPE frame, so a stream
    /// whose handshake produced garbage surfaces as a protocol error on
    /// that connection alone. The other failure shape is quieter: if the
    /// client is still waiting for a `101` that never came, neither side
    /// speaks, and repe applies no read timeout or idle deadline — the
    /// framework's own upgrade timeout is what bounds that.
    ///
    /// To *name* the returned type in your own signatures, the transport
    /// crate is re-exported as `repe::tokio_tungstenite`; call sites that
    /// pass the value straight to
    /// [`serve_connection`](Self::serve_connection) never need to.
    ///
    /// This call is where the connection's inbound thresholds are fixed —
    /// they cannot be changed afterwards — which is precisely why it
    /// exists rather than leaving embedders to call the transport's
    /// `from_raw_socket` themselves and silently substitute its defaults
    /// for the limits the server was built with. The outbound guard
    /// travels with the server config and applies on every path.
    pub async fn adopt_upgraded<S>(&self, io: S) -> WebSocketStream<S>
    where
        S: AsyncRead + AsyncWrite + Unpin,
    {
        WebSocketStream::from_raw_socket(
            io,
            tungstenite::protocol::Role::Server,
            Some(self.config.limits.into()),
        )
        .await
    }

    /// [`adopt_upgraded`](Self::adopt_upgraded) for a framework that hands
    /// back the bytes it read past the upgrade request separately from the
    /// stream, as `(io, buffered)`.
    ///
    /// A client may legally pipeline its first frame with the upgrade
    /// request, so those bytes can be real REPE traffic. `hyper` hides this
    /// — its `Upgraded` replays what it buffered — but a framework that
    /// returns the two halves separately needs somewhere to put them, and
    /// dropping them loses a frame. Pass them here and they are decoded
    /// ahead of anything read from `io`.
    ///
    /// Prefer [`adopt_upgraded`](Self::adopt_upgraded) when the stream
    /// already replays its own leftovers; passing `buffered` bytes that
    /// `io` will also yield would double-decode them.
    pub async fn adopt_upgraded_partially_read<S>(
        &self,
        io: S,
        buffered: Vec<u8>,
    ) -> WebSocketStream<S>
    where
        S: AsyncRead + AsyncWrite + Unpin,
    {
        WebSocketStream::from_partially_read(
            io,
            buffered,
            tungstenite::protocol::Role::Server,
            Some(self.config.limits.into()),
        )
        .await
    }

    /// Run one connection's reader/writer loop using this server's
    /// router, hooks, and capacities. Pair with
    /// [`WebSocketServer::accept`] to serve a stream the embedder
    /// accepted and upgraded itself.
    ///
    /// Generic over the underlying byte stream, so the connection need
    /// not have come from a [`TcpStream`] this crate accepted. A stream
    /// some *other* HTTP stack upgraded — an `axum`/`hyper` route that
    /// answered the 101 itself — is served by wrapping its upgraded IO
    /// with [`adopt_upgraded`](Self::adopt_upgraded) and passing the
    /// result here.
    ///
    /// Connect/disconnect hooks (and any [`PeerRegistry`] attached via
    /// [`WebSocketServer::with_peer_registry`]) fire for connections
    /// served this way, exactly as under [`WebSocketServer::serve`].
    ///
    /// The connection's off-reader handlers see their cancellation signal
    /// ([`CallContext::is_cancelled`](crate::CallContext::is_cancelled) /
    /// [`CallContext::cancelled`](crate::CallContext::cancelled)) fire on
    /// disconnect. To also fire it on an embedder-driven shutdown, use
    /// [`serve_connection_with_cancel`](Self::serve_connection_with_cancel).
    pub async fn serve_connection<S>(&self, ws: WebSocketStream<S>) -> Result<(), RepeError>
    where
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    {
        // No parent: the connection token is cancelled only when this
        // connection's reader exits (disconnect). No captured handshake,
        // so on_peer_connect_with_handshake hooks do not fire.
        handle_connection_with_config(ws, Arc::clone(&self.config), CancellationToken::new(), None)
            .await
    }

    /// Like [`serve_connection`](Self::serve_connection), but threads the
    /// [`HandshakeContext`] from [`WebSocketServer::accept_with_handshake`]
    /// through so
    /// [`on_peer_connect_with_handshake`](WebSocketServer::on_peer_connect_with_handshake)
    /// hooks fire for this connection. For a one-port co-hosting embedder
    /// that keys peers off the upgrade request.
    pub async fn serve_connection_with_handshake<S>(
        &self,
        ws: WebSocketStream<S>,
        handshake: HandshakeContext,
    ) -> Result<(), RepeError>
    where
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    {
        handle_connection_with_config(
            ws,
            Arc::clone(&self.config),
            CancellationToken::new(),
            Some(handshake),
        )
        .await
    }

    /// Like [`serve_connection`](Self::serve_connection), but ties this
    /// connection's cancellation signal to a shared [`ShutdownToken`] as
    /// well as to disconnect.
    ///
    /// For a one-port co-hosting embedder that owns its accept loop:
    /// create one [`ShutdownToken`], serve each connection through this
    /// method, and call [`ShutdownToken::cancel`] on shutdown to wake
    /// every connection's in-flight off-reader handlers at once while you
    /// drain your own task set. The connection's token is a child of the
    /// shared one, so cancelling the shared token cancels every
    /// connection, and a single connection's disconnect cancels only its
    /// own child.
    pub async fn serve_connection_with_cancel<S>(
        &self,
        ws: WebSocketStream<S>,
        shutdown: &ShutdownToken,
    ) -> Result<(), RepeError>
    where
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    {
        handle_connection_with_config(ws, Arc::clone(&self.config), shutdown.child_token(), None)
            .await
    }

    /// [`serve_connection_with_cancel`](Self::serve_connection_with_cancel)
    /// plus the captured [`HandshakeContext`] — the union of co-hosting,
    /// embedder-driven drain, and handshake-keyed peers. Cancelling the
    /// shared [`ShutdownToken`] winds the connection's in-flight off-reader
    /// handlers down, and
    /// [`on_peer_connect_with_handshake`](WebSocketServer::on_peer_connect_with_handshake)
    /// hooks fire from the captured `handshake`.
    pub async fn serve_connection_with_cancel_and_handshake<S>(
        &self,
        ws: WebSocketStream<S>,
        handshake: HandshakeContext,
        shutdown: &ShutdownToken,
    ) -> Result<(), RepeError>
    where
        S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    {
        handle_connection_with_config(
            ws,
            Arc::clone(&self.config),
            shutdown.child_token(),
            Some(handshake),
        )
        .await
    }

    /// Report a transport-level error through this server's
    /// [`on_error`](WebSocketServer::on_error) hooks (or the default
    /// stderr fallback). Used by the built-in accept loops; a co-hosting
    /// embedder that owns its loop reports the [`RepeError`] returned by
    /// [`serve_connection`](Self::serve_connection) however it likes.
    pub(crate) fn report_error(&self, err: ConnectionError) {
        report_error(&self.config.on_error, err);
    }

    /// One connection's full lifecycle for the built-in accept loops:
    /// handshake, serve, and report any handshake/connection error. The
    /// [`HandshakeContext`] is captured only when a handshake-aware connect
    /// hook is registered, so a server that uses none pays nothing extra on
    /// the accept path. `expected_path` must already be normalized.
    /// `shutdown` is `Some` for the graceful-drain loop (ties the
    /// connection token to the shared trigger) and `None` otherwise.
    async fn accept_and_serve(
        &self,
        stream: TcpStream,
        expected_path: &str,
        shutdown: Option<&ShutdownToken>,
    ) {
        let capture = !self.config.on_connect_ctx.is_empty();
        match accept_repe_websocket(stream, expected_path, capture, self.config.limits).await {
            Ok((ws, handshake)) => {
                let conn_token = match shutdown {
                    Some(token) => token.child_token(),
                    None => CancellationToken::new(),
                };
                if let Err(err) = handle_connection_with_config(
                    ws,
                    Arc::clone(&self.config),
                    conn_token,
                    handshake,
                )
                .await
                {
                    self.report_error(ConnectionError::Connection(err));
                }
            }
            Err(err) => self.report_error(ConnectionError::Handshake(err)),
        }
    }
}

pub async fn proxy_connection<S>(
    ws_stream: WebSocketStream<S>,
    upstream: AsyncClient,
) -> Result<(), RepeError>
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    proxy_connection_with_limits(ws_stream, upstream, crate::WebSocketLimits::default()).await
}

/// [`proxy_connection`] with explicit size limits.
///
/// Only the outbound guard applies: the stream is already upgraded, so its
/// inbound thresholds were fixed by whoever performed the handshake. A response
/// forwarded from upstream that exceeds `assumed_peer_frame_limit` is refused
/// rather than sent, since sending it would make the downstream reader close the
/// connection and leave the proxy with no error to report.
pub async fn proxy_connection_with_limits<S>(
    ws_stream: WebSocketStream<S>,
    upstream: AsyncClient,
    limits: crate::WebSocketLimits,
) -> Result<(), RepeError>
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    let (mut writer, mut reader) = ws_stream.split();

    loop {
        let frame = match reader.next().await {
            Some(Ok(frame)) => frame,
            Some(Err(err)) => return Err(websocket_transport_error(err)),
            None => break,
        };

        let request = match decode_request_payload(frame)? {
            FramePayload::Bytes(payload) => Message::from_slice_exact(&payload)?,
            FramePayload::Continue => continue,
            FramePayload::Close => break,
        };

        if let Some(response) = upstream.forward_message(&request).await? {
            // A proxy has no error hooks, so the refusal is reported by
            // substituting the error response `frame_outbound` builds.
            if let Some(bytes) = frame_outbound(response, &limits, &[]) {
                writer
                    .send(WsMessage::Binary(bytes))
                    .await
                    .map_err(websocket_transport_error)?;
            }
        }
    }

    let _ = writer.send(WsMessage::Close(None)).await;
    writer.close().await.map_err(websocket_transport_error)
}

/// Perform the REPE upgrade handshake, optionally capturing the request
/// context. `capture_handshake` is `false` for the plain accept paths so
/// they pay no per-connection cost building a [`HandshakeContext`] no hook
/// will read; it is `true` only when an
/// [`on_peer_connect_with_handshake`](WebSocketServer::on_peer_connect_with_handshake)
/// hook (or the explicit
/// [`accept_with_handshake`](WebSocketServer::accept_with_handshake)) needs
/// it. The returned `Option` is `Some` iff `capture_handshake` was `true`.
async fn accept_repe_websocket(
    stream: TcpStream,
    expected_path: &str,
    capture_handshake: bool,
    limits: crate::WebSocketLimits,
) -> Result<(WebSocketStream<TcpStream>, Option<HandshakeContext>), RepeError> {
    // The handshake `Callback` borrows the request only for the duration
    // of `on_request`, so stash the captured context in a shared slot the
    // validator fills and we read back once the upgrade completes. When no
    // hook will read it, the slot is absent and the validator skips the
    // capture entirely.
    let captured = capture_handshake.then(|| Arc::new(std::sync::Mutex::new(None)));
    let ws = accept_hdr_async_with_config(
        stream,
        WebSocketPathValidator {
            expected: expected_path.to_owned(),
            captured: captured.clone(),
        },
        Some(limits.into()),
    )
    .await
    .map_err(websocket_transport_error)?;
    // The validator populates the slot on the accept path; a rejected path
    // returns `Err` above before we get here.
    let handshake = captured.and_then(|slot| {
        slot.lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take()
    });
    Ok((ws, handshake))
}

async fn handle_connection_with_config<S>(
    ws_stream: WebSocketStream<S>,
    config: Arc<ConnectionConfig>,
    conn_token: CancellationToken,
    handshake: Option<HandshakeContext>,
) -> Result<(), RepeError>
where
    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
    let (outbound_tx, outbound_rx) = mpsc::channel::<Message>(config.outbound_capacity);

    let peer_id_value = config.peer_id_counter.fetch_add(1, Ordering::Relaxed);
    debug_assert!(
        peer_id_value != PeerId::DETACHED.0,
        "peer id counter collided with PeerId::DETACHED sentinel"
    );
    let peer_id = PeerId(peer_id_value);

    let sink = Arc::new(WsPeerSink {
        tx: outbound_tx.clone(),
    });
    let peer = PeerHandle::new(peer_id, sink);

    // Per-connection cap on concurrent off-reader handlers. `None`
    // (set via `with_offreader_limit(0)`) means unbounded.
    let offreader_sem = config.offreader_limit.map(|n| Arc::new(Semaphore::new(n)));

    // Build the disconnect guard *before* invoking connect hooks. If a
    // later connect hook panics after an earlier one (e.g. the
    // registry-insert hook) has already side-effected, unwinding still
    // runs the guard's Drop and the disconnect hook tears the
    // partial state back down. Without this ordering, a panicking
    // connect hook leaves the peer wedged in the registry forever.
    let (ws_writer, ws_reader) = ws_stream.split();
    let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();

    // Abort the writer if this connection task is itself dropped (a
    // server-level graceful drain aborting at its deadline) so the writer
    // cannot outlive the connection's teardown.
    let writer_guard = AbortOnDrop(tokio::spawn(writer_task(
        ws_writer,
        outbound_rx,
        shutdown_rx,
        config.limits,
        Arc::clone(&config.on_error),
    )));

    let reader_result = {
        let _guard = DisconnectGuard {
            peer_id,
            hooks: Arc::clone(&config.on_disconnect),
            // Cancel on reader exit so off-reader handlers still running
            // on blocking threads observe the disconnect promptly.
            cancel: conn_token.clone(),
        };

        // Fire connect hooks *before* the reader/writer tasks process
        // traffic, so any notifies queued here are already in the
        // outbound channel when the writer task begins draining.
        for hook in config.on_connect.iter() {
            hook(peer.clone());
        }
        // Handshake-aware hooks run after the plain ones (so a
        // `with_peer_registry` insert has already landed and the peer is
        // present for `alias`) and only when a handshake was captured
        // (the built-in `serve*` loops and the `*_with_handshake`
        // co-hosting path; not plain `serve_connection`).
        if let Some(handshake) = &handshake {
            for hook in config.on_connect_ctx.iter() {
                hook(&peer, handshake);
            }
        }

        // Bundle the per-connection dispatch state for the reader. `peer`
        // is threaded into each request's `CallContext` so handlers can
        // push notifies back to the originator (via `Router::with_json_ctx`
        // / `with_typed_ctx` or a registry-backed `RegistryCallable`), and
        // `conn_token` becomes each handler's cancellation signal.
        let conn = ConnDispatch {
            peer,
            outbound_tx,
            conn_token: conn_token.clone(),
            on_error: Arc::clone(&config.on_error),
        };

        // Stop reading promptly when the connection token is cancelled by
        // a parent (embedder-driven shutdown). On the normal path the
        // reader returns on its own and this arm never fires; for a
        // parentless connection the token is only cancelled by the guard
        // on the way out, after the reader has already returned, so the
        // arm stays dormant.
        tokio::select! {
            r = reader_task(ws_reader, &config.router, conn, offreader_sem) => r,
            _ = conn_token.cancelled() => Ok(()),
        }
        // _guard drops here (on every exit path, including unwind),
        // firing disconnect hooks and cancelling the connection token.
        // Any registry entry holding a PeerHandle clone (and thus a
        // sender clone) is released, helping the writer task drain.
    };

    // Tell the writer to drain any queued messages and exit, regardless
    // of whether sender clones still linger in user-held PeerHandles.
    let _ = shutdown_tx.send(());

    let writer_result = match writer_guard.await {
        Ok(r) => r,
        Err(join_err) => Err(RepeError::Io(std::io::Error::other(format!(
            "websocket writer task panicked: {join_err}"
        )))),
    };

    reader_result.and(writer_result)
}

/// Per-connection dispatch state shared by every request on a
/// connection: the calling peer, where to push results, the connection's
/// cancellation token, and the error sink. Bundled so the inline and
/// off-reader paths thread one value rather than four parallel arguments.
struct ConnDispatch {
    peer: PeerHandle,
    outbound_tx: mpsc::Sender<Message>,
    conn_token: CancellationToken,
    on_error: Arc<Vec<ErrorHook>>,
}

async fn reader_task<S>(
    mut ws_reader: SplitStream<WebSocketStream<S>>,
    router: &Router,
    conn: ConnDispatch,
    offreader_sem: Option<Arc<Semaphore>>,
) -> Result<(), RepeError>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    // One signal shared by every inline dispatch on this connection; the
    // off-reader path builds its own owned clone per spawned handler.
    let inline_signal = TokenSignal(conn.conn_token.clone());
    loop {
        let frame = match ws_reader.next().await {
            Some(Ok(frame)) => frame,
            Some(Err(err)) => return Err(websocket_transport_error(err)),
            None => break,
        };

        let payload = match decode_request_payload(frame)? {
            FramePayload::Bytes(payload) => payload,
            FramePayload::Continue => continue,
            FramePayload::Close => break,
        };
        // Borrow the frame rather than copying its query and body into an owned
        // Message; only the off-reader path (whose spawned task outlives
        // `payload`) materializes one.
        let view = MessageView::from_slice_exact(&payload)?;

        // Validate + look up the handler here, on the reader, so early error
        // responses and the execution mode are computed identically for the
        // inline and off-reader paths; only where dispatch runs differs.
        match route(router, &view.header, view.query) {
            RouteOutcome::Reject {
                notify,
                code,
                message,
            } => {
                if !notify {
                    let mut response = create_error_response_unstamped_view(&view, code, message);
                    // The outbound channel carries owned messages framed later by
                    // the writer task, so stamp the borrowed query in (an error
                    // response is always query-less, so it is copied here).
                    stamp_response_query(&mut response, Cow::Borrowed(view.query));
                    if conn.outbound_tx.send(response).await.is_err() {
                        break;
                    }
                }
            }
            RouteOutcome::Dispatch {
                handler,
                notify,
                path,
            } => match handler.execution() {
                Execution::Inline => {
                    // Thread the calling peer and the connection's
                    // cancellation signal to handlers so `with_json_ctx` /
                    // `with_typed_ctx` (and registry-backed callables) can
                    // push notifies back through this connection during
                    // request handling and observe disconnect/shutdown.
                    let ctx = CallContext::with_cancel(path, &conn.peer, &inline_signal);
                    if let Some(mut response) = dispatch_view(handler.as_ref(), &view, &ctx, notify)
                    {
                        // The response is query-less and the writer task frames
                        // it later, so stamp the borrowed query in rather than
                        // referencing `payload`. A handler that set its own
                        // response query keeps it and pays no copy.
                        stamp_response_query(&mut response, Cow::Borrowed(view.query));
                        if conn.outbound_tx.send(response).await.is_err() {
                            // Writer task exited (likely wire error);
                            // abandon reader. The disconnect guard still
                            // fires when we return.
                            break;
                        }
                    }
                }
                Execution::OffReader => {
                    // The spawned blocking task outlives `payload`, so it needs
                    // an owned request.
                    let request = view.to_message();
                    if !spawn_off_reader(&offreader_sem, &conn, handler, request, notify).await {
                        break;
                    }
                }
            },
        }
    }
    // `conn` drops here, releasing this connection's peer and sender
    // clone of the outbound channel and helping the writer drain.
    drop(conn);
    Ok(())
}

/// Dispatch an off-reader handler on a blocking thread so the reader
/// keeps decoding inbound frames while it runs or parks.
///
/// Acquires a per-connection permit first. If the cap is saturated it
/// rejects (non-notify) or drops (notify) the request rather than
/// blocking the reader — blocking here would stall the ACK/cancel
/// frames in-flight handlers need to finish and free a slot, the very
/// deadlock off-reader dispatch exists to avoid. A handler panic is
/// caught and mapped to an error response so it cannot tear down the
/// connection, which an off-reader handler shares with other concurrent
/// transfers.
///
/// Returns `false` if the outbound channel is closed (the caller should
/// stop reading), `true` otherwise.
async fn spawn_off_reader(
    offreader_sem: &Option<Arc<Semaphore>>,
    conn: &ConnDispatch,
    handler: Arc<dyn HandlerErased>,
    request: Message,
    notify: bool,
) -> bool {
    let permit = match offreader_sem {
        Some(sem) => match Arc::clone(sem).try_acquire_owned() {
            Ok(permit) => Some(permit),
            Err(_) => {
                let method = request.query_str().unwrap_or("").to_string();
                report_error(&conn.on_error, ConnectionError::Saturation { method });
                if notify {
                    // No response to reject a notify with; drop it.
                    return true;
                }
                let response = create_error_response_like(
                    &request,
                    ErrorCode::ResourceExhausted,
                    "off-reader dispatch limit reached; retry",
                );
                return conn.outbound_tx.send(response).await.is_ok();
            }
        },
        None => None,
    };

    let peer = conn.peer.clone();
    let outbound_tx = conn.outbound_tx.clone();
    // Owned clone of the connection token so the off-reader handler's
    // `CallContext` can borrow a signal from its own blocking-thread
    // stack rather than the reader task's.
    let cancel_token = conn.conn_token.clone();
    let on_error = Arc::clone(&conn.on_error);
    tokio::task::spawn_blocking(move || {
        // Hold the permit for the whole handler run; dropped on return
        // (including the panic path), which is what lets the idle
        // watchdog reclaim a wedged slot once it cancels the transfer.
        let _permit = permit;
        let path = request.query_str().unwrap_or("");
        let cancel_signal = TokenSignal(cancel_token);
        let ctx = CallContext::with_cancel(path, &peer, &cancel_signal);
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            dispatch(handler.as_ref(), &request, &ctx, notify)
        }));
        let response = match outcome {
            Ok(maybe_response) => maybe_response,
            Err(_) => {
                // The default panic hook has already printed the panic;
                // report a repe-level event so the failure is attributable
                // here too -- especially for a notify, which has no
                // response to carry the error back to the client. The
                // connection is deliberately kept alive (it is shared
                // with other concurrent off-reader transfers).
                report_error(
                    &on_error,
                    ConnectionError::HandlerPanic {
                        method: path.to_string(),
                    },
                );
                (!notify).then(|| {
                    create_error_response_like(
                        &request,
                        ErrorCode::InternalError,
                        "handler panicked",
                    )
                })
            }
        };
        if let Some(mut response) = response {
            // Echo the request query by moving its owned buffer into the response
            // (`Cow::Owned`, no copy -- handlers leave it empty); a panic error
            // response already carries its own query, so the stamp is a no-op.
            stamp_response_query(&mut response, Cow::Owned(request.query));
            // Best-effort: the writer may already be gone if the
            // connection closed while this handler ran.
            let _ = outbound_tx.blocking_send(response);
        }
    });
    true
}

/// Serialize an outbound message, refusing one the peer is assumed to reject.
///
/// Every outbound message funnels through the writer task, which makes this the
/// one place the guard has to live. A response is replaced by an error response
/// carrying the same request id, so the caller gets a real REPE error instead of
/// a vanished connection. A notify has no response to carry anything, so it is
/// dropped and reported through the error hooks.
///
/// Returns `None` when nothing should go on the wire.
fn frame_outbound(
    m: Message,
    limits: &crate::WebSocketLimits,
    on_error: &[ErrorHook],
) -> Option<Vec<u8>> {
    // Size the frame in closed form and check the limit before building it,
    // rather than framing first and measuring the result. `into_wire_bytes`
    // emits exactly `HEADER_SIZE + query + body` bytes, so the guard sees the
    // same number either way — `frame_outbound_checks_the_length_it_frames`
    // pins that equality so the two cannot drift.
    //
    // Ordering it this way is what keeps the message intact through the check,
    // which is what the common path is actually paying for: the method name is
    // read only to report a rejection, so it no longer has to be copied out of
    // the message before it is consumed. Every frame the server sends was
    // allocating (and immediately dropping) a `String` for a hook that almost
    // never fires. A rejected frame is now never built either, which is the
    // one case where that buffer is at its largest.
    let frame_len = crate::constants::HEADER_SIZE + m.query.len() + m.body.len();
    let Err(err) = limits.check_outbound(frame_len) else {
        return Some(m.into_wire_bytes());
    };
    let (size, limit) = match err {
        RepeError::MessageTooLarge { size, limit } => (size, limit),
        _ => unreachable!("check_outbound yields only MessageTooLarge"),
    };
    report_error(
        on_error,
        ConnectionError::OutboundTooLarge {
            method: m.query_str().unwrap_or("").to_string(),
            size,
            limit,
        },
    );
    if m.header.notify != 0 {
        return None;
    }
    let id = m.header.id;
    let mut replacement = crate::message::create_error_message(
        ErrorCode::InternalError,
        format!(
            "response is {size} bytes, over the {limit} byte assumed peer frame limit; \
             raise the peer's inbound limit or reduce the response"
        ),
    );
    // Carry the request id across so the client matches this to its pending
    // request. Only the id changes, so the header's length stays correct.
    replacement.header.id = id;
    Some(replacement.into_wire_bytes())
}

async fn writer_task<S>(
    mut ws_writer: SplitSink<WebSocketStream<S>, WsMessage>,
    mut outbound_rx: mpsc::Receiver<Message>,
    mut shutdown_rx: oneshot::Receiver<()>,
    limits: crate::WebSocketLimits,
    on_error: Arc<Vec<ErrorHook>>,
) -> Result<(), RepeError>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    let mut result: Result<(), RepeError> = Ok(());
    loop {
        tokio::select! {
            biased;
            // Drain queued messages preferentially so already-enqueued
            // notifies make the wire before shutdown.
            msg = outbound_rx.recv() => match msg {
                Some(m) => {
                    let Some(bytes) = frame_outbound(m, &limits, &on_error) else {
                        continue;
                    };
                    if let Err(err) = ws_writer.send(WsMessage::Binary(bytes)).await {
                        result = Err(websocket_transport_error(err));
                        break;
                    }
                }
                None => break,
            },
            _ = &mut shutdown_rx => {
                // Shutdown requested: flush whatever is immediately
                // available, then exit. Bounded by SHUTDOWN_DRAIN_TIMEOUT
                // so a slow peer (TCP still responsive but throttled)
                // cannot pin the connection task open. Sends that
                // arrive after we break are discarded when outbound_rx
                // drops.
                let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_TIMEOUT;
                while let Ok(m) = outbound_rx.try_recv() {
                    let Some(bytes) = frame_outbound(m, &limits, &on_error) else {
                        continue;
                    };
                    let send_fut = ws_writer.send(WsMessage::Binary(bytes));
                    match tokio::time::timeout_at(deadline, send_fut).await {
                        Ok(Ok(())) => {}
                        Ok(Err(err)) => {
                            result = Err(websocket_transport_error(err));
                            break;
                        }
                        Err(_) => break,
                    }
                }
                break;
            }
        }
    }
    let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_TIMEOUT;
    let _ = tokio::time::timeout_at(deadline, ws_writer.send(WsMessage::Close(None))).await;
    let _ = tokio::time::timeout_at(deadline, ws_writer.close()).await;
    result
}

pub(crate) struct WsPeerSink {
    tx: mpsc::Sender<Message>,
}

impl PeerSink for WsPeerSink {
    fn send_notify(&self, method: &str, body: NotifyBody) -> Result<(), PeerSendError> {
        let body_format = body.body_format();
        let body_bytes = body.into_bytes();
        let msg = Message::builder()
            .id(0)
            .notify(true)
            .query_str(method)
            .query_format(QueryFormat::JsonPointer)
            .body_format_code(u16::from(body_format))
            .body_bytes(body_bytes)
            .build();

        match self.tx.try_send(msg) {
            Ok(()) => Ok(()),
            Err(TrySendError::Full(_)) => Err(PeerSendError::Full),
            Err(TrySendError::Closed(_)) => Err(PeerSendError::Disconnected),
        }
    }

    fn is_connected(&self) -> bool {
        !self.tx.is_closed()
    }
}

struct DisconnectGuard {
    peer_id: PeerId,
    hooks: Arc<Vec<DisconnectHook>>,
    cancel: CancellationToken,
}

impl Drop for DisconnectGuard {
    fn drop(&mut self) {
        // Cancel before firing hooks so an off-reader handler polling
        // `ctx.is_cancelled()` observes the disconnect as early as
        // possible. This is a no-op when the token was already cancelled
        // by a parent (shutdown).
        self.cancel.cancel();
        for hook in self.hooks.iter() {
            hook(self.peer_id);
        }
    }
}

enum FramePayload {
    /// A binary frame's raw bytes, to be parsed as a [`MessageView`] (reader) or
    /// an owned [`Message`] (proxy) by the caller.
    Bytes(Vec<u8>),
    Continue,
    Close,
}

fn decode_request_payload(frame: WsMessage) -> Result<FramePayload, RepeError> {
    match frame {
        WsMessage::Binary(payload) => Ok(FramePayload::Bytes(payload)),
        WsMessage::Ping(_) | WsMessage::Pong(_) | WsMessage::Frame(_) => Ok(FramePayload::Continue),
        WsMessage::Close(_) => Ok(FramePayload::Close),
        WsMessage::Text(_) => Err(websocket_invalid_data_error(
            "websocket transport requires binary messages",
        )),
    }
}

/// Peek at an accepted `stream` and report whether the client is opening
/// a WebSocket upgrade (as opposed to issuing a plain HTTP request),
/// **without consuming any bytes**.
///
/// This is the WS-vs-HTTP fork a one-port co-hosting embedder needs: route
/// `true` to [`WebSocketServer::accept`] +
/// [`serve_connection`](SharedWebSocketServer::serve_connection) and `false`
/// to your own HTTP handler, all on one TCP port. Because
/// [`WebSocketServer::accept`] replays the handshake from the start of the
/// stream, this helper only *peeks* (`TcpStream::peek`) — it leaves the
/// request bytes in the socket buffer so the subsequent `accept` (or your
/// HTTP handler) sees the full request intact. See
/// `examples/websocket_cohosting.rs` for the worked fork.
///
/// The classification is a sniff, not a full handshake validation: it
/// looks for an `Upgrade: websocket` header (compared case-insensitively,
/// per RFC 6455 §4.2.1) within the request head, and matches the
/// `websocket` token only inside that header's value, so a plain
/// `GET /websocket-status` request is not misclassified.
///
/// The two misclassification directions are **not** symmetric:
///
/// - A false positive (plain HTTP sniffed as an upgrade) is harmless. The
///   `true` branch hands off to [`WebSocketServer::accept`], whose
///   authoritative RFC 6455 validation rejects the request and fails the
///   handshake rather than corrupting anything.
/// - A false negative is **not** recoverable here. If a real upgrade's
///   `Upgrade` header has not arrived in the connection's first readable
///   chunk (TCP may split the request head across segments) or falls
///   beyond the 1 KiB peek window, the request is routed to the HTTP
///   handler with no second look.
///
/// The peek reads the request head that arrives in the connection's first
/// readable chunk (bounded to 1 KiB). A real WebSocket upgrade — a short
/// `GET` line plus its `Upgrade`/`Connection` headers — sends a compact
/// head with those headers up front, so a false negative is unlikely on a
/// sane network; but it depends on client and network framing, not on the
/// heuristic alone. An embedder that must be exact can read and buffer the
/// request head itself (up to the terminating `\r\n\r\n`) before
/// classifying.
///
/// # Errors
///
/// Returns the underlying [`std::io::Error`] if peeking the stream fails.
///
/// # Blocking and timeouts
///
/// `peek` resolves only once at least one byte is readable. A peer that
/// connects and immediately closes (EOF) yields an empty, non-upgrade head
/// and is reported as `false`; but a peer that connects and holds the
/// socket open *without sending* leaves this future pending indefinitely,
/// pinning the spawned task (a slowloris). This mirrors
/// [`WebSocketServer::accept`], which likewise awaits the client's bytes,
/// so it is not specific to co-hosting — but because this helper is the
/// recommended one-port entry point, production embedders should wrap the
/// peek in a [`tokio::time::timeout`] and drop the connection if the
/// request head does not arrive promptly.
pub async fn is_websocket_upgrade(stream: &TcpStream) -> std::io::Result<bool> {
    let mut buf = [0u8; 1024];
    let n = stream.peek(&mut buf).await?;
    Ok(head_requests_websocket_upgrade(&buf[..n]))
}

/// Scan an HTTP request head for a WebSocket upgrade signal. Pure and
/// byte-slice-based so it is unit-testable without a socket.
fn head_requests_websocket_upgrade(head: &[u8]) -> bool {
    // Restrict to the header block when its terminator is present, so a
    // body can never contribute a spurious match.
    let block = match find_subslice(head, b"\r\n\r\n") {
        Some(end) => &head[..end],
        None => head,
    };
    for line in block.split(|&b| b == b'\n') {
        // `trim_ascii` strips the trailing CR (and any surrounding space).
        let line = line.trim_ascii();
        let Some(colon) = line.iter().position(|&b| b == b':') else {
            continue;
        };
        let (name, rest) = line.split_at(colon);
        // `rest` starts at the colon; skip it for the value.
        if name.eq_ignore_ascii_case(b"upgrade")
            && contains_ignore_ascii_case(&rest[1..], b"websocket")
        {
            return true;
        }
    }
    false
}

/// First index of `needle` within `haystack`, or `None`. `needle` must be
/// non-empty.
fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Whether `haystack` contains `needle` as a contiguous run, compared
/// ASCII-case-insensitively.
fn contains_ignore_ascii_case(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    if haystack.len() < needle.len() {
        return false;
    }
    haystack
        .windows(needle.len())
        .any(|w| w.eq_ignore_ascii_case(needle))
}

fn normalize_path(path: &str) -> String {
    if path.is_empty() || path == "/" {
        "/".to_string()
    } else if path.starts_with('/') {
        path.trim_end_matches('/').to_string()
    } else {
        format!("/{}", path.trim_end_matches('/'))
    }
}

fn path_not_found_response(request: &Request) -> ErrorResponse {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Some(format!(
            "REPE websocket endpoint not found: {}",
            request.uri().path()
        )))
        .expect("valid handshake rejection response")
}

fn websocket_transport_error(err: tungstenite::Error) -> RepeError {
    match err {
        tungstenite::Error::Io(io_err) => RepeError::Io(io_err),
        tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed => RepeError::Io(
            std::io::Error::new(ErrorKind::ConnectionAborted, "websocket connection closed"),
        ),
        other => RepeError::Io(std::io::Error::other(other.to_string())),
    }
}

fn websocket_invalid_data_error(message: &str) -> RepeError {
    RepeError::Io(std::io::Error::new(ErrorKind::InvalidData, message))
}

struct WebSocketPathValidator {
    expected: String,
    /// Where to stash the captured [`HandshakeContext`], or `None` when no
    /// hook will read it (the plain accept paths) so the capture is
    /// skipped entirely.
    captured: Option<Arc<std::sync::Mutex<Option<HandshakeContext>>>>,
}

impl Callback for WebSocketPathValidator {
    #[allow(clippy::result_large_err)]
    fn on_request(self, request: &Request, response: Response) -> Result<Response, ErrorResponse> {
        if request.uri().path() == self.expected {
            // Capture the request context for the connect hook before the
            // borrow ends, but only when a slot was provided (a hook needs
            // it) and only on the accept path (a rejected upgrade returns
            // below without capturing).
            if let Some(slot) = &self.captured {
                *slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) =
                    Some(HandshakeContext::from_http_request(request));
            }
            Ok(response)
        } else {
            Err(path_not_found_response(request))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants::BodyFormat;
    use crate::websocket_client::WebSocketClient;
    use serde_json::json;
    use std::sync::Mutex;
    use std::time::Duration;

    async fn run_default_connection(
        ws_stream: WebSocketStream<TcpStream>,
        router: Router,
    ) -> Result<(), RepeError> {
        let config = Arc::new(ConnectionConfig {
            router,
            limits: crate::WebSocketLimits::default(),
            outbound_capacity: DEFAULT_OUTBOUND_CAPACITY,
            offreader_limit: Some(DEFAULT_OFFREADER_LIMIT),
            peer_id_counter: Arc::new(AtomicU64::new(0)),
            on_connect: Arc::new(Vec::new()),
            on_connect_ctx: Arc::new(Vec::new()),
            on_disconnect: Arc::new(Vec::new()),
            on_error: Arc::new(Vec::new()),
        });
        handle_connection_with_config(ws_stream, config, CancellationToken::new(), None).await
    }

    #[tokio::test(flavor = "current_thread")]
    async fn websocket_server_roundtrip() {
        let router = Router::new().with_json("/mul", |value| {
            let a = value.get("a").and_then(|v| v.as_i64()).unwrap_or_default();
            let b = value.get("b").and_then(|v| v.as_i64()).unwrap_or_default();
            Ok(json!({ "prod": a * b }))
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server_task = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let (ws_stream, _handshake) =
                accept_repe_websocket(stream, "/repe", false, crate::WebSocketLimits::default())
                    .await
                    .unwrap();
            run_default_connection(ws_stream, router).await.unwrap();
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let out = client
            .call_json("/mul", &json!({ "a": 6, "b": 7 }))
            .await
            .unwrap();
        assert_eq!(out["prod"], 42);

        drop(client);
        server_task.await.unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn serve_with_shutdown_stops_accepting_and_returns() {
        // Feature 3: a client round-trips before shutdown; firing the
        // shutdown future makes the serve loop return Ok(()) and the
        // listener is dropped, so a subsequent connect no longer
        // succeeds. Driven through serve_listener_with_shutdown (the
        // single accept loop) with a pre-bound listener to avoid a
        // port-reuse race.
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();

        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
        let server = WebSocketServer::new(router);
        let serve = tokio::spawn(async move {
            server
                .serve_listener_with_shutdown(listener, "/repe", async {
                    let _ = shutdown_rx.await;
                })
                .await
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let resp = client.call_json("/ping", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "ok": true }));

        // Fire shutdown; the serve future must return Ok(()).
        shutdown_tx.send(()).unwrap();
        let result = tokio::time::timeout(Duration::from_secs(5), serve)
            .await
            .expect("serve future did not return after shutdown")
            .expect("serve task panicked");
        assert!(result.is_ok(), "serve returned an error: {result:?}");

        // The listener was dropped when serve returned, so a fresh
        // connect attempt does not yield a working client (it errors
        // or times out).
        let after = tokio::time::timeout(
            Duration::from_secs(2),
            WebSocketClient::connect(&format!("ws://{addr}/repe")),
        )
        .await;
        assert!(
            matches!(after, Ok(Err(_)) | Err(_)),
            "connect unexpectedly succeeded after shutdown"
        );

        drop(client);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn websocket_proxy_forwards_raw_messages() {
        let upstream_router = Router::new().with_json("/echo", Ok);
        let upstream_listener = crate::async_server::AsyncServer::listen(("127.0.0.1", 0))
            .await
            .unwrap();
        let upstream_addr = upstream_listener.local_addr().unwrap();
        let upstream_task = tokio::spawn(async move {
            crate::async_server::AsyncServer::new(upstream_router)
                .serve(upstream_listener)
                .await
                .unwrap();
        });

        let proxy_listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let proxy_addr = proxy_listener.local_addr().unwrap();
        let proxy_task = tokio::spawn(async move {
            let upstream = AsyncClient::connect(upstream_addr).await.unwrap();
            let (stream, _) = proxy_listener.accept().await.unwrap();
            let (ws_stream, _handshake) =
                accept_repe_websocket(stream, "/repe", false, crate::WebSocketLimits::default())
                    .await
                    .unwrap();
            proxy_connection(ws_stream, upstream).await.unwrap();
        });

        let client = WebSocketClient::connect(&format!("ws://{proxy_addr}/repe"))
            .await
            .unwrap();
        let out = client
            .call_json("/echo", &json!({ "ok": true }))
            .await
            .unwrap();
        assert_eq!(out, json!({ "ok": true }));

        drop(client);
        proxy_task.await.unwrap();
        upstream_task.abort();
    }

    async fn serve_one(
        listener: TcpListener,
        path: &str,
        server: WebSocketServer,
    ) -> tokio::task::JoinHandle<()> {
        // Dogfood the public one-port co-hosting surface
        // (into_shared + accept + serve_connection) so the whole
        // WebSocket test suite exercises it.
        let path = path.to_string();
        let shared = server.into_shared();
        tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let path = path.clone();
                let shared = shared.clone();
                tokio::spawn(async move {
                    if let Ok(ws_stream) = WebSocketServer::accept(stream, &path).await {
                        let _ = shared.serve_connection(ws_stream).await;
                    }
                });
            }
        })
    }

    #[tokio::test(flavor = "current_thread")]
    async fn registry_receives_broadcast() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).with_peer_registry(peers.clone());
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");

        // Round-trip a request so we know the peer is registered by
        // the time the broadcast runs.
        let _ = client.call_json("/ping", &json!({})).await.unwrap();

        assert_eq!(peers.len(), 1);
        let results = peers
            .broadcast_notify_json("/announce", &json!({ "hello": "world" }))
            .unwrap();
        assert_eq!(results.len(), 1);
        for r in results.values() {
            r.as_ref().expect("broadcast send");
        }

        let pushed = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .expect("notify did not arrive")
            .expect("subscriber channel closed");
        assert!(pushed.header.notify != 0);
        assert_eq!(pushed.query_str().unwrap(), "/announce");
        let body: serde_json::Value = pushed.json_body().unwrap();
        assert_eq!(body, json!({ "hello": "world" }));

        drop(client);
        // Wait for disconnect to propagate.
        for _ in 0..50 {
            if peers.is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(peers.is_empty(), "peer not removed after disconnect");
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_reaches_multiple_peers() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).with_peer_registry(peers.clone());
        let server_task = serve_one(listener, "/repe", server).await;

        let mut clients = Vec::new();
        let mut receivers = Vec::new();
        for _ in 0..3 {
            let c = WebSocketClient::connect(&format!("ws://{addr}/repe"))
                .await
                .unwrap();
            let rx = c.subscribe_notifies().expect("subscribe");
            // Synchronize so the peer is registered.
            c.call_json("/ping", &json!({})).await.unwrap();
            clients.push(c);
            receivers.push(rx);
        }

        assert_eq!(peers.len(), 3);
        let results = peers
            .broadcast_notify_json("/event", &json!({ "n": 1 }))
            .unwrap();
        assert_eq!(results.len(), 3);
        for r in results.values() {
            r.as_ref().expect("broadcast send");
        }

        for mut rx in receivers {
            let pushed = tokio::time::timeout(Duration::from_secs(2), rx.recv())
                .await
                .expect("notify did not arrive")
                .expect("channel closed");
            assert_eq!(pushed.query_str().unwrap(), "/event");
        }

        for c in clients {
            drop(c);
        }
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn connect_hook_queued_notify_arrives_before_response() {
        let router = Router::new().with_json("/sync", |_| Ok(json!({ "ok": true })));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).on_peer_connect(|peer| {
            // Hook queues a notify before any traffic. The writer task
            // drains this before any response can be produced.
            let _ = peer.send_notify(
                "/welcome",
                NotifyBody::Json(serde_json::to_vec(&json!({ "id": peer.peer_id().0 })).unwrap()),
            );
        });
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");

        // The welcome notify must arrive before the /sync response.
        let pushed = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .expect("welcome notify did not arrive")
            .expect("channel closed");
        assert_eq!(pushed.query_str().unwrap(), "/welcome");

        let resp = client.call_json("/sync", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "ok": true }));

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn disconnect_hook_fires_on_drop() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let disconnected = Arc::new(Mutex::new(Vec::<PeerId>::new()));
        let disconnected_clone = Arc::clone(&disconnected);

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router)
            .on_peer_disconnect(move |id| disconnected_clone.lock().unwrap().push(id));
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        // Synchronize so the connection is fully accepted.
        client.call_json("/ping", &json!({})).await.unwrap();
        drop(client);

        for _ in 0..50 {
            if !disconnected.lock().unwrap().is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        let observed = disconnected.lock().unwrap();
        assert_eq!(observed.len(), 1, "expected exactly one disconnect");
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn slow_consumer_surfaces_backpressure() {
        // Capacity 1: the second outbound send saturates the channel.
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router)
            .with_outbound_capacity(1)
            .with_peer_registry(peers.clone());
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        // Subscribe but never drain, so notifies accumulate in the
        // *server's* outbound channel as well (after the writer fills
        // its own buffer). The exact mechanism doesn't matter; we
        // just need to push enough that try_send eventually returns
        // Full.
        let _notifies = client.subscribe_notifies().expect("subscribe");
        client.call_json("/ping", &json!({})).await.unwrap();

        assert_eq!(peers.len(), 1);

        // Push notifies until we see Full. The bound is small so this
        // happens quickly; cap at a generous limit.
        let mut saw_full = false;
        for i in 0..1024 {
            let results = peers
                .broadcast_notify_json("/burst", &json!({ "i": i }))
                .unwrap();
            for (_, r) in results {
                match r {
                    Err(PeerSendError::Full) => {
                        saw_full = true;
                        break;
                    }
                    Err(PeerSendError::Disconnected) => break,
                    _ => {}
                }
            }
            if saw_full {
                break;
            }
        }
        assert!(saw_full, "expected PeerSendError::Full under backpressure");

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_after_disconnect_surfaces_disconnected() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).with_peer_registry(peers.clone());
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        client.call_json("/ping", &json!({})).await.unwrap();
        assert_eq!(peers.len(), 1);

        // Snapshot the peer handles so we can keep them after the
        // registry removes them on disconnect.
        let captured = peers.peers();
        assert_eq!(captured.len(), 1);

        drop(client);
        for _ in 0..50 {
            if peers.is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(peers.is_empty());

        // The captured handle's outbound channel is now closed.
        let err = captured[0]
            .send_notify("/after", NotifyBody::Json(b"{}".to_vec()))
            .unwrap_err();
        assert!(matches!(err, PeerSendError::Disconnected));

        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn hooks_compose_in_registration_order() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let order = Arc::new(Mutex::new(Vec::<u32>::new()));
        let order_a = Arc::clone(&order);
        let order_b = Arc::clone(&order);

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router)
            .on_peer_connect(move |_| order_a.lock().unwrap().push(1))
            .on_peer_connect(move |_| order_b.lock().unwrap().push(2));
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        client.call_json("/ping", &json!({})).await.unwrap();

        let snapshot = order.lock().unwrap().clone();
        assert_eq!(snapshot, vec![1, 2]);

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_utf8_and_raw() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).with_peer_registry(peers.clone());
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");
        client.call_json("/ping", &json!({})).await.unwrap();

        let utf_results = peers.broadcast_notify_utf8("/msg", "hello");
        for (_, r) in utf_results {
            r.expect("utf8 broadcast send");
        }

        let raw_results =
            peers.broadcast_notify_raw("/bytes", BodyFormat::RawBinary, &[1u8, 2, 3, 4]);
        for (_, r) in raw_results {
            r.expect("raw broadcast send");
        }

        let m1 = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(m1.query_str().unwrap(), "/msg");
        assert_eq!(m1.body, b"hello".to_vec());
        assert_eq!(m1.header.body_format, BodyFormat::Utf8 as u16);

        let m2 = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(m2.query_str().unwrap(), "/bytes");
        assert_eq!(m2.body, vec![1u8, 2, 3, 4]);
        assert_eq!(m2.header.body_format, BodyFormat::RawBinary as u16);

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    #[should_panic(expected = "WebSocketServer outbound capacity must be >= 1")]
    async fn outbound_capacity_zero_panics() {
        let router = Router::new();
        let _ = WebSocketServer::new(router).with_outbound_capacity(0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn panicking_connect_hook_still_runs_disconnect_cleanup() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        // with_peer_registry's insert hook runs first; the second hook
        // panics, simulating a faulty embedder callback. The disconnect
        // guard must still fire on unwind and remove the peer.
        let server = WebSocketServer::new(router)
            .with_peer_registry(peers.clone())
            .on_peer_connect(|_| panic!("boom"));
        let server_task = serve_one(listener, "/repe", server).await;

        // The client's handshake will likely succeed (the panic happens
        // post-handshake during hook execution), but the connection
        // will be torn down. We just need the registry to be empty
        // after the dust settles.
        let _ = WebSocketClient::connect(&format!("ws://{addr}/repe")).await;

        for _ in 0..100 {
            if peers.is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(
            peers.is_empty(),
            "panicking connect hook leaked peer in registry"
        );
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn handler_pushes_notify_to_calling_peer_via_with_json_ctx() {
        // A handler registered via with_json_ctx pushes a progress
        // notify back to the calling peer mid-request. Both the
        // notify and the response must arrive on the same connection.
        let router = Router::new().with_json_ctx("/work", |ctx, _params| {
            if let Some(peer) = ctx.peer() {
                let _ = peer.send_notify(
                    "/progress",
                    NotifyBody::Json(serde_json::to_vec(&json!({ "stage": "running" })).unwrap()),
                );
            }
            Ok(json!({ "done": true }))
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");

        let resp = client.call_json("/work", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "done": true }));

        let pushed = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .expect("progress notify did not arrive")
            .expect("channel closed");
        assert!(pushed.header.notify != 0);
        assert_eq!(pushed.query_str().unwrap(), "/progress");
        let body: serde_json::Value = pushed.json_body().unwrap();
        assert_eq!(body, json!({ "stage": "running" }));

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn ctx_handler_sees_no_peer_under_legacy_handle() {
        // When a context-aware handler is invoked via the legacy
        // HandlerErased::handle path (no peer threaded), ctx.peer()
        // is None. This guards the TCP-transport / direct-dispatch
        // fallback shape so a ctx-aware handler does not panic when
        // there is no peer.
        let router = Router::new().with_json_ctx("/probe", |ctx, _params| {
            Ok(json!({ "has_peer": ctx.peer().is_some() }))
        });
        let handler = router.get("/probe").expect("handler exists");

        let req = Message::builder()
            .id(1)
            .query_str("/probe")
            .query_format(QueryFormat::JsonPointer)
            .body_json(&json!({}))
            .unwrap()
            .build();
        let resp = handler.handle(&req).unwrap();
        let body: serde_json::Value = resp.json_body().unwrap();
        assert_eq!(body, json!({ "has_peer": false }));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn registry_callable_receives_peer_via_with_context() {
        // A Registry-backed handler wrapped in `WithContext` must see
        // the calling peer when the request comes in over the
        // WebSocket transport.
        use crate::Registry;
        use crate::registry::WithContext;

        let registry = Arc::new(Registry::new());
        registry
            .register_function(
                "/work",
                WithContext(|ctx: &CallContext, _params| {
                    if let Some(peer) = ctx.peer() {
                        let _ = peer.send_notify(
                            "/progress",
                            NotifyBody::Json(
                                serde_json::to_vec(&json!({ "stage": "registry" })).unwrap(),
                            ),
                        );
                    }
                    Ok(json!({ "done": true }))
                }),
            )
            .unwrap();

        let router = Router::new().with_registry("", Arc::clone(&registry));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");

        let resp = client.call_json("/work", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "done": true }));

        let pushed = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .expect("registry handler did not push a notify")
            .expect("channel closed");
        assert_eq!(pushed.query_str().unwrap(), "/progress");

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn middleware_preserves_ctx_across_pipeline() {
        // Middleware that calls next.run(req) without knowing about
        // CallContext must still thread ctx to the leaf handler.
        // This is what lets existing middleware compose with new
        // context-aware handlers.
        use crate::server::Next;
        let router = Router::new()
            .with_middleware(|req: &Message, next: Next<'_>| next.run(req))
            .with_json_ctx("/work", |ctx, _params| {
                Ok(json!({ "has_peer": ctx.peer().is_some() }))
            });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let resp = client.call_json("/work", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "has_peer": true }));

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn middleware_reads_calling_peer_via_next_ctx() {
        // Feature 5: a middleware that is not itself context-aware can
        // still reach the calling peer through `next.ctx()` /
        // `next.peer()`. Driven over the WebSocket server so a real
        // peer is attached.
        use crate::server::Next;
        use std::sync::atomic::AtomicBool;

        let saw_peer = Arc::new(AtomicBool::new(false));
        let saw_peer_mw = Arc::clone(&saw_peer);
        let router = Router::new()
            .with_middleware(move |req: &Message, next: Next<'_>| {
                // `peer()` is sugar for `ctx().and_then(|c| c.peer())`;
                // the two must agree.
                assert_eq!(
                    next.peer().is_some(),
                    next.ctx().and_then(|c| c.peer()).is_some()
                );
                if next.peer().is_some() {
                    saw_peer_mw.store(true, Ordering::SeqCst);
                }
                next.run(req)
            })
            .with_json("/ping", |_| Ok(json!({ "ok": true })));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let resp = client.call_json("/ping", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "ok": true }));
        assert!(
            saw_peer.load(Ordering::SeqCst),
            "middleware did not observe the calling peer via next.ctx()/next.peer()"
        );

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn shared_registry_across_two_servers_mints_unique_ids() {
        let router_a = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let router_b = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        let la = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let aa = la.local_addr().unwrap();
        let lb = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let ab = lb.local_addr().unwrap();

        let sa = WebSocketServer::new(router_a).with_peer_registry(peers.clone());
        let sb = WebSocketServer::new(router_b).with_peer_registry(peers.clone());
        let ta = serve_one(la, "/repe", sa).await;
        let tb = serve_one(lb, "/repe", sb).await;

        let c1 = WebSocketClient::connect(&format!("ws://{aa}/repe"))
            .await
            .unwrap();
        let c2 = WebSocketClient::connect(&format!("ws://{ab}/repe"))
            .await
            .unwrap();
        // Round-trips so both peers are registered.
        c1.call_json("/ping", &json!({})).await.unwrap();
        c2.call_json("/ping", &json!({})).await.unwrap();

        // Both peers must be present with distinct ids.
        assert_eq!(peers.len(), 2);
        let snapshot = peers.peers();
        let ids: std::collections::HashSet<_> = snapshot.iter().map(|p| p.peer_id().0).collect();
        assert_eq!(ids.len(), 2, "shared registry minted colliding PeerIds");

        drop(c1);
        drop(c2);
        ta.abort();
        tb.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn into_shared_serves_connection_and_registers_peer() {
        // Feature 4: drive a connection through into_shared() + accept
        // + serve_connection directly (the one-port co-hosting shape an
        // embedder uses to share a TCP port with its own HTTP routes),
        // round-trip a request, and assert a PeerRegistry attached via
        // with_peer_registry observes the peer.
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();
        let server = WebSocketServer::new(router).with_peer_registry(peers.clone());
        let shared = server.into_shared();

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();

        let accept_task = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            if let Ok(ws) = WebSocketServer::accept(stream, "/repe").await {
                let _ = shared.serve_connection(ws).await;
            }
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let resp = client.call_json("/ping", &json!({})).await.unwrap();
        assert_eq!(resp, json!({ "ok": true }));

        // Connect hooks fire before traffic is processed, so by the time
        // the /ping response is in hand the peer is already registered.
        assert_eq!(peers.len(), 1);

        drop(client);
        let _ = tokio::time::timeout(Duration::from_secs(5), accept_task).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn off_reader_handler_does_not_block_the_reader() {
        use std::sync::Condvar;
        // `/wait` is off-reader and parks on a condvar until `/signal`
        // (an inline handler on the *same* connection) opens the gate.
        // If the off-reader handler ran on the reader task, `/signal`
        // could never be decoded and this would deadlock.
        let gate = Arc::new((Mutex::new(false), Condvar::new()));
        let gate_wait = Arc::clone(&gate);
        let gate_signal = Arc::clone(&gate);

        let router = Router::new()
            .with_json_blocking("/wait", move |_| {
                let (lock, cv) = &*gate_wait;
                let mut ready = lock.lock().unwrap();
                while !*ready {
                    ready = cv.wait(ready).unwrap();
                }
                Ok(json!({ "woke": true }))
            })
            .with_json("/signal", move |_| {
                let (lock, cv) = &*gate_signal;
                *lock.lock().unwrap() = true;
                cv.notify_all();
                Ok(json!({ "signaled": true }))
            });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let waiter = client.clone();
        let wait_call = tokio::spawn(async move { waiter.call_json("/wait", &json!({})).await });

        // Give `/wait` time to reach the server and park.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // If the reader were blocked inside `/wait`, this would time out.
        let signaled = tokio::time::timeout(
            Duration::from_secs(2),
            client.call_json("/signal", &json!({})),
        )
        .await
        .expect("/signal timed out: off-reader handler blocked the reader")
        .unwrap();
        assert_eq!(signaled["signaled"], true);

        let woke = tokio::time::timeout(Duration::from_secs(2), wait_call)
            .await
            .expect("/wait timed out")
            .unwrap()
            .unwrap();
        assert_eq!(woke["woke"], true);

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn off_reader_handler_panic_returns_error_and_keeps_connection() {
        // A panicking off-reader handler is caught and mapped to an
        // error response (not swallowed into a client hang), and it must
        // not take the connection down.
        let router = Router::new()
            .with_json_blocking(
                "/boom",
                |_| -> Result<serde_json::Value, (ErrorCode, String)> {
                    panic!("handler exploded");
                },
            )
            .with_json("/ping", |_| Ok(json!({ "pong": true })));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();

        let err = tokio::time::timeout(
            Duration::from_secs(2),
            client.call_json("/boom", &json!({})),
        )
        .await
        .expect("/boom timed out: panic produced no response")
        .unwrap_err();
        match err {
            RepeError::ServerError { code, .. } => {
                assert_eq!(code, ErrorCode::InternalError)
            }
            other => panic!("expected ServerError, got {other:?}"),
        }

        // The connection is still alive afterward.
        let pong = client.call_json("/ping", &json!({})).await.unwrap();
        assert_eq!(pong["pong"], true);

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn off_reader_limit_rejects_when_saturated() {
        use std::sync::Condvar;
        // Cap of 1: the first `/hold` takes the only slot and parks; a
        // second `/hold` on the same connection must be rejected (not
        // queued, and without blocking the reader).
        let gate = Arc::new((Mutex::new(false), Condvar::new()));
        let gate_hold = Arc::clone(&gate);

        let router = Router::new().with_json_blocking("/hold", move |_| {
            let (lock, cv) = &*gate_hold;
            let mut ready = lock.lock().unwrap();
            while !*ready {
                ready = cv.wait(ready).unwrap();
            }
            Ok(json!({ "released": true }))
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).with_offreader_limit(1);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let holder = client.clone();
        let first = tokio::spawn(async move { holder.call_json("/hold", &json!({})).await });

        // Let the first `/hold` take the slot and park.
        tokio::time::sleep(Duration::from_millis(100)).await;

        let rejected = tokio::time::timeout(
            Duration::from_secs(2),
            client.call_json("/hold", &json!({})),
        )
        .await
        .expect("second /hold timed out instead of being rejected")
        .unwrap_err();
        match rejected {
            RepeError::ServerError { code, .. } => {
                assert_eq!(code, ErrorCode::ResourceExhausted)
            }
            other => panic!("expected saturation ServerError, got {other:?}"),
        }

        // Release the first `/hold`; it completes and frees the slot.
        {
            let (lock, cv) = &*gate;
            *lock.lock().unwrap() = true;
            cv.notify_all();
        }
        let released = tokio::time::timeout(Duration::from_secs(2), first)
            .await
            .expect("first /hold timed out")
            .unwrap()
            .unwrap();
        assert_eq!(released["released"], true);

        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn off_reader_drives_windowed_stream_to_completion() {
        // Feature 1 end-to-end: a `with_json_ctx_blocking` /begin
        // handler drives a real repe::stream producer (wait_for_credit
        // -> peer.send_notify -> record_sent); inbound ACKs route
        // through an inline /ack handler that calls record_ack; and a
        // multi-window transfer completes over the WebSocket transport
        // with the client draining notifies. Because /begin runs off
        // the reader, the reader stays free to decode the ACK frames the
        // producer parks waiting on -- the deadlock this whole feature
        // exists to remove. The window holds only 4 chunks of a
        // 16-chunk transfer, so it fills and is released repeatedly;
        // the transfer can only complete if credit release works.
        use crate::stream::{TransferControl, TransferRegistry};
        use std::time::Instant;

        const WINDOW: u64 = 1024;
        const CHUNK: u64 = 256;
        const NUM_CHUNKS: u64 = 16; // 4096 bytes total; window = 4 chunks

        #[derive(Hash, Eq, PartialEq, Copy, Clone)]
        struct TransferId(u64);

        let registry: Arc<TransferRegistry<TransferId>> = Arc::new(TransferRegistry::new());
        let registry_begin = Arc::clone(&registry);
        let registry_ack = Arc::clone(&registry);

        let router = Router::new()
            .with_json_ctx_blocking("/begin", move |ctx, _params| {
                let peer = ctx.peer().expect("websocket peer present").clone();
                let control = TransferControl::new(WINDOW);
                control.set_peer(peer);
                registry_begin.register(TransferId(1), Arc::clone(&control));

                let mut offset: u64 = 0;
                for seq in 0..NUM_CHUNKS {
                    let last = seq + 1 == NUM_CHUNKS;
                    let deadline = Instant::now() + Duration::from_secs(10);
                    control
                        .wait_for_credit(CHUNK, deadline)
                        .map_err(|e| (ErrorCode::ApplicationErrorBase, e.to_string()))?;
                    let through = offset + CHUNK;
                    let body =
                        serde_json::to_vec(&json!({ "through": through, "last": last })).unwrap();
                    let peer = control.peer().expect("peer installed");
                    peer.send_notify("/chunk", NotifyBody::Json(body))
                        .map_err(|e| {
                            (ErrorCode::ApplicationErrorBase, format!("send failed: {e}"))
                        })?;
                    control.record_sent(through);
                    offset = through;
                }
                registry_begin.unregister(TransferId(1));
                Ok(json!({ "sent": NUM_CHUNKS, "bytes": offset }))
            })
            .with_json("/ack", move |params| {
                let file_index = params["file_index"].as_u64().unwrap_or(0) as u32;
                let through = params["through"].as_u64().unwrap_or(0);
                if let Some(control) = registry_ack.get(TransferId(1)) {
                    control.record_ack(file_index, through);
                }
                Ok(json!({ "ok": true }))
            });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");

        // /begin runs the whole transfer and only responds when done, so
        // drive it concurrently while we drain chunk notifies and ACK.
        let begin_client = client.clone();
        let begin = tokio::spawn(async move { begin_client.call_json("/begin", &json!({})).await });

        let mut count: u64 = 0;
        let mut last_through: u64 = 0;
        loop {
            let chunk = tokio::time::timeout(Duration::from_secs(10), notifies.recv())
                .await
                .expect("chunk notify did not arrive (producer likely starved for credit)")
                .expect("notify channel closed");
            assert_eq!(chunk.query_str().unwrap(), "/chunk");
            let body: serde_json::Value = chunk.json_body().unwrap();
            let through = body["through"].as_u64().unwrap();
            let last = body["last"].as_bool().unwrap();
            // Chunks arrive in order, each advancing by exactly CHUNK.
            assert_eq!(through, last_through + CHUNK);
            last_through = through;
            count += 1;
            // ACK everything received so far; record_ack releases credit
            // so a producer parked in wait_for_credit resumes.
            client
                .call_json("/ack", &json!({ "file_index": 0, "through": through }))
                .await
                .unwrap();
            if last {
                break;
            }
        }
        assert_eq!(count, NUM_CHUNKS);
        assert_eq!(last_through, NUM_CHUNKS * CHUNK);

        let begin_resp = tokio::time::timeout(Duration::from_secs(10), begin)
            .await
            .expect("/begin did not complete")
            .expect("/begin task panicked")
            .expect("/begin returned an error");
        assert_eq!(begin_resp["sent"].as_u64(), Some(NUM_CHUNKS));
        assert_eq!(begin_resp["bytes"].as_u64(), Some(NUM_CHUNKS * CHUNK));
        assert!(
            registry.is_empty(),
            "transfer should be unregistered after completion"
        );

        drop(client);
        server_task.abort();
    }

    // ---- Request 1: cancellation signal on CallContext -------------

    fn dummy_peer() -> PeerHandle {
        struct Dummy;
        impl PeerSink for Dummy {
            fn send_notify(&self, _: &str, _: NotifyBody) -> Result<(), PeerSendError> {
                Ok(())
            }
        }
        PeerHandle::new(PeerId(99), Arc::new(Dummy))
    }

    #[tokio::test(flavor = "current_thread")]
    async fn call_context_cancelled_future_resolves_when_token_cancels() {
        // Drive CallContext::cancelled() against a real token-backed
        // signal: before cancel it must not resolve; after cancel it
        // resolves and is_cancelled() flips.
        let token = CancellationToken::new();
        let signal = TokenSignal(token.clone());
        let peer = dummy_peer();
        let ctx = CallContext::with_cancel("/m", &peer, &signal);

        assert!(!ctx.is_cancelled());
        let early = tokio::time::timeout(Duration::from_millis(50), ctx.cancelled()).await;
        assert!(early.is_err(), "cancelled() resolved before cancel");

        token.cancel();
        assert!(ctx.is_cancelled());
        tokio::time::timeout(Duration::from_secs(1), ctx.cancelled())
            .await
            .expect("cancelled() did not resolve after token cancel");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn detached_context_cancelled_never_resolves() {
        // The peer-less, signal-less context degrades to a
        // never-cancelling no-op so a select! arm built on it stays
        // dormant rather than firing spuriously.
        let ctx = CallContext::detached("/m");
        assert!(!ctx.is_cancelled());
        let r = tokio::time::timeout(Duration::from_millis(50), ctx.cancelled()).await;
        assert!(r.is_err(), "detached cancelled() must never resolve");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn off_reader_handler_observes_cancellation_on_disconnect() {
        use std::sync::atomic::AtomicBool;
        // A sync off-reader handler polls ctx.is_cancelled() at loop
        // boundaries (the documented pattern). When the client
        // disconnects, the DisconnectGuard cancels the connection token
        // and the handler observes it and winds down.
        let observed = Arc::new(AtomicBool::new(false));
        let observed_h = Arc::clone(&observed);

        let router = Router::new().with_json_ctx_blocking("/run", move |ctx, _params| {
            loop {
                if ctx.is_cancelled() {
                    observed_h.store(true, Ordering::SeqCst);
                    return Ok(json!({ "cancelled": true }));
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router);
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        // Fire the long off-reader handler as a notify so there is no
        // held response future (and thus no client clone) keeping the
        // connection open: dropping the sole client handle truly closes
        // it, which is what triggers the disconnect we want to observe.
        client.notify_json("/run", &json!({})).await.unwrap();

        // Let the handler reach its poll loop, then disconnect.
        tokio::time::sleep(Duration::from_millis(100)).await;
        drop(client);

        let mut seen = false;
        for _ in 0..200 {
            if observed.load(Ordering::SeqCst) {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(
            seen,
            "off-reader handler did not observe cancellation on disconnect"
        );
        server_task.abort();
    }

    // ---- Request 2: graceful connection drain on shutdown ----------

    #[tokio::test(flavor = "current_thread")]
    async fn graceful_drain_cancels_inflight_and_returns() {
        use std::sync::atomic::AtomicBool;
        // serve_listener_with_graceful_drain: on shutdown the drain
        // cancels in-flight off-reader handlers (so a cooperative handler
        // winds down) and returns Ok within the deadline. The client
        // stays connected, so cancellation comes purely from the drain.
        let observed = Arc::new(AtomicBool::new(false));
        let observed_h = Arc::clone(&observed);

        let router = Router::new().with_json_ctx_blocking("/run", move |ctx, _params| {
            loop {
                if ctx.is_cancelled() {
                    observed_h.store(true, Ordering::SeqCst);
                    return Ok(json!({ "done": true }));
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
        let server = WebSocketServer::new(router);
        let serve = tokio::spawn(async move {
            server
                .serve_listener_with_graceful_drain(
                    listener,
                    "/repe",
                    async {
                        let _ = shutdown_rx.await;
                    },
                    Duration::from_secs(5),
                )
                .await
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        // Fire the handler as a notify so it runs off-reader without a
        // held response future.
        client.notify_json("/run", &json!({})).await.unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        shutdown_tx.send(()).unwrap();
        let result = tokio::time::timeout(Duration::from_secs(5), serve)
            .await
            .expect("serve did not return after graceful drain")
            .expect("serve task panicked");
        assert!(result.is_ok(), "serve returned error: {result:?}");
        // The handler observes the drain's cancel within its poll
        // interval, which can land just after the connection task (and
        // thus serve) has already returned -- so poll for it.
        let mut seen = false;
        for _ in 0..200 {
            if observed.load(Ordering::SeqCst) {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(seen, "handler did not observe drain cancellation");

        drop(client);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn graceful_drain_aborts_uncooperative_handler_after_timeout() {
        // A handler that never checks cancellation blocks until the test
        // releases it. The drain must abort the connection at its
        // deadline rather than wait for the handler, so serve returns
        // promptly despite the stuck blocking thread.
        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
        let release_rx = Arc::new(Mutex::new(release_rx));

        let router = Router::new().with_json_blocking("/stuck", move |_| {
            let _ = release_rx.lock().unwrap().recv();
            Ok(json!({ "done": true }))
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
        let server = WebSocketServer::new(router);
        let serve = tokio::spawn(async move {
            server
                .serve_listener_with_graceful_drain(
                    listener,
                    "/repe",
                    async {
                        let _ = shutdown_rx.await;
                    },
                    Duration::from_millis(300),
                )
                .await
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let runner = client.clone();
        let _call = tokio::spawn(async move { runner.call_json("/stuck", &json!({})).await });
        tokio::time::sleep(Duration::from_millis(100)).await;

        shutdown_tx.send(()).unwrap();
        let result = tokio::time::timeout(Duration::from_secs(3), serve)
            .await
            .expect("graceful drain hung on an uncooperative handler")
            .expect("serve task panicked");
        assert!(result.is_ok(), "serve returned error: {result:?}");

        // Release the blocking handler so its thread exits cleanly.
        let _ = release_tx.send(());
        drop(client);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cohosting_serve_connection_with_cancel_wakes_handler() {
        use std::sync::atomic::AtomicBool;
        // The co-hosting shape: an embedder owns its accept loop and
        // serves through serve_connection_with_cancel with a shared
        // ShutdownToken. Cancelling the token wakes an in-flight
        // off-reader handler even though the client stays connected.
        let observed = Arc::new(AtomicBool::new(false));
        let observed_h = Arc::clone(&observed);

        let router = Router::new().with_json_ctx_blocking("/run", move |ctx, _params| {
            loop {
                if ctx.is_cancelled() {
                    observed_h.store(true, Ordering::SeqCst);
                    return Ok(json!({ "done": true }));
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let shared = WebSocketServer::new(router).into_shared();
        let token = ShutdownToken::new();
        let token_for_loop = token.clone();

        let accept_task = tokio::spawn(async move {
            if let Ok((stream, _)) = listener.accept().await
                && let Ok(ws) = WebSocketServer::accept(stream, "/repe").await
            {
                let _ = shared
                    .serve_connection_with_cancel(ws, &token_for_loop)
                    .await;
            }
        });

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        client.notify_json("/run", &json!({})).await.unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        token.cancel();

        let mut seen = false;
        for _ in 0..200 {
            if observed.load(Ordering::SeqCst) {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(seen, "handler did not observe ShutdownToken cancellation");

        drop(client);
        let _ = tokio::time::timeout(Duration::from_secs(2), accept_task).await;
    }

    // ---- Request 3: structured error hook --------------------------

    #[test]
    fn connection_error_maps_to_wire_code() {
        assert_eq!(
            ConnectionError::HandlerPanic {
                method: "/x".into()
            }
            .error_code(),
            Some(ErrorCode::InternalError)
        );
        assert_eq!(
            ConnectionError::Saturation {
                method: "/x".into()
            }
            .error_code(),
            Some(ErrorCode::ResourceExhausted)
        );
        assert_eq!(
            ConnectionError::Connection(RepeError::InvalidSpec(0)).error_code(),
            None
        );
        assert_eq!(
            ConnectionError::Handshake(RepeError::InvalidSpec(0)).error_code(),
            None
        );
    }

    // ---- Outbound framing guard ------------------------------------

    /// `frame_outbound` sizes a frame in closed form and checks the limit
    /// before building it, so the number the guard sees is right only while
    /// `HEADER_SIZE + query + body` is what `into_wire_bytes` emits. This pins
    /// the threshold end to end — a frame exactly at the limit goes out, one
    /// byte over is refused — plus the two things the reordering could quietly
    /// break: the reported `size` is still the framed length, and the method
    /// name still survives to the hook now that it is read from a message the
    /// guard has already inspected rather than copied out beforehand.
    #[test]
    fn frame_outbound_checks_the_length_it_frames() {
        const PATH: &str = "/sized";
        const BODY: usize = 64;
        let build = |notify: bool| {
            Message::builder()
                .id(1)
                .notify(notify)
                .query_str(PATH)
                .query_format(QueryFormat::JsonPointer)
                .body_bytes(vec![b'x'; BODY])
                .body_format_code(u16::from(BodyFormat::RawBinary))
                .build()
        };
        let framed_len = build(true).into_wire_bytes().len();
        assert_eq!(
            framed_len,
            crate::constants::HEADER_SIZE + PATH.len() + BODY
        );

        let at_limit =
            crate::WebSocketLimits::default().with_assumed_peer_frame_limit(Some(framed_len));
        assert_eq!(
            frame_outbound(build(true), &at_limit, &[])
                .expect("a frame exactly at the limit goes out")
                .len(),
            framed_len,
        );

        // One byte under. A notify has no response to carry an error, so it is
        // dropped outright — the unambiguous signal that the guard fired.
        let under =
            crate::WebSocketLimits::default().with_assumed_peer_frame_limit(Some(framed_len - 1));
        assert!(frame_outbound(build(true), &under, &[]).is_none());

        // The same refusal on a request yields the replacement error frame and
        // reports what the refused message was carrying.
        let seen = Arc::new(Mutex::new(Vec::<(String, usize, usize)>::new()));
        let seen_h = Arc::clone(&seen);
        let hook: ErrorHook = Arc::new(move |err: &ConnectionError| {
            if let ConnectionError::OutboundTooLarge {
                method,
                size,
                limit,
            } = err
            {
                seen_h.lock().unwrap().push((method.clone(), *size, *limit));
            }
        });
        let replacement = frame_outbound(build(false), &under, std::slice::from_ref(&hook))
            .expect("a request's response is replaced rather than dropped");
        assert_ne!(replacement.len(), framed_len);
        assert_eq!(
            *seen.lock().unwrap(),
            vec![(PATH.to_string(), framed_len, framed_len - 1)],
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn on_error_hook_receives_handler_panic() {
        let events = Arc::new(Mutex::new(Vec::<String>::new()));
        let events_h = Arc::clone(&events);

        let router = Router::new()
            .with_json_blocking(
                "/boom",
                |_| -> Result<serde_json::Value, (ErrorCode, String)> {
                    panic!("kaboom");
                },
            )
            .with_json("/ping", |_| Ok(json!({ "ok": true })));

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router).on_error(move |err| {
            if let ConnectionError::HandlerPanic { method } = err {
                events_h.lock().unwrap().push(format!("panic:{method}"));
            }
        });
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        // The panic is caught and surfaces as an InternalError response.
        let err = client.call_json("/boom", &json!({})).await.unwrap_err();
        match err {
            RepeError::ServerError { code, .. } => assert_eq!(code, ErrorCode::InternalError),
            other => panic!("expected ServerError, got {other:?}"),
        }
        // Connection survives; round-trip to be sure the hook ran.
        let _ = client.call_json("/ping", &json!({})).await.unwrap();

        let mut seen = false;
        for _ in 0..200 {
            if events.lock().unwrap().iter().any(|e| e == "panic:/boom") {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(seen, "on_error did not receive HandlerPanic for /boom");
        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn on_error_hook_receives_saturation() {
        use std::sync::Condvar;
        let events = Arc::new(Mutex::new(Vec::<String>::new()));
        let events_h = Arc::clone(&events);
        let gate = Arc::new((Mutex::new(false), Condvar::new()));
        let gate_hold = Arc::clone(&gate);

        let router = Router::new().with_json_blocking("/hold", move |_| {
            let (lock, cv) = &*gate_hold;
            let mut ready = lock.lock().unwrap();
            while !*ready {
                ready = cv.wait(ready).unwrap();
            }
            Ok(json!({ "released": true }))
        });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = WebSocketServer::new(router)
            .with_offreader_limit(1)
            .on_error(move |err| {
                if let ConnectionError::Saturation { method } = err {
                    events_h.lock().unwrap().push(format!("sat:{method}"));
                }
            });
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        let holder = client.clone();
        let _first = tokio::spawn(async move { holder.call_json("/hold", &json!({})).await });
        tokio::time::sleep(Duration::from_millis(100)).await;
        // Second /hold saturates the cap-of-1 and is rejected.
        let err = client.call_json("/hold", &json!({})).await.unwrap_err();
        match err {
            RepeError::ServerError { code, .. } => assert_eq!(code, ErrorCode::ResourceExhausted),
            other => panic!("expected ServerError, got {other:?}"),
        }

        let mut seen = false;
        for _ in 0..200 {
            if events.lock().unwrap().iter().any(|e| e == "sat:/hold") {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(seen, "on_error did not receive Saturation for /hold");

        // Release the first handler so its thread exits cleanly.
        {
            let (lock, cv) = &*gate;
            *lock.lock().unwrap() = true;
            cv.notify_all();
        }
        drop(client);
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn on_error_hook_receives_handshake_error() {
        let events = Arc::new(Mutex::new(Vec::<String>::new()));
        let events_h = Arc::clone(&events);

        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
        let server = WebSocketServer::new(router).on_error(move |err| {
            if let ConnectionError::Handshake(_) = err {
                events_h.lock().unwrap().push("handshake".into());
            }
        });
        let serve = tokio::spawn(async move {
            server
                .serve_listener_with_shutdown(listener, "/repe", async {
                    let _ = shutdown_rx.await;
                })
                .await
        });

        // Connect to the wrong path: the server rejects the upgrade, so
        // its accept loop reports a Handshake error through on_error.
        let bad = WebSocketClient::connect(&format!("ws://{addr}/wrong")).await;
        assert!(bad.is_err(), "connect to wrong path should fail");

        let mut seen = false;
        for _ in 0..200 {
            if !events.lock().unwrap().is_empty() {
                seen = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(seen, "on_error did not receive a Handshake error");

        shutdown_tx.send(()).unwrap();
        let _ = tokio::time::timeout(Duration::from_secs(5), serve).await;
    }

    // ---- Friction 1: one-port co-hosting WS-vs-HTTP classifier ------

    #[test]
    fn classifier_detects_websocket_upgrade_head() {
        let req = b"GET /repe HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\n\
                    Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZQ==\r\n\
                    Sec-WebSocket-Version: 13\r\n\r\n";
        assert!(head_requests_websocket_upgrade(req));
    }

    #[test]
    fn classifier_is_case_insensitive() {
        let req = b"GET / HTTP/1.1\r\nupgrade: WebSocket\r\n\r\n";
        assert!(head_requests_websocket_upgrade(req));
    }

    #[test]
    fn classifier_rejects_plain_http() {
        let req = b"GET /healthz HTTP/1.1\r\nHost: x\r\nAccept: */*\r\n\r\n";
        assert!(!head_requests_websocket_upgrade(req));
    }

    #[test]
    fn classifier_ignores_websocket_outside_the_upgrade_header() {
        // "websocket" appears in the request target and a header value but
        // never as an Upgrade header, so this is a plain HTTP request.
        let req =
            b"GET /websocket-status HTTP/1.1\r\nHost: x\r\nUser-Agent: websocket-probe/1.0\r\n\r\n";
        assert!(!head_requests_websocket_upgrade(req));
    }

    #[test]
    fn classifier_handles_head_without_terminator() {
        // The first readable chunk ended mid-header, but the Upgrade line
        // is already complete and present.
        let req = b"GET /repe HTTP/1.1\r\nUpgrade: websocket\r\nConnection: Upg";
        assert!(head_requests_websocket_upgrade(req));
    }

    #[test]
    fn classifier_empty_head_is_not_upgrade() {
        assert!(!head_requests_websocket_upgrade(b""));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn is_websocket_upgrade_peeks_without_consuming() {
        use tokio::io::AsyncWriteExt;

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();

        // The server classifies each accepted stream and confirms peek left
        // the request head intact for a subsequent reader (`accept`).
        let server = tokio::spawn(async move {
            let mut verdicts = Vec::new();
            for _ in 0..2 {
                let (stream, _) = listener.accept().await.unwrap();
                let is_ws = is_websocket_upgrade(&stream).await.unwrap();
                // Peek again: the bytes must still be there (non-destructive).
                let mut buf = [0u8; 32];
                let n = stream.peek(&mut buf).await.unwrap();
                verdicts.push((is_ws, buf[..n].starts_with(b"GET ")));
            }
            verdicts
        });

        let mut ws_like = TcpStream::connect(addr).await.unwrap();
        ws_like
            .write_all(b"GET /repe HTTP/1.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
            .await
            .unwrap();
        ws_like.flush().await.unwrap();

        let mut http = TcpStream::connect(addr).await.unwrap();
        http.write_all(b"GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n")
            .await
            .unwrap();
        http.flush().await.unwrap();

        let verdicts = tokio::time::timeout(Duration::from_secs(5), server)
            .await
            .expect("classifier server hung")
            .unwrap();
        // Connection order is deterministic on loopback (first connect is
        // accepted first), but assert on the set to stay robust: exactly one
        // upgrade and one non-upgrade, both with their head still readable.
        assert!(verdicts.iter().all(|(_, head_intact)| *head_intact));
        let upgrades = verdicts.iter().filter(|(is_ws, _)| *is_ws).count();
        assert_eq!(upgrades, 1, "exactly one stream should classify as WS");

        drop(ws_like);
        drop(http);
    }

    // ---- Friction 2: handshake-context connect hook + alias --------

    /// Co-hosting accept loop that threads the captured [`HandshakeContext`]
    /// so `on_peer_connect_with_handshake` hooks fire (mirrors the built-in
    /// `serve*` loops, which also capture it).
    async fn serve_one_with_handshake(
        listener: TcpListener,
        path: &str,
        server: WebSocketServer,
    ) -> tokio::task::JoinHandle<()> {
        let path = path.to_string();
        let shared = server.into_shared();
        tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let path = path.clone();
                let shared = shared.clone();
                tokio::spawn(async move {
                    if let Ok((ws, hs)) =
                        WebSocketServer::accept_with_handshake(stream, &path).await
                    {
                        let _ = shared.serve_connection_with_handshake(ws, hs).await;
                    }
                });
            }
        })
    }

    #[tokio::test(flavor = "current_thread")]
    async fn handshake_query_param_drives_alias_for_targeted_push() {
        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let peers = PeerRegistry::new();

        // Capture the context fields the hook saw, to assert the handshake
        // was threaded through with its path, query, and headers intact.
        let captured = Arc::new(Mutex::new(None::<(String, Option<String>, Option<String>)>));
        let captured_hook = Arc::clone(&captured);
        let peers_hook = peers.clone();
        let server = WebSocketServer::new(router)
            .with_peer_registry(peers.clone())
            .on_peer_connect_with_handshake(move |peer, hs| {
                *captured_hook.lock().unwrap() = Some((
                    hs.path().to_string(),
                    hs.query().map(str::to_string),
                    hs.header("upgrade").map(str::to_string),
                ));
                // The embedder's key rides in the query string: token=<id>.
                if let Some(token) = hs.query().and_then(|q| q.strip_prefix("token=")) {
                    peers_hook.alias(peer.peer_id(), token);
                }
            });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server_task = serve_one_with_handshake(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe?token=abc123"))
            .await
            .unwrap();
        let mut notifies = client.subscribe_notifies().expect("subscribe");
        // Round-trip so the connect hooks (registry insert, then alias) ran.
        client.call_json("/ping", &json!({})).await.unwrap();

        // The hook observed the upgrade request context.
        let seen = captured.lock().unwrap().clone().expect("hook fired");
        assert_eq!(seen.0, "/repe");
        assert_eq!(seen.1.as_deref(), Some("token=abc123"));
        assert_eq!(seen.2.as_deref(), Some("websocket"));

        // Targeted push addressed by the embedder's own identity -- no
        // parallel key -> PeerId map maintained by hand.
        let handle = peers.get_by("abc123").expect("alias resolved to a peer");
        handle
            .send_notify("/nudge", NotifyBody::Json(b"{}".to_vec()))
            .unwrap();

        let pushed = tokio::time::timeout(Duration::from_secs(2), notifies.recv())
            .await
            .expect("nudge did not arrive")
            .expect("notify channel closed");
        assert_eq!(pushed.query_str().unwrap(), "/nudge");

        // Disconnect drops the peer and its alias in one step.
        drop(client);
        for _ in 0..50 {
            if peers.get_by("abc123").is_none() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(
            peers.get_by("abc123").is_none(),
            "alias not cleaned up on disconnect"
        );
        server_task.abort();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn plain_serve_connection_does_not_fire_handshake_hook() {
        // A connection served through plain `serve_connection` carries no
        // captured handshake, so `on_peer_connect_with_handshake` must not
        // fire (while the plain `on_peer_connect` still does).
        use std::sync::atomic::AtomicUsize;
        let plain = Arc::new(AtomicUsize::new(0));
        let ctx = Arc::new(AtomicUsize::new(0));
        let plain_h = Arc::clone(&plain);
        let ctx_h = Arc::clone(&ctx);

        let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));
        let server = WebSocketServer::new(router)
            .on_peer_connect(move |_| {
                plain_h.fetch_add(1, Ordering::SeqCst);
            })
            .on_peer_connect_with_handshake(move |_, _| {
                ctx_h.fetch_add(1, Ordering::SeqCst);
            });

        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        // serve_one uses plain accept + serve_connection (no handshake).
        let server_task = serve_one(listener, "/repe", server).await;

        let client = WebSocketClient::connect(&format!("ws://{addr}/repe"))
            .await
            .unwrap();
        client.call_json("/ping", &json!({})).await.unwrap();

        assert_eq!(plain.load(Ordering::SeqCst), 1, "plain connect hook ran");
        assert_eq!(
            ctx.load(Ordering::SeqCst),
            0,
            "handshake hook must not fire without a captured handshake"
        );

        drop(client);
        server_task.abort();
    }

    #[test]
    fn handshake_capture_drops_non_ascii_header_values_and_keeps_ascii() {
        // The capture path keeps only header values that round-trip to
        // clean text, so an embedder keying off a token / auth header sees
        // a non-ASCII value as absent (fail-closed) rather than as a
        // U+FFFD-mangled key that no `get_by` lookup would ever match.
        use tungstenite::http;
        let garbled = http::HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap();
        let request = http::Request::builder()
            .uri("/repe?token=abc123")
            .header("authorization", "Bearer good-token")
            .header("x-garbled", garbled)
            .body(())
            .unwrap();

        let ctx = HandshakeContext::from_http_request(&request);

        // The ASCII header survives and stays case-insensitively addressable.
        assert_eq!(ctx.header("authorization"), Some("Bearer good-token"));
        assert_eq!(ctx.header("Authorization"), Some("Bearer good-token"));
        // The non-ASCII value is dropped at capture: absent, not mangled.
        assert_eq!(ctx.header("x-garbled"), None);
        // ...and it is absent from the full iterator too.
        assert!(ctx.headers().all(|(name, _)| name != "x-garbled"));
        // Path and query are still captured verbatim.
        assert_eq!(ctx.path(), "/repe");
        assert_eq!(ctx.query(), Some("token=abc123"));
    }

    #[test]
    fn handshake_debug_redacts_credentials() {
        // The hand-written Debug must not spill the query string or header
        // values (the documented key / token carriers) into logs.
        use tungstenite::http;
        let request = http::Request::builder()
            .uri("/repe?token=super-secret")
            .header("authorization", "Bearer super-secret")
            .body(())
            .unwrap();

        let ctx = HandshakeContext::from_http_request(&request);
        let rendered = format!("{ctx:?}");

        // Neither secret value appears anywhere in the rendering.
        assert!(
            !rendered.contains("super-secret"),
            "Debug leaked a credential: {rendered}"
        );
        // The safe-to-show shape does: the path and the header *name*.
        assert!(rendered.contains("/repe"), "rendered = {rendered}");
        assert!(rendered.contains("authorization"), "rendered = {rendered}");
        // Query presence is signalled without exposing its value.
        assert!(rendered.contains("<redacted>"), "rendered = {rendered}");
    }
}