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//! # Permission enforcement: backend canonical
30//!
31//! All Space/set permission gates live in the backend's
32//! `apply_space_patch` implementation (see `memory::MemoryBackend`
33//! under the `memory` feature for the reference impl). The handler
34//! [`handle_space_set`] does NOT permission-check.
35//!
36//! The pure helper [`required_permissions_for_op`] in [`permissions`]
37//! maps each [`SpacePatchOp`] variant to its required permission strings
38//! per draft-atwood-jmap-chat-00 §Space/set. Backends consume this
39//! helper inside `apply_space_patch` after resolving the caller's
40//! effective permissions from the Space `members` entry whose `id` is
41//! the `accountId` (the owner, per draft §Terminology). The gates apply
42//! whether or not [`jmap_server::JmapBackend::principal_id`] resolves a
43//! caller identity.
44//! Handlers MUST NOT consume the helper for gating — backends are the
45//! single source of truth. This mirrors the workspace-wide rule
46//! documented in workspace AGENTS.md "Caller identity (foundation
47//! seam)":
48//!
49//! - Handlers do NO permission checking.
50//! - Defense-in-depth handler pre-checks are allowed but the backend
51//!   MUST re-verify atomically with the mutation.
52
53#![forbid(unsafe_code)]
54
55use std::sync::Arc;
56
57use jmap_server::{Dispatcher, HandlerFuture, JmapHandler};
58
59pub mod backend;
60pub mod ban;
61pub mod chat;
62pub mod contact;
63pub mod emoji;
64mod helpers;
65pub mod invite;
66/// In-memory reference implementation of [`ChatBackend`].
67///
68/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
69/// the full module documentation.
70#[cfg(feature = "memory")]
71pub mod memory;
72pub mod message;
73pub mod permissions;
74pub mod position;
75pub mod presence;
76pub mod push;
77pub mod space;
78
79pub use backend::{
80    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, ChatBackend,
81    ChatContactProperty, ChatLimits, ChatProperty, EmojiSetOp, GetObject, InviteJoinRefusal,
82    JmapBackend, JmapObject, MessageProperty, OpResult, QueryChangesResult, QueryObject,
83    QueryResult, ReadPositionProperty, SetError, SetErrorType, SetObject, SlowModeError,
84    SpaceMetadataPatch, SpacePatchOp, SpaceProperty,
85};
86pub use ban::{handle_ban_changes, handle_ban_get, handle_ban_set};
87pub use chat::{
88    handle_chat_changes, handle_chat_get, handle_chat_query, handle_chat_query_changes,
89    handle_chat_set, handle_chat_typing,
90};
91pub use contact::{
92    handle_contact_changes, handle_contact_get, handle_contact_query, handle_contact_query_changes,
93    handle_contact_set,
94};
95pub use emoji::{
96    handle_emoji_changes, handle_emoji_get, handle_emoji_query, handle_emoji_query_changes,
97    handle_emoji_set,
98};
99pub use invite::{handle_invite_changes, handle_invite_get, handle_invite_set};
100pub use message::{
101    handle_message_changes, handle_message_get, handle_message_query, handle_message_query_changes,
102    handle_message_set,
103};
104pub use permissions::{
105    required_permissions_for_op, RequiredPermissions, BAN, MANAGE_CHANNELS, MANAGE_MEMBERS,
106    MANAGE_ROLES, MANAGE_SPACE, PIN,
107};
108pub use position::{handle_position_changes, handle_position_get, handle_position_set};
109pub use presence::{handle_presence_changes, handle_presence_get, handle_presence_set};
110pub use push::{
111    build_chat_message_push, chat_state_change_for, should_push, strip_unsupported_chat_push,
112    validate_chat_push, BuiltPush, OwnerFlags, PushItem,
113};
114pub use space::{
115    handle_space_changes, handle_space_get, handle_space_join, handle_space_query,
116    handle_space_query_changes, handle_space_set,
117};
118
119// ---------------------------------------------------------------------------
120// register_chat_handlers — the main entry point for consumers
121// ---------------------------------------------------------------------------
122
123/// Register all JMAP Chat method handlers with `dispatcher`.
124///
125/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
126/// You may pass any `Arc<B>` — the function clones it internally into each
127/// registered handler closure. Sharing the same `Arc<B>` across this call
128/// and other application-level uses of the backend is a memory
129/// optimization, not a correctness requirement; separate `Arc<B>` instances
130/// pointing at the same underlying backend would also work.
131///
132/// After this call, the dispatcher handles:
133/// `Chat/*`, `Message/*`, `Space/*`, `SpaceBan/*`, `ChatContact/*`,
134/// `ReadPosition/*`, `CustomEmoji/*`, `SpaceInvite/*`, and `PresenceStatus/*`.
135///
136/// The dispatcher's `CallerCtx` is taken from `B::CallerCtx`; every registered
137/// closure forwards it as `&ctx` into the wrapped `handle_*` function. Backends
138/// that use `type CallerCtx = ()` therefore see `&()` inside every handler.
139///
140/// # Re-registration semantics
141///
142/// This function calls [`Dispatcher::register`] once per
143/// draft-atwood-jmap-chat-00 method name. `Dispatcher::register`
144/// **silently overwrites** any pre-existing handler under the same
145/// method name (the underlying primitive is `HashMap::insert`). Three
146/// consequences callers MUST be aware of:
147///
148/// - **Double-call**: invoking this function twice on the same
149///   dispatcher loses the first set's handlers. The second call wins.
150/// - **Custom overrides go LAST**: to replace a single handler (e.g.
151///   provide a custom `Chat/get`), call this function FIRST, then
152///   `dispatcher.register("Chat/get", my_override)`. The inverse
153///   order silently undoes the custom handler.
154/// - **No collision diagnostic**: there is no error or log when a
155///   handler is overwritten. The contract is "last register wins" and
156///   the caller is responsible for ordering.
157///
158/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
159pub fn register_chat_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
160where
161    B: ChatBackend + 'static,
162{
163    // Helper: register one method with a closure that takes
164    // (Arc<B>, call_id, args, ctx).
165    //
166    // `$ci` is the call_id string (echoed back to the client). Most handlers
167    // ignore it and use `_ci` as the identifier.
168    //
169    // `$ctx` is the per-request caller context (`B::CallerCtx`) forwarded
170    // by the dispatcher. Closures pass `&ctx` to the inner `handle_*` fn.
171    macro_rules! reg {
172        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident| $body:expr) => {{
173            let backend_arc: Arc<B> = Arc::clone(&$backend);
174            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
175                backend_arc,
176                move |$b: Arc<B>, $ci: String, $a: serde_json::Value, $ctx: B::CallerCtx| {
177                    Box::pin(async move { $body }) as HandlerFuture
178                },
179            ));
180            dispatcher.register($method, h);
181        }};
182    }
183
184    // Chat
185    reg!("Chat/get", backend, |b, _ci, a, ctx| {
186        handle_chat_get(&*b, &ctx, a).await
187    });
188    reg!("Chat/changes", backend, |b, _ci, a, ctx| {
189        handle_chat_changes(&*b, &ctx, a).await
190    });
191    reg!("Chat/query", backend, |b, _ci, a, ctx| {
192        handle_chat_query(&*b, &ctx, a).await
193    });
194    reg!("Chat/queryChanges", backend, |b, _ci, a, ctx| {
195        handle_chat_query_changes(&*b, &ctx, a).await
196    });
197    reg!("Chat/set", backend, |b, _ci, a, ctx| {
198        handle_chat_set(&*b, &ctx, a).await
199    });
200    reg!("Chat/typing", backend, |b, _ci, a, ctx| {
201        handle_chat_typing(&*b, &ctx, a).await
202    });
203
204    // Message
205    reg!("Message/get", backend, |b, _ci, a, ctx| {
206        handle_message_get(&*b, &ctx, a).await
207    });
208    reg!("Message/changes", backend, |b, _ci, a, ctx| {
209        handle_message_changes(&*b, &ctx, a).await
210    });
211    reg!("Message/query", backend, |b, _ci, a, ctx| {
212        handle_message_query(&*b, &ctx, a).await
213    });
214    reg!("Message/queryChanges", backend, |b, _ci, a, ctx| {
215        handle_message_query_changes(&*b, &ctx, a).await
216    });
217    reg!("Message/set", backend, |b, _ci, a, ctx| {
218        handle_message_set(&*b, &ctx, a).await
219    });
220
221    // Space
222    reg!("Space/get", backend, |b, _ci, a, ctx| {
223        handle_space_get(&*b, &ctx, a).await
224    });
225    reg!("Space/changes", backend, |b, _ci, a, ctx| {
226        handle_space_changes(&*b, &ctx, a).await
227    });
228    reg!("Space/query", backend, |b, _ci, a, ctx| {
229        handle_space_query(&*b, &ctx, a).await
230    });
231    reg!("Space/queryChanges", backend, |b, _ci, a, ctx| {
232        handle_space_query_changes(&*b, &ctx, a).await
233    });
234    reg!("Space/set", backend, |b, _ci, a, ctx| {
235        handle_space_set(&*b, &ctx, a).await
236    });
237    reg!("Space/join", backend, |b, _ci, a, ctx| {
238        handle_space_join(&*b, &ctx, a).await
239    });
240
241    // ChatContact
242    reg!("ChatContact/get", backend, |b, _ci, a, ctx| {
243        handle_contact_get(&*b, &ctx, a).await
244    });
245    reg!("ChatContact/changes", backend, |b, _ci, a, ctx| {
246        handle_contact_changes(&*b, &ctx, a).await
247    });
248    reg!("ChatContact/query", backend, |b, _ci, a, ctx| {
249        handle_contact_query(&*b, &ctx, a).await
250    });
251    reg!("ChatContact/queryChanges", backend, |b, _ci, a, ctx| {
252        handle_contact_query_changes(&*b, &ctx, a).await
253    });
254    reg!("ChatContact/set", backend, |b, _ci, a, ctx| {
255        handle_contact_set(&*b, &ctx, a).await
256    });
257
258    // ReadPosition
259    reg!("ReadPosition/get", backend, |b, _ci, a, ctx| {
260        handle_position_get(&*b, &ctx, a).await
261    });
262    reg!("ReadPosition/changes", backend, |b, _ci, a, ctx| {
263        handle_position_changes(&*b, &ctx, a).await
264    });
265    reg!("ReadPosition/set", backend, |b, _ci, a, ctx| {
266        handle_position_set(&*b, &ctx, a).await
267    });
268
269    // SpaceInvite
270    reg!("SpaceInvite/get", backend, |b, _ci, a, ctx| {
271        handle_invite_get(&*b, &ctx, a).await
272    });
273    reg!("SpaceInvite/changes", backend, |b, _ci, a, ctx| {
274        handle_invite_changes(&*b, &ctx, a).await
275    });
276    reg!("SpaceInvite/set", backend, |b, _ci, a, ctx| {
277        handle_invite_set(&*b, &ctx, a).await
278    });
279
280    // SpaceBan
281    reg!("SpaceBan/get", backend, |b, _ci, a, ctx| {
282        handle_ban_get(&*b, &ctx, a).await
283    });
284    reg!("SpaceBan/changes", backend, |b, _ci, a, ctx| {
285        handle_ban_changes(&*b, &ctx, a).await
286    });
287    reg!("SpaceBan/set", backend, |b, _ci, a, ctx| {
288        handle_ban_set(&*b, &ctx, a).await
289    });
290
291    // CustomEmoji
292    reg!("CustomEmoji/get", backend, |b, _ci, a, ctx| {
293        handle_emoji_get(&*b, &ctx, a).await
294    });
295    reg!("CustomEmoji/changes", backend, |b, _ci, a, ctx| {
296        handle_emoji_changes(&*b, &ctx, a).await
297    });
298    reg!("CustomEmoji/query", backend, |b, _ci, a, ctx| {
299        handle_emoji_query(&*b, &ctx, a).await
300    });
301    reg!("CustomEmoji/queryChanges", backend, |b, _ci, a, ctx| {
302        handle_emoji_query_changes(&*b, &ctx, a).await
303    });
304    reg!("CustomEmoji/set", backend, |b, _ci, a, ctx| {
305        handle_emoji_set(&*b, &ctx, a).await
306    });
307
308    // PresenceStatus
309    reg!("PresenceStatus/get", backend, |b, _ci, a, ctx| {
310        handle_presence_get(&*b, &ctx, a).await
311    });
312    reg!("PresenceStatus/changes", backend, |b, _ci, a, ctx| {
313        handle_presence_changes(&*b, &ctx, a).await
314    });
315    reg!("PresenceStatus/set", backend, |b, _ci, a, ctx| {
316        handle_presence_set(&*b, &ctx, a).await
317    });
318}
319
320/// Generic closure-to-[`JmapHandler`] adapter from [`jmap_server`].
321///
322/// Re-exported so the [`register_chat_handlers`] macro body can name
323/// `ClosureHandler` without a fully-qualified path. **Stability**: this
324/// re-export pins the major-version contract of [`jmap_server::ClosureHandler`]
325/// into this crate's public surface — a breaking change to that type
326/// upstream is a breaking change here. Consumers needing a closure handler
327/// adapter SHOULD prefer importing from [`jmap_server`] directly; the
328/// re-export is retained primarily for the in-crate macro and for
329/// backward-compatible spelling of the existing handler-registration
330/// pattern.
331pub use jmap_server::ClosureHandler;