jmap-scene-server 0.6.2

JMAP Scene method handlers (draft-atwood-jmap-scene-00 SceneAsset) — backend-agnostic, plugs into jmap-server Dispatcher
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
//! In-memory reference implementation of [`SceneBackend`].
//!
//! # This is a reference implementation, not production
//!
//! `MemoryBackend` backs this crate's integration tests and is a readable
//! example for anyone writing a real backend. All state lives in
//! `HashMap`s behind a `std::sync::Mutex`; nothing is persisted. Blobs are
//! registered by size only, with `add_blob`.
//!
//! # Caller context
//!
//! `CallerCtx` is a type implementing [`MemoryCaller`](jmap_server::MemoryCaller):
//! the caller's Principal id ([`Id`](jmap_types::Id), the default), whose
//! string is the caller's `userId`, or `()` for a deployment without
//! identity, whose every caller acts as the user named by the account id.
//! The owner of an asset or
//! a region is its `ownerId`;
//! [`SceneBackend::may_modify_asset`] and
//! [`SceneBackend::may_update_region`] allow the owner and the users
//! registered with `add_admin`, and so does
//! [`SceneBackend::may_destroy_region`]. [`SceneBackend::may_modify_object`] allows the object's
//! owner, its region's owner and the admins; a created object's `ownerId`
//! is the caller.
//!
//! # Accounts
//!
//! An account exists once
//! [`MemoryBackend::with_account`](crate::memory::MemoryBackend::with_account) (or
//! [`MemoryBackend::register_account`](crate::memory::MemoryBackend::register_account)) registers it with the Scene
//! capability object it advertises; every call naming any other account is
//! `accountNotFound` (RFC 8620 §3.6.2).
//!
//! # Avatars
//!
//! [`SceneBackend::caller_user_id`] is the caller.
//! [`SceneBackend::may_enter_region`] refuses the users barred from a
//! region with `ban_from_region`. [`SceneBackend::may_eject_avatar`] allows the avatar's
//! region owner and the admins. Each region's `activeAvatarCount` is
//! recomputed from its avatars with `leftAt` `null` whenever an avatar
//! enters or leaves.
//!
//! # Interactions
//!
//! [`SceneBackend::accept_interaction`] refuses the interactions of users
//! registered with `rate_limit_interactions` and records the rest, read
//! back with `accepted_interactions`.
//! [`SceneBackend::accept_region_event`] does the same for region events
//! with `rate_limit_region_events` and `accepted_region_events`.
//!
//! # Visibility
//!
//! [`SceneBackend::may_access_region`] refuses an `"invite"` region to
//! everyone but its owner, the admins, the users in its `invitedUserIds`,
//! the users given access with `grant_region_access` (one of the "other
//! mechanisms" an `"invite"` region MAY admit by) and the users with an
//! active avatar in it; other policies, and a region that is not stored,
//! admit everyone (there are no Spaces here). `hide_object` takes an object out of one user's
//! visibility set, for [`SceneBackend::is_object_visible`]; `block` makes
//! one user blocked by another, for [`SceneBackend::is_user_blocked`];
//! `hide_region_avatars` hides a region's avatars from one user, as for a
//! region bound to an E2EE call, for
//! [`SceneBackend::may_see_region_avatars`].
//! `reserve_display_name` adds a name to the list
//! [`SceneBackend::reserved_display_names`] returns for every account.
//! `/query` omits the regions, objects and avatars those hooks hide from
//! the caller; `activeAvatarCount` stays the true count.
//!
//! [`SceneBackend::avatar_view`] follows per-account rules: `hide_avatar`
//! hides one avatar from one viewer, `withhold_avatar` withholds an
//! [`AvatarRedaction`]'s properties, and
//! `reveal_avatar` undoes either. Each advances the account's SceneAvatar
//! state. The avatar's own user, the region owner and the admins always
//! see it in full. `SceneAvatar/query` leaves hidden avatars out and
//! matches the redacted values. Once an account has a rule,
//! `SceneAvatar/changes` answers from the caller's view, from snapshots
//! kept per state; a state from before the first rule is
//! `cannotCalculateChanges`.
//!
//! # Observers
//!
//! `set_supports_observe` turns on [`SceneBackend::supports_observe`].
//! [`SceneBackend::observer_accounts`] is every registered account (or
//! the list given to `restrict_observer_accounts`),
//! [`SceneBackend::may_observe_region`] declines the regions registered
//! with `decline_observers` (until `admit_observers`), and
//! [`SceneBackend::set_observing`] counts each user's observing
//! connections per region. A region's `observerCount` is the users
//! observing it who have access and no active avatar there, or `0` while
//! `allowObservers` is `false` or the region declines observers. It is
//! recomputed, advancing the SceneRegion state when it changes, whenever
//! any of those inputs changes: an observer starts or stops, an avatar
//! enters or leaves, the region is updated, and the knobs that change
//! access or the observer policy from outside the region
//! (`grant_region_access`, `revoke_region_access`, `add_admin`,
//! `decline_observers`, `admit_observers`). There are no Spaces here, so
//! no other access change exists.
//!
//! # Companion capabilities and bindings
//!
//! `advertise` records a capability URI for an account, for
//! [`SceneBackend::has_capability`]. `set_region_binding` records what a
//! binding id references; [`SceneBackend::region_binding`] answers
//! [`BindingTarget::Missing`] for any id not recorded. `set_channel_space`
//! records that a channel belongs to a Space;
//! [`SceneBackend::channel_in_space`] answers `false` for any pair not
//! recorded.
//!
//! # Quota
//!
//! `set_storage_quota` sets an account's total asset storage in bytes;
//! [`SceneBackend::create_object`] refuses a `SceneAsset` that would
//! exceed it, a `SceneRegion` beyond the capability's
//! `maxRegionsPerAccount`, and a `SceneObject` beyond its
//! `maxObjectsPerRegion`, with `overQuota`.
//!
//! # Region destroy
//!
//! Destroying a `SceneRegion` also destroys the stored `SceneObject` and
//! `SceneAvatar` records whose `regionId` names it. Destroying a
//! `SceneObject` also destroys its descendants, in the same state step.
//!
//! # Query
//!
//! `SceneAsset/query`, `SceneRegion/query`, `SceneObject/query` and
//! `SceneAvatar/query` evaluate the filter and sort
//! with the [`crate::query`] functions. `/queryChanges` is not implemented: results
//! say `canCalculateChanges: false` and `/queryChanges` returns
//! `cannotCalculateChanges` (RFC 8620 §5.6).
//!
//! # Concurrency
//!
//! The `await_holding_lock` lint is denied module-wide: no guard is held
//! across an `.await`.

#![deny(clippy::await_holding_lock)]

mod history;

use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;

use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
use jmap_scene_types::{
    AccessPolicy, SceneAsset, SceneAvatar, SceneCapability, SceneInteractionEvent, SceneObject,
    SceneRegion, SceneRegionEvent,
};
use jmap_scene_types::{
    SceneAssetComparator, SceneAssetFilter, SceneAvatarComparator, SceneAvatarFilter,
    SceneObjectComparator, SceneObjectFilter, SceneRegionComparator, SceneRegionFilter,
};
use jmap_server::{
    BeginSetError, ConditionalBackend, DeferredFailure, MemoryCaller, ScopedGuard, ScopedState,
    SetOp, SetScope, SetScopeRequest, apply_patch_object, limit_or_max, resolve_query_start,
};
use jmap_types::{Id, State};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};

use crate::query::{
    asset_matches, avatar_matches, compare_assets, compare_avatars, compare_objects,
    compare_regions, object_matches, region_local_position, region_matches,
};
use crate::{AvatarRedaction, AvatarView, BindingProperty, BindingTarget, SceneBackend};
use jmap_server::{
    BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
    JmapAccounts, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult, QueryObject,
    QueryParams, QueryResult, SetError, SetErrorType, SetObject,
};

/// How one id changed in one state step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Change {
    Created,
    Updated,
    Destroyed,
    /// Restored from object history (draft-ietf-jmap-object-history §5.1).
    Restored,
}

/// `type_name` → `account_id` → `V`. Nested rather than tuple-keyed so a
/// lookup borrows the `&str` account id instead of allocating a `String`.
type Keyed<V> = HashMap<&'static str, HashMap<String, V>>;

/// The avatar changes and the regions to recount that [`Inner::admit`]
/// leaves for its caller to commit.
type Admitted = (Vec<(Id, Change)>, Vec<Id>);

/// The per-avatar visibility rules of one account (§Avatar Visibility).
#[derive(Default, Clone)]
struct AvatarRules {
    /// `(viewer userId, avatar id)` pairs: the avatar is hidden from the
    /// viewer.
    hidden: HashSet<(String, Id)>,
    /// `(viewer userId, avatar id)` → the properties withheld from the
    /// viewer.
    withheld: HashMap<(String, Id), AvatarRedaction>,
}

/// One `SceneAvatar` state of an account with [`AvatarRules`]: what every
/// caller's view at that state is computed from.
#[derive(Clone)]
struct AvatarSnapshot {
    state: u64,
    avatars: HashMap<Id, Value>,
    rules: AvatarRules,
}

