signaling 0.5.0

Sans-IO Signaling in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
//! SFU-capable V2 room and worker state.
//!
//! Rooms are identified by a UUIDv8 minted by the service and clients by a numeric
//! `u64`, browser registrations are admission-token bound, and P2P-to-SFU upgrades
//! commit only after every `JoinMember` command has succeeded.

use crate::sfu;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration, Instant};
use uuid::Uuid;

const MAX_P2P_MEMBERS: usize = 2;
const MAX_QUEUED_MESSAGES: usize = 1024;
const HEALTH_INTERVAL_MS: u64 = 30_000;
const EVENT_DEDUP_CAPACITY: usize = 4096;
/// How long an SFU room must sit at ≤2 members before it downgrades back to
/// direct P2P. The dwell absorbs brief membership churn (a third participant
/// leaving and immediately rejoining) so the room does not flap between modes.
const DOWNGRADE_DWELL: Duration = Duration::from_secs(2);

/// V2 rooms are identified by a UUIDv8 (RFC 9562 §5.8), minted by the service rather
/// than chosen by a client. Clients remain numeric.
pub type RoomId = Uuid;
pub type ClientId = u64;

/// Number of characters in a room token: 16 bytes of UUID, base64url, unpadded.
pub const ROOM_TOKEN_LEN: usize = 22;

/// Mint a room id: a UUIDv8 whose 122 free bits are random.
///
/// Version 8 is RFC 9562's application-defined layout, which is what lets this project
/// give the remaining bits meaning later (a home-node tag, an expiry) without minting
/// something that is no longer a well-formed UUID.
pub fn new_room_id() -> RoomId {
    // `new_v4` is the crate's route to the OS CSPRNG; `new_v8` then restamps the version
    // and variant nibbles over it, leaving 122 random bits — the same 122 a v4 carries.
    Uuid::new_v8(Uuid::new_v4().into_bytes())
}

/// Render a room id as the token that appears in a room link: base64url, unpadded.
pub fn format_room_token(room_id: &RoomId) -> String {
    URL_SAFE_NO_PAD.encode(room_id.as_bytes())
}

/// Parse a room token back into a room id, rejecting anything that is not exactly one
/// canonical encoding of a UUIDv8.
///
/// Three checks, each closing a way for one room to acquire two identities:
///   * exactly [`ROOM_TOKEN_LEN`] base64url characters — no padding, no whitespace;
///   * canonical trailing bits. 128 is not a multiple of 6, so the final character
///     carries 2 significant bits and 4 that must be zero. Sixteen distinct final
///     characters would otherwise decode to the same UUID, and since rooms are keyed by
///     the value received, those spellings would become sixteen different rooms. The
///     decoder rejects non-zero trailing bits, so only `A`, `Q`, `g` and `w` can end a
///     valid token;
///   * version 8 and the RFC 9562 variant, so a v4 UUID or arbitrary 16 bytes is not
///     mistaken for a token this service minted.
pub fn parse_room_token(token: &str) -> Option<RoomId> {
    if token.len() != ROOM_TOKEN_LEN {
        return None;
    }
    let bytes = URL_SAFE_NO_PAD.decode(token).ok()?;
    let bytes: [u8; 16] = bytes.try_into().ok()?;
    let room_id = Uuid::from_bytes(bytes);
    is_room_uuid(&room_id).then_some(room_id)
}

