Skip to main content

jmap_scene_server/
memory.rs

1//! In-memory reference implementation of [`SceneBackend`].
2//!
3//! # This is a reference implementation, not production
4//!
5//! `MemoryBackend` backs this crate's integration tests and is a readable
6//! example for anyone writing a real backend. All state lives in
7//! `HashMap`s behind a `std::sync::Mutex`; nothing is persisted. Blobs are
8//! registered by size only, with `add_blob`.
9//!
10//! # Caller context
11//!
12//! `CallerCtx` is a type implementing [`MemoryCaller`](jmap_server::MemoryCaller):
13//! the caller's Principal id ([`Id`](jmap_types::Id), the default), whose
14//! string is the caller's `userId`, or `()` for a deployment without
15//! identity, whose every caller acts as the user named by the account id.
16//! The owner of an asset or
17//! a region is its `ownerId`;
18//! [`SceneBackend::may_modify_asset`] and
19//! [`SceneBackend::may_update_region`] allow the owner and the users
20//! registered with `add_admin`, and so does
21//! [`SceneBackend::may_destroy_region`]. [`SceneBackend::may_modify_object`] allows the object's
22//! owner, its region's owner and the admins; a created object's `ownerId`
23//! is the caller.
24//!
25//! # Accounts
26//!
27//! An account exists once
28//! [`MemoryBackend::with_account`](crate::memory::MemoryBackend::with_account) (or
29//! [`MemoryBackend::register_account`](crate::memory::MemoryBackend::register_account)) registers it with the Scene
30//! capability object it advertises; every call naming any other account is
31//! `accountNotFound` (RFC 8620 §3.6.2).
32//!
33//! # Avatars
34//!
35//! [`SceneBackend::caller_user_id`] is the caller.
36//! [`SceneBackend::may_enter_region`] refuses the users barred from a
37//! region with `ban_from_region`. [`SceneBackend::may_eject_avatar`] allows the avatar's
38//! region owner and the admins. Each region's `activeAvatarCount` is
39//! recomputed from its avatars with `leftAt` `null` whenever an avatar
40//! enters or leaves.
41//!
42//! # Interactions
43//!
44//! [`SceneBackend::accept_interaction`] refuses the interactions of users
45//! registered with `rate_limit_interactions` and records the rest, read
46//! back with `accepted_interactions`.
47//! [`SceneBackend::accept_region_event`] does the same for region events
48//! with `rate_limit_region_events` and `accepted_region_events`.
49//!
50//! # Visibility
51//!
52//! [`SceneBackend::may_access_region`] refuses an `"invite"` region to
53//! everyone but its owner, the admins, the users in its `invitedUserIds`,
54//! the users given access with `grant_region_access` (one of the "other
55//! mechanisms" an `"invite"` region MAY admit by) and the users with an
56//! active avatar in it; other policies, and a region that is not stored,
57//! admit everyone (there are no Spaces here). `hide_object` takes an object out of one user's
58//! visibility set, for [`SceneBackend::is_object_visible`]; `block` makes
59//! one user blocked by another, for [`SceneBackend::is_user_blocked`];
60//! `hide_region_avatars` hides a region's avatars from one user, as for a
61//! region bound to an E2EE call, for
62//! [`SceneBackend::may_see_region_avatars`].
63//! `reserve_display_name` adds a name to the list
64//! [`SceneBackend::reserved_display_names`] returns for every account.
65//! `/query` omits the regions, objects and avatars those hooks hide from
66//! the caller; `activeAvatarCount` stays the true count.
67//!
68//! [`SceneBackend::avatar_view`] follows per-account rules: `hide_avatar`
69//! hides one avatar from one viewer, `withhold_avatar` withholds an
70//! [`AvatarRedaction`]'s properties, and
71//! `reveal_avatar` undoes either. Each advances the account's SceneAvatar
72//! state. The avatar's own user, the region owner and the admins always
73//! see it in full. `SceneAvatar/query` leaves hidden avatars out and
74//! matches the redacted values. Once an account has a rule,
75//! `SceneAvatar/changes` answers from the caller's view, from snapshots
76//! kept per state; a state from before the first rule is
77//! `cannotCalculateChanges`.
78//!
79//! # Observers
80//!
81//! `set_supports_observe` turns on [`SceneBackend::supports_observe`].
82//! [`SceneBackend::observer_accounts`] is every registered account (or
83//! the list given to `restrict_observer_accounts`),
84//! [`SceneBackend::may_observe_region`] declines the regions registered
85//! with `decline_observers` (until `admit_observers`), and
86//! [`SceneBackend::set_observing`] counts each user's observing
87//! connections per region. A region's `observerCount` is the users
88//! observing it who have access and no active avatar there, or `0` while
89//! `allowObservers` is `false` or the region declines observers. It is
90//! recomputed, advancing the SceneRegion state when it changes, whenever
91//! any of those inputs changes: an observer starts or stops, an avatar
92//! enters or leaves, the region is updated, and the knobs that change
93//! access or the observer policy from outside the region
94//! (`grant_region_access`, `revoke_region_access`, `add_admin`,
95//! `decline_observers`, `admit_observers`). There are no Spaces here, so
96//! no other access change exists.
97//!
98//! # Companion capabilities and bindings
99//!
100//! `advertise` records a capability URI for an account, for
101//! [`SceneBackend::has_capability`]. `set_region_binding` records what a
102//! binding id references; [`SceneBackend::region_binding`] answers
103//! [`BindingTarget::Missing`] for any id not recorded. `set_channel_space`
104//! records that a channel belongs to a Space;
105//! [`SceneBackend::channel_in_space`] answers `false` for any pair not
106//! recorded.
107//!
108//! # Quota
109//!
110//! `set_storage_quota` sets an account's total asset storage in bytes;
111//! [`SceneBackend::create_object`] refuses a `SceneAsset` that would
112//! exceed it, a `SceneRegion` beyond the capability's
113//! `maxRegionsPerAccount`, and a `SceneObject` beyond its
114//! `maxObjectsPerRegion`, with `overQuota`.
115//!
116//! # Region destroy
117//!
118//! Destroying a `SceneRegion` also destroys the stored `SceneObject` and
119//! `SceneAvatar` records whose `regionId` names it. Destroying a
120//! `SceneObject` also destroys its descendants, in the same state step.
121//!
122//! # Query
123//!
124//! `SceneAsset/query`, `SceneRegion/query`, `SceneObject/query` and
125//! `SceneAvatar/query` evaluate the filter and sort
126//! with the [`crate::query`] functions. `/queryChanges` is not implemented: results
127//! say `canCalculateChanges: false` and `/queryChanges` returns
128//! `cannotCalculateChanges` (RFC 8620 §5.6).
129//!
130//! # Concurrency
131//!
132//! The `await_holding_lock` lint is denied module-wide: no guard is held
133//! across an `.await`.
134
135#![deny(clippy::await_holding_lock)]
136
137mod history;
138
139use std::collections::{HashMap, HashSet};
140use std::marker::PhantomData;
141
142use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
143use jmap_scene_types::{
144    AccessPolicy, SceneAsset, SceneAvatar, SceneCapability, SceneInteractionEvent, SceneObject,
145    SceneRegion, SceneRegionEvent,
146};
147use jmap_scene_types::{
148    SceneAssetComparator, SceneAssetFilter, SceneAvatarComparator, SceneAvatarFilter,
149    SceneObjectComparator, SceneObjectFilter, SceneRegionComparator, SceneRegionFilter,
150};
151use jmap_server::{
152    BeginSetError, ConditionalBackend, DeferredFailure, MemoryCaller, ScopedGuard, ScopedState,
153    SetOp, SetScope, SetScopeRequest, apply_patch_object, limit_or_max, resolve_query_start,
154};
155use jmap_types::{Id, State};
156use serde::Serialize;
157use serde::de::DeserializeOwned;
158use serde_json::{Value, json};
159
160use crate::query::{
161    asset_matches, avatar_matches, compare_assets, compare_avatars, compare_objects,
162    compare_regions, object_matches, region_local_position, region_matches,
163};
164use crate::{AvatarRedaction, AvatarView, BindingProperty, BindingTarget, SceneBackend};
165use jmap_server::{
166    BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
167    JmapAccounts, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult, QueryObject,
168    QueryParams, QueryResult, SetError, SetErrorType, SetObject,
169};
170
171/// How one id changed in one state step.
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum Change {
174    Created,
175    Updated,
176    Destroyed,
177    /// Restored from object history (draft-ietf-jmap-object-history §5.1).
178    Restored,
179}
180
181/// `type_name` → `account_id` → `V`. Nested rather than tuple-keyed so a
182/// lookup borrows the `&str` account id instead of allocating a `String`.
183type Keyed<V> = HashMap<&'static str, HashMap<String, V>>;
184
185/// The avatar changes and the regions to recount that [`Inner::admit`]
186/// leaves for its caller to commit.
187type Admitted = (Vec<(Id, Change)>, Vec<Id>);
188
189/// The per-avatar visibility rules of one account (§Avatar Visibility).
190#[derive(Default, Clone)]
191struct AvatarRules {
192    /// `(viewer userId, avatar id)` pairs: the avatar is hidden from the
193    /// viewer.
194    hidden: HashSet<(String, Id)>,
195    /// `(viewer userId, avatar id)` → the properties withheld from the
196    /// viewer.
197    withheld: HashMap<(String, Id), AvatarRedaction>,
198}
199
200/// One `SceneAvatar` state of an account with [`AvatarRules`]: what every
201/// caller's view at that state is computed from.
202#[derive(Clone)]
203struct AvatarSnapshot {
204    state: u64,
205    avatars: HashMap<Id, Value>,
206    rules: AvatarRules,
207}
208
209/// The store, behind a [`ScopedState`] so a conditional Foo/set can isolate
210/// and roll it back (docs/design/conditional.md §7).
211#[derive(Default, Clone)]
212struct Inner {
213    /// `type_name` → `account_id` → `id → stored object`.
214    objects: Keyed<HashMap<Id, Value>>,
215    /// `type_name` → `account_id` → state counter.
216    states: Keyed<u64>,
217    /// `type_name` → `account_id` → `(state after the change, id, change)`.
218    log: Keyed<Vec<(u64, Id, Change)>>,
219    /// Registered accounts and their Scene capability object.
220    accounts: HashMap<String, SceneCapability>,
221    /// `(account_id, blob_id)` → blob size in bytes.
222    blobs: HashMap<(String, String), u64>,
223    /// Account → total `SceneAsset` storage limit in bytes.
224    storage_quota: HashMap<String, u64>,
225    /// User ids with admin privileges.
226    admins: HashSet<String>,
227    /// Account → advertised capability URIs.
228    capabilities: HashMap<String, HashSet<String>>,
229    /// `(binding property, id)` → what the id references.
230    bindings: HashMap<(BindingProperty, String), BindingTarget>,
231    channel_spaces: HashSet<(String, String)>,
232    /// `(region id, userId)` pairs granted access to an `"invite"` region.
233    grants: HashSet<(String, String)>,
234    /// `(region id, userId)` pairs barred from entering the region.
235    bans: HashSet<(String, String)>,
236    /// `(userId, object id)` pairs outside that user's visibility set.
237    hidden: HashSet<(String, Id)>,
238    /// User ids whose interactions [`SceneBackend::accept_interaction`]
239    /// refuses as over the rate.
240    rate_limited: HashSet<String>,
241    /// Interactions [`SceneBackend::accept_interaction`] accepted, in order.
242    interactions: Vec<SceneInteractionEvent>,
243    /// User ids whose region events [`SceneBackend::accept_region_event`]
244    /// refuses as over the rate.
245    region_event_limited: HashSet<String>,
246    /// Region events [`SceneBackend::accept_region_event`] accepted, in
247    /// order.
248    region_events: Vec<SceneRegionEvent>,
249    /// `(blocking userId, blocked userId)` pairs.
250    blocked: HashSet<(String, String)>,
251    /// `(userId, region id)` pairs: regions whose avatars that user may
252    /// not see.
253    hidden_avatars: HashSet<(String, Id)>,
254    /// Reserved avatar display names.
255    reserved_names: Vec<String>,
256    /// Account → the per-avatar visibility rules of
257    /// [`SceneBackend::avatar_view`]. An account appears here once a rule
258    /// is set, and from then on answers `SceneAvatar/changes` from each
259    /// caller's view.
260    avatar_rules: HashMap<String, AvatarRules>,
261    /// Account → one snapshot per `SceneAvatar` state since the first rule:
262    /// the state, the stored avatars and the rules then in force.
263    avatar_views: HashMap<String, Vec<AvatarSnapshot>>,
264    /// Whether [`SceneBackend::supports_observe`] answers `true`.
265    supports_observe: bool,
266    /// `(account, region id)` → observing userId → number of its
267    /// connections observing, from [`SceneBackend::set_observing`].
268    observers: HashMap<(String, Id), HashMap<String, usize>>,
269    /// Region ids whose observers [`SceneBackend::may_observe_region`]
270    /// declines by policy.
271    declined_observers: HashSet<Id>,
272    /// What [`SceneBackend::observer_accounts`] answers instead of every
273    /// registered account, once set.
274    observer_accounts: Option<Vec<Id>>,
275    /// Object history, once `MemoryBackend::with_object_history` turns it
276    /// on.
277    history: Option<jmap_object_history_server::HistoryStore>,
278}
279
280impl Inner {
281    fn objects(&self, type_name: &'static str, account_id: &Id) -> Option<&HashMap<Id, Value>> {
282        self.objects
283            .get(type_name)
284            .and_then(|m| m.get(account_id.as_ref()))
285    }
286
287    fn objects_mut(&mut self, type_name: &'static str, account_id: &Id) -> &mut HashMap<Id, Value> {
288        self.objects
289            .entry(type_name)
290            .or_default()
291            .entry(account_id.as_ref().to_owned())
292            .or_default()
293    }
294
295    fn state(&self, type_name: &'static str, account_id: &Id) -> u64 {
296        self.states
297            .get(type_name)
298            .and_then(|m| m.get(account_id.as_ref()))
299            .copied()
300            .unwrap_or(0)
301    }
302
303    /// Advance the state of `type_name` once and log `changes` under it.
304    fn commit(&mut self, type_name: &'static str, account_id: &Id, changes: Vec<(Id, Change)>) {
305        let state = self
306            .states
307            .entry(type_name)
308            .or_default()
309            .entry(account_id.as_ref().to_owned())
310            .or_insert(0);
311        *state += 1;
312        let state = *state;
313        self.log
314            .entry(type_name)
315            .or_default()
316            .entry(account_id.as_ref().to_owned())
317            .or_default()
318            .extend(changes.into_iter().map(|(id, c)| (state, id, c)));
319        if type_name == SceneAvatar::TYPE_NAME {
320            self.snapshot_avatars(account_id);
321        }
322    }
323
324    /// Record the account's current avatars and rules under its current
325    /// `SceneAvatar` state, once the account has avatar rules.
326    fn snapshot_avatars(&mut self, account_id: &Id) {
327        let Some(rules) = self.avatar_rules.get(account_id.as_ref()).cloned() else {
328            return;
329        };
330        let snapshot = AvatarSnapshot {
331            state: self.state(SceneAvatar::TYPE_NAME, account_id),
332            avatars: self
333                .objects(SceneAvatar::TYPE_NAME, account_id)
334                .cloned()
335                .unwrap_or_default(),
336            rules,
337        };
338        self.avatar_views
339            .entry(account_id.as_ref().to_owned())
340            .or_default()
341            .push(snapshot);
342    }
343
344    /// Change the account's avatar rules with `change`, then advance the
345    /// `SceneAvatar` state: "Whenever the caller's view changes, the server
346    /// advances the `SceneAvatar` state string". The first rule also records
347    /// the view before it, so `/changes` from that state still works.
348    fn change_avatar_rules(&mut self, account_id: &Id, change: impl FnOnce(&mut AvatarRules)) {
349        if !self.avatar_rules.contains_key(account_id.as_ref()) {
350            self.avatar_rules
351                .insert(account_id.as_ref().to_owned(), AvatarRules::default());
352            self.snapshot_avatars(account_id);
353        }
354        if let Some(rules) = self.avatar_rules.get_mut(account_id.as_ref()) {
355            change(rules);
356        }
357        self.commit(SceneAvatar::TYPE_NAME, account_id, Vec::new());
358    }
359
360    /// [`SceneBackend::avatar_view`] of `avatar` for `viewer` under
361    /// `rules`: whole for the avatar's own user, the admins and the region
362    /// owner ("The server SHOULD NOT hide avatars, or withhold their
363    /// properties, from the region owner and administrators"), else as the
364    /// rules say.
365    fn avatar_view(
366        &self,
367        viewer: &str,
368        account_id: &Id,
369        avatar: &SceneAvatar,
370        rules: Option<&AvatarRules>,
371    ) -> AvatarView {
372        let Some(rules) = rules else {
373            return AvatarView::Full;
374        };
375        if avatar.user_id == viewer
376            || self.admins.contains(viewer)
377            || self.owns_region(viewer, account_id, &avatar.region_id)
378        {
379            return AvatarView::Full;
380        }
381        let key = (viewer.to_owned(), avatar.id.clone());
382        if rules.hidden.contains(&key) {
383            return AvatarView::Hidden;
384        }
385        match rules.withheld.get(&key) {
386            Some(r) => AvatarView::Redacted(r.clone()),
387            None => AvatarView::Full,
388        }
389    }
390
391    /// `avatar` as `viewer` sees it under `rules`, or `None` when hidden.
392    fn viewed_avatar(
393        &self,
394        viewer: &str,
395        account_id: &Id,
396        mut avatar: SceneAvatar,
397        rules: Option<&AvatarRules>,
398    ) -> Option<SceneAvatar> {
399        match self.avatar_view(viewer, account_id, &avatar, rules) {
400            AvatarView::Hidden => None,
401            AvatarView::Redacted(r) => {
402                r.apply(&mut avatar);
403                Some(avatar)
404            }
405            _ => Some(avatar),
406        }
407    }
408
409    /// The avatars of `snapshot` as `viewer` sees them, by id.
410    fn view_at(
411        &self,
412        viewer: &str,
413        account_id: &Id,
414        snapshot: &AvatarSnapshot,
415    ) -> HashMap<Id, Value> {
416        snapshot
417            .avatars
418            .iter()
419            .filter_map(|(id, v)| {
420                let a = decode::<SceneAvatar>(v).ok()?;
421                let seen = self.viewed_avatar(viewer, account_id, a, Some(&snapshot.rules))?;
422                Some((id.clone(), serde_json::to_value(seen).ok()?))
423            })
424            .collect()
425    }
426
427    /// `SceneAvatar/changes` from `viewer`'s view (§Avatar Visibility): an
428    /// avatar that became visible is `created`, one that became hidden
429    /// `destroyed`, one whose returned value changed `updated`. `None`
430    /// when `since` predates the account's first snapshot.
431    fn avatar_changes_for(
432        &self,
433        viewer: &str,
434        account_id: &Id,
435        since: u64,
436        max_changes: Option<u64>,
437    ) -> Option<Result<ChangesResult, BackendChangesError<MemoryError>>> {
438        let snapshots = self.avatar_views.get(account_id.as_ref())?;
439        let start = snapshots.iter().position(|s| s.state == since)?;
440        let base = self.view_at(viewer, account_id, &snapshots[start]);
441        let diff = |now: &HashMap<Id, Value>| {
442            let mut created = Vec::new();
443            let mut updated = Vec::new();
444            let mut destroyed = Vec::new();
445            for (id, v) in now {
446                match base.get(id) {
447                    None => created.push(id.clone()),
448                    Some(old) if old != v => updated.push(id.clone()),
449                    Some(_) => {}
450                }
451            }
452            for id in base.keys().filter(|id| !now.contains_key(*id)) {
453                destroyed.push(id.clone());
454            }
455            (created, updated, destroyed)
456        };
457        let current = self.state(SceneAvatar::TYPE_NAME, account_id);
458        let mut result = (Vec::new(), Vec::new(), Vec::new());
459        let mut upto = since;
460        for snapshot in &snapshots[start + 1..] {
461            let next = diff(&self.view_at(viewer, account_id, snapshot));
462            let count = (next.0.len() + next.1.len() + next.2.len()) as u64;
463            if let Some(max) = max_changes
464                && count > max
465            {
466                if upto == since {
467                    return Some(Err(BackendChangesError::TooManyChanges { limit: max }));
468                }
469                break;
470            }
471            result = next;
472            upto = snapshot.state;
473        }
474        let (created, updated, destroyed) = result;
475        Some(Ok(ChangesResult::new(
476            created,
477            updated,
478            destroyed,
479            upto < current,
480            State::from(upto.to_string()),
481        )))
482    }
483
484    /// Set each of `regions`' `activeAvatarCount` to its number of avatars
485    /// with `leftAt` `null`, and, for a region with the observer
486    /// properties, its `observerCount` (see [`Self::observer_count`]), and
487    /// advance the `SceneRegion` state once if any count changed.
488    fn recount(&mut self, account_id: &Id, regions: &[Id]) {
489        let mut changed = Vec::new();
490        for region in regions {
491            let active = self
492                .all::<SceneAvatar>(account_id)
493                .filter(|a| a.region_id == *region && a.left_at.is_none())
494                .count();
495            let observers = self.observer_count(account_id, region);
496            let Some(stored) = self
497                .objects_mut(SceneRegion::TYPE_NAME, account_id)
498                .get_mut(region)
499            else {
500                continue;
501            };
502            let mut differs = false;
503            if stored.get("activeAvatarCount") != Some(&json!(active)) {
504                stored["activeAvatarCount"] = json!(active);
505                differs = true;
506            }
507            if let Some(observers) = observers
508                && stored.get("observerCount") != Some(&json!(observers))
509            {
510                stored["observerCount"] = json!(observers);
511                differs = true;
512            }
513            if differs {
514                changed.push((region.clone(), Change::Updated));
515            }
516        }
517        if !changed.is_empty() {
518            self.commit(SceneRegion::TYPE_NAME, account_id, changed);
519        }
520    }
521
522    /// [`Self::recount`] every region some user observes
523    /// ([`SceneBackend::set_observing`]), or only those with id `region_id`
524    /// when given, in every account: after a change outside the region
525    /// record that may change who counts as its observer (access or the
526    /// observer policy).
527    fn recount_observed(&mut self, region_id: Option<&Id>) {
528        let mut by_account: HashMap<Id, Vec<Id>> = HashMap::new();
529        for (account, region) in self.observers.keys() {
530            if region_id.is_none_or(|r| r == region) {
531                by_account
532                    .entry(Id::from(account.as_str()))
533                    .or_default()
534                    .push(region.clone());
535            }
536        }
537        for (account, regions) in by_account {
538            self.recount(&account, &regions);
539        }
540    }
541
542    /// §Entering a Region for `avatar`, which carries its minted id, under
543    /// the lock: the steps of [`SceneBackend::create_object`] for a
544    /// `SceneAvatar`. Returns the
545    /// trait's error type unboxed, as `create_object` does.
546    ///
547    /// `defer`: an atomic conditional-02 scope is open on this task, so the
548    /// `maxAvatarsPerRegion` check is left to its commit
549    /// (`final_state_failures`). The one-record check is not: records are
550    /// never destroyed, so the final state cannot differ.
551    fn enter(
552        &mut self,
553        account_id: &Id,
554        avatar: SceneAvatar,
555        defer: bool,
556    ) -> Result<Value, BackendSetError<MemoryError>> {
557        // "When the user already has a SceneAvatar record in the same
558        // region, whether present or departed, the server MUST NOT create a
559        // second record and MUST return an `alreadyExists` SetError".
560        if let Some(existing) = self
561            .all::<SceneAvatar>(account_id)
562            .find(|a| a.user_id == avatar.user_id && a.region_id == avatar.region_id)
563        {
564            return Err(BackendSetError::SetError(Box::new(
565                SetError::new(SetErrorType::AlreadyExists)
566                    .with_description("the user already has an avatar record in this region")
567                    .with_existing_id(existing.id),
568            )));
569        }
570        let (mut changes, mut regions) = self.admit(account_id, &avatar, defer)?;
571        let id = avatar.id.clone();
572        let value = serde_json::to_value(&avatar)
573            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize SceneAvatar", &e)))?;
574        self.objects_mut(SceneAvatar::TYPE_NAME, account_id)
575            .insert(id.clone(), value.clone());
576        changes.push((id, Change::Created));
577        regions.push(avatar.region_id);
578        self.commit(SceneAvatar::TYPE_NAME, account_id, changes);
579        self.recount(account_id, &regions);
580        Ok(value)
581    }
582
583    /// The steps a create and a re-entry of `avatar` share, under the
584    /// lock: refuse with `overQuota` when its region already holds
585    /// `maxAvatarsPerRegion` present avatars, then set `leftAt` to
586    /// `avatar.joined_at` on the user's present avatars ("a user is
587    /// present in at most one region at a time"). Returns those avatars'
588    /// changes and their regions, for the caller to commit and recount.
589    fn admit(
590        &mut self,
591        account_id: &Id,
592        avatar: &SceneAvatar,
593        defer: bool,
594    ) -> Result<Admitted, BackendSetError<MemoryError>> {
595        let max = self
596            .accounts
597            .get(account_id.as_ref())
598            .and_then(|c| c.max_avatars_per_region);
599        let present = self
600            .all::<SceneAvatar>(account_id)
601            .filter(|a| a.region_id == avatar.region_id && a.left_at.is_none())
602            .count() as u64;
603        if !defer && max.is_some_and(|max| present >= max) {
604            return Err(BackendSetError::SetError(Box::new(
605                SetError::new(SetErrorType::OverQuota)
606                    .with_description("maxAvatarsPerRegion reached"),
607            )));
608        }
609
610        let previous: Vec<SceneAvatar> = self
611            .all::<SceneAvatar>(account_id)
612            .filter(|a| a.user_id == avatar.user_id && a.left_at.is_none())
613            .collect();
614        let avatars = self.objects_mut(SceneAvatar::TYPE_NAME, account_id);
615        let mut changes = Vec::new();
616        let mut regions = Vec::new();
617        // "When the user has an active SceneAvatar in a different region,
618        // the server SHOULD set `leftAt` on the previous avatar".
619        for previous in previous {
620            if let Some(v) = avatars.get_mut(&previous.id) {
621                v["leftAt"] = json!(avatar.joined_at);
622                changes.push((previous.id, Change::Updated));
623                regions.push(previous.region_id);
624            }
625        }
626        Ok((changes, regions))
627    }
628
629    /// The `observerCount` of region `region_id`, or `None` when it has no
630    /// observer properties: "the number of users currently observing the
631    /// region through an observer subscription ... who do not have an
632    /// active avatar in it. A user with several observing connections
633    /// counts once." A user who lost access no longer receives events, and
634    /// `allowObservers` `false` "stops event delivery to the region's
635    /// current observers", so neither counts.
636    fn observer_count(&self, account_id: &Id, region_id: &Id) -> Option<usize> {
637        let region = self.region(account_id, region_id)?;
638        region.observer_count?;
639        if region.allow_observers == Some(false) || self.declined_observers.contains(region_id) {
640            return Some(0);
641        }
642        let watching = self
643            .observers
644            .get(&(account_id.as_ref().to_owned(), region_id.clone()));
645        Some(watching.map_or(0, |users| {
646            users
647                .keys()
648                .filter(|user| {
649                    self.admits(user, account_id, &region)
650                        && !self.all::<SceneAvatar>(account_id).any(|a| {
651                            a.region_id == *region_id && a.user_id == **user && a.left_at.is_none()
652                        })
653                })
654                .count()
655        }))
656    }
657
658    /// The stored region `region_id`, if it decodes.
659    fn region(&self, account_id: &Id, region_id: &Id) -> Option<SceneRegion> {
660        self.objects(SceneRegion::TYPE_NAME, account_id)
661            .and_then(|m| m.get(region_id))
662            .and_then(|v| decode::<SceneRegion>(v).ok())
663    }
664
665    /// `true` if `caller` is the owner of the region `region_id`.
666    fn owns_region(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
667        self.region(account_id, region_id)
668            .is_some_and(|r| r.owner_id == caller)
669    }
670
671    /// `true` if `caller` has access to `region`: "A user has access to a
672    /// region when its `accessPolicy` admits the user, when the user is
673    /// the region owner, when the user has deployment-defined
674    /// administrative privileges, or when the user has an active
675    /// `SceneAvatar` in it"; `"invite"` admits "The users whose `userIds` are
676    /// listed in `invitedUserIds`" and those given a grant.
677    fn admits(&self, caller: &str, account_id: &Id, region: &SceneRegion) -> bool {
678        region.access_policy != AccessPolicy::Invite
679            || region.owner_id == caller
680            || self.admins.contains(caller)
681            || region.invited_user_ids.iter().any(|u| u == caller)
682            || self
683                .grants
684                .contains(&(region.id.as_ref().to_owned(), caller.to_owned()))
685            || self
686                .all::<SceneAvatar>(account_id)
687                .any(|a| a.region_id == region.id && a.user_id == caller && a.left_at.is_none())
688    }
689
690    /// [`SceneBackend::may_access_region`]: [`Self::admits`]; a region that
691    /// is not stored admits everyone.
692    fn may_access(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
693        self.region(account_id, region_id)
694            .is_none_or(|r| self.admits(caller, account_id, &r))
695    }
696
697    /// Every stored object of type `O` that decodes.
698    fn all<O: JmapObject>(&self, account_id: &Id) -> impl Iterator<Item = O> + '_ + use<'_, O> {
699        self.objects(O::TYPE_NAME, account_id)
700            .into_iter()
701            .flat_map(HashMap::values)
702            .filter_map(|v| O::deserialize(v).ok())
703    }
704
705    /// The log entries of `type_name` in `account_id` after state `since`,
706    /// oldest first.
707    fn log_window(
708        &self,
709        type_name: &'static str,
710        account_id: &Id,
711        since: u64,
712    ) -> impl Iterator<Item = &(u64, Id, Change)> + '_ + use<'_> {
713        self.log
714            .get(type_name)
715            .and_then(|m| m.get(account_id.as_ref()))
716            .into_iter()
717            .flatten()
718            .filter(move |(s, _, _)| *s > since)
719    }
720
721    /// The state a `/changes` from `since` with `maxChanges` `max` goes up
722    /// to: the current state, or an intermediate one.
723    ///
724    /// RFC 8620 §5.2: over maxChanges "the server SHOULD generate an
725    /// update to take the client to an intermediate state", and only
726    /// when "unable to calculate an intermediate state" return
727    /// cannotCalculateChanges. One commit logs all its ids under one
728    /// state, so the intermediate state is the last whose whole commit
729    /// fits, oldest first. Each distinct id is one entry of
730    /// [`Inner::net_changes`].
731    fn changes_upto(
732        &self,
733        type_name: &'static str,
734        account_id: &Id,
735        since: u64,
736        max: u64,
737    ) -> Result<u64, BackendChangesError<MemoryError>> {
738        let mut seen: HashSet<&Id> = HashSet::new();
739        let (mut fits, mut commit) = (since, since);
740        for (s, id, _) in self.log_window(type_name, account_id, since) {
741            if *s != commit {
742                (fits, commit) = (commit, *s);
743            }
744            if seen.insert(id) && seen.len() as u64 > max {
745                if fits == since {
746                    return Err(BackendChangesError::TooManyChanges { limit: max });
747                }
748                return Ok(fits);
749            }
750        }
751        Ok(self.state(type_name, account_id))
752    }
753
754    /// Each id changed after state `since` up to `upto`, once, with its
755    /// net change.
756    ///
757    /// RFC 8620 §5.2: each id appears once, in the bucket of its net
758    /// change since `since_state`. A create followed by an update stays
759    /// created; a later destroy or re-create overrides.
760    fn net_changes(
761        &self,
762        type_name: &'static str,
763        account_id: &Id,
764        since: u64,
765        upto: u64,
766    ) -> Vec<(Id, Change)> {
767        let window = || {
768            self.log_window(type_name, account_id, since)
769                .filter(move |(s, _, _)| *s <= upto)
770        };
771        let mut net: Vec<(Id, Change)> = Vec::new();
772        for (_, id, change) in window() {
773            match net.iter_mut().find(|(seen, _)| seen == id) {
774                Some((_, prev)) if *prev == Change::Created && *change == Change::Updated => {}
775                Some((_, prev)) => *prev = *change,
776                None => net.push((id.clone(), *change)),
777            }
778        }
779        // Object history -04 §5.1: an id restored in the window is
780        // classified by whether it existed at sinceState and exists now,
781        // "exactly as if the object had never been destroyed between them".
782        let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
783        for (_, id, change) in window() {
784            events.entry(id.clone()).or_default().push(match change {
785                Change::Created => ChangeEvent::Created,
786                Change::Updated => ChangeEvent::Updated,
787                Change::Destroyed => ChangeEvent::Destroyed,
788                Change::Restored => ChangeEvent::Restored,
789            });
790        }
791        net.retain_mut(|(id, change)| {
792            let Some(list) = events
793                .get(id)
794                .filter(|l| l.contains(&ChangeEvent::Restored))
795            else {
796                return true;
797            };
798            match fold_restore(list) {
799                Some(ChangeKind::Created) => *change = Change::Created,
800                Some(ChangeKind::Destroyed) => *change = Change::Destroyed,
801                Some(_) => *change = Change::Updated,
802                None => return false,
803            }
804            true
805        });
806        net
807    }
808
809    /// The ids of the `O` objects in `account_id` that `caller` sees and
810    /// that match `filter`, in `sort` order. `filter` and `sort` re-decode
811    /// as the concrete type's once `O::TYPE_NAME` is known.
812    fn query_ids<O: QueryObject>(
813        &self,
814        caller: &str,
815        account_id: &Id,
816        filter: Option<&O::Filter>,
817        sort: &[O::Comparator],
818    ) -> Result<Vec<Id>, BackendQueryError<MemoryError>> {
819        Ok(if O::TYPE_NAME == SceneAsset::TYPE_NAME {
820            let filter: Option<SceneAssetFilter> = filter.map(recode).transpose()?;
821            let sort: Vec<SceneAssetComparator> = recode(&sort)?;
822            sorted_ids(
823                self.all::<SceneAsset>(account_id),
824                |a| filter.as_ref().is_none_or(|f| asset_matches(f, a)),
825                |a, b| compare_assets(a, b, &sort),
826                |a| a.id,
827            )
828        } else if O::TYPE_NAME == SceneRegion::TYPE_NAME {
829            let filter: Option<SceneRegionFilter> = filter.map(recode).transpose()?;
830            let sort: Vec<SceneRegionComparator> = recode(&sort)?;
831            sorted_ids(
832                self.all::<SceneRegion>(account_id),
833                |r| {
834                    self.may_access(caller, account_id, &r.id)
835                        && filter.as_ref().is_none_or(|f| region_matches(f, r))
836                },
837                |a, b| compare_regions(a, b, &sort),
838                |r| r.id,
839            )
840        } else if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
841            let filter: Option<SceneAvatarFilter> = filter.map(recode).transpose()?;
842            let sort: Vec<SceneAvatarComparator> = recode(&sort)?;
843            // §Avatar Visibility: hidden avatars are left out and the
844            // filters and sorts see "the values returned to the caller".
845            let rules = self.avatar_rules.get(account_id.as_ref());
846            sorted_ids(
847                self.all::<SceneAvatar>(account_id)
848                    .filter_map(|a| self.viewed_avatar(caller, account_id, a, rules)),
849                |a| {
850                    self.may_access(caller, account_id, &a.region_id)
851                        && !self
852                            .blocked
853                            .contains(&(caller.to_owned(), a.user_id.clone()))
854                        && !self
855                            .hidden_avatars
856                            .contains(&(caller.to_owned(), a.region_id.clone()))
857                        && filter.as_ref().is_none_or(|f| avatar_matches(f, a))
858                },
859                |a, b| compare_avatars(a, b, &sort),
860                |a| a.id,
861            )
862        } else if O::TYPE_NAME == SceneObject::TYPE_NAME {
863            let filter: Option<SceneObjectFilter> = filter.map(recode).transpose()?;
864            let sort: Vec<SceneObjectComparator> = recode(&sort)?;
865            let all: HashMap<Id, SceneObject> = self
866                .all::<SceneObject>(account_id)
867                .map(|o| (o.id.clone(), o))
868                .collect();
869            sorted_ids(
870                all.values(),
871                |o| {
872                    self.may_access(caller, account_id, &o.region_id)
873                        && !self.hidden.contains(&(caller.to_owned(), o.id.clone()))
874                        && filter.as_ref().is_none_or(|f| {
875                            object_matches(f, o, region_local_position(o, |id| all.get(id)))
876                        })
877                },
878                |a, b| compare_objects(a, b, &sort),
879                |o| o.id.clone(),
880            )
881        } else {
882            return Err(BackendQueryError::Other(MemoryError::new(format!(
883                "query of {} is not implemented",
884                O::TYPE_NAME
885            ))));
886        })
887    }
888}
889
890/// A fully in-memory implementation of [`SceneBackend`].
891///
892/// Cloning is cheap and **shared-state**; see the [`Clone`] impl.
893///
894/// `C` is the [`JmapAccounts::CallerCtx`]: [`Id`], the caller's Principal
895/// id, by default, or `()` for a deployment without identity (see the
896/// module documentation, "Caller context").
897#[non_exhaustive]
898pub struct MemoryBackend<C = Id> {
899    inner: ScopedState<Inner>,
900    caller: PhantomData<fn() -> C>,
901}
902
903/// An empty backend: [`MemoryBackend::new`] for any caller context, such
904/// as `MemoryBackend::<()>::default()` for a deployment without identity.
905impl<C> Default for MemoryBackend<C> {
906    fn default() -> Self {
907        Self {
908            inner: ScopedState::default(),
909            caller: PhantomData,
910        }
911    }
912}
913
914/// Manual `Clone` impl, not `#[derive(Clone)]`: cloning is **shared-state**.
915///
916/// A clone copies no data. The original and the clone hold `Arc::clone`s
917/// of the same [`ScopedState`]-guarded store and observe each other's mutations, so
918/// one handle can seed or inspect state while another serves requests. This
919/// impl must never become a deep copy; for independent state construct a
920/// fresh [`MemoryBackend::new`] instead of calling `.clone()`.
921impl<C> Clone for MemoryBackend<C> {
922    fn clone(&self) -> Self {
923        Self {
924            inner: self.inner.clone(),
925            caller: PhantomData,
926        }
927    }
928}
929
930impl MemoryBackend {
931    /// An empty backend with no accounts, whose callers are Principal ids
932    /// (`C = Id`). Equivalent to [`Self::default`].
933    pub fn new() -> Self {
934        Self::default()
935    }
936}
937
938/// The `userId` `caller` acts as in `account_id`: its Principal id, or, for
939/// a caller without identity, the account id.
940fn acting_user<C: MemoryCaller>(caller: &C, account_id: &Id) -> String {
941    caller.principal().unwrap_or(account_id).as_ref().to_owned()
942}
943
944impl<C: MemoryCaller> MemoryBackend<C> {
945    /// The store, for setup and test helpers, which never run inside a
946    /// conditional Foo/set scope. A poisoned lock is taken anyway.
947    fn lock(&self) -> ScopedGuard<'_, Inner> {
948        self.inner.lock_unscoped()
949    }
950
951    /// The store, for the backend methods: waits while another task's
952    /// conditional Foo/set scope is open (docs/design/conditional.md §7).
953    async fn locked(&self) -> ScopedGuard<'_, Inner> {
954        self.inner.lock().await
955    }
956
957    /// Register `account_id` with the `urn:ietf:params:jmap:scene` account capability object
958    /// it advertises, and return `self` for chaining.
959    ///
960    /// Until an account is registered every method call naming it is
961    /// `accountNotFound` (RFC 8620 §3.6.2). The builder form of
962    /// [`Self::register_account`].
963    ///
964    /// ```
965    /// use jmap_scene_server::memory::MemoryBackend;
966    /// use jmap_server::JmapAccounts;
967    /// use jmap_types::Id;
968    ///
969    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
970    /// let capability = serde_json::from_value(serde_json::json!({
971    ///     "mayCreateRegion": true,
972    ///     "mayCreateObject": true,
973    ///     "supportedVisualTypes": ["model/gltf-binary"],
974    ///     "maxRegionsPerAccount": null,
975    ///     "maxObjectsPerRegion": null,
976    ///     "maxAvatarsPerRegion": null,
977    ///     "maxAssetSizeBytes": null,
978    ///     "supportsSceneAsset": false
979    /// }))?;
980    /// let account = Id::from("a1");
981    /// let backend = MemoryBackend::new().with_account(&account, capability);
982    /// let caller = Id::from("alice");
983    /// tokio::runtime::Runtime::new()?.block_on(async {
984    ///     assert!(backend.account_exists(&caller, &account).await?);
985    ///     assert!(!backend.account_exists(&caller, &Id::from("a2")).await?);
986    ///     Ok(())
987    /// })
988    /// # }
989    /// ```
990    ///
991    /// # Panics
992    ///
993    /// In debug builds, if `account_id` is the empty string (RFC 8620
994    /// §1.2, bd:JMAP-dx0s).
995    #[must_use]
996    pub fn with_account(self, account_id: &Id, capability: SceneCapability) -> Self {
997        self.register_account(account_id, capability);
998        self
999    }
1000
1001    /// Register `account_id` with the `urn:ietf:params:jmap:scene` account capability object
1002    /// it advertises: the `&self` form of [`Self::with_account`], for a
1003    /// backend already shared with a dispatcher.
1004    ///
1005    /// Registering an account again replaces its capability; its objects
1006    /// are kept.
1007    ///
1008    /// # Panics
1009    ///
1010    /// In debug builds, if `account_id` is the empty string (RFC 8620
1011    /// §1.2, bd:JMAP-dx0s).
1012    pub fn register_account(&self, account_id: &Id, capability: SceneCapability) {
1013        debug_assert!(
1014            !account_id.as_ref().is_empty(),
1015            "register_account: account_id must not be the empty string \
1016             (RFC 8620 §1.2, bd:JMAP-dx0s)"
1017        );
1018        self.lock()
1019            .accounts
1020            .insert(account_id.as_ref().to_owned(), capability);
1021    }
1022
1023    /// Record an uploaded blob `blob_id` of `size` bytes in `account_id`.
1024    #[doc(hidden)]
1025    pub fn add_blob(&self, account_id: &Id, blob_id: &str, size: u64) {
1026        self.lock()
1027            .blobs
1028            .insert((account_id.as_ref().to_owned(), blob_id.to_owned()), size);
1029    }
1030
1031    /// Limit the total `size` of `account_id`'s SceneAssets to `bytes`.
1032    #[doc(hidden)]
1033    pub fn set_storage_quota(&self, account_id: &Id, bytes: u64) {
1034        self.lock()
1035            .storage_quota
1036            .insert(account_id.as_ref().to_owned(), bytes);
1037    }
1038
1039    /// Give `user` admin privileges, recounting the `observerCount` of the
1040    /// observed regions, since an admin has access to every region.
1041    #[doc(hidden)]
1042    pub fn add_admin(&self, user: &str) {
1043        let mut inner = self.lock();
1044        inner.admins.insert(user.to_owned());
1045        inner.recount_observed(None);
1046    }
1047
1048    /// Advertise the companion capability `uri` (e.g.
1049    /// `urn:ietf:params:jmap:chat`) on `account_id`, so
1050    /// [`SceneBackend::has_capability`] answers `true` for it. List the
1051    /// same capability in the account's Session `accountCapabilities`.
1052    pub fn advertise(&self, account_id: &Id, uri: &str) {
1053        self.lock()
1054            .capabilities
1055            .entry(account_id.as_ref().to_owned())
1056            .or_default()
1057            .insert(uri.to_owned());
1058    }
1059
1060    /// Record that binding `property` set to `id` references `target`.
1061    #[doc(hidden)]
1062    pub fn set_region_binding(&self, property: BindingProperty, id: &str, target: BindingTarget) {
1063        self.lock()
1064            .bindings
1065            .insert((property, id.to_owned()), target);
1066    }
1067
1068    /// Record that channel `channel_id` is a channel of Space `space_id`.
1069    #[doc(hidden)]
1070    pub fn set_channel_space(&self, channel_id: &str, space_id: &str) {
1071        self.lock()
1072            .channel_spaces
1073            .insert((channel_id.to_owned(), space_id.to_owned()));
1074    }
1075
1076    /// Give `user` access to the `"invite"` region `region_id`, recounting
1077    /// its `observerCount`.
1078    #[doc(hidden)]
1079    pub fn grant_region_access(&self, region_id: &str, user: &str) {
1080        let mut inner = self.lock();
1081        inner.grants.insert((region_id.to_owned(), user.to_owned()));
1082        inner.recount_observed(Some(&Id::from(region_id)));
1083    }
1084
1085    /// Withdraw the access [`Self::grant_region_access`] gave `user` to
1086    /// region `region_id`, recounting its `observerCount`.
1087    #[doc(hidden)]
1088    pub fn revoke_region_access(&self, region_id: &str, user: &str) {
1089        let mut inner = self.lock();
1090        inner
1091            .grants
1092            .remove(&(region_id.to_owned(), user.to_owned()));
1093        inner.recount_observed(Some(&Id::from(region_id)));
1094    }
1095
1096    /// Bar `user` from entering region `region_id`, for
1097    /// [`SceneBackend::may_enter_region`].
1098    #[doc(hidden)]
1099    pub fn ban_from_region(&self, region_id: &str, user: &str) {
1100        self.lock()
1101            .bans
1102            .insert((region_id.to_owned(), user.to_owned()));
1103    }
1104
1105    /// Take object `object_id` out of `user`'s visibility set, for
1106    /// [`SceneBackend::is_object_visible`].
1107    #[doc(hidden)]
1108    pub fn hide_object(&self, user: &str, object_id: &str) {
1109        self.lock()
1110            .hidden
1111            .insert((user.to_owned(), Id::from(object_id)));
1112    }
1113
1114    /// Make `user` blocked by `blocker`, for
1115    /// [`SceneBackend::is_user_blocked`].
1116    #[doc(hidden)]
1117    pub fn block(&self, blocker: &str, user: &str) {
1118        self.lock()
1119            .blocked
1120            .insert((blocker.to_owned(), user.to_owned()));
1121    }
1122
1123    /// Hide the avatars of region `region_id` from `user`, for
1124    /// [`SceneBackend::may_see_region_avatars`].
1125    #[doc(hidden)]
1126    pub fn hide_region_avatars(&self, user: &str, region_id: &str) {
1127        self.lock()
1128            .hidden_avatars
1129            .insert((user.to_owned(), Id::from(region_id)));
1130    }
1131
1132    /// Advertise (`true`) or withdraw `supportsObserve`, for
1133    /// [`SceneBackend::supports_observe`]. List the same value in the
1134    /// Session's `urn:ietf:params:jmap:scene:websocket` capability.
1135    pub fn set_supports_observe(&self, on: bool) {
1136        self.lock().supports_observe = on;
1137    }
1138
1139    /// Decline observers of region `region_id` by policy, for
1140    /// [`SceneBackend::may_observe_region`], recounting its
1141    /// `observerCount` (to `0`).
1142    #[doc(hidden)]
1143    pub fn decline_observers(&self, region_id: &str) {
1144        let mut inner = self.lock();
1145        inner.declined_observers.insert(Id::from(region_id));
1146        inner.recount_observed(Some(&Id::from(region_id)));
1147    }
1148
1149    /// Undo [`Self::decline_observers`] for region `region_id`,
1150    /// recounting its `observerCount`.
1151    #[doc(hidden)]
1152    pub fn admit_observers(&self, region_id: &str) {
1153        let mut inner = self.lock();
1154        inner.declined_observers.remove(&Id::from(region_id));
1155        inner.recount_observed(Some(&Id::from(region_id)));
1156    }
1157
1158    /// Make [`SceneBackend::observer_accounts`] answer `accounts` instead
1159    /// of every registered account, as a deployment that checks only
1160    /// some of the accounts a user can access would.
1161    #[doc(hidden)]
1162    pub fn restrict_observer_accounts(&self, accounts: &[&str]) {
1163        self.lock().observer_accounts = Some(accounts.iter().map(|a| Id::from(*a)).collect());
1164    }
1165
1166    /// Hide avatar `avatar_id` of `account_id` from `viewer`, for
1167    /// [`SceneBackend::avatar_view`], and advance the account's
1168    /// SceneAvatar state.
1169    #[doc(hidden)]
1170    pub fn hide_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
1171        let key = (viewer.to_owned(), Id::from(avatar_id));
1172        self.lock().change_avatar_rules(account_id, |rules| {
1173            rules.withheld.remove(&key);
1174            rules.hidden.insert(key);
1175        });
1176    }
1177
1178    /// Withhold the properties of `redaction` of avatar `avatar_id` of
1179    /// `account_id` from `viewer`, for [`SceneBackend::avatar_view`], and
1180    /// advance the account's SceneAvatar state.
1181    #[doc(hidden)]
1182    pub fn withhold_avatar(
1183        &self,
1184        account_id: &Id,
1185        viewer: &str,
1186        avatar_id: &str,
1187        redaction: AvatarRedaction,
1188    ) {
1189        let key = (viewer.to_owned(), Id::from(avatar_id));
1190        self.lock().change_avatar_rules(account_id, |rules| {
1191            rules.hidden.remove(&key);
1192            rules.withheld.insert(key, redaction);
1193        });
1194    }
1195
1196    /// Show avatar `avatar_id` of `account_id` to `viewer` in full again,
1197    /// and advance the account's SceneAvatar state.
1198    #[doc(hidden)]
1199    pub fn reveal_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
1200        let key = (viewer.to_owned(), Id::from(avatar_id));
1201        self.lock().change_avatar_rules(account_id, |rules| {
1202            rules.hidden.remove(&key);
1203            rules.withheld.remove(&key);
1204        });
1205    }
1206
1207    /// Refuse every interaction of `user` as over the rate, for
1208    /// [`SceneBackend::accept_interaction`].
1209    #[doc(hidden)]
1210    pub fn rate_limit_interactions(&self, user: &str) {
1211        self.lock().rate_limited.insert(user.to_owned());
1212    }
1213
1214    /// The interactions [`SceneBackend::accept_interaction`] accepted, in
1215    /// order: what a WebSocket transport would deliver.
1216    #[doc(hidden)]
1217    pub fn accepted_interactions(&self) -> Vec<SceneInteractionEvent> {
1218        self.lock().interactions.clone()
1219    }
1220
1221    /// Refuse every region event `user` broadcasts as over the rate, for
1222    /// [`SceneBackend::accept_region_event`].
1223    #[doc(hidden)]
1224    pub fn rate_limit_region_events(&self, user: &str) {
1225        self.lock().region_event_limited.insert(user.to_owned());
1226    }
1227
1228    /// The region events [`SceneBackend::accept_region_event`] accepted,
1229    /// in order: what a WebSocket transport would deliver.
1230    #[doc(hidden)]
1231    pub fn accepted_region_events(&self) -> Vec<SceneRegionEvent> {
1232        self.lock().region_events.clone()
1233    }
1234
1235    /// Reserve avatar display name `name`, for
1236    /// [`SceneBackend::reserved_display_names`].
1237    #[doc(hidden)]
1238    pub fn reserve_display_name(&self, name: &str) {
1239        self.lock().reserved_names.push(name.to_owned());
1240    }
1241
1242    /// Store `value` as object `id` of `type_name` without validation or a
1243    /// state change, to seed states the methods cannot reach.
1244    #[doc(hidden)]
1245    #[cfg(feature = "test-helpers")]
1246    pub fn insert_object_for_test(
1247        &self,
1248        type_name: &'static str,
1249        account_id: &Id,
1250        id: &str,
1251        value: Value,
1252    ) {
1253        self.lock()
1254            .objects_mut(type_name, account_id)
1255            .insert(Id::from(id), value);
1256    }
1257}
1258
1259/// Opaque storage-layer error returned by [`MemoryBackend`].
1260#[non_exhaustive]
1261#[derive(Debug)]
1262pub struct MemoryError {
1263    description: String,
1264}
1265
1266impl MemoryError {
1267    /// A [`MemoryError`] with a human-readable description.
1268    pub fn new(description: impl Into<String>) -> Self {
1269        Self {
1270            description: description.into(),
1271        }
1272    }
1273
1274    /// Human-readable description of the failure.
1275    pub fn description(&self) -> &str {
1276        &self.description
1277    }
1278
1279    /// Construct a [`MemoryError`] for a `serde_json` failure during
1280    /// `context` (the operation that failed).
1281    ///
1282    /// Only the error's [`serde_json::error::Category`] is kept. A serde
1283    /// data error quotes the offending value (`invalid type: string
1284    /// "alice@example.com", expected u64`), and the `JmapAccounts::Error`
1285    /// contract forbids PII and blob content in `Display` output
1286    /// (bd:JMAP-510h.37).
1287    pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
1288        Self::new(format!("{context}: serde_json {:?} error", e.classify()))
1289    }
1290}
1291
1292impl std::fmt::Display for MemoryError {
1293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1294        write!(f, "MemoryBackend error: {}", self.description)
1295    }
1296}
1297
1298impl std::error::Error for MemoryError {}
1299
1300fn not_found<E>() -> BackendSetError<E> {
1301    BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
1302}
1303
1304fn decode<O: JmapObject>(v: &Value) -> Result<O, MemoryError> {
1305    O::deserialize(v).map_err(|e| MemoryError::serde(format_args!("decode {}", O::TYPE_NAME), &e))
1306}
1307
1308fn recode_as<T: DeserializeOwned>(v: &Value) -> Result<T, BackendQueryError<MemoryError>> {
1309    T::deserialize(v)
1310        .map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))
1311}
1312
1313/// Re-decode `v`, a value of a generic `QueryObject` associated type, as
1314/// the concrete type `T` it is once `O::TYPE_NAME` is known.
1315fn recode<T: DeserializeOwned>(v: &impl Serialize) -> Result<T, BackendQueryError<MemoryError>> {
1316    let v = serde_json::to_value(v)
1317        .map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))?;
1318    recode_as(&v)
1319}
1320
1321/// The ids of `list` that `keep` accepts, ordered by `cmp`.
1322fn sorted_ids<T>(
1323    list: impl Iterator<Item = T>,
1324    keep: impl Fn(&T) -> bool,
1325    cmp: impl Fn(&T, &T) -> std::cmp::Ordering,
1326    id: impl Fn(T) -> Id,
1327) -> Vec<Id> {
1328    let mut list: Vec<T> = list.filter(|t| keep(t)).collect();
1329    list.sort_by(|a, b| cmp(a, b));
1330    list.into_iter().map(id).collect()
1331}
1332
1333impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
1334    type Error = MemoryError;
1335    type CallerCtx = C;
1336
1337    /// [`MemoryCaller::principal`].
1338    fn principal_id(caller: &C) -> Option<&Id> {
1339        caller.principal()
1340    }
1341
1342    async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, MemoryError> {
1343        Ok(self
1344            .locked()
1345            .await
1346            .accounts
1347            .contains_key(account_id.as_ref()))
1348    }
1349}
1350
1351impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
1352    async fn get_objects<O: GetObject + Send + Sync>(
1353        &self,
1354        _caller: &C,
1355        account_id: &Id,
1356        ids: Option<&[Id]>,
1357        _properties: Option<&[String]>,
1358    ) -> Result<(Vec<O>, Vec<Id>), MemoryError> {
1359        let inner = self.locked().await;
1360        let map = inner.objects(O::TYPE_NAME, account_id);
1361        match ids {
1362            None => {
1363                let list = map
1364                    .into_iter()
1365                    .flat_map(HashMap::values)
1366                    .map(decode)
1367                    .collect::<Result<_, _>>()?;
1368                Ok((list, Vec::new()))
1369            }
1370            Some(ids) => {
1371                let mut found = Vec::new();
1372                let mut missing = Vec::new();
1373                for id in ids {
1374                    match map.and_then(|m| m.get(id)) {
1375                        Some(v) => found.push(decode(v)?),
1376                        None => missing.push(id.clone()),
1377                    }
1378                }
1379                Ok((found, missing))
1380            }
1381        }
1382    }
1383
1384    async fn get_state<O: JmapObject + Send + Sync>(
1385        &self,
1386        _caller: &C,
1387        account_id: &Id,
1388    ) -> Result<State, MemoryError> {
1389        Ok(State::from(
1390            self.locked()
1391                .await
1392                .state(O::TYPE_NAME, account_id)
1393                .to_string(),
1394        ))
1395    }
1396
1397    async fn get_changes<O: JmapObject + Send + Sync>(
1398        &self,
1399        caller: &C,
1400        account_id: &Id,
1401        params: jmap_server::ChangesParams<'_>,
1402    ) -> Result<ChangesResult, BackendChangesError<MemoryError>> {
1403        let viewer = acting_user(caller, account_id);
1404        let since_state = params.since_state;
1405        let max_changes = params.max_changes;
1406        let inner = self.locked().await;
1407        let since: u64 = since_state
1408            .as_ref()
1409            .parse()
1410            .map_err(|_| BackendChangesError::CannotCalculate)?;
1411        let current = inner.state(O::TYPE_NAME, account_id);
1412        if since > current {
1413            return Err(BackendChangesError::CannotCalculate);
1414        }
1415        // §Avatar Visibility: once the account has avatar rules, answer
1416        // from the caller's view; a state before the first rule cannot be
1417        // calculated.
1418        if O::TYPE_NAME == SceneAvatar::TYPE_NAME
1419            && inner.avatar_rules.contains_key(account_id.as_ref())
1420        {
1421            return inner
1422                .avatar_changes_for(&viewer, account_id, since, max_changes)
1423                .unwrap_or(Err(BackendChangesError::CannotCalculate));
1424        }
1425
1426        let upto = match max_changes {
1427            Some(max) => inner.changes_upto(O::TYPE_NAME, account_id, since, max)?,
1428            None => current,
1429        };
1430        let net = inner.net_changes(O::TYPE_NAME, account_id, since, upto);
1431        let bucket = |want: Change| -> Vec<Id> {
1432            net.iter()
1433                .filter(|(_, c)| *c == want)
1434                .map(|(id, _)| id.clone())
1435                .collect()
1436        };
1437        Ok(ChangesResult::new(
1438            bucket(Change::Created),
1439            bucket(Change::Updated),
1440            bucket(Change::Destroyed),
1441            upto < current,
1442            State::from(upto.to_string()),
1443        ))
1444    }
1445
1446    async fn query_objects<O: QueryObject + Send + Sync>(
1447        &self,
1448        caller: &C,
1449        account_id: &Id,
1450        params: QueryParams<'_, O>,
1451    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
1452        let caller = &acting_user(caller, account_id);
1453        let QueryParams {
1454            filter,
1455            sort,
1456            limit,
1457            position,
1458            anchor,
1459            anchor_offset,
1460            ..
1461        } = params;
1462        let sort = sort.unwrap_or_default();
1463        let inner = self.locked().await;
1464        let ids = inner.query_ids::<O>(caller, account_id, filter, sort)?;
1465
1466        let total = ids.len() as u64;
1467        let start = resolve_query_start(&ids, position, anchor, anchor_offset)
1468            .map_err(BackendQueryError::Method)?;
1469        let page = ids
1470            .into_iter()
1471            .skip(start)
1472            .take(limit_or_max(limit))
1473            .collect();
1474        Ok(QueryResult::new(
1475            page,
1476            start as u64,
1477            Some(total),
1478            State::from(inner.state(O::TYPE_NAME, account_id).to_string()),
1479            false,
1480        ))
1481    }
1482
1483    async fn query_changes<O: QueryObject + Send + Sync>(
1484        &self,
1485        _caller: &C,
1486        _account_id: &Id,
1487        _params: QueryChangesParams<'_, O>,
1488    ) -> Result<QueryChangesResult, BackendChangesError<MemoryError>> {
1489        Err(BackendChangesError::CannotCalculate)
1490    }
1491}
1492
1493impl<C: MemoryCaller> SceneBackend for MemoryBackend<C> {
1494    async fn scene_capability(
1495        &self,
1496        _caller: &C,
1497        account_id: &Id,
1498    ) -> Result<SceneCapability, MemoryError> {
1499        self.locked()
1500            .await
1501            .accounts
1502            .get(account_id.as_ref())
1503            .cloned()
1504            .ok_or_else(|| MemoryError::new("account not registered"))
1505    }
1506
1507    async fn blob_size(
1508        &self,
1509        _caller: &C,
1510        account_id: &Id,
1511        blob_id: &Id,
1512    ) -> Result<Option<u64>, MemoryError> {
1513        Ok(self
1514            .lock()
1515            .blobs
1516            .get(&(account_id.as_ref().to_owned(), blob_id.as_ref().to_owned()))
1517            .copied())
1518    }
1519
1520    async fn create_object<O, F>(
1521        &self,
1522        caller: &C,
1523        account_id: &Id,
1524        _create_id: &str,
1525        build: F,
1526    ) -> Result<(Id, O), BackendSetError<MemoryError>>
1527    where
1528        O: SetObject + Send + Sync,
1529        F: FnOnce(&Id) -> O + Send,
1530    {
1531        let caller = &acting_user(caller, account_id);
1532        let id = Id::from(ulid::Ulid::new().to_string());
1533        let mut value = serde_json::to_value(build(&id)).map_err(|e| {
1534            BackendSetError::Other(MemoryError::serde("serialize created object", &e))
1535        })?;
1536        let mut inner = self.locked().await;
1537        if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
1538            let avatar: SceneAvatar = decode(&value).map_err(BackendSetError::Other)?;
1539            let stored = inner.enter(account_id, avatar, self.inner.deferring())?;
1540            return Ok((id, decode(&stored).map_err(BackendSetError::Other)?));
1541        }
1542        // "Account asset storage quota exceeded", checked under the lock.
1543        if O::TYPE_NAME == SceneAsset::TYPE_NAME
1544            && let Some(&quota) = inner.storage_quota.get(account_id.as_ref())
1545        {
1546            let used: u64 = inner.all::<SceneAsset>(account_id).map(|a| a.size).sum();
1547            let size = value.get("size").and_then(Value::as_u64).unwrap_or(0);
1548            if used.saturating_add(size) > quota {
1549                return Err(BackendSetError::SetError(Box::new(
1550                    SetError::new(SetErrorType::OverQuota)
1551                        .with_description("account asset storage quota exceeded"),
1552                )));
1553            }
1554        }
1555        // "`overQuota` when `maxRegionsPerAccount` would be exceeded",
1556        // counted under the lock.
1557        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
1558            let max = inner
1559                .accounts
1560                .get(account_id.as_ref())
1561                .and_then(|c| c.max_regions_per_account);
1562            let held = inner.all::<SceneRegion>(account_id).count() as u64;
1563            if max.is_some_and(|max| held >= max) {
1564                return Err(BackendSetError::SetError(Box::new(
1565                    SetError::new(SetErrorType::OverQuota)
1566                        .with_description("maxRegionsPerAccount reached"),
1567                )));
1568            }
1569        }
1570        // "`overQuota` when `maxObjectsPerRegion` would be exceeded",
1571        // counted under the lock; "The userId of the user who created this
1572        // object".
1573        if O::TYPE_NAME == SceneObject::TYPE_NAME {
1574            let max = inner
1575                .accounts
1576                .get(account_id.as_ref())
1577                .and_then(|c| c.max_objects_per_region);
1578            let region = value.get("regionId").and_then(Value::as_str);
1579            let held = inner
1580                .all::<SceneObject>(account_id)
1581                .filter(|o| Some(o.region_id.as_ref()) == region)
1582                .count() as u64;
1583            if max.is_some_and(|max| held >= max) {
1584                return Err(BackendSetError::SetError(Box::new(
1585                    SetError::new(SetErrorType::OverQuota)
1586                        .with_description("maxObjectsPerRegion reached"),
1587                )));
1588            }
1589            value["ownerId"] = json!(caller);
1590        }
1591        let stored: O = decode(&value).map_err(BackendSetError::Other)?;
1592        inner
1593            .objects_mut(O::TYPE_NAME, account_id)
1594            .insert(id.clone(), value);
1595        inner.commit(
1596            O::TYPE_NAME,
1597            account_id,
1598            vec![(id.clone(), Change::Created)],
1599        );
1600        Ok((id, stored))
1601    }
1602
1603    async fn update_object<O: SetObject + Send + Sync>(
1604        &self,
1605        _caller: &C,
1606        account_id: &Id,
1607        id: &Id,
1608        patch: O::Patch,
1609    ) -> Result<Option<O>, BackendSetError<MemoryError>> {
1610        let mut inner = self.locked().await;
1611        let mut current = inner
1612            .objects(O::TYPE_NAME, account_id)
1613            .and_then(|m| m.get(id))
1614            .cloned()
1615            .ok_or_else(not_found)?;
1616
1617        let was_left = current.get("leftAt").is_some_and(|l| !l.is_null());
1618        let patch = serde_json::to_value(&patch)
1619            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
1620        let (Value::Object(patch), Value::Object(base)) = (patch, &mut current) else {
1621            return Err(BackendSetError::SetError(Box::new(SetError::new(
1622                SetErrorType::InvalidPatch,
1623            ))));
1624        };
1625        apply_patch_object(base, &patch).map_err(|e| {
1626            BackendSetError::SetError(Box::new(
1627                SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
1628            ))
1629        })?;
1630        if O::deserialize(&current).is_err() {
1631            return Err(BackendSetError::SetError(Box::new(
1632                SetError::new(SetErrorType::InvalidProperties)
1633                    .with_description(format!("patched {} is invalid", O::TYPE_NAME)),
1634            )));
1635        }
1636        let mut changes = Vec::new();
1637        let mut regions = Vec::new();
1638        let left_to = patch
1639            .get("leftAt")
1640            .filter(|_| O::TYPE_NAME == SceneAvatar::TYPE_NAME);
1641        if let Some(to) = left_to {
1642            // Leave and re-entry preconditions, re-checked under the lock.
1643            let refuse = |description: &str| {
1644                BackendSetError::SetError(Box::new(
1645                    SetError::new(SetErrorType::InvalidProperties)
1646                        .with_description(description)
1647                        .with_properties(["leftAt"]),
1648                ))
1649            };
1650            match (to.is_null(), was_left) {
1651                (false, true) => return Err(refuse("the avatar has already left")),
1652                (true, false) => return Err(refuse("the avatar is present")),
1653                (true, true) => {
1654                    let avatar: SceneAvatar = decode(&current).map_err(BackendSetError::Other)?;
1655                    (changes, regions) =
1656                        inner.admit(account_id, &avatar, self.inner.deferring())?;
1657                }
1658                (false, false) => {}
1659            }
1660            regions.extend(
1661                current
1662                    .get("regionId")
1663                    .and_then(Value::as_str)
1664                    .map(Id::from),
1665            );
1666        }
1667        if let Some(previous) = inner.current(O::TYPE_NAME, account_id, id).cloned() {
1668            inner.record_replace(O::TYPE_NAME, account_id, id, previous);
1669        }
1670        inner
1671            .objects_mut(O::TYPE_NAME, account_id)
1672            .insert(id.clone(), current);
1673        changes.push((id.clone(), Change::Updated));
1674        inner.commit(O::TYPE_NAME, account_id, changes);
1675        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
1676            // `allowObservers` or the access rules may have changed who
1677            // counts as an observer; a changed `observerCount` is "changed
1678            // in a way not explicitly requested", so the region is echoed.
1679            let before = inner.region(account_id, id).and_then(|r| r.observer_count);
1680            inner.recount(account_id, std::slice::from_ref(id));
1681            if let Some(after) = inner
1682                .objects(O::TYPE_NAME, account_id)
1683                .and_then(|m| m.get(id))
1684                && after.get("observerCount").and_then(Value::as_u64) != before
1685            {
1686                return Ok(Some(decode::<O>(after).map_err(BackendSetError::Other)?));
1687            }
1688        }
1689        inner.recount(account_id, &regions);
1690        Ok(None)
1691    }
1692
1693    async fn destroy_object<O: SetObject + Send + Sync>(
1694        &self,
1695        _caller: &C,
1696        account_id: &Id,
1697        id: &Id,
1698    ) -> Result<(), BackendSetError<MemoryError>> {
1699        let mut inner = self.locked().await;
1700        let map = inner.objects_mut(O::TYPE_NAME, account_id);
1701        if !map.contains_key(id) {
1702            return Err(not_found());
1703        }
1704        // "removes the SceneObject and all its children (objects whose
1705        // `parentId` references this object, recursively)".
1706        let mut gone = vec![id.clone()];
1707        if O::TYPE_NAME == SceneObject::TYPE_NAME {
1708            let mut i = 0;
1709            while let Some(parent) = gone.get(i).cloned() {
1710                let children: Vec<Id> = map
1711                    .iter()
1712                    .filter(|(k, v)| {
1713                        v.get("parentId").and_then(Value::as_str) == Some(parent.as_ref())
1714                            && !gone.contains(k)
1715                    })
1716                    .map(|(k, _)| k.clone())
1717                    .collect();
1718                gone.extend(children);
1719                i += 1;
1720            }
1721        }
1722        let removed: Vec<(Id, Value)> = gone
1723            .iter()
1724            .filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
1725            .collect();
1726        for (k, v) in removed {
1727            inner.record_destroy(O::TYPE_NAME, account_id, &k, v);
1728        }
1729        inner.commit(
1730            O::TYPE_NAME,
1731            account_id,
1732            gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
1733        );
1734        // "removes the SceneRegion and all SceneObject and SceneAvatar
1735        // records in it", each reported destroyed, in the same locked step.
1736        if O::TYPE_NAME == SceneRegion::TYPE_NAME {
1737            for contained in [SceneObject::TYPE_NAME, SceneAvatar::TYPE_NAME] {
1738                let map = inner.objects_mut(contained, account_id);
1739                let gone: Vec<Id> = map
1740                    .iter()
1741                    .filter(|(_, v)| v.get("regionId").and_then(Value::as_str) == Some(id.as_ref()))
1742                    .map(|(k, _)| k.clone())
1743                    .collect();
1744                if gone.is_empty() {
1745                    continue;
1746                }
1747                let removed: Vec<(Id, Value)> = gone
1748                    .iter()
1749                    .filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
1750                    .collect();
1751                for (k, v) in removed {
1752                    inner.record_destroy(contained, account_id, &k, v);
1753                }
1754                inner.commit(
1755                    contained,
1756                    account_id,
1757                    gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
1758                );
1759            }
1760        }
1761        Ok(())
1762    }
1763
1764    async fn may_modify_asset(
1765        &self,
1766        caller: &C,
1767        _account_id: &Id,
1768        asset: &SceneAsset,
1769    ) -> Result<bool, MemoryError> {
1770        let caller = &acting_user(caller, _account_id);
1771        // "Only the asset owner or an admin may modify asset metadata."
1772        Ok(asset.owner_id == *caller || self.locked().await.admins.contains(caller))
1773    }
1774
1775    fn has_capability(&self, _caller: &C, account_id: &Id, uri: &str) -> bool {
1776        self.lock()
1777            .capabilities
1778            .get(account_id.as_ref())
1779            .is_some_and(|c| c.contains(uri))
1780    }
1781
1782    async fn region_binding(
1783        &self,
1784        _caller: &C,
1785        _account_id: &Id,
1786        property: BindingProperty,
1787        id: &Id,
1788    ) -> Result<BindingTarget, MemoryError> {
1789        Ok(self
1790            .lock()
1791            .bindings
1792            .get(&(property, id.as_ref().to_owned()))
1793            .copied()
1794            .unwrap_or(BindingTarget::Missing))
1795    }
1796
1797    async fn channel_in_space(
1798        &self,
1799        _caller: &C,
1800        _account_id: &Id,
1801        channel_id: &Id,
1802        space_id: &Id,
1803    ) -> Result<bool, MemoryError> {
1804        Ok(self
1805            .lock()
1806            .channel_spaces
1807            .contains(&(channel_id.as_ref().to_owned(), space_id.as_ref().to_owned())))
1808    }
1809
1810    async fn may_update_region(
1811        &self,
1812        caller: &C,
1813        _account_id: &Id,
1814        region: &SceneRegion,
1815    ) -> Result<bool, MemoryError> {
1816        let caller = &acting_user(caller, _account_id);
1817        // "Only the owner or an admin may modify region properties."
1818        Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
1819    }
1820
1821    async fn may_destroy_region(
1822        &self,
1823        caller: &C,
1824        _account_id: &Id,
1825        region: &SceneRegion,
1826    ) -> Result<bool, MemoryError> {
1827        let caller = &acting_user(caller, _account_id);
1828        // "Only the region owner or an admin may destroy a region."
1829        Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
1830    }
1831
1832    async fn may_modify_object(
1833        &self,
1834        caller: &C,
1835        account_id: &Id,
1836        object: &SceneObject,
1837    ) -> Result<bool, MemoryError> {
1838        let caller = &acting_user(caller, account_id);
1839        // "Only the object's `ownerId`, the region owner, or a
1840        // deployment-admin may modify another user's object."
1841        let inner = self.locked().await;
1842        Ok(inner.admins.contains(caller)
1843            || object.owner_id.as_ref() == Some(caller)
1844            || inner.owns_region(caller, account_id, &object.region_id))
1845    }
1846
1847    async fn caller_user_id(&self, caller: &C, _account_id: &Id) -> Result<String, MemoryError> {
1848        let caller = &acting_user(caller, _account_id);
1849        Ok(caller.clone())
1850    }
1851
1852    async fn may_enter_region(
1853        &self,
1854        caller: &C,
1855        _account_id: &Id,
1856        region: &SceneRegion,
1857    ) -> Result<bool, MemoryError> {
1858        let caller = &acting_user(caller, _account_id);
1859        Ok(!self
1860            .lock()
1861            .bans
1862            .contains(&(region.id.as_ref().to_owned(), caller.clone())))
1863    }
1864
1865    async fn may_access_region(
1866        &self,
1867        caller: &C,
1868        account_id: &Id,
1869        region_id: &Id,
1870    ) -> Result<bool, MemoryError> {
1871        let caller = &acting_user(caller, account_id);
1872        Ok(self
1873            .locked()
1874            .await
1875            .may_access(caller, account_id, region_id))
1876    }
1877
1878    async fn is_object_visible(
1879        &self,
1880        caller: &C,
1881        _account_id: &Id,
1882        object: &SceneObject,
1883    ) -> Result<bool, MemoryError> {
1884        let caller = &acting_user(caller, _account_id);
1885        Ok(!self
1886            .lock()
1887            .hidden
1888            .contains(&(caller.clone(), object.id.clone())))
1889    }
1890
1891    async fn is_user_blocked(&self, caller: &C, user_id: &str) -> Result<bool, MemoryError> {
1892        // A caller without identity has blocked no one.
1893        let Some(caller) = caller.principal() else {
1894            return Ok(false);
1895        };
1896        Ok(self
1897            .lock()
1898            .blocked
1899            .contains(&(caller.as_ref().to_owned(), user_id.to_owned())))
1900    }
1901
1902    async fn may_see_region_avatars(
1903        &self,
1904        caller: &C,
1905        _account_id: &Id,
1906        region_id: &Id,
1907    ) -> Result<bool, MemoryError> {
1908        let caller = &acting_user(caller, _account_id);
1909        Ok(!self
1910            .lock()
1911            .hidden_avatars
1912            .contains(&(caller.clone(), region_id.clone())))
1913    }
1914
1915    async fn avatar_view(
1916        &self,
1917        caller: &C,
1918        account_id: &Id,
1919        avatar: &SceneAvatar,
1920    ) -> Result<AvatarView, MemoryError> {
1921        let viewer = acting_user(caller, account_id);
1922        let inner = self.locked().await;
1923        let rules = inner.avatar_rules.get(account_id.as_ref());
1924        Ok(inner.avatar_view(&viewer, account_id, avatar, rules))
1925    }
1926
1927    fn supports_observe(&self, _caller: &C) -> bool {
1928        self.lock().supports_observe
1929    }
1930
1931    async fn may_observe_region(
1932        &self,
1933        _caller: &C,
1934        _account_id: &Id,
1935        region: &SceneRegion,
1936    ) -> Result<bool, MemoryError> {
1937        Ok(!self.locked().await.declined_observers.contains(&region.id))
1938    }
1939
1940    /// Every registered account, in id order: access to each region is
1941    /// checked separately.
1942    async fn observer_accounts(&self, _caller: &C, _own: &Id) -> Result<Vec<Id>, MemoryError> {
1943        let inner = self.locked().await;
1944        if let Some(accounts) = &inner.observer_accounts {
1945            return Ok(accounts.clone());
1946        }
1947        let mut accounts: Vec<Id> = inner
1948            .accounts
1949            .keys()
1950            .map(|a| Id::from(a.as_str()))
1951            .collect();
1952        accounts.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
1953        Ok(accounts)
1954    }
1955
1956    async fn set_observing(
1957        &self,
1958        caller: &C,
1959        account_id: &Id,
1960        region_id: &Id,
1961        observing: bool,
1962    ) -> Result<(), MemoryError> {
1963        let user = acting_user(caller, account_id);
1964        let mut inner = self.locked().await;
1965        let key = (account_id.as_ref().to_owned(), region_id.clone());
1966        let users = inner.observers.entry(key.clone()).or_default();
1967        let n = users.entry(user.clone()).or_insert(0);
1968        if observing {
1969            *n += 1;
1970        } else {
1971            *n = n.saturating_sub(1);
1972            if *n == 0 {
1973                users.remove(&user);
1974            }
1975        }
1976        if users.is_empty() {
1977            inner.observers.remove(&key);
1978        }
1979        inner.recount(account_id, std::slice::from_ref(region_id));
1980        Ok(())
1981    }
1982
1983    async fn reserved_display_names(
1984        &self,
1985        _caller: &C,
1986        _account_id: &Id,
1987    ) -> Result<Vec<String>, MemoryError> {
1988        Ok(self.locked().await.reserved_names.clone())
1989    }
1990
1991    async fn may_eject_avatar(
1992        &self,
1993        caller: &C,
1994        account_id: &Id,
1995        avatar: &SceneAvatar,
1996    ) -> Result<bool, MemoryError> {
1997        let caller = &acting_user(caller, account_id);
1998        // "Region owners and administrators MAY eject avatars".
1999        let inner = self.locked().await;
2000        Ok(inner.admins.contains(caller)
2001            || inner.owns_region(caller, account_id, &avatar.region_id))
2002    }
2003
2004    async fn accept_interaction(
2005        &self,
2006        _caller: &C,
2007        _account_id: &Id,
2008        event: &SceneInteractionEvent,
2009    ) -> Result<bool, MemoryError> {
2010        let mut inner = self.locked().await;
2011        if inner.rate_limited.contains(&event.user_id) {
2012            return Ok(false);
2013        }
2014        inner.interactions.push(event.clone());
2015        Ok(true)
2016    }
2017
2018    async fn accept_region_event(
2019        &self,
2020        caller: &C,
2021        account_id: &Id,
2022        event: &SceneRegionEvent,
2023    ) -> Result<bool, MemoryError> {
2024        let caller = acting_user(caller, account_id);
2025        let mut inner = self.locked().await;
2026        if inner.region_event_limited.contains(&caller) {
2027            return Ok(false);
2028        }
2029        inner.region_events.push(event.clone());
2030        Ok(true)
2031    }
2032
2033    fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &Id) -> bool {
2034        [
2035            SceneAsset::TYPE_NAME,
2036            SceneRegion::TYPE_NAME,
2037            SceneObject::TYPE_NAME,
2038            SceneAvatar::TYPE_NAME,
2039        ]
2040        .contains(&O::TYPE_NAME)
2041    }
2042}
2043
2044// ---------------------------------------------------------------------------
2045// ConditionalBackend (draft-ietf-jmap-conditional-02)
2046// ---------------------------------------------------------------------------
2047
2048/// Conditional Scene Foo/set (bd JMAP-y1yu.15): the whole store is one
2049/// [`ScopedState`], so a scope isolates every account, and an atomic
2050/// rollback restores objects, state strings, change logs, derived counts
2051/// and queued deliveries together. Under an atomic scope the backend leaves
2052/// `maxAvatarsPerRegion` to the commit, which checks the final state
2053/// (`final_state_failures`).
2054impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
2055    async fn begin_set(
2056        &self,
2057        _caller: &C,
2058        request: SetScopeRequest<'_>,
2059    ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
2060        Ok(self.inner.open(request, final_state_failures).await)
2061    }
2062}
2063
2064/// The avatar changes an atomic scope made that break a region-wide rule
2065/// in the state it would commit (conditional-02 §4.2;
2066/// draft-atwood-jmap-scene-00 §Entering a Region): more present avatars in
2067/// a region than the account's `maxAvatarsPerRegion`, as `overQuota` on
2068/// each present avatar the scope created or changed in that region.
2069fn final_state_failures(before: &Inner, after: &Inner) -> Vec<DeferredFailure> {
2070    let mut failures = Vec::new();
2071    for (account, capability) in &after.accounts {
2072        let account_id = Id::from(account.as_str());
2073        let old: HashMap<Id, SceneAvatar> = before
2074            .all::<SceneAvatar>(&account_id)
2075            .map(|a| (a.id.clone(), a))
2076            .collect();
2077        let now: Vec<SceneAvatar> = after.all::<SceneAvatar>(&account_id).collect();
2078        for a in &now {
2079            let op = match old.get(&a.id) {
2080                None => SetOp::Create(a.id.clone()),
2081                Some(prev) if prev != a => SetOp::Update(a.id.clone()),
2082                Some(_) => continue,
2083            };
2084            let Some(max) = capability.max_avatars_per_region else {
2085                continue;
2086            };
2087            let present = now
2088                .iter()
2089                .filter(|b| b.region_id == a.region_id && b.left_at.is_none())
2090                .count() as u64;
2091            if a.left_at.is_none() && present > max {
2092                failures.push(DeferredFailure::new(
2093                    op,
2094                    SetError::new(SetErrorType::OverQuota)
2095                        .with_description("maxAvatarsPerRegion reached"),
2096                ));
2097            }
2098        }
2099    }
2100    failures
2101}
2102
2103#[cfg(test)]
2104mod memory_error_tests {
2105    use super::MemoryError;
2106
2107    /// The `JmapAccounts::Error` contract: "Implementations MUST NOT
2108    /// include ... PII shaped like an email address" in `Display`
2109    /// output. serde_json data errors quote the offending value, so
2110    /// [`MemoryError::serde`] must drop the message (bd:JMAP-510h.37).
2111    #[test]
2112    fn serde_error_display_omits_offending_value() {
2113        let canary = "alice@example.com";
2114        let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
2115            .expect_err("a string is not a u64");
2116        assert!(
2117            e.to_string().contains(canary),
2118            "precondition: serde_json quotes the value"
2119        );
2120
2121        let shown = MemoryError::serde("decode", &e).to_string();
2122        assert!(!shown.contains(canary), "canary leaked: {shown}");
2123        assert!(
2124            shown.contains("decode") && shown.contains("Data"),
2125            "{shown}"
2126        );
2127    }
2128}
2129
2130#[cfg(test)]
2131mod clone_tests {
2132    use super::MemoryBackend;
2133
2134    /// Oracle (bd:JMAP-q7k6): `MemoryBackend::clone` is a shared-state
2135    /// clone, never a deep copy, so a clone and its original hold the
2136    /// same store while a fresh instance does not.
2137    #[test]
2138    fn clone_shares_store() {
2139        let a = MemoryBackend::new();
2140        let clone = a.clone();
2141        let fresh = MemoryBackend::new();
2142        a.add_admin("u1");
2143        let admin = |b: &MemoryBackend| b.inner.lock_unscoped().admins.contains("u1");
2144        assert!(admin(&clone), "a clone sees the original's writes");
2145        assert!(!admin(&fresh), "a fresh backend does not");
2146    }
2147}
2148
2149#[cfg(test)]
2150mod max_changes_tests {
2151    use super::*;
2152    use jmap_scene_types::SceneObject as T;
2153
2154    /// A backend whose `T` log holds one commit per element of `states`,
2155    /// each creating the listed ids under one state.
2156    fn with_creates(states: &[&[&str]]) -> MemoryBackend {
2157        let backend = MemoryBackend::new();
2158        let mut inner = backend.lock();
2159        for ids in states {
2160            let changes = ids
2161                .iter()
2162                .map(|s| (Id::from(*s), Change::Created))
2163                .collect();
2164            inner.commit(T::TYPE_NAME, &Id::from("acc1"), changes);
2165        }
2166        drop(inner);
2167        backend
2168    }
2169
2170    /// Oracle: RFC 8620 §5.2, expected pages written by hand: "the server
2171    /// MUST ensure the number of ids returned across "created", "updated",
2172    /// and "destroyed" does not exceed this limit. If there are more
2173    /// changes than this ..., the server SHOULD generate an update to take
2174    /// the client to an intermediate state, from which the client can
2175    /// continue to call "Foo/changes" until it is fully up to date." Three
2176    /// one-create states against `maxChanges` 2 page as states 1-2, then 3.
2177    #[tokio::test]
2178    async fn over_max_changes_pages_through_intermediate_state() {
2179        let backend = with_creates(&[&["a"], &["b"], &["c"]]);
2180
2181        let first = changes(&backend, "0", 2).await.expect("first page");
2182        assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
2183        assert!(first.has_more_changes);
2184        assert_eq!(first.new_state.as_ref(), "2");
2185
2186        let rest = changes(&backend, "2", 2).await.expect("second page");
2187        assert_eq!(rest.created, [Id::from("c")]);
2188        assert!(!rest.has_more_changes);
2189        assert_eq!(rest.new_state.as_ref(), "3");
2190    }
2191
2192    /// Oracle: RFC 8620 §5.2 "If it is unable to calculate an intermediate
2193    /// state, it MUST return a "cannotCalculateChanges" error response
2194    /// instead." One state creating three ids cannot be split under
2195    /// `maxChanges` 2.
2196    #[tokio::test]
2197    async fn one_state_over_max_changes_cannot_calculate() {
2198        let backend = with_creates(&[&["a", "b", "c"]]);
2199        assert!(matches!(
2200            changes(&backend, "0", 2).await,
2201            Err(BackendChangesError::TooManyChanges { limit: 2 })
2202        ));
2203    }
2204
2205    fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
2206        ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
2207        ids
2208    }
2209
2210    async fn changes(
2211        backend: &MemoryBackend,
2212        since: &str,
2213        max: u64,
2214    ) -> Result<ChangesResult, BackendChangesError<<MemoryBackend as JmapAccounts>::Error>> {
2215        backend
2216            .get_changes::<T>(
2217                &Id::from("caller"),
2218                &Id::from("acc1"),
2219                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
2220            )
2221            .await
2222    }
2223}