/// The store, behind a [`ScopedState`] so a conditional Foo/set can isolate
/// and roll it back (docs/design/conditional.md §7).
#[derive(Default, Clone)]
struct Inner {
    /// `type_name` → `account_id` → `id → stored object`.
    objects: Keyed<HashMap<Id, Value>>,
    /// `type_name` → `account_id` → state counter.
    states: Keyed<u64>,
    /// `type_name` → `account_id` → `(state after the change, id, change)`.
    log: Keyed<Vec<(u64, Id, Change)>>,
    /// Registered accounts and their Scene capability object.
    accounts: HashMap<String, SceneCapability>,
    /// `(account_id, blob_id)` → blob size in bytes.
    blobs: HashMap<(String, String), u64>,
    /// Account → total `SceneAsset` storage limit in bytes.
    storage_quota: HashMap<String, u64>,
    /// User ids with admin privileges.
    admins: HashSet<String>,
    /// Account → advertised capability URIs.
    capabilities: HashMap<String, HashSet<String>>,
    /// `(binding property, id)` → what the id references.
    bindings: HashMap<(BindingProperty, String), BindingTarget>,
    channel_spaces: HashSet<(String, String)>,
    /// `(region id, userId)` pairs granted access to an `"invite"` region.
    grants: HashSet<(String, String)>,
    /// `(region id, userId)` pairs barred from entering the region.
    bans: HashSet<(String, String)>,
    /// `(userId, object id)` pairs outside that user's visibility set.
    hidden: HashSet<(String, Id)>,
    /// User ids whose interactions [`SceneBackend::accept_interaction`]
    /// refuses as over the rate.
    rate_limited: HashSet<String>,
    /// Interactions [`SceneBackend::accept_interaction`] accepted, in order.
    interactions: Vec<SceneInteractionEvent>,
    /// User ids whose region events [`SceneBackend::accept_region_event`]
    /// refuses as over the rate.
    region_event_limited: HashSet<String>,
    /// Region events [`SceneBackend::accept_region_event`] accepted, in
    /// order.
    region_events: Vec<SceneRegionEvent>,
    /// `(blocking userId, blocked userId)` pairs.
    blocked: HashSet<(String, String)>,
    /// `(userId, region id)` pairs: regions whose avatars that user may
    /// not see.
    hidden_avatars: HashSet<(String, Id)>,
    /// Reserved avatar display names.
    reserved_names: Vec<String>,
    /// Account → the per-avatar visibility rules of
    /// [`SceneBackend::avatar_view`]. An account appears here once a rule
    /// is set, and from then on answers `SceneAvatar/changes` from each
    /// caller's view.
    avatar_rules: HashMap<String, AvatarRules>,
    /// Account → one snapshot per `SceneAvatar` state since the first rule:
    /// the state, the stored avatars and the rules then in force.
    avatar_views: HashMap<String, Vec<AvatarSnapshot>>,
    /// Whether [`SceneBackend::supports_observe`] answers `true`.
    supports_observe: bool,
    /// `(account, region id)` → observing userId → number of its
    /// connections observing, from [`SceneBackend::set_observing`].
    observers: HashMap<(String, Id), HashMap<String, usize>>,
    /// Region ids whose observers [`SceneBackend::may_observe_region`]
    /// declines by policy.
    declined_observers: HashSet<Id>,
    /// What [`SceneBackend::observer_accounts`] answers instead of every
    /// registered account, once set.
    observer_accounts: Option<Vec<Id>>,
    /// Object history, once `MemoryBackend::with_object_history` turns it
    /// on.
    history: Option<jmap_object_history_server::HistoryStore>,
}

impl Inner {
    fn objects(&self, type_name: &'static str, account_id: &Id) -> Option<&HashMap<Id, Value>> {
        self.objects
            .get(type_name)
            .and_then(|m| m.get(account_id.as_ref()))
    }

    fn objects_mut(&mut self, type_name: &'static str, account_id: &Id) -> &mut HashMap<Id, Value> {
        self.objects
            .entry(type_name)
            .or_default()
            .entry(account_id.as_ref().to_owned())
            .or_default()
    }

    fn state(&self, type_name: &'static str, account_id: &Id) -> u64 {
        self.states
            .get(type_name)
            .and_then(|m| m.get(account_id.as_ref()))
            .copied()
            .unwrap_or(0)
    }

    /// Advance the state of `type_name` once and log `changes` under it.
    fn commit(&mut self, type_name: &'static str, account_id: &Id, changes: Vec<(Id, Change)>) {
        let state = self
            .states
            .entry(type_name)
            .or_default()
            .entry(account_id.as_ref().to_owned())
            .or_insert(0);
        *state += 1;
        let state = *state;
        self.log
            .entry(type_name)
            .or_default()
            .entry(account_id.as_ref().to_owned())
            .or_default()
            .extend(changes.into_iter().map(|(id, c)| (state, id, c)));
        if type_name == SceneAvatar::TYPE_NAME {
            self.snapshot_avatars(account_id);
        }
    }

    /// Record the account's current avatars and rules under its current
    /// `SceneAvatar` state, once the account has avatar rules.
    fn snapshot_avatars(&mut self, account_id: &Id) {
        let Some(rules) = self.avatar_rules.get(account_id.as_ref()).cloned() else {
            return;
        };
        let snapshot = AvatarSnapshot {
            state: self.state(SceneAvatar::TYPE_NAME, account_id),
            avatars: self
                .objects(SceneAvatar::TYPE_NAME, account_id)
                .cloned()
                .unwrap_or_default(),
            rules,
        };
        self.avatar_views
            .entry(account_id.as_ref().to_owned())
            .or_default()
            .push(snapshot);
    }

    /// Change the account's avatar rules with `change`, then advance the
    /// `SceneAvatar` state: "Whenever the caller's view changes, the server
    /// advances the `SceneAvatar` state string". The first rule also records
    /// the view before it, so `/changes` from that state still works.
    fn change_avatar_rules(&mut self, account_id: &Id, change: impl FnOnce(&mut AvatarRules)) {
        if !self.avatar_rules.contains_key(account_id.as_ref()) {
            self.avatar_rules
                .insert(account_id.as_ref().to_owned(), AvatarRules::default());
            self.snapshot_avatars(account_id);
        }
        if let Some(rules) = self.avatar_rules.get_mut(account_id.as_ref()) {
            change(rules);
        }
        self.commit(SceneAvatar::TYPE_NAME, account_id, Vec::new());
    }

    /// [`SceneBackend::avatar_view`] of `avatar` for `viewer` under
    /// `rules`: whole for the avatar's own user, the admins and the region
    /// owner ("The server SHOULD NOT hide avatars, or withhold their
    /// properties, from the region owner and administrators"), else as the
    /// rules say.
    fn avatar_view(
        &self,
        viewer: &str,
        account_id: &Id,
        avatar: &SceneAvatar,
        rules: Option<&AvatarRules>,
    ) -> AvatarView {
        let Some(rules) = rules else {
            return AvatarView::Full;
        };
        if avatar.user_id == viewer
            || self.admins.contains(viewer)
            || self.owns_region(viewer, account_id, &avatar.region_id)
        {
            return AvatarView::Full;
        }
        let key = (viewer.to_owned(), avatar.id.clone());
        if rules.hidden.contains(&key) {
            return AvatarView::Hidden;
        }
        match rules.withheld.get(&key) {
            Some(r) => AvatarView::Redacted(r.clone()),
            None => AvatarView::Full,
        }
    }

    /// `avatar` as `viewer` sees it under `rules`, or `None` when hidden.
    fn viewed_avatar(
        &self,
        viewer: &str,
        account_id: &Id,
        mut avatar: SceneAvatar,
        rules: Option<&AvatarRules>,
    ) -> Option<SceneAvatar> {
        match self.avatar_view(viewer, account_id, &avatar, rules) {
            AvatarView::Hidden => None,
            AvatarView::Redacted(r) => {
                r.apply(&mut avatar);
                Some(avatar)
            }
            _ => Some(avatar),
        }
    }

    /// The avatars of `snapshot` as `viewer` sees them, by id.
    fn view_at(
        &self,
        viewer: &str,
        account_id: &Id,
        snapshot: &AvatarSnapshot,
    ) -> HashMap<Id, Value> {
        snapshot
            .avatars
            .iter()
            .filter_map(|(id, v)| {
                let a = decode::<SceneAvatar>(v).ok()?;
                let seen = self.viewed_avatar(viewer, account_id, a, Some(&snapshot.rules))?;
                Some((id.clone(), serde_json::to_value(seen).ok()?))
            })
            .collect()
    }

    /// `SceneAvatar/changes` from `viewer`'s view (§Avatar Visibility): an
    /// avatar that became visible is `created`, one that became hidden
    /// `destroyed`, one whose returned value changed `updated`. `None`
    /// when `since` predates the account's first snapshot.
    fn avatar_changes_for(
        &self,
        viewer: &str,
        account_id: &Id,
        since: u64,
        max_changes: Option<u64>,
    ) -> Option<Result<ChangesResult, BackendChangesError<MemoryError>>> {
        let snapshots = self.avatar_views.get(account_id.as_ref())?;
        let start = snapshots.iter().position(|s| s.state == since)?;
        let base = self.view_at(viewer, account_id, &snapshots[start]);
        let diff = |now: &HashMap<Id, Value>| {
            let mut created = Vec::new();
            let mut updated = Vec::new();
            let mut destroyed = Vec::new();
            for (id, v) in now {
                match base.get(id) {
                    None => created.push(id.clone()),
                    Some(old) if old != v => updated.push(id.clone()),
                    Some(_) => {}
                }
            }
            for id in base.keys().filter(|id| !now.contains_key(*id)) {
                destroyed.push(id.clone());
            }
            (created, updated, destroyed)
        };
        let current = self.state(SceneAvatar::TYPE_NAME, account_id);
        let mut result = (Vec::new(), Vec::new(), Vec::new());
        let mut upto = since;
        for snapshot in &snapshots[start + 1..] {
            let next = diff(&self.view_at(viewer, account_id, snapshot));
            let count = (next.0.len() + next.1.len() + next.2.len()) as u64;
            if let Some(max) = max_changes
                && count > max
            {
                if upto == since {
                    return Some(Err(BackendChangesError::TooManyChanges { limit: max }));
                }
                break;
            }
            result = next;
            upto = snapshot.state;
        }
        let (created, updated, destroyed) = result;
        Some(Ok(ChangesResult::new(
            created,
            updated,
            destroyed,
            upto < current,
            State::from(upto.to_string()),
        )))
    }

