musli-web 0.5.0

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

use core::cell::{Cell, RefCell};
use core::future::Future;
use core::hash::Hash;
use core::marker::PhantomData;
use core::mem;
use core::ops::Deref;
use core::pin::Pin;
use core::ptr::NonNull;
use core::task::{Context, Poll, Waker};
use core::{any, fmt};
use std::collections::VecDeque;

use alloc::boxed::Box;
use alloc::format;
use alloc::rc::Rc;
use alloc::rc::Weak;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use std::collections::hash_map::{Entry, HashMap};

use slab::Slab;

use crate::api::{self, ChannelId, DecodeBody, Event, Format, MessageId, Mode};
use crate::format;

#[cfg(test)]
mod tests;

const MAX_CAPACITY: usize = 1048576;

/// An empty request body.
#[non_exhaustive]
pub struct EmptyBody;

/// An empty callback.
#[non_exhaustive]
pub struct EmptyCallback;

trait RequestCallback {
    fn error(&self, error: Error);

    fn as_request(&self) -> Option<&(dyn Callback<Result<RawPacket, Error>> + 'static)> {
        None
    }

    fn as_channel(&self) -> Option<&(dyn Fn(Result<ChannelId, Error>) + 'static)> {
        None
    }

    /// The format and mode this is a negotiation for, if it is one.
    fn as_negotiate(&self) -> Option<(Format, Mode)> {
        None
    }
}

/// The pending callback used for a format negotiation issued by the service
/// itself.
struct NegotiateCallback(Format, Mode);

impl RequestCallback for NegotiateCallback {
    #[inline]
    fn as_negotiate(&self) -> Option<(Format, Mode)> {
        Some((self.0, self.1))
    }

    #[inline]
    fn error(&self, error: Error) {
        tracing::debug!("Format negotiation failed: {error}");
    }
}

/// Slab of state listeners.
type StateListeners = Slab<Rc<dyn Callback<State>>>;
/// Slab of broadcast listeners.
type Broadcasts = HashMap<MessageId, Slab<Rc<dyn Callback<Result<RawPacket>>>>>;
/// Queue of recycled buffers.
type Buffers = VecDeque<Box<BufData>>;
/// Pending requests.
type PendingRequests = HashMap<u32, Box<Pending<dyn RequestCallback>>>;

/// Location information for WebSocket implementation.
#[doc(hidden)]
pub struct Location {
    pub(crate) protocol: String,
    pub(crate) host: String,
    pub(crate) port: String,
}

pub(crate) mod sealed_socket {
    pub trait Sealed {}
}

pub(crate) trait SocketImpl
where
    Self: Sized + self::sealed_socket::Sealed,
{
    #[doc(hidden)]
    type Handles;

    #[doc(hidden)]
    fn new(url: &str, handles: &Self::Handles) -> Result<Self, Error>;

    /// Send a message in the given [`Mode`].
    ///
    /// [`Mode::Binary`] writes a binary frame and [`Mode::Text`] a text frame,
    /// which is what carries the mode between peers.
    #[doc(hidden)]
    fn send(&self, mode: Mode, data: &[u8]) -> Result<(), Error>;

    #[doc(hidden)]
    fn close(self) -> Result<(), Error>;
}

pub(crate) mod sealed_window {
    pub trait Sealed {}
}

pub(crate) trait WindowImpl
where
    Self: Sized + self::sealed_window::Sealed,
{
    #[doc(hidden)]
    type Timeout;

    #[doc(hidden)]
    type OnBeforeUnload;

    #[doc(hidden)]
    fn new() -> Result<Self, Error>;

    #[doc(hidden)]
    fn location(&self) -> Result<Location, Error>;

    #[doc(hidden)]
    fn set_timeout(
        &self,
        millis: u32,
        callback: impl Fn() + 'static,
    ) -> Result<Self::Timeout, Error>;

    #[doc(hidden)]
    fn onbeforeunload(&self, callback: impl Fn() + 'static) -> Result<Self::OnBeforeUnload, Error>;
}

pub(crate) mod sealed_web {
    pub trait Sealed {}
}

/// Central trait for web integration.
///
/// Since web integration is currently unstable, this requires multiple
/// different implementations, each time an ecosystem breaking change is
/// released.
///
/// The crate in focus here is `web-sys`, and the corresponding modules provide
/// integrations:
///
/// * [web03] for `web-sys` `0.3.x`.
///
/// [web03]: crate::web03
pub trait WebImpl
where
    Self: 'static + Copy + Sized + self::sealed_web::Sealed,
{
    #[doc(hidden)]
    #[allow(private_bounds)]
    type Window: WindowImpl;

    #[doc(hidden)]
    type Handles;

    #[doc(hidden)]
    #[allow(private_bounds)]
    type Socket: SocketImpl<Handles = Self::Handles>;

    #[doc(hidden)]
    #[allow(private_interfaces)]
    fn handles(shared: &Weak<Shared<Self>>) -> Self::Handles;

    #[doc(hidden)]
    fn random(range: u32) -> u32;
}

/// Construct a new [`ServiceBuilder`] associated with the given [`Connect`]
/// strategy.
pub fn connect<H>(connect: Connect) -> ServiceBuilder<H, EmptyCallback>
where
    H: WebImpl,
{
    ServiceBuilder {
        connect,
        on_error: EmptyCallback,
        close_before_unload: false,
        format: Format::DEFAULT,
        mode: Mode::DEFAULT,
        app: 0,
        _marker: PhantomData,
    }
}

/// The state of the connection.
///
/// A listener for state changes can be set up through for example
/// [`Handle::on_state_change`].
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub enum State {
    /// The connection is open.
    Open,
    /// The connection is closed.
    Closed,
    /// The server states an application version other than the one this
    /// client was built with, see [`ServiceBuilder::app_version`].
    ///
    /// The connection is closed and the service stops reconnecting, since
    /// connecting again reaches the same server. The page is out of date, so
    /// the usual thing to do is to ask the user to reload it, or to reload it
    /// outright. [`Service::open`] tries again, which is only worth doing if
    /// the server might have changed back.
    Incompatible {
        /// The application version the server states.
        server: u32,
        /// The application version this client states.
        client: u32,
    },
}

impl State {
    /// Check if the state is open.
    pub fn is_open(&self) -> bool {
        matches!(self, Self::Open)
    }

    /// Check if the connection was refused because the server states another
    /// application version, see [`State::Incompatible`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::State;
    ///
    /// assert!(State::Incompatible { server: 2, client: 1 }.is_incompatible());
    /// assert!(!State::Closed.is_incompatible());
    /// ```
    pub fn is_incompatible(&self) -> bool {
        matches!(self, Self::Incompatible { .. })
    }
}

/// Error type for the WebSocket service.
///
/// Errors are delivered to request, channel and broadcast callbacks, and to
/// the connection-wide handler set with [`ServiceBuilder::on_error`]. Use the
/// accessors below to tell what failed instead of matching on the text
/// produced by [`Display`], which is meant for humans and may change:
///
/// * [`is_not_connected`] - the request was never sent, since there was no
///   open connection or channel to send it over. It is safe to send it again
///   once the connection is open.
/// * [`is_connection_lost`] - the request was sent, or about to be, but the
///   connection closed before a response arrived. The server may or may not
///   have handled it.
/// * [`is_cancelled`] - the request was replaced by another one before it was
///   answered.
/// * [`as_server_error`] - the server answered with an error, such as one
///   returned by its handler. If the handler failed with a typed error,
///   [`server_error`] decodes it.
/// * [`is_decode`] - something received could not be decoded, such as a
///   response which does not match the expected type.
///
/// Anything else, such as a failure in the browser APIs, only carries a
/// message.
///
/// # Examples
///
/// ```
/// use musli_web::web::Error;
///
/// fn describe(error: &Error) -> String {
///     if error.is_not_connected() {
///         String::from("Not connected, try again later")
///     } else if error.is_connection_lost() {
///         String::from("Connection lost, the request may not have been handled")
///     } else if let Some(message) = error.as_server_error() {
///         format!("The server said: {message}")
///     } else {
///         error.to_string()
///     }
/// }
///
/// let error = Error::message("Something else");
/// assert_eq!(describe(&error), "Something else");
/// ```
///
/// [`Display`]: core::fmt::Display
/// [`is_not_connected`]: Self::is_not_connected
/// [`is_connection_lost`]: Self::is_connection_lost
/// [`is_cancelled`]: Self::is_cancelled
/// [`as_server_error`]: Self::as_server_error
/// [`server_error`]: Self::server_error
/// [`is_decode`]: Self::is_decode
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
}

impl Error {
    #[inline]
    fn new(kind: ErrorKind) -> Self {
        Self { kind }
    }

    /// Check if the error is caused by an empty packet.
    ///
    /// An empty packet is also a [decode error](Self::is_decode).
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::{Error, RawPacket};
    ///
    /// let packet = RawPacket::empty();
    /// let e = packet.decode::<u32>().unwrap_err();
    ///
    /// assert!(e.is_empty_packet());
    /// assert!(e.is_decode());
    /// ```
    #[inline]
    pub fn is_empty_packet(&self) -> bool {
        matches!(self.kind, ErrorKind::EmptyPacket)
    }

    /// Check if the request was never sent, since there was no open
    /// connection or channel to send it over.
    ///
    /// This is the error a request or channel gets when it is sent before the
    /// connection is [open](State::Open), after the [`Service`] has been
    /// dropped, or over a [`Channel`] which is not open. Since the server never
    /// saw the request, it is safe to send it again once the connection is
    /// open, see [`Handle::on_state_change`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::Error;
    ///
    /// let error = Error::message("Something else");
    /// assert!(!error.is_not_connected());
    /// ```
    #[inline]
    pub fn is_not_connected(&self) -> bool {
        matches!(self.kind, ErrorKind::NotConnected(..))
    }

    /// Check if the connection closed before a response to the request
    /// arrived.
    ///
    /// Unlike [`is_not_connected`], the request was sent, or was being sent,
    /// so the server may or may not have handled it. This is the error every
    /// pending request gets when the connection closes or when the
    /// [`Service`] is dropped.
    ///
    /// [`is_not_connected`]: Self::is_not_connected
    #[inline]
    pub fn is_connection_lost(&self) -> bool {
        matches!(self.kind, ErrorKind::ConnectionLost(..))
    }

    /// Check if the request was cancelled before it was answered, since
    /// another request took its place.
    #[inline]
    pub fn is_cancelled(&self) -> bool {
        matches!(self.kind, ErrorKind::Cancelled)
    }

    /// Check if the error is a server error, and if so return the message
    /// reported by the server.
    ///
    /// Server errors are produced by a [`Handler`] which returns an error or
    /// which does not support the request or broadcast being made. The message
    /// is returned as the server sent it, without the `Server error: ` prefix
    /// that [`Display`] adds.
    ///
    /// [`Display`]: core::fmt::Display
    /// [`Handler`]: <https://docs.rs/musli-web/latest/musli_web/ws/trait.Handler.html>
    ///
    /// This is the message of a [typed error](Self::server_error) too.
    #[inline]
    pub fn as_server_error(&self) -> Option<&str> {
        match &self.kind {
            ErrorKind::Server(error) => Some(&error.message),
            _ => None,
        }
    }

    /// Decode the typed error the server answered with.
    ///
    /// A handler which fails with a `ws::TypedError<E>` sends `E` encoded in
    /// the body format of the connection, see [Errors]. This decodes it back
    /// as `T`, which should be the same type as `E` or one which is
    /// compatible with it, typically from an API crate shared with the server.
    ///
    /// Returns `Ok(None)` if this is not a server error, or if it is one which
    /// carries no typed error, such as a handler error which is plain text or
    /// an error the server produced on its own for a request it does not
    /// support. Those still have a message, see [`as_server_error`].
    ///
    /// # Errors
    ///
    /// Errors if the typed error does not decode as `T`. The returned error is
    /// a [decode error](Self::is_decode).
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::{Decode, Encode};
    /// use musli_web::web::Error;
    ///
    /// #[derive(Debug, PartialEq, Encode, Decode)]
    /// enum ServerError {
    ///     NotFound,
    ///     Forbidden,
    /// }
    ///
    /// fn describe(error: &Error) -> String {
    ///     match error.server_error::<ServerError>() {
    ///         Ok(Some(ServerError::NotFound)) => String::from("No such thing"),
    ///         Ok(Some(ServerError::Forbidden)) => String::from("Not allowed"),
    ///         // NB: Not a typed error, or not one we understand.
    ///         Ok(None) | Err(..) => error.to_string(),
    ///     }
    /// }
    ///
    /// let error = Error::message("Something else");
    /// assert_eq!(error.server_error::<ServerError>().unwrap(), None);
    /// assert_eq!(describe(&error), "Something else");
    /// ```
    ///
    /// [Errors]: <https://docs.rs/musli-web/latest/musli_web/ws/index.html#errors>
    /// [`as_server_error`]: Self::as_server_error
    pub fn server_error<'de, T>(&'de self) -> Result<Option<T>>
    where
        T: DecodeBody<'de>,
    {
        let ErrorKind::Server(error) = &self.kind else {
            return Ok(None);
        };

        let Some((format, payload)) = &error.payload else {
            return Ok(None);
        };

        let value = format
            .decode(payload, &mut 0)
            .map_err(Error::decode_error_message)?;

        Ok(Some(value))
    }

    /// Check if the error is caused by something received which could not be
    /// decoded.
    ///
    /// This covers a response or broadcast whose body does not decode as the
    /// requested type, an [empty packet](Self::is_empty_packet), a frame from
    /// the server whose header, error message or format could not be decoded,
    /// and a [typed error](Self::server_error) which does not decode as the
    /// requested type.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// let e = packet.decode::<u32>().unwrap_err();
    ///
    /// assert!(e.is_decode());
    /// ```
    #[inline]
    pub fn is_decode(&self) -> bool {
        matches!(
            self.kind,
            ErrorKind::EmptyPacket
                | ErrorKind::UnknownFormat(..)
                | ErrorKind::DecodeResponseHeader(..)
                | ErrorKind::DecodeErrorMessage(..)
                | ErrorKind::DecodePacket(..)
        )
    }

    /// Format a WebSocket error consisting of a message.
    ///
    /// None of the accessors on [`Error`] match an error constructed this way.
    #[inline]
    pub fn message(message: impl fmt::Display) -> Self {
        Self::new(ErrorKind::Message(message.to_string()))
    }

    #[inline]
    fn server(error: ServerError) -> Self {
        Self::new(ErrorKind::Server(error))
    }

    #[inline]
    pub(crate) fn decode_response_header(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodeResponseHeader(error))
    }

    #[inline]
    pub(crate) fn decode_error_message(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodeErrorMessage(error))
    }

    #[inline]
    pub(crate) fn decode_packet(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodePacket(error))
    }

    #[inline]
    pub(crate) fn encoding_header(error: format::Error) -> Self {
        Self::new(ErrorKind::EncodingHeader(error))
    }

    #[inline]
    pub(crate) fn encoding_body(error: format::Error) -> Self {
        Self::new(ErrorKind::EncodingBody(error))
    }
}

