jmap-scene-server 0.4.0

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
//! 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 the caller's userId (`String`). 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.
//!
//! # 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`.
//!
//! # 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.
//!
//! # Companion capabilities and bindings
//!
//! `advertise_capability` 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)]

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, MutexGuard};

use jmap_scene_types::{
    AccessPolicy, SceneAsset, SceneAvatar, SceneCapability, SceneInteractionEvent, SceneObject,
    SceneRegion,
};
use jmap_scene_types::{
    SceneAssetComparator, SceneAssetFilter, SceneAvatarComparator, SceneAvatarFilter,
    SceneObjectComparator, SceneObjectFilter, SceneRegionComparator, SceneRegionFilter,
};
use jmap_server::{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::{BindingProperty, BindingTarget, SceneBackend};
use jmap_server::{
    BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject, JmapBackend,
    JmapObject, 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,
}

/// `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>);

#[derive(Default)]
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>,
    /// UserIds 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)>,
    /// UserIds whose interactions [`SceneBackend::accept_interaction`]
    /// refuses as over the rate.
    rate_limited: HashSet<String>,
    /// Interactions [`SceneBackend::accept_interaction`] accepted, in order.
    interactions: Vec<SceneInteractionEvent>,
    /// `(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>,
}

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)));
    }

    /// Set each of `regions`' `activeAvatarCount` to its number of avatars
    /// with `leftAt` `null`, 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 Some(stored) = self
                .objects_mut(SceneRegion::TYPE_NAME, account_id)
                .get_mut(region)
            else {
                continue;
            };
            if stored.get("activeAvatarCount") != Some(&json!(active)) {
                stored["activeAvatarCount"] = json!(active);
                changed.push((region.clone(), Change::Updated));
            }
        }
        if !changed.is_empty() {
            self.commit(SceneRegion::TYPE_NAME, account_id, changed);
        }
    }

    /// §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.
    fn enter(
        &mut self,
        account_id: &Id,
        avatar: SceneAvatar,
    ) -> 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)?;
        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,
    ) -> 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 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 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())
    }
}

/// A fully in-memory implementation of [`SceneBackend`].
///
/// Cloning is cheap and **shared-state**; see the [`Clone`] impl.
#[derive(Default)]
#[non_exhaustive]
pub struct MemoryBackend {
    inner: Arc<Mutex<Inner>>,
}

