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