#[derive(Debug)]
enum ErrorKind {
    EmptyPacket,
    /// The request was never sent. Carries the text to display.
    NotConnected(&'static str),
    /// The connection closed while the request was pending. Carries the text
    /// to display.
    ConnectionLost(&'static str),
    Cancelled,
    Message(String),
    Server(ServerError),
    UnknownFormat(u8),
    DecodeResponseHeader(format::Error),
    DecodeErrorMessage(format::Error),
    DecodePacket(format::Error),
    EncodingHeader(format::Error),
    EncodingBody(format::Error),
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::EmptyPacket => write!(f, "Packet is empty"),
            ErrorKind::NotConnected(message) => write!(f, "{message}"),
            ErrorKind::ConnectionLost(message) => write!(f, "{message}"),
            ErrorKind::Cancelled => write!(f, "Request cancelled"),
            ErrorKind::Message(message) => write!(f, "{message}"),
            ErrorKind::Server(error) => write!(f, "Server error: {}", error.message),
            ErrorKind::UnknownFormat(format) => write!(
                f,
                "Server used unknown format id {format} for a message body"
            ),
            ErrorKind::DecodeResponseHeader(..) => {
                write!(f, "Encoding error when decoding response header")
            }
            ErrorKind::DecodeErrorMessage(..) => {
                write!(f, "Encoding error when decoding error response")
            }
            ErrorKind::DecodePacket(..) => write!(f, "Encoding error when decoding packet"),
            ErrorKind::EncodingHeader(..) => write!(f, "Encoding error when encoding header"),
            ErrorKind::EncodingBody(..) => write!(f, "Encoding error when encoding body"),
        }
    }
}

impl core::error::Error for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match &self.kind {
            ErrorKind::DecodeResponseHeader(error) => Some(error),
            ErrorKind::DecodeErrorMessage(error) => Some(error),
            ErrorKind::DecodePacket(error) => Some(error),
            ErrorKind::EncodingHeader(error) => Some(error),
            ErrorKind::EncodingBody(error) => Some(error),
            _ => None,
        }
    }
}

#[cfg(feature = "wasm_bindgen02")]
impl From<wasm_bindgen02::JsValue> for Error {
    #[inline]
    fn from(error: wasm_bindgen02::JsValue) -> Self {
        Self::new(ErrorKind::Message(format!("{error:?}")))
    }
}

/// An error response from the server, see [error
/// responses](crate::api#error-responses).
#[derive(Debug, Clone)]
struct ServerError {
    /// The human readable message.
    message: String,
    /// The typed payload, and the format it is encoded with.
    payload: Option<(Format, Box<[u8]>)>,
}

impl ServerError {
    /// A server error without a payload.
    #[inline]
    fn message(message: &str) -> Self {
        Self {
            message: String::from(message),
            payload: None,
        }
    }
}

type Result<T, E = Error> = core::result::Result<T, E>;

const INITIAL_TIMEOUT: u32 = 250;
const MAX_TIMEOUT: u32 = 4000;

/// How to connect to the WebSocket.
#[derive(Debug)]
enum ConnectKind {
    Location { path: String },
    Url { url: String },
}

/// A specification for how to connect a WebSocket.
pub struct Connect {
    kind: ConnectKind,
}

impl Connect {
    /// Connect to the same location with a custom path.
    ///
    /// Note that any number of `/` prefixes are ignored, the canonical
    /// representation always ignores them and the path is relative to the
    /// current location.
    #[inline]
    pub fn location(path: impl AsRef<str>) -> Self {
        Self {
            kind: ConnectKind::Location {
                path: String::from(path.as_ref()),
            },
        }
    }

    /// Connect to the specified URL.
    #[inline]
    pub fn url(url: String) -> Self {
        Self {
            kind: ConnectKind::Url { url },
        }
    }
}

impl fmt::Debug for Connect {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.kind.fmt(f)
    }
}

/// Generic but shared fields which do not depend on specialization over `H`.
struct Generic {
    state_listeners: RefCell<StateListeners>,
    /// The number of times the connection has opened, see
    /// [`Handle::generation`].
    generation: Cell<u64>,
    requests: RefCell<PendingRequests>,
    broadcasts: RefCell<Broadcasts>,
    buffers: RefCell<Buffers>,
}

/// Shared implementation details for WebSocket implementations.
pub(crate) struct Shared<H>
where
    H: WebImpl,
{
    connect: Connect,
    state: Cell<State>,
    should_be: Cell<State>,
    connecting: Cell<bool>,
    /// The format in effect, as agreed by the [negotiation protocol].
    ///
    /// [negotiation protocol]: crate::api#negotiating-the-format
    format: Cell<Format>,
    /// The format the user asked for, re-negotiated on every reconnect.
    requested: Format,
    /// The mode in effect, as decided by the frame the negotiation was answered
    /// in.
    mode: Cell<Mode>,
    /// The mode the user asked for, re-negotiated on every reconnect.
    requested_mode: Mode,
    /// The application version this client states, or zero for none.
    app: u32,
    handle: Handle<H>,
    pub(crate) on_error: Box<dyn Callback<Error>>,
    window: H::Window,
    handles: H::Handles,
    serial: Cell<u32>,
    defer_broadcasts: RefCell<VecDeque<Weak<dyn Callback<Result<RawPacket>>>>>,
    defer_state_listeners: RefCell<VecDeque<Weak<dyn Callback<State>>>>,
    pub(crate) socket: RefCell<Option<H::Socket>>,
    output: RefCell<Vec<u8>>,
    current_timeout: Cell<u32>,
    reconnect_timeout: RefCell<Option<<H::Window as WindowImpl>::Timeout>>,
    _window_onbeforeunload: Option<<H::Window as WindowImpl>::OnBeforeUnload>,
    g: Rc<Generic>,
}

impl<H> Drop for Shared<H>
where
    H: WebImpl,
{
    fn drop(&mut self) {
        if let Some(s) = self.socket.take() {
            tracing::debug!("Closing connection during drop");

            if let Err(error) = s.close() {
                self.on_error.call(error);
            }
        }

        // We don't need to worry about mutable borrows here, since we only have
        // weak references to Shared and by virtue of this being dropped they
        // are all invalid.
        let state_listeners = mem::take(&mut *self.g.state_listeners.borrow_mut());

        // NB: Listeners are called before the requests are taken, since a
        // listener can cancel a request of its own, such as a channel which
        // was being opened.
        for (_, listener) in state_listeners {
            listener.call(State::Closed);
        }

        let requests = mem::take(&mut *self.g.requests.borrow_mut());

        for (_, p) in requests {
            p.callback.error(Error::new(ErrorKind::ConnectionLost(
                "Websocket service closed",
            )));
        }
    }
}

/// Builder of a service.
pub struct ServiceBuilder<H, E>
where
    H: WebImpl,
{
    connect: Connect,
    on_error: E,
    close_before_unload: bool,
    format: Format,
    mode: Mode,
    app: u32,
    _marker: PhantomData<H>,
}

impl<H, E> ServiceBuilder<H, E>
where
    H: WebImpl,
    E: Callback<Error>,
{
    /// Set the error handler to use for the service.
    pub fn on_error<U>(self, on_error: U) -> ServiceBuilder<H, U>
    where
        U: Callback<Error>,
    {
        ServiceBuilder {
            connect: self.connect,
            on_error,
            close_before_unload: self.close_before_unload,
            format: self.format,
            mode: self.mode,
            app: self.app,
            _marker: self._marker,
        }
    }

    /// Set the [`Format`] to use for message bodies.
    ///
    /// The format is negotiated with the server once the connection is
    /// established, see the [negotiation protocol]. If the server does not
    /// support it the error is reported through [`ServiceBuilder::on_error`]
    /// and the connection falls back to [`Format::DEFAULT`], which can be
    /// observed through [`Handle::format`].
    ///
    /// Defaults to [`Format::DEFAULT`].
    ///
    /// [negotiation protocol]: crate::api#negotiating-the-format
    #[inline]
    pub fn format(mut self, format: Format) -> ServiceBuilder<H, E> {
        self.format = format;
        self
    }

    /// Set the [`Mode`] the socket should run in.
    ///
    /// [`Mode::Text`] makes every frame human readable, so the traffic can be
    /// read straight out of the browser's network inspector. It requires a
    /// [`Format`] which is human readable too, so it is normally combined with
    /// [`Format::Json`]:
    ///
    /// ```
    /// use musli_web::api::{Format, Mode};
    ///
    /// assert!(Mode::Text.accepts(Format::Json));
    /// ```
    ///
    /// Like the format, the mode is settled with the server once the connection
    /// is established, see the [negotiation protocol]. A server which cannot
    /// carry the requested format in the requested mode reports the error
    /// through [`ServiceBuilder::on_error`] and the connection falls back to
    /// [`Mode::DEFAULT`], which can be observed through [`Handle::mode`].
    ///
    /// Defaults to [`Mode::DEFAULT`].
    ///
    /// [negotiation protocol]: crate::api#negotiating-the-format
    #[inline]
    pub fn mode(mut self, mode: Mode) -> ServiceBuilder<H, E> {
        self.mode = mode;
        self
    }

    /// State the version of the application's API this client was built
    /// with.
    ///
    /// This is a version of *your* protocol, the requests and broadcasts
    /// defined with [`api::define!`], as opposed to [`api::VERSION`] which is
    /// the version of the envelope this crate puts around them. Give it the
    /// same constant the server passes to `ws::Connect::app_version`, from a
    /// crate both of them depend on, and bump it whenever the API changes in a
    /// way an older page cannot cope with.
    ///
    /// When the connection is established the server states its version, and
    /// if it is not this one the service reports [`State::Incompatible`]
    /// instead of [`State::Open`], closes the connection and stops
    /// reconnecting. That is how a page which was loaded before the server was
    /// upgraded learns that it has to reload.
    ///
    /// Zero, which is the default, states no version. The check only applies
    /// when both peers state one, so a client or a server which does not opt
    /// in behaves exactly as if this did not exist. See [application
    /// versions].
    ///
    /// [`api::define!`]: crate::api::define
    /// [application versions]: crate::api#application-versions
    ///
    /// # Examples
    ///
    /// Reloading the page once the server says it is out of date:
    ///
    /// ```no_run
    /// use musli_web::web03::prelude::*;
    ///
    /// /// Shared with the server, bumped whenever the API changes.
    /// const APP_VERSION: u32 = 7;
    ///
    /// let service = ws::connect(ws::Connect::location("ws"))
    ///     .app_version(APP_VERSION)
    ///     .build();
    ///
    /// // Keep the listener for as long as the page should reload itself.
    /// let (_, listener) = service.handle().on_state_change(|state: ws::State| {
    ///     // Carries both versions, as `State::Incompatible { server, client }`.
    ///     if state.is_incompatible() {
    ///         reload_page();
    ///     }
    /// });
    ///
    /// /// With `web-sys`, `window().location().reload()`.
    /// fn reload_page() {
    ///     # todo!()
    /// }
    /// # drop(listener);
    /// ```
    #[inline]
    pub fn app_version(mut self, version: u32) -> Self {
        self.app = version;
        self
    }

    /// Install an event handler which will try to close the WebSocket
    /// connection on page unload.
    ///
    /// This is not strictly necessary, but some browsers like Firefox might be
    /// slow to recycle the connection unless it has been explicitly closed.
    #[inline]
    pub fn close_before_unload(mut self) -> Self {
        self.close_before_unload = true;
        self
    }

    /// Build a new service and open it.
    ///
    /// In order to close or open the service again, see [`Service::close`] and
    /// [`Service::open`].
    pub fn build(self) -> Service<H> {
        let window = match H::Window::new() {
            Ok(window) => window,
            Err(error) => {
                panic!("{error}")
            }
        };

        let shared = Rc::<Shared<H>>::new_cyclic(move |shared| {
            let window_onbeforeunload = if self.close_before_unload {
                let shared = shared.clone();

                let result = window.onbeforeunload(move || {
                    tracing::debug!("Trying to close WebSocket connection on page unload");

                    if let Some(shared) = shared.upgrade() {
                        shared.close();
                    }
                });

                match result {
                    Ok(onbeforeunload) => Some(onbeforeunload),
                    Err(error) => {
                        self.on_error.call(Error::message(format_args!(
                            "Failed to set onbeforeunload: {error}"
                        )));
                        None
                    }
                }
            } else {
                None
            };

            Shared {
                connect: self.connect,
                state: Cell::new(State::Closed),
                should_be: Cell::new(State::Closed),
                connecting: Cell::new(false),
                format: Cell::new(self.format),
                requested: self.format,
                mode: Cell::new(self.mode),
                requested_mode: self.mode,
                app: self.app,
                handle: Handle {
                    shared: shared.clone(),
                },
                on_error: Box::new(self.on_error),
                window,
                handles: H::handles(shared),
                serial: Cell::new(0),
                defer_broadcasts: RefCell::new(VecDeque::new()),
                defer_state_listeners: RefCell::new(VecDeque::new()),
                socket: RefCell::new(None),
                output: RefCell::new(Vec::new()),
                current_timeout: Cell::new(INITIAL_TIMEOUT),
                reconnect_timeout: RefCell::new(None),
                _window_onbeforeunload: window_onbeforeunload,
                g: Rc::new(Generic {
                    state_listeners: RefCell::new(Slab::new()),
                    generation: Cell::new(0),
                    broadcasts: RefCell::new(HashMap::new()),
                    requests: RefCell::new(PendingRequests::new()),
                    buffers: RefCell::new(VecDeque::new()),
                }),
            }
        });

        let service = Service { shared };
        service.open();
        service
    }
}

/// The service handle.
///
/// Once dropped this will cause the service to be disconnected and all requests
/// to be cancelled.
pub struct Service<H>
where
    H: WebImpl,
{
    shared: Rc<Shared<H>>,
}

impl<H> Service<H>
where
    H: WebImpl,
{
    /// Attempt to establish a WebSocket connection.
    #[deprecated(since = "0.3.0", note = "Use `open` instead")]
    pub fn connect(&self) {
        self.shared.open()
    }

    /// Open the WebSocket connection.
    ///
    /// Calling this method indicates that the connection should stay open, and
    /// the implementation will attempt to reconnect until [`Service::close`] is
    /// called.
    pub fn open(&self) {
        self.shared.open()
    }

    /// Close the WebSocket connection.
    ///
    /// This is not strictly necessary, but some browsers like Firefox might be
    /// slow to recycle the connection unless it has been explicitly closed.
    ///
    /// It is generally recommended that you call this when `beforeunload` on
    /// window is fired.
    pub fn close(&self) {
        self.shared.close();
    }

    /// Return the handle to the service.
    ///
    /// A [`Handle`] instances does not force the underlying WebSocket to stay
    /// connected, and is invalidated when [`Service`] is destructed.
    pub fn handle(&self) -> &Handle<H> {
        &self.shared.handle
    }
}