    /// Set each of `regions`' `activeAvatarCount` to its number of avatars
    /// with `leftAt` `null`, and, for a region with the observer
    /// properties, its `observerCount` (see [`Self::observer_count`]), and
    /// advance the `SceneRegion` state once if any count changed.
    fn recount(&mut self, account_id: &Id, regions: &[Id]) {
        let mut changed = Vec::new();
        for region in regions {
            let active = self
                .all::<SceneAvatar>(account_id)
                .filter(|a| a.region_id == *region && a.left_at.is_none())
                .count();
            let observers = self.observer_count(account_id, region);
            let Some(stored) = self
                .objects_mut(SceneRegion::TYPE_NAME, account_id)
                .get_mut(region)
            else {
                continue;
            };
            let mut differs = false;
            if stored.get("activeAvatarCount") != Some(&json!(active)) {
                stored["activeAvatarCount"] = json!(active);
                differs = true;
            }
            if let Some(observers) = observers
                && stored.get("observerCount") != Some(&json!(observers))
            {
                stored["observerCount"] = json!(observers);
                differs = true;
            }
            if differs {
                changed.push((region.clone(), Change::Updated));
            }
        }
        if !changed.is_empty() {
            self.commit(SceneRegion::TYPE_NAME, account_id, changed);
        }
    }

    /// [`Self::recount`] every region some user observes
    /// ([`SceneBackend::set_observing`]), or only those with id `region_id`
    /// when given, in every account: after a change outside the region
    /// record that may change who counts as its observer (access or the
    /// observer policy).
    fn recount_observed(&mut self, region_id: Option<&Id>) {
        let mut by_account: HashMap<Id, Vec<Id>> = HashMap::new();
        for (account, region) in self.observers.keys() {
            if region_id.is_none_or(|r| r == region) {
                by_account
                    .entry(Id::from(account.as_str()))
                    .or_default()
                    .push(region.clone());
            }
        }
        for (account, regions) in by_account {
            self.recount(&account, &regions);
        }
    }

    /// §Entering a Region for `avatar`, which carries its minted id, under
    /// the lock: the steps of [`SceneBackend::create_object`] for a
    /// `SceneAvatar`. Returns the
    /// trait's error type unboxed, as `create_object` does.
    ///
    /// `defer`: an atomic conditional-02 scope is open on this task, so the
    /// `maxAvatarsPerRegion` check is left to its commit
    /// (`final_state_failures`). The one-record check is not: records are
    /// never destroyed, so the final state cannot differ.
    fn enter(
        &mut self,
        account_id: &Id,
        avatar: SceneAvatar,
        defer: bool,
    ) -> Result<Value, BackendSetError<MemoryError>> {
        // "When the user already has a SceneAvatar record in the same
        // region, whether present or departed, the server MUST NOT create a
        // second record and MUST return an `alreadyExists` SetError".
        if let Some(existing) = self
            .all::<SceneAvatar>(account_id)
            .find(|a| a.user_id == avatar.user_id && a.region_id == avatar.region_id)
        {
            return Err(BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::AlreadyExists)
                    .with_description("the user already has an avatar record in this region")
                    .with_existing_id(existing.id),
            )));
        }
        let (mut changes, mut regions) = self.admit(account_id, &avatar, defer)?;
        let id = avatar.id.clone();
        let value = serde_json::to_value(&avatar)
            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize SceneAvatar", &e)))?;
        self.objects_mut(SceneAvatar::TYPE_NAME, account_id)
            .insert(id.clone(), value.clone());
        changes.push((id, Change::Created));
        regions.push(avatar.region_id);
        self.commit(SceneAvatar::TYPE_NAME, account_id, changes);
        self.recount(account_id, &regions);
        Ok(value)
    }

    /// The steps a create and a re-entry of `avatar` share, under the
    /// lock: refuse with `overQuota` when its region already holds
    /// `maxAvatarsPerRegion` present avatars, then set `leftAt` to
    /// `avatar.joined_at` on the user's present avatars ("a user is
    /// present in at most one region at a time"). Returns those avatars'
    /// changes and their regions, for the caller to commit and recount.
    fn admit(
        &mut self,
        account_id: &Id,
        avatar: &SceneAvatar,
        defer: bool,
    ) -> Result<Admitted, BackendSetError<MemoryError>> {
        let max = self
            .accounts
            .get(account_id.as_ref())
            .and_then(|c| c.max_avatars_per_region);
        let present = self
            .all::<SceneAvatar>(account_id)
            .filter(|a| a.region_id == avatar.region_id && a.left_at.is_none())
            .count() as u64;
        if !defer && max.is_some_and(|max| present >= max) {
            return Err(BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::OverQuota)
                    .with_description("maxAvatarsPerRegion reached"),
            )));
        }

        let previous: Vec<SceneAvatar> = self
            .all::<SceneAvatar>(account_id)
            .filter(|a| a.user_id == avatar.user_id && a.left_at.is_none())
            .collect();
        let avatars = self.objects_mut(SceneAvatar::TYPE_NAME, account_id);
        let mut changes = Vec::new();
        let mut regions = Vec::new();
        // "When the user has an active SceneAvatar in a different region,
        // the server SHOULD set `leftAt` on the previous avatar".
        for previous in previous {
            if let Some(v) = avatars.get_mut(&previous.id) {
                v["leftAt"] = json!(avatar.joined_at);
                changes.push((previous.id, Change::Updated));
                regions.push(previous.region_id);
            }
        }
        Ok((changes, regions))
    }

    /// The `observerCount` of region `region_id`, or `None` when it has no
    /// observer properties: "the number of users currently observing the
    /// region through an observer subscription ... who do not have an
    /// active avatar in it. A user with several observing connections
    /// counts once." A user who lost access no longer receives events, and
    /// `allowObservers` `false` "stops event delivery to the region's
    /// current observers", so neither counts.
    fn observer_count(&self, account_id: &Id, region_id: &Id) -> Option<usize> {
        let region = self.region(account_id, region_id)?;
        region.observer_count?;
        if region.allow_observers == Some(false) || self.declined_observers.contains(region_id) {
            return Some(0);
        }
        let watching = self
            .observers
            .get(&(account_id.as_ref().to_owned(), region_id.clone()));
        Some(watching.map_or(0, |users| {
            users
                .keys()
                .filter(|user| {
                    self.admits(user, account_id, &region)
                        && !self.all::<SceneAvatar>(account_id).any(|a| {
                            a.region_id == *region_id && a.user_id == **user && a.left_at.is_none()
                        })
                })
                .count()
        }))
    }

    /// The stored region `region_id`, if it decodes.
    fn region(&self, account_id: &Id, region_id: &Id) -> Option<SceneRegion> {
        self.objects(SceneRegion::TYPE_NAME, account_id)
            .and_then(|m| m.get(region_id))
            .and_then(|v| decode::<SceneRegion>(v).ok())
    }

    /// `true` if `caller` is the owner of the region `region_id`.
    fn owns_region(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
        self.region(account_id, region_id)
            .is_some_and(|r| r.owner_id == caller)
    }

    /// `true` if `caller` has access to `region`: "A user has access to a
    /// region when its `accessPolicy` admits the user, when the user is
    /// the region owner, when the user has deployment-defined
    /// administrative privileges, or when the user has an active
    /// `SceneAvatar` in it"; `"invite"` admits "The users whose `userIds` are
    /// listed in `invitedUserIds`" and those given a grant.
    fn admits(&self, caller: &str, account_id: &Id, region: &SceneRegion) -> bool {
        region.access_policy != AccessPolicy::Invite
            || region.owner_id == caller
            || self.admins.contains(caller)
            || region.invited_user_ids.iter().any(|u| u == caller)
            || self
                .grants
                .contains(&(region.id.as_ref().to_owned(), caller.to_owned()))
            || self
                .all::<SceneAvatar>(account_id)
                .any(|a| a.region_id == region.id && a.user_id == caller && a.left_at.is_none())
    }

    /// [`SceneBackend::may_access_region`]: [`Self::admits`]; a region that
    /// is not stored admits everyone.
    fn may_access(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
        self.region(account_id, region_id)
            .is_none_or(|r| self.admits(caller, account_id, &r))
    }

    /// Every stored object of type `O` that decodes.
    fn all<O: JmapObject>(&self, account_id: &Id) -> impl Iterator<Item = O> + '_ + use<'_, O> {
        self.objects(O::TYPE_NAME, account_id)
            .into_iter()
            .flat_map(HashMap::values)
            .filter_map(|v| O::deserialize(v).ok())
    }

    /// The log entries of `type_name` in `account_id` after state `since`,
    /// oldest first.
    fn log_window(
        &self,
        type_name: &'static str,
        account_id: &Id,
        since: u64,
    ) -> impl Iterator<Item = &(u64, Id, Change)> + '_ + use<'_> {
        self.log
            .get(type_name)
            .and_then(|m| m.get(account_id.as_ref()))
            .into_iter()
            .flatten()
            .filter(move |(s, _, _)| *s > since)
    }

    /// The state a `/changes` from `since` with `maxChanges` `max` goes up
    /// to: the current state, or an intermediate one.
    ///
    /// RFC 8620 §5.2: over maxChanges "the server SHOULD generate an
    /// update to take the client to an intermediate state", and only
    /// when "unable to calculate an intermediate state" return
    /// cannotCalculateChanges. One commit logs all its ids under one
    /// state, so the intermediate state is the last whose whole commit
    /// fits, oldest first. Each distinct id is one entry of
    /// [`Inner::net_changes`].
    fn changes_upto(
        &self,
        type_name: &'static str,
        account_id: &Id,
        since: u64,
        max: u64,
    ) -> Result<u64, BackendChangesError<MemoryError>> {
        let mut seen: HashSet<&Id> = HashSet::new();
        let (mut fits, mut commit) = (since, since);
        for (s, id, _) in self.log_window(type_name, account_id, since) {
            if *s != commit {
                (fits, commit) = (commit, *s);
            }
            if seen.insert(id) && seen.len() as u64 > max {
                if fits == since {
                    return Err(BackendChangesError::TooManyChanges { limit: max });
                }
                return Ok(fits);
            }
        }
        Ok(self.state(type_name, account_id))
    }

    /// Each id changed after state `since` up to `upto`, once, with its
    /// net change.
    ///
    /// RFC 8620 §5.2: each id appears once, in the bucket of its net
    /// change since `since_state`. A create followed by an update stays
    /// created; a later destroy or re-create overrides.
    fn net_changes(
        &self,
        type_name: &'static str,
        account_id: &Id,
        since: u64,
        upto: u64,
    ) -> Vec<(Id, Change)> {
        let window = || {
            self.log_window(type_name, account_id, since)
                .filter(move |(s, _, _)| *s <= upto)
        };
        let mut net: Vec<(Id, Change)> = Vec::new();
        for (_, id, change) in window() {
            match net.iter_mut().find(|(seen, _)| seen == id) {
                Some((_, prev)) if *prev == Change::Created && *change == Change::Updated => {}
                Some((_, prev)) => *prev = *change,
                None => net.push((id.clone(), *change)),
            }
        }
        // Object history -04 §5.1: an id restored in the window is
        // classified by whether it existed at sinceState and exists now,
        // "exactly as if the object had never been destroyed between them".
        let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
        for (_, id, change) in window() {
            events.entry(id.clone()).or_default().push(match change {
                Change::Created => ChangeEvent::Created,
                Change::Updated => ChangeEvent::Updated,
                Change::Destroyed => ChangeEvent::Destroyed,
                Change::Restored => ChangeEvent::Restored,
            });
        }
        net.retain_mut(|(id, change)| {
            let Some(list) = events
                .get(id)
                .filter(|l| l.contains(&ChangeEvent::Restored))
            else {
                return true;
            };
            match fold_restore(list) {
                Some(ChangeKind::Created) => *change = Change::Created,
                Some(ChangeKind::Destroyed) => *change = Change::Destroyed,
                Some(_) => *change = Change::Updated,
                None => return false,
            }
            true
        });
        net
    }

    /// The ids of the `O` objects in `account_id` that `caller` sees and
    /// that match `filter`, in `sort` order. `filter` and `sort` re-decode
    /// as the concrete type's once `O::TYPE_NAME` is known.
    fn query_ids<O: QueryObject>(
        &self,
        caller: &str,
        account_id: &Id,
        filter: Option<&O::Filter>,
        sort: &[O::Comparator],
    ) -> Result<Vec<Id>, BackendQueryError<MemoryError>> {
        Ok(if O::TYPE_NAME == SceneAsset::TYPE_NAME {
            let filter: Option<SceneAssetFilter> = filter.map(recode).transpose()?;
            let sort: Vec<SceneAssetComparator> = recode(&sort)?;
            sorted_ids(
                self.all::<SceneAsset>(account_id),
                |a| filter.as_ref().is_none_or(|f| asset_matches(f, a)),
                |a, b| compare_assets(a, b, &sort),
                |a| a.id,
            )
        } else if O::TYPE_NAME == SceneRegion::TYPE_NAME {
            let filter: Option<SceneRegionFilter> = filter.map(recode).transpose()?;
            let sort: Vec<SceneRegionComparator> = recode(&sort)?;
            sorted_ids(
                self.all::<SceneRegion>(account_id),
                |r| {
                    self.may_access(caller, account_id, &r.id)
                        && filter.as_ref().is_none_or(|f| region_matches(f, r))
                },
                |a, b| compare_regions(a, b, &sort),
                |r| r.id,
            )
        } else if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
            let filter: Option<SceneAvatarFilter> = filter.map(recode).transpose()?;
            let sort: Vec<SceneAvatarComparator> = recode(&sort)?;
            // §Avatar Visibility: hidden avatars are left out and the
            // filters and sorts see "the values returned to the caller".
            let rules = self.avatar_rules.get(account_id.as_ref());
            sorted_ids(
                self.all::<SceneAvatar>(account_id)
                    .filter_map(|a| self.viewed_avatar(caller, account_id, a, rules)),
                |a| {
                    self.may_access(caller, account_id, &a.region_id)
                        && !self
                            .blocked
                            .contains(&(caller.to_owned(), a.user_id.clone()))
                        && !self
                            .hidden_avatars
                            .contains(&(caller.to_owned(), a.region_id.clone()))
                        && filter.as_ref().is_none_or(|f| avatar_matches(f, a))
                },
                |a, b| compare_avatars(a, b, &sort),
                |a| a.id,
            )
        } else if O::TYPE_NAME == SceneObject::TYPE_NAME {
            let filter: Option<SceneObjectFilter> = filter.map(recode).transpose()?;
            let sort: Vec<SceneObjectComparator> = recode(&sort)?;
            let all: HashMap<Id, SceneObject> = self
                .all::<SceneObject>(account_id)
                .map(|o| (o.id.clone(), o))
                .collect();
            sorted_ids(
                all.values(),
                |o| {
                    self.may_access(caller, account_id, &o.region_id)
                        && !self.hidden.contains(&(caller.to_owned(), o.id.clone()))
                        && filter.as_ref().is_none_or(|f| {
                            object_matches(f, o, region_local_position(o, |id| all.get(id)))
                        })
                },
                |a, b| compare_objects(a, b, &sort),
                |o| o.id.clone(),
            )
        } else {
            return Err(BackendQueryError::Other(MemoryError::new(format!(
                "query of {} is not implemented",
                O::TYPE_NAME
            ))));
        })
    }
}

