#![deny(clippy::await_holding_lock)]
mod history;
use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
use jmap_scene_types::{
AccessPolicy, SceneAsset, SceneAvatar, SceneCapability, SceneInteractionEvent, SceneObject,
SceneRegion, SceneRegionEvent,
};
use jmap_scene_types::{
SceneAssetComparator, SceneAssetFilter, SceneAvatarComparator, SceneAvatarFilter,
SceneObjectComparator, SceneObjectFilter, SceneRegionComparator, SceneRegionFilter,
};
use jmap_server::{
BeginSetError, ConditionalBackend, DeferredFailure, MemoryCaller, ScopedGuard, ScopedState,
SetOp, SetScope, SetScopeRequest, apply_patch_object, limit_or_max, resolve_query_start,
};
use jmap_types::{Id, State};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use crate::query::{
asset_matches, avatar_matches, compare_assets, compare_avatars, compare_objects,
compare_regions, object_matches, region_local_position, region_matches,
};
use crate::{AvatarRedaction, AvatarView, BindingProperty, BindingTarget, SceneBackend};
use jmap_server::{
BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
JmapAccounts, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult, QueryObject,
QueryParams, QueryResult, SetError, SetErrorType, SetObject,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Change {
Created,
Updated,
Destroyed,
Restored,
}
type Keyed<V> = HashMap<&'static str, HashMap<String, V>>;
type Admitted = (Vec<(Id, Change)>, Vec<Id>);
#[derive(Default, Clone)]
struct AvatarRules {
hidden: HashSet<(String, Id)>,
withheld: HashMap<(String, Id), AvatarRedaction>,
}
#[derive(Clone)]
struct AvatarSnapshot {
state: u64,
avatars: HashMap<Id, Value>,
rules: AvatarRules,
}
#[derive(Default, Clone)]
struct Inner {
objects: Keyed<HashMap<Id, Value>>,
states: Keyed<u64>,
log: Keyed<Vec<(u64, Id, Change)>>,
accounts: HashMap<String, SceneCapability>,
blobs: HashMap<(String, String), u64>,
storage_quota: HashMap<String, u64>,
admins: HashSet<String>,
capabilities: HashMap<String, HashSet<String>>,
bindings: HashMap<(BindingProperty, String), BindingTarget>,
channel_spaces: HashSet<(String, String)>,
grants: HashSet<(String, String)>,
bans: HashSet<(String, String)>,
hidden: HashSet<(String, Id)>,
rate_limited: HashSet<String>,
interactions: Vec<SceneInteractionEvent>,
region_event_limited: HashSet<String>,
region_events: Vec<SceneRegionEvent>,
blocked: HashSet<(String, String)>,
hidden_avatars: HashSet<(String, Id)>,
reserved_names: Vec<String>,
avatar_rules: HashMap<String, AvatarRules>,
avatar_views: HashMap<String, Vec<AvatarSnapshot>>,
supports_observe: bool,
observers: HashMap<(String, Id), HashMap<String, usize>>,
declined_observers: HashSet<Id>,
observer_accounts: Option<Vec<Id>>,
history: Option<jmap_object_history_server::HistoryStore>,
}
impl Inner {
fn objects(&self, type_name: &'static str, account_id: &Id) -> Option<&HashMap<Id, Value>> {
self.objects
.get(type_name)
.and_then(|m| m.get(account_id.as_ref()))
}
fn objects_mut(&mut self, type_name: &'static str, account_id: &Id) -> &mut HashMap<Id, Value> {
self.objects
.entry(type_name)
.or_default()
.entry(account_id.as_ref().to_owned())
.or_default()
}
fn state(&self, type_name: &'static str, account_id: &Id) -> u64 {
self.states
.get(type_name)
.and_then(|m| m.get(account_id.as_ref()))
.copied()
.unwrap_or(0)
}
fn commit(&mut self, type_name: &'static str, account_id: &Id, changes: Vec<(Id, Change)>) {
let state = self
.states
.entry(type_name)
.or_default()
.entry(account_id.as_ref().to_owned())
.or_insert(0);
*state += 1;
let state = *state;
self.log
.entry(type_name)
.or_default()
.entry(account_id.as_ref().to_owned())
.or_default()
.extend(changes.into_iter().map(|(id, c)| (state, id, c)));
if type_name == SceneAvatar::TYPE_NAME {
self.snapshot_avatars(account_id);
}
}
fn snapshot_avatars(&mut self, account_id: &Id) {
let Some(rules) = self.avatar_rules.get(account_id.as_ref()).cloned() else {
return;
};
let snapshot = AvatarSnapshot {
state: self.state(SceneAvatar::TYPE_NAME, account_id),
avatars: self
.objects(SceneAvatar::TYPE_NAME, account_id)
.cloned()
.unwrap_or_default(),
rules,
};
self.avatar_views
.entry(account_id.as_ref().to_owned())
.or_default()
.push(snapshot);
}
fn change_avatar_rules(&mut self, account_id: &Id, change: impl FnOnce(&mut AvatarRules)) {
if !self.avatar_rules.contains_key(account_id.as_ref()) {
self.avatar_rules
.insert(account_id.as_ref().to_owned(), AvatarRules::default());
self.snapshot_avatars(account_id);
}
if let Some(rules) = self.avatar_rules.get_mut(account_id.as_ref()) {
change(rules);
}
self.commit(SceneAvatar::TYPE_NAME, account_id, Vec::new());
}
fn avatar_view(
&self,
viewer: &str,
account_id: &Id,
avatar: &SceneAvatar,
rules: Option<&AvatarRules>,
) -> AvatarView {
let Some(rules) = rules else {
return AvatarView::Full;
};
if avatar.user_id == viewer
|| self.admins.contains(viewer)
|| self.owns_region(viewer, account_id, &avatar.region_id)
{
return AvatarView::Full;
}
let key = (viewer.to_owned(), avatar.id.clone());
if rules.hidden.contains(&key) {
return AvatarView::Hidden;
}
match rules.withheld.get(&key) {
Some(r) => AvatarView::Redacted(r.clone()),
None => AvatarView::Full,
}
}
fn viewed_avatar(
&self,
viewer: &str,
account_id: &Id,
mut avatar: SceneAvatar,
rules: Option<&AvatarRules>,
) -> Option<SceneAvatar> {
match self.avatar_view(viewer, account_id, &avatar, rules) {
AvatarView::Hidden => None,
AvatarView::Redacted(r) => {
r.apply(&mut avatar);
Some(avatar)
}
_ => Some(avatar),
}
}
fn view_at(
&self,
viewer: &str,
account_id: &Id,
snapshot: &AvatarSnapshot,
) -> HashMap<Id, Value> {
snapshot
.avatars
.iter()
.filter_map(|(id, v)| {
let a = decode::<SceneAvatar>(v).ok()?;
let seen = self.viewed_avatar(viewer, account_id, a, Some(&snapshot.rules))?;
Some((id.clone(), serde_json::to_value(seen).ok()?))
})
.collect()
}
fn avatar_changes_for(
&self,
viewer: &str,
account_id: &Id,
since: u64,
max_changes: Option<u64>,
) -> Option<Result<ChangesResult, BackendChangesError<MemoryError>>> {
let snapshots = self.avatar_views.get(account_id.as_ref())?;
let start = snapshots.iter().position(|s| s.state == since)?;
let base = self.view_at(viewer, account_id, &snapshots[start]);
let diff = |now: &HashMap<Id, Value>| {
let mut created = Vec::new();
let mut updated = Vec::new();
let mut destroyed = Vec::new();
for (id, v) in now {
match base.get(id) {
None => created.push(id.clone()),
Some(old) if old != v => updated.push(id.clone()),
Some(_) => {}
}
}
for id in base.keys().filter(|id| !now.contains_key(*id)) {
destroyed.push(id.clone());
}
(created, updated, destroyed)
};
let current = self.state(SceneAvatar::TYPE_NAME, account_id);
let mut result = (Vec::new(), Vec::new(), Vec::new());
let mut upto = since;
for snapshot in &snapshots[start + 1..] {
let next = diff(&self.view_at(viewer, account_id, snapshot));
let count = (next.0.len() + next.1.len() + next.2.len()) as u64;
if let Some(max) = max_changes
&& count > max
{
if upto == since {
return Some(Err(BackendChangesError::TooManyChanges { limit: max }));
}
break;
}
result = next;
upto = snapshot.state;
}
let (created, updated, destroyed) = result;
Some(Ok(ChangesResult::new(
created,
updated,
destroyed,
upto < current,
State::from(upto.to_string()),
)))
}
fn recount(&mut self, account_id: &Id, regions: &[Id]) {
let mut changed = Vec::new();
for region in regions {
let active = self
.all::<SceneAvatar>(account_id)
.filter(|a| a.region_id == *region && a.left_at.is_none())
.count();
let observers = self.observer_count(account_id, region);
let Some(stored) = self
.objects_mut(SceneRegion::TYPE_NAME, account_id)
.get_mut(region)
else {
continue;
};
let mut differs = false;
if stored.get("activeAvatarCount") != Some(&json!(active)) {
stored["activeAvatarCount"] = json!(active);
differs = true;
}
if let Some(observers) = observers
&& stored.get("observerCount") != Some(&json!(observers))
{
stored["observerCount"] = json!(observers);
differs = true;
}
if differs {
changed.push((region.clone(), Change::Updated));
}
}
if !changed.is_empty() {
self.commit(SceneRegion::TYPE_NAME, account_id, changed);
}
}
fn recount_observed(&mut self, region_id: Option<&Id>) {
let mut by_account: HashMap<Id, Vec<Id>> = HashMap::new();
for (account, region) in self.observers.keys() {
if region_id.is_none_or(|r| r == region) {
by_account
.entry(Id::from(account.as_str()))
.or_default()
.push(region.clone());
}
}
for (account, regions) in by_account {
self.recount(&account, ®ions);
}
}
fn enter(
&mut self,
account_id: &Id,
avatar: SceneAvatar,
defer: bool,
) -> Result<Value, BackendSetError<MemoryError>> {
if let Some(existing) = self
.all::<SceneAvatar>(account_id)
.find(|a| a.user_id == avatar.user_id && a.region_id == avatar.region_id)
{
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::AlreadyExists)
.with_description("the user already has an avatar record in this region")
.with_existing_id(existing.id),
)));
}
let (mut changes, mut regions) = self.admit(account_id, &avatar, defer)?;
let id = avatar.id.clone();
let value = serde_json::to_value(&avatar)
.map_err(|e| BackendSetError::Other(MemoryError::serde("serialize SceneAvatar", &e)))?;
self.objects_mut(SceneAvatar::TYPE_NAME, account_id)
.insert(id.clone(), value.clone());
changes.push((id, Change::Created));
regions.push(avatar.region_id);
self.commit(SceneAvatar::TYPE_NAME, account_id, changes);
self.recount(account_id, ®ions);
Ok(value)
}
fn admit(
&mut self,
account_id: &Id,
avatar: &SceneAvatar,
defer: bool,
) -> Result<Admitted, BackendSetError<MemoryError>> {
let max = self
.accounts
.get(account_id.as_ref())
.and_then(|c| c.max_avatars_per_region);
let present = self
.all::<SceneAvatar>(account_id)
.filter(|a| a.region_id == avatar.region_id && a.left_at.is_none())
.count() as u64;
if !defer && max.is_some_and(|max| present >= max) {
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::OverQuota)
.with_description("maxAvatarsPerRegion reached"),
)));
}
let previous: Vec<SceneAvatar> = self
.all::<SceneAvatar>(account_id)
.filter(|a| a.user_id == avatar.user_id && a.left_at.is_none())
.collect();
let avatars = self.objects_mut(SceneAvatar::TYPE_NAME, account_id);
let mut changes = Vec::new();
let mut regions = Vec::new();
for previous in previous {
if let Some(v) = avatars.get_mut(&previous.id) {
v["leftAt"] = json!(avatar.joined_at);
changes.push((previous.id, Change::Updated));
regions.push(previous.region_id);
}
}
Ok((changes, regions))
}
fn observer_count(&self, account_id: &Id, region_id: &Id) -> Option<usize> {
let region = self.region(account_id, region_id)?;
region.observer_count?;
if region.allow_observers == Some(false) || self.declined_observers.contains(region_id) {
return Some(0);
}
let watching = self
.observers
.get(&(account_id.as_ref().to_owned(), region_id.clone()));
Some(watching.map_or(0, |users| {
users
.keys()
.filter(|user| {
self.admits(user, account_id, ®ion)
&& !self.all::<SceneAvatar>(account_id).any(|a| {
a.region_id == *region_id && a.user_id == **user && a.left_at.is_none()
})
})
.count()
}))
}
fn region(&self, account_id: &Id, region_id: &Id) -> Option<SceneRegion> {
self.objects(SceneRegion::TYPE_NAME, account_id)
.and_then(|m| m.get(region_id))
.and_then(|v| decode::<SceneRegion>(v).ok())
}
fn owns_region(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
self.region(account_id, region_id)
.is_some_and(|r| r.owner_id == caller)
}
fn admits(&self, caller: &str, account_id: &Id, region: &SceneRegion) -> bool {
region.access_policy != AccessPolicy::Invite
|| region.owner_id == caller
|| self.admins.contains(caller)
|| region.invited_user_ids.iter().any(|u| u == caller)
|| self
.grants
.contains(&(region.id.as_ref().to_owned(), caller.to_owned()))
|| self
.all::<SceneAvatar>(account_id)
.any(|a| a.region_id == region.id && a.user_id == caller && a.left_at.is_none())
}
fn may_access(&self, caller: &str, account_id: &Id, region_id: &Id) -> bool {
self.region(account_id, region_id)
.is_none_or(|r| self.admits(caller, account_id, &r))
}
fn all<O: JmapObject>(&self, account_id: &Id) -> impl Iterator<Item = O> + '_ + use<'_, O> {
self.objects(O::TYPE_NAME, account_id)
.into_iter()
.flat_map(HashMap::values)
.filter_map(|v| O::deserialize(v).ok())
}
fn log_window(
&self,
type_name: &'static str,
account_id: &Id,
since: u64,
) -> impl Iterator<Item = &(u64, Id, Change)> + '_ + use<'_> {
self.log
.get(type_name)
.and_then(|m| m.get(account_id.as_ref()))
.into_iter()
.flatten()
.filter(move |(s, _, _)| *s > since)
}
fn changes_upto(
&self,
type_name: &'static str,
account_id: &Id,
since: u64,
max: u64,
) -> Result<u64, BackendChangesError<MemoryError>> {
let mut seen: HashSet<&Id> = HashSet::new();
let (mut fits, mut commit) = (since, since);
for (s, id, _) in self.log_window(type_name, account_id, since) {
if *s != commit {
(fits, commit) = (commit, *s);
}
if seen.insert(id) && seen.len() as u64 > max {
if fits == since {
return Err(BackendChangesError::TooManyChanges { limit: max });
}
return Ok(fits);
}
}
Ok(self.state(type_name, account_id))
}
fn net_changes(
&self,
type_name: &'static str,
account_id: &Id,
since: u64,
upto: u64,
) -> Vec<(Id, Change)> {
let window = || {
self.log_window(type_name, account_id, since)
.filter(move |(s, _, _)| *s <= upto)
};
let mut net: Vec<(Id, Change)> = Vec::new();
for (_, id, change) in window() {
match net.iter_mut().find(|(seen, _)| seen == id) {
Some((_, prev)) if *prev == Change::Created && *change == Change::Updated => {}
Some((_, prev)) => *prev = *change,
None => net.push((id.clone(), *change)),
}
}
let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
for (_, id, change) in window() {
events.entry(id.clone()).or_default().push(match change {
Change::Created => ChangeEvent::Created,
Change::Updated => ChangeEvent::Updated,
Change::Destroyed => ChangeEvent::Destroyed,
Change::Restored => ChangeEvent::Restored,
});
}
net.retain_mut(|(id, change)| {
let Some(list) = events
.get(id)
.filter(|l| l.contains(&ChangeEvent::Restored))
else {
return true;
};
match fold_restore(list) {
Some(ChangeKind::Created) => *change = Change::Created,
Some(ChangeKind::Destroyed) => *change = Change::Destroyed,
Some(_) => *change = Change::Updated,
None => return false,
}
true
});
net
}
fn query_ids<O: QueryObject>(
&self,
caller: &str,
account_id: &Id,
filter: Option<&O::Filter>,
sort: &[O::Comparator],
) -> Result<Vec<Id>, BackendQueryError<MemoryError>> {
Ok(if O::TYPE_NAME == SceneAsset::TYPE_NAME {
let filter: Option<SceneAssetFilter> = filter.map(recode).transpose()?;
let sort: Vec<SceneAssetComparator> = recode(&sort)?;
sorted_ids(
self.all::<SceneAsset>(account_id),
|a| filter.as_ref().is_none_or(|f| asset_matches(f, a)),
|a, b| compare_assets(a, b, &sort),
|a| a.id,
)
} else if O::TYPE_NAME == SceneRegion::TYPE_NAME {
let filter: Option<SceneRegionFilter> = filter.map(recode).transpose()?;
let sort: Vec<SceneRegionComparator> = recode(&sort)?;
sorted_ids(
self.all::<SceneRegion>(account_id),
|r| {
self.may_access(caller, account_id, &r.id)
&& filter.as_ref().is_none_or(|f| region_matches(f, r))
},
|a, b| compare_regions(a, b, &sort),
|r| r.id,
)
} else if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
let filter: Option<SceneAvatarFilter> = filter.map(recode).transpose()?;
let sort: Vec<SceneAvatarComparator> = recode(&sort)?;
let rules = self.avatar_rules.get(account_id.as_ref());
sorted_ids(
self.all::<SceneAvatar>(account_id)
.filter_map(|a| self.viewed_avatar(caller, account_id, a, rules)),
|a| {
self.may_access(caller, account_id, &a.region_id)
&& !self
.blocked
.contains(&(caller.to_owned(), a.user_id.clone()))
&& !self
.hidden_avatars
.contains(&(caller.to_owned(), a.region_id.clone()))
&& filter.as_ref().is_none_or(|f| avatar_matches(f, a))
},
|a, b| compare_avatars(a, b, &sort),
|a| a.id,
)
} else if O::TYPE_NAME == SceneObject::TYPE_NAME {
let filter: Option<SceneObjectFilter> = filter.map(recode).transpose()?;
let sort: Vec<SceneObjectComparator> = recode(&sort)?;
let all: HashMap<Id, SceneObject> = self
.all::<SceneObject>(account_id)
.map(|o| (o.id.clone(), o))
.collect();
sorted_ids(
all.values(),
|o| {
self.may_access(caller, account_id, &o.region_id)
&& !self.hidden.contains(&(caller.to_owned(), o.id.clone()))
&& filter.as_ref().is_none_or(|f| {
object_matches(f, o, region_local_position(o, |id| all.get(id)))
})
},
|a, b| compare_objects(a, b, &sort),
|o| o.id.clone(),
)
} else {
return Err(BackendQueryError::Other(MemoryError::new(format!(
"query of {} is not implemented",
O::TYPE_NAME
))));
})
}
}
#[non_exhaustive]
pub struct MemoryBackend<C = Id> {
inner: ScopedState<Inner>,
caller: PhantomData<fn() -> C>,
}
impl<C> Default for MemoryBackend<C> {
fn default() -> Self {
Self {
inner: ScopedState::default(),
caller: PhantomData,
}
}
}
impl<C> Clone for MemoryBackend<C> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
caller: PhantomData,
}
}
}
impl MemoryBackend {
pub fn new() -> Self {
Self::default()
}
}
fn acting_user<C: MemoryCaller>(caller: &C, account_id: &Id) -> String {
caller.principal().unwrap_or(account_id).as_ref().to_owned()
}
impl<C: MemoryCaller> MemoryBackend<C> {
fn lock(&self) -> ScopedGuard<'_, Inner> {
self.inner.lock_unscoped()
}
async fn locked(&self) -> ScopedGuard<'_, Inner> {
self.inner.lock().await
}
#[must_use]
pub fn with_account(self, account_id: &Id, capability: SceneCapability) -> Self {
self.register_account(account_id, capability);
self
}
pub fn register_account(&self, account_id: &Id, capability: SceneCapability) {
debug_assert!(
!account_id.as_ref().is_empty(),
"register_account: account_id must not be the empty string \
(RFC 8620 §1.2, bd:JMAP-dx0s)"
);
self.lock()
.accounts
.insert(account_id.as_ref().to_owned(), capability);
}
#[doc(hidden)]
pub fn add_blob(&self, account_id: &Id, blob_id: &str, size: u64) {
self.lock()
.blobs
.insert((account_id.as_ref().to_owned(), blob_id.to_owned()), size);
}
#[doc(hidden)]
pub fn set_storage_quota(&self, account_id: &Id, bytes: u64) {
self.lock()
.storage_quota
.insert(account_id.as_ref().to_owned(), bytes);
}
#[doc(hidden)]
pub fn add_admin(&self, user: &str) {
let mut inner = self.lock();
inner.admins.insert(user.to_owned());
inner.recount_observed(None);
}
pub fn advertise(&self, account_id: &Id, uri: &str) {
self.lock()
.capabilities
.entry(account_id.as_ref().to_owned())
.or_default()
.insert(uri.to_owned());
}
#[doc(hidden)]
pub fn set_region_binding(&self, property: BindingProperty, id: &str, target: BindingTarget) {
self.lock()
.bindings
.insert((property, id.to_owned()), target);
}
#[doc(hidden)]
pub fn set_channel_space(&self, channel_id: &str, space_id: &str) {
self.lock()
.channel_spaces
.insert((channel_id.to_owned(), space_id.to_owned()));
}
#[doc(hidden)]
pub fn grant_region_access(&self, region_id: &str, user: &str) {
let mut inner = self.lock();
inner.grants.insert((region_id.to_owned(), user.to_owned()));
inner.recount_observed(Some(&Id::from(region_id)));
}
#[doc(hidden)]
pub fn revoke_region_access(&self, region_id: &str, user: &str) {
let mut inner = self.lock();
inner
.grants
.remove(&(region_id.to_owned(), user.to_owned()));
inner.recount_observed(Some(&Id::from(region_id)));
}
#[doc(hidden)]
pub fn ban_from_region(&self, region_id: &str, user: &str) {
self.lock()
.bans
.insert((region_id.to_owned(), user.to_owned()));
}
#[doc(hidden)]
pub fn hide_object(&self, user: &str, object_id: &str) {
self.lock()
.hidden
.insert((user.to_owned(), Id::from(object_id)));
}
#[doc(hidden)]
pub fn block(&self, blocker: &str, user: &str) {
self.lock()
.blocked
.insert((blocker.to_owned(), user.to_owned()));
}
#[doc(hidden)]
pub fn hide_region_avatars(&self, user: &str, region_id: &str) {
self.lock()
.hidden_avatars
.insert((user.to_owned(), Id::from(region_id)));
}
pub fn set_supports_observe(&self, on: bool) {
self.lock().supports_observe = on;
}
#[doc(hidden)]
pub fn decline_observers(&self, region_id: &str) {
let mut inner = self.lock();
inner.declined_observers.insert(Id::from(region_id));
inner.recount_observed(Some(&Id::from(region_id)));
}
#[doc(hidden)]
pub fn admit_observers(&self, region_id: &str) {
let mut inner = self.lock();
inner.declined_observers.remove(&Id::from(region_id));
inner.recount_observed(Some(&Id::from(region_id)));
}
#[doc(hidden)]
pub fn restrict_observer_accounts(&self, accounts: &[&str]) {
self.lock().observer_accounts = Some(accounts.iter().map(|a| Id::from(*a)).collect());
}
#[doc(hidden)]
pub fn hide_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
let key = (viewer.to_owned(), Id::from(avatar_id));
self.lock().change_avatar_rules(account_id, |rules| {
rules.withheld.remove(&key);
rules.hidden.insert(key);
});
}
#[doc(hidden)]
pub fn withhold_avatar(
&self,
account_id: &Id,
viewer: &str,
avatar_id: &str,
redaction: AvatarRedaction,
) {
let key = (viewer.to_owned(), Id::from(avatar_id));
self.lock().change_avatar_rules(account_id, |rules| {
rules.hidden.remove(&key);
rules.withheld.insert(key, redaction);
});
}
#[doc(hidden)]
pub fn reveal_avatar(&self, account_id: &Id, viewer: &str, avatar_id: &str) {
let key = (viewer.to_owned(), Id::from(avatar_id));
self.lock().change_avatar_rules(account_id, |rules| {
rules.hidden.remove(&key);
rules.withheld.remove(&key);
});
}
#[doc(hidden)]
pub fn rate_limit_interactions(&self, user: &str) {
self.lock().rate_limited.insert(user.to_owned());
}
#[doc(hidden)]
pub fn accepted_interactions(&self) -> Vec<SceneInteractionEvent> {
self.lock().interactions.clone()
}
#[doc(hidden)]
pub fn rate_limit_region_events(&self, user: &str) {
self.lock().region_event_limited.insert(user.to_owned());
}
#[doc(hidden)]
pub fn accepted_region_events(&self) -> Vec<SceneRegionEvent> {
self.lock().region_events.clone()
}
#[doc(hidden)]
pub fn reserve_display_name(&self, name: &str) {
self.lock().reserved_names.push(name.to_owned());
}
#[doc(hidden)]
#[cfg(feature = "test-helpers")]
pub fn insert_object_for_test(
&self,
type_name: &'static str,
account_id: &Id,
id: &str,
value: Value,
) {
self.lock()
.objects_mut(type_name, account_id)
.insert(Id::from(id), value);
}
}
#[non_exhaustive]
#[derive(Debug)]
pub struct MemoryError {
description: String,
}
impl MemoryError {
pub fn new(description: impl Into<String>) -> Self {
Self {
description: description.into(),
}
}
pub fn description(&self) -> &str {
&self.description
}
pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
Self::new(format!("{context}: serde_json {:?} error", e.classify()))
}
}
impl std::fmt::Display for MemoryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MemoryBackend error: {}", self.description)
}
}
impl std::error::Error for MemoryError {}
fn not_found<E>() -> BackendSetError<E> {
BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
}
fn decode<O: JmapObject>(v: &Value) -> Result<O, MemoryError> {
O::deserialize(v).map_err(|e| MemoryError::serde(format_args!("decode {}", O::TYPE_NAME), &e))
}
fn recode_as<T: DeserializeOwned>(v: &Value) -> Result<T, BackendQueryError<MemoryError>> {
T::deserialize(v)
.map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))
}
fn recode<T: DeserializeOwned>(v: &impl Serialize) -> Result<T, BackendQueryError<MemoryError>> {
let v = serde_json::to_value(v)
.map_err(|e| BackendQueryError::Other(MemoryError::serde("recode query argument", &e)))?;
recode_as(&v)
}
fn sorted_ids<T>(
list: impl Iterator<Item = T>,
keep: impl Fn(&T) -> bool,
cmp: impl Fn(&T, &T) -> std::cmp::Ordering,
id: impl Fn(T) -> Id,
) -> Vec<Id> {
let mut list: Vec<T> = list.filter(|t| keep(t)).collect();
list.sort_by(|a, b| cmp(a, b));
list.into_iter().map(id).collect()
}
impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
type Error = MemoryError;
type CallerCtx = C;
fn principal_id(caller: &C) -> Option<&Id> {
caller.principal()
}
async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, MemoryError> {
Ok(self
.locked()
.await
.accounts
.contains_key(account_id.as_ref()))
}
}
impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &C,
account_id: &Id,
ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), MemoryError> {
let inner = self.locked().await;
let map = inner.objects(O::TYPE_NAME, account_id);
match ids {
None => {
let list = map
.into_iter()
.flat_map(HashMap::values)
.map(decode)
.collect::<Result<_, _>>()?;
Ok((list, Vec::new()))
}
Some(ids) => {
let mut found = Vec::new();
let mut missing = Vec::new();
for id in ids {
match map.and_then(|m| m.get(id)) {
Some(v) => found.push(decode(v)?),
None => missing.push(id.clone()),
}
}
Ok((found, missing))
}
}
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &C,
account_id: &Id,
) -> Result<State, MemoryError> {
Ok(State::from(
self.locked()
.await
.state(O::TYPE_NAME, account_id)
.to_string(),
))
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
caller: &C,
account_id: &Id,
params: jmap_server::ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<MemoryError>> {
let viewer = acting_user(caller, account_id);
let since_state = params.since_state;
let max_changes = params.max_changes;
let inner = self.locked().await;
let since: u64 = since_state
.as_ref()
.parse()
.map_err(|_| BackendChangesError::CannotCalculate)?;
let current = inner.state(O::TYPE_NAME, account_id);
if since > current {
return Err(BackendChangesError::CannotCalculate);
}
if O::TYPE_NAME == SceneAvatar::TYPE_NAME
&& inner.avatar_rules.contains_key(account_id.as_ref())
{
return inner
.avatar_changes_for(&viewer, account_id, since, max_changes)
.unwrap_or(Err(BackendChangesError::CannotCalculate));
}
let upto = match max_changes {
Some(max) => inner.changes_upto(O::TYPE_NAME, account_id, since, max)?,
None => current,
};
let net = inner.net_changes(O::TYPE_NAME, account_id, since, upto);
let bucket = |want: Change| -> Vec<Id> {
net.iter()
.filter(|(_, c)| *c == want)
.map(|(id, _)| id.clone())
.collect()
};
Ok(ChangesResult::new(
bucket(Change::Created),
bucket(Change::Updated),
bucket(Change::Destroyed),
upto < current,
State::from(upto.to_string()),
))
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
caller: &C,
account_id: &Id,
params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<MemoryError>> {
let caller = &acting_user(caller, account_id);
let QueryParams {
filter,
sort,
limit,
position,
anchor,
anchor_offset,
..
} = params;
let sort = sort.unwrap_or_default();
let inner = self.locked().await;
let ids = inner.query_ids::<O>(caller, account_id, filter, sort)?;
let total = ids.len() as u64;
let start = resolve_query_start(&ids, position, anchor, anchor_offset)
.map_err(BackendQueryError::Method)?;
let page = ids
.into_iter()
.skip(start)
.take(limit_or_max(limit))
.collect();
Ok(QueryResult::new(
page,
start as u64,
Some(total),
State::from(inner.state(O::TYPE_NAME, account_id).to_string()),
false,
))
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &C,
_account_id: &Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<MemoryError>> {
Err(BackendChangesError::CannotCalculate)
}
}
impl<C: MemoryCaller> SceneBackend for MemoryBackend<C> {
async fn scene_capability(
&self,
_caller: &C,
account_id: &Id,
) -> Result<SceneCapability, MemoryError> {
self.locked()
.await
.accounts
.get(account_id.as_ref())
.cloned()
.ok_or_else(|| MemoryError::new("account not registered"))
}
async fn blob_size(
&self,
_caller: &C,
account_id: &Id,
blob_id: &Id,
) -> Result<Option<u64>, MemoryError> {
Ok(self
.lock()
.blobs
.get(&(account_id.as_ref().to_owned(), blob_id.as_ref().to_owned()))
.copied())
}
async fn create_object<O, F>(
&self,
caller: &C,
account_id: &Id,
_create_id: &str,
build: F,
) -> Result<(Id, O), BackendSetError<MemoryError>>
where
O: SetObject + Send + Sync,
F: FnOnce(&Id) -> O + Send,
{
let caller = &acting_user(caller, account_id);
let id = Id::from(ulid::Ulid::new().to_string());
let mut value = serde_json::to_value(build(&id)).map_err(|e| {
BackendSetError::Other(MemoryError::serde("serialize created object", &e))
})?;
let mut inner = self.locked().await;
if O::TYPE_NAME == SceneAvatar::TYPE_NAME {
let avatar: SceneAvatar = decode(&value).map_err(BackendSetError::Other)?;
let stored = inner.enter(account_id, avatar, self.inner.deferring())?;
return Ok((id, decode(&stored).map_err(BackendSetError::Other)?));
}
if O::TYPE_NAME == SceneAsset::TYPE_NAME
&& let Some("a) = inner.storage_quota.get(account_id.as_ref())
{
let used: u64 = inner.all::<SceneAsset>(account_id).map(|a| a.size).sum();
let size = value.get("size").and_then(Value::as_u64).unwrap_or(0);
if used.saturating_add(size) > quota {
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::OverQuota)
.with_description("account asset storage quota exceeded"),
)));
}
}
if O::TYPE_NAME == SceneRegion::TYPE_NAME {
let max = inner
.accounts
.get(account_id.as_ref())
.and_then(|c| c.max_regions_per_account);
let held = inner.all::<SceneRegion>(account_id).count() as u64;
if max.is_some_and(|max| held >= max) {
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::OverQuota)
.with_description("maxRegionsPerAccount reached"),
)));
}
}
if O::TYPE_NAME == SceneObject::TYPE_NAME {
let max = inner
.accounts
.get(account_id.as_ref())
.and_then(|c| c.max_objects_per_region);
let region = value.get("regionId").and_then(Value::as_str);
let held = inner
.all::<SceneObject>(account_id)
.filter(|o| Some(o.region_id.as_ref()) == region)
.count() as u64;
if max.is_some_and(|max| held >= max) {
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::OverQuota)
.with_description("maxObjectsPerRegion reached"),
)));
}
value["ownerId"] = json!(caller);
}
let stored: O = decode(&value).map_err(BackendSetError::Other)?;
inner
.objects_mut(O::TYPE_NAME, account_id)
.insert(id.clone(), value);
inner.commit(
O::TYPE_NAME,
account_id,
vec![(id.clone(), Change::Created)],
);
Ok((id, stored))
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
_caller: &C,
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> Result<Option<O>, BackendSetError<MemoryError>> {
let mut inner = self.locked().await;
let mut current = inner
.objects(O::TYPE_NAME, account_id)
.and_then(|m| m.get(id))
.cloned()
.ok_or_else(not_found)?;
let was_left = current.get("leftAt").is_some_and(|l| !l.is_null());
let patch = serde_json::to_value(&patch)
.map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
let (Value::Object(patch), Value::Object(base)) = (patch, &mut current) else {
return Err(BackendSetError::SetError(Box::new(SetError::new(
SetErrorType::InvalidPatch,
))));
};
apply_patch_object(base, &patch).map_err(|e| {
BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
))
})?;
if O::deserialize(¤t).is_err() {
return Err(BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::InvalidProperties)
.with_description(format!("patched {} is invalid", O::TYPE_NAME)),
)));
}
let mut changes = Vec::new();
let mut regions = Vec::new();
let left_to = patch
.get("leftAt")
.filter(|_| O::TYPE_NAME == SceneAvatar::TYPE_NAME);
if let Some(to) = left_to {
let refuse = |description: &str| {
BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::InvalidProperties)
.with_description(description)
.with_properties(["leftAt"]),
))
};
match (to.is_null(), was_left) {
(false, true) => return Err(refuse("the avatar has already left")),
(true, false) => return Err(refuse("the avatar is present")),
(true, true) => {
let avatar: SceneAvatar = decode(¤t).map_err(BackendSetError::Other)?;
(changes, regions) =
inner.admit(account_id, &avatar, self.inner.deferring())?;
}
(false, false) => {}
}
regions.extend(
current
.get("regionId")
.and_then(Value::as_str)
.map(Id::from),
);
}
if let Some(previous) = inner.current(O::TYPE_NAME, account_id, id).cloned() {
inner.record_replace(O::TYPE_NAME, account_id, id, previous);
}
inner
.objects_mut(O::TYPE_NAME, account_id)
.insert(id.clone(), current);
changes.push((id.clone(), Change::Updated));
inner.commit(O::TYPE_NAME, account_id, changes);
if O::TYPE_NAME == SceneRegion::TYPE_NAME {
let before = inner.region(account_id, id).and_then(|r| r.observer_count);
inner.recount(account_id, std::slice::from_ref(id));
if let Some(after) = inner
.objects(O::TYPE_NAME, account_id)
.and_then(|m| m.get(id))
&& after.get("observerCount").and_then(Value::as_u64) != before
{
return Ok(Some(decode::<O>(after).map_err(BackendSetError::Other)?));
}
}
inner.recount(account_id, ®ions);
Ok(None)
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
_caller: &C,
account_id: &Id,
id: &Id,
) -> Result<(), BackendSetError<MemoryError>> {
let mut inner = self.locked().await;
let map = inner.objects_mut(O::TYPE_NAME, account_id);
if !map.contains_key(id) {
return Err(not_found());
}
let mut gone = vec![id.clone()];
if O::TYPE_NAME == SceneObject::TYPE_NAME {
let mut i = 0;
while let Some(parent) = gone.get(i).cloned() {
let children: Vec<Id> = map
.iter()
.filter(|(k, v)| {
v.get("parentId").and_then(Value::as_str) == Some(parent.as_ref())
&& !gone.contains(k)
})
.map(|(k, _)| k.clone())
.collect();
gone.extend(children);
i += 1;
}
}
let removed: Vec<(Id, Value)> = gone
.iter()
.filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
.collect();
for (k, v) in removed {
inner.record_destroy(O::TYPE_NAME, account_id, &k, v);
}
inner.commit(
O::TYPE_NAME,
account_id,
gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
);
if O::TYPE_NAME == SceneRegion::TYPE_NAME {
for contained in [SceneObject::TYPE_NAME, SceneAvatar::TYPE_NAME] {
let map = inner.objects_mut(contained, account_id);
let gone: Vec<Id> = map
.iter()
.filter(|(_, v)| v.get("regionId").and_then(Value::as_str) == Some(id.as_ref()))
.map(|(k, _)| k.clone())
.collect();
if gone.is_empty() {
continue;
}
let removed: Vec<(Id, Value)> = gone
.iter()
.filter_map(|k| map.remove(k).map(|v| (k.clone(), v)))
.collect();
for (k, v) in removed {
inner.record_destroy(contained, account_id, &k, v);
}
inner.commit(
contained,
account_id,
gone.into_iter().map(|k| (k, Change::Destroyed)).collect(),
);
}
}
Ok(())
}
async fn may_modify_asset(
&self,
caller: &C,
_account_id: &Id,
asset: &SceneAsset,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(asset.owner_id == *caller || self.locked().await.admins.contains(caller))
}
fn has_capability(&self, _caller: &C, account_id: &Id, uri: &str) -> bool {
self.lock()
.capabilities
.get(account_id.as_ref())
.is_some_and(|c| c.contains(uri))
}
async fn region_binding(
&self,
_caller: &C,
_account_id: &Id,
property: BindingProperty,
id: &Id,
) -> Result<BindingTarget, MemoryError> {
Ok(self
.lock()
.bindings
.get(&(property, id.as_ref().to_owned()))
.copied()
.unwrap_or(BindingTarget::Missing))
}
async fn channel_in_space(
&self,
_caller: &C,
_account_id: &Id,
channel_id: &Id,
space_id: &Id,
) -> Result<bool, MemoryError> {
Ok(self
.lock()
.channel_spaces
.contains(&(channel_id.as_ref().to_owned(), space_id.as_ref().to_owned())))
}
async fn may_update_region(
&self,
caller: &C,
_account_id: &Id,
region: &SceneRegion,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
}
async fn may_destroy_region(
&self,
caller: &C,
_account_id: &Id,
region: &SceneRegion,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(region.owner_id == *caller || self.locked().await.admins.contains(caller))
}
async fn may_modify_object(
&self,
caller: &C,
account_id: &Id,
object: &SceneObject,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, account_id);
let inner = self.locked().await;
Ok(inner.admins.contains(caller)
|| object.owner_id.as_ref() == Some(caller)
|| inner.owns_region(caller, account_id, &object.region_id))
}
async fn caller_user_id(&self, caller: &C, _account_id: &Id) -> Result<String, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(caller.clone())
}
async fn may_enter_region(
&self,
caller: &C,
_account_id: &Id,
region: &SceneRegion,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(!self
.lock()
.bans
.contains(&(region.id.as_ref().to_owned(), caller.clone())))
}
async fn may_access_region(
&self,
caller: &C,
account_id: &Id,
region_id: &Id,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, account_id);
Ok(self
.locked()
.await
.may_access(caller, account_id, region_id))
}
async fn is_object_visible(
&self,
caller: &C,
_account_id: &Id,
object: &SceneObject,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(!self
.lock()
.hidden
.contains(&(caller.clone(), object.id.clone())))
}
async fn is_user_blocked(&self, caller: &C, user_id: &str) -> Result<bool, MemoryError> {
let Some(caller) = caller.principal() else {
return Ok(false);
};
Ok(self
.lock()
.blocked
.contains(&(caller.as_ref().to_owned(), user_id.to_owned())))
}
async fn may_see_region_avatars(
&self,
caller: &C,
_account_id: &Id,
region_id: &Id,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, _account_id);
Ok(!self
.lock()
.hidden_avatars
.contains(&(caller.clone(), region_id.clone())))
}
async fn avatar_view(
&self,
caller: &C,
account_id: &Id,
avatar: &SceneAvatar,
) -> Result<AvatarView, MemoryError> {
let viewer = acting_user(caller, account_id);
let inner = self.locked().await;
let rules = inner.avatar_rules.get(account_id.as_ref());
Ok(inner.avatar_view(&viewer, account_id, avatar, rules))
}
fn supports_observe(&self, _caller: &C) -> bool {
self.lock().supports_observe
}
async fn may_observe_region(
&self,
_caller: &C,
_account_id: &Id,
region: &SceneRegion,
) -> Result<bool, MemoryError> {
Ok(!self.locked().await.declined_observers.contains(®ion.id))
}
async fn observer_accounts(&self, _caller: &C, _own: &Id) -> Result<Vec<Id>, MemoryError> {
let inner = self.locked().await;
if let Some(accounts) = &inner.observer_accounts {
return Ok(accounts.clone());
}
let mut accounts: Vec<Id> = inner
.accounts
.keys()
.map(|a| Id::from(a.as_str()))
.collect();
accounts.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
Ok(accounts)
}
async fn set_observing(
&self,
caller: &C,
account_id: &Id,
region_id: &Id,
observing: bool,
) -> Result<(), MemoryError> {
let user = acting_user(caller, account_id);
let mut inner = self.locked().await;
let key = (account_id.as_ref().to_owned(), region_id.clone());
let users = inner.observers.entry(key.clone()).or_default();
let n = users.entry(user.clone()).or_insert(0);
if observing {
*n += 1;
} else {
*n = n.saturating_sub(1);
if *n == 0 {
users.remove(&user);
}
}
if users.is_empty() {
inner.observers.remove(&key);
}
inner.recount(account_id, std::slice::from_ref(region_id));
Ok(())
}
async fn reserved_display_names(
&self,
_caller: &C,
_account_id: &Id,
) -> Result<Vec<String>, MemoryError> {
Ok(self.locked().await.reserved_names.clone())
}
async fn may_eject_avatar(
&self,
caller: &C,
account_id: &Id,
avatar: &SceneAvatar,
) -> Result<bool, MemoryError> {
let caller = &acting_user(caller, account_id);
let inner = self.locked().await;
Ok(inner.admins.contains(caller)
|| inner.owns_region(caller, account_id, &avatar.region_id))
}
async fn accept_interaction(
&self,
_caller: &C,
_account_id: &Id,
event: &SceneInteractionEvent,
) -> Result<bool, MemoryError> {
let mut inner = self.locked().await;
if inner.rate_limited.contains(&event.user_id) {
return Ok(false);
}
inner.interactions.push(event.clone());
Ok(true)
}
async fn accept_region_event(
&self,
caller: &C,
account_id: &Id,
event: &SceneRegionEvent,
) -> Result<bool, MemoryError> {
let caller = acting_user(caller, account_id);
let mut inner = self.locked().await;
if inner.region_event_limited.contains(&caller) {
return Ok(false);
}
inner.region_events.push(event.clone());
Ok(true)
}
fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &Id) -> bool {
[
SceneAsset::TYPE_NAME,
SceneRegion::TYPE_NAME,
SceneObject::TYPE_NAME,
SceneAvatar::TYPE_NAME,
]
.contains(&O::TYPE_NAME)
}
}
impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
async fn begin_set(
&self,
_caller: &C,
request: SetScopeRequest<'_>,
) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
Ok(self.inner.open(request, final_state_failures).await)
}
}
fn final_state_failures(before: &Inner, after: &Inner) -> Vec<DeferredFailure> {
let mut failures = Vec::new();
for (account, capability) in &after.accounts {
let account_id = Id::from(account.as_str());
let old: HashMap<Id, SceneAvatar> = before
.all::<SceneAvatar>(&account_id)
.map(|a| (a.id.clone(), a))
.collect();
let now: Vec<SceneAvatar> = after.all::<SceneAvatar>(&account_id).collect();
for a in &now {
let op = match old.get(&a.id) {
None => SetOp::Create(a.id.clone()),
Some(prev) if prev != a => SetOp::Update(a.id.clone()),
Some(_) => continue,
};
let Some(max) = capability.max_avatars_per_region else {
continue;
};
let present = now
.iter()
.filter(|b| b.region_id == a.region_id && b.left_at.is_none())
.count() as u64;
if a.left_at.is_none() && present > max {
failures.push(DeferredFailure::new(
op,
SetError::new(SetErrorType::OverQuota)
.with_description("maxAvatarsPerRegion reached"),
));
}
}
}
failures
}
#[cfg(test)]
mod memory_error_tests {
use super::MemoryError;
#[test]
fn serde_error_display_omits_offending_value() {
let canary = "alice@example.com";
let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
.expect_err("a string is not a u64");
assert!(
e.to_string().contains(canary),
"precondition: serde_json quotes the value"
);
let shown = MemoryError::serde("decode", &e).to_string();
assert!(!shown.contains(canary), "canary leaked: {shown}");
assert!(
shown.contains("decode") && shown.contains("Data"),
"{shown}"
);
}
}
#[cfg(test)]
mod clone_tests {
use super::MemoryBackend;
#[test]
fn clone_shares_store() {
let a = MemoryBackend::new();
let clone = a.clone();
let fresh = MemoryBackend::new();
a.add_admin("u1");
let admin = |b: &MemoryBackend| b.inner.lock_unscoped().admins.contains("u1");
assert!(admin(&clone), "a clone sees the original's writes");
assert!(!admin(&fresh), "a fresh backend does not");
}
}
#[cfg(test)]
mod max_changes_tests {
use super::*;
use jmap_scene_types::SceneObject as T;
fn with_creates(states: &[&[&str]]) -> MemoryBackend {
let backend = MemoryBackend::new();
let mut inner = backend.lock();
for ids in states {
let changes = ids
.iter()
.map(|s| (Id::from(*s), Change::Created))
.collect();
inner.commit(T::TYPE_NAME, &Id::from("acc1"), changes);
}
drop(inner);
backend
}
#[tokio::test]
async fn over_max_changes_pages_through_intermediate_state() {
let backend = with_creates(&[&["a"], &["b"], &["c"]]);
let first = changes(&backend, "0", 2).await.expect("first page");
assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
assert!(first.has_more_changes);
assert_eq!(first.new_state.as_ref(), "2");
let rest = changes(&backend, "2", 2).await.expect("second page");
assert_eq!(rest.created, [Id::from("c")]);
assert!(!rest.has_more_changes);
assert_eq!(rest.new_state.as_ref(), "3");
}
#[tokio::test]
async fn one_state_over_max_changes_cannot_calculate() {
let backend = with_creates(&[&["a", "b", "c"]]);
assert!(matches!(
changes(&backend, "0", 2).await,
Err(BackendChangesError::TooManyChanges { limit: 2 })
));
}
fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
ids
}
async fn changes(
backend: &MemoryBackend,
since: &str,
max: u64,
) -> Result<ChangesResult, BackendChangesError<<MemoryBackend as JmapAccounts>::Error>> {
backend
.get_changes::<T>(
&Id::from("caller"),
&Id::from("acc1"),
jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
)
.await
}
}