wse-client 3.2.0

Rust client for WSE servers, natively and in the browser: topics with message recovery, reconnects, MessagePack, end-to-end encryption and signed messages.
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
//! The protocol on one client: what the server's messages mean, which reach
//! the application, the topics subscribed and where each stands, and the
//! gaps being recovered. No I/O: what it sends goes in its write queue.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;

use bytes::Bytes;
use web_time::Instant;

use crate::client::{Queued, Shared, Status};
use crate::decode::{self, Envelope, epoch_of};
use crate::delivery::{self, Delivered};
use crate::error::Error;
use crate::handler::{
    Connected, Event, Gap, GapReason, Handler, NotDelivered, Recovery, ServerError, Subscribed,
};
use crate::message::{Message, OwnedMessage, Payload, Position, Signature};
use crate::security::{Keys, Sealing};
use crate::sequencer::{Streams, Verdict};

/// Messages held per topic while a gap is recovered; past it the client
/// stops waiting.
const HELD_MAX: usize = 1000;

/// Recovery requests in a row that got no answer at all before the client
/// stops asking on this connection: the server application does not
/// answer them.
const UNANSWERED_MAX: u32 = 2;

type Map<V> = HashMap<Box<str>, V, foldhash::fast::RandomState>;

/// A stream of a topic waiting for the server to replay what it missed.
struct Hole {
    epoch: u32,
    /// What came past the hole, by offset.
    held: BTreeMap<u64, OwnedMessage>,
    deadline: Instant,
    /// The request out for it, not answered yet.
    request: Option<u64>,
    /// The offset the last request asked from.
    requested_from: Option<u64>,
    /// An answer came for it.
    answered: bool,
}

#[derive(Default)]
struct Topic {
    streams: Streams,
    /// One per stream with a gap: usually none, at most one per node that
    /// publishes on the topic.
    holes: Vec<Hole>,
    /// Since when this connection has had the topic: from then on whatever
    /// the server publishes on it reaches the client, so silence then shows
    /// a quiet stream. None while away: time away proves nothing.
    live_since: Option<Instant>,
}

/// A recovery request out. The server answers a connection's requests in
/// order, so each topic's answers settle its requests front to back.
struct Request {
    id: u64,
    /// Asked for a hole, not by a subscription.
    for_hole: bool,
    /// The streams it named.
    named: Vec<u32>,
}

/// How long past the server's `history_ttl` a stream that heard nothing
/// while connected is still named: the clocks of a node and a client do not
/// tick together.
const QUIET_MARGIN: Duration = Duration::from_secs(5);

/// What the session asks of the connection.
pub(crate) enum Outgoing {
    /// Sealed on a connection with an end-to-end session; never sent there
    /// in plaintext.
    Text(String),
    /// The handshake's own (client_hello, the answer to a ping): as it is
    /// before the session opens, sealed after.
    Handshake(String),
    /// A message of the outbox, its number with it: a server that does not
    /// answer takes it once it is written.
    Kept {
        s: u64,
        text: bytestring::ByteString,
    },
}

pub(crate) struct Session<H> {
    /// The application's handler, behind the delivery's gate where the
    /// client was made with one.
    pub(crate) handler: Delivered<H>,
    shared: Arc<Shared>,
    recovery_timeout: Duration,
    /// Topics the client subscribed to: subscribed again on every
    /// connection.
    wanted: BTreeSet<String>,
    topics: Map<Topic>,
    /// The recovery requests out, by topic, oldest first.
    requests: Map<VecDeque<Request>>,
    next_request: u64,
    /// Topics whose history the server said it cannot replay, by epoch.
    unrecoverable: Map<u32>,
    unanswered: u32,
    holes: usize,
    next_deadline: Option<Instant>,
    /// What to send.
    pub(crate) to_write: Vec<Outgoing>,
    /// Sends that wait until each topic they require is continuous, in the
    /// order they were sent: on every connection, the last user's dropped.
    waiting: VecDeque<Queued>,
    /// The earliest of their deadlines (ms since the epoch): one that runs
    /// out while it waits goes, `expired`.
    waiting_until: u64,
    /// The outbox: every message sent but a live or signed one, until the
    /// server answers for it (`Config::offline`).
    pub(crate) outbox: Option<crate::outbox::Outbox>,
    /// The server of this connection answers the outbox (`acks`).
    server_answers: bool,
    /// The outbox's clears this session made ([`Shared::clears`]).
    clears: u64,

    keys: Arc<Keys>,

    // The connection's own.
    /// Its end-to-end session.
    pub(crate) sealing: Option<Sealing>,
    /// The connection cannot go on, nor the client.
    pub(crate) fatal: Option<Error>,
    /// The server took the connection.
    pub(crate) ready: bool,
    /// Became ready on the last frame.
    pub(crate) became_ready: bool,
    /// The client's status, which reads as connected before the
    /// application hears of the connection.
    pub(crate) status: Option<tokio::sync::watch::Sender<Status>>,
    pub(crate) connected_before: bool,
    server_recovery: bool,
    /// The user the server took the connection for: a message the server
    /// signed for a user is taken only when it is this one.
    user_id: Option<String>,
    /// The user the server took the last connection for, once there was one.
    last_user: Option<Option<String>>,
    /// [`Shared::users`] and [`Shared::connections`], which only the session
    /// moves.
    users: u64,
    connections: u64,
    /// When the frames being read came: the connection's task sets it once
    /// per batch.
    pub(crate) clock: Instant,
    /// How long the server keeps a stream that receives nothing
    /// (`history_ttl`): one quiet for longer while connected is not named in
    /// a recovery.
    history_ttl: Option<Duration>,
    /// How long a healthy connection never stays silent.
    idle_timeout: Duration,
    /// When this connection last showed the server alive, and when the run
    /// of such frames ending there began. A pause between two longer than
    /// the idle limit (the machine asleep, the app suspended) starts a new
    /// run: what is read on waking may have been sent before it, and proves
    /// nothing about the time between.
    last_alive: Option<Instant>,
    alive_since: Option<Instant>,
    /// What the application committed: where its recoveries start.
    pub(crate) committed: Option<crate::config::Committed>,
}

impl<H: Handler> Session<H> {
    pub(crate) fn new(
        handler: Delivered<H>,
        shared: Arc<Shared>,
        keys: Arc<Keys>,
        topics: &[String],
        recovery_timeout: Duration,
        idle_timeout: Duration,
    ) -> Self {
        Self {
            handler,
            shared,
            keys,
            sealing: None,
            fatal: None,
            recovery_timeout,
            wanted: topics.iter().cloned().collect(),
            topics: Map::default(),
            requests: Map::default(),
            next_request: 0,
            unrecoverable: Map::default(),
            unanswered: 0,
            holes: 0,
            next_deadline: None,
            to_write: Vec::new(),
            waiting: VecDeque::new(),
            waiting_until: u64::MAX,
            outbox: None,
            server_answers: false,
            clears: 0,
            ready: false,
            became_ready: false,
            status: None,
            connected_before: false,
            server_recovery: false,
            user_id: None,
            last_user: None,
            users: 0,
            connections: 0,
            clock: Instant::now(),
            history_ttl: None,
            idle_timeout,
            last_alive: None,
            alive_since: None,
            committed: None,
        }
    }

    /// Frames that show the server alive were read at `now`.
    pub(crate) fn alive_at(&mut self, now: Instant) {
        if self
            .last_alive
            .is_none_or(|last| now.saturating_duration_since(last) > self.idle_timeout)
        {
            self.alive_since = Some(now);
        }
        self.last_alive = Some(now);
    }

    /// A message the application sent, for this connection's write queue: none
    /// that was sent as another user, or signed or sent live on another
    /// connection; one that requires topics not continuous waits for them.
    pub(crate) fn queue(&mut self, frame: Queued) {
        self.catch_up_clears();
        if frame.clears != self.clears {
            self.dropped(&frame, "cleared");
        } else if frame.user != self.users {
            tracing::warn!("[WSE] a message sent as the previous user was dropped");
            self.dropped(&frame, "user_changed");
        } else if let Some(on) = frame.only_on {
            if self.ready && on == self.connections {
                self.to_write.push(Outgoing::Text(frame.text));
            } else {
                tracing::warn!("[WSE] a message for a connection that went was dropped");
            }
        } else if frame.requires.as_deref().is_some_and(|topics| {
            !self.ready || !delivery::lock(self.handler.gate()).continuous(topics)
        }) {
            self.waiting_until = self.waiting_until.min(frame.until.unwrap_or(u64::MAX));
            self.waiting.push_back(frame);
        } else {
            self.keep(frame);
        }
    }

    /// A message for the outbox, which hands it to the writer before the
    /// next write ([`Session::before_write`]); without an outbox, for this
    /// connection.
    fn keep(&mut self, frame: Queued) {
        match &mut self.outbox {
            Some(outbox) => {
                let size = frame.size();
                let now = crate::outbox::now_ms();
                // What is left of its time: it counts from its send.
                let ttl = frame
                    .until
                    .map(|until| Duration::from_millis(until.saturating_sub(now)));
                outbox.add(
                    frame.id,
                    frame.text,
                    size,
                    ttl,
                    now,
                    frame.requires,
                    frame.tag,
                );
            }
            None => self.to_write.push(Outgoing::Text(frame.text)),
        }
    }

    /// Right before the write queue is written: the sends whose topics are
    /// continuous now, and what the outbox has for the connection, go in it,
    /// in one batch.
    pub(crate) fn before_write(&mut self) {
        self.release_waiting();
        self.write_outbox();
    }

    /// A message dropped before it reached the outbox: its place given back,
    /// and the application told.
    fn dropped(&mut self, frame: &Queued, why: &str) {
        if !frame.counted {
            return;
        }
        if let Some(room) = &self.shared.room {
            room.give_back(frame.size());
        }
        let mut outcomes = crate::outbox::Outcomes::default();
        outcomes.refuse(why, frame.id.clone(), frame.tag);
        self.report_outcomes(outcomes);
    }

    /// What the outbox has to write on this connection goes in its turn.
    fn write_outbox(&mut self) {
        let Some(outbox) = &mut self.outbox else {
            return;
        };
        let mut outcomes = crate::outbox::Outcomes::default();
        let to_write = &mut self.to_write;
        let gate = self.handler.gate();
        let tags = self.shared.tags.as_deref();
        outbox.due(
            crate::outbox::now_ms(),
            &mut outcomes,
            // A window's send, as its window says (the gate let go meanwhile:
            // the owner takes its own lock).
            |topics, tag| match tags {
                Some(tags) if tag != 0 => !tags.holds_back(tag, topics),
                _ => !delivery::lock(gate).holds_back(topics),
            },
            |s, text| to_write.push(Outgoing::Kept { s, text }),
        );
        self.report_outcomes(outcomes);
    }

    /// What became of messages of the outbox, to the application; of a
    /// bridge owner's windows' sends, to the owner.
    fn report_outcomes(&mut self, outcomes: crate::outbox::Outcomes) {
        if !outcomes.delivered.is_empty() {
            self.handler.event(Event::Delivered(outcomes.delivered));
        }
        for (reason, ids) in outcomes.not_delivered {
            self.handler
                .event(Event::NotDelivered(NotDelivered { reason, ids }));
        }
        if !outcomes.tagged.is_empty()
            && let Some(tags) = &self.shared.tags
        {
            tags.outcomes(outcomes.tagged);
        }
    }