/// A fully in-memory implementation of [`SceneBackend`].
///
/// Cloning is cheap and **shared-state**; see the [`Clone`] impl.
///
/// `C` is the [`JmapAccounts::CallerCtx`]: [`Id`], the caller's Principal
/// id, by default, or `()` for a deployment without identity (see the
/// module documentation, "Caller context").
#[non_exhaustive]
pub struct MemoryBackend<C = Id> {
    inner: ScopedState<Inner>,
    caller: PhantomData<fn() -> C>,
}

/// An empty backend: [`MemoryBackend::new`] for any caller context, such
/// as `MemoryBackend::<()>::default()` for a deployment without identity.
impl<C> Default for MemoryBackend<C> {
    fn default() -> Self {
        Self {
            inner: ScopedState::default(),
            caller: PhantomData,
        }
    }
}

/// Manual `Clone` impl, not `#[derive(Clone)]`: cloning is **shared-state**.
///
/// A clone copies no data. The original and the clone hold `Arc::clone`s
/// of the same [`ScopedState`]-guarded store and observe each other's mutations, so
/// one handle can seed or inspect state while another serves requests. This
/// impl must never become a deep copy; for independent state construct a
/// fresh [`MemoryBackend::new`] instead of calling `.clone()`.
impl<C> Clone for MemoryBackend<C> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            caller: PhantomData,
        }
    }
}

impl MemoryBackend {
    /// An empty backend with no accounts, whose callers are Principal ids
    /// (`C = Id`). Equivalent to [`Self::default`].
    pub fn new() -> Self {
        Self::default()
    }
}

/// The `userId` `caller` acts as in `account_id`: its Principal id, or, for
/// a caller without identity, the account id.
fn acting_user<C: MemoryCaller>(caller: &C, account_id: &Id) -> String {
    caller.principal().unwrap_or(account_id).as_ref().to_owned()
}