impl<H> Clone for Service<H>
where
    H: WebImpl,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            shared: self.shared.clone(),
        }
    }
}

impl<H> Shared<H>
where
    H: WebImpl,
{
    /// Send a client message.
    fn send_client_request<T>(&self, serial: u32, channel: ChannelId, body: &T) -> Result<()>
    where
        T: api::Request,
    {
        let Some(ref socket) = *self.socket.borrow() else {
            return Err(Error::new(ErrorKind::NotConnected(
                "Socket is not connected",
            )));
        };

        let format = self.format.get();
        let mode = self.mode.get();

        let header = api::RequestHeader {
            version: api::VERSION,
            serial,
            id: <T::Endpoint as api::Endpoint>::ID.get(),
            format: format.to_u8(),
            channel,
            app: 0,
        };

        let out = &mut *self.output.borrow_mut();

        format::encode_envelope(mode, &mut *out, &header).map_err(Error::encoding_header)?;
        format
            .encode(&mut *out, body)
            .map_err(Error::encoding_body)?;

        tracing::debug!(
            header.serial,
            ?header.id,
            len = out.len(),
            "Sending request"
        );

        socket.send(mode, out.as_slice())?;

        out.clear();
        out.shrink_to(MAX_CAPACITY);
        Ok(())
    }

    /// Send a client message.
    fn send_connect(&self, serial: u32) -> Result<()> {
        let Some(ref socket) = *self.socket.borrow() else {
            return Err(Error::new(ErrorKind::NotConnected(
                "Socket is not connected",
            )));
        };

        let mode = self.mode.get();

        let header = api::RequestHeader {
            version: api::VERSION,
            serial,
            id: MessageId::CONNECT.get(),
            // NB: Carries no body.
            format: 0,
            channel: ChannelId::NONE,
            app: 0,
        };

        let out = &mut *self.output.borrow_mut();

        format::encode_envelope(mode, &mut *out, &header).map_err(Error::encoding_header)?;

        tracing::debug!(
            header.serial,
            ?header.id,
            len = out.len(),
            "Sending request"
        );

        socket.send(mode, out.as_slice())?;

        out.clear();
        out.shrink_to(MAX_CAPACITY);
        Ok(())
    }

    /// Ask the server to use the requested format for the rest of the
    /// connection.
    fn send_negotiate(self: &Rc<Self>) -> Result<()> {
        let format = self.requested;
        let mode = self.requested_mode;
        let serial = self.serial.get();
        self.serial.set(serial.wrapping_add(1));

        {
            let Some(ref socket) = *self.socket.borrow() else {
                return Err(Error::new(ErrorKind::NotConnected(
                    "Socket is not connected",
                )));
            };

            let header = api::RequestHeader {
                version: api::VERSION,
                serial,
                id: MessageId::NEGOTIATE.get(),
                format: format.to_u8(),
                // NB: Carries no body.
                channel: ChannelId::NONE,
                app: self.app,
            };

            let out = &mut *self.output.borrow_mut();

            // NB: The frame this goes out in is what asks for the mode, so the
            // envelope has to be spelled the same way.
            format::encode_envelope(mode, &mut *out, &header).map_err(Error::encoding_header)?;

            tracing::debug!(?format, ?mode, "Requesting format");

            socket.send(mode, out.as_slice())?;

            out.clear();
            out.shrink_to(MAX_CAPACITY);
        }

        let pending = Pending {
            id: MessageId::NEGOTIATE,
            serial,
            callback: NegotiateCallback(format, mode),
        };

        let existing = self
            .g
            .requests
            .borrow_mut()
            .insert(serial, Box::new(pending));

        if let Some(p) = existing {
            p.callback.error(Error::new(ErrorKind::Cancelled));
        }

        Ok(())
    }

    /// Send a disconnect.
    fn remove_channel(&self, channel: ChannelId) {
        if let Err(error) = self._send_disconnect(channel) {
            self.on_error.call(error);
        }
    }

    fn _send_disconnect(&self, channel: ChannelId) -> Result<()> {
        let Some(ref socket) = *self.socket.borrow() else {
            return Err(Error::new(ErrorKind::NotConnected(
                "Socket is not connected",
            )));
        };

        let mode = self.mode.get();

        let header = api::RequestHeader {
            version: api::VERSION,
            serial: 0,
            id: MessageId::DISCONNECT.get(),
            // NB: Carries no body.
            format: 0,
            channel,
            app: 0,
        };

        let out = &mut *self.output.borrow_mut();

        format::encode_envelope(mode, &mut *out, &header).map_err(Error::encoding_header)?;

        tracing::debug!(
            header.serial,
            ?header.id,
            len = out.len(),
            "Sending request"
        );

        socket.send(mode, out.as_slice())?;

        out.clear();
        out.shrink_to(MAX_CAPACITY);
        Ok(())
    }

    pub(crate) fn next_buffer(self: &Rc<Self>, needed: usize) -> Box<BufData> {
        match self.g.buffers.borrow_mut().pop_front() {
            Some(mut buf) => {
                // NB: Recycled buffers are cleared when they are returned, so
                // every message starts writing from the beginning.
                debug_assert!(buf.data.is_empty());
                buf.data.reserve(needed);
                buf
            }
            None => Box::new(BufData::with_capacity(Rc::downgrade(&self.g), needed)),
        }
    }

    /// Handle a text frame.
    pub(crate) fn text_message(self: &Rc<Self>, text: &str) -> Result<()> {
        let bytes = text.as_bytes();
        let mut buf = self.next_buffer(bytes.len());
        buf.data.extend_from_slice(bytes);
        self.message(Mode::Text, buf)
    }

    /// Resolve the format a message body is encoded with from its envelope.
    fn body_format(header: &api::ResponseHeader) -> Result<Format> {
        let Some(format) = Format::from_u8(header.format) else {
            return Err(Error::new(ErrorKind::UnknownFormat(header.format)));
        };

        Ok(format)
    }

    /// Decode the body of an error response, whose `error` header is `id`.
    ///
    /// An error id which carries no message is reported with `unsupported`.
    fn server_error(
        id: MessageId,
        header: &api::ResponseHeader,
        buf: &[u8],
        mut at: usize,
        unsupported: &str,
    ) -> Result<ServerError> {
        let typed = match id {
            MessageId::ERROR_MESSAGE => false,
            MessageId::TYPED_ERROR_MESSAGE => true,
            _ => return Ok(ServerError::message(unsupported)),
        };

        let format = Self::body_format(header)?;

        let error: api::ErrorMessage<'_> = format
            .decode(buf, &mut at)
            .map_err(Error::decode_error_message)?;

        // NB: The payload is only decoded once the caller says what type it
        // is, see `Error::server_error`.
        let payload = if typed {
            Some((format, Box::from(buf.get(at..).unwrap_or_default())))
        } else {
            None
        };

        Ok(ServerError {
            message: String::from(error.message),
            payload,
        })
    }

    pub(crate) fn message(self: &Rc<Self>, mode: Mode, buf: Box<BufData>) -> Result<()> {
        // Wrap the buffer in a simple shared reference-counted container.
        let buf = BufRc::new(buf);
        let mut at = 0;

        // NB: The frame type is the mode, so a message can always be read
        // regardless of what has been agreed on.
        let header: api::ResponseHeader = match format::decode_envelope(mode, &buf, &mut at) {
            Ok(header) => header,
            // NB: The server speaks a protocol this build does not have, so
            // there is nothing to be gained by carrying on with the session.
            // The connection is dropped rather than negotiated.
            Err(error) if error.unsupported_version().is_some() => {
                self.on_error.call(Error::decode_response_header(error));
                return self.close_and_reconnect();
            }
            Err(error) => return Err(Error::decode_response_header(error)),
        };

        if let Some(broadcast) = MessageId::new(header.broadcast) {
            tracing::debug!(?header, "Got broadcast");

            if broadcast == MessageId::SERVER_HELLO {
                // NB: The connection is not reported as open until the format
                // has been negotiated, so that server-initiated messages are
                // never encoded with a format this client did not agree to.
                tracing::debug!("Server hello, negotiating format");
                self.send_negotiate()?;

                // NB: Checked after negotiating, so that the server hears
                // which version this client states and can tell why it goes
                // away.
                if self.app != 0 && header.app != 0 && header.app != self.app {
                    self.incompatible(header.app);
                }

                return Ok(());
            }

            if !self.defer_broadcasts(broadcast) {
                return Ok(());
            };

            if let Some(id) = MessageId::new(header.error) {
                let error = Self::server_error(id, &header, &buf, at, "Unsupported broadcast")?;

                while let Some(callback) = self.defer_broadcasts.borrow_mut().pop_front() {
                    if let Some(callback) = callback.upgrade() {
                        callback.call(Err(Error::server(error.clone())));
                    }
                }

                return Ok(());
            }

            let format = Self::body_format(&header)?;

            let packet = RawPacket {
                buf: Some(buf.clone()),
                at: Cell::new(at),
                id: broadcast,
                format,
                channel: header.channel,
            };

            while let Some(callback) = self.defer_broadcasts.borrow_mut().pop_front() {
                if let Some(callback) = callback.upgrade() {
                    callback.call(Ok(packet.clone()));
                }
            }
        } else {
            tracing::debug!(?header, "Got response");
            let p = self.g.requests.borrow_mut().remove(&header.serial);

            if let Some(p) = p {
                if let Some(id) = MessageId::new(header.error) {
                    let error =
                        match Self::server_error(id, &header, &buf, at, "Unsupported request") {
                            Ok(error) => error,
                            // NB: Fail the request rather than leave it waiting
                            // for a response which has already arrived.
                            Err(error) if p.callback.as_negotiate().is_none() => {
                                p.callback.error(error);
                                return Ok(());
                            }
                            Err(error) => return Err(error),
                        };

                    if let Some((format, requested)) = p.callback.as_negotiate() {
                        // NB: The server cannot speak the requested format, or
                        // cannot carry it in the requested mode, so fall back to
                        // the defaults rather than leaving the connection
                        // unusable.
                        self.on_error.call(Error::message(format_args!(
                            "Server rejected format `{format}` in `{requested}` mode ({}), falling back to `{}`",
                            error.message,
                            Format::DEFAULT
                        )));

                        self.format.set(Format::DEFAULT);
                        // NB: The frame this arrived in is the mode the server
                        // settled on, so there is nothing to guess at.
                        self.mode.set(mode);
                        self.emit_state_change(State::Open);
                        return Ok(());
                    }

                    p.callback.error(Error::server(error));
                    return Ok(());
                }

                match p.id {
                    MessageId::NEGOTIATE => {
                        let Some((requested, _)) = p.callback.as_negotiate() else {
                            p.callback
                                .error(Error::message("Unexpected negotiate response"));
                            return Ok(());
                        };

                        // NB: Trust the format the server echoed back over the
                        // one that was asked for, so that a server which
                        // downgrades is honored. The mode is read off the frame
                        // for the same reason.
                        let accepted = Format::from_u8(header.format).unwrap_or(requested);
                        tracing::debug!(?accepted, ?mode, "Format negotiated");
                        self.format.set(accepted);
                        self.mode.set(mode);
                        self.emit_state_change(State::Open);
                        return Ok(());
                    }
                    MessageId::CONNECT => {
                        let Some(callback) = &p.callback.as_channel() else {
                            p.callback
                                .error(Error::message("Unexpected channel response"));
                            return Ok(());
                        };

                        callback(Ok(header.channel));
                        return Ok(());
                    }
                    _ => {
                        let Some(callback) = p.callback.as_request() else {
                            p.callback
                                .error(Error::message("Unexpected channel response"));
                            return Ok(());
                        };

                        let format = Self::body_format(&header)?;

                        let packet = RawPacket {
                            id: p.id,
                            buf: Some(buf),
                            at: Cell::new(at),
                            format,
                            channel: header.channel,
                        };

                        callback.call(Ok(packet));
                        return Ok(());
                    }
                }
            }

            // NB: This is normal, it simply indicates that the handler has been
            // closed.
            tracing::trace!(?header.serial, "Got message with unknown serial");
        }

        Ok(())
    }

    fn defer_broadcasts(self: &Rc<Self>, kind: MessageId) -> bool {
        // Note: We need to defer this, since the outcome of calling
        // the broadcast callback might be that the broadcast
        // listener is modified, which could require mutable access
        // to broadcasts.
        let mut defer = self.defer_broadcasts.borrow_mut();

        let broadcasts = self.g.broadcasts.borrow();

        let Some(broadcasts) = broadcasts.get(&kind) else {
            return false;
        };

        for (_, callback) in broadcasts.iter() {
            defer.push_back(Rc::downgrade(callback));
        }

        !defer.is_empty()
    }

    pub(crate) fn close_and_reconnect(self: &Rc<Self>) -> Result<(), Error> {
        tracing::debug!("Closing and reconnecting");

        // We need a weak reference back to shared state to handle the timeout.
        let shared = Rc::downgrade(self);

        if self.state.get() == State::Closed {
            let current_timeout = self.current_timeout.get();

            if current_timeout < MAX_TIMEOUT {
                let fuzz = H::random(50);

                self.current_timeout.set(
                    current_timeout
                        .saturating_mul(2)
                        .saturating_add(fuzz)
                        .min(MAX_TIMEOUT),
                );
            }
        } else {
            self.current_timeout.set(INITIAL_TIMEOUT);
            self.close_once();
        }

        let timeout = self.current_timeout.get();

        tracing::debug!(?timeout, "Setting");

        let timeout = self.window.set_timeout(timeout, move || {
            if let Some(shared) = shared.upgrade() {
                Self::try_once(&shared);
            }
        })?;

        drop(self.reconnect_timeout.borrow_mut().replace(timeout));
        self.connecting.set(false);
        Ok(())
    }

    /// Give up on a server which states application version `server`.
    ///
    /// Connecting again would reach the same server, so this stops
    /// reconnecting until [`Service::open`] is called again.
    fn incompatible(self: &Rc<Self>, server: u32) {
        let client = self.app;
        tracing::debug!(server, client, "Incompatible server");

        self.should_be.set(State::Closed);

        let timeout = self.reconnect_timeout.borrow_mut().take();
        drop(timeout);

        self.current_timeout.set(INITIAL_TIMEOUT);
        self.connecting.set(false);

        // NB: The socket goes first, so that a listener which looks at the
        // service sees it closed.
        if let Some(s) = self.socket.take() {
            if let Err(error) = s.close() {
                self.on_error.call(error);
            }
        }

        self.close_pending();
        self.emit_state_change(State::Incompatible { server, client });
    }

    /// Fail the pending request with the given serial, if it is still pending.
    fn fail_request(&self, serial: u32, error: Error) {
        let p = self.g.requests.borrow_mut().remove(&serial);

        if let Some(p) = p {
            p.callback.error(error);
        }
    }

    /// Close an pending requests with an error, since there is no chance they
    /// will be responded to any more.
    fn close_pending(self: &Rc<Self>) {
        loop {
            let Some(serial) = self.g.requests.borrow().keys().next().copied() else {
                break;
            };

            let p = {
                let mut requests = self.g.requests.borrow_mut();

                let Some(p) = requests.remove(&serial) else {
                    break;
                };

                p
            };

            p.callback
                .error(Error::new(ErrorKind::ConnectionLost("Connection closed")));
        }
    }

    fn emit_state_change(&self, state: State) {
        if self.state.get() == state {
            return;
        }

        self.state.set(state);

        if state == State::Open {
            // NB: Bumped before any listener runs, so that every listener sees
            // the generation of the connection that just opened.
            let generation = self.g.generation.get().wrapping_add(1);
            self.g.generation.set(generation);
        }

        {
            // We need to collect callbacks to avoid the callback recursively
            // borrowing state listeners, which it would if it modifies any
            // existing state listeners.
            let mut defer = self.defer_state_listeners.borrow_mut();

            for (_, callback) in self.g.state_listeners.borrow().iter() {
                defer.push_back(Rc::downgrade(callback));
            }

            if defer.is_empty() {
                return;
            }
        }

        while let Some(callback) = self.defer_state_listeners.borrow_mut().pop_front() {
            if let Some(callback) = callback.upgrade() {
                callback.call(state);
            }
        }
    }

    #[inline]
    fn open(self: &Rc<Self>) {
        self.should_be.set(State::Open);
        self.try_once();
    }

    fn close(self: &Rc<Self>) {
        self.should_be.set(State::Closed);

        // NB: A pending reconnect would otherwise only be stopped by
        // `should_be` once it fires, and would keep the timer alive until then.
        let timeout = self.reconnect_timeout.borrow_mut().take();
        drop(timeout);

        // NB: The next `open` starts over rather than inheriting the back-off
        // of the connection which was closed on purpose.
        self.current_timeout.set(INITIAL_TIMEOUT);
        self.close_once();
    }

    fn try_once(self: &Rc<Self>) {
        if self.should_be.get() == State::Open && !self.connecting.get() {
            tracing::debug!("Trying to open connection");
            self.connect_once();
        }
    }

    fn close_once(self: &Rc<Self>) {
        self.connecting.set(false);
        self.emit_state_change(State::Closed);

        if let Some(s) = self.socket.take() {
            tracing::debug!("Closing old socket once");

            if let Err(error) = s.close() {
                self.on_error.call(error);
            }
        }

        self.close_pending();
    }

    fn connect_once(self: &Rc<Self>) {
        self.connecting.set(true);

        // NB: A failed attempt leaves no socket behind whose events could ever
        // reset `connecting`, so it has to be reset here or `open` would never
        // try again.
        if let Err(error) = self.try_connect() {
            self.on_error.call(error);
            self.should_be.set(State::Closed);
            self.connecting.set(false);
        }
    }

    fn try_connect(self: &Rc<Self>) -> Result<()> {
        let url = match &self.connect.kind {
            ConnectKind::Location { path } => {
                let location = match WindowImpl::location(&self.window) {
                    Ok(location) => location,
                    Err(e) => {
                        return Err(Error::message(format_args!("Could not get location: {e}")));
                    }
                };

                let Location {
                    protocol,
                    host,
                    port,
                } = location;

                let protocol = match protocol.as_str() {
                    "https:" => "wss:",
                    "http:" => "ws:",
                    other => {
                        return Err(Error::message(format_args!(
                            "Unsupported protocol `{other}` for same host connection"
                        )));
                    }
                };

                let path = ForcePrefix(path, '/');
                format!("{protocol}//{host}:{port}{path}")
            }
            ConnectKind::Url { url } => url.clone(),
        };

        // We explicitly want to close and dispose of the old socket first.
        if let Some(s) = self.socket.borrow_mut().take() {
            tracing::debug!("Closing old socket");

            if let Err(error) = s.close() {
                self.on_error.call(error);
            }
        }

        let ws = SocketImpl::new(&url, &self.handles)?;
        *self.socket.borrow_mut() = Some(ws);
        Ok(())
    }
}

