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