impl<C: MemoryCaller> MemoryBackend<C> {
    /// The store, for setup and test helpers, which never run inside a
    /// conditional Foo/set scope. A poisoned lock is taken anyway.
    fn lock(&self) -> ScopedGuard<'_, Inner> {
        self.inner.lock_unscoped()
    }

    /// The store, for the backend methods: waits while another task's
    /// conditional Foo/set scope is open (docs/design/conditional.md §7).
    async fn locked(&self) -> ScopedGuard<'_, Inner> {
        self.inner.lock().await
    }

    /// Register `account_id` with the `urn:ietf:params:jmap:scene` account capability object
    /// it advertises, and return `self` for chaining.
    ///
    /// Until an account is registered every method call naming it is
    /// `accountNotFound` (RFC 8620 §3.6.2). The builder form of
    /// [`Self::register_account`].
    ///
    /// ```
    /// use jmap_scene_server::memory::MemoryBackend;
    /// use jmap_server::JmapAccounts;
    /// use jmap_types::Id;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let capability = serde_json::from_value(serde_json::json!({
    ///     "mayCreateRegion": true,
    ///     "mayCreateObject": true,
    ///     "supportedVisualTypes": ["model/gltf-binary"],
    ///     "maxRegionsPerAccount": null,
    ///     "maxObjectsPerRegion": null,
    ///     "maxAvatarsPerRegion": null,
    ///     "maxAssetSizeBytes": null,
    ///     "supportsSceneAsset": false
    /// }))?;
    /// let account = Id::from("a1");
    /// let backend = MemoryBackend::new().with_account(&account, capability);
    /// let caller = Id::from("alice");
    /// tokio::runtime::Runtime::new()?.block_on(async {
    ///     assert!(backend.account_exists(&caller, &account).await?);
    ///     assert!(!backend.account_exists(&caller, &Id::from("a2")).await?);
    ///     Ok(())
    /// })
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// In debug builds, if `account_id` is the empty string (RFC 8620
    /// §1.2, bd:JMAP-dx0s).
    #[must_use]
    pub fn with_account(self, account_id: &Id, capability: SceneCapability) -> Self {
        self.register_account(account_id, capability);
        self
    }

    /// Register `account_id` with the `urn:ietf:params:jmap:scene` account capability object
    /// it advertises: the `&self` form of [`Self::with_account`], for a
    /// backend already shared with a dispatcher.
    ///
    /// Registering an account again replaces its capability; its objects
    /// are kept.
    ///
    /// # Panics
    ///
    /// In debug builds, if `account_id` is the empty string (RFC 8620
    /// §1.2, bd:JMAP-dx0s).
    pub fn register_account(&self, account_id: &Id, capability: SceneCapability) {
        debug_assert!(
            !account_id.as_ref().is_empty(),
            "register_account: account_id must not be the empty string \
             (RFC 8620 §1.2, bd:JMAP-dx0s)"
        );
        self.lock()
            .accounts
            .insert(account_id.as_ref().to_owned(), capability);
    }

    /// Record an uploaded blob `blob_id` of `size` bytes in `account_id`.
    #[doc(hidden)]
    pub fn add_blob(&self, account_id: &Id, blob_id: &str, size: u64) {
        self.lock()
            .blobs
            .insert((account_id.as_ref().to_owned(), blob_id.to_owned()), size);
    }

    /// Limit the total `size` of `account_id`'s SceneAssets to `bytes`.
    #[doc(hidden)]
    pub fn set_storage_quota(&self, account_id: &Id, bytes: u64) {
        self.lock()
            .storage_quota
            .insert(account_id.as_ref().to_owned(), bytes);
    }

    /// Give `user` admin privileges, recounting the `observerCount` of the
    /// observed regions, since an admin has access to every region.
    #[doc(hidden)]
    pub fn add_admin(&self, user: &str) {
        let mut inner = self.lock();
        inner.admins.insert(user.to_owned());
        inner.recount_observed(None);
    }

    /// Advertise the companion capability `uri` (e.g.
    /// `urn:ietf:params:jmap:chat`) on `account_id`, so
    /// [`SceneBackend::has_capability`] answers `true` for it. List the
    /// same capability in the account's Session `accountCapabilities`.
    pub fn advertise(&self, account_id: &Id, uri: &str) {
        self.lock()
            .capabilities
            .entry(account_id.as_ref().to_owned())
            .or_default()
            .insert(uri.to_owned());
    }

    /// Record that binding `property` set to `id` references `target`.
    #[doc(hidden)]
    pub fn set_region_binding(&self, property: BindingProperty, id: &str, target: BindingTarget) {
        self.lock()
            .bindings
            .insert((property, id.to_owned()), target);
    }

    /// Record that channel `channel_id` is a channel of Space `space_id`.
    #[doc(hidden)]
    pub fn set_channel_space(&self, channel_id: &str, space_id: &str) {
        self.lock()
            .channel_spaces
            .insert((channel_id.to_owned(), space_id.to_owned()));
    }

    /// Give `user` access to the `"invite"` region `region_id`, recounting
    /// its `observerCount`.
    #[doc(hidden)]
    pub fn grant_region_access(&self, region_id: &str, user: &str) {
        let mut inner = self.lock();
        inner.grants.insert((region_id.to_owned(), user.to_owned()));
        inner.recount_observed(Some(&Id::from(region_id)));
    }

    /// Withdraw the access [`Self::grant_region_access`] gave `user` to
    /// region `region_id`, recounting its `observerCount`.
    #[doc(hidden)]
    pub fn revoke_region_access(&self, region_id: &str, user: &str) {
        let mut inner = self.lock();
        inner
            .grants
            .remove(&(region_id.to_owned(), user.to_owned()));
        inner.recount_observed(Some(&Id::from(region_id)));
    }

    /// Bar `user` from entering region `region_id`, for
    /// [`SceneBackend::may_enter_region`].
    #[doc(hidden)]
    pub fn ban_from_region(&self, region_id: &str, user: &str) {
        self.lock()
            .bans
            .insert((region_id.to_owned(), user.to_owned()));
    }

    /// Take object `object_id` out of `user`'s visibility set, for
    /// [`SceneBackend::is_object_visible`].
    #[doc(hidden)]
    pub fn hide_object(&self, user: &str, object_id: &str) {
        self.lock()
            .hidden
            .insert((user.to_owned(), Id::from(object_id)));
    }

    /// Make `user` blocked by `blocker`, for
    /// [`SceneBackend::is_user_blocked`].
    #[doc(hidden)]
    pub fn block(&self, blocker: &str, user: &str) {
        self.lock()
            .blocked
            .insert((blocker.to_owned(), user.to_owned()));
    }

    /// Hide the avatars of region `region_id` from `user`, for
    /// [`SceneBackend::may_see_region_avatars`].
    #[doc(hidden)]
    pub fn hide_region_avatars(&self, user: &str, region_id: &str) {
        self.lock()
            .hidden_avatars
            .insert((user.to_owned(), Id::from(region_id)));
    }

    /// Advertise (`true`) or withdraw `supportsObserve`, for
    /// [`SceneBackend::supports_observe`]. List the same value in the
    /// Session's `urn:ietf:params:jmap:scene:websocket` capability.
    pub fn set_supports_observe(&self, on: bool) {
        self.lock().supports_observe = on;
    }

    /// Decline observers of region `region_id` by policy, for
    /// [`SceneBackend::may_observe_region`], recounting its
    /// `observerCount` (to `0`).
    #[doc(hidden)]
    pub fn decline_observers(&self, region_id: &str) {
        let mut inner = self.lock();
        inner.declined_observers.insert(Id::from(region_id));
        inner.recount_observed(Some(&Id::from(region_id)));
    }

    /// Undo [`Self::decline_observers`] for region `region_id`,
    /// recounting its `observerCount`.
    #[doc(hidden)]
    pub fn admit_observers(&self, region_id: &str) {
        let mut inner = self.lock();
        inner.declined_observers.remove(&Id::from(region_id));
        inner.recount_observed(Some(&Id::from(region_id)));
    }

    /// Make [`SceneBackend::observer_accounts`] answer `accounts` instead
    /// of every registered account, as a deployment that checks only
    /// some of the accounts a user can access would.
    #[doc(hidden)]
    pub fn restrict_observer_accounts(&self, accounts: &[&str]) {
        self.lock().observer_accounts = Some(accounts.iter().map(|a| Id::from(*a)).collect());
    }

    /// Hide avatar `avatar_id` of `account_id` from `viewer`, for
    /// [`SceneBackend::avatar_view`], and advance the account's
    /// SceneAvatar state.
    #[doc(hidden)]
    pub fn hide_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
        let key = (viewer.to_owned(), Id::from(avatar_id));
        self.lock().change_avatar_rules(account_id, |rules| {
            rules.withheld.remove(&key);
            rules.hidden.insert(key);
        });
    }

    /// Withhold the properties of `redaction` of avatar `avatar_id` of
    /// `account_id` from `viewer`, for [`SceneBackend::avatar_view`], and
    /// advance the account's SceneAvatar state.
    #[doc(hidden)]
    pub fn withhold_avatar(
        &self,
        account_id: &Id,
        viewer: &str,
        avatar_id: &str,
        redaction: AvatarRedaction,
    ) {
        let key = (viewer.to_owned(), Id::from(avatar_id));
        self.lock().change_avatar_rules(account_id, |rules| {
            rules.hidden.remove(&key);
            rules.withheld.insert(key, redaction);
        });
    }

    /// Show avatar `avatar_id` of `account_id` to `viewer` in full again,
    /// and advance the account's SceneAvatar state.
    #[doc(hidden)]
    pub fn reveal_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
        let key = (viewer.to_owned(), Id::from(avatar_id));
        self.lock().change_avatar_rules(account_id, |rules| {
            rules.hidden.remove(&key);
            rules.withheld.remove(&key);
        });
    }

    /// Refuse every interaction of `user` as over the rate, for
    /// [`SceneBackend::accept_interaction`].
    #[doc(hidden)]
    pub fn rate_limit_interactions(&self, user: &str) {
        self.lock().rate_limited.insert(user.to_owned());
    }

    /// The interactions [`SceneBackend::accept_interaction`] accepted, in
    /// order: what a WebSocket transport would deliver.
    #[doc(hidden)]
    pub fn accepted_interactions(&self) -> Vec<SceneInteractionEvent> {
        self.lock().interactions.clone()
    }

    /// Refuse every region event `user` broadcasts as over the rate, for
    /// [`SceneBackend::accept_region_event`].
    #[doc(hidden)]
    pub fn rate_limit_region_events(&self, user: &str) {
        self.lock().region_event_limited.insert(user.to_owned());
    }

    /// The region events [`SceneBackend::accept_region_event`] accepted,
    /// in order: what a WebSocket transport would deliver.
    #[doc(hidden)]
    pub fn accepted_region_events(&self) -> Vec<SceneRegionEvent> {
        self.lock().region_events.clone()
    }

    /// Reserve avatar display name `name`, for
    /// [`SceneBackend::reserved_display_names`].
    #[doc(hidden)]
    pub fn reserve_display_name(&self, name: &str) {
        self.lock().reserved_names.push(name.to_owned());
    }

    /// Store `value` as object `id` of `type_name` without validation or a
    /// state change, to seed states the methods cannot reach.
    #[doc(hidden)]
    #[cfg(feature = "test-helpers")]
    pub fn insert_object_for_test(
        &self,
        type_name: &'static str,
        account_id: &Id,
        id: &str,
        value: Value,
    ) {
        self.lock()
            .objects_mut(type_name, account_id)
            .insert(Id::from(id), value);
    }
}