/// Trait governing how callbacks are called.
pub trait Callback<I>
where
    Self: 'static,
{
    /// Call the callback.
    fn call(&self, input: I);
}

impl<I> Callback<I> for EmptyCallback {
    #[inline]
    fn call(&self, _: I) {}
}

impl<F, I> Callback<I> for F
where
    F: 'static + Fn(I),
{
    #[inline]
    fn call(&self, input: I) {
        self(input)
    }
}

/// A builder for a [`Channel`], see [`Handle::channel`].
///
/// Set the callback to tell about the channel opening and closing with
/// [`ChannelBuilder::on_change`], and open the channel with
/// [`ChannelBuilder::open`].
pub struct ChannelBuilder<'a, H, C>
where
    H: WebImpl,
{
    shared: &'a Weak<Shared<H>>,
    callback: C,
}

impl<'a, H, C> ChannelBuilder<'a, H, C>
where
    H: WebImpl,
{
    /// Set the callback which is told about the channel opening and closing.
    ///
    /// The callback is called with:
    ///
    /// * [`ChannelEvent::Opened`] every time the channel has been opened,
    ///   whether for the first time or again after a reconnect. This is the
    ///   point at which to send the requests which need the channel.
    /// * [`ChannelEvent::Closed`] when an open channel has been lost with the
    ///   connection.
    /// * [`ChannelEvent::Failed`] when the server could not open the channel.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloRequest<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloResponse<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Hello;
    ///
    ///         impl Endpoint for Hello {
    ///             impl<'de> Request for HelloRequest<'de>;
    ///             type Response<'de> = HelloResponse<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     OnHello(Result<ws::Packet<api::Hello>, ws::Error>),
    ///     Channel(ws::ChannelEvent),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     message: String,
    ///     _hello: ws::Request,
    ///     channel: ws::Channel,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let channel = ctx.props().ws
    ///             .channel()
    ///             .on_change(ctx.link().callback(Msg::Channel))
    ///             .open();
    ///
    ///         Self {
    ///             message: String::from("No Message :("),
    ///             _hello: ws::Request::new(),
    ///             channel,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::OnHello(Err(error)) => {
    ///                 tracing::error!("Request error: {:?}", error);
    ///                 false
    ///             }
    ///             Msg::OnHello(Ok(packet)) => {
    ///                 if let Ok(response) = packet.decode() {
    ///                     self.message = response.message.to_owned();
    ///                 }
    ///
    ///                 true
    ///             }
    ///             Msg::Channel(ws::ChannelEvent::Opened(..)) => {
    ///                 self._hello = self.channel
    ///                     .request()
    ///                     .body(api::HelloRequest { message: "Hello!"})
    ///                     .on_packet(ctx.link().callback(Msg::OnHello))
    ///                     .send();
    ///
    ///                 true
    ///             }
    ///             Msg::Channel(ws::ChannelEvent::Failed(error)) => {
    ///                 tracing::error!("Channel error: {error}");
    ///                 true
    ///             }
    ///             Msg::Channel(..) => true,
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Message: {}", self.message)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn on_change<U>(self, callback: U) -> ChannelBuilder<'a, H, U>
    where
        U: Callback<ChannelEvent>,
    {
        ChannelBuilder {
            shared: self.shared,
            callback,
        }
    }
}

impl<'a, H, C> ChannelBuilder<'a, H, C>
where
    C: Callback<ChannelEvent>,
    H: WebImpl,
{
    /// Open the channel.
    ///
    /// The channel is opened straight away if the connection is open, and
    /// otherwise as soon as it opens. After that it is opened again every time
    /// the connection reopens, until the returned [`Channel`] and every clone
    /// of it has been dropped.
    pub fn open(self) -> Channel<H> {
        let inner = Rc::new(ChannelInner {
            handle: Handle {
                shared: self.shared.clone(),
            },
            id: Cell::new(ChannelId::NONE),
            generation: Cell::new(0),
            on_change: Box::new(self.callback),
            queue: RefCell::new(VecDeque::new()),
            connect: RefCell::new(Request::new()),
            state: RefCell::new(StateListener::new()),
        });

        let (state, listener) = inner.handle.on_state_change({
            // NB: Weak, since the listener is owned by the channel.
            let inner = Rc::downgrade(&inner);

            move |state: State| {
                if let Some(inner) = inner.upgrade() {
                    inner.on_state(state);
                }
            }
        });

        *inner.state.borrow_mut() = listener;

        if state.is_open() {
            inner.connect();
        }

        Channel { inner }
    }
}

/// Ask the server for a new channel over the current connection.
///
/// The callback is called with the id the server allocated, or with the error
/// which prevented it.
fn connect_channel<H>(
    shared: &Weak<Shared<H>>,
    callback: impl Fn(Result<ChannelId, Error>) + 'static,
) -> Request
where
    H: WebImpl,
{
    struct RequestCallbackImpl<C>(C);

    impl<C> RequestCallback for RequestCallbackImpl<C>
    where
        C: Fn(Result<ChannelId, Error>) + 'static,
    {
        #[inline]
        fn as_channel(&self) -> Option<&(dyn Fn(Result<ChannelId, Error>) + 'static)> {
            Some(&self.0)
        }

        #[inline]
        fn error(&self, error: Error) {
            (self.0)(Err(error));
        }
    }

    let Some(shared) = shared.upgrade() else {
        callback(Err(Error::new(ErrorKind::NotConnected(
            "WebSocket service is down",
        ))));
        return Request::new();
    };

    if shared.state.get() != State::Open {
        callback(Err(Error::new(ErrorKind::NotConnected(
            "WebSocket is not connected",
        ))));
        return Request::new();
    }

    let serial = shared.serial.get();
    shared.serial.set(serial.wrapping_add(1));

    let pending = Pending {
        id: MessageId::CONNECT,
        serial,
        callback: RequestCallbackImpl(callback),
    };

    let existing = shared
        .g
        .requests
        .borrow_mut()
        .insert(serial, Box::new(pending));

    if let Some(p) = existing {
        p.callback.error(Error::new(ErrorKind::Cancelled));
    }

    if let Err(error) = shared.send_connect(serial) {
        // NB: The request is registered before it is sent, since sending
        // can observe synchronously that the peer has gone away and fail
        // every pending request before it returns. If that did not already
        // fail this request, it is failed here.
        shared.fail_request(serial, error);
        return Request::new();
    }

    Request {
        serial,
        g: Rc::downgrade(&shared.g),
    }
}

/// A request builder .
///
/// Associate the callback to be used by using either
/// [`RequestBuilder::on_packet`] or [`RequestBuilder::on_raw_packet`] depending
/// on your needs.
///
/// Send the request with [`RequestBuilder::send`].
pub struct RequestBuilder<'a, H, B, C>
where
    H: WebImpl,
{
    shared: &'a Weak<Shared<H>>,
    channel: Option<ChannelId>,
    body: B,
    callback: C,
}

impl<'a, H, B, C> RequestBuilder<'a, H, B, C>
where
    H: WebImpl,
{
    /// Set the body of the request.
    #[inline]
    pub fn body<U>(self, body: U) -> RequestBuilder<'a, H, U, C>
    where
        U: api::Request,
    {
        RequestBuilder {
            shared: self.shared,
            channel: self.channel,
            body,
            callback: self.callback,
        }
    }

    /// Handle the response using the specified callback.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloRequest<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloResponse<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Hello;
    ///
    ///         impl Endpoint for Hello {
    ///             impl<'de> Request for HelloRequest<'de>;
    ///             type Response<'de> = HelloResponse<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     OnHello(Result<ws::Packet<api::Hello>, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     message: String,
    ///     _hello: ws::Request,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let hello = ctx.props().ws
    ///             .request()
    ///             .body(api::HelloRequest { message: "Hello!"})
    ///             .on_packet(ctx.link().callback(Msg::OnHello))
    ///             .send();
    ///
    ///         Self {
    ///             message: String::from("No Message :("),
    ///             _hello: hello,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::OnHello(Err(error)) => {
    ///                 tracing::error!("Request error: {:?}", error);
    ///                 false
    ///             }
    ///             Msg::OnHello(Ok(packet)) => {
    ///                 if let Ok(response) = packet.decode() {
    ///                     self.message = response.message.to_owned();
    ///                 }
    ///
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Message: {}", self.message)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn on_packet<E>(
        self,
        callback: impl Callback<Result<Packet<E>>>,
    ) -> RequestBuilder<'a, H, B, impl Callback<Result<RawPacket>>>
    where
        E: api::Endpoint,
    {
        self.on_raw_packet(move |result: Result<RawPacket>| match result {
            Ok(ok) => callback.call(Ok(Packet::new(ok))),
            Err(err) => callback.call(Err(err)),
        })
    }

    /// Handle the response using the specified callback.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloRequest<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloResponse<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Hello;
    ///
    ///         impl Endpoint for Hello {
    ///             impl<'de> Request for HelloRequest<'de>;
    ///             type Response<'de> = HelloResponse<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     OnHello(Result<ws::RawPacket, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     message: String,
    ///     _hello: ws::Request,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let link = ctx.link().clone();
    ///
    ///         let hello = ctx.props().ws
    ///             .request()
    ///             .body(api::HelloRequest { message: "Hello!"})
    ///             .on_raw_packet(move |packet| link.send_message(Msg::OnHello(packet)))
    ///             .send();
    ///
    ///         Self {
    ///             message: String::from("No Message :("),
    ///             _hello: hello,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::OnHello(Err(error)) => {
    ///                 tracing::error!("Request error: {:?}", error);
    ///                 false
    ///             }
    ///             Msg::OnHello(Ok(packet)) => {
    ///                 if let Ok(response) = packet.decode::<api::HelloResponse>() {
    ///                     self.message = response.message.to_owned();
    ///                 }
    ///
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Message: {}", self.message)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn on_raw_packet<U>(self, callback: U) -> RequestBuilder<'a, H, B, U>
    where
        U: Callback<Result<RawPacket, Error>>,
    {
        RequestBuilder {
            shared: self.shared,
            channel: self.channel,
            body: self.body,
            callback,
        }
    }
}

