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; the crate root re-exports the ones an
12//! impl needs.
13
14use jmap_chat_types::SpacePatchOp;
15use jmap_server::{BackendSetError, JmapBackend, JmapObject, SetError, SetErrorType, SetObject};
16
17// ---------------------------------------------------------------------------
18// Space/set structural-mutation result
19// ---------------------------------------------------------------------------
20
21/// The outcome of a single [`SpacePatchOp`](crate::SpacePatchOp) applied by
22/// [`ChatBackend::apply_space_patch`].
23///
24/// `op_index` is the zero-based index of the op within the input `Vec`, used
25/// by handlers to construct a descriptive error message identifying which
26/// per-key entry failed (e.g. `addRoles[2] failed: ...`).
27///
28/// `outcome` is:
29/// - `Ok(Some(id))` — the op produced a new server-assigned id (e.g.
30///   [`SpacePatchOp::AddRole`], [`SpacePatchOp::AddChannel`],
31///   [`SpacePatchOp::AddCategory`]). The handler reports this id back to
32///   the client via the `/set` response.
33/// - `Ok(None)` — the op completed but produced no id (every `Remove*` and
34///   `Update*` variant).
35/// - `Err(SetError)` — the op was rejected (e.g. permission denied, target
36///   id not found, role hierarchy violation, count limit exceeded).
37///
38/// Per RFC 8620 §5.3 `/set`, an update target is per-target atomic on the
39/// wire: it appears in exactly one of `updated` or `notUpdated`. If **any**
40/// `OpResult` in the returned `Vec` has an `Err`, the handler reports the
41/// containing update target in `notUpdated`. The handler is free to choose
42/// which `Err` to surface; the reference handler surfaces the first.
43///
44/// This type lives in `jmap-chat-server` (not `jmap-chat-types`) because
45/// [`SetError`] is defined in `jmap-server` and `jmap-chat-types` cannot
46/// depend on it (per the workspace dependency rule: types crates depend
47/// only on `jmap-types`, `serde`, `serde_json`).
48///
49/// `#[non_exhaustive]` preserves the ability to add fields without a
50/// SemVer break (e.g. an audit-log handle, commit ordering hint,
51/// permission-diagnostic annotation). External consumers MUST construct
52/// instances via [`OpResult::ok`] or [`OpResult::err`] rather than
53/// field-init syntax.
54///
55/// # Field-addition policy
56///
57/// Future fields added to `OpResult` are an **additive non-breaking
58/// change**: the new field MUST have a `Default` value (typical for
59/// `Option` / `Vec` / `HashMap`) and the new field is exposed via a
60/// `with_*`-style builder setter rather than being appended as a third
61/// positional argument to [`OpResult::ok`] or [`OpResult::err`]. The
62/// `ok(op_index, id)` and `err(op_index, error)` constructors therefore
63/// stay stable across the crate's pre-1.0 lifetime, matching the
64/// [`ChatLimits`]-style canonical workspace pattern for
65/// `#[non_exhaustive]` types with builder setters.
66#[non_exhaustive]
67#[derive(Debug)]
68pub struct OpResult {
69    /// Zero-based index of the originating op in the input `Vec<SpacePatchOp>`.
70    pub op_index: usize,
71    /// The outcome of applying that op.
72    pub outcome: Result<Option<jmap_types::Id>, SetError>,
73}
74
75impl OpResult {
76    /// Construct an `Ok` result for a successfully applied op.
77    ///
78    /// The contained `Id` is the server-assigned id when the op was a
79    /// create (the kit's response includes it under `created[create_id].id`);
80    /// pass `None` for updates and destroys, which have no id to surface.
81    #[must_use]
82    pub const fn ok(op_index: usize, id: Option<jmap_types::Id>) -> Self {
83        Self {
84            op_index,
85            outcome: Ok(id),
86        }
87    }
88
89    /// Construct an `Err` result for a rejected op.
90    ///
91    /// The kit's `handle_space_set` surfaces this error to the JMAP
92    /// `notUpdated` map for the containing update target.
93    #[must_use]
94    pub const fn err(op_index: usize, error: SetError) -> Self {
95        Self {
96            op_index,
97            outcome: Err(error),
98        }
99    }
100
101    /// Builder-style setter for [`Self::op_index`].
102    ///
103    /// Lets callers update the originating op index after construction.
104    /// Useful when re-indexing a result produced for one op into the
105    /// position of another (e.g. when filtering a batch).
106    #[must_use]
107    pub const fn with_op_index(mut self, op_index: usize) -> Self {
108        self.op_index = op_index;
109        self
110    }
111
112    /// Builder-style setter for [`Self::outcome`].
113    ///
114    /// Lets callers replace the outcome after construction. Useful for
115    /// retry / fallback flows that re-classify a transient error into a
116    /// success or vice versa before surfacing the result to the
117    /// handler.
118    #[must_use]
119    pub fn with_outcome(mut self, outcome: Result<Option<jmap_types::Id>, SetError>) -> Self {
120        self.outcome = outcome;
121        self
122    }
123}
124
125// ---------------------------------------------------------------------------
126// Per-Space content limits
127// ---------------------------------------------------------------------------
128
129/// Implementation-defined per-Space content limits enforced by
130/// `Space/set` handlers.
131///
132/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
133/// 2026-05-11), each `add*` op on a Space MUST return an `overQuota`
134/// SetError (RFC 8620 §5.3) when the resulting count would exceed a
135/// server-defined limit. The spec does not name or normatively define
136/// the cap values; they are implementation-defined and may vary per
137/// account or per tenant.
138///
139/// Backends override [`ChatBackend::limits`] to supply their own values.
140/// The default impl returns conservative reference-impl-grade values
141/// suitable for tests and single-tenant dev servers; production
142/// deployments are expected to override.
143///
144/// Client visibility of these caps (when desired) is via JMAP Quotas
145/// (`urn:ietf:params:jmap:quotas`, RFC 9425), not via this struct.
146/// The `urn:ietf:params:jmap:chat` session capability does NOT advertise
147/// the count caps (the previous cap-advertising fields `maxRolesPerSpace`,
148/// `maxSpaceMembers`, `maxChannelsPerSpace`, `maxCategoriesPerSpace`
149/// were removed from the draft in spec commit `80d5e11`).
150///
151/// See the workspace `AGENTS.md` "Backend caps and limits" section for
152/// the cross-extension pattern this struct establishes for JMAP Chat.
153#[non_exhaustive]
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct ChatLimits {
156    /// Maximum number of roles per Space. Enforced against the
157    /// resulting count after applying every `addRoles` entry in a
158    /// `Space/set` update patch.
159    pub max_roles_per_space: u32,
160    /// Maximum number of members per Space. Enforced against the
161    /// resulting count after applying every `addMembers` entry in a
162    /// `Space/set` update patch.
163    pub max_space_members: u32,
164    /// Maximum number of channels per Space. Enforced against the
165    /// resulting count after applying every `addChannels` entry in a
166    /// `Space/set` update patch. The current channel count is the sum
167    /// of `space.uncategorizedChannelIds.len()` and every
168    /// `space.categories[].channelIds.len()`.
169    pub max_channels_per_space: u32,
170    /// Maximum number of categories per Space. Enforced against the
171    /// resulting count after applying every `addCategories` entry in
172    /// a `Space/set` update patch.
173    pub max_categories_per_space: u32,
174    /// Maximum number of members per group Chat. Enforced against the
175    /// resulting count after applying every `addMembers` entry in a
176    /// `Chat/set` update patch.
177    pub max_group_chat_members: u32,
178    /// `bodyType` values the account advertises as `supportedBodyTypes`
179    /// and `Message/set` accepts (draft-atwood-jmap-chat-00
180    /// §Account-Level Capability Object). Defaults to
181    /// [`crate::message::SUPPORTED_BODY_TYPES`]. The list "MUST include
182    /// `"text/plain"` unless the server accepts only end-to-end encrypted
183    /// body types"; `Message/set` rejects a `bodyType` not listed here,
184    /// including the implied `"text/plain"` of an omitted `bodyType`.
185    pub supported_body_types: &'static [&'static str],
186    /// Listed types that a companion specification reserves for
187    /// server-created Messages (e.g. `"application/mimi-fanout"`,
188    /// draft-atwood-jmap-chat-mimi-00). `Message/set` create rejects
189    /// them with an `invalidProperties` SetError naming `bodyType`;
190    /// update does not. Defaults to empty.
191    pub server_reserved_body_types: &'static [&'static str],
192    /// `bodyType` values that indicate an end-to-end encrypted body.
193    /// Defaults to [`crate::message::ENCRYPTED_BODY_TYPES`]. For these
194    /// types `Message/set` create and update reject a non-empty
195    /// `mentions`, `broadcastMentions`, `attachments`, `actions`,
196    /// `replyTo`, `threadRootId`, `topicId` or `subject`
197    /// (draft-atwood-jmap-chat-00 §Fields Inside the Ciphertext). A MIMI
198    /// deployment adds `"application/mimi-fanout"`, which "is an
199    /// encrypted body type for the purposes of" that draft
200    /// (draft-atwood-jmap-chat-mimi-00 §MLS Messages).
201    pub encrypted_body_types: &'static [&'static str],
202    /// The account's `supportsThreads` capability value
203    /// (draft-atwood-jmap-chat-00 §Thread Model). When `true`,
204    /// `Message/get` computes `replyCount` and `unreadReplyCount`, and
205    /// `Message/query` accepts the `threadRootId` filter, which the
206    /// backend's `query_objects` must then implement. Defaults to `false`.
207    pub supports_threads: bool,
208    /// The account's `maxBodyBytes` capability value
209    /// (draft-atwood-jmap-chat-00 §Account-Level Capability Object):
210    /// "Maximum UTF-8 byte length of a Message `body`." `Message/set`
211    /// create rejects a longer `body` with a `tooLarge` SetError.
212    /// Defaults to 100,000.
213    pub max_body_bytes: u64,
214    /// The account's `maxAttachmentBytes` capability value: "Maximum size
215    /// in bytes of a single attachment blob." `Message/set` create
216    /// rejects an Attachment whose `size` exceeds it with a `tooLarge`
217    /// SetError, before consulting [`ChatBackend::attachment_blob`].
218    /// Defaults to 50,000,000.
219    pub max_attachment_bytes: u64,
220    /// The account's `maxAttachmentsPerMessage` capability value:
221    /// "Maximum number of attachments per message." `Message/set` create
222    /// rejects more with a `tooLarge` SetError. Defaults to 16.
223    pub max_attachments_per_message: u64,
224}
225
226impl Default for ChatLimits {
227    fn default() -> Self {
228        Self::new(50, 10_000, 500, 100)
229    }
230}
231
232impl ChatLimits {
233    /// Construct a [`ChatLimits`] with the four Space cap fields
234    /// specified in declaration order: roles, members, channels,
235    /// categories. [`Self::max_group_chat_members`] defaults to 1000;
236    /// override it with [`Self::with_max_group_chat_members`].
237    ///
238    /// The struct is `#[non_exhaustive]` so external callers (tests
239    /// using `MemoryBackend::set_limits_for_test`, production backends
240    /// overriding [`ChatBackend::limits`]) need a constructor to build
241    /// one. Future cap-field additions to [`ChatLimits`] are an
242    /// additive non-breaking change because the constructor stays
243    /// stable; callers wanting to override the new field combine
244    /// `ChatLimits::new(..)` with [`Self::with_max_roles_per_space`]
245    /// / [`Self::with_max_space_members`] /
246    /// [`Self::with_max_channels_per_space`] /
247    /// [`Self::with_max_categories_per_space`] and a future analogous
248    /// setter.
249    pub const fn new(
250        max_roles_per_space: u32,
251        max_space_members: u32,
252        max_channels_per_space: u32,
253        max_categories_per_space: u32,
254    ) -> Self {
255        Self {
256            max_roles_per_space,
257            max_space_members,
258            max_channels_per_space,
259            max_categories_per_space,
260            max_group_chat_members: 1_000,
261            supported_body_types: crate::message::SUPPORTED_BODY_TYPES,
262            server_reserved_body_types: &[],
263            encrypted_body_types: crate::message::ENCRYPTED_BODY_TYPES,
264            supports_threads: false,
265            max_body_bytes: 100_000,
266            max_attachment_bytes: 50_000_000,
267            max_attachments_per_message: 16,
268        }
269    }
270
271    /// Builder-style setter for [`Self::max_roles_per_space`].
272    #[must_use]
273    pub const fn with_max_roles_per_space(mut self, max: u32) -> Self {
274        self.max_roles_per_space = max;
275        self
276    }
277
278    /// Builder-style setter for [`Self::max_space_members`].
279    #[must_use]
280    pub const fn with_max_space_members(mut self, max: u32) -> Self {
281        self.max_space_members = max;
282        self
283    }
284
285    /// Builder-style setter for [`Self::max_channels_per_space`].
286    #[must_use]
287    pub const fn with_max_channels_per_space(mut self, max: u32) -> Self {
288        self.max_channels_per_space = max;
289        self
290    }
291
292    /// Builder-style setter for [`Self::max_categories_per_space`].
293    #[must_use]
294    pub const fn with_max_categories_per_space(mut self, max: u32) -> Self {
295        self.max_categories_per_space = max;
296        self
297    }
298
299    /// Builder-style setter for [`Self::max_group_chat_members`].
300    #[must_use]
301    pub const fn with_max_group_chat_members(mut self, max: u32) -> Self {
302        self.max_group_chat_members = max;
303        self
304    }
305
306    /// Builder-style setter for [`Self::supported_body_types`].
307    #[must_use]
308    pub const fn with_supported_body_types(mut self, types: &'static [&'static str]) -> Self {
309        self.supported_body_types = types;
310        self
311    }
312
313    /// Builder-style setter for [`Self::server_reserved_body_types`].
314    #[must_use]
315    pub const fn with_server_reserved_body_types(mut self, types: &'static [&'static str]) -> Self {
316        self.server_reserved_body_types = types;
317        self
318    }
319
320    /// Builder-style setter for [`Self::encrypted_body_types`].
321    #[must_use]
322    pub const fn with_encrypted_body_types(mut self, types: &'static [&'static str]) -> Self {
323        self.encrypted_body_types = types;
324        self
325    }
326
327    /// Builder-style setter for [`Self::supports_threads`].
328    #[must_use]
329    pub const fn with_supports_threads(mut self, supports: bool) -> Self {
330        self.supports_threads = supports;
331        self
332    }
333
334    /// Builder-style setter for [`Self::max_body_bytes`].
335    #[must_use]
336    pub const fn with_max_body_bytes(mut self, max: u64) -> Self {
337        self.max_body_bytes = max;
338        self
339    }
340
341    /// Builder-style setter for [`Self::max_attachment_bytes`].
342    #[must_use]
343    pub const fn with_max_attachment_bytes(mut self, max: u64) -> Self {
344        self.max_attachment_bytes = max;
345        self
346    }
347
348    /// Builder-style setter for [`Self::max_attachments_per_message`].
349    #[must_use]
350    pub const fn with_max_attachments_per_message(mut self, max: u64) -> Self {
351        self.max_attachments_per_message = max;
352        self
353    }
354}
355
356// ---------------------------------------------------------------------------
357// Attachment blob verification
358// ---------------------------------------------------------------------------
359
360/// The stored blob behind an Attachment `blobId`, as reported by
361/// [`ChatBackend::attachment_blob`].
362///
363/// `handle_message_set` compares these against the Attachment's `size`
364/// and `sha256` (draft-atwood-jmap-chat-00 §Attachment, `size`: "Servers
365/// MUST verify against actual content"; `sha256`: "Servers SHOULD
366/// verify").
367#[non_exhaustive]
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369pub struct AttachmentBlob {
370    /// Byte count of the stored blob.
371    pub size: u64,
372    /// SHA-256 digest of the stored blob's bytes.
373    pub sha256: [u8; 32],
374}
375
376impl AttachmentBlob {
377    /// Construct an [`AttachmentBlob`] from the stored blob's byte count
378    /// and SHA-256 digest.
379    #[must_use]
380    pub const fn new(size: u64, sha256: [u8; 32]) -> Self {
381        Self { size, sha256 }
382    }
383}
384
385// ---------------------------------------------------------------------------
386// Custom emoji authorization gate
387// ---------------------------------------------------------------------------
388
389/// Identifies the kind of `CustomEmoji/set` operation being authorized by
390/// [`ChatBackend::may_set_custom_emoji`].
391///
392/// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11, "refactor:
393/// implementation-defined emoji authorization"), authorization for
394/// `CustomEmoji/set` is fully implementation-defined for both server-global
395/// and Space-scoped emoji. The kit forwards the op kind so the backend can
396/// apply different policies per op (e.g. allow create+update but require
397/// elevated rights for destroy).
398#[non_exhaustive]
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub enum EmojiSetOp {
401    /// `CustomEmoji/set` `create` — a new emoji is being added.
402    Create,
403    /// `CustomEmoji/set` `update` — an existing emoji's mutable fields
404    /// (currently `name` and `blobId`) are being patched.
405    Update,
406    /// `CustomEmoji/set` `destroy` — an existing emoji is being removed.
407    Destroy,
408}
409
410/// Why [`ChatBackend::join_space_with_invite`] refused a redemption.
411#[non_exhaustive]
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
413pub enum InviteJoinRefusal {
414    /// The invite, or the Space it names, no longer exists.
415    NotFound,
416    /// The invite's `uses` has reached `maxUses`.
417    Exhausted,
418    /// The owner is already a member of the Space.
419    AlreadyMember,
420}
421
422// ---------------------------------------------------------------------------
423// Slow-mode rate-limit gate
424// ---------------------------------------------------------------------------
425
426/// Outcome of a [`ChatBackend::slow_mode_check`] rejection.
427///
428/// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec commit
429/// `de60acb` (2026-05-11) which softened the manage-channels exemption to
430/// SHOULD: a non-exempt member who sends faster than the configured rate
431/// MUST be rejected with a `rateLimit` SetError (RFC 8620 §5.3) carrying a
432/// `serverRetryAfter` UTCDate that tells the client when it may retry.
433///
434/// `retry_after` is a fully-formed [`jmap_types::UTCDate`] — the backend
435/// has already done the arithmetic (typically "now + remaining slow-mode
436/// window"). The handler serialises it verbatim onto the wire as the
437/// `serverRetryAfter` SetError extra field.
438///
439/// `#[non_exhaustive]` preserves the ability to add fields without a
440/// SemVer break (e.g. an error code, sender-facing retry hint string,
441/// "this is your N-th throttle in M minutes" diagnostic counter).
442/// External consumers MUST construct instances via [`SlowModeError::new`]
443/// rather than field-init syntax.
444#[non_exhaustive]
445#[derive(Debug, Clone)]
446pub struct SlowModeError {
447    /// When the rate-limited sender may retry.
448    pub retry_after: jmap_types::UTCDate,
449}
450
451impl SlowModeError {
452    /// Construct a [`SlowModeError`] from a precomputed retry-after
453    /// [`UTCDate`].
454    ///
455    /// [`UTCDate`]: jmap_types::UTCDate
456    #[must_use]
457    pub const fn new(retry_after: jmap_types::UTCDate) -> Self {
458        Self { retry_after }
459    }
460}
461
462impl std::fmt::Display for SlowModeError {
463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        write!(
465            f,
466            "slow-mode rate limit; retry after {}",
467            self.retry_after.as_ref()
468        )
469    }
470}
471
472impl std::error::Error for SlowModeError {}
473
474// ---------------------------------------------------------------------------
475// ChatBackend trait
476// ---------------------------------------------------------------------------
477
478/// Storage backend for JMAP Chat method handlers.
479///
480/// Implementors provide the actual data access; the method handler modules
481/// in this crate translate between JMAP wire protocol and backend calls.
482///
483/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
484/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
485/// supertrait. Only write operations and type introspection are here.
486///
487/// This trait is not object-safe by design (generic methods). Use
488/// `Arc<impl ChatBackend>` when sharing across tasks.
489///
490/// # Async vs sync method convention
491///
492/// `ChatBackend` carves its methods into two groups:
493///
494/// 1. **Mutation / hot-path hooks are async.** [`ChatBackend::create_object`],
495///    [`ChatBackend::update_object`], [`ChatBackend::destroy_object`],
496///    [`ChatBackend::apply_space_patch`],
497///    [`ChatBackend::apply_space_metadata_patch`],
498///    [`ChatBackend::expire_message`],
499///    [`ChatBackend::read_and_burn_message`],
500///    [`ChatBackend::slow_mode_check`],
501///    [`ChatBackend::generate_invite_code`],
502///    [`ChatBackend::is_contact_blocked`], and
503///    [`ChatBackend::may_set_custom_emoji`] all return
504///    `impl Future + Send`. These methods consult per-account state,
505///    may issue I/O, and run on the JMAP request hot path; the async
506///    signature lets production backends `.await` storage / cache /
507///    policy lookups without runtime-pinning hazards.
508///
509/// 2. **Policy / capability hooks are sync.** [`ChatBackend::supports_type`],
510///    [`ChatBackend::limits`], [`ChatBackend::protect_last_admin`], and
511///    [`ChatBackend::retains_edit_history`] are synchronous methods.
512///    These hooks answer deployment-policy or capability questions
513///    whose answer SHOULD be derivable from in-process state (a
514///    startup-loaded config snapshot, a cached per-account record).
515///    The sync shape keeps the trait surface easy to implement for
516///    single-process and reference backends, which are the dominant
517///    use case for a kit crate. `generate_invite_code` is async and
518///    fallible instead, because an HSM or KMS entropy source needs I/O
519///    and can fail.
520///
521/// The carve-up is intentional and is NOT a "we forgot to async these"
522/// regression. Production backends that need to consult an async
523/// source for any of the four sync hooks have two options: (a)
524/// pre-cache the answer at startup or on a background refresh; or (b)
525/// file a follow-up bead proposing the conversion for that specific
526/// method, with the production constraint documented. Per-method
527/// rustdoc notes ("`# Why sync, not async`" / "`# Fallibility and
528/// async — known limitations`") spell out the workaround on each
529/// affected method. Flipping any of the sync hooks to async is a
530/// major-version breaking change for downstream implementors;
531/// converting them all preemptively for hypothetical multi-tenant
532/// SaaS deployments would over-engineer the kit-vs-product posture
533/// described in workspace `AGENTS.md`.
534pub trait ChatBackend: JmapBackend {
535    /// Create a new object.
536    ///
537    /// Returns `(assigned_id, created_object)` on success. `create_id` is the
538    /// client-side creation id used in the `/set` request.
539    ///
540    /// # Authorisation contract
541    ///
542    /// This method is the canonical enforcement point for caller authorisation
543    /// per workspace AGENTS.md "Caller identity (foundation seam)" and per-crate
544    /// AGENTS.md "Permission enforcement: backend canonical". The caller of a
545    /// chat account is its owner, whose Space member entry is the accountId
546    /// (draft-atwood-jmap-chat §Terminology). Implementors MUST verify that
547    /// `caller` may act as the owner of `account_id` before performing the
548    /// mutation, and MUST return [`BackendSetError::SetError`] carrying
549    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. Handlers in this crate do no
550    /// account-access checking, so a backend that trusts the handler lets any
551    /// caller write any account. Space permission and role-hierarchy gates
552    /// resolve against the owner's member entry through the `may_*` hooks (for
553    /// example [`Self::may_send_message`]), [`Self::apply_space_patch`] and
554    /// [`Self::apply_space_metadata_patch`].
555    ///
556    /// # Id assignment
557    ///
558    /// The backend mints the new object's id, calls `build(&id)` exactly
559    /// once to obtain the complete object, and stores that object under
560    /// `id` in the same atomic write. `build` sets the object's `id` field
561    /// to the id it is given; the backend stores the built object as is.
562    /// RFC 8620 §5.3 lists `id` among the "server-set properties".
563    ///
564    /// `Message/set` builds an owner-composed Message with `senderMsgId`
565    /// equal to that id (draft-atwood-jmap-chat-00 §Message `senderMsgId`:
566    /// "Equals `id` for messages composed by the owner."). A
567    /// server-originated Message ([`crate::message::store_server_message`]) carries
568    /// the `senderMsgId` its originator chose. In both cases the backend
569    /// stores `senderMsgId` unchanged.
570    ///
571    /// # Per-type uniqueness contracts
572    ///
573    /// For most types the (id) primary key is the only uniqueness
574    /// invariant the backend must enforce, and the backend's normal
575    /// server-assigned-id discipline closes that. A few types carry
576    /// additional uniqueness invariants on non-id fields that the
577    /// backend MUST enforce atomically with the create — the handler
578    /// pre-checks defensively but cannot close the
579    /// two-concurrent-requests race window.
580    ///
581    /// - **`ReadPosition`** — at most one record per
582    ///   `(account_id, chat_id)`. Clients cannot create one
583    ///   (`ReadPosition/set` create is `forbidden`); the server creates
584    ///   it on first message delivery in
585    ///   [`crate::message::handle_message_set`] and on
586    ///   [`crate::space::handle_space_join`], which pre-check via a
587    ///   sequential scan, but two concurrent requests for
588    ///   the same `chatId` can both pass the pre-check and then both
589    ///   reach `create_object`. The
590    ///   backend MUST enforce a unique constraint on
591    ///   `(account_id, chat_id)` at the storage layer (typically a
592    ///   composite unique index in a database backend) and surface a
593    ///   duplicate as `BackendSetError::SetError(SetError::new(
594    ///   SetErrorType::AlreadyExists).with_existing_id(canonical))`.
595    ///   See draft-atwood-jmap-chat-00 §ReadPosition.
596    /// - **`ChatContact`** — at most one record per
597    ///   `(account_id, identity)`, compared octet for octet.
598    ///   [`crate::contact::handle_contact_set`] does not pre-check: the
599    ///   backend MUST reject a duplicate atomically with the create as
600    ///   `BackendSetError::SetError(SetError::new(
601    ///   SetErrorType::AlreadyExists).with_existing_id(existing))`, where
602    ///   `existing` is the id of the ChatContact that holds the
603    ///   `identity`. See draft-atwood-jmap-chat-00 §ChatContact/set.
604    /// - **`CustomEmoji`** — at most one emoji per `(account_id,
605    ///   spaceId, name)`, an absent `spaceId` being the server-global
606    ///   scope. [`crate::emoji::handle_emoji_set`] does not pre-check:
607    ///   the backend MUST reject a duplicate create as
608    ///   `BackendSetError::SetError(SetError::new(
609    ///   SetErrorType::AlreadyExists).with_existing_id(existing))` and,
610    ///   in `update_object`, a rename onto a held name as an
611    ///   `invalidProperties` SetError naming `name`. See
612    ///   draft-atwood-jmap-chat-00 §CustomEmoji `name`.
613    /// - **`Chat`** with `kind == Direct` — at most one direct chat
614    ///   per `(account_id, contact_id)`. The handler at
615    ///   [`crate::chat::handle_chat_set`] uses optimistic
616    ///   create-then-validate with rollback; backends MAY enforce a
617    ///   storage-level unique constraint to eliminate the rollback
618    ///   path entirely, but it is not required because the
619    ///   handler's rollback closes the race correctly. See
620    ///   draft-atwood-jmap-chat-00 §Chat.
621    ///
622    /// The reference `MemoryBackend` does NOT
623    /// enforce the `ReadPosition` `(account, chatId)` uniqueness
624    /// constraint at the storage layer — it is single-Mutex
625    /// per-call so concurrent racing cannot occur in practice, but a
626    /// production backend that holds different locks per record (or
627    /// no lock at all between read and write) MUST.
628    ///
629    /// # Errors
630    ///
631    /// Reject a create that RFC 8620 §5.3 defines an error for with
632    /// [`BackendSetError::SetError`] carrying the matching
633    /// [`SetErrorType`]; the handler places it verbatim in `notCreated`.
634    /// For create these are `forbidden`, `overQuota`, `tooLarge`,
635    /// `rateLimit` and `invalidProperties`. An `invalidProperties` error
636    /// SHOULD name in `properties` "*all* the properties that were
637    /// invalid", for example `chatId` when a Message names a Chat that does
638    /// not exist.
639    ///
640    /// Return [`BackendSetError::Other`] only for unexpected storage
641    /// failures. The handler reports it as `serverFail` without the
642    /// error's `Display` text, which tells the client to retry; a
643    /// deterministic rejection returned as `Other` invites retries that
644    /// cannot succeed.
645    ///
646    /// # State and change log
647    ///
648    /// RFC 8620 §5.1 defines the state string over "*all* the data of
649    /// this type in the account": "If the data changes, this string MUST
650    /// change." Every successful `create_object`,
651    /// [`update_object`](Self::update_object) and
652    /// [`destroy_object`](Self::destroy_object) MUST advance
653    /// [`get_state`](JmapBackend::get_state) for `O` in `account_id` and
654    /// record the id as created, updated or destroyed so
655    /// [`get_changes`](JmapBackend::get_changes) reports it.
656    ///
657    /// When [`ChatLimits::supports_threads`] is `true`, `Message/get`
658    /// returns the server-computed `replyCount` and `unreadReplyCount`
659    /// (draft-atwood-jmap-chat-00 §Message), so a write that changes them
660    /// changes those Messages. The backend MUST then also record as
661    /// updated in `Message` state:
662    ///
663    /// - on a Message create or destroy (including
664    ///   [`expire_message`](Self::expire_message) and
665    ///   [`read_and_burn_message`](Self::read_and_burn_message)), the
666    ///   still-stored Message its `replyTo` names, whose `replyCount`
667    ///   changed;
668    /// - on a ReadPosition update that changes `lastReadMessageId`, each
669    ///   thread root (no `threadRootId`) in that Chat with a direct reply
670    ///   whose id moved across `lastReadMessageId`, whose
671    ///   `unreadReplyCount` changed.
672    ///
673    /// The write, the state advance and the change record MUST be atomic
674    /// with respect to other callers: the reference `MemoryBackend` does
675    /// all three under one mutex acquisition, and a database backend uses
676    /// one transaction. A call that returns `Err` MUST leave the stored
677    /// data, the state and the change log unchanged.
678    fn create_object<O, F>(
679        &self,
680        caller: &Self::CallerCtx,
681        account_id: &jmap_types::Id,
682        create_id: &str,
683        build: F,
684    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
685    + Send
686    where
687        O: SetObject + Send + Sync,
688        F: FnOnce(&jmap_types::Id) -> O + Send;
689
690    /// Apply a partial update (patch) to an existing object.
691    ///
692    /// Returns `Some(updated_object)` if the backend modified any properties
693    /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
694    /// or `None` if the patch was applied verbatim.
695    ///
696    /// # Authorisation contract
697    ///
698    /// Implementors MUST verify that `caller` may act as the owner of
699    /// `account_id` before applying the patch and MUST return [`BackendSetError::SetError`]
700    /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
701    /// for the workspace-canonical rationale; the same rule applies here.
702    ///
703    /// # Patch format
704    ///
705    /// `patch` is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
706    /// Merge Patch: "The keys are a path in JSON Pointer format
707    /// \[RFC6901\], with an implicit leading "/"". So `{"a/b": null}`
708    /// removes member `b` of property `a`; it does not touch a top-level
709    /// property literally named `a/b`. A `null` value sets the
710    /// property's default if it has one, otherwise removes it. A pointer
711    /// into an array, a pointer whose parent does not exist, or two keys
712    /// where one pointer is a prefix of the other "MUST be rejected with
713    /// an "invalidPatch" error".
714    ///
715    /// Implementors SHOULD apply `patch` with
716    /// [`jmap_server::apply_patch_object`], which enforces these rules
717    /// all-or-nothing, and map any [`jmap_server::PatchPathError`] to
718    /// [`jmap_server::SetErrorType::InvalidPatch`], as the reference
719    /// `MemoryBackend` does.
720    ///
721    /// # Errors
722    ///
723    /// As for [`create_object`](Self::create_object), plus these RFC 8620
724    /// §5.3 rules for update:
725    ///
726    /// - "If an id given cannot be found, the update or destroy MUST be
727    ///   rejected with a "notFound" set error."
728    /// - A patch that breaks the rules under "Patch format" is
729    ///   `invalidPatch`.
730    /// - A patched record that is invalid is `invalidProperties`. That
731    ///   includes changing a server-set property, though "it is not an
732    ///   error to include a server-set property in an update as long as
733    ///   the value is identical to the current value on the server."
734    ///
735    /// # Atomicity
736    ///
737    /// RFC 8620 §5.3: the server "MUST NOT only commit part of an update
738    /// to a single record". Apply the whole patch and validate the result
739    /// before writing it, so that on any error the stored record is
740    /// unchanged. State and change log follow
741    /// [`create_object`](Self::create_object) ("State and change log"); an
742    /// `Ok(None)` return still advances the state.
743    fn update_object<O: SetObject + Send + Sync>(
744        &self,
745        caller: &Self::CallerCtx,
746        account_id: &jmap_types::Id,
747        id: &jmap_types::Id,
748        patch: O::Patch,
749    ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
750
751    /// Destroy an existing object by id.
752    ///
753    /// # Authorisation contract
754    ///
755    /// Implementors MUST verify that `caller` may act as the owner of
756    /// `account_id` before destroying it and MUST return [`BackendSetError::SetError`]
757    /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
758    /// for the workspace-canonical rationale; the same rule applies here.
759    ///
760    /// # Errors
761    ///
762    /// As for [`create_object`](Self::create_object), plus these RFC 8620
763    /// §5.3 rules for destroy: an unknown id, including one already
764    /// destroyed, is `notFound`, and a destroy that "would violate an ACL
765    /// or other permissions policy" is `forbidden`.
766    ///
767    /// `destroy_object::<Space>` MUST return `forbidden` unless the caller
768    /// holds `manage_space` in that Space, checked atomically with the
769    /// destroy (draft-atwood-jmap-chat-00 §Destroying a Space: "The caller
770    /// MUST hold `"manage_space"`"). The handler does no check of its own.
771    ///
772    /// # Cascades
773    ///
774    /// `destroy_object::<Message>` MUST also remove the id from its
775    /// Chat's `pinnedMessageIds` (draft-atwood-jmap-chat-00 §Chat:
776    /// "When a pinned Message is hard-deleted, the server MUST remove
777    /// its id from this list."), as
778    /// [`expire_message`](Self::expire_message) does. That change is
779    /// a Chat update.
780    ///
781    /// `destroy_object::<Space>` MUST also destroy every channel Chat
782    /// whose `spaceId` is the Space and every Message in those Chats
783    /// (draft-atwood-jmap-chat-00 §Destroying a Space: "Cascades to all
784    /// channel Chats and their Messages. Hard-deletes all records; no
785    /// tombstones are retained."). Those are Chat and Message destroys.
786    ///
787    /// Every Chat destroy, including those cascades, MUST also destroy
788    /// the Chat's ReadPosition (draft-atwood-jmap-chat-00 §ReadPosition:
789    /// the server "destroys it when the Chat is destroyed"). That is a
790    /// ReadPosition destroy.
791    ///
792    /// If the backend itself changes another record because of the
793    /// destroy, it MUST advance that record type's state and record the
794    /// change in the same atomic step, so `/changes` on that type sees it.
795    /// State and change log for `O` follow
796    /// [`create_object`](Self::create_object) ("State and change log").
797    fn destroy_object<O: SetObject + Send + Sync>(
798        &self,
799        caller: &Self::CallerCtx,
800        account_id: &jmap_types::Id,
801        id: &jmap_types::Id,
802    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
803
804    /// Called after a Chat is destroyed, so a companion extension can
805    /// update the records that reference it. Examples:
806    /// draft-atwood-jmap-chat-tasks-00 §Lifecycle ("the affected Tasks'
807    /// `chatId` fields MUST be cleared") and draft-atwood-jmap-vtc-00
808    /// §VTCCall ("the server MUST clear the corresponding field to
809    /// `null` on all VTCCalls that reference it").
810    ///
811    /// # When the handler calls this
812    ///
813    /// Once for each Chat that a request destroys, after the destroy
814    /// succeeds:
815    ///
816    /// - a `Chat/set` destroy;
817    /// - each channel in a successful `Space/set` `removeChannels` patch;
818    /// - each channel Chat whose `spaceId` is a Space that `Space/set`
819    ///   destroys (draft-atwood-jmap-chat-00 §Destroying a Space:
820    ///   "Cascades to all channel Chats"). These calls come before
821    ///   [`Self::on_space_destroyed`] for that Space.
822    ///
823    /// It is not called when the handler deletes a duplicate direct Chat
824    /// it created in the same request, because no response ever named
825    /// that id.
826    ///
827    /// The destroy is already committed, so the hook cannot fail the
828    /// request. A backend handles its own errors here. A change it makes
829    /// to another record type MUST advance that type's state, as in
830    /// [`Self::destroy_object`] ("Cascades").
831    ///
832    /// # Default implementation
833    ///
834    /// Does nothing. A backend that implements an extension which
835    /// references Chats overrides it.
836    fn on_chat_destroyed(
837        &self,
838        caller: &Self::CallerCtx,
839        account_id: &jmap_types::Id,
840        chat_id: &jmap_types::Id,
841    ) -> impl std::future::Future<Output = ()> + Send {
842        let _ = (caller, account_id, chat_id);
843        async {}
844    }
845
846    /// Called after a `Space/set` destroy succeeds, so a companion
847    /// extension can update the records that reference the Space.
848    /// Examples: draft-atwood-jmap-vtc-00 §VTCCall (clear `spaceId` on
849    /// VTCCalls) and draft-atwood-jmap-chat-filenode-00 §Space Deletion
850    /// ("the server SHOULD also destroy the associated file tree").
851    ///
852    /// The handler calls it once per destroyed Space, after
853    /// [`Self::on_chat_destroyed`] for each of its channel Chats. The
854    /// error and state rules of [`Self::on_chat_destroyed`] apply.
855    ///
856    /// # Default implementation
857    ///
858    /// Does nothing. A backend that implements an extension which
859    /// references Spaces overrides it.
860    fn on_space_destroyed(
861        &self,
862        caller: &Self::CallerCtx,
863        account_id: &jmap_types::Id,
864        space_id: &jmap_types::Id,
865    ) -> impl std::future::Future<Output = ()> + Send {
866        let _ = (caller, account_id, space_id);
867        async {}
868    }
869
870    /// Called after a `SpaceBan/set` create succeeds, with the stored
871    /// ban, so a companion extension can apply the ban to its own
872    /// records. Example: draft-atwood-jmap-vtc-00 §Access Control "Space
873    /// ban enforcement" (the server "MUST set `leftAt` on that
874    /// VTCParticipant record"; "The ban takes effect immediately on
875    /// active calls").
876    ///
877    /// The handler calls it once per created ban. The error and state
878    /// rules of [`Self::on_chat_destroyed`] apply.
879    ///
880    /// # Default implementation
881    ///
882    /// Does nothing. A backend that implements an extension which must
883    /// enforce Space bans overrides it.
884    fn on_space_ban_created(
885        &self,
886        caller: &Self::CallerCtx,
887        account_id: &jmap_types::Id,
888        ban: &jmap_chat_types::SpaceBan,
889    ) -> impl std::future::Future<Output = ()> + Send {
890        let _ = (caller, account_id, ban);
891        async {}
892    }
893
894    /// Called when the owner's action must be sent to other participants'
895    /// servers: a new Message, a retraction (`deletedForAll`), an edit, a
896    /// reaction added or removed, a group Chat change, a read receipt, a
897    /// typing signal or a presence change. A backend that implements
898    /// draft-atwood-jmap-chat-federation-00 turns the
899    /// [`OutboundEvent`](crate::OutboundEvent) into `Peer/deliver`
900    /// (`message`, `edit` or `reactionUpdate`), `Peer/retract`,
901    /// `Peer/groupUpdate`, `Peer/receipt`, `Peer/typing` or `Peer/presence`
902    /// calls, typically by enqueueing the durable ones (§Persistent Queue).
903    /// [`OutboundEvent::Typing`](crate::OutboundEvent::Typing) also drives
904    /// the local `typing` push to the Chat's other local participants.
905    ///
906    /// # When the handler calls this
907    ///
908    /// - `Message/set` create:
909    ///   [`OutboundEvent::NewMessage`](crate::OutboundEvent::NewMessage), after the Message is written
910    ///   (draft-atwood-jmap-chat-00 §Message/set: "enqueues the message for
911    ///   outbound delivery").
912    /// - `Message/set` update setting `deletedForAll: true`:
913    ///   [`OutboundEvent::Retract`](crate::OutboundEvent::Retract), after the update is written
914    ///   (§Peer/retract "Sender Behavior": "the server MUST send
915    ///   `Peer/retract` to the server of every other participant in the
916    ///   Chat"). If the write fails, nothing is reported.
917    /// - `Message/set` update editing `body`, `bodyType`, `mentions` or
918    ///   `broadcastMentions` and not deleting the Message:
919    ///   [`OutboundEvent::Edit`](crate::OutboundEvent::Edit), after the update is written.
920    /// - `Chat/set` create of a group Chat, or update that changes a group
921    ///   Chat's members, roles, `name`, `description` or `avatarBlobId`:
922    ///   one [`OutboundEvent::GroupUpdate`](crate::OutboundEvent::GroupUpdate) per action, after the write
923    ///   (draft-atwood-jmap-chat-00 §Chat/set).
924    ///
925    /// - `Message/set` update patching `reactions/<senderReactionId>` and
926    ///   not deleting the Message:
927    ///   one [`OutboundEvent::ReactionUpdate`](crate::OutboundEvent::ReactionUpdate) per key that adds a
928    ///   reaction or removes a stored one, after the update is written
929    ///   (draft-atwood-jmap-chat-00 §Adding and Removing Reactions).
930    /// - `Message/set` update setting a non-null `readAt` on a Message whose
931    ///   `senderId` is not the accountId:
932    ///   [`OutboundEvent::Receipt`](crate::OutboundEvent::Receipt), after
933    ///   the update (or the `burnOnRead` hard-delete) is written, unless
934    ///   the effective `receiptSharing` (`Chat.receiptSharing`, else
935    ///   `PresenceStatus.receiptSharing`) is `false`
936    ///   (draft-atwood-jmap-chat-federation-00 §Peer/receipt "Sender
937    ///   Behavior").
938    /// - `Chat/typing`: [`OutboundEvent::Typing`](crate::OutboundEvent::Typing),
939    ///   after the request is validated (draft-atwood-jmap-chat-00
940    ///   §Chat/typing).
941    /// - `PresenceStatus/set` update naming `presence`, `statusText` or
942    ///   `statusEmoji`: [`OutboundEvent::Presence`](crate::OutboundEvent::Presence),
943    ///   after the update is written
944    ///   (draft-atwood-jmap-chat-federation-00 §Peer/subscribePresence).
945    ///
946    /// The hook cannot fail the request. A backend handles its own errors
947    /// here.
948    ///
949    /// # Default implementation
950    ///
951    /// Does nothing, for a server that does not federate.
952    fn on_outbound_event(
953        &self,
954        caller: &Self::CallerCtx,
955        account_id: &jmap_types::Id,
956        event: &crate::OutboundEvent,
957    ) -> impl std::future::Future<Output = ()> + Send {
958        let _ = (caller, account_id, event);
959        async {}
960    }
961
962    /// Returns `true` if this backend supports JMAP object type `O` for
963    /// `account_id`, as seen by `caller`.
964    ///
965    /// # Types in scope
966    ///
967    /// Implementors should answer for the object types this trait
968    /// covers (draft-atwood-jmap-chat-00): `Chat`, `Message`, `Space`,
969    /// `SpaceInvite`, `SpaceBan`, `ChatContact`, `CustomEmoji`,
970    /// `ReadPosition`, and `PresenceStatus`. Backends MAY answer for
971    /// object types from sibling extensions if they also implement those
972    /// traits. A backend that does not recognise `O` SHOULD return
973    /// `false`.
974    ///
975    /// # Callers
976    ///
977    /// The handler library in this crate does not call this method. The
978    /// server consumer calls it when building the JMAP session capability
979    /// response.
980    ///
981    /// # Per-account semantics
982    ///
983    /// Capabilities are per account (RFC 8620 §1.6.2, §2
984    /// `accountCapabilities`), so the answer may vary with `caller` and
985    /// `account_id`. Backends that support every type in this trait for
986    /// every account can ignore both arguments and return `true`.
987    ///
988    /// # Why sync, not async
989    ///
990    /// Type-support is a deployment capability question answered from
991    /// in-process state. A backend whose supported types come from
992    /// configuration or a per-account record SHOULD load it ahead of the
993    /// request and answer from the in-memory snapshot. See the
994    /// trait-level "Async vs sync method convention" section above for
995    /// the workspace rationale.
996    fn supports_type<O: JmapObject>(
997        &self,
998        caller: &Self::CallerCtx,
999        account_id: &jmap_types::Id,
1000    ) -> bool;
1001
1002    /// Generate a cryptographically random invite code.
1003    ///
1004    /// Implementations MUST use a CSPRNG seeded from OS entropy. The
1005    /// recommended choices are [`rand::rngs::OsRng`] or the [`getrandom`]
1006    /// crate directly. Do NOT use `rand::thread_rng()` for security-relevant
1007    /// output: although current `rand` versions document `ThreadRng` as
1008    /// cryptographically secure, its underlying algorithm is
1009    /// implementation-defined and has changed across releases, and the
1010    /// `rand` book explicitly routes security-sensitive callers to `OsRng`.
1011    ///
1012    /// The returned string must be unguessable — do NOT use timestamps,
1013    /// sequential counters, or non-CSPRNG sources.
1014    ///
1015    /// # Output shape contract
1016    ///
1017    /// Implementations MUST satisfy ALL of the following for the kit's
1018    /// constant-time-compare guarantee (see below) to hold:
1019    ///
1020    /// 1. **Fixed length across calls.** Every invocation of
1021    ///    `generate_invite_code` on a single backend MUST return a
1022    ///    string of the same byte length. A backend that returns
1023    ///    variable-length codes leaks a length oracle through the
1024    ///    constant-time-compare timing channel: `ct_eq` returns
1025    ///    `Choice(0)` cheaply on length mismatch, so an attacker can
1026    ///    learn whether their candidate code matches the stored
1027    ///    length even when the content compare is constant-time.
1028    /// 2. **Minimum 128 bits of CSPRNG entropy.** The reference
1029    ///    `MemoryBackend` impl in this crate (in `memory.rs`) emits
1030    ///    32 lowercase-hex characters (16 bytes = 128 bits) which is
1031    ///    the workspace floor. Production backends MAY use more; less
1032    ///    is forbidden. The trait method itself is abstract — no
1033    ///    default impl — so backends MUST provide one.
1034    /// 3. **ASCII-safe encoding.** The returned bytes MUST be 7-bit
1035    ///    ASCII printable, byte-length-equal-to-char-length, and
1036    ///    safe to use as-is in JMAP wire format and HTTP-style
1037    ///    URL paths (no `/`, `+`, `=`, or whitespace). Recommended
1038    ///    encodings: lowercase hex (the default), base32 unpadded,
1039    ///    base64url unpadded. Plain base64 with `/` is forbidden
1040    ///    because downstream URL-encoded redemption flows misroute
1041    ///    the slash. Non-ASCII output is forbidden because
1042    ///    helpers that take byte-prefix slices (e.g. the
1043    ///    `iso8601_before` partial-comparison family) panic on
1044    ///    multi-byte UTF-8 boundaries.
1045    /// 4. **Sufficient lifespan.** Codes MUST remain
1046    ///    discriminable from each other across the backend's
1047    ///    retention window. With 128 bits of entropy and
1048    ///    well-mixed CSPRNG output, collision probability is
1049    ///    cryptographically negligible up to 2^64 active codes.
1050    ///
1051    /// A backend that cannot meet any of points 1–3 MUST NOT
1052    /// expose `Space/join`'s invite-code redemption path, or MUST
1053    /// build its own redemption with a different constant-time
1054    /// argument. The kit's `handle_space_join` assumes the contract
1055    /// without re-validating each code's shape.
1056    ///
1057    /// # Constant-time comparison contract
1058    ///
1059    /// Consumers of the returned code (notably `Space/join` invite-code
1060    /// lookup) MUST compare it against attacker-supplied values in
1061    /// constant time using `subtle::ConstantTimeEq::ct_eq` or equivalent.
1062    /// The reference handler in `space::handle_space_join` already does
1063    /// this; backends that build their own invite-redemption paths must
1064    /// preserve the invariant. A plain `String == String` short-circuits
1065    /// at the first mismatched byte and exposes a byte-by-byte timing
1066    /// oracle for credential recovery.
1067    ///
1068    /// # Errors
1069    ///
1070    /// A backend that cannot mint a code (entropy starvation, an
1071    /// unreachable HSM or KMS) returns `Err`; `SpaceInvite/set` reports
1072    /// that create as `serverFail`. Never fall back to a predictable code.
1073    ///
1074    /// `caller` and `account_id` identify the SpaceInvite create the code
1075    /// is for, so a backend can scope its entropy source per account.
1076    ///
1077    /// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
1078    /// [`getrandom`]: https://docs.rs/getrandom
1079    fn generate_invite_code(
1080        &self,
1081        caller: &Self::CallerCtx,
1082        account_id: &jmap_types::Id,
1083    ) -> impl std::future::Future<Output = Result<String, Self::Error>> + Send;
1084
1085    /// Redeem the SpaceInvite `invite_id` for `Space/join`: add the owner
1086    /// (member entry `account_id`, no roles, `joinedAt` = `joined_at`) to
1087    /// the invite's Space and increment the invite's `uses`.
1088    ///
1089    /// Per draft-atwood-jmap-chat-00 §Space/join: "The `uses` increment
1090    /// and membership insertion MUST be performed within a single atomic
1091    /// operation so that concurrent redemptions cannot exceed `maxUses`."
1092    ///
1093    /// # Atomicity contract
1094    ///
1095    /// The `uses < maxUses` check, the already-member check, the member
1096    /// append and the `uses` increment MUST all take effect or none, and
1097    /// MUST be serialized against concurrent redemptions of the invite
1098    /// and concurrent membership writes to the Space (a transaction or
1099    /// compare-and-swap). Composing this from `update_object` calls loses
1100    /// that guarantee: a failed second write leaves a member admitted
1101    /// without a use counted, and concurrent joins both pass `maxUses`.
1102    ///
1103    /// # Account scope
1104    ///
1105    /// `account_id` is the request's `accountId`, which names the
1106    /// account hosting the Space; the handler resolves the invite code
1107    /// only within that account, and `invite_id` and its Space live
1108    /// there. Implementations need no server-wide invite-code index.
1109    ///
1110    /// # When the handler calls this
1111    ///
1112    /// Once, after the invite resolved by code and is unexpired, and
1113    /// after the ban and `closedAt` checks. The handler maps each
1114    /// [`InviteJoinRefusal`] to the draft's `invalidArguments` method
1115    /// error. There is no default: a non-atomic default would reinstate
1116    /// the race.
1117    fn join_space_with_invite(
1118        &self,
1119        caller: &Self::CallerCtx,
1120        account_id: &jmap_types::Id,
1121        invite_id: &jmap_types::Id,
1122        joined_at: &jmap_types::UTCDate,
1123    ) -> impl std::future::Future<Output = Result<Result<(), InviteJoinRefusal>, Self::Error>> + Send;
1124
1125    /// Apply a `readAt`-setting `patch` to the `burnOnRead` Message
1126    /// `message_id` and hard-delete it, as one atomic operation.
1127    ///
1128    /// Per draft-atwood-jmap-chat-00 §Message `burnOnRead`: "the
1129    /// receiving server MUST permanently hard-delete this message (row
1130    /// removal, not tombstone) immediately after setting `readAt`."
1131    ///
1132    /// # Authorisation contract
1133    ///
1134    /// Implementors MUST verify that `caller` may act as the owner of
1135    /// `account_id` before setting `readAt` and deleting the Message and MUST return [`BackendSetError::SetError`]
1136    /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
1137    /// for the workspace-canonical rationale; the same rule applies here.
1138    ///
1139    /// # Atomicity contract
1140    ///
1141    /// Validate `patch` against the stored Message exactly as
1142    /// [`Self::update_object`] would, then remove the row, record the id
1143    /// in the `destroyed` set of the `Message` change log (bumping the
1144    /// `Message` state once), and unpin it from its Chat (§Chat
1145    /// `pinnedMessageIds`). All of it takes effect or none: on any error
1146    /// nothing is committed, so a retried `readAt` patch burns again.
1147    /// Composing this from `update_object` and [`Self::expire_message`]
1148    /// loses that guarantee: a failed delete leaves `readAt` stored, and
1149    /// a retry finds nothing left to set.
1150    ///
1151    /// # When the handler calls this
1152    ///
1153    /// `Message/set` update calls this instead of `update_object` when
1154    /// the patch sets a non-null `readAt` and the stored Message has
1155    /// `burnOnRead: true`. Return `SetError` `notFound` if the Message
1156    /// does not exist and the `update_object` `SetError` for an invalid
1157    /// patch. There is no default: a non-atomic default would reinstate
1158    /// the gap.
1159    fn read_and_burn_message(
1160        &self,
1161        caller: &Self::CallerCtx,
1162        account_id: &jmap_types::Id,
1163        message_id: &jmap_types::Id,
1164        patch: jmap_types::PatchObject,
1165    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
1166
1167    /// Implementation-defined per-Space content limits for this caller
1168    /// and account.
1169    ///
1170    /// Called by `handle_space_set` once per request, before
1171    /// dispatching to [`Self::apply_space_patch`], to enforce
1172    /// per-aggregate caps on roles, members, channels, and categories
1173    /// per Space (draft-atwood-jmap-chat-00 §Space/set, spec commit
1174    /// `80d5e11`), and by `handle_message_set` once per request to
1175    /// validate `bodyType` against [`ChatLimits::supported_body_types`]
1176    /// and [`ChatLimits::server_reserved_body_types`].
1177    ///
1178    /// The default implementation returns [`ChatLimits::default`],
1179    /// which carries conservative reference-impl-grade values. The
1180    /// `caller` and `account_id` arguments are plumbed even though the
1181    /// default impl ignores them, so production backends can vary caps
1182    /// per-account (Free vs. Pro tier, multi-tenant SaaS, etc.)
1183    /// without a future API break. Implementations SHOULD return
1184    /// quickly (in-process struct construction, possibly off a cached
1185    /// per-account record) — this method is called on the hot
1186    /// `Space/set` path.
1187    ///
1188    /// # Why sync, not async
1189    ///
1190    /// `Space/set` calls this once per request before dispatching the
1191    /// mutation; an async `.await` here would add a roundtrip to the
1192    /// hot path of every Space mutation. Production backends with
1193    /// per-tenant caps SHOULD cache the resolved [`ChatLimits`] for
1194    /// each account on first use and serve from the cache thereafter.
1195    /// See the trait-level "Async vs sync method convention" section
1196    /// above for the workspace rationale.
1197    ///
1198    /// Workspace cross-extension pattern: see `AGENTS.md` "Backend
1199    /// caps and limits".
1200    fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
1201        ChatLimits::default()
1202    }
1203
1204    /// Apply a sequence of structural mutations to a Space
1205    /// (draft-atwood-jmap-chat-00 §Space/set).
1206    ///
1207    /// `Space/set` `update` operations use semantic mutation keys
1208    /// (`addRoles`, `removeRoles`, `addMembers`, …) rather than RFC 8620
1209    /// JSON Pointer patches. The handler in `space::handle_space_set`
1210    /// parses the wire object, unfolds each array entry into a
1211    /// [`SpacePatchOp`](crate::SpacePatchOp) value, then calls this method with the resulting
1212    /// ordered `Vec`.
1213    ///
1214    /// # Authorisation contract
1215    ///
1216    /// Implementors MUST verify that `caller` may act as the owner of
1217    /// `account_id` before applying any op, and MUST return
1218    /// [`BackendSetError::SetError`] with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden)
1219    /// for the whole call otherwise; the handler reports it in `notUpdated`.
1220    /// The per-op permission and role-hierarchy gates under "Per-op error
1221    /// semantics" are also enforced here, atomically with the mutation. See
1222    /// [`Self::create_object`] for the workspace-canonical rationale.
1223    ///
1224    /// # Ordering and atomicity
1225    ///
1226    /// Implementations SHOULD apply ops in input order and SHOULD provide
1227    /// best-effort transactional semantics so that a partial failure does
1228    /// not leave the Space in a half-updated state. The reference
1229    /// in-memory implementation locks the entire backend for the duration
1230    /// of the call. A database-backed implementation should wrap the
1231    /// sequence in a single transaction.
1232    ///
1233    /// # Permission and limit checks
1234    ///
1235    /// Permission gates (`manage_space`, `manage_roles`,
1236    /// `manage_members`, `manage_channels`) are backend-canonical per
1237    /// workspace AGENTS.md "Caller identity (foundation seam)": the
1238    /// reference handler does NOT apply gates before calling this
1239    /// method, and the backend is responsible for rejecting any op the
1240    /// caller is not authorized to perform.
1241    ///
1242    /// Per-aggregate count limits on roles, members, channels, and
1243    /// categories per Space are **backend-canonical** as of
1244    /// bd:JMAP-x2gd.44: the backend MUST query its own
1245    /// [`ChatBackend::limits`], project the post-patch counts for the
1246    /// target Space, and reject the whole patch with an `overQuota`
1247    /// SetError (RFC 8620 §5.3) if any aggregate would exceed its
1248    /// cap. The cap enforcement MUST be atomic with the mutation
1249    /// itself — typically inside the same database transaction or
1250    /// the same mutex critical section. Per
1251    /// draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
1252    /// 2026-05-11), this behavior is normative.
1253    ///
1254    /// The handler at [`crate::space::handle_space_set`] additionally
1255    /// runs a defense-in-depth pre-flight cap check before this
1256    /// method, but the pre-flight is non-load-bearing: a backend
1257    /// caller that bypasses the JMAP wire layer (admin tool,
1258    /// federation receiver, internal batch importer) and calls
1259    /// `apply_space_patch` directly MUST still see caps enforced.
1260    /// The pre-flight exists only to surface `overQuota` to the
1261    /// client as a single SetError without consuming a backend
1262    /// round-trip; backends MAY rely on the handler having pre-checked
1263    /// for performance, but MUST NOT rely on it for correctness.
1264    ///
1265    /// The role-position hierarchy check (members may only add or modify
1266    /// roles whose `position` is strictly less than their own
1267    /// highest-position role — draft §Space/set L1260, L1266) MUST
1268    /// be enforced by the backend because it is atomic with the
1269    /// mutation and depends on the current Space state.
1270    ///
1271    /// # Cross-type cascade contract
1272    ///
1273    /// Several `SpacePatchOp` variants have side effects on other JMAP
1274    /// types in the chat extension (`Chat`, `Message`). The wire-format
1275    /// `Space/set` response describes only the Space-side change, but
1276    /// `/changes` subscribers on the cascaded types depend on the
1277    /// backend bumping the relevant type state tokens. A backend that
1278    /// performs the cross-type mutations but forgets the state bumps
1279    /// silently desynchronises every multi-client subscriber — the
1280    /// failure is invisible to single-tenant smoke tests.
1281    ///
1282    /// The required cascades are:
1283    ///
1284    /// * `RemoveChannel` — MUST destroy the channel-kind `Chat` record
1285    ///   and every `Message` whose `chatId` matches the removed
1286    ///   channel (draft §Space/set L1283: "Cascades to all
1287    ///   Messages in those channels."), and the channel's
1288    ///   `ReadPosition` (draft §ReadPosition: the server "destroys it
1289    ///   when the Chat is destroyed"). The `Chat`, `Message` and
1290    ///   `ReadPosition` type state tokens MUST bump so their `/changes`
1291    ///   subscribers see the destruction.
1292    ///
1293    /// * `RemoveCategory` — MUST clear `Chat.categoryId` on every
1294    ///   channel-kind `Chat` whose `categoryId` named the removed
1295    ///   category (the channels fall back to uncategorized). The
1296    ///   `Chat` type state token MUST bump and the affected channel
1297    ///   ids MUST appear in the next `Chat/changes` entry's `updated`
1298    ///   list.
1299    ///
1300    /// * `AddCategory` / `UpdateCategory` with a non-empty `channelIds`
1301    ///   array — MUST set `Chat.categoryId` on each named channel
1302    ///   (relocating it from its previous category or from
1303    ///   uncategorized). The `Chat` type state token MUST bump and
1304    ///   the relocated channel ids MUST appear in `Chat/changes`
1305    ///   `updated`. This pins a regression class where channel
1306    ///   relocations silently bypass the `Chat/changes` log; a
1307    ///   backend that mutates `Chat.categoryId` without bumping the
1308    ///   `Chat` state token desynchronises every multi-client
1309    ///   subscriber.
1310    ///
1311    /// * `RemoveRole` — MUST strip the removed role id from
1312    ///   `roleIds` on every `SpaceMember` of this Space (draft
1313    ///   §Space/set L1263). Members embed directly in `Space`,
1314    ///   so the cascade is captured by the existing `Space` state
1315    ///   bump; no separate `Member/changes` rotation is required.
1316    ///
1317    /// * `RemoveMember` — MUST remove the member entry and keep
1318    ///   `Space.memberCount` consistent with `members.len()`. The
1319    ///   spec does not mandate cascade to the member's `ReadPosition`
1320    ///   records; the reference impl leaves them in place and treats
1321    ///   ReadPosition cleanup as implementation-defined. A backend
1322    ///   that destroys orphaned ReadPositions MUST bump the
1323    ///   `ReadPosition` type state token; a backend that retains
1324    ///   them MUST NOT.
1325    ///
1326    /// State-token bumps SHOULD be batched per call: one bump per
1327    /// affected type per `apply_space_patch` invocation, not one bump
1328    /// per op. The reference impl combines every channel created,
1329    /// updated, and destroyed by a patch into a single `Chat/changes`
1330    /// entry; doing the same in production keeps `/changes`
1331    /// rotation rates proportional to client-visible mutations rather
1332    /// than to internal op count.
1333    ///
1334    /// # Server-set field invariants
1335    ///
1336    /// Server-set fields on the target Space (`memberCount`,
1337    /// `updatedAt`, and any future analogous cached aggregates) MUST
1338    /// be kept consistent with the post-mutation state. Specifically,
1339    /// after any combination of `AddMember` and `RemoveMember` ops,
1340    /// `Space.memberCount` MUST equal `Space.members.len()` as
1341    /// observed by the next `Space/get`. Backends MAY store these as
1342    /// cached values that they recompute on every mutation, or MAY
1343    /// compute them lazily at read time; either is acceptable as
1344    /// long as `Space/get` returns values consistent with the
1345    /// returned `members` array. The natural-minimal "persist
1346    /// memberCount once and trust it" implementation is **not**
1347    /// correct: subsequent mutations to `members` would let
1348    /// `memberCount` drift silently.
1349    ///
1350    /// `Space.closedAt` is server-set the same way: when the caller
1351    /// removes themselves as the last member holding `manage_space`
1352    /// and other members remain, the backend MUST set `closedAt` in
1353    /// the same mutation (draft §Space/set `removeMembers`). The
1354    /// handler rejects every other update to a closed Space.
1355    ///
1356    /// # Per-op error semantics
1357    ///
1358    /// Backend rejections that originate from a single op carry both
1359    /// a typed [`SetErrorType`] and a human-readable `description`
1360    /// string. The kit's integration tests pin specific
1361    /// (`SetErrorType`, `description`-substring) pairs for the
1362    /// common failure modes; a backend that returns a different
1363    /// variant or an empty description will fail those tests when
1364    /// plugged in.
1365    ///
1366    /// The following table records the contract for the
1367    /// failure modes the kit exercises today:
1368    ///
1369    /// | Op + failure mode | `SetErrorType` | `description` MUST contain |
1370    /// |---|---|---|
1371    /// | 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) |
1372    /// | `AddRole` / `UpdateRole` naming a role (or new `position`) at or above caller's highest role `position`; `AddMember` assigning, or `UpdateMember` adding or removing, such a role (draft §Space/set: "servers SHOULD enforce this"; a backend that enforces it uses this row) | `Forbidden` | `"hierarchy"` or `"position"` |
1373    /// | Any op or combination of ops that takes the Space from at least one member holding `manage_members` or `manage_space` to none (when [`Self::protect_last_admin`] returns `true`), other than self-removal | `InvalidProperties` (`properties`: the patch key(s) concerned, among `removeRoles`, `updateRoles`, `removeMembers`, `updateMembers`) | `"last-admin"` or `"manage_members"` |
1374    /// | `AddMember` with `userId` already a member | `InvalidProperties` (`properties: ["userId"]`) | implementation-defined; the reference impl names the duplicate userId |
1375    /// | `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 |
1376    /// | `RemoveRole` / `RemoveChannel` / `RemoveCategory` with an id that does not exist on this Space | `NotFound` | implementation-defined; the reference impl names the missing id |
1377    ///
1378    /// The "MUST contain ... as a substring" rule on permission-denied
1379    /// failures lets downstream UI / CLI consumers route
1380    /// permission-request flows by parsing the description, and lets
1381    /// users see "Permission denied: missing manage_space" rather
1382    /// than a bare "Permission denied". Deployments that need a
1383    /// programmatic alternative SHOULD additionally surface the
1384    /// missing permission via [`SetError::with_extra`] under a
1385    /// deployment-specific key — substring matching is the floor,
1386    /// not the ceiling.
1387    ///
1388    /// Note on routing: per-op rejections normally surface inside the
1389    /// returned [`OpResult`] vector, NOT as a top-level
1390    /// [`BackendSetError`] return. The handler at
1391    /// [`crate::space::handle_space_set`] applies the kit's per-
1392    /// update-target atomicity: any failing op in the patch fails the
1393    /// whole `update` target, so the test fixtures see the first-failing
1394    /// op's `(SetErrorType, description)` surface on
1395    /// `notUpdated[<spaceId>]`. The table above describes the
1396    /// per-op outcome content; the handler does not synthesise new
1397    /// variants or rewrite descriptions.
1398    ///
1399    /// # Return value
1400    ///
1401    /// On success, returns a `Vec<OpResult>` of the same length as `ops`,
1402    /// in input order. Each entry reports the outcome of one op (id
1403    /// assignment for `Add*` variants, error for rejections). The
1404    /// handler maps per-op errors back into the `/set` response shape
1405    /// per [`OpResult`]'s documentation.
1406    ///
1407    /// Returns [`BackendSetError::Other`] only for backend-level failures
1408    /// (the storage layer is unreachable, the account does not exist,
1409    /// `space_id` is unknown, etc.) — i.e. failures that prevent any op
1410    /// from being attempted. Per-op rejections (permission denied,
1411    /// invalid id, role hierarchy violation, etc.) go in the `outcome`
1412    /// field of the returned [`OpResult`] vector, not in an error return.
1413    fn apply_space_patch(
1414        &self,
1415        caller: &Self::CallerCtx,
1416        account_id: &jmap_types::Id,
1417        space_id: &jmap_types::Id,
1418        ops: Vec<SpacePatchOp>,
1419    ) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
1420
1421    /// Apply a JSON Merge Patch to a Space's top-level metadata fields
1422    /// (draft-atwood-jmap-chat-00 §Space/set, `name`, `description`,
1423    /// `iconBlobId`, `isPublic`, `isPubliclyPreviewable`).
1424    ///
1425    /// `Space/set` `update` operations carrying *only* top-level
1426    /// metadata fields (and not the semantic-mutation keys
1427    /// `addRoles` / `addMembers` / `addChannels` / `addCategories`
1428    /// etc.) route through this method instead of the generic
1429    /// [`Self::update_object`]. Mixed patches carrying both top-level
1430    /// metadata AND semantic-mutation keys call
1431    /// [`Self::apply_space_patch`] first (for the structural ops) and
1432    /// this method second (for the metadata). The handler at
1433    /// `space::handle_space_set` is responsible for the split and for
1434    /// stripping non-metadata keys before calling this method.
1435    ///
1436    /// # Authorisation contract
1437    ///
1438    /// Implementors MUST verify that `caller` may act as the owner of
1439    /// `account_id` before applying the patch and MUST return [`BackendSetError::SetError`]
1440    /// with [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`]
1441    /// for the workspace-canonical rationale; the same rule applies here.
1442    ///
1443    /// # Permission and atomicity
1444    ///
1445    /// Per draft-atwood-jmap-chat-00, every top-level metadata field
1446    /// carries the marker "Mutable by members with `manage_space`
1447    /// permission". Implementations MUST gate the mutation on the
1448    /// caller's effective permissions in the target Space: verify the
1449    /// caller holds `manage_space` (resolved through the Space's role
1450    /// hierarchy) and reject the patch with
1451    /// [`SetErrorType::Forbidden`] if not. The caller is the owner, whose
1452    /// `members` entry is the `account_id` (draft §Terminology), so look
1453    /// the caller up by `account_id`, not by the principal, whether or
1454    /// not [`JmapBackend::principal_id`] returns `Some`; the same holds
1455    /// for every caller-membership or permission check in this trait.
1456    ///
1457    /// The check fires inside this method atomically with the
1458    /// mutation: snapshot the Space's role/member state, evaluate
1459    /// the permission gate, and apply the merge patch in one
1460    /// critical section. Backend canonical per workspace AGENTS.md.
1461    ///
1462    /// # `patch` shape
1463    ///
1464    /// The handler decodes the wire patch's metadata-key subset
1465    /// (`name`, `description`, `iconBlobId`, `isPublic`,
1466    /// `isPubliclyPreviewable`) into a [`SpaceMetadataPatch`](crate::SpaceMetadataPatch),
1467    /// stripping structural mutation keys (`addRoles` etc.) before
1468    /// building it. Each field is `Option<_>`; nullable target fields
1469    /// use `Option<Clearable<T>>` so the backend can distinguish
1470    /// "wire null" (clear) from "absent" (unchanged). Backends MAY
1471    /// validate the values further (e.g. reject an `icon_blob_id`
1472    /// referencing a non-existent blob) and surface those as
1473    /// [`SetError`] returns. The expected `SetErrorType` for
1474    /// value-level validation failures is
1475    /// [`SetErrorType::InvalidProperties`] with the offending field
1476    /// name in `properties` — see the "Diagnostic content
1477    /// convention" section below for the blob-not-found shape
1478    /// specifically. (RFC 8620 §5.3 defines `blobNotFound` only as
1479    /// a method-level error; at the SetError level it surfaces as
1480    /// `InvalidProperties` naming the offending blob-id field.)
1481    ///
1482    /// # Return value
1483    ///
1484    /// The discriminator between `Ok(Some(space))` and `Ok(None)` is
1485    /// the **wire-visible Space shape**:
1486    ///
1487    /// - Return `Ok(None)` if the wire-visible `Space` (the shape
1488    ///   `Space/get` would serialise after applying this patch) is
1489    ///   identical to the result of mechanically applying the patch
1490    ///   keys to the prior state with no additional server-side
1491    ///   modification. The handler can then build the `/set` `updated`
1492    ///   entry from the input patch alone with no extra fetch.
1493    /// - Return `Ok(Some(space))` if the backend modified any
1494    ///   wire-visible property beyond what the client requested
1495    ///   (RFC 8620 §5.3 server-set field echo, e.g. a normalised
1496    ///   `name`, a derived `iconBlobId`, a server-bumped
1497    ///   `memberCount`, or any spec-defined server-set field that
1498    ///   `Space/get` would return). The handler echoes the returned
1499    ///   `Space` to the client.
1500    ///
1501    /// Server-internal bookkeeping that is NOT part of the
1502    /// wire-visible `Space` shape (e.g. private last-touched
1503    /// timestamps used only for `/changes` cache-keying, internal
1504    /// sequence numbers) MUST NOT itself drive the `Some` path —
1505    /// the discriminator is "would `Space/get` return a different
1506    /// shape?", not "did the backend touch anything internally?".
1507    /// A backend that bumps an internal timestamp on every metadata
1508    /// patch correctly returns `Ok(None)` when the wire shape is
1509    /// otherwise unchanged.
1510    ///
1511    /// `Err(BackendSetError::SetError(e))` with `e.kind ==
1512    /// SetErrorType::Forbidden` when the caller fails the
1513    /// `manage_space` gate.
1514    ///
1515    /// # Diagnostic content convention
1516    ///
1517    /// The `SetError.description` on a `manage_space`-gate rejection
1518    /// MUST contain `"manage_space"` as a substring. The kit's
1519    /// integration tests assert this (e.g.
1520    /// `tests/space_metadata_apply.rs`); a backend that returns a
1521    /// bare `SetError::new(SetErrorType::Forbidden)` with no
1522    /// `description` will fail those tests. Build the error via
1523    /// `SetError::new(SetErrorType::Forbidden).with_description(
1524    /// "manage_space permission required")` (or any other string
1525    /// that contains the literal `"manage_space"`).
1526    ///
1527    /// Future blob-validation rejections (e.g. `iconBlobId`
1528    /// referencing a non-existent blob, see the `patch` shape
1529    /// section above) SHOULD surface as
1530    /// `SetErrorType::InvalidProperties` with
1531    /// `properties: ["iconBlobId"]` and a description that names
1532    /// the offending blob id. The reference impl does not validate
1533    /// blobs today; production backends with a blob store SHOULD.
1534    ///
1535    /// Rationale for the separate metadata patch method: routing
1536    /// top-level metadata through the generic `update_object::<Space>`
1537    /// would bypass the permission gate, since the generic path is
1538    /// not permission-aware. This method exists so that top-level
1539    /// `Space/set` `update` requests carrying only metadata fields
1540    /// (`name` / `description` / `iconBlobId` / `isPublic` /
1541    /// `isPubliclyPreviewable`) route through a `manage_space`-gated
1542    /// path instead.
1543    fn apply_space_metadata_patch(
1544        &self,
1545        caller: &Self::CallerCtx,
1546        account_id: &jmap_types::Id,
1547        space_id: &jmap_types::Id,
1548        patch: jmap_chat_types::SpaceMetadataPatch,
1549    ) -> impl std::future::Future<
1550        Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
1551    > + Send;
1552
1553    /// Extra top-level Space properties owned by a Space extension, such
1554    /// as `calendarId` (draft-atwood-jmap-chat-calendars-00 §calendarId)
1555    /// or `taskListId` (draft-atwood-jmap-chat-tasks-00 §taskListId).
1556    ///
1557    /// `Space/set` accepts a listed key instead of rejecting it as
1558    /// `invalidProperties`. On `create`, a non-null value is stored in
1559    /// [`jmap_chat_types::Space::extra`] through `create_object`. In an
1560    /// `update` patch, the key travels in
1561    /// [`SpaceMetadataPatch::extra`](crate::SpaceMetadataPatch::extra) through
1562    /// [`Self::apply_space_metadata_patch`], so it is subject to that
1563    /// method's `manage_space` gate; a `null` value removes the property
1564    /// (RFC 7396). `Space/get` returns stored values like any other
1565    /// property. The non-member restricted view omits them.
1566    ///
1567    /// The handler does not validate values. A backend that must check
1568    /// one (for example, that `taskListId` names an existing TaskList on
1569    /// the same account) rejects it in `create_object` or
1570    /// `apply_space_metadata_patch` with an `invalidProperties` SetError
1571    /// naming the key. A listed key that is already a core Space property
1572    /// or a structural patch key keeps its core meaning.
1573    ///
1574    /// # Default implementation
1575    ///
1576    /// Returns an empty list, so no extension property is accepted.
1577    /// Backends that implement a Space extension override it.
1578    fn space_extension_properties(
1579        &self,
1580        caller: &Self::CallerCtx,
1581        account_id: &jmap_types::Id,
1582    ) -> &'static [&'static str] {
1583        let _ = (caller, account_id);
1584        &[]
1585    }
1586
1587    /// Whether the backend should reject any [`Self::apply_space_patch`]
1588    /// that would leave the target Space with zero members holding
1589    /// either `manage_members` or `manage_space` permission.
1590    ///
1591    /// # Invariant (by outcome, not by op type)
1592    ///
1593    /// The protection is invariant on the *post-patch* state of the
1594    /// (member, role, permission) graph, not on any single op variant.
1595    /// A backend that returns `true` from this method MUST reject every
1596    /// patch that takes the Space from at least one member holding
1597    /// `manage_members` or `manage_space` to none, including (non-exhaustively)
1598    /// the cases below. Self-removal (a `removeMembers` holding only the
1599    /// accountId, which references the owner per draft §Terminology) is
1600    /// exempt: draft §Space/set says
1601    /// "Last-administrator protection does not apply to self-removal."
1602    ///
1603    ///
1604    /// - `RemoveMember` that removes the last admin member.
1605    /// - `UpdateMember` that strips a role granting `manage_members` or
1606    ///   `manage_space` from a member who holds no other such role.
1607    /// - `UpdateRole` that removes `manage_members` or `manage_space`
1608    ///   permission from a role currently held by the last admin.
1609    /// - `RemoveRole` that drops a permission-granting role from the
1610    ///   graph when no other role grants the same permission to a
1611    ///   remaining member.
1612    /// - Any combination of the above within a single `ops` vector
1613    ///   whose cumulative effect is zero admins.
1614    ///
1615    /// Production backends should project the post-patch graph and
1616    /// reject when the admin count would reach zero, regardless of
1617    /// which op caused the transition.
1618    ///
1619    /// # Why this exists
1620    ///
1621    /// The 2026-05-12 design reversal dropped the `Space.ownerId` field:
1622    /// "who controls a Space" is now fully implementation-defined /
1623    /// out-of-band per draft-atwood-jmap-chat-00.
1624    /// Without a normative owner identity, the kit cannot enforce the
1625    /// previous "owner cannot be removed" rule. Instead the kit exposes
1626    /// this purely permission-graph-based knob: production backends that
1627    /// want to prevent the "no admin left" failure mode return `true`
1628    /// (the trait default); deployments with their own designated
1629    /// controller principal or external admin-tracking system can opt
1630    /// out by returning `false`.
1631    ///
1632    /// # Default implementation
1633    ///
1634    /// Returns `true` — production-safe by default. A third-party
1635    /// backend that does not override this method gets last-admin
1636    /// protection automatically.
1637    ///
1638    /// # Why the reference `MemoryBackend` overrides this to `false`
1639    ///
1640    /// The reference impl flips the default to keep existing
1641    /// integration tests (which do not seed admin memberships) passing
1642    /// unchanged. Tests that exercise the protection path opt in via
1643    /// `MemoryBackend::set_protect_last_admin_for_test(true)`.
1644    ///
1645    /// # Atomicity
1646    ///
1647    /// The check fires inside [`Self::apply_space_patch`] atomically
1648    /// with the candidate mutation: the backend snapshots the Space's
1649    /// member/role state, projects the post-patch admin count across
1650    /// all ops in the patch (member adds/removes, role-id changes,
1651    /// permission edits), and rejects the whole update target with an
1652    /// `invalidProperties` SetError naming the patch key(s) concerned
1653    /// if zero admins would remain (draft §Space/set `removeMembers`:
1654    /// "a refusal names the patch key concerned").
1655    ///
1656    /// # Why sync, not async
1657    ///
1658    /// This predicate is a deployment-policy flag: a backend either
1659    /// enforces the last-admin invariant or it does not. Backends
1660    /// that consult an external admin-tracking service to derive the
1661    /// answer SHOULD cache the per-account boolean and answer from
1662    /// the cache. See the trait-level "Async vs sync method
1663    /// convention" section above for the workspace rationale.
1664    fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
1665        let _ = (caller, account_id);
1666        true
1667    }
1668
1669    /// Whether the backend retains edit history for messages.
1670    ///
1671    /// Per draft-atwood-jmap-chat-00 commit `0783fc4` ("condition
1672    /// MessageRevision push on edit-history retention") +
1673    /// `§Message editHistory`: servers MAY limit retained
1674    /// MessageRevisions, and when the server does not retain edit
1675    /// history, the `editHistory` field MUST be omitted from
1676    /// `Message/get` and (in principle) `Message/changes` responses.
1677    /// `Message/changes` per RFC 8620 §5.2 returns only id arrays,
1678    /// not Message objects, so the spec's "omit from /changes" is
1679    /// a no-op at the wire level — the kit only enforces the
1680    /// `Message/get` projection.
1681    ///
1682    /// # When the handler calls this
1683    ///
1684    /// `handle_message_get` consults this predicate once per call.
1685    /// When `false`, every returned `Message` has its
1686    /// `edit_history` field set to `None` before serialization,
1687    /// which serde's `skip_serializing_if = "Option::is_none"`
1688    /// collapses to a wire-absent field per spec.
1689    ///
1690    /// # Why sync, not async
1691    ///
1692    /// This is a static deployment-policy flag, not a per-call
1693    /// decision — it does not consult per-account state, principal
1694    /// identity, or per-message bounds. Production backends that
1695    /// need to vary retention per-account would file a follow-up
1696    /// bead for a parallel `retains_edit_history_for_account` hook
1697    /// rather than reshaping this method.
1698    ///
1699    /// # Default implementation
1700    ///
1701    /// Returns `false` — no retention. This matches the workspace's
1702    /// "kit defines the hook; consumer enforces the policy" posture.
1703    /// Production backends that retain edit history MUST override
1704    /// this to `true`; the reference `MemoryBackend` exposes a
1705    /// test-only setter for tests that need the retain-on path.
1706    fn retains_edit_history(&self) -> bool {
1707        false
1708    }
1709
1710    /// Whether the backend keeps `Chat.unreadCount` itself instead of
1711    /// the kit recomputing it.
1712    ///
1713    /// draft-atwood-jmap-chat-00 §Chat `unreadCount` (jmap-chat-spec
1714    /// 33702a5 L629): "The value is advisory, for display such as
1715    /// badges. Servers SHOULD keep it accurate, but MAY update it some
1716    /// time after the change that affects it, MAY combine several such
1717    /// changes into one update, and MAY report a server-defined maximum
1718    /// in place of any larger count. Whenever the server changes the
1719    /// value, the Chat's state changes as for any other property
1720    /// ({{RFC8620}} Section 5.1)."
1721    ///
1722    /// # When the handlers call this
1723    ///
1724    /// When `false`, the kit keeps the count exact: `Chat/get` recomputes
1725    /// `unreadCount` from the account's Messages and ReadPositions, and
1726    /// every Message create or destroy, Message expiry, read-and-burn and
1727    /// ReadPosition update writes the recomputed count to each affected
1728    /// Chat through [`ChatBackend::update_object`], which advances the
1729    /// `Chat` state.
1730    ///
1731    /// When `true`, the kit does neither: `Chat/get` returns the stored
1732    /// `unreadCount` and no Chat is rewritten. The backend sees every
1733    /// write that moves the count (the `create_object`, `update_object`
1734    /// and `destroy_object` calls for Message and ReadPosition,
1735    /// [`ChatBackend::expire_message`] and
1736    /// [`ChatBackend::read_and_burn_message`]), and may defer, coalesce or
1737    /// cap its update. It MUST still advance the `Chat` state, and log the
1738    /// Chat as updated for `Chat/changes`, whenever the stored value
1739    /// changes (RFC 8620 §5.1: "If the data changes, this string MUST
1740    /// change").
1741    ///
1742    /// # Default implementation
1743    ///
1744    /// Returns `false`, the exact upkeep the spec's SHOULD asks for. A
1745    /// backend for which the per-event rewrite costs too much (it scans
1746    /// every Message in the account) overrides this to `true`.
1747    fn maintains_unread_count(&self) -> bool {
1748        false
1749    }
1750
1751    /// Whether the [`ChatContact`] `contact_id` has `blocked: true` on the
1752    /// contact list of `account_id`.
1753    ///
1754    /// Delivery paths call this per recipient: `account_id` is the
1755    /// recipient (the owner of the contact list) and `contact_id` is the
1756    /// sender's or referenced ChatContact id *in that account*.
1757    /// draft-atwood-jmap-chat-00 §Blocked Contacts: "Typing and presence
1758    /// push events whose sending or referenced ChatContact has
1759    /// `blocked: true` on the receiving owner's contact list are
1760    /// similarly dropped server-side before delivery to any of the
1761    /// owner's clients". §ChatContact `id` "identifies the ChatContact only
1762    /// on this server", so `contact_id` is always resolved within
1763    /// `account_id`'s list; it is never looked up in the sender's account.
1764    ///
1765    /// [`ChatContact`]: jmap_chat_types::ChatContact
1766    ///
1767    /// # Callers
1768    ///
1769    /// [`crate::should_push`] calls it with the push owner's account and
1770    /// `Message.senderId`. [`crate::should_deliver_typing`] calls it with
1771    /// the typing event's recipient and `senderId`.
1772    /// [`crate::project_presence`] calls it with the presence event's
1773    /// recipient and `contactId`.
1774    /// [`crate::handle_chat_typing`] does not call it: the request carries
1775    /// the sender's `accountId`, and the recipient's account is known only
1776    /// to the transport that fans the event out, which calls
1777    /// [`crate::should_deliver_typing`] per recipient.
1778    ///
1779    /// # Default implementation
1780    ///
1781    /// Fetches `contact_id` from `account_id` with
1782    /// [`JmapBackend::get_objects`] and returns its `blocked` field, or
1783    /// `Ok(false)` when `account_id` holds no such ChatContact. The
1784    /// callers pass the recipient's `caller`, the same one they use to
1785    /// read the recipient's Chat. Override this only when ChatContacts are
1786    /// not stored behind `get_objects` or a cheaper lookup exists.
1787    fn is_contact_blocked(
1788        &self,
1789        caller: &Self::CallerCtx,
1790        account_id: &jmap_types::Id,
1791        contact_id: &jmap_types::Id,
1792    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1793        async move {
1794            let (contacts, _) = self
1795                .get_objects::<jmap_chat_types::ChatContact>(
1796                    caller,
1797                    account_id,
1798                    Some(std::slice::from_ref(contact_id)),
1799                    None,
1800                )
1801                .await?;
1802            Ok(contacts.iter().any(|c| c.id == *contact_id && c.blocked))
1803        }
1804    }
1805
1806    /// The owner's identity for `account_id`: the value of the
1807    /// `ownerUserId` Session field (draft-atwood-jmap-chat-00 §Session
1808    /// Object Extensions).
1809    ///
1810    /// [`crate::contact::handle_contact_set`] rejects a `ChatContact/set`
1811    /// create whose `identity` equals this value, octet for octet, with
1812    /// an `invalidProperties` SetError naming `identity`
1813    /// (draft-atwood-jmap-chat-00 §ChatContact/set: "the owner has no
1814    /// ChatContact").
1815    ///
1816    /// # Default implementation
1817    ///
1818    /// Returns `Ok(None)`: the owner's identity is unknown and the check
1819    /// is skipped. Backends that serve `ownerUserId` MUST override this
1820    /// to return the same value.
1821    fn owner_user_id(
1822        &self,
1823        _caller: &Self::CallerCtx,
1824        _account_id: &jmap_types::Id,
1825    ) -> impl std::future::Future<Output = Result<Option<String>, Self::Error>> + Send {
1826        async { Ok(None) }
1827    }
1828
1829    /// The permissions of the implicit `@everyone` role in `space`, the
1830    /// account `account_id`'s Space.
1831    ///
1832    /// Every member holds that role, "which serves as the permission
1833    /// floor" (draft-atwood-jmap-chat-00 §SpaceRole, jmap-chat-spec
1834    /// 29e9a41 L812), and §Space Permission Resolution step 1 (L1705)
1835    /// unions its permissions with the member's SpaceRoles. The draft puts
1836    /// them on no wire object, so the backend decides where each Space's
1837    /// set is stored. The chat bindings (`jmap-chat-filenode-server`,
1838    /// `jmap-chat-vtc-server`) and the `Peer/deliver` handler of
1839    /// `jmap-chat-federation-server` read it here.
1840    ///
1841    /// No default: a permission floor has no neutral value.
1842    fn everyone_permissions(
1843        &self,
1844        caller: &Self::CallerCtx,
1845        account_id: &jmap_types::Id,
1846        space: &jmap_chat_types::Space,
1847    ) -> impl std::future::Future<
1848        Output = Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, Self::Error>,
1849    > + Send;
1850
1851    /// Authorization gate consulted by `handle_emoji_set` before every
1852    /// `CustomEmoji/set` create, update, or destroy.
1853    ///
1854    /// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11,
1855    /// "refactor: implementation-defined emoji authorization"):
1856    /// authorization for `CustomEmoji/set` is fully
1857    /// implementation-defined, for both server-global and Space-scoped
1858    /// emoji. When the caller is not authorized, the handler emits a
1859    /// `forbidden` SetError (RFC 8620 §5.3).
1860    ///
1861    /// # `target_space_id` semantics
1862    ///
1863    /// `target_space_id` is the **actual scope of the emoji this op
1864    /// targets**:
1865    ///
1866    /// - `None` — the emoji is server-global (its `spaceId` field is
1867    ///   absent / null).
1868    /// - `Some(id)` — the emoji is scoped to that Space (its `spaceId`
1869    ///   field equals `id`).
1870    ///
1871    /// For `Create`, the handler reads the scope from the create
1872    /// payload. For `Update` and `Destroy`, the handler pre-fetches
1873    /// the existing emoji via `get_objects` and passes its current
1874    /// `spaceId`. If the pre-fetch reports the id as not found, the
1875    /// handler skips this gate entirely and lets `update_object` /
1876    /// `destroy_object` surface a `notFound` SetError naturally — a
1877    /// non-existent target consumes no authorization decision.
1878    ///
1879    /// # When the handler calls this
1880    ///
1881    /// Exactly once per create/update/destroy entry in the request,
1882    /// AFTER wire-format validation has succeeded and BEFORE the
1883    /// corresponding `create_object` / `update_object` /
1884    /// `destroy_object` call. The handler skips the underlying mutation
1885    /// when the outer `Result` is `Ok(Err(_))` or when the outer is
1886    /// `Err(_)`. The wire mapping is:
1887    ///
1888    /// - `Ok(Ok(()))` — permit; the handler proceeds to the underlying
1889    ///   `create_object` / `update_object` / `destroy_object`.
1890    /// - `Ok(Err(set_err))` — deny with reason; the handler serialises
1891    ///   `set_err` into the appropriate `notCreated` / `notUpdated` /
1892    ///   `notDestroyed` map verbatim. Backends construct the SetError
1893    ///   with the type, description, and any `with_extra` fields the
1894    ///   deployment wants the client to see.
1895    /// - `Err(e)` — backend infrastructure failure; the handler maps
1896    ///   to a `serverFail` SetError.
1897    ///
1898    /// # Default implementation
1899    ///
1900    /// The default returns `Ok(Ok(()))` — every op is permitted. This
1901    /// matches the workspace's "kit defines the hook; consumer
1902    /// enforces the policy" posture (see the parallel design of
1903    /// [`Self::slow_mode_check`]). Production backends SHOULD override
1904    /// this method to apply the deployment's permission model — e.g.
1905    /// "only members of `target_space_id` may modify a Space-scoped
1906    /// emoji" or "only `manage_emoji` permission-holders may modify
1907    /// server-global emoji."
1908    ///
1909    /// # SetError shape recommendation
1910    ///
1911    /// Production backends SHOULD return
1912    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1913    ///     .with_description("…")))` for authorization denials, mirroring
1914    /// the workspace convention for /set responses. The description
1915    /// should explain the deployment's denial reason without leaking
1916    /// internal policy details — e.g. "Space-scoped emoji on this
1917    /// Space requires `manage_channels` permission" rather than
1918    /// "principal abc123 is not in role admin on Space xyz789".
1919    ///
1920    /// # Foundation seam
1921    ///
1922    /// Backends that wish to identify the caller call
1923    /// [`jmap_server::JmapBackend::principal_id`] on `caller` to learn
1924    /// whether identity is wired, and compare `account_id` (the owner's
1925    /// member entry, draft §Terminology) against the Space's `members`
1926    /// list, or consult ACLs or whatever permission model the
1927    /// deployment uses. Backends whose
1928    /// `principal_id` returns `None` (the workspace default, see the
1929    /// "Caller identity (foundation seam)" section of the workspace
1930    /// `AGENTS.md`) cannot meaningfully implement identity-scoped
1931    /// authorization — they should either override `principal_id`
1932    /// first or return `Ok(Ok(()))` to match the reference posture.
1933    fn may_set_custom_emoji(
1934        &self,
1935        _caller: &Self::CallerCtx,
1936        _account_id: &jmap_types::Id,
1937        _target_space_id: Option<&jmap_types::Id>,
1938        _op: EmojiSetOp,
1939    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
1940        async { Ok(Ok(())) }
1941    }
1942
1943    /// Authorization gate consulted by `handle_message_set` before a
1944    /// create or update with a non-empty `broadcastMentions` array is
1945    /// applied.
1946    ///
1947    /// Per draft-atwood-jmap-chat-00 §4.4.1: sending a `Message` with
1948    /// a non-empty `broadcastMentions` array requires the
1949    /// `"mention_broadcast"` Space permission. The server MUST reject
1950    /// with `forbidden` when the caller lacks the permission.
1951    ///
1952    /// For group/direct chats NOT part of any Space (`spaceId` is
1953    /// `None`), broadcast mentions are unrestricted per spec; the
1954    /// handler skips calling this method entirely in that case.
1955    ///
1956    /// # `space_id` semantics
1957    ///
1958    /// `space_id` is the Space that contains the target Chat (channel).
1959    /// The handler resolves it by pre-fetching the Chat and reading
1960    /// its `space_id` field. This method is only called when
1961    /// `space_id` is `Some` — the handler skips the call for
1962    /// group/direct chats with no Space.
1963    ///
1964    /// # `chat_id` semantics
1965    ///
1966    /// `chat_id` is the target channel Chat, whose `permissionOverrides`
1967    /// apply: per draft-atwood-jmap-chat-00 §Space Permission Resolution,
1968    /// "When determining whether a member may perform an action in a
1969    /// channel Chat, servers MUST evaluate permissions in this order",
1970    /// so an override may deny or allow `mention_broadcast` in one
1971    /// channel only.
1972    ///
1973    /// # When the handler calls this
1974    ///
1975    /// `handle_message_set` invokes `may_broadcast_mention` once per
1976    /// create entry or edit whose post-patch `broadcastMentions` is
1977    /// non-empty AND whose target Chat has a `spaceId`; rich-body
1978    /// `"broadcast"` spans are display-only and never trigger it
1979    /// (draft-atwood-jmap-chat-00 §Rich Body Format). The call
1980    /// fires AFTER structural validation (`validate_broadcast_mentions`)
1981    /// has succeeded and BEFORE `create_object` / `update_object`, so
1982    /// malformed payloads do not consume an authorization decision and
1983    /// an unauthorized message never touches storage.
1984    ///
1985    /// # Default implementation
1986    ///
1987    /// Returns `Ok(Ok(()))` — every op is permitted. This matches the
1988    /// workspace's "kit defines the hook; consumer enforces the policy"
1989    /// posture (see the parallel design of [`Self::may_set_custom_emoji`]).
1990    /// Production backends SHOULD override this method to check the
1991    /// caller's `mention_broadcast` permission in the target channel,
1992    /// resolved per §Space Permission Resolution (see
1993    /// [`resolve_channel_permissions`](crate::permissions::resolve_channel_permissions)).
1994    ///
1995    /// # SetError shape recommendation
1996    ///
1997    /// Production backends SHOULD return
1998    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)
1999    ///     .with_description("sender lacks mention_broadcast permission in this channel")))`.
2000    fn may_broadcast_mention(
2001        &self,
2002        _caller: &Self::CallerCtx,
2003        _account_id: &jmap_types::Id,
2004        _space_id: &jmap_types::Id,
2005        _chat_id: &jmap_types::Id,
2006    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2007        async { Ok(Ok(())) }
2008    }
2009
2010    /// Authorization gate consulted by `handle_chat_set` before an update
2011    /// whose patch touches `pinnedMessageIds` is applied.
2012    ///
2013    /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "For group
2014    /// chats, only admins may modify this list. For direct chats, the
2015    /// owner may modify it freely. For channel chats, only members with
2016    /// the `"pin"` Space permission may modify this list." For a channel
2017    /// the `"pin"` permission is resolved per §Space Permission
2018    /// Resolution, so the channel's `permissionOverrides` apply.
2019    ///
2020    /// # When the handler calls this
2021    ///
2022    /// Once per update entry whose patch sets `pinnedMessageIds` (or a
2023    /// pointer path beneath it), AFTER wire-format validation and BEFORE
2024    /// `update_object`. A `chat_id` that does not resolve SHOULD yield
2025    /// `Ok(Ok(()))` so `update_object` surfaces `notFound`. The return
2026    /// mapping is the same as [`Self::may_set_custom_emoji`].
2027    ///
2028    /// # Default implementation
2029    ///
2030    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
2031    /// parallel hooks above. Production backends SHOULD override this
2032    /// method and deny with
2033    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
2034    fn may_set_pinned_messages(
2035        &self,
2036        _caller: &Self::CallerCtx,
2037        _account_id: &jmap_types::Id,
2038        _chat_id: &jmap_types::Id,
2039    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2040        async { Ok(Ok(())) }
2041    }
2042
2043    /// Authorization gate consulted by `handle_ban_set` before each
2044    /// SpaceBan create, update or destroy.
2045    ///
2046    /// Per draft-atwood-jmap-chat-00 §SpaceBan/set: create, update and
2047    /// destroy each "Requires `"ban"` permission in the Space."
2048    ///
2049    /// # When the handler calls this
2050    ///
2051    /// Once per entry, AFTER wire-format validation and BEFORE
2052    /// `create_object` / `update_object` / `destroy_object`. `space_id`
2053    /// is the create body's `spaceId`, or the stored ban's `spaceId` for
2054    /// update and destroy; an update or destroy whose ban does not
2055    /// resolve skips the gate so the backend surfaces `notFound`. The
2056    /// return mapping is the same as [`Self::may_set_custom_emoji`].
2057    ///
2058    /// # Default implementation
2059    ///
2060    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
2061    /// parallel hooks above. Production backends SHOULD override this
2062    /// method and deny with
2063    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
2064    fn may_set_space_ban(
2065        &self,
2066        _caller: &Self::CallerCtx,
2067        _account_id: &jmap_types::Id,
2068        _space_id: &jmap_types::Id,
2069    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2070        async { Ok(Ok(())) }
2071    }
2072
2073    /// Authorization gate consulted by `handle_invite_set` before each
2074    /// SpaceInvite create or destroy.
2075    ///
2076    /// Per draft-atwood-jmap-chat-00 §SpaceInvite/set: create "Requires
2077    /// `"manage_members"` permission"; destroy "Requires
2078    /// `"manage_members"` permission or ownership of the invite."
2079    ///
2080    /// # When the handler calls this
2081    ///
2082    /// Once per entry, AFTER wire-format validation and BEFORE
2083    /// `create_object` / `destroy_object`. `space_id` is the create body's
2084    /// `spaceId`, or the stored invite's `spaceId` for destroy.
2085    /// `created_by` is `None` on create and the stored invite's
2086    /// `createdBy` on destroy. A destroy whose invite does not resolve
2087    /// skips the gate so the backend surfaces `notFound`. The return
2088    /// mapping is the same as [`Self::may_set_custom_emoji`].
2089    ///
2090    /// # Default implementation
2091    ///
2092    /// Returns `Ok(Ok(()))` — every op is permitted, matching the
2093    /// parallel hooks above. Production backends SHOULD override this
2094    /// method and deny with
2095    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
2096    fn may_set_space_invite(
2097        &self,
2098        _caller: &Self::CallerCtx,
2099        _account_id: &jmap_types::Id,
2100        _space_id: &jmap_types::Id,
2101        _created_by: Option<&jmap_types::Id>,
2102    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2103        async { Ok(Ok(())) }
2104    }
2105
2106    /// Visibility gate consulted by `handle_invite_get` and
2107    /// `handle_invite_changes` for each stored SpaceInvite.
2108    ///
2109    /// Per draft-atwood-jmap-chat-00 §SpaceInvite/get: "Only members of
2110    /// the Space may retrieve its invites. Members with
2111    /// `"manage_members"` permission see all invites; other members see
2112    /// only invites they created." §SpaceInvite/changes: "The same
2113    /// visibility rules as `SpaceInvite/get` apply".
2114    ///
2115    /// # When the handler calls this
2116    ///
2117    /// Once per invite returned by `get_objects`. `Ok(false)` hides the
2118    /// invite: `/get` reports a requested id as `notFound`, and
2119    /// `/changes` omits it from `created` and `updated`.
2120    ///
2121    /// # Default implementation
2122    ///
2123    /// Returns `Ok(true)`, so every invite is visible, matching the
2124    /// parallel hooks above. Production backends SHOULD override this
2125    /// method; invite codes are join credentials.
2126    fn may_get_space_invite(
2127        &self,
2128        _caller: &Self::CallerCtx,
2129        _account_id: &jmap_types::Id,
2130        _invite: &jmap_chat_types::SpaceInvite,
2131    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
2132        async { Ok(true) }
2133    }
2134
2135    /// Visibility gate consulted by `handle_ban_get` for each stored
2136    /// SpaceBan.
2137    ///
2138    /// Per draft-atwood-jmap-chat-00 §SpaceBan/get: "Members with
2139    /// `"ban"` permission in the Space see all SpaceBan records for that
2140    /// Space. A banned user fetching their own account sees only SpaceBan
2141    /// records where `userId` is the accountId."
2142    ///
2143    /// # When the handler calls this
2144    ///
2145    /// Once per ban returned by `get_objects`. `Ok(false)` hides the ban,
2146    /// and a requested id is reported as `notFound`. `SpaceBan/changes`
2147    /// does not consult this hook, because the spec defines it as plain
2148    /// "Standard JMAP `/changes`".
2149    ///
2150    /// # Default implementation
2151    ///
2152    /// Returns `Ok(true)`, so every ban is visible, matching the parallel
2153    /// hooks above. Production backends SHOULD override this method.
2154    fn may_get_space_ban(
2155        &self,
2156        _caller: &Self::CallerCtx,
2157        _account_id: &jmap_types::Id,
2158        _ban: &jmap_chat_types::SpaceBan,
2159    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
2160        async { Ok(true) }
2161    }
2162
2163    /// Authorization gate consulted by `handle_message_set` before each
2164    /// Message create.
2165    ///
2166    /// Per draft-atwood-jmap-chat-00 §Message/set: "The server MUST verify
2167    /// the sender is a current member of the target Chat. For group chats,
2168    /// this means a ChatMember record exists; for channel chats, the
2169    /// sender must be a member of the containing Space. Non-members MUST
2170    /// receive a SetError of type `forbidden`." and "For channel Chats,
2171    /// the server MUST verify the sender holds the `"send"` permission
2172    /// (resolved per {{space-permissions}}) before accepting the message;
2173    /// if absent, the server MUST return a SetError of type `forbidden`."
2174    /// [`resolve_channel_permissions`](crate::permissions::resolve_channel_permissions)
2175    /// implements that resolution.
2176    ///
2177    /// # When the handler calls this
2178    ///
2179    /// Once per create entry, AFTER wire-format validation and the
2180    /// closed-Chat and closed-Space checks, and BEFORE `create_object`.
2181    /// A `chat_id` that does not resolve SHOULD yield `Ok(Ok(()))` so
2182    /// `create_object` surfaces the normal error. The return mapping is
2183    /// the same as [`Self::may_set_custom_emoji`].
2184    ///
2185    /// # Default implementation
2186    ///
2187    /// Returns `Ok(Ok(()))` — every create is permitted, matching the
2188    /// parallel hooks above. Production backends SHOULD override this
2189    /// method and deny with
2190    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`.
2191    fn may_send_message(
2192        &self,
2193        _caller: &Self::CallerCtx,
2194        _account_id: &jmap_types::Id,
2195        _chat_id: &jmap_types::Id,
2196    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2197        async { Ok(Ok(())) }
2198    }
2199
2200    /// Per-Chat restriction gate consulted by `handle_message_set` before
2201    /// each Message create, with the stored target Chat.
2202    ///
2203    /// For extensions that bind a Chat to something outside JMAP Chat and
2204    /// so restrict it, e.g. draft-atwood-jmap-chat-mimi-00 §message/mls:
2205    /// "The server MUST reject a `Message/set` create in a Chat with a
2206    /// `roomId` with a `forbidden` SetError." Extension properties of the
2207    /// Chat are in [`Chat::extra`](jmap_chat_types::Chat::extra).
2208    /// [`Self::may_send_message`] is the sender's membership and
2209    /// permission gate; this one sees the Chat itself.
2210    ///
2211    /// # When the handler calls this
2212    ///
2213    /// Once per create entry whose `chatId` resolves, AFTER wire-format
2214    /// validation and BEFORE the closed-Chat check and
2215    /// [`Self::may_send_message`]. The return mapping is the same as
2216    /// [`Self::may_set_custom_emoji`].
2217    ///
2218    /// # Default implementation
2219    ///
2220    /// Returns `Ok(Ok(()))`: every create is permitted (fail-open, like
2221    /// the hooks above).
2222    fn may_create_message(
2223        &self,
2224        _caller: &Self::CallerCtx,
2225        _account_id: &jmap_types::Id,
2226        _chat: &jmap_chat_types::Chat,
2227    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2228        async { Ok(Ok(())) }
2229    }
2230
2231    /// Per-Chat restriction gate consulted by `handle_message_set` before
2232    /// each Message update, with the stored Message, its stored Chat and
2233    /// the client's patch keys.
2234    ///
2235    /// For extension-bound Chats, e.g. draft-atwood-jmap-chat-mimi-00
2236    /// §message/mls: "The server MUST reject a `Message/set` update that
2237    /// changes `body`, `bodyType`, or `reactions` of a Message in a Chat
2238    /// with a `roomId` with an `invalidProperties` SetError naming the
2239    /// changed properties."
2240    ///
2241    /// # When the handler calls this
2242    ///
2243    /// Once per update entry whose Message and Chat resolve, AFTER the
2244    /// patch keys and `bodyType` are validated and BEFORE the sender,
2245    /// edit-limit and reaction checks and `update_object`. `patch_keys`
2246    /// are the keys exactly as the client sent them, so a reaction change
2247    /// appears as `reactions/<senderReactionId>`. The return mapping is
2248    /// the same as [`Self::may_set_custom_emoji`].
2249    ///
2250    /// # Default implementation
2251    ///
2252    /// Returns `Ok(Ok(()))`: every update is permitted (fail-open, like
2253    /// the hooks above).
2254    fn may_update_message(
2255        &self,
2256        _caller: &Self::CallerCtx,
2257        _account_id: &jmap_types::Id,
2258        _chat: &jmap_chat_types::Chat,
2259        _message: &jmap_chat_types::Message,
2260        _patch_keys: &[&str],
2261    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2262        async { Ok(Ok(())) }
2263    }
2264
2265    /// Per-Chat restriction gate consulted by `handle_chat_set` before
2266    /// each Chat update, with the stored Chat and the client's patch keys.
2267    ///
2268    /// For extension-bound Chats, e.g. draft-atwood-jmap-chat-mimi-00
2269    /// §Chat.roomId: "The server MUST reject, with `forbidden`, a
2270    /// `Chat/set` update on such a Chat that sets `name`, `description`,
2271    /// or `avatarBlobId` or that uses the `addMembers`, `removeMembers`,
2272    /// or `updateMemberRoles` patch key".
2273    ///
2274    /// # When the handler calls this
2275    ///
2276    /// Once per update entry whose Chat resolves, AFTER the patch keys
2277    /// are validated and BEFORE the closed-group, admin, member-patch and
2278    /// `pinnedMessageIds` checks and `update_object`. `patch_keys` are
2279    /// the keys exactly as the client sent them. The return mapping is
2280    /// the same as [`Self::may_set_custom_emoji`].
2281    ///
2282    /// # Default implementation
2283    ///
2284    /// Returns `Ok(Ok(()))`: every update is permitted (fail-open, like
2285    /// the hooks above).
2286    fn may_update_chat(
2287        &self,
2288        _caller: &Self::CallerCtx,
2289        _account_id: &jmap_types::Id,
2290        _chat: &jmap_chat_types::Chat,
2291        _patch_keys: &[&str],
2292    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2293        async { Ok(Ok(())) }
2294    }
2295
2296    /// Blob lookup consulted by `handle_message_set` for each Attachment
2297    /// of a Message create.
2298    ///
2299    /// Per draft-atwood-jmap-chat-00 §Attachment, `size`: "Servers MUST
2300    /// verify against actual content", and `sha256`: "Servers SHOULD
2301    /// verify". The handler compares the returned [`AttachmentBlob`]
2302    /// against the Attachment and rejects a mismatch with an
2303    /// `invalidProperties` SetError naming `attachments` (§Input
2304    /// Validation). The `sha256` comparison is constant-time
2305    /// (`subtle::ConstantTimeEq`), so implementations return the digest
2306    /// rather than comparing it themselves.
2307    ///
2308    /// # When the handler calls this
2309    ///
2310    /// Once per Attachment, AFTER the `maxAttachmentsPerMessage` and
2311    /// `maxAttachmentBytes` checks (§Denial of Service: "Enforce
2312    /// `maxBodyBytes` and `maxAttachmentBytes` at parse time, before any
2313    /// fetch or storage") and BEFORE `create_object`.
2314    ///
2315    /// # Return mapping
2316    ///
2317    /// - `Ok(Ok(Some(blob)))`: compare the Attachment against `blob`.
2318    /// - `Ok(Ok(None))`: the backend does not verify this blob; accept.
2319    /// - `Ok(Err(set_error))`: reject the create with `set_error`, e.g.
2320    ///   `invalidProperties` naming `attachments` for an unknown `blobId`
2321    ///   (RFC 8620 §5.3 defines `blobNotFound` only for upload paths).
2322    /// - `Err(e)`: `serverFail`.
2323    ///
2324    /// Required: the `size` check is a MUST, so a backend that cannot
2325    /// verify blobs says so explicitly by returning `Ok(Ok(None))`.
2326    fn attachment_blob(
2327        &self,
2328        caller: &Self::CallerCtx,
2329        account_id: &jmap_types::Id,
2330        blob_id: &jmap_types::Id,
2331    ) -> impl std::future::Future<
2332        Output = Result<Result<Option<AttachmentBlob>, SetError>, Self::Error>,
2333    > + Send;
2334
2335    /// FileNode resolution consulted by `handle_message_set` for each
2336    /// create Attachment that carries `filenodeId`.
2337    ///
2338    /// Per draft-atwood-jmap-chat-filenode-00 §filenodeId: "When
2339    /// `filenodeId` is present on an Attachment, the fields `blobId`,
2340    /// `filename`, `contentType`, `size`, and `sha256` become OPTIONAL for
2341    /// that Attachment entry; the server MUST populate any absent fields
2342    /// from the referenced FileNode's properties before storage", and the
2343    /// server "MUST verify that the referenced FileNode exists and belongs
2344    /// to the same Space" and that "the sender has at least read access".
2345    /// `chat` is the message's target Chat. A deployment offering
2346    /// `urn:ietf:params:jmap:chat:filenode` implements this with
2347    /// `jmap_chat_filenode_server::resolve_filenode_attachment`.
2348    ///
2349    /// # When the handler calls this
2350    ///
2351    /// Once per such Attachment, AFTER the `maxAttachmentsPerMessage`
2352    /// check and the `may_send_message` gate, and BEFORE the
2353    /// draft-atwood-jmap-chat-00 §Input Validation checks, the
2354    /// `maxAttachmentBytes` check and [`Self::attachment_blob`], which all
2355    /// apply to the returned Attachment.
2356    ///
2357    /// # Return mapping
2358    ///
2359    /// - `Ok(Ok(Some(attachment)))`: store `attachment`, the entry with
2360    ///   its absent fields filled.
2361    /// - `Ok(Ok(None))`: the extension is not active; the entry must carry
2362    ///   all five fields, as an Attachment without `filenodeId` does.
2363    /// - `Ok(Err(set_error))`: reject the create with `set_error`.
2364    /// - `Err(e)`: `serverFail`.
2365    ///
2366    /// # Default implementation
2367    ///
2368    /// Returns `Ok(Ok(None))`: no FileNode store, matching the fail-open
2369    /// hooks above.
2370    fn filenode_attachment(
2371        &self,
2372        _caller: &Self::CallerCtx,
2373        _account_id: &jmap_types::Id,
2374        _chat: &jmap_chat_types::Chat,
2375        _attachment: &jmap_chat_types::AttachmentCreate,
2376    ) -> impl std::future::Future<
2377        Output = Result<Result<Option<jmap_chat_types::Attachment>, SetError>, Self::Error>,
2378    > + Send {
2379        async { Ok(Ok(None)) }
2380    }
2381
2382    /// Visibility gate consulted by `handle_message_get` and
2383    /// `handle_message_query`.
2384    ///
2385    /// Per draft-atwood-jmap-chat-00 §Message/query: "For channel Chats,
2386    /// the server MUST verify the caller holds the `"view"` permission
2387    /// before returning messages in `Message/get` or `Message/query`
2388    /// responses; messages in channels the caller cannot view MUST be
2389    /// omitted." The permission is resolved per §Space Permission
2390    /// Resolution, as in [`Self::may_send_message`].
2391    ///
2392    /// # When the handler calls this
2393    ///
2394    /// `Message/get` calls it once per distinct `chatId` among the
2395    /// returned messages; `Ok(false)` hides those messages, and a
2396    /// requested id is reported as `notFound`. `Message/query` calls it
2397    /// for the filter's top-level `chatId` and returns no ids when it
2398    /// yields `Ok(false)`. A query without `chatId` spans Chats, so the
2399    /// backend's `query_objects` MUST itself omit messages the caller
2400    /// cannot view; the handler cannot filter a page it did not cut.
2401    /// `Message/changes` does not consult this hook, because the spec
2402    /// defines it as plain "Standard JMAP `/changes`".
2403    ///
2404    /// # Default implementation
2405    ///
2406    /// Returns `Ok(true)`, so every Chat is viewable, matching the
2407    /// parallel hooks above. Production backends SHOULD override this
2408    /// method.
2409    fn may_view_chat(
2410        &self,
2411        _caller: &Self::CallerCtx,
2412        _account_id: &jmap_types::Id,
2413        _chat_id: &jmap_types::Id,
2414    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
2415        async { Ok(true) }
2416    }
2417
2418    /// Referential check consulted by `handle_chat_set` before an update
2419    /// that adds ids to `pinnedMessageIds` is applied.
2420    ///
2421    /// Per draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: "Each id
2422    /// MUST be the id of a Message in this Chat; the server MUST reject a
2423    /// `Chat/set` update that would add any other id with
2424    /// `invalidProperties`."
2425    ///
2426    /// # When the handler calls this
2427    ///
2428    /// After [`Self::may_set_pinned_messages`] permits the update and
2429    /// BEFORE `update_object`, with `added` holding only the ids in the
2430    /// new list that are not already in the stored list. Ids already
2431    /// pinned are not re-checked: the requirement covers adding, and a
2432    /// stale id left behind by a backend that missed a hard delete must
2433    /// not make the list impossible to edit. Not called when `added` is
2434    /// empty or `chat_id` does not resolve.
2435    ///
2436    /// Return `Ok(Err(SetError))` with type `invalidProperties` and
2437    /// properties `["pinnedMessageIds"]` when any id in `added` is not a
2438    /// Message whose `chatId` is `chat_id`.
2439    ///
2440    /// # Default implementation
2441    ///
2442    /// Fetches `added` with [`JmapBackend::get_objects`] and accepts only
2443    /// when every id comes back as a Message whose `chatId` is `chat_id`.
2444    /// Override this only when Messages are not stored behind
2445    /// `get_objects` or a cheaper lookup exists.
2446    fn validate_pinned_message_ids(
2447        &self,
2448        caller: &Self::CallerCtx,
2449        account_id: &jmap_types::Id,
2450        chat_id: &jmap_types::Id,
2451        added: &[jmap_types::Id],
2452    ) -> impl std::future::Future<Output = Result<Result<(), SetError>, Self::Error>> + Send {
2453        async move {
2454            let (messages, _) = self
2455                .get_objects::<jmap_chat_types::Message>(caller, account_id, Some(added), None)
2456                .await?;
2457            let in_chat = |id: &jmap_types::Id| {
2458                messages
2459                    .iter()
2460                    .any(|m| m.id == *id && m.chat_id == *chat_id)
2461            };
2462            if added.iter().all(in_chat) {
2463                return Ok(Ok(()));
2464            }
2465            Ok(Err(SetError::new(SetErrorType::InvalidProperties)
2466                .with_properties(["pinnedMessageIds"])
2467                .with_description(
2468                    "pinned id is not a Message in this Chat",
2469                )))
2470        }
2471    }
2472
2473    /// Throttle gate consulted before a `Message/set` create lands on
2474    /// the rate-limited path.
2475    ///
2476    /// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec
2477    /// commit `de60acb` (2026-05-11, "soften slow-mode exemption to
2478    /// SHOULD with rationale"): a `Chat` with `slowModeSeconds > 0`
2479    /// throttles the rate at which a member may post messages. The
2480    /// spec SHOULD-exempts members holding the `manage_channels`
2481    /// permission, and servers MAY define additional exempt
2482    /// principals. The kit does not opine on the exemption set — the
2483    /// backend implements the policy.
2484    ///
2485    /// When the caller is throttled, the backend returns
2486    /// `Err(`[`SlowModeError`]`)` with `retry_after` set to a UTCDate
2487    /// the rate-limited sender may use to schedule a retry. The
2488    /// `Message/set` create handler maps the error onto a
2489    /// `rateLimit` SetError (RFC 8620 §5.3 `SetError.type`) whose
2490    /// `serverRetryAfter` extra field carries the UTCDate verbatim.
2491    ///
2492    /// # When the handler calls this
2493    ///
2494    /// `handle_message_set` invokes `slow_mode_check` once per create
2495    /// entry, after wire-format validation has succeeded and before
2496    /// `create_object`. A throttle rejection short-circuits to
2497    /// `notCreated[create_id] = { type: "rateLimit",
2498    /// serverRetryAfter: <UTCDate> }` and the create_object call is
2499    /// never made.
2500    ///
2501    /// # Default implementation
2502    ///
2503    /// The default returns `Ok(())` — no throttle. This is appropriate
2504    /// for backends that have not yet implemented rate-tracking and
2505    /// for single-tenant dev servers where no abuse path exists.
2506    /// Production backends SHOULD override this method with their own
2507    /// per-(account, chat, caller) rate tracker.
2508    ///
2509    /// # No state on the kit
2510    ///
2511    /// The kit deliberately does not provide a reference rate-tracker
2512    /// — that is deployment territory. The reference `MemoryBackend`
2513    /// keeps the default no-op behaviour for the same reason.
2514    fn slow_mode_check(
2515        &self,
2516        _caller: &Self::CallerCtx,
2517        _account_id: &jmap_types::Id,
2518        _chat_id: &jmap_types::Id,
2519    ) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
2520        async { Ok(()) }
2521    }
2522
2523    /// Hard-delete a message ("expire" it) due to a per-message expiry
2524    /// event.
2525    ///
2526    /// Called by [`crate::expiry::sweep_expired`] for each message whose
2527    /// `senderExpiresAt`, Chat `messageExpirySeconds` or
2528    /// `expiresAfterReadSeconds` deadline has passed
2529    /// (draft-atwood-jmap-chat-00 §Message, §Chat). The kit does NOT run a
2530    /// scheduler; consumers call the sweep, or this method directly, when
2531    /// a timer fires.
2532    ///
2533    /// # Contract
2534    ///
2535    /// Per draft-atwood-jmap-chat-00, an expiry MUST hard-delete the
2536    /// row (not tombstone) and the message MUST appear in the
2537    /// `destroyed` set of subsequent `Message/changes` results.
2538    /// Implementations therefore SHOULD:
2539    ///
2540    /// - Remove the underlying record so a subsequent `Message/get`
2541    ///   does not find it.
2542    /// - Bump the per-account `Message` state token and record the id
2543    ///   in the change log so `Message/changes` sees it as destroyed.
2544    /// - Remove the id from its Chat's `pinnedMessageIds` (§Chat
2545    ///   `pinnedMessageIds`: "When a pinned Message is hard-deleted, the
2546    ///   server MUST remove its id from this list."). The same applies to
2547    ///   `destroy_object::<Message>`.
2548    ///
2549    /// # Idempotency
2550    ///
2551    /// If the message no longer exists — because a previous
2552    /// `expire_message` call or [`Self::read_and_burn_message`] has
2553    /// already deleted it — this method MUST
2554    /// return `Ok(())`, AND MUST NOT bump the per-account `Message`
2555    /// state token in that case. The no-op case must be
2556    /// observationally indistinguishable from "the scheduler never
2557    /// fired" for `Message/changes` subscribers; a state bump on the
2558    /// retry path would surface a spurious empty change set on every
2559    /// re-fire and induce a poll storm. Expiry events are
2560    /// inherently retry-friendly (a scheduler may re-fire if it
2561    /// crashed mid-batch). The
2562    /// return type is `Result<(), Self::Error>` (not
2563    /// `BackendSetError`) precisely to prevent a `NotFound`
2564    /// SetError construction on this path: expiry is an internal
2565    /// scheduler hook, not a `/set`-shaped call, and there is no
2566    /// JMAP wire surface for per-message expiry rejection.
2567    ///
2568    /// A `Message/set` read of a `burnOnRead` Message does not use this
2569    /// hook; it calls [`Self::read_and_burn_message`] so the `readAt`
2570    /// write and the hard-delete are atomic. The expiry sweep
2571    /// ([`crate::sweep_expired`]) does call it for a read
2572    /// `burnOnRead` Message that reached the store another way.
2573    ///
2574    /// # Default implementation
2575    ///
2576    /// The default returns `Ok(())` without doing anything, so expired
2577    /// messages stay in the store and remain visible to `Message/get`.
2578    /// It is correct only for a backend on which no message ever
2579    /// expires. Backends whose messages can carry `senderExpiresAt`,
2580    /// `expiresAfterReadSeconds` or a Chat `messageExpirySeconds` MUST
2581    /// override this method: for `senderExpiresAt`,
2582    /// draft-atwood-jmap-chat-00 §Message says "servers MUST
2583    /// permanently delete this message — removing the row entirely,
2584    /// not leaving a tombstone — at or before this time".
2585    fn expire_message(
2586        &self,
2587        _caller: &Self::CallerCtx,
2588        _account_id: &jmap_types::Id,
2589        _message_id: &jmap_types::Id,
2590    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
2591        async { Ok(()) }
2592    }
2593}
2594
2595#[cfg(test)]
2596mod tests {
2597    use super::SlowModeError;
2598    use jmap_types::UTCDate;
2599
2600    #[test]
2601    fn slow_mode_error_display_contains_retry_after() {
2602        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
2603        let rendered = format!("{err}");
2604        assert!(
2605            rendered.contains("slow-mode rate limit"),
2606            "Display missing prefix: {rendered}"
2607        );
2608        assert!(
2609            rendered.contains("2026-05-16T12:34:56Z"),
2610            "Display missing retry_after timestamp: {rendered}"
2611        );
2612    }
2613
2614    #[test]
2615    fn slow_mode_error_is_std_error() {
2616        // Compile-time check that SlowModeError implements std::error::Error.
2617        // If this fails to compile, the trait impl regressed.
2618        fn assert_is_error<E: std::error::Error>(_: &E) {}
2619        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
2620        assert_is_error(&err);
2621    }
2622
2623    #[test]
2624    fn slow_mode_error_boxes_as_dyn_error() {
2625        // Independent oracle: the std error machinery itself. If
2626        // SlowModeError does not implement std::error::Error this
2627        // conversion does not compile.
2628        let err = SlowModeError::new(UTCDate::from("2026-05-16T12:34:56Z"));
2629        let boxed: Box<dyn std::error::Error> = Box::new(err);
2630        assert!(boxed.to_string().contains("slow-mode rate limit"));
2631    }
2632
2633    use super::OpResult;
2634    use jmap_server::{SetError, SetErrorType};
2635
2636    #[test]
2637    fn op_result_ok_carries_op_index_and_optional_id() {
2638        let r = OpResult::ok(3, Some(jmap_types::Id::from("space-1")));
2639        assert_eq!(r.op_index, 3);
2640        assert_eq!(r.outcome, Ok(Some(jmap_types::Id::from("space-1"))));
2641    }
2642
2643    #[test]
2644    fn op_result_ok_with_none_id_for_update_or_destroy() {
2645        let r = OpResult::ok(0, None);
2646        assert_eq!(r.op_index, 0);
2647        assert_eq!(r.outcome, Ok(None));
2648    }
2649
2650    #[test]
2651    fn op_result_err_carries_op_index_and_set_error() {
2652        let r = OpResult::err(7, SetError::new(SetErrorType::Forbidden));
2653        assert_eq!(r.op_index, 7);
2654        match r.outcome {
2655            Err(e) => assert_eq!(e.error_type, SetErrorType::Forbidden),
2656            Ok(_) => panic!("expected Err outcome"),
2657        }
2658    }
2659
2660    #[test]
2661    fn op_result_with_op_index_replaces_field() {
2662        let r = OpResult::ok(0, None).with_op_index(42);
2663        assert_eq!(r.op_index, 42);
2664        assert_eq!(r.outcome, Ok(None));
2665    }
2666
2667    #[test]
2668    fn op_result_with_outcome_replaces_field() {
2669        let r =
2670            OpResult::ok(0, None).with_outcome(Err(SetError::new(SetErrorType::InvalidProperties)));
2671        assert_eq!(r.op_index, 0);
2672        match r.outcome {
2673            Err(e) => assert_eq!(e.error_type, SetErrorType::InvalidProperties),
2674            Ok(_) => panic!("expected Err outcome after with_outcome"),
2675        }
2676    }
2677
2678    // Const-context smoke tests — lock in the const fn markers so a
2679    // future refactor that accidentally drops `const` from any of
2680    // these constructors / builders is caught at compile time
2681    // (bd:JMAP-x2gd.79).
2682
2683    use super::ChatLimits;
2684
2685    /// `OpResult::ok` is callable in const context.
2686    #[test]
2687    fn op_result_ok_is_const_fn() {
2688        const _R: OpResult = OpResult::ok(0, None);
2689    }
2690
2691    /// `ChatLimits::new` plus all four `with_*` setters chain in const
2692    /// context — proves the entire builder pipeline stays const.
2693    #[test]
2694    fn chat_limits_builder_is_const_fn() {
2695        const _LIMITS: ChatLimits = ChatLimits::new(1, 2, 3, 4)
2696            .with_max_roles_per_space(10)
2697            .with_max_space_members(20)
2698            .with_max_channels_per_space(30)
2699            .with_max_categories_per_space(40);
2700    }
2701
2702    // Note: `SlowModeError::new` is `const fn` (clippy::nursery
2703    // `missing_const_for_fn` would re-fire if the marker were dropped),
2704    // but a const-context smoke test cannot be authored without a
2705    // const-constructible `UTCDate`. `UTCDate` wraps a `String`, and
2706    // `String` is not const-constructible from a non-empty literal in
2707    // stable Rust today. The clippy lint covers the regression case.
2708}