/// Opaque storage-layer error returned by [`MemoryBackend`].
#[non_exhaustive]
#[derive(Debug)]
pub struct MemoryError {
    description: String,
}

impl MemoryError {
    /// A [`MemoryError`] with a human-readable description.
    pub fn new(description: impl Into<String>) -> Self {
        Self {
            description: description.into(),
        }
    }

    /// Human-readable description of the failure.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Construct a [`MemoryError`] for a `serde_json` failure during
    /// `context` (the operation that failed).
    ///
    /// Only the error's [`serde_json::error::Category`] is kept. A serde
    /// data error quotes the offending value (`invalid type: string
    /// "alice@example.com", expected u64`), and the `JmapAccounts::Error`
    /// contract forbids PII and blob content in `Display` output
    /// (bd:JMAP-510h.37).
    pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
        Self::new(format!("{context}: serde_json {:?} error", e.classify()))
    }
}

impl std::fmt::Display for MemoryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MemoryBackend error: {}", self.description)
    }
}

impl std::error::Error for MemoryError {}

fn not_found<E>() -> BackendSetError<E> {
    BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
}

fn decode<O: JmapObject>(v: &Value) -> Result<O, MemoryError> {
    O::deserialize(v).map_err(|e| MemoryError::serde(format_args!("decode {}", O::TYPE_NAME), &e))
}

fn recode_as<T: DeserializeOwned>(v: &Value) -> Result<T, BackendQueryError<MemoryError>> {
    T::deserialize(v)
        .map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))
}

/// Re-decode `v`, a value of a generic `QueryObject` associated type, as
/// the concrete type `T` it is once `O::TYPE_NAME` is known.
fn recode<T: DeserializeOwned>(v: &impl Serialize) -> Result<T, BackendQueryError<MemoryError>> {
    let v = serde_json::to_value(v)
        .map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))?;
    recode_as(&v)
}

/// The ids of `list` that `keep` accepts, ordered by `cmp`.
fn sorted_ids<T>(
    list: impl Iterator<Item = T>,
    keep: impl Fn(&T) -> bool,
    cmp: impl Fn(&T, &T) -> std::cmp::Ordering,
    id: impl Fn(T) -> Id,
) -> Vec<Id> {
    let mut list: Vec<T> = list.filter(|t| keep(t)).collect();
    list.sort_by(|a, b| cmp(a, b));
    list.into_iter().map(id).collect()
}

impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
    type Error = MemoryError;
    type CallerCtx = C;

    /// [`MemoryCaller::principal`].
    fn principal_id(caller: &C) -> Option<&Id> {
        caller.principal()
    }

    async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, MemoryError> {
        Ok(self
            .locked()
            .await
            .accounts
            .contains_key(account_id.as_ref()))
    }
}

impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        ids: Option<&[Id]>,
        _properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), MemoryError> {
        let inner = self.locked().await;
        let map = inner.objects(O::TYPE_NAME, account_id);
        match ids {
            None => {
                let list = map
                    .into_iter()
                    .flat_map(HashMap::values)
                    .map(decode)
                    .collect::<Result<_, _>>()?;
                Ok((list, Vec::new()))
            }
            Some(ids) => {
                let mut found = Vec::new();
                let mut missing = Vec::new();
                for id in ids {
                    match map.and_then(|m| m.get(id)) {
                        Some(v) => found.push(decode(v)?),
                        None => missing.push(id.clone()),
                    }
                }
                Ok((found, missing))
            }
        }
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
    ) -> Result<State, MemoryError> {
        Ok(State::from(
            self.locked()
                .await
                .state(O::TYPE_NAME, account_id)
                .to_string(),
        ))
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        caller: &C,
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<MemoryError>> {
        let viewer = acting_user(caller, account_id);
        let since_state = params.since_state;
        let max_changes = params.max_changes;
        let inner = self.locked().await;
        let since: u64 = since_state
            .as_ref()
            .parse()
            .map_err(|_| BackendChangesError::CannotCalculate)?;
        let current = inner.state(O::TYPE_NAME, account_id);
        if since > current {
            return Err(BackendChangesError::CannotCalculate);
        }
        // §Avatar Visibility: once the account has avatar rules, answer
        // from the caller's view; a state before the first rule cannot be
        // calculated.
        if O::TYPE_NAME == SceneAvatar::TYPE_NAME
            && inner.avatar_rules.contains_key(account_id.as_ref())
        {
            return inner
                .avatar_changes_for(&viewer, account_id, since, max_changes)
                .unwrap_or(Err(BackendChangesError::CannotCalculate));
        }

        let upto = match max_changes {
            Some(max) => inner.changes_upto(O::TYPE_NAME, account_id, since, max)?,
            None => current,
        };
        let net = inner.net_changes(O::TYPE_NAME, account_id, since, upto);
        let bucket = |want: Change| -> Vec<Id> {
            net.iter()
                .filter(|(_, c)| *c == want)
                .map(|(id, _)| id.clone())
                .collect()
        };
        Ok(ChangesResult::new(
            bucket(Change::Created),
            bucket(Change::Updated),
            bucket(Change::Destroyed),
            upto < current,
            State::from(upto.to_string()),
        ))
    }

    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &C,
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
        let caller = &acting_user(caller, account_id);
        let QueryParams {
            filter,
            sort,
            limit,
            position,
            anchor,
            anchor_offset,
            ..
        } = params;
        let sort = sort.unwrap_or_default();
        let inner = self.locked().await;
        let ids = inner.query_ids::<O>(caller, account_id, filter, sort)?;

        let total = ids.len() as u64;
        let start = resolve_query_start(&ids, position, anchor, anchor_offset)
            .map_err(BackendQueryError::Method)?;
        let page = ids
            .into_iter()
            .skip(start)
            .take(limit_or_max(limit))
            .collect();
        Ok(QueryResult::new(
            page,
            start as u64,
            Some(total),
            State::from(inner.state(O::TYPE_NAME, account_id).to_string()),
            false,
        ))
    }

    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        _caller: &C,
        _account_id: &Id,
        _params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>> {
        Err(BackendChangesError::CannotCalculate)
    }
}

impl<C: MemoryCaller> SceneBackend for MemoryBackend<C> {
    async fn scene_capability(
        &self,
        _caller: &C,
        account_id: &Id,
    ) -> Result<SceneCapability, MemoryError> {
        self.locked()
            .await
            .accounts
            .get(account_id.as_ref())
            .cloned()
            .ok_or_else(|| MemoryError::new("account not registered"))
    }

    async fn blob_size(
        &self,
        _caller: &C,
        account_id: &Id,
        blob_id: &Id,
    ) -> Result<Option<u64>, MemoryError> {
        Ok(self
            .lock()
            .blobs
            .get(&(account_id.as_ref().to_owned(), blob_id.as_ref().to_owned()))
            .copied())
    }