impl<'a, H, B, C> RequestBuilder<'a, H, B, C>
where
    B: api::Request,
    C: Callback<Result<RawPacket>>,
    H: WebImpl,
{
    /// Send the request.
    ///
    /// This requires that a body has been set using [`RequestBuilder::body`].
    pub fn send(self) -> Request {
        struct RequestCallbackImpl<C>(C);

        impl<C> RequestCallback for RequestCallbackImpl<C>
        where
            C: Callback<Result<RawPacket>>,
        {
            #[inline]
            fn as_request(&self) -> Option<&(dyn Callback<Result<RawPacket>> + 'static)> {
                Some(&self.0)
            }

            #[inline]
            fn error(&self, error: Error) {
                self.0.call(Err(error));
            }
        }

        let Some(shared) = self.shared.upgrade() else {
            self.callback.call(Err(Error::new(ErrorKind::NotConnected(
                "WebSocket service is down",
            ))));
            return Request::new();
        };

        if shared.state.get() != State::Open {
            self.callback.call(Err(Error::new(ErrorKind::NotConnected(
                "WebSocket is not connected",
            ))));
            return Request::new();
        }

        let Some(channel) = self.channel else {
            self.callback.call(Err(Error::new(ErrorKind::NotConnected(
                "WebSocket request over closed channel",
            ))));
            return Request::new();
        };

        let serial = shared.serial.get();
        shared.serial.set(serial.wrapping_add(1));

        let pending = Pending {
            id: <B::Endpoint as api::Endpoint>::ID,
            serial,
            callback: RequestCallbackImpl(self.callback),
        };

        let existing = shared
            .g
            .requests
            .borrow_mut()
            .insert(serial, Box::new(pending));

        if let Some(p) = existing {
            p.callback.error(Error::new(ErrorKind::Cancelled));
        }

        if let Err(error) = shared.send_client_request(serial, channel, &self.body) {
            // NB: The request is registered before it is sent, since sending
            // can observe synchronously that the peer has gone away and fail
            // every pending request before it returns. If that did not already
            // fail this request, it is failed here.
            shared.fail_request(serial, error);
            return Request::new();
        }

        Request {
            serial,
            g: Rc::downgrade(&shared.g),
        }
    }
}

/// The handle for a pending request.
///
/// Dropping or [`clear()`] this handle will cancel the request.
///
/// [`clear()`]: Self::clear
pub struct Request {
    serial: u32,
    g: Weak<Generic>,
}

impl Request {
    /// An empty request handler.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let mut request = ws::Request::new();
    /// assert_eq!(request.is_pending(), false);
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Self {
            serial: 0,
            g: Weak::new(),
        }
    }

    /// Clear the request handle without dropping it, cancelling any pending
    /// requests.
    pub fn clear(&mut self) {
        let removed = {
            let serial = mem::take(&mut self.serial);

            let Some(g) = self.g.upgrade() else {
                return;
            };

            self.g = Weak::new();

            let Some(p) = g.requests.borrow_mut().remove(&serial) else {
                return;
            };

            p
        };

        drop(removed);
    }

    /// Indicates if a request is pending.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let mut request = ws::Request::new();
    /// assert_eq!(request.is_pending(), false);
    /// ```
    #[inline]
    pub fn is_pending(&self) -> bool {
        let Some(g) = self.g.upgrade() else {
            return false;
        };

        g.requests.borrow().contains_key(&self.serial)
    }
}

impl Default for Request {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Request {
    #[inline]
    fn drop(&mut self) {
        self.clear();
    }
}

/// A request in flight which resolves to its decoded response, see
/// [`Handle::call`].
///
/// Dropping it cancels the request, the same way as dropping a [`Request`]
/// does.
#[must_use = "Futures do nothing unless polled, and dropping this cancels the request"]
pub struct Call<T> {
    slot: Rc<CallSlot>,
    request: Request,
    _marker: PhantomData<fn() -> T>,
}

/// Where the callback of a [`Call`] leaves the outcome of the request.
#[derive(Default)]
struct CallSlot {
    result: Cell<Option<Result<RawPacket>>>,
    waker: Cell<Option<Waker>>,
}

impl<T> Call<T> {
    /// Send a request through `builder`, keeping the outcome for the
    /// returned future.
    fn send<H, B>(builder: RequestBuilder<'_, H, B, EmptyCallback>) -> Self
    where
        H: WebImpl,
        B: api::Request,
    {
        let slot = Rc::new(CallSlot::default());

        // NB: The callback can be called before `send` returns, such as when
        // the request is not connected. The slot then already has the outcome
        // when the future is first polled.
        let request = builder
            .on_raw_packet({
                let slot = slot.clone();

                move |result: Result<RawPacket>| {
                    slot.result.set(Some(result));

                    if let Some(waker) = slot.waker.take() {
                        waker.wake();
                    }
                }
            })
            .send();

        Self {
            slot,
            request,
            _marker: PhantomData,
        }
    }

    /// Indicates if the request is still waiting for its response.
    ///
    /// Once this is `false`, polling the future no longer has to wait.
    #[inline]
    pub fn is_pending(&self) -> bool {
        self.request.is_pending()
    }
}

impl<T> Future for Call<T>
where
    for<'de> T: DecodeBody<'de>,
{
    type Output = Result<T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();

        let Some(result) = this.slot.result.take() else {
            this.slot.waker.set(Some(cx.waker().clone()));
            return Poll::Pending;
        };

        Poll::Ready(result.and_then(|packet| packet.decode()))
    }
}

impl<T> fmt::Debug for Call<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Call")
            .field("type", &any::type_name::<T>())
            .field("is_pending", &self.is_pending())
            .finish()
    }
}

/// A set of pending requests, kept alive until each completes.
///
/// Dropping a [`Request`] cancels it, so a component with several requests
/// in flight at once has to keep every one of them somewhere. Push each one
/// sent into a `Requests` with [`Requests::push`]. A request stays pending
/// until it completes in any way, by its response, an error, or the
/// connection being lost, and the set forgets it once it has.
///
/// Every request still pending is cancelled when the set is dropped or
/// [`cleared`], so a component which keeps a set cancels what it sent once
/// it goes away.
///
/// To keep at most one request for each of a number of things, such as one
/// fetch per row, use [`KeyedRequests`] instead.
///
/// [`cleared`]: Requests::clear
///
/// # Examples
///
/// ```
/// # extern crate yew023 as yew;
/// use yew::prelude::*;
/// use musli_web::web03::prelude::*;
///
/// mod api {
///     use musli::{Decode, Encode};
///     use musli_web::api;
///
///     #[derive(Encode, Decode)]
///     pub struct SaveRequest<'de> {
///         pub text: &'de str,
///     }
///
///     api::define! {
///         pub type Save;
///
///         impl Endpoint for Save {
///             impl<'de> Request for SaveRequest<'de>;
///             type Response<'de> = ();
///         }
///     }
/// }
///
/// enum Msg {
///     Save(String),
///     Saved(Result<ws::Packet<api::Save>, ws::Error>),
/// }
///
/// #[derive(Properties, PartialEq)]
/// struct Props {
///     ws: ws::Handle,
/// }
///
/// struct Notes {
///     // Every save sent which has not completed yet.
///     saves: ws::Requests,
/// }
///
/// impl Component for Notes {
///     type Message = Msg;
///     type Properties = Props;
///
///     fn create(_: &Context<Self>) -> Self {
///         Self {
///             saves: ws::Requests::new(),
///         }
///     }
///
///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
///         match msg {
///             Msg::Save(text) => {
///                 // Saving again does not cancel an earlier save.
///                 self.saves.push(
///                     ctx.props()
///                         .ws
///                         .request()
///                         .body(api::SaveRequest { text: &text })
///                         .on_packet(ctx.link().callback(Msg::Saved))
///                         .send(),
///                 );
///
///                 true
///             }
///             Msg::Saved(result) => {
///                 if let Err(error) = result {
///                     tracing::error!("Save failed: {error}");
///                 }
///
///                 true
///             }
///         }
///     }
///
///     fn view(&self, ctx: &Context<Self>) -> Html {
///         let onclick = ctx.link().callback(|_: MouseEvent| Msg::Save(String::from("Hello")));
///
///         html! {
///             <>
///                 <button {onclick}>{"Save"}</button>
///                 if !self.saves.is_empty() {
///                     <p>{format!("Saving {}...", self.saves.len())}</p>
///                 }
///             </>
///         }
///     }
/// }
/// ```
#[derive(Default)]
pub struct Requests {
    requests: Vec<Request>,
}

impl Requests {
    /// Construct an empty set of requests.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let requests = ws::Requests::new();
    /// assert!(requests.is_empty());
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Self {
            requests: Vec::new(),
        }
    }

    /// Keep `request` until it completes.
    ///
    /// A request which is not pending, such as one which could not be sent,
    /// is dropped straight away.
    pub fn push(&mut self, request: Request) {
        if !request.is_pending() {
            return;
        }

        // NB: Completed requests are only forgotten when the set would
        // otherwise have to grow, which keeps pushing amortized constant time
        // while holding at most twice as many requests as were ever pending
        // at once.
        if self.requests.len() == self.requests.capacity() {
            self.requests.retain(Request::is_pending);
        }

        self.requests.push(request);
    }

    /// The number of requests which are still pending.
    pub fn len(&self) -> usize {
        self.requests.iter().filter(|r| r.is_pending()).count()
    }

    /// Whether no request is pending.
    pub fn is_empty(&self) -> bool {
        !self.requests.iter().any(Request::is_pending)
    }

    /// Cancel every pending request.
    pub fn clear(&mut self) {
        let requests = mem::take(&mut self.requests);
        // NB: Dropped once the set is empty, since cancelling a request drops
        // its callback.
        drop(requests);
    }
}

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

impl Extend<Request> for Requests {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = Request>,
    {
        for request in iter {
            self.push(request);
        }
    }
}

/// A set of pending requests with at most one for each key, kept alive until
/// each completes.
///
/// This is like [`Requests`], except that each request is stored under a key
/// with [`KeyedRequests::insert`]. Storing a request under a key which already
/// has one cancels the request stored before it, so that what is fetched for
/// a key is always the latest. Any number of keys can have a request in
/// flight at once, and a key is forgotten once its request completes.
///
/// Every request still pending is cancelled when the set is dropped or
/// [`cleared`].
///
/// [`cleared`]: KeyedRequests::clear
///
/// # Examples
///
/// ```
/// # extern crate yew023 as yew;
/// use yew::prelude::*;
/// use musli_web::web03::prelude::*;
///
/// mod api {
///     use musli::{Decode, Encode};
///     use musli_web::api;
///
///     #[derive(Encode, Decode)]
///     pub struct RenameRequest<'de> {
///         pub id: u32,
///         pub name: &'de str,
///     }
///
///     api::define! {
///         pub type Rename;
///
///         impl Endpoint for Rename {
///             impl<'de> Request for RenameRequest<'de>;
///             type Response<'de> = ();
///         }
///     }
/// }
///
/// enum Msg {
///     Rename(u32, String),
///     Renamed(Result<ws::Packet<api::Rename>, ws::Error>),
/// }
///
/// #[derive(Properties, PartialEq)]
/// struct Props {
///     ws: ws::Handle,
///     rows: Vec<u32>,
/// }
///
/// struct Rows {
///     // At most one rename in flight for each row.
///     renames: ws::KeyedRequests<u32>,
/// }
///
/// impl Component for Rows {
///     type Message = Msg;
///     type Properties = Props;
///
///     fn create(_: &Context<Self>) -> Self {
///         Self {
///             renames: ws::KeyedRequests::new(),
///         }
///     }
///
///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
///         match msg {
///             Msg::Rename(id, name) => {
///                 // Renaming a row again cancels its earlier rename, but
///                 // leaves the renames of other rows alone.
///                 self.renames.insert(
///                     id,
///                     ctx.props()
///                         .ws
///                         .request()
///                         .body(api::RenameRequest { id, name: &name })
///                         .on_packet(ctx.link().callback(Msg::Renamed))
///                         .send(),
///                 );
///
///                 true
///             }
///             Msg::Renamed(_) => true,
///         }
///     }
///
///     fn view(&self, ctx: &Context<Self>) -> Html {
///         html! {
///             {for ctx.props().rows.iter().copied().map(|id| {
///                 let onclick = ctx.link().callback(move |_: MouseEvent| {
///                     Msg::Rename(id, format!("Row {id}"))
///                 });
///
///                 let label = if self.renames.is_pending(&id) {
///                     String::from("Renaming...")
///                 } else {
///                     format!("Rename #{id}")
///                 };
///
///                 html!(<button {onclick}>{label}</button>)
///             })}
///         }
///     }
/// }
/// ```
pub struct KeyedRequests<K> {
    requests: HashMap<K, Request>,
}

impl<K> KeyedRequests<K> {
    /// Construct an empty set of requests.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let requests = ws::KeyedRequests::<u32>::new();
    /// assert!(requests.is_empty());
    /// ```
    #[inline]
    pub fn new() -> Self {
        Self {
            requests: HashMap::new(),
        }
    }

    /// The number of keys whose request is still pending.
    pub fn len(&self) -> usize {
        self.requests.values().filter(|r| r.is_pending()).count()
    }

    /// Whether no request is pending.
    pub fn is_empty(&self) -> bool {
        !self.requests.values().any(Request::is_pending)
    }

    /// Iterate over the keys whose request is still pending, in no
    /// particular order.
    pub fn keys(&self) -> impl Iterator<Item = &K> {
        self.requests
            .iter()
            .filter(|(_, r)| r.is_pending())
            .map(|(k, _)| k)
    }

    /// Cancel every pending request.
    pub fn clear(&mut self) {
        let requests = mem::take(&mut self.requests);
        // NB: Dropped once the set is empty, since cancelling a request drops
        // its callback.
        drop(requests);
    }
}

impl<K> KeyedRequests<K>
where
    K: Eq + Hash,
{
    /// Keep `request` under `key` until it completes, cancelling the request
    /// stored under `key` before it.
    ///
    /// A request which is not pending, such as one which could not be sent,
    /// is dropped straight away, but still cancels the one before it.
    pub fn insert(&mut self, key: K, request: Request) {
        if !request.is_pending() {
            let old = self.requests.remove(&key);
            drop(old);
            return;
        }

        // NB: Completed requests are only forgotten when the set would
        // otherwise have to grow, see `Requests::push`.
        if self.requests.len() == self.requests.capacity() {
            self.requests.retain(|_, r| r.is_pending());
        }

        let old = self.requests.insert(key, request);
        drop(old);
    }

    /// Cancel the request stored under `key`, returning whether it was still
    /// pending.
    pub fn remove<Q>(&mut self, key: &Q) -> bool
    where
        K: core::borrow::Borrow<Q>,
        Q: ?Sized + Eq + Hash,
    {
        let Some(request) = self.requests.remove(key) else {
            return false;
        };

        let pending = request.is_pending();
        drop(request);
        pending
    }

    /// Whether the request stored under `key` is still pending.
    pub fn is_pending<Q>(&self, key: &Q) -> bool
    where
        K: core::borrow::Borrow<Q>,
        Q: ?Sized + Eq + Hash,
    {
        self.requests.get(key).is_some_and(Request::is_pending)
    }
}

