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