    async fn create_object<O, F>(
        &self,
        caller: &C,
        account_id: &Id,
        _create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<MemoryError>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        let caller = &acting_user(caller, account_id);
        let id = Id::from(ulid::Ulid::new().to_string());
        let mut value = serde_json::to_value(build(&id)).map_err(|e| {
            BackendSetError::Other(MemoryError::serde("serialize created object", &e))
        })?;
        let mut inner = self.locked().await;
        if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
            let avatar: SceneAvatar = decode(&value).map_err(BackendSetError::Other)?;
            let stored = inner.enter(account_id, avatar, self.inner.deferring())?;
            return Ok((id, decode(&stored).map_err(BackendSetError::Other)?));
        }
        // "Account asset storage quota exceeded", checked under the lock.
        if O::TYPE_NAME == SceneAsset::TYPE_NAME
            && let Some(&quota) = inner.storage_quota.get(account_id.as_ref())
        {
            let used: u64 = inner.all::<SceneAsset>(account_id).map(|a| a.size).sum();
            let size = value.get("size").and_then(Value::as_u64).unwrap_or(0);
            if used.saturating_add(size) > quota {
                return Err(BackendSetError::SetError(Box::new(
                    SetError::new(SetErrorType::OverQuota)
                        .with_description("account asset storage quota exceeded"),
                )));
            }
        }
        // "`overQuota` when `maxRegionsPerAccount` would be exceeded",
        // counted under the lock.
        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
            let max = inner
                .accounts
                .get(account_id.as_ref())
                .and_then(|c| c.max_regions_per_account);
            let held = inner.all::<SceneRegion>(account_id).count() as u64;
            if max.is_some_and(|max| held >= max) {
                return Err(BackendSetError::SetError(Box::new(
                    SetError::new(SetErrorType::OverQuota)
                        .with_description("maxRegionsPerAccount reached"),
                )));
            }
        }
        // "`overQuota` when `maxObjectsPerRegion` would be exceeded",
        // counted under the lock; "The userId of the user who created this
        // object".
        if O::TYPE_NAME == SceneObject::TYPE_NAME {
            let max = inner
                .accounts
                .get(account_id.as_ref())
                .and_then(|c| c.max_objects_per_region);
            let region = value.get("regionId").and_then(Value::as_str);
            let held = inner
                .all::<SceneObject>(account_id)
                .filter(|o| Some(o.region_id.as_ref()) == region)
                .count() as u64;
            if max.is_some_and(|max| held >= max) {
                return Err(BackendSetError::SetError(Box::new(
                    SetError::new(SetErrorType::OverQuota)
                        .with_description("maxObjectsPerRegion reached"),
                )));
            }
            value["ownerId"] = json!(caller);
        }
        let stored: O = decode(&value).map_err(BackendSetError::Other)?;
        inner
            .objects_mut(O::TYPE_NAME, account_id)
            .insert(id.clone(), value);
        inner.commit(
            O::TYPE_NAME,
            account_id,
            vec![(id.clone(), Change::Created)],
        );
        Ok((id, stored))
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<MemoryError>> {
        let mut inner = self.locked().await;
        let mut current = inner
            .objects(O::TYPE_NAME, account_id)
            .and_then(|m| m.get(id))
            .cloned()
            .ok_or_else(not_found)?;

        let was_left = current.get("leftAt").is_some_and(|l| !l.is_null());
        let patch = serde_json::to_value(&patch)
            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
        let (Value::Object(patch), Value::Object(base)) = (patch, &mut current) else {
            return Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::InvalidPatch,
            ))));
        };
        apply_patch_object(base, &patch).map_err(|e| {
            BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
            ))
        })?;
        if O::deserialize(&current).is_err() {
            return Err(BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::InvalidProperties)
                    .with_description(format!("patched {} is invalid", O::TYPE_NAME)),
            )));
        }
        let mut changes = Vec::new();
        let mut regions = Vec::new();
        let left_to = patch
            .get("leftAt")
            .filter(|_| O::TYPE_NAME == SceneAvatar::TYPE_NAME);
        if let Some(to) = left_to {
            // Leave and re-entry preconditions, re-checked under the lock.
            let refuse = |description: &str| {
                BackendSetError::SetError(Box::new(
                    SetError::new(SetErrorType::InvalidProperties)
                        .with_description(description)
                        .with_properties(["leftAt"]),
                ))
            };
            match (to.is_null(), was_left) {
                (false, true) => return Err(refuse("the avatar has already left")),
                (true, false) => return Err(refuse("the avatar is present")),
                (true, true) => {
                    let avatar: SceneAvatar = decode(&current).map_err(BackendSetError::Other)?;
                    (changes, regions) =
                        inner.admit(account_id, &avatar, self.inner.deferring())?;
                }
                (false, false) => {}
            }
            regions.extend(
                current
                    .get("regionId")
                    .and_then(Value::as_str)
                    .map(Id::from),
            );
        }
        if let Some(previous) = inner.current(O::TYPE_NAME, account_id, id).cloned() {
            inner.record_replace(O::TYPE_NAME, account_id, id, previous);
        }
        inner
            .objects_mut(O::TYPE_NAME, account_id)
            .insert(id.clone(), current);
        changes.push((id.clone(), Change::Updated));
        inner.commit(O::TYPE_NAME, account_id, changes);
        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
            // `allowObservers` or the access rules may have changed who
            // counts as an observer; a changed `observerCount` is "changed
            // in a way not explicitly requested", so the region is echoed.
            let before = inner.region(account_id, id).and_then(|r| r.observer_count);
            inner.recount(account_id, std::slice::from_ref(id));
            if let Some(after) = inner
                .objects(O::TYPE_NAME, account_id)
                .and_then(|m| m.get(id))
                && after.get("observerCount").and_then(Value::as_u64) != before
            {
                return Ok(Some(decode::<O>(after).map_err(BackendSetError::Other)?));
            }
        }
        inner.recount(account_id, &regions);
        Ok(None)
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<MemoryError>> {
        let mut inner = self.locked().await;
        let map = inner.objects_mut(O::TYPE_NAME, account_id);
        if !map.contains_key(id) {
            return Err(not_found());
        }
        // "removes the SceneObject and all its children (objects whose
        // `parentId` references this object, recursively)".
        let mut gone = vec![id.clone()];
        if O::TYPE_NAME == SceneObject::TYPE_NAME {
            let mut i = 0;
            while let Some(parent) = gone.get(i).cloned() {
                let children: Vec<Id> = map
                    .iter()
                    .filter(|(k, v)| {
                        v.get("parentId").and_then(Value::as_str) == Some(parent.as_ref())
                            && !gone.contains(k)
                    })
                    .map(|(k, _)| k.clone())
                    .collect();
                gone.extend(children);
                i += 1;
            }
        }
        let removed: Vec<(Id, Value)> = gone
            .iter()
            .filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
            .collect();
        for (k, v) in removed {
            inner.record_destroy(O::TYPE_NAME, account_id, &k, v);
        }
        inner.commit(
            O::TYPE_NAME,
            account_id,
            gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
        );
        // "removes the SceneRegion and all SceneObject and SceneAvatar
        // records in it", each reported destroyed, in the same locked step.
        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
            for contained in [SceneObject::TYPE_NAME, SceneAvatar::TYPE_NAME] {
                let map = inner.objects_mut(contained, account_id);
                let gone: Vec<Id> = map
                    .iter()
                    .filter(|(_, v)| v.get("regionId").and_then(Value::as_str) == Some(id.as_ref()))
                    .map(|(k, _)| k.clone())
                    .collect();
                if gone.is_empty() {
                    continue;
                }
                let removed: Vec<(Id, Value)> = gone
                    .iter()
                    .filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
                    .collect();
                for (k, v) in removed {
                    inner.record_destroy(contained, account_id, &k, v);
                }
                inner.commit(
                    contained,
                    account_id,
                    gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
                );
            }
        }
        Ok(())
    }

    async fn may_modify_asset(
        &self,
        caller: &C,
        _account_id: &Id,
        asset: &SceneAsset,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        // "Only the asset owner or an admin may modify asset metadata."
        Ok(asset.owner_id == *caller || self.locked().await.admins.contains(caller))
    }

    fn has_capability(&self, _caller: &C, account_id: &Id, uri: &str) -> bool {
        self.lock()
            .capabilities
            .get(account_id.as_ref())
            .is_some_and(|c| c.contains(uri))
    }

    async fn region_binding(
        &self,
        _caller: &C,
        _account_id: &Id,
        property: BindingProperty,
        id: &Id,
    ) -> Result<BindingTarget, MemoryError> {
        Ok(self
            .lock()
            .bindings
            .get(&(property, id.as_ref().to_owned()))
            .copied()
            .unwrap_or(BindingTarget::Missing))
    }

    async fn channel_in_space(
        &self,
        _caller: &C,
        _account_id: &Id,
        channel_id: &Id,
        space_id: &Id,
    ) -> Result<bool, MemoryError> {
        Ok(self
            .lock()
            .channel_spaces
            .contains(&(channel_id.as_ref().to_owned(), space_id.as_ref().to_owned())))
    }

    async fn may_update_region(
        &self,
        caller: &C,
        _account_id: &Id,
        region: &SceneRegion,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        // "Only the owner or an admin may modify region properties."
        Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
    }

    async fn may_destroy_region(
        &self,
        caller: &C,
        _account_id: &Id,
        region: &SceneRegion,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        // "Only the region owner or an admin may destroy a region."
        Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
    }

    async fn may_modify_object(
        &self,
        caller: &C,
        account_id: &Id,
        object: &SceneObject,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, account_id);
        // "Only the object's `ownerId`, the region owner, or a
        // deployment-admin may modify another user's object."
        let inner = self.locked().await;
        Ok(inner.admins.contains(caller)
            || object.owner_id.as_ref() == Some(caller)
            || inner.owns_region(caller, account_id, &object.region_id))
    }

    async fn caller_user_id(&self, caller: &C, _account_id: &Id) -> Result<String, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        Ok(caller.clone())
    }

    async fn may_enter_region(
        &self,
        caller: &C,
        _account_id: &Id,
        region: &SceneRegion,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        Ok(!self
            .lock()
            .bans
            .contains(&(region.id.as_ref().to_owned(), caller.clone())))
    }

    async fn may_access_region(
        &self,
        caller: &C,
        account_id: &Id,
        region_id: &Id,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, account_id);
        Ok(self
            .locked()
            .await
            .may_access(caller, account_id, region_id))
    }

    async fn is_object_visible(
        &self,
        caller: &C,
        _account_id: &Id,
        object: &SceneObject,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        Ok(!self
            .lock()
            .hidden
            .contains(&(caller.clone(), object.id.clone())))
    }

    async fn is_user_blocked(&self, caller: &C, user_id: &str) -> Result<bool, MemoryError> {
        // A caller without identity has blocked no one.
        let Some(caller) = caller.principal() else {
            return Ok(false);
        };
        Ok(self
            .lock()
            .blocked
            .contains(&(caller.as_ref().to_owned(), user_id.to_owned())))
    }

    async fn may_see_region_avatars(
        &self,
        caller: &C,
        _account_id: &Id,
        region_id: &Id,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, _account_id);
        Ok(!self
            .lock()
            .hidden_avatars
            .contains(&(caller.clone(), region_id.clone())))
    }

    async fn avatar_view(
        &self,
        caller: &C,
        account_id: &Id,
        avatar: &SceneAvatar,
    ) -> Result<AvatarView, MemoryError> {
        let viewer = acting_user(caller, account_id);
        let inner = self.locked().await;
        let rules = inner.avatar_rules.get(account_id.as_ref());
        Ok(inner.avatar_view(&viewer, account_id, avatar, rules))
    }

    fn supports_observe(&self, _caller: &C) -> bool {
        self.lock().supports_observe
    }

    async fn may_observe_region(
        &self,
        _caller: &C,
        _account_id: &Id,
        region: &SceneRegion,
    ) -> Result<bool, MemoryError> {
        Ok(!self.locked().await.declined_observers.contains(&region.id))
    }

    /// Every registered account, in id order: access to each region is
    /// checked separately.
    async fn observer_accounts(&self, _caller: &C, _own: &Id) -> Result<Vec<Id>, MemoryError> {
        let inner = self.locked().await;
        if let Some(accounts) = &inner.observer_accounts {
            return Ok(accounts.clone());
        }
        let mut accounts: Vec<Id> = inner
            .accounts
            .keys()
            .map(|a| Id::from(a.as_str()))
            .collect();
        accounts.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
        Ok(accounts)
    }

    async fn set_observing(
        &self,
        caller: &C,
        account_id: &Id,
        region_id: &Id,
        observing: bool,
    ) -> Result<(), MemoryError> {
        let user = acting_user(caller, account_id);
        let mut inner = self.locked().await;
        let key = (account_id.as_ref().to_owned(), region_id.clone());
        let users = inner.observers.entry(key.clone()).or_default();
        let n = users.entry(user.clone()).or_insert(0);
        if observing {
            *n += 1;
        } else {
            *n = n.saturating_sub(1);
            if *n == 0 {
                users.remove(&user);
            }
        }
        if users.is_empty() {
            inner.observers.remove(&key);
        }
        inner.recount(account_id, std::slice::from_ref(region_id));
        Ok(())
    }

    async fn reserved_display_names(
        &self,
        _caller: &C,
        _account_id: &Id,
    ) -> Result<Vec<String>, MemoryError> {
        Ok(self.locked().await.reserved_names.clone())
    }

    async fn may_eject_avatar(
        &self,
        caller: &C,
        account_id: &Id,
        avatar: &SceneAvatar,
    ) -> Result<bool, MemoryError> {
        let caller = &acting_user(caller, account_id);
        // "Region owners and administrators MAY eject avatars".
        let inner = self.locked().await;
        Ok(inner.admins.contains(caller)
            || inner.owns_region(caller, account_id, &avatar.region_id))
    }

    async fn accept_interaction(
        &self,
        _caller: &C,
        _account_id: &Id,
        event: &SceneInteractionEvent,
    ) -> Result<bool, MemoryError> {
        let mut inner = self.locked().await;
        if inner.rate_limited.contains(&event.user_id) {
            return Ok(false);
        }
        inner.interactions.push(event.clone());
        Ok(true)
    }

    async fn accept_region_event(
        &self,
        caller: &C,
        account_id: &Id,
        event: &SceneRegionEvent,
    ) -> Result<bool, MemoryError> {
        let caller = acting_user(caller, account_id);
        let mut inner = self.locked().await;
        if inner.region_event_limited.contains(&caller) {
            return Ok(false);
        }
        inner.region_events.push(event.clone());
        Ok(true)
    }

    fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &Id) -> bool {
        [
            SceneAsset::TYPE_NAME,
            SceneRegion::TYPE_NAME,
            SceneObject::TYPE_NAME,
            SceneAvatar::TYPE_NAME,
        ]
        .contains(&O::TYPE_NAME)
    }
}