impl<K> Default for KeyedRequests<K> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<K> fmt::Debug for KeyedRequests<K>
where
    K: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.keys()).finish()
    }
}

/// The handle for a pending request.
///
/// Dropping or calling [`clear()`] on this handle remove the listener.
///
/// [`clear()`]: Self::clear
pub struct Listener {
    kind: Option<MessageId>,
    index: usize,
    g: Weak<Generic>,
}

impl Listener {
    /// Construct an empty listener.
    #[inline]
    pub const fn new() -> Self {
        Self {
            kind: None,
            index: 0,
            g: Weak::new(),
        }
    }

    /// Build up an empty listener with the specified kind.
    #[inline]
    pub(crate) const fn empty_with_kind(kind: MessageId) -> Self {
        Self {
            kind: Some(kind),
            index: 0,
            g: Weak::new(),
        }
    }

    /// Clear the listener without dropping it.
    ///
    /// This will remove the associated broadcast listener from being notified.
    pub fn clear(&mut self) {
        // Gather values here to drop them outside of the upgrade block.
        let removed;
        let removed_value;

        {
            let Some(g) = self.g.upgrade() else {
                return;
            };

            self.g = Weak::new();
            let index = mem::take(&mut self.index);

            let Some(kind) = self.kind.take() else {
                return;
            };

            let mut broadcasts = g.broadcasts.borrow_mut();

            let Entry::Occupied(mut e) = broadcasts.entry(kind) else {
                return;
            };

            removed = e.get_mut().try_remove(index);

            if e.get().is_empty() {
                removed_value = Some(e.remove());
            } else {
                removed_value = None;
            }
        }

        // Drop here, to avoid invoking any destructors which might borrow
        // shared mutably earlier.
        drop(removed);
        drop(removed_value);
    }
}

impl Default for Listener {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Listener {
    #[inline]
    fn drop(&mut self) {
        self.clear();
    }
}

/// The handle for state change listening.
///
/// Dropping or calling [`clear()`] on this handle will remove the associated
/// callback from being notified.
///
/// [`clear()`]: Self::clear
pub struct StateListener {
    index: usize,
    g: Weak<Generic>,
}

impl StateListener {
    /// Construct an empty state listener.
    #[inline]
    pub const fn new() -> Self {
        Self {
            index: 0,
            g: Weak::new(),
        }
    }

    /// Clear the state listener without dropping it.
    ///
    /// This will remove the associated callback from being notified.
    pub fn clear(&mut self) {
        let removed = {
            let Some(g) = self.g.upgrade() else {
                return;
            };

            self.g = Weak::new();

            g.state_listeners.borrow_mut().try_remove(self.index)
        };

        drop(removed);
    }
}

impl Default for StateListener {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for StateListener {
    #[inline]
    fn drop(&mut self) {
        self.clear();
    }
}

pub(crate) struct BufData {
    /// Buffer being used.
    pub(crate) data: Vec<u8>,
    /// Number of strong references to this buffer.
    strong: Cell<usize>,
    /// Reference to shared state where the buffer will be recycled to.
    g: Weak<Generic>,
}

impl BufData {
    fn with_capacity(g: Weak<Generic>, capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            strong: Cell::new(0),
            g,
        }
    }

    unsafe fn dec(ptr: NonNull<BufData>) {
        unsafe {
            let count = ptr.as_ref().strong.get().wrapping_sub(1);
            ptr.as_ref().strong.set(count);

            if count > 0 {
                return;
            }

            let mut buf = Box::from_raw(ptr.as_ptr());

            // Try to recycle the buffer if shared is available, else let it be
            // dropped and free here.
            let Some(g) = buf.as_ref().g.upgrade() else {
                return;
            };

            let mut buffers = g.buffers.borrow_mut();

            // NB: The next message is written from the start of the buffer, so
            // the contents of this one must not linger.
            buf.data.clear();

            // We size our buffers to some max capacity to avod overuse in case
            // we infrequently need to handle some massive message. If we don't
            // shrink the allocation, then memory use can run away over time.
            buf.data.shrink_to(MAX_CAPACITY);

            buffers.push_back(buf);
        }
    }

    unsafe fn inc(ptr: NonNull<BufData>) {
        unsafe {
            let count = ptr.as_ref().strong.get().wrapping_add(1);

            if count == 0 {
                std::process::abort();
            }

            ptr.as_ref().strong.set(count);
        }
    }
}

/// A shared buffer of data that is recycled when dropped.
struct BufRc {
    data: NonNull<BufData>,
}

impl BufRc {
    fn new(data: Box<BufData>) -> Self {
        let data = NonNull::from(Box::leak(data));

        unsafe {
            BufData::inc(data);
        }

        Self { data }
    }
}

impl Deref for BufRc {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe { &(*self.data.as_ptr()).data }
    }
}

impl Clone for BufRc {
    fn clone(&self) -> Self {
        unsafe {
            BufData::inc(self.data);
        }

        Self { data: self.data }
    }
}

impl Drop for BufRc {
    fn drop(&mut self) {
        unsafe {
            BufData::dec(self.data);
        }
    }
}

/// A raw packet of data.
#[derive(Clone)]
pub struct RawPacket {
    id: MessageId,
    buf: Option<BufRc>,
    at: Cell<usize>,
    format: Format,
    channel: ChannelId,
}

impl RawPacket {
    /// Construct an empty raw packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::MessageId;
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    ///
    /// assert!(packet.is_empty());
    /// assert_eq!(packet.id(), MessageId::EMPTY);
    /// ```
    pub const fn empty() -> Self {
        Self {
            id: MessageId::EMPTY,
            buf: None,
            at: Cell::new(0),
            format: Format::DEFAULT,
            channel: ChannelId::NONE,
        }
    }

    /// The [`Format`] the body of this packet is encoded with.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::Format;
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.format(), Format::DEFAULT);
    /// ```
    #[inline]
    pub fn format(&self) -> Format {
        self.format
    }

    /// Return the channel this packet belongs to.
    ///
    /// For a response this is the channel the request was sent over, and for
    /// a broadcast it is the channel the broadcast originated from, as written
    /// by [`ws::Server::broadcast_from`]. A page can compare it to the id of its
    /// own channel to recognize the echo of a change it made itself, see
    /// [`RawPacket::is_from`].
    ///
    /// This is [`ChannelId::NONE`] for a request which was not sent over a
    /// channel, and for a broadcast which no channel is credited with, such as
    /// one written with [`ws::Server::broadcast`].
    ///
    /// [`ws::Server::broadcast`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast
    /// [`ws::Server::broadcast_from`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast_from
    #[inline]
    pub fn channel(&self) -> ChannelId {
        self.channel
    }

    /// Test if this packet originated from `channel`.
    ///
    /// This is `true` if the packet is a broadcast which was written with
    /// [`ws::Server::broadcast_from`] and `channel` as its origin, or a
    /// response to a request sent over `channel`. It is never `true` for
    /// [`ChannelId::NONE`], so a broadcast which no channel is credited with
    /// is not mistaken for the echo of a page which has not opened a channel
    /// yet.
    ///
    /// Channel ids are unique across every connection to a server by
    /// default, so a broadcast caused by another client never matches.
    ///
    /// [`ws::Server::broadcast_from`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast_from
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::ChannelId;
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.channel(), ChannelId::NONE);
    /// assert!(!packet.is_from(ChannelId::NONE));
    /// ```
    #[inline]
    pub fn is_from(&self, channel: ChannelId) -> bool {
        channel != ChannelId::NONE && self.channel == channel
    }

    /// Decode the contents of a raw packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`RawPacket::is_empty`].
    pub fn decode<'this, T>(&'this self) -> Result<T>
    where
        T: DecodeBody<'this>,
    {
        if self.id == MessageId::EMPTY {
            return Err(Error::new(ErrorKind::EmptyPacket));
        }

        let mut at = self.at.get();

        match self.format.decode(self.as_slice(), &mut at) {
            Ok(value) => {
                self.at.set(at);
                Ok(value)
            }
            Err(error) => {
                self.at.set(self.len());
                Err(Error::decode_packet(error))
            }
        }
    }

    /// Get the underlying byte slice of the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.as_slice(), &[0u8; 0]);
    /// ```
    pub fn as_slice(&self) -> &[u8] {
        match &self.buf {
            Some(buf) => buf.as_ref(),
            None => &[],
        }
    }

    /// Get the number of bytes remaining to be decoded in the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.remaining(), 0);
    /// ```
    pub fn remaining(&self) -> usize {
        self.as_slice().len().saturating_sub(self.at.get())
    }

    /// Get the length of the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.len(), 0);
    /// ```
    pub fn len(&self) -> usize {
        match &self.buf {
            Some(buf) => buf.len(),
            None => 0,
        }
    }

    /// Check if the packet is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert!(packet.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.at.get() >= self.len()
    }

    /// The id of the packet this is a response to as specified by
    /// [`Endpoint::ID`] or [`Broadcast::ID`].
    ///
    /// [`Endpoint::ID`]: crate::api::Endpoint::ID
    /// [`Broadcast::ID`]: crate::api::Broadcast::ID
    pub fn id(&self) -> MessageId {
        self.id
    }
}

impl fmt::Debug for RawPacket {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawPacket")
            .field("remaining", &self.remaining())
            .finish()
    }
}

/// A typed packet of data.
pub struct Packet<T> {
    raw: RawPacket,
    _marker: PhantomData<T>,
}

impl<T> Packet<T> {
    /// Construct an empty package.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::MessageId;
    /// use musli_web::web::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    ///
    /// assert!(packet.is_empty());
    /// assert_eq!(packet.id(), MessageId::EMPTY);
    /// ```
    pub const fn empty() -> Self {
        Self {
            raw: RawPacket::empty(),
            _marker: PhantomData,
        }
    }

    /// Return the channel this packet belongs to.
    ///
    /// For a response this is the channel the request was sent over, and for
    /// a broadcast it is the channel the broadcast originated from, as written
    /// by [`ws::Server::broadcast_from`]. A page can compare it to the id of its
    /// own channel to recognize the echo of a change it made itself, see
    /// [`Packet::is_from`].
    ///
    /// This is [`ChannelId::NONE`] for a request which was not sent over a
    /// channel, and for a broadcast which no channel is credited with, such as
    /// one written with [`ws::Server::broadcast`].
    ///
    /// [`ws::Server::broadcast`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast
    /// [`ws::Server::broadcast_from`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast_from
    #[inline]
    pub fn channel(&self) -> ChannelId {
        self.raw.channel()
    }

    /// Test if this packet originated from `channel`.
    ///
    /// This is `true` if the packet is a broadcast which was written with
    /// [`ws::Server::broadcast_from`] and `channel` as its origin, or a
    /// response to a request sent over `channel`. It is never `true` for
    /// [`ChannelId::NONE`], so a broadcast which no channel is credited with
    /// is not mistaken for the echo of a page which has not opened a channel
    /// yet.
    ///
    /// Channel ids are unique across every connection to a server by
    /// default, so a broadcast caused by another client never matches.
    ///
    /// [`ws::Server::broadcast_from`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast_from
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::ChannelId;
    /// use musli_web::web::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    /// assert_eq!(packet.channel(), ChannelId::NONE);
    /// assert!(!packet.is_from(ChannelId::NONE));
    /// ```
    #[inline]
    pub fn is_from(&self, channel: ChannelId) -> bool {
        self.raw.is_from(channel)
    }

    /// The [`Format`] the body of this packet is encoded with.
    #[inline]
    pub fn format(&self) -> Format {
        self.raw.format()
    }

    /// Construct a new typed package from a raw one.
    ///
    /// Note that this does not guarantee that the typed package is correct, but
    /// the `T` parameter becomes associated with it allowing it to be used
    /// automatically with methods such as [`Packet::decode`].
    #[inline]
    pub fn new(raw: RawPacket) -> Self {
        Self {
            raw,
            _marker: PhantomData,
        }
    }

    /// Convert a packet into a raw packet.
    ///
    /// To determine which endpoint or broadcast it belongs to the
    /// [`RawPacket::id`] method can be used.
    pub fn into_raw(self) -> RawPacket {
        self.raw
    }

    /// Get the number of bytes remaining to be decoded in the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    /// assert_eq!(packet.remaining(), 0);
    /// ```
    pub fn remaining(&self) -> usize {
        self.raw.remaining()
    }

    /// Check if the packet is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    /// assert!(packet.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// The id of the packet this is a response to as specified by
    /// [`Endpoint::ID`] or [`Broadcast::ID`].
    ///
    /// [`Endpoint::ID`]: crate::api::Endpoint::ID
    /// [`Broadcast::ID`]: crate::api::Broadcast::ID
    pub fn id(&self) -> MessageId {
        self.raw.id()
    }
}

impl<T> Packet<T>
where
    T: api::Decodable,
{
    /// Decode the contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    pub fn decode(&self) -> Result<T::Type<'_>> {
        self.decode_any()
    }

    /// Decode any contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    pub fn decode_any<'de, R>(&'de self) -> Result<R>
    where
        R: DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Packet<T>
where
    T: api::Endpoint,
{
    /// Decode the contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    pub fn decode_response(&self) -> Result<T::Response<'_>> {
        self.decode_any_response()
    }

    /// Decode any contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    pub fn decode_any_response<'de, R>(&'de self) -> Result<R>
    where
        R: DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Packet<T>
where
    T: api::Broadcast,
{
    /// Decode the primary event related to a broadcast.
    pub fn decode_event<'de>(&'de self) -> Result<T::Event<'de>>
    where
        T: api::BroadcastWithEvent,
    {
        self.decode_event_any()
    }

    /// Decode any event related to a broadcast.
    pub fn decode_event_any<'de, E>(&'de self) -> Result<E>
    where
        E: Event<Broadcast = T> + DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Clone for Packet<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            raw: self.raw.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Packet<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Packet")
            .field("type", &any::type_name::<T>())
            .field("remaining", &self.remaining())
            .finish()
    }
}

/// A handle to the WebSocket service.
pub struct Handle<H>
where
    H: WebImpl,
{
    shared: Weak<Shared<H>>,
}