    /// The connection wrote the outbox's messages up to and with `last`: a
    /// server that does not answer took them.
    pub(crate) fn wrote(&mut self, last: Option<u64>) {
        if let (Some(last), Some(outbox)) = (last, &mut self.outbox) {
            let outcomes = outbox.wrote(last);
            self.report_outcomes(outcomes);
        }
    }

    /// The application cleared the outbox (the user signed out): what was
    /// sent before goes.
    pub(crate) fn catch_up_clears(&mut self) {
        let clears = self.shared.clears.load(Ordering::Acquire);
        if clears == self.clears {
            return;
        }
        self.clears = clears;
        // Not written yet: it is not.
        self.to_write
            .retain(|outgoing| !matches!(outgoing, Outgoing::Kept { .. }));
        let waiting: Vec<Queued> = self.waiting.drain(..).collect();
        self.waiting_until = u64::MAX;
        for frame in &waiting {
            self.dropped(frame, "cleared");
        }
        if let Some(outbox) = &mut self.outbox {
            let outcomes = outbox.clear();
            self.report_outcomes(outcomes);
        }
    }

    /// The server owes the outbox an answer on this connection (for the
    /// messages it has in hand, or to the hello while messages wait): a
    /// close waits for it, within its own time, and what the answer lets go
    /// out goes first.
    pub(crate) fn awaits_answers(&self) -> bool {
        self.outbox
            .as_ref()
            .is_some_and(crate::outbox::Outbox::owed)
    }

    /// The outbox's hello, for the connection's `client_hello`.
    pub(crate) fn outbox_hello(&self) -> Option<serde_json::Value> {
        self.outbox.as_ref().map(crate::outbox::Outbox::hello)
    }

    /// Whether the connection's task takes messages while there is no
    /// connection: the outbox keeps them.
    pub(crate) fn keeps(&self) -> bool {
        self.outbox.is_some()
    }

    /// Sends waiting for their topics.
    pub(crate) fn waiting(&self) -> usize {
        self.waiting.len()
    }

    /// The sends whose topics are continuous now go, in the order they were
    /// sent, right before the write queue is written; one sent as the last user
    /// goes nowhere.
    pub(crate) fn release_waiting(&mut self) {
        if self.waiting.is_empty() || !self.ready {
            return;
        }
        let users = self.users;
        let now = crate::outbox::now_ms();
        let mut released = Vec::new();
        let mut stale = Vec::new();
        let mut late = Vec::new();
        {
            let gate = delivery::lock(self.handler.gate());
            let mut kept = VecDeque::with_capacity(self.waiting.len());
            self.waiting_until = u64::MAX;
            for frame in self.waiting.drain(..) {
                if frame.user != users {
                    stale.push(frame);
                } else if frame.until.is_some_and(|until| until <= now) {
                    late.push(frame);
                } else if gate.continuous(frame.requires.as_deref().unwrap_or_default()) {
                    released.push(frame);
                } else {
                    self.waiting_until = self.waiting_until.min(frame.until.unwrap_or(u64::MAX));
                    kept.push_back(frame);
                }
            }
            self.waiting = kept;
        }
        for frame in &stale {
            tracing::warn!("[WSE] a message sent as the previous user was dropped");
            self.dropped(frame, "user_changed");
        }
        for frame in &late {
            self.dropped(frame, "expired");
        }
        for frame in released {
            self.keep(frame);
        }
    }

    /// Sends that ran out of time while they waited for their topics go,
    /// `expired`, with a connection or without.
    fn expire_waiting(&mut self, now: u64) {
        if self.waiting_until > now {
            return;
        }
        let mut late = Vec::new();
        let mut kept = VecDeque::with_capacity(self.waiting.len());
        self.waiting_until = u64::MAX;
        for frame in self.waiting.drain(..) {
            if frame.until.is_some_and(|until| until <= now) {
                late.push(frame);
            } else {
                self.waiting_until = self.waiting_until.min(frame.until.unwrap_or(u64::MAX));
                kept.push_back(frame);
            }
        }
        self.waiting = kept;
        for frame in &late {
            self.dropped(frame, "expired");
        }
    }

    /// A new connection: nothing of the last one carries over but the
    /// topics and their positions.
    pub(crate) fn open(&mut self, sealing: Option<Sealing>) {
        self.sealing = sealing;
        self.fatal = None;
        self.ready = false;
        self.server_answers = false;
        self.became_ready = false;
        self.server_recovery = false;
        self.history_ttl = None;
        self.last_alive = None;
        self.alive_since = None;
        self.user_id = None;
        self.requests.clear();
        self.unrecoverable.clear();
        self.unanswered = 0;
        self.to_write.clear();
        for topic in self.topics.values_mut() {
            for hole in &mut topic.holes {
                hole.request = None;
            }
        }
        // The new connection's server names its own key and id.
        if let Ok(mut server_kid) = self.shared.server_kid.lock() {
            *server_kid = None;
        }
        if let Ok(mut connection) = self.shared.connection.lock() {
            *connection = None;
        }
    }

    /// The connection went away.
    pub(crate) fn close(&mut self) {
        // Keys belong to one connection.
        self.sealing = None;
        self.ready = false;
        self.shared.ready.store(false, Ordering::Release);
        // What waits goes on the next one.
        if let Some(outbox) = &mut self.outbox {
            let outcomes = outbox.disconnected();
            self.report_outcomes(outcomes);
        }
        self.requests.clear();
        // A stream that heard nothing for longer than the server keeps one,
        // while this connection had its topic, is gone there: naming it would
        // fail the recovery. Silence counts only within the run of frames
        // read up to the last one, never up to a close read late (after a
        // sleep the server kept publishing), and that last frame may trail
        // its sending by up to the idle limit. Silence while away shows
        // nothing, so nothing is forgotten for it.
        let quiet_before = match (self.history_ttl, self.last_alive, self.alive_since) {
            (Some(ttl), Some(last), Some(since)) => last
                .checked_sub(ttl + QUIET_MARGIN + self.idle_timeout)
                .filter(|before| since <= *before),
            _ => None,
        };
        self.last_alive = None;
        self.alive_since = None;
        for topic in self.topics.values_mut() {
            for hole in &mut topic.holes {
                hole.request = None;
            }
            let since = topic.live_since.take();
            if let Some(before) = quiet_before
                && since.is_some_and(|since| since <= before)
            {
                let holes = &topic.holes;
                topic
                    .streams
                    .forget_quiet(before, |epoch| holes.iter().any(|h| h.epoch == epoch));
            }
        }
    }

    /// The client stops: whatever is held is delivered, its gaps reported.
    pub(crate) fn finish(&mut self) {
        for (topic, epoch) in self.holes_where(|_| true) {
            self.give_up(&topic, epoch, GapReason::Closed);
        }
        // What waits for its topics goes with the client; the outbox's
        // messages too, unless a file keeps them for the next.
        let waiting: Vec<Queued> = self.waiting.drain(..).collect();
        for frame in &waiting {
            self.dropped(frame, "closed");
        }
        if let Some(outbox) = &mut self.outbox {
            let outcomes = outbox.close();
            self.report_outcomes(outcomes);
        }
    }

    /// The holes `pick` picks, by topic and stream.
    fn holes_where(&self, pick: impl Fn(&Hole) -> bool) -> Vec<(Box<str>, u32)> {
        self.topics
            .iter()
            .flat_map(|(name, topic)| {
                topic
                    .holes
                    .iter()
                    .filter(|hole| pick(hole))
                    .map(move |hole| (name.clone(), hole.epoch))
            })
            .collect()
    }

    // -- Frames ------------------------------------------------------------

    /// A JSON message; false when `text` is not one.
    pub(crate) fn on_json(&mut self, text: &str, frame: Option<&Bytes>) -> bool {
        match decode::json_envelope(text) {
            Ok(envelope) => {
                self.on_envelope(envelope, frame);
                true
            }
            Err(e) => {
                tracing::debug!("[WSE] not a message: {e}");
                false
            }
        }
    }

    /// A msgpack message; false when `data` is not one.
    pub(crate) fn on_msgpack(&mut self, data: &[u8], frame: Option<&Bytes>) -> bool {
        match decode::msgpack_envelope(data) {
            Ok(envelope) => {
                self.on_envelope(envelope, frame);
                true
            }
            Err(e) => {
                tracing::debug!("[WSE] not a message: {e}");
                false
            }
        }
    }

    /// A frame that came unsealed on a connection with an end-to-end
    /// session: before the session only the server's answer, an error and
    /// heartbeats may; inside it nothing may.
    pub(crate) fn on_unsealed(&mut self, text: Option<&str>) {
        let envelope = text.and_then(|text| decode::json_envelope(text).ok());
        let open = self.sealing.as_ref().is_some_and(Sealing::is_open);
        let handshake = envelope.as_ref().is_some_and(|e| {
            matches!(
                e.t.as_deref(),
                Some("server_hello" | "error" | "ping" | "PING" | "pong" | "PONG")
            )
        });
        // A server pings inside the session only: an unsealed ping is not
        // answered, or its answer could reach the server once its side of
        // the session is open, and be refused there.
        let ping = envelope
            .as_ref()
            .is_some_and(|e| matches!(e.t.as_deref(), Some("ping" | "PING" | "pong" | "PONG")));
        if ping && !open {
            return;
        }
        match envelope {
            Some(mut envelope) if handshake && !open => {
                // What the handshake needs, never a topic's message nor the
                // application's: nothing unsealed reaches either.
                envelope.tp = None;
                envelope.e = None;
                envelope.o = None;
                self.dispatch(&envelope.into_message(None));
            }
            _ => {
                let why = if open { "inside" } else { "before" };
                self.fail(Error::Encryption(format!(
                    "a plaintext frame {why} the session"
                )));
            }
        }
    }

    /// The connection and the client end with `error`.
    pub(crate) fn fail(&mut self, error: Error) {
        if self.fatal.is_none() {
            tracing::error!("[WSE] {error}: closing, without falling back to plaintext");
            self.fatal = Some(error);
        }
    }

