Skip to main content

jmap_server/
lib.rs

1//! Backend-agnostic JMAP server framework (RFC 8620).
2//!
3//! Provides request parsing, ResultReference resolution, HTTP response helpers,
4//! the [`Dispatcher`] machinery, shared backend infrastructure, and generic
5//! JMAP method handlers.
6//!
7//! # Version coupling with `jmap-types` (bd:JMAP-wlip.18)
8//!
9//! This crate re-exports the wire-format types from `jmap-types`
10//! (`Id`, `JmapError`, `JmapRequest`, `JmapResponse`, `Invocation`,
11//! `PushSubscription`, `ResultReference`, `Argument`, `State`, `UTCDate`)
12//! plus the marker traits (`GetObject`, `JmapObject`, `QueryObject`,
13//! `SetObject`).
14//! The public API of this crate is therefore *coupled* to
15//! `jmap-types`' public API: any breaking change to a re-exported
16//! type in `jmap-types` is a breaking change here, even when this
17//! crate's own surface is otherwise additive.
18//!
19//! **SemVer pin discipline**: consumers that depend on both
20//! `jmap-server` and `jmap-types` directly MUST pin the `jmap-types`
21//! version to the exact version `jmap-server` resolves to. The
22//! simplest path is to NOT depend on `jmap-types` directly and use
23//! `jmap_server::{Id, JmapError, ...}` instead — re-exports
24//! guarantee consistency. Depending on both with mismatched versions
25//! produces cargo's "expected `jmap_types::Id`, found `jmap_types::Id`"
26//! error (same type name, two different version hashes).
27
28#![forbid(unsafe_code)]
29
30pub use jmap_types::{
31    Argument, Id, Invocation, JmapError, JmapRequest, JmapResponse, PushSubscription,
32    ResultReference, State, UTCDate,
33};
34
35pub mod backend;
36pub mod handlers;
37mod helpers;
38
39pub use backend::{
40    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
41    JmapBackend, JmapObject, QueryChangesResult, QueryObject, QueryResult, ReservedExtrasKey,
42    SetError, SetErrorType, SetObject, RESERVED_SET_ERROR_WIRE_NAMES,
43};
44pub use handlers::{
45    handle_changes, handle_get, handle_query, handle_query_changes, server_fail_from_backend,
46    server_fail_value_from_backend, SERVER_FAIL_INTERNAL_DESC,
47};
48#[allow(deprecated)]
49pub use helpers::ser;
50pub use helpers::{
51    apply_jmap_patch, apply_patch_object, bool_arg, enforce_max_objects_in_get,
52    enforce_max_objects_in_set, extract_account_id, filter_arg, json_merge_patch, not_found_json,
53    now_utc_string, now_utc_string_checked, optional_arg, query_anchor_args, resolve_query_offset,
54    resolve_query_start, serialize_value, take_bool_arg, utc_date_from_epoch_seconds,
55    MergePatchError, PatchPathError,
56};
57
58mod parse;
59mod push;
60mod response;
61
62pub use parse::{check_known_capabilities, parse_request, resolve_args};
63pub use push::{
64    is_deliverable, register_push_subscription_handlers, state_change_for, PushSubscriptionBackend,
65    StoredPushSubscription, MAX_PUSH_EXPIRY_SECS,
66};
67pub use response::{error_invocation, error_status, request_error, RequestError};
68
69use std::{
70    collections::{BTreeMap, HashMap},
71    fmt,
72    future::Future,
73    pin::Pin,
74    sync::Arc,
75};
76
77use serde_json::Value;
78use tokio::task;
79
80/// The successful result of one [`JmapHandler::call`].
81///
82/// `#[non_exhaustive]` so fields can be added without breaking handler
83/// crates; build it with [`HandlerOutput::new`] and
84/// [`HandlerOutput::with_extra`].
85#[derive(Debug, Clone, PartialEq)]
86#[non_exhaustive]
87pub struct HandlerOutput {
88    /// The method's response arguments. The dispatcher pairs this with the
89    /// call's method name and call id as the primary response invocation.
90    pub primary: Value,
91    /// Zero or more invocations appended to `methodResponses` immediately
92    /// after the primary response, in order. Most handlers leave this
93    /// empty. RFC 8621 §7.5 `EmailSubmission/set` uses it for the implicit
94    /// `Email/set` response for `onSuccessUpdateEmail`.
95    pub extra_invocations: Vec<Invocation>,
96}
97
98impl HandlerOutput {
99    /// A handler result with only a primary response.
100    pub fn new(primary: Value) -> Self {
101        Self {
102            primary,
103            extra_invocations: Vec::new(),
104        }
105    }
106
107    /// Set the invocations to append after the primary response.
108    pub fn with_extra(mut self, extra_invocations: Vec<Invocation>) -> Self {
109        self.extra_invocations = extra_invocations;
110        self
111    }
112}
113
114/// The return type for all [`JmapHandler`] implementations.
115///
116/// Handlers must return a `Send` future.  The concrete type is a heap-allocated
117/// trait object so the trait itself remains object-safe.
118pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<HandlerOutput, JmapError>> + Send>>;
119
120/// Implement this for each JMAP method handler.
121///
122/// `CallerCtx` is whatever your auth layer produces — an `Identity`, a session
123/// token, `()`, etc. The dispatcher passes it through unchanged.
124///
125/// # /set response contract
126///
127/// Handlers for `/set` methods (RFC 8620 §5.3) that create objects MUST include
128/// an `"id"` field (type string) in each entry of the `"created"` map.  The
129/// dispatcher reads this field to accumulate `createdIds` in the response.
130/// Entries without an `"id"` field are silently skipped — the dispatcher cannot
131/// retroactively error a method call that already returned success.
132pub trait JmapHandler<CallerCtx>: Send + Sync {
133    /// `method` is the registered method name for this call.  A single handler
134    /// instance may be registered under multiple names (e.g. both `"Foo/get"` and
135    /// `"Bar/get"`); this parameter lets the handler distinguish between them.
136    ///
137    /// `call_id` is the client-supplied identifier for this invocation (RFC 8620 §3.3).
138    /// Handlers may use it for logging or correlation but need not echo it —
139    /// the dispatcher echoes it in the response automatically.
140    ///
141    /// Both parameters are `String` (not `&str`) because the returned future is
142    /// `'static` — it must own all data it captures.  Handlers that do not need
143    /// `method`/`call_id` can ignore them; handlers that do (e.g. echo) simply
144    /// capture the owned value.
145    fn call(
146        &self,
147        method: String,
148        call_id: String,
149        args: Value,
150        caller: CallerCtx,
151    ) -> HandlerFuture;
152}
153
154/// Walk a `/set` handler's primary response and accumulate every
155/// `created[client_id].id` pair into `sink` (RFC 8620 §3.4
156/// `createdIds`) (bd:JMAP-wlip.10).
157///
158/// Lives next to the [`JmapHandler`] doc contract that requires
159/// every entry of `created` to contain a string `"id"` field. Entries
160/// that violate the contract — no `"id"` key, or an `"id"` of a
161/// non-string type — are silently skipped, because the dispatcher
162/// cannot produce a method-level error for a method call that already
163/// succeeded. The shared helper makes the silent-skip behaviour
164/// auditable in one place rather than inlined in the dispatcher loop.
165///
166/// Non-`/set` primary responses (no `"created"` key at the top level,
167/// or `"created"` of a non-Object type) leave `sink` unchanged.
168///
169/// Collision semantics (bd:JMAP-jfia.3): when a creationId in the
170/// `/set` response collides with an entry already in `sink` — whether
171/// from an earlier `/set` call in the same batch OR from the client's
172/// pre-populated `createdIds` map — `BTreeMap::insert` silently
173/// overwrites: last write wins. The pre-populated collision case is
174/// exercised by
175/// [`tests::created_ids_pre_populated_collision_last_write_wins`].
176/// See the dispatcher call site for the full rationale.
177fn extract_created_ids_into(primary: &Value, sink: &mut BTreeMap<Id, Id>) {
178    let Some(map) = primary.get("created").and_then(|v| v.as_object()) else {
179        return;
180    };
181    for (client_id, created_obj) in map {
182        if let Some(id_val) = created_obj.get("id").and_then(|v| v.as_str()) {
183            sink.insert(Id::from(client_id.as_str()), Id::from(id_val));
184        }
185    }
186}
187
188/// Dispatches a [`JmapRequest`] to registered method handlers.
189///
190/// Register handlers with [`Dispatcher::register`], then call
191/// [`Dispatcher::dispatch`] per request.  `CallerCtx` is cloned for each
192/// method call in the batch, so it must be `Clone`.
193///
194/// `CallerCtx` must also be `'static` because each handler call is spawned as
195/// a [`tokio::task`].  To share non-static data (e.g. a database connection),
196/// wrap it in `Arc<T>` — `Arc` is `Clone + Send + 'static` when `T: Send + Sync`.
197///
198/// # Thread safety
199///
200/// `Dispatcher` is both `Send` and `Sync`.  Register handlers on one thread,
201/// then wrap in `Arc` and share across tasks — `dispatch` takes `&self` and is
202/// safe to call concurrently.
203pub struct Dispatcher<CallerCtx> {
204    handlers: HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>,
205}
206
207/// Returned by [`Dispatcher::try_register`] when a handler is already
208/// registered under the requested method name.
209///
210/// Added in bd:JMAP-jfia.4 alongside `try_register` to make the
211/// duplicate-registration foot-gun explicit at the call site rather
212/// than silently dropping a binding.
213#[non_exhaustive]
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct DuplicateMethodError {
216    /// The method name that was already registered.
217    pub method: String,
218}
219
220impl std::fmt::Display for DuplicateMethodError {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        write!(f, "handler already registered for method {:?}", self.method)
223    }
224}
225
226impl std::error::Error for DuplicateMethodError {}
227
228impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx> {
229    /// Create an empty dispatcher with no registered handlers.
230    pub fn new() -> Self {
231        Self {
232            handlers: HashMap::new(),
233        }
234    }
235
236    /// Register a handler for the given method name.
237    ///
238    /// **Registering the same name twice silently replaces the earlier
239    /// handler.** This is a real foot-gun in the workspace pattern where
240    /// each extension crate ships a `register_*_handlers` macro that
241    /// registers ~10 method names against a single `Dispatcher`: a typo
242    /// or accidental double-registration drops one binding with no
243    /// diagnostic, and the handler that "never fires" is hard to debug
244    /// (bd:JMAP-jfia.4). Prefer [`Dispatcher::try_register`] in new
245    /// code; `register` is kept for ergonomic call sites where the
246    /// silent-overwrite is the deliberate choice (e.g. a test fixture
247    /// that overrides a handler for a specific scenario).
248    ///
249    /// Using `Arc` rather than `Box` allows the same handler instance to be
250    /// shared across multiple method name registrations (via `Arc::clone`).
251    pub fn register(
252        &mut self,
253        method: impl Into<String>,
254        handler: Arc<dyn JmapHandler<CallerCtx>>,
255    ) {
256        self.handlers.insert(method.into(), handler);
257    }
258
259    /// Register a handler for the given method name, returning an error
260    /// if the method name is already registered.
261    ///
262    /// This is the recommended registration entry point for production
263    /// code paths (bd:JMAP-jfia.4). Unlike [`Dispatcher::register`], a
264    /// duplicate method name produces
265    /// [`DuplicateMethodError`] rather than silently replacing the
266    /// existing handler, surfacing the collision at the call site that
267    /// caused it.
268    ///
269    /// On `Err(DuplicateMethodError)` the dispatcher's handler map is
270    /// left unchanged — the existing handler is preserved and the
271    /// would-be registration is dropped.
272    ///
273    /// Using `Arc` rather than `Box` allows the same handler instance to be
274    /// shared across multiple method name registrations (via `Arc::clone`).
275    ///
276    /// # Errors
277    ///
278    /// Returns [`DuplicateMethodError`] when `method` is already
279    /// registered.
280    pub fn try_register(
281        &mut self,
282        method: impl Into<String>,
283        handler: Arc<dyn JmapHandler<CallerCtx>>,
284    ) -> Result<(), DuplicateMethodError> {
285        let method = method.into();
286        if self.handlers.contains_key(&method) {
287            return Err(DuplicateMethodError { method });
288        }
289        self.handlers.insert(method, handler);
290        Ok(())
291    }
292
293    /// Process a validated [`JmapRequest`] and return a [`JmapResponse`].
294    ///
295    /// Method calls are processed sequentially per RFC 8620 §3.3.  Each
296    /// handler runs in a `tokio::task::spawn` for panic isolation: a panicking
297    /// handler returns a `serverFail` invocation rather than crashing the
298    /// connection task.
299    ///
300    /// `CallerCtx` must be `Clone + Send + 'static`; see the struct-level doc.
301    ///
302    /// # Runtime requirement (bd:JMAP-jfia.24)
303    ///
304    /// `dispatch` invokes [`tokio::task::spawn`] internally and
305    /// therefore **requires a Tokio runtime in scope at the call
306    /// site**. The async-fn signature itself does not advertise this
307    /// requirement — there is no `?Send` async-trait bound and no
308    /// `Spawner` parameter — but calling `dispatch` without a Tokio
309    /// runtime will panic at the first method call with a
310    /// `there is no reactor running` error.
311    ///
312    /// This is a structural coupling to the Tokio ecosystem.
313    /// Production consumers running under `tokio::main` /
314    /// `Runtime::block_on` already satisfy this; consumers
315    /// experimenting with alternative runtimes (`async-std`,
316    /// `smol`, `embassy`, etc.) cannot use `Dispatcher` without
317    /// either a Tokio compat shim or a custom dispatcher
318    /// re-implementation. Decoupling the spawn mechanism is a
319    /// major-bump API change tracked separately.
320    ///
321    /// # Cancellation
322    ///
323    /// **Per-request cancellation is not supported in the current API**
324    /// (bd:JMAP-wlip.23). If this future is dropped while a handler
325    /// task is running (e.g., the HTTP connection closes), the spawned
326    /// [`tokio::task`] runs to completion — tokio does not cancel
327    /// tasks when their `JoinHandle` is dropped. The handler result
328    /// is discarded.
329    ///
330    /// Production consequence: a JMAP server with a long-running
331    /// backend operation (e.g., `Email/query` over a 10M-mailbox
332    /// account, a slow full-text search, a slow downstream-service
333    /// lookup) cannot react to client disconnect. Every disconnect
334    /// leaks resource consumption equal to the full backend cost.
335    /// Adversarial clients can amplify this into a DoS by opening
336    /// many requests and dropping them.
337    ///
338    /// Recommended mitigations until per-request cancellation is wired:
339    ///
340    /// - **Bound each backend operation's runtime at the backend
341    ///   layer**, e.g. by passing a deadline / timeout from the
342    ///   backend impl's storage client (`tokio::time::timeout` around
343    ///   each database call, RPC deadline, etc.). The handler does
344    ///   not need to know about deadlines; the backend impl does.
345    /// - **Server-wide shutdown** via `tokio::select!` with a
346    ///   broadcast channel from `main` works for the dispatcher loop
347    ///   itself but does NOT propagate into spawned handler tasks.
348    ///   To shut down cleanly, drain the dispatcher first and then
349    ///   let in-flight handler tasks finish.
350    ///
351    /// The "implement cancellation at the handler level" advice
352    /// previously given here was unworkable: the spawned task has
353    /// no access to the outer dispatch-future's context (no token,
354    /// no shared liveness flag), and the [`JmapHandler::call`]
355    /// signature carries no cancellation token.
356    ///
357    /// A future revision may add an opt-in cancellation-token shape
358    /// (CallerCtx-carried token, or a dispatch-time
359    /// `cancel: CancellationToken` parameter that gets signalled on
360    /// future-drop). That is a workspace-architectural decision —
361    /// adding `tokio_util` to the dep allowlist plus threading the
362    /// token through every backend trait method — and is tracked
363    /// separately.
364    pub async fn dispatch(
365        &self,
366        request: JmapRequest,
367        caller: CallerCtx,
368        session_state: State,
369    ) -> JmapResponse {
370        let mut method_responses: Vec<Invocation> = Vec::with_capacity(request.method_calls.len());
371        let client_sent_created_ids = request.created_ids.is_some();
372        let mut created_ids: BTreeMap<Id, Id> = request.created_ids.unwrap_or_default();
373
374        for Invocation {
375            name: method,
376            arguments: mut args,
377            call_id,
378        } in request.method_calls
379        {
380            // Resolve ResultReferences from prior responses.
381            if let Err(e) = resolve_args(&mut args, &method_responses) {
382                method_responses.push(error_invocation(&call_id, e));
383                continue;
384            }
385
386            // Look up the handler.
387            let Some(handler) = self.handlers.get(&method).map(Arc::clone) else {
388                method_responses.push(error_invocation(&call_id, JmapError::unknown_method()));
389                continue;
390            };
391
392            let caller_clone = caller.clone();
393            let method_clone = method.clone();
394            let call_id_clone = call_id.clone();
395
396            // Run in a spawned task for panic isolation.
397            let result: Result<Result<HandlerOutput, JmapError>, tokio::task::JoinError> =
398                task::spawn(async move {
399                    handler
400                        .call(method_clone, call_id_clone, args, caller_clone)
401                        .await
402                })
403                .await;
404
405            match result {
406                Ok(Ok(HandlerOutput {
407                    primary: primary_value,
408                    extra_invocations,
409                })) => {
410                    // Accumulate createdIds from /set responses (RFC 8620 §3.4).
411                    // Only when the client sent createdIds; otherwise the field
412                    // is omitted from the response.
413                    //
414                    // Duplicate-creationId behaviour (bd:JMAP-wlip.7,
415                    // bd:JMAP-jfia.3): BTreeMap::insert silently overwrites
416                    // on duplicate key. Two flavours of duplicate:
417                    //
418                    //   (a) Intra-batch: a client reuses the same
419                    //   creationId across two /set calls in the same
420                    //   batch (e.g. "c1" in both Mailbox/set and
421                    //   Email/set). The second mapping wins and the
422                    //   first is lost.
423                    //
424                    //   (b) Pre-populated collision: a client
425                    //   pre-populates createdIds with X->A and a /set
426                    //   call in the same batch returns X->B (B != A).
427                    //   The /set value wins and the pre-populated A is
428                    //   lost. This is reachable via long-lived
429                    //   background tasks replaying a queued request
430                    //   whose creationIds overlap with the current
431                    //   session's batch.
432                    //
433                    // RFC 8620 §3.4 does not explicitly require either
434                    // last-write-wins or rejection; the convention here
435                    // is last-write-wins because (a) the response order
436                    // is deterministic so the behaviour is at least
437                    // reproducible, (b) detecting either flavour of
438                    // duplicate would require either a per-batch
439                    // creationId pre-check (adds a HashSet allocation
440                    // per request) or a second pass over
441                    // method_responses after dispatch, and (c) this
442                    // crate is the canonical foundation for every
443                    // *-server extension — a wire-behaviour change
444                    // (e.g. reject-on-collision) would ripple to every
445                    // downstream consumer and is out of scope for a
446                    // foundation crate without an RFC mandate.
447                    //
448                    // Clients SHOULD generate unique creationIds across
449                    // a batch and SHOULD NOT pre-populate creationIds
450                    // that any /set call in the same batch will
451                    // produce. Both collision flavours are exercised
452                    // explicitly by
453                    // [`tests::created_ids_intra_batch_collision_last_write_wins`]
454                    // and
455                    // [`tests::created_ids_pre_populated_collision_last_write_wins`]
456                    // so a future refactor that flips the order is
457                    // caught.
458                    if client_sent_created_ids {
459                        extract_created_ids_into(&primary_value, &mut created_ids);
460                    }
461                    // Push the primary response first, then any extra invocations
462                    // appended by the handler (e.g. onSuccessUpdateEmail from
463                    // EmailSubmission/set, RFC 8621 §7.5).  Order is preserved.
464                    method_responses.push(Invocation::new(method, primary_value, call_id));
465                    method_responses.extend(extra_invocations);
466                }
467                Ok(Err(e)) => {
468                    method_responses.push(error_invocation(&call_id, e));
469                }
470                Err(join_err) => {
471                    // Panics and cancellations both map to serverFail, but with
472                    // distinct descriptions to aid server-side diagnostics.
473                    let desc = if join_err.is_cancelled() {
474                        "task cancelled"
475                    } else {
476                        "internal error"
477                    };
478                    method_responses.push(error_invocation(&call_id, JmapError::server_fail(desc)));
479                }
480            }
481        }
482
483        let created_ids = client_sent_created_ids.then_some(created_ids);
484
485        JmapResponse::new(method_responses, session_state, created_ids)
486    }
487}
488
489impl<CallerCtx: Clone + Send + 'static> Default for Dispatcher<CallerCtx> {
490    fn default() -> Self {
491        Self::new()
492    }
493}
494
495impl<CallerCtx> fmt::Debug for Dispatcher<CallerCtx> {
496    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497        f.debug_struct("Dispatcher")
498            .field("methods", &self.handlers.keys())
499            .finish()
500    }
501}
502
503// ---------------------------------------------------------------------------
504// ClosureHandler — generic backend-wrapping JmapHandler that forwards CallerCtx
505// ---------------------------------------------------------------------------
506
507/// Type alias for the closure stored inside [`ClosureHandler`].
508///
509/// The `String` argument is the `call_id` (the client-supplied correlation
510/// identifier from RFC 8620 §3.3), not the method name.  If you need the
511/// method name inside the closure, register the handler with
512/// [`Dispatcher::register`] and use [`JmapHandler`] directly instead.
513///
514/// `C` is the caller context (e.g. an auth identity) forwarded from
515/// [`Dispatcher::dispatch`]. Closures that don't need it can ignore the
516/// argument with `_ctx`.
517pub type BackendCallFn<B, C> =
518    dyn Fn(Arc<B>, String, serde_json::Value, C) -> HandlerFuture + Send + Sync + 'static;
519
520/// A [`JmapHandler`] that wraps an async closure over a shared backend and
521/// forwards `CallerCtx` to it.
522///
523/// Use this when your handler closures need per-request context — for
524/// example, an auth identity that controls which data the handler can
525/// access. Closures that don't need the context can simply ignore the
526/// `ctx` parameter.
527///
528/// # Usage
529///
530/// ```rust,ignore
531/// use jmap_server::{ClosureHandler, Dispatcher};
532/// use std::sync::Arc;
533///
534/// #[derive(Clone)]
535/// struct AuthCtx { user_id: String }
536///
537/// let handler: Arc<ClosureHandler<MyBackend, AuthCtx>> =
538///     Arc::new(ClosureHandler::new(
539///         Arc::new(my_backend),
540///         |b, call_id, args, ctx| {
541///             Box::pin(async move {
542///                 // ctx.user_id is available here
543///                 handle_something(&*b, args, &ctx.user_id).await
544///             })
545///         },
546///     ));
547///
548/// let mut dispatcher: Dispatcher<AuthCtx> = Dispatcher::new();
549/// dispatcher.register("MyMethod/get", handler);
550/// ```
551/// A [`JmapHandler`] handle wrapping a shared backend + an async
552/// closure. Construct via [`ClosureHandler::new`] — the fields are
553/// crate-private (bd:JMAP-jfia.5) to keep the handle opaque, prevent
554/// post-construction hot-swap of the closure or backend, and let the
555/// constructor remain the sole site that enforces invariants when
556/// future fields (per-handler tracing context, metrics handle, etc.)
557/// are added.
558#[non_exhaustive]
559pub struct ClosureHandler<B: Send + Sync + 'static, C: Clone + Send + 'static> {
560    /// Shared reference to the backend implementation, passed to the
561    /// closure on every method call. Crate-private to keep
562    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
563    pub(crate) backend: Arc<B>,
564    /// The async closure invoked for each JMAP method call this handler
565    /// receives from the dispatcher. Crate-private to keep
566    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
567    pub(crate) call_fn: Box<BackendCallFn<B, C>>,
568}
569
570impl<B: Send + Sync + 'static, C: Clone + Send + 'static> ClosureHandler<B, C> {
571    /// Construct a [`ClosureHandler`] wrapping a shared backend and an
572    /// async closure (bd:JMAP-wlip.17).
573    ///
574    /// This is the supported construction path. The struct is
575    /// `#[non_exhaustive]` so future fields (per-handler tracing
576    /// context, metrics handle, timeout, etc.) can be added without a
577    /// major-version bump — external callers MUST go through `new`
578    /// rather than struct-literal syntax.
579    ///
580    /// The `call_fn` parameter is generic over
581    /// `F: Fn(...) + Send + Sync + 'static` (bd:JMAP-jfia.40), so
582    /// callers can pass a closure directly without wrapping it in
583    /// `Box::new`. Existing callers that already wrap in
584    /// `Box::new(...)` continue to compile unchanged:
585    /// `Box<dyn Fn(...) + Send + Sync + 'static>` itself implements
586    /// `Fn(...)` via the blanket
587    /// `impl<F: Fn(...)> Fn(...) for Box<F>`, so the boxed form
588    /// satisfies the generic bound. Internally, the closure is boxed
589    /// once at construction and stored as
590    /// `Box<BackendCallFn<B, C>>`.
591    pub fn new<F>(backend: Arc<B>, call_fn: F) -> Self
592    where
593        F: Fn(Arc<B>, String, serde_json::Value, C) -> HandlerFuture + Send + Sync + 'static,
594    {
595        Self {
596            backend,
597            call_fn: Box::new(call_fn),
598        }
599    }
600}
601
602impl<B: Send + Sync + 'static, C: Clone + Send + 'static> JmapHandler<C> for ClosureHandler<B, C> {
603    fn call(
604        &self,
605        _method: String,
606        call_id: String,
607        args: serde_json::Value,
608        caller: C,
609    ) -> HandlerFuture {
610        (self.call_fn)(Arc::clone(&self.backend), call_id, args, caller)
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use super::*;
617    use serde_json::{json, Value};
618    use std::sync::{Arc, Mutex};
619
620    // Compile-time: Dispatcher must be Send + Sync so it can be wrapped in Arc
621    // and shared across tokio tasks.  This assertion catches future regressions
622    // that would silently break thread-safety (e.g., adding a Cell or Rc field).
623    #[allow(dead_code)]
624    fn assert_dispatcher_send_sync() {
625        fn check<T: Send + Sync>() {}
626        check::<Dispatcher<String>>();
627        check::<Dispatcher<()>>();
628    }
629
630    // -----------------------------------------------------------------------
631    // Test handler implementations
632    // -----------------------------------------------------------------------
633
634    /// Returns a fixed Value regardless of inputs.
635    struct EchoHandler(Value);
636
637    impl<C: Clone + Send + 'static> JmapHandler<C> for EchoHandler {
638        fn call(
639            &self,
640            _method: String,
641            _call_id: String,
642            _args: Value,
643            _caller: C,
644        ) -> HandlerFuture {
645            let v = self.0.clone();
646            Box::pin(async move { Ok(HandlerOutput::new(v)) })
647        }
648    }
649
650    /// Returns a fixed error.
651    struct ErrorHandler(JmapError);
652
653    impl JmapHandler<String> for ErrorHandler {
654        fn call(
655            &self,
656            _method: String,
657            _call_id: String,
658            _args: Value,
659            _caller: String,
660        ) -> HandlerFuture {
661            let e = self.0.clone();
662            Box::pin(async move { Err(e) })
663        }
664    }
665
666    /// Captures the resolved args it was called with.
667    struct CaptureArgsHandler(Arc<Mutex<Option<Value>>>);
668
669    impl JmapHandler<String> for CaptureArgsHandler {
670        fn call(
671            &self,
672            _method: String,
673            _call_id: String,
674            args: Value,
675            _caller: String,
676        ) -> HandlerFuture {
677            let slot = self.0.clone();
678            Box::pin(async move {
679                *slot.lock().expect("test: mutex poisoned") = Some(args);
680                Ok(HandlerOutput::new(json!({})))
681            })
682        }
683    }
684
685    /// Captures the caller value it was called with.
686    struct CaptureCallerHandler(Arc<Mutex<Option<String>>>);
687
688    impl JmapHandler<String> for CaptureCallerHandler {
689        fn call(
690            &self,
691            _method: String,
692            _call_id: String,
693            _args: Value,
694            caller: String,
695        ) -> HandlerFuture {
696            let slot = self.0.clone();
697            Box::pin(async move {
698                *slot.lock().expect("test: mutex poisoned") = Some(caller);
699                Ok(HandlerOutput::new(json!({})))
700            })
701        }
702    }
703
704    /// Panics unconditionally.
705    struct PanicHandler;
706
707    impl JmapHandler<String> for PanicHandler {
708        fn call(
709            &self,
710            _method: String,
711            _call_id: String,
712            _args: Value,
713            _caller: String,
714        ) -> HandlerFuture {
715            Box::pin(async move { panic!("deliberate test panic") })
716        }
717    }
718
719    // -----------------------------------------------------------------------
720    // Helper: build a minimal JmapRequest with a single method call.
721    // -----------------------------------------------------------------------
722
723    fn single_call(method: &str, args: Value, call_id: &str) -> JmapRequest {
724        JmapRequest::new(
725            vec!["urn:ietf:params:jmap:core".into()],
726            vec![Invocation::new(method, args, call_id)],
727            None,
728        )
729    }
730
731    // -----------------------------------------------------------------------
732    // Basic dispatch
733    // -----------------------------------------------------------------------
734
735    /// Oracle: RFC 8620 §7.1 — unknownMethod when no handler is registered.
736    #[tokio::test]
737    async fn unknown_method_returns_error_invocation() {
738        let d: Dispatcher<String> = Dispatcher::new();
739        let req = single_call("Foo/get", json!({}), "c0");
740        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
741        assert_eq!(resp.method_responses.len(), 1);
742        let Invocation {
743            arguments: args,
744            call_id,
745            ..
746        } = &resp.method_responses[0];
747        assert_eq!(call_id, "c0");
748        assert_eq!(args["type"], "unknownMethod");
749    }
750
751    /// Oracle: RFC 8620 §3.5 — successful call appears in methodResponses.
752    #[tokio::test]
753    async fn known_method_success() {
754        let mut d: Dispatcher<String> = Dispatcher::new();
755        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
756        let req = single_call("Foo/get", json!({}), "c1");
757        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
758        assert_eq!(resp.method_responses.len(), 1);
759        let Invocation {
760            name: method,
761            arguments: args,
762            call_id,
763        } = &resp.method_responses[0];
764        assert_eq!(method, "Foo/get");
765        assert_eq!(call_id, "c1");
766        assert_eq!(args["list"], json!([]));
767    }
768
769    /// Oracle: RFC 8620 §3.6.2 — method-level errors appear in methodResponses.
770    #[tokio::test]
771    async fn handler_returns_error() {
772        let mut d: Dispatcher<String> = Dispatcher::new();
773        d.register("Foo/get", Arc::new(ErrorHandler(JmapError::not_found())));
774        let req = single_call("Foo/get", json!({}), "c2");
775        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
776        assert_eq!(resp.method_responses.len(), 1);
777        let Invocation {
778            arguments: args, ..
779        } = &resp.method_responses[0];
780        assert_eq!(args["type"], "notFound");
781    }
782
783    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
784    /// "The following additional errors may be returned instead of the
785    /// "Foo/set" response: "requestTooLarge": The total number of objects
786    /// to create, update, or destroy exceeds the maximum number the server
787    /// is willing to process in a single method call." The over-cap
788    /// Foo/set gets an "error" invocation of type requestTooLarge in
789    /// place of its response, and the next method call in the same
790    /// request still runs.
791    #[tokio::test]
792    async fn set_over_max_objects_is_method_error_request_too_large() {
793        struct CappedSetHandler;
794
795        impl JmapHandler<String> for CappedSetHandler {
796            fn call(
797                &self,
798                _method: String,
799                _call_id: String,
800                args: Value,
801                _caller: String,
802            ) -> HandlerFuture {
803                Box::pin(async move {
804                    let map = args.as_object().cloned().unwrap_or_default();
805                    enforce_max_objects_in_set(&map, 1)?;
806                    Ok(HandlerOutput::new(json!({"created": {}})))
807                })
808            }
809        }
810
811        let mut d: Dispatcher<String> = Dispatcher::new();
812        d.register("Foo/set", Arc::new(CappedSetHandler));
813        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
814        let req = JmapRequest::new(
815            vec!["urn:ietf:params:jmap:core".into()],
816            vec![
817                Invocation::new(
818                    "Foo/set",
819                    json!({"accountId": "a1", "destroy": ["x1", "x2"]}),
820                    "c0",
821                ),
822                Invocation::new("Foo/get", json!({"accountId": "a1"}), "c1"),
823            ],
824            None,
825        );
826        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
827        assert_eq!(resp.method_responses.len(), 2);
828        let Invocation {
829            name,
830            arguments: args,
831            call_id,
832        } = &resp.method_responses[0];
833        assert_eq!(name, "error");
834        assert_eq!(call_id, "c0");
835        assert_eq!(args["type"], "requestTooLarge");
836        let Invocation {
837            name,
838            arguments: args,
839            call_id,
840        } = &resp.method_responses[1];
841        assert_eq!(name, "Foo/get");
842        assert_eq!(call_id, "c1");
843        assert_eq!(args["list"], json!([]));
844    }
845
846    /// Oracle (bd:JMAP-jfia.4): try_register MUST return Ok for the
847    /// first registration of a method name, and Err(DuplicateMethodError)
848    /// for any subsequent registration of the same name. On Err the
849    /// dispatcher's handler map MUST be left unchanged — the
850    /// already-registered handler stays in place.
851    #[tokio::test]
852    async fn try_register_succeeds_then_errors_on_duplicate() {
853        let mut d: Dispatcher<String> = Dispatcher::new();
854        let first = Arc::new(EchoHandler(json!({"v": "first"})));
855        let second = Arc::new(EchoHandler(json!({"v": "second"})));
856
857        d.try_register("Foo/get", first)
858            .expect("first registration must succeed");
859
860        let err = d
861            .try_register("Foo/get", second)
862            .expect_err("second registration must error");
863        assert_eq!(err.method, "Foo/get");
864        assert_eq!(
865            err.to_string(),
866            "handler already registered for method \"Foo/get\""
867        );
868
869        // The first handler MUST still be the one that fires — try_register
870        // must NOT have replaced it as a side-effect of the error path.
871        let req = single_call("Foo/get", json!({}), "c0");
872        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
873        let Invocation {
874            arguments: args, ..
875        } = &resp.method_responses[0];
876        assert_eq!(
877            args["v"], "first",
878            "try_register error path must not replace the existing handler"
879        );
880    }
881
882    /// Oracle (bd:JMAP-jfia.4): register (the silent-overwrite variant)
883    /// MUST continue to replace on duplicate, since established consumers
884    /// depend on that ergonomic for test fixtures. Pins the contract so
885    /// a future refactor that "fixes" register's silent overwrite is
886    /// caught.
887    #[tokio::test]
888    async fn register_silently_overwrites_on_duplicate() {
889        let mut d: Dispatcher<String> = Dispatcher::new();
890        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "first"}))));
891        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "second"}))));
892
893        let req = single_call("Foo/get", json!({}), "c0");
894        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
895        let Invocation {
896            arguments: args, ..
897        } = &resp.method_responses[0];
898        assert_eq!(args["v"], "second", "register must replace on duplicate");
899    }
900
901    /// Oracle: RFC 8620 §3.4 — sessionState in response matches what dispatcher was given.
902    #[tokio::test]
903    async fn session_state_echoed() {
904        let d: Dispatcher<String> = Dispatcher::new();
905        let req = JmapRequest::new(vec!["urn:ietf:params:jmap:core".into()], vec![], None);
906        let resp = d.dispatch(req, "alice".into(), "my-state-123".into()).await;
907        assert_eq!(resp.session_state.as_ref(), "my-state-123");
908    }
909
910    // -----------------------------------------------------------------------
911    // Batch
912    // -----------------------------------------------------------------------
913
914    /// Oracle: RFC 8620 §3.3 — methodCalls processed in order, all responses present.
915    /// Also covers: error in one method does not abort the batch (RFC 8620 §3.6.2).
916    #[tokio::test]
917    async fn mixed_batch_all_responses_in_order() {
918        let mut d: Dispatcher<String> = Dispatcher::new();
919        d.register("M/a", Arc::new(EchoHandler(json!({"ok": true}))));
920        // "M/b" is NOT registered → unknownMethod
921        let req = JmapRequest::new(
922            vec!["urn:ietf:params:jmap:core".into()],
923            vec![
924                Invocation::new("M/a", json!({}), "c0"),
925                Invocation::new("M/b", json!({}), "c1"),
926                Invocation::new("M/a", json!({}), "c2"),
927            ],
928            None,
929        );
930        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
931        assert_eq!(
932            resp.method_responses.len(),
933            3,
934            "all three calls must produce a response"
935        );
936        // responses[0]: M/a success
937        assert_eq!(resp.method_responses[0].call_id, "c0");
938        assert!(
939            resp.method_responses[0].arguments.get("type").is_none(),
940            "c0 must not be an error"
941        );
942        // responses[1]: M/b unknownMethod
943        assert_eq!(resp.method_responses[1].call_id, "c1");
944        assert_eq!(resp.method_responses[1].arguments["type"], "unknownMethod");
945        // responses[2]: M/a success (error in [1] did not abort the batch)
946        assert_eq!(resp.method_responses[2].call_id, "c2");
947        assert!(
948            resp.method_responses[2].arguments.get("type").is_none(),
949            "c2 must not be an error"
950        );
951    }
952
953    /// Oracle: RFC 8620 §3.6.2 — error in one method does not abort subsequent calls.
954    #[tokio::test]
955    async fn error_does_not_abort_subsequent_calls() {
956        let mut d: Dispatcher<String> = Dispatcher::new();
957        d.register("M/ok", Arc::new(EchoHandler(json!({"ok": true}))));
958        d.register("M/err", Arc::new(ErrorHandler(JmapError::forbidden())));
959        let req = JmapRequest::new(
960            vec!["urn:ietf:params:jmap:core".into()],
961            vec![
962                Invocation::new("M/err", json!({}), "c0"),
963                Invocation::new("M/ok", json!({}), "c1"),
964            ],
965            None,
966        );
967        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
968        assert_eq!(resp.method_responses.len(), 2);
969        assert_eq!(resp.method_responses[0].arguments["type"], "forbidden");
970        assert!(
971            resp.method_responses[1].arguments.get("type").is_none(),
972            "second call must succeed"
973        );
974    }
975
976    // -----------------------------------------------------------------------
977    // Panic isolation
978    // -----------------------------------------------------------------------
979
980    /// Oracle: RFC 8620 §7.1 serverFail; PLAN.md panic isolation design decision.
981    #[tokio::test]
982    async fn panicking_handler_returns_server_fail() {
983        let mut d: Dispatcher<String> = Dispatcher::new();
984        d.register("Panic/now", Arc::new(PanicHandler));
985        let req = single_call("Panic/now", json!({}), "c0");
986        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
987        assert_eq!(resp.method_responses.len(), 1);
988        let Invocation {
989            arguments: args, ..
990        } = &resp.method_responses[0];
991        assert_eq!(
992            args["type"], "serverFail",
993            "panicking handler must produce serverFail"
994        );
995    }
996
997    /// Oracle (bd:JMAP-wlip.12): security invariant — panic payloads
998    /// may contain secrets and MUST NOT leak through ANY field of the
999    /// error invocation, not just `description`. A future refactor that
1000    /// surfaces panic-payload text through a typed `context`, an
1001    /// `innerError` nested object, or any other field would slip past a
1002    /// single-field check.
1003    ///
1004    /// The assertion walks the entire methodResponse args Value
1005    /// recursively and asserts that no string anywhere in the tree
1006    /// contains the canary `"deliberate test panic"` from
1007    /// [`PanicHandler`].
1008    ///
1009    /// **Decision record (bd:JMAP-jfia.14)**: a future "simplify" pass
1010    /// will reasonably suggest narrowing this to a single-field check
1011    /// against `args["description"]` because that is where panic
1012    /// payloads land today. That suggestion is **WRONG** and must be
1013    /// rejected: a single-field check encodes the current
1014    /// implementation rather than the security invariant. The
1015    /// recursive walk encodes the actual invariant ("panic-payload
1016    /// text does not leak to the wire, ANYWHERE in the response shape")
1017    /// and survives refactors of the error shape. Defending this
1018    /// shape protects the workspace credential/PII redaction policy
1019    /// from drift.
1020    #[tokio::test]
1021    async fn panic_message_not_in_response() {
1022        /// Returns `true` iff any `Value::String` in the tree
1023        /// contains `needle`.
1024        fn value_contains_recursive(v: &Value, needle: &str) -> bool {
1025            match v {
1026                Value::String(s) => s.contains(needle),
1027                Value::Array(arr) => arr.iter().any(|x| value_contains_recursive(x, needle)),
1028                Value::Object(o) => o.values().any(|x| value_contains_recursive(x, needle)),
1029                Value::Null | Value::Bool(_) | Value::Number(_) => false,
1030            }
1031        }
1032
1033        let mut d: Dispatcher<String> = Dispatcher::new();
1034        d.register("Panic/now", Arc::new(PanicHandler));
1035        let req = single_call("Panic/now", json!({}), "c0");
1036        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1037        let Invocation {
1038            arguments: args, ..
1039        } = &resp.method_responses[0];
1040        assert!(
1041            !value_contains_recursive(args, "deliberate test panic"),
1042            "panic message must not leak into ANY field of the response: {args}"
1043        );
1044    }
1045
1046    // -----------------------------------------------------------------------
1047    // ResultReference end-to-end
1048    // -----------------------------------------------------------------------
1049
1050    /// Oracle: RFC 8620 §3.7 — #-prefixed args resolved from prior responses before handler call.
1051    #[tokio::test]
1052    async fn result_reference_resolved_before_dispatch() {
1053        let captured = Arc::new(Mutex::new(None::<Value>));
1054        let mut d: Dispatcher<String> = Dispatcher::new();
1055        d.register(
1056            "Foo/get",
1057            Arc::new(EchoHandler(json!({"list": [{"id": "item-1"}]}))),
1058        );
1059        d.register(
1060            "Bar/query",
1061            Arc::new(CaptureArgsHandler(Arc::clone(&captured))),
1062        );
1063        let req = JmapRequest::new(
1064            vec!["urn:ietf:params:jmap:core".into()],
1065            vec![
1066                Invocation::new("Foo/get", json!({}), "c0"),
1067                Invocation::new(
1068                    "Bar/query",
1069                    json!({"#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}}),
1070                    "c1",
1071                ),
1072            ],
1073            None,
1074        );
1075        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1076        assert_eq!(resp.method_responses.len(), 2);
1077        // c1 must succeed, not be an error
1078        assert!(
1079            resp.method_responses[1].arguments.get("type").is_none(),
1080            "Bar/query must succeed after ResultReference resolution"
1081        );
1082        // Handler must have received the resolved value, not the original #ids object
1083        let got = captured
1084            .lock()
1085            .unwrap()
1086            .clone()
1087            .expect("CaptureArgsHandler was not called");
1088        assert_eq!(
1089            got["ids"],
1090            json!("item-1"),
1091            "resolved value must be the string item-1"
1092        );
1093        assert!(
1094            got.get("#ids").is_none(),
1095            "#ids key must have been replaced"
1096        );
1097    }
1098
1099    /// Oracle: RFC 8620 §3.7 — resolution failure → error for that call, batch continues.
1100    #[tokio::test]
1101    async fn result_reference_failure_stops_that_call() {
1102        let d: Dispatcher<String> = Dispatcher::new();
1103        let req = single_call(
1104            "Foo/get",
1105            json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
1106            "c0",
1107        );
1108        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1109        assert_eq!(resp.method_responses.len(), 1);
1110        let Invocation {
1111            arguments: args, ..
1112        } = &resp.method_responses[0];
1113        assert!(
1114            args.get("type").is_some(),
1115            "failed ResultReference must produce an error invocation"
1116        );
1117    }
1118
1119    // -----------------------------------------------------------------------
1120    // createdIds
1121    // -----------------------------------------------------------------------
1122
1123    /// Oracle: RFC 8620 §3.3 createdIds — server-assigned IDs returned from /set
1124    /// responses are accumulated into resp.created_ids when client sent createdIds.
1125    #[tokio::test]
1126    async fn created_ids_accumulated_from_set_response() {
1127        let mut d: Dispatcher<String> = Dispatcher::new();
1128        d.register(
1129            "Foo/set",
1130            Arc::new(EchoHandler(
1131                json!({"created": {"client-1": {"id": "server-abc"}}}),
1132            )),
1133        );
1134        // Client sends createdIds (empty map) to signal it wants the response field.
1135        let req = JmapRequest::new(
1136            vec!["urn:ietf:params:jmap:core".into()],
1137            vec![Invocation::new("Foo/set", json!({}), "c0")],
1138            Some(std::collections::BTreeMap::new()),
1139        );
1140        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1141        let ids = resp
1142            .created_ids
1143            .as_ref()
1144            .expect("created_ids must be Some when client sent createdIds");
1145        assert_eq!(
1146            ids.get(&Id::from("client-1")),
1147            Some(&Id::from("server-abc")),
1148            "client-1 must map to server-abc"
1149        );
1150    }
1151
1152    /// Oracle: RFC 8620 §3.4 — createdIds omitted when no objects were created.
1153    #[tokio::test]
1154    async fn created_ids_absent_when_no_set() {
1155        let mut d: Dispatcher<String> = Dispatcher::new();
1156        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
1157        let req = single_call("Foo/get", json!({}), "c0");
1158        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1159        assert!(
1160            resp.created_ids.is_none(),
1161            "created_ids must be None when no /set call created objects"
1162        );
1163    }
1164
1165    /// Oracle: RFC 8620 §3.3 — createdIds accumulates across ALL /set calls in the batch.
1166    #[tokio::test]
1167    async fn created_ids_accumulated_across_multiple_set_calls() {
1168        let mut d: Dispatcher<String> = Dispatcher::new();
1169        d.register(
1170            "A/set",
1171            Arc::new(EchoHandler(json!({"created": {"cA": {"id": "sA"}}}))),
1172        );
1173        d.register(
1174            "B/set",
1175            Arc::new(EchoHandler(json!({"created": {"cB": {"id": "sB"}}}))),
1176        );
1177        // Client sends createdIds to signal it wants the response field.
1178        let req = JmapRequest::new(
1179            vec!["urn:ietf:params:jmap:core".into()],
1180            vec![
1181                Invocation::new("A/set", json!({}), "c0"),
1182                Invocation::new("B/set", json!({}), "c1"),
1183            ],
1184            Some(std::collections::BTreeMap::new()),
1185        );
1186        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1187        let ids = resp
1188            .created_ids
1189            .as_ref()
1190            .expect("created_ids must be Some when client sent createdIds");
1191        assert_eq!(
1192            ids.get(&Id::from("cA")),
1193            Some(&Id::from("sA")),
1194            "cA must be present"
1195        );
1196        assert_eq!(
1197            ids.get(&Id::from("cB")),
1198            Some(&Id::from("sB")),
1199            "cB must be present"
1200        );
1201    }
1202
1203    /// Oracle: RFC 8620 §3.4 — pre-populated client createdIds are preserved and
1204    /// new /set entries are merged in alongside them.
1205    #[tokio::test]
1206    async fn created_ids_merges_with_pre_populated_map() {
1207        let mut d: Dispatcher<String> = Dispatcher::new();
1208        d.register(
1209            "Foo/set",
1210            Arc::new(EchoHandler(
1211                json!({"created": {"client-new": {"id": "server-new"}}}),
1212            )),
1213        );
1214        // Client sends a pre-populated createdIds map.
1215        let mut initial = std::collections::BTreeMap::new();
1216        initial.insert(Id::from("client-old"), Id::from("server-old"));
1217        let req = JmapRequest::new(
1218            vec!["urn:ietf:params:jmap:core".into()],
1219            vec![Invocation::new("Foo/set", json!({}), "c0")],
1220            Some(initial),
1221        );
1222        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1223        let ids = resp
1224            .created_ids
1225            .as_ref()
1226            .expect("created_ids must be Some when client sent createdIds");
1227        assert_eq!(
1228            ids.get(&Id::from("client-old")),
1229            Some(&Id::from("server-old")),
1230            "pre-populated entry must be preserved"
1231        );
1232        assert_eq!(
1233            ids.get(&Id::from("client-new")),
1234            Some(&Id::from("server-new")),
1235            "new /set entry must be merged in"
1236        );
1237    }
1238
1239    /// Oracle (bd:JMAP-jfia.3): when the client pre-populates
1240    /// `createdIds` with `X -> A` and a `/set` call in the same batch
1241    /// returns `X -> B` (`B != A`), the dispatcher applies last-write-
1242    /// wins semantics: the response carries `X -> B`, and the
1243    /// pre-populated `A` is dropped. This is surprising and the spec is
1244    /// ambiguous on which semantics is correct (RFC 8620 §3.4), but
1245    /// matches the intra-batch duplicate convention documented at the
1246    /// dispatch call site and avoids a wire-behaviour change in the
1247    /// canonical foundation crate. The test exists to catch a future
1248    /// refactor that silently flips the order to first-write-wins.
1249    #[tokio::test]
1250    async fn created_ids_pre_populated_collision_last_write_wins() {
1251        let mut d: Dispatcher<String> = Dispatcher::new();
1252        d.register(
1253            "Foo/set",
1254            Arc::new(EchoHandler(
1255                json!({"created": {"client-X": {"id": "server-B"}}}),
1256            )),
1257        );
1258        // Client pre-populates client-X -> server-A.
1259        let mut initial = std::collections::BTreeMap::new();
1260        initial.insert(Id::from("client-X"), Id::from("server-A"));
1261        let req = JmapRequest::new(
1262            vec!["urn:ietf:params:jmap:core".into()],
1263            vec![Invocation::new("Foo/set", json!({}), "c0")],
1264            Some(initial),
1265        );
1266        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1267        let ids = resp
1268            .created_ids
1269            .as_ref()
1270            .expect("created_ids must be Some when client sent createdIds");
1271        assert_eq!(
1272            ids.get(&Id::from("client-X")),
1273            Some(&Id::from("server-B")),
1274            "last-write-wins: /set response overrides pre-populated entry"
1275        );
1276        assert_eq!(
1277            ids.len(),
1278            1,
1279            "no extra entries should appear from the collision"
1280        );
1281    }
1282
1283    /// Oracle (bd:JMAP-jfia.3): when two `/set` calls in the same batch
1284    /// report the same creationId with different values, the
1285    /// dispatcher applies last-write-wins: the second `/set` response's
1286    /// mapping is the one preserved in the final `createdIds` map. The
1287    /// existing dispatch call-site comment documents this convention
1288    /// (bd:JMAP-wlip.7); the test pins it.
1289    #[tokio::test]
1290    async fn created_ids_intra_batch_collision_last_write_wins() {
1291        let mut d: Dispatcher<String> = Dispatcher::new();
1292        d.register(
1293            "A/set",
1294            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sA"}}}))),
1295        );
1296        d.register(
1297            "B/set",
1298            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sB"}}}))),
1299        );
1300        let req = JmapRequest::new(
1301            vec!["urn:ietf:params:jmap:core".into()],
1302            vec![
1303                Invocation::new("A/set", json!({}), "c0"),
1304                Invocation::new("B/set", json!({}), "c1"),
1305            ],
1306            Some(std::collections::BTreeMap::new()),
1307        );
1308        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1309        let ids = resp
1310            .created_ids
1311            .as_ref()
1312            .expect("created_ids must be Some when client sent createdIds");
1313        assert_eq!(
1314            ids.get(&Id::from("cX")),
1315            Some(&Id::from("sB")),
1316            "last-write-wins: second /set call's mapping for cX preserved"
1317        );
1318        assert_eq!(
1319            ids.len(),
1320            1,
1321            "no extra entries should appear from the collision"
1322        );
1323    }
1324
1325    // -----------------------------------------------------------------------
1326    // CallerCtx
1327    // -----------------------------------------------------------------------
1328
1329    /// Oracle: PLAN.md CallerCtx design — caller value passed through to handler unchanged.
1330    #[tokio::test]
1331    async fn caller_ctx_passed_to_handler() {
1332        let captured = Arc::new(Mutex::new(None::<String>));
1333        let mut d: Dispatcher<String> = Dispatcher::new();
1334        d.register(
1335            "Foo/get",
1336            Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
1337        );
1338        let req = single_call("Foo/get", json!({}), "c0");
1339        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1340        assert!(
1341            resp.method_responses[0].arguments.get("type").is_none(),
1342            "must succeed"
1343        );
1344        let got = captured
1345            .lock()
1346            .unwrap()
1347            .clone()
1348            .expect("handler was not called");
1349        assert_eq!(got, "alice", "caller must be passed through unchanged");
1350    }
1351
1352    /// Oracle: PLAN.md — CallerCtx = () must work (unit type as auth context).
1353    #[tokio::test]
1354    async fn unit_caller_ctx_works() {
1355        let mut d: Dispatcher<()> = Dispatcher::new();
1356        d.register("Foo/get", Arc::new(EchoHandler(json!({"ok": true}))));
1357        let req = single_call("Foo/get", json!({}), "c0");
1358        let resp = d.dispatch(req, (), "s0".into()).await;
1359        assert_eq!(resp.method_responses.len(), 1);
1360        assert!(
1361            resp.method_responses[0].arguments.get("type").is_none(),
1362            "must succeed with () caller"
1363        );
1364    }
1365
1366    // -----------------------------------------------------------------------
1367    // Extra invocations
1368    // -----------------------------------------------------------------------
1369
1370    /// A handler that returns both a primary response and one extra invocation.
1371    ///
1372    /// Models RFC 8621 §7.5 EmailSubmission/set with onSuccessUpdateEmail: the
1373    /// submission response is primary; the implied Email/set call is extra.
1374    struct ExtraInvocationHandler;
1375
1376    impl JmapHandler<String> for ExtraInvocationHandler {
1377        fn call(
1378            &self,
1379            _method: String,
1380            _call_id: String,
1381            _args: Value,
1382            _caller: String,
1383        ) -> HandlerFuture {
1384            Box::pin(async move {
1385                let primary = json!({"type": "primary"});
1386                let extra: Vec<Invocation> = vec![Invocation::new(
1387                    "Extra/call",
1388                    json!({"type": "extra"}),
1389                    "x0",
1390                )];
1391                Ok(HandlerOutput::new(primary).with_extra(extra))
1392            })
1393        }
1394    }
1395
1396    /// Oracle: handler returning extra invocations → both primary and extra appear in
1397    /// methodResponses in order (primary first, then extra).
1398    #[tokio::test]
1399    async fn extra_invocations_appended_after_primary() {
1400        let mut d: Dispatcher<String> = Dispatcher::new();
1401        d.register("Sub/set", Arc::new(ExtraInvocationHandler));
1402        let req = single_call("Sub/set", json!({}), "c0");
1403        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1404
1405        assert_eq!(
1406            resp.method_responses.len(),
1407            2,
1408            "primary + 1 extra = 2 total invocations"
1409        );
1410        // First: the primary Sub/set response.
1411        assert_eq!(resp.method_responses[0].name, "Sub/set");
1412        assert_eq!(resp.method_responses[0].call_id, "c0");
1413        assert_eq!(resp.method_responses[0].arguments["type"], "primary");
1414        // Second: the appended extra invocation.
1415        assert_eq!(resp.method_responses[1].name, "Extra/call");
1416        assert_eq!(resp.method_responses[1].call_id, "x0");
1417        assert_eq!(resp.method_responses[1].arguments["type"], "extra");
1418    }
1419
1420    /// Oracle: ClosureHandler forwards CallerCtx to the closure.
1421    /// The closure receives the exact same value that was passed to dispatch().
1422    #[tokio::test]
1423    async fn closure_handler_forwards_caller() {
1424        #[derive(Clone)]
1425        struct Ctx(String);
1426
1427        struct DummyBackend;
1428
1429        // Use a shared capture to record what ctx the closure received.
1430        let received: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
1431        let received_clone = Arc::clone(&received);
1432
1433        let handler: Arc<ClosureHandler<DummyBackend, Ctx>> = Arc::new(ClosureHandler::new(
1434            Arc::new(DummyBackend),
1435            move |_b: Arc<DummyBackend>, _call_id: String, _args: Value, ctx: Ctx| {
1436                let cap = Arc::clone(&received_clone);
1437                Box::pin(async move {
1438                    *cap.lock().unwrap() = Some(ctx.0.clone());
1439                    Ok(HandlerOutput::new(serde_json::json!({})))
1440                })
1441            },
1442        ));
1443
1444        let ctx = Ctx("alice".to_owned());
1445        handler
1446            .call("Test/get".into(), "c1".into(), serde_json::json!({}), ctx)
1447            .await
1448            .expect("handler must succeed");
1449
1450        assert_eq!(
1451            received.lock().unwrap().as_deref(),
1452            Some("alice"),
1453            "CallerCtx must be forwarded to the closure"
1454        );
1455    }
1456
1457    /// Oracle: ClosureHandler implements JmapHandler<C> and can be
1458    /// registered with Dispatcher<C>.
1459    #[test]
1460    fn closure_handler_is_jmap_handler() {
1461        // Compile-time check: ClosureHandler<B, C> must satisfy JmapHandler<C>.
1462        fn assert_handler<C: Clone + Send + 'static, H: JmapHandler<C>>(_: &H) {}
1463
1464        struct DummyBackend;
1465        #[derive(Clone)]
1466        struct Ctx;
1467
1468        let h = ClosureHandler::new(Arc::new(DummyBackend), |_b, _ci, _a, _ctx| {
1469            Box::pin(async { Ok(HandlerOutput::new(serde_json::json!({}))) })
1470        });
1471        assert_handler::<Ctx, _>(&h);
1472    }
1473}