impl<H> Handle<H>
where
    H: WebImpl,
{
    /// The [`Format`] currently in effect for message bodies.
    ///
    /// Before the connection has been opened this is the format which was
    /// requested through [`ServiceBuilder::format`]. Once the connection is
    /// open it is the format the server actually agreed to, which can differ if
    /// the server does not support what was asked for.
    pub fn format(&self) -> Format {
        let Some(shared) = self.shared.upgrade() else {
            return Format::DEFAULT;
        };

        shared.format.get()
    }

    /// The [`Mode`] the socket is currently running in.
    ///
    /// Before the connection has been opened this is the mode which was
    /// requested through [`ServiceBuilder::mode`]. Once the connection is open
    /// it is the mode which was settled on, which can differ if the server
    /// could not carry the negotiated format that way.
    pub fn mode(&self) -> Mode {
        let Some(shared) = self.shared.upgrade() else {
            return Mode::DEFAULT;
        };

        shared.mode.get()
    }

    /// The generation of the connection.
    ///
    /// This counts the number of times the connection has opened, that is
    /// reached [`State::Open`]. It is `0` until the connection first opens,
    /// and goes up by one every time it opens again after having been closed.
    /// A handle which is not connected to a service, such as
    /// [`Handle::default`], always reports `0`.
    ///
    /// The generation is updated before any listener hears of the connection
    /// opening, so it can be read from inside [`Handle::on_state_change`] and
    /// [`Handle::on_open`] callbacks.
    ///
    /// Comparing the generation to the one data was last fetched in tells
    /// whether it has to be fetched again, see [refetching after a
    /// reconnect](crate::web#refetching-after-a-reconnect).
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let handle = ws::Handle::default();
    /// assert_eq!(handle.generation(), 0);
    /// ```
    pub fn generation(&self) -> u64 {
        let Some(shared) = self.shared.upgrade() else {
            return 0;
        };

        shared.g.generation.get()
    }

    /// Set up a new logical channel to the WebSocket server.
    ///
    /// A channel can be uniquely identified on the client and server side over
    /// a single connection. This means that if you send a request over a
    /// channel using [`Channel::request`], the server can access the
    /// [`ChannelId`] to determine which channel sent the request and the client
    /// has the ability to correlate any responses sent by the server by
    /// inspecting [`Packet::channel`] or [`RawPacket::channel`].
    ///
    /// A broadcast caused by a request over a channel can name that channel as
    /// its origin with [`ws::Server::broadcast_from`], which every listener
    /// sees as [`Packet::channel`]. This lets a page skip the echo of its own
    /// changes with [`Packet::is_from`], without carrying the [`ChannelId`] in
    /// the body of the event.
    ///
    /// The maximum number of channels is implementation defined, but expect it
    /// to be relatively low like `65535` (non-zero 16 bits) to reduce payload
    /// sizes. Failure to allocate a channel is reported as
    /// [`ChannelEvent::Failed`].
    ///
    /// [`ws::Server::broadcast_from`]: https://docs.rs/musli-web/latest/musli_web/ws/struct.Server.html#method.broadcast_from
    ///
    /// # Reconnecting
    ///
    /// The server forgets a channel when the connection it was opened over
    /// closes. The [`Channel`] returned by [`ChannelBuilder::open`] takes care
    /// of this: it opens itself again every time the connection reopens, so a
    /// component holds the same [`Channel`] for its whole life. Every time it
    /// opens the callback set with [`ChannelBuilder::on_change`] is told with
    /// [`ChannelEvent::Opened`], which is when to send the requests the
    /// component needs the channel for. It gets a new id each time, and
    /// [`ChannelEvent::Closed`] is reported when it is lost.
    ///
    /// While the channel is not open [`Channel::is_open`] returns `false`, and
    /// requests over it fail with [`Error::is_not_connected`] without being
    /// sent, so there is no need to check before sending. A request which
    /// should go out as soon as the channel is back can be queued with
    /// [`Channel::when_open`].
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// enum Msg {
    ///     Channel(ws::ChannelEvent),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     channel: ws::Channel,
    /// }
    ///
    /// impl App {
    ///     fn fetch(&mut self, ctx: &Context<Self>) {
    ///         // Send the requests this component shows the result of over
    ///         // `self.channel`.
    ///     }
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         // The channel is opened once the connection is, and opened
    ///         // again every time the connection reopens.
    ///         let channel = ctx.props().ws
    ///             .channel()
    ///             .on_change(ctx.link().callback(Msg::Channel))
    ///             .open();
    ///
    ///         Self { channel }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::Channel(ws::ChannelEvent::Opened(..)) => {
    ///                 // Opened for the first time or after a reconnect, so
    ///                 // fetch everything again.
    ///                 self.fetch(ctx);
    ///                 true
    ///             }
    ///             Msg::Channel(ws::ChannelEvent::Failed(error)) => {
    ///                 tracing::error!("Could not open channel: {error}");
    ///                 true
    ///             }
    ///             Msg::Channel(..) => true,
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Channel open: {}", self.channel.is_open())}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn channel(&self) -> ChannelBuilder<'_, H, EmptyCallback> {
        ChannelBuilder {
            shared: &self.shared,
            callback: EmptyCallback,
        }
    }

    /// Send a request of type `T`.
    ///
    /// Returns a handle for the request.
    ///
    /// If the handle is dropped, the request is cancelled.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloRequest<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct HelloResponse<'de> {
    ///         pub message: &'de str,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Hello;
    ///
    ///         impl Endpoint for Hello {
    ///             impl<'de> Request for HelloRequest<'de>;
    ///             type Response<'de> = HelloResponse<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     OnHello(Result<ws::Packet<api::Hello>, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     message: String,
    ///     _hello: ws::Request,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let hello = ctx.props().ws
    ///             .request()
    ///             .body(api::HelloRequest { message: "Hello!"})
    ///             .on_packet(ctx.link().callback(Msg::OnHello))
    ///             .send();
    ///
    ///         Self {
    ///             message: String::from("No Message :("),
    ///             _hello: hello,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::OnHello(Err(error)) => {
    ///                 tracing::error!("Request error: {:?}", error);
    ///                 false
    ///             }
    ///             Msg::OnHello(Ok(packet)) => {
    ///                 if let Ok(response) = packet.decode() {
    ///                     self.message = response.message.to_owned();
    ///                 }
    ///
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Message: {}", self.message)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn request(&self) -> RequestBuilder<'_, H, EmptyBody, EmptyCallback> {
        RequestBuilder {
            shared: &self.shared,
            channel: Some(ChannelId::NONE),
            body: EmptyBody,
            callback: EmptyCallback,
        }
    }

    /// Send a request over the default channel and get a future which
    /// resolves to its decoded response.
    ///
    /// This is an asynchronous alternative to building the request with
    /// [`request`] and handling the response with a callback. The returned
    /// [`Call`] resolves to the response of the endpoint `body` is a request
    /// for, decoded as an owned value. Dropping it before it resolves cancels
    /// the request.
    ///
    /// The request is sent straight away, the future only waits for the
    /// response. It has to be driven by something which polls futures, such as
    /// [`Scope::send_future`] in yew or `wasm_bindgen_futures::spawn_local`.
    /// Note that a future handed to either of them is not dropped when the
    /// component goes away, so the request is not cancelled with it.
    ///
    /// The response type of the endpoint must be owned, which is what the
    /// `for<'de> ...: DecodeBody<'de>` bound says: it decodes from any buffer,
    /// so it holds on to none of them. A response declared as `type
    /// Response<'de> = User;` qualifies, one which borrows such as `type
    /// Response<'de> = UserRef<'de>;` does not compile here. For those use
    /// [`RequestBuilder::on_packet`] and decode from the [`Packet`] instead.
    ///
    /// See [`Channel::call`] to call over a channel.
    ///
    /// [`request`]: Self::request
    /// [`Scope::send_future`]: <https://docs.rs/yew/latest/yew/html/struct.Scope.html#method.send_future>
    ///
    /// # Errors
    ///
    /// The future resolves to an [`Error`] which tells what went wrong, the
    /// same as the one a callback would get:
    ///
    /// * [`Error::is_not_connected`] if the request was never sent since the
    ///   connection is not open.
    /// * [`Error::is_connection_lost`] if the connection closed before the
    ///   response arrived.
    /// * [`Error::is_cancelled`] if another request took its place.
    /// * [`Error::as_server_error`] if the handler on the server failed, and
    ///   [`Error::server_error`] to decode the typed error it failed with.
    /// * [`Error::is_decode`] if the response does not decode as the response
    ///   type, for instance since the server is built from another version of
    ///   the API.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct UserRequest<'de> {
    ///         pub name: &'de str,
    ///     }
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct UserResponse {
    ///         pub name: String,
    ///         pub age: u32,
    ///     }
    ///
    ///     api::define! {
    ///         pub type User;
    ///
    ///         impl Endpoint for User {
    ///             impl<'de> Request for UserRequest<'de>;
    ///             type Response<'de> = UserResponse;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     Age(Result<u32, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct Age {
    ///     age: Option<u32>,
    /// }
    ///
    /// impl Component for Age {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let call = ctx.props().ws.call(api::UserRequest { name: "Alice" });
    ///
    ///         ctx.link().send_future(async move {
    ///             Msg::Age(call.await.map(|user| user.age))
    ///         });
    ///
    ///         Self { age: None }
    ///     }
    ///
    ///     fn update(&mut self, _: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::Age(Ok(age)) => {
    ///                 self.age = Some(age);
    ///                 true
    ///             }
    ///             Msg::Age(Err(error)) => {
    ///                 tracing::error!("Failed to get age: {error}");
    ///                 false
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, _: &Context<Self>) -> Html {
    ///         html! {
    ///             if let Some(age) = self.age {
    ///                 <p>{format!("Alice is {age}")}</p>
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    pub fn call<B>(&self, body: B) -> Call<<B::Endpoint as api::Endpoint>::Response<'static>>
    where
        B: api::Request,
        for<'de> <B::Endpoint as api::Endpoint>::Response<'static>: DecodeBody<'de>,
    {
        Call::send(self.request().body(body))
    }

    /// Listen for broadcasts of type `T`.
    ///
    /// Returns a handle for the listener that will cancel the listener if
    /// dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct TickEvent<'de> {
    ///         pub message: &'de str,
    ///         pub tick: u32,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Tick;
    ///
    ///         impl Broadcast for Tick {
    ///             impl<'de> Event for TickEvent<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     Tick(Result<ws::Packet<api::Tick>, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     tick: u32,
    ///     _listen: ws::Listener,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let listen = ctx.props().ws.on_broadcast(ctx.link().callback(Msg::Tick));
    ///
    ///         Self {
    ///             tick: 0,
    ///             _listen: listen,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::Tick(Err(error)) => {
    ///                 tracing::error!("Tick error: {error}");
    ///                 false
    ///             }
    ///             Msg::Tick(Ok(packet)) => {
    ///                 if let Ok(tick) = packet.decode_event() {
    ///                     self.tick = tick.tick;
    ///                 }
    ///
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Tick: {}", self.tick)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn on_broadcast<T>(&self, callback: impl Callback<Result<Packet<T>>>) -> Listener
    where
        T: api::Broadcast,
    {
        self.on_raw_broadcast::<T>(move |result| match result {
            Ok(packet) => callback.call(Ok(Packet::new(packet))),
            Err(error) => callback.call(Err(error)),
        })
    }

    /// Listen for broadcasts of type `T`.
    ///
    /// Returns a handle for the listener that will cancel the listener if
    /// dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// mod api {
    ///     use musli::{Decode, Encode};
    ///     use musli_web::api;
    ///
    ///     #[derive(Encode, Decode)]
    ///     pub struct TickEvent<'de> {
    ///         pub message: &'de str,
    ///         pub tick: u32,
    ///     }
    ///
    ///     api::define! {
    ///         pub type Tick;
    ///
    ///         impl Broadcast for Tick {
    ///             impl<'de> Event for TickEvent<'de>;
    ///         }
    ///     }
    /// }
    ///
    /// enum Msg {
    ///     Tick(Result<ws::RawPacket, ws::Error>),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     tick: u32,
    ///     _listen: ws::Listener,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let link = ctx.link().clone();
    ///         let listen = ctx.props().ws.on_raw_broadcast::<api::Tick>(ctx.link().callback(Msg::Tick));
    ///
    ///         Self {
    ///             tick: 0,
    ///             _listen: listen,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::Tick(Err(error)) => {
    ///                 tracing::error!("Tick error: {error}");
    ///                 false
    ///             }
    ///             Msg::Tick(Ok(packet)) => {
    ///                 if let Ok(tick) = packet.decode::<api::TickEvent>() {
    ///                     self.tick = tick.tick;
    ///                 }
    ///
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("Tick: {}", self.tick)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    /// ```
    pub fn on_raw_broadcast<T>(&self, callback: impl Callback<Result<RawPacket>>) -> Listener
    where
        T: api::Broadcast,
    {
        let Some(shared) = self.shared.upgrade() else {
            return Listener::empty_with_kind(T::ID);
        };

        let index = {
            let mut broadcasts = shared.g.broadcasts.borrow_mut();
            let slots = broadcasts.entry(T::ID).or_default();
            slots.insert(Rc::new(callback))
        };

        Listener {
            kind: Some(T::ID),
            index,
            g: Rc::downgrade(&shared.g),
        }
    }

    /// Listen for state changes to the underlying connection.
    ///
    /// This indicates when the connection is open and ready to receive requests
    /// through [`State::Open`], or if it's closed and requests will be queued
    /// through [`State::Closed`]. A server which states another application
    /// version is reported through [`State::Incompatible`], see
    /// [`ServiceBuilder::app_version`].
    ///
    /// Note that if you are connecting through a proxy the reported updates
    /// might be volatile. It is always best to send a message over the
    /// connection on the server side that once received allows the client to
    /// know that it is connected.
    ///
    /// Dropping the returned handle will cancel the listener.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// enum Msg {
    ///     StateChange(ws::State),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     state: ws::State,
    ///     _listen: ws::StateListener,
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let link = ctx.link().clone();
    ///
    ///         let (state, listen) = ctx.props().ws.on_state_change(move |state| {
    ///             link.send_message(Msg::StateChange(state));
    ///         });
    ///
    ///         Self {
    ///             state,
    ///             _listen: listen,
    ///         }
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::StateChange(state) => {
    ///                 self.state = state;
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, ctx: &Context<Self>) -> Html {
    ///         html! {
    ///             <div>
    ///                 <h1>{"WebSocket Example"}</h1>
    ///                 <p>{format!("State: {:?}", self.state)}</p>
    ///             </div>
    ///         }
    ///     }
    /// }
    pub fn on_state_change(&self, callback: impl Callback<State>) -> (State, StateListener) {
        let Some(shared) = self.shared.upgrade() else {
            return (
                State::Closed,
                StateListener {
                    index: 0,
                    g: Weak::new(),
                },
            );
        };

        let (state, index) = {
            let index = shared
                .g
                .state_listeners
                .borrow_mut()
                .insert(Rc::new(callback));
            (shared.state.get(), index)
        };

        let listener = StateListener {
            index,
            g: Rc::downgrade(&shared.g),
        };

        (state, listener)
    }

    /// Listen for the connection opening.
    ///
    /// The callback is called with the new [generation] every time the
    /// connection reaches [`State::Open`], which is the point at which a
    /// component should fetch what it shows again. It is not called when the
    /// connection closes.
    ///
    /// The returned generation is `Some` with the current generation if the
    /// connection is open already, in which case the callback is not called
    /// for it, and `None` if it is not. A component can fetch straight away
    /// if it is `Some`, and otherwise wait for the callback.
    ///
    /// Dropping the returned handle will cancel the listener.
    ///
    /// [generation]: Self::generation
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate yew023 as yew;
    /// use yew::prelude::*;
    /// use musli_web::web03::prelude::*;
    ///
    /// enum Msg {
    ///     Opened(u64),
    /// }
    ///
    /// #[derive(Properties, PartialEq)]
    /// struct Props {
    ///     ws: ws::Handle,
    /// }
    ///
    /// struct App {
    ///     /// The generation the data was last fetched in.
    ///     fetched: Option<u64>,
    ///     _open: ws::StateListener,
    /// }
    ///
    /// impl App {
    ///     fn fetch(&mut self, ctx: &Context<Self>, generation: u64) {
    ///         if self.fetched == Some(generation) {
    ///             return;
    ///         }
    ///
    ///         self.fetched = Some(generation);
    ///         // Send the requests this component shows the result of.
    ///     }
    /// }
    ///
    /// impl Component for App {
    ///     type Message = Msg;
    ///     type Properties = Props;
    ///
    ///     fn create(ctx: &Context<Self>) -> Self {
    ///         let (generation, open) = ctx.props().ws.on_open(ctx.link().callback(Msg::Opened));
    ///
    ///         let mut this = Self {
    ///             fetched: None,
    ///             _open: open,
    ///         };
    ///
    ///         if let Some(generation) = generation {
    ///             this.fetch(ctx, generation);
    ///         }
    ///
    ///         this
    ///     }
    ///
    ///     fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ///         match msg {
    ///             Msg::Opened(generation) => {
    ///                 self.fetch(ctx, generation);
    ///                 true
    ///             }
    ///         }
    ///     }
    ///
    ///     fn view(&self, _: &Context<Self>) -> Html {
    ///         html! {}
    ///     }
    /// }
    /// ```
    pub fn on_open(&self, callback: impl Callback<u64>) -> (Option<u64>, StateListener) {
        let Some(shared) = self.shared.upgrade() else {
            return (None, StateListener::new());
        };

        let callback = {
            // NB: Weak, since the listener is owned by the generic state.
            let g = Rc::downgrade(&shared.g);

            move |state: State| {
                if state != State::Open {
                    return;
                }

                if let Some(g) = g.upgrade() {
                    callback.call(g.generation.get());
                }
            }
        };

        let index = shared
            .g
            .state_listeners
            .borrow_mut()
            .insert(Rc::new(callback));

        let generation = shared
            .state
            .get()
            .is_open()
            .then(|| shared.g.generation.get());

        let listener = StateListener {
            index,
            g: Rc::downgrade(&shared.g),
        };

        (generation, listener)
    }
}

impl<H> Clone for Handle<H>
where
    H: WebImpl,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            shared: self.shared.clone(),
        }
    }
}