    fn on_envelope<'a>(&mut self, envelope: Envelope<'a>, frame: Option<&'a Bytes>) {
        if envelope.t.as_deref() == Some("signed") {
            self.on_signed(envelope, frame);
            return;
        }
        if envelope.t.as_deref() == Some("batch") {
            match envelope.p {
                Some(Payload::Json(p)) => {
                    for message in decode::json_batch(p).unwrap_or_default() {
                        let _ = self.on_json(message, frame);
                    }
                }
                Some(Payload::Msgpack(p)) => {
                    for message in decode::msgpack_batch(p).unwrap_or_default() {
                        let _ = self.on_msgpack(message, frame);
                    }
                }
                _ => {}
            }
            return;
        }
        let message = envelope.into_message(frame);
        match (message.position, &message.topic) {
            (Some(at), Some(_)) if !is_protocol(message.kind()) => self.on_stamped(message, at),
            _ => self.dispatch(&message),
        }
    }

    /// A message the server signed: checked against the pinned keys, then
    /// delivered as its signed body says, with the proof. Dropped when the
    /// check fails, when the body names another topic than the one it came
    /// on, or another user than this connection's.
    fn on_signed<'a>(&mut self, outer: Envelope<'a>, frame: Option<&'a Bytes>) {
        let (Some(body), Some(sig), Some(kid)) = (outer.sb, outer.sig, outer.kid) else {
            tracing::warn!("[WSE] malformed signed message dropped");
            return;
        };
        let verified = match self.keys.check_server(&kid, &body, &sig) {
            Ok(verified) => verified,
            Err(why) => {
                tracing::warn!("[WSE] signed message dropped: {why}");
                return;
            }
        };
        let Ok(signed) = decode::json_envelope(&body) else {
            tracing::warn!("[WSE] signed message dropped: its body is not a JSON object");
            return;
        };
        if signed.t.is_none() {
            tracing::warn!("[WSE] signed message dropped: its body has no type");
            return;
        }
        match (&outer.tp, &signed.tp) {
            (Some(came_on), Some(signed_for)) if came_on != signed_for => {
                tracing::warn!(
                    "[WSE] message signed for topic {signed_for} that came on {came_on} dropped"
                );
                return;
            }
            // Signed for one connection, not for a topic's subscribers.
            (Some(came_on), None) => {
                tracing::warn!("[WSE] message signed for no topic that came on {came_on} dropped");
                return;
            }
            _ => {}
        }
        // The time the server signed, in milliseconds: the one a reader can
        // trust, written as the other clients write it; and the user the
        // message is for, when it is for one.
        #[derive(serde::Deserialize)]
        struct Signed<'b> {
            ts: Option<u64>,
            #[serde(borrow)]
            to: Option<Cow<'b, str>>,
        }
        let Ok(Signed { ts, to }) = serde_json::from_str::<Signed<'_>>(&body) else {
            tracing::warn!("[WSE] signed message dropped: its body is malformed");
            return;
        };
        if let Some(to) = to
            && self.user_id.as_deref() != Some(&*to)
        {
            tracing::warn!("[WSE] message signed for user {to} dropped: not this connection's");
            return;
        }
        let signed_at = ts.map(|ms| Cow::Owned(rfc3339_ms(ms)));
        let signature = Signature {
            body: body.to_string(),
            sig: sig.into_owned(),
            kid: kid.into_owned(),
            verified,
        };
        let id = signed.n;
        let message = Envelope {
            t: signed.t,
            p: signed.p,
            c: outer.c,
            ts: signed_at,
            tp: outer.tp.or(signed.tp),
            e: outer.e,
            o: outer.o,
            ..Envelope::default()
        };
        let mut message = message.into_message(frame);
        message.id = id;
        message.signature = Some(Arc::new(signature));
        match (message.position, &message.topic) {
            (Some(at), Some(_)) if !is_protocol(message.kind()) => self.on_stamped(message, at),
            _ => self.dispatch(&message),
        }
    }

    /// What reaches the application, the server's protocol messages aside.
    fn dispatch(&mut self, message: &Message<'_>) {
        match message.kind() {
            "ping" | "PING" => self.answer_ping(message),
            "PONG" | "pong" => {}
            "server_ready" => self.on_server_ready(message),
            "server_hello" => self.on_server_hello(message),
            "subscription_update" => self.on_subscription_reply(message),
            "error" => self.on_error(message),
            "outbox" => self.on_outbox(message),
            "ack" => self.on_ack(message),
            "nack" => self.on_nack(message),
            _ => self.handler.message(message),
        }
    }

    // -- Topic messages in order --------------------------------------------

    fn on_stamped(&mut self, message: Message<'_>, at: Position) {
        let name = message.topic.as_deref().unwrap_or_default();
        let topic = match self.topics.get_mut(name) {
            Some(topic) => topic,
            None => self.topics.entry(name.into()).or_default(),
        };
        topic.live_since.get_or_insert(self.clock);
        // A hole in another stream of the topic does not hold this one.
        let held_here = topic.holes.iter().any(|h| h.epoch == at.epoch);
        match topic.streams.check(at, self.clock) {
            Verdict::Duplicate => {}
            Verdict::Deliver => {
                if !self.unrecoverable.is_empty() {
                    self.unrecoverable.remove(name);
                }
                self.handler.message(&message);
                if held_here {
                    self.drain(name, at.epoch);
                }
            }
            Verdict::Gap if held_here => {
                let Some(hole) = topic.holes.iter_mut().find(|h| h.epoch == at.epoch) else {
                    return;
                };
                hole.held
                    .entry(at.offset)
                    .or_insert_with(|| message.to_owned());
                if hole.held.len() > HELD_MAX {
                    self.give_up(name, at.epoch, GapReason::Overflow);
                }
            }
            Verdict::Gap => {
                if self.unrecoverable.get(name) == Some(&at.epoch) {
                    self.unrecoverable.remove(name);
                    self.skip(name, &message, at, GapReason::NotRecovered);
                } else if !self.start_hole(name, &message, at) {
                    self.skip(name, &message, at, GapReason::Unavailable);
                }
            }
        }
    }

    fn recovery_available(&self) -> bool {
        !self.recovery_timeout.is_zero()
            && self.server_recovery
            && self.unanswered < UNANSWERED_MAX
            && self.ready
    }

    /// Holds `message` and asks the server for what is missing before it.
    fn start_hole(&mut self, name: &str, message: &Message<'_>, at: Position) -> bool {
        if !self.recovery_available() {
            return false;
        }
        let Some(topic) = self.topics.get_mut(name) else {
            return false;
        };
        if topic.holes.iter().any(|h| h.epoch == at.epoch)
            || topic.streams.stream(at.epoch).is_none()
        {
            return false;
        }
        let deadline = Instant::now() + self.recovery_timeout;
        let mut held = BTreeMap::new();
        held.insert(at.offset, message.to_owned());
        topic.holes.push(Hole {
            epoch: at.epoch,
            held,
            deadline,
            request: None,
            requested_from: None,
            answered: false,
        });
        self.holes += 1;
        self.next_deadline = Some(self.next_deadline.map_or(deadline, |d| d.min(deadline)));
        self.request_recovery(name, at.epoch);
        true
    }

    /// Asks the server to replay a topic from the last message of the
    /// stream with the hole: it replays that stream, and every other
    /// stream of the topic, from that point.
    fn request_recovery(&mut self, name: &str, epoch: u32) {
        let Some(topic) = self.topics.get_mut(name) else {
            return;
        };
        let Some(hole) = topic.holes.iter_mut().find(|h| h.epoch == epoch) else {
            return;
        };
        if hole.request.is_some() {
            return;
        }
        let Some(from) = topic.streams.stream(epoch) else {
            return;
        };
        let id = self.next_request;
        self.next_request += 1;
        hole.request = Some(id);
        hole.requested_from = Some(from.offset);
        // From the hole's stream (where a server before 3.1 replays from),
        // with where the client stands in each.
        let streams: Vec<Position> = topic.streams.positions().collect();
        let named = streams.iter().map(|s| s.epoch).collect();
        self.requests
            .entry(name.into())
            .or_default()
            .push_back(Request {
                id,
                for_hole: true,
                named,
            });
        let request = subscription(&[name], &[(name, from, streams)]);
        self.to_write.push(Outgoing::Text(request));
    }

    /// Delivers what became in order; closes a filled hole.
    fn drain(&mut self, name: &str, epoch: u32) {
        loop {
            let Some(topic) = self.topics.get_mut(name) else {
                return;
            };
            let Some(hole) = topic.holes.iter_mut().find(|h| h.epoch == epoch) else {
                return;
            };
            let Some(next_offset) = topic
                .streams
                .stream(epoch)
                .and_then(|last| last.offset.checked_add(1))
            else {
                break;
            };
            hole.held = hole.held.split_off(&next_offset);
            let Some(next) = hole.held.remove(&next_offset) else {
                break;
            };
            topic.streams.advance(
                Position {
                    epoch,
                    offset: next_offset,
                },
                self.clock,
            );
            self.handler.message(&next.as_message());
        }
        let filled = self
            .topics
            .get(name)
            .and_then(|t| t.holes.iter().find(|h| h.epoch == epoch))
            .is_some_and(|h| h.held.is_empty());
        if filled {
            self.close_hole(name, epoch);
            tracing::info!("[WSE] recovered the gap on {name}");
        }
    }

    fn close_hole(&mut self, name: &str, epoch: u32) -> Option<Hole> {
        let holes = &mut self.topics.get_mut(name)?.holes;
        let index = holes.iter().position(|h| h.epoch == epoch)?;
        let hole = holes.swap_remove(index);
        self.holes -= 1;
        if self.next_deadline == Some(hole.deadline) || self.holes == 0 {
            self.next_deadline = self.first_deadline();
        }
        Some(hole)
    }

    /// The deadline of the hole that gives up first.
    fn first_deadline(&self) -> Option<Instant> {
        self.topics
            .values()
            .flat_map(|t| t.holes.iter().map(|h| h.deadline))
            .min()
    }

    /// Stops waiting: reports what is missing, delivers what is held.
    fn give_up(&mut self, name: &str, epoch: u32, reason: GapReason) {
        let Some(hole) = self.close_hole(name, epoch) else {
            return;
        };
        let mut last = self
            .topics
            .get(name)
            .and_then(|t| t.streams.stream(epoch))
            .map(|p| p.offset);
        for (offset, message) in hole.held {
            if last.is_some_and(|last| offset <= last) {
                continue;
            }
            if let Some(first) = last.and_then(|last| last.checked_add(1))
                && offset > first
            {
                self.report(name, epoch, Some(first), Some(offset - 1), reason);
            }
            if let Some(topic) = self.topics.get_mut(name) {
                topic
                    .streams
                    .advance(Position { epoch, offset }, self.clock);
            }
            self.handler.message(&message.as_message());
            last = Some(offset);
        }
    }

    /// Takes a gap at once: reports it, delivers `message`.
    fn skip(&mut self, name: &str, message: &Message<'_>, at: Position, reason: GapReason) {
        let Some(topic) = self.topics.get_mut(name) else {
            return;
        };
        let last = topic.streams.stream(at.epoch);
        topic.streams.advance(at, self.clock);
        if let Some(first) = last.and_then(|last| last.offset.checked_add(1))
            && at.offset > first
        {
            self.report(name, at.epoch, Some(first), Some(at.offset - 1), reason);
        }
        self.handler.message(message);
    }

    fn report(
        &mut self,
        topic: &str,
        epoch: u32,
        first: Option<u64>,
        last: Option<u64>,
        reason: GapReason,
    ) {
        let gap = Gap {
            topic: topic.to_owned(),
            epoch,
            first,
            last,
            reason,
        };
        tracing::warn!(
            "[WSE] {topic} lost offsets {first:?}..{last:?} ({:?} messages, {reason:?})",
            gap.missed()
        );
        self.handler.event(Event::Gap(gap));
    }

    /// When the next hole gives up waiting.
    pub(crate) fn next_deadline(&self) -> Option<Instant> {
        match (self.next_deadline, self.outbox_deadline()) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }

    /// When the first message of the outbox not written yet runs out (or a
    /// rewrite of its store owed can go), or a send waiting for its topics.
    pub(crate) fn outbox_deadline(&self) -> Option<Instant> {
        let outbox = self
            .outbox
            .as_ref()
            .and_then(crate::outbox::Outbox::deadline);
        let waiting = (self.waiting_until != u64::MAX).then(|| {
            let left = self.waiting_until.saturating_sub(crate::outbox::now_ms());
            Instant::now() + Duration::from_millis(left)
        });
        match (outbox, waiting) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }

    /// Messages of the outbox that waited too long to be sent go, and the
    /// application hears of them; a rewrite of its store owed goes; sends
    /// that ran out of time waiting for their topics go.
    pub(crate) fn expire_outbox(&mut self, now: Instant) {
        if let Some(outbox) = &mut self.outbox
            && outbox.deadline().is_some_and(|at| at <= now)
        {
            let mut outcomes = crate::outbox::Outcomes::default();
            outbox.expire(crate::outbox::now_ms(), &mut outcomes);
            outbox.heal(now);
            self.report_outcomes(outcomes);
        }
        self.expire_waiting(crate::outbox::now_ms());
    }

    /// Holes whose wait is over give up; messages of the outbox that waited
    /// too long to be sent go.
    pub(crate) fn on_deadline(&mut self, now: Instant) {
        self.clock = now;
        self.expire_outbox(now);
        // Nothing came back for these: the server application may not
        // answer recovery requests. After a few, the client stops asking.
        let unanswered = self
            .holes_where(|h| h.deadline <= now && h.request.is_some() && !h.answered)
            .len();
        self.unanswered = self
            .unanswered
            .saturating_add(u32::try_from(unanswered).unwrap_or(u32::MAX));
        for (name, epoch) in self.holes_where(|h| h.deadline <= now) {
            self.give_up(&name, epoch, GapReason::Timeout);
        }
    }

    // -- Subscriptions -----------------------------------------------------

    /// Subscribes to topics not subscribed yet, from where the client
    /// stands in them.
    pub(crate) fn subscribe(&mut self, topics: Vec<String>) {
        let new: Vec<String> = topics
            .into_iter()
            .filter(|t| !t.is_empty())
            .filter(|t| self.wanted.insert(t.clone()))
            .collect();
        if self.ready && !new.is_empty() {
            self.rewind_to_committed(&new);
            self.send_subscription(&new);
        }
    }

    /// Where the application says the recovery of `topics` starts (what it
    /// committed it applied): delivery steps back to it, so what came after
    /// is taken again when it is replayed.
    fn rewind_to_committed(&mut self, topics: &[String]) {
        let Some(committed) = self.committed.clone() else {
            return;
        };
        let Some(positions) = committed(self.user_id.as_deref()) else {
            return;
        };
        let now = self.clock;
        let mut holes = 0;
        for name in topics {
            let topic = self.topics.entry(name.as_str().into()).or_default();
            holes += topic.holes.len();
            topic.holes.clear();
            topic.streams = Streams::default();
            for at in positions.get(name.as_str()).into_iter().flatten() {
                topic.streams.advance(*at, now);
            }
        }
        self.holes -= holes;
        self.next_deadline = self.first_deadline();
    }

    /// Unsubscribes, and forgets where the client stood in the topics: a
    /// later subscription starts from the next message.
    pub(crate) fn unsubscribe(&mut self, topics: Vec<String>) {
        for topic in &topics {
            self.wanted.remove(topic);
            if let Some(state) = self.topics.remove(topic.as_str())
                && !state.holes.is_empty()
            {
                self.holes -= state.holes.len();
                self.next_deadline = self.first_deadline();
            }
            self.requests.remove(topic.as_str());
            self.unrecoverable.remove(topic.as_str());
        }
        if self.ready && !topics.is_empty() {
            let mut text = String::from(
                r#"{"c":"WSE","t":"subscription_update","p":{"action":"unsubscribe","topics":"#,
            );
            push_json(&mut text, &topics);
            text.push_str("},\"v\":1}");
            self.to_write.push(Outgoing::Text(text));
        }
    }

    /// A subscription request for `topics`, with the positions the client
    /// has of them.
    fn send_subscription(&mut self, topics: &[String]) {
        let mut positions = Vec::new();
        if self.server_recovery {
            for topic in topics {
                let Some(t) = self.topics.get(topic.as_str()) else {
                    continue;
                };
                if let Some(at) = t.streams.position() {
                    positions.push((
                        topic.as_str(),
                        at,
                        t.streams.positions().collect::<Vec<_>>(),
                    ));
                }
            }
        }
        let now = Instant::now();
        for (topic, at, streams) in &positions {
            let (topic, at) = (*topic, *at);
            let id = self.next_request;
            self.next_request += 1;
            let named = streams.iter().map(|s| s.epoch).collect();
            let hole = self
                .topics
                .get_mut(topic)
                .and_then(|t| t.holes.iter_mut().find(|h| h.epoch == at.epoch));
            let for_hole = hole.is_some();
            if let Some(hole) = hole {
                hole.request = Some(id);
                hole.requested_from = Some(at.offset);
                // The wait starts again with the request: the replay comes
                // after it, not before.
                hole.deadline = now + self.recovery_timeout;
            }
            self.requests
                .entry(topic.into())
                .or_default()
                .push_back(Request {
                    id,
                    for_hole,
                    named,
                });
        }
        if self.holes > 0 {
            self.next_deadline = self.first_deadline();
        }
        let names: Vec<&str> = topics.iter().map(String::as_str).collect();
        self.to_write
            .push(Outgoing::Text(subscription(&names, &positions)));
        // Holes in the topics' other streams ask for themselves.
        for (topic, epoch) in self.holes_where(|h| h.request.is_none()) {
            if topics.iter().any(|t| **t == *topic) {
                self.request_recovery(&topic, epoch);
            }
        }
    }

    fn on_subscription_reply(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Reply {
            success_topics: Vec<String>,
            failed_topics: Vec<String>,
            recovery: BTreeMap<String, Info>,
        }
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Info {
            epoch: Option<String>,
            offset: Option<u64>,
            recovered: Option<bool>,
            count: u64,
            /// From 3.1: each stream the server holds, epoch -> last offset.
            streams: Option<BTreeMap<String, u64>>,
        }
        let Ok(reply) = message.payload::<Reply>() else {
            tracing::debug!("[WSE] unreadable subscription reply dropped");
            return;
        };
        if !reply.failed_topics.is_empty() {
            tracing::warn!("[WSE] subscription refused for {:?}", reply.failed_topics);
        }
        if self.ready {
            for name in &reply.success_topics {
                self.topics
                    .entry(name.as_str().into())
                    .or_default()
                    .live_since
                    .get_or_insert(self.clock);
            }
        }
        let mut recovery = Vec::with_capacity(reply.recovery.len());
        for (topic, info) in &reply.recovery {
            let epoch = info.epoch.as_deref().and_then(epoch_of);
            let recovered = info.recovered.unwrap_or(true);
            let streams: Option<Vec<Position>> = info.streams.as_ref().map(|streams| {
                streams
                    .iter()
                    .filter_map(|(epoch, offset)| {
                        Some(Position {
                            epoch: epoch_of(epoch)?,
                            offset: *offset,
                        })
                    })
                    .collect()
            });
            let request = self.on_recovery_reply(
                topic,
                recovered,
                epoch,
                info.epoch.is_some(),
                info.offset,
                streams.is_some(),
            );
            if let Some(streams) = &streams {
                self.take_streams(topic, request.as_ref(), streams, recovered);
            }
            recovery.push(Recovery {
                topic: topic.clone(),
                recovered,
                count: info.count,
                position: epoch
                    .zip(info.offset)
                    .map(|(epoch, offset)| Position { epoch, offset }),
            });
        }
        self.handler.event(Event::Subscribed(Subscribed {
            topics: reply.success_topics,
            failed: reply.failed_topics,
            recovery,
        }));
    }

    /// The answer to the oldest request out for `name`: which one it was.
    fn on_recovery_reply(
        &mut self,
        name: &str,
        recovered: bool,
        epoch: Option<u32>,
        has_epoch: bool,
        offset: Option<u64>,
        listed_streams: bool,
    ) -> Option<Request> {
        let Some(request) = self.requests.get_mut(name).and_then(VecDeque::pop_front) else {
            return None; // an answer to a plain subscription: nothing moves
        };
        if self.requests.get(name).is_some_and(VecDeque::is_empty) {
            self.requests.remove(name);
        }
        self.unanswered = 0;
        let hole = self
            .topics
            .get_mut(name)
            .and_then(|t| t.holes.iter_mut().find(|h| h.request == Some(request.id)));
        if let Some(hole) = hole {
            hole.request = None;
            hole.answered = true;
            let (hole_epoch, requested_from) = (hole.epoch, hole.requested_from);
            // The replay came before this answer.
            self.drain(name, hole_epoch);
            let Some(topic) = self
                .topics
                .get(name)
                .filter(|t| t.holes.iter().any(|h| h.epoch == hole_epoch))
            else {
                return Some(request); // filled
            };
            let progressed = topic
                .streams
                .stream(hole_epoch)
                .zip(requested_from)
                .is_some_and(|(at, from)| at.offset > from);
            // A replay the server's outbound budget cut short answers
            // `recovered: false` in the same history, past where it was
            // asked from: ask again from where it got to.
            if progressed && (recovered || epoch == Some(hole_epoch)) {
                self.request_recovery(name, hole_epoch);
            } else {
                let reason = if recovered {
                    GapReason::Incomplete
                } else {
                    GapReason::NotRecovered
                };
                self.give_up(name, hole_epoch, reason);
            }
            return Some(request);
        }
        if request.for_hole {
            return Some(request); // the answer for a hole settled meanwhile
        }
        // The replay moved the position as it came; a server that lists its
        // streams says with them what was missed.
        if recovered || listed_streams {
            return Some(request);
        }
        let Some(at) = self.topics.get(name).and_then(|t| t.streams.position()) else {
            return Some(request);
        };
        match epoch {
            // The server has no history of the topic any more, or a new one:
            // it restarted.
            None if !has_epoch => self.report(name, at.epoch, None, None, GapReason::EpochChanged),
            Some(epoch) if epoch != at.epoch => {
                self.report(name, epoch, None, None, GapReason::EpochChanged)
            }
            _ => {
                if offset.is_some_and(|offset| offset <= at.offset) {
                    return Some(request); // nothing was missed
                }
                // The next gap of this stream is reported at once instead of
                // asked for: the server cannot replay it.
                self.unrecoverable.insert(name.into(), at.epoch);
            }
        }
        Some(request)
    }

    /// The streams the server holds of a topic, as its reply lists them
    /// (from 3.1): where the client starts in each one it did not know;
    /// when a recovery did not recover, what each one it knew lost. A stream
    /// the request named that the server does not hold is forgotten: naming
    /// it again would fail every later recovery.
    fn take_streams(
        &mut self,
        name: &str,
        request: Option<&Request>,
        listed: &[Position],
        recovered: bool,
    ) {
        let now = self.clock;
        let lost = !recovered && request.is_some_and(|r| !r.for_hole);
        let mut reports: Vec<(u32, Option<u64>, Option<u64>)> = Vec::new();
        let topic = self.topics.entry(name.into()).or_default();
        let holes: Vec<u32> = topic.holes.iter().map(|h| h.epoch).collect();
        for at in listed {
            if holes.contains(&at.epoch) {
                continue;
            }
            match topic.streams.stream(at.epoch) {
                None => topic.streams.raise(*at, now),
                Some(own) if lost && at.offset > own.offset => {
                    reports.push((at.epoch, own.offset.checked_add(1), Some(at.offset)));
                    topic.streams.raise(*at, now);
                }
                Some(_) => {}
            }
        }
        for &epoch in request.map(|r| r.named.as_slice()).unwrap_or_default() {
            if holes.contains(&epoch) || listed.iter().any(|at| at.epoch == epoch) {
                continue;
            }
            if lost && let Some(own) = topic.streams.stream(epoch) {
                reports.push((epoch, own.offset.checked_add(1), None));
            }
            topic.streams.forget(epoch);
        }
        // Not recovered with nothing to show for it: the server cannot show
        // the client missed nothing.
        if lost
            && reports.is_empty()
            && let Some(at) = topic.streams.position()
        {
            reports.push((at.epoch, None, None));
        }
        for (epoch, first, last) in reports {
            self.report(name, epoch, first, last, GapReason::NotRecovered);
        }
    }

    // -- The server's protocol messages --------------------------------------

    fn answer_ping(&mut self, ping: &Message<'_>) {
        #[derive(serde::Deserialize)]
        struct Ping<'a> {
            #[serde(borrow)]
            server_time: Option<&'a serde_json::value::RawValue>,
            #[serde(borrow)]
            timestamp: Option<&'a serde_json::value::RawValue>,
        }
        let now = now_ms();
        let echoed = ping
            .payload::<Ping<'_>>()
            .ok()
            .and_then(|p| {
                p.server_time
                    .or(p.timestamp)
                    .map(|raw| raw.get().to_owned())
            })
            .unwrap_or_else(|| now.to_string());
        let pong = format!(
            r#"{{"c":"WSE","t":"PONG","p":{{"client_timestamp":{now},"server_timestamp":{echoed}}},"v":1}}"#
        );
        self.to_write.push(Outgoing::Handshake(pong));
    }

    fn on_server_ready(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Ready {
            connection_id: Option<String>,
            details: Details,
        }
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Details {
            connection_id: Option<String>,
            user_id: Option<String>,
            features: Features,
            signing: Option<SigningKey>,
            cnf: Option<Cnf>,
        }
        #[derive(serde::Deserialize)]
        struct Cnf {
            jkt: Option<String>,
        }
        let ready = message.payload::<Ready>().unwrap_or_default();
        // A session bound to this client's key: the server, sealed, says so.
        // Otherwise the token at the upgrade was not this client's (one put
        // in its place on the way), or names no key.
        if self.sealing.is_some()
            && let Some(own) = self.keys.bound_thumbprint()
            && ready.details.cnf.as_ref().and_then(|c| c.jkt.as_deref()) != Some(own.as_str())
        {
            self.fail(Error::Auth(
                "the server did not bind the session to this client's key (cnf); for a token \
                 that names no key, set Encryption::bind_session to false"
                    .to_owned(),
            ));
            return;
        }
        // Sealed in an end-to-end session: what it names can be trusted.
        if let Some(signing) = ready.details.signing {
            self.take_signing_key(signing.kid);
        }
        let connection_id = ready
            .connection_id
            .or(ready.details.connection_id)
            .unwrap_or_default();
        if ready.details.features.recovery {
            self.server_recovery = true;
        }
        if let Some(ttl) = ready.details.features.history_ttl {
            self.history_ttl = Some(Duration::from_secs(ttl));
        }
        self.server_answers = ready.details.features.acks;
        self.take_connection(connection_id, ready.details.user_id);
    }

    /// The server's answer to the outbox's hello: what it took, and its
    /// name. What it took is delivered; the rest goes again, in order,
    /// before anything new.
    fn on_outbox(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Answer {
            acked: u64,
            node: String,
            refused: Vec<Refused>,
            /// How far past `acked` the server cannot tell whether it took
            /// a message (none: it can tell all).
            unsure: u64,
        }
        #[derive(serde::Deserialize)]
        struct Refused {
            s: u64,
            from: Option<u64>,
            code: Option<String>,
        }
        let answer = message.payload::<Answer>().unwrap_or_default();
        let refused: Vec<(u64, u64, &str)> = answer
            .refused
            .iter()
            .map(|r| {
                let why = r.code.as_deref().unwrap_or("refused");
                (r.from.unwrap_or(r.s), r.s, why)
            })
            .collect();
        if let Some(outbox) = &mut self.outbox {
            let outcomes = outbox.answered(answer.acked, &refused, &answer.node, answer.unsure);
            self.report_outcomes(outcomes);
        }
    }

    /// The server took every message up to and with `s`.
    fn on_ack(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize)]
        struct Ack {
            s: u64,
        }
        if let (Ok(ack), Some(outbox)) = (message.payload::<Ack>(), &mut self.outbox) {
            let outcomes = outbox.acked(ack.s);
            self.report_outcomes(outcomes);
        }
    }

    /// The server refused messages `from` to `s` for good.
    fn on_nack(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize)]
        struct Nack {
            s: u64,
            from: Option<u64>,
            code: Option<String>,
        }
        if let (Ok(nack), Some(outbox)) = (message.payload::<Nack>(), &mut self.outbox) {
            let why = nack.code.as_deref().unwrap_or("refused");
            let outcomes = outbox.refused(nack.from.unwrap_or(nack.s), nack.s, why);
            self.report_outcomes(outcomes);
        }
    }

    fn on_server_hello(&mut self, message: &Message<'_>) {
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Hello {
            server_version: Option<String>,
            connection_id: Option<String>,
            features: Features,
            signing: Option<SigningKey>,
            e2e: Option<serde_json::Value>,
        }
        let hello = message.payload::<Hello>().unwrap_or_default();
        if hello.features.recovery {
            self.server_recovery = true;
        }
        if let Some(ttl) = hello.features.history_ttl {
            self.history_ttl = Some(Duration::from_secs(ttl));
        }
        if let Some(sealing) = &mut self.sealing {
            let answer = hello
                .e2e
                .as_ref()
                .ok_or_else(|| Error::Encryption("the server did not answer the offer".to_owned()))
                .and_then(|e2e| {
                    sealing.accept(
                        &self.keys,
                        e2e,
                        hello.connection_id.as_deref().unwrap_or(""),
                    )
                });
            match answer {
                Ok(()) => {
                    tracing::info!("[WSE] end-to-end session open");
                    // Bound to this client's key: its proof is the first
                    // message the session seals.
                    let th = self.sealing.as_ref().and_then(Sealing::transcript_hash);
                    match th.map(|th| self.keys.prove_session(&th)).transpose() {
                        Ok(Some(Some(proof))) => self.to_write.insert(0, Outgoing::Text(proof)),
                        Ok(_) => {}
                        Err(error) => self.fail(error),
                    }
                }
                Err(error) => self.fail(error),
            }
            // server_hello comes unsealed, and anyone in between may have
            // written it: only the sealed server_ready takes the connection
            // and names the signing key. Nothing goes before it.
            return;
        }
        if let Some(signing) = hello.signing {
            self.take_signing_key(signing.kid);
        }
        // A 3.x server sends server_ready, at once or when its application
        // takes the connection; an older one may never send it.
        let older = hello
            .server_version
            .as_deref()
            .and_then(|v| v.split('.').next())
            .and_then(|major| major.parse::<u32>().ok())
            .is_some_and(|major| major < 3);
        if older && !self.ready {
            self.take_connection(hello.connection_id.unwrap_or_default(), None);
        }
    }

    /// The server's signing key: what this client's signed messages are
    /// for. One it pins, when it pins any.
    fn take_signing_key(&mut self, kid: String) {
        let kid = if self.keys.signs_for(&kid) {
            Some(kid)
        } else {
            tracing::warn!("[WSE] the server names signing key {kid}, which is not pinned");
            None
        };
        if let Ok(mut server_kid) = self.shared.server_kid.lock() {
            *server_kid = kid;
        }
    }

    /// The server took the connection: subscribe again, tell the
    /// application.
    fn take_connection(&mut self, connection_id: String, user_id: Option<String>) {
        if self.ready {
            return;
        }
        self.ready = true;
        self.became_ready = true;
        if let Ok(mut connection) = self.shared.connection.lock() {
            *connection = Some((connection_id.clone(), user_id.clone()));
        }
        if self.last_user.as_ref().is_some_and(|last| *last != user_id) {
            self.forget_user();
        }
        self.last_user = Some(user_id.clone());
        self.user_id.clone_from(&user_id);
        self.connections += 1;
        self.shared
            .connections
            .store(self.connections, Ordering::Release);
        self.shared.ready.store(true, Ordering::Release);
        let topics: Vec<String> = self.wanted.iter().cloned().collect();
        if !topics.is_empty() {
            self.rewind_to_committed(&topics);
            self.send_subscription(&topics);
        }
        // The outbox: another user's go, and the rest goes once the server
        // said what it took (or at once, to a server that does not answer).
        if let Some(outbox) = &mut self.outbox {
            let outcomes = outbox.connected(user_id.as_deref(), crate::outbox::now_ms());
            outbox.server_answers(self.server_answers);
            self.report_outcomes(outcomes);
        }
        tracing::info!(
            "[WSE] connected as {connection_id} (recovery: {})",
            self.server_recovery
        );
        let reconnected = std::mem::replace(&mut self.connected_before, true);
        // Connected before the application hears it, so that a status it
        // reads then says so.
        if let Some(status) = &self.status {
            status.send_replace(Status::Connected);
        }
        self.handler.event(Event::Connected(Connected {
            connection_id,
            user_id,
            reconnected,
            recovery: self.server_recovery,
        }));
    }

    /// The server took the connection for another user than the last: what
    /// the last one sent and was not sent yet, and where its topics stood,
    /// are not this one's.
    fn forget_user(&mut self) {
        self.users += 1;
        self.shared.users.store(self.users, Ordering::Release);
        self.topics.clear();
        self.unrecoverable.clear();
        self.holes = 0;
        self.next_deadline = None;
    }

    fn on_error(&mut self, message: &Message<'_>) {
        let details = message.payload_value().unwrap_or_default();
        let field = |name: &str| {
            details
                .get(name)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_owned()
        };
        let (code, text) = (field("code"), field("message"));
        tracing::warn!("[WSE] server error {code}: {text}");
        if self.sealing.is_some()
            && matches!(code.as_str(), "E2E_UNSUPPORTED" | "KEY_EXCHANGE_FAILED")
        {
            // Another attempt would be refused the same way.
            self.fail(Error::Encryption(format!(
                "the server refused the session: {text}"
            )));
        }
        self.handler.event(Event::ServerError(ServerError {
            code,
            message: text,
            details,
        }));
    }
}

