Skip to main content

jmap_chat_server/
backend.rs

1//! ChatBackend trait and supporting types for JMAP Chat method handlers.
2//!
3//! Consumers implement [`ChatBackend`] for their storage system. The method
4//! handlers in sibling modules call into the backend through this trait.
5//!
6//! The read-side operations (`get_objects`, `get_state`, `get_changes`,
7//! `query_objects`, `query_changes`) are defined on the [`jmap_server::JmapBackend`]
8//! supertrait. Only write operations are here.
9//!
10//! Marker traits and property selector enums live in `jmap-types` and
11//! `jmap-chat-types` respectively; they are re-exported here for convenience.
12
13pub use jmap_chat_types::backend::{
14    ChatContactProperty, ChatProperty, MessageProperty, ReadPositionProperty, SpaceProperty,
15};
16pub use jmap_chat_types::space_set::{SpaceMetadataPatch, SpacePatchOp};
17pub use jmap_server::{
18    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
19    JmapBackend, JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType,
20    SetObject,
21};
22
23// ---------------------------------------------------------------------------
24// Space/set structural-mutation result
25// ---------------------------------------------------------------------------
26
27/// The outcome of a single [`SpacePatchOp`] applied by
28/// [`ChatBackend::apply_space_patch`].
29///
30/// `op_index` is the zero-based index of the op within the input `Vec`, used
31/// by handlers to construct a descriptive error message identifying which
32/// per-key entry failed (e.g. `addRoles[2] failed: ...`).
33///
34/// `outcome` is:
35/// - `Ok(Some(id))` — the op produced a new server-assigned id (e.g.
36///   [`SpacePatchOp::AddRole`], [`SpacePatchOp::AddChannel`],
37///   [`SpacePatchOp::AddCategory`]). The handler reports this id back to
38///   the client via the `/set` response.
39/// - `Ok(None)` — the op completed but produced no id (every `Remove*` and
40///   `Update*` variant).
41/// - `Err(SetError)` — the op was rejected (e.g. permission denied, target
42///   id not found, role hierarchy violation, count limit exceeded).
43///
44/// Per RFC 8620 §5.3 `/set`, an update target is per-target atomic on the
45/// wire: it appears in exactly one of `updated` or `notUpdated`. If **any**
46/// `OpResult` in the returned `Vec` has an `Err`, the handler reports the
47/// containing update target in `notUpdated`. The handler is free to choose
48/// which `Err` to surface; the reference handler surfaces the first.
49///
50/// This type lives in `jmap-chat-server` (not `jmap-chat-types`) because
51/// [`SetError`] is defined in `jmap-server` and `jmap-chat-types` cannot
52/// depend on it (per the workspace dependency rule: types crates depend
53/// only on `jmap-types`, `serde`, `serde_json`).
54///
55/// `#[non_exhaustive]` preserves the ability to add fields without a
56/// SemVer break (e.g. an audit-log handle, commit ordering hint,
57/// permission-diagnostic annotation). External consumers MUST construct
58/// instances via [`OpResult::ok`] or [`OpResult::err`] rather than
59/// field-init syntax.
60///
61/// # Field-addition policy
62///
63/// Future fields added to `OpResult` are an **additive non-breaking
64/// change**: the new field MUST have a `Default` value (typical for
65/// `Option` / `Vec` / `HashMap`) and the new field is exposed via a
66/// `with_*`-style builder setter rather than being appended as a third
67/// positional argument to [`OpResult::ok`] or [`OpResult::err`]. The
68/// `ok(op_index, id)` and `err(op_index, error)` constructors therefore
69/// stay stable across the crate's pre-1.0 lifetime, matching the
70/// [`ChatLimits`]-style canonical workspace pattern for
71/// `#[non_exhaustive]` types with builder setters.
72#[non_exhaustive]
73#[derive(Debug)]
74pub struct OpResult {
75    /// Zero-based index of the originating op in the input `Vec<SpacePatchOp>`.
76    pub op_index: usize,
77    /// The outcome of applying that op.
78    pub outcome: Result<Option<jmap_types::Id>, SetError>,
79}
80
81impl OpResult {
82    /// Construct an `Ok` result for a successfully applied op.
83    ///
84    /// The contained `Id` is the server-assigned id when the op was a
85    /// create (the kit's response includes it under `created[create_id].id`);
86    /// pass `None` for updates and destroys, which have no id to surface.
87    #[must_use]
88    pub const fn ok(op_index: usize, id: Option<jmap_types::Id>) -> Self {
89        Self {
90            op_index,
91            outcome: Ok(id),
92        }
93    }
94
95    /// Construct an `Err` result for a rejected op.
96    ///
97    /// The kit's `handle_space_set` surfaces this error to the JMAP
98    /// `notUpdated` map for the containing update target.
99    #[must_use]
100    pub const fn err(op_index: usize, error: SetError) -> Self {
101        Self {
102            op_index,
103            outcome: Err(error),
104        }
105    }
106
107    /// Builder-style setter for [`Self::op_index`].
108    ///
109    /// Lets callers update the originating op index after construction.
110    /// Useful when re-indexing a result produced for one op into the
111    /// position of another (e.g. when filtering a batch).
112    #[must_use]
113    pub const fn with_op_index(mut self, op_index: usize) -> Self {
114        self.op_index = op_index;
115        self
116    }
117
118    /// Builder-style setter for [`Self::outcome`].
119    ///
120    /// Lets callers replace the outcome after construction. Useful for
121    /// retry / fallback flows that re-classify a transient error into a
122    /// success or vice versa before surfacing the result to the
123    /// handler.
124    #[must_use]
125    pub fn with_outcome(mut self, outcome: Result<Option<jmap_types::Id>, SetError>) -> Self {
126        self.outcome = outcome;
127        self
128    }
129}
130
131// ---------------------------------------------------------------------------
132// Per-Space content limits
133// ---------------------------------------------------------------------------
134
135/// Implementation-defined per-Space content limits enforced by
136/// `Space/set` handlers.
137///
138/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
139/// 2026-05-11), each `add*` op on a Space MUST return an `overQuota`
140/// SetError (RFC 8620 §5.3) when the resulting count would exceed a
141/// server-defined limit. The spec does not name or normatively define
142/// the cap values; they are implementation-defined and may vary per
143/// account or per tenant.
144///
145/// Backends override [`ChatBackend::limits`] to supply their own values.
146/// The default impl returns conservative reference-impl-grade values
147/// suitable for tests and single-tenant dev servers; production
148/// deployments are expected to override.
149///
150/// Client visibility of these caps (when desired) is via JMAP Quotas
151/// (`urn:ietf:params:jmap:quotas`, RFC 9425), not via this struct.
152/// The `urn:ietf:params:jmap:chat` session capability does NOT advertise
153/// the count caps (the previous cap-advertising fields `maxRolesPerSpace`,
154/// `maxSpaceMembers`, `maxChannelsPerSpace`, `maxCategoriesPerSpace`
155/// were removed from the draft in spec commit `80d5e11`).
156///
157/// See the workspace `AGENTS.md` "Backend caps and limits" section for
158/// the cross-extension pattern this struct establishes for JMAP Chat.
159#[non_exhaustive]
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct ChatLimits {
162    /// Maximum number of roles per Space. Enforced against the
163    /// resulting count after applying every `addRoles` entry in a
164    /// `Space/set` update patch.
165    pub max_roles_per_space: u32,
166    /// Maximum number of members per Space. Enforced against the
167    /// resulting count after applying every `addMembers` entry in a
168    /// `Space/set` update patch.
169    pub max_space_members: u32,
170    /// Maximum number of channels per Space. Enforced against the
171    /// resulting count after applying every `addChannels` entry in a
172    /// `Space/set` update patch. The current channel count is the sum
173    /// of `space.uncategorizedChannelIds.len()` and every
174    /// `space.categories[].channelIds.len()`.
175    pub max_channels_per_space: u32,
176    /// Maximum number of categories per Space. Enforced against the
177    /// resulting count after applying every `addCategories` entry in
178    /// a `Space/set` update patch.
179    pub max_categories_per_space: u32,
180    /// Maximum number of members per group Chat. Enforced against the
181    /// resulting count after applying every `addMembers` entry in a
182    /// `Chat/set` update patch.
183    pub max_group_chat_members: u32,
184    /// `bodyType` values the account advertises as `supportedBodyTypes`
185    /// and `Message/set` accepts (draft-atwood-jmap-chat-00
186    /// §Account-Level Capability Object). Defaults to
187    /// [`crate::message::SUPPORTED_BODY_TYPES`]. The list "MUST include
188    /// `"text/plain"` unless the server accepts only end-to-end encrypted
189    /// body types"; `Message/set` rejects a `bodyType` not listed here,
190    /// including the implied `"text/plain"` of an omitted `bodyType`.
191    pub supported_body_types: &'static [&'static str],
192    /// Listed types that a companion specification reserves for
193    /// server-created Messages (e.g. `"application/mimi-fanout"`,
194    /// draft-atwood-jmap-chat-mimi-00). `Message/set` create rejects
195    /// them with an `invalidProperties` SetError naming `bodyType`;
196    /// update does not. Defaults to empty.
197    pub server_reserved_body_types: &'static [&'static str],
198}
199
200impl Default for ChatLimits {
201    fn default() -> Self {
202        Self::new(50, 10_000, 500, 100)
203    }
204}
205
206impl ChatLimits {
207    /// Construct a [`ChatLimits`] with the four Space cap fields
208    /// specified in declaration order: roles, members, channels,
209    /// categories. [`Self::max_group_chat_members`] defaults to 1000;
210    /// override it with [`Self::with_max_group_chat_members`].
211    ///
212    /// The struct is `#[non_exhaustive]` so external callers (tests
213    /// using `MemoryBackend::set_limits_for_test`, production backends
214    /// overriding [`ChatBackend::limits`]) need a constructor to build
215    /// one. Future cap-field additions to [`ChatLimits`] are an
216    /// additive non-breaking change because the constructor stays
217    /// stable; callers wanting to override the new field combine
218    /// `ChatLimits::new(..)` with [`Self::with_max_roles_per_space`]
219    /// / [`Self::with_max_space_members`] /
220    /// [`Self::with_max_channels_per_space`] /
221    /// [`Self::with_max_categories_per_space`] and a future analogous
222    /// setter.
223    pub const fn new(
224        max_roles_per_space: u32,
225        max_space_members: u32,
226        max_channels_per_space: u32,
227        max_categories_per_space: u32,
228    ) -> Self {
229        Self {
230            max_roles_per_space,
231            max_space_members,
232            max_channels_per_space,
233            max_categories_per_space,
234            max_group_chat_members: 1_000,
235            supported_body_types: crate::message::SUPPORTED_BODY_TYPES,
236            server_reserved_body_types: &[],
237        }
238    }
239
240    /// Builder-style setter for [`Self::max_roles_per_space`].
241    #[must_use]
242    pub const fn with_max_roles_per_space(mut self, max: u32) -> Self {
243        self.max_roles_per_space = max;
244        self
245    }
246
247    /// Builder-style setter for [`Self::max_space_members`].
248    #[must_use]
249    pub const fn with_max_space_members(mut self, max: u32) -> Self {
250        self.max_space_members = max;
251        self
252    }
253
254    /// Builder-style setter for [`Self::max_channels_per_space`].
255    #[must_use]
256    pub const fn with_max_channels_per_space(mut self, max: u32) -> Self {
257        self.max_channels_per_space = max;
258        self
259    }
260
261    /// Builder-style setter for [`Self::max_categories_per_space`].
262    #[must_use]
263    pub const fn with_max_categories_per_space(mut self, max: u32) -> Self {
264        self.max_categories_per_space = max;
265        self
266    }
267
268    /// Builder-style setter for [`Self::max_group_chat_members`].
269    #[must_use]
270    pub const fn with_max_group_chat_members(mut self, max: u32) -> Self {
271        self.max_group_chat_members = max;
272        self
273    }
274
275    /// Builder-style setter for [`Self::supported_body_types`].
276    #[must_use]
277    pub const fn with_supported_body_types(mut self, types: &'static [&'static str]) -> Self {
278        self.supported_body_types = types;
279        self
280    }
281
282    /// Builder-style setter for [`Self::server_reserved_body_types`].
283    #[must_use]
284    pub const fn with_server_reserved_body_types(mut self, types: &'static [&'static str]) -> Self {
285        self.server_reserved_body_types = types;
286        self
287    }
288}
289
290// ---------------------------------------------------------------------------
291// Custom emoji authorization gate
292// ---------------------------------------------------------------------------
293
294/// Identifies the kind of `CustomEmoji/set` operation being authorized by
295/// [`ChatBackend::may_set_custom_emoji`].
296///
297/// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11, "refactor:
298/// implementation-defined emoji authorization"), authorization for
299/// `CustomEmoji/set` is fully implementation-defined for both server-global
300/// and Space-scoped emoji. The kit forwards the op kind so the backend can
301/// apply different policies per op (e.g. allow create+update but require
302/// elevated rights for destroy).
303#[non_exhaustive]
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum EmojiSetOp {
306    /// `CustomEmoji/set` `create` — a new emoji is being added.
307    Create,
308    /// `CustomEmoji/set` `update` — an existing emoji's mutable fields
309    /// (currently `name` and `blobId`) are being patched.
310    Update,
311    /// `CustomEmoji/set` `destroy` — an existing emoji is being removed.
312    Destroy,
313}
314
315/// Why [`ChatBackend::join_space_with_invite`] refused a redemption.
316#[non_exhaustive]
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum InviteJoinRefusal {
319    /// The invite, or the Space it names, no longer exists.
320    NotFound,
321    /// The invite's `uses` has reached `maxUses`.
322    Exhausted,
323    /// The owner is already a member of the Space.
324    AlreadyMember,
325}
326
327// ---------------------------------------------------------------------------
328// Slow-mode rate-limit gate
329// ---------------------------------------------------------------------------
330
331/// Outcome of a [`ChatBackend::slow_mode_check`] rejection.
332///
333/// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec commit
334/// `de60acb` (2026-05-11) which softened the manage-channels exemption to
335/// SHOULD: a non-exempt member who sends faster than the configured rate
336/// MUST be rejected with a `rateLimited` SetError carrying a
337/// `serverRetryAfter` UTCDate that tells the client when it may retry.
338///
339/// `retry_after` is a fully-formed [`jmap_types::UTCDate`] — the backend
340/// has already done the arithmetic (typically "now + remaining slow-mode
341/// window"). The handler serialises it verbatim onto the wire as the
342/// `serverRetryAfter` SetError extra field.
343///
344/// `#[non_exhaustive]` preserves the ability to add fields without a
345/// SemVer break (e.g. an error code, sender-facing retry hint string,
346/// "this is your N-th throttle in M minutes" diagnostic counter).
347/// External consumers MUST construct instances via [`SlowModeError::new`]
348/// rather than field-init syntax.
349#[non_exhaustive]
350#[derive(Debug, Clone)]
351pub struct SlowModeError {
352    /// When the rate-limited sender may retry.
353    pub retry_after: jmap_types::UTCDate,
354}
355
356impl SlowModeError {
357    /// Construct a [`SlowModeError`] from a precomputed retry-after
358    /// [`UTCDate`].
359    ///
360    /// [`UTCDate`]: jmap_types::UTCDate
361    #[must_use]
362    pub const fn new(retry_after: jmap_types::UTCDate) -> Self {
363        Self { retry_after }
364    }
365}
366
367impl std::fmt::Display for SlowModeError {
368    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
369        write!(
370            f,
371            "slow-mode rate limit; retry after {}",
372            self.retry_after.as_ref()
373        )
374    }
375}
376
377impl std::error::Error for SlowModeError {}
378
379// ---------------------------------------------------------------------------
380// ChatBackend trait
381// ---------------------------------------------------------------------------
382
383/// Storage backend for JMAP Chat method handlers.
384///
385/// Implementors provide the actual data access; the method handler modules
386/// in this crate translate between JMAP wire protocol and backend calls.
387///
388/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
389/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
390/// supertrait. Only write operations and type introspection are here.
391///
392/// This trait is not object-safe by design (generic methods). Use
393/// `Arc<impl ChatBackend>` when sharing across tasks.
394///
395/// # Async vs sync method convention
396///
397/// `ChatBackend` carves its methods into two groups:
398///
399/// 1. **Mutation / hot-path hooks are async.** [`ChatBackend::create_object`],
400///    [`ChatBackend::update_object`], [`ChatBackend::destroy_object`],
401///    [`ChatBackend::apply_space_patch`],
402///    [`ChatBackend::apply_space_metadata_patch`],
403///    [`ChatBackend::expire_message`],
404///    [`ChatBackend::read_and_burn_message`],
405///    [`ChatBackend::slow_mode_check`],
406///    [`ChatBackend::is_contact_blocked`], and
407///    [`ChatBackend::may_set_custom_emoji`] all return
408///    `impl Future + Send`. These methods consult per-account state,
409///    may issue I/O, and run on the JMAP request hot path; the async
410///    signature lets production backends `.await` storage / cache /
411///    policy lookups without runtime-pinning hazards.
412///
413/// 2. **Policy / capability hooks are sync.** [`ChatBackend::supports_type`],
414///    [`ChatBackend::generate_invite_code`], [`ChatBackend::limits`],
415///    [`ChatBackend::protect_last_admin`], and
416///    [`ChatBackend::retains_edit_history`] are synchronous methods.
417///    These hooks answer deployment-policy or capability questions
418///    whose answer SHOULD be derivable from in-process state (a
419///    startup-loaded config snapshot, a cached per-account record, a
420///    CSPRNG handle). The sync shape keeps the trait surface easy to
421///    implement for single-process and reference backends, which are
422///    the dominant use case for a kit crate.
423///
424/// The carve-up is intentional and is NOT a "we forgot to async these"
425/// regression. Production backends that need to consult an async
426/// source for any of the five sync hooks have two options: (a)
427/// pre-cache the answer at startup or on a background refresh; or (b)
428/// file a follow-up bead proposing the conversion for that specific
429/// method, with the production constraint documented. Per-method
430/// rustdoc notes ("`# Why sync, not async`" / "`# Fallibility and
431/// async — known limitations`") spell out the workaround on each
432/// affected method. Flipping any of the sync hooks to async is a
433/// major-version breaking change for downstream implementors;
434/// converting them all preemptively for hypothetical multi-tenant
435/// SaaS deployments would over-engineer the kit-vs-product posture
436/// described in workspace `AGENTS.md`.
437pub trait ChatBackend: JmapBackend {
438    /// Create a new object.
439    ///
440    /// Returns `(assigned_id, created_object)` on success. `create_id` is the
441    /// client-side creation id used in the `/set` request.
442    ///
443    /// # Sentinel fields the backend MUST replace
444    ///
445    /// The method handlers in this crate pass partially-constructed objects
446    /// with sentinel values that the backend MUST replace with real values
447    /// before storing:
448    ///
449    /// - **`id`**: The `id` field in the input object is always set to
450    ///   `"placeholder"`. The backend MUST replace it with a real, unique,
451    ///   account-scoped ID and return that ID as the first element of the
452    ///   result tuple.
453    ///
454    /// Failing to replace this sentinel will cause the client to receive an
455    /// invalid wire value (`"placeholder"`) as the assigned id of every
456    /// created `Space`, `Chat`, `Message`, `SpaceInvite`, `SpaceBan`,
457    /// `CustomEmoji`, and `ReadPosition`.
458    ///
459    /// # Per-type uniqueness contracts
460    ///
461    /// For most types the (id) primary key is the only uniqueness
462    /// invariant the backend must enforce, and the backend's normal
463    /// server-assigned-id discipline closes that. A few types carry
464    /// additional uniqueness invariants on non-id fields that the
465    /// backend MUST enforce atomically with the create — the handler
466    /// pre-checks defensively but cannot close the
467    /// two-concurrent-requests race window.
468    ///
469    /// - **`ReadPosition`** — at most one record per
470    ///   `(account_id, chat_id)`. Clients cannot create one
471    ///   (`ReadPosition/set` create is `forbidden`); the server creates
472    ///   it on first message delivery in
473    ///   [`crate::message::handle_message_set`], which pre-checks via a
474    ///   sequential scan, but two concurrent `Message/set` requests for
475    ///   the same `chatId` can both pass the pre-check and then both
476    ///   reach `create_object`. The
477    ///   backend MUST enforce a unique constraint on
478    ///   `(account_id, chat_id)` at the storage layer (typically a
479    ///   composite unique index in a database backend) and surface a
480    ///   duplicate as `BackendSetError::SetError(SetError::new(
481    ///   SetErrorType::AlreadyExists).with_existing_id(canonical))`.
482    ///   See draft-atwood-jmap-chat-00 §ReadPosition.
483    /// - **`ChatContact`** — at most one record per
484    ///   `(account_id, identity)`, compared octet for octet.
485    ///   [`crate::contact::handle_contact_set`] does not pre-check: the
486    ///   backend MUST reject a duplicate atomically with the create as
487    ///   `BackendSetError::SetError(SetError::new(
488    ///   SetErrorType::AlreadyExists).with_existing_id(existing))`, where
489    ///   `existing` is the id of the ChatContact that holds the
490    ///   `identity`. See draft-atwood-jmap-chat-00 §ChatContact/set.
491    /// - **`Chat`** with `kind == Direct` — at most one direct chat
492    ///   per `(account_id, contact_id)`. The handler at
493    ///   [`crate::chat::handle_chat_set`] uses optimistic
494    ///   create-then-validate with rollback; backends MAY enforce a
495    ///   storage-level unique constraint to eliminate the rollback
496    ///   path entirely, but it is not required because the
497    ///   handler's rollback closes the race correctly. See
498    ///   draft-atwood-jmap-chat-00 §Chat.
499    ///
500    /// The reference [`crate::memory::MemoryBackend`] does NOT
501    /// enforce the `ReadPosition` `(account, chatId)` uniqueness
502    /// constraint at the storage layer — it is single-Mutex
503    /// per-call so concurrent racing cannot occur in practice, but a
504    /// production backend that holds different locks per record (or
505    /// no lock at all between read and write) MUST.
506    ///
507    /// # Errors
508    ///
509    /// Reject a create that RFC 8620 §5.3 defines an error for with
510    /// [`BackendSetError::SetError`] carrying the matching
511    /// [`SetErrorType`]; the handler places it verbatim in `notCreated`.
512    /// For create these are `forbidden`, `overQuota`, `tooLarge`,
513    /// `rateLimit` and `invalidProperties`. An `invalidProperties` error
514    /// SHOULD name in `properties` "*all* the properties that were
515    /// invalid", for example `chatId` when a Message names a Chat that does
516    /// not exist.
517    ///
518    /// Return [`BackendSetError::Other`] only for unexpected storage
519    /// failures. The handler reports it as `serverFail` without the
520    /// error's `Display` text, which tells the client to retry; a
521    /// deterministic rejection returned as `Other` invites retries that
522    /// cannot succeed.
523    ///
524    /// # State and change log
525    ///
526    /// RFC 8620 §5.1 defines the state string over "*all* the data of
527    /// this type in the account": "If the data changes, this string MUST
528    /// change." Every successful `create_object`,
529    /// [`update_object`](Self::update_object) and
530    /// [`destroy_object`](Self::destroy_object) MUST advance
531    /// [`get_state`](JmapBackend::get_state) for `O` in `account_id` and
532    /// record the id as created, updated or destroyed so
533    /// [`get_changes`](JmapBackend::get_changes) reports it.
534    ///
535    /// The write, the state advance and the change record MUST be atomic
536    /// with respect to other callers: the reference `MemoryBackend` does
537    /// all three under one mutex acquisition, and a database backend uses
538    /// one transaction. A call that returns `Err` MUST leave the stored
539    /// data, the state and the change log unchanged.
540    fn create_object<O: SetObject + Send + Sync>(
541        &self,
542        caller: &Self::CallerCtx,
543        account_id: &jmap_types::Id,
544        create_id: &str,
545        obj: O,
546    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
547           + Send;
548
549    /// Apply a partial update (patch) to an existing object.
550    ///
551    /// Returns `Some(updated_object)` if the backend modified any properties
552    /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
553    /// or `None` if the patch was applied verbatim.
554    ///
555    /// # Patch format
556    ///
557    /// `patch` is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
558    /// Merge Patch: "The keys are a path in JSON Pointer format
559    /// \[RFC6901\], with an implicit leading "/"". So `{"a/b": null}`
560    /// removes member `b` of property `a`; it does not touch a top-level
561    /// property literally named `a/b`. A `null` value sets the
562    /// property's default if it has one, otherwise removes it. A pointer
563    /// into an array, a pointer whose parent does not exist, or two keys
564    /// where one pointer is a prefix of the other "MUST be rejected with
565    /// an "invalidPatch" error".
566    ///
567    /// Implementors SHOULD apply `patch` with
568    /// [`jmap_server::apply_patch_object`], which enforces these rules
569    /// all-or-nothing, and map any [`jmap_server::PatchPathError`] to
570    /// [`jmap_server::SetErrorType::InvalidPatch`], as the reference
571    /// `MemoryBackend` does.
572    ///
573    /// # Errors
574    ///
575    /// As for [`create_object`](Self::create_object), plus these RFC 8620
576    /// §5.3 rules for update:
577    ///
578    /// - "If an id given cannot be found, the update or destroy MUST be
579    ///   rejected with a "notFound" set error."
580    /// - A patch that breaks the rules under "Patch format" is
581    ///   `invalidPatch`.
582    /// - A patched record that is invalid is `invalidProperties`. That
583    ///   includes changing a server-set property, though "it is not an
584    ///   error to include a server-set property in an update as long as
585    ///   the value is identical to the current value on the server."
586    ///
587    /// # Atomicity
588    ///
589    /// RFC 8620 §5.3: the server "MUST NOT only commit part of an update
590    /// to a single record". Apply the whole patch and validate the result
591    /// before writing it, so that on any error the stored record is
592    /// unchanged. State and change log follow
593    /// [`create_object`](Self::create_object) ("State and change log"); an
594    /// `Ok(None)` return still advances the state.
595    fn update_object<O: SetObject + Send + Sync>(
596        &self,
597        caller: &Self::CallerCtx,
598        account_id: &jmap_types::Id,
599        id: &jmap_types::Id,
600        patch: O::Patch,
601    ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
602
603    /// Destroy an existing object by id.
604    ///
605    /// # Errors
606    ///
607    /// As for [`create_object`](Self::create_object), plus these RFC 8620
608    /// §5.3 rules for destroy: an unknown id, including one already
609    /// destroyed, is `notFound`, and a destroy that "would violate an ACL
610    /// or other permissions policy" is `forbidden`.
611    ///
612    /// # Cascades
613    ///
614    /// `destroy_object::<Message>` MUST also remove the id from its
615    /// Chat's `pinnedMessageIds` (draft-atwood-jmap-chat-00 §Chat:
616    /// "When a pinned Message is hard-deleted, the server MUST remove
617    /// its id from this list."), as
618    /// [`expire_message`](Self::expire_message) does. That change is
619    /// a Chat update.
620    ///
621    /// `destroy_object::<Space>` MUST also destroy every channel Chat
622    /// whose `spaceId` is the Space and every Message in those Chats
623    /// (draft-atwood-jmap-chat-00 §Destroying a Space: "Cascades to all
624    /// channel Chats and their Messages. Hard-deletes all records; no
625    /// tombstones are retained."). Those are Chat and Message destroys.
626    ///
627    /// If the backend itself changes another record because of the
628    /// destroy, it MUST advance that record type's state and record the
629    /// change in the same atomic step, so `/changes` on that type sees it.
630    /// State and change log for `O` follow
631    /// [`create_object`](Self::create_object) ("State and change log").
632    fn destroy_object<O: SetObject + Send + Sync>(
633        &self,
634        caller: &Self::CallerCtx,
635        account_id: &jmap_types::Id,
636        id: &jmap_types::Id,
637    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
638
639    /// Returns true if this backend implements the given JMAP object type.
640    ///
641    /// # Contract
642    ///
643    /// This is a **global, stateless backend-capability check** — it asks
644    /// "did this implementation wire up the methods needed for type
645    /// `O`?", not "does this user's account have this type enabled?".
646    /// That is why the method is synchronous and takes no `caller` or
647    /// `account_id` arguments. Per-account capability variation belongs
648    /// in the consumer's session-capability builder (workspace AGENTS.md
649    /// library-kit posture), NOT here.
650    ///
651    /// # Types in scope
652    ///
653    /// Implementors should answer for the object types this trait
654    /// covers (draft-atwood-jmap-chat-00): `Chat`, `Message`, `Space`,
655    /// `SpaceInvite`, `SpaceBan`, `ChatContact`, `CustomEmoji`,
656    /// `ReadPosition`, and `PresenceStatus`. Backends MAY answer for
657    /// object types from sibling extensions if they also implement those
658    /// traits. A backend that does not recognise `O` SHOULD return
659    /// `false`.
660    ///
661    /// # Callers
662    ///
663    /// The handler library in this crate does not call this method. The
664    /// server consumer calls it when building the JMAP session capability
665    /// response.
666    ///
667    /// # Per-account semantics
668    ///
669    /// Capabilities are per account (RFC 8620 §1.6.2, §2
670    /// `accountCapabilities`), so the answer may vary with `caller` and
671    /// `account_id`. Backends that support every type in this trait for
672    /// every account can ignore both arguments and return `true`.
673    ///
674    /// # Why sync, not async
675    ///
676    /// Type-support is a deployment capability question answered from
677    /// in-process state. A backend whose supported types come from
678    /// configuration or a per-account record SHOULD load it ahead of the
679    /// request and answer from the in-memory snapshot. See the
680    /// trait-level "Async vs sync method convention" section above for
681    /// the workspace rationale.
682    fn supports_type<O: JmapObject>(
683        &self,
684        caller: &Self::CallerCtx,
685        account_id: &jmap_types::Id,
686    ) -> bool;
687
688    /// Generate a cryptographically random invite code.
689    ///
690    /// Implementations MUST use a CSPRNG seeded from OS entropy. The
691    /// recommended choices are [`rand::rngs::OsRng`] or the [`getrandom`]
692    /// crate directly. Do NOT use `rand::thread_rng()` for security-relevant
693    /// output: although current `rand` versions document `ThreadRng` as
694    /// cryptographically secure, its underlying algorithm is
695    /// implementation-defined and has changed across releases, and the
696    /// `rand` book explicitly routes security-sensitive callers to `OsRng`.
697    ///
698    /// The returned string must be unguessable — do NOT use timestamps,
699    /// sequential counters, or non-CSPRNG sources.
700    ///
701    /// # Output shape contract
702    ///
703    /// Implementations MUST satisfy ALL of the following for the kit's
704    /// constant-time-compare guarantee (see below) to hold:
705    ///
706    /// 1. **Fixed length across calls.** Every invocation of
707    ///    `generate_invite_code` on a single backend MUST return a
708    ///    string of the same byte length. A backend that returns
709    ///    variable-length codes leaks a length oracle through the
710    ///    constant-time-compare timing channel: `ct_eq` returns
711    ///    `Choice(0)` cheaply on length mismatch, so an attacker can
712    ///    learn whether their candidate code matches the stored
713    ///    length even when the content compare is constant-time.
714    /// 2. **Minimum 128 bits of CSPRNG entropy.** The reference
715    ///    `MemoryBackend` impl in this crate (in `memory.rs`) emits
716    ///    32 lowercase-hex characters (16 bytes = 128 bits) which is
717    ///    the workspace floor. Production backends MAY use more; less
718    ///    is forbidden. The trait method itself is abstract — no
719    ///    default impl — so backends MUST provide one.
720    /// 3. **ASCII-safe encoding.** The returned bytes MUST be 7-bit
721    ///    ASCII printable, byte-length-equal-to-char-length, and
722    ///    safe to use as-is in JMAP wire format and HTTP-style
723    ///    URL paths (no `/`, `+`, `=`, or whitespace). Recommended
724    ///    encodings: lowercase hex (the default), base32 unpadded,
725    ///    base64url unpadded. Plain base64 with `/` is forbidden
726    ///    because downstream URL-encoded redemption flows misroute
727    ///    the slash. Non-ASCII output is forbidden because
728    ///    helpers that take byte-prefix slices (e.g. the
729    ///    `iso8601_before` partial-comparison family) panic on
730    ///    multi-byte UTF-8 boundaries.
731    /// 4. **Sufficient lifespan.** Codes MUST remain
732    ///    discriminable from each other across the backend's
733    ///    retention window. With 128 bits of entropy and
734    ///    well-mixed CSPRNG output, collision probability is
735    ///    cryptographically negligible up to 2^64 active codes.
736    ///
737    /// A backend that cannot meet any of points 1–3 MUST NOT
738    /// expose `Space/join`'s invite-code redemption path, or MUST
739    /// build its own redemption with a different constant-time
740    /// argument. The kit's `handle_space_join` assumes the contract
741    /// without re-validating each code's shape.
742    ///
743    /// # Constant-time comparison contract
744    ///
745    /// Consumers of the returned code (notably `Space/join` invite-code
746    /// lookup) MUST compare it against attacker-supplied values in
747    /// constant time using `subtle::ConstantTimeEq::ct_eq` or equivalent.
748    /// The reference handler in `space::handle_space_join` already does
749    /// this; backends that build their own invite-redemption paths must
750    /// preserve the invariant. A plain `String == String` short-circuits
751    /// at the first mismatched byte and exposes a byte-by-byte timing
752    /// oracle for credential recovery.
753    ///
754    /// # Fallibility and async — known limitations
755    ///
756    /// This method is sync and infallible. Backends that mint codes
757    /// via a remote source (HSM, KMS, hardened sandbox where
758    /// `getrandom` is gated, etc.) cannot surface failure from this
759    /// signature and cannot `.await` a network call. Such backends
760    /// must pre-fetch a buffer of codes at startup and serve from it,
761    /// or panic on entropy starvation. A future revision MAY change
762    /// the signature to `async fn generate_invite_code(&self) ->
763    /// Result<String, Self::Error>` to support remote / fallible
764    /// entropy sources without forcing the pre-fetch workaround.
765    ///
766    /// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
767    /// [`getrandom`]: https://docs.rs/getrandom
768    fn generate_invite_code(&self) -> String;
769
770    /// Redeem the SpaceInvite `invite_id` for `Space/join`: add the owner
771    /// (member entry `account_id`, no roles, `joinedAt` = `joined_at`) to
772    /// the invite's Space and increment the invite's `uses`.
773    ///
774    /// Per draft-atwood-jmap-chat-00 §Space/join: "The `uses` increment
775    /// and membership insertion MUST be performed within a single atomic
776    /// operation so that concurrent redemptions cannot exceed `maxUses`."
777    ///
778    /// # Atomicity contract
779    ///
780    /// The `uses < maxUses` check, the already-member check, the member
781    /// append and the `uses` increment MUST all take effect or none, and
782    /// MUST be serialized against concurrent redemptions of the invite
783    /// and concurrent membership writes to the Space (a transaction or
784    /// compare-and-swap). Composing this from `update_object` calls loses
785    /// that guarantee: a failed second write leaves a member admitted
786    /// without a use counted, and concurrent joins both pass `maxUses`.
787    ///
788    /// # Account scope
789    ///
790    /// `account_id` is the request's `accountId`, which names the
791    /// account hosting the Space; the handler resolves the invite code
792    /// only within that account, and `invite_id` and its Space live
793    /// there. Implementations need no server-wide invite-code index.
794    ///
795    /// # When the handler calls this
796    ///
797    /// Once, after the invite resolved by code and is unexpired, and
798    /// after the ban and `closedAt` checks. The handler maps each
799    /// [`InviteJoinRefusal`] to the draft's `invalidArguments` method
800    /// error. There is no default: a non-atomic default would reinstate
801    /// the race.
802    fn join_space_with_invite(
803        &self,
804        caller: &Self::CallerCtx,
805        account_id: &jmap_types::Id,
806        invite_id: &jmap_types::Id,
807        joined_at: &jmap_types::UTCDate,
808    ) -> impl std::future::Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send;
809
810    /// Apply a `readAt`-setting `patch` to the `burnOnRead` Message
811    /// `message_id` and hard-delete it, as one atomic operation.
812    ///
813    /// Per draft-atwood-jmap-chat-00 §Message `burnOnRead`: "the
814    /// receiving server MUST permanently hard-delete this message (row
815    /// removal, not tombstone) immediately after setting `readAt`."
816    ///
817    /// # Atomicity contract
818    ///
819    /// Validate `patch` against the stored Message exactly as
820    /// [`Self::update_object`] would, then remove the row, record the id
821    /// in the `destroyed` set of the `Message` change log (bumping the
822    /// `Message` state once), and unpin it from its Chat (§Chat
823    /// `pinnedMessageIds`). All of it takes effect or none: on any error
824    /// nothing is committed, so a retried `readAt` patch burns again.
825    /// Composing this from `update_object` and [`Self::expire_message`]
826    /// loses that guarantee: a failed delete leaves `readAt` stored, and
827    /// a retry finds nothing left to set.
828    ///
829    /// # When the handler calls this
830    ///
831    /// `Message/set` update calls this instead of `update_object` when
832    /// the patch sets a non-null `readAt` and the stored Message has
833    /// `burnOnRead: true`. Return `SetError` `notFound` if the Message
834    /// does not exist and the `update_object` `SetError` for an invalid
835    /// patch. There is no default: a non-atomic default would reinstate
836    /// the gap.
837    fn read_and_burn_message(
838        &self,
839        caller: &Self::CallerCtx,
840        account_id: &jmap_types::Id,
841        message_id: &jmap_types::Id,
842        patch: jmap_types::PatchObject,
843    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
844
845    /// Implementation-defined per-Space content limits for this caller
846    /// and account.
847    ///
848    /// Called by `handle_space_set` once per request, before
849    /// dispatching to [`Self::apply_space_patch`], to enforce
850    /// per-aggregate caps on roles, members, channels, and categories
851    /// per Space (draft-atwood-jmap-chat-00 §Space/set, spec commit
852    /// `80d5e11`), and by `handle_message_set` once per request to
853    /// validate `bodyType` against [`ChatLimits::supported_body_types`]
854    /// and [`ChatLimits::server_reserved_body_types`].
855    ///
856    /// The default implementation returns [`ChatLimits::default`],
857    /// which carries conservative reference-impl-grade values. The
858    /// `caller` and `account_id` arguments are plumbed even though the
859    /// default impl ignores them, so production backends can vary caps
860    /// per-account (Free vs. Pro tier, multi-tenant SaaS, etc.)
861    /// without a future API break. Implementations SHOULD return
862    /// quickly (in-process struct construction, possibly off a cached
863    /// per-account record) — this method is called on the hot
864    /// `Space/set` path.
865    ///
866    /// # Why sync, not async
867    ///
868    /// `Space/set` calls this once per request before dispatching the
869    /// mutation; an async `.await` here would add a roundtrip to the
870    /// hot path of every Space mutation. Production backends with
871    /// per-tenant caps SHOULD cache the resolved [`ChatLimits`] for
872    /// each account on first use and serve from the cache thereafter.
873    /// See the trait-level "Async vs sync method convention" section
874    /// above for the workspace rationale.
875    ///
876    /// Workspace cross-extension pattern: see `AGENTS.md` "Backend
877    /// caps and limits".
878    fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
879        ChatLimits::default()
880    }
881
882    /// Apply a sequence of structural mutations to a Space
883    /// (draft-atwood-jmap-chat-00 §Space/set).
884    ///
885    /// `Space/set` `update` operations use semantic mutation keys
886    /// (`addRoles`, `removeRoles`, `addMembers`, …) rather than RFC 8620
887    /// JSON Pointer patches. The handler in `space::handle_space_set`
888    /// parses the wire object, unfolds each array entry into a
889    /// [`SpacePatchOp`] value, then calls this method with the resulting
890    /// ordered `Vec`.
891    ///
892    /// # Ordering and atomicity
893    ///
894    /// Implementations SHOULD apply ops in input order and SHOULD provide
895    /// best-effort transactional semantics so that a partial failure does
896    /// not leave the Space in a half-updated state. The reference
897    /// in-memory implementation locks the entire backend for the duration
898    /// of the call. A database-backed implementation should wrap the
899    /// sequence in a single transaction.
900    ///
901    /// # Permission and limit checks
902    ///
903    /// Permission gates (`manage_space`, `manage_roles`,
904    /// `manage_members`, `manage_channels`) are backend-canonical per
905    /// workspace AGENTS.md "Caller identity (foundation seam)": the
906    /// reference handler does NOT apply gates before calling this
907    /// method, and the backend is responsible for rejecting any op the
908    /// caller is not authorized to perform.
909    ///
910    /// Per-aggregate count limits on roles, members, channels, and
911    /// categories per Space are **backend-canonical** as of
912    /// bd:JMAP-x2gd.44: the backend MUST query its own
913    /// [`ChatBackend::limits`], project the post-patch counts for the
914    /// target Space, and reject the whole patch with an `overQuota`
915    /// SetError (RFC 8620 §5.3) if any aggregate would exceed its
916    /// cap. The cap enforcement MUST be atomic with the mutation
917    /// itself — typically inside the same database transaction or
918    /// the same mutex critical section. Per
919    /// draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
920    /// 2026-05-11), this behavior is normative.
921    ///
922    /// The handler at [`crate::space::handle_space_set`] additionally
923    /// runs a defense-in-depth pre-flight cap check before this
924    /// method, but the pre-flight is non-load-bearing: a backend
925    /// caller that bypasses the JMAP wire layer (admin tool,
926    /// federation receiver, internal batch importer) and calls
927    /// `apply_space_patch` directly MUST still see caps enforced.
928    /// The pre-flight exists only to surface `overQuota` to the
929    /// client as a single SetError without consuming a backend
930    /// round-trip; backends MAY rely on the handler having pre-checked
931    /// for performance, but MUST NOT rely on it for correctness.
932    ///
933    /// The role-position hierarchy check (members may only add or modify
934    /// roles whose `position` is strictly less than their own
935    /// highest-position role — draft §Space/set lines 1096, 1102) MUST
936    /// be enforced by the backend because it is atomic with the
937    /// mutation and depends on the current Space state.
938    ///
939    /// # Cross-type cascade contract
940    ///
941    /// Several `SpacePatchOp` variants have side effects on other JMAP
942    /// types in the chat extension (`Chat`, `Message`). The wire-format
943    /// `Space/set` response describes only the Space-side change, but
944    /// `/changes` subscribers on the cascaded types depend on the
945    /// backend bumping the relevant type state tokens. A backend that
946    /// performs the cross-type mutations but forgets the state bumps
947    /// silently desynchronises every multi-client subscriber — the
948    /// failure is invisible to single-tenant smoke tests.
949    ///
950    /// The required cascades are:
951    ///
952    /// * `RemoveChannel` — MUST destroy the channel-kind `Chat` record
953    ///   and every `Message` whose `chatId` matches the removed
954    ///   channel (draft §Space/set line 1117: "Cascades to all
955    ///   Messages in those channels."). The `Chat` and `Message` type
956    ///   state tokens MUST both bump so `Chat/changes` and
957    ///   `Message/changes` subscribers see the destruction.
958    ///
959    /// * `RemoveCategory` — MUST clear `Chat.categoryId` on every
960    ///   channel-kind `Chat` whose `categoryId` named the removed
961    ///   category (the channels fall back to uncategorized). The
962    ///   `Chat` type state token MUST bump and the affected channel
963    ///   ids MUST appear in the next `Chat/changes` entry's `updated`
964    ///   list.
965    ///
966    /// * `AddCategory` / `UpdateCategory` with a non-empty `channelIds`
967    ///   array — MUST set `Chat.categoryId` on each named channel
968    ///   (relocating it from its previous category or from
969    ///   uncategorized). The `Chat` type state token MUST bump and
970    ///   the relocated channel ids MUST appear in `Chat/changes`
971    ///   `updated`. This pins a regression class where channel
972    ///   relocations silently bypass the `Chat/changes` log; a
973    ///   backend that mutates `Chat.categoryId` without bumping the
974    ///   `Chat` state token desynchronises every multi-client
975    ///   subscriber.
976    ///
977    /// * `RemoveRole` — MUST strip the removed role id from
978    ///   `roleIds` on every `SpaceMember` of this Space (draft
979    ///   §Space/set line 1099). Members embed directly in `Space`,
980    ///   so the cascade is captured by the existing `Space` state
981    ///   bump; no separate `Member/changes` rotation is required.
982    ///
983    /// * `RemoveMember` — MUST remove the member entry and keep
984    ///   `Space.memberCount` consistent with `members.len()`. The
985    ///   spec does not mandate cascade to the member's `ReadPosition`
986    ///   records; the reference impl leaves them in place and treats
987    ///   ReadPosition cleanup as implementation-defined. A backend
988    ///   that destroys orphaned ReadPositions MUST bump the
989    ///   `ReadPosition` type state token; a backend that retains
990    ///   them MUST NOT.
991    ///
992    /// State-token bumps SHOULD be batched per call: one bump per
993    /// affected type per `apply_space_patch` invocation, not one bump
994    /// per op. The reference impl combines every channel created,
995    /// updated, and destroyed by a patch into a single `Chat/changes`
996    /// entry; doing the same in production keeps `/changes`
997    /// rotation rates proportional to client-visible mutations rather
998    /// than to internal op count.
999    ///
1000    /// # Server-set field invariants
1001    ///
1002    /// Server-set fields on the target Space (`memberCount`,
1003    /// `updatedAt`, and any future analogous cached aggregates) MUST
1004    /// be kept consistent with the post-mutation state. Specifically,
1005    /// after any combination of `AddMember` and `RemoveMember` ops,
1006    /// `Space.memberCount` MUST equal `Space.members.len()` as
1007    /// observed by the next `Space/get`. Backends MAY store these as
1008    /// cached values that they recompute on every mutation, or MAY
1009    /// compute them lazily at read time; either is acceptable as
1010    /// long as `Space/get` returns values consistent with the
1011    /// returned `members` array. The natural-minimal "persist
1012    /// memberCount once and trust it" implementation is **not**
1013    /// correct: subsequent mutations to `members` would let
1014    /// `memberCount` drift silently.
1015    ///
1016    /// `Space.closedAt` is server-set the same way: when the caller
1017    /// removes themselves as the last member holding `manage_space`
1018    /// and other members remain, the backend MUST set `closedAt` in
1019    /// the same mutation (draft §Space/set `removeMembers`). The
1020    /// handler rejects every other update to a closed Space.
1021    ///
1022    /// # Per-op error semantics
1023    ///
1024    /// Backend rejections that originate from a single op carry both
1025    /// a typed [`SetErrorType`] and a human-readable `description`
1026    /// string. The kit's integration tests pin specific
1027    /// (`SetErrorType`, `description`-substring) pairs for the
1028    /// common failure modes; a backend that returns a different
1029    /// variant or an empty description will fail those tests when
1030    /// plugged in.
1031    ///
1032    /// The following table records the contract for the
1033    /// failure modes the kit exercises today:
1034    ///
1035    /// | Op + failure mode | `SetErrorType` | `description` MUST contain |
1036    /// |---|---|---|
1037    /// | Any op, caller lacks the spec-mandated permission | `Forbidden` | the permission identifier as a substring (`"manage_space"`, `"manage_channels"`, `"manage_members"`, `"manage_roles"`, or a deployment-specific permission name) |
1038    /// | `AddRole` / `UpdateRole` at or above caller's highest role `position` | `Forbidden` | `"hierarchy"` or `"position"` |
1039    /// | Any op or combination of ops whose post-patch projection leaves the Space with zero `manage_members`-holding members (when [`Self::protect_last_admin`] returns `true`), other than self-removal | `InvalidProperties` (`properties: ["removeMembers"]`) | `"last-admin"` or `"manage_members"` |
1040    /// | `AddMember` with `userId` already a member | `InvalidProperties` (`properties: ["userId"]`) | implementation-defined; the reference impl names the duplicate userId |
1041    /// | `AddMember` with a `roleId` that does not name a role on this Space | `InvalidProperties` (`properties: ["roleIds"]`) | implementation-defined; the reference impl names the unknown roleId |
1042    /// | `RemoveRole` / `RemoveChannel` / `RemoveCategory` with an id that does not exist on this Space | `NotFound` | implementation-defined; the reference impl names the missing id |
1043    ///
1044    /// The "MUST contain ... as a substring" rule on permission-denied
1045    /// failures lets downstream UI / CLI consumers route
1046    /// permission-request flows by parsing the description, and lets
1047    /// users see "Permission denied: missing manage_space" rather
1048    /// than a bare "Permission denied". Deployments that need a
1049    /// programmatic alternative SHOULD additionally surface the
1050    /// missing permission via [`SetError::with_extra`] under a
1051    /// deployment-specific key — substring matching is the floor,
1052    /// not the ceiling.
1053    ///
1054    /// Note on routing: per-op rejections normally surface inside the
1055    /// returned [`OpResult`] vector, NOT as a top-level
1056    /// [`BackendSetError`] return. The handler at
1057    /// [`crate::space::handle_space_set`] applies the kit's per-
1058    /// update-target atomicity: any failing op in the patch fails the
1059    /// whole `update` target, so the test fixtures see the first-failing
1060    /// op's `(SetErrorType, description)` surface on
1061    /// `notUpdated[<spaceId>]`. The table above describes the
1062    /// per-op outcome content; the handler does not synthesise new
1063    /// variants or rewrite descriptions.
1064    ///
1065    /// # Return value
1066    ///
1067    /// On success, returns a `Vec<OpResult>` of the same length as `ops`,
1068    /// in input order. Each entry reports the outcome of one op (id
1069    /// assignment for `Add*` variants, error for rejections). The
1070    /// handler maps per-op errors back into the `/set` response shape
1071    /// per [`OpResult`]'s documentation.
1072    ///
1073    /// Returns [`BackendSetError::Other`] only for backend-level failures
1074    /// (the storage layer is unreachable, the account does not exist,
1075    /// `space_id` is unknown, etc.) — i.e. failures that prevent any op
1076    /// from being attempted. Per-op rejections (permission denied,
1077    /// invalid id, role hierarchy violation, etc.) go in the `outcome`
1078    /// field of the returned [`OpResult`] vector, not in an error return.
1079    fn apply_space_patch(
1080        &self,
1081        caller: &Self::CallerCtx,
1082        account_id: &jmap_types::Id,
1083        space_id: &jmap_types::Id,
1084        ops: Vec<SpacePatchOp>,
1085    ) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
1086
1087    /// Apply a JSON Merge Patch to a Space's top-level metadata fields
1088    /// (draft-atwood-jmap-chat-00 §Space/set, `name`, `description`,
1089    /// `iconBlobId`, `isPublic`, `isPubliclyPreviewable`).
1090    ///
1091    /// `Space/set` `update` operations carrying *only* top-level
1092    /// metadata fields (and not the semantic-mutation keys
1093    /// `addRoles` / `addMembers` / `addChannels` / `addCategories`
1094    /// etc.) route through this method instead of the generic
1095    /// [`Self::update_object`]. Mixed patches carrying both top-level
1096    /// metadata AND semantic-mutation keys call
1097    /// [`Self::apply_space_patch`] first (for the structural ops) and
1098    /// this method second (for the metadata). The handler at
1099    /// `space::handle_space_set` is responsible for the split and for
1100    /// stripping non-metadata keys before calling this method.
1101    ///
1102    /// # Permission and atomicity
1103    ///
1104    /// Per draft-atwood-jmap-chat-00, every top-level metadata field
1105    /// carries the marker "Mutable by members with `manage_space`
1106    /// permission". Implementations MUST gate the mutation on the
1107    /// caller's effective permissions in the target Space: verify the
1108    /// caller holds `manage_space` (resolved through the Space's role
1109    /// hierarchy) and reject the patch with
1110    /// [`SetErrorType::Forbidden`] if not. The caller is the owner, whose
1111    /// `members` entry is the `account_id` (draft §Terminology), so look
1112    /// the caller up by `account_id`, not by the principal, whether or
1113    /// not [`JmapBackend::principal_id`] returns `Some`; the same holds
1114    /// for every caller-membership or permission check in this trait.
1115    ///
1116    /// The check fires inside this method atomically with the
1117    /// mutation: snapshot the Space's role/member state, evaluate
1118    /// the permission gate, and apply the merge patch in one
1119    /// critical section. Backend canonical per workspace AGENTS.md.
1120    ///
1121    /// # `patch` shape
1122    ///
1123    /// The handler decodes the wire patch's metadata-key subset
1124    /// (`name`, `description`, `iconBlobId`, `isPublic`,
1125    /// `isPubliclyPreviewable`) into a [`SpaceMetadataPatch`],
1126    /// stripping structural mutation keys (`addRoles` etc.) before
1127    /// building it. Each field is `Option<_>`; nullable target fields
1128    /// use `Option<Clearable<T>>` so the backend can distinguish
1129    /// "wire null" (clear) from "absent" (unchanged). Backends MAY
1130    /// validate the values further (e.g. reject an `icon_blob_id`
1131    /// referencing a non-existent blob) and surface those as
1132    /// [`SetError`] returns. The expected `SetErrorType` for
1133    /// value-level validation failures is
1134    /// [`SetErrorType::InvalidProperties`] with the offending field
1135    /// name in `properties` — see the "Diagnostic content
1136    /// convention" section below for the blob-not-found shape
1137    /// specifically. (RFC 8620 §5.3 defines `blobNotFound` only as
1138    /// a method-level error; at the SetError level it surfaces as
1139    /// `InvalidProperties` naming the offending blob-id field.)
1140    ///
1141    /// # Return value
1142    ///
1143    /// The discriminator between `Ok(Some(space))` and `Ok(None)` is
1144    /// the **wire-visible Space shape**:
1145    ///
1146    /// - Return `Ok(None)` if the wire-visible `Space` (the shape
1147    ///   `Space/get` would serialise after applying this patch) is
1148    ///   identical to the result of mechanically applying the patch
1149    ///   keys to the prior state with no additional server-side
1150    ///   modification. The handler can then build the `/set` `updated`
1151    ///   entry from the input patch alone with no extra fetch.
1152    /// - Return `Ok(Some(space))` if the backend modified any
1153    ///   wire-visible property beyond what the client requested
1154    ///   (RFC 8620 §5.3 server-set field echo, e.g. a normalised
1155    ///   `name`, a derived `iconBlobId`, a server-bumped
1156    ///   `memberCount`, or any spec-defined server-set field that
1157    ///   `Space/get` would return). The handler echoes the returned
1158    ///   `Space` to the client.
1159    ///
1160    /// Server-internal bookkeeping that is NOT part of the
1161    /// wire-visible `Space` shape (e.g. private last-touched
1162    /// timestamps used only for `/changes` cache-keying, internal
1163    /// sequence numbers) MUST NOT itself drive the `Some` path —
1164    /// the discriminator is "would `Space/get` return a different
1165    /// shape?", not "did the backend touch anything internally?".
1166    /// A backend that bumps an internal timestamp on every metadata
1167    /// patch correctly returns `Ok(None)` when the wire shape is
1168    /// otherwise unchanged.
1169    ///
1170    /// `Err(BackendSetError::SetError(e))` with `e.kind ==
1171    /// SetErrorType::Forbidden` when the caller fails the
1172    /// `manage_space` gate.
1173    ///
1174    /// # Diagnostic content convention
1175    ///
1176    /// The `SetError.description` on a `manage_space`-gate rejection
1177    /// MUST contain `"manage_space"` as a substring. The kit's
1178    /// integration tests assert this (e.g.
1179    /// `tests/space_metadata_apply.rs`); a backend that returns a
1180    /// bare `SetError::new(SetErrorType::Forbidden)` with no
1181    /// `description` will fail those tests. Build the error via
1182    /// `SetError::new(SetErrorType::Forbidden).with_description(
1183    /// "manage_space permission required")` (or any other string
1184    /// that contains the literal `"manage_space"`).
1185    ///
1186    /// Future blob-validation rejections (e.g. `iconBlobId`
1187    /// referencing a non-existent blob, see the `patch` shape
1188    /// section above) SHOULD surface as
1189    /// `SetErrorType::InvalidProperties` with
1190    /// `properties: ["iconBlobId"]` and a description that names
1191    /// the offending blob id. The reference impl does not validate
1192    /// blobs today; production backends with a blob store SHOULD.
1193    ///
1194    /// Rationale for the separate metadata patch method: routing
1195    /// top-level metadata through the generic `update_object::<Space>`
1196    /// would bypass the permission gate, since the generic path is
1197    /// not permission-aware. This method exists so that top-level
1198    /// `Space/set` `update` requests carrying only metadata fields
1199    /// (`name` / `description` / `iconBlobId` / `isPublic` /
1200    /// `isPubliclyPreviewable`) route through a `manage_space`-gated
1201    /// path instead.
1202    fn apply_space_metadata_patch(
1203        &self,
1204        caller: &Self::CallerCtx,
1205        account_id: &jmap_types::Id,
1206        space_id: &jmap_types::Id,
1207        patch: jmap_chat_types::SpaceMetadataPatch,
1208    ) -> impl std::future::Future<
1209        Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
1210    > + Send;
1211
1212    /// Whether the backend should reject any [`Self::apply_space_patch`]
1213    /// that would leave the target Space with zero members holding
1214    /// either `manage_members` or `manage_space` permission.
1215    ///
1216    /// # Invariant (by outcome, not by op type)
1217    ///
1218    /// The protection is invariant on the *post-patch* state of the
1219    /// (member, role, permission) graph, not on any single op variant.
1220    /// A backend that returns `true` from this method MUST reject every
1221    /// patch whose post-application projection has zero members holding
1222    /// `manage_members` or `manage_space`, including (non-exhaustively)
1223    /// the cases below. Self-removal (a `removeMembers` holding only the
1224    /// accountId, which references the owner per draft §Terminology) is
1225    /// exempt: draft §Space/set says
1226    /// "Last-administrator protection does not apply to self-removal."
1227    ///
1228    ///
1229    /// - `RemoveMember` that removes the last admin member.
1230    /// - `UpdateMember` that strips a role granting `manage_members` or
1231    ///   `manage_space` from a member who holds no other such role.
1232    /// - `UpdateRole` that removes `manage_members` or `manage_space`
1233    ///   permission from a role currently held by the last admin.
1234    /// - `RemoveRole` that drops a permission-granting role from the
1235    ///   graph when no other role grants the same permission to a
1236    ///   remaining member.
1237    /// - Any combination of the above within a single `ops` vector
1238    ///   whose cumulative effect is zero admins.
1239    ///
1240    /// Production backends should project the post-patch graph and
1241    /// reject when the admin count would reach zero, regardless of
1242    /// which op caused the transition.
1243    ///
1244    /// # Why this exists
1245    ///
1246    /// The 2026-05-12 design reversal dropped the `Space.ownerId` field:
1247    /// "who controls a Space" is now fully implementation-defined /
1248    /// out-of-band per draft-atwood-jmap-chat-00.
1249    /// Without a normative owner identity, the kit cannot enforce the
1250    /// previous "owner cannot be removed" rule. Instead the kit exposes
1251    /// this purely permission-graph-based knob: production backends that
1252    /// want to prevent the "no admin left" failure mode return `true`
1253    /// (the trait default); deployments with their own designated
1254    /// controller principal or external admin-tracking system can opt
1255    /// out by returning `false`.
1256    ///
1257    /// # Default implementation
1258    ///
1259    /// Returns `true` — production-safe by default. A third-party
1260    /// backend that does not override this method gets last-admin
1261    /// protection automatically.
1262    ///
1263    /// # Why the reference `MemoryBackend` overrides this to `false`
1264    ///
1265    /// The reference impl flips the default to keep existing
1266    /// integration tests (which do not seed admin memberships) passing
1267    /// unchanged. Tests that exercise the protection path opt in via
1268    /// `MemoryBackend::set_protect_last_admin_for_test(true)`.
1269    ///
1270    /// The reference impl's projection is intentionally narrow: it
1271    /// covers `RemoveMember` only, and does NOT model `UpdateMember`
1272    /// role-strip, `UpdateRole` permission-strip, or `RemoveRole`
1273    /// paths to zero-admin state. Production backends with the full
1274    /// invariant requirement MUST extend the projection.
1275    ///
1276    /// # Atomicity
1277    ///
1278    /// The check fires inside [`Self::apply_space_patch`] atomically
1279    /// with the candidate mutation: the backend snapshots the Space's
1280    /// member/role state, projects the post-patch admin count across
1281    /// all ops in the patch (member adds/removes, role-id changes,
1282    /// permission edits), and rejects the whole update target with a
1283    /// `Forbidden` SetError if zero admins would remain.
1284    ///
1285    /// # Why sync, not async
1286    ///
1287    /// This predicate is a deployment-policy flag: a backend either
1288    /// enforces the last-admin invariant or it does not. Backends
1289    /// that consult an external admin-tracking service to derive the
1290    /// answer SHOULD cache the per-account boolean and answer from
1291    /// the cache. See the trait-level "Async vs sync method
1292    /// convention" section above for the workspace rationale.
1293    fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
1294        let _ = (caller, account_id);
1295        true
1296    }
1297
1298    /// Whether the backend retains edit history for messages.
1299    ///
1300    /// Per draft-atwood-jmap-chat-00 commit `0783fc4` ("condition
1301    /// MessageRevision push on edit-history retention") +
1302    /// `§Message editHistory`: servers MAY limit retained
1303    /// MessageRevisions, and when the server does not retain edit
1304    /// history, the `editHistory` field MUST be omitted from
1305    /// `Message/get` and (in principle) `Message/changes` responses.
1306    /// `Message/changes` per RFC 8620 §5.2 returns only id arrays,
1307    /// not Message objects, so the spec's "omit from /changes" is
1308    /// a no-op at the wire level — the kit only enforces the
1309    /// `Message/get` projection.
1310    ///
1311    /// # When the handler calls this
1312    ///
1313    /// `handle_message_get` consults this predicate once per call.
1314    /// When `false`, every returned `Message` has its
1315    /// `edit_history` field set to `None` before serialization,
1316    /// which serde's `skip_serializing_if = "Option::is_none"`
1317    /// collapses to a wire-absent field per spec.
1318    ///
1319    /// # Why sync, not async
1320    ///
1321    /// This is a static deployment-policy flag, not a per-call
1322    /// decision — it does not consult per-account state, principal
1323    /// identity, or per-message bounds. Production backends that
1324    /// need to vary retention per-account would file a follow-up
1325    /// bead for a parallel `retains_edit_history_for_account` hook
1326    /// rather than reshaping this method.
1327    ///
1328    /// # Default implementation
1329    ///
1330    /// Returns `false` — no retention. This matches the workspace's
1331    /// "kit defines the hook; consumer enforces the policy" posture.
1332    /// Production backends that retain edit history MUST override
1333    /// this to `true`; the reference `MemoryBackend` exposes a
1334    /// test-only setter for tests that need the retain-on path.
1335    fn retains_edit_history(&self) -> bool {
1336        false
1337    }
1338
1339    /// Predicate consulted by typing/presence fan-out paths: is the
1340    /// caller (the sender of the ephemeral event) blocked by the
1341    /// recipient who owns `account_id`'s contact list?
1342    ///
1343    /// Per draft-atwood-jmap-chat-00 commit `d68b4e3` (2026-05-11,
1344    /// "close blocked-sender suppression gaps for typing/presence"):
1345    /// when the sender corresponds to a [`ChatContact`] whose
1346    /// `blocked` is `true` on the recipient's contact list, the
1347    /// server MUST silently suppress the ephemeral event for that
1348    /// recipient. The sender is NOT informed.
1349    ///
1350    /// [`ChatContact`]: jmap_chat_types::ChatContact
1351    ///
1352    /// # Argument semantics
1353    ///
1354    /// - `caller`: identity of the sender. Backends with identity
1355    ///   wired resolve this via
1356    ///   [`JmapBackend::principal_id`];
1357    ///   the resolved principal is matched against the
1358    ///   [`ChatContact`]'s implementation-defined principal binding
1359    ///   to determine which `ChatContact` (if any) in the recipient's
1360    ///   list represents the sender.
1361    /// - `account_id`: the **recipient's** account, i.e. the account
1362    ///   that owns the [`ChatContact`] list to consult. NOT the
1363    ///   sender's account.
1364    /// - `contact_id`: the candidate [`ChatContact`] id within the
1365    ///   recipient's account. The backend checks whether THIS
1366    ///   contact's `blocked` field is `true` AND whether THIS
1367    ///   contact corresponds to the sender (via the principal
1368    ///   binding resolved from `caller`).
1369    ///
1370    /// # Single-user mode (principal_id returns None)
1371    ///
1372    /// Backends that have not wired identity cannot match the sender
1373    /// against a `ChatContact` principal binding. Such backends
1374    /// SHOULD fail-safe by returning `Ok(false)` (the default impl
1375    /// does this), which preserves visibility — under-suppression in
1376    /// a single-user dev deployment is preferable to
1377    /// over-suppression that would mask a misconfigured backend.
1378    ///
1379    /// # When the handler calls this
1380    ///
1381    /// `handle_chat_typing` consults this predicate when the target
1382    /// `Chat` is direct (a single recipient identified by
1383    /// `Chat.contact_id`). The kit does not implement transport-layer
1384    /// fan-out (push events to subscribers) — that is the consumer's
1385    /// responsibility — so the consultation result does not change
1386    /// the handler's wire response. The call site is the documented
1387    /// integration point: production transport that fans typing
1388    /// events out to subscribers SHOULD consult this predicate
1389    /// before each per-recipient event.
1390    ///
1391    /// Group / channel chats are skipped on the kit side. The kit
1392    /// handler has no way to enumerate fan-out recipients; that work
1393    /// belongs to the consumer's transport layer, which must call
1394    /// this predicate per recipient with that recipient's
1395    /// `account_id`.
1396    ///
1397    /// # Default implementation
1398    ///
1399    /// Returns `Ok(false)` — no one is blocked. This is appropriate
1400    /// for backends that have not yet implemented contact lists, and
1401    /// it matches the workspace's "kit defines the hook; consumer
1402    /// enforces the policy" posture.
1403    fn is_contact_blocked(
1404        &self,
1405        _caller: &Self::CallerCtx,
1406        _account_id: &jmap_types::Id,
1407        _contact_id: &jmap_types::Id,
1408    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1409        async { Ok(false) }
1410    }
1411
1412    /// The owner's identity for `account_id`: the value of the
1413    /// `ownerUserId` Session field (draft-atwood-jmap-chat-00 §Session
1414    /// Object Extensions).
1415    ///
1416    /// [`crate::contact::handle_contact_set`] rejects a `ChatContact/set`
1417    /// create whose `identity` equals this value, octet for octet, with
1418    /// an `invalidProperties` SetError naming `identity`
1419    /// (draft-atwood-jmap-chat-00 §ChatContact/set: "the owner has no
1420    /// ChatContact").
1421    ///
1422    /// # Default implementation
1423    ///
1424    /// Returns `Ok(None)`: the owner's identity is unknown and the check
1425    /// is skipped. Backends that serve `ownerUserId` MUST override this
1426    /// to return the same value.
1427    fn owner_user_id(
1428        &self,
1429        _caller: &Self::CallerCtx,
1430        _account_id: &jmap_types::Id,
1431    ) -> impl std::future::Future<Output = Result<Option<String>, Self::Error>> + Send {
1432        async { Ok(None) }
1433    }
1434
1435    /// Authorization gate consulted by `handle_emoji_set` before every
1436    /// `CustomEmoji/set` create, update, or destroy.
1437    ///
1438    /// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11,
1439    /// "refactor: implementation-defined emoji authorization"):
1440    /// authorization for `CustomEmoji/set` is fully
1441    /// implementation-defined, for both server-global and Space-scoped
1442    /// emoji. When the caller is not authorized, the handler emits a
1443    /// `forbidden` SetError (RFC 8620 §5.3).
1444    ///
1445    /// # `target_space_id` semantics
1446    ///
1447    /// `target_space_id` is the **actual scope of the emoji this op
1448    /// targets**:
1449    ///
1450    /// - `None` — the emoji is server-global (its `spaceId` field is
1451    ///   absent / null).
1452    /// - `Some(id)` — the emoji is scoped to that Space (its `spaceId`
1453    ///   field equals `id`).
1454    ///
1455    /// For `Create`, the handler reads the scope from the create
1456    /// payload. For `Update` and `Destroy`, the handler pre-fetches
1457    /// the existing emoji via `get_objects` and passes its current
1458    /// `spaceId`. If the pre-fetch reports the id as not found, the
1459    /// handler skips this gate entirely and lets `update_object` /
1460    /// `destroy_object` surface a `notFound` SetError naturally — a
1461    /// non-existent target consumes no authorization decision.
1462    ///
1463    /// # When the handler calls this
1464    ///
1465    /// Exactly once per create/update/destroy entry in the request,
1466    /// AFTER wire-format validation has succeeded and BEFORE the
1467    /// corresponding `create_object` / `update_object` /
1468    /// `destroy_object` call. The handler skips the underlying mutation
1469    /// when the outer `Result` is `Ok(Err(_))` or when the outer is
1470    /// `Err(_)`. The wire mapping is:
1471    ///
1472    /// - `Ok(Ok(()))` — permit; the handler proceeds to the underlying
1473    ///   `create_object` / `update_object` / `destroy_object`.
1474    /// - `Ok(Err(set_err))` — deny with reason; the handler serialises
1475    ///   `set_err` into the appropriate `notCreated` / `notUpdated` /
1476    ///   `notDestroyed` map verbatim. Backends construct the SetError
1477    ///   with the type, description, and any `with_extra` fields the
1478    ///   deployment wants the client to see.
1479    /// - `Err(e)` — backend infrastructure failure; the handler maps
1480    ///   to a `serverFail` SetError.
1481    ///
1482    /// # Default implementation
1483    ///
1484    /// The default returns `Ok(Ok(()))` — every op is permitted. This
1485    /// matches the workspace's "kit defines the hook; consumer
1486    /// enforces the policy" posture (see the parallel design of
1487    /// [`Self::slow_mode_check`]). Production backends SHOULD override
1488    /// this method to apply the deployment's permission model — e.g.
1489    /// "only members of `target_space_id` may modify a Space-scoped
1490    /// emoji" or "only `manage_emoji` permission-holders may modify
1491    /// server-global emoji."
1492    ///
1493    /// # SetError shape recommendation
1494    ///
1495    /// Production backends SHOULD return
1496    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1497    ///     .with_description("…")))` for authorization denials, mirroring
1498    /// the workspace convention for /set responses. The description
1499    /// should explain the deployment's denial reason without leaking
1500    /// internal policy details — e.g. "Space-scoped emoji on this
1501    /// Space requires `manage_channels` permission" rather than
1502    /// "principal abc123 is not in role admin on Space xyz789".
1503    ///
1504    /// # Foundation seam
1505    ///
1506    /// Backends that wish to identify the caller call
1507    /// [`jmap_server::JmapBackend::principal_id`] on `caller` to learn
1508    /// whether identity is wired, and compare `account_id` (the owner's
1509    /// member entry, draft §Terminology) against the Space's `members`
1510    /// list, or consult ACLs or whatever permission model the
1511    /// deployment uses. Backends whose
1512    /// `principal_id` returns `None` (the workspace default, see the
1513    /// "Caller identity (foundation seam)" section of the workspace
1514    /// `AGENTS.md`) cannot meaningfully implement identity-scoped
1515    /// authorization — they should either override `principal_id`
1516    /// first or return `Ok(Ok(()))` to match the reference posture.
1517    fn may_set_custom_emoji(
1518        &self,
1519        _caller: &Self::CallerCtx,
1520        _account_id: &jmap_types::Id,
1521        _target_space_id: Option<&jmap_types::Id>,
1522        _op: EmojiSetOp,
1523    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1524        async { Ok(Ok(())) }
1525    }
1526
1527    /// Authorization gate consulted by `handle_message_set` before a
1528    /// create or update with a non-empty `broadcastMentions` array is
1529    /// applied.
1530    ///
1531    /// Per draft-atwood-jmap-chat-00 §4.4.1: sending a `Message` with
1532    /// a non-empty `broadcastMentions` array requires the
1533    /// `"mention_broadcast"` Space permission. The server MUST reject
1534    /// with `forbidden` when the caller lacks the permission.
1535    ///
1536    /// For group/direct chats NOT part of any Space (`spaceId` is
1537    /// `None`), broadcast mentions are unrestricted per spec; the
1538    /// handler skips calling this method entirely in that case.
1539    ///
1540    /// # `space_id` semantics
1541    ///
1542    /// `space_id` is the Space that contains the target Chat (channel).
1543    /// The handler resolves it by pre-fetching the Chat and reading
1544    /// its `space_id` field. This method is only called when
1545    /// `space_id` is `Some` — the handler skips the call for
1546    /// group/direct chats with no Space.
1547    ///
1548    /// # When the handler calls this
1549    ///
1550    /// `handle_message_set` invokes `may_broadcast_mention` once per
1551    /// create entry or edit whose post-patch `broadcastMentions` is
1552    /// non-empty AND whose target Chat has a `spaceId`; rich-body
1553    /// `"broadcast"` spans are display-only and never trigger it
1554    /// (draft-atwood-jmap-chat-00 §Rich Body Format). The call
1555    /// fires AFTER structural validation (`validate_broadcast_mentions`)
1556    /// has succeeded and BEFORE `create_object` / `update_object`, so
1557    /// malformed payloads do not consume an authorization decision and
1558    /// an unauthorized message never touches storage.
1559    ///
1560    /// # Default implementation
1561    ///
1562    /// Returns `Ok(Ok(()))` — every op is permitted. This matches the
1563    /// workspace's "kit defines the hook; consumer enforces the policy"
1564    /// posture (see the parallel design of [`Self::may_set_custom_emoji`]).
1565    /// Production backends SHOULD override this method to check the
1566    /// caller's `mention_broadcast` permission in the target Space's
1567    /// role hierarchy.
1568    ///
1569    /// # SetError shape recommendation
1570    ///
1571    /// Production backends SHOULD return
1572    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1573    ///     .with_description("sender lacks mention_broadcast permission in this Space")))`.
1574    fn may_broadcast_mention(
1575        &self,
1576        _caller: &Self::CallerCtx,
1577        _account_id: &jmap_types::Id,
1578        _space_id: &jmap_types::Id,
1579    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1580        async { Ok(Ok(())) }
1581    }
1582
1583    /// Authorization gate consulted by `handle_chat_set` before an update
1584    /// whose patch touches `pinnedMessageIds` is applied.
1585    ///
1586    /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "For group
1587    /// chats, only admins may modify this list. For direct chats, the
1588    /// owner may modify it freely. For channel chats, only members with
1589    /// the `"pin"` Space permission may modify this list."
1590    ///
1591    /// # When the handler calls this
1592    ///
1593    /// Once per update entry whose patch sets `pinnedMessageIds` (or a
1594    /// pointer path beneath it), AFTER wire-format validation and BEFORE
1595    /// `update_object`. A `chat_id` that does not resolve SHOULD yield
1596    /// `Ok(Ok(()))` so `update_object` surfaces `notFound`. The return
1597    /// mapping is the same as [`Self::may_set_custom_emoji`].
1598    ///
1599    /// # Default implementation
1600    ///
1601    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1602    /// parallel hooks above. Production backends SHOULD override this
1603    /// method and deny with
1604    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1605    fn may_set_pinned_messages(
1606        &self,
1607        _caller: &Self::CallerCtx,
1608        _account_id: &jmap_types::Id,
1609        _chat_id: &jmap_types::Id,
1610    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1611        async { Ok(Ok(())) }
1612    }
1613
1614    /// Authorization gate consulted by `handle_ban_set` before each
1615    /// SpaceBan create, update or destroy.
1616    ///
1617    /// Per draft-atwood-jmap-chat-00 §SpaceBan/set: create, update and
1618    /// destroy each "Requires `"ban"` permission in the Space."
1619    ///
1620    /// # When the handler calls this
1621    ///
1622    /// Once per entry, AFTER wire-format validation and BEFORE
1623    /// `create_object` / `update_object` / `destroy_object`. `space_id`
1624    /// is the create body's `spaceId`, or the stored ban's `spaceId` for
1625    /// update and destroy; an update or destroy whose ban does not
1626    /// resolve skips the gate so the backend surfaces `notFound`. The
1627    /// return mapping is the same as [`Self::may_set_custom_emoji`].
1628    ///
1629    /// # Default implementation
1630    ///
1631    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1632    /// parallel hooks above. Production backends SHOULD override this
1633    /// method and deny with
1634    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1635    fn may_set_space_ban(
1636        &self,
1637        _caller: &Self::CallerCtx,
1638        _account_id: &jmap_types::Id,
1639        _space_id: &jmap_types::Id,
1640    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1641        async { Ok(Ok(())) }
1642    }
1643
1644    /// Authorization gate consulted by `handle_invite_set` before each
1645    /// SpaceInvite create or destroy.
1646    ///
1647    /// Per draft-atwood-jmap-chat-00 §SpaceInvite/set: create "Requires
1648    /// `"manage_members"` permission"; destroy "Requires
1649    /// `"manage_members"` permission or ownership of the invite."
1650    ///
1651    /// # When the handler calls this
1652    ///
1653    /// Once per entry, AFTER wire-format validation and BEFORE
1654    /// `create_object` / `destroy_object`. `space_id` is the create body's
1655    /// `spaceId`, or the stored invite's `spaceId` for destroy.
1656    /// `created_by` is `None` on create and the stored invite's
1657    /// `createdBy` on destroy. A destroy whose invite does not resolve
1658    /// skips the gate so the backend surfaces `notFound`. The return
1659    /// mapping is the same as [`Self::may_set_custom_emoji`].
1660    ///
1661    /// # Default implementation
1662    ///
1663    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
1664    /// parallel hooks above. Production backends SHOULD override this
1665    /// method and deny with
1666    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
1667    fn may_set_space_invite(
1668        &self,
1669        _caller: &Self::CallerCtx,
1670        _account_id: &jmap_types::Id,
1671        _space_id: &jmap_types::Id,
1672        _created_by: Option<&jmap_types::Id>,
1673    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1674        async { Ok(Ok(())) }
1675    }
1676
1677    /// Visibility gate consulted by `handle_invite_get` and
1678    /// `handle_invite_changes` for each stored SpaceInvite.
1679    ///
1680    /// Per draft-atwood-jmap-chat-00 §SpaceInvite/get: "Only members of
1681    /// the Space may retrieve its invites. Members with
1682    /// `"manage_members"` permission see all invites; other members see
1683    /// only invites they created." §SpaceInvite/changes: "The same
1684    /// visibility rules as `SpaceInvite/get` apply".
1685    ///
1686    /// # When the handler calls this
1687    ///
1688    /// Once per invite returned by `get_objects`. `Ok(false)` hides the
1689    /// invite: `/get` reports a requested id as `notFound`, and
1690    /// `/changes` omits it from `created` and `updated`.
1691    ///
1692    /// # Default implementation
1693    ///
1694    /// Returns `Ok(true)`, so every invite is visible, matching the
1695    /// parallel hooks above. Production backends SHOULD override this
1696    /// method; invite codes are join credentials.
1697    fn may_get_space_invite(
1698        &self,
1699        _caller: &Self::CallerCtx,
1700        _account_id: &jmap_types::Id,
1701        _invite: &jmap_chat_types::SpaceInvite,
1702    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1703        async { Ok(true) }
1704    }
1705
1706    /// Visibility gate consulted by `handle_ban_get` for each stored
1707    /// SpaceBan.
1708    ///
1709    /// Per draft-atwood-jmap-chat-00 §SpaceBan/get: "Members with
1710    /// `"ban"` permission in the Space see all SpaceBan records for that
1711    /// Space. A banned user fetching their own account sees only SpaceBan
1712    /// records where `userId` is the accountId."
1713    ///
1714    /// # When the handler calls this
1715    ///
1716    /// Once per ban returned by `get_objects`. `Ok(false)` hides the ban,
1717    /// and a requested id is reported as `notFound`. `SpaceBan/changes`
1718    /// does not consult this hook, because the spec defines it as plain
1719    /// "Standard JMAP `/changes`".
1720    ///
1721    /// # Default implementation
1722    ///
1723    /// Returns `Ok(true)`, so every ban is visible, matching the parallel
1724    /// hooks above. Production backends SHOULD override this method.
1725    fn may_get_space_ban(
1726        &self,
1727        _caller: &Self::CallerCtx,
1728        _account_id: &jmap_types::Id,
1729        _ban: &jmap_chat_types::SpaceBan,
1730    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1731        async { Ok(true) }
1732    }
1733
1734    /// Referential check consulted by `handle_chat_set` before an update
1735    /// that adds ids to `pinnedMessageIds` is applied.
1736    ///
1737    /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "Each id
1738    /// MUST be the id of a Message in this Chat; the server MUST reject a
1739    /// `Chat/set` update that would add any other id with
1740    /// `invalidProperties`."
1741    ///
1742    /// # When the handler calls this
1743    ///
1744    /// After [`Self::may_set_pinned_messages`] permits the update and
1745    /// BEFORE `update_object`, with `added` holding only the ids in the
1746    /// new list that are not already in the stored list. Ids already
1747    /// pinned are not re-checked: the requirement covers adding, and a
1748    /// stale id left behind by a backend that missed a hard delete must
1749    /// not make the list impossible to edit. Not called when `added` is
1750    /// empty or `chat_id` does not resolve.
1751    ///
1752    /// Return `Ok(Err(SetError))` with type `invalidProperties` and
1753    /// properties `["pinnedMessageIds"]` when any id in `added` is not a
1754    /// Message whose `chatId` is `chat_id`.
1755    ///
1756    /// # Default implementation
1757    ///
1758    /// Returns `Ok(Ok(()))`, matching the parallel hooks above. Backends
1759    /// that store Messages SHOULD override it; the spec rule is a MUST.
1760    fn validate_pinned_message_ids(
1761        &self,
1762        _caller: &Self::CallerCtx,
1763        _account_id: &jmap_types::Id,
1764        _chat_id: &jmap_types::Id,
1765        _added: &[jmap_types::Id],
1766    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1767        async { Ok(Ok(())) }
1768    }
1769
1770    /// Throttle gate consulted before a `Message/set` create lands on
1771    /// the rate-limited path.
1772    ///
1773    /// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec
1774    /// commit `de60acb` (2026-05-11, "soften slow-mode exemption to
1775    /// SHOULD with rationale"): a `Chat` with `slowModeSeconds > 0`
1776    /// throttles the rate at which a member may post messages. The
1777    /// spec SHOULD-exempts members holding the `manage_channels`
1778    /// permission, and servers MAY define additional exempt
1779    /// principals. The kit does not opine on the exemption set — the
1780    /// backend implements the policy.
1781    ///
1782    /// When the caller is throttled, the backend returns
1783    /// `Err(`[`SlowModeError`]`)` with `retry_after` set to a UTCDate
1784    /// the rate-limited sender may use to schedule a retry. The
1785    /// `Message/set` create handler maps the error onto a
1786    /// `rateLimited` SetError (RFC 8620 §5.3 `SetError.type`) whose
1787    /// `serverRetryAfter` extra field carries the UTCDate verbatim.
1788    ///
1789    /// # When the handler calls this
1790    ///
1791    /// `handle_message_set` invokes `slow_mode_check` once per create
1792    /// entry, after wire-format validation has succeeded and before
1793    /// `create_object`. A throttle rejection short-circuits to
1794    /// `notCreated[create_id] = { type: "rateLimited",
1795    /// serverRetryAfter: <UTCDate> }` and the create_object call is
1796    /// never made.
1797    ///
1798    /// # Default implementation
1799    ///
1800    /// The default returns `Ok(())` — no throttle. This is appropriate
1801    /// for backends that have not yet implemented rate-tracking and
1802    /// for single-tenant dev servers where no abuse path exists.
1803    /// Production backends SHOULD override this method with their own
1804    /// per-(account, chat, caller) rate tracker.
1805    ///
1806    /// # No state on the kit
1807    ///
1808    /// The kit deliberately does not provide a reference rate-tracker
1809    /// — that is deployment territory. The reference `MemoryBackend`
1810    /// keeps the default no-op behaviour for the same reason.
1811    fn slow_mode_check(
1812        &self,
1813        _caller: &Self::CallerCtx,
1814        _account_id: &jmap_types::Id,
1815        _chat_id: &jmap_types::Id,
1816    ) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
1817        async { Ok(()) }
1818    }
1819
1820    /// Hard-delete a message ("expire" it) due to a per-message expiry
1821    /// event.
1822    ///
1823    /// Called by the kit from two places:
1824    ///
1825    /// 1. The `Message/set` update handler when a patch sets `readAt` on
1826    ///    a message whose pre-patch `burnOnRead` is `true`
1827    ///    (draft-atwood-jmap-chat-00 §Message `burnOnRead`).
1828    /// 2. A deployment-provided scheduler when a message's
1829    ///    `senderExpiresAt` fires (draft-atwood-jmap-chat-00 §Message
1830    ///    `senderExpiresAt`). The kit does NOT run a scheduler;
1831    ///    consumers wire one in and call this method directly when a
1832    ///    timer fires.
1833    ///
1834    /// # Contract
1835    ///
1836    /// Per draft-atwood-jmap-chat-00, an expiry MUST hard-delete the
1837    /// row (not tombstone) and the message MUST appear in the
1838    /// `destroyed` set of subsequent `Message/changes` results.
1839    /// Implementations therefore SHOULD:
1840    ///
1841    /// - Remove the underlying record so a subsequent `Message/get`
1842    ///   does not find it.
1843    /// - Bump the per-account `Message` state token and record the id
1844    ///   in the change log so `Message/changes` sees it as destroyed.
1845    /// - Remove the id from its Chat's `pinnedMessageIds` (§Chat
1846    ///   `pinnedMessageIds`: "When a pinned Message is hard-deleted, the
1847    ///   server MUST remove its id from this list."). The same applies to
1848    ///   `destroy_object::<Message>`.
1849    ///
1850    /// # Idempotency
1851    ///
1852    /// If the message no longer exists — because a previous
1853    /// `expire_message` call or [`Self::read_and_burn_message`] has
1854    /// already deleted it — this method MUST
1855    /// return `Ok(())`, AND MUST NOT bump the per-account `Message`
1856    /// state token in that case. The no-op case must be
1857    /// observationally indistinguishable from "the scheduler never
1858    /// fired" for `Message/changes` subscribers; a state bump on the
1859    /// retry path would surface a spurious empty change set on every
1860    /// re-fire and induce a poll storm. Expiry events are
1861    /// inherently retry-friendly (a scheduler may re-fire if it
1862    /// crashed mid-batch). The
1863    /// return type is `Result<(), Self::Error>` (not
1864    /// `BackendSetError`) precisely to prevent a `NotFound`
1865    /// SetError construction on this path: expiry is an internal
1866    /// scheduler hook, not a `/set`-shaped call, and there is no
1867    /// JMAP wire surface for per-message expiry rejection.
1868    ///
1869    /// Burn-on-read does not use this hook; `Message/set` calls
1870    /// [`Self::read_and_burn_message`] so the `readAt` write and the
1871    /// hard-delete are atomic.
1872    ///
1873    /// # Default implementation
1874    ///
1875    /// The default returns `Ok(())` without doing anything. This is
1876    /// appropriate for backends that have not yet implemented expiry.
1877    /// Production backends that need expiry SHOULD override this method.
1878    fn expire_message(
1879        &self,
1880        _caller: &Self::CallerCtx,
1881        _account_id: &jmap_types::Id,
1882        _message_id: &jmap_types::Id,
1883    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
1884        async { Ok(()) }
1885    }
1886}
1887
1888#[cfg(test)]
1889mod tests {
1890    use super::SlowModeError;
1891    use jmap_types::UTCDate;
1892
1893    #[test]
1894    fn slow_mode_error_display_contains_retry_after() {
1895        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1896        let rendered = format!("{err}");
1897        assert!(
1898            rendered.contains("slow-mode rate limit"),
1899            "Display missing prefix: {rendered}"
1900        );
1901        assert!(
1902            rendered.contains("2026-05-16T12:34:56Z"),
1903            "Display missing retry_after timestamp: {rendered}"
1904        );
1905    }
1906
1907    #[test]
1908    fn slow_mode_error_is_std_error() {
1909        // Compile-time check that SlowModeError implements std::error::Error.
1910        // If this fails to compile, the trait impl regressed.
1911        fn assert_is_error<E: std::error::Error>(_: &E) {}
1912        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1913        assert_is_error(&err);
1914    }
1915
1916    #[test]
1917    fn slow_mode_error_boxes_as_dyn_error() {
1918        // Independent oracle: the std error machinery itself. If
1919        // SlowModeError does not implement std::error::Error this
1920        // conversion does not compile.
1921        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
1922        let boxed: Box<dyn std::error::Error> = Box::new(err);
1923        assert!(boxed.to_string().contains("slow-mode rate limit"));
1924    }
1925
1926    use super::OpResult;
1927    use jmap_server::backend::{SetError, SetErrorType};
1928
1929    #[test]
1930    fn op_result_ok_carries_op_index_and_optional_id() {
1931        let r = OpResult::ok(3, Some(jmap_types::Id::from("space-1")));
1932        assert_eq!(r.op_index, 3);
1933        assert_eq!(r.outcome, Ok(Some(jmap_types::Id::from("space-1"))));
1934    }
1935
1936    #[test]
1937    fn op_result_ok_with_none_id_for_update_or_destroy() {
1938        let r = OpResult::ok(0, None);
1939        assert_eq!(r.op_index, 0);
1940        assert_eq!(r.outcome, Ok(None));
1941    }
1942
1943    #[test]
1944    fn op_result_err_carries_op_index_and_set_error() {
1945        let r = OpResult::err(7, SetError::new(SetErrorType::Forbidden));
1946        assert_eq!(r.op_index, 7);
1947        match r.outcome {
1948            Err(e) => assert_eq!(e.error_type, SetErrorType::Forbidden),
1949            Ok(_) => panic!("expected Err outcome"),
1950        }
1951    }
1952
1953    #[test]
1954    fn op_result_with_op_index_replaces_field() {
1955        let r = OpResult::ok(0, None).with_op_index(42);
1956        assert_eq!(r.op_index, 42);
1957        assert_eq!(r.outcome, Ok(None));
1958    }
1959
1960    #[test]
1961    fn op_result_with_outcome_replaces_field() {
1962        let r =
1963            OpResult::ok(0, None).with_outcome(Err(SetError::new(SetErrorType::InvalidProperties)));
1964        assert_eq!(r.op_index, 0);
1965        match r.outcome {
1966            Err(e) => assert_eq!(e.error_type, SetErrorType::InvalidProperties),
1967            Ok(_) => panic!("expected Err outcome after with_outcome"),
1968        }
1969    }
1970
1971    // Const-context smoke tests — lock in the const fn markers so a
1972    // future refactor that accidentally drops `const` from any of
1973    // these constructors / builders is caught at compile time
1974    // (bd:JMAP-x2gd.79).
1975
1976    use super::ChatLimits;
1977
1978    /// `OpResult::ok` is callable in const context.
1979    #[test]
1980    fn op_result_ok_is_const_fn() {
1981        const _R: OpResult = OpResult::ok(0, None);
1982    }
1983
1984    /// `ChatLimits::new` plus all four `with_*` setters chain in const
1985    /// context — proves the entire builder pipeline stays const.
1986    #[test]
1987    fn chat_limits_builder_is_const_fn() {
1988        const _LIMITS: ChatLimits = ChatLimits::new(1, 2, 3, 4)
1989            .with_max_roles_per_space(10)
1990            .with_max_space_members(20)
1991            .with_max_channels_per_space(30)
1992            .with_max_categories_per_space(40);
1993    }
1994
1995    // Note: `SlowModeError::new` is `const fn` (clippy::nursery
1996    // `missing_const_for_fn` would re-fire if the marker were dropped),
1997    // but a const-context smoke test cannot be authored without a
1998    // const-constructible `UTCDate`. `UTCDate` wraps a `String`, and
1999    // `String` is not const-constructible from a non-empty literal in
2000    // stable Rust today. The clippy lint covers the regression case.
2001}