Skip to main content

jmap_chat_server/
memory.rs

1//! In-memory reference implementation of [`ChatBackend`].
2//!
3//! # This is a reference implementation, not production
4//!
5//! `MemoryBackend` is intended for three audiences:
6//!
7//! 1. **Workspace integration tests** — every `tests/*.rs` integration test
8//!    in this crate exercises method handlers against this backend.
9//! 2. **Downstream contributors** — a documented, complete, source-readable
10//!    implementation of the [`ChatBackend`] trait to
11//!    study when writing a real (database-backed) backend.
12//! 3. **Examples and smoke tests** — boot a real JMAP-for-Chat dispatcher
13//!    with one line of code, without standing up a database.
14//!
15//! It is **not** suitable for production: all state is held in `HashMap`s
16//! behind a `std::sync::Mutex`, persistence is not implemented, and a number
17//! of JMAP Chat draft edge cases are simplified (see source comments).
18//!
19//! # Feature flag and API stability
20//!
21//! This module is gated behind `feature = "memory"` and is **not** enabled
22//! by default. Its public API stability is opt-in: it may break across
23//! minor versions while the crate is pre-1.0.
24//!
25//! # Example
26//!
27//! ```rust,ignore
28//! use std::sync::Arc;
29//! use jmap_chat_server::{memory::MemoryBackend, register_chat_handlers};
30//! use jmap_server::Dispatcher;
31//!
32//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
33//! register_chat_handlers(&mut dispatcher, Arc::new(MemoryBackend::new()));
34//! ```
35//!
36//! # Concurrency
37//!
38//! `std::sync::Mutex` is used for simplicity. The `await_holding_lock`
39//! clippy lint is enabled module-wide and enforces that no lock guard
40//! is held across an `.await`. If a future change requires holding a
41//! guard across `.await`, switch to `tokio::sync::Mutex` rather than
42//! disabling the lint.
43//!
44//! Every `lock()` in this module ends in a bare `.unwrap()` on purpose.
45//! `Mutex::lock` fails only when another thread panicked while holding the
46//! guard, so the state behind it may be half-updated; that panic is
47//! already a bug in this module, and there is no consistent state to
48//! recover. Panicking again surfaces it instead of serving corrupt data.
49//! The crate's tests never poison the lock. A production backend that must
50//! survive a poisoned lock should implement the trait with its own locking
51//! rather than copy this pattern.
52//!
53//! # Tracking
54//!
55//! Promoted from `tests/common/mod.rs` per Beads issue JMAP-hwdv (epic)
56//! and JMAP-hwdv.3 (this crate, mirror of canonical JMAP-hwdv.1 in
57//! jmap-mail-server).
58
59#![allow(async_fn_in_trait)]
60#![deny(clippy::await_holding_lock)]
61
62mod history;
63
64use std::collections::{BTreeSet, HashMap, HashSet};
65use std::marker::PhantomData;
66use std::sync::{Arc, Mutex};
67
68use crate::{
69    AttachmentBlob, ChatAccessPolicy, ChatEvents, ChatLimits, ChatMessageLifecycle, ChatModeration,
70    ChatResolvers, ChatRestrictions, ChatSettings, ChatSpaces, ChatStore, EmojiSetOp,
71    InviteJoinRefusal, OpResult, SlowModeError, SpacePatchOp, SpacePolicy,
72    strip_unsupported_chat_push, validate_chat_push,
73};
74use jmap_chat_types::{ChatPermission, ChatPushCapability};
75use jmap_metadata_server::{
76    ChangedProperties, MetadataCondition, MetadataFilterError, MetadataOnlyChanges, SetKind,
77    changed_properties, check_metadata_depth, check_metadata_write, is_metadata_property,
78};
79use jmap_metadata_types::DataTypeMetadataInfo;
80use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
81use jmap_server::{
82    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
83    JmapAccounts, JmapObject, JmapReads, MemoryCaller, QueryChangesParams, QueryChangesResult,
84    QueryObject, QueryParams, QueryResult, SetError, SetErrorType, SetObject,
85};
86use jmap_server::{
87    BeginSetError, ConditionalBackend, DeferredFailure, MergePatchError, PatchPathError,
88    PushSubscriptionBackend, ScopedState, SetOp, SetScope, SetScopeRequest, StoredPushSubscription,
89    apply_patch_object, check_patch_paths, json_merge_patch, limit_or_max, now_utc_string,
90    resolve_query_start,
91};
92use jmap_types::{Id, PushSubscription, State};
93
94/// The most push subscriptions the single owner may hold at once.
95///
96/// RFC 8620 §8.6 (rfc8620.txt:4172-4175): "The server MUST limit the number
97/// of push subscriptions any one user may have". A create at the cap gets
98/// `overQuota`.
99///
100/// ponytail: one fixed cap for every caller. The upgrade path is a
101/// per-caller limit read from the backend's configuration.
102pub const MAX_PUSH_SUBSCRIPTIONS: usize = 50;
103
104// ---------------------------------------------------------------------------
105// Internal state
106// ---------------------------------------------------------------------------
107
108/// Per-ID fate tracker for RFC 8620 §5.2 ID deduplication across change log
109/// entries in one `/changes` window.
110///
111/// - created+updated → `Created`
112/// - created+destroyed → omitted (the client never knew the object), except
113///   for `Message`, which is reported as `Destroyed`
114/// - updated+destroyed → `Destroyed`
115/// - updated+updated → `Updated`
116///
117/// Mirrors the canonical jmap-mail-server `IdFate` enum.
118#[derive(Debug, Clone, Copy)]
119enum IdFate {
120    Created,
121    Updated,
122    Destroyed,
123}
124
125/// A change log entry for one state transition.
126#[derive(Clone, Debug)]
127struct ChangeEntry {
128    /// The state counter AFTER this change.
129    new_state: u64,
130    created: Vec<Id>,
131    updated: Vec<Id>,
132    destroyed: Vec<Id>,
133    /// The top-level properties this change altered on every id in
134    /// `updated`, or `None` when not known. Feeds
135    /// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges` and
136    /// `updatedProperties`.
137    updated_props: Option<BTreeSet<String>>,
138    /// Ids restored from object history (draft-ietf-jmap-object-history
139    /// §5.1).
140    restored: Vec<Id>,
141}
142
143impl ChangeEntry {
144    /// `true` for an update that changed only `metadata` and/or
145    /// `privateMetadata` (draft-ietf-jmap-metadata-05 §3.3).
146    fn is_metadata_only_update(&self) -> bool {
147        self.created.is_empty()
148            && self.destroyed.is_empty()
149            && self.updated_props.as_ref().is_some_and(|props| {
150                !props.is_empty() && props.iter().all(|p| is_metadata_property(p))
151            })
152    }
153}
154
155/// Shared inner state, behind a [`ScopedState`] so a conditional Foo/set
156/// can isolate and roll it back (docs/design/conditional.md §7).
157#[derive(Default, Clone)]
158struct Inner {
159    /// `type_name` → `account_id` → `id → serialized object`
160    objects: HashMap<&'static str, HashMap<String, HashMap<Id, serde_json::Value>>>,
161    /// `type_name` → `account_id` → current state counter
162    states: HashMap<&'static str, HashMap<String, u64>>,
163    /// `type_name` → `account_id` → ordered change entries
164    change_log: HashMap<&'static str, HashMap<String, Vec<ChangeEntry>>>,
165    /// `type_name` → `account_id` → the oldest state `/changes` can still
166    /// start from, once [`MemoryBackend::with_change_log_limit`] has
167    /// dropped older entries. Absent: every state since creation.
168    change_log_floor: HashMap<&'static str, HashMap<String, u64>>,
169    /// Entries kept per type and account; `None` keeps all. Set via
170    /// [`MemoryBackend::with_change_log_limit`].
171    change_log_limit: Option<usize>,
172    /// Lifecycle and outbound events kept, each list separately; `None`
173    /// keeps all. Set via [`MemoryBackend::with_event_limit`].
174    event_limit: Option<usize>,
175    /// explicitly registered account ids (accounts may exist with no objects yet)
176    known_accounts: HashSet<String>,
177    /// Test-only override for [`ChatSettings::limits`]. `None` means use
178    /// [`ChatLimits::default`]. Set via
179    /// `MemoryBackend::set_limits_for_test`.
180    limits_override: Option<ChatLimits>,
181    /// `(account_id, blobId)` → stored blob metadata reported by
182    /// [`ChatResolvers::attachment_blob`]. Set via
183    /// `MemoryBackend::set_attachment_blob_for_test`.
184    attachment_blobs: HashMap<(String, Id), AttachmentBlob>,
185    /// Test-only override for [`ChatSettings::retains_edit_history`].
186    /// Set via `MemoryBackend::set_retains_edit_history_for_test`.
187    retains_edit_history: bool,
188    /// Test-only override for [`ChatSettings::maintains_unread_count`].
189    /// Set via `MemoryBackend::set_maintains_unread_count_for_test`.
190    maintains_unread_count: bool,
191    /// Test-only override for [`ChatSpaces::protect_last_admin`].
192    ///
193    /// Default `false` — opposite the trait default of `true` — so
194    /// existing tests that do not seed admin memberships are not
195    /// broken. Tests that exercise the protection path opt in via
196    /// `MemoryBackend::set_protect_last_admin_for_test`.
197    /// Production deployments override the trait method instead.
198    protect_last_admin: bool,
199    /// account id → owner's identity, served by
200    /// [`ChatSettings::owner_user_id`]. Set via
201    /// `MemoryBackend::set_owner_user_id_for_test`.
202    owner_user_ids: HashMap<String, String>,
203    /// Push subscriptions by id. Every caller acts as the one owner, so
204    /// every stored subscription belongs to every caller.
205    push_subscriptions: HashMap<Id, StoredPushSubscription>,
206    /// account id -> its `urn:ietf:params:jmap:chat:push` capability
207    /// object. Accounts not in the map do not advertise the capability.
208    /// Set via `MemoryBackend::set_chat_push_capability_for_test`.
209    chat_push_caps: HashMap<Id, ChatPushCapability>,
210    /// Served by [`ChatSpaces::space_extension_properties`]. Empty by
211    /// default. Set via
212    /// `MemoryBackend::set_space_extension_properties_for_test`.
213    space_extension_properties: &'static [&'static str],
214    /// Every lifecycle callback received, in call order. Drained via
215    /// `MemoryBackend::take_lifecycle_events_for_test`.
216    lifecycle_events: Vec<LifecycleEvent>,
217    /// Every [`ChatEvents::on_outbound_event`] received, in call order.
218    /// Drained via `MemoryBackend::take_outbound_events_for_test`.
219    outbound_events: Vec<crate::OutboundEvent>,
220    /// Permissions of the implicit `@everyone` role in every Space
221    /// without an entry in `space_everyone_permissions`.
222    /// Set via [`MemoryBackend::set_everyone_permissions`].
223    everyone_permissions: HashSet<ChatPermission>,
224    /// Space id → that Space's `@everyone` permissions.
225    /// Set via [`MemoryBackend::set_space_everyone_permissions`].
226    space_everyone_permissions: HashMap<String, HashSet<ChatPermission>>,
227    /// Source of every id this backend assigns; see [`Inner::mint_id`].
228    /// Shared, not snapshotted: an atomic rollback keeps the generator
229    /// moving forward, so ids stay increasing (rolled-back ids are
230    /// skipped).
231    ids: Arc<Mutex<ulid::Generator>>,
232    /// `type_name` → the draft-ietf-jmap-metadata-05 §1.2.1
233    /// [`DataTypeMetadataInfo`] set by [`MemoryBackend::with_metadata_info`].
234    /// A type without an entry does not have the metadata properties.
235    metadata_info: HashMap<&'static str, DataTypeMetadataInfo>,
236    /// The `urn:ietf:params:jmap:search` capability of every account, set
237    /// by [`MemoryBackend::with_search_capability`].
238    search: Option<jmap_search::SearchCapability>,
239    /// Object history, once `MemoryBackend::with_object_history` turns it
240    /// on.
241    history: Option<jmap_object_history_server::HistoryStore>,
242}
243
244/// One lifecycle callback received by the [`MemoryBackend`], as
245/// returned by [`MemoryBackend::drain_lifecycle_events`].
246#[non_exhaustive]
247#[derive(Debug, Clone, PartialEq)]
248pub enum LifecycleEvent {
249    /// [`ChatEvents::on_chat_destroyed`] with this Chat id.
250    ChatDestroyed(Id),
251    /// [`ChatEvents::on_space_destroyed`] with this Space id.
252    SpaceDestroyed(Id),
253    /// [`ChatEvents::on_space_ban_created`] with this ban.
254    SpaceBanCreated(jmap_chat_types::SpaceBan),
255}
256
257impl Inner {
258    /// A fresh ULID, greater than every id minted before it.
259    ///
260    /// The draft assigns ULIDs to Chats (L570), Messages (L675), Roles
261    /// and Categories (§Space/set `addRoles` / `addCategories`: "Server
262    /// assigns ULIDs"), and `unreadCount` / `unreadReplyCount` compare
263    /// Message ids lexicographically. A monotonic generator keeps that
264    /// order for ids minted within the same millisecond.
265    fn mint_id(&mut self) -> Id {
266        let ulid = self
267            .ids
268            .lock()
269            .unwrap_or_else(std::sync::PoisonError::into_inner)
270            .generate()
271            .expect("80 random ULID bits cannot overflow within one millisecond in practice");
272        Id::from(ulid.to_string())
273    }
274
275    /// The `@everyone` permissions of Space `space_id`.
276    fn everyone_for(&self, space_id: &str) -> &HashSet<ChatPermission> {
277        self.space_everyone_permissions
278            .get(space_id)
279            .unwrap_or(&self.everyone_permissions)
280    }
281
282    /// The `@everyone` permissions of the stored Space `space_val`.
283    fn everyone_in(&self, space_val: &serde_json::Value) -> &HashSet<ChatPermission> {
284        self.everyone_for(
285            space_val
286                .get("id")
287                .and_then(|v| v.as_str())
288                .unwrap_or_default(),
289        )
290    }
291
292    fn current_state(&self, type_name: &'static str, account_id: &str) -> u64 {
293        self.states
294            .get(type_name)
295            .and_then(|m| m.get(account_id))
296            .copied()
297            .unwrap_or(0)
298    }
299
300    fn bump_state(&mut self, type_name: &'static str, account_id: &str) -> u64 {
301        let entry = self
302            .states
303            .entry(type_name)
304            .or_default()
305            .entry(account_id.to_owned())
306            .or_insert(0);
307        *entry += 1;
308        *entry
309    }
310
311    /// The store for `type_name` in `account_id`, created empty on first
312    /// use. Pure storage: it never registers the account (bd:JMAP-ayoz.36);
313    /// mutations check `require_account` first.
314    fn objects_mut(
315        &mut self,
316        type_name: &'static str,
317        account_id: &str,
318    ) -> &mut HashMap<Id, serde_json::Value> {
319        self.objects
320            .entry(type_name)
321            .or_default()
322            .entry(account_id.to_owned())
323            .or_default()
324    }
325
326    /// `Err` unless `account_id` was registered. Creates and copies are
327    /// per-object mutations, not account lifecycle operations
328    /// (bd:JMAP-ayoz.2, JMAP-ayoz.36): one aimed at an unknown account fails
329    /// instead of registering it. The handlers answer `accountNotFound`
330    /// before this is reached; it guards direct backend callers.
331    fn require_account(&self, account_id: &str) -> Result<(), BackendSetError<MemoryError>> {
332        if self.known_accounts.contains(account_id) {
333            Ok(())
334        } else {
335            Err(BackendSetError::Other(MemoryError::new(format!(
336                "unknown account {account_id:?}"
337            ))))
338        }
339    }
340
341    /// `notFound` for an update or destroy in an account nobody registered:
342    /// it has no objects (RFC 8620 §5.3).
343    fn require_account_for_target(
344        &self,
345        account_id: &str,
346    ) -> Result<(), BackendSetError<MemoryError>> {
347        if self.known_accounts.contains(account_id) {
348            Ok(())
349        } else {
350            Err(BackendSetError::SetError(Box::new(SetError::new(
351                SetErrorType::NotFound,
352            ))))
353        }
354    }
355
356    fn objects_ref(
357        &self,
358        type_name: &'static str,
359        account_id: &str,
360    ) -> Option<&HashMap<Id, serde_json::Value>> {
361        self.objects.get(type_name).and_then(|m| m.get(account_id))
362    }
363
364    /// The change log of `type_name` in `account_id`, for the caller to
365    /// push one entry onto. With a [`MemoryBackend::with_change_log_limit`]
366    /// limit, the oldest entries are dropped first to leave room for it,
367    /// and the floor moves up to the newest dropped state.
368    fn change_log_mut(
369        &mut self,
370        type_name: &'static str,
371        account_id: &str,
372    ) -> &mut Vec<ChangeEntry> {
373        let limit = self.change_log_limit;
374        let log = self
375            .change_log
376            .entry(type_name)
377            .or_default()
378            .entry(account_id.to_owned())
379            .or_default();
380        if let Some(limit) = limit
381            && log.len() >= limit
382        {
383            let excess = log.len() + 1 - limit.max(1);
384            let n = excess.min(log.len());
385            let dropped_to = n.checked_sub(1).map(|i| log[i].new_state);
386            log.drain(..n);
387            if let Some(floor) = dropped_to {
388                let slot = self
389                    .change_log_floor
390                    .entry(type_name)
391                    .or_default()
392                    .entry(account_id.to_owned())
393                    .or_default();
394                *slot = (*slot).max(floor);
395            }
396        }
397        self.change_log
398            .entry(type_name)
399            .or_default()
400            .entry(account_id.to_owned())
401            .or_default()
402    }
403
404    /// Push `event` onto `list`, then drop the oldest beyond `limit`.
405    fn push_capped<T>(list: &mut Vec<T>, event: T, limit: Option<usize>) {
406        list.push(event);
407        if let Some(limit) = limit
408            && list.len() > limit
409        {
410            let excess = list.len() - limit;
411            list.drain(..excess);
412        }
413    }
414}
415
416// ---------------------------------------------------------------------------
417// MemoryBackend
418// ---------------------------------------------------------------------------
419
420/// A fully in-memory implementation of [`ChatBackend`](crate::ChatBackend).
421///
422/// Stores objects as serialized JSON; each mutation bumps a monotonic state
423/// counter and records a change log entry. Used as both the integration-test
424/// harness and the canonical example for backend implementors.
425///
426/// Cloning is cheap and **shared-state**; see the [`Clone`] impl.
427///
428/// `C` is the [`JmapAccounts::CallerCtx`]: [`Id`], the caller's Principal
429/// id, by default, or `()` for a deployment without identity. This
430/// backend keeps no per-user state, so every caller acts as the account
431/// owner; [`JmapAccounts::principal_id`] returns
432/// [`MemoryCaller::principal`].
433#[non_exhaustive]
434pub struct MemoryBackend<C = Id> {
435    inner: ScopedState<Inner>,
436    caller: PhantomData<fn() -> C>,
437}
438
439/// Manual `Clone` impl, not `#[derive(Clone)]`: cloning is **shared-state**.
440///
441/// A clone copies no data. The original and the clone hold `Arc::clone`s
442/// of the same `Mutex`-guarded store and observe each other's mutations, so
443/// one handle can seed or inspect state while another serves requests. This
444/// impl must never become a deep copy; for independent state construct a
445/// fresh [`MemoryBackend::new`] instead of calling `.clone()`.
446impl<C> Clone for MemoryBackend<C> {
447    fn clone(&self) -> Self {
448        Self {
449            inner: self.inner.clone(),
450            caller: PhantomData,
451        }
452    }
453}
454
455impl<C> Default for MemoryBackend<C> {
456    fn default() -> Self {
457        Self {
458            inner: ScopedState::new(Inner {
459                everyone_permissions: HashSet::from([ChatPermission::View, ChatPermission::Send]),
460                ..Inner::default()
461            }),
462            caller: PhantomData,
463        }
464    }
465}
466
467impl MemoryBackend {
468    /// Create a new, empty `MemoryBackend`.
469    ///
470    /// The implicit `@everyone` role grants `"view"` and `"send"` in every
471    /// Space; change that with [`set_everyone_permissions`](Self::set_everyone_permissions).
472    ///
473    /// Its callers are Principal ids (`C = Id`);
474    /// `MemoryBackend::<()>::default()` takes callers without identity.
475    pub fn new() -> Self {
476        Self::default()
477    }
478}
479
480impl<C: MemoryCaller> MemoryBackend<C> {
481    /// Give `data_type` the draft-ietf-jmap-metadata-05 `metadata`
482    /// property, configured by `info` (the [`DataTypeMetadataInfo`] of -05
483    /// §1.2.1). draft-atwood-jmap-chat-00 lets a server list `Chat`,
484    /// `Message` and `Space` in the capability's `dataTypes`.
485    ///
486    /// Without this call a type has no metadata: `Foo/set` rejects a
487    /// write to `metadata` or `privateMetadata` with `invalidProperties`
488    /// and `Foo/query` rejects a metadata filter condition with
489    /// `unsupportedFilter`. With it, `Foo/set` validates metadata writes
490    /// (-05 §3.2), `Foo/query` evaluates the -05 §3.6 conditions, and
491    /// `Foo/changes` honours `ignoreMetadataOnlyChanges` and reports
492    /// `updatedProperties` (-05 §3.3). Advertising the capability in the
493    /// session is the server's job: list `info` under `data_type` in the
494    /// account's `urn:ietf:params:jmap:metadata` `dataTypes`.
495    ///
496    /// None of the three types has a rights object or belongs to a
497    /// container with one (the Space permission model is not one, per
498    /// draft-atwood-jmap-chat-00 §Space), so -05 §4.1 asks only that the
499    /// account is not read-only, and this backend has no read-only
500    /// accounts: every metadata write passes rule 1's `maySetMetadata`
501    /// check (fail-open, JMAP-bghk).
502    ///
503    /// # Panics
504    ///
505    /// Panics if `data_type` is not `"Chat"`, `"Message"` or `"Space"`,
506    /// or if `info.supports_private` is true: this backend has no
507    /// per-user state to own `privateMetadata`
508    /// (-05 §2).
509    #[must_use]
510    pub fn with_metadata_info(self, data_type: &str, info: DataTypeMetadataInfo) -> Self {
511        let type_name = metadata_type_name(data_type).unwrap_or_else(|| {
512            panic!(
513                "MemoryBackend supports metadata only on Chat, Message and Space, not {data_type:?}"
514            )
515        });
516        assert!(
517            !info.supports_private,
518            "MemoryBackend does not support privateMetadata (supportsPrivate must be false)"
519        );
520        self.inner
521            .lock_unscoped()
522            .metadata_info
523            .insert(type_name, info);
524        self
525    }
526
527    /// Advertise JMAP Search (`urn:ietf:params:jmap:search`, crate-jmap
528    /// docs/specs/jmap-search.md) with `capability` for every account:
529    /// [`ChatSettings::search_capability`] returns it.
530    ///
531    /// When `capability` lists `"Message"` in `dataTypes`, `Message/query`
532    /// evaluates `where` over the account's Messages in Chats the owner
533    /// may view, each as its stored representation without `editHistory`
534    /// unless edit history is retained (as `Message/get` returns it), and
535    /// `$text` as a case-insensitive substring of `body`
536    /// (`i;unicode-casemap`). Advertising the capability in the session is
537    /// the server's job.
538    ///
539    /// ponytail: the computed `replyCount` and `unreadReplyCount`, which
540    /// `Message/get` fills in, are not stored, so a pointer to them is
541    /// missing. Upgrade path: compute them into the candidate.
542    #[must_use]
543    pub fn with_search_capability(self, capability: jmap_search::SearchCapability) -> Self {
544        self.inner.lock_unscoped().search = Some(capability);
545        self
546    }
547
548    /// Set the permissions of the implicit `@everyone` role, which every
549    /// member of every Space holds (draft-atwood-jmap-chat-00 §Space
550    /// Permission Resolution step 1). The draft does not say where they
551    /// are stored; this backend keeps one set for every Space without its
552    /// own set from [`set_space_everyone_permissions`](Self::set_space_everyone_permissions).
553    pub fn set_everyone_permissions(&self, permissions: HashSet<ChatPermission>) {
554        self.inner.lock_unscoped().everyone_permissions = permissions;
555    }
556
557    /// Set the permissions of the implicit `@everyone` role in Space
558    /// `space_id` only, replacing the [`set_everyone_permissions`](Self::set_everyone_permissions)
559    /// set there.
560    pub fn set_space_everyone_permissions(
561        &self,
562        space_id: &Id,
563        permissions: HashSet<ChatPermission>,
564    ) {
565        self.inner
566            .lock_unscoped()
567            .space_everyone_permissions
568            .insert(space_id.to_string(), permissions);
569    }
570
571    /// Test-only entry point that registers an account as known even
572    /// if it has no objects yet. Production callers must not use this
573    /// method; the API stability disclaimer on the `memory` feature
574    /// applies doubly here.
575    ///
576    /// The name is retained (not renamed to `register_account_for_test`)
577    /// for backward compatibility with the workspace's existing
578    /// integration test suite, which calls this method through the
579    /// public API surface. `#[doc(hidden)]` removes it from `cargo doc`
580    /// output so downstream consumers do not see it as a documented
581    /// part of the surface.
582    #[doc(hidden)]
583    pub fn register_account(&self, account_id: &Id) {
584        debug_assert!(
585            !account_id.as_ref().is_empty(),
586            "register_account: account_id must not be the empty string \
587             (RFC 8620 §1.2, bd:JMAP-dx0s)"
588        );
589        let mut inner = self.inner.lock_unscoped();
590        inner.known_accounts.insert(account_id.as_ref().to_owned());
591    }
592
593    /// Register `account_id` as known and return `self`, for
594    /// builder-style fixture setup. Until then the account is unknown
595    /// (`accountNotFound`, RFC 8620 §3.6.2).
596    ///
597    /// # Panics
598    ///
599    /// In debug builds, if `account_id` is the empty string (RFC 8620
600    /// §1.2, bd:JMAP-dx0s).
601    #[must_use]
602    pub fn with_account(self, account_id: &Id) -> Self {
603        self.register_account(account_id);
604        self
605    }
606
607    /// Seed a pre-existing object into the store without bumping the
608    /// state counter or recording a change-log entry. Test-fixture setup
609    /// only (to store an object as a logged create, use
610    /// [`insert_object`](Self::insert_object)); registers `account_id` as known. Mirrors
611    /// `jmap_mail_server::memory::MemoryBackend::seed_object`.
612    ///
613    /// `type_name` is the `TYPE_NAME` of a type this backend stores:
614    /// `"Chat"`, `"Message"`, `"Space"`, `"ChatContact"`, `"ReadPosition"`, `"CustomEmoji"`, `"SpaceInvite"`, `"SpaceBan"`, `"ChatBan"`, `"PresenceStatus"`.
615    ///
616    /// # Panics
617    ///
618    /// If `type_name` is not one of the names above, or `value` is not a
619    /// JSON object whose `id` string equals `id`.
620    pub fn seed_object(
621        &self,
622        account_id: &Id,
623        type_name: &'static str,
624        id: &Id,
625        value: serde_json::Value,
626    ) {
627        const KNOWN_TYPES: &[&str] = &[
628            jmap_chat_types::Chat::TYPE_NAME,
629            jmap_chat_types::Message::TYPE_NAME,
630            jmap_chat_types::Space::TYPE_NAME,
631            jmap_chat_types::ChatContact::TYPE_NAME,
632            jmap_chat_types::ReadPosition::TYPE_NAME,
633            jmap_chat_types::CustomEmoji::TYPE_NAME,
634            jmap_chat_types::SpaceInvite::TYPE_NAME,
635            jmap_chat_types::SpaceBan::TYPE_NAME,
636            jmap_chat_types::ChatBan::TYPE_NAME,
637            jmap_chat_types::PresenceStatus::TYPE_NAME,
638        ];
639        assert!(
640            KNOWN_TYPES.contains(&type_name),
641            "seed_object: type_name {type_name:?} is not one of the known \
642             TYPE_NAME values {KNOWN_TYPES:?}"
643        );
644        let obj = value.as_object().unwrap_or_else(|| {
645            panic!("seed_object: value must be a JSON object with an `id` field, got {value:?}")
646        });
647        let value_id = obj
648            .get("id")
649            .and_then(serde_json::Value::as_str)
650            .unwrap_or_else(|| {
651                panic!(
652                    "seed_object: value must contain an `id` string field; got value = {value:?}"
653                )
654            });
655        assert_eq!(
656            value_id,
657            id.as_ref(),
658            "seed_object: value's `id` field {value_id:?} does not match the \
659             `id` argument {id:?}"
660        );
661        let account = account_id.as_ref();
662        let mut inner = self.inner.lock_unscoped();
663
664        // Seeding is fixture setup: it registers the account (explicitly,
665        // since `objects_mut` no longer does, bd:JMAP-ayoz.36).
666        inner.known_accounts.insert(account.to_owned());
667        inner
668            .objects_mut(type_name, account)
669            .insert(id.clone(), value);
670    }
671
672    // -------------------------------------------------------------------
673    // Test-only helpers
674    //
675    // All methods in this section are `#[doc(hidden)]` and carry the
676    // "Production callers must not use this method; the API stability
677    // disclaimer on the `memory` feature applies doubly here" banner.
678    // The canonical-template pattern across the workspace's reference
679    // backends is `#[doc(hidden)] + descriptive name + banner` rather
680    // than a `_for_test` rename. Several existing methods here carry a
681    // `_for_test` suffix as a name-stability concession; new helpers
682    // SHOULD prefer descriptive names without the suffix per the
683    // canonical mail-server pattern (bd:JMAP-x2gd.49).
684    // -------------------------------------------------------------------
685
686    /// Test-only: flip the [`ChatSettings::retains_edit_history`] flag.
687    ///
688    /// Pass `true` to make `Message/get` return `editHistory` on
689    /// fetched messages, or `false` to omit it. The default is
690    /// `false`, matching the trait default (the reference backend
691    /// does not retain edit history out of the box). Production
692    /// callers must not use this method; the API stability disclaimer
693    /// on the `memory` feature applies doubly here.
694    #[doc(hidden)]
695    #[cfg(feature = "test-helpers")]
696    pub fn set_retains_edit_history_for_test(&self, retain: bool) {
697        let mut inner = self.inner.lock_unscoped();
698        inner.retains_edit_history = retain;
699    }
700
701    /// Test-only: flip the [`ChatSettings::maintains_unread_count`] flag.
702    ///
703    /// Pass `true` to make the handlers leave `Chat.unreadCount` to the
704    /// backend. The reference backend never updates the stored value,
705    /// so with `true` it stays as seeded. The default is `false`,
706    /// matching the trait default. Production callers must not use this
707    /// method; the API stability disclaimer on the `memory` feature
708    /// applies doubly here.
709    #[doc(hidden)]
710    #[cfg(feature = "test-helpers")]
711    pub fn set_maintains_unread_count_for_test(&self, value: bool) {
712        let mut inner = self.inner.lock_unscoped();
713        inner.maintains_unread_count = value;
714    }
715
716    /// Test-only: flip the [`ChatSpaces::protect_last_admin`] flag.
717    ///
718    /// Pass `true` to enable last-admin protection on Space patches,
719    /// or `false` to disable. The default is `false`, opposite
720    /// the trait default of `true` — this is intentional: production
721    /// deployments inherit the trait default; the reference backend
722    /// opts out so existing demo tests don't have to seed admin
723    /// memberships. Production callers must not use this method; the
724    /// API stability disclaimer on the `memory` feature applies
725    /// doubly here.
726    ///
727    /// See `bd:JMAP-g7wu.2.4.3` for the design rationale (last-admin
728    /// protection replacing the dropped `Space.ownerId` design).
729    #[doc(hidden)]
730    #[cfg(feature = "test-helpers")]
731    pub fn set_protect_last_admin_for_test(&self, value: bool) {
732        let mut inner = self.inner.lock_unscoped();
733        inner.protect_last_admin = value;
734    }
735
736    /// Queue `event` in the store, so an atomic rollback drops it with the
737    /// change that caused it; waits like any backend write.
738    async fn record_lifecycle_event(&self, event: LifecycleEvent) {
739        let mut inner = self.inner.lock().await;
740        let limit = inner.event_limit;
741        Inner::push_capped(&mut inner.lifecycle_events, event, limit);
742    }
743
744    /// Mint a fresh object id, as [`ChatStore::create_object`] does.
745    ///
746    /// For a wrapping backend that must act on the complete object before
747    /// it is stored (for example, to commit it elsewhere first): mint the
748    /// id, build the object, act, then store it with
749    /// [`insert_object`](Self::insert_object) or
750    /// [`insert_message`](Self::insert_message).
751    pub fn mint_id(&self) -> Id {
752        self.inner.lock_unscoped().mint_id()
753    }
754
755    /// Store `object` under its own `id` in `account_id` as a create: the
756    /// state advances and the change log records the id as created, as for
757    /// [`ChatStore::create_object`], with the same per-type uniqueness
758    /// checks. The id may be one the caller chose (such as a hash-derived
759    /// `ChatContact` id) or one from [`mint_id`](Self::mint_id).
760    ///
761    /// # Errors
762    ///
763    /// - `alreadyExists` naming the stored object when the id is taken, or
764    ///   when a per-type uniqueness contract (`ChatContact` `identity`,
765    ///   `CustomEmoji` `name`) is violated.
766    /// - [`BackendSetError::Other`] when `account_id` is not registered, or
767    ///   when `object` does not serialize to a JSON object with a
768    ///   non-empty `id` string.
769    pub async fn insert_object<O: SetObject + Send + Sync>(
770        &self,
771        account_id: &Id,
772        object: O,
773    ) -> Result<O, BackendSetError<MemoryError>> {
774        let val = serde_json::to_value(&object)
775            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;
776        let id = object_id_of(&val)?;
777        let mut inner = self.inner.lock().await;
778        reject_taken_id(&inner, O::TYPE_NAME, account_id, &id)?;
779        let defer = self.inner.deferring();
780        insert_created(&mut inner, O::TYPE_NAME, account_id, &id, val, defer)?;
781        Ok(object)
782    }
783
784    /// [`insert_object`](Self::insert_object) for an owner-composed
785    /// Message, also recording its
786    /// [`OutboundEvent::NewMessage`](crate::OutboundEvent::NewMessage) in
787    /// the same write, as [`ChatStore::create_message`] does.
788    ///
789    /// # Errors
790    ///
791    /// As [`insert_object`](Self::insert_object).
792    pub async fn insert_message(
793        &self,
794        account_id: &Id,
795        message: jmap_chat_types::Message,
796    ) -> Result<jmap_chat_types::Message, BackendSetError<MemoryError>> {
797        let val = serde_json::to_value(&message)
798            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;
799        let id = object_id_of(&val)?;
800        let mut inner = self.inner.lock().await;
801        reject_taken_id(&inner, "Message", account_id, &id)?;
802        let defer = self.inner.deferring();
803        insert_created(&mut inner, "Message", account_id, &id, val, defer)?;
804        let limit = inner.event_limit;
805        Inner::push_capped(
806            &mut inner.outbound_events,
807            crate::OutboundEvent::NewMessage {
808                chat_id: message.chat_id.clone(),
809                message_id: message.id.clone(),
810                sender_msg_id: message.sender_msg_id.clone(),
811            },
812            limit,
813        );
814        Ok(message)
815    }
816
817    /// Keep at most `limit` change-log entries (at least one) per data
818    /// type and account, dropping the oldest. A `Foo/changes` from a state older than the
819    /// oldest kept entry then fails with `cannotCalculateChanges` (RFC 8620
820    /// §5.2), and the client resyncs. Without a limit the log grows with
821    /// every change, which suits tests but not a long-running embedder.
822    #[must_use]
823    pub fn with_change_log_limit(self, limit: usize) -> Self {
824        self.inner.lock_unscoped().change_log_limit = Some(limit);
825        self
826    }
827
828    /// Keep at most `limit` of the recorded lifecycle events and of the
829    /// recorded outbound events (each list separately), dropping the
830    /// oldest. `0` records none. Without a limit both lists grow until
831    /// drained with [`drain_lifecycle_events`](Self::drain_lifecycle_events)
832    /// and [`drain_outbound_events`](Self::drain_outbound_events).
833    #[must_use]
834    pub fn with_event_limit(self, limit: usize) -> Self {
835        self.inner.lock_unscoped().event_limit = Some(limit);
836        self
837    }
838
839    /// Drain the lifecycle callbacks recorded so far
840    /// ([`ChatEvents::on_chat_destroyed`],
841    /// [`ChatEvents::on_space_destroyed`],
842    /// [`ChatEvents::on_space_ban_created`]), oldest first.
843    pub fn drain_lifecycle_events(&self) -> Vec<LifecycleEvent> {
844        std::mem::take(&mut self.inner.lock_unscoped().lifecycle_events)
845    }
846
847    /// Drain the [`ChatEvents::on_outbound_event`] events recorded so
848    /// far, oldest first.
849    pub fn drain_outbound_events(&self) -> Vec<crate::OutboundEvent> {
850        std::mem::take(&mut self.inner.lock_unscoped().outbound_events)
851    }
852
853    /// Test-only: drain the lifecycle callbacks received so far
854    /// ([`ChatEvents::on_chat_destroyed`],
855    /// [`ChatEvents::on_space_destroyed`],
856    /// [`ChatEvents::on_space_ban_created`]), oldest first.
857    #[doc(hidden)]
858    #[cfg(feature = "test-helpers")]
859    pub fn take_lifecycle_events_for_test(&self) -> Vec<LifecycleEvent> {
860        std::mem::take(&mut self.inner.lock_unscoped().lifecycle_events)
861    }
862
863    /// Test-only: drain the [`ChatEvents::on_outbound_event`] events
864    /// received so far, oldest first.
865    #[doc(hidden)]
866    #[cfg(feature = "test-helpers")]
867    pub fn take_outbound_events_for_test(&self) -> Vec<crate::OutboundEvent> {
868        std::mem::take(&mut self.inner.lock_unscoped().outbound_events)
869    }
870
871    /// Test-only: set the list returned by
872    /// [`ChatSpaces::space_extension_properties`], standing in for a
873    /// Space extension that owns those properties. Production callers
874    /// must not use this method; the API stability disclaimer on the
875    /// `memory` feature applies doubly here.
876    #[doc(hidden)]
877    #[cfg(feature = "test-helpers")]
878    pub fn set_space_extension_properties_for_test(&self, keys: &'static [&'static str]) {
879        let mut inner = self.inner.lock_unscoped();
880        inner.space_extension_properties = keys;
881    }
882
883    /// Test-only: set the owner's identity for `account_id`, as returned
884    /// by [`ChatSettings::owner_user_id`] (the `ownerUserId` Session
885    /// field). Unset accounts return `None`. Production callers must not
886    /// use this method; the API stability disclaimer on the `memory`
887    /// feature applies doubly here.
888    #[doc(hidden)]
889    #[cfg(feature = "test-helpers")]
890    pub fn set_owner_user_id_for_test(&self, account_id: &Id, owner_user_id: &str) {
891        let mut inner = self.inner.lock_unscoped();
892        inner
893            .owner_user_ids
894            .insert(account_id.as_ref().to_owned(), owner_user_id.to_owned());
895    }
896
897    /// Test-only: set whether `account_id` advertises
898    /// `urn:ietf:params:jmap:chat:push`, and with which capability object.
899    ///
900    /// `Some(cap)` advertises it; `None` withdraws it. Push subscription
901    /// create and update validate `chatPush` against these capabilities,
902    /// and list strips entries for accounts without one
903    /// (draft-atwood-jmap-chat-push-00 §PushSubscription Extension). No
904    /// account advertises it by default. Production callers must not use
905    /// this method; the API stability disclaimer on the `memory` feature
906    /// applies doubly here.
907    #[doc(hidden)]
908    #[cfg(feature = "test-helpers")]
909    pub fn set_chat_push_capability_for_test(
910        &self,
911        account_id: &Id,
912        cap: Option<ChatPushCapability>,
913    ) {
914        let mut inner = self.inner.lock_unscoped();
915        match cap {
916            Some(cap) => inner.chat_push_caps.insert(account_id.clone(), cap),
917            None => inner.chat_push_caps.remove(account_id),
918        };
919    }
920
921    /// Test-only: override the [`ChatLimits`] returned by
922    /// [`ChatSettings::limits`].
923    ///
924    /// Pass `Some(limits)` to install a custom cap structure, or `None`
925    /// to revert to [`ChatLimits::default`]. Used by count-limit
926    /// enforcement integration tests (bd:JMAP-g7wu.2.4.8) that need
927    /// tight caps to exercise the `overQuota` path without seeding
928    /// hundreds of objects. Production callers must not use this
929    /// method; the API stability disclaimer on the `memory` feature
930    /// applies doubly here.
931    #[doc(hidden)]
932    #[cfg(feature = "test-helpers")]
933    pub fn set_limits_for_test(&self, limits: Option<ChatLimits>) {
934        let mut inner = self.inner.lock_unscoped();
935        inner.limits_override = limits;
936    }
937
938    /// Test-only: record the stored blob behind `blob_id` in `account_id`
939    /// for [`ChatResolvers::attachment_blob`], or forget it with `None`.
940    ///
941    /// ponytail: the reference backend has no blob store, so it holds only
942    /// the size and digest; an unregistered `blobId` is reported as
943    /// unchecked (`Ok(Ok(None))`).
944    #[doc(hidden)]
945    #[cfg(feature = "test-helpers")]
946    pub fn set_attachment_blob_for_test(
947        &self,
948        account_id: &str,
949        blob_id: &str,
950        blob: Option<AttachmentBlob>,
951    ) {
952        let mut inner = self.inner.lock_unscoped();
953        let key = (account_id.to_owned(), Id::from(blob_id));
954        match blob {
955            Some(b) => inner.attachment_blobs.insert(key, b),
956            None => inner.attachment_blobs.remove(&key),
957        };
958    }
959
960    /// Test-only: directly inject a JSON-shaped object into the backend
961    /// store, bypassing the normal `create_object` validation/serde
962    /// round-trip and skipping change-log emission.
963    ///
964    /// This exists for integration tests that need to seed objects for
965    /// types whose `Chat/set` create path is not yet implemented (e.g.
966    /// channels — bd:JMAP-g7wu.2.4.4). Production callers must not use
967    /// this method; the API stability disclaimer on the `memory`
968    /// feature applies doubly here.
969    #[doc(hidden)]
970    #[cfg(feature = "test-helpers")]
971    pub fn insert_object_for_test(
972        &self,
973        type_name: &'static str,
974        account_id: &str,
975        id: &str,
976        value: serde_json::Value,
977    ) {
978        let mut inner = self.inner.lock_unscoped();
979        // Fixture setup registers the account, as `seed_object` does;
980        // `objects_mut` no longer does (bd:JMAP-ayoz.36).
981        inner.known_accounts.insert(account_id.to_owned());
982        inner
983            .objects_mut(type_name, account_id)
984            .insert(Id::from(id), value);
985    }
986
987    /// Test-only: return the first Category id stored on the given Space.
988    /// Used by Space/set Category tests that need to refer back to a
989    /// server-assigned category id. Production callers must not use
990    /// this method; the API stability disclaimer on the `memory`
991    /// feature applies doubly here.
992    ///
993    /// Panics if the Space has no categories or does not exist.
994    #[doc(hidden)]
995    pub fn first_category_id(&self, space_id: &Id) -> Id {
996        let inner = self.inner.lock_unscoped();
997        // Walk every account looking for this space id. Integration
998        // tests use a single account "a1" so the iteration is trivial.
999        for map in inner
1000            .objects
1001            .get("Space")
1002            .into_iter()
1003            .flat_map(HashMap::values)
1004        {
1005            if let Some(space) = map.get(space_id) {
1006                let cats = space
1007                    .get("categories")
1008                    .and_then(|v| v.as_array())
1009                    .expect("Space.categories must be an array");
1010                let id = cats
1011                    .first()
1012                    .and_then(|c| c.get("id"))
1013                    .and_then(|id| id.as_str())
1014                    .expect("Space has at least one category");
1015                return Id::from(id);
1016            }
1017        }
1018        panic!("Space {space_id} not found");
1019    }
1020
1021    /// Test-only: return a snapshot of the named Chat's JSON value.
1022    /// Used to assert cross-reference fields like `categoryId` after
1023    /// Space/set Category mutations have cascaded. Production callers
1024    /// must not use this method; the API stability disclaimer on the
1025    /// `memory` feature applies doubly here.
1026    ///
1027    /// Panics if the Chat does not exist.
1028    #[doc(hidden)]
1029    pub fn peek_chat(&self, chat_id: &Id) -> serde_json::Value {
1030        let inner = self.inner.lock_unscoped();
1031        for map in inner
1032            .objects
1033            .get("Chat")
1034            .into_iter()
1035            .flat_map(HashMap::values)
1036        {
1037            if let Some(chat) = map.get(chat_id) {
1038                return chat.clone();
1039            }
1040        }
1041        panic!("Chat {chat_id} not found");
1042    }
1043}
1044
1045/// Opaque storage-layer error returned by [`MemoryBackend`] operations.
1046///
1047/// Carries a human-readable description of the underlying failure
1048/// (serialization round-trip miss, account-not-registered race, etc.).
1049/// The description is intended for test failure messages and
1050/// diagnostic logging; it is not a stable wire-format identifier.
1051///
1052/// # Forward compatibility
1053///
1054/// This type is `#[non_exhaustive]` and uses a named-field shape so
1055/// future revisions can add structured context (error kind, source
1056/// reference, account id, etc.) without a breaking change. Outside-
1057/// crate construction goes through [`MemoryError::new`]; outside-crate
1058/// reads go through [`MemoryError::description`].
1059///
1060/// Mirrors the canonical jmap-mail-server `MemoryError` shape.
1061#[non_exhaustive]
1062#[derive(Debug)]
1063pub struct MemoryError {
1064    description: String,
1065}
1066
1067impl MemoryError {
1068    /// Construct a [`MemoryError`] from a human-readable description.
1069    pub fn new(description: impl Into<String>) -> Self {
1070        Self {
1071            description: description.into(),
1072        }
1073    }
1074
1075    /// Human-readable description of the underlying failure.
1076    pub fn description(&self) -> &str {
1077        &self.description
1078    }
1079
1080    /// Construct a [`MemoryError`] for a `serde_json` failure during
1081    /// `context` (the operation that failed).
1082    ///
1083    /// Only the error's [`serde_json::error::Category`] is kept. A serde
1084    /// data error quotes the offending value (`invalid type: string
1085    /// "alice@example.com", expected u64`), and the `JmapAccounts::Error`
1086    /// contract forbids PII and blob content in `Display` output
1087    /// (bd:JMAP-510h.37).
1088    pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
1089        Self::new(format!("{context}: serde_json {:?} error", e.classify()))
1090    }
1091}
1092
1093impl std::fmt::Display for MemoryError {
1094    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1095        write!(f, "MemoryBackend error: {}", self.description)
1096    }
1097}
1098
1099impl std::error::Error for MemoryError {}
1100
1101impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
1102    type Error = MemoryError;
1103    type CallerCtx = C;
1104
1105    /// [`MemoryCaller::principal`].
1106    fn principal_id(caller: &C) -> Option<&Id> {
1107        caller.principal()
1108    }
1109
1110    /// The info set by [`MemoryBackend::with_metadata_info`], the same for
1111    /// every account.
1112    fn metadata_info<O: JmapObject>(
1113        &self,
1114        _caller: &C,
1115        _account_id: &Id,
1116    ) -> Option<DataTypeMetadataInfo> {
1117        self.inner
1118            .lock_unscoped()
1119            .metadata_info
1120            .get(O::TYPE_NAME)
1121            .cloned()
1122    }
1123
1124    async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, Self::Error> {
1125        let inner = self.inner.lock().await;
1126        Ok(inner.known_accounts.contains(account_id.as_ref()))
1127    }
1128}
1129
1130impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
1131    async fn get_objects<O: GetObject + Send + Sync>(
1132        &self,
1133        _caller: &C,
1134        account_id: &Id,
1135        ids: Option<&[Id]>,
1136        _properties: Option<&[String]>,
1137    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1138        let inner = self.inner.lock().await;
1139        let map = inner.objects_ref(O::TYPE_NAME, account_id.as_ref());
1140
1141        match ids {
1142            None => {
1143                // Return all objects.
1144                let mut list = Vec::new();
1145                if let Some(m) = map {
1146                    for val in m.values() {
1147                        match O::deserialize(val) {
1148                            Ok(obj) => list.push(obj),
1149                            Err(e) => {
1150                                return Err(MemoryError::serde(
1151                                    format_args!("deserialize {}", O::TYPE_NAME),
1152                                    &e,
1153                                ));
1154                            }
1155                        }
1156                    }
1157                }
1158                Ok((list, vec![]))
1159            }
1160            Some(id_slice) => {
1161                let mut found = Vec::new();
1162                let mut not_found = Vec::new();
1163                for id in id_slice {
1164                    match map.and_then(|m| m.get(id)) {
1165                        Some(val) => match O::deserialize(val) {
1166                            Ok(obj) => found.push(obj),
1167                            Err(e) => {
1168                                return Err(MemoryError::serde(
1169                                    format_args!("deserialize {}", O::TYPE_NAME),
1170                                    &e,
1171                                ));
1172                            }
1173                        },
1174                        None => not_found.push(id.clone()),
1175                    }
1176                }
1177                Ok((found, not_found))
1178            }
1179        }
1180    }
1181
1182    async fn get_state<O: JmapObject + Send + Sync>(
1183        &self,
1184        _caller: &C,
1185        account_id: &Id,
1186    ) -> Result<State, Self::Error> {
1187        let inner = self.inner.lock().await;
1188        let n = inner.current_state(O::TYPE_NAME, account_id.as_ref());
1189        Ok(State::from(n.to_string()))
1190    }
1191
1192    async fn get_changes<O: JmapObject + Send + Sync>(
1193        &self,
1194        _caller: &C,
1195        account_id: &Id,
1196        params: jmap_server::ChangesParams<'_>,
1197    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1198        let since_state = params.since_state;
1199        let max_changes = params.max_changes;
1200        // draft-ietf-jmap-metadata-05 §3: jmap_server::handle_changes has
1201        // already folded a `using` without the capability into this flag.
1202        let mode = if params.ignore_metadata_only_changes {
1203            MetadataOnlyChanges::Ignore
1204        } else {
1205            MetadataOnlyChanges::Report
1206        };
1207        let inner = self.inner.lock().await;
1208
1209        let since_n: u64 = since_state
1210            .as_ref()
1211            .parse()
1212            .map_err(|_| BackendChangesError::CannotCalculate)?;
1213        // RFC 8620 §5.2 cannotCalculateChanges: the entries after
1214        // `since_n` were dropped by the change-log limit.
1215        if inner
1216            .change_log_floor
1217            .get(O::TYPE_NAME)
1218            .and_then(|m| m.get(account_id.as_ref()))
1219            .is_some_and(|&floor| since_n < floor)
1220        {
1221            return Err(BackendChangesError::CannotCalculate);
1222        }
1223
1224        let log = inner
1225            .change_log
1226            .get(O::TYPE_NAME)
1227            .and_then(|m| m.get(account_id.as_ref()))
1228            .map(Vec::as_slice)
1229            .unwrap_or(&[]);
1230
1231        // Collect entries with new_state > since_n.
1232        let mut relevant: Vec<&ChangeEntry> =
1233            log.iter().filter(|e| e.new_state > since_n).collect();
1234
1235        let current_state = inner.current_state(O::TYPE_NAME, account_id.as_ref());
1236
1237        // RFC 8620 §5.2: over maxChanges "the server SHOULD generate an
1238        // update to take the client to an intermediate state", and only
1239        // when "unable to calculate an intermediate state" return
1240        // cannotCalculateChanges. Whole entries are taken, oldest first,
1241        // while their ids fit; an entry's ids bound what it adds after the
1242        // dedup below. A metadata-only update under Ignore adds none: -05
1243        // §3.3 "Excluded ids do not count toward maxChanges". The first
1244        // entry alone over the limit has no intermediate state.
1245        let mut has_more = false;
1246        if let Some(max) = max_changes {
1247            let mut ids = 0u64;
1248            if let Some(cut) = relevant.iter().position(|e| {
1249                if !(mode == MetadataOnlyChanges::Ignore && e.is_metadata_only_update()) {
1250                    ids +=
1251                        (e.created.len() + e.updated.len() + e.destroyed.len() + e.restored.len())
1252                            as u64;
1253                }
1254                ids > max
1255            }) {
1256                if cut == 0 {
1257                    return Err(BackendChangesError::TooManyChanges { limit: max });
1258                }
1259                relevant.truncate(cut);
1260                has_more = true;
1261            }
1262        }
1263        let new_state = match relevant.last() {
1264            Some(e) if has_more => e.new_state,
1265            _ => current_state,
1266        };
1267
1268        let (created, updated, destroyed, window_props) =
1269            window_changes(&relevant, O::TYPE_NAME, mode);
1270
1271        // -05 §3.3 `updatedProperties`; no chat type has the RFC 8621
1272        // §2.2 count properties that only Mailbox/changes may list.
1273        let updated_properties = window_props.updated_properties(&updated, mode, &[]);
1274        Ok(ChangesResult::new(
1275            created,
1276            updated,
1277            destroyed,
1278            has_more,
1279            State::from(new_state.to_string()),
1280        )
1281        .with_updated_properties(updated_properties))
1282    }
1283
1284    async fn query_objects<O: QueryObject + Send + Sync>(
1285        &self,
1286        _caller: &C,
1287        account_id: &Id,
1288        params: QueryParams<'_, O>,
1289    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1290        let QueryParams {
1291            filter,
1292            sort,
1293            limit,
1294            position,
1295            anchor,
1296            anchor_offset,
1297            ..
1298        } = params;
1299        let inner = self.inner.lock().await;
1300
1301        // Serialize the generic filter to a serde_json::Value so we can
1302        // inspect it for type-specific filter keys; O is generic here, so
1303        // the typed `jmap_chat_types` filter-condition fields are not nameable.
1304        let filter_val: Option<serde_json::Value> =
1305            filter.and_then(|f| serde_json::to_value(f).ok());
1306        let sort_val: Option<serde_json::Value> = sort.and_then(|s| serde_json::to_value(s).ok());
1307        if let Some(fv) = &filter_val {
1308            check_metadata_filter(fv, inner.metadata_info.get(O::TYPE_NAME))?;
1309            check_where(fv, O::TYPE_NAME, inner.search.as_ref())?;
1310        }
1311
1312        let mut ids: Vec<Id> = inner
1313            .objects_ref(O::TYPE_NAME, account_id.as_ref())
1314            .map(|m| {
1315                let mut keys: Vec<Id> = m.keys().cloned().collect();
1316
1317                // RFC 8620 §5.5 `filter`, applied in-process; production
1318                // backends would push it into a database query.
1319                if let Some(ref fv) = filter_val {
1320                    keys.retain(|id| filter_matches(&inner, O::TYPE_NAME, &m[id], fv, account_id));
1321                }
1322
1323                if O::TYPE_NAME == "Message" {
1324                    // draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec
1325                    // 77c3474 L1301): "messages in channels the caller cannot
1326                    // view SHOULD be omitted"; done here by choice.
1327                    keys.retain(|id| message_listed(&inner, m.get(id), account_id));
1328                }
1329
1330                // draft-atwood-jmap-chat-00 §Space/query: "When the request
1331                // includes an `isPublic: true` filter condition, the server
1332                // MUST include in the result `ids` array the identifiers of
1333                // Spaces for which the caller is not a member but which have
1334                // both `isPublic: true` and `isPubliclyPreviewable: true`."
1335                // Any other non-member Space is left out, as Space/get treats
1336                // a non-previewable one as not found. The condition may sit
1337                // inside a FilterOperator; the filter has already been
1338                // applied, so a revealed Space also matches all of it.
1339                if O::TYPE_NAME == "Space" {
1340                    let want_public = filter_val.as_ref().is_some_and(has_is_public_true);
1341                    keys.retain(|id| space_listed(&m[id], account_id, want_public));
1342                }
1343
1344                keys.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
1345                // RFC 8620 §5.5 `sort`; the stable sort keeps id order
1346                // for ties.
1347                if let Some(comparators) = sort_val.as_ref().and_then(|v| v.as_array()) {
1348                    keys.sort_by(|a, b| compare_by_sort(&m[a], &m[b], comparators));
1349                }
1350                keys
1351            })
1352            .unwrap_or_default();
1353
1354        let total = ids.len() as u64;
1355        let query_state = State::from(
1356            inner
1357                .current_state(O::TYPE_NAME, account_id.as_ref())
1358                .to_string(),
1359        );
1360
1361        // RFC 8620 §5.5 position / anchor / anchorOffset.
1362        let start = resolve_query_start(&ids, position, anchor, anchor_offset)
1363            .map_err(BackendQueryError::Method)?;
1364
1365        ids = ids[start..]
1366            .iter()
1367            .take(limit_or_max(limit))
1368            .cloned()
1369            .collect();
1370
1371        Ok(QueryResult::new(
1372            ids,
1373            start as u64,
1374            Some(total),
1375            query_state,
1376            true,
1377        ))
1378    }
1379
1380    /// Returns the changes to a `/query` result set since `since_query_state`.
1381    ///
1382    /// RFC 8620 §5.6: `/queryChanges` reports changes to the results of
1383    /// the same query, so `filter` and `sort` are applied by re-running
1384    /// [`Self::query_objects`], which also hides Messages in Chats the
1385    /// caller cannot view and Spaces the caller may not see: an id that
1386    /// `/query` omits is never announced in `added`. `removed` holds the
1387    /// destroyed ids and the updated ids that no longer match. Mirrors the
1388    /// canonical `jmap-mail-server` `MemoryBackend::query_changes`.
1389    ///
1390    /// ponytail: only the queried type's change log is read, so a Message
1391    /// hidden or revealed by a Chat membership change (no Message change)
1392    /// is not reported; a backend that needs this logs such Messages as
1393    /// updated.
1394    async fn query_changes<O: QueryObject + Send + Sync>(
1395        &self,
1396        caller: &C,
1397        account_id: &Id,
1398        params: QueryChangesParams<'_, O>,
1399    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1400        let QueryChangesParams {
1401            since_query_state,
1402            filter,
1403            sort,
1404            max_changes,
1405            ..
1406        } = params;
1407        let changes = self
1408            .get_changes::<O>(
1409                caller,
1410                account_id,
1411                jmap_server::ChangesParams::new(since_query_state).max_changes(max_changes),
1412            )
1413            .await?;
1414
1415        // The current result of the same query, unpaginated: `added`
1416        // indices are positions in it (RFC 8620 §5.6).
1417        let current = self
1418            .query_objects::<O>(
1419                caller,
1420                account_id,
1421                QueryParams::new().filter(filter).sort(sort),
1422            )
1423            .await
1424            .map_err(|e| match e {
1425                BackendQueryError::Other(e) => BackendChangesError::Other(e),
1426                // Changes to a query the server cannot run cannot be
1427                // calculated; the client's follow-up /query receives the
1428                // method error itself.
1429                _ => BackendChangesError::CannotCalculate,
1430            })?;
1431        let created_set: HashSet<&Id> = changes.created.iter().collect();
1432        let updated_set: HashSet<&Id> = changes.updated.iter().collect();
1433
1434        // Every destroyed or updated id: an update may touch a filter or
1435        // sort property, so RFC 8620 §5.6 requires the id in `removed` and,
1436        // if it still matches, reinserted via `added`.
1437        let mut removed: Vec<Id> = changes
1438            .destroyed
1439            .iter()
1440            .chain(changes.updated.iter())
1441            .cloned()
1442            .collect();
1443        removed.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
1444        removed.dedup();
1445
1446        // Created or updated ids that match the query now.
1447        let added: Vec<AddedItem> = current
1448            .ids
1449            .iter()
1450            .enumerate()
1451            .filter(|(_, id)| created_set.contains(id) || updated_set.contains(id))
1452            .map(|(pos, id)| AddedItem::new(id.clone(), pos as u64))
1453            .collect();
1454
1455        Ok(QueryChangesResult::new(
1456            since_query_state.clone(),
1457            changes.new_state,
1458            current.total,
1459            removed,
1460            added,
1461        ))
1462    }
1463}
1464
1465impl<C: MemoryCaller> ChatStore for MemoryBackend<C> {
1466    async fn create_object<O, F>(
1467        &self,
1468        _caller: &C,
1469        account_id: &Id,
1470        _create_id: &str,
1471        build: F,
1472    ) -> Result<(Id, O), BackendSetError<Self::Error>>
1473    where
1474        O: SetObject + Send + Sync,
1475        F: FnOnce(&Id) -> O + Send,
1476    {
1477        let server_id = self.inner.lock().await.mint_id();
1478        let stored_obj = build(&server_id);
1479        let val = serde_json::to_value(&stored_obj)
1480            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;
1481
1482        let mut inner = self.inner.lock().await;
1483        let defer = self.inner.deferring();
1484        insert_created(&mut inner, O::TYPE_NAME, account_id, &server_id, val, defer)?;
1485        Ok((server_id, stored_obj))
1486    }
1487
1488    /// Mints the id, builds and stores the Message, records the state
1489    /// change and pushes the `NewMessage` event under one lock
1490    /// acquisition, so no other caller observes the Message without its
1491    /// event or the event without its Message.
1492    async fn create_message<F>(
1493        &self,
1494        _caller: &C,
1495        account_id: &Id,
1496        _create_id: &str,
1497        build: F,
1498    ) -> Result<(Id, jmap_chat_types::Message), BackendSetError<Self::Error>>
1499    where
1500        F: FnOnce(&Id) -> jmap_chat_types::Message + Send,
1501    {
1502        let mut inner = self.inner.lock().await;
1503        let server_id = inner.mint_id();
1504        let message = build(&server_id);
1505        let val = serde_json::to_value(&message)
1506            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;
1507        let defer = self.inner.deferring();
1508        insert_created(&mut inner, "Message", account_id, &server_id, val, defer)?;
1509        let limit = inner.event_limit;
1510        Inner::push_capped(
1511            &mut inner.outbound_events,
1512            crate::OutboundEvent::NewMessage {
1513                chat_id: message.chat_id.clone(),
1514                message_id: message.id.clone(),
1515                sender_msg_id: message.sender_msg_id.clone(),
1516            },
1517            limit,
1518        );
1519        Ok((server_id, message))
1520    }
1521
1522    async fn update_object<O: SetObject + Send + Sync>(
1523        &self,
1524        _caller: &C,
1525        account_id: &Id,
1526        id: &Id,
1527        patch: O::Patch,
1528    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
1529        let mut inner = self.inner.lock().await;
1530        inner.require_account_for_target(account_id.as_ref())?;
1531        let (current, changed) = patched_copy::<O>(&mut inner, account_id.as_ref(), id, &patch)?;
1532
1533        // `CustomEmoji` uniqueness contract on `update_object`.
1534        if O::TYPE_NAME == "CustomEmoji"
1535            && !self.inner.deferring()
1536            && emoji_name_holder(&inner, account_id, &current, Some(id)).is_some()
1537        {
1538            return Err(BackendSetError::SetError(Box::new(
1539                SetError::new(SetErrorType::InvalidProperties).with_properties(["name"]),
1540            )));
1541        }
1542        // `CustomEmoji` image size cap on a `blobId` change. An unchanged
1543        // blob is not re-judged, so lowering the cap does not freeze
1544        // renames of existing emoji.
1545        if O::TYPE_NAME == "CustomEmoji" {
1546            let stored_blob = inner
1547                .objects_ref(O::TYPE_NAME, account_id.as_ref())
1548                .and_then(|m| m.get(id))
1549                .and_then(|e| e.get("blobId"));
1550            let limits = inner.limits_override.unwrap_or_default();
1551            if current.get("blobId") != stored_blob
1552                && emoji_blob_over_cap(&inner, account_id, &current, &limits)
1553            {
1554                return Err(over_quota_error(crate::emoji::EMOJI_TOO_LARGE));
1555            }
1556        }
1557
1558        let unread_changed = if O::TYPE_NAME == "ReadPosition" {
1559            let old = inner
1560                .objects_ref(O::TYPE_NAME, account_id.as_ref())
1561                .and_then(|m| m.get(id))
1562                .cloned()
1563                .unwrap_or_default();
1564            roots_with_unread_change(&inner, account_id.as_ref(), &old, &current)
1565        } else {
1566            Vec::new()
1567        };
1568        // Object history: a Message deleted with `deletedAt` loses its
1569        // versions (chat-00 §Message, decision 22); anything else records
1570        // the version this update replaces.
1571        let previous = inner
1572            .objects_ref(O::TYPE_NAME, account_id.as_ref())
1573            .and_then(|m| m.get(id))
1574            .cloned();
1575        if O::TYPE_NAME == "Message" && current.get("deletedAt").is_some_and(|v| !v.is_null()) {
1576            inner.purge_message_history(account_id, id);
1577        } else if let (Some(h), Some(previous)) = (inner.history.as_mut(), previous) {
1578            h.record_replace(O::TYPE_NAME, account_id, id, previous);
1579        }
1580        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
1581        inner
1582            .objects_mut(O::TYPE_NAME, account_id.as_ref())
1583            .insert(id.clone(), current);
1584        inner
1585            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
1586            .push(ChangeEntry {
1587                new_state,
1588                created: vec![],
1589                updated: vec![id.clone()],
1590                destroyed: vec![],
1591                restored: vec![],
1592                updated_props: Some(changed),
1593            });
1594        record_thread_count_changes(&mut inner, account_id.as_ref(), unread_changed);
1595
1596        Ok(None)
1597    }
1598
1599    async fn destroy_object<O: SetObject + Send + Sync>(
1600        &self,
1601        _caller: &C,
1602        account_id: &Id,
1603        id: &Id,
1604    ) -> Result<(), BackendSetError<Self::Error>> {
1605        let mut inner = self.inner.lock().await;
1606        inner.require_account_for_target(account_id.as_ref())?;
1607
1608        // draft-atwood-jmap-chat-00 §Destroying a Space (jmap-chat-spec
1609        // 77c3474 L1391): "The caller SHOULD hold `"manage_space"`"; this
1610        // backend requires it by choice. Checked under the same lock hold as
1611        // the removal, as `apply_space_metadata_patch_impl` does.
1612        if O::TYPE_NAME == "Space"
1613            && let Some(space_val) = inner
1614                .objects_ref("Space", account_id.as_ref())
1615                .and_then(|m| m.get(id))
1616        {
1617            let caller_perms =
1618                caller_effective_permissions(space_val, account_id, inner.everyone_in(space_val))
1619                    .unwrap_or_default();
1620            if !caller_perms.contains(&ChatPermission::ManageSpace) {
1621                return Err(BackendSetError::SetError(Box::new(
1622                    SetError::new(SetErrorType::Forbidden).with_description(
1623                        "caller lacks required permission `manage_space` to destroy the Space",
1624                    ),
1625                )));
1626            }
1627        }
1628
1629        // The Space's Chats, before the cascade removes them.
1630        let space_chats: Vec<Id> = if O::TYPE_NAME == "Space" {
1631            inner
1632                .objects_ref("Chat", account_id.as_ref())
1633                .map(|chats| {
1634                    chats
1635                        .iter()
1636                        .filter(|(_, c)| {
1637                            c.get("spaceId").and_then(|v| v.as_str()) == Some(id.as_ref())
1638                        })
1639                        .map(|(k, _)| k.clone())
1640                        .collect()
1641                })
1642                .unwrap_or_default()
1643        } else {
1644            Vec::new()
1645        };
1646        let removed = if O::TYPE_NAME == "Message" {
1647            // Purges the Message's history (chat-00 §Message).
1648            hard_delete_message(&mut inner, account_id.as_ref(), id)
1649        } else {
1650            let last = inner
1651                .objects_mut(O::TYPE_NAME, account_id.as_ref())
1652                .remove(id);
1653            if let Some(last) = &last
1654                && O::TYPE_NAME != "Space"
1655                && let Some(h) = inner.history.as_mut()
1656            {
1657                h.record_destroy(O::TYPE_NAME, account_id, id, last.clone());
1658            }
1659            last.is_some()
1660        };
1661
1662        if !removed {
1663            return Err(BackendSetError::SetError(Box::new(SetError::new(
1664                SetErrorType::NotFound,
1665            ))));
1666        }
1667        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
1668        inner
1669            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
1670            .push(ChangeEntry {
1671                new_state,
1672                created: vec![],
1673                updated: vec![],
1674                destroyed: vec![id.clone()],
1675                restored: vec![],
1676                updated_props: None,
1677            });
1678        if O::TYPE_NAME == "Space" {
1679            destroy_space_channels(&mut inner, account_id.as_ref(), id);
1680            inner.purge_space_history(account_id, id, &space_chats);
1681        }
1682        if O::TYPE_NAME == "Chat" {
1683            destroy_read_positions(&mut inner, account_id.as_ref(), std::slice::from_ref(id));
1684        }
1685        Ok(())
1686    }
1687
1688    fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &jmap_types::Id) -> bool {
1689        true
1690    }
1691}
1692
1693impl<C: MemoryCaller> ChatSpaces for MemoryBackend<C> {
1694    async fn generate_invite_code(
1695        &self,
1696        _caller: &C,
1697        _account_id: &Id,
1698    ) -> Result<String, MemoryError> {
1699        // CSPRNG-backed invite code, per the contract documented on
1700        // `ChatSpaces::generate_invite_code` (bd:JMAP-sc1b.78, bd:JMAP-sc1b.93).
1701        //
1702        // 16 random bytes = 128 bits of entropy, hex-encoded to 32 chars.
1703        // Far above the 48-bit nanosecond-truncated value the original
1704        // implementation produced, and unguessable to a network attacker.
1705        //
1706        // `getrandom::fill` reads from the OS CSPRNG (e.g. `getrandom(2)` on
1707        // Linux, `RtlGenRandom` on Windows, `arc4random_buf` on BSD/Apple).
1708        // On the supported tier-1 targets it cannot fail except via a kernel
1709        // bug or missing entropy at very early boot; that is an `Err`, never
1710        // a predictable fallback, which is exactly the failure mode this fix
1711        // closes.
1712        let mut bytes = [0u8; 16];
1713        getrandom::fill(&mut bytes)
1714            .map_err(|e| MemoryError::new(format!("OS CSPRNG unavailable: {e}")))?;
1715        // Hex-encode without pulling in the `hex` crate.
1716        let mut out = String::with_capacity(bytes.len() * 2);
1717        for byte in bytes {
1718            // Standard hex encoding; `{:02x}` on a u8 cannot fail.
1719            use std::fmt::Write as _;
1720            let _ = write!(out, "{byte:02x}");
1721        }
1722        Ok(out)
1723    }
1724
1725    /// Reference implementation of [`ChatSpaces::join_space_with_invite`].
1726    ///
1727    /// Every check and both writes run under one hold of the backend
1728    /// lock, which is the atomic operation draft-atwood-jmap-chat-00
1729    /// §Space/join requires. All checks precede the first write, so a
1730    /// refusal or error leaves storage unchanged.
1731    async fn join_space_with_invite(
1732        &self,
1733        _caller: &C,
1734        account_id: &Id,
1735        invite_id: &Id,
1736        joined_at: &jmap_types::UTCDate,
1737    ) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
1738        let mut inner = self.inner.lock().await;
1739        let acct = account_id.as_ref();
1740
1741        let Some(stored) = inner
1742            .objects_ref("SpaceInvite", acct)
1743            .and_then(|m| m.get(invite_id))
1744        else {
1745            return Ok(Err(InviteJoinRefusal::NotFound));
1746        };
1747        let invite: jmap_chat_types::SpaceInvite = serde_json::from_value(stored.clone())
1748            .map_err(|e| MemoryError::serde("stored SpaceInvite", &e))?;
1749        if invite.max_uses.is_some_and(|max| invite.uses >= max) {
1750            return Ok(Err(InviteJoinRefusal::Exhausted));
1751        }
1752
1753        let Some(space) = inner
1754            .objects_mut("Space", acct)
1755            .get_mut(&invite.space_id)
1756            .and_then(serde_json::Value::as_object_mut)
1757        else {
1758            return Ok(Err(InviteJoinRefusal::NotFound));
1759        };
1760        let Some(members) = space
1761            .entry("members")
1762            .or_insert_with(|| serde_json::json!([]))
1763            .as_array_mut()
1764        else {
1765            return Err(MemoryError::new("stored Space members is not an array"));
1766        };
1767        if members
1768            .iter()
1769            .any(|m| m.get("id").and_then(|v| v.as_str()) == Some(acct))
1770        {
1771            return Ok(Err(InviteJoinRefusal::AlreadyMember));
1772        }
1773        members.push(serde_json::json!({
1774            "id": acct,
1775            "roleIds": [],
1776            "joinedAt": joined_at,
1777        }));
1778        if let Some(stored) = inner
1779            .objects_mut("SpaceInvite", acct)
1780            .get_mut(invite_id)
1781            .and_then(serde_json::Value::as_object_mut)
1782        {
1783            stored.insert(
1784                "uses".to_owned(),
1785                serde_json::json!(invite.uses.saturating_add(1)),
1786            );
1787        }
1788
1789        for (type_name, id) in [("Space", &invite.space_id), ("SpaceInvite", invite_id)] {
1790            let new_state = inner.bump_state(type_name, acct);
1791            inner.change_log_mut(type_name, acct).push(ChangeEntry {
1792                new_state,
1793                created: vec![],
1794                updated: vec![id.clone()],
1795                destroyed: vec![],
1796                restored: vec![],
1797                updated_props: None,
1798            });
1799        }
1800        Ok(Ok(()))
1801    }
1802
1803    /// Reference implementation of [`ChatSpaces::protect_last_admin`].
1804    ///
1805    /// Returns the test-only override set via
1806    /// `MemoryBackend::set_protect_last_admin_for_test` when set;
1807    /// otherwise returns `false`, **opposite** the trait default of
1808    /// `true`. See that method's documentation and `bd:JMAP-g7wu.2.4.3`
1809    /// for the rationale: production deployments inherit the trait
1810    /// default; the reference backend opts out so existing demo tests
1811    /// don't have to seed admin memberships.
1812    fn protect_last_admin(&self, _caller: &C, _account_id: &Id) -> bool {
1813        let inner = self.inner.lock_unscoped();
1814        inner.protect_last_admin
1815    }
1816
1817    /// Reference implementation of
1818    /// [`ChatSpaces::space_extension_properties`]: the list set via
1819    /// `MemoryBackend::set_space_extension_properties_for_test`, empty
1820    /// by default. Values are stored unvalidated.
1821    fn space_extension_properties(&self, _caller: &C, _account_id: &Id) -> &'static [&'static str] {
1822        let inner = self.inner.lock_unscoped();
1823        inner.space_extension_properties
1824    }
1825
1826    /// Reference implementation of [`ChatSpaces::apply_space_patch`].
1827    ///
1828    /// Dispatches each [`SpacePatchOp`] to a per-variant helper. All
1829    /// twelve variants are implemented: Category (bd:JMAP-g7wu.2.4.5),
1830    /// Channel (bd:JMAP-g7wu.2.4.4), and Role/Member
1831    /// (bd:JMAP-g7wu.2.4.3).
1832    ///
1833    /// The entire patch runs under one mutex acquisition, providing
1834    /// best-effort transactional semantics for the reference impl. A
1835    /// failure mid-way through the op vector does NOT roll back ops
1836    /// that already succeeded — they remain applied. **Exception:**
1837    /// the helper runs a pre-validation pass over the ops and rejects the whole patch up-front with a
1838    /// single `forbidden` [`SetError`] if any op would fail permission or
1839    /// role-hierarchy enforcement. This implements criterion 6
1840    /// "whole-patch reject on permission failure" from
1841    /// `bd:JMAP-g7wu.2.4.3`. Per-op failures with other error types
1842    /// (`NotFound`, `InvalidProperties`) keep the legacy per-op outcome
1843    /// shape. Production backends should wrap the sequence in a real
1844    /// transaction.
1845    ///
1846    /// # Caller identity
1847    ///
1848    /// The caller is the owner, whose member entry is the accountId
1849    /// (draft-atwood-jmap-chat-00 §Terminology), so permission and
1850    /// role-hierarchy gates resolve against `account_id`. They apply
1851    /// whether or not [`JmapAccounts::principal_id`] resolves an
1852    /// identity; this backend never consults it.
1853    ///
1854    /// # Change-log emission
1855    ///
1856    /// One consolidated change-log entry per affected type per call:
1857    ///
1858    /// - `Space`: one `updated` entry if any op mutated the host Space.
1859    /// - `Chat`: one entry combining all channels created, updated, and
1860    ///   destroyed by this patch. Same batching rationale as the Space
1861    ///   entry — keeps `Chat/changes` from amplifying state-token
1862    ///   rotations.
1863    /// - `Message`: one `destroyed` entry listing every Message
1864    ///   cascade-destroyed by `RemoveChannel`.
1865    ///
1866    /// Category-cascade Chat mutations (`apply_category_op` →
1867    /// `set_channel_category`) and the Channel variants both populate
1868    /// the per-type tracking sets, so a `Chat/changes` subscriber sees
1869    /// the cascade regardless of which Space/set patch key triggered
1870    /// it (bd:JMAP-g7wu.2.4.9 closed the original gap).
1871    async fn apply_space_patch(
1872        &self,
1873        _caller: &C,
1874        account_id: &Id,
1875        space_id: &Id,
1876        ops: Vec<SpacePatchOp>,
1877    ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
1878        let mut inner = self.inner.lock().await;
1879        apply_space_patch_impl(&mut inner, account_id, space_id, ops)
1880    }
1881
1882    /// Reference implementation of
1883    /// [`ChatSpaces::apply_space_metadata_patch`].
1884    ///
1885    /// Applies the JSON Merge Patch to the target Space's top-level
1886    /// metadata fields under a single mutex acquisition, with the
1887    /// `manage_space` permission gate applied atomically against the
1888    /// owner's member entry, mirroring the [`Self::apply_space_patch`]
1889    /// contract.
1890    ///
1891    /// See `bd:JMAP-g7wu.2.4.13`.
1892    async fn apply_space_metadata_patch(
1893        &self,
1894        _caller: &C,
1895        account_id: &Id,
1896        space_id: &Id,
1897        patch: jmap_chat_types::SpaceMetadataPatch,
1898    ) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
1899        let patch_map = space_metadata_patch_to_map(patch).map_err(BackendSetError::Other)?;
1900        let mut inner = self.inner.lock().await;
1901        apply_space_metadata_patch_impl(&mut inner, account_id, space_id, patch_map)
1902    }
1903
1904    /// The set from [`MemoryBackend::set_space_everyone_permissions`] for
1905    /// `space`, else the one from [`MemoryBackend::set_everyone_permissions`].
1906    async fn everyone_permissions(
1907        &self,
1908        _caller: &C,
1909        _account_id: &Id,
1910        space: &jmap_chat_types::Space,
1911    ) -> Result<HashSet<ChatPermission>, Self::Error> {
1912        Ok(self
1913            .inner
1914            .lock()
1915            .await
1916            .everyone_for(space.id.as_ref())
1917            .clone())
1918    }
1919}
1920
1921impl<C: MemoryCaller> SpacePolicy for MemoryBackend<C> {
1922    /// Reference implementation of [`SpacePolicy::may_set_custom_emoji`].
1923    ///
1924    /// Demonstration-only: returns `Ok(Ok(()))` unconditionally. The
1925    /// reference backend does not honor identity-scoped permissions
1926    /// because it treats every caller as the account owner, whatever
1927    /// `JmapAccounts::principal_id` returns. A meaningful permission
1928    /// model — e.g. "only members of the target Space may modify a
1929    /// Space-scoped emoji" — requires the production backend to
1930    /// override both `principal_id` and this method.
1931    ///
1932    /// Spec: draft-atwood-jmap-chat-00 commit `9344aec` (authorization
1933    /// for `CustomEmoji/set` is implementation-defined).
1934    async fn may_set_custom_emoji(
1935        &self,
1936        _caller: &C,
1937        _account_id: &Id,
1938        _target_space_id: Option<&Id>,
1939        _op: EmojiSetOp,
1940    ) -> Result<Result<(), SetError>, Self::Error> {
1941        Ok(Ok(()))
1942    }
1943
1944    /// Reference implementation of [`SpacePolicy::may_set_space_ban`].
1945    ///
1946    /// Implements draft-atwood-jmap-chat-00 §SpaceBan/set: each op
1947    /// "Requires `"ban"` permission in the Space." A Space that does not
1948    /// exist is permitted, matching the pinned-messages gate. The
1949    /// caller's member entry is `account_id` (draft §Terminology).
1950    async fn may_set_space_ban(
1951        &self,
1952        _caller: &C,
1953        account_id: &Id,
1954        space_id: &Id,
1955    ) -> Result<Result<(), SetError>, Self::Error> {
1956        let inner = self.inner.lock().await;
1957        let Some(space) = inner
1958            .objects_ref("Space", account_id.as_ref())
1959            .and_then(|m| m.get(space_id))
1960        else {
1961            return Ok(Ok(()));
1962        };
1963        Ok(
1964            if caller_effective_permissions(space, account_id, inner.everyone_in(space))
1965                .is_some_and(|perms| perms.contains(&ChatPermission::Ban))
1966            {
1967                Ok(())
1968            } else {
1969                Err(SetError::new(SetErrorType::Forbidden)
1970                    .with_description("caller lacks required permission `ban` in this Space"))
1971            },
1972        )
1973    }
1974
1975    /// Reference implementation of [`SpacePolicy::may_set_space_invite`].
1976    ///
1977    /// Implements draft-atwood-jmap-chat-00 §SpaceInvite/set: create
1978    /// "Requires `"manage_members"` permission"; destroy also permits
1979    /// "ownership of the invite", which is `createdBy` equal to
1980    /// `account_id` (draft §SpaceInvite.createdBy). A Space that does not
1981    /// exist is permitted, matching the ban gate.
1982    async fn may_set_space_invite(
1983        &self,
1984        _caller: &C,
1985        account_id: &Id,
1986        space_id: &Id,
1987        created_by: Option<&Id>,
1988    ) -> Result<Result<(), SetError>, Self::Error> {
1989        if created_by == Some(account_id) {
1990            return Ok(Ok(()));
1991        }
1992        let inner = self.inner.lock().await;
1993        let Some(space) = inner
1994            .objects_ref("Space", account_id.as_ref())
1995            .and_then(|m| m.get(space_id))
1996        else {
1997            return Ok(Ok(()));
1998        };
1999        Ok(
2000            if caller_effective_permissions(space, account_id, inner.everyone_in(space))
2001                .is_some_and(|perms| perms.contains(&ChatPermission::ManageMembers))
2002            {
2003                Ok(())
2004            } else {
2005                Err(SetError::new(SetErrorType::Forbidden).with_description(
2006                    "caller lacks required permission `manage_members` in this Space",
2007                ))
2008            },
2009        )
2010    }
2011
2012    /// Reference implementation of [`SpacePolicy::may_get_space_invite`].
2013    ///
2014    /// Implements draft-atwood-jmap-chat-00 §SpaceInvite/get: only a
2015    /// member of the invite's Space sees it, and only if it holds
2016    /// `manage_members` or created the invite (`createdBy` equal to
2017    /// `account_id`, the caller's member entry per draft §Terminology).
2018    /// An invite whose Space does not exist is visible, matching
2019    /// [`Self::may_set_space_invite`], which lets such an invite be
2020    /// created.
2021    async fn may_get_space_invite(
2022        &self,
2023        _caller: &C,
2024        account_id: &Id,
2025        invite: &jmap_chat_types::SpaceInvite,
2026    ) -> Result<bool, Self::Error> {
2027        let inner = self.inner.lock().await;
2028        let Some(space) = inner
2029            .objects_ref("Space", account_id.as_ref())
2030            .and_then(|m| m.get(&invite.space_id))
2031        else {
2032            return Ok(true);
2033        };
2034        Ok(
2035            caller_effective_permissions(space, account_id, inner.everyone_in(space)).is_some_and(
2036                |p| p.contains(&ChatPermission::ManageMembers) || invite.created_by == *account_id,
2037            ),
2038        )
2039    }
2040
2041    /// Reference implementation of [`SpacePolicy::may_get_space_ban`].
2042    ///
2043    /// Implements draft-atwood-jmap-chat-00 §SpaceBan/get: a holder of
2044    /// `ban` in the ban's Space sees it, and so does the banned user
2045    /// (`userId` equal to `account_id`). Everyone else does not. A ban
2046    /// whose Space does not exist is visible, matching
2047    /// [`Self::may_set_space_ban`], which lets such a ban be created.
2048    async fn may_get_space_ban(
2049        &self,
2050        _caller: &C,
2051        account_id: &Id,
2052        ban: &jmap_chat_types::SpaceBan,
2053    ) -> Result<bool, Self::Error> {
2054        if ban.user_id == *account_id {
2055            return Ok(true);
2056        }
2057        let inner = self.inner.lock().await;
2058        let Some(space) = inner
2059            .objects_ref("Space", account_id.as_ref())
2060            .and_then(|m| m.get(&ban.space_id))
2061        else {
2062            return Ok(true);
2063        };
2064        Ok(
2065            caller_effective_permissions(space, account_id, inner.everyone_in(space))
2066                .is_some_and(|p| p.contains(&ChatPermission::Ban)),
2067        )
2068    }
2069}
2070
2071impl<C: MemoryCaller> ChatAccessPolicy for MemoryBackend<C> {
2072    /// Reference implementation of [`ChatAccessPolicy::may_broadcast_mention`].
2073    ///
2074    /// Implements draft-atwood-jmap-chat-00 §`BroadcastMention`: a
2075    /// non-empty `broadcastMentions` array in a channel requires the
2076    /// [`ChatPermission::MentionBroadcast`]
2077    /// permission, resolved in channel `chat_id` per §Space Permission
2078    /// Resolution. The caller's member entry is `account_id` (draft
2079    /// §Terminology). A Space or Chat that does not exist is permitted,
2080    /// matching the ban gate.
2081    async fn may_broadcast_mention(
2082        &self,
2083        _caller: &C,
2084        account_id: &Id,
2085        space_id: &Id,
2086        chat_id: &Id,
2087    ) -> Result<Result<(), SetError>, Self::Error> {
2088        let inner = self.inner.lock().await;
2089        let space_exists = inner
2090            .objects_ref("Space", account_id.as_ref())
2091            .is_some_and(|m| m.contains_key(space_id));
2092        let Some(chat) = inner
2093            .objects_ref("Chat", account_id.as_ref())
2094            .and_then(|m| m.get(chat_id))
2095            .filter(|_| space_exists)
2096        else {
2097            return Ok(Ok(()));
2098        };
2099        Ok(
2100            if owner_channel_permissions(&inner, account_id, chat)
2101                .is_some_and(|perms| perms.contains(&ChatPermission::MentionBroadcast))
2102            {
2103                Ok(())
2104            } else {
2105                Err(SetError::new(SetErrorType::Forbidden).with_description(
2106                    "caller lacks required permission `mention_broadcast` in this channel",
2107                ))
2108            },
2109        )
2110    }
2111
2112    /// Reference implementation of [`ChatAccessPolicy::may_send_message`].
2113    ///
2114    /// Implements draft-atwood-jmap-chat-00 §Message/set: in a group Chat
2115    /// the owner's `ChatMember` entry (id = accountId) must exist; in a
2116    /// channel the owner must be a member of the containing Space and hold
2117    /// `"send"` after §Space Permission Resolution. A channel whose Space
2118    /// does not exist has no members, so the create is forbidden. Direct
2119    /// chats are not restricted. A Chat that does not exist is permitted
2120    /// so `create_object` surfaces the normal error.
2121    async fn may_send_message(
2122        &self,
2123        _caller: &C,
2124        account_id: &Id,
2125        chat_id: &Id,
2126    ) -> Result<Result<(), SetError>, Self::Error> {
2127        let inner = self.inner.lock().await;
2128        let Some(chat) = inner
2129            .objects_ref("Chat", account_id.as_ref())
2130            .and_then(|m| m.get(chat_id))
2131        else {
2132            return Ok(Ok(()));
2133        };
2134        let denied = match chat.get("kind").and_then(|v| v.as_str()) {
2135            Some("group") => {
2136                let is_member =
2137                    chat.get("members")
2138                        .and_then(|v| v.as_array())
2139                        .is_some_and(|members| {
2140                            members.iter().any(|m| {
2141                                m.get("id").and_then(|v| v.as_str()) == Some(account_id.as_ref())
2142                            })
2143                        });
2144                (!is_member).then_some("sender is not a member of this Chat")
2145            }
2146            Some("channel") => match owner_channel_permissions(&inner, account_id, chat) {
2147                None => Some("sender is not a member of the containing Space"),
2148                Some(perms) if !perms.contains(&ChatPermission::Send) => {
2149                    Some("sender lacks required permission `send` in this channel")
2150                }
2151                Some(_) => None,
2152            },
2153            _ => None,
2154        };
2155        Ok(match denied {
2156            Some(desc) => Err(SetError::new(SetErrorType::Forbidden).with_description(desc)),
2157            None => Ok(()),
2158        })
2159    }
2160
2161    /// Reference implementation of [`ChatAccessPolicy::may_view_chat`].
2162    ///
2163    /// Implements draft-atwood-jmap-chat-00 §Message/query: a channel's
2164    /// messages are visible only when the owner holds `"view"` there
2165    /// after §Space Permission Resolution. Other Chats, and Chats that
2166    /// do not exist, are visible. `query_objects` applies the same rule.
2167    async fn may_view_chat(
2168        &self,
2169        _caller: &C,
2170        account_id: &Id,
2171        chat_id: &Id,
2172    ) -> Result<bool, Self::Error> {
2173        let inner = self.inner.lock().await;
2174        Ok(owner_may_view_chat(&inner, account_id, chat_id))
2175    }
2176
2177    /// Reference implementation of [`ChatAccessPolicy::may_set_pinned_messages`].
2178    ///
2179    /// Implements draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`:
2180    /// group chats require the caller to be a member with role `admin`;
2181    /// direct chats permit the owner freely; channel chats require the
2182    /// [`ChatPermission::Pin`] permission, resolved in the
2183    /// channel per §Space Permission Resolution. A Chat that does not exist is permitted so `update_object`
2184    /// surfaces `notFound`.
2185    ///
2186    /// The caller is the owner, whose member entry is the accountId
2187    /// (draft §Terminology), so the gate looks up `account_id` in
2188    /// `members` whether or not [`JmapAccounts::principal_id`] resolves
2189    /// an identity.
2190    async fn may_set_pinned_messages(
2191        &self,
2192        _caller: &C,
2193        account_id: &Id,
2194        chat_id: &Id,
2195    ) -> Result<Result<(), SetError>, Self::Error> {
2196        let inner = self.inner.lock().await;
2197        let Some(chat) = inner
2198            .objects_ref("Chat", account_id.as_ref())
2199            .and_then(|m| m.get(chat_id))
2200        else {
2201            return Ok(Ok(()));
2202        };
2203        let denied = match chat.get("kind").and_then(|v| v.as_str()) {
2204            Some("direct") => None,
2205            Some("group") => (!is_group_admin(chat, account_id))
2206                .then_some("only group chat admins may modify pinnedMessageIds"),
2207            Some("channel") => {
2208                let has_pin = owner_channel_permissions(&inner, account_id, chat)
2209                    .is_some_and(|perms| perms.contains(&ChatPermission::Pin));
2210                (!has_pin).then_some("caller lacks required permission `pin` in this channel")
2211            }
2212            _ => Some("internal: Chat has no recognized kind"),
2213        };
2214        Ok(match denied {
2215            Some(desc) => Err(SetError::new(SetErrorType::Forbidden).with_description(desc)),
2216            None => Ok(()),
2217        })
2218    }
2219
2220    /// Reference implementation of [`ChatAccessPolicy::slow_mode_check`].
2221    ///
2222    /// Demonstration-only: this backend has no rate-tracker and always
2223    /// returns `Ok(())`. The kit defines the hook; production
2224    /// backends plug in their own per-(account, chat, caller) tracker
2225    /// and the SHOULD-exempt permission logic per
2226    /// draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` + commit
2227    /// `de60acb`.
2228    ///
2229    /// The override exists rather than relying on the trait's default
2230    /// `Ok(())` so the posture is explicit in the reference impl — a
2231    /// future contributor reading `MemoryBackend` cannot mistake the
2232    /// absence of a rate-tracker for an oversight.
2233    async fn slow_mode_check(
2234        &self,
2235        _caller: &C,
2236        _account_id: &Id,
2237        _chat_id: &Id,
2238    ) -> Result<(), SlowModeError> {
2239        Ok(())
2240    }
2241}
2242
2243impl<C: MemoryCaller> ChatRestrictions for MemoryBackend<C> {}
2244
2245impl<C: MemoryCaller> ChatModeration for MemoryBackend<C> {}
2246
2247impl<C: MemoryCaller> ChatMessageLifecycle for MemoryBackend<C> {
2248    /// Reference implementation of [`ChatMessageLifecycle::expire_message`].
2249    ///
2250    /// Hard-deletes the message from the in-memory store and appends a
2251    /// `Message` change-log entry recording the id as `destroyed`, so
2252    /// subsequent `Message/changes` calls see the expiry per
2253    /// draft-atwood-jmap-chat-00.
2254    ///
2255    /// If the message is already gone (e.g., a previous `expire_message`
2256    /// call or a cascade destroy already removed it), returns `Ok(())`
2257    /// without bumping state — the expiry is a no-op, consistent with
2258    /// the trait's idempotency contract.
2259    async fn expire_message(
2260        &self,
2261        _caller: &C,
2262        account_id: &Id,
2263        message_id: &Id,
2264    ) -> Result<(), Self::Error> {
2265        let mut inner = self.inner.lock().await;
2266
2267        if hard_delete_message(&mut inner, account_id.as_ref(), message_id) {
2268            let new_state = inner.bump_state("Message", account_id.as_ref());
2269            inner
2270                .change_log_mut("Message", account_id.as_ref())
2271                .push(ChangeEntry {
2272                    new_state,
2273                    created: vec![],
2274                    updated: vec![],
2275                    destroyed: vec![message_id.clone()],
2276                    restored: vec![],
2277                    updated_props: None,
2278                });
2279        }
2280        Ok(())
2281    }
2282
2283    /// Reference implementation of [`ChatMessageLifecycle::read_and_burn_message`].
2284    ///
2285    /// Validates the patch on a clone and hard-deletes the row under one
2286    /// hold of the backend lock, recording the id as `destroyed`. The
2287    /// patched copy is never stored: the row is removed in the same
2288    /// critical section, so only the deletion is observable. An invalid
2289    /// patch returns before any write.
2290    async fn read_and_burn_message(
2291        &self,
2292        _caller: &C,
2293        account_id: &Id,
2294        message_id: &Id,
2295        patch: jmap_types::PatchObject,
2296    ) -> Result<(), BackendSetError<Self::Error>> {
2297        let mut inner = self.inner.lock().await;
2298        let acct = account_id.as_ref();
2299        patched_copy::<jmap_chat_types::Message>(&mut inner, acct, message_id, &patch)?;
2300        hard_delete_message(&mut inner, acct, message_id);
2301        let new_state = inner.bump_state("Message", acct);
2302        inner.change_log_mut("Message", acct).push(ChangeEntry {
2303            new_state,
2304            created: vec![],
2305            updated: vec![],
2306            destroyed: vec![message_id.clone()],
2307            restored: vec![],
2308            updated_props: None,
2309        });
2310        Ok(())
2311    }
2312}
2313
2314impl<C: MemoryCaller> ChatEvents for MemoryBackend<C> {
2315    /// Records the call for
2316    /// `MemoryBackend::take_lifecycle_events_for_test`.
2317    fn on_chat_destroyed(
2318        &self,
2319        _caller: &C,
2320        _account_id: &Id,
2321        chat_id: &Id,
2322    ) -> impl std::future::Future<Output = ()> + Send {
2323        self.record_lifecycle_event(LifecycleEvent::ChatDestroyed(chat_id.clone()))
2324    }
2325
2326    /// Records the call for
2327    /// `MemoryBackend::take_lifecycle_events_for_test`.
2328    fn on_space_destroyed(
2329        &self,
2330        _caller: &C,
2331        _account_id: &Id,
2332        space_id: &Id,
2333    ) -> impl std::future::Future<Output = ()> + Send {
2334        self.record_lifecycle_event(LifecycleEvent::SpaceDestroyed(space_id.clone()))
2335    }
2336
2337    /// Records the call for
2338    /// `MemoryBackend::take_lifecycle_events_for_test`.
2339    fn on_space_ban_created(
2340        &self,
2341        _caller: &C,
2342        _account_id: &Id,
2343        ban: &jmap_chat_types::SpaceBan,
2344    ) -> impl std::future::Future<Output = ()> + Send {
2345        self.record_lifecycle_event(LifecycleEvent::SpaceBanCreated(ban.clone()))
2346    }
2347
2348    /// Records the event for
2349    /// `MemoryBackend::take_outbound_events_for_test`.
2350    fn on_outbound_event(
2351        &self,
2352        _caller: &C,
2353        _account_id: &Id,
2354        event: &crate::OutboundEvent,
2355    ) -> impl std::future::Future<Output = ()> + Send {
2356        let event = event.clone();
2357        async move {
2358            // Queued in the store: an atomic rollback drops it, so nothing
2359            // goes out for a change that never happened (§4.3).
2360            let mut inner = self.inner.lock().await;
2361            let limit = inner.event_limit;
2362            Inner::push_capped(&mut inner.outbound_events, event, limit);
2363        }
2364    }
2365}
2366
2367impl<C: MemoryCaller> ChatSettings for MemoryBackend<C> {
2368    /// Reference implementation of [`ChatSettings::limits`].
2369    ///
2370    /// Returns the test-only override set via
2371    /// `MemoryBackend::set_limits_for_test` when present, else falls
2372    /// back to [`ChatLimits::default`]. Production backends ignore the
2373    /// override knob and read from their own per-account
2374    /// configuration.
2375    fn limits(&self, _caller: &C, _account_id: &Id) -> ChatLimits {
2376        let inner = self.inner.lock_unscoped();
2377        inner.limits_override.unwrap_or_default()
2378    }
2379
2380    /// Reference implementation of [`ChatSettings::retains_edit_history`].
2381    ///
2382    /// Returns the test-only override set via
2383    /// `MemoryBackend::set_retains_edit_history_for_test` when set;
2384    /// otherwise returns `false`, matching the trait default. The
2385    /// reference backend does not retain edit history out of the box.
2386    ///
2387    /// Spec: draft-atwood-jmap-chat-00 commit `0783fc4`.
2388    fn retains_edit_history(&self) -> bool {
2389        let inner = self.inner.lock_unscoped();
2390        inner.retains_edit_history
2391    }
2392
2393    fn maintains_unread_count(&self) -> bool {
2394        let inner = self.inner.lock_unscoped();
2395        inner.maintains_unread_count
2396    }
2397
2398    /// Reference implementation of [`ChatSettings::owner_user_id`].
2399    ///
2400    /// Returns the value set via
2401    /// `MemoryBackend::set_owner_user_id_for_test` for `account_id`,
2402    /// or `None` when unset.
2403    async fn owner_user_id(
2404        &self,
2405        _caller: &C,
2406        account_id: &Id,
2407    ) -> Result<Option<String>, Self::Error> {
2408        let inner = self.inner.lock().await;
2409        Ok(inner.owner_user_ids.get(account_id.as_ref()).cloned())
2410    }
2411
2412    /// Reference implementation of [`ChatSettings::search_capability`]:
2413    /// the capability set by [`MemoryBackend::with_search_capability`], for
2414    /// every account.
2415    async fn search_capability(
2416        &self,
2417        _caller: &C,
2418        _account_id: &Id,
2419    ) -> Result<Option<jmap_search::SearchCapability>, Self::Error> {
2420        Ok(self.inner.lock().await.search.clone())
2421    }
2422}
2423
2424impl<C: MemoryCaller> ChatResolvers for MemoryBackend<C> {
2425    /// Reference implementation of [`ChatResolvers::attachment_blob`]:
2426    /// reports the blob registered via
2427    /// `MemoryBackend::set_attachment_blob_for_test`, else `Ok(Ok(None))`.
2428    async fn attachment_blob(
2429        &self,
2430        _caller: &C,
2431        account_id: &Id,
2432        blob_id: &Id,
2433    ) -> Result<Result<Option<AttachmentBlob>, SetError>, Self::Error> {
2434        let inner = self.inner.lock().await;
2435        Ok(Ok(inner
2436            .attachment_blobs
2437            .get(&(account_id.as_ref().to_owned(), blob_id.clone()))
2438            .copied()))
2439    }
2440}
2441
2442/// Reference RFC 8620 §7.2 push subscription storage.
2443///
2444/// Single-owner mode (every caller acts as the owner): every subscription belongs to
2445/// the one caller, and [`MAX_PUSH_SUBSCRIPTIONS`] caps them all.
2446///
2447/// ponytail: `url` and `keys` are stored as plain values and dropped on
2448/// destroy without zeroization. This backend is demonstration-quality; the
2449/// secure-erase MUST (rfc8620.txt:3725-3727) is a consumer MUST stated on
2450/// [`PushSubscriptionBackend`].
2451///
2452/// ponytail: no creation rate limit and no `PushVerification` delivery. The
2453/// backend has no clock window and no HTTP client; both are consumer MUSTs
2454/// stated on [`PushSubscriptionBackend`].
2455impl<C: MemoryCaller> PushSubscriptionBackend for MemoryBackend<C> {
2456    const PUSH_SUBSCRIPTION_EXTENSION_PROPERTIES: &'static [&'static str] =
2457        &[crate::push::CHAT_PUSH];
2458
2459    async fn list_push_subscriptions(
2460        &self,
2461        _caller: &C,
2462    ) -> Result<Vec<StoredPushSubscription>, MemoryError> {
2463        let inner = self.inner.lock().await;
2464        Ok(inner
2465            .push_subscriptions
2466            .values()
2467            .cloned()
2468            .map(|mut stored| {
2469                strip_unsupported_chat_push(&mut stored.subscription.extra, &inner.chat_push_caps);
2470                stored
2471            })
2472            .collect())
2473    }
2474
2475    /// Store `new` under a fresh id with a 128-bit verification code, or
2476    /// return `overQuota` when [`MAX_PUSH_SUBSCRIPTIONS`] are already
2477    /// stored. The cap is checked under the same lock as the insert.
2478    /// A `chatPush` that fails [`validate_chat_push`] is rejected and
2479    /// nothing is stored.
2480    async fn create_push_subscription(
2481        &self,
2482        _caller: &C,
2483        mut new: PushSubscription,
2484    ) -> Result<StoredPushSubscription, BackendSetError<MemoryError>> {
2485        let expected_code = random_base64url_code();
2486        let mut inner = self.inner.lock().await;
2487        validate_chat_push(&new.extra, &inner.chat_push_caps).map_err(BackendSetError::SetError)?;
2488        // Under an atomic scope the cap is checked on the final state at
2489        // commit, so a create and a destroy in one call can replace a
2490        // subscription at the cap.
2491        if !self.inner.deferring() && inner.push_subscriptions.len() >= MAX_PUSH_SUBSCRIPTIONS {
2492            return Err(BackendSetError::SetError(Box::new(
2493                SetError::new(SetErrorType::OverQuota).with_description(format!(
2494                    "at most {MAX_PUSH_SUBSCRIPTIONS} push subscriptions per user"
2495                )),
2496            )));
2497        }
2498        let id = inner.mint_id();
2499        new.id = Some(id.clone());
2500        let stored = StoredPushSubscription {
2501            subscription: new,
2502            expected_code,
2503        };
2504        inner.push_subscriptions.insert(id, stored.clone());
2505        Ok(stored)
2506    }
2507
2508    /// Replace the stored subscription with `sub`. A `chatPush` that fails
2509    /// [`validate_chat_push`] is rejected and the stored one is kept.
2510    async fn update_push_subscription(
2511        &self,
2512        _caller: &C,
2513        sub: PushSubscription,
2514    ) -> Result<PushSubscription, BackendSetError<MemoryError>> {
2515        let mut inner = self.inner.lock().await;
2516        validate_chat_push(&sub.extra, &inner.chat_push_caps).map_err(BackendSetError::SetError)?;
2517        let stored = sub
2518            .id
2519            .as_ref()
2520            .and_then(|id| inner.push_subscriptions.get_mut(id))
2521            .ok_or_else(|| {
2522                BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
2523            })?;
2524        stored.subscription = sub.clone();
2525        Ok(sub)
2526    }
2527
2528    async fn destroy_push_subscription(
2529        &self,
2530        _caller: &C,
2531        id: &Id,
2532    ) -> Result<(), BackendSetError<MemoryError>> {
2533        let mut inner = self.inner.lock().await;
2534        inner
2535            .push_subscriptions
2536            .remove(id)
2537            .map(|_| ())
2538            .ok_or_else(|| {
2539                BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
2540            })
2541    }
2542}
2543
2544/// A push verification code: 16 bytes from the OS CSPRNG (128 bits),
2545/// encoded as unpadded base64url (RFC 4648 §5), always 22 characters.
2546///
2547/// RFC 8620 §7.2.2 (rfc8620.txt:3784-3786): the code "MUST contain
2548/// sufficient entropy to avoid the client being able to guess the code via
2549/// brute force." Panics if the OS CSPRNG fails, for the reason given in
2550/// `generate_invite_code`.
2551fn random_base64url_code() -> String {
2552    let mut bytes = [0u8; 16];
2553    getrandom::fill(&mut bytes).expect("OS CSPRNG must be available for push verification codes");
2554    base64url_unpadded(&bytes)
2555}
2556
2557/// Encode `bytes` as unpadded base64url (RFC 4648 §5).
2558fn base64url_unpadded(bytes: &[u8]) -> String {
2559    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2560    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
2561    for chunk in bytes.chunks(3) {
2562        let n = chunk
2563            .iter()
2564            .enumerate()
2565            .fold(0u32, |n, (i, &b)| n | u32::from(b) << (16 - 8 * i));
2566        for i in 0..=chunk.len() {
2567            out.push(char::from(ALPHABET[(n >> (18 - 6 * i)) as usize & 63]));
2568        }
2569    }
2570    out
2571}
2572
2573/// Stored `O` `id` with `patch` applied, validated but not stored, and
2574/// the top-level properties the patch changed.
2575///
2576/// `notFound` if `id` is absent; `invalidPatch` / `invalidProperties`
2577/// if the patch does not apply or the result is not a valid `O`. Works
2578/// on a clone, so an error leaves storage unchanged.
2579///
2580/// A patch that writes draft-ietf-jmap-metadata-05 `metadata` or
2581/// `privateMetadata` is checked in -05 §3.2 order: request-only patch
2582/// errors (`invalidPatch`), rule 1 (`notFound`), rules 2 and 3
2583/// ([`Inner::check_metadata_set`]), value-dependent patch errors, then
2584/// rule 4 (`maxDepth`) on the value as it would be stored.
2585fn patched_copy<O: SetObject>(
2586    inner: &mut Inner,
2587    account_id: &str,
2588    id: &Id,
2589    patch: &O::Patch,
2590) -> Result<(serde_json::Value, BTreeSet<String>), BackendSetError<MemoryError>> {
2591    let invalid_patch = |e: PatchPathError| {
2592        BackendSetError::SetError(Box::new(
2593            SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
2594        ))
2595    };
2596    let patch_val = serde_json::to_value(patch)
2597        .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
2598    let no_patch = serde_json::Map::new();
2599    let patch_map = patch_val.as_object().unwrap_or(&no_patch);
2600    // -05 §3.2: "Patch errors that can be determined from the request
2601    // alone (for example, two paths where one is a prefix of the other)
2602    // MUST be reported with "invalidPatch" before rule 1 is evaluated."
2603    check_patch_paths(patch_map).map_err(invalid_patch)?;
2604
2605    let existing = inner.objects_mut(O::TYPE_NAME, account_id).get(id).cloned();
2606
2607    let mut current = match existing {
2608        Some(v) => v,
2609        None => {
2610            return Err(BackendSetError::SetError(Box::new(SetError::new(
2611                SetErrorType::NotFound,
2612            ))));
2613        }
2614    };
2615
2616    // JMAP patch (RFC 8620 §5.3): keys are JSON Pointer paths, values
2617    // replace the pointed-to member wholesale. `apply_patch_object` is
2618    // all-or-nothing, and `current` is a clone of the stored value, so an
2619    // invalidPatch leaves storage unchanged. Its nesting DoS cap
2620    // (bd:JMAP-wlip.1, path segments + value depth) also surfaces here
2621    // as invalidPatch.
2622    let mut changed = BTreeSet::new();
2623    if let serde_json::Value::Object(base) = &mut current {
2624        // -05 §3.2 rules 2 and 3 run before the patch is applied.
2625        let metadata_info = if metadata_type_name(O::TYPE_NAME).is_some() {
2626            inner.check_metadata_set(O::TYPE_NAME, SetKind::Update, patch_map, Some(base))?
2627        } else {
2628            None
2629        };
2630        // -05 §2 `metadata` has "default: {}", so a `metadata/<namespace>`
2631        // pointer finds its parent.
2632        if metadata_info.is_some() {
2633            base.entry("metadata")
2634                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
2635        }
2636        let before = base.clone();
2637        // The value-dependent patch errors (missing parent, path through
2638        // an array or a Binary value) land here, after rule 3 and before rule 4 (-05 §3.2).
2639        apply_patch_object(base, patch_map).map_err(invalid_patch)?;
2640        if let Some(info) = &metadata_info {
2641            // -05 §3.2: "In an update, null is equivalent to {}"; the
2642            // patch removed the property instead.
2643            for property in ["metadata", "privateMetadata"] {
2644                if patch_map
2645                    .get(property)
2646                    .is_some_and(serde_json::Value::is_null)
2647                {
2648                    base.insert(
2649                        property.to_owned(),
2650                        serde_json::Value::Object(serde_json::Map::new()),
2651                    );
2652                }
2653            }
2654            // -05 §3.2 rule 4 runs on the value as it would be stored.
2655            check_metadata_depth(patch_map, base, info)
2656                .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
2657        }
2658        changed = changed_properties(&before, base);
2659    }
2660
2661    // Re-validate the patched copy as `O` before storing
2662    // (bd:JMAP-yk3i): a `null` or wrong-typed value on a required
2663    // property would otherwise be stored and fail every later `/get`.
2664    // The offending property is named only when the patch touches a
2665    // single top-level property; otherwise the description carries it.
2666    if let Err(e) = O::deserialize(&current) {
2667        let mut props: Vec<String> = patch_map
2668            .keys()
2669            .map(|k| {
2670                let top = k.split('/').next().unwrap_or(k);
2671                top.replace("~1", "/").replace("~0", "~")
2672            })
2673            .collect();
2674        props.sort();
2675        props.dedup();
2676        let mut err = SetError::new(SetErrorType::InvalidProperties)
2677            .with_description(format!("patched {} is invalid: {e}", O::TYPE_NAME));
2678        if props.len() == 1 {
2679            err = err.with_properties(props);
2680        }
2681        return Err(BackendSetError::SetError(Box::new(err)));
2682    }
2683    Ok((current, changed))
2684}
2685
2686/// The `TYPE_NAME` of the chat type named `data_type` if it is one this
2687/// backend can give draft-ietf-jmap-metadata-05 properties
2688/// (draft-atwood-jmap-chat-00 names `Chat`, `Message` and `Space`).
2689/// `ChatContact` has a `metadata` property of its own
2690/// (draft-atwood-jmap-chat-00 §4.4) and is not one of them.
2691fn metadata_type_name(data_type: &str) -> Option<&'static str> {
2692    [
2693        jmap_chat_types::Chat::TYPE_NAME,
2694        jmap_chat_types::Message::TYPE_NAME,
2695        jmap_chat_types::Space::TYPE_NAME,
2696    ]
2697    .into_iter()
2698    .find(|t| *t == data_type)
2699}
2700
2701fn invalid_metadata_property(property: &str, description: &str) -> BackendSetError<MemoryError> {
2702    BackendSetError::SetError(Box::new(
2703        SetError::new(SetErrorType::InvalidProperties)
2704            .with_properties([property])
2705            .with_description(description),
2706    ))
2707}
2708
2709impl Inner {
2710    /// draft-ietf-jmap-metadata-05 §3.2 rules 1 to 3 for a metadata write
2711    /// on a `type_name` object, before the write is applied. Returns the
2712    /// type's [`DataTypeMetadataInfo`] for the rule 4 check after applying,
2713    /// or `None` when `entry` writes no metadata.
2714    ///
2715    /// `entry` is the create object or update patch and `stored` the
2716    /// object before an update (`None` on create). Rule 1's `notFound` is
2717    /// the caller's: this backend has no read rights, so only a missing
2718    /// object is unreadable. Rule 1's `forbidden` never applies: see
2719    /// [`MemoryBackend::with_metadata_info`].
2720    fn check_metadata_set(
2721        &self,
2722        type_name: &'static str,
2723        kind: SetKind,
2724        entry: &serde_json::Map<String, serde_json::Value>,
2725        stored: Option<&serde_json::Map<String, serde_json::Value>>,
2726    ) -> Result<Option<DataTypeMetadataInfo>, BackendSetError<MemoryError>> {
2727        let Some(first) = entry.keys().find(|k| crate::helpers::is_metadata_key(k)) else {
2728            return Ok(None);
2729        };
2730        // -05 §1.2.1: an unlisted type "does not gain the metadata or
2731        // privateMetadata properties".
2732        let Some(info) = self.metadata_info.get(type_name) else {
2733            return Err(invalid_metadata_property(
2734                first,
2735                "metadata is not supported on this data type",
2736            ));
2737        };
2738        check_metadata_write(kind, entry, stored, info)
2739            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
2740        Ok(Some(info.clone()))
2741    }
2742}
2743
2744/// The store half of `create_object` and `create_message`: checks the
2745/// per-type create contracts, inserts `val` under `server_id`, advances
2746/// the state and records the change, all under the caller's lock. On
2747/// `Err` nothing is changed.
2748///
2749/// `defer`: an atomic conditional-02 scope is open on this task
2750/// ([`ScopedState::deferring`]), so the `CustomEmoji` name and per-Space
2751/// count checks are left to its commit (`final_state_failures`). The
2752/// `ChatContact` identity check is not: an identity cannot be given up
2753/// within one call (`ChatContact` destroy is refused), so the final state
2754/// could not differ.
2755/// The non-empty `id` string of a serialized object.
2756fn object_id_of(val: &serde_json::Value) -> Result<Id, BackendSetError<MemoryError>> {
2757    match val.get("id").and_then(serde_json::Value::as_str) {
2758        Some(id) if !id.is_empty() => Ok(Id::from(id)),
2759        _ => Err(BackendSetError::Other(MemoryError::new(
2760            "insert_object: object has no non-empty `id` string",
2761        ))),
2762    }
2763}
2764
2765/// `alreadyExists` when `id` is already stored for `type_name` in
2766/// `account_id`.
2767fn reject_taken_id(
2768    inner: &Inner,
2769    type_name: &'static str,
2770    account_id: &Id,
2771    id: &Id,
2772) -> Result<(), BackendSetError<MemoryError>> {
2773    if inner
2774        .objects_ref(type_name, account_id.as_ref())
2775        .is_some_and(|m| m.contains_key(id))
2776    {
2777        return Err(BackendSetError::SetError(Box::new(
2778            SetError::new(SetErrorType::AlreadyExists).with_existing_id(id.clone()),
2779        )));
2780    }
2781    Ok(())
2782}
2783
2784fn insert_created(
2785    inner: &mut Inner,
2786    type_name: &'static str,
2787    account_id: &Id,
2788    server_id: &Id,
2789    val: serde_json::Value,
2790    defer: bool,
2791) -> Result<(), BackendSetError<MemoryError>> {
2792    check_metadata_create(inner, type_name, &val)?;
2793
2794    // `ChatContact` uniqueness contract on create: at most
2795    // one ChatContact per `identity`, compared octet for octet.
2796    if type_name == "ChatContact" {
2797        let existing = inner
2798            .objects_ref(type_name, account_id.as_ref())
2799            .and_then(|m| {
2800                m.iter()
2801                    .find(|(_, c)| c.get("identity") == val.get("identity"))
2802            })
2803            .map(|(id, _)| id.clone());
2804        if let Some(existing) = existing {
2805            return Err(BackendSetError::SetError(Box::new(
2806                SetError::new(SetErrorType::AlreadyExists).with_existing_id(existing),
2807            )));
2808        }
2809    }
2810
2811    // `CustomEmoji` uniqueness contract on create.
2812    if type_name == "CustomEmoji"
2813        && !defer
2814        && let Some(existing) = emoji_name_holder(inner, account_id, &val, None)
2815    {
2816        return Err(BackendSetError::SetError(Box::new(
2817            SetError::new(SetErrorType::AlreadyExists).with_existing_id(existing),
2818        )));
2819    }
2820
2821    // `CustomEmoji` caps on create. The count is cross-object, so an
2822    // atomic scope leaves it to `final_state_failures`; the image size is
2823    // the emoji's own.
2824    if type_name == "CustomEmoji" {
2825        let limits = inner.limits_override.unwrap_or_default();
2826        let space_full = !defer
2827            && limits.max_custom_emoji_per_space.is_some_and(|max| {
2828                emoji_scope(&val).is_some_and(|space| {
2829                    emoji_count_in_space(inner, account_id.as_ref(), &space) >= u64::from(max)
2830                })
2831            });
2832        if space_full {
2833            return Err(over_quota_error(crate::emoji::TOO_MANY_EMOJI));
2834        }
2835        if emoji_blob_over_cap(inner, account_id, &val, &limits) {
2836            return Err(over_quota_error(crate::emoji::EMOJI_TOO_LARGE));
2837        }
2838    }
2839
2840    let reply_parent = if type_name == "Message" {
2841        stored_reply_parent(inner, account_id.as_ref(), &val)
2842    } else {
2843        None
2844    };
2845    inner.require_account(account_id.as_ref())?;
2846    let new_state = inner.bump_state(type_name, account_id.as_ref());
2847    inner
2848        .objects_mut(type_name, account_id.as_ref())
2849        .insert(server_id.clone(), val);
2850    inner
2851        .change_log_mut(type_name, account_id.as_ref())
2852        .push(ChangeEntry {
2853            new_state,
2854            created: vec![server_id.clone()],
2855            updated: vec![],
2856            destroyed: vec![],
2857            restored: vec![],
2858            updated_props: None,
2859        });
2860    record_thread_count_changes(
2861        inner,
2862        account_id.as_ref(),
2863        reply_parent.into_iter().collect(),
2864    );
2865    Ok(())
2866}
2867
2868/// draft-ietf-jmap-metadata-05 §3.2 checks for a created object `val` of
2869/// type `type_name`: rules 1 to 3 on its metadata properties, then rule 4
2870/// on the stored value. Types without the -05 properties pass unchecked.
2871fn check_metadata_create(
2872    inner: &Inner,
2873    type_name: &'static str,
2874    val: &serde_json::Value,
2875) -> Result<(), BackendSetError<MemoryError>> {
2876    let (Some(type_name), Some(obj)) = (metadata_type_name(type_name), val.as_object()) else {
2877        return Ok(());
2878    };
2879    let entry: serde_json::Map<String, serde_json::Value> = obj
2880        .iter()
2881        .filter(|(k, _)| is_metadata_property(k))
2882        .map(|(k, v)| (k.clone(), v.clone()))
2883        .collect();
2884    if let Some(info) = inner.check_metadata_set(type_name, SetKind::Create, &entry, None)? {
2885        check_metadata_depth(&entry, obj, &info)
2886            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
2887    }
2888    Ok(())
2889}
2890
2891/// Remove Message `id` and unpin it from its Chat under the same lock.
2892///
2893/// draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "When a pinned
2894/// Message is hard-deleted, the server MUST remove its id from this
2895/// list." Bumps `Chat` state when a pin is removed, and records the
2896/// `replyTo` parent's `replyCount` change; the caller records the
2897/// `Message` destroy. Returns whether the Message existed.
2898fn hard_delete_message(inner: &mut Inner, account_id: &str, id: &Id) -> bool {
2899    // chat-00 §Message (decision 22): a hard-deleted Message keeps no
2900    // versions, whatever removed it (destroy, expiry, burn on read).
2901    inner.purge_message_history(&Id::from(account_id), id);
2902    let Some(msg) = inner.objects_mut("Message", account_id).remove(id) else {
2903        return false;
2904    };
2905    let reply_parent = stored_reply_parent(inner, account_id, &msg);
2906    record_thread_count_changes(inner, account_id, reply_parent.into_iter().collect());
2907    let Some(chat_id) = msg.get("chatId").and_then(|v| v.as_str()).map(Id::from) else {
2908        return true;
2909    };
2910    let unpinned = inner
2911        .objects_mut("Chat", account_id)
2912        .get_mut(&chat_id)
2913        .and_then(|chat| chat.get_mut("pinnedMessageIds")?.as_array_mut())
2914        .is_some_and(|pins| {
2915            let before = pins.len();
2916            pins.retain(|v| v.as_str() != Some(id.as_ref()));
2917            pins.len() != before
2918        });
2919    if unpinned {
2920        let new_state = inner.bump_state("Chat", account_id);
2921        inner.change_log_mut("Chat", account_id).push(ChangeEntry {
2922            new_state,
2923            created: vec![],
2924            updated: vec![chat_id],
2925            destroyed: vec![],
2926            restored: vec![],
2927            updated_props: None,
2928        });
2929    }
2930    true
2931}
2932
2933/// The still-stored Message that `msg`'s `replyTo` names, whose
2934/// `replyCount` ("Count of messages in this chat with `replyTo` equal to
2935/// this message's `id`", draft-atwood-jmap-chat-00 §Message) changes when
2936/// `msg` is created or destroyed.
2937fn stored_reply_parent(inner: &Inner, account_id: &str, msg: &serde_json::Value) -> Option<Id> {
2938    let parent = Id::from(msg.get("replyTo")?.as_str()?);
2939    inner
2940        .objects_ref("Message", account_id)?
2941        .contains_key(&parent)
2942        .then_some(parent)
2943}
2944
2945/// Thread roots whose `unreadReplyCount` differs between `ReadPosition`
2946/// `old` and `new` (draft-atwood-jmap-chat-00 §Message: "Count of
2947/// replies to this message received after the owner's
2948/// `ReadPosition.lastReadMessageId` in this Chat", only when
2949/// "`threadRootId` is absent"). A reply is unread when the owner did not
2950/// send it (`senderId` is not the accountId) and its id sorts after
2951/// `lastReadMessageId`, or always when that is absent, as
2952/// `fill_reply_counts` computes it.
2953fn roots_with_unread_change(
2954    inner: &Inner,
2955    account_id: &str,
2956    old: &serde_json::Value,
2957    new: &serde_json::Value,
2958) -> Vec<Id> {
2959    let last_read = |rp: &serde_json::Value| {
2960        rp.get("lastReadMessageId")
2961            .and_then(|v| v.as_str())
2962            .map(str::to_owned)
2963    };
2964    let (old_read, new_read) = (last_read(old), last_read(new));
2965    if old_read == new_read {
2966        return Vec::new();
2967    }
2968    let chat_id = new.get("chatId");
2969    let Some(msgs) = inner.objects_ref("Message", account_id) else {
2970        return Vec::new();
2971    };
2972    let unread = |read: &Option<String>, id: &str| read.as_deref().is_none_or(|l| id > l);
2973    let mut roots: Vec<Id> = Vec::new();
2974    for (id, reply) in msgs {
2975        if reply.get("chatId") != chat_id
2976            || reply.get("senderId").and_then(|v| v.as_str()) == Some(account_id)
2977            || unread(&old_read, id.as_ref()) == unread(&new_read, id.as_ref())
2978        {
2979            continue;
2980        }
2981        let Some(parent) = reply.get("replyTo").and_then(|v| v.as_str()).map(Id::from) else {
2982            continue;
2983        };
2984        let is_root = msgs
2985            .get(&parent)
2986            .is_some_and(|p| p.get("threadRootId").is_none_or(serde_json::Value::is_null));
2987        if is_root && !roots.contains(&parent) {
2988            roots.push(parent);
2989        }
2990    }
2991    roots
2992}
2993
2994/// Record `ids` as updated Messages because a server-computed thread
2995/// count changed (see "State and change log" on
2996/// [`ChatStore::create_object`]). A no-op when `ids` is empty or
2997/// `supportsThreads` is off, since the counts are then not returned.
2998fn record_thread_count_changes(inner: &mut Inner, account_id: &str, ids: Vec<Id>) {
2999    if ids.is_empty() || !inner.limits_override.unwrap_or_default().supports_threads {
3000        return;
3001    }
3002    let new_state = inner.bump_state("Message", account_id);
3003    inner
3004        .change_log_mut("Message", account_id)
3005        .push(ChangeEntry {
3006            new_state,
3007            created: vec![],
3008            updated: ids,
3009            destroyed: vec![],
3010            restored: vec![],
3011            updated_props: None,
3012        });
3013}
3014
3015/// Destroy every channel Chat of Space `space_id`, and their Messages.
3016///
3017/// draft-atwood-jmap-chat-00 §Destroying a Space: "Cascades to all
3018/// channel Chats and their Messages. Hard-deletes all records; no
3019/// tombstones are retained." Records one `Chat` and one `Message`
3020/// change entry when anything was removed. The caller holds the lock
3021/// that destroyed the Space, so the cascade is atomic with it.
3022fn destroy_space_channels(inner: &mut Inner, account_id: &str, space_id: &Id) {
3023    let chat_ids: Vec<Id> = inner
3024        .objects_ref("Chat", account_id)
3025        .map(|chats| {
3026            chats
3027                .keys()
3028                .filter(|id| channel_belongs_to_space(inner, account_id, id, space_id))
3029                .cloned()
3030                .collect()
3031        })
3032        .unwrap_or_default();
3033    if chat_ids.is_empty() {
3034        return;
3035    }
3036    let message_ids: Vec<Id> = chat_ids
3037        .iter()
3038        .flat_map(|chat_id| scan_messages_in_chat(inner, account_id, chat_id))
3039        .collect();
3040    let msgs = inner.objects_mut("Message", account_id);
3041    for msg_id in &message_ids {
3042        msgs.remove(msg_id);
3043    }
3044    let chats = inner.objects_mut("Chat", account_id);
3045    for chat_id in &chat_ids {
3046        chats.remove(chat_id);
3047    }
3048    destroy_read_positions(inner, account_id, &chat_ids);
3049    let new_state = inner.bump_state("Chat", account_id);
3050    inner.change_log_mut("Chat", account_id).push(ChangeEntry {
3051        new_state,
3052        created: vec![],
3053        updated: vec![],
3054        destroyed: chat_ids,
3055        restored: vec![],
3056        updated_props: None,
3057    });
3058    if !message_ids.is_empty() {
3059        let new_state = inner.bump_state("Message", account_id);
3060        inner
3061            .change_log_mut("Message", account_id)
3062            .push(ChangeEntry {
3063                new_state,
3064                created: vec![],
3065                updated: vec![],
3066                destroyed: message_ids,
3067                restored: vec![],
3068                updated_props: None,
3069            });
3070    }
3071}
3072
3073/// Apply a [`SpacePatchOp`] sequence to the in-memory Space store.
3074///
3075/// This is the implementation core of
3076/// [`ChatSpaces::apply_space_patch`], whose trait method locks the
3077/// `Inner` mutex before invoking it. Permission gating and
3078/// role-position hierarchy resolve against the owner's member entry
3079/// `account_id` (draft-atwood-jmap-chat-00 §Terminology).
3080///
3081/// See `bd:JMAP-g7wu.2.4.3` for the acceptance criteria this
3082/// implements (criteria 1, 2, 4, 5, 6).
3083fn apply_space_patch_impl(
3084    inner: &mut Inner,
3085    account_id: &Id,
3086    space_id: &Id,
3087    ops: Vec<SpacePatchOp>,
3088) -> Result<Vec<OpResult>, BackendSetError<MemoryError>> {
3089    // Confirm the target Space exists before doing any work.
3090    if !inner
3091        .objects_ref("Space", account_id.as_ref())
3092        .is_some_and(|m| m.contains_key(space_id))
3093    {
3094        return Err(BackendSetError::SetError(Box::new(SetError::new(
3095            SetErrorType::NotFound,
3096        ))));
3097    }
3098
3099    // ---------------------------------------------------------------
3100    // Pre-validation: policy checks that, on failure, reject the WHOLE patch with a
3101    // single `forbidden` SetError. Per criterion 6 of
3102    // bd:JMAP-g7wu.2.4.3: "if any op in the patch is forbidden, the
3103    // WHOLE update for that Space id is rejected."
3104    //
3105    // Other failure shapes (NotFound on a non-existent role id,
3106    // InvalidProperties on a malformed payload) keep the legacy
3107    // per-op outcome — those are structural, not policy.
3108    // ---------------------------------------------------------------
3109    let protect_last_admin = inner.protect_last_admin;
3110    // Snapshot the Space for pre-validation reads.
3111    let space_snapshot = inner
3112        .objects_ref("Space", account_id.as_ref())
3113        .and_then(|m| m.get(space_id))
3114        .cloned()
3115        .ok_or_else(|| {
3116            BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
3117        })?;
3118    let everyone = inner.everyone_in(&space_snapshot).clone();
3119
3120    if let Err(e) = validate_space_patch_ops(
3121        &space_snapshot,
3122        account_id,
3123        &ops,
3124        protect_last_admin,
3125        &everyone,
3126    ) {
3127        return Err(BackendSetError::SetError(e));
3128    }
3129
3130    // Per-aggregate count limit check (bd:JMAP-x2gd.44 — backend-canonical
3131    // enforcement). The handler may have done a defense-in-depth pre-flight
3132    // check, but the backend MUST re-verify atomically with the mutation so
3133    // direct callers (admin tools, federation receivers, batch importers
3134    // that bypass `handle_space_set`) still see caps enforced.
3135    let limits = inner.limits_override.unwrap_or_default();
3136    if let Some(set_err) = check_count_caps(&space_snapshot, &ops, &limits) {
3137        return Err(BackendSetError::SetError(Box::new(set_err)));
3138    }
3139
3140    let mut results = Vec::with_capacity(ops.len());
3141    let mut effects = SpacePatchEffects::default();
3142
3143    // Draft §Space/set `removeMembers`: "If the member removing
3144    // themselves is the last member holding `"manage_space"` and other
3145    // members remain, leaving closes the Space: the server MUST set
3146    // `closedAt` ({{space}}) in the same operation." Record a leaving
3147    // `manage_space` holder here; the close is decided after the ops.
3148    // The owner removes themselves by the accountId (§Terminology).
3149    let leaving_space_manager = ops
3150        .iter()
3151        .any(|op| matches!(op, SpacePatchOp::RemoveMember(id) if id == account_id))
3152        && member_effective_permissions(&space_snapshot, account_id.as_ref(), &everyone)
3153            .is_some_and(|p| p.contains(&ChatPermission::ManageSpace));
3154
3155    for (op_index, op) in ops.into_iter().enumerate() {
3156        let outcome = apply_space_patch_op(inner, account_id.as_ref(), space_id, op, &mut effects);
3157        results.push(OpResult {
3158            op_index,
3159            outcome: outcome.map_err(|e| *e),
3160        });
3161    }
3162
3163    if leaving_space_manager && close_if_no_manager(inner, account_id, space_id, &everyone) {
3164        effects.space_mutated = true;
3165    }
3166    log_space_patch(inner, account_id.as_ref(), space_id, effects);
3167    Ok(results)
3168}
3169
3170/// What the ops of one [`apply_space_patch_impl`] call changed, for its
3171/// change-log entries.
3172#[derive(Default)]
3173struct SpacePatchEffects {
3174    /// Whether the Space itself changed.
3175    space_mutated: bool,
3176    /// Channel Chats created.
3177    chats_created: Vec<Id>,
3178    /// Chats updated.
3179    chats_updated: HashSet<Id>,
3180    /// Channel Chats destroyed.
3181    chats_destroyed: Vec<Id>,
3182    /// Messages destroyed with their channel.
3183    messages_destroyed: Vec<Id>,
3184}
3185
3186/// Apply one [`SpacePatchOp`] of [`apply_space_patch_impl`] to the Space
3187/// `space_id`, recording what it changed in `effects`. Returns the id the
3188/// op created, if any, or its [`SetError`].
3189fn apply_space_patch_op(
3190    inner: &mut Inner,
3191    account_id: &str,
3192    space_id: &Id,
3193    op: SpacePatchOp,
3194    effects: &mut SpacePatchEffects,
3195) -> Result<Option<Id>, Box<SetError>> {
3196    let space_mutated = &mut effects.space_mutated;
3197    match &op {
3198        SpacePatchOp::AddRole(_) => apply_add_role(inner, account_id, space_id, op, space_mutated),
3199        SpacePatchOp::RemoveRole(_) => apply_remove_role(
3200            inner,
3201            account_id,
3202            space_id,
3203            op,
3204            &mut effects.chats_updated,
3205            space_mutated,
3206        ),
3207        SpacePatchOp::UpdateRole { .. } => {
3208            apply_update_role(inner, account_id, space_id, op, space_mutated)
3209        }
3210        SpacePatchOp::AddMember(_) => {
3211            apply_add_member(inner, account_id, space_id, op, space_mutated)
3212        }
3213        SpacePatchOp::RemoveMember(_) => {
3214            apply_remove_member(inner, account_id, space_id, op, space_mutated)
3215        }
3216        SpacePatchOp::UpdateMember { .. } => {
3217            apply_update_member(inner, account_id, space_id, op, space_mutated)
3218        }
3219        SpacePatchOp::AddCategory(_)
3220        | SpacePatchOp::RemoveCategory(_)
3221        | SpacePatchOp::UpdateCategory { .. } => apply_category_op(
3222            inner,
3223            account_id,
3224            space_id,
3225            op,
3226            &mut effects.chats_updated,
3227            space_mutated,
3228        ),
3229        SpacePatchOp::AddChannel(_) => apply_add_channel(
3230            inner,
3231            account_id,
3232            space_id,
3233            op,
3234            &mut effects.chats_created,
3235            space_mutated,
3236        ),
3237        SpacePatchOp::RemoveChannel(_) => apply_remove_channel(
3238            inner,
3239            account_id,
3240            space_id,
3241            op,
3242            &mut effects.chats_destroyed,
3243            &mut effects.messages_destroyed,
3244            space_mutated,
3245        ),
3246        SpacePatchOp::UpdateChannel { .. } => apply_update_channel(
3247            inner,
3248            account_id,
3249            space_id,
3250            op,
3251            &mut effects.chats_updated,
3252            space_mutated,
3253        ),
3254        // `SpacePatchOp` is `#[non_exhaustive]` upstream. A
3255        // future-added variant cannot be matched at compile time;
3256        // fail closed.
3257        _ => Err(Box::new(
3258            SetError::new(SetErrorType::Forbidden).with_description(stub_description(&op)),
3259        )),
3260    }
3261}
3262
3263/// Close the Space `space_id` (set `closedAt`) when the owner of
3264/// `account_id`, the last member holding `"manage_space"`, has left it and
3265/// other members remain (draft-atwood-jmap-chat-00 §Space/set
3266/// `removeMembers`). Returns whether it was closed.
3267fn close_if_no_manager(
3268    inner: &mut Inner,
3269    account_id: &Id,
3270    space_id: &Id,
3271    everyone: &HashSet<ChatPermission>,
3272) -> bool {
3273    let Some(space) = inner
3274        .objects_mut("Space", account_id.as_ref())
3275        .get_mut(space_id)
3276    else {
3277        return false;
3278    };
3279    let member_ids: Vec<&str> = space
3280        .get("members")
3281        .and_then(|v| v.as_array())
3282        .map(|arr| arr.iter().filter_map(|m| m["id"].as_str()).collect())
3283        .unwrap_or_default();
3284    let closes = space.get("closedAt").is_none()
3285        && !member_ids.is_empty()
3286        && !member_ids.contains(&account_id.as_ref())
3287        && member_ids.iter().all(|m| {
3288            !member_effective_permissions(space, m, everyone)
3289                .is_some_and(|p| p.contains(&ChatPermission::ManageSpace))
3290        });
3291    if closes {
3292        space["closedAt"] = serde_json::Value::String(now_utc_string().into_inner());
3293    }
3294    closes
3295}
3296
3297/// Bump the states and log the change entries for what one
3298/// [`apply_space_patch_impl`] call changed, and drop the `ReadPosition`s of
3299/// the channels it destroyed.
3300fn log_space_patch(inner: &mut Inner, account_id: &str, space_id: &Id, effects: SpacePatchEffects) {
3301    let SpacePatchEffects {
3302        space_mutated,
3303        chats_created,
3304        chats_updated,
3305        chats_destroyed,
3306        messages_destroyed,
3307    } = effects;
3308    // Bump state + log a change entry on the Space if any op mutated it.
3309    // We deliberately log one change per call rather than one per op:
3310    // the wire response surfaces the whole patch as a single update,
3311    // and one change-log entry per call keeps `Space/changes` from
3312    // amplifying state-token rotations unnecessarily.
3313    if space_mutated {
3314        let new_state = inner.bump_state("Space", account_id);
3315        inner.change_log_mut("Space", account_id).push(ChangeEntry {
3316            new_state,
3317            created: vec![],
3318            updated: vec![space_id.clone()],
3319            destroyed: vec![],
3320            restored: vec![],
3321            updated_props: None,
3322        });
3323    }
3324
3325    destroy_read_positions(inner, account_id, &chats_destroyed);
3326
3327    // Same batching rationale: one Chat change-log entry per call,
3328    // combining every channel created, updated, and destroyed by
3329    // this patch.
3330    if !chats_created.is_empty() || !chats_updated.is_empty() || !chats_destroyed.is_empty() {
3331        let new_state = inner.bump_state("Chat", account_id);
3332        // De-dup `updated` against `created` and `destroyed` so a
3333        // channel touched by multiple ops in the same patch surfaces
3334        // in only the most-impactful list (destroyed > created >
3335        // updated). HashSet iteration is non-deterministic; sort the
3336        // updated ids so the change-log entry is reproducible.
3337        let mut updated: Vec<Id> = chats_updated
3338            .into_iter()
3339            .filter(|id| !chats_created.contains(id) && !chats_destroyed.contains(id))
3340            .collect();
3341        updated.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
3342        inner.change_log_mut("Chat", account_id).push(ChangeEntry {
3343            new_state,
3344            created: chats_created,
3345            updated,
3346            destroyed: chats_destroyed,
3347            restored: vec![],
3348            updated_props: None,
3349        });
3350    }
3351
3352    if !messages_destroyed.is_empty() {
3353        let new_state = inner.bump_state("Message", account_id);
3354        inner
3355            .change_log_mut("Message", account_id)
3356            .push(ChangeEntry {
3357                new_state,
3358                created: vec![],
3359                updated: vec![],
3360                destroyed: messages_destroyed,
3361                restored: vec![],
3362                updated_props: None,
3363            });
3364    }
3365}
3366
3367/// Convert a typed [`jmap_chat_types::SpaceMetadataPatch`] into the
3368/// `serde_json::Map<String, Value>` shape the internal
3369/// [`apply_space_metadata_patch_impl`] consumes. The reference impl
3370/// continues to apply changes via `json_merge_patch` on a stored
3371/// JSON value; the typed trait surface is a public-API hygiene
3372/// improvement (bd:JMAP-x2gd.39) — the internal merge-patch path is
3373/// unchanged.
3374///
3375/// A serializer failure is a [`MemoryError`] (surfaced as `serverFail`),
3376/// not a panic (bd:JMAP-ic0j.38).
3377fn space_metadata_patch_to_map(
3378    patch: jmap_chat_types::SpaceMetadataPatch,
3379) -> Result<serde_json::Map<String, serde_json::Value>, MemoryError> {
3380    // The struct's derive(Serialize) already emits camelCase keys,
3381    // collapses `Clearable::Clear` to `null`, and skips `None`
3382    // fields. We just need an Object out of it.
3383    let value = jmap_server::serialize_value(&patch)
3384        .map_err(|_| MemoryError::new("SpaceMetadataPatch serialization failed"))?;
3385    Ok(match value {
3386        serde_json::Value::Object(map) => map,
3387        // Unreachable: SpaceMetadataPatch serializes as an object
3388        // (all fields are object-keyed, `extra` is `#[serde(flatten)]`
3389        // and `SpaceMetadataPatch` itself is a struct).
3390        _ => serde_json::Map::new(),
3391    })
3392}
3393
3394/// Backend-canonical impl of
3395/// [`ChatSpaces::apply_space_metadata_patch`] for the reference
3396/// in-memory store (bd:JMAP-g7wu.2.4.13).
3397///
3398/// Snapshots the target Space, enforces the `manage_space` gate,
3399/// and applies the JSON
3400/// Merge Patch (RFC 7396) atomically under the inner mutex.
3401///
3402/// # Permission gate
3403///
3404/// Per draft-atwood-jmap-chat-00 §Space/set, every top-level
3405/// metadata field (`name`, `description`, `iconBlobId`, `isPublic`,
3406/// `isPubliclyPreviewable`) requires `manage_space`. The gate logic
3407/// mirrors [`validate_space_patch_ops`]: the caller's effective
3408/// permission set, keyed on the owner's member entry `account_id`
3409/// (draft §Terminology), must contain `manage_space`, else the whole
3410/// patch is rejected with [`SetErrorType::Forbidden`].
3411///
3412/// Empty patches (`patch_map.is_empty()`) are still rejected at the
3413/// gate when the caller lacks `manage_space`. Letting them through
3414/// would be a small information leak (the caller learns the Space
3415/// exists) without practical value — RFC 8620 §5.3 tolerates no-op
3416/// updates but does not REQUIRE them to bypass authorization.
3417///
3418/// # Atomicity
3419///
3420/// The lock is held across the read-check-write sequence so the
3421/// gate decision and the write cannot race against a concurrent
3422/// role-change that would invalidate the decision. This matches the
3423/// canonical backend-side-enforcement pattern from
3424/// `apply_space_patch_impl`.
3425fn apply_space_metadata_patch_impl(
3426    inner: &mut Inner,
3427    account_id: &Id,
3428    space_id: &Id,
3429    patch_map: serde_json::Map<String, serde_json::Value>,
3430) -> Result<Option<jmap_chat_types::Space>, BackendSetError<MemoryError>> {
3431    // Confirm the target Space exists. Surface NotFound at the
3432    // SetError level (per-target, NOT per-account) so the handler's
3433    // `notUpdated` bucket can render it.
3434    let space_val = inner
3435        .objects_ref("Space", account_id.as_ref())
3436        .and_then(|m| m.get(space_id))
3437        .cloned()
3438        .ok_or_else(|| {
3439            BackendSetError::SetError(Box::new(SetError::new(SetErrorType::NotFound)))
3440        })?;
3441
3442    // Permission gate: the caller's effective permissions in the
3443    // Space must include `manage_space`.
3444    let caller_perms =
3445        caller_effective_permissions(&space_val, account_id, inner.everyone_in(&space_val))
3446            .unwrap_or_default();
3447    if !caller_perms.contains(&ChatPermission::ManageSpace) {
3448        return Err(BackendSetError::SetError(
3449            Box::new(SetError::new(SetErrorType::Forbidden).with_description(
3450                "caller lacks required permission `manage_space` to mutate Space top-level metadata",
3451            )),
3452        ));
3453    }
3454
3455    // Empty patch is a no-op. Treat as a successful update with no
3456    // server-set field echo; the handler still emits an entry into
3457    // the `updated` map (per RFC 8620 §5.3 tolerance for no-op
3458    // updates). Skip the state bump and change-log entry so a no-op
3459    // does not rotate the Space type's state token.
3460    if patch_map.is_empty() {
3461        return Ok(None);
3462    }
3463
3464    // Apply the merge patch in place. The wire-shape JSON object is
3465    // canonical for in-memory storage (extras-preservation policy);
3466    // the patch keys have already been filtered to METADATA_FIELDS
3467    // and the registered extension properties by the handler.
3468    //
3469    // A `MergePatchError::DepthExceeded` return (bd:JMAP-wlip.1) surfaces
3470    // as `SetErrorType::InvalidPatch` — the depth cap is a DoS guard,
3471    // never fires on legitimate JMAP `/set update` shapes. `current` is a
3472    // local owned clone of `space_val`, so a partially-applied patch on
3473    // error is discarded without touching the storage map.
3474    let mut current = space_val;
3475    if let Err(MergePatchError::DepthExceeded) =
3476        json_merge_patch(&mut current, serde_json::Value::Object(patch_map))
3477    {
3478        return Err(BackendSetError::SetError(Box::new(
3479            SetError::new(SetErrorType::InvalidPatch)
3480                .with_description("patch nesting exceeds server limit"),
3481        )));
3482    }
3483
3484    let new_state = inner.bump_state("Space", account_id.as_ref());
3485    inner
3486        .objects_mut("Space", account_id.as_ref())
3487        .insert(space_id.clone(), current);
3488    inner
3489        .change_log_mut("Space", account_id.as_ref())
3490        .push(ChangeEntry {
3491            new_state,
3492            created: vec![],
3493            updated: vec![space_id.clone()],
3494            destroyed: vec![],
3495            restored: vec![],
3496            updated_props: None,
3497        });
3498
3499    // Return `None` to match the `update_object` contract: no
3500    // server-set field echo beyond what the client requested.
3501    Ok(None)
3502}
3503
3504/// Apply one Category-family [`SpacePatchOp`] to the in-memory Space.
3505///
3506/// Per draft-atwood-jmap-chat-00 §Space/set:
3507/// - `addCategories`: assigns a fresh `CategoryId` and pushes the category
3508///   into `space.categories`. If the entry's `channelIds` list references
3509///   channels of the Space, those channels' `categoryId` is updated and
3510///   they leave their previous category or `uncategorizedChannelIds`.
3511/// - `removeCategories`: removes the named category. Channels currently
3512///   pointing at that category have their `categoryId` cleared and are
3513///   appended to `space.uncategorizedChannelIds` (cascade per §Space/set L1292).
3514/// - `updateCategories`: applies the per-field patch. A `channelIds`
3515///   wholesale-replacement updates each channel's `categoryId` to match:
3516///   channels that left the list get `categoryId = None` and join
3517///   `uncategorizedChannelIds`; channels that joined the list get
3518///   `categoryId = Some(this category)` and leave their previous
3519///   category or `uncategorizedChannelIds`.
3520///
3521/// All cross-reference updates use the same in-memory Chat store so the
3522/// Space-side `categories[].channel_ids` and the Chat-side `categoryId`
3523/// stay consistent. Every channel whose `categoryId` changes here is
3524/// also pushed into the caller's `chats_updated` set so the post-loop
3525/// bookkeeping in `apply_space_patch` emits a `Chat/changes` entry for
3526/// the cascade (bd:JMAP-g7wu.2.4.9).
3527fn apply_category_op(
3528    inner: &mut Inner,
3529    account_id: &str,
3530    space_id: &Id,
3531    op: SpacePatchOp,
3532    chats_updated: &mut HashSet<Id>,
3533    space_mutated: &mut bool,
3534) -> Result<Option<Id>, Box<SetError>> {
3535    // The Space exists (the caller verified). Pull it out as a typed
3536    // value, apply the mutation, write it back.
3537    let mut space_val = stored_space(inner, account_id, space_id)?;
3538    let categories: &mut Vec<serde_json::Value> = space_val
3539        .get_mut("categories")
3540        .and_then(|v| v.as_array_mut())
3541        .ok_or_else(categories_not_array)?;
3542
3543    let assigned_id = match op {
3544        SpacePatchOp::AddCategory(cat) => Some(add_category(
3545            inner,
3546            account_id,
3547            space_id,
3548            cat,
3549            categories,
3550            chats_updated,
3551        )?),
3552        SpacePatchOp::RemoveCategory(target_id) => {
3553            remove_category(
3554                inner,
3555                account_id,
3556                space_id,
3557                &target_id,
3558                categories,
3559                chats_updated,
3560            )?;
3561            None
3562        }
3563        SpacePatchOp::UpdateCategory { id, patch } => {
3564            update_category(
3565                inner,
3566                (account_id, space_id),
3567                &id,
3568                patch,
3569                categories,
3570                chats_updated,
3571            )?;
3572            None
3573        }
3574
3575        // Caller filters non-category ops out before reaching this helper.
3576        _ => unreachable!("apply_category_op called with non-category variant"),
3577    };
3578    *space_mutated = true;
3579
3580    Ok(assigned_id)
3581}
3582
3583/// A clone of the stored Space `space_id`, or `notFound`.
3584fn stored_space(
3585    inner: &Inner,
3586    account_id: &str,
3587    space_id: &Id,
3588) -> Result<serde_json::Value, Box<SetError>> {
3589    inner
3590        .objects_ref("Space", account_id)
3591        .and_then(|m| m.get(space_id))
3592        .cloned()
3593        .ok_or_else(|| Box::new(SetError::new(SetErrorType::NotFound)))
3594}
3595
3596/// The `forbidden` [`SetError`] for a stored Space whose `categories` is
3597/// not an array.
3598fn categories_not_array() -> SetError {
3599    SetError::new(SetErrorType::Forbidden)
3600        .with_description("internal: Space.categories not an array")
3601}
3602
3603/// The `invalidProperties` [`SetError`] for a category `channelIds` entry
3604/// `ch_id` that is not a channel of the Space.
3605fn not_a_space_channel(ch_id: &Id) -> Box<SetError> {
3606    Box::new(
3607        SetError::new(SetErrorType::InvalidProperties)
3608            .with_properties(vec!["channelIds".to_owned()])
3609            .with_description(format!(
3610                "channelId {} is not a channel of this Space",
3611                ch_id.as_ref()
3612            )),
3613    )
3614}
3615
3616/// The `notFound` [`SetError`] for a category `id` the Space lacks, or the
3617/// position of the category in `categories`.
3618fn category_position(categories: &[serde_json::Value], id: &Id) -> Result<usize, Box<SetError>> {
3619    categories
3620        .iter()
3621        .position(|v| v.get("id").and_then(|s| s.as_str()) == Some(id.as_ref()))
3622        .ok_or_else(|| {
3623            Box::new(
3624                SetError::new(SetErrorType::NotFound)
3625                    .with_description(format!("category {} not found", id.as_ref())),
3626            )
3627        })
3628}
3629
3630/// `addCategories` for [`apply_category_op`]: store `cat` under a fresh
3631/// id, which is returned, and move its channels into it. `categories` are
3632/// the Space's categories before the op.
3633fn add_category(
3634    inner: &mut Inner,
3635    account_id: &str,
3636    space_id: &Id,
3637    cat: jmap_chat_types::CategoryCreate,
3638    categories: &[serde_json::Value],
3639    chats_updated: &mut HashSet<Id>,
3640) -> Result<Id, Box<SetError>> {
3641    // Mint a fresh CategoryId (draft §Space/set `addCategories`:
3642    // "Server assigns ULIDs").
3643    let new_id = inner.mint_id();
3644    // The draft leaves the default `position` open; an entry without
3645    // one is appended after the highest existing category position.
3646    let position = cat.position.unwrap_or_else(|| {
3647        categories
3648            .iter()
3649            .filter_map(|c| c.get("position").and_then(serde_json::Value::as_u64))
3650            .max()
3651            .map_or(0, |max| max.saturating_add(1))
3652    });
3653
3654    // Validate every channel id in the entry's channel_ids refers
3655    // to an existing Chat with kind=channel and space_id matching
3656    // this Space. The spec says "channelIds (String[])" without
3657    // strict validation language, but accepting nonexistent ids
3658    // would create dangling references on the Space side.
3659    if let Some(ch_id) = cat
3660        .channel_ids
3661        .iter()
3662        .find(|ch_id| !channel_belongs_to_space(inner, account_id, ch_id, space_id))
3663    {
3664        return Err(not_a_space_channel(ch_id));
3665    }
3666
3667    // Re-fetch space_val + categories after the validation borrows
3668    // (channel_belongs_to_space took an immutable inner borrow).
3669    let mut space_val = stored_space(inner, account_id, space_id)?;
3670
3671    // Set each named channel's category_id and pull it out of
3672    // uncategorized_channel_ids if present. Every channel whose
3673    // categoryId changes is recorded so Chat/changes sees the
3674    // cascade (bd:JMAP-g7wu.2.4.9).
3675    let owned_channel_ids: Vec<Id> = cat.channel_ids.clone();
3676    for ch_id in &owned_channel_ids {
3677        set_channel_category(inner, account_id, ch_id, Some(&new_id));
3678        chats_updated.insert(ch_id.clone());
3679    }
3680    if let Some(unc) = space_val
3681        .get_mut("uncategorizedChannelIds")
3682        .and_then(|v| v.as_array_mut())
3683    {
3684        unc.retain(|v| {
3685            v.as_str()
3686                .is_none_or(|s| !owned_channel_ids.iter().any(|id| id.as_ref() == s))
3687        });
3688    }
3689    let cats = space_val
3690        .get_mut("categories")
3691        .and_then(|v| v.as_array_mut())
3692        .ok_or_else(categories_not_array)?;
3693    remove_from_categories(cats, &owned_channel_ids);
3694    let channel_ids = owned_channel_ids
3695        .iter()
3696        .map(|id| serde_json::Value::from(id.as_ref()))
3697        .collect();
3698    let mut stored = cat.extra;
3699    stored.insert("id".to_owned(), serde_json::Value::from(new_id.as_ref()));
3700    stored.insert("name".to_owned(), serde_json::Value::String(cat.name));
3701    stored.insert("position".to_owned(), serde_json::Value::from(position));
3702    stored.insert(
3703        "channelIds".to_owned(),
3704        serde_json::Value::Array(channel_ids),
3705    );
3706    cats.push(serde_json::Value::Object(stored));
3707
3708    inner
3709        .objects_mut("Space", account_id)
3710        .insert(space_id.clone(), space_val);
3711    Ok(new_id)
3712}
3713
3714/// `removeCategories` for [`apply_category_op`]: drop the category
3715/// `target_id` and move its channels to `uncategorizedChannelIds`.
3716/// `categories` are the Space's categories before the op.
3717fn remove_category(
3718    inner: &mut Inner,
3719    account_id: &str,
3720    space_id: &Id,
3721    target_id: &Id,
3722    categories: &[serde_json::Value],
3723    chats_updated: &mut HashSet<Id>,
3724) -> Result<(), Box<SetError>> {
3725    // Find the category. Cascade: every channel currently in this
3726    // category gets its category_id cleared and is appended to
3727    // uncategorized. Per draft §Space/set L1292.
3728    let pos = category_position(categories, target_id)?;
3729    // The stored channel_ids on the category mirror the Chats'
3730    // category_id; scan Chats to be safe (Space-side could drift).
3731    let scanned: Vec<Id> = scan_channels_in_category(inner, account_id, target_id);
3732
3733    // Drop the category and append channels to uncategorized.
3734    let mut space_val = stored_space(inner, account_id, space_id)?;
3735    let cats = space_val
3736        .get_mut("categories")
3737        .and_then(|v| v.as_array_mut())
3738        .ok_or_else(categories_not_array)?;
3739    cats.remove(pos);
3740
3741    let unc = space_val
3742        .get_mut("uncategorizedChannelIds")
3743        .and_then(|v| v.as_array_mut())
3744        .ok_or_else(|| {
3745            SetError::new(SetErrorType::Forbidden)
3746                .with_description("internal: Space.uncategorizedChannelIds not an array")
3747        })?;
3748    for ch_id in &scanned {
3749        unc.push(serde_json::Value::String(ch_id.as_ref().to_owned()));
3750    }
3751    inner
3752        .objects_mut("Space", account_id)
3753        .insert(space_id.clone(), space_val);
3754
3755    // Clear each scanned channel's category_id pointer.
3756    // Every cleared channel is recorded so Chat/changes sees
3757    // the cascade (bd:JMAP-g7wu.2.4.9).
3758    for ch_id in &scanned {
3759        set_channel_category(inner, account_id, ch_id, None);
3760        chats_updated.insert(ch_id.clone());
3761    }
3762    Ok(())
3763}
3764
3765/// `updateCategories` for [`apply_category_op`]: apply `patch` to the
3766/// category `id` of the Space `space.1` in account `space.0`. A
3767/// `channelIds` replacement moves the channels that left it to
3768/// `uncategorizedChannelIds` and those that joined it out of where they
3769/// were. `categories` are the Space's categories before the op.
3770fn update_category(
3771    inner: &mut Inner,
3772    space: (&str, &Id),
3773    id: &Id,
3774    patch: jmap_chat_types::CategoryPatch,
3775    categories: &[serde_json::Value],
3776    chats_updated: &mut HashSet<Id>,
3777) -> Result<(), Box<SetError>> {
3778    use jmap_chat_types::Category;
3779    let (account_id, space_id) = space;
3780
3781    // Find the category.
3782    let pos = category_position(categories, id)?;
3783
3784    // Deserialize, apply the patch, re-serialize.
3785    let mut cat: Category = serde_json::from_value(categories[pos].clone()).map_err(|e| {
3786        SetError::new(SetErrorType::Forbidden)
3787            .with_description(format!("internal: deserialize Category: {e}"))
3788    })?;
3789
3790    if let Some(name) = patch.name {
3791        cat.name = name;
3792    }
3793    if let Some(position) = patch.position {
3794        cat.position = position;
3795    }
3796
3797    // Wholesale channel_ids replacement requires cross-reference
3798    // bookkeeping on the channels.
3799    let Some(new_ids) = patch.channel_ids else {
3800        // Only metadata changed; write back the category.
3801        return write_category(inner, space, pos, &cat, &[], &[]);
3802    };
3803    // Validate every new id is a channel of this Space.
3804    if let Some(ch_id) = new_ids
3805        .iter()
3806        .find(|ch_id| !channel_belongs_to_space(inner, account_id, ch_id, space_id))
3807    {
3808        return Err(not_a_space_channel(ch_id));
3809    }
3810
3811    let old_ids = cat.channel_ids.clone();
3812
3813    // Channels in old but not in new: clear category_id and
3814    // append to uncategorized.
3815    let removed: Vec<&Id> = old_ids.iter().filter(|o| !new_ids.contains(o)).collect();
3816    // Channels in new but not in old: set category_id to this
3817    // category and remove from uncategorized.
3818    let added: Vec<&Id> = new_ids.iter().filter(|n| !old_ids.contains(n)).collect();
3819
3820    cat.channel_ids = new_ids.clone();
3821    write_category(inner, space, pos, &cat, &removed, &added)?;
3822
3823    // Update each channel's category_id. Every channel
3824    // whose categoryId changed is recorded so Chat/changes
3825    // sees the cascade (bd:JMAP-g7wu.2.4.9).
3826    for ch_id in &removed {
3827        set_channel_category(inner, account_id, ch_id, None);
3828        chats_updated.insert((*ch_id).clone());
3829    }
3830    for ch_id in &added {
3831        set_channel_category(inner, account_id, ch_id, Some(id));
3832        chats_updated.insert((*ch_id).clone());
3833    }
3834    Ok(())
3835}
3836
3837/// Store `cat` as the category at `pos` of the Space `space.1` in account
3838/// `space.0`, appending the channels `removed` from it to
3839/// `uncategorizedChannelIds` and taking those `added` to it out of there
3840/// and out of every other category. With both empty only the category
3841/// changes.
3842fn write_category(
3843    inner: &mut Inner,
3844    space: (&str, &Id),
3845    pos: usize,
3846    cat: &jmap_chat_types::Category,
3847    removed: &[&Id],
3848    added: &[&Id],
3849) -> Result<(), Box<SetError>> {
3850    let (account_id, space_id) = space;
3851    // Mutate Space first (uncategorized list).
3852    let mut space_val = stored_space(inner, account_id, space_id)?;
3853    if let Some(unc) = space_val
3854        .get_mut("uncategorizedChannelIds")
3855        .and_then(|v| v.as_array_mut())
3856    {
3857        for ch_id in removed {
3858            unc.push(serde_json::Value::String(ch_id.as_ref().to_owned()));
3859        }
3860        unc.retain(|v| {
3861            v.as_str()
3862                .is_none_or(|s| !added.iter().any(|id| id.as_ref() == s))
3863        });
3864    }
3865    // Write back the updated category.
3866    let cats = space_val
3867        .get_mut("categories")
3868        .and_then(|v| v.as_array_mut())
3869        .ok_or_else(categories_not_array)?;
3870    remove_from_categories(cats, added);
3871    cats[pos] = serde_json::to_value(cat).map_err(|e| {
3872        SetError::new(SetErrorType::Forbidden)
3873            .with_description(format!("internal: serialize Category: {e}"))
3874    })?;
3875    inner
3876        .objects_mut("Space", account_id)
3877        .insert(space_id.clone(), space_val);
3878    Ok(())
3879}
3880
3881/// Apply one [`SpacePatchOp::AddChannel`] to the in-memory Space.
3882///
3883/// Per draft-atwood-jmap-chat-00 §Space/set `addChannels` (L1280):
3884/// - The server creates a Chat record of `kind: "channel"` with
3885///   `spaceId` set to this Space's id and a fresh server-assigned id.
3886/// - If `categoryId` is provided, validate that the named category
3887///   exists on this Space; append the new channel's id to that
3888///   category's `channelIds` array.
3889/// - If `categoryId` is absent, append the new channel's id to the
3890///   Space's `uncategorizedChannelIds` array.
3891/// - `name` is required; `position` and `topic` are optional.
3892///   `slowModeSeconds` and `permissionOverrides` are server-managed
3893///   and start absent (the spec does not allow the client to set them
3894///   at create time — those flow through `updateChannels` later).
3895fn apply_add_channel(
3896    inner: &mut Inner,
3897    account_id: &str,
3898    space_id: &Id,
3899    op: SpacePatchOp,
3900    chats_created: &mut Vec<Id>,
3901    space_mutated: &mut bool,
3902) -> Result<Option<Id>, Box<SetError>> {
3903    use jmap_chat_types::ChannelCreate;
3904
3905    let create: ChannelCreate = match op {
3906        SpacePatchOp::AddChannel(c) => c,
3907        _ => unreachable!("apply_add_channel called with non-AddChannel variant"),
3908    };
3909
3910    // If categoryId is provided, verify the category exists on this Space.
3911    // This must happen before any mutation so a bad categoryId is a clean
3912    // rejection rather than a half-applied side effect.
3913    if let Some(cat_id) = &create.category_id {
3914        check_space_category(inner, account_id, space_id, cat_id)?;
3915    }
3916
3917    // Mint a fresh channel Chat id.
3918    let new_id = inner.mint_id();
3919    let category_id = create.category_id.clone();
3920    let chat_obj = new_channel_object(&new_id, space_id, create);
3921    inner
3922        .objects_mut("Chat", account_id)
3923        .insert(new_id.clone(), serde_json::Value::Object(chat_obj));
3924
3925    // Update Space-side cross-references. Re-fetch the Space because
3926    // the validation borrow above was released, and the `objects_mut`
3927    // on "Chat" above invalidated any earlier borrow regardless.
3928    let mut space_val = inner
3929        .objects_ref("Space", account_id)
3930        .and_then(|m| m.get(space_id))
3931        .cloned()
3932        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
3933    // Append the new channel id to its category's channelIds, or to
3934    // uncategorizedChannelIds.
3935    place_channel(&mut space_val, &new_id, category_id.as_ref())?;
3936    inner
3937        .objects_mut("Space", account_id)
3938        .insert(space_id.clone(), space_val);
3939
3940    chats_created.push(new_id.clone());
3941    *space_mutated = true;
3942    Ok(Some(new_id))
3943}
3944
3945/// The stored Chat record for the channel `new_id` of the Space `space_id`
3946/// that an `addChannels` entry `create` describes.
3947///
3948/// Required fields per `Chat`:
3949///   id, kind, createdAt, unreadCount, pinnedMessageIds, muted,
3950///   receiveTypingIndicators
3951/// Channel-specific: spaceId, name, categoryId?, position?, topic?
3952/// Defaults for muted (false) and receiveTypingIndicators (true)
3953/// match the values used by Chat/set create at chat.rs:266-273.
3954fn new_channel_object(
3955    new_id: &Id,
3956    space_id: &Id,
3957    create: jmap_chat_types::ChannelCreate,
3958) -> serde_json::Map<String, serde_json::Value> {
3959    let now = now_utc_string();
3960    let mut chat_obj = serde_json::Map::new();
3961    chat_obj.insert(
3962        "id".to_owned(),
3963        serde_json::Value::String(new_id.as_ref().to_owned()),
3964    );
3965    chat_obj.insert(
3966        "kind".to_owned(),
3967        serde_json::Value::String("channel".to_owned()),
3968    );
3969    chat_obj.insert(
3970        "createdAt".to_owned(),
3971        serde_json::Value::String(now.into_inner()),
3972    );
3973    chat_obj.insert("unreadCount".to_owned(), serde_json::Value::from(0u64));
3974    chat_obj.insert(
3975        "pinnedMessageIds".to_owned(),
3976        serde_json::Value::Array(vec![]),
3977    );
3978    chat_obj.insert("muted".to_owned(), serde_json::Value::Bool(false));
3979    chat_obj.insert(
3980        "receiveTypingIndicators".to_owned(),
3981        serde_json::Value::Bool(true),
3982    );
3983    chat_obj.insert(
3984        "spaceId".to_owned(),
3985        serde_json::Value::String(space_id.as_ref().to_owned()),
3986    );
3987    chat_obj.insert("name".to_owned(), serde_json::Value::String(create.name));
3988    if let Some(cat_id) = &create.category_id {
3989        chat_obj.insert(
3990            "categoryId".to_owned(),
3991            serde_json::Value::String(cat_id.as_ref().to_owned()),
3992        );
3993    }
3994    if let Some(pos) = create.position {
3995        chat_obj.insert("position".to_owned(), serde_json::Value::from(pos));
3996    }
3997    if let Some(topic) = create.topic {
3998        chat_obj.insert("topic".to_owned(), serde_json::Value::String(topic));
3999    }
4000    chat_obj
4001}
4002
4003/// Apply one [`SpacePatchOp::RemoveChannel`] to the in-memory Space.
4004///
4005/// Per draft-atwood-jmap-chat-00 §Space/set L1283: removeChannels
4006/// "Cascades to all Messages in those channels." This implementation:
4007///
4008/// 1. Verifies the named id refers to a channel-kind Chat with
4009///    `spaceId` matching this Space. Any other id is `notFound`.
4010/// 2. Destroys the Chat record itself.
4011/// 3. Scans the Message store for every Message whose `chatId` matches
4012///    the removed channel; destroys each one.
4013/// 4. Removes the channel id from the Space's `uncategorizedChannelIds`
4014///    and from any category's `channelIds` it appears in.
4015///
4016/// All four steps run within the single mutex hold inherited from
4017/// `apply_space_patch`, so the Chat removal, the Message cascade, and
4018/// the Space-side bookkeeping are atomic with respect to other
4019/// `MemoryBackend` callers.
4020fn apply_remove_channel(
4021    inner: &mut Inner,
4022    account_id: &str,
4023    space_id: &Id,
4024    op: SpacePatchOp,
4025    chats_destroyed: &mut Vec<Id>,
4026    messages_destroyed: &mut Vec<Id>,
4027    space_mutated: &mut bool,
4028) -> Result<Option<Id>, Box<SetError>> {
4029    let target_id: Id = match op {
4030        SpacePatchOp::RemoveChannel(id) => id,
4031        _ => unreachable!("apply_remove_channel called with non-RemoveChannel variant"),
4032    };
4033
4034    // Confirm the id names a channel-kind Chat of this Space.
4035    if !channel_belongs_to_space(inner, account_id, &target_id, space_id) {
4036        return Err(Box::new(
4037            SetError::new(SetErrorType::NotFound).with_description(format!(
4038                "channel {} is not a channel of this Space",
4039                target_id.as_ref()
4040            )),
4041        ));
4042    }
4043
4044    // Cascade Messages first so a half-completed run leaves Messages
4045    // referring to a still-extant Chat rather than orphaned Messages
4046    // pointing at a vanished Chat. (We are inside a single mutex hold
4047    // so partial visibility is internal, but the ordering preserves
4048    // referential integrity for tests that grep mid-run state.)
4049    let cascade_ids = scan_messages_in_chat(inner, account_id, &target_id);
4050    if !cascade_ids.is_empty() {
4051        let msg_map = inner.objects_mut("Message", account_id);
4052        for msg_id in &cascade_ids {
4053            msg_map.remove(msg_id);
4054        }
4055        messages_destroyed.extend(cascade_ids);
4056    }
4057
4058    // Destroy the Chat record.
4059    inner.objects_mut("Chat", account_id).remove(&target_id);
4060
4061    // Remove the channel id from Space-side cross-references.
4062    let mut space_val = inner
4063        .objects_ref("Space", account_id)
4064        .and_then(|m| m.get(space_id))
4065        .cloned()
4066        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4067
4068    if let Some(unc) = space_val
4069        .get_mut("uncategorizedChannelIds")
4070        .and_then(|v| v.as_array_mut())
4071    {
4072        unc.retain(|v| v.as_str() != Some(target_id.as_ref()));
4073    }
4074    if let Some(cats) = space_val
4075        .get_mut("categories")
4076        .and_then(|v| v.as_array_mut())
4077    {
4078        for cat in cats.iter_mut() {
4079            if let Some(ch_ids) = cat.get_mut("channelIds").and_then(|v| v.as_array_mut()) {
4080                ch_ids.retain(|v| v.as_str() != Some(target_id.as_ref()));
4081            }
4082        }
4083    }
4084    inner
4085        .objects_mut("Space", account_id)
4086        .insert(space_id.clone(), space_val);
4087
4088    chats_destroyed.push(target_id);
4089    *space_mutated = true;
4090    Ok(None)
4091}
4092
4093/// Apply one [`SpacePatchOp::UpdateChannel`] to the in-memory Space.
4094///
4095/// Per draft-atwood-jmap-chat-00 §Space/set L1286: `updateChannels`
4096/// patches one of `name`, `topic`, `categoryId`, `position`,
4097/// `slowModeSeconds`, `permissionOverrides`. The nullable fields use
4098/// [`jmap_chat_types::Clearable`] semantics: `null` clears
4099/// and absence leaves unchanged.
4100///
4101/// `categoryId` changes additionally maintain Space-side cross-references:
4102/// the channel id is removed from its previous category's `channelIds`
4103/// (or from `uncategorizedChannelIds`) and added to the new category's
4104/// `channelIds` (or to `uncategorizedChannelIds` when cleared). The new
4105/// category, if any, must already exist on this Space — otherwise the
4106/// op fails with `invalidProperties` on `categoryId`.
4107fn apply_update_channel(
4108    inner: &mut Inner,
4109    account_id: &str,
4110    space_id: &Id,
4111    op: SpacePatchOp,
4112    chats_updated: &mut HashSet<Id>,
4113    space_mutated: &mut bool,
4114) -> Result<Option<Id>, Box<SetError>> {
4115    use jmap_chat_types::ChannelPatch;
4116    use jmap_chat_types::Clearable;
4117
4118    let (id, patch): (Id, ChannelPatch) = match op {
4119        SpacePatchOp::UpdateChannel { id, patch } => (id, patch),
4120        _ => unreachable!("apply_update_channel called with non-UpdateChannel variant"),
4121    };
4122
4123    // Confirm the id names a channel-kind Chat of this Space.
4124    if !channel_belongs_to_space(inner, account_id, &id, space_id) {
4125        return Err(Box::new(
4126            SetError::new(SetErrorType::NotFound).with_description(format!(
4127                "channel {} is not a channel of this Space",
4128                id.as_ref()
4129            )),
4130        ));
4131    }
4132
4133    // If categoryId is changing to a non-null value, validate that the
4134    // target category exists on this Space before mutating anything.
4135    // A null categoryId (Clearable::Clear) does not need this check.
4136    if let Some(Clearable::Set(new_cat)) = &patch.category_id {
4137        check_space_category(inner, account_id, space_id, new_cat)?;
4138    }
4139
4140    // Apply the patch to the Chat record. We collect categoryId before
4141    // mutation so the Space-side cross-reference update below knows
4142    // both the old and new pointers.
4143    let old_category_id: Option<Id> = inner
4144        .objects_ref("Chat", account_id)
4145        .and_then(|m| m.get(&id))
4146        .and_then(|v| v.get("categoryId"))
4147        .and_then(|c| c.as_str())
4148        .map(Id::from);
4149
4150    let category_id = {
4151        let chat_map = inner.objects_mut("Chat", account_id);
4152        let Some(chat_val) = chat_map.get_mut(&id) else {
4153            // We just confirmed existence via channel_belongs_to_space;
4154            // this is unreachable in single-thread execution.
4155            return Err(Box::new(SetError::new(SetErrorType::NotFound)));
4156        };
4157        let serde_json::Value::Object(obj) = chat_val else {
4158            return Err(Box::new(
4159                SetError::new(SetErrorType::Forbidden)
4160                    .with_description("internal: Chat record not a JSON object"),
4161            ));
4162        };
4163        patch_channel_record(obj, patch)?
4164    };
4165
4166    // Maintain Space-side cross-references for categoryId changes.
4167    if let Some(category_id) = category_id {
4168        let new_category_id: Option<Id> = match category_id {
4169            Clearable::Set(c) => Some(c),
4170            Clearable::Clear => None,
4171        };
4172
4173        // Only do bookkeeping if the assignment actually changed —
4174        // a no-op same-category update should not shuffle arrays.
4175        if old_category_id != new_category_id {
4176            let mut space_val = inner
4177                .objects_ref("Space", account_id)
4178                .and_then(|m| m.get(space_id))
4179                .cloned()
4180                .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4181
4182            // Remove from previous home.
4183            unplace_channel(&mut space_val, &id, old_category_id.as_ref());
4184            // Add to new home.
4185            place_channel(&mut space_val, &id, new_category_id.as_ref())?;
4186
4187            inner
4188                .objects_mut("Space", account_id)
4189                .insert(space_id.clone(), space_val);
4190            *space_mutated = true;
4191        }
4192    }
4193
4194    chats_updated.insert(id);
4195    Ok(None)
4196}
4197
4198/// Apply the channel `patch` of an `updateChannels` entry to the stored
4199/// Chat record `obj`, field by field (`name`, `position`, `topic`,
4200/// `categoryId`, `slowModeSeconds`, `permissionOverrides`), and return its
4201/// `categoryId` change. A field that fails leaves the earlier ones applied.
4202fn patch_channel_record(
4203    obj: &mut serde_json::Map<String, serde_json::Value>,
4204    patch: jmap_chat_types::ChannelPatch,
4205) -> Result<Option<jmap_chat_types::Clearable<Id>>, Box<SetError>> {
4206    use jmap_chat_types::Clearable;
4207
4208    if let Some(name) = patch.name {
4209        obj.insert("name".to_owned(), serde_json::Value::String(name));
4210    }
4211    if let Some(pos) = patch.position {
4212        obj.insert("position".to_owned(), serde_json::Value::from(pos));
4213    }
4214    match patch.topic {
4215        Some(Clearable::Set(t)) => {
4216            obj.insert("topic".to_owned(), serde_json::Value::String(t));
4217        }
4218        Some(Clearable::Clear) => {
4219            obj.remove("topic");
4220        }
4221        None => {}
4222    }
4223    match &patch.category_id {
4224        Some(Clearable::Set(c)) => {
4225            obj.insert(
4226                "categoryId".to_owned(),
4227                serde_json::Value::String(c.as_ref().to_owned()),
4228            );
4229        }
4230        Some(Clearable::Clear) => {
4231            obj.remove("categoryId");
4232        }
4233        None => {}
4234    }
4235    match patch.slow_mode_seconds {
4236        Some(Clearable::Set(s)) => {
4237            obj.insert("slowModeSeconds".to_owned(), serde_json::Value::from(s));
4238        }
4239        Some(Clearable::Clear) => {
4240            obj.remove("slowModeSeconds");
4241        }
4242        None => {}
4243    }
4244    match patch.permission_overrides {
4245        Some(Clearable::Set(po)) => {
4246            let val = serde_json::to_value(&po).map_err(|e| {
4247                SetError::new(SetErrorType::Forbidden)
4248                    .with_description(format!("internal: serialize permissionOverrides: {e}"))
4249            })?;
4250            obj.insert("permissionOverrides".to_owned(), val);
4251        }
4252        Some(Clearable::Clear) => {
4253            obj.remove("permissionOverrides");
4254        }
4255        None => {}
4256    }
4257    Ok(patch.category_id)
4258}
4259
4260/// Check that `cat_id` names a category of the Space `space_id`, before a
4261/// channel is put in it: `notFound` without the Space, `invalidProperties`
4262/// on `categoryId` without the category.
4263fn check_space_category(
4264    inner: &Inner,
4265    account_id: &str,
4266    space_id: &Id,
4267    cat_id: &Id,
4268) -> Result<(), Box<SetError>> {
4269    let space_val = inner
4270        .objects_ref("Space", account_id)
4271        .and_then(|m| m.get(space_id))
4272        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4273    let exists = space_val
4274        .get("categories")
4275        .and_then(|v| v.as_array())
4276        .is_some_and(|cats| {
4277            cats.iter()
4278                .any(|c| c.get("id").and_then(|s| s.as_str()) == Some(cat_id.as_ref()))
4279        });
4280    if !exists {
4281        return Err(Box::new(
4282            SetError::new(SetErrorType::InvalidProperties)
4283                .with_properties(vec!["categoryId".to_owned()])
4284                .with_description(format!(
4285                    "categoryId {} does not refer to a category of this Space",
4286                    cat_id.as_ref()
4287                )),
4288        ));
4289    }
4290    Ok(())
4291}
4292
4293/// Take the channel `id` out of its home in the stored Space `space_val`:
4294/// the `channelIds` of its category `category`, or
4295/// `uncategorizedChannelIds`. A missing array is left alone.
4296fn unplace_channel(space_val: &mut serde_json::Value, id: &Id, category: Option<&Id>) {
4297    match category {
4298        Some(prev_cat) => {
4299            if let Some(cats) = space_val
4300                .get_mut("categories")
4301                .and_then(|v| v.as_array_mut())
4302            {
4303                for cat in cats.iter_mut() {
4304                    if cat.get("id").and_then(|s| s.as_str()) == Some(prev_cat.as_ref()) {
4305                        if let Some(ch_ids) =
4306                            cat.get_mut("channelIds").and_then(|v| v.as_array_mut())
4307                        {
4308                            ch_ids.retain(|v| v.as_str() != Some(id.as_ref()));
4309                        }
4310                        break;
4311                    }
4312                }
4313            }
4314        }
4315        None => {
4316            if let Some(unc) = space_val
4317                .get_mut("uncategorizedChannelIds")
4318                .and_then(|v| v.as_array_mut())
4319            {
4320                unc.retain(|v| v.as_str() != Some(id.as_ref()));
4321            }
4322        }
4323    }
4324}
4325
4326/// Append the channel `id` to its new home in the stored Space
4327/// `space_val`: the `channelIds` of its category `category`, or
4328/// `uncategorizedChannelIds`. A missing array is a `forbidden` internal
4329/// error.
4330fn place_channel(
4331    space_val: &mut serde_json::Value,
4332    id: &Id,
4333    category: Option<&Id>,
4334) -> Result<(), Box<SetError>> {
4335    if let Some(new_cat) = category {
4336        let cats = space_val
4337            .get_mut("categories")
4338            .and_then(|v| v.as_array_mut())
4339            .ok_or_else(categories_not_array)?;
4340        for cat in cats.iter_mut() {
4341            if cat.get("id").and_then(|s| s.as_str()) == Some(new_cat.as_ref()) {
4342                let ch_ids = cat
4343                    .get_mut("channelIds")
4344                    .and_then(|v| v.as_array_mut())
4345                    .ok_or_else(|| {
4346                        SetError::new(SetErrorType::Forbidden)
4347                            .with_description("internal: Category.channelIds not an array")
4348                    })?;
4349                ch_ids.push(serde_json::Value::String(id.as_ref().to_owned()));
4350                break;
4351            }
4352        }
4353    } else {
4354        let unc = space_val
4355            .get_mut("uncategorizedChannelIds")
4356            .and_then(|v| v.as_array_mut())
4357            .ok_or_else(|| {
4358                SetError::new(SetErrorType::Forbidden)
4359                    .with_description("internal: Space.uncategorizedChannelIds not an array")
4360            })?;
4361        unc.push(serde_json::Value::String(id.as_ref().to_owned()));
4362    }
4363    Ok(())
4364}
4365
4366// ===========================================================================
4367// Role + Member variant helpers (bd:JMAP-g7wu.2.4.3)
4368// ===========================================================================
4369
4370/// Apply `SpacePatchOp::AddRole`: assign a fresh `RoleId`, push the role
4371/// into `space.roles`. Permission and role-position hierarchy
4372/// enforcement happens in [`validate_space_patch_ops`] before this
4373/// helper runs.
4374fn apply_add_role(
4375    inner: &mut Inner,
4376    account_id: &str,
4377    space_id: &Id,
4378    op: SpacePatchOp,
4379    space_mutated: &mut bool,
4380) -> Result<Option<Id>, Box<SetError>> {
4381    let role = match op {
4382        SpacePatchOp::AddRole(r) => r,
4383        _ => unreachable!("apply_add_role called with non-AddRole variant"),
4384    };
4385
4386    // Mint a fresh RoleId (draft §Space/set `addRoles`: "Server assigns
4387    // ULIDs"). Inserting it after serializing overrides any client `id`
4388    // carried in `extra`.
4389    let new_id = inner.mint_id();
4390    let mut stored = serde_json::to_value(&role).map_err(|e| {
4391        SetError::new(SetErrorType::Forbidden)
4392            .with_description(format!("internal: serialize RoleCreate: {e}"))
4393    })?;
4394    if let Some(fields) = stored.as_object_mut() {
4395        fields.insert("id".to_owned(), serde_json::Value::from(new_id.as_ref()));
4396    }
4397
4398    let mut space_val = inner
4399        .objects_ref("Space", account_id)
4400        .and_then(|m| m.get(space_id))
4401        .cloned()
4402        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4403
4404    let roles = space_val
4405        .get_mut("roles")
4406        .and_then(|v| v.as_array_mut())
4407        .ok_or_else(|| {
4408            SetError::new(SetErrorType::Forbidden)
4409                .with_description("internal: Space.roles not an array")
4410        })?;
4411
4412    roles.push(stored);
4413
4414    inner
4415        .objects_mut("Space", account_id)
4416        .insert(space_id.clone(), space_val);
4417    *space_mutated = true;
4418    Ok(Some(new_id))
4419}
4420
4421/// Apply `SpacePatchOp::RemoveRole`: remove the named role and cascade-
4422/// demote any members whose only remaining role would be the removed
4423/// one (draft-atwood-jmap-chat-00 §Space/set L1263). Permission
4424/// and hierarchy checks happen in [`validate_space_patch_ops`].
4425fn apply_remove_role(
4426    inner: &mut Inner,
4427    account_id: &str,
4428    space_id: &Id,
4429    op: SpacePatchOp,
4430    chats_updated: &mut HashSet<Id>,
4431    space_mutated: &mut bool,
4432) -> Result<Option<Id>, Box<SetError>> {
4433    let target_id = match op {
4434        SpacePatchOp::RemoveRole(id) => id,
4435        _ => unreachable!("apply_remove_role called with non-RemoveRole variant"),
4436    };
4437
4438    let mut space_val = inner
4439        .objects_ref("Space", account_id)
4440        .and_then(|m| m.get(space_id))
4441        .cloned()
4442        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4443
4444    let roles = space_val
4445        .get_mut("roles")
4446        .and_then(|v| v.as_array_mut())
4447        .ok_or_else(|| {
4448            SetError::new(SetErrorType::Forbidden)
4449                .with_description("internal: Space.roles not an array")
4450        })?;
4451    let pos = roles
4452        .iter()
4453        .position(|v| v.get("id").and_then(|s| s.as_str()) == Some(target_id.as_ref()));
4454    let Some(pos) = pos else {
4455        return Err(Box::new(
4456            SetError::new(SetErrorType::NotFound)
4457                .with_description(format!("role {} not found", target_id.as_ref())),
4458        ));
4459    };
4460    roles.remove(pos);
4461
4462    // Cascade: members holding the removed role have it stripped from
4463    // their `roleIds`. Members whose only role was the removed one
4464    // are left with an empty `roleIds`, which is the `@everyone`-only
4465    // state (draft-atwood-jmap-chat-00 §Space/set L1263 + the
4466    // conventional empty-role-ids representation).
4467    if let Some(members) = space_val.get_mut("members").and_then(|v| v.as_array_mut()) {
4468        for member in members.iter_mut() {
4469            if let Some(role_ids) = member.get_mut("roleIds").and_then(|v| v.as_array_mut()) {
4470                role_ids.retain(|v| v.as_str() != Some(target_id.as_ref()));
4471            }
4472        }
4473    }
4474
4475    inner
4476        .objects_mut("Space", account_id)
4477        .insert(space_id.clone(), space_val);
4478    *space_mutated = true;
4479
4480    // Draft §Space/set `removeRoles` (jmap-chat-spec 77c3474 L1355):
4481    // "Servers MAY also remove each channel's `permissionOverrides` entries
4482    // whose `targetId` is a removed role"; this backend does so by choice.
4483    // Each channel changed here is reported as updated.
4484    for (chat_id, chat) in inner.objects_mut("Chat", account_id).iter_mut() {
4485        if chat.get("kind").and_then(|k| k.as_str()) != Some("channel")
4486            || chat.get("spaceId").and_then(|s| s.as_str()) != Some(space_id.as_ref())
4487        {
4488            continue;
4489        }
4490        let Some(overrides) = chat
4491            .get_mut("permissionOverrides")
4492            .and_then(|v| v.as_array_mut())
4493        else {
4494            continue;
4495        };
4496        let before = overrides.len();
4497        overrides.retain(|o| {
4498            o.get("targetType").and_then(|t| t.as_str()) != Some("role")
4499                || o.get("targetId").and_then(|t| t.as_str()) != Some(target_id.as_ref())
4500        });
4501        if overrides.len() != before {
4502            chats_updated.insert(chat_id.clone());
4503        }
4504    }
4505    Ok(None)
4506}
4507
4508/// Apply `SpacePatchOp::UpdateRole`: apply the
4509/// [`RolePatch`](jmap_chat_types::RolePatch) to the named role. Permission
4510/// and hierarchy checks happen in [`validate_space_patch_ops`].
4511fn apply_update_role(
4512    inner: &mut Inner,
4513    account_id: &str,
4514    space_id: &Id,
4515    op: SpacePatchOp,
4516    space_mutated: &mut bool,
4517) -> Result<Option<Id>, Box<SetError>> {
4518    use jmap_chat_types::Clearable;
4519    use jmap_chat_types::SpaceRole;
4520
4521    let (target_id, patch) = match op {
4522        SpacePatchOp::UpdateRole { id, patch } => (id, patch),
4523        _ => unreachable!("apply_update_role called with non-UpdateRole variant"),
4524    };
4525
4526    let mut space_val = inner
4527        .objects_ref("Space", account_id)
4528        .and_then(|m| m.get(space_id))
4529        .cloned()
4530        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4531
4532    let roles = space_val
4533        .get_mut("roles")
4534        .and_then(|v| v.as_array_mut())
4535        .ok_or_else(|| {
4536            SetError::new(SetErrorType::Forbidden)
4537                .with_description("internal: Space.roles not an array")
4538        })?;
4539    let pos = roles
4540        .iter()
4541        .position(|v| v.get("id").and_then(|s| s.as_str()) == Some(target_id.as_ref()));
4542    let Some(pos) = pos else {
4543        return Err(Box::new(
4544            SetError::new(SetErrorType::NotFound)
4545                .with_description(format!("role {} not found", target_id.as_ref())),
4546        ));
4547    };
4548
4549    // Deserialize, apply patch, re-serialize. The `#[non_exhaustive]`
4550    // attribute on `SpaceRole` makes the struct-expression update
4551    // syntax illegal, so the in-place mutation pattern is required.
4552    let mut role: SpaceRole = serde_json::from_value(roles[pos].clone()).map_err(|e| {
4553        SetError::new(SetErrorType::Forbidden)
4554            .with_description(format!("internal: deserialize SpaceRole: {e}"))
4555    })?;
4556    if let Some(name) = patch.name {
4557        role.name = name;
4558    }
4559    match patch.color {
4560        Some(Clearable::Set(c)) => role.color = Some(c),
4561        Some(Clearable::Clear) => role.color = None,
4562        None => {}
4563    }
4564    if let Some(permissions) = patch.permissions {
4565        role.permissions = permissions;
4566    }
4567    if let Some(position) = patch.position {
4568        role.position = position;
4569    }
4570    roles[pos] = serde_json::to_value(&role).map_err(|e| {
4571        SetError::new(SetErrorType::Forbidden)
4572            .with_description(format!("internal: serialize SpaceRole: {e}"))
4573    })?;
4574
4575    inner
4576        .objects_mut("Space", account_id)
4577        .insert(space_id.clone(), space_val);
4578    *space_mutated = true;
4579    Ok(None)
4580}
4581
4582/// Apply `SpacePatchOp::AddMember`: push a new `SpaceMember` into the
4583/// Space's `members` array and bump `memberCount`. Permission and
4584/// hierarchy checks (and existence checks on each role id) happen in
4585/// [`validate_space_patch_ops`].
4586fn apply_add_member(
4587    inner: &mut Inner,
4588    account_id: &str,
4589    space_id: &Id,
4590    op: SpacePatchOp,
4591    space_mutated: &mut bool,
4592) -> Result<Option<Id>, Box<SetError>> {
4593    let (user_id, role_ids) = match op {
4594        SpacePatchOp::AddMember(create) => (create.user_id, create.role_ids),
4595        _ => unreachable!("apply_add_member called with non-AddMember variant"),
4596    };
4597
4598    let mut space_val = inner
4599        .objects_ref("Space", account_id)
4600        .and_then(|m| m.get(space_id))
4601        .cloned()
4602        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4603    check_new_member(&space_val, &user_id, &role_ids)?;
4604
4605    // Build the wire-shape member object directly. `SpaceMember` is
4606    // `#[non_exhaustive]`, so the struct-expression construction is
4607    // illegal; serializing a freshly-built JSON Map sidesteps that.
4608    let mut member_obj = serde_json::Map::new();
4609    member_obj.insert(
4610        "id".to_owned(),
4611        serde_json::Value::String(user_id.as_ref().to_owned()),
4612    );
4613    member_obj.insert(
4614        "roleIds".to_owned(),
4615        serde_json::Value::Array(
4616            role_ids
4617                .iter()
4618                .map(|id| serde_json::Value::String(id.as_ref().to_owned()))
4619                .collect(),
4620        ),
4621    );
4622    member_obj.insert(
4623        "joinedAt".to_owned(),
4624        serde_json::Value::String(now_utc_string().into_inner()),
4625    );
4626
4627    let members = space_val
4628        .get_mut("members")
4629        .and_then(|v| v.as_array_mut())
4630        .ok_or_else(|| {
4631            SetError::new(SetErrorType::Forbidden)
4632                .with_description("internal: Space.members not an array")
4633        })?;
4634    members.push(serde_json::Value::Object(member_obj));
4635
4636    // Keep `memberCount` consistent with `members.len()`. The field
4637    // is required on Space (draft §4.11) and clients rely on it for
4638    // UI counts.
4639    let new_count = members.len() as u64;
4640    if let Some(count_field) = space_val.get_mut("memberCount") {
4641        *count_field = serde_json::Value::from(new_count);
4642    }
4643
4644    inner
4645        .objects_mut("Space", account_id)
4646        .insert(space_id.clone(), space_val);
4647    *space_mutated = true;
4648    Ok(None)
4649}
4650
4651/// Check an `addMembers` entry against the stored Space `space_val`: the
4652/// user `user_id` is not a member yet and every id in `role_ids` names a
4653/// role of the Space. Each failure is `invalidProperties`.
4654fn check_new_member(
4655    space_val: &serde_json::Value,
4656    user_id: &Id,
4657    role_ids: &[Id],
4658) -> Result<(), Box<SetError>> {
4659    // Reject if already a member: duplicate-add is an
4660    // invalidProperties error against the wire-level userId field.
4661    if space_val
4662        .get("members")
4663        .and_then(|v| v.as_array())
4664        .is_some_and(|members| {
4665            members
4666                .iter()
4667                .any(|m| m.get("id").and_then(|v| v.as_str()) == Some(user_id.as_ref()))
4668        })
4669    {
4670        return Err(Box::new(
4671            SetError::new(SetErrorType::InvalidProperties)
4672                .with_properties(vec!["userId".to_owned()])
4673                .with_description(format!(
4674                    "member {} is already a member of this Space",
4675                    user_id.as_ref()
4676                )),
4677        ));
4678    }
4679
4680    // Validate every role_id refers to an existing SpaceRole on this
4681    // Space. A nonexistent role_id would create a dangling
4682    // reference; reject as InvalidProperties on `roleIds`.
4683    if !role_ids.is_empty() {
4684        let existing: HashSet<String> = space_val
4685            .get("roles")
4686            .and_then(|v| v.as_array())
4687            .map(|arr| {
4688                arr.iter()
4689                    .filter_map(|r| r.get("id").and_then(|v| v.as_str()).map(str::to_owned))
4690                    .collect()
4691            })
4692            .unwrap_or_default();
4693        for rid in role_ids {
4694            if !existing.contains(rid.as_ref()) {
4695                return Err(Box::new(
4696                    SetError::new(SetErrorType::InvalidProperties)
4697                        .with_properties(vec!["roleIds".to_owned()])
4698                        .with_description(format!(
4699                            "role {} does not exist in this Space",
4700                            rid.as_ref()
4701                        )),
4702                ));
4703            }
4704        }
4705    }
4706    Ok(())
4707}
4708
4709/// Apply `SpacePatchOp::RemoveMember`: remove the named member and
4710/// decrement `memberCount`. Permission and last-admin-protection
4711/// checks happen in [`validate_space_patch_ops`].
4712fn apply_remove_member(
4713    inner: &mut Inner,
4714    account_id: &str,
4715    space_id: &Id,
4716    op: SpacePatchOp,
4717    space_mutated: &mut bool,
4718) -> Result<Option<Id>, Box<SetError>> {
4719    let target_id = match op {
4720        SpacePatchOp::RemoveMember(id) => id,
4721        _ => unreachable!("apply_remove_member called with non-RemoveMember variant"),
4722    };
4723
4724    let mut space_val = inner
4725        .objects_ref("Space", account_id)
4726        .and_then(|m| m.get(space_id))
4727        .cloned()
4728        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4729
4730    let members = space_val
4731        .get_mut("members")
4732        .and_then(|v| v.as_array_mut())
4733        .ok_or_else(|| {
4734            SetError::new(SetErrorType::Forbidden)
4735                .with_description("internal: Space.members not an array")
4736        })?;
4737
4738    let pos = members
4739        .iter()
4740        .position(|m| m.get("id").and_then(|v| v.as_str()) == Some(target_id.as_ref()));
4741    let Some(pos) = pos else {
4742        return Err(Box::new(
4743            SetError::new(SetErrorType::NotFound)
4744                .with_description(format!("member {} not found", target_id.as_ref())),
4745        ));
4746    };
4747    members.remove(pos);
4748
4749    // Keep `memberCount` consistent with `members.len()`.
4750    let new_count = members.len() as u64;
4751    if let Some(count_field) = space_val.get_mut("memberCount") {
4752        *count_field = serde_json::Value::from(new_count);
4753    }
4754
4755    inner
4756        .objects_mut("Space", account_id)
4757        .insert(space_id.clone(), space_val);
4758    *space_mutated = true;
4759    Ok(None)
4760}
4761
4762/// Apply `SpacePatchOp::UpdateMember`: apply the
4763/// [`MemberPatch`](jmap_chat_types::MemberPatch) to
4764/// the named member. Permission and hierarchy checks happen in
4765/// [`validate_space_patch_ops`].
4766fn apply_update_member(
4767    inner: &mut Inner,
4768    account_id: &str,
4769    space_id: &Id,
4770    op: SpacePatchOp,
4771    space_mutated: &mut bool,
4772) -> Result<Option<Id>, Box<SetError>> {
4773    use jmap_chat_types::Clearable;
4774
4775    let (user_id, patch) = match op {
4776        SpacePatchOp::UpdateMember { user_id, patch } => (user_id, patch),
4777        _ => unreachable!("apply_update_member called with non-UpdateMember variant"),
4778    };
4779
4780    let mut space_val = inner
4781        .objects_ref("Space", account_id)
4782        .and_then(|m| m.get(space_id))
4783        .cloned()
4784        .ok_or_else(|| SetError::new(SetErrorType::NotFound))?;
4785
4786    // Validate any new role ids referenced in the patch before mutating.
4787    if let Some(role_ids) = &patch.role_ids {
4788        let existing: HashSet<String> = space_val
4789            .get("roles")
4790            .and_then(|v| v.as_array())
4791            .map(|arr| {
4792                arr.iter()
4793                    .filter_map(|r| r.get("id").and_then(|v| v.as_str()).map(str::to_owned))
4794                    .collect()
4795            })
4796            .unwrap_or_default();
4797        for rid in role_ids {
4798            if !existing.contains(rid.as_ref()) {
4799                return Err(Box::new(
4800                    SetError::new(SetErrorType::InvalidProperties)
4801                        .with_properties(vec!["roleIds".to_owned()])
4802                        .with_description(format!(
4803                            "role {} does not exist in this Space",
4804                            rid.as_ref()
4805                        )),
4806                ));
4807            }
4808        }
4809    }
4810
4811    let members = space_val
4812        .get_mut("members")
4813        .and_then(|v| v.as_array_mut())
4814        .ok_or_else(|| {
4815            SetError::new(SetErrorType::Forbidden)
4816                .with_description("internal: Space.members not an array")
4817        })?;
4818
4819    let pos = members
4820        .iter()
4821        .position(|m| m.get("id").and_then(|v| v.as_str()) == Some(user_id.as_ref()));
4822    let Some(pos) = pos else {
4823        return Err(Box::new(
4824            SetError::new(SetErrorType::NotFound)
4825                .with_description(format!("member {} not found", user_id.as_ref())),
4826        ));
4827    };
4828
4829    // Apply the patch in place on the wire-shape JSON object. The
4830    // `SpaceMember` type is `#[non_exhaustive]`, so direct
4831    // struct-expression update is illegal; in-place edits on the
4832    // JSON map preserve unknown fields (extras-preservation policy).
4833    let member_obj = members[pos].as_object_mut().ok_or_else(|| {
4834        SetError::new(SetErrorType::Forbidden)
4835            .with_description("internal: SpaceMember not a JSON object")
4836    })?;
4837    if let Some(role_ids) = patch.role_ids {
4838        member_obj.insert(
4839            "roleIds".to_owned(),
4840            serde_json::Value::Array(
4841                role_ids
4842                    .iter()
4843                    .map(|id| serde_json::Value::String(id.as_ref().to_owned()))
4844                    .collect(),
4845            ),
4846        );
4847    }
4848    match patch.nick {
4849        Some(Clearable::Set(s)) => {
4850            member_obj.insert("nick".to_owned(), serde_json::Value::String(s));
4851        }
4852        Some(Clearable::Clear) => {
4853            member_obj.remove("nick");
4854        }
4855        None => {}
4856    }
4857
4858    inner
4859        .objects_mut("Space", account_id)
4860        .insert(space_id.clone(), space_val);
4861    *space_mutated = true;
4862    Ok(None)
4863}
4864
4865// ---------------------------------------------------------------------------
4866// Permission / hierarchy / last-admin pre-validation helpers
4867// (bd:JMAP-g7wu.2.4.3 criteria 1, 2, 3-replacement, 6, 7)
4868// ---------------------------------------------------------------------------
4869
4870/// Project the post-patch aggregate counts and reject the whole patch
4871/// with an `overQuota` [`SetError`] (RFC 8620 §5.3) if any aggregate
4872/// (roles, members, channels, categories) would exceed its cap from
4873/// [`ChatLimits`].
4874///
4875/// Backend-canonical cap enforcement per bd:JMAP-x2gd.44. The handler
4876/// at [`crate::space::handle_space_set`] runs a defense-in-depth
4877/// pre-flight check before this function fires, but the pre-flight
4878/// is non-load-bearing — a direct caller of `apply_space_patch`
4879/// (admin tool, federation receiver, batch importer) MUST still see
4880/// caps enforced.
4881///
4882/// Returns `None` if no `Add*` ops are present or all caps are
4883/// satisfied. Returns the first offending collection's `SetError`
4884/// otherwise — matching the handler's "first cap to trip" surface
4885/// for response shape parity.
4886///
4887/// Identity-independent and policy-rather-than-structural; the
4888/// sibling [`validate_space_patch_ops`] handles permission gating,
4889/// role-position hierarchy, and last-admin protection.
4890fn check_count_caps(
4891    space_val: &serde_json::Value,
4892    ops: &[SpacePatchOp],
4893    limits: &ChatLimits,
4894) -> Option<SetError> {
4895    let (add_roles, add_members, add_channels, add_categories) = crate::helpers::count_add_ops(ops);
4896    if add_roles == 0 && add_members == 0 && add_channels == 0 && add_categories == 0 {
4897        return None;
4898    }
4899
4900    let count_array = |key: &str| -> u32 {
4901        space_val
4902            .get(key)
4903            .and_then(|v| v.as_array())
4904            .map(|a| u32::try_from(a.len()).unwrap_or(u32::MAX))
4905            .unwrap_or(0)
4906    };
4907
4908    let cur_roles = count_array("roles");
4909    let cur_members = count_array("members");
4910    let cur_categories = count_array("categories");
4911    // Channels = uncategorizedChannelIds + sum(categories[].channelIds).
4912    let uncategorized = space_val
4913        .get("uncategorizedChannelIds")
4914        .and_then(|v| v.as_array())
4915        .map(|a| a.len())
4916        .unwrap_or(0);
4917    let categorized: usize = space_val
4918        .get("categories")
4919        .and_then(|v| v.as_array())
4920        .map(|arr| {
4921            arr.iter()
4922                .map(|c| {
4923                    c.get("channelIds")
4924                        .and_then(|v| v.as_array())
4925                        .map(|a| a.len())
4926                        .unwrap_or(0)
4927                })
4928                .sum()
4929        })
4930        .unwrap_or(0);
4931    let cur_channels = u32::try_from(uncategorized + categorized).unwrap_or(u32::MAX);
4932
4933    // Per-aggregate static description — names which aggregate was
4934    // exceeded without disclosing the per-Space count or the per-account
4935    // cap value. See bd:JMAP-x2gd.107: leaking either through an error
4936    // description back-channels deployment policy and membership counts
4937    // to any caller who can propose a /set patch. The aggregate name
4938    // alone is enough for a client to know which collection to retry
4939    // without; numeric counts and caps are deployment-private.
4940    let exceeded =
4941        |description: &'static str, current: u32, add: u32, cap: u32| -> Option<SetError> {
4942            if add == 0 {
4943                return None;
4944            }
4945            if current.saturating_add(add) > cap {
4946                Some(SetError::new(SetErrorType::OverQuota).with_description(description))
4947            } else {
4948                None
4949            }
4950        };
4951
4952    // First cap to trip determines the SetError (see `handle_space_set`'s
4953    // per-target single-error contract). `find_map` expresses that
4954    // ordered "first hit wins" semantic in one combinator chain rather
4955    // than four sequential `if-let-Some` early-returns.
4956    [
4957        (
4958            "too many roles",
4959            cur_roles,
4960            add_roles,
4961            limits.max_roles_per_space,
4962        ),
4963        (
4964            "too many members",
4965            cur_members,
4966            add_members,
4967            limits.max_space_members,
4968        ),
4969        (
4970            "too many channels",
4971            cur_channels,
4972            add_channels,
4973            limits.max_channels_per_space,
4974        ),
4975        (
4976            "too many categories",
4977            cur_categories,
4978            add_categories,
4979            limits.max_categories_per_space,
4980        ),
4981    ]
4982    .into_iter()
4983    .find_map(|(description, current, add, cap)| exceeded(description, current, add, cap))
4984}
4985
4986/// Pre-validate all ops in the patch.
4987///
4988/// Walks every op (Role, Member, Channel, Category) and applies:
4989///
4990/// - **Permission gating** (criterion 1): the caller's effective
4991///   permissions must be a superset of
4992///   [`required_permissions_for_op`](crate::required_permissions_for_op)'s
4993///   return value for each op. Gated permissions per
4994///   draft-atwood-jmap-chat-00 §Space/set:
4995///   * Role ops (`AddRole`, `RemoveRole`, `UpdateRole`): `manage_roles`
4996///   * Member ops (`AddMember`, `RemoveMember`): `manage_members`.
4997///     `UpdateMember`: `manage_roles` when it modifies `roleIds`,
4998///     `manage_members` when it changes `nick` (draft L1277)
4999///   * Channel ops (`AddChannel`, `RemoveChannel`, `UpdateChannel`)
5000///     and Category ops (`AddCategory`, `RemoveCategory`,
5001///     `UpdateCategory`): `manage_channels`
5002/// - **Role-position hierarchy** (criterion 2): the caller may only
5003///   add or modify roles whose `position` is strictly less than their
5004///   own highest-position role (draft §Space/set L1260, L1266).
5005///   Cross-cuts `AddRole`, `UpdateRole`, `AddMember` (when `role_ids` is
5006///   non-empty), and `UpdateMember` (when `patch.role_ids` is set: every
5007///   role the patch grants or removes, i.e. the symmetric difference
5008///   of the member's current and new `roleIds`, must rank below the
5009///   caller).
5010///   Channel and Category ops have no hierarchy check.
5011/// - **Last-admin protection** (criterion 3 replacement): when
5012///   `protect_last_admin` is true, the patch's ops in aggregate must
5013///   not take the Space from at least one member holding either
5014///   `manage_members` or `manage_space` to none; refused with
5015///   `invalidProperties` naming the patch key(s) concerned (see
5016///   [`last_admin_patch_keys`]). Self-removal (only
5017///   `account_id` in `removeMembers`) skips this check and the
5018///   `manage_members` gate, per draft §Space/set `removeMembers`.
5019///   Likewise a single `updateMembers` entry for `account_id` holding
5020///   only `nick` skips the `manage_members` gate, per draft §Space/set
5021///   `updateMembers`. The owner's own member entry is keyed by the
5022///   accountId (draft §Terminology), so self-operations compare against
5023///   `account_id`.
5024///
5025/// Returns `Ok(())` if the patch passes all checks. Returns
5026/// `Err(SetError)` on the FIRST failure encountered — this is the
5027/// whole-patch reject of criterion 6.
5028///
5029/// Permission gating and hierarchy resolve the caller's permissions
5030/// and role position from the `account_id` member entry, which is the
5031/// owner's (draft §Terminology), whether or not the backend resolves a
5032/// caller identity. The last-admin-protection check fires when its
5033/// config flag is on.
5034///
5035/// History: prior to bd:JMAP-g7wu.2.4.14 this helper was named
5036/// `validate_role_member_ops` and only gated Role/Member ops, leaving
5037/// the Channel and Category ops at the backend without a permission
5038/// pre-check. The rename + filter drop close that gap.
5039///
5040/// Per-aggregate count caps are enforced separately by the sibling
5041/// [`check_count_caps`] above — caps are identity-independent and
5042/// policy-rather-than-structural, so they are not part of this
5043/// validator.
5044fn validate_space_patch_ops(
5045    space_val: &serde_json::Value,
5046    account_id: &Id,
5047    ops: &[SpacePatchOp],
5048    protect_last_admin: bool,
5049    everyone: &HashSet<ChatPermission>,
5050) -> Result<(), Box<SetError>> {
5051    // Draft §Space/set `removeMembers`: a patch whose `removeMembers`
5052    // holds only the accountId is self-removal, which "the server
5053    // MUST permit ... regardless of the caller's permission set" and to
5054    // which "Last-administrator protection does not apply".
5055    let mut removed = ops.iter().filter_map(|op| match op {
5056        SpacePatchOp::RemoveMember(id) => Some(id),
5057        _ => None,
5058    });
5059    let self_removal =
5060        matches!((removed.next(), removed.next()), (Some(id), None) if id == account_id);
5061
5062    // Draft §Space/set `updateMembers`: "A member MAY set their own
5063    // `nick` by submitting `updateMembers` with a single entry whose `id`
5064    // is the accountId and which contains only `nick`; the server MUST
5065    // permit this regardless of the caller's permission set."
5066    let mut updated = ops.iter().filter_map(|op| match op {
5067        SpacePatchOp::UpdateMember { user_id, patch } => Some((user_id, patch)),
5068        _ => None,
5069    });
5070    let self_nick = match (updated.next(), updated.next()) {
5071        (Some((id, patch)), None) => {
5072            id == account_id
5073                && patch.nick.is_some()
5074                && patch.role_ids.is_none()
5075                && patch.extra.is_empty()
5076        }
5077        _ => false,
5078    };
5079
5080    // Permission gating + hierarchy.
5081    let caller_perms =
5082        caller_effective_permissions(space_val, account_id, everyone).unwrap_or_default();
5083    let caller_highest = caller_highest_position(space_val, account_id).unwrap_or(0);
5084
5085    for op in ops {
5086        let exempt = (self_removal && matches!(op, SpacePatchOp::RemoveMember(_)))
5087            || (self_nick && matches!(op, SpacePatchOp::UpdateMember { .. }));
5088        check_op_permissions(op, &caller_perms, exempt)?;
5089        check_op_hierarchy(space_val, op, caller_highest)?;
5090    }
5091
5092    // Last-admin protection. Draft §Space/set `removeMembers`: "The
5093    // same protection applies to an `updateMembers` role change, a
5094    // `removeRoles` entry, or an `updateRoles` permission change ...; a
5095    // refusal names the patch key concerned."
5096    if protect_last_admin && let Some(keys) = last_admin_patch_keys(space_val, ops, self_removal) {
5097        return Err(Box::new(
5098            SetError::new(SetErrorType::InvalidProperties)
5099                .with_properties(keys)
5100                .with_description(
5101                    "this patch would leave the Space with no \
5102                     `manage_members`/`manage_space` holder (last-admin protection)",
5103                ),
5104        ));
5105    }
5106
5107    Ok(())
5108}
5109
5110/// The permission gate of [`validate_space_patch_ops`] for one op: the
5111/// caller, holding `caller_perms`, must hold every permission the op
5112/// requires, none when `exempt` (a self-removal or self-`nick` update).
5113fn check_op_permissions(
5114    op: &SpacePatchOp,
5115    caller_perms: &HashSet<ChatPermission>,
5116    exempt: bool,
5117) -> Result<(), Box<SetError>> {
5118    use crate::permissions::{RequiredPermissions, required_permissions_for_op};
5119
5120    // Permission gate (criterion 1). Applies to ALL op
5121    // families. `required_permissions_for_op` returns the
5122    // per-variant permission set from draft-atwood-jmap-chat-00
5123    // §Space/set; a caller missing any required permission
5124    // triggers a whole-patch reject (criterion 6). An unknown
5125    // op variant fails closed via `RequiredPermissions::UnknownOp`
5126    // — the kit cannot enumerate permissions for a variant it
5127    // does not recognize, so the safe answer is "no, you cannot
5128    // apply it".
5129    // `RequiredPermissions` is `#[non_exhaustive]` at the public
5130    // crate boundary, but the compiler sees all variants from
5131    // within this crate. Match exhaustively on the in-crate
5132    // variant set so a future Conditional / Layered / etc. arm
5133    // forces a deliberate fail-closed decision at compile time
5134    // rather than silently routing through a wildcard.
5135    let required = match required_permissions_for_op(op) {
5136        RequiredPermissions::Known(slice) => slice,
5137        RequiredPermissions::UnknownOp => {
5138            return Err(Box::new(
5139                SetError::new(SetErrorType::Forbidden).with_description(format!(
5140                    "unknown SpacePatchOp variant `{}`; this version of \
5141                         the kit cannot determine its permission requirement, \
5142                         rejecting fail-closed",
5143                    variant_name(op)
5144                )),
5145            ));
5146        }
5147    };
5148    let required = if exempt { &[] } else { required };
5149    for req in required {
5150        if !caller_perms.contains(req) {
5151            return Err(Box::new(
5152                SetError::new(SetErrorType::Forbidden).with_description(format!(
5153                    "caller lacks required permission `{}` for {}",
5154                    req,
5155                    variant_name(op)
5156                )),
5157            ));
5158        }
5159    }
5160    Ok(())
5161}
5162
5163/// The role-position hierarchy gate of [`validate_space_patch_ops`] for
5164/// one op, against the caller's highest role position `caller_highest` in
5165/// the stored Space `space_val`.
5166fn check_op_hierarchy(
5167    space_val: &serde_json::Value,
5168    op: &SpacePatchOp,
5169    caller_highest: u64,
5170) -> Result<(), Box<SetError>> {
5171    // Hierarchy gate (criterion 2). Only applies to ops that
5172    // grant or modify role placements:
5173    //   - AddRole: the new role's position must be < caller's
5174    //     highest.
5175    //   - UpdateRole: both the existing role's position AND
5176    //     the new position (if patch.position is set) must
5177    //     be < caller's highest.
5178    //   - AddMember (when role_ids is non-empty): every
5179    //     role_id's position must be < caller's highest.
5180    //   - UpdateMember (when patch.role_ids is set): every
5181    //     role granted or removed (the symmetric difference of
5182    //     the member's current and new roleIds; roleIds is a
5183    //     full replacement) must be < caller's highest.
5184    //   - RemoveMember: no hierarchy check (removing a
5185    //     member doesn't reshape roles).
5186    //   - RemoveRole: the existing role's position must be <
5187    //     caller's highest.
5188    match op {
5189        SpacePatchOp::AddRole(role) if role.position >= caller_highest => {
5190            return Err(Box::new(hierarchy_error(
5191                role.position,
5192                caller_highest,
5193                "AddRole",
5194            )));
5195        }
5196        SpacePatchOp::RemoveRole(target_id) => {
5197            if let Some(pos) = role_position(space_val, target_id.as_ref())
5198                && pos >= caller_highest
5199            {
5200                return Err(Box::new(hierarchy_error(pos, caller_highest, "RemoveRole")));
5201            }
5202            // Nonexistent role id is a per-op NotFound, not
5203            // a permission failure — leave for the apply
5204            // pass.
5205        }
5206        SpacePatchOp::UpdateRole { id, patch } => {
5207            if let Some(pos) = role_position(space_val, id.as_ref())
5208                && pos >= caller_highest
5209            {
5210                return Err(Box::new(hierarchy_error(pos, caller_highest, "UpdateRole")));
5211            }
5212            if let Some(new_pos) = patch.position
5213                && new_pos >= caller_highest
5214            {
5215                return Err(Box::new(hierarchy_error(
5216                    new_pos,
5217                    caller_highest,
5218                    "UpdateRole (new position)",
5219                )));
5220            }
5221        }
5222        SpacePatchOp::AddMember(create) => {
5223            for rid in &create.role_ids {
5224                if let Some(pos) = role_position(space_val, rid.as_ref())
5225                    && pos >= caller_highest
5226                {
5227                    return Err(Box::new(hierarchy_error(pos, caller_highest, "AddMember")));
5228                }
5229                // Nonexistent role id surfaces in apply pass
5230                // as InvalidProperties.
5231            }
5232        }
5233        SpacePatchOp::UpdateMember { user_id, patch } => {
5234            if let Some(role_ids) = &patch.role_ids {
5235                let current = member_role_ids(space_val, user_id.as_ref());
5236                let new: HashSet<&str> = role_ids.iter().map(|r| r.as_ref()).collect();
5237                for rid in current.symmetric_difference(&new) {
5238                    if let Some(pos) = role_position(space_val, rid)
5239                        && pos >= caller_highest
5240                    {
5241                        return Err(Box::new(hierarchy_error(
5242                            pos,
5243                            caller_highest,
5244                            "UpdateMember",
5245                        )));
5246                    }
5247                }
5248            }
5249        }
5250        SpacePatchOp::RemoveMember(_) => {
5251            // No hierarchy check on member removal.
5252        }
5253        _ => {}
5254    }
5255    Ok(())
5256}
5257
5258/// The patch keys to name when `ops` would take the Space from at
5259/// least one member holding `manage_members` or `manage_space` to none;
5260/// `None` when an admin remains or the Space had none to begin with.
5261///
5262/// Projects the post-patch member/role graph across `removeMembers`,
5263/// `updateMembers` roleIds, `addMembers`, `removeRoles` and
5264/// `updateRoles` permissions. A self-removal entry is left out of the
5265/// projection: draft §Space/set says "Last-administrator protection
5266/// does not apply to self-removal." A key is named when one of its
5267/// entries, applied to the pre-patch graph, demotes an admin member or
5268/// an admin-granting role; the keys are listed in draft §Space/set
5269/// order.
5270fn last_admin_patch_keys(
5271    space_val: &serde_json::Value,
5272    ops: &[SpacePatchOp],
5273    self_removal: bool,
5274) -> Option<Vec<&'static str>> {
5275    // Role id -> whether the role grants an admin permission.
5276    let pre_roles = admin_roles(space_val);
5277    // Member id -> roleIds.
5278    let pre_members: HashMap<&str, HashSet<&str>> = space_val
5279        .get("members")
5280        .and_then(|v| v.as_array())
5281        .into_iter()
5282        .flatten()
5283        .filter_map(|m| {
5284            let id = m.get("id")?.as_str()?;
5285            Some((id, member_role_ids(space_val, id)))
5286        })
5287        .collect();
5288
5289    let is_admin = |roles: &HashMap<&str, bool>, role_ids: &HashSet<&str>| {
5290        role_ids
5291            .iter()
5292            .any(|r| roles.get(r).copied().unwrap_or(false))
5293    };
5294    if !pre_members.values().any(|ids| is_admin(&pre_roles, ids)) {
5295        return None;
5296    }
5297
5298    let mut roles = pre_roles.clone();
5299    let mut members = pre_members.clone();
5300    // Flags in draft §Space/set key order.
5301    let mut flagged = [false; 4];
5302    const KEYS: [&str; 4] = [
5303        "removeRoles",
5304        "updateRoles",
5305        "removeMembers",
5306        "updateMembers",
5307    ];
5308    for op in ops {
5309        match op {
5310            SpacePatchOp::RemoveRole(id) => {
5311                flagged[0] |= pre_roles.get(id.as_ref()).copied().unwrap_or(false);
5312                roles.remove(id.as_ref());
5313            }
5314            SpacePatchOp::UpdateRole { id, patch } => {
5315                if let (Some(perms), Some(admin)) = (&patch.permissions, roles.get_mut(id.as_ref()))
5316                {
5317                    *admin = perms.iter().any(|p| grants_admin(p.as_str()));
5318                    flagged[1] |= pre_roles[id.as_ref()] && !*admin;
5319                }
5320            }
5321            SpacePatchOp::RemoveMember(id) if !self_removal => {
5322                if let Some(ids) = pre_members.get(id.as_ref()) {
5323                    flagged[2] |= is_admin(&pre_roles, ids);
5324                }
5325                members.remove(id.as_ref());
5326            }
5327            SpacePatchOp::UpdateMember { user_id, patch } => {
5328                if let (Some(new), Some(cur)) = (&patch.role_ids, members.get_mut(user_id.as_ref()))
5329                {
5330                    *cur = new.iter().map(|r| r.as_ref()).collect();
5331                    flagged[3] |= pre_members
5332                        .get(user_id.as_ref())
5333                        .is_some_and(|pre| is_admin(&pre_roles, pre))
5334                        && !is_admin(&pre_roles, cur);
5335                }
5336            }
5337            SpacePatchOp::AddMember(create) => {
5338                members.insert(
5339                    create.user_id.as_ref(),
5340                    create.role_ids.iter().map(|r| r.as_ref()).collect(),
5341                );
5342            }
5343            _ => {}
5344        }
5345    }
5346
5347    if members.values().any(|ids| is_admin(&roles, ids)) {
5348        return None;
5349    }
5350    Some(
5351        KEYS.iter()
5352            .zip(flagged)
5353            .filter_map(|(k, f)| f.then_some(*k))
5354            .collect(),
5355    )
5356}
5357
5358/// Whether the permission `p` is an admin one for last-admin protection:
5359/// `manage_members` or `manage_space`.
5360fn grants_admin(p: &str) -> bool {
5361    p == ChatPermission::ManageMembers.as_str() || p == ChatPermission::ManageSpace.as_str()
5362}
5363
5364/// Each role id of the stored Space `space_val`, with whether the role
5365/// grants an admin permission ([`grants_admin`]).
5366fn admin_roles(space_val: &serde_json::Value) -> HashMap<&str, bool> {
5367    space_val
5368        .get("roles")
5369        .and_then(|v| v.as_array())
5370        .into_iter()
5371        .flatten()
5372        .filter_map(|r| {
5373            let id = r.get("id")?.as_str()?;
5374            let admin = r
5375                .get("permissions")
5376                .and_then(|v| v.as_array())
5377                .into_iter()
5378                .flatten()
5379                .filter_map(|p| p.as_str())
5380                .any(grants_admin);
5381            Some((id, admin))
5382        })
5383        .collect()
5384}
5385
5386/// Construct the standard "role position not strictly less than
5387/// caller's highest" `SetError`. Used by [`validate_space_patch_ops`].
5388fn hierarchy_error(target_pos: u64, caller_highest: u64, op_label: &str) -> SetError {
5389    SetError::new(SetErrorType::Forbidden).with_description(format!(
5390        "{op_label}: target role position {target_pos} is not strictly less than \
5391         caller's highest role position {caller_highest} (role-position hierarchy, \
5392         draft §Space/set L1260, L1266)"
5393    ))
5394}
5395
5396/// Resolve the caller's effective permission set within `space_val`.
5397///
5398/// `caller_id` is the caller's member entry id: the accountId, since
5399/// the caller is the owner (draft §Terminology). Returns the union of
5400/// `permissions` across every `SpaceRole` referenced by the caller's
5401/// `members[i].role_ids`, plus `everyone`, the implicit `@everyone`
5402/// role's permissions.
5403///
5404/// Returns `None` if the caller is not a member of the Space.
5405fn caller_effective_permissions(
5406    space_val: &serde_json::Value,
5407    caller_id: &Id,
5408    everyone: &HashSet<ChatPermission>,
5409) -> Option<HashSet<ChatPermission>> {
5410    member_effective_permissions(space_val, caller_id.as_ref(), everyone)
5411}
5412
5413/// Resolve `member_id`'s effective permission set within `space_val`.
5414/// Same semantics as [`caller_effective_permissions`] but keyed on a
5415/// raw string id (used by the last-admin-protection scan).
5416fn member_effective_permissions(
5417    space_val: &serde_json::Value,
5418    member_id: &str,
5419    everyone: &HashSet<ChatPermission>,
5420) -> Option<HashSet<ChatPermission>> {
5421    let members = space_val.get("members").and_then(|v| v.as_array())?;
5422    let member = members
5423        .iter()
5424        .find(|m| m.get("id").and_then(|v| v.as_str()) == Some(member_id))?;
5425    let role_ids: HashSet<String> = member
5426        .get("roleIds")
5427        .and_then(|v| v.as_array())
5428        .map(|arr| {
5429            arr.iter()
5430                .filter_map(|v| v.as_str().map(str::to_owned))
5431                .collect()
5432        })
5433        .unwrap_or_default();
5434    let mut perms = everyone.clone();
5435    if let Some(roles) = space_val.get("roles").and_then(|v| v.as_array()) {
5436        for role in roles {
5437            let Some(rid) = role.get("id").and_then(|v| v.as_str()) else {
5438                continue;
5439            };
5440            if !role_ids.contains(rid) {
5441                continue;
5442            }
5443            if let Some(role_perms) = role.get("permissions").and_then(|v| v.as_array()) {
5444                perms.extend(
5445                    role_perms
5446                        .iter()
5447                        .filter_map(|p| serde_json::from_value(p.clone()).ok()),
5448                );
5449            }
5450        }
5451    }
5452    Some(perms)
5453}
5454
5455/// The owner's permissions in channel Chat `chat`, resolved per
5456/// draft-atwood-jmap-chat-00 §Space Permission Resolution against the
5457/// owner's Space member entry (id = accountId, draft §Terminology).
5458///
5459/// Returns `None` when the containing Space does not exist, the owner is
5460/// not one of its members, or the stored `permissionOverrides` does not
5461/// parse; the caller then denies (fail closed).
5462fn owner_channel_permissions(
5463    inner: &Inner,
5464    account_id: &Id,
5465    chat: &serde_json::Value,
5466) -> Option<HashSet<ChatPermission>> {
5467    use crate::permissions::resolve_channel_permissions;
5468    use jmap_chat_types::ChannelPermission;
5469
5470    let space_id = chat.get("spaceId").and_then(|v| v.as_str())?;
5471    let space = inner
5472        .objects_ref("Space", account_id.as_ref())?
5473        .get(&Id::from(space_id))?;
5474    let base = caller_effective_permissions(space, account_id, inner.everyone_in(space))?;
5475    let overrides: Vec<ChannelPermission> = match chat.get("permissionOverrides") {
5476        None | Some(serde_json::Value::Null) => Vec::new(),
5477        Some(v) => serde_json::from_value(v.clone()).ok()?,
5478    };
5479    let role_ids = member_role_ids(space, account_id.as_ref());
5480    Some(resolve_channel_permissions(
5481        base,
5482        space_id,
5483        account_id.as_ref(),
5484        &role_ids,
5485        &overrides,
5486    ))
5487}
5488
5489/// The `created`, `updated` and `destroyed` ids of a `/changes` window,
5490/// the change-log entries `relevant` of type `type_name`, and the
5491/// properties each id's updates changed (draft-ietf-jmap-metadata-05
5492/// §3.3).
5493fn window_changes(
5494    relevant: &[&ChangeEntry],
5495    type_name: &str,
5496    mode: MetadataOnlyChanges,
5497) -> (Vec<Id>, Vec<Id>, Vec<Id>, ChangedProperties) {
5498    let (mut fates, mut order, mut window_props) = window_fates(relevant, type_name);
5499    fold_window_restores(relevant, &mut fates, &mut order, &mut window_props);
5500
5501    let mut created: Vec<Id> = Vec::new();
5502    let mut updated: Vec<Id> = Vec::new();
5503    let mut destroyed: Vec<Id> = Vec::new();
5504    // `fates.remove` emits each id once and skips ids omitted above.
5505    for id in order {
5506        match fates.remove(&id) {
5507            Some(IdFate::Created) => created.push(id),
5508            // -05 §3.3: under Ignore, "exclude from the updated array
5509            // any id whose only changes since sinceState ... are
5510            // confined to metadata and/or privateMetadata".
5511            Some(IdFate::Updated)
5512                if mode == MetadataOnlyChanges::Ignore
5513                    && window_props.is_metadata_only(id.as_ref()) => {}
5514            Some(IdFate::Updated) => updated.push(id),
5515            Some(IdFate::Destroyed) => destroyed.push(id),
5516            None => {}
5517        }
5518    }
5519    (created, updated, destroyed, window_props)
5520}
5521
5522/// The fate of each id created, updated or destroyed in the change-log
5523/// entries `relevant` of type `type_name`, the ids in first-seen order, and
5524/// the properties their updates changed.
5525///
5526/// RFC 8620 §5.2 ID deduplication across the window, using the
5527/// canonical jmap-mail-server `IdFate` rules. `order` keeps first-seen
5528/// order so the response lists are deterministic.
5529fn window_fates(
5530    relevant: &[&ChangeEntry],
5531    type_name: &str,
5532) -> (HashMap<Id, IdFate>, Vec<Id>, ChangedProperties) {
5533    let mut fates: HashMap<Id, IdFate> = HashMap::new();
5534    let mut order: Vec<Id> = Vec::new();
5535    let mut window_props = ChangedProperties::new();
5536    for entry in relevant {
5537        for id in &entry.created {
5538            if fates.insert(id.clone(), IdFate::Created).is_none() {
5539                order.push(id.clone());
5540            }
5541        }
5542        for id in &entry.updated {
5543            window_props.record(id.as_ref(), entry.updated_props.as_ref());
5544            let fate = match fates.get(id) {
5545                Some(IdFate::Created) => IdFate::Created,
5546                Some(IdFate::Destroyed) => IdFate::Destroyed,
5547                _ => IdFate::Updated,
5548            };
5549            if fates.insert(id.clone(), fate).is_none() {
5550                order.push(id.clone());
5551            }
5552        }
5553        for id in &entry.destroyed {
5554            // "If a record has been created AND destroyed since the old
5555            // state, the server SHOULD remove the id from the response
5556            // entirely." (RFC 8620 §5.2). Message is the exception:
5557            // "Servers SHOULD list it in `destroyed`: a client may have
5558            // learned of the Message through a push notification, and
5559            // needs the id to purge its copy." (draft-atwood-jmap-chat-00
5560            // §Message/changes)
5561            if type_name != "Message" && matches!(fates.get(id), Some(IdFate::Created)) {
5562                fates.remove(id);
5563            } else if fates.insert(id.clone(), IdFate::Destroyed).is_none() {
5564                order.push(id.clone());
5565            }
5566        }
5567    }
5568    (fates, order, window_props)
5569}
5570
5571/// Settle the fate of each id restored in the change-log entries
5572/// `relevant`.
5573///
5574/// Object history -04 §5.1: an id restored in the window is
5575/// classified by whether it existed at sinceState and exists now,
5576/// "exactly as if the object had never been destroyed between them".
5577fn fold_window_restores(
5578    relevant: &[&ChangeEntry],
5579    fates: &mut HashMap<Id, IdFate>,
5580    order: &mut Vec<Id>,
5581    window_props: &mut ChangedProperties,
5582) {
5583    let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
5584    for entry in relevant {
5585        for (ids, event) in [
5586            (&entry.created, ChangeEvent::Created),
5587            (&entry.updated, ChangeEvent::Updated),
5588            (&entry.destroyed, ChangeEvent::Destroyed),
5589            (&entry.restored, ChangeEvent::Restored),
5590        ] {
5591            for id in ids {
5592                events.entry(id.clone()).or_default().push(event);
5593            }
5594        }
5595    }
5596    for (id, list) in &events {
5597        if !list.contains(&ChangeEvent::Restored) {
5598            continue;
5599        }
5600        let fate = match fold_restore(list) {
5601            Some(ChangeKind::Created) => IdFate::Created,
5602            Some(ChangeKind::Destroyed) => IdFate::Destroyed,
5603            Some(_) => {
5604                // A restore is never metadata-only.
5605                window_props.record(id.as_ref(), None);
5606                IdFate::Updated
5607            }
5608            None => {
5609                fates.remove(id);
5610                continue;
5611            }
5612        };
5613        if fates.insert(id.clone(), fate).is_none() {
5614            order.push(id.clone());
5615        }
5616    }
5617}
5618
5619/// Whether the stored Message `msg` stays in a `Message/query` result for
5620/// `account_id`: the owner may view its Chat ([`owner_may_view_chat`]). A
5621/// Message without a `chatId` stays.
5622fn message_listed(inner: &Inner, msg: Option<&serde_json::Value>, account_id: &Id) -> bool {
5623    msg.and_then(|obj| obj.get("chatId"))
5624        .and_then(|v| v.as_str())
5625        .is_none_or(|cid| owner_may_view_chat(inner, account_id, &Id::from(cid)))
5626}
5627
5628/// Whether the stored Space `space` stays in a `Space/query` result for
5629/// `account_id`: the owner is a member, or `want_public` (the filter holds
5630/// `isPublic: true`) and the Space is public and publicly previewable
5631/// (draft-atwood-jmap-chat-00 §Space/query).
5632fn space_listed(space: &serde_json::Value, account_id: &Id, want_public: bool) -> bool {
5633    let flag = |k: &str| space.get(k).and_then(serde_json::Value::as_bool) == Some(true);
5634    let is_member = space
5635        .get("members")
5636        .and_then(|v| v.as_array())
5637        .is_some_and(|ms| {
5638            ms.iter()
5639                .any(|mm| mm.get("id").and_then(|v| v.as_str()) == Some(account_id.as_ref()))
5640        });
5641    is_member || (want_public && flag("isPublic") && flag("isPubliclyPreviewable"))
5642}
5643
5644/// Whether the owner may see the messages of Chat `chat_id`
5645/// (draft-atwood-jmap-chat-00 §Message/query `"view"` gate). Only
5646/// channel Chats are gated; an unknown Chat is visible.
5647fn owner_may_view_chat(inner: &Inner, account_id: &Id, chat_id: &Id) -> bool {
5648    let Some(chat) = inner
5649        .objects_ref("Chat", account_id.as_ref())
5650        .and_then(|m| m.get(chat_id))
5651    else {
5652        return true;
5653    };
5654    if chat.get("kind").and_then(|v| v.as_str()) != Some("channel") {
5655        return true;
5656    }
5657    owner_channel_permissions(inner, account_id, chat)
5658        .is_some_and(|perms| perms.contains(&ChatPermission::View))
5659}
5660
5661/// Resolve the caller's highest role `position` within `space_val`.
5662///
5663/// `caller_id` is the caller's member entry id (the accountId), as in
5664/// [`caller_effective_permissions`].
5665///
5666/// Returns `Some(max position)` if the caller is a member; the value
5667/// is at least 0 (a member with no explicit roles implicitly holds
5668/// `@everyone` at position 0). Returns `None` if the caller is not
5669/// a member of the Space.
5670fn caller_highest_position(space_val: &serde_json::Value, caller_id: &Id) -> Option<u64> {
5671    let members = space_val.get("members").and_then(|v| v.as_array())?;
5672    let member = members
5673        .iter()
5674        .find(|m| m.get("id").and_then(|v| v.as_str()) == Some(caller_id.as_ref()))?;
5675    let role_ids: HashSet<String> = member
5676        .get("roleIds")
5677        .and_then(|v| v.as_array())
5678        .map(|arr| {
5679            arr.iter()
5680                .filter_map(|v| v.as_str().map(str::to_owned))
5681                .collect()
5682        })
5683        .unwrap_or_default();
5684    let mut max: u64 = 0;
5685    if let Some(roles) = space_val.get("roles").and_then(|v| v.as_array()) {
5686        for role in roles {
5687            let Some(rid) = role.get("id").and_then(|v| v.as_str()) else {
5688                continue;
5689            };
5690            if !role_ids.contains(rid) {
5691                continue;
5692            }
5693            let Some(pos) = role.get("position").and_then(|v| v.as_u64()) else {
5694                continue;
5695            };
5696            if pos > max {
5697                max = pos;
5698            }
5699        }
5700    }
5701    Some(max)
5702}
5703
5704/// Look up an existing role's `position` by id.
5705/// The `roleIds` currently held by member `member_id`, or an empty set
5706/// when the member is absent (the apply pass reports `notFound`).
5707fn member_role_ids<'a>(space_val: &'a serde_json::Value, member_id: &str) -> HashSet<&'a str> {
5708    space_val
5709        .get("members")
5710        .and_then(|v| v.as_array())
5711        .and_then(|ms| {
5712            ms.iter()
5713                .find(|m| m.get("id").and_then(|v| v.as_str()) == Some(member_id))
5714        })
5715        .and_then(|m| m.get("roleIds"))
5716        .and_then(|v| v.as_array())
5717        .map(|ids| ids.iter().filter_map(|v| v.as_str()).collect())
5718        .unwrap_or_default()
5719}
5720
5721fn role_position(space_val: &serde_json::Value, role_id: &str) -> Option<u64> {
5722    let roles = space_val.get("roles").and_then(|v| v.as_array())?;
5723    roles
5724        .iter()
5725        .find(|r| r.get("id").and_then(|v| v.as_str()) == Some(role_id))
5726        .and_then(|r| r.get("position").and_then(|v| v.as_u64()))
5727}
5728
5729// ---------------------------------------------------------------------------
5730// Message filter helpers (draft-atwood-jmap-chat-00 §4.13)
5731// ---------------------------------------------------------------------------
5732
5733/// A broadcast mention whose scope resolves to include the owner
5734/// satisfies hasMention. The [`MemoryBackend`] reference impl resolves:
5735///   "everyone" -> true (owner is always a member)
5736///   "here"     -> true (reference impl: all accounts active)
5737///   "admins"   -> `owner_is_admin()` (see [`owner_is_chat_admin`])
5738/// Unknown scopes -> false (defensive: do not match on unrecognized scope)
5739fn broadcast_mention_matches_owner(
5740    bm: &serde_json::Value,
5741    owner_is_admin: impl FnOnce() -> bool,
5742) -> bool {
5743    match bm.get("scope").and_then(|v| v.as_str()) {
5744        Some("everyone") => true,
5745        Some("here") => true,
5746        Some("admins") => owner_is_admin(),
5747        _ => false, // unknown scope: conservative no-match
5748    }
5749}
5750
5751/// Whether the owner holds administrative authority in the Chat
5752/// `chat_id`, the reference impl's predicate for the `"admins"`
5753/// broadcast scope.
5754///
5755/// draft-atwood-jmap-chat-00 §`BroadcastMention`: `"admins"` is "members
5756/// holding administrative authority in the Space or Chat; the predicate
5757/// that defines "admin" ... is deployment-defined". The predicate here
5758/// is evaluated against the owner's member entry (accountId):
5759/// - group: the owner's `ChatMember` `role` is `"admin"` (§`ChatMember`);
5760/// - channel: the owner's Space permissions include `"manage_members"`
5761///   or `"manage_space"`, the holders §Space/set last-administrator
5762///   protection keeps;
5763/// - direct, or a Chat that is not stored: no admins.
5764fn owner_is_chat_admin(
5765    inner: &Inner,
5766    account_id: &Id,
5767    chat_id: Option<&serde_json::Value>,
5768) -> bool {
5769    let Some(chat) = chat_id.and_then(|v| v.as_str()).and_then(|id| {
5770        inner
5771            .objects_ref("Chat", account_id.as_ref())?
5772            .get(&Id::from(id))
5773    }) else {
5774        return false;
5775    };
5776    match chat.get("kind").and_then(|v| v.as_str()) {
5777        Some("group") => is_group_admin(chat, account_id),
5778        Some("channel") => chat
5779            .get("spaceId")
5780            .and_then(|v| v.as_str())
5781            .and_then(|sid| {
5782                inner
5783                    .objects_ref("Space", account_id.as_ref())?
5784                    .get(&Id::from(sid))
5785            })
5786            .and_then(|space| {
5787                caller_effective_permissions(space, account_id, inner.everyone_in(space))
5788            })
5789            .is_some_and(|perms| {
5790                perms.contains(&ChatPermission::ManageMembers)
5791                    || perms.contains(&ChatPermission::ManageSpace)
5792            }),
5793        _ => false,
5794    }
5795}
5796
5797/// Whether `member_id`'s entry in group `chat`'s `members` has
5798/// `role: "admin"` (draft-atwood-jmap-chat-00 §`ChatMember`).
5799fn is_group_admin(chat: &serde_json::Value, member_id: &Id) -> bool {
5800    chat.get("members")
5801        .and_then(|v| v.as_array())
5802        .is_some_and(|members| {
5803            members.iter().any(|m| {
5804                m.get("id").and_then(|v| v.as_str()) == Some(member_id.as_ref())
5805                    && m.get("role").and_then(|v| v.as_str()) == Some("admin")
5806            })
5807        })
5808}
5809
5810/// The id of a stored `CustomEmoji` other than `except` with the same
5811/// `name` and scope as `emoji`.
5812///
5813/// draft-atwood-jmap-chat-00 §`CustomEmoji` `name`: "MUST be unique within
5814/// its scope (Space or server-global)." The scope is `spaceId`; an absent
5815/// or null `spaceId` is the server-global scope.
5816fn emoji_name_holder(
5817    inner: &Inner,
5818    account_id: &Id,
5819    emoji: &serde_json::Value,
5820    except: Option<&Id>,
5821) -> Option<Id> {
5822    let scope = |e: &serde_json::Value| e.get("spaceId").filter(|v| !v.is_null()).cloned();
5823    inner
5824        .objects_ref("CustomEmoji", account_id.as_ref())?
5825        .iter()
5826        .find(|(id, e)| {
5827            Some(*id) != except && e.get("name") == emoji.get("name") && scope(e) == scope(emoji)
5828        })
5829        .map(|(id, _)| id.clone())
5830}
5831
5832/// The `spaceId` of a stored `CustomEmoji`; `None` for a server-global one.
5833fn emoji_scope(emoji: &serde_json::Value) -> Option<serde_json::Value> {
5834    emoji.get("spaceId").filter(|v| !v.is_null()).cloned()
5835}
5836
5837/// How many stored `CustomEmoji` of `account_id` belong to Space `space`,
5838/// for [`ChatLimits::max_custom_emoji_per_space`].
5839fn emoji_count_in_space(inner: &Inner, account_id: &str, space: &serde_json::Value) -> u64 {
5840    inner.objects_ref("CustomEmoji", account_id).map_or(0, |m| {
5841        m.values()
5842            .filter(|e| emoji_scope(e).as_ref() == Some(space))
5843            .fold(0, |n, _| n.saturating_add(1))
5844    })
5845}
5846
5847/// Whether the blob of `emoji` is larger than
5848/// [`ChatLimits::max_custom_emoji_bytes`]. The size is the one recorded
5849/// with `MemoryBackend::set_attachment_blob_for_test`, the same store
5850/// [`ChatResolvers::attachment_blob`] reports; an unrecorded blob is not
5851/// checked, as there.
5852fn emoji_blob_over_cap(
5853    inner: &Inner,
5854    account_id: &Id,
5855    emoji: &serde_json::Value,
5856    limits: &ChatLimits,
5857) -> bool {
5858    let (Some(max), Some(blob_id)) = (
5859        limits.max_custom_emoji_bytes,
5860        emoji.get("blobId").and_then(serde_json::Value::as_str),
5861    ) else {
5862        return false;
5863    };
5864    inner
5865        .attachment_blobs
5866        .get(&(account_id.as_ref().to_owned(), Id::from(blob_id)))
5867        .is_some_and(|b| b.size > max)
5868}
5869
5870/// An `overQuota` [`SetError`] (RFC 8620 §5.3) with a static `description`.
5871fn over_quota_error(description: &str) -> BackendSetError<MemoryError> {
5872    BackendSetError::SetError(Box::new(
5873        SetError::new(SetErrorType::OverQuota).with_description(description),
5874    ))
5875}
5876
5877/// Order two stored objects by RFC 8620 §5.5 `sort` comparators
5878/// (`property`, `isAscending` defaulting to `true`).
5879///
5880/// An absent or null property sorts last in either direction
5881/// (draft-atwood-jmap-chat-00 §ChatContact/query "`ChatContact`s for which
5882/// the field is absent sort last"; §Chat/query "chats without messages
5883/// sort last").
5884///
5885/// Two `UTCDate` strings compare chronologically ([`utc_date_key`]): RFC
5886/// 8620 §1.4 omits a zero time-secfrac, so byte-wise `...:05Z` sorts
5887/// after `...:05.001Z` (bd:JMAP-rvp2).
5888///
5889/// ponytail: other strings compare byte-wise, ignoring `collation`.
5890/// Values of mismatched JSON types compare equal.
5891fn compare_by_sort(
5892    a: &serde_json::Value,
5893    b: &serde_json::Value,
5894    comparators: &[serde_json::Value],
5895) -> std::cmp::Ordering {
5896    use serde_json::Value;
5897    use std::cmp::Ordering;
5898    for c in comparators {
5899        let Some(property) = c.get("property").and_then(Value::as_str) else {
5900            continue;
5901        };
5902        let x = a.get(property).filter(|v| !v.is_null());
5903        let y = b.get(property).filter(|v| !v.is_null());
5904        let ord = match (x, y) {
5905            (None, None) => Ordering::Equal,
5906            (None, Some(_)) => Ordering::Greater,
5907            (Some(_), None) => Ordering::Less,
5908            (Some(x), Some(y)) => {
5909                let ord = match (x, y) {
5910                    (Value::String(x), Value::String(y)) => {
5911                        match (utc_date_key(x), utc_date_key(y)) {
5912                            (Some(x), Some(y)) => x.cmp(&y),
5913                            _ => x.cmp(y),
5914                        }
5915                    }
5916                    (Value::Number(x), Value::Number(y)) => x
5917                        .as_f64()
5918                        .partial_cmp(&y.as_f64())
5919                        .unwrap_or(Ordering::Equal),
5920                    (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
5921                    _ => Ordering::Equal,
5922                };
5923                if c.get("isAscending").and_then(Value::as_bool) == Some(false) {
5924                    ord.reverse()
5925                } else {
5926                    ord
5927                }
5928            }
5929        };
5930        if ord != Ordering::Equal {
5931            return ord;
5932        }
5933    }
5934    Ordering::Equal
5935}
5936
5937/// Chronological sort key of an RFC 8620 §1.4 `UTCDate` string: whole
5938/// epoch seconds, then the fraction digits without trailing zeros, which
5939/// order lexicographically as they do numerically. `None` when `s` is not
5940/// a `UTCDate`.
5941fn utc_date_key(s: &str) -> Option<(i64, &str)> {
5942    let secs = jmap_types::UTCDate::from(s).to_epoch_seconds().ok()?;
5943    let frac = s
5944        .strip_suffix('Z')?
5945        .split_once('.')
5946        .map_or("", |(_, f)| f.trim_end_matches('0'));
5947    Some((secs, frac))
5948}
5949
5950/// Check whether a stored object of type `type_name` passes an RFC 8620
5951/// §5.5 filter: a `FilterOperator` (`AND` / `OR` / `NOT` over `conditions`)
5952/// or a type-specific `FilterCondition` (see [`condition_matches`]).
5953fn filter_matches(
5954    inner: &Inner,
5955    type_name: &str,
5956    obj: &serde_json::Value,
5957    filter: &serde_json::Value,
5958    account_id: &Id,
5959) -> bool {
5960    let mut conditions = filter
5961        .get("conditions")
5962        .and_then(serde_json::Value::as_array)
5963        .into_iter()
5964        .flatten();
5965    let sub = |f: &serde_json::Value| filter_matches(inner, type_name, obj, f, account_id);
5966    // RFC 8620 §5.5: "AND: All of the conditions must match", "OR: At
5967    // least one of the conditions must match", "NOT: None of the
5968    // conditions must match".
5969    match filter.get("operator").and_then(serde_json::Value::as_str) {
5970        Some("AND") => conditions.all(sub),
5971        Some("OR") => conditions.any(sub),
5972        Some("NOT") => !conditions.any(sub),
5973        _ => condition_matches(inner, type_name, obj, filter, account_id),
5974    }
5975}
5976
5977/// The six draft-ietf-jmap-metadata-05 §3.6 `FilterCondition` fields.
5978const METADATA_CONDITION_KEYS: [&str; 6] = [
5979    "metadataExists",
5980    "privateMetadataExists",
5981    "metadataTextContains",
5982    "privateMetadataTextContains",
5983    "metadataTextEquals",
5984    "privateMetadataTextEquals",
5985];
5986
5987/// Validate the draft-ietf-jmap-metadata-05 §3.6 conditions on every leaf
5988/// of `filter`, a `FilterCondition` or `FilterOperator` tree (RFC 8620 §5.5),
5989/// before any object is matched.
5990///
5991/// A type without `info` has no metadata (-05 §1.2.1: it "does not gain
5992/// the metadata or privateMetadata properties"), so a metadata leaf is
5993/// `unsupportedFilter` (RFC 8620 §5.5: "The filter is syntactically valid,
5994/// but the server cannot process it"). Otherwise
5995/// [`MetadataCondition::take_from`] applies -05 §3.6: a malformed path is
5996/// `invalidArguments`, and a `privateMetadata*` condition is
5997/// `unsupportedFilter` because `supportsPrivate` is false.
5998fn check_metadata_filter(
5999    filter: &serde_json::Value,
6000    info: Option<&DataTypeMetadataInfo>,
6001) -> Result<(), BackendQueryError<MemoryError>> {
6002    let unsupported = |description: String| {
6003        let mut err = jmap_types::JmapError::unsupported_filter();
6004        err.description = Some(description);
6005        BackendQueryError::Method(err)
6006    };
6007    if filter.get("operator").is_some() {
6008        return filter
6009            .get("conditions")
6010            .and_then(serde_json::Value::as_array)
6011            .into_iter()
6012            .flatten()
6013            .try_for_each(|f| check_metadata_filter(f, info));
6014    }
6015    let Some(leaf) = filter.as_object() else {
6016        return Ok(());
6017    };
6018    if !METADATA_CONDITION_KEYS
6019        .iter()
6020        .any(|k| leaf.contains_key(*k))
6021    {
6022        return Ok(());
6023    }
6024    let Some(info) = info else {
6025        return Err(unsupported(
6026            "metadata filter conditions are not supported".to_owned(),
6027        ));
6028    };
6029    MetadataCondition::take_from(&mut leaf.clone(), info)
6030        .map(drop)
6031        .map_err(|e| match e {
6032            MetadataFilterError::InvalidArguments(d) => {
6033                BackendQueryError::Method(jmap_types::JmapError::invalid_arguments(d))
6034            }
6035            other => unsupported(other.to_string()),
6036        })
6037}
6038
6039/// Whether a stored object passes the draft-ietf-jmap-metadata-05 §3.6
6040/// conditions of one `FilterCondition` `cond`, matched against its
6041/// `metadata` (absent means `{}`, -05 §2). A leaf without them matches.
6042/// The `privateMetadata*` conditions never reach this point:
6043/// [`check_metadata_filter`] rejects them, since this backend has
6044/// `supportsPrivate` false.
6045fn metadata_leaf_matches(obj: &serde_json::Value, cond: &serde_json::Value) -> bool {
6046    <MetadataCondition as serde::Deserialize>::deserialize(cond)
6047        .is_ok_and(|c| c.matches(obj.get("metadata").and_then(|m| m.as_object()), None))
6048}
6049
6050/// Whether `filter`, a `FilterCondition` or a `FilterOperator` tree (RFC 8620
6051/// §5.5), contains an `isPublic: true` `FilterCondition` at any depth.
6052fn has_is_public_true(filter: &serde_json::Value) -> bool {
6053    filter.get("isPublic") == Some(&serde_json::Value::Bool(true))
6054        || filter
6055            .get("conditions")
6056            .and_then(serde_json::Value::as_array)
6057            .is_some_and(|cs| cs.iter().any(has_is_public_true))
6058}
6059
6060/// Check whether a stored object passes one `FilterCondition` of the
6061/// draft-atwood-jmap-chat-00 `/query` method for `type_name`; all supplied
6062/// keys must match (AND semantics).
6063///
6064/// - Chat (§Chat/query): `kind`, `muted`.
6065/// - `ChatContact` (§ChatContact/query): `blocked`, `presence`, and
6066///   `identity` ("equals the value octet for octet").
6067/// - Message: see [`message_matches_filter`].
6068/// - Space (§Space/query): `name` ("substring match"), `isPublic`.
6069/// - `CustomEmoji` (§CustomEmoji/query): `spaceId`; absent returns all.
6070/// - Chat, Message and Space also take the draft-ietf-jmap-metadata-05
6071///   §3.6 conditions; see [`metadata_leaf_matches`].
6072///
6073/// A Boolean property absent from the stored object takes its `false`
6074/// default.
6075fn condition_matches(
6076    inner: &Inner,
6077    type_name: &str,
6078    obj: &serde_json::Value,
6079    cond: &serde_json::Value,
6080    account_id: &Id,
6081) -> bool {
6082    let eq = |k: &str| cond.get(k).is_none_or(|want| obj.get(k) == Some(want));
6083    let flag_eq = |k: &str| {
6084        cond.get(k)
6085            .and_then(serde_json::Value::as_bool)
6086            .is_none_or(|want| {
6087                obj.get(k)
6088                    .and_then(serde_json::Value::as_bool)
6089                    .unwrap_or(false)
6090                    == want
6091            })
6092    };
6093    match type_name {
6094        "Chat" => eq("kind") && flag_eq("muted") && metadata_leaf_matches(obj, cond),
6095        "ChatContact" => flag_eq("blocked") && eq("presence") && eq("identity"),
6096        "Message" => {
6097            message_matches_filter(inner, obj, cond, account_id)
6098                && metadata_leaf_matches(obj, cond)
6099                && message_where_matches(inner, obj, cond)
6100        }
6101        "Space" => {
6102            flag_eq("isPublic")
6103                && metadata_leaf_matches(obj, cond)
6104                && cond
6105                    .get("name")
6106                    .and_then(serde_json::Value::as_str)
6107                    .is_none_or(|part| {
6108                        obj.get("name")
6109                            .and_then(serde_json::Value::as_str)
6110                            .is_some_and(|name| name.contains(part))
6111                    })
6112        }
6113        "CustomEmoji" => eq("spaceId"),
6114        _ => true,
6115    }
6116}
6117
6118/// Check whether a stored Message JSON value passes one
6119/// draft-atwood-jmap-chat-00 §Message/query `FilterCondition`.
6120///
6121/// Supported filter keys (`text` is refused by the handler):
6122/// - `chatId`, `threadRootId`, `topicId`: exact match against the
6123///   message's field of the same name
6124/// - `hasAttachment`: whether `attachments` is non-empty
6125/// - `hasMention`: whether the message mentions the owner — either a
6126///   `mentions` entry whose `id` is `account_id` or a `broadcastMentions`
6127///   entry whose scope resolves to include the owner via
6128///   [`broadcast_mention_matches_owner`]
6129///
6130/// All supplied filter keys must match (AND semantics).
6131fn message_matches_filter(
6132    inner: &Inner,
6133    obj: &serde_json::Value,
6134    filter: &serde_json::Value,
6135    account_id: &Id,
6136) -> bool {
6137    // §Message/query `chatId`, `threadRootId` ("Return only messages in
6138    // this thread") and `topicId` ("Return only messages whose `topicId`
6139    // equals this value"). An encrypted Message carries no `topicId`, so
6140    // it never matches that filter.
6141    let eq = |k: &str| filter.get(k).is_none_or(|want| obj.get(k) == Some(want));
6142    if !(eq("chatId") && eq("threadRootId") && eq("topicId")) {
6143        return false;
6144    }
6145
6146    // §Message/query `hasAttachment`: "Filter to messages with or without
6147    // attachments."
6148    if let Some(want) = filter.get("hasAttachment").and_then(|v| v.as_bool()) {
6149        let has = obj
6150            .get("attachments")
6151            .and_then(|v| v.as_array())
6152            .is_some_and(|a| !a.is_empty());
6153        if has != want {
6154            return false;
6155        }
6156    }
6157
6158    // draft-atwood-jmap-chat-00 §Message/query `hasMention`: "the
6159    // accountId appears in `mentions`, OR `broadcastMentions` contains a
6160    // scope whose resolved recipient set includes the owner."
6161    if let Some(want) = filter.get("hasMention").and_then(|v| v.as_bool()) {
6162        let has_direct = obj
6163            .get("mentions")
6164            .and_then(|v| v.as_array())
6165            .is_some_and(|arr| {
6166                arr.iter()
6167                    .any(|m| m.get("id").and_then(|v| v.as_str()) == Some(account_id.as_ref()))
6168            });
6169        let has = has_direct
6170            || obj
6171                .get("broadcastMentions")
6172                .and_then(|v| v.as_array())
6173                .is_some_and(|arr| {
6174                    arr.iter().any(|bm| {
6175                        broadcast_mention_matches_owner(bm, || {
6176                            owner_is_chat_admin(inner, account_id, obj.get("chatId"))
6177                        })
6178                    })
6179                });
6180        if has != want {
6181            return false;
6182        }
6183    }
6184
6185    true
6186}
6187
6188/// Every JMAP Search `where` in the `type_name` filter `filter` checked
6189/// against `search`, the backend's capability (crate-jmap
6190/// docs/specs/jmap-search.md §Errors), so a direct `query_objects` call
6191/// cannot evaluate an expression the handlers would refuse.
6192/// `unsupportedFilter` without the capability, and for a type that is not
6193/// listed in it.
6194fn check_where(
6195    filter: &serde_json::Value,
6196    type_name: &str,
6197    search: Option<&jmap_search::SearchCapability>,
6198) -> Result<(), BackendQueryError<MemoryError>> {
6199    for w in jmap_search::where_values(filter) {
6200        let Some(cap) = search else {
6201            return Err(BackendQueryError::Method(
6202                jmap_types::JmapError::unsupported_filter(),
6203            ));
6204        };
6205        jmap_search::check_where(w, type_name, cap).map_err(BackendQueryError::Method)?;
6206    }
6207    Ok(())
6208}
6209
6210/// Whether the stored Message `obj` passes the JMAP Search `where` of the
6211/// `FilterCondition` `cond` (crate-jmap docs/specs/jmap-search.md); a
6212/// condition without `where` passes, and one that does not parse (which
6213/// the handler and [`check_where`] refuse first) fails.
6214///
6215/// The candidate is `obj` without `editHistory` unless edit history is
6216/// retained, as `Message/get` returns it; `$text` is a case-insensitive
6217/// (`i;unicode-casemap`) substring of `body`.
6218fn message_where_matches(inner: &Inner, obj: &serde_json::Value, cond: &serde_json::Value) -> bool {
6219    struct MessageCandidate(serde_json::Value);
6220    impl jmap_search::Candidate for MessageCandidate {
6221        fn field(&self, pointer: &str) -> Option<&serde_json::Value> {
6222            self.0.pointer(pointer)
6223        }
6224        fn matches_text(&self, text: &str) -> bool {
6225            let casemap = Some("i;unicode-casemap");
6226            self.0
6227                .get("body")
6228                .and_then(serde_json::Value::as_str)
6229                .is_some_and(|b| {
6230                    jmap_search::collate(b, casemap).contains(&*jmap_search::collate(text, casemap))
6231                })
6232        }
6233    }
6234    let Some(w) = cond.get("where").filter(|w| !w.is_null()) else {
6235        return true;
6236    };
6237    let Ok(expr) = jmap_search::Expression::parse(w) else {
6238        return false;
6239    };
6240    let mut json = obj.clone();
6241    if !inner.retains_edit_history
6242        && let Some(m) = json.as_object_mut()
6243    {
6244        m.remove("editHistory");
6245    }
6246    expr.matches(&MessageCandidate(json))
6247}
6248
6249/// Return every Message id whose `chatId` field equals `chat_id`.
6250fn scan_messages_in_chat(inner: &Inner, account_id: &str, chat_id: &Id) -> Vec<Id> {
6251    let Some(msgs) = inner.objects_ref("Message", account_id) else {
6252        return Vec::new();
6253    };
6254    msgs.iter()
6255        .filter(|(_, v)| v.get("chatId").and_then(|c| c.as_str()) == Some(chat_id.as_ref()))
6256        .map(|(id, _)| id.clone())
6257        .collect()
6258}
6259
6260/// Destroy the `ReadPosition` of every Chat in `chat_ids`, recording one
6261/// `ReadPosition` change entry when anything was removed.
6262///
6263/// draft-atwood-jmap-chat-00 §`ReadPosition`: the server "destroys it when
6264/// the Chat is destroyed". The caller holds the lock that destroyed the
6265/// Chats, so the cascade is atomic with it.
6266fn destroy_read_positions(inner: &mut Inner, account_id: &str, chat_ids: &[Id]) {
6267    let doomed: Vec<Id> = inner
6268        .objects_ref("ReadPosition", account_id)
6269        .map(|positions| {
6270            positions
6271                .iter()
6272                .filter(|(_, v)| {
6273                    v.get("chatId")
6274                        .and_then(|c| c.as_str())
6275                        .is_some_and(|c| chat_ids.iter().any(|id| id.as_ref() == c))
6276                })
6277                .map(|(id, _)| id.clone())
6278                .collect()
6279        })
6280        .unwrap_or_default();
6281    if doomed.is_empty() {
6282        return;
6283    }
6284    let positions = inner.objects_mut("ReadPosition", account_id);
6285    for id in &doomed {
6286        positions.remove(id);
6287    }
6288    let new_state = inner.bump_state("ReadPosition", account_id);
6289    inner
6290        .change_log_mut("ReadPosition", account_id)
6291        .push(ChangeEntry {
6292            new_state,
6293            created: vec![],
6294            updated: vec![],
6295            destroyed: doomed,
6296            restored: vec![],
6297            updated_props: None,
6298        });
6299}
6300
6301/// True if `chat_id` names an existing Chat with kind=channel and
6302/// `space_id` matching `space_id`.
6303fn channel_belongs_to_space(inner: &Inner, account_id: &str, chat_id: &Id, space_id: &Id) -> bool {
6304    inner
6305        .objects_ref("Chat", account_id)
6306        .and_then(|m| m.get(chat_id))
6307        .map(|v| {
6308            v.get("kind").and_then(|k| k.as_str()) == Some("channel")
6309                && v.get("spaceId").and_then(|s| s.as_str()) == Some(space_id.as_ref())
6310        })
6311        .unwrap_or(false)
6312}
6313
6314/// Return every channel-kind Chat whose `categoryId` equals `target_id`.
6315fn scan_channels_in_category(inner: &Inner, account_id: &str, target_id: &Id) -> Vec<Id> {
6316    let Some(chats) = inner.objects_ref("Chat", account_id) else {
6317        return Vec::new();
6318    };
6319    chats
6320        .iter()
6321        .filter(|(_, v)| {
6322            v.get("kind").and_then(|k| k.as_str()) == Some("channel")
6323                && v.get("categoryId").and_then(|c| c.as_str()) == Some(target_id.as_ref())
6324        })
6325        .map(|(id, _)| id.clone())
6326        .collect()
6327}
6328
6329/// Remove `ids` from every category's `channelIds` so a channel being
6330/// assigned elsewhere keeps a single home (draft §Category: "The server
6331/// MUST keep them consistent").
6332fn remove_from_categories<S: AsRef<str>>(cats: &mut [serde_json::Value], ids: &[S]) {
6333    for cat in cats {
6334        if let Some(ch_ids) = cat.get_mut("channelIds").and_then(|v| v.as_array_mut()) {
6335            ch_ids.retain(|v| {
6336                v.as_str()
6337                    .is_none_or(|s| !ids.iter().any(|id| id.as_ref() == s))
6338            });
6339        }
6340    }
6341}
6342
6343/// Set or clear a Chat's `categoryId` field in place. Silently no-ops if
6344/// the Chat does not exist (the caller has already validated existence
6345/// via `channel_belongs_to_space` or `scan_channels_in_category`).
6346fn set_channel_category(inner: &mut Inner, account_id: &str, chat_id: &Id, new_cat: Option<&Id>) {
6347    let map = inner.objects_mut("Chat", account_id);
6348    let Some(chat_val) = map.get_mut(chat_id) else {
6349        return;
6350    };
6351    let obj = match chat_val {
6352        serde_json::Value::Object(o) => o,
6353        _ => return,
6354    };
6355    match new_cat {
6356        Some(cat_id) => {
6357            obj.insert(
6358                "categoryId".to_owned(),
6359                serde_json::Value::String(cat_id.as_ref().to_owned()),
6360            );
6361        }
6362        None => {
6363            obj.remove("categoryId");
6364        }
6365    }
6366}
6367
6368/// Per-variant rejection text for the `#[non_exhaustive]`
6369/// future-variant catch-all in `apply_space_patch_impl`.
6370///
6371/// As of `bd:JMAP-g7wu.2.4.3` all twelve known `SpacePatchOp`
6372/// variants (Role/Member/Channel/Category) are routed to dedicated
6373/// `apply_*` helpers and never reach this stub. Only an
6374/// `#[non_exhaustive]`-added future variant — visible after a
6375/// `jmap-chat-types` upgrade but before the corresponding handler
6376/// lands here — would fall through.
6377fn stub_description(op: &SpacePatchOp) -> String {
6378    let _ = op;
6379    "unknown SpacePatchOp variant (tracked under bd:JMAP-g7wu.2.4)".to_owned()
6380}
6381
6382fn variant_name(op: &SpacePatchOp) -> &'static str {
6383    match op {
6384        SpacePatchOp::AddRole(_) => "AddRole",
6385        SpacePatchOp::RemoveRole(_) => "RemoveRole",
6386        SpacePatchOp::UpdateRole { .. } => "UpdateRole",
6387        SpacePatchOp::AddMember(_) => "AddMember",
6388        SpacePatchOp::RemoveMember(_) => "RemoveMember",
6389        SpacePatchOp::UpdateMember { .. } => "UpdateMember",
6390        SpacePatchOp::AddChannel(_) => "AddChannel",
6391        SpacePatchOp::RemoveChannel(_) => "RemoveChannel",
6392        SpacePatchOp::UpdateChannel { .. } => "UpdateChannel",
6393        SpacePatchOp::AddCategory(_) => "AddCategory",
6394        SpacePatchOp::RemoveCategory(_) => "RemoveCategory",
6395        SpacePatchOp::UpdateCategory { .. } => "UpdateCategory",
6396        _ => "Unknown",
6397    }
6398}
6399
6400/// The conformance-suite seam for one caller type: the `test-helpers`
6401/// setters stand in for account provisioning, seeding and the outbound
6402/// queue, and `$caller` is the caller of every request.
6403#[cfg(all(feature = "testkit", feature = "test-helpers"))]
6404macro_rules! conformance_backend {
6405    ($ctx:ty, $doc:literal, |$account:ident| $caller:expr) => {
6406        impl crate::testkit::ConformanceBackend for MemoryBackend<$ctx> {
6407            #[doc = $doc]
6408            fn caller(&self, $account: &Id) -> $ctx {
6409                $caller
6410            }
6411
6412            async fn add_account(&self, account_id: &Id, owner_user_id: &str) {
6413                self.register_account(account_id);
6414                self.set_owner_user_id_for_test(account_id, owner_user_id);
6415            }
6416
6417            /// # Panics
6418            ///
6419            /// If `object` has no `id` string.
6420            async fn seed(
6421                &self,
6422                account_id: &Id,
6423                type_name: &'static str,
6424                object: serde_json::Value,
6425            ) {
6426                let id = object["id"]
6427                    .as_str()
6428                    .unwrap_or_else(|| {
6429                        panic!("seed: {type_name} object has no `id` string: {object}")
6430                    })
6431                    .to_owned();
6432                self.insert_object_for_test(type_name, account_id.as_ref(), &id, object);
6433            }
6434
6435            fn take_outbound_events(&self) -> Option<Vec<crate::OutboundEvent>> {
6436                Some(self.take_outbound_events_for_test())
6437            }
6438        }
6439    };
6440}
6441
6442#[cfg(all(feature = "testkit", feature = "test-helpers"))]
6443conformance_backend!(
6444    (),
6445    "A caller without identity: every request acts as every account's owner.",
6446    |_account_id| ()
6447);
6448
6449#[cfg(all(feature = "testkit", feature = "test-helpers"))]
6450conformance_backend!(
6451    Id,
6452    "The account id: the owner's Space member id (draft-atwood-jmap-chat-00 §Terminology).",
6453    |account_id| account_id.clone()
6454);
6455
6456// ---------------------------------------------------------------------------
6457// ConditionalBackend (draft-ietf-jmap-conditional-02)
6458// ---------------------------------------------------------------------------
6459
6460/// Conditional chat Foo/set (bd JMAP-y1yu.9): the whole store is one
6461/// [`ScopedState`], so a scope isolates every type in every account, and an
6462/// atomic rollback restores objects, state strings, change logs, push
6463/// subscriptions and the queued lifecycle and outbound events, so nothing
6464/// is announced for a change that never happened (§4.3). Under an atomic
6465/// scope the backend leaves its cross-object checks (`CustomEmoji` names and
6466/// per-Space counts, the push subscription cap) to the commit, which
6467/// checks the final state (`final_state_failures`).
6468impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
6469    async fn begin_set(
6470        &self,
6471        _caller: &C,
6472        request: SetScopeRequest<'_>,
6473    ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
6474        Ok(self.inner.open(request, final_state_failures).await)
6475    }
6476}
6477
6478/// The changes an atomic scope made that break a cross-object constraint
6479/// in the state it would commit (conditional-02 §4.2):
6480///
6481/// - two `CustomEmoji` with one `name` in one scope (account-wide or one
6482///   Space): `alreadyExists` with `existingId` on a create,
6483///   `invalidProperties` `name` on an update, as outside a scope;
6484/// - a Space holding more `CustomEmoji` than
6485///   [`ChatLimits::max_custom_emoji_per_space`]: `overQuota` on the
6486///   creates in that Space (jmap-chat-implementer-guide §2.2);
6487/// - more than [`MAX_PUSH_SUBSCRIPTIONS`] push subscriptions:
6488///   `overQuota` on the creates.
6489///
6490/// Only objects the scope created or changed are reported, once each.
6491fn final_state_failures(before: &Inner, after: &Inner) -> Vec<DeferredFailure> {
6492    let mut failures = Vec::new();
6493    let scope = |e: &serde_json::Value| e.get("spaceId").filter(|v| !v.is_null()).cloned();
6494    {
6495        let (type_name, property) = ("CustomEmoji", "name");
6496        for (account, objects) in after.objects.get(type_name).into_iter().flatten() {
6497            let old = before.objects_ref(type_name, account);
6498            for (id, obj) in objects {
6499                let op = match old.and_then(|o| o.get(id)) {
6500                    None => SetOp::Create(id.clone()),
6501                    Some(prev) if prev != obj => SetOp::Update(id.clone()),
6502                    Some(_) => continue,
6503                };
6504                let clash = objects.iter().find(|(other, o)| {
6505                    *other != id && o.get(property) == obj.get(property) && scope(o) == scope(obj)
6506                });
6507                if let Some((existing, _)) = clash {
6508                    let error = match op {
6509                        SetOp::Create(_) => SetError::new(SetErrorType::AlreadyExists)
6510                            .with_existing_id(existing.clone()),
6511                        _ => SetError::new(SetErrorType::InvalidProperties)
6512                            .with_properties([property]),
6513                    };
6514                    failures.push(DeferredFailure::new(op, error));
6515                }
6516            }
6517        }
6518    }
6519    if let Some(max) = after
6520        .limits_override
6521        .unwrap_or_default()
6522        .max_custom_emoji_per_space
6523    {
6524        for (account, objects) in after.objects.get("CustomEmoji").into_iter().flatten() {
6525            let old = before.objects_ref("CustomEmoji", account);
6526            for (id, obj) in objects {
6527                let Some(space) = emoji_scope(obj) else {
6528                    continue;
6529                };
6530                let created = old.is_none_or(|o| !o.contains_key(id));
6531                let reported = failures
6532                    .iter()
6533                    .any(|f| matches!(&f.op, SetOp::Create(c) if c == id));
6534                if created
6535                    && !reported
6536                    && emoji_count_in_space(after, account, &space) > u64::from(max)
6537                {
6538                    failures.push(DeferredFailure::new(
6539                        SetOp::Create(id.clone()),
6540                        SetError::new(SetErrorType::OverQuota)
6541                            .with_description(crate::emoji::TOO_MANY_EMOJI),
6542                    ));
6543                }
6544            }
6545        }
6546    }
6547    if after.push_subscriptions.len() > MAX_PUSH_SUBSCRIPTIONS {
6548        for id in after.push_subscriptions.keys() {
6549            if !before.push_subscriptions.contains_key(id) {
6550                failures.push(DeferredFailure::new(
6551                    SetOp::Create(id.clone()),
6552                    SetError::new(SetErrorType::OverQuota).with_description(format!(
6553                        "at most {MAX_PUSH_SUBSCRIPTIONS} push subscriptions per user"
6554                    )),
6555                ));
6556            }
6557        }
6558    }
6559    failures
6560}
6561
6562#[cfg(test)]
6563mod tests {
6564    use super::*;
6565
6566    use jmap_chat_types::ChatContact;
6567    use std::collections::HashSet;
6568
6569    /// Oracle: RFC 8620 §5.2 /changes rules, expected lists written by hand.
6570    /// "If a record has been created AND destroyed since the old state, the
6571    /// server SHOULD remove the id from the response entirely"; a record
6572    /// created then updated is reported only in `created`; one updated then
6573    /// destroyed is reported only in `destroyed`.
6574    #[tokio::test]
6575    async fn get_changes_dedups_ids_across_window() {
6576        let backend = MemoryBackend::<()>::default();
6577        let id = |s: &str| Id::from(s);
6578        {
6579            let mut inner = backend.inner.lock_unscoped();
6580            let log = inner.change_log_mut(ChatContact::TYPE_NAME, "acc1");
6581            log.push(ChangeEntry {
6582                new_state: 1,
6583                created: vec![id("eph"), id("fresh")],
6584                updated: vec![],
6585                destroyed: vec![],
6586                restored: vec![],
6587                updated_props: None,
6588            });
6589            log.push(ChangeEntry {
6590                new_state: 2,
6591                created: vec![],
6592                updated: vec![id("fresh"), id("old"), id("doomed")],
6593                destroyed: vec![id("eph")],
6594                restored: vec![],
6595                updated_props: None,
6596            });
6597            log.push(ChangeEntry {
6598                new_state: 3,
6599                created: vec![],
6600                updated: vec![id("old")],
6601                destroyed: vec![id("doomed"), id("gone")],
6602                restored: vec![],
6603                updated_props: None,
6604            });
6605        }
6606
6607        let changes = backend
6608            .get_changes::<ChatContact>(
6609                &(),
6610                &id("acc1"),
6611                jmap_server::ChangesParams::new(&State::from("0")),
6612            )
6613            .await
6614            .expect("get_changes must succeed");
6615
6616        assert_eq!(changes.created, vec![id("fresh")]);
6617        assert_eq!(changes.updated, vec![id("old")]);
6618        assert_eq!(changes.destroyed, vec![id("doomed"), id("gone")]);
6619    }
6620
6621    /// Oracle: draft-atwood-jmap-chat-00 §Message/changes, expected lists
6622    /// written by hand. "When a Message is created and hard-deleted ...
6623    /// between the `sinceState` and the new state ... Servers SHOULD list it
6624    /// in `destroyed`" — unlike the RFC 8620 §5.2 omit-both rule the other
6625    /// chat types follow (bd:JMAP-ic0j.76).
6626    #[tokio::test]
6627    async fn get_changes_lists_created_and_destroyed_message_in_destroyed() {
6628        let backend = MemoryBackend::<()>::default();
6629        let id = |s: &str| Id::from(s);
6630        {
6631            let mut inner = backend.inner.lock_unscoped();
6632            let log = inner.change_log_mut(jmap_chat_types::Message::TYPE_NAME, "acc1");
6633            log.push(ChangeEntry {
6634                new_state: 1,
6635                created: vec![id("burnt"), id("kept")],
6636                updated: vec![],
6637                destroyed: vec![],
6638                restored: vec![],
6639                updated_props: None,
6640            });
6641            log.push(ChangeEntry {
6642                new_state: 2,
6643                created: vec![],
6644                updated: vec![id("burnt")],
6645                destroyed: vec![],
6646                restored: vec![],
6647                updated_props: None,
6648            });
6649            log.push(ChangeEntry {
6650                new_state: 3,
6651                created: vec![],
6652                updated: vec![],
6653                destroyed: vec![id("burnt")],
6654                restored: vec![],
6655                updated_props: None,
6656            });
6657        }
6658
6659        let changes = backend
6660            .get_changes::<jmap_chat_types::Message>(
6661                &(),
6662                &id("acc1"),
6663                jmap_server::ChangesParams::new(&State::from("0")),
6664            )
6665            .await
6666            .expect("get_changes must succeed");
6667
6668        assert_eq!(changes.created, vec![id("kept")]);
6669        assert!(changes.updated.is_empty());
6670        assert_eq!(changes.destroyed, vec![id("burnt")]);
6671    }
6672
6673    /// Oracle: RFC 8620 §1.4 — a UTCDate is an RFC 3339 instant whose zero
6674    /// time-secfrac "MUST be omitted", so `00:00:01Z` is one millisecond
6675    /// after `00:00:00.999Z` and before `00:00:01.001Z` (bd:JMAP-rvp2).
6676    #[test]
6677    fn compare_by_sort_orders_utc_dates_chronologically() {
6678        use serde_json::json;
6679        let comparators = [json!({ "property": "receivedAt", "isAscending": true })];
6680        let mut msgs = [
6681            json!({ "id": "c", "receivedAt": "2026-01-01T00:00:01.001Z" }),
6682            json!({ "id": "b", "receivedAt": "2026-01-01T00:00:01Z" }),
6683            json!({ "id": "a", "receivedAt": "2026-01-01T00:00:00.999Z" }),
6684            json!({ "id": "d", "receivedAt": "2026-01-01T00:00:01.01Z" }),
6685        ];
6686        msgs.sort_by(|x, y| compare_by_sort(x, y, &comparators));
6687        let ids: Vec<&str> = msgs.iter().map(|m| m["id"].as_str().unwrap()).collect();
6688        assert_eq!(ids, ["a", "b", "c", "d"]);
6689
6690        let descending = [json!({ "property": "receivedAt", "isAscending": false })];
6691        msgs.sort_by(|x, y| compare_by_sort(x, y, &descending));
6692        let ids: Vec<&str> = msgs.iter().map(|m| m["id"].as_str().unwrap()).collect();
6693        assert_eq!(ids, ["d", "c", "b", "a"]);
6694    }
6695
6696    /// Oracle: invite codes are CSPRNG-derived, so a batch of generated codes
6697    /// must show high entropy — no duplicates across a large sample, no
6698    /// monotone-in-time leakage, no shared prefix.
6699    ///
6700    /// This is a behavioural canary on bd:JMAP-sc1b.93. The pre-fix
6701    /// nanosecond-derived impl produced strictly monotone-in-time output
6702    /// with a 16-byte-wide identical prefix between consecutive calls; the
6703    /// CSPRNG impl does not.
6704    ///
6705    /// The test deliberately makes no claim about the *value* of any single
6706    /// code (that would require the code under test to be its own oracle).
6707    /// It only asserts structural properties that the failing implementation
6708    /// could not satisfy.
6709    #[tokio::test]
6710    async fn generate_invite_code_is_csprng() {
6711        let backend = MemoryBackend::<()>::default();
6712        const N: usize = 256;
6713        let mut codes: HashSet<String> = HashSet::with_capacity(N);
6714        for _ in 0..N {
6715            let code = backend
6716                .generate_invite_code(&(), &Id::from("acct"))
6717                .await
6718                .expect("OS CSPRNG available in tests");
6719            codes.insert(code);
6720        }
6721        // 256 CSPRNG samples of 128 bits each have negligible birthday-collision
6722        // probability (~256^2 / 2^129 ≈ 10^-34). Any duplicate indicates the
6723        // impl regressed to a counter, a timestamp, or a constant.
6724        assert_eq!(
6725            codes.len(),
6726            N,
6727            "expected {N} distinct invite codes; found {} duplicates",
6728            N - codes.len()
6729        );
6730        // Every code is 32 hex chars (16 bytes * 2).
6731        for c in &codes {
6732            assert_eq!(
6733                c.len(),
6734                32,
6735                "invite code must be 32 hex chars (16 random bytes); got len {} ({})",
6736                c.len(),
6737                c
6738            );
6739            assert!(
6740                c.chars().all(|ch| ch.is_ascii_hexdigit()),
6741                "invite code must be lowercase hex; got {c}"
6742            );
6743        }
6744        // Sanity tripwire for the pre-fix bug: the original nanos impl
6745        // produced sequential codes with a 10-12 char shared prefix
6746        // (high-order nanoseconds change slowly between two adjacent calls).
6747        // A CSPRNG produces near-uniform random output, so the longest
6748        // shared prefix across a 256-sample batch should be tiny.
6749        let sorted: Vec<&String> = {
6750            let mut v: Vec<&String> = codes.iter().collect();
6751            v.sort();
6752            v
6753        };
6754        let max_prefix: usize = sorted
6755            .windows(2)
6756            .map(|w| {
6757                w[0].as_bytes()
6758                    .iter()
6759                    .zip(w[1].as_bytes())
6760                    .take_while(|(a, b)| a == b)
6761                    .count()
6762            })
6763            .max()
6764            .unwrap_or(0);
6765        // Even with 256 samples a CSPRNG can incidentally produce one pair
6766        // sharing 4-5 hex chars; pre-fix the shared prefix was always >=10.
6767        assert!(
6768            max_prefix < 10,
6769            "max shared prefix across sorted codes is {max_prefix}; >=10 suggests timestamp-derived output (bd:JMAP-sc1b.93 regression)"
6770        );
6771    }
6772
6773    /// Oracle: RFC 4648 §10 test vectors, with `+`/`/` mapped to `-`/`_`
6774    /// (§5) and `=` padding removed.
6775    #[test]
6776    fn base64url_unpadded_matches_rfc4648_vectors() {
6777        for (input, expected) in [
6778            ("", ""),
6779            ("f", "Zg"),
6780            ("fo", "Zm8"),
6781            ("foo", "Zm9v"),
6782            ("foob", "Zm9vYg"),
6783            ("fooba", "Zm9vYmE"),
6784            ("foobar", "Zm9vYmFy"),
6785        ] {
6786            assert_eq!(base64url_unpadded(input.as_bytes()), expected);
6787        }
6788        assert_eq!(base64url_unpadded(&[0xfb, 0xff, 0xbf]), "-_-_");
6789    }
6790
6791    // json_merge_patch tests live in jmap-server (the function's home
6792    // crate as of bd:JMAP-sc1b.103). Adding chat-specific behavioural
6793    // canaries here is fine; merge-patch RFC 7396 conformance is not
6794    // re-tested per sibling.
6795}
6796
6797#[cfg(test)]
6798mod memory_error_tests {
6799    use super::MemoryError;
6800
6801    /// The `JmapAccounts::Error` contract: "Implementations MUST NOT
6802    /// include ... PII shaped like an email address" in `Display`
6803    /// output. serde_json data errors quote the offending value, so
6804    /// [`MemoryError::serde`] must drop the message (bd:JMAP-510h.37).
6805    #[test]
6806    fn serde_error_display_omits_offending_value() {
6807        let canary = "alice@example.com";
6808        let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
6809            .expect_err("a string is not a u64");
6810        assert!(
6811            e.to_string().contains(canary),
6812            "precondition: serde_json quotes the value"
6813        );
6814
6815        let shown = MemoryError::serde("decode", &e).to_string();
6816        assert!(!shown.contains(canary), "canary leaked: {shown}");
6817        assert!(
6818            shown.contains("decode") && shown.contains("Data"),
6819            "{shown}"
6820        );
6821    }
6822}
6823
6824#[cfg(test)]
6825mod clone_tests {
6826    use super::MemoryBackend;
6827    use jmap_types::Id;
6828
6829    /// Oracle (bd:JMAP-q7k6): `MemoryBackend::clone` is a shared-state
6830    /// clone, never a deep copy, so a clone and its original hold the
6831    /// same store while a fresh instance does not.
6832    #[test]
6833    fn clone_shares_store() {
6834        let a = MemoryBackend::<()>::default();
6835        let clone = a.clone();
6836        let fresh = MemoryBackend::<()>::default();
6837        a.register_account(&Id::from("acc"));
6838        let known = |b: &MemoryBackend<()>| b.inner.lock_unscoped().known_accounts.contains("acc");
6839        assert!(known(&clone), "a clone sees the original's writes");
6840        assert!(!known(&fresh), "a fresh backend does not");
6841    }
6842}
6843
6844#[cfg(test)]
6845mod fixture_helper_tests {
6846    use super::*;
6847    use serde_json::json;
6848
6849    /// `with_account` makes the account known (RFC 8620 §3.6.2: an
6850    /// unknown accountId is `accountNotFound`, so `account_exists` is the
6851    /// observable).
6852    #[tokio::test]
6853    async fn with_account_registers_account() {
6854        let acc = Id::from("acc1");
6855        let backend = MemoryBackend::<()>::default().with_account(&acc);
6856        assert!(backend.account_exists(&(), &acc).await.unwrap());
6857        assert!(
6858            !backend
6859                .account_exists(&(), &Id::from("acc2"))
6860                .await
6861                .unwrap()
6862        );
6863    }
6864
6865    /// A seeded object is readable, registers its account, and leaves the
6866    /// state at its initial value. Fixture: hand-written JSON.
6867    #[tokio::test]
6868    async fn seed_object_is_readable_without_state_change() {
6869        let acc = Id::from("acc1");
6870        let backend = MemoryBackend::<()>::default();
6871        let before = backend
6872            .get_state::<jmap_chat_types::CustomEmoji>(&(), &acc)
6873            .await
6874            .unwrap();
6875        backend.seed_object(
6876            &acc,
6877            jmap_chat_types::CustomEmoji::TYPE_NAME,
6878            &Id::from("x1"),
6879            json!({"id": "x1", "name": "party", "blobId": "b1", "createdBy": "u1", "createdAt": "2026-01-01T00:00:00Z"}),
6880        );
6881        assert!(backend.account_exists(&(), &acc).await.unwrap());
6882        let (found, not_found) = backend
6883            .get_objects::<jmap_chat_types::CustomEmoji>(&(), &acc, Some(&[Id::from("x1")]), None)
6884            .await
6885            .unwrap();
6886        assert_eq!(found.len(), 1);
6887        assert!(not_found.is_empty());
6888        assert_eq!(
6889            backend
6890                .get_state::<jmap_chat_types::CustomEmoji>(&(), &acc)
6891                .await
6892                .unwrap(),
6893            before
6894        );
6895    }
6896
6897    #[test]
6898    #[should_panic(expected = "not one of the known")]
6899    fn seed_object_rejects_unknown_type_name() {
6900        MemoryBackend::<()>::default().seed_object(
6901            &Id::from("acc1"),
6902            "NoSuchType",
6903            &Id::from("x1"),
6904            json!({"id": "x1"}),
6905        );
6906    }
6907
6908    #[test]
6909    #[should_panic(expected = "does not match the `id` argument")]
6910    fn seed_object_rejects_id_mismatch() {
6911        MemoryBackend::<()>::default().seed_object(
6912            &Id::from("acc1"),
6913            jmap_chat_types::CustomEmoji::TYPE_NAME,
6914            &Id::from("x1"),
6915            json!({"id": "other"}),
6916        );
6917    }
6918}
6919
6920#[cfg(all(test, debug_assertions))]
6921mod empty_account_id_tests {
6922    use super::{Id, MemoryBackend};
6923
6924    /// Oracle: RFC 8620 §1.2, an Id "is a String of at least 1 and a
6925    /// maximum of 255 octets in size" (bd:JMAP-dx0s).
6926    #[test]
6927    #[should_panic(expected = "account_id must not be the empty string")]
6928    fn register_account_rejects_empty_id() {
6929        MemoryBackend::<()>::default().register_account(&Id::from(""));
6930    }
6931}
6932
6933#[cfg(test)]
6934mod max_changes_tests {
6935    use super::*;
6936    use jmap_chat_types::ChatContact as T;
6937
6938    const CALLER: () = ();
6939
6940    /// A backend whose `T` log holds one state per element of `states`,
6941    /// each creating the listed ids.
6942    fn with_creates(states: &[&[&str]]) -> MemoryBackend<()> {
6943        let backend = MemoryBackend::<()>::default();
6944        let mut inner = backend.inner.lock_unscoped();
6945        for ids in states {
6946            let new_state = inner.bump_state(T::TYPE_NAME, "acc1");
6947            inner
6948                .change_log_mut(T::TYPE_NAME, "acc1")
6949                .push(ChangeEntry {
6950                    new_state,
6951                    created: ids.iter().map(|s| Id::from(*s)).collect(),
6952                    updated: vec![],
6953                    destroyed: vec![],
6954                    restored: vec![],
6955                    updated_props: None,
6956                });
6957        }
6958        drop(inner);
6959        backend
6960    }
6961
6962    /// Oracle: RFC 8620 §5.2, expected pages written by hand: "the server
6963    /// MUST ensure the number of ids returned across "created", "updated",
6964    /// and "destroyed" does not exceed this limit. If there are more
6965    /// changes than this ..., the server SHOULD generate an update to take
6966    /// the client to an intermediate state, from which the client can
6967    /// continue to call "Foo/changes" until it is fully up to date." Three
6968    /// one-create states against `maxChanges` 2 page as states 1-2, then 3.
6969    #[tokio::test]
6970    async fn over_max_changes_pages_through_intermediate_state() {
6971        let backend = with_creates(&[&["a"], &["b"], &["c"]]);
6972
6973        let first = changes(&backend, "0", 2).await.expect("first page");
6974        assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
6975        assert!(first.has_more_changes);
6976        assert_eq!(first.new_state.as_ref(), "2");
6977
6978        let rest = changes(&backend, "2", 2).await.expect("second page");
6979        assert_eq!(rest.created, [Id::from("c")]);
6980        assert!(!rest.has_more_changes);
6981        assert_eq!(rest.new_state.as_ref(), "3");
6982    }
6983
6984    /// Oracle: RFC 8620 §5.2 "If it is unable to calculate an intermediate
6985    /// state, it MUST return a "cannotCalculateChanges" error response
6986    /// instead." One state creating three ids cannot be split under
6987    /// `maxChanges` 2.
6988    #[tokio::test]
6989    async fn one_state_over_max_changes_cannot_calculate() {
6990        let backend = with_creates(&[&["a", "b", "c"]]);
6991        assert!(matches!(
6992            changes(&backend, "0", 2).await,
6993            Err(BackendChangesError::TooManyChanges { limit: 2 })
6994        ));
6995    }
6996
6997    fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
6998        ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
6999        ids
7000    }
7001
7002    async fn changes(
7003        backend: &MemoryBackend<()>,
7004        since: &str,
7005        max: u64,
7006    ) -> Result<ChangesResult, BackendChangesError<<MemoryBackend<()> as JmapAccounts>::Error>>
7007    {
7008        backend
7009            .get_changes::<T>(
7010                &CALLER,
7011                &Id::from("acc1"),
7012                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
7013            )
7014            .await
7015    }
7016}
7017
7018/// The final-state half of the [`ChatLimits::max_custom_emoji_per_space`]
7019/// cap (bd:JMAP-b9qs). The handler pre-check and the create path never
7020/// let a single `CustomEmoji/set` reach it, so it is driven directly.
7021///
7022/// Oracle: jmap-chat-implementer-guide §2.2: "The server MUST reject
7023/// `CustomEmoji/set` with `overQuota` ... when the count ... limit is
7024/// exceeded"; draft-ietf-jmap-conditional-02 §4.2 judges an atomic call
7025/// on its final state.
7026#[cfg(test)]
7027mod emoji_cap_tests {
7028    use super::*;
7029
7030    fn emoji(name: &str, space: &str) -> serde_json::Value {
7031        serde_json::json!({ "name": name, "blobId": "b", "spaceId": space })
7032    }
7033
7034    #[test]
7035    fn final_state_over_the_cap_fails_only_the_creates() {
7036        let mut before = Inner {
7037            limits_override: Some(ChatLimits::default().with_max_custom_emoji_per_space(Some(1))),
7038            ..Inner::default()
7039        };
7040        before
7041            .objects_mut("CustomEmoji", "acc1")
7042            .insert(Id::from("old"), emoji("old", "s1"));
7043        let mut after = before.clone();
7044        after
7045            .objects_mut("CustomEmoji", "acc1")
7046            .insert(Id::from("new"), emoji("new", "s1"));
7047        after
7048            .objects_mut("CustomEmoji", "acc1")
7049            .insert(Id::from("elsewhere"), emoji("new", "s2"));
7050
7051        let failures = final_state_failures(&before, &after);
7052        assert_eq!(failures.len(), 1, "{failures:?}");
7053        assert_eq!(failures[0].op, SetOp::Create(Id::from("new")));
7054        assert_eq!(failures[0].error.error_type, SetErrorType::OverQuota);
7055
7056        // At the cap (the old emoji gone): nothing fails.
7057        after
7058            .objects_mut("CustomEmoji", "acc1")
7059            .remove(&Id::from("old"));
7060        assert!(final_state_failures(&before, &after).is_empty());
7061    }
7062}