// ---------------------------------------------------------------------------
// ConditionalBackend (draft-ietf-jmap-conditional-02)
// ---------------------------------------------------------------------------

/// Conditional Scene Foo/set (bd JMAP-y1yu.15): the whole store is one
/// [`ScopedState`], so a scope isolates every account, and an atomic
/// rollback restores objects, state strings, change logs, derived counts
/// and queued deliveries together. Under an atomic scope the backend leaves
/// `maxAvatarsPerRegion` to the commit, which checks the final state
/// (`final_state_failures`).
impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
    async fn begin_set(
        &self,
        _caller: &C,
        request: SetScopeRequest<'_>,
    ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
        Ok(self.inner.open(request, final_state_failures).await)
    }
}

/// The avatar changes an atomic scope made that break a region-wide rule
/// in the state it would commit (conditional-02 §4.2;
/// draft-atwood-jmap-scene-00 §Entering a Region): more present avatars in
/// a region than the account's `maxAvatarsPerRegion`, as `overQuota` on
/// each present avatar the scope created or changed in that region.
fn final_state_failures(before: &Inner, after: &Inner) -> Vec<DeferredFailure> {
    let mut failures = Vec::new();
    for (account, capability) in &after.accounts {
        let account_id = Id::from(account.as_str());
        let old: HashMap<Id, SceneAvatar> = before
            .all::<SceneAvatar>(&account_id)
            .map(|a| (a.id.clone(), a))
            .collect();
        let now: Vec<SceneAvatar> = after.all::<SceneAvatar>(&account_id).collect();
        for a in &now {
            let op = match old.get(&a.id) {
                None => SetOp::Create(a.id.clone()),
                Some(prev) if prev != a => SetOp::Update(a.id.clone()),
                Some(_) => continue,
            };
            let Some(max) = capability.max_avatars_per_region else {
                continue;
            };
            let present = now
                .iter()
                .filter(|b| b.region_id == a.region_id && b.left_at.is_none())
                .count() as u64;
            if a.left_at.is_none() && present > max {
                failures.push(DeferredFailure::new(
                    op,
                    SetError::new(SetErrorType::OverQuota)
                        .with_description("maxAvatarsPerRegion reached"),
                ));
            }
        }
    }
    failures
}

#[cfg(test)]
mod memory_error_tests {
    use super::MemoryError;

    /// The `JmapAccounts::Error` contract: "Implementations MUST NOT
    /// include ... PII shaped like an email address" in `Display`
    /// output. serde_json data errors quote the offending value, so
    /// [`MemoryError::serde`] must drop the message (bd:JMAP-510h.37).
    #[test]
    fn serde_error_display_omits_offending_value() {
        let canary = "alice@example.com";
        let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
            .expect_err("a string is not a u64");
        assert!(
            e.to_string().contains(canary),
            "precondition: serde_json quotes the value"
        );

        let shown = MemoryError::serde("decode", &e).to_string();
        assert!(!shown.contains(canary), "canary leaked: {shown}");
        assert!(
            shown.contains("decode") && shown.contains("Data"),
            "{shown}"
        );
    }
}

#[cfg(test)]
mod clone_tests {
    use super::MemoryBackend;

    /// Oracle (bd:JMAP-q7k6): `MemoryBackend::clone` is a shared-state
    /// clone, never a deep copy, so a clone and its original hold the
    /// same store while a fresh instance does not.
    #[test]
    fn clone_shares_store() {
        let a = MemoryBackend::new();
        let clone = a.clone();
        let fresh = MemoryBackend::new();
        a.add_admin("u1");
        let admin = |b: &MemoryBackend| b.inner.lock_unscoped().admins.contains("u1");
        assert!(admin(&clone), "a clone sees the original's writes");
        assert!(!admin(&fresh), "a fresh backend does not");
    }
}

#[cfg(test)]
mod max_changes_tests {
    use super::*;
    use jmap_scene_types::SceneObject as T;

    /// A backend whose `T` log holds one commit per element of `states`,
    /// each creating the listed ids under one state.
    fn with_creates(states: &[&[&str]]) -> MemoryBackend {
        let backend = MemoryBackend::new();
        let mut inner = backend.lock();
        for ids in states {
            let changes = ids
                .iter()
                .map(|s| (Id::from(*s), Change::Created))
                .collect();
            inner.commit(T::TYPE_NAME, &Id::from("acc1"), changes);
        }
        drop(inner);
        backend
    }

    /// Oracle: RFC 8620 §5.2, expected pages written by hand: "the server
    /// MUST ensure the number of ids returned across "created", "updated",
    /// and "destroyed" does not exceed this limit. If there are more
    /// changes than this ..., the server SHOULD generate an update to take
    /// the client to an intermediate state, from which the client can
    /// continue to call "Foo/changes" until it is fully up to date." Three
    /// one-create states against `maxChanges` 2 page as states 1-2, then 3.
    #[tokio::test]
    async fn over_max_changes_pages_through_intermediate_state() {
        let backend = with_creates(&[&["a"], &["b"], &["c"]]);

        let first = changes(&backend, "0", 2).await.expect("first page");
        assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
        assert!(first.has_more_changes);
        assert_eq!(first.new_state.as_ref(), "2");

        let rest = changes(&backend, "2", 2).await.expect("second page");
        assert_eq!(rest.created, [Id::from("c")]);
        assert!(!rest.has_more_changes);
        assert_eq!(rest.new_state.as_ref(), "3");
    }

    /// Oracle: RFC 8620 §5.2 "If it is unable to calculate an intermediate
    /// state, it MUST return a "cannotCalculateChanges" error response
    /// instead." One state creating three ids cannot be split under
    /// `maxChanges` 2.
    #[tokio::test]
    async fn one_state_over_max_changes_cannot_calculate() {
        let backend = with_creates(&[&["a", "b", "c"]]);
        assert!(matches!(
            changes(&backend, "0", 2).await,
            Err(BackendChangesError::TooManyChanges { limit: 2 })
        ));
    }

    fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
        ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
        ids
    }

    async fn changes(
        backend: &MemoryBackend,
        since: &str,
        max: u64,
    ) -> Result<ChangesResult, BackendChangesError<<MemoryBackend as JmapAccounts>::Error>> {
        backend
            .get_changes::<T>(
                &Id::from("caller"),
                &Id::from("acc1"),
                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
            )
            .await
    }
}