/// 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 `Mutex`-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 Clone for MemoryBackend {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl MemoryBackend {
    /// An empty backend with no accounts.
    pub fn new() -> Self {
        Self::default()
    }

    fn lock(&self) -> MutexGuard<'_, Inner> {
        // A poisoned lock means a test already panicked mid-mutation.
        self.inner.lock().expect("MemoryBackend lock poisoned")
    }

    /// Register `account_id` with the Scene capability object it
    /// advertises.
    #[doc(hidden)]
    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.
    #[doc(hidden)]
    pub fn add_admin(&self, user: &str) {
        self.lock().admins.insert(user.to_owned());
    }

    /// Advertise capability `uri` for `account_id`.
    #[doc(hidden)]
    pub fn advertise_capability(&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`.
    #[doc(hidden)]
    pub fn grant_region_access(&self, region_id: &str, user: &str) {
        self.lock()
            .grants
            .insert((region_id.to_owned(), user.to_owned()));
    }

    /// 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)));
    }

    /// 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()
    }

    /// 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 `JmapBackend::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 JmapBackend for MemoryBackend {
    type Error = MemoryError;
    type CallerCtx = String;

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

    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        _caller: &String,
        account_id: &Id,
        ids: Option<&[Id]>,
        _properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), MemoryError> {
        let inner = self.lock();
        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: &String,
        account_id: &Id,
    ) -> Result<State, MemoryError> {
        Ok(State::from(
            self.lock().state(O::TYPE_NAME, account_id).to_string(),
        ))
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        _caller: &String,
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<MemoryError>> {
        let since_state = params.since_state;
        let max_changes = params.max_changes;
        let inner = self.lock();
        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);
        }

        let window = || {
            inner
                .log
                .get(O::TYPE_NAME)
                .and_then(|m| m.get(account_id.as_ref()))
                .into_iter()
                .flatten()
                .filter(move |(s, _, _)| *s > since)
        };

        // 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 `net` below.
        let mut upto = current;
        if let Some(max) = max_changes {
            let mut seen: HashSet<&Id> = HashSet::new();
            let (mut fits, mut commit) = (since, since);
            for (s, id, _) in window() {
                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 });
                    }
                    upto = fits;
                    break;
                }
            }
        }

        // 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.
        let mut net: Vec<(Id, Change)> = Vec::new();
        for (_, id, change) in window().filter(|(s, _, _)| *s <= upto) {
            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)),
            }
        }
        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: &String,
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
        let QueryParams {
            filter,
            sort,
            limit,
            position,
            anchor,
            anchor_offset,
            ..
        } = params;
        let sort = sort.unwrap_or_default();
        let inner = self.lock();
        let ids = if O::TYPE_NAME == SceneAsset::TYPE_NAME {
            let filter: Option<SceneAssetFilter> = filter.map(recode).transpose()?;
            let sort: Vec<SceneAssetComparator> = recode(&sort)?;
            sorted_ids(
                inner.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(
                inner.all::<SceneRegion>(account_id),
                |r| {
                    inner.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)?;
            sorted_ids(
                inner.all::<SceneAvatar>(account_id),
                |a| {
                    inner.may_access(caller, account_id, &a.region_id)
                        && !inner.blocked.contains(&(caller.clone(), a.user_id.clone()))
                        && !inner
                            .hidden_avatars
                            .contains(&(caller.clone(), 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> = inner
                .all::<SceneObject>(account_id)
                .map(|o| (o.id.clone(), o))
                .collect();
            sorted_ids(
                all.values(),
                |o| {
                    inner.may_access(caller, account_id, &o.region_id)
                        && !inner.hidden.contains(&(caller.clone(), 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
            ))));
        };

        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: &String,
        _account_id: &Id,
        _params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>> {
        Err(BackendChangesError::CannotCalculate)
    }
}

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

    async fn blob_size(
        &self,
        _caller: &String,
        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: &String,
        account_id: &Id,
        _create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<MemoryError>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        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.lock();
        if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
            let avatar: SceneAvatar = decode(&value).map_err(BackendSetError::Other)?;
            let stored = inner.enter(account_id, avatar)?;
            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: &String,
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<MemoryError>> {
        let mut inner = self.lock();
        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)?;
                }
                (false, false) => {}
            }
            regions.extend(
                current
                    .get("regionId")
                    .and_then(Value::as_str)
                    .map(Id::from),
            );
        }
        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);
        inner.recount(account_id, &regions);
        Ok(None)
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &String,
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<MemoryError>> {
        let mut inner = self.lock();
        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;
            }
        }
        for k in &gone {
            map.remove(k);
        }
        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;
                }
                for k in &gone {
                    map.remove(k);
                }
                inner.commit(
                    contained,
                    account_id,
                    gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
                );
            }
        }
        Ok(())
    }

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

    fn has_capability(&self, _caller: &String, 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: &String,
        _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: &String,
        _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: &String,
        _account_id: &Id,
        region: &SceneRegion,
    ) -> Result<bool, MemoryError> {
        // "Only the owner or an admin may modify region properties."
        Ok(region.owner_id == *caller || self.lock().admins.contains(caller))
    }

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

    async fn may_modify_object(
        &self,
        caller: &String,
        account_id: &Id,
        object: &SceneObject,
    ) -> Result<bool, MemoryError> {
        // "Only the object's `ownerId`, the region owner, or a
        // deployment-admin may modify another user's object."
        let inner = self.lock();
        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: &String,
        _account_id: &Id,
    ) -> Result<String, MemoryError> {
        Ok(caller.clone())
    }

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

    async fn may_access_region(
        &self,
        caller: &String,
        account_id: &Id,
        region_id: &Id,
    ) -> Result<bool, MemoryError> {
        Ok(self.lock().may_access(caller, account_id, region_id))
    }

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

    async fn is_user_blocked(&self, caller: &String, user_id: &str) -> Result<bool, MemoryError> {
        Ok(self
            .lock()
            .blocked
            .contains(&(caller.clone(), user_id.to_owned())))
    }

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

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

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

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

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

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

    /// The `JmapBackend::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;
    use std::sync::Arc;

    /// Oracle (bd:JMAP-q7k6): `MemoryBackend::clone` is a shared-state
    /// `Arc` 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();
        assert!(Arc::ptr_eq(&a.inner, &a.clone().inner));
        assert!(!Arc::ptr_eq(&a.inner, &MemoryBackend::new().inner));
    }
}

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

    const CALLER: String = String::new();

    /// 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 JmapBackend>::Error>> {
        backend
            .get_changes::<T>(
                &CALLER,
                &Id::from("acc1"),
                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
            )
            .await
    }
}