/// True when `room_id` is a UUIDv8 with the RFC 9562 variant, the only shape this
/// service mints or accepts.
pub fn is_room_uuid(room_id: &RoomId) -> bool {
    room_id.get_version_num() == 8 && matches!(room_id.get_variant(), uuid::Variant::RFC4122)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoomMode {
    P2p,
    Upgrading,
    Sfu,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Admission {
    pub mode: RoomMode,
    pub signal_epoch: u64,
    pub admission_token: String,
    pub is_initiator: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdmissionResult {
    Complete(Admission),
    Pending,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemovalResult {
    Complete(Option<Promotion>),
    Pending,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Registration {
    pub mode: RoomMode,
    pub signal_epoch: u64,
    pub is_initiator: Option<bool>,
    pub queued_messages: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Delivery {
    pub room_id: RoomId,
    pub client_id: ClientId,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Promotion {
    pub room_id: RoomId,
    pub client_id: ClientId,
    pub signal_epoch: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendResult {
    P2p(Option<Delivery>),
    Sfu,
    Dropped,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    Sfu(sfu::Output),
    AdmissionCompleted {
        authority_request_id: u64,
        result: Result<Admission, String>,
    },
    RemovalCompleted {
        authority_request_id: u64,
        room_id: RoomId,
        client_id: ClientId,
        result: Result<(), String>,
    },
    Upgraded {
        room_id: RoomId,
        signal_epoch: u64,
        existing_clients: Vec<ClientId>,
    },
    Downgraded {
        room_id: RoomId,
        signal_epoch: u64,
        /// The member elected to offer the direct P2P connection; every other
        /// member becomes the answerer.
        initiator_client_id: ClientId,
        clients: Vec<ClientId>,
    },
    Deliver(Delivery),
    RoomFailed {
        room_id: RoomId,
        clients: Vec<ClientId>,
        reason: String,
    },
}

struct Member {
    token: String,
    is_initiator: bool,
    lifecycle_id: u64,
    registered: bool,
    reconnect_deadline: Option<Instant>,
    queued_messages: VecDeque<String>,
}

struct Upgrade {
    authority_request_id: u64,
    joining_client_id: ClientId,
    ordered_clients: Vec<ClientId>,
    joined_clients: Vec<ClientId>,
    next_client: usize,
}

struct PendingJoin {
    authority_request_id: u64,
    client_id: ClientId,
}

struct PendingLeave {
    authority_request_id: Option<u64>,
    client_id: ClientId,
}

struct Room {
    members: HashMap<ClientId, Member>,
    mode: RoomMode,
    signal_epoch: u64,
    assignment_epoch: u64,
    assigned_instance: Option<String>,
    upgrade: Option<Upgrade>,
    pending_join: Option<PendingJoin>,
    pending_leave: Option<PendingLeave>,
    /// When an SFU room shrinks to at most two members it becomes eligible for a
    /// downgrade back to direct P2P. This is the deadline after which the dwell
    /// expires and `commit_downgrade` runs; cleared whenever the room stops being
    /// a stable ≤2-member SFU room (a third joins, or a transition starts).
    downgrade_deadline: Option<Instant>,
}

struct Worker {
    connection_id: Option<sfu::ConnectionId>,
    capacity: sfu::Capacity,
    health: Option<sfu::Health>,
    assigned_rooms: HashSet<RoomId>,
    assigned_clients: usize,
    seen_events: HashSet<u64>,
    seen_event_order: VecDeque<u64>,
    disconnect_deadline: Option<Instant>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PendingCommand {
    SyncRoom {
        instance_id: String,
        room_id: RoomId,
        assignment_epoch: u64,
        replay: Vec<sfu::Command>,
    },
    UpgradeJoin {
        instance_id: String,
        room_id: RoomId,
        client_id: ClientId,
        lifecycle_id: u64,
        assignment_epoch: u64,
    },
    SfuJoin {
        instance_id: String,
        room_id: RoomId,
        client_id: ClientId,
        lifecycle_id: u64,
        assignment_epoch: u64,
    },
    SfuLeave {
        instance_id: String,
        room_id: RoomId,
        client_id: ClientId,
        lifecycle_id: u64,
        assignment_epoch: u64,
    },
    Signal,
    Cleanup,
}

pub struct RoomTable {
    rooms: HashMap<RoomId, Room>,
    workers: HashMap<String, Worker>,
    lifecycle_ids: HashMap<(RoomId, ClientId), u64>,
    pending_commands: HashMap<u64, PendingCommand>,
    unacknowledged_commands: HashMap<u64, sfu::Command>,
    command_workers: HashMap<u64, String>,
    next_sfu_request_id: u64,
    reconnect_grace: Duration,
    downgrade_dwell: Duration,
    actions: VecDeque<Action>,
}

impl RoomTable {
    pub fn new(reconnect_grace: Duration) -> Self {
        Self {
            rooms: HashMap::new(),
            workers: HashMap::new(),
            lifecycle_ids: HashMap::new(),
            pending_commands: HashMap::new(),
            unacknowledged_commands: HashMap::new(),
            command_workers: HashMap::new(),
            next_sfu_request_id: 1,
            reconnect_grace,
            downgrade_dwell: DOWNGRADE_DWELL,
            actions: VecDeque::new(),
        }
    }

    /// Override the SFU→P2P downgrade dwell (default [`DOWNGRADE_DWELL`]). Lets a deployment tune
    /// how long a room lingers at two SFU members before returning to direct P2P.
    pub fn set_downgrade_dwell(&mut self, dwell: Duration) {
        self.downgrade_dwell = dwell;
    }

    pub fn admit(
        &mut self,
        authority_request_id: u64,
        now: Instant,
        room_id: RoomId,
        client_id: ClientId,
        admission_token: String,
    ) -> Result<AdmissionResult, String> {
        if self
            .rooms
            .get(&room_id)
            .is_some_and(|room| room.members.contains_key(&client_id))
        {
            return Err("DUPLICATE_CLIENT".into());
        }

        if !self.rooms.contains_key(&room_id) {
            let lifecycle_id = self.next_lifecycle(room_id, client_id);
            let mut members = HashMap::new();
            members.insert(
                client_id,
                new_member(
                    now,
                    self.reconnect_grace,
                    admission_token.clone(),
                    true,
                    lifecycle_id,
                ),
            );
            self.rooms.insert(
                room_id,
                Room {
                    members,
                    mode: RoomMode::P2p,
                    signal_epoch: 0,
                    assignment_epoch: 0,
                    assigned_instance: None,
                    upgrade: None,
                    pending_join: None,
                    pending_leave: None,
                    downgrade_deadline: None,
                },
            );
            return Ok(AdmissionResult::Complete(Admission {
                mode: RoomMode::P2p,
                signal_epoch: 0,
                admission_token,
                is_initiator: Some(true),
            }));
        }

        let mode = self.rooms[&room_id].mode;
        match mode {
            RoomMode::Upgrading => return Err("ROOM_TRANSITION".into()),
            RoomMode::Failed => return Err("WORKER_UNAVAILABLE".into()),
            RoomMode::Sfu => {
                if self.rooms[&room_id].pending_join.is_some()
                    || self.rooms[&room_id].pending_leave.is_some()
                {
                    return Err("ROOM_TRANSITION".into());
                }
                return self.admit_to_sfu(
                    authority_request_id,
                    now,
                    room_id,
                    client_id,
                    admission_token,
                );
            }
            RoomMode::P2p => {}
        }

        if self.rooms[&room_id].members.len() < MAX_P2P_MEMBERS {
            let lifecycle_id = self.next_lifecycle(room_id, client_id);
            let room = self.rooms.get_mut(&room_id).expect("room checked");
            room.members.insert(
                client_id,
                new_member(
                    now,
                    self.reconnect_grace,
                    admission_token.clone(),
                    false,
                    lifecycle_id,
                ),
            );
            return Ok(AdmissionResult::Complete(Admission {
                mode: RoomMode::P2p,
                signal_epoch: room.signal_epoch,
                admission_token,
                is_initiator: Some(false),
            }));
        }

        let instance_id = self.select_worker(3).ok_or("NO_SFU_AVAILABLE")?;
        let lifecycle_id = self.next_lifecycle(room_id, client_id);
        let room = self.rooms.get_mut(&room_id).expect("room checked");
        room.members.insert(
            client_id,
            new_member(
                now,
                self.reconnect_grace,
                admission_token,
                false,
                lifecycle_id,
            ),
        );
        room.mode = RoomMode::Upgrading;
        room.assignment_epoch = room.assignment_epoch.saturating_add(1);
        room.assigned_instance = Some(instance_id.clone());
        let mut ordered_clients = room.members.keys().copied().collect::<Vec<_>>();
        ordered_clients.sort_unstable();
        // The new member is always joined last, matching the documented barrier.
        ordered_clients.retain(|candidate| *candidate != client_id);
        ordered_clients.push(client_id);
        // A worker membership lifecycle begins at the upgrade boundary. Existing
        // P2P members therefore receive fresh lifecycle IDs as well.
        for existing_client in ordered_clients
            .iter()
            .copied()
            .filter(|candidate| *candidate != client_id)
        {
            let lifecycle = self.next_lifecycle(room_id, existing_client);
            self.rooms
                .get_mut(&room_id)
                .and_then(|room| room.members.get_mut(&existing_client))
                .expect("existing upgrade member")
                .lifecycle_id = lifecycle;
        }
        let room = self.rooms.get_mut(&room_id).expect("room checked");
        room.upgrade = Some(Upgrade {
            authority_request_id,
            joining_client_id: client_id,
            ordered_clients,
            joined_clients: Vec::new(),
            next_client: 0,
        });
        let worker = self.workers.get_mut(&instance_id).expect("selected worker");
        worker.assigned_rooms.insert(room_id);
        worker.assigned_clients = worker.assigned_clients.saturating_add(3);
        self.issue_next_upgrade_join(room_id)?;
        Ok(AdmissionResult::Pending)
    }

    pub fn register(
        &mut self,
        room_id: RoomId,
        client_id: ClientId,
        token: &str,
    ) -> Result<Registration, String> {
        let room = self.rooms.get_mut(&room_id).ok_or("UNAUTHORIZED")?;
        if room.mode == RoomMode::Upgrading {
            return Err("ROOM_TRANSITION".into());
        }
        let is_initiator = {
            let member = room.members.get_mut(&client_id).ok_or("UNAUTHORIZED")?;
            if !constant_time_eq(member.token.as_bytes(), token.as_bytes()) {
                return Err("UNAUTHORIZED".into());
            }
            if member.registered {
                return Err("Duplicated registration".into());
            }
            member.registered = true;
            member.reconnect_deadline = None;
            member.is_initiator
        };
        let mut queued_messages = Vec::new();
        if room.mode == RoomMode::P2p {
            for (&other_id, other) in &mut room.members {
                if other_id != client_id {
                    queued_messages.extend(other.queued_messages.drain(..));
                }
            }
        }
        Ok(Registration {
            mode: room.mode,
            signal_epoch: room.signal_epoch,
            is_initiator: (room.mode == RoomMode::P2p).then_some(is_initiator),
            queued_messages,
        })
    }

    fn admit_to_sfu(
        &mut self,
        authority_request_id: u64,
        now: Instant,
        room_id: RoomId,
        client_id: ClientId,
        admission_token: String,
    ) -> Result<AdmissionResult, String> {
        let instance_id = self.rooms[&room_id]
            .assigned_instance
            .clone()
            .ok_or("WORKER_UNAVAILABLE")?;
        let connection_id = self
            .workers
            .get(&instance_id)
            .and_then(|worker| worker.connection_id)
            .ok_or("WORKER_UNAVAILABLE")?;
        let lifecycle_id = self.next_lifecycle(room_id, client_id);
        let room = self.rooms.get_mut(&room_id).expect("room checked");
        room.members.insert(
            client_id,
            new_member(
                now,
                self.reconnect_grace,
                admission_token,
                false,
                lifecycle_id,
            ),
        );
        room.pending_join = Some(PendingJoin {
            authority_request_id,
            client_id,
        });
        // A new member is joining, so the room is no longer a downgrade candidate.
        room.downgrade_deadline = None;
        let assignment_epoch = room.assignment_epoch;
        let request_id = self.next_command_id();
        self.queue_command(
            instance_id.clone(),
            connection_id,
            sfu::Command {
                request_id,
                command: sfu::CommandKind::Join(sfu::JoinMember {
                    room_id,
                    client_id,
                    lifecycle_id,
                    assignment_epoch,
                }),
            },
            PendingCommand::SfuJoin {
                instance_id,
                room_id,
                client_id,
                lifecycle_id,
                assignment_epoch,
            },
        );
        Ok(AdmissionResult::Pending)
    }

    pub fn deregister(&mut self, now: Instant, room_id: RoomId, client_id: ClientId) {
        let is_sfu = {
            let Some(room) = self.rooms.get_mut(&room_id) else {
                return;
            };
            let is_sfu = room.mode == RoomMode::Sfu;
            let Some(member) = room.members.get_mut(&client_id) else {
                return;
            };
            if !member.registered {
                return;
            }
            member.registered = false;
            is_sfu
        };
        // Match the chat.rs example: an SFU member whose WebSocket drops (browser close, refresh,
        // crash) is treated as an *immediate* leave — issue the `Leave` command to the worker now
        // so its forwarded media stops and the other clients' grid tiles prune without waiting out
        // the reconnect grace. Only fall back to the grace deadline when the leave can't be issued
        // yet (worker unavailable or a leave already pending), where `handle_timeout` retries it.
        if is_sfu && self.issue_sfu_leave(room_id, client_id, sfu::LeaveReason::Disconnected) {
            return;
        }
        // P2P and upgrading members keep the reconnect grace so a quick refresh can rejoin without
        // collapsing the call or prematurely promoting the survivor.
        if let Some(member) = self
            .rooms
            .get_mut(&room_id)
            .and_then(|room| room.members.get_mut(&client_id))
        {
            member.reconnect_deadline = Some(now + self.reconnect_grace);
        }
    }

    /// Queue an immediate `Leave` command to the SFU worker owning `room_id`, recording the room's
    /// pending leave. Returns `false` (queuing nothing) when the room/member is gone, a leave is
    /// already in flight, or no worker connection is available; the caller then falls back to a
    /// reconnect deadline that `handle_timeout` retries.
    fn issue_sfu_leave(
        &mut self,
        room_id: RoomId,
        client_id: ClientId,
        reason: sfu::LeaveReason,
    ) -> bool {
        let Some(room) = self.rooms.get(&room_id) else {
            return false;
        };
        if room.mode != RoomMode::Sfu || room.pending_leave.is_some() {
            return false;
        }
        let Some(member) = room.members.get(&client_id) else {
            return false;
        };
        let lifecycle_id = member.lifecycle_id;
        let assignment_epoch = room.assignment_epoch;
        let Some(instance_id) = room.assigned_instance.clone() else {
            return false;
        };
        let Some(connection_id) = self
            .workers
            .get(&instance_id)
            .and_then(|worker| worker.connection_id)
        else {
            return false;
        };
        let room = self.rooms.get_mut(&room_id).expect("room checked");
        room.pending_leave = Some(PendingLeave {
            authority_request_id: None,
            client_id,
        });
        let request_id = self.next_command_id();
        self.queue_command(
            instance_id.clone(),
            connection_id,
            sfu::Command {
                request_id,
                command: sfu::CommandKind::Leave(sfu::LeaveMember {
                    room_id,
                    client_id,
                    lifecycle_id,
                    assignment_epoch,
                    reason,
                }),
            },
            PendingCommand::SfuLeave {
                instance_id,
                room_id,
                client_id,
                lifecycle_id,
                assignment_epoch,
            },
        );
        true
    }

    pub fn send(
        &mut self,
        room_id: RoomId,
        client_id: ClientId,
        signal_epoch: u64,
        message: String,
    ) -> Result<SendResult, String> {
        let room = self.rooms.get_mut(&room_id).ok_or("CLIENT_NOT_FOUND")?;
        if room.signal_epoch != signal_epoch || room.mode == RoomMode::Upgrading {
            return Ok(SendResult::Dropped);
        }
        let member = room.members.get(&client_id).ok_or("CLIENT_NOT_FOUND")?;
        if room.mode == RoomMode::Sfu {
            let instance_id = room.assigned_instance.clone().ok_or("WORKER_UNAVAILABLE")?;
            let connection_id = self
                .workers
                .get(&instance_id)
                .and_then(|worker| worker.connection_id)
                .ok_or("WORKER_UNAVAILABLE")?;
            let signal = sfu::Signal {
                room_id,
                client_id,
                lifecycle_id: member.lifecycle_id,
                assignment_epoch: room.assignment_epoch,
                message_json: message,
                sdp_request_id: None,
            };
            let request_id = self.next_command_id();
            self.queue_command(
                instance_id,
                connection_id,
                sfu::Command {
                    request_id,
                    command: sfu::CommandKind::Signal(signal),
                },
                PendingCommand::Signal,
            );
            return Ok(SendResult::Sfu);
        }

        let peer_id = room.members.keys().find(|&&id| id != client_id).copied();
        let Some(peer_id) = peer_id else {
            let source = room.members.get_mut(&client_id).expect("member checked");
            push_queued(source, message)?;
            return Ok(SendResult::P2p(None));
        };
        if room
            .members
            .get(&peer_id)
            .is_some_and(|peer| peer.registered)
        {
            return Ok(SendResult::P2p(Some(Delivery {
                room_id,
                client_id: peer_id,
                message,
            })));
        }
        let source = room.members.get_mut(&client_id).expect("member checked");
        push_queued(source, message)?;
        Ok(SendResult::P2p(None))
    }

    pub fn handle_sfu_input(&mut self, input: sfu::Input) -> Result<(), String> {
        match input {
            sfu::Input::Register {
                connection_id,
                instance_id,
                request_id,
                capacity,
            } => self.register_worker(connection_id, instance_id, request_id, capacity),
            sfu::Input::CommandResult {
                connection_id,
                instance_id,
                result,
                now,
            } => self.handle_command_result(connection_id, &instance_id, result, now),
            sfu::Input::Event {
                connection_id,
                instance_id,
                event,
            } => self.handle_worker_event(connection_id, &instance_id, event),
            sfu::Input::Disconnected {
                connection_id,
                instance_id,
                now,
            } => {
                if let Some(worker) = self.workers.get_mut(&instance_id)
                    && worker.connection_id == Some(connection_id)
                {
                    worker.connection_id = None;
                    worker.health = None;
                    worker.disconnect_deadline = Some(now + self.reconnect_grace);
                }
                Ok(())
            }
        }
    }

    fn register_worker(
        &mut self,
        connection_id: sfu::ConnectionId,
        instance_id: String,
        request_id: u64,
        capacity: sfu::Capacity,
    ) -> Result<(), String> {
        if instance_id.is_empty()
            || request_id == 0
            || capacity.max_rooms == 0
            || capacity.max_clients == 0
        {
            self.actions
                .push_back(Action::Sfu(sfu::Output::RegistrationError {
                    connection_id,
                    request_id,
                    error: sfu::Error {
                        reason: "INVALID_REQUEST".into(),
                        retryable: false,
                    },
                }));
            return Ok(());
        }
        let resumed = self.workers.contains_key(&instance_id);
        let old_connection = self
            .workers
            .get(&instance_id)
            .and_then(|worker| worker.connection_id);
        let worker = self
            .workers
            .entry(instance_id.clone())
            .or_insert_with(|| Worker {
                connection_id: None,
                capacity,
                health: None,
                assigned_rooms: HashSet::new(),
                assigned_clients: 0,
                seen_events: HashSet::new(),
                seen_event_order: VecDeque::new(),
                disconnect_deadline: None,
            });
        worker.connection_id = Some(connection_id);
        worker.capacity = capacity;
        worker.health = None;
        worker.disconnect_deadline = None;
        if let Some(old_connection) = old_connection.filter(|old| *old != connection_id) {
            self.actions.push_back(Action::Sfu(sfu::Output::Close {
                connection_id: old_connection,
            }));
        }
        self.actions.push_back(Action::Sfu(sfu::Output::Registered {
            connection_id,
            request_id,
            health_interval_ms: HEALTH_INTERVAL_MS,
            resumed,
        }));
        let superseded_syncs = self
            .pending_commands
            .iter()
            .filter_map(|(&request_id, pending)| {
                matches!(
                    pending,
                    PendingCommand::SyncRoom {
                        instance_id: pending_instance,
                        ..
                    } if pending_instance == &instance_id
                )
                .then_some(request_id)
            })
            .collect::<Vec<_>>();
        for request_id in superseded_syncs {
            self.pending_commands.remove(&request_id);
            self.unacknowledged_commands.remove(&request_id);
            self.command_workers.remove(&request_id);
        }
        let mut assigned_rooms = self
            .workers
            .get(&instance_id)
            .map(|worker| worker.assigned_rooms.iter().copied().collect::<Vec<_>>())
            .unwrap_or_default();
        assigned_rooms.sort_unstable();
        for room_id in assigned_rooms {
            let Some(room) = self.rooms.get(&room_id) else {
                continue;
            };
            let assignment_epoch = room.assignment_epoch;
            let members = room
                .members
                .iter()
                .map(|(&client_id, member)| sfu::MemberProjection {
                    client_id,
                    lifecycle_id: member.lifecycle_id,
                })
                .collect();
            let replay = self
                .command_workers
                .iter()
                .filter(|(_, worker)| worker.as_str() == instance_id)
                .filter(|(request_id, _)| {
                    !matches!(
                        self.pending_commands.get(request_id),
                        Some(PendingCommand::SyncRoom { .. })
                    )
                })
                .filter_map(|(request_id, _)| self.unacknowledged_commands.get(request_id))
                .filter(|command| command_room_id(command) == Some(room_id))
                .cloned()
                .collect::<Vec<_>>();
            let request_id = self.next_command_id();
            self.queue_command(
                instance_id.clone(),
                connection_id,
                sfu::Command {
                    request_id,
                    command: sfu::CommandKind::SyncRoom(sfu::SyncRoom {
                        room_id,
                        assignment_epoch,
                        members,
                    }),
                },
                PendingCommand::SyncRoom {
                    instance_id: instance_id.clone(),
                    room_id,
                    assignment_epoch,
                    replay,
                },
            );
        }
        Ok(())
    }

    fn handle_worker_event(
        &mut self,
        connection_id: sfu::ConnectionId,
        instance_id: &str,
        event: sfu::Event,
    ) -> Result<(), String> {
        let worker = self.workers.get_mut(instance_id).ok_or("UNKNOWN_SFU")?;
        if worker.connection_id != Some(connection_id) || event.request_id == 0 {
            return Err("STALE_SFU_SESSION".into());
        }
        if worker.seen_events.contains(&event.request_id) {
            self.actions.push_back(Action::Sfu(sfu::Output::EventAck {
                connection_id,
                request_id: event.request_id,
            }));
            return Ok(());
        }
        worker.seen_events.insert(event.request_id);
        worker.seen_event_order.push_back(event.request_id);
        if worker.seen_event_order.len() > EVENT_DEDUP_CAPACITY
            && let Some(oldest) = worker.seen_event_order.pop_front()
        {
            worker.seen_events.remove(&oldest);
        }
        match event.event {
            sfu::EventKind::Health(health) => {
                log::info!(
                    "SFU health: instance_id={instance_id} connection_id={connection_id} request_id={} state={:?} rooms={} clients={}",
                    event.request_id,
                    health.state,
                    health.current_rooms,
                    health.current_clients
                );
                worker.capacity = health.capacity;
                worker.health = Some(health);
            }
            sfu::EventKind::Signal(signal) => {
                let room = self.rooms.get(&signal.room_id).ok_or("ROOM_NOT_FOUND")?;
                let member = room
                    .members
                    .get(&signal.client_id)
                    .ok_or("CLIENT_NOT_FOUND")?;
                if room.mode != RoomMode::Sfu
                    || room.assigned_instance.as_deref() != Some(instance_id)
                    || room.assignment_epoch != signal.assignment_epoch
                    || member.lifecycle_id != signal.lifecycle_id
                {
                    return Err("STALE_ASSIGNMENT".into());
                }
                // The worker-originated SDP (a publish answer or a server-initiated subscribe
                // re-offer) and its candidates. Log the body to show
                // the worker->signaling leg (before signaling relays it on to the browser).
                log::info!(
                    "SFU event: instance_id={instance_id} operation=signal room_id={} client_id={}\n{}",
                    format_room_token(&signal.room_id),
                    signal.client_id,
                    signal.message_json
                );
                self.actions.push_back(Action::Deliver(Delivery {
                    room_id: signal.room_id,
                    client_id: signal.client_id,
                    message: signal.message_json,
                }));
            }
            sfu::EventKind::Failure { error, room_id, .. } => {
                if let Some(room_id) = room_id {
                    self.fail_room(room_id, error.reason);
                }
            }
        }
        self.actions.push_back(Action::Sfu(sfu::Output::EventAck {
            connection_id,
            request_id: event.request_id,
        }));
        Ok(())
    }

    fn handle_command_result(
        &mut self,
        connection_id: sfu::ConnectionId,
        instance_id: &str,
        result: sfu::CommandResult,
        now: Instant,
    ) -> Result<(), String> {
        let worker = self.workers.get(instance_id).ok_or("UNKNOWN_SFU")?;
        if worker.connection_id != Some(connection_id) {
            return Err("STALE_SFU_SESSION".into());
        }
        let Some(pending) = self.pending_commands.remove(&result.request_id) else {
            log::debug!(
                "SFU command result deduplicated: instance_id={instance_id} connection_id={connection_id} request_id={}",
                result.request_id
            );
            return Ok(());
        };
        match &result.result {
            Ok(_) => log::info!(
                "SFU command result: instance_id={instance_id} connection_id={connection_id} request_id={} result=OK",
                result.request_id
            ),
            Err(error) => log::warn!(
                "SFU command result: instance_id={instance_id} connection_id={connection_id} request_id={} result=ERR reason={}",
                result.request_id,
                error.reason
            ),
        }
        self.unacknowledged_commands.remove(&result.request_id);
        self.command_workers.remove(&result.request_id);
        match pending {
            PendingCommand::SyncRoom {
                instance_id: expected_instance,
                room_id,
                assignment_epoch,
                replay,
            } => {
                let valid = matches!(
                    &result.result,
                    Ok(sfu::CommandOk::RoomSynced(synced))
                        if synced.room_id == room_id
                            && synced.assignment_epoch == assignment_epoch
                );
                if expected_instance != instance_id || !valid {
                    self.fail_room(room_id, "WORKER_UNAVAILABLE".into());
                } else {
                    for command in replay {
                        self.actions.push_back(Action::Sfu(sfu::Output::Command {
                            connection_id,
                            command,
                        }));
                    }
                }
            }
            PendingCommand::UpgradeJoin {
                instance_id: expected_instance,
                room_id,
                client_id,
                lifecycle_id,
                assignment_epoch,
            } => {
                let valid = matches!(
                    &result.result,
                    Ok(sfu::CommandOk::MemberJoined(joined))
                        if joined.room_id == room_id
                            && joined.client_id == client_id
                            && joined.lifecycle_id == lifecycle_id
                            && joined.assignment_epoch == assignment_epoch
                );
                if expected_instance != instance_id || !valid {
                    let reason = result.result.err().map_or_else(
                        || "INVALID_COMMAND_RESULT".to_string(),
                        |error| error.reason,
                    );
                    self.abort_upgrade(room_id, reason)?;
                    return Ok(());
                }
                let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
                let upgrade = room.upgrade.as_mut().ok_or("ROOM_TRANSITION")?;
                upgrade.joined_clients.push(client_id);
                upgrade.next_client += 1;
                if upgrade.next_client == upgrade.ordered_clients.len() {
                    self.commit_upgrade(room_id)?;
                } else {
                    self.issue_next_upgrade_join(room_id)?;
                }
            }
            PendingCommand::SfuJoin {
                instance_id: expected_instance,
                room_id,
                client_id,
                lifecycle_id,
                assignment_epoch,
            } => {
                let valid = matches!(
                    &result.result,
                    Ok(sfu::CommandOk::MemberJoined(joined))
                        if joined.room_id == room_id
                            && joined.client_id == client_id
                            && joined.lifecycle_id == lifecycle_id
                            && joined.assignment_epoch == assignment_epoch
                );
                let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
                let pending_join = room.pending_join.take().ok_or("ROOM_TRANSITION")?;
                if expected_instance == instance_id && valid {
                    if let Some(worker) = self.workers.get_mut(instance_id) {
                        worker.assigned_clients = worker.assigned_clients.saturating_add(1);
                    }
                    let member = room.members.get(&client_id).ok_or("CLIENT_NOT_FOUND")?;
                    self.actions.push_back(Action::AdmissionCompleted {
                        authority_request_id: pending_join.authority_request_id,
                        result: Ok(Admission {
                            mode: RoomMode::Sfu,
                            signal_epoch: room.signal_epoch,
                            admission_token: member.token.clone(),
                            is_initiator: None,
                        }),
                    });
                } else {
                    room.members.remove(&pending_join.client_id);
                    self.actions.push_back(Action::AdmissionCompleted {
                        authority_request_id: pending_join.authority_request_id,
                        result: Err(result
                            .result
                            .err()
                            .map_or_else(|| "INVALID_COMMAND_RESULT".into(), |error| error.reason)),
                    });
                }
            }
            PendingCommand::SfuLeave {
                instance_id: expected_instance,
                room_id,
                client_id,
                lifecycle_id,
                assignment_epoch,
            } => {
                let valid = matches!(
                    &result.result,
                    Ok(sfu::CommandOk::MemberLeft(left))
                        if left.room_id == room_id
                            && left.client_id == client_id
                            && left.lifecycle_id == lifecycle_id
                            && left.assignment_epoch == assignment_epoch
                );
                let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
                let pending_leave = room.pending_leave.take().ok_or("ROOM_TRANSITION")?;
                if expected_instance == instance_id && valid {
                    room.members.remove(&client_id);
                    if let Some(worker) = self.workers.get_mut(instance_id) {
                        worker.assigned_clients = worker.assigned_clients.saturating_sub(1);
                        if room.members.is_empty() {
                            worker.assigned_rooms.remove(&room_id);
                        }
                    }
                    if let Some(authority_request_id) = pending_leave.authority_request_id {
                        self.actions.push_back(Action::RemovalCompleted {
                            authority_request_id,
                            room_id,
                            client_id,
                            result: Ok(()),
                        });
                    }
                    if room.members.is_empty() {
                        self.rooms.remove(&room_id);
                    } else {
                        // A member left an SFU room; if it has shrunk to at most two
                        // members and is otherwise idle, start the downgrade dwell.
                        self.arm_downgrade(room_id, now);
                    }
                } else {
                    if let Some(authority_request_id) = pending_leave.authority_request_id {
                        self.actions.push_back(Action::RemovalCompleted {
                            authority_request_id,
                            room_id,
                            client_id,
                            result: Err(result.result.err().map_or_else(
                                || "INVALID_COMMAND_RESULT".into(),
                                |error| error.reason,
                            )),
                        });
                    }
                }
            }
            PendingCommand::Signal | PendingCommand::Cleanup => {}
        }
        Ok(())
    }

    fn issue_next_upgrade_join(&mut self, room_id: RoomId) -> Result<(), String> {
        let room = self.rooms.get(&room_id).ok_or("ROOM_NOT_FOUND")?;
        let upgrade = room.upgrade.as_ref().ok_or("ROOM_TRANSITION")?;
        let client_id = upgrade.ordered_clients[upgrade.next_client];
        let member = room.members.get(&client_id).ok_or("CLIENT_NOT_FOUND")?;
        let instance_id = room.assigned_instance.clone().ok_or("WORKER_UNAVAILABLE")?;
        let connection_id = self
            .workers
            .get(&instance_id)
            .and_then(|worker| worker.connection_id)
            .ok_or("WORKER_UNAVAILABLE")?;
        let join = sfu::JoinMember {
            room_id,
            client_id,
            lifecycle_id: member.lifecycle_id,
            assignment_epoch: room.assignment_epoch,
        };
        let request_id = self.next_command_id();
        self.queue_command(
            instance_id.clone(),
            connection_id,
            sfu::Command {
                request_id,
                command: sfu::CommandKind::Join(join.clone()),
            },
            PendingCommand::UpgradeJoin {
                instance_id,
                room_id,
                client_id,
                lifecycle_id: join.lifecycle_id,
                assignment_epoch: join.assignment_epoch,
            },
        );
        Ok(())
    }

    fn commit_upgrade(&mut self, room_id: RoomId) -> Result<(), String> {
        let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
        let upgrade = room.upgrade.take().ok_or("ROOM_TRANSITION")?;
        room.mode = RoomMode::Sfu;
        room.signal_epoch = room.signal_epoch.saturating_add(1);
        for member in room.members.values_mut() {
            member.queued_messages.clear();
            member.is_initiator = false;
        }
        let joining = room
            .members
            .get(&upgrade.joining_client_id)
            .ok_or("CLIENT_NOT_FOUND")?;
        let admission = Admission {
            mode: RoomMode::Sfu,
            signal_epoch: room.signal_epoch,
            admission_token: joining.token.clone(),
            is_initiator: None,
        };
        let existing_clients = room
            .members
            .keys()
            .copied()
            .filter(|client_id| *client_id != upgrade.joining_client_id)
            .collect();
        self.actions.push_back(Action::Upgraded {
            room_id,
            signal_epoch: room.signal_epoch,
            existing_clients,
        });
        self.actions.push_back(Action::AdmissionCompleted {
            authority_request_id: upgrade.authority_request_id,
            result: Ok(admission),
        });
        Ok(())
    }

    fn abort_upgrade(&mut self, room_id: RoomId, reason: String) -> Result<(), String> {
        let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
        let upgrade = room.upgrade.take().ok_or("ROOM_TRANSITION")?;
        room.members.remove(&upgrade.joining_client_id);
        room.mode = RoomMode::P2p;
        let instance_id = room.assigned_instance.take().ok_or("WORKER_UNAVAILABLE")?;
        let assignment_epoch = room.assignment_epoch;
        let connection_id = self
            .workers
            .get(&instance_id)
            .and_then(|worker| worker.connection_id);
        if let Some(worker) = self.workers.get_mut(&instance_id) {
            worker.assigned_rooms.remove(&room_id);
            worker.assigned_clients = worker.assigned_clients.saturating_sub(3);
        }
        if let Some(connection_id) = connection_id {
            for client_id in upgrade.joined_clients {
                let lifecycle_id = self
                    .rooms
                    .get(&room_id)
                    .and_then(|room| room.members.get(&client_id))
                    .map(|member| member.lifecycle_id)
                    .ok_or("CLIENT_NOT_FOUND")?;
                let request_id = self.next_command_id();
                self.queue_command(
                    instance_id.clone(),
                    connection_id,
                    sfu::Command {
                        request_id,
                        command: sfu::CommandKind::Leave(sfu::LeaveMember {
                            room_id,
                            client_id,
                            lifecycle_id,
                            assignment_epoch,
                            reason: sfu::LeaveReason::RoomClosed,
                        }),
                    },
                    PendingCommand::Cleanup,
                );
            }
        }
        self.actions.push_back(Action::AdmissionCompleted {
            authority_request_id: upgrade.authority_request_id,
            result: Err(if reason.is_empty() {
                "WORKER_UNAVAILABLE".into()
            } else {
                reason
            }),
        });
        Ok(())
    }

    /// True when `room_id` is a stable SFU room small enough to run as direct P2P
    /// again: SFU mode, at most two members, and no membership transition or
    /// unfinished worker leave in flight.
    fn is_downgrade_eligible(&self, room_id: RoomId) -> bool {
        self.rooms.get(&room_id).is_some_and(|room| {
            room.mode == RoomMode::Sfu
                && !room.members.is_empty()
                && room.members.len() <= MAX_P2P_MEMBERS
                && room.upgrade.is_none()
                && room.pending_join.is_none()
                && room.pending_leave.is_none()
        })
    }

    /// Arm (or leave armed) the downgrade dwell for an SFU room that has shrunk to
    /// at most two members; clear it otherwise. Idempotent — an already-armed
    /// deadline is preserved so churn within the dwell does not keep pushing it out.
    fn arm_downgrade(&mut self, room_id: RoomId, now: Instant) {
        let eligible = self.is_downgrade_eligible(room_id);
        if let Some(room) = self.rooms.get_mut(&room_id) {
            if eligible {
                if room.downgrade_deadline.is_none() {
                    room.downgrade_deadline = Some(now + self.downgrade_dwell);
                }
            } else {
                room.downgrade_deadline = None;
            }
        }
    }

    /// Break-before-make SFU→P2P downgrade. Commits P2P and a new signal epoch,
    /// elects the lowest client id as the direct offerer, tears down every member's
    /// SFU leg on the worker, frees the assignment, and emits `Downgraded` so each
    /// browser is told to close its SFU peer connection and negotiate directly.
    fn commit_downgrade(&mut self, room_id: RoomId) -> Result<(), String> {
        let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
        room.mode = RoomMode::P2p;
        room.signal_epoch = room.signal_epoch.saturating_add(1);
        room.downgrade_deadline = None;
        let assignment_epoch = room.assignment_epoch;
        let instance_id = room.assigned_instance.take();

        let mut clients: Vec<ClientId> = room.members.keys().copied().collect();
        clients.sort_unstable();
        let initiator_client_id = *clients.first().ok_or("CLIENT_NOT_FOUND")?;
        let mut leaving = Vec::with_capacity(clients.len());
        for (&client_id, member) in room.members.iter_mut() {
            member.is_initiator = client_id == initiator_client_id;
            member.queued_messages.clear();
            leaving.push((client_id, member.lifecycle_id));
        }
        let signal_epoch = room.signal_epoch;

        // Tear down the SFU legs of every member and free the worker assignment.
        if let Some(instance_id) = instance_id {
            let connection_id = self
                .workers
                .get(&instance_id)
                .and_then(|worker| worker.connection_id);
            if let Some(worker) = self.workers.get_mut(&instance_id) {
                worker.assigned_rooms.remove(&room_id);
                worker.assigned_clients = worker.assigned_clients.saturating_sub(leaving.len());
            }
            if let Some(connection_id) = connection_id {
                for (client_id, lifecycle_id) in &leaving {
                    let request_id = self.next_command_id();
                    self.queue_command(
                        instance_id.clone(),
                        connection_id,
                        sfu::Command {
                            request_id,
                            command: sfu::CommandKind::Leave(sfu::LeaveMember {
                                room_id,
                                client_id: *client_id,
                                lifecycle_id: *lifecycle_id,
                                assignment_epoch,
                                reason: sfu::LeaveReason::RoomClosed,
                            }),
                        },
                        PendingCommand::Cleanup,
                    );
                }
            }
        }

        self.actions.push_back(Action::Downgraded {
            room_id,
            signal_epoch,
            initiator_client_id,
            clients,
        });
        Ok(())
    }

    fn fail_room(&mut self, room_id: RoomId, reason: String) {
        if let Some(room) = self.rooms.get_mut(&room_id) {
            room.mode = RoomMode::Failed;
            let clients = room.members.keys().copied().collect();
            self.actions.push_back(Action::RoomFailed {
                room_id,
                clients,
                reason,
            });
        }
    }

    fn select_worker(&self, additional_clients: usize) -> Option<String> {
        self.workers
            .iter()
            .filter(|(_, worker)| {
                let Some(health) = worker.health else {
                    return false;
                };
                worker.connection_id.is_some()
                    && health.state == sfu::State::Ready
                    && worker.assigned_rooms.len() < worker.capacity.max_rooms as usize
                    && worker.assigned_clients.saturating_add(additional_clients)
                        <= worker.capacity.max_clients as usize
            })
            .min_by_key(|(instance_id, worker)| {
                (
                    worker.assigned_clients,
                    worker.assigned_rooms.len(),
                    *instance_id,
                )
            })
            .map(|(instance_id, _)| instance_id.clone())
    }

    fn next_lifecycle(&mut self, room_id: RoomId, client_id: ClientId) -> u64 {
        let value = self.lifecycle_ids.entry((room_id, client_id)).or_default();
        *value = value.saturating_add(1).max(1);
        *value
    }

    fn next_command_id(&mut self) -> u64 {
        let request_id = self.next_sfu_request_id;
        self.next_sfu_request_id = self.next_sfu_request_id.saturating_add(1).max(1);
        request_id
    }

    fn queue_command(
        &mut self,
        instance_id: String,
        connection_id: sfu::ConnectionId,
        command: sfu::Command,
        pending: PendingCommand,
    ) {
        let (operation, room_id, client_id) = match &command.command {
            sfu::CommandKind::SyncRoom(c) => ("sync_room", c.room_id, 0),
            sfu::CommandKind::Join(c) => ("join", c.room_id, c.client_id),
            sfu::CommandKind::Leave(c) => ("leave", c.room_id, c.client_id),
            sfu::CommandKind::Signal(c) => ("signal", c.room_id, c.client_id),
        };
        // A signal command forwards the browser's opaque SDP/candidate to the worker; append it
        // (like a browser send) to show label the hop by type and expand
        // the SDP. Other commands carry no such body.
        let body = match &command.command {
            sfu::CommandKind::Signal(c) => format!("\n{}", c.message_json),
            _ => String::new(),
        };
        let request_id = command.request_id;
        log::info!(
            "SFU command: instance_id={instance_id} connection_id={connection_id} request_id={request_id} operation={operation} room_id={} client_id={client_id}{body}",
            format_room_token(&room_id)
        );
        self.pending_commands.insert(command.request_id, pending);
        self.command_workers.insert(command.request_id, instance_id);
        self.unacknowledged_commands
            .insert(command.request_id, command.clone());
        self.actions.push_back(Action::Sfu(sfu::Output::Command {
            connection_id,
            command,
        }));
    }

    pub fn remove(
        &mut self,
        authority_request_id: u64,
        room_id: RoomId,
        client_id: ClientId,
        token: &str,
    ) -> Result<RemovalResult, String> {
        let room = self.rooms.get_mut(&room_id).ok_or("ROOM_NOT_FOUND")?;
        let member = room.members.get(&client_id).ok_or("CLIENT_NOT_FOUND")?;
        if !constant_time_eq(member.token.as_bytes(), token.as_bytes()) {
            return Err("UNAUTHORIZED".into());
        }
        if room.mode == RoomMode::Upgrading
            || room.pending_join.is_some()
            || room.pending_leave.is_some()
        {
            return Err("ROOM_TRANSITION".into());
        }
        if room.mode == RoomMode::Sfu {
            let instance_id = room.assigned_instance.clone().ok_or("WORKER_UNAVAILABLE")?;
            let connection_id = self
                .workers
                .get(&instance_id)
                .and_then(|worker| worker.connection_id)
                .ok_or("WORKER_UNAVAILABLE")?;
            let lifecycle_id = member.lifecycle_id;
            let room = self.rooms.get_mut(&room_id).expect("room checked");
            room.pending_leave = Some(PendingLeave {
                authority_request_id: Some(authority_request_id),
                client_id,
            });
            let assignment_epoch = room.assignment_epoch;
            let request_id = self.next_command_id();
            self.queue_command(
                instance_id.clone(),
                connection_id,
                sfu::Command {
                    request_id,
                    command: sfu::CommandKind::Leave(sfu::LeaveMember {
                        room_id,
                        client_id,
                        lifecycle_id,
                        assignment_epoch,
                        reason: sfu::LeaveReason::User,
                    }),
                },
                PendingCommand::SfuLeave {
                    instance_id,
                    room_id,
                    client_id,
                    lifecycle_id,
                    assignment_epoch,
                },
            );
            return Ok(RemovalResult::Pending);
        }
        if room.mode == RoomMode::Failed {
            room.members.remove(&client_id);
            if room.members.is_empty() {
                self.rooms.remove(&room_id);
            }
            return Ok(RemovalResult::Complete(None));
        }
        room.members.remove(&client_id);
        let promotion = promote_survivor(room_id, room);
        if room.members.is_empty() {
            self.rooms.remove(&room_id);
        }
        Ok(RemovalResult::Complete(promotion))
    }

    pub fn occupancy(&self, room_id: RoomId) -> (usize, RoomMode) {
        self.rooms
            .get(&room_id)
            .map_or((0, RoomMode::P2p), |room| (room.members.len(), room.mode))
    }

    pub fn room_count(&self) -> usize {
        self.rooms.len()
    }

    pub fn member_count(&self) -> usize {
        self.rooms.values().map(|room| room.members.len()).sum()
    }

    pub fn registered_count(&self) -> usize {
        self.rooms
            .values()
            .flat_map(|room| room.members.values())
            .filter(|member| member.registered)
            .count()
    }

    pub fn connected_sfu_count(&self) -> usize {
        self.workers
            .values()
            .filter(|worker| worker.connection_id.is_some())
            .count()
    }

    pub fn ready_sfu_count(&self) -> usize {
        self.workers
            .values()
            .filter(|worker| {
                worker.connection_id.is_some()
                    && worker
                        .health
                        .is_some_and(|health| health.state == sfu::State::Ready)
            })
            .count()
    }

    pub fn handle_timeout(&mut self, now: Instant) -> Vec<Promotion> {
        let mut promotions = Vec::new();
        let expired_workers = self
            .workers
            .iter()
            .filter_map(|(instance_id, worker)| {
                worker
                    .disconnect_deadline
                    .filter(|deadline| *deadline <= now)
                    .map(|_| instance_id.clone())
            })
            .collect::<Vec<_>>();
        for instance_id in expired_workers {
            self.expire_worker(&instance_id);
        }
        let room_ids = self.rooms.keys().copied().collect::<Vec<_>>();
        for room_id in room_ids {
            // SFU→P2P downgrade: the ≤2-member dwell has expired. Re-check eligibility
            // (a third member may have joined during the dwell) before committing.
            let downgrade_due = self
                .rooms
                .get(&room_id)
                .and_then(|room| room.downgrade_deadline)
                .is_some_and(|deadline| deadline <= now);
            if downgrade_due {
                if self.is_downgrade_eligible(room_id) {
                    let _ = self.commit_downgrade(room_id);
                } else if let Some(room) = self.rooms.get_mut(&room_id) {
                    room.downgrade_deadline = None;
                }
                continue;
            }
            let expired_sfu_client = self.rooms.get(&room_id).and_then(|room| {
                (room.mode == RoomMode::Sfu && room.pending_leave.is_none())
                    .then(|| {
                        room.members.iter().find_map(|(&client_id, member)| {
                            member
                                .reconnect_deadline
                                .filter(|deadline| *deadline <= now)
                                .map(|_| client_id)
                        })
                    })
                    .flatten()
            });
            if let Some(client_id) = expired_sfu_client {
                // Retry the leave that couldn't be issued when the browser disconnected (worker
                // was unavailable then); re-arm the grace if it still can't go out.
                if !self.issue_sfu_leave(room_id, client_id, sfu::LeaveReason::Disconnected)
                    && let Some(member) = self
                        .rooms
                        .get_mut(&room_id)
                        .and_then(|room| room.members.get_mut(&client_id))
                {
                    member.reconnect_deadline = Some(now + self.reconnect_grace);
                }
                continue;
            }
            let Some(room) = self.rooms.get_mut(&room_id) else {
                continue;
            };
            if room.mode != RoomMode::P2p {
                continue;
            }
            let expired = room
                .members
                .iter()
                .filter_map(|(&client_id, member)| {
                    member
                        .reconnect_deadline
                        .filter(|deadline| *deadline <= now)
                        .map(|_| client_id)
                })
                .collect::<Vec<_>>();
            for client_id in &expired {
                room.members.remove(client_id);
            }
            // Only an actual removal can produce a survivor to promote. Without this guard
            // the sweep re-promotes the lone member of every idle one-member P2P room on
            // each timeout — including rooms nothing happened in — and the browser reads a
            // `p2p-promote` as "the other side left".
            if !expired.is_empty()
                && let Some(promotion) = promote_survivor(room_id, room)
            {
                promotions.push(promotion);
            }
            if room.members.is_empty() {
                self.rooms.remove(&room_id);
            }
        }
        promotions
    }

    pub fn poll_timeout(&self) -> Option<Instant> {
        let browser_timeout = self
            .rooms
            .values()
            .filter(|room| {
                room.mode == RoomMode::P2p
                    || (room.mode == RoomMode::Sfu && room.pending_leave.is_none())
            })
            .flat_map(|room| {
                room.members
                    .values()
                    .filter_map(|member| member.reconnect_deadline)
            })
            .min();
        let worker_timeout = self
            .workers
            .values()
            .filter_map(|worker| worker.disconnect_deadline)
            .min();
        let downgrade_timeout = self
            .rooms
            .values()
            .filter_map(|room| room.downgrade_deadline)
            .min();
        [browser_timeout, worker_timeout, downgrade_timeout]
            .into_iter()
            .flatten()
            .min()
    }

    pub fn poll_action(&mut self) -> Option<Action> {
        self.actions.pop_front()
    }

    pub fn clear(&mut self) {
        self.rooms.clear();
        self.workers.clear();
        self.pending_commands.clear();
        self.unacknowledged_commands.clear();
        self.command_workers.clear();
        self.actions.clear();
    }

    fn expire_worker(&mut self, instance_id: &str) {
        let assigned_rooms = self
            .workers
            .get(instance_id)
            .map(|worker| worker.assigned_rooms.iter().copied().collect::<Vec<_>>())
            .unwrap_or_default();
        for room_id in assigned_rooms {
            if self
                .rooms
                .get(&room_id)
                .is_some_and(|room| room.mode == RoomMode::Upgrading)
            {
                let _ = self.abort_upgrade(room_id, "WORKER_UNAVAILABLE".into());
                continue;
            }
            let Some(room) = self.rooms.get_mut(&room_id) else {
                continue;
            };
            if let Some(join) = room.pending_join.take() {
                room.members.remove(&join.client_id);
                self.actions.push_back(Action::AdmissionCompleted {
                    authority_request_id: join.authority_request_id,
                    result: Err("WORKER_UNAVAILABLE".into()),
                });
            }
            if let Some(leave) = room.pending_leave.take()
                && let Some(authority_request_id) = leave.authority_request_id
            {
                self.actions.push_back(Action::RemovalCompleted {
                    authority_request_id,
                    room_id,
                    client_id: leave.client_id,
                    result: Err("WORKER_UNAVAILABLE".into()),
                });
            }
            room.mode = RoomMode::Failed;
            self.actions.push_back(Action::RoomFailed {
                room_id,
                clients: room.members.keys().copied().collect(),
                reason: "WORKER_UNAVAILABLE".into(),
            });
        }
        let request_ids = self
            .command_workers
            .iter()
            .filter_map(|(&request_id, worker)| (worker == instance_id).then_some(request_id))
            .collect::<Vec<_>>();
        for request_id in request_ids {
            self.command_workers.remove(&request_id);
            self.unacknowledged_commands.remove(&request_id);
            self.pending_commands.remove(&request_id);
        }
        if let Some(worker) = self.workers.get_mut(instance_id) {
            worker.disconnect_deadline = None;
            worker.assigned_rooms.clear();
            worker.assigned_clients = 0;
        }
    }
}

fn new_member(
    now: Instant,
    reconnect_grace: Duration,
    token: String,
    is_initiator: bool,
    lifecycle_id: u64,
) -> Member {
    Member {
        token,
        is_initiator,
        lifecycle_id,
        registered: false,
        reconnect_deadline: Some(now + reconnect_grace),
        queued_messages: VecDeque::new(),
    }
}

fn push_queued(member: &mut Member, message: String) -> Result<(), String> {
    if member.queued_messages.len() >= MAX_QUEUED_MESSAGES {
        return Err("RESOURCE_EXHAUSTED".into());
    }
    member.queued_messages.push_back(message);
    Ok(())
}

fn command_room_id(command: &sfu::Command) -> Option<RoomId> {
    match &command.command {
        sfu::CommandKind::SyncRoom(command) => Some(command.room_id),
        sfu::CommandKind::Join(command) => Some(command.room_id),
        sfu::CommandKind::Leave(command) => Some(command.room_id),
        sfu::CommandKind::Signal(command) => Some(command.room_id),
    }
}

fn promote_survivor(room_id: RoomId, room: &mut Room) -> Option<Promotion> {
    if room.members.len() != 1 || room.mode != RoomMode::P2p {
        return None;
    }
    let (&client_id, member) = room.members.iter_mut().next()?;
    member.is_initiator = true;
    member.queued_messages.clear();
    member.registered.then_some(Promotion {
        room_id,
        client_id,
        signal_epoch: room.signal_epoch,
    })
}

fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    if left.len() != right.len() {
        return false;
    }
    left.iter()
        .zip(right)
        .fold(0_u8, |difference, (&left, &right)| {
            difference | (left ^ right)
        })
        == 0
}

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

    /// A deterministic, valid room id for tests: `new_v8` stamps the version and variant
    /// over the seed, so `room(42)` is stable across runs and still parses as a token.
    fn room(seed: u128) -> RoomId {
        Uuid::new_v8(seed.to_be_bytes())
    }

    #[test]
    fn room_tokens_round_trip_and_are_22_characters() {
        for seed in [0, 1, 42, u128::MAX] {
            let id = room(seed);
            let token = format_room_token(&id);
            assert_eq!(token.len(), ROOM_TOKEN_LEN, "token {token:?}");
            assert_eq!(parse_room_token(&token), Some(id));
        }
        let minted = new_room_id();
        assert!(is_room_uuid(&minted), "minted id must be a UUIDv8");
        assert_eq!(parse_room_token(&format_room_token(&minted)), Some(minted));
    }

    #[test]
    fn room_token_parsing_rejects_every_non_canonical_spelling() {
        let id = room(42);
        let token = format_room_token(&id);

        // 128 bits is not a multiple of 6, so the final character carries 4 must-be-zero
        // bits. Flipping any of them yields a string that decodes to the same UUID — if it
        // were accepted, one room would answer to sixteen different links.
        let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        let last = alphabet.find(token.chars().last().unwrap()).unwrap();
        for bump in 1..16 {
            let twin: String = token[..ROOM_TOKEN_LEN - 1]
                .chars()
                .chain(alphabet.chars().nth(last + bump))
                .collect();
            assert_ne!(twin, token);
            assert_eq!(parse_room_token(&twin), None, "accepted twin {twin:?}");
        }

        for invalid in [
            "",
            "short",
            &token[..ROOM_TOKEN_LEN - 1],                  // too short
            &format!("{token}A"),                          // too long
            &format!("{}=", &token[..ROOM_TOKEN_LEN - 1]), // padded
            &token.to_lowercase(), // case-folded: a different UUID or invalid
            "не-ascii-токен-2222222",
        ] {
            assert_eq!(parse_room_token(invalid), None, "accepted {invalid:?}");
        }

        // A v4 UUID is well-formed but is not something this service minted.
        let v4 = Uuid::new_v4();
        assert!(!is_room_uuid(&v4));
        assert_eq!(
            parse_room_token(&URL_SAFE_NO_PAD.encode(v4.as_bytes())),
            None,
            "a non-v8 UUID must not parse as a room token"
        );
    }

    fn register_ready_worker(rooms: &mut RoomTable) {
        rooms
            .handle_sfu_input(sfu::Input::Register {
                connection_id: 9,
                instance_id: "worker-1".into(),
                request_id: 1,
                capacity: sfu::Capacity {
                    max_rooms: 10,
                    max_clients: 100,
                },
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::Sfu(sfu::Output::Registered { .. }))
        ));
        rooms
            .handle_sfu_input(sfu::Input::Event {
                connection_id: 9,
                instance_id: "worker-1".into(),
                event: sfu::Event {
                    request_id: 2,
                    event: sfu::EventKind::Health(sfu::Health {
                        state: sfu::State::Ready,
                        capacity: sfu::Capacity {
                            max_rooms: 10,
                            max_clients: 100,
                        },
                        current_rooms: 0,
                        current_clients: 0,
                    }),
                },
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::Sfu(sfu::Output::EventAck { .. }))
        ));
    }

    #[test]
    fn admission_registration_relay_and_promotion() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));
        let first = match rooms
            .admit(1, now, room(42), 101, "token-1".into())
            .unwrap()
        {
            AdmissionResult::Complete(value) => value,
            AdmissionResult::Pending => panic!("first join cannot be pending"),
        };
        let second = match rooms
            .admit(2, now, room(42), 102, "token-2".into())
            .unwrap()
        {
            AdmissionResult::Complete(value) => value,
            AdmissionResult::Pending => panic!("second join cannot be pending"),
        };
        assert_eq!(first.is_initiator, Some(true));
        assert_eq!(second.is_initiator, Some(false));
        assert_eq!(
            rooms.admit(3, now, room(42), 103, "token-3".into()),
            Err("NO_SFU_AVAILABLE".into())
        );
        rooms
            .register(room(42), 101, &first.admission_token)
            .unwrap();
        rooms
            .register(room(42), 102, &second.admission_token)
            .unwrap();
        assert!(matches!(
            rooms.send(room(42), 101, 0, "candidate".into()).unwrap(),
            SendResult::P2p(Some(Delivery { client_id: 102, .. }))
        ));
        let promotion = match rooms
            .remove(3, room(42), 102, &second.admission_token)
            .unwrap()
        {
            RemovalResult::Complete(Some(promotion)) => promotion,
            result => panic!("unexpected removal result: {result:?}"),
        };
        assert_eq!(promotion.client_id, 101);
    }

    /// A lone member waiting for a peer must never be promoted by a timeout. The sweep runs
    /// for every room whenever any deadline in the table fires, so an unrelated room's
    /// reconnect grace used to hand this room's only member a `p2p-promote`, which its
    /// browser renders as "the remote side hung up".
    #[test]
    fn idle_single_member_room_is_not_promoted_by_an_unrelated_timeout() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));

        // Room 7: two members, one of which disconnects and starts its reconnect grace.
        let leaving = match rooms
            .admit(1, now, room(7), 701, "token-701".into())
            .unwrap()
        {
            AdmissionResult::Complete(value) => value,
            result => panic!("unexpected admission: {result:?}"),
        };
        let staying = match rooms
            .admit(2, now, room(7), 702, "token-702".into())
            .unwrap()
        {
            AdmissionResult::Complete(value) => value,
            result => panic!("unexpected admission: {result:?}"),
        };
        rooms
            .register(room(7), 701, &leaving.admission_token)
            .unwrap();
        rooms
            .register(room(7), 702, &staying.admission_token)
            .unwrap();
        rooms.deregister(now, room(7), 701);

        // Room 42: a single registered member waiting for someone to join.
        let alone = match rooms
            .admit(3, now, room(42), 101, "token-101".into())
            .unwrap()
        {
            AdmissionResult::Complete(value) => value,
            result => panic!("unexpected admission: {result:?}"),
        };
        rooms
            .register(room(42), 101, &alone.admission_token)
            .unwrap();

        // Room 7's grace expires. Its survivor is promoted; room 42 must be untouched.
        let promotions = rooms.handle_timeout(now + Duration::from_secs(11));
        assert_eq!(
            promotions.len(),
            1,
            "only room 7 may promote: {promotions:?}"
        );
        assert_eq!(promotions[0].room_id, room(7));
        assert_eq!(promotions[0].client_id, 702);

        // And a later sweep with nothing pending promotes nobody at all.
        assert!(
            rooms
                .handle_timeout(now + Duration::from_secs(30))
                .is_empty(),
            "an idle sweep must not promote anyone"
        );
    }

    #[test]
    fn third_join_commits_only_after_all_worker_join_results() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));
        register_ready_worker(&mut rooms);
        for (request, client) in [(10, 101), (11, 102)] {
            assert!(matches!(
                rooms
                    .admit(request, now, room(42), client, format!("token-{client}"))
                    .unwrap(),
                AdmissionResult::Complete(_)
            ));
        }
        assert_eq!(
            rooms
                .admit(12, now, room(42), 103, "token-103".into())
                .unwrap(),
            AdmissionResult::Pending
        );
        for expected_client in [101, 102, 103] {
            let command = match rooms.poll_action().unwrap() {
                Action::Sfu(sfu::Output::Command { command, .. }) => command,
                action => panic!("unexpected action: {action:?}"),
            };
            let join = match command.command {
                sfu::CommandKind::Join(join) => join,
                _ => panic!("expected join command"),
            };
            assert_eq!(join.client_id, expected_client);
            rooms
                .handle_sfu_input(sfu::Input::CommandResult {
                    connection_id: 9,
                    instance_id: "worker-1".into(),
                    result: sfu::CommandResult {
                        request_id: command.request_id,
                        result: Ok(sfu::CommandOk::MemberJoined(join)),
                    },
                    now,
                })
                .unwrap();
        }
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::Upgraded {
                signal_epoch: 1,
                ..
            })
        ));
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::AdmissionCompleted {
                authority_request_id: 12,
                result: Ok(Admission {
                    mode: RoomMode::Sfu,
                    is_initiator: None,
                    ..
                }),
            })
        ));
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Sfu));

        assert_eq!(
            rooms
                .admit(13, now, room(42), 104, "token-104".into())
                .unwrap(),
            AdmissionResult::Pending
        );
        let command = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("unexpected action: {action:?}"),
        };
        let join = match command.command {
            sfu::CommandKind::Join(join) => join,
            _ => panic!("expected join command"),
        };
        rooms
            .handle_sfu_input(sfu::Input::CommandResult {
                connection_id: 9,
                instance_id: "worker-1".into(),
                result: sfu::CommandResult {
                    request_id: command.request_id,
                    result: Ok(sfu::CommandOk::MemberJoined(join)),
                },
                now,
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::AdmissionCompleted {
                authority_request_id: 13,
                result: Ok(Admission {
                    mode: RoomMode::Sfu,
                    ..
                }),
            })
        ));
        assert_eq!(rooms.occupancy(room(42)), (4, RoomMode::Sfu));

        assert_eq!(
            rooms.remove(14, room(42), 104, "token-104").unwrap(),
            RemovalResult::Pending
        );
        let command = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("unexpected action: {action:?}"),
        };
        let leave = match command.command {
            sfu::CommandKind::Leave(leave) => leave,
            _ => panic!("expected leave command"),
        };
        rooms
            .handle_sfu_input(sfu::Input::CommandResult {
                connection_id: 9,
                instance_id: "worker-1".into(),
                result: sfu::CommandResult {
                    request_id: command.request_id,
                    result: Ok(sfu::CommandOk::MemberLeft(leave)),
                },
                now,
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::RemovalCompleted {
                authority_request_id: 14,
                result: Ok(()),
                ..
            })
        ));
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Sfu));

        assert_eq!(
            rooms.send(room(42), 101, 1, r#"{"type":"candidate"}"#.into()),
            Ok(SendResult::Sfu)
        );
        let pending_signal = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("unexpected signal action: {action:?}"),
        };
        rooms
            .handle_sfu_input(sfu::Input::Disconnected {
                connection_id: 9,
                instance_id: "worker-1".into(),
                now,
            })
            .unwrap();
        rooms
            .handle_sfu_input(sfu::Input::Register {
                connection_id: 10,
                instance_id: "worker-1".into(),
                request_id: 50,
                capacity: sfu::Capacity {
                    max_rooms: 10,
                    max_clients: 100,
                },
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::Sfu(sfu::Output::Registered { resumed: true, .. }))
        ));
        let sync = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("unexpected reconnect action: {action:?}"),
        };
        let sync_room = match sync.command {
            sfu::CommandKind::SyncRoom(sync_room) => sync_room,
            _ => panic!("expected room synchronization"),
        };
        assert!(
            rooms.poll_action().is_none(),
            "replay must wait for RoomSynced"
        );
        rooms
            .handle_sfu_input(sfu::Input::CommandResult {
                connection_id: 10,
                instance_id: "worker-1".into(),
                result: sfu::CommandResult {
                    request_id: sync.request_id,
                    result: Ok(sfu::CommandOk::RoomSynced(sfu::RoomSynced {
                        room_id: sync_room.room_id,
                        assignment_epoch: sync_room.assignment_epoch,
                    })),
                },
                now,
            })
            .unwrap();
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::Sfu(sfu::Output::Command { command, connection_id: 10 }))
                if command == pending_signal
        ));
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Sfu));
    }

    #[test]
    fn worker_disconnect_grace_expires_assigned_rooms() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));
        register_ready_worker(&mut rooms);
        for (request, client) in [(10, 101), (11, 102)] {
            rooms
                .admit(request, now, room(42), client, format!("token-{client}"))
                .unwrap();
        }
        rooms
            .admit(12, now, room(42), 103, "token-103".into())
            .unwrap();
        for _ in 0..3 {
            let command = match rooms.poll_action().unwrap() {
                Action::Sfu(sfu::Output::Command { command, .. }) => command,
                action => panic!("unexpected action: {action:?}"),
            };
            let join = match command.command {
                sfu::CommandKind::Join(join) => join,
                _ => panic!("expected join"),
            };
            rooms
                .handle_sfu_input(sfu::Input::CommandResult {
                    connection_id: 9,
                    instance_id: "worker-1".into(),
                    result: sfu::CommandResult {
                        request_id: command.request_id,
                        result: Ok(sfu::CommandOk::MemberJoined(join)),
                    },
                    now,
                })
                .unwrap();
        }
        assert!(matches!(rooms.poll_action(), Some(Action::Upgraded { .. })));
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::AdmissionCompleted { .. })
        ));
        rooms
            .handle_sfu_input(sfu::Input::Disconnected {
                connection_id: 9,
                instance_id: "worker-1".into(),
                now,
            })
            .unwrap();
        rooms.handle_timeout(now + Duration::from_secs(10));
        assert!(matches!(
            rooms.poll_action(),
            Some(Action::RoomFailed { room_id, .. }) if room_id == room(42)
        ));
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Failed));
    }

    #[test]
    fn sfu_member_disconnect_issues_immediate_leave() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));
        register_ready_worker(&mut rooms);
        let first = match rooms
            .admit(10, now, room(42), 101, "token-101".into())
            .unwrap()
        {
            AdmissionResult::Complete(admission) => admission,
            result => panic!("unexpected admission: {result:?}"),
        };
        rooms
            .admit(11, now, room(42), 102, "token-102".into())
            .unwrap();
        rooms
            .admit(12, now, room(42), 103, "token-103".into())
            .unwrap();
        for _ in 0..3 {
            let command = match rooms.poll_action().unwrap() {
                Action::Sfu(sfu::Output::Command { command, .. }) => command,
                action => panic!("unexpected action: {action:?}"),
            };
            let join = match command.command {
                sfu::CommandKind::Join(join) => join,
                _ => panic!("expected join"),
            };
            rooms
                .handle_sfu_input(sfu::Input::CommandResult {
                    connection_id: 9,
                    instance_id: "worker-1".into(),
                    result: sfu::CommandResult {
                        request_id: command.request_id,
                        result: Ok(sfu::CommandOk::MemberJoined(join)),
                    },
                    now,
                })
                .unwrap();
        }
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Sfu));

        // Register client 101's browser WebSocket, then drain the upgrade/registration actions.
        rooms
            .register(room(42), 101, &first.admission_token)
            .unwrap();
        while rooms.poll_action().is_some() {}

        // The WebSocket drops (browser close/refresh). An SFU member must be left immediately —
        // no reconnect grace — so the worker stops forwarding its media right away.
        rooms.deregister(now, room(42), 101);
        let command = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("expected immediate leave command, got: {action:?}"),
        };
        let leave = match command.command {
            sfu::CommandKind::Leave(leave) => leave,
            other => panic!("expected leave, got: {other:?}"),
        };
        assert_eq!(leave.room_id, room(42));
        assert_eq!(leave.client_id, 101);
        assert!(matches!(leave.reason, sfu::LeaveReason::Disconnected));
        assert!(rooms.poll_action().is_none());
    }

    #[test]
    fn sfu_room_downgrades_to_p2p_after_dwell_at_two_members() {
        let now = Instant::now();
        let mut rooms = RoomTable::new(Duration::from_secs(10));
        register_ready_worker(&mut rooms);
        let tokens = [(10, 101), (11, 102), (12, 103)].map(|(request, client)| {
            match rooms
                .admit(request, now, room(42), client, format!("token-{client}"))
                .unwrap()
            {
                AdmissionResult::Complete(admission) => (client, admission.admission_token),
                AdmissionResult::Pending => (client, format!("token-{client}")),
            }
        });
        for _ in 0..3 {
            let command = match rooms.poll_action().unwrap() {
                Action::Sfu(sfu::Output::Command { command, .. }) => command,
                action => panic!("unexpected action: {action:?}"),
            };
            let join = match command.command {
                sfu::CommandKind::Join(join) => join,
                _ => panic!("expected join"),
            };
            rooms
                .handle_sfu_input(sfu::Input::CommandResult {
                    connection_id: 9,
                    instance_id: "worker-1".into(),
                    result: sfu::CommandResult {
                        request_id: command.request_id,
                        result: Ok(sfu::CommandOk::MemberJoined(join)),
                    },
                    now,
                })
                .unwrap();
        }
        assert_eq!(rooms.occupancy(room(42)), (3, RoomMode::Sfu));
        // Register the members so they carry no reconnect deadline (as real SFU members do).
        for (client, token) in &tokens {
            rooms.register(room(42), *client, token).unwrap();
        }
        while rooms.poll_action().is_some() {}

        // The third member leaves; drive its MemberLeft so the room shrinks to two.
        assert_eq!(
            rooms.remove(14, room(42), 103, "token-103").unwrap(),
            RemovalResult::Pending
        );
        let command = match rooms.poll_action().unwrap() {
            Action::Sfu(sfu::Output::Command { command, .. }) => command,
            action => panic!("unexpected action: {action:?}"),
        };
        let leave = match command.command {
            sfu::CommandKind::Leave(leave) => leave,
            _ => panic!("expected leave"),
        };
        rooms
            .handle_sfu_input(sfu::Input::CommandResult {
                connection_id: 9,
                instance_id: "worker-1".into(),
                result: sfu::CommandResult {
                    request_id: command.request_id,
                    result: Ok(sfu::CommandOk::MemberLeft(leave)),
                },
                now,
            })
            .unwrap();
        while rooms.poll_action().is_some() {}
        assert_eq!(rooms.occupancy(room(42)), (2, RoomMode::Sfu));

        // The dwell is armed and does not fire early.
        assert!(rooms.poll_timeout().is_some());
        rooms.handle_timeout(now + Duration::from_secs(1));
        assert_eq!(
            rooms.occupancy(room(42)),
            (2, RoomMode::Sfu),
            "downgrade must wait out the dwell"
        );
        assert!(rooms.poll_action().is_none());

        // After the dwell, the room downgrades to direct P2P.
        rooms.handle_timeout(now + DOWNGRADE_DWELL + Duration::from_secs(1));
        assert_eq!(rooms.occupancy(room(42)), (2, RoomMode::P2p));

        let mut leaves = 0;
        let mut downgraded = false;
        while let Some(action) = rooms.poll_action() {
            match action {
                Action::Sfu(sfu::Output::Command { command, .. }) => {
                    assert!(matches!(command.command, sfu::CommandKind::Leave(_)));
                    leaves += 1;
                }
                Action::Downgraded {
                    room_id,
                    signal_epoch,
                    initiator_client_id,
                    mut clients,
                } => {
                    assert_eq!(room_id, room(42));
                    assert_eq!(signal_epoch, 2, "P2P->SFU->P2P bumps the epoch twice");
                    assert_eq!(initiator_client_id, 101, "lowest client id offers");
                    clients.sort_unstable();
                    assert_eq!(clients, vec![101, 102]);
                    downgraded = true;
                }
                other => panic!("unexpected action after downgrade: {other:?}"),
            }
        }
        assert_eq!(leaves, 2, "both remaining members' SFU legs must be left");
        assert!(downgraded, "a Downgraded control must be emitted");

        // A fresh third join can upgrade the room again.
        assert_eq!(
            rooms
                .admit(20, now, room(42), 104, "token-104".into())
                .unwrap(),
            AdmissionResult::Pending
        );
        assert!(matches!(
            rooms.occupancy(room(42)),
            (3, RoomMode::Upgrading)
        ));
    }
}