/// Construct a default handle that is not connected to a backend.
///
/// # Examples
///
/// ```
/// use musli_web::web03::prelude::*;
///
/// let handle = ws::Handle::default();
/// ```
impl<H> Default for Handle<H>
where
    H: WebImpl,
{
    #[inline]
    fn default() -> Self {
        Self {
            shared: Weak::new(),
        }
    }
}

impl<H> PartialEq for Handle<H>
where
    H: WebImpl,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        Weak::ptr_eq(&self.shared, &other.shared)
    }
}

impl<H> fmt::Debug for Handle<H>
where
    H: WebImpl,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_struct("Handle");

        if let Some(shared) = self.shared.upgrade() {
            f.field("connect", &shared.connect);
            f.field("state", &shared.state.get());
        }

        f.finish()
    }
}

/// What happened to a [`Channel`], as told to the callback set with
/// [`ChannelBuilder::on_change`].
#[derive(Debug)]
#[non_exhaustive]
pub enum ChannelEvent {
    /// The channel was opened over the current connection with the given
    /// [`ChannelId`], and requests can be sent over it.
    ///
    /// This is reported every time the channel opens, including after a
    /// reconnect, at which point the server has forgotten everything which
    /// was sent over the channel before and the id is likely different.
    Opened(ChannelId),
    /// The channel was lost along with the connection it was opened over.
    ///
    /// It opens again by itself once the connection is back.
    Closed,
    /// The server could not open the channel, for example since it has run
    /// out of channel ids or its handler refused it.
    ///
    /// The channel stays closed until the connection reopens, at which point
    /// it is tried again.
    Failed(Error),
}

/// A logical channel to a WebSocket server, which opens itself again every
/// time the connection does.
///
/// A channel is set up with [`Handle::channel`], see it for more details.
///
/// Cloning a channel is cheap and every clone refers to the same channel. The
/// channel is closed and stops reopening once the last clone has been dropped.
///
/// While the channel is not open, such as before the server has answered or
/// while the connection is down, [`Channel::is_open`] returns `false`,
/// [`Channel::id`] returns [`ChannelId::NONE`], and requests sent over it fail
/// with [`Error::is_not_connected`] without being sent.
pub struct Channel<H>
where
    H: WebImpl,
{
    inner: Rc<ChannelInner<H>>,
}

/// The state of a channel shared by its clones.
struct ChannelInner<H>
where
    H: WebImpl,
{
    handle: Handle<H>,
    /// The id of the channel while it is open, or [`ChannelId::NONE`].
    id: Cell<ChannelId>,
    /// The generation of the connection the channel was last opened over.
    generation: Cell<u64>,
    on_change: Box<dyn Callback<ChannelEvent>>,
    /// Waiting to be called once the channel is open, see
    /// [`Channel::when_open`].
    queue: RefCell<VecDeque<Box<dyn FnOnce(&Channel<H>)>>>,
    /// The pending request to open the channel.
    connect: RefCell<Request>,
    state: RefCell<StateListener>,
}

impl<H> ChannelInner<H>
where
    H: WebImpl,
{
    fn is_open(&self) -> bool {
        let id = self.id.get();

        if id == ChannelId::NONE {
            return false;
        }

        let Some(shared) = self.handle.shared.upgrade() else {
            return false;
        };

        shared.state.get().is_open() && shared.g.generation.get() == self.generation.get()
    }

    fn on_state(self: &Rc<Self>, state: State) {
        match state {
            State::Open => {
                self.connect();
            }
            State::Closed | State::Incompatible { .. } => {
                // NB: Dropped outside of the borrow, since dropping a request
                // touches the shared request table.
                let connect = mem::take(&mut *self.connect.borrow_mut());
                drop(connect);

                if self.id.replace(ChannelId::NONE) != ChannelId::NONE {
                    self.on_change.call(ChannelEvent::Closed);
                }
            }
        }
    }

    fn connect(self: &Rc<Self>) {
        let request = connect_channel(&self.handle.shared, {
            let inner = Rc::downgrade(self);

            move |result| {
                if let Some(inner) = inner.upgrade() {
                    inner.connected(result);
                }
            }
        });

        let old = mem::replace(&mut *self.connect.borrow_mut(), request);
        drop(old);
    }

    fn connected(self: &Rc<Self>, result: Result<ChannelId>) {
        let id = match result {
            Ok(id) => id,
            Err(error) => {
                // NB: These mean that the connection went away, in which case
                // the channel is opened again once it is back.
                if !(error.is_connection_lost() || error.is_not_connected() || error.is_cancelled())
                {
                    self.on_change.call(ChannelEvent::Failed(error));
                }

                return;
            }
        };

        self.id.set(id);
        self.generation.set(self.handle.generation());

        let channel = Channel {
            inner: self.clone(),
        };

        // NB: Each call can close the channel, in which case what remains in
        // the queue waits for it to open again.
        while channel.is_open() {
            let Some(f) = self.queue.borrow_mut().pop_front() else {
                break;
            };

            f(&channel);
        }

        if channel.is_open() && self.id.get() == id {
            self.on_change.call(ChannelEvent::Opened(id));
        }
    }
}

impl<H> Drop for ChannelInner<H>
where
    H: WebImpl,
{
    #[inline]
    fn drop(&mut self) {
        // NB: A channel from an earlier connection was dropped by the server
        // along with that connection, and its id may since have been handed
        // to another channel over the current one.
        if self.is_open() {
            if let Some(shared) = self.handle.shared.upgrade() {
                shared.remove_channel(self.id.get());
            }
        }
    }
}

impl<H> Channel<H>
where
    H: WebImpl,
{
    /// The id the server gave the channel.
    ///
    /// This is [`ChannelId::NONE`] while the channel is not [open], and
    /// usually changes each time the channel opens again after a reconnect.
    ///
    /// [open]: Self::is_open
    #[inline]
    pub fn id(&self) -> ChannelId {
        if self.inner.is_open() {
            self.inner.id.get()
        } else {
            ChannelId::NONE
        }
    }

    /// The [generation] of the connection the channel was last opened over.
    ///
    /// This is `0` until the channel first opens.
    ///
    /// [generation]: Handle::generation
    #[inline]
    pub fn generation(&self) -> u64 {
        self.inner.generation.get()
    }

    /// Whether requests can be sent over this channel.
    ///
    /// This is `true` from when the server has opened the channel until the
    /// connection it was opened over closes. It is `false` for a [default]
    /// channel, and while the channel is being opened again after a
    /// reconnect. A request over a channel which is not open fails with
    /// [`Error::is_not_connected`] without being sent.
    ///
    /// [default]: Channel::default
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::web03::prelude::*;
    ///
    /// let channel = ws::Channel::default();
    /// assert!(!channel.is_open());
    /// ```
    #[inline]
    pub fn is_open(&self) -> bool {
        self.inner.is_open()
    }

    /// Get the handle this channel was opened through.
    ///
    /// A handle sheds the channel information and allows for setting up things
    /// like broadcast listener.
    #[inline]
    pub fn handle(&self) -> &Handle<H> {
        &self.inner.handle
    }

    /// Send a request of type `T` over the channel.
    ///
    /// Returns a handle for the request. If the handle is dropped, the request
    /// is cancelled.
    ///
    /// If the channel is not [open], the request fails with
    /// [`Error::is_not_connected`] without being sent. Send it once the
    /// channel has opened instead, as reported by [`ChannelEvent::Opened`], or
    /// use [`Channel::when_open`]. See [`ChannelBuilder::on_change`] for an
    /// example.
    ///
    /// [open]: Self::is_open
    pub fn request(&self) -> RequestBuilder<'_, H, EmptyBody, EmptyCallback> {
        RequestBuilder {
            shared: &self.inner.handle.shared,
            channel: self.inner.is_open().then(|| self.inner.id.get()),
            body: EmptyBody,
            callback: EmptyCallback,
        }
    }

    /// Send a request over the current channel and get a future which
    /// resolves to its decoded response.
    ///
    /// This is the same as [`Handle::call`] except that the request is sent
    /// over this channel, see it for how the response is decoded and the
    /// errors it resolves to. Like [`request`], it fails with
    /// [`Error::is_not_connected`] without being sent if the channel is not
    /// open.
    ///
    /// [`request`]: Self::request
    pub fn call<B>(&self, body: B) -> Call<<B::Endpoint as api::Endpoint>::Response<'static>>
    where
        B: api::Request,
        for<'de> <B::Endpoint as api::Endpoint>::Response<'static>: DecodeBody<'de>,
    {
        Call::send(self.request().body(body))
    }

    /// Call `f` with the channel once it is open.
    ///
    /// If the channel is open, `f` is called straight away. Otherwise it is
    /// queued and called as soon as the channel opens, before
    /// [`ChannelEvent::Opened`] is reported. Queued calls are made in the order
    /// they were queued, and are dropped without being called if the channel
    /// is dropped first.
    ///
    /// This suits a request made in response to the user, which should be
    /// sent even if the connection happens to be down at the time.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::cell::Cell;
    /// use std::rc::Rc;
    ///
    /// use musli_web::web03::prelude::*;
    ///
    /// let channel = ws::Channel::default();
    /// let called = Rc::new(Cell::new(false));
    ///
    /// channel.when_open({
    ///     let called = called.clone();
    ///     move |_: &ws::Channel| called.set(true)
    /// });
    ///
    /// // A default channel never opens.
    /// assert!(!called.get());
    /// ```
    pub fn when_open(&self, f: impl FnOnce(&Channel<H>) + 'static) {
        if self.inner.is_open() {
            f(self);
            return;
        }

        self.inner.queue.borrow_mut().push_back(Box::new(f));
    }
}

impl<H> Clone for Channel<H>
where
    H: WebImpl,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

/// Construct a channel which is not connected to a service and never opens.
///
/// This is a placeholder for a component which does not have a channel yet.
///
/// # Examples
///
/// ```
/// use musli_web::web03::prelude::*;
///
/// let channel = ws::Channel::default();
/// assert!(!channel.is_open());
/// assert_eq!(channel.id(), ws::ChannelId::NONE);
/// ```
impl<H> Default for Channel<H>
where
    H: WebImpl,
{
    #[inline]
    fn default() -> Self {
        Self {
            inner: Rc::new(ChannelInner {
                handle: Handle::default(),
                id: Cell::new(ChannelId::NONE),
                generation: Cell::new(0),
                on_change: Box::new(EmptyCallback),
                queue: RefCell::new(VecDeque::new()),
                connect: RefCell::new(Request::new()),
                state: RefCell::new(StateListener::new()),
            }),
        }
    }
}

/// Channels are equal if they are opened through the same service and are
/// currently open with the same id, or are both closed.
///
/// So a property holding a channel changes when the channel opens, closes or
/// opens again with a new id.
impl<H> PartialEq for Channel<H>
where
    H: WebImpl,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        Weak::ptr_eq(&self.inner.handle.shared, &other.inner.handle.shared)
            && self.id() == other.id()
    }
}

impl<H> fmt::Debug for Channel<H>
where
    H: WebImpl,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_struct("Channel");

        if let Some(shared) = self.inner.handle.shared.upgrade() {
            f.field("connect", &shared.connect);
            f.field("state", &shared.state.get());
        }

        f.field("id", &self.id());
        f.field("generation", &self.generation());
        f.finish()
    }
}

struct Pending<C>
where
    C: ?Sized,
{
    id: MessageId,
    serial: u32,
    callback: C,
}

impl<C> fmt::Debug for Pending<C> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Pending")
            .field("serial", &self.serial)
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

struct ForcePrefix<'a>(&'a str, char);

impl fmt::Display for ForcePrefix<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self(string, prefix) = *self;
        prefix.fmt(f)?;
        string.trim_start_matches(prefix).fmt(f)?;
        Ok(())
    }
}