/// Milliseconds since the Unix epoch in RFC 3339, UTC, as the TypeScript
/// client's `toISOString()` writes them.
fn rfc3339_ms(ms: u64) -> String {
    let secs = ms / 1000;
    let (days, of_day) = (secs / 86_400, secs % 86_400);
    // Days since the epoch to a civil date (Howard Hinnant's algorithm).
    let z = days as i64 + 719_468;
    let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        of_day / 3600,
        of_day % 3600 / 60,
        of_day % 60,
        ms % 1000
    )
}

/// The server's own messages: never a topic's, whatever they carry.
fn is_protocol(kind: &str) -> bool {
    matches!(
        kind,
        "ping"
            | "PING"
            | "pong"
            | "PONG"
            | "server_ready"
            | "server_hello"
            | "subscription_update"
            | "error"
            | "outbox"
            | "ack"
            | "nack"
    )
}

#[derive(serde::Deserialize, Default)]
#[serde(default)]
struct Features {
    recovery: bool,
    /// The server answers the outbox (3.2).
    acks: bool,
    /// Seconds a stream that receives nothing stays recoverable (3.1).
    history_ttl: Option<u64>,
}

#[derive(serde::Deserialize)]
struct SigningKey {
    kid: String,
}

/// A `subscription_update` subscribing to `topics`, recovering from
/// `positions`: per topic, its last message and where it stands in each
/// stream.
fn subscription(topics: &[&str], positions: &[(&str, Position, Vec<Position>)]) -> String {
    let mut text =
        String::from(r#"{"c":"WSE","t":"subscription_update","p":{"action":"subscribe","topics":"#);
    push_json(&mut text, topics);
    if !positions.is_empty() {
        text.push_str(r#","recover":true,"recovery":{"#);
        for (i, (topic, at, streams)) in positions.iter().enumerate() {
            if i > 0 {
                text.push(',');
            }
            push_json(&mut text, topic);
            let _ = write!(
                text,
                r#":{{"epoch":"{:08x}","offset":{}"#,
                at.epoch, at.offset
            );
            if !streams.is_empty() {
                text.push_str(r#","streams":{"#);
                for (j, stream) in streams.iter().enumerate() {
                    if j > 0 {
                        text.push(',');
                    }
                    let _ = write!(text, r#""{:08x}":{}"#, stream.epoch, stream.offset);
                }
                text.push('}');
            }
            text.push('}');
        }
        text.push('}');
    }
    text.push_str("},\"v\":1}");
    text
}

fn push_json<T: serde::Serialize + ?Sized>(text: &mut String, value: &T) {
    // Strings and lists of strings: always encodable.
    text.push_str(&serde_json::to_string(value).unwrap_or_else(|_| "null".to_owned()));
}

/// What the machine's two clocks say about a sleep between two readings: a
/// monotonic clock stands still while the machine sleeps (Linux, macOS),
/// the wall clock does not. A connection that crossed a sleep may be gone
/// without a word (a router that forgot it): the idle check, on the
/// monotonic clock, would see it only after `idle_timeout` of waking time.
/// In a browser the page's own socket and events see to that.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) struct SleepWatch {
    wall: web_time::SystemTime,
    mono: Instant,
}

#[cfg(not(target_arch = "wasm32"))]
impl SleepWatch {
    pub(crate) fn new(wall: web_time::SystemTime, mono: Instant) -> Self {
        Self { wall, mono }
    }

    /// How long the machine slept since the last reading, when that is at
    /// least `at_least`. A wall clock set back, or a skew shorter than
    /// `at_least`, is no sleep.
    pub(crate) fn slept(
        &mut self,
        wall: web_time::SystemTime,
        mono: Instant,
        at_least: Duration,
    ) -> Option<Duration> {
        let walled = wall.duration_since(self.wall).unwrap_or(Duration::ZERO);
        let ran = mono.saturating_duration_since(self.mono);
        self.wall = wall;
        self.mono = mono;
        let gap = walled.saturating_sub(ran);
        (gap >= at_least).then_some(gap)
    }
}

pub(crate) fn now_ms() -> u64 {
    web_time::SystemTime::now()
        .duration_since(web_time::UNIX_EPOCH)
        .map_or(0, |d| d.as_millis() as u64)
}

/// The client's heartbeat as a message: where the WebSocket has no pings of
/// its own to send (the browser's), and in an end-to-end session, where only
/// a sealed answer shows the server is alive.
pub(crate) fn ping() -> String {
    format!(
        r#"{{"c":"WSE","t":"ping","p":{{"timestamp":{}}},"v":1}}"#,
        now_ms()
    )
}

/// The first frame of a connection, with the end-to-end offer when it
/// opens a session.
pub(crate) fn client_hello(
    compression: bool,
    e2e: Option<serde_json::Value>,
    outbox: Option<serde_json::Value>,
) -> String {
    let mut p = serde_json::json!({
        "client_version": env!("CARGO_PKG_VERSION"),
        "protocol_version": 1,
        "features": {
            "compression": compression,
            "encryption": e2e.is_some(),
            "batching": true,
        },
    });
    if let Some(e2e) = e2e {
        p["e2e"] = e2e;
    }
    if let Some(outbox) = outbox {
        p["outbox"] = outbox;
    }
    serde_json::json!({"c": "WSE", "t": "client_hello", "p": p, "v": 1}).to_string()
}

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

    /// What reached the application.
    #[derive(Default)]
    struct Seen {
        offsets: Vec<u64>,
        events: Vec<Event>,
    }

    impl Handler for Seen {
        fn message(&mut self, message: &Message<'_>) {
            if let Some(at) = message.position() {
                self.offsets.push(at.offset);
            }
        }
        fn event(&mut self, event: Event) {
            self.events.push(event);
        }
    }

    fn session(recovery_timeout: Duration) -> Session<Seen> {
        let shared = Arc::new(Shared::new(None, None));
        let keys = Arc::new(Keys::from_config(&crate::Config::new("ws://x")).unwrap());
        let mut session = Session::new(
            Delivered::passing(Seen::default()),
            shared,
            keys,
            &["t".to_owned()],
            recovery_timeout,
            Duration::from_secs(40),
        );
        session.open(None);
        session
    }

    fn ready(session: &mut Session<Seen>, recovery: bool) {
        ready_as(session, "u", recovery);
    }

    fn ready_as(session: &mut Session<Seen>, user: &str, recovery: bool) {
        session.on_json(
            &format!(
                r#"{{"c":"WSE","t":"server_ready","p":{{"details":{{"connection_id":"c1","user_id":"{user}","features":{{"recovery":{recovery}}}}}}}}}"#
            ),
            None,
        );
    }

    fn feed(session: &mut Session<Seen>, epoch: &str, offsets: &[u64]) {
        for o in offsets {
            session.on_json(
                &format!(r#"{{"tp":"t","e":"{epoch}","o":{o},"c":"U","t":"m","p":{{}}}}"#),
                None,
            );
        }
        session.alive_at(session.clock);
    }

    /// The server's frames go on every 15 seconds, `n` times (the
    /// heartbeat's PONGs).
    fn pongs(session: &mut Session<Seen>, n: u32) {
        for _ in 0..n {
            session.clock += Duration::from_secs(15);
            session.alive_at(session.clock);
        }
    }

    /// The texts in the write queue, taken out.
    fn sent(session: &mut Session<Seen>) -> Vec<serde_json::Value> {
        session
            .to_write
            .drain(..)
            .map(|outgoing| match outgoing {
                Outgoing::Text(text) | Outgoing::Handshake(text) => {
                    serde_json::from_str(&text).unwrap()
                }
                Outgoing::Kept { text, .. } => serde_json::from_str(&text).unwrap(),
            })
            .collect()
    }

    fn gaps(session: &Session<Seen>) -> Vec<(Option<u64>, Option<u64>, GapReason)> {
        session
            .handler
            .inner
            .events
            .iter()
            .filter_map(|e| match e {
                Event::Gap(g) => Some((g.first, g.last, g.reason)),
                _ => None,
            })
            .collect()
    }

    const E: &str = "0000000a";

    /// The server's answer to a recovery request for `t`.
    fn reply(s: &mut Session<Seen>, epoch: &str, offset: u64, recovered: bool, count: u64) {
        s.on_json(
            &format!(
                r#"{{"c":"WSE","t":"subscription_update","p":{{"success_topics":["t"],"recovery":{{"t":{{"epoch":"{epoch}","offset":{offset},"recovered":{recovered},"count":{count}}}}}}}}}"#
            ),
            None,
        );
    }

    #[test]
    fn an_unsealed_handshake_frame_never_reaches_a_topic() {
        let mut s = session(Duration::from_secs(3));
        // Before a session: a ping with a topic's stamp, written by whoever
        // sits in between.
        s.on_unsealed(Some(
            r#"{"t":"ping","tp":"t","e":"0000000a","o":18446744073709551615,"p":{}}"#,
        ));
        assert!(s.handler.inner.offsets.is_empty());
        assert!(
            s.topics
                .get("t")
                .and_then(|t| t.streams.position())
                .is_none()
        );
        // Not answered either: a server pings inside the session only.
        assert!(s.to_write.is_empty());
        // A stamped protocol message moves no topic either.
        ready(&mut s, true);
        s.on_json(
            r#"{"t":"error","tp":"t","e":"0000000a","o":99,"p":{"code":"X","message":"y"}}"#,
            None,
        );
        feed(&mut s, E, &[1]);
        assert_eq!(s.handler.inner.offsets, [1]);
    }

    #[test]
    fn a_recovery_starts_where_the_application_committed() {
        use crate::message::Position;
        let committed: Arc<std::sync::Mutex<BTreeMap<String, Vec<Position>>>> = Arc::default();
        let positions = Arc::clone(&committed);
        let mut s = session(Duration::from_secs(3));
        s.committed = Some(Arc::new(move |user: Option<&str>| {
            assert_eq!(user, Some("u"));
            Some(positions.lock().unwrap().clone())
        }));
        ready(&mut s, true);
        sent(&mut s);
        feed(&mut s, E, &[1, 2, 3, 4]);
        // The application applied up to 2 when the connection went.
        committed.lock().unwrap().insert(
            "t".to_owned(),
            vec![Position {
                epoch: 0xa,
                offset: 2,
            }],
        );
        s.close();
        s.open(None);
        ready(&mut s, true);
        let request = &sent(&mut s)[0];
        assert_eq!(
            request["p"]["recovery"]["t"]["streams"],
            serde_json::json!({ E: 2 })
        );
        // 3 and 4 come again, and are taken.
        feed(&mut s, E, &[3, 4, 5]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 3, 4, 3, 4, 5]);
    }

    #[test]
    fn a_late_answer_settles_only_its_own_hole() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        sent(&mut s);
        feed(&mut s, E, &[1, 3]);
        // The replay fills the hole before its answer comes.
        feed(&mut s, E, &[2]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 3]);
        // Another hole, another request.
        feed(&mut s, E, &[5]);
        assert_eq!(sent(&mut s).len(), 2);
        // The first request's answer is not the second's.
        reply(&mut s, E, 3, true, 1);
        assert!(gaps(&s).is_empty());
        feed(&mut s, E, &[4]);
        reply(&mut s, E, 5, true, 1);
        assert_eq!(s.handler.inner.offsets, [1, 2, 3, 4, 5]);
        assert!(gaps(&s).is_empty());
        assert_eq!(s.next_deadline(), None);
    }

    #[test]
    fn gaps_in_two_streams_of_a_topic_are_recovered_each() {
        const F: &str = "0000000b";
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        sent(&mut s);
        feed(&mut s, E, &[1]);
        feed(&mut s, F, &[1]);
        feed(&mut s, E, &[3]);
        // A gap in the other stream is held too, not skipped.
        feed(&mut s, F, &[3]);
        assert_eq!(sent(&mut s).len(), 2);
        feed(&mut s, E, &[2]);
        feed(&mut s, F, &[2]);
        reply(&mut s, E, 3, true, 1);
        reply(&mut s, F, 3, true, 1);
        assert_eq!(s.handler.inner.offsets, [1, 1, 2, 3, 2, 3]);
        assert!(gaps(&s).is_empty());
        assert_eq!(s.next_deadline(), None);
    }

    #[test]
    fn a_replay_the_server_cut_short_is_asked_for_again() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        sent(&mut s);
        feed(&mut s, E, &[1, 5]);
        sent(&mut s);
        // The server's outbound budget let one through.
        feed(&mut s, E, &[2]);
        reply(&mut s, E, 2, false, 1);
        assert!(gaps(&s).is_empty());
        let again = sent(&mut s);
        assert_eq!(
            again[0]["p"]["recovery"],
            serde_json::json!({"t": {"epoch": E, "offset": 2, "streams": {E: 2}}})
        );
        feed(&mut s, E, &[3, 4]);
        reply(&mut s, E, 4, true, 2);
        assert_eq!(s.handler.inner.offsets, [1, 2, 3, 4, 5]);
        assert!(gaps(&s).is_empty());
    }

    #[test]
    fn a_reconnect_gives_a_hole_its_whole_wait_again() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 3]);
        let first = s.next_deadline().unwrap();
        s.close();
        std::thread::sleep(Duration::from_millis(20));
        s.open(None);
        ready(&mut s, true);
        assert!(s.next_deadline().unwrap() > first);
        assert!(gaps(&s).is_empty());
    }

    #[test]
    fn signed_times_read_as_the_other_clients_write_them() {
        assert_eq!(rfc3339_ms(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(rfc3339_ms(951_782_400_000), "2000-02-29T00:00:00.000Z");
        assert_eq!(rfc3339_ms(1_700_000_000_123), "2023-11-14T22:13:20.123Z");
    }

    #[test]
    fn a_message_signed_for_no_topic_is_not_taken_on_one() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        s.on_json(
            r#"{"t":"signed","tp":"t","e":"0000000a","o":1,"sb":"{\"t\":\"fill\",\"p\":{}}","sig":"AA","kid":"k"}"#,
            None,
        );
        assert!(s.handler.inner.offsets.is_empty());
        // Signed for the topic it came on: taken.
        s.on_json(
            r#"{"t":"signed","tp":"t","e":"0000000a","o":1,"sb":"{\"t\":\"fill\",\"tp\":\"t\",\"p\":{}}","sig":"AA","kid":"k"}"#,
            None,
        );
        assert_eq!(s.handler.inner.offsets, [1]);
    }

    #[test]
    fn a_gap_is_filled_by_the_replay_and_what_came_past_it_follows() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        assert_eq!(sent(&mut s)[0]["p"]["topics"], serde_json::json!(["t"]));
        feed(&mut s, E, &[1, 2, 4, 5]);
        assert_eq!(s.handler.inner.offsets, [1, 2]);
        // The client asks from the last one it has.
        let request = sent(&mut s);
        assert_eq!(
            request[0]["p"]["recovery"],
            serde_json::json!({"t": {"epoch": E, "offset": 2, "streams": {E: 2}}})
        );
        // The replay: 3, then 4 and 5 again.
        feed(&mut s, E, &[3, 4, 5]);
        s.on_json(
            r#"{"c":"WSE","t":"subscription_update","p":{"success_topics":["t"],"failed_topics":[],"recovery":{"t":{"epoch":"0000000a","offset":5,"recovered":true,"count":3}}}}"#,
            None,
        );
        assert_eq!(s.handler.inner.offsets, [1, 2, 3, 4, 5]);
        assert!(gaps(&s).is_empty());
        assert_eq!(s.next_deadline(), None);
        feed(&mut s, E, &[6]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 3, 4, 5, 6]);
    }

    #[test]
    fn a_gap_not_filled_in_time_is_reported_and_what_is_held_delivered() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 3, 4]);
        assert_eq!(s.handler.inner.offsets, [1]);
        s.on_deadline(Instant::now() + Duration::from_secs(4));
        assert_eq!(s.handler.inner.offsets, [1, 3, 4]);
        assert_eq!(gaps(&s), [(Some(2), Some(2), GapReason::Timeout)]);
        feed(&mut s, E, &[5]);
        assert_eq!(s.handler.inner.offsets, [1, 3, 4, 5]);
    }

    #[test]
    fn without_recovery_a_gap_is_reported_at_once() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, false);
        feed(&mut s, E, &[1, 4, 4, 5]);
        assert_eq!(s.handler.inner.offsets, [1, 4, 5]);
        assert_eq!(gaps(&s), [(Some(2), Some(3), GapReason::Unavailable)]);
    }

    #[test]
    fn a_new_connection_asks_for_its_topics_from_where_it_left_off() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 2]);
        sent(&mut s);
        s.close();
        s.open(None);
        ready(&mut s, true);
        let request = sent(&mut s);
        assert_eq!(
            request[0]["p"],
            serde_json::json!({
                "action": "subscribe",
                "topics": ["t"],
                "recover": true,
                "recovery": {"t": {"epoch": E, "offset": 2, "streams": {E: 2}}},
            })
        );
        // The server restarted meanwhile: its history began again.
        s.on_json(
            r#"{"c":"WSE","t":"subscription_update","p":{"success_topics":["t"],"recovery":{"t":{"epoch":"0000000b","offset":0,"recovered":false,"count":0}}}}"#,
            None,
        );
        assert_eq!(gaps(&s), [(None, None, GapReason::EpochChanged)]);
        let Some(Event::Connected(again)) = s
            .handler
            .inner
            .events
            .iter()
            .rev()
            .find(|e| matches!(e, Event::Connected(_)))
        else {
            panic!("connected");
        };
        assert!(again.reconnected);
    }

    /// A send that requires topics waits until each is continuous, while
    /// the others go past it; one sent as the last user goes nowhere.
    #[test]
    fn a_send_that_requires_topics_waits_for_them_and_is_its_users() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        sent(&mut s);
        let frame = |s: &Session<Seen>, kind: &str, requires: &[&str]| Queued {
            text: format!(r#"{{"t":"{kind}","p":{{}}}}"#),
            user: s.users,
            only_on: None,
            requires: (!requires.is_empty())
                .then(|| requires.iter().map(|t| (*t).to_owned()).collect()),
            id: kind.into(),
            until: None,
            counted: false,
            clears: 0,
            tag: 0,
        };
        let kinds = |s: &mut Session<Seen>| -> Vec<String> {
            s.release_waiting();
            sent(s)
                .into_iter()
                .map(|m| m["t"].as_str().unwrap().to_owned())
                .collect()
        };
        // Neither `a` nor `b` is held: not continuous.
        s.queue(frame(&s, "first", &["a"]));
        s.queue(frame(&s, "second", &["a", "b"]));
        s.queue(frame(&s, "plain", &[]));
        assert_eq!(kinds(&mut s), ["plain"]);
        assert_eq!(s.waiting(), 2);
        // Held in best effort, `a` is continuous: the first goes.
        delivery::lock(s.handler.gate()).track(&["a".to_owned()]);
        assert_eq!(kinds(&mut s), ["first"]);
        delivery::lock(s.handler.gate()).track(&["b".to_owned()]);
        assert_eq!(kinds(&mut s), ["second"]);

        // Sent as the last user, it is not the next one's.
        s.queue(frame(&s, "last users", &["c"]));
        s.close();
        s.open(None);
        ready_as(&mut s, "someone else", true);
        sent(&mut s);
        delivery::lock(s.handler.gate()).track(&["c".to_owned()]);
        assert!(kinds(&mut s).is_empty());
        assert_eq!(s.waiting(), 0);
    }

    #[test]
    fn a_connection_for_another_user_asks_for_its_topics_afresh() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 2]);
        sent(&mut s);
        s.close();
        s.open(None);
        ready_as(&mut s, "someone else", true);
        let request = sent(&mut s);
        assert_eq!(request[0]["p"]["topics"], serde_json::json!(["t"]));
        assert_eq!(request[0]["p"].get("recovery"), None);
        // Where the last user's stream stood holds nothing back.
        feed(&mut s, E, &[1]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 1]);
    }

    /// The server's answer for `t`, listing its streams (from 3.1).
    fn reply_streams(s: &mut Session<Seen>, recovered: bool, streams: &[(&str, u64)]) {
        let streams: serde_json::Map<String, serde_json::Value> = streams
            .iter()
            .map(|(epoch, offset)| ((*epoch).to_owned(), (*offset).into()))
            .collect();
        let reply = serde_json::json!({
            "c": "WSE",
            "t": "subscription_update",
            "p": {
                "success_topics": ["t"],
                "recovery": {"t": {
                    "epoch": E, "offset": 0, "recovered": recovered, "count": 0,
                    "streams": streams,
                }},
            },
        });
        s.on_json(&reply.to_string(), None);
    }

    fn reconnect(s: &mut Session<Seen>) -> Vec<serde_json::Value> {
        sent(s);
        s.close();
        s.open(None);
        ready(s, true);
        sent(s)
    }

    const F: &str = "0000000f";

    #[test]
    fn a_recovery_names_every_stream_of_the_topic() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, F, &[4]);
        feed(&mut s, E, &[1, 2]);
        let request = reconnect(&mut s);
        assert_eq!(
            request[0]["p"]["recovery"],
            serde_json::json!({"t": {"epoch": E, "offset": 2, "streams": {E: 2, F: 4}}})
        );
    }

    #[test]
    fn a_listed_stream_the_client_did_not_know_starts_where_the_server_was() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        sent(&mut s);
        reply_streams(&mut s, false, &[(F, 5)]);
        feed(&mut s, F, &[3, 5, 6]);
        assert_eq!(s.handler.inner.offsets, [6]);
        assert!(gaps(&s).is_empty());
    }

    #[test]
    fn a_recovery_that_did_not_recover_reports_what_each_stream_lost() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 2]);
        feed(&mut s, F, &[4]);
        reconnect(&mut s);
        // F the server does not hold any more; E went on to 5.
        reply_streams(&mut s, false, &[(E, 5)]);
        assert_eq!(
            gaps(&s),
            [
                (Some(3), Some(5), GapReason::NotRecovered),
                (Some(5), None, GapReason::NotRecovered),
            ]
        );
        feed(&mut s, E, &[6]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 4, 6]);
        // F is forgotten: not named again.
        let request = reconnect(&mut s);
        assert_eq!(
            request[0]["p"]["recovery"]["t"]["streams"],
            serde_json::json!({E: 6})
        );
    }

    #[test]
    fn a_recovery_with_nothing_to_show_still_says_it_did_not_recover() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 2]);
        reconnect(&mut s);
        reply_streams(&mut s, false, &[(E, 2)]);
        assert_eq!(gaps(&s), [(None, None, GapReason::NotRecovered)]);
    }

    /// The streams the recovery after a reconnect names.
    fn named_after_reconnect(s: &mut Session<Seen>) -> serde_json::Value {
        sent(s);
        s.close();
        s.open(None);
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c2","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        let request = sent(s);
        assert_eq!(request[0]["p"]["recover"], true);
        request[0]["p"]["recovery"]["t"]["streams"].clone()
    }

    #[test]
    fn a_stream_quiet_for_longer_than_the_server_keeps_it_is_not_named() {
        let mut s = session(Duration::from_secs(3));
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c1","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        feed(&mut s, F, &[4]);
        // Connected all along, a frame every 15 seconds: F heard nothing
        // for three minutes.
        pongs(&mut s, 12);
        feed(&mut s, E, &[1]);
        assert_eq!(named_after_reconnect(&mut s), serde_json::json!({E: 1}));
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn the_clocks_tell_a_sleep_longer_than_a_beat() {
        let beat = Duration::from_secs(15);
        let wall = web_time::UNIX_EPOCH + Duration::from_secs(1_000_000);
        let mono = Instant::now();
        let mut watch = SleepWatch::new(wall, mono);
        // A beat awake: both clocks moved alike.
        assert_eq!(watch.slept(wall + beat, mono + beat, beat), None);
        // Ten minutes asleep: the wall clock went on, the monotonic one stood.
        assert_eq!(
            watch.slept(
                wall + beat * 2 + Duration::from_secs(600),
                mono + beat * 2,
                beat
            ),
            Some(Duration::from_secs(600))
        );
        // Awake again: nothing more.
        assert_eq!(
            watch.slept(
                wall + beat * 3 + Duration::from_secs(600),
                mono + beat * 3,
                beat
            ),
            None
        );
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn a_clock_set_back_or_a_short_skew_is_no_sleep() {
        let beat = Duration::from_secs(15);
        let wall = web_time::UNIX_EPOCH + Duration::from_secs(1_000_000);
        let mono = Instant::now();
        let mut watch = SleepWatch::new(wall, mono);
        // Set back an hour.
        assert_eq!(
            watch.slept(wall - Duration::from_secs(3600), mono + beat, beat),
            None
        );
        // A few seconds of skew between the clocks.
        let wall = wall - Duration::from_secs(3600);
        assert_eq!(
            watch.slept(wall + beat + Duration::from_secs(3), mono + beat * 2, beat),
            None
        );
    }

    #[test]
    fn a_close_heard_only_after_a_sleep_keeps_the_stream() {
        let mut s = session(Duration::from_secs(3));
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c1","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        feed(&mut s, E, &[1]);
        // Asleep (or the app suspended) for 400 seconds: the server went on
        // publishing and keeping the stream, and the close is read on waking.
        s.clock += Duration::from_secs(400);
        assert_eq!(named_after_reconnect(&mut s), serde_json::json!({E: 1}));
    }

    #[test]
    fn frames_read_on_waking_prove_nothing_about_the_time_asleep() {
        let mut s = session(Duration::from_secs(3));
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c1","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        feed(&mut s, E, &[1]);
        s.clock += Duration::from_secs(400);
        // Sent before the sleep, read after it.
        feed(&mut s, F, &[1]);
        assert_eq!(
            named_after_reconnect(&mut s),
            serde_json::json!({E: 1, F: 1})
        );
    }

    #[test]
    fn a_sleep_the_connection_lived_through_counts_from_waking() {
        let mut s = session(Duration::from_secs(3));
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c1","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        feed(&mut s, F, &[4]);
        s.clock += Duration::from_secs(400);
        // The connection outlived the sleep: what the server sent meanwhile
        // is read on waking, the PONGs go on, and F stays silent for three
        // more minutes.
        feed(&mut s, E, &[1]);
        pongs(&mut s, 12);
        feed(&mut s, E, &[2]);
        assert_eq!(named_after_reconnect(&mut s), serde_json::json!({E: 2}));
    }

    #[test]
    fn time_away_does_not_count_as_a_quiet_stream() {
        let mut s = session(Duration::from_secs(3));
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c1","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        feed(&mut s, E, &[1]);
        sent(&mut s);
        // Lost at once, and away far longer than the server keeps a quiet
        // stream: what the server published meanwhile kept the stream there.
        s.close();
        s.clock += Duration::from_secs(400);
        s.open(None);
        s.on_json(
            r#"{"c":"WSE","t":"server_ready","p":{"details":{"connection_id":"c2","user_id":"u","features":{"recovery":true,"history_ttl":60}}}}"#,
            None,
        );
        let request = sent(&mut s);
        assert_eq!(request[0]["p"]["recover"], true);
        assert_eq!(
            request[0]["p"]["recovery"]["t"]["streams"],
            serde_json::json!({E: 1})
        );
    }

    #[test]
    fn a_topic_left_starts_over_when_joined_again() {
        let mut s = session(Duration::from_secs(3));
        ready(&mut s, true);
        feed(&mut s, E, &[1, 2]);
        s.unsubscribe(vec!["t".to_owned()]);
        s.subscribe(vec!["t".to_owned()]);
        let requests = sent(&mut s);
        assert_eq!(requests.last().unwrap()["p"].get("recovery"), None);
        feed(&mut s, E, &[9]);
        assert_eq!(s.handler.inner.offsets, [1, 2, 9]);
        assert!(gaps(&s).is_empty());
    }

    #[test]
    fn requests_are_json() {
        let last = Position {
            epoch: 0xab,
            offset: 7,
        };
        let other = Position {
            epoch: 0x12,
            offset: 3,
        };
        let text = subscription(&["a\"b", "c"], &[("c", last, vec![other, last])]);
        let value: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
        assert_eq!(
            value["p"],
            serde_json::json!({
                "action": "subscribe",
                "topics": ["a\"b", "c"],
                "recover": true,
                "recovery": {"c": {
                    "epoch": "000000ab",
                    "offset": 7,
                    "streams": {"00000012": 3, "000000ab": 7},
                }},
            })
        );
        let hello: serde_json::Value =
            serde_json::from_str(client_hello(true, None, None).as_str()).unwrap();
        assert_eq!(hello["t"], "client_hello");
        assert_eq!(hello["p"]["features"]["compression"], true);
    }

    /// What reading a topic message costs, frames apart: run with
    /// `cargo test --release -p wse-client --lib -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn the_cost_of_a_message() {
        #[derive(serde::Deserialize)]
        struct Tick<'a> {
            #[serde(borrow)]
            symbol: &'a str,
            price: f64,
        }
        struct Decode(f64);
        impl Handler for Decode {
            fn message(&mut self, message: &Message<'_>) {
                if message.kind() == "tick" {
                    let tick: Tick<'_> = message.payload().unwrap();
                    self.0 += tick.price + tick.symbol.len() as f64;
                }
            }
        }
        let n = 1_000_000u64;
        let frames: Vec<String> = (1..=n)
            .map(|o| {
                format!(
                    r#"{{"tp":"bench","e":"0000abcd","o":{o},"t":"tick","p":{{"symbol":"BTCUSDT","price":67012.5,"qty":0.0125,"side":"buy","ts":1794600000000}}}}"#
                )
            })
            .collect();
        let shared = Arc::new(Shared::new(None, None));
        let keys = Arc::new(Keys::from_config(&crate::Config::new("ws://x")).unwrap());
        let mut s = Session::new(
            Delivered::passing(Decode(0.0)),
            shared,
            keys,
            &[],
            Duration::from_secs(3),
            Duration::from_secs(40),
        );
        s.open(None);
        let started = std::time::Instant::now();
        for frame in &frames {
            s.on_json(frame, None);
        }
        let all = started.elapsed().as_nanos() as f64 / n as f64;
        // The envelope alone.
        let started = std::time::Instant::now();
        let mut kinds = 0usize;
        for frame in &frames {
            kinds += decode::json_envelope(frame).unwrap().t.unwrap().len();
        }
        let envelope = started.elapsed().as_nanos() as f64 / n as f64;
        // A whole serde_json::Value, as a typical client reads it.
        let started = std::time::Instant::now();
        for frame in &frames {
            let value: serde_json::Value = serde_json::from_str(frame).unwrap();
            kinds += value["t"].as_str().unwrap().len();
        }
        let value = started.elapsed().as_nanos() as f64 / n as f64;
        println!(
            "per message: session {all:.0} ns (envelope {envelope:.0} ns); a serde_json::Value {value:.0} ns [{kinds} {}]",
            s.handler.inner.0
        );
    }

    /// An application that hears of the connection and reads the client's
    /// status reads it connected.
    #[test]
    fn the_status_reads_connected_when_the_application_hears_of_the_connection() {
        struct Watch(tokio::sync::watch::Receiver<Status>, Option<Status>);
        impl crate::handler::Handler for Watch {
            fn message(&mut self, _: &Message<'_>) {}
            fn event(&mut self, event: crate::handler::Event) {
                if matches!(event, crate::handler::Event::Connected(_)) {
                    self.1 = Some(self.0.borrow().clone());
                }
            }
        }
        let (status, seen) = tokio::sync::watch::channel(Status::Connecting);
        let shared = Arc::new(Shared::new(None, None));
        let keys = Arc::new(Keys::from_config(&crate::Config::new("ws://x")).unwrap());
        let mut s = Session::new(
            Delivered::passing(Watch(seen, None)),
            shared,
            keys,
            &[],
            Duration::from_secs(3),
            Duration::from_secs(40),
        );
        s.status = Some(status);
        s.open(None);
        s.on_json(
            r#"{"t":"server_ready","p":{"details":{"user_id":"ann"}}}"#,
            None,
        );
        assert_eq!(s.handler.inner.1, Some(Status::Connected));
    }

    #[test]
    fn a_kept_send_that_requires_topics_waits_for_them_again_after_a_reconnect() {
        use crate::outbox::{Offline, Outbox, Room};
        let topics = vec!["t".to_owned()];
        let gate = Arc::new(std::sync::Mutex::new(
            delivery::Gate::new(Some(crate::Delivery::new("consumer")), "ws://x", &topics).unwrap(),
        ));
        let offline = Offline::in_memory();
        let room = Arc::new(Room::new(&offline));
        let shared = Arc::new(Shared::new(None, Some(Arc::clone(&room))));
        let keys = Arc::new(Keys::from_config(&crate::Config::new("ws://x")).unwrap());
        let mut s = Session::new(
            Delivered::new(Seen::default(), Arc::clone(&gate), true),
            shared,
            keys,
            &topics,
            Duration::from_secs(3),
            Duration::from_secs(40),
        );
        s.outbox = Some(Outbox::open(
            &offline,
            Arc::clone(&room),
            Arc::new(|_, _| {}),
            Arc::new(|| {}),
        ));
        let ready = r#"{"t":"server_ready","p":{"details":{"user_id":"ann","features":{"acks":true,"recovery":true}}}}"#;
        let answered = r#"{"t":"outbox","p":{"acked":0,"node":"n"}}"#;
        let kept = |s: &Session<Seen>| {
            s.to_write
                .iter()
                .any(|o| matches!(o, Outgoing::Kept { .. }))
        };
        s.open(None);
        s.on_json(ready, None);
        s.on_json(answered, None);
        s.on_json(
            r#"{"t":"subscription_update","p":{"success_topics":["t"]}}"#,
            None,
        );
        delivery::lock(&gate).resynced(1);
        s.to_write.clear();
        let text = format!(
            "{}{}",
            " ".repeat(crate::outbox::HEADROOM),
            r#"{"t":"order","id":"needs-t"}"#
        );
        assert!(room.take(text.len() - crate::outbox::HEADROOM));
        s.queue(Queued {
            text,
            user: 0,
            only_on: None,
            requires: Some(topics.clone().into_boxed_slice()),
            id: "needs-t".into(),
            until: None,
            counted: true,
            clears: 0,
            tag: 0,
        });
        s.before_write();
        assert!(kept(&s), "continuous: it goes");
        s.wrote(Some(1));
        // The connection goes before its answer; on the next one the topic is
        // not continuous until its resync.
        s.close();
        s.handler.event(Event::Disconnected(crate::Disconnected {
            code: None,
            reason: "cut".into(),
            retry_in: Duration::ZERO,
            attempt: 1,
        }));
        s.open(None);
        s.on_json(ready, None);
        s.on_json(answered, None);
        assert!(!delivery::lock(&gate).continuous(&topics));
        s.before_write();
        assert!(!kept(&s), "not before its topic is continuous again");
        s.on_json(
            r#"{"t":"subscription_update","p":{"success_topics":["t"]}}"#,
            None,
        );
        delivery::lock(&gate).resynced(2);
        s.before_write();
        assert!(kept(&s), "once it is, in its place");
    }
}