1#![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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum Change {
174 Created,
175 Updated,
176 Destroyed,
177 Restored,
179}
180
181type Keyed<V> = HashMap<&'static str, HashMap<String, V>>;
184
185type Admitted = (Vec<(Id, Change)>, Vec<Id>);
188
189#[derive(Default, Clone)]
191struct AvatarRules {
192 hidden: HashSet<(String, Id)>,
195 withheld: HashMap<(String, Id), AvatarRedaction>,
198}
199
200#[derive(Clone)]
203struct AvatarSnapshot {
204 state: u64,
205 avatars: HashMap<Id, Value>,
206 rules: AvatarRules,
207}
208
209#[derive(Default, Clone)]
212struct Inner {
213 objects: Keyed<HashMap<Id, Value>>,
215 states: Keyed<u64>,
217 log: Keyed<Vec<(u64, Id, Change)>>,
219 accounts: HashMap<String, SceneCapability>,
221 blobs: HashMap<(String, String), u64>,
223 storage_quota: HashMap<String, u64>,
225 admins: HashSet<String>,
227 capabilities: HashMap<String, HashSet<String>>,
229 bindings: HashMap<(BindingProperty, String), BindingTarget>,
231 channel_spaces: HashSet<(String, String)>,
232 grants: HashSet<(String, String)>,
234 bans: HashSet<(String, String)>,
236 hidden: HashSet<(String, Id)>,
238 rate_limited: HashSet<String>,
241 interactions: Vec<SceneInteractionEvent>,
243 region_event_limited: HashSet<String>,
246 region_events: Vec<SceneRegionEvent>,
249 blocked: HashSet<(String, String)>,
251 hidden_avatars: HashSet<(String, Id)>,
254 reserved_names: Vec<String>,
256 avatar_rules: HashMap<String, AvatarRules>,
261 avatar_views: HashMap<String, Vec<AvatarSnapshot>>,
264 supports_observe: bool,
266 observers: HashMap<(String, Id), HashMap<String, usize>>,
269 declined_observers: HashSet<Id>,
272 observer_accounts: Option<Vec<Id>>,
275 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 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 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 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 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 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 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 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 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 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, ®ions);
539 }
540 }
541
542 fn enter(
552 &mut self,
553 account_id: &Id,
554 avatar: SceneAvatar,
555 defer: bool,
556 ) -> Result<Value, BackendSetError<MemoryError>> {
557 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, ®ions);
580 Ok(value)
581 }
582
583 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 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 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, ®ion)
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 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 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 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 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 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 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 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 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 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 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 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#[non_exhaustive]
898pub struct MemoryBackend<C = Id> {
899 inner: ScopedState<Inner>,
900 caller: PhantomData<fn() -> C>,
901}
902
903impl<C> Default for MemoryBackend<C> {
906 fn default() -> Self {
907 Self {
908 inner: ScopedState::default(),
909 caller: PhantomData,
910 }
911 }
912}
913
914impl<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 pub fn new() -> Self {
934 Self::default()
935 }
936}
937
938fn 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 fn lock(&self) -> ScopedGuard<'_, Inner> {
948 self.inner.lock_unscoped()
949 }
950
951 async fn locked(&self) -> ScopedGuard<'_, Inner> {
954 self.inner.lock().await
955 }
956
957 #[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 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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 pub fn set_supports_observe(&self, on: bool) {
1136 self.lock().supports_observe = on;
1137 }
1138
1139 #[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 #[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 #[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 #[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 #[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 #[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 #[doc(hidden)]
1210 pub fn rate_limit_interactions(&self, user: &str) {
1211 self.lock().rate_limited.insert(user.to_owned());
1212 }
1213
1214 #[doc(hidden)]
1217 pub fn accepted_interactions(&self) -> Vec<SceneInteractionEvent> {
1218 self.lock().interactions.clone()
1219 }
1220
1221 #[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 #[doc(hidden)]
1231 pub fn accepted_region_events(&self) -> Vec<SceneRegionEvent> {
1232 self.lock().region_events.clone()
1233 }
1234
1235 #[doc(hidden)]
1238 pub fn reserve_display_name(&self, name: &str) {
1239 self.lock().reserved_names.push(name.to_owned());
1240 }
1241
1242 #[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#[non_exhaustive]
1261#[derive(Debug)]
1262pub struct MemoryError {
1263 description: String,
1264}
1265
1266impl MemoryError {
1267 pub fn new(description: impl Into<String>) -> Self {
1269 Self {
1270 description: description.into(),
1271 }
1272 }
1273
1274 pub fn description(&self) -> &str {
1276 &self.description
1277 }
1278
1279 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
1313fn 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
1321fn 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 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 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 if O::TYPE_NAME == SceneAsset::TYPE_NAME
1544 && let Some("a) = 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 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 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(¤t).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 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(¤t).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 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, ®ions);
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 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 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 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 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 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 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 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(®ion.id))
1938 }
1939
1940 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 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
2044impl<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
2064fn 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 #[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 #[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 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 #[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 #[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}