Skip to main content

jmap_chat_server/
lib.rs

1//! JMAP Chat extension method handlers.
2//!
3//! # Usage
4//!
5//! Implement [`ChatBackend`] for your storage layer, then call
6//! [`register_chat_handlers`] to wire all method names into a
7//! [`jmap_server::Dispatcher`]:
8//!
9//! ```rust,no_run
10//! # use std::sync::Arc;
11//! # use jmap_chat_server::{ChatBackend, register_chat_handlers};
12//! # use jmap_server::Dispatcher;
13//! # fn example<B: ChatBackend<CallerCtx = ()> + 'static>(backend: B) {
14//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
15//! register_chat_handlers(&mut dispatcher, Arc::new(backend));
16//! # }
17//! ```
18//!
19//! # `memory` feature (reference implementation)
20//!
21//! Enable the `memory` feature to expose the `memory::MemoryBackend`
22//! reference implementation of [`ChatBackend`]. This is the same
23//! backend used by this crate's own integration tests, intended for
24//! downstream contributors to study and for smoke tests / examples
25//! that do not want to stand up a real database. **Not production.**
26//! API stability is opt-in via this feature and may break across minor
27//! versions while the crate is pre-1.0.
28//!
29//! # `realistic-demo-ids` feature (test-id format toggle)
30//!
31//! The `realistic-demo-ids` feature changes the id-minting format
32//! that [`memory::MemoryBackend`] uses for server-assigned object
33//! ids. It requires `memory` to be enabled (the feature only
34//! affects the in-memory reference backend; no other code path
35//! observes it).
36//!
37//! - **Default (feature OFF):** deterministic, lex-orderable
38//!   per-(type, account) ids of the form `"<type><n:016x>"`. Easy
39//!   to read in test debug output. Load-bearing for
40//!   draft-atwood-jmap-chat-00 `Chat.unreadCount` semantics (count
41//!   of `Message`s whose id is lex-greater than
42//!   `lastReadMessageId`).
43//! - **Feature ON:** mail-server-style timestamp+counter ids of
44//!   the form `"{n:016x}"`. Lex-orderable globally within a
45//!   process, not repeatable across runs.
46//!
47//! **Cargo feature unification hazard.** The output format of
48//! every `MemoryBackend`-minted id depends on this feature, and
49//! cargo unifies features across the dep graph. If crate A's
50//! tests activate `realistic-demo-ids` for realism and crate B's
51//! tests consume `MemoryBackend` expecting the deterministic
52//! format, a unified workspace build silently switches B to the
53//! realistic format and B's tests break. Crates that depend on
54//! a specific id format MUST NOT rely on the *absence* of the
55//! feature elsewhere in the dep graph — they MUST encode the
56//! expected format in their own tests via fixture matching or
57//! prefix assertions rather than literal id comparison.
58//!
59//! # Permission enforcement: backend canonical
60//!
61//! All Space/set permission gates live in the backend's
62//! `apply_space_patch` implementation (see `memory::MemoryBackend`
63//! under the `memory` feature for the reference impl). The handler
64//! [`handle_space_set`] does NOT permission-check.
65//!
66//! The pure helper [`required_permissions_for_op`] in [`permissions`]
67//! maps each [`SpacePatchOp`] variant to its required permission strings
68//! per draft-atwood-jmap-chat-00 §Space/set. Backends consume this
69//! helper inside `apply_space_patch` after resolving the caller's
70//! effective permissions via [`jmap_server::JmapBackend::principal_id`].
71//! Handlers MUST NOT consume the helper for gating — backends are the
72//! single source of truth. This mirrors the workspace-wide rule
73//! documented in workspace AGENTS.md "Caller identity (foundation
74//! seam)":
75//!
76//! - Handlers do NO permission checking.
77//! - Defense-in-depth handler pre-checks are allowed but the backend
78//!   MUST re-verify atomically with the mutation.
79//! - A `None` return from `JmapBackend::principal_id` means the
80//!   deployment has not wired identity; chat permission semantics
81//!   cannot be honored and the backend MUST reject the patch rather
82//!   than fail open.
83
84#![forbid(unsafe_code)]
85
86use std::sync::Arc;
87
88use jmap_server::{Dispatcher, HandlerFuture, JmapHandler};
89
90pub mod backend;
91pub mod ban;
92pub mod chat;
93pub mod contact;
94pub mod emoji;
95mod helpers;
96pub mod invite;
97/// In-memory reference implementation of [`ChatBackend`].
98///
99/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
100/// the full module documentation.
101#[cfg(feature = "memory")]
102pub mod memory;
103pub mod message;
104pub mod permissions;
105pub mod position;
106pub mod presence;
107pub mod space;
108
109pub use backend::{
110    AddedItem, BackendChangesError, BackendSetError, ChangesResult, ChatBackend,
111    ChatContactProperty, ChatLimits, ChatProperty, EmojiSetOp, GetObject, JmapBackend, JmapObject,
112    MessageProperty, OpResult, QueryChangesResult, QueryObject, QueryResult, ReadPositionProperty,
113    SetError, SetErrorType, SetObject, SlowModeError, SpaceMetadataPatch, SpacePatchOp,
114    SpaceProperty,
115};
116pub use ban::{handle_ban_changes, handle_ban_get, handle_ban_set};
117pub use chat::{
118    handle_chat_changes, handle_chat_get, handle_chat_query, handle_chat_query_changes,
119    handle_chat_set, handle_chat_typing,
120};
121pub use contact::{
122    handle_contact_changes, handle_contact_get, handle_contact_query, handle_contact_query_changes,
123    handle_contact_set,
124};
125pub use emoji::{
126    handle_emoji_changes, handle_emoji_get, handle_emoji_query, handle_emoji_query_changes,
127    handle_emoji_set,
128};
129pub use invite::{handle_invite_changes, handle_invite_get, handle_invite_set};
130pub use message::{
131    handle_message_changes, handle_message_get, handle_message_query, handle_message_query_changes,
132    handle_message_set,
133};
134pub use permissions::{
135    required_permissions_for_op, RequiredPermissions, MANAGE_CHANNELS, MANAGE_MEMBERS,
136    MANAGE_ROLES, MANAGE_SPACE,
137};
138pub use position::{handle_position_changes, handle_position_get, handle_position_set};
139pub use presence::{handle_presence_changes, handle_presence_get, handle_presence_set};
140pub use space::{
141    handle_space_changes, handle_space_get, handle_space_join, handle_space_query,
142    handle_space_query_changes, handle_space_set,
143};
144
145// ---------------------------------------------------------------------------
146// register_chat_handlers — the main entry point for consumers
147// ---------------------------------------------------------------------------
148
149/// Register all JMAP Chat method handlers with `dispatcher`.
150///
151/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
152/// You may pass any `Arc<B>` — the function clones it internally into each
153/// registered handler closure. Sharing the same `Arc<B>` across this call
154/// and other application-level uses of the backend is a memory
155/// optimization, not a correctness requirement; separate `Arc<B>` instances
156/// pointing at the same underlying backend would also work.
157///
158/// After this call, the dispatcher handles:
159/// `Chat/*`, `Message/*`, `Space/*`, `SpaceBan/*`, `ChatContact/*`,
160/// `ReadPosition/*`, `CustomEmoji/*`, `SpaceInvite/*`, and `PresenceStatus/*`.
161///
162/// The dispatcher's `CallerCtx` is taken from `B::CallerCtx`; every registered
163/// closure forwards it as `&ctx` into the wrapped `handle_*` function. Backends
164/// that use `type CallerCtx = ()` therefore see `&()` inside every handler.
165///
166/// # Re-registration semantics
167///
168/// This function calls [`Dispatcher::register`] once per
169/// draft-atwood-jmap-chat-00 method name. `Dispatcher::register`
170/// **silently overwrites** any pre-existing handler under the same
171/// method name (the underlying primitive is `HashMap::insert`). Three
172/// consequences callers MUST be aware of:
173///
174/// - **Double-call**: invoking this function twice on the same
175///   dispatcher loses the first set's handlers. The second call wins.
176/// - **Custom overrides go LAST**: to replace a single handler (e.g.
177///   provide a custom `Chat/get`), call this function FIRST, then
178///   `dispatcher.register("Chat/get", my_override)`. The inverse
179///   order silently undoes the custom handler.
180/// - **No collision diagnostic**: there is no error or log when a
181///   handler is overwritten. The contract is "last register wins" and
182///   the caller is responsible for ordering.
183///
184/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
185pub fn register_chat_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
186where
187    B: ChatBackend + 'static,
188{
189    // Helper: register one method with a closure that takes
190    // (Arc<B>, call_id, args, ctx).
191    //
192    // `$ci` is the call_id string (echoed back to the client). Most handlers
193    // ignore it and use `_ci` as the identifier.
194    //
195    // `$ctx` is the per-request caller context (`B::CallerCtx`) forwarded
196    // by the dispatcher. Closures pass `&ctx` to the inner `handle_*` fn.
197    macro_rules! reg {
198        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident| $body:expr) => {{
199            let backend_arc: Arc<B> = Arc::clone(&$backend);
200            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
201                backend_arc,
202                move |$b: Arc<B>, $ci: String, $a: serde_json::Value, $ctx: B::CallerCtx| {
203                    Box::pin(async move { $body }) as HandlerFuture
204                },
205            ));
206            dispatcher.register($method, h);
207        }};
208    }
209
210    // Chat
211    reg!("Chat/get", backend, |b, _ci, a, ctx| {
212        handle_chat_get(&*b, &ctx, a).await
213    });
214    reg!("Chat/changes", backend, |b, _ci, a, ctx| {
215        handle_chat_changes(&*b, &ctx, a).await
216    });
217    reg!("Chat/query", backend, |b, _ci, a, ctx| {
218        handle_chat_query(&*b, &ctx, a).await
219    });
220    reg!("Chat/queryChanges", backend, |b, _ci, a, ctx| {
221        handle_chat_query_changes(&*b, &ctx, a).await
222    });
223    reg!("Chat/set", backend, |b, _ci, a, ctx| {
224        handle_chat_set(&*b, &ctx, a).await
225    });
226    reg!("Chat/typing", backend, |b, _ci, a, ctx| {
227        handle_chat_typing(&*b, &ctx, a).await
228    });
229
230    // Message
231    reg!("Message/get", backend, |b, _ci, a, ctx| {
232        handle_message_get(&*b, &ctx, a).await
233    });
234    reg!("Message/changes", backend, |b, _ci, a, ctx| {
235        handle_message_changes(&*b, &ctx, a).await
236    });
237    reg!("Message/query", backend, |b, _ci, a, ctx| {
238        handle_message_query(&*b, &ctx, a).await
239    });
240    reg!("Message/queryChanges", backend, |b, _ci, a, ctx| {
241        handle_message_query_changes(&*b, &ctx, a).await
242    });
243    reg!("Message/set", backend, |b, _ci, a, ctx| {
244        handle_message_set(&*b, &ctx, a).await
245    });
246
247    // Space
248    reg!("Space/get", backend, |b, _ci, a, ctx| {
249        handle_space_get(&*b, &ctx, a).await
250    });
251    reg!("Space/changes", backend, |b, _ci, a, ctx| {
252        handle_space_changes(&*b, &ctx, a).await
253    });
254    reg!("Space/query", backend, |b, _ci, a, ctx| {
255        handle_space_query(&*b, &ctx, a).await
256    });
257    reg!("Space/queryChanges", backend, |b, _ci, a, ctx| {
258        handle_space_query_changes(&*b, &ctx, a).await
259    });
260    reg!("Space/set", backend, |b, _ci, a, ctx| {
261        handle_space_set(&*b, &ctx, a).await
262    });
263    reg!("Space/join", backend, |b, _ci, a, ctx| {
264        handle_space_join(&*b, &ctx, a).await
265    });
266
267    // ChatContact
268    reg!("ChatContact/get", backend, |b, _ci, a, ctx| {
269        handle_contact_get(&*b, &ctx, a).await
270    });
271    reg!("ChatContact/changes", backend, |b, _ci, a, ctx| {
272        handle_contact_changes(&*b, &ctx, a).await
273    });
274    reg!("ChatContact/query", backend, |b, _ci, a, ctx| {
275        handle_contact_query(&*b, &ctx, a).await
276    });
277    reg!("ChatContact/queryChanges", backend, |b, _ci, a, ctx| {
278        handle_contact_query_changes(&*b, &ctx, a).await
279    });
280    reg!("ChatContact/set", backend, |b, _ci, a, ctx| {
281        handle_contact_set(&*b, &ctx, a).await
282    });
283
284    // ReadPosition
285    reg!("ReadPosition/get", backend, |b, _ci, a, ctx| {
286        handle_position_get(&*b, &ctx, a).await
287    });
288    reg!("ReadPosition/changes", backend, |b, _ci, a, ctx| {
289        handle_position_changes(&*b, &ctx, a).await
290    });
291    reg!("ReadPosition/set", backend, |b, _ci, a, ctx| {
292        handle_position_set(&*b, &ctx, a).await
293    });
294
295    // SpaceInvite
296    reg!("SpaceInvite/get", backend, |b, _ci, a, ctx| {
297        handle_invite_get(&*b, &ctx, a).await
298    });
299    reg!("SpaceInvite/changes", backend, |b, _ci, a, ctx| {
300        handle_invite_changes(&*b, &ctx, a).await
301    });
302    reg!("SpaceInvite/set", backend, |b, _ci, a, ctx| {
303        handle_invite_set(&*b, &ctx, a).await
304    });
305
306    // SpaceBan
307    reg!("SpaceBan/get", backend, |b, _ci, a, ctx| {
308        handle_ban_get(&*b, &ctx, a).await
309    });
310    reg!("SpaceBan/changes", backend, |b, _ci, a, ctx| {
311        handle_ban_changes(&*b, &ctx, a).await
312    });
313    reg!("SpaceBan/set", backend, |b, _ci, a, ctx| {
314        handle_ban_set(&*b, &ctx, a).await
315    });
316
317    // CustomEmoji
318    reg!("CustomEmoji/get", backend, |b, _ci, a, ctx| {
319        handle_emoji_get(&*b, &ctx, a).await
320    });
321    reg!("CustomEmoji/changes", backend, |b, _ci, a, ctx| {
322        handle_emoji_changes(&*b, &ctx, a).await
323    });
324    reg!("CustomEmoji/query", backend, |b, _ci, a, ctx| {
325        handle_emoji_query(&*b, &ctx, a).await
326    });
327    reg!("CustomEmoji/queryChanges", backend, |b, _ci, a, ctx| {
328        handle_emoji_query_changes(&*b, &ctx, a).await
329    });
330    reg!("CustomEmoji/set", backend, |b, _ci, a, ctx| {
331        handle_emoji_set(&*b, &ctx, a).await
332    });
333
334    // PresenceStatus
335    reg!("PresenceStatus/get", backend, |b, _ci, a, ctx| {
336        handle_presence_get(&*b, &ctx, a).await
337    });
338    reg!("PresenceStatus/changes", backend, |b, _ci, a, ctx| {
339        handle_presence_changes(&*b, &ctx, a).await
340    });
341    reg!("PresenceStatus/set", backend, |b, _ci, a, ctx| {
342        handle_presence_set(&*b, &ctx, a).await
343    });
344}
345
346/// Generic closure-to-[`JmapHandler`] adapter from [`jmap_server`].
347///
348/// Re-exported so the [`register_chat_handlers`] macro body can name
349/// `ClosureHandler` without a fully-qualified path. **Stability**: this
350/// re-export pins the major-version contract of [`jmap_server::ClosureHandler`]
351/// into this crate's public surface — a breaking change to that type
352/// upstream is a breaking change here. Consumers needing a closure handler
353/// adapter SHOULD prefer importing from [`jmap_server`] directly; the
354/// re-export is retained primarily for the in-crate macro and for
355/// backward-compatible spelling of the existing handler-registration
356/// pattern.
357pub use jmap_server::ClosureHandler;