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#![cfg_attr(docsrs, feature(doc_cfg))]
29#![forbid(unsafe_code)]
30
31pub use jmap_types::{
32    Argument, Id, Invocation, JmapError, JmapRequest, JmapResponse, PushSubscription,
33    ResultReference, State, UTCDate,
34};
35
36mod backend;
37mod caller;
38mod conditional;
39mod handlers;
40mod helpers;
41mod history;
42mod i18n;
43
44/// The draft-ietf-jmap-metadata-05 §1.2.1 DataTypeMetadataInfo that
45/// [`JmapAccounts::metadata_info`] returns, re-exported so a backend or a
46/// wrapper can name it without a direct `jmap-metadata-types` dependency.
47pub use jmap_metadata_types::DataTypeMetadataInfo;
48
49pub use backend::{
50    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesParams,
51    ChangesResult, DelegateJmapAccounts, DelegateJmapReads, GetObject, JmapAccounts, JmapBackend,
52    JmapObject, JmapReads, QueryChangesParams, QueryChangesResult, QueryObject, QueryParams,
53    QueryResult, ReservedExtrasKey, SetError, SetErrorType, SetObject, backend_set_error_value,
54};
55pub use caller::MemoryCaller;
56pub use conditional::{
57    BeginSetError, CommitError, CommitFuture, ConditionalBackend, DeferredFailure,
58    RegistrationError, RollbackFuture, SetMode, SetOp, SetScope, SetScopeId, SetScopeRequest,
59    SetSupport, current_set_scope, serialized_writes_scope,
60};
61pub use handlers::{
62    SERVER_FAIL_INTERNAL_DESC, changes_error_from_backend, handle_changes, handle_get,
63    handle_get_with_metadata, handle_query, handle_query_changes, handle_query_changes_with_i18n,
64    handle_query_with_i18n, server_fail_from_backend, server_fail_value_from_backend,
65};
66pub use helpers::{
67    CREATE_ID_PLACEHOLDER, MergePatchError, MetadataProjection, PatchPathError, apply_jmap_patch,
68    apply_patch_object, bool_arg, check_blob_ids, check_patch_paths, check_read_only_patch,
69    enforce_max_objects_in_get, enforce_max_objects_in_set, extract_account_id, filter_arg,
70    is_client_updatable, json_merge_patch, json_type_name, limit_or_max, not_found_json,
71    now_utc_string, now_utc_string_checked, optional_arg, parse_max_changes, parse_wire_id,
72    patch_values_as_object, query_anchor_args, reject_did_bearing_properties,
73    reject_metadata_filter_arg, reject_metadata_filter_without_capability, reject_read_only_patch,
74    reject_server_set, resolve_blob_ref, resolve_blob_refs, resolve_creation_ref,
75    resolve_query_offset, resolve_query_start, resolve_set_id_refs, serialize_value,
76    strip_read_only_patch, take_bool_arg, uses_metadata, utc_date_from_epoch_seconds,
77};
78pub use history::{
79    DestroyedQueryChangesParams, DestroyedQueryParams, HistoryGetParams, HistoryGetResult,
80    NoRestoreHooks, OBJECT_HISTORY_PROPERTY, ObjectHistoryBackend, ParentRestoreHooks,
81    RestoreAccumulators, RestoreHooks, Restored, append_restore_results, apply_restore_patch,
82    attach_object_history, enforce_max_objects_in_set_with_restore, handle_get_with_history,
83    handle_query_changes_with_history, handle_query_with_history, history_get, history_query,
84    history_query_changes, history_set, names_object_history, object_history_set_error,
85    parse_destroyed_query_arguments, parse_history_get_arguments, parse_restore_argument,
86    require_history_support, restored_diff, run_restore_phase, strip_object_history_property,
87};
88pub use i18n::{
89    I18nInfo, I18nProjection, I18nSet, localized_query_state, localized_update, unwrap_query_state,
90    uses_i18n,
91};
92
93mod parse;
94mod push;
95mod response;
96#[cfg(feature = "scoped-state")]
97mod scoped_state;
98
99pub use parse::{
100    MAX_FILTER_DEPTH, check_known_capabilities, filter_nests_deeper_than, parse_request,
101    parse_request_bytes, resolve_args,
102};
103pub use push::{
104    MAX_PUSH_EXPIRY_SECS, PushSubscriptionBackend, StoredPushSubscription, is_deliverable,
105    register_push_subscription_conditional, register_push_subscription_handlers, state_change_for,
106};
107pub use response::{RequestError, error_invocation, error_status, problem_response, request_error};
108#[cfg(feature = "scoped-state")]
109pub use scoped_state::{ScopeGate, ScopedGuard, ScopedState};
110
111use std::{
112    collections::{BTreeMap, BTreeSet, HashMap},
113    fmt,
114    future::Future,
115    pin::Pin,
116    sync::Arc,
117};
118
119use serde_json::Value;
120use tokio::task;
121
122/// The successful result of one [`JmapHandler::call`].
123///
124/// `#[non_exhaustive]` so fields can be added without breaking handler
125/// crates; build it with [`HandlerOutput::new`] and
126/// [`HandlerOutput::with_extra`].
127#[derive(Debug, Clone, PartialEq)]
128#[non_exhaustive]
129pub struct HandlerOutput {
130    /// The method's response arguments. The dispatcher pairs this with the
131    /// call's method name and call id as the primary response invocation.
132    pub primary: Value,
133    /// Zero or more invocations appended to `methodResponses` immediately
134    /// after the primary response, in order. Most handlers leave this
135    /// empty. RFC 8621 §7.5 `EmailSubmission/set` uses it for the implicit
136    /// `Email/set` response for `onSuccessUpdateEmail`.
137    pub extra_invocations: Vec<Invocation>,
138    /// Per object id, the top-level properties this `/get` response blanked
139    /// or left out because the caller may not read them. Never written to
140    /// the wire: the dispatcher's draft-ietf-jmap-conditional-02
141    /// evaluator answers a precondition on one of them `forbidden` (§9.1).
142    /// Empty for most handlers.
143    pub unreadable: BTreeMap<Id, BTreeSet<String>>,
144}
145
146impl HandlerOutput {
147    /// A handler result with only a primary response.
148    pub fn new(primary: Value) -> Self {
149        Self {
150            primary,
151            extra_invocations: Vec::new(),
152            unreadable: BTreeMap::new(),
153        }
154    }
155
156    /// Set the invocations to append after the primary response.
157    pub fn with_extra(mut self, extra_invocations: Vec<Invocation>) -> Self {
158        self.extra_invocations = extra_invocations;
159        self
160    }
161
162    /// Set [`HandlerOutput::unreadable`]: the properties a `/get` response
163    /// withheld from the caller, by object id.
164    pub fn with_unreadable(mut self, unreadable: BTreeMap<Id, BTreeSet<String>>) -> Self {
165        self.unreadable = unreadable;
166        self
167    }
168}
169
170/// The return type for all [`JmapHandler`] implementations.
171///
172/// Handlers must return a `Send` future.  The concrete type is a heap-allocated
173/// trait object so the trait itself remains object-safe.
174pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<HandlerOutput, JmapError>> + Send>>;
175
176/// Everything [`Dispatcher::dispatch`] hands a [`JmapHandler`] for one
177/// method call (RFC 8620 §3.2 Invocation, plus the caller).
178///
179/// `#[non_exhaustive]` so the dispatcher can pass more per-call context
180/// (a deadline, a tracing span, the request's creation ids) without
181/// breaking every handler (bd:JMAP-wf92.7). Handlers read the public
182/// fields; code that calls a handler directly builds one with
183/// [`CallContext::new`].
184///
185/// Fields are owned because the returned [`HandlerFuture`] is
186/// `'static`.
187#[derive(Debug, Clone, PartialEq)]
188#[non_exhaustive]
189pub struct CallContext<CallerCtx> {
190    /// The registered method name for this call. One handler may be
191    /// registered under several names (e.g. `"Foo/get"` and
192    /// `"Bar/get"`); this tells them apart.
193    pub method: String,
194    /// The client-supplied method call id (RFC 8620 §3.2). The
195    /// dispatcher echoes it in the response; handlers may use it for
196    /// logging or correlation.
197    pub call_id: String,
198    /// The call's arguments, with result references already resolved
199    /// (RFC 8620 §3.7).
200    pub args: Value,
201    /// Whatever the auth layer produced, passed to
202    /// [`Dispatcher::dispatch`] and cloned for each call.
203    pub caller: CallerCtx,
204    /// Creation id to server-assigned id for every record created
205    /// earlier in this request, plus the client's initial `createdIds`
206    /// (RFC 8620 §3.3, §5.3). A `/set` handler resolves `#`-prefixed
207    /// Id-typed values against it with [`resolve_creation_ref`]; the
208    /// dispatcher cannot, because only the handler knows which
209    /// properties are Id-typed (bd:JMAP-8ypy).
210    pub created_ids: BTreeMap<Id, Id>,
211    /// The request's `using` capability URIs (RFC 8620 §3.3). Extensions
212    /// change method behaviour per request on it; e.g.
213    /// draft-ietf-jmap-metadata-05 §3 extends `Foo/changes` only for
214    /// requests whose `using` includes `urn:ietf:params:jmap:metadata`.
215    pub using: Vec<String>,
216    /// The call is an atomic Foo/set (draft-ietf-jmap-conditional-02 §4):
217    /// the dispatcher removed the `atomic` argument and will commit all of
218    /// the method's changes or none. A handler need not act on it; it is
219    /// there for handlers that can fail fast.
220    pub atomic: bool,
221}
222
223impl<CallerCtx> CallContext<CallerCtx> {
224    /// A context for one method call.
225    pub fn new(
226        method: impl Into<String>,
227        call_id: impl Into<String>,
228        args: Value,
229        caller: CallerCtx,
230    ) -> Self {
231        Self {
232            method: method.into(),
233            call_id: call_id.into(),
234            args,
235            caller,
236            created_ids: BTreeMap::new(),
237            using: Vec::new(),
238            atomic: false,
239        }
240    }
241
242    /// Set [`CallContext::created_ids`]; [`CallContext::new`] leaves it
243    /// empty.
244    pub fn with_created_ids(mut self, created_ids: BTreeMap<Id, Id>) -> Self {
245        self.created_ids = created_ids;
246        self
247    }
248
249    /// Set [`CallContext::using`]; [`CallContext::new`] leaves it empty.
250    pub fn with_using(mut self, using: Vec<String>) -> Self {
251        self.using = using;
252        self
253    }
254
255    /// Set [`CallContext::atomic`]; [`CallContext::new`] leaves it false.
256    pub fn with_atomic(mut self, atomic: bool) -> Self {
257        self.atomic = atomic;
258        self
259    }
260}
261
262/// Implement this for each JMAP method handler.
263///
264/// `CallerCtx` is whatever your auth layer produces — an `Identity`, a session
265/// token, `()`, etc. The dispatcher passes it through unchanged.
266///
267/// # /set response contract
268///
269/// Handlers for `/set` methods (RFC 8620 §5.3) that create objects MUST include
270/// an `"id"` field (type string) in each entry of the `"created"` map.  The
271/// dispatcher reads this field to accumulate `createdIds` in the response.
272/// Entries without an `"id"` field are silently skipped — the dispatcher cannot
273/// retroactively error a method call that already returned success.
274pub trait JmapHandler<CallerCtx>: Send + Sync {
275    /// Handle one method call. See [`CallContext`] for what `cx` carries.
276    fn call(&self, cx: CallContext<CallerCtx>) -> HandlerFuture;
277}
278
279/// Walk a `/set` handler's primary response and accumulate every
280/// `created[client_id].id` pair into `sink` (RFC 8620 §3.4
281/// `createdIds`) (bd:JMAP-wlip.10).
282///
283/// Lives next to the [`JmapHandler`] doc contract that requires
284/// every entry of `created` to contain a string `"id"` field. Entries
285/// that violate the contract — no `"id"` key, or an `"id"` of a
286/// non-string type — are silently skipped, because the dispatcher
287/// cannot produce a method-level error for a method call that already
288/// succeeded. The shared helper makes the silent-skip behaviour
289/// auditable in one place rather than inlined in the dispatcher loop.
290///
291/// Non-`/set` primary responses (no `"created"` key at the top level,
292/// or `"created"` of a non-Object type) leave `sink` unchanged.
293///
294/// Collision semantics (bd:JMAP-jfia.3): when a creationId in the
295/// `/set` response collides with an entry already in `sink` — whether
296/// from an earlier `/set` call in the same batch OR from the client's
297/// pre-populated `createdIds` map — `BTreeMap::insert` silently
298/// overwrites: last write wins. The pre-populated collision case is
299/// exercised by
300/// [`tests::created_ids_pre_populated_collision_last_write_wins`].
301/// See the dispatcher call site for the full rationale.
302fn extract_created_ids_into(primary: &Value, sink: &mut BTreeMap<Id, Id>) {
303    let Some(map) = primary.get("created").and_then(|v| v.as_object()) else {
304        return;
305    };
306    for (client_id, created_obj) in map {
307        if let Some(id_val) = created_obj.get("id").and_then(|v| v.as_str()) {
308            sink.insert(Id::from(client_id.as_str()), Id::from(id_val));
309        }
310    }
311}
312
313/// Dispatches a [`JmapRequest`] to registered method handlers.
314///
315/// Register handlers with [`Dispatcher::register`], then call
316/// [`Dispatcher::dispatch`] per request.  `CallerCtx` is cloned for each
317/// method call in the batch, so it must be `Clone`.
318///
319/// `CallerCtx` must also be `'static` because each handler call is spawned as
320/// a [`tokio::task`].  To share non-static data (e.g. a database connection),
321/// wrap it in `Arc<T>` — `Arc` is `Clone + Send + 'static` when `T: Send + Sync`.
322///
323/// # Thread safety
324///
325/// `Dispatcher` is both `Send` and `Sync`.  Register handlers on one thread,
326/// then wrap in `Arc` and share across tasks — `dispatch` takes `&self` and is
327/// safe to call concurrently.
328pub struct Dispatcher<CallerCtx> {
329    handlers: HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>,
330    guard: Option<MethodGuard<CallerCtx>>,
331    /// Conditional-02 support attached per Foo/set method name.
332    set_support: HashMap<String, SetSupport<CallerCtx>>,
333    /// Methods registered through [`Dispatcher::register_history_aware`].
334    history_aware: BTreeSet<String>,
335}
336
337type MethodGuard<CallerCtx> = Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync>;
338
339/// Returned by [`Dispatcher::try_register`] when a handler is already
340/// registered under the requested method name.
341///
342/// Added in bd:JMAP-jfia.4 alongside `try_register` to make the
343/// duplicate-registration foot-gun explicit at the call site rather
344/// than silently dropping a binding.
345#[non_exhaustive]
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub struct DuplicateMethodError {
348    /// The method name that was already registered.
349    pub method: String,
350}
351
352impl std::fmt::Display for DuplicateMethodError {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        write!(f, "handler already registered for method {:?}", self.method)
355    }
356}
357
358impl std::error::Error for DuplicateMethodError {}
359
360impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx> {
361    /// Create an empty dispatcher with no registered handlers.
362    pub fn new() -> Self {
363        Self {
364            handlers: HashMap::new(),
365            guard: None,
366            set_support: HashMap::new(),
367            history_aware: BTreeSet::new(),
368        }
369    }
370
371    /// Install a guard that every method call must pass before its handler
372    /// runs.
373    ///
374    /// [`Dispatcher::dispatch`] calls `guard` with the method name and the
375    /// caller after resolving the call's result references and before
376    /// looking up its handler. An `Err` becomes that call's error response
377    /// (RFC 8620 §3.6.2), in its place in `methodResponses`; the handler
378    /// does not run, and later calls in the batch are still processed.
379    /// A rejected call produces no result for later references to resolve
380    /// against (RFC 8620 §3.7).
381    ///
382    /// Without a guard every call reaches its handler. Setting a guard
383    /// again replaces the previous one.
384    pub fn set_guard(
385        &mut self,
386        guard: impl Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync + 'static,
387    ) {
388        self.guard = Some(Box::new(guard));
389    }
390
391    /// Register a handler for the given method name.
392    ///
393    /// **Registering the same name twice silently replaces the earlier
394    /// handler.** This is a real foot-gun in the workspace pattern where
395    /// each extension crate ships a `register_*_handlers` macro that
396    /// registers ~10 method names against a single `Dispatcher`: a typo
397    /// or accidental double-registration drops one binding with no
398    /// diagnostic, and the handler that "never fires" is hard to debug
399    /// (bd:JMAP-jfia.4). Prefer [`Dispatcher::try_register`] in new
400    /// code; `register` is kept for ergonomic call sites where the
401    /// silent-overwrite is the deliberate choice (e.g. a test fixture
402    /// that overrides a handler for a specific scenario).
403    ///
404    /// Using `Arc` rather than `Box` allows the same handler instance to be
405    /// shared across multiple method name registrations (via `Arc::clone`).
406    ///
407    /// Drops any conditional support attached to `method`
408    /// ([`Dispatcher::attach_set_support`]) and any history-aware mark
409    /// ([`Dispatcher::register_history_aware`]): the new handler must opt
410    /// in again.
411    pub fn register(
412        &mut self,
413        method: impl Into<String>,
414        handler: Arc<dyn JmapHandler<CallerCtx>>,
415    ) {
416        let method = method.into();
417        self.set_support.remove(&method);
418        self.history_aware.remove(&method);
419        self.handlers.insert(method, handler);
420    }
421
422    /// Register a handler for the given method name, returning an error
423    /// if the method name is already registered.
424    ///
425    /// This is the recommended registration entry point for production
426    /// code paths (bd:JMAP-jfia.4). Unlike [`Dispatcher::register`], a
427    /// duplicate method name produces
428    /// [`DuplicateMethodError`] rather than silently replacing the
429    /// existing handler, surfacing the collision at the call site that
430    /// caused it.
431    ///
432    /// On `Err(DuplicateMethodError)` the dispatcher's handler map is
433    /// left unchanged — the existing handler is preserved and the
434    /// would-be registration is dropped.
435    ///
436    /// Using `Arc` rather than `Box` allows the same handler instance to be
437    /// shared across multiple method name registrations (via `Arc::clone`).
438    ///
439    /// # Errors
440    ///
441    /// Returns [`DuplicateMethodError`] when `method` is already
442    /// registered.
443    pub fn try_register(
444        &mut self,
445        method: impl Into<String>,
446        handler: Arc<dyn JmapHandler<CallerCtx>>,
447    ) -> Result<(), DuplicateMethodError> {
448        let method = method.into();
449        if self.handlers.contains_key(&method) {
450            return Err(DuplicateMethodError { method });
451        }
452        self.handlers.insert(method, handler);
453        Ok(())
454    }
455
456    /// The names of the methods registered on this dispatcher, in sorted
457    /// order: every name [`Self::register`] or [`Self::try_register`] took,
458    /// including those an extension crate's `register_*_handlers` added.
459    ///
460    /// For a front dispatcher that bridges every method an inner one
461    /// serves, or a Session object that lists what is served.
462    ///
463    /// ```
464    /// use jmap_server::Dispatcher;
465    ///
466    /// let dispatcher: Dispatcher<()> = Dispatcher::new();
467    /// assert_eq!(dispatcher.methods().count(), 0);
468    /// ```
469    pub fn methods(&self) -> impl Iterator<Item = &str> + '_ {
470        let mut names: Vec<&str> = self.handlers.keys().map(String::as_str).collect();
471        names.sort_unstable();
472        names.into_iter()
473    }
474
475    /// Process a validated [`JmapRequest`] and return a [`JmapResponse`].
476    ///
477    /// Method calls are processed sequentially per RFC 8620 §3.3.  Each
478    /// handler runs in a `tokio::task::spawn` for panic isolation: a panicking
479    /// handler returns a `serverFail` invocation rather than crashing the
480    /// connection task, and emits one `tracing::error!` event with only the
481    /// `method` and `call_id` fields (never the panic payload or arguments).
482    ///
483    /// `CallerCtx` must be `Clone + Send + 'static`; see the struct-level doc.
484    ///
485    /// # Runtime requirement (bd:JMAP-jfia.24)
486    ///
487    /// `dispatch` invokes [`tokio::task::spawn`] internally and
488    /// therefore **requires a Tokio runtime in scope at the call
489    /// site**. The async-fn signature itself does not advertise this
490    /// requirement — there is no `?Send` async-trait bound and no
491    /// `Spawner` parameter — but calling `dispatch` without a Tokio
492    /// runtime will panic at the first method call with a
493    /// `there is no reactor running` error.
494    ///
495    /// This is a structural coupling to the Tokio ecosystem.
496    /// Production consumers running under `tokio::main` /
497    /// `Runtime::block_on` already satisfy this; consumers
498    /// experimenting with alternative runtimes (`async-std`,
499    /// `smol`, `embassy`, etc.) cannot use `Dispatcher` without
500    /// either a Tokio compat shim or a custom dispatcher
501    /// re-implementation. Decoupling the spawn mechanism is a
502    /// major-bump API change tracked separately.
503    ///
504    /// # Cancellation
505    ///
506    /// Dropping the future returned by `dispatch` does **not** cancel
507    /// method calls that are already running (bd:JMAP-wlip.34). Each
508    /// call runs in its own [`tokio::task::spawn`]ed task, and tokio
509    /// does not abort a task when its `JoinHandle` is dropped, so a
510    /// running call finishes and only its response is lost. Calls
511    /// later in the batch that had not started yet are never run.
512    ///
513    /// This is deliberate: a client that disconnects (for example,
514    /// the HTTP connection closes) can never interrupt a backend
515    /// mid-write and leave a `/set` half applied. `dispatch` takes no
516    /// cancellation token, and [`JmapHandler::call`] receives none.
517    ///
518    /// The cost is that a disconnected client cannot stop an
519    /// expensive call (a large `Email/query`, a slow full-text
520    /// search): the backend does the full work anyway, and a client
521    /// that opens and drops many requests can use this to consume
522    /// server resources. Bound that cost in the backend, for example
523    /// with `tokio::time::timeout` or an RPC deadline around each
524    /// storage call, and limit request concurrency per client.
525    ///
526    /// For a clean shutdown, stop accepting new requests and let
527    /// in-flight `dispatch` calls and their spawned tasks finish; a
528    /// shutdown signal that drops `dispatch` futures does not reach
529    /// the spawned tasks.
530    pub async fn dispatch(
531        &self,
532        request: JmapRequest,
533        caller: CallerCtx,
534        session_state: State,
535    ) -> JmapResponse {
536        let mut method_responses: Vec<Invocation> = Vec::with_capacity(request.method_calls.len());
537        let client_sent_created_ids = request.created_ids.is_some();
538        let mut created_ids: BTreeMap<Id, Id> = request.created_ids.unwrap_or_default();
539
540        for Invocation {
541            name: method,
542            arguments: mut args,
543            call_id,
544        } in request.method_calls
545        {
546            // Resolve ResultReferences from prior responses.
547            if let Err(e) = resolve_args(&mut args, &method_responses)
548                .and_then(|()| parse::check_filter_depth(&args))
549                .and_then(|()| parse::check_state_arguments(&args))
550            {
551                method_responses.push(error_invocation(&call_id, e));
552                continue;
553            }
554
555            if let Some(Err(e)) = self.guard.as_ref().map(|guard| guard(&method, &caller)) {
556                method_responses.push(error_invocation(&call_id, e));
557                continue;
558            }
559
560            // Look up the handler.
561            let Some(handler) = self.handlers.get(&method).map(Arc::clone) else {
562                method_responses.push(error_invocation(&call_id, JmapError::unknown_method()));
563                continue;
564            };
565
566            // draft-ietf-jmap-conditional-02 (docs/design/conditional.md
567            // §5.2): every Foo/set call goes through the decision-2 check;
568            // one with conditional arguments runs under the evaluator.
569            // docs/design/DECISIONS.md decision 18: history arguments
570            // without urn:ietf:params:jmap:object-history in `using`, or
571            // sent to a method that is not history-aware.
572            if let Err(e) = history::check_history_arguments(
573                &method,
574                &mut args,
575                &request.using,
576                self.history_aware.contains(&method),
577            ) {
578                method_responses.push(error_invocation(&call_id, e));
579                continue;
580            }
581
582            let conditional = if method.ends_with("/set") {
583                // RFC 8620 §5.3: an update key or destroy id may name a
584                // record an earlier call created; the handler resolves
585                // references to its own creates after its create phase.
586                if let Value::Object(map) = &mut args {
587                    resolve_set_id_refs(map, &created_ids, &serde_json::Map::new());
588                }
589                match self.prepare_conditional(&method, &mut args, &request.using, &caller) {
590                    Ok(c) => c,
591                    Err(e) => {
592                        method_responses.push(error_invocation(&call_id, e));
593                        continue;
594                    }
595                }
596            } else {
597                None
598            };
599
600            let caller_clone = caller.clone();
601            let method_clone = method.clone();
602            let call_id_clone = call_id.clone();
603            // ponytail: clones the map per call; it is bounded by
604            // maxCallsInRequest x maxObjectsInSet. Arc it if that grows.
605            let created_ids_snapshot = created_ids.clone();
606            let using = request.using.clone();
607
608            // Run in a spawned task for panic isolation.
609            let result: Result<Result<HandlerOutput, JmapError>, tokio::task::JoinError> =
610                task::spawn(async move {
611                    let cx = CallContext::new(method_clone, call_id_clone, args, caller_clone)
612                        .with_created_ids(created_ids_snapshot)
613                        .with_using(using);
614                    match conditional {
615                        Some(prepared) => prepared.run(handler, cx).await,
616                        None => handler.call(cx).await,
617                    }
618                })
619                .await;
620
621            match result {
622                Ok(Ok(HandlerOutput {
623                    primary: primary_value,
624                    extra_invocations,
625                    ..
626                })) => {
627                    // Accumulate createdIds from every /set response: RFC 8620
628                    // §5.3 says the server "MUST keep a simple map for the
629                    // duration of the request" so later calls can resolve
630                    // "#" references (bd:JMAP-8ypy). The map is echoed in
631                    // the response only when the client sent createdIds
632                    // (RFC 8620 §3.4).
633                    //
634                    // Duplicate-creationId behaviour (bd:JMAP-wlip.7,
635                    // bd:JMAP-jfia.3): BTreeMap::insert silently overwrites
636                    // on duplicate key. Two flavours of duplicate:
637                    //
638                    //   (a) Intra-batch: a client reuses the same
639                    //   creationId across two /set calls in the same
640                    //   batch (e.g. "c1" in both Mailbox/set and
641                    //   Email/set). The second mapping wins and the
642                    //   first is lost.
643                    //
644                    //   (b) Pre-populated collision: a client
645                    //   pre-populates createdIds with X->A and a /set
646                    //   call in the same batch returns X->B (B != A).
647                    //   The /set value wins and the pre-populated A is
648                    //   lost. This is reachable via long-lived
649                    //   background tasks replaying a queued request
650                    //   whose creationIds overlap with the current
651                    //   session's batch.
652                    //
653                    // RFC 8620 §3.4 does not explicitly require either
654                    // last-write-wins or rejection; the convention here
655                    // is last-write-wins because (a) the response order
656                    // is deterministic so the behaviour is at least
657                    // reproducible, (b) detecting either flavour of
658                    // duplicate would require either a per-batch
659                    // creationId pre-check (adds a HashSet allocation
660                    // per request) or a second pass over
661                    // method_responses after dispatch, and (c) this
662                    // crate is the canonical foundation for every
663                    // *-server extension — a wire-behaviour change
664                    // (e.g. reject-on-collision) would ripple to every
665                    // downstream consumer and is out of scope for a
666                    // foundation crate without an RFC mandate.
667                    //
668                    // Clients SHOULD generate unique creationIds across
669                    // a batch and SHOULD NOT pre-populate creationIds
670                    // that any /set call in the same batch will
671                    // produce. Both collision flavours are exercised
672                    // explicitly by
673                    // [`tests::created_ids_intra_batch_collision_last_write_wins`]
674                    // and
675                    // [`tests::created_ids_pre_populated_collision_last_write_wins`]
676                    // so a future refactor that flips the order is
677                    // caught.
678                    extract_created_ids_into(&primary_value, &mut created_ids);
679                    // Push the primary response first, then any extra invocations
680                    // appended by the handler (e.g. onSuccessUpdateEmail from
681                    // EmailSubmission/set, RFC 8621 §7.5).  Order is preserved.
682                    method_responses.push(Invocation::new(method, primary_value, call_id));
683                    method_responses.extend(extra_invocations);
684                }
685                Ok(Err(e)) => {
686                    method_responses.push(error_invocation(&call_id, e));
687                }
688                Err(join_err) => {
689                    // Panics and cancellations both map to serverFail, but with
690                    // distinct descriptions to aid server-side diagnostics.
691                    let desc = if join_err.is_cancelled() {
692                        "task cancelled"
693                    } else {
694                        "internal error"
695                    };
696                    // Side channel so operators can tell a caught panic from a
697                    // handler's own serverFail (bd:JMAP-jfia.29). Only the
698                    // method name and call id: the panic payload and the
699                    // arguments may carry secrets. Passed as `&str` so text
700                    // formatters escape the client-chosen call id.
701                    if join_err.is_panic() {
702                        tracing::error!(
703                            method = method.as_str(),
704                            call_id = call_id.as_str(),
705                            "method handler panicked"
706                        );
707                    }
708                    method_responses.push(error_invocation(&call_id, JmapError::server_fail(desc)));
709                }
710            }
711        }
712
713        let created_ids = client_sent_created_ids.then_some(created_ids);
714
715        JmapResponse::new(method_responses, session_state, created_ids)
716    }
717}
718
719impl<CallerCtx: Clone + Send + 'static> Default for Dispatcher<CallerCtx> {
720    fn default() -> Self {
721        Self::new()
722    }
723}
724
725impl<CallerCtx> fmt::Debug for Dispatcher<CallerCtx> {
726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727        f.debug_struct("Dispatcher")
728            .field("methods", &self.handlers.keys())
729            .field("guard", &self.guard.is_some())
730            .field("set_support", &self.set_support.keys())
731            .finish()
732    }
733}
734
735// ---------------------------------------------------------------------------
736// ClosureHandler — generic backend-wrapping JmapHandler that forwards CallerCtx
737// ---------------------------------------------------------------------------
738
739/// Type alias for the closure stored inside [`ClosureHandler`].
740///
741/// The closure gets the shared backend and the call's [`CallContext`]
742/// (method name, call id, arguments and caller). Taking the context as
743/// one `#[non_exhaustive]` struct lets the dispatcher pass more per-call
744/// context later without changing this signature (bd:JMAP-wf92.7).
745pub type BackendCallFn<B, C> =
746    dyn Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static;
747
748/// A [`JmapHandler`] that wraps an async closure over a shared backend and
749/// forwards `CallerCtx` to it.
750///
751/// Use this when your handler closures need per-request context — for
752/// example, an auth identity that controls which data the handler can
753/// access. The closure receives the whole [`CallContext`] and reads the
754/// fields it needs.
755///
756/// # Usage
757///
758/// ```rust,ignore
759/// use jmap_server::{ClosureHandler, Dispatcher};
760/// use std::sync::Arc;
761///
762/// #[derive(Clone)]
763/// struct AuthCtx { user_id: String }
764///
765/// let handler: Arc<ClosureHandler<MyBackend, AuthCtx>> =
766///     Arc::new(ClosureHandler::new(
767///         Arc::new(my_backend),
768///         |b, cx| {
769///             Box::pin(async move {
770///                 // cx.caller.user_id is available here
771///                 handle_something(&*b, cx.args, &cx.caller.user_id).await
772///             })
773///         },
774///     ));
775///
776/// let mut dispatcher: Dispatcher<AuthCtx> = Dispatcher::new();
777/// dispatcher.register("MyMethod/get", handler);
778/// ```
779/// A [`JmapHandler`] handle wrapping a shared backend + an async
780/// closure. Construct via [`ClosureHandler::new`] — the fields are
781/// crate-private (bd:JMAP-jfia.5) to keep the handle opaque, prevent
782/// post-construction hot-swap of the closure or backend, and let the
783/// constructor remain the sole site that enforces invariants when
784/// future fields (per-handler tracing context, metrics handle, etc.)
785/// are added.
786#[non_exhaustive]
787pub struct ClosureHandler<B: Send + Sync + 'static, C: Clone + Send + 'static> {
788    /// Shared reference to the backend implementation, passed to the
789    /// closure on every method call. Crate-private to keep
790    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
791    pub(crate) backend: Arc<B>,
792    /// The async closure invoked for each JMAP method call this handler
793    /// receives from the dispatcher. Crate-private to keep
794    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
795    pub(crate) call_fn: Box<BackendCallFn<B, C>>,
796}
797
798impl<B: Send + Sync + 'static, C: Clone + Send + 'static> ClosureHandler<B, C> {
799    /// Construct a [`ClosureHandler`] wrapping a shared backend and an
800    /// async closure (bd:JMAP-wlip.17).
801    ///
802    /// This is the supported construction path. The struct is
803    /// `#[non_exhaustive]` so future fields (per-handler tracing
804    /// context, metrics handle, timeout, etc.) can be added without a
805    /// major-version bump — external callers MUST go through `new`
806    /// rather than struct-literal syntax.
807    ///
808    /// The `call_fn` parameter is generic over
809    /// `F: Fn(Arc<B>, CallContext<C>) + Send + Sync + 'static`
810    /// (bd:JMAP-jfia.40), so callers can pass a closure directly
811    /// without wrapping it in `Box::new`; an already-boxed closure also
812    /// satisfies the bound. Internally, the closure is boxed once at
813    /// construction and stored as `Box<BackendCallFn<B, C>>`.
814    pub fn new<F>(backend: Arc<B>, call_fn: F) -> Self
815    where
816        F: Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static,
817    {
818        Self {
819            backend,
820            call_fn: Box::new(call_fn),
821        }
822    }
823}
824
825impl<B: Send + Sync + 'static, C: Clone + Send + 'static> JmapHandler<C> for ClosureHandler<B, C> {
826    fn call(&self, cx: CallContext<C>) -> HandlerFuture {
827        (self.call_fn)(Arc::clone(&self.backend), cx)
828    }
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834    use serde_json::{Value, json};
835    use std::sync::{Arc, Mutex};
836
837    // Compile-time: Dispatcher must be Send + Sync so it can be wrapped in Arc
838    // and shared across tokio tasks.  This assertion catches future regressions
839    // that would silently break thread-safety (e.g., adding a Cell or Rc field).
840    #[allow(dead_code)]
841    fn assert_dispatcher_send_sync() {
842        fn check<T: Send + Sync>() {}
843        check::<Dispatcher<String>>();
844        check::<Dispatcher<()>>();
845    }
846
847    // -----------------------------------------------------------------------
848    // Test handler implementations
849    // -----------------------------------------------------------------------
850
851    /// Returns a fixed Value regardless of inputs.
852    struct EchoHandler(Value);
853
854    impl<C: Clone + Send + 'static> JmapHandler<C> for EchoHandler {
855        fn call(&self, _cx: CallContext<C>) -> HandlerFuture {
856            let v = self.0.clone();
857            Box::pin(async move { Ok(HandlerOutput::new(v)) })
858        }
859    }
860
861    /// Returns a fixed error.
862    struct ErrorHandler(JmapError);
863
864    impl JmapHandler<String> for ErrorHandler {
865        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
866            let e = self.0.clone();
867            Box::pin(async move { Err(e) })
868        }
869    }
870
871    /// Captures the resolved args it was called with.
872    struct CaptureArgsHandler(Arc<Mutex<Option<Value>>>);
873
874    impl JmapHandler<String> for CaptureArgsHandler {
875        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
876            let args = cx.args;
877            let slot = self.0.clone();
878            Box::pin(async move {
879                *slot.lock().expect("test: mutex poisoned") = Some(args);
880                Ok(HandlerOutput::new(json!({})))
881            })
882        }
883    }
884
885    /// Captures the caller value it was called with.
886    struct CaptureCallerHandler(Arc<Mutex<Option<String>>>);
887
888    impl JmapHandler<String> for CaptureCallerHandler {
889        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
890            let caller = cx.caller;
891            let slot = self.0.clone();
892            Box::pin(async move {
893                *slot.lock().expect("test: mutex poisoned") = Some(caller);
894                Ok(HandlerOutput::new(json!({})))
895            })
896        }
897    }
898
899    /// Panics unconditionally.
900    struct PanicHandler;
901
902    impl JmapHandler<String> for PanicHandler {
903        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
904            Box::pin(async move { panic!("deliberate test panic") })
905        }
906    }
907
908    // -----------------------------------------------------------------------
909    // Helper: build a minimal JmapRequest with a single method call.
910    // -----------------------------------------------------------------------
911
912    fn single_call(method: &str, args: Value, call_id: &str) -> JmapRequest {
913        JmapRequest::new(
914            vec!["urn:ietf:params:jmap:core".into()],
915            vec![Invocation::new(method, args, call_id)],
916            None,
917        )
918    }
919
920    // -----------------------------------------------------------------------
921    // Basic dispatch
922    // -----------------------------------------------------------------------
923
924    /// Oracle: RFC 8620 §7.1 — unknownMethod when no handler is registered.
925    #[tokio::test]
926    async fn unknown_method_returns_error_invocation() {
927        let d: Dispatcher<String> = Dispatcher::new();
928        let req = single_call("Foo/get", json!({}), "c0");
929        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
930        assert_eq!(resp.method_responses.len(), 1);
931        let Invocation {
932            arguments: args,
933            call_id,
934            ..
935        } = &resp.method_responses[0];
936        assert_eq!(call_id, "c0");
937        assert_eq!(args["type"], "unknownMethod");
938    }
939
940    /// Oracle: RFC 8620 §3.5 — successful call appears in methodResponses.
941    #[tokio::test]
942    async fn known_method_success() {
943        let mut d: Dispatcher<String> = Dispatcher::new();
944        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
945        let req = single_call("Foo/get", json!({}), "c1");
946        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
947        assert_eq!(resp.method_responses.len(), 1);
948        let Invocation {
949            name: method,
950            arguments: args,
951            call_id,
952        } = &resp.method_responses[0];
953        assert_eq!(method, "Foo/get");
954        assert_eq!(call_id, "c1");
955        assert_eq!(args["list"], json!([]));
956    }
957
958    /// A FilterCondition wrapped in `levels` nested `AND` operators.
959    fn nested_filter(levels: usize) -> Value {
960        (0..levels).fold(
961            json!({ "text": "x" }),
962            |inner, _| json!({ "operator": "AND", "conditions": [inner] }),
963        )
964    }
965
966    /// Oracle: RFC 8620 §5.5 (rfc8620.txt:2626) — `unsupportedFilter`
967    /// "The "filter" is syntactically valid, but the server cannot process
968    /// it", and the 32-level cap documented on `parse_request`. A filter
969    /// one operator level past the cap is refused before the handler runs.
970    #[tokio::test]
971    async fn filter_nested_past_cap_is_unsupported_filter() {
972        let slot = Arc::new(Mutex::new(None));
973        let mut d: Dispatcher<String> = Dispatcher::new();
974        d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
975        let req = single_call("Foo/query", json!({ "filter": nested_filter(33) }), "c0");
976        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
977        let Invocation {
978            name, arguments, ..
979        } = &resp.method_responses[0];
980        assert_eq!(name, "error");
981        assert_eq!(arguments["type"], "unsupportedFilter");
982        assert!(
983            slot.lock().expect("test: mutex poisoned").is_none(),
984            "handler must not run on a refused filter"
985        );
986    }
987
988    /// Oracle: RFC 8620 §5.3 / §5.4 type `ifInState`, `ifFromInState` and
989    /// `destroyFromIfInState` as `String|null`; any other value is refused
990    /// with invalidArguments before the handler runs (it would otherwise
991    /// read a number as "absent" and write unconditionally).
992    #[tokio::test]
993    async fn non_string_state_arguments_are_invalid_arguments() {
994        for key in ["ifInState", "ifFromInState", "destroyFromIfInState"] {
995            let slot = Arc::new(Mutex::new(None));
996            let mut d: Dispatcher<String> = Dispatcher::new();
997            d.register("Foo/copy", Arc::new(CaptureArgsHandler(slot.clone())));
998            let req = single_call("Foo/copy", json!({ key: 5 }), "c0");
999            let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1000            let Invocation {
1001                name, arguments, ..
1002            } = &resp.method_responses[0];
1003            assert_eq!(name, "error", "{key}");
1004            assert_eq!(arguments["type"], "invalidArguments", "{key}");
1005            assert!(
1006                slot.lock().expect("test: mutex poisoned").is_none(),
1007                "{key}"
1008            );
1009
1010            let slot = Arc::new(Mutex::new(None));
1011            let mut d: Dispatcher<String> = Dispatcher::new();
1012            d.register("Foo/copy", Arc::new(CaptureArgsHandler(slot.clone())));
1013            for ok in [json!(null), json!("s1")] {
1014                let req = single_call("Foo/copy", json!({ key: ok }), "c0");
1015                let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1016                assert_eq!(resp.method_responses[0].name, "Foo/copy", "{key}");
1017            }
1018        }
1019    }
1020
1021    /// Positive control for the cap: 32 operator levels, the documented
1022    /// limit, still reach the handler unchanged.
1023    #[tokio::test]
1024    async fn filter_nested_at_cap_reaches_handler() {
1025        let slot = Arc::new(Mutex::new(None));
1026        let mut d: Dispatcher<String> = Dispatcher::new();
1027        d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
1028        let args = json!({ "filter": nested_filter(32) });
1029        let req = single_call("Foo/query", args.clone(), "c0");
1030        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1031        assert_eq!(resp.method_responses[0].name, "Foo/query");
1032        assert_eq!(*slot.lock().expect("test: mutex poisoned"), Some(args));
1033    }
1034
1035    /// Oracle: RFC 8620 §3.6.2 — method-level errors appear in methodResponses.
1036    #[tokio::test]
1037    async fn handler_returns_error() {
1038        let mut d: Dispatcher<String> = Dispatcher::new();
1039        d.register("Foo/get", Arc::new(ErrorHandler(JmapError::forbidden())));
1040        let req = single_call("Foo/get", json!({}), "c2");
1041        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1042        assert_eq!(resp.method_responses.len(), 1);
1043        let Invocation {
1044            arguments: args, ..
1045        } = &resp.method_responses[0];
1046        assert_eq!(args["type"], "forbidden");
1047    }
1048
1049    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
1050    /// "The following additional errors may be returned instead of the
1051    /// "Foo/set" response: "requestTooLarge": The total number of objects
1052    /// to create, update, or destroy exceeds the maximum number the server
1053    /// is willing to process in a single method call." The over-cap
1054    /// Foo/set gets an "error" invocation of type requestTooLarge in
1055    /// place of its response, and the next method call in the same
1056    /// request still runs.
1057    #[tokio::test]
1058    async fn set_over_max_objects_is_method_error_request_too_large() {
1059        struct CappedSetHandler;
1060
1061        impl JmapHandler<String> for CappedSetHandler {
1062            fn call(&self, cx: CallContext<String>) -> HandlerFuture {
1063                let args = cx.args;
1064                Box::pin(async move {
1065                    let map = args.as_object().cloned().unwrap_or_default();
1066                    enforce_max_objects_in_set(&map, 1)?;
1067                    Ok(HandlerOutput::new(json!({"created": {}})))
1068                })
1069            }
1070        }
1071
1072        let mut d: Dispatcher<String> = Dispatcher::new();
1073        d.register("Foo/set", Arc::new(CappedSetHandler));
1074        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
1075        let req = JmapRequest::new(
1076            vec!["urn:ietf:params:jmap:core".into()],
1077            vec![
1078                Invocation::new(
1079                    "Foo/set",
1080                    json!({"accountId": "a1", "destroy": ["x1", "x2"]}),
1081                    "c0",
1082                ),
1083                Invocation::new("Foo/get", json!({"accountId": "a1"}), "c1"),
1084            ],
1085            None,
1086        );
1087        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1088        assert_eq!(resp.method_responses.len(), 2);
1089        let Invocation {
1090            name,
1091            arguments: args,
1092            call_id,
1093        } = &resp.method_responses[0];
1094        assert_eq!(name, "error");
1095        assert_eq!(call_id, "c0");
1096        assert_eq!(args["type"], "requestTooLarge");
1097        let Invocation {
1098            name,
1099            arguments: args,
1100            call_id,
1101        } = &resp.method_responses[1];
1102        assert_eq!(name, "Foo/get");
1103        assert_eq!(call_id, "c1");
1104        assert_eq!(args["list"], json!([]));
1105    }
1106
1107    /// Oracle (bd:JMAP-jfia.4): try_register MUST return Ok for the
1108    /// first registration of a method name, and Err(DuplicateMethodError)
1109    /// for any subsequent registration of the same name. On Err the
1110    /// dispatcher's handler map MUST be left unchanged — the
1111    /// already-registered handler stays in place.
1112    /// `methods` lists every registered name once, sorted, whichever of
1113    /// `register` and `try_register` added it (toy-consumer finding b4).
1114    #[test]
1115    fn methods_lists_registered_names_sorted() {
1116        let mut d: Dispatcher<String> = Dispatcher::new();
1117        d.register("Foo/set", Arc::new(EchoHandler(json!({}))));
1118        d.try_register("Bar/get", Arc::new(EchoHandler(json!({}))))
1119            .expect("first registration");
1120        d.register("Foo/get", Arc::new(EchoHandler(json!({}))));
1121        let _ = d.try_register("Foo/get", Arc::new(EchoHandler(json!({}))));
1122        assert_eq!(
1123            d.methods().collect::<Vec<_>>(),
1124            ["Bar/get", "Foo/get", "Foo/set"]
1125        );
1126    }
1127
1128    #[tokio::test]
1129    async fn try_register_succeeds_then_errors_on_duplicate() {
1130        let mut d: Dispatcher<String> = Dispatcher::new();
1131        let first = Arc::new(EchoHandler(json!({"v": "first"})));
1132        let second = Arc::new(EchoHandler(json!({"v": "second"})));
1133
1134        d.try_register("Foo/get", first)
1135            .expect("first registration must succeed");
1136
1137        let err = d
1138            .try_register("Foo/get", second)
1139            .expect_err("second registration must error");
1140        assert_eq!(err.method, "Foo/get");
1141        assert_eq!(
1142            err.to_string(),
1143            "handler already registered for method \"Foo/get\""
1144        );
1145
1146        // The first handler MUST still be the one that fires — try_register
1147        // must NOT have replaced it as a side-effect of the error path.
1148        let req = single_call("Foo/get", json!({}), "c0");
1149        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1150        let Invocation {
1151            arguments: args, ..
1152        } = &resp.method_responses[0];
1153        assert_eq!(
1154            args["v"], "first",
1155            "try_register error path must not replace the existing handler"
1156        );
1157    }
1158
1159    /// Oracle (bd:JMAP-jfia.4): register (the silent-overwrite variant)
1160    /// MUST continue to replace on duplicate, since established consumers
1161    /// depend on that ergonomic for test fixtures. Pins the contract so
1162    /// a future refactor that "fixes" register's silent overwrite is
1163    /// caught.
1164    #[tokio::test]
1165    async fn register_silently_overwrites_on_duplicate() {
1166        let mut d: Dispatcher<String> = Dispatcher::new();
1167        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "first"}))));
1168        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "second"}))));
1169
1170        let req = single_call("Foo/get", json!({}), "c0");
1171        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1172        let Invocation {
1173            arguments: args, ..
1174        } = &resp.method_responses[0];
1175        assert_eq!(args["v"], "second", "register must replace on duplicate");
1176    }
1177
1178    /// Oracle: RFC 8620 §3.4 — sessionState in response matches what dispatcher was given.
1179    #[tokio::test]
1180    async fn session_state_echoed() {
1181        let d: Dispatcher<String> = Dispatcher::new();
1182        let req = JmapRequest::new(vec!["urn:ietf:params:jmap:core".into()], vec![], None);
1183        let resp = d.dispatch(req, "alice".into(), "my-state-123".into()).await;
1184        assert_eq!(resp.session_state.as_ref(), "my-state-123");
1185    }
1186
1187    // -----------------------------------------------------------------------
1188    // Batch
1189    // -----------------------------------------------------------------------
1190
1191    /// Oracle: RFC 8620 §3.3 — methodCalls processed in order, all responses present.
1192    /// Also covers: error in one method does not abort the batch (RFC 8620 §3.6.2).
1193    #[tokio::test]
1194    async fn mixed_batch_all_responses_in_order() {
1195        let mut d: Dispatcher<String> = Dispatcher::new();
1196        d.register("M/a", Arc::new(EchoHandler(json!({"ok": true}))));
1197        // "M/b" is NOT registered → unknownMethod
1198        let req = JmapRequest::new(
1199            vec!["urn:ietf:params:jmap:core".into()],
1200            vec![
1201                Invocation::new("M/a", json!({}), "c0"),
1202                Invocation::new("M/b", json!({}), "c1"),
1203                Invocation::new("M/a", json!({}), "c2"),
1204            ],
1205            None,
1206        );
1207        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1208        assert_eq!(
1209            resp.method_responses.len(),
1210            3,
1211            "all three calls must produce a response"
1212        );
1213        // responses[0]: M/a success
1214        assert_eq!(resp.method_responses[0].call_id, "c0");
1215        assert!(
1216            resp.method_responses[0].arguments.get("type").is_none(),
1217            "c0 must not be an error"
1218        );
1219        // responses[1]: M/b unknownMethod
1220        assert_eq!(resp.method_responses[1].call_id, "c1");
1221        assert_eq!(resp.method_responses[1].arguments["type"], "unknownMethod");
1222        // responses[2]: M/a success (error in [1] did not abort the batch)
1223        assert_eq!(resp.method_responses[2].call_id, "c2");
1224        assert!(
1225            resp.method_responses[2].arguments.get("type").is_none(),
1226            "c2 must not be an error"
1227        );
1228    }
1229
1230    /// Oracle: RFC 8620 §3.6.2 — error in one method does not abort subsequent calls.
1231    #[tokio::test]
1232    async fn error_does_not_abort_subsequent_calls() {
1233        let mut d: Dispatcher<String> = Dispatcher::new();
1234        d.register("M/ok", Arc::new(EchoHandler(json!({"ok": true}))));
1235        d.register("M/err", Arc::new(ErrorHandler(JmapError::forbidden())));
1236        let req = JmapRequest::new(
1237            vec!["urn:ietf:params:jmap:core".into()],
1238            vec![
1239                Invocation::new("M/err", json!({}), "c0"),
1240                Invocation::new("M/ok", json!({}), "c1"),
1241            ],
1242            None,
1243        );
1244        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1245        assert_eq!(resp.method_responses.len(), 2);
1246        assert_eq!(resp.method_responses[0].arguments["type"], "forbidden");
1247        assert!(
1248            resp.method_responses[1].arguments.get("type").is_none(),
1249            "second call must succeed"
1250        );
1251    }
1252
1253    // -----------------------------------------------------------------------
1254    // Panic isolation
1255    // -----------------------------------------------------------------------
1256
1257    /// Oracle: RFC 8620 §7.1 serverFail; PLAN.md panic isolation design decision.
1258    #[tokio::test]
1259    async fn panicking_handler_returns_server_fail() {
1260        let mut d: Dispatcher<String> = Dispatcher::new();
1261        d.register("Panic/now", Arc::new(PanicHandler));
1262        let req = single_call("Panic/now", json!({}), "c0");
1263        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1264        assert_eq!(resp.method_responses.len(), 1);
1265        let Invocation {
1266            arguments: args, ..
1267        } = &resp.method_responses[0];
1268        assert_eq!(
1269            args["type"], "serverFail",
1270            "panicking handler must produce serverFail"
1271        );
1272    }
1273
1274    /// Oracle (bd:JMAP-wlip.12): security invariant — panic payloads
1275    /// may contain secrets and MUST NOT leak through ANY field of the
1276    /// error invocation, not just `description`. A future refactor that
1277    /// surfaces panic-payload text through a typed `context`, an
1278    /// `innerError` nested object, or any other field would slip past a
1279    /// single-field check.
1280    ///
1281    /// The assertion walks the entire methodResponse args Value
1282    /// recursively and asserts that no string anywhere in the tree
1283    /// contains the canary `"deliberate test panic"` from
1284    /// [`PanicHandler`].
1285    ///
1286    /// **Decision record (bd:JMAP-jfia.14)**: a future "simplify" pass
1287    /// will reasonably suggest narrowing this to a single-field check
1288    /// against `args["description"]` because that is where panic
1289    /// payloads land today. That suggestion is **WRONG** and must be
1290    /// rejected: a single-field check encodes the current
1291    /// implementation rather than the security invariant. The
1292    /// recursive walk encodes the actual invariant ("panic-payload
1293    /// text does not leak to the wire, ANYWHERE in the response shape")
1294    /// and survives refactors of the error shape. Defending this
1295    /// shape protects the workspace credential/PII redaction policy
1296    /// from drift.
1297    #[tokio::test]
1298    async fn panic_message_not_in_response() {
1299        /// Returns `true` iff any `Value::String` in the tree
1300        /// contains `needle`.
1301        fn value_contains_recursive(v: &Value, needle: &str) -> bool {
1302            match v {
1303                Value::String(s) => s.contains(needle),
1304                Value::Array(arr) => arr.iter().any(|x| value_contains_recursive(x, needle)),
1305                Value::Object(o) => o.values().any(|x| value_contains_recursive(x, needle)),
1306                Value::Null | Value::Bool(_) | Value::Number(_) => false,
1307            }
1308        }
1309
1310        let mut d: Dispatcher<String> = Dispatcher::new();
1311        d.register("Panic/now", Arc::new(PanicHandler));
1312        let req = single_call("Panic/now", json!({}), "c0");
1313        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1314        let Invocation {
1315            arguments: args, ..
1316        } = &resp.method_responses[0];
1317        assert!(
1318            !value_contains_recursive(args, "deliberate test panic"),
1319            "panic message must not leak into ANY field of the response: {args}"
1320        );
1321    }
1322
1323    // -----------------------------------------------------------------------
1324    // ResultReference end-to-end
1325    // -----------------------------------------------------------------------
1326
1327    /// Oracle: RFC 8620 §3.7 — #-prefixed args resolved from prior responses before handler call.
1328    #[tokio::test]
1329    async fn result_reference_resolved_before_dispatch() {
1330        let captured = Arc::new(Mutex::new(None::<Value>));
1331        let mut d: Dispatcher<String> = Dispatcher::new();
1332        d.register(
1333            "Foo/get",
1334            Arc::new(EchoHandler(json!({"list": [{"id": "item-1"}]}))),
1335        );
1336        d.register(
1337            "Bar/query",
1338            Arc::new(CaptureArgsHandler(Arc::clone(&captured))),
1339        );
1340        let req = JmapRequest::new(
1341            vec!["urn:ietf:params:jmap:core".into()],
1342            vec![
1343                Invocation::new("Foo/get", json!({}), "c0"),
1344                Invocation::new(
1345                    "Bar/query",
1346                    json!({"#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}}),
1347                    "c1",
1348                ),
1349            ],
1350            None,
1351        );
1352        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1353        assert_eq!(resp.method_responses.len(), 2);
1354        // c1 must succeed, not be an error
1355        assert!(
1356            resp.method_responses[1].arguments.get("type").is_none(),
1357            "Bar/query must succeed after ResultReference resolution"
1358        );
1359        // Handler must have received the resolved value, not the original #ids object
1360        let got = captured
1361            .lock()
1362            .unwrap()
1363            .clone()
1364            .expect("CaptureArgsHandler was not called");
1365        assert_eq!(
1366            got["ids"],
1367            json!("item-1"),
1368            "resolved value must be the string item-1"
1369        );
1370        assert!(
1371            got.get("#ids").is_none(),
1372            "#ids key must have been replaced"
1373        );
1374    }
1375
1376    /// Oracle: RFC 8620 §3.7 — resolution failure → error for that call, batch continues.
1377    #[tokio::test]
1378    async fn result_reference_failure_stops_that_call() {
1379        let d: Dispatcher<String> = Dispatcher::new();
1380        let req = single_call(
1381            "Foo/get",
1382            json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
1383            "c0",
1384        );
1385        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1386        assert_eq!(resp.method_responses.len(), 1);
1387        let Invocation {
1388            arguments: args, ..
1389        } = &resp.method_responses[0];
1390        assert!(
1391            args.get("type").is_some(),
1392            "failed ResultReference must produce an error invocation"
1393        );
1394    }
1395
1396    // -----------------------------------------------------------------------
1397    // createdIds
1398    // -----------------------------------------------------------------------
1399
1400    /// Oracle: RFC 8620 §3.3 createdIds — server-assigned IDs returned from /set
1401    /// responses are accumulated into resp.created_ids when client sent createdIds.
1402    #[tokio::test]
1403    async fn created_ids_accumulated_from_set_response() {
1404        let mut d: Dispatcher<String> = Dispatcher::new();
1405        d.register(
1406            "Foo/set",
1407            Arc::new(EchoHandler(
1408                json!({"created": {"client-1": {"id": "server-abc"}}}),
1409            )),
1410        );
1411        // Client sends createdIds (empty map) to signal it wants the response field.
1412        let req = JmapRequest::new(
1413            vec!["urn:ietf:params:jmap:core".into()],
1414            vec![Invocation::new("Foo/set", json!({}), "c0")],
1415            Some(std::collections::BTreeMap::new()),
1416        );
1417        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1418        let ids = resp
1419            .created_ids
1420            .as_ref()
1421            .expect("created_ids must be Some when client sent createdIds");
1422        assert_eq!(
1423            ids.get(&Id::from("client-1")),
1424            Some(&Id::from("server-abc")),
1425            "client-1 must map to server-abc"
1426        );
1427    }
1428
1429    /// Captures the `created_ids` it was called with.
1430    struct CaptureCreatedIdsHandler(Arc<Mutex<Option<BTreeMap<Id, Id>>>>);
1431
1432    impl JmapHandler<String> for CaptureCreatedIdsHandler {
1433        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
1434            *self.0.lock().expect("test: mutex poisoned") = Some(cx.created_ids);
1435            Box::pin(async move { Ok(HandlerOutput::new(json!({}))) })
1436        }
1437    }
1438
1439    /// Oracle: RFC 8620 §5.3 — "the server MUST keep a simple map for
1440    /// the duration of the request of creation id to record id for each
1441    /// newly created record, so it can substitute in the correct value
1442    /// if necessary in later method calls". The map exists whether or
1443    /// not the client sent createdIds; only the response echo depends on
1444    /// that (RFC 8620 §3.4).
1445    #[tokio::test]
1446    async fn created_ids_reach_later_call_without_client_created_ids() {
1447        let slot = Arc::new(Mutex::new(None));
1448        let mut d: Dispatcher<String> = Dispatcher::new();
1449        d.register(
1450            "Graph/set",
1451            Arc::new(EchoHandler(json!({"created": {"g": {"id": "G1"}}}))),
1452        );
1453        d.register(
1454            "GraphNode/set",
1455            Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
1456        );
1457        let req = JmapRequest::new(
1458            vec!["urn:ietf:params:jmap:core".into()],
1459            vec![
1460                Invocation::new("Graph/set", json!({}), "c0"),
1461                Invocation::new("GraphNode/set", json!({}), "c1"),
1462            ],
1463            None,
1464        );
1465        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1466        let seen = slot
1467            .lock()
1468            .expect("test: mutex poisoned")
1469            .take()
1470            .expect("GraphNode/set handler must run");
1471        assert_eq!(
1472            seen,
1473            BTreeMap::from([(Id::from("g"), Id::from("G1"))]),
1474            "later call must see the earlier creation"
1475        );
1476        assert!(
1477            resp.created_ids.is_none(),
1478            "response omits createdIds when the client did not send it"
1479        );
1480    }
1481
1482    /// Oracle: RFC 8620 §5.3 — "an initial set of creation id to real id
1483    /// values may be passed with a request"; the first call must already
1484    /// see them.
1485    #[tokio::test]
1486    async fn created_ids_initial_map_reaches_first_call() {
1487        let slot = Arc::new(Mutex::new(None));
1488        let mut d: Dispatcher<String> = Dispatcher::new();
1489        d.register(
1490            "Email/set",
1491            Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
1492        );
1493        let initial = BTreeMap::from([(Id::from("m"), Id::from("M1"))]);
1494        let req = JmapRequest::new(
1495            vec!["urn:ietf:params:jmap:core".into()],
1496            vec![Invocation::new("Email/set", json!({}), "c0")],
1497            Some(initial.clone()),
1498        );
1499        d.dispatch(req, "alice".into(), "s0".into()).await;
1500        let seen = slot.lock().expect("test: mutex poisoned").take();
1501        assert_eq!(seen, Some(initial));
1502    }
1503
1504    /// Oracle: RFC 8620 §3.4 — createdIds omitted when no objects were created.
1505    #[tokio::test]
1506    async fn created_ids_absent_when_no_set() {
1507        let mut d: Dispatcher<String> = Dispatcher::new();
1508        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
1509        let req = single_call("Foo/get", json!({}), "c0");
1510        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1511        assert!(
1512            resp.created_ids.is_none(),
1513            "created_ids must be None when no /set call created objects"
1514        );
1515    }
1516
1517    /// Oracle: RFC 8620 §3.3 — createdIds accumulates across ALL /set calls in the batch.
1518    #[tokio::test]
1519    async fn created_ids_accumulated_across_multiple_set_calls() {
1520        let mut d: Dispatcher<String> = Dispatcher::new();
1521        d.register(
1522            "A/set",
1523            Arc::new(EchoHandler(json!({"created": {"cA": {"id": "sA"}}}))),
1524        );
1525        d.register(
1526            "B/set",
1527            Arc::new(EchoHandler(json!({"created": {"cB": {"id": "sB"}}}))),
1528        );
1529        // Client sends createdIds to signal it wants the response field.
1530        let req = JmapRequest::new(
1531            vec!["urn:ietf:params:jmap:core".into()],
1532            vec![
1533                Invocation::new("A/set", json!({}), "c0"),
1534                Invocation::new("B/set", json!({}), "c1"),
1535            ],
1536            Some(std::collections::BTreeMap::new()),
1537        );
1538        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1539        let ids = resp
1540            .created_ids
1541            .as_ref()
1542            .expect("created_ids must be Some when client sent createdIds");
1543        assert_eq!(
1544            ids.get(&Id::from("cA")),
1545            Some(&Id::from("sA")),
1546            "cA must be present"
1547        );
1548        assert_eq!(
1549            ids.get(&Id::from("cB")),
1550            Some(&Id::from("sB")),
1551            "cB must be present"
1552        );
1553    }
1554
1555    /// Oracle: RFC 8620 §3.4 — pre-populated client createdIds are preserved and
1556    /// new /set entries are merged in alongside them.
1557    #[tokio::test]
1558    async fn created_ids_merges_with_pre_populated_map() {
1559        let mut d: Dispatcher<String> = Dispatcher::new();
1560        d.register(
1561            "Foo/set",
1562            Arc::new(EchoHandler(
1563                json!({"created": {"client-new": {"id": "server-new"}}}),
1564            )),
1565        );
1566        // Client sends a pre-populated createdIds map.
1567        let mut initial = std::collections::BTreeMap::new();
1568        initial.insert(Id::from("client-old"), Id::from("server-old"));
1569        let req = JmapRequest::new(
1570            vec!["urn:ietf:params:jmap:core".into()],
1571            vec![Invocation::new("Foo/set", json!({}), "c0")],
1572            Some(initial),
1573        );
1574        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1575        let ids = resp
1576            .created_ids
1577            .as_ref()
1578            .expect("created_ids must be Some when client sent createdIds");
1579        assert_eq!(
1580            ids.get(&Id::from("client-old")),
1581            Some(&Id::from("server-old")),
1582            "pre-populated entry must be preserved"
1583        );
1584        assert_eq!(
1585            ids.get(&Id::from("client-new")),
1586            Some(&Id::from("server-new")),
1587            "new /set entry must be merged in"
1588        );
1589    }
1590
1591    /// Oracle (bd:JMAP-jfia.3): when the client pre-populates
1592    /// `createdIds` with `X -> A` and a `/set` call in the same batch
1593    /// returns `X -> B` (`B != A`), the dispatcher applies last-write-
1594    /// wins semantics: the response carries `X -> B`, and the
1595    /// pre-populated `A` is dropped. This is surprising and the spec is
1596    /// ambiguous on which semantics is correct (RFC 8620 §3.4), but
1597    /// matches the intra-batch duplicate convention documented at the
1598    /// dispatch call site and avoids a wire-behaviour change in the
1599    /// canonical foundation crate. The test exists to catch a future
1600    /// refactor that silently flips the order to first-write-wins.
1601    #[tokio::test]
1602    async fn created_ids_pre_populated_collision_last_write_wins() {
1603        let mut d: Dispatcher<String> = Dispatcher::new();
1604        d.register(
1605            "Foo/set",
1606            Arc::new(EchoHandler(
1607                json!({"created": {"client-X": {"id": "server-B"}}}),
1608            )),
1609        );
1610        // Client pre-populates client-X -> server-A.
1611        let mut initial = std::collections::BTreeMap::new();
1612        initial.insert(Id::from("client-X"), Id::from("server-A"));
1613        let req = JmapRequest::new(
1614            vec!["urn:ietf:params:jmap:core".into()],
1615            vec![Invocation::new("Foo/set", json!({}), "c0")],
1616            Some(initial),
1617        );
1618        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1619        let ids = resp
1620            .created_ids
1621            .as_ref()
1622            .expect("created_ids must be Some when client sent createdIds");
1623        assert_eq!(
1624            ids.get(&Id::from("client-X")),
1625            Some(&Id::from("server-B")),
1626            "last-write-wins: /set response overrides pre-populated entry"
1627        );
1628        assert_eq!(
1629            ids.len(),
1630            1,
1631            "no extra entries should appear from the collision"
1632        );
1633    }
1634
1635    /// Oracle (bd:JMAP-jfia.3): when two `/set` calls in the same batch
1636    /// report the same creationId with different values, the
1637    /// dispatcher applies last-write-wins: the second `/set` response's
1638    /// mapping is the one preserved in the final `createdIds` map. The
1639    /// existing dispatch call-site comment documents this convention
1640    /// (bd:JMAP-wlip.7); the test pins it.
1641    #[tokio::test]
1642    async fn created_ids_intra_batch_collision_last_write_wins() {
1643        let mut d: Dispatcher<String> = Dispatcher::new();
1644        d.register(
1645            "A/set",
1646            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sA"}}}))),
1647        );
1648        d.register(
1649            "B/set",
1650            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sB"}}}))),
1651        );
1652        let req = JmapRequest::new(
1653            vec!["urn:ietf:params:jmap:core".into()],
1654            vec![
1655                Invocation::new("A/set", json!({}), "c0"),
1656                Invocation::new("B/set", json!({}), "c1"),
1657            ],
1658            Some(std::collections::BTreeMap::new()),
1659        );
1660        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1661        let ids = resp
1662            .created_ids
1663            .as_ref()
1664            .expect("created_ids must be Some when client sent createdIds");
1665        assert_eq!(
1666            ids.get(&Id::from("cX")),
1667            Some(&Id::from("sB")),
1668            "last-write-wins: second /set call's mapping for cX preserved"
1669        );
1670        assert_eq!(
1671            ids.len(),
1672            1,
1673            "no extra entries should appear from the collision"
1674        );
1675    }
1676
1677    // -----------------------------------------------------------------------
1678    // Method guard
1679    // -----------------------------------------------------------------------
1680
1681    /// Oracle: RFC 8620 §3.6.2 — a method-level error is returned as an
1682    /// `["error", {"type": ...}, callId]` response in place of that call's
1683    /// response, and later calls in the batch are still processed.
1684    #[tokio::test]
1685    async fn guard_rejection_replaces_only_that_call() {
1686        let captured = Arc::new(Mutex::new(None::<String>));
1687        let mut d: Dispatcher<String> = Dispatcher::new();
1688        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
1689        d.register(
1690            "Bar/set",
1691            Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
1692        );
1693        d.set_guard(|method, caller: &String| {
1694            if method == "Bar/set" && caller == "mallory" {
1695                Err(JmapError::forbidden())
1696            } else {
1697                Ok(())
1698            }
1699        });
1700        let batch = || {
1701            JmapRequest::new(
1702                vec!["urn:ietf:params:jmap:core".into()],
1703                vec![
1704                    Invocation::new("Foo/get", json!({}), "c0"),
1705                    Invocation::new("Bar/set", json!({}), "c1"),
1706                    Invocation::new("Foo/get", json!({}), "c2"),
1707                ],
1708                None,
1709            )
1710        };
1711
1712        let resp = d.dispatch(batch(), "mallory".into(), "s0".into()).await;
1713        let got: Vec<(String, Value, String)> = resp
1714            .method_responses
1715            .into_iter()
1716            .map(|i| (i.name, i.arguments, i.call_id))
1717            .collect();
1718        assert_eq!(
1719            got,
1720            vec![
1721                ("Foo/get".into(), json!({"list": []}), "c0".into()),
1722                ("error".into(), json!({"type": "forbidden"}), "c1".into()),
1723                ("Foo/get".into(), json!({"list": []}), "c2".into()),
1724            ]
1725        );
1726        assert!(
1727            captured.lock().unwrap().is_none(),
1728            "rejected call's handler must not run"
1729        );
1730
1731        let resp = d.dispatch(batch(), "alice".into(), "s0".into()).await;
1732        assert_eq!(resp.method_responses[1].name, "Bar/set");
1733        assert_eq!(captured.lock().unwrap().as_deref(), Some("alice"));
1734    }
1735
1736    /// Oracle: bd:JMAP-v9py.15.8 decision — the guard runs after result
1737    /// references resolve (RFC 8620 §3.7 `invalidResultReference` wins) and
1738    /// before handler lookup (a rejected unregistered method gets the
1739    /// guard's error, not RFC 8620 §3.6.2 `unknownMethod`).
1740    #[tokio::test]
1741    async fn guard_runs_after_reference_resolution_before_lookup() {
1742        let mut d: Dispatcher<String> = Dispatcher::new();
1743        d.set_guard(|_, _: &String| Err(JmapError::forbidden()));
1744        let req = JmapRequest::new(
1745            vec!["urn:ietf:params:jmap:core".into()],
1746            vec![
1747                Invocation::new(
1748                    "Foo/get",
1749                    json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
1750                    "c0",
1751                ),
1752                Invocation::new("Unregistered/get", json!({}), "c1"),
1753            ],
1754            None,
1755        );
1756        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1757        assert_eq!(resp.method_responses.len(), 2);
1758        assert_eq!(
1759            resp.method_responses[0].arguments["type"],
1760            "invalidResultReference"
1761        );
1762        assert_eq!(resp.method_responses[1].arguments["type"], "forbidden");
1763    }
1764
1765    // -----------------------------------------------------------------------
1766    // CallerCtx
1767    // -----------------------------------------------------------------------
1768
1769    /// Oracle: PLAN.md CallerCtx design — caller value passed through to handler unchanged.
1770    #[tokio::test]
1771    async fn caller_ctx_passed_to_handler() {
1772        let captured = Arc::new(Mutex::new(None::<String>));
1773        let mut d: Dispatcher<String> = Dispatcher::new();
1774        d.register(
1775            "Foo/get",
1776            Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
1777        );
1778        let req = single_call("Foo/get", json!({}), "c0");
1779        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1780        assert!(
1781            resp.method_responses[0].arguments.get("type").is_none(),
1782            "must succeed"
1783        );
1784        let got = captured
1785            .lock()
1786            .unwrap()
1787            .clone()
1788            .expect("handler was not called");
1789        assert_eq!(got, "alice", "caller must be passed through unchanged");
1790    }
1791
1792    /// Oracle: PLAN.md — CallerCtx = () must work (unit type as auth context).
1793    #[tokio::test]
1794    async fn unit_caller_ctx_works() {
1795        let mut d: Dispatcher<()> = Dispatcher::new();
1796        d.register("Foo/get", Arc::new(EchoHandler(json!({"ok": true}))));
1797        let req = single_call("Foo/get", json!({}), "c0");
1798        let resp = d.dispatch(req, (), "s0".into()).await;
1799        assert_eq!(resp.method_responses.len(), 1);
1800        assert!(
1801            resp.method_responses[0].arguments.get("type").is_none(),
1802            "must succeed with () caller"
1803        );
1804    }
1805
1806    // -----------------------------------------------------------------------
1807    // Extra invocations
1808    // -----------------------------------------------------------------------
1809
1810    /// A handler that returns both a primary response and one extra invocation.
1811    ///
1812    /// Models RFC 8621 §7.5 EmailSubmission/set with onSuccessUpdateEmail: the
1813    /// submission response is primary; the implied Email/set call is extra.
1814    struct ExtraInvocationHandler;
1815
1816    impl JmapHandler<String> for ExtraInvocationHandler {
1817        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
1818            Box::pin(async move {
1819                let primary = json!({"type": "primary"});
1820                let extra: Vec<Invocation> = vec![Invocation::new(
1821                    "Extra/call",
1822                    json!({"type": "extra"}),
1823                    "x0",
1824                )];
1825                Ok(HandlerOutput::new(primary).with_extra(extra))
1826            })
1827        }
1828    }
1829
1830    /// Oracle: handler returning extra invocations → both primary and extra appear in
1831    /// methodResponses in order (primary first, then extra).
1832    #[tokio::test]
1833    async fn extra_invocations_appended_after_primary() {
1834        let mut d: Dispatcher<String> = Dispatcher::new();
1835        d.register("Sub/set", Arc::new(ExtraInvocationHandler));
1836        let req = single_call("Sub/set", json!({}), "c0");
1837        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
1838
1839        assert_eq!(
1840            resp.method_responses.len(),
1841            2,
1842            "primary + 1 extra = 2 total invocations"
1843        );
1844        // First: the primary Sub/set response.
1845        assert_eq!(resp.method_responses[0].name, "Sub/set");
1846        assert_eq!(resp.method_responses[0].call_id, "c0");
1847        assert_eq!(resp.method_responses[0].arguments["type"], "primary");
1848        // Second: the appended extra invocation.
1849        assert_eq!(resp.method_responses[1].name, "Extra/call");
1850        assert_eq!(resp.method_responses[1].call_id, "x0");
1851        assert_eq!(resp.method_responses[1].arguments["type"], "extra");
1852    }
1853
1854    /// Oracle: ClosureHandler forwards CallerCtx to the closure.
1855    /// The closure receives the exact same value that was passed to dispatch().
1856    #[tokio::test]
1857    async fn closure_handler_forwards_caller() {
1858        #[derive(Clone)]
1859        struct Ctx(String);
1860
1861        struct DummyBackend;
1862
1863        // Use a shared capture to record what ctx the closure received.
1864        let received: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
1865        let received_clone = Arc::clone(&received);
1866
1867        let handler: Arc<ClosureHandler<DummyBackend, Ctx>> = Arc::new(ClosureHandler::new(
1868            Arc::new(DummyBackend),
1869            move |_b: Arc<DummyBackend>, cx: CallContext<Ctx>| {
1870                let cap = Arc::clone(&received_clone);
1871                Box::pin(async move {
1872                    *cap.lock().unwrap() = Some(cx.caller.0.clone());
1873                    Ok(HandlerOutput::new(serde_json::json!({})))
1874                })
1875            },
1876        ));
1877
1878        let ctx = Ctx("alice".to_owned());
1879        handler
1880            .call(CallContext::new(
1881                "Test/get",
1882                "c1",
1883                serde_json::json!({}),
1884                ctx,
1885            ))
1886            .await
1887            .expect("handler must succeed");
1888
1889        assert_eq!(
1890            received.lock().unwrap().as_deref(),
1891            Some("alice"),
1892            "CallerCtx must be forwarded to the closure"
1893        );
1894    }
1895
1896    /// Oracle: RFC 8620 §3.2 — an Invocation is a method name, its
1897    /// arguments and a method call id. Dispatching `["Foo/get",
1898    /// {"accountId": "a1"}, "c7"]` through a ClosureHandler MUST hand the
1899    /// closure exactly that name, id and arguments (the method name was
1900    /// dropped before bd:JMAP-wf92.7).
1901    #[tokio::test]
1902    async fn closure_handler_receives_method_call_id_and_args() {
1903        struct DummyBackend;
1904        let seen: Arc<Mutex<Option<(String, String, Value)>>> = Arc::new(Mutex::new(None));
1905        let seen_clone = Arc::clone(&seen);
1906        let handler = ClosureHandler::new(
1907            Arc::new(DummyBackend),
1908            move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
1909                *seen_clone.lock().unwrap() = Some((cx.method, cx.call_id, cx.args));
1910                Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
1911            },
1912        );
1913        let mut d: Dispatcher<()> = Dispatcher::new();
1914        d.register("Foo/get", Arc::new(handler));
1915        d.dispatch(
1916            single_call("Foo/get", json!({"accountId": "a1"}), "c7"),
1917            (),
1918            "s0".into(),
1919        )
1920        .await;
1921        assert_eq!(
1922            seen.lock().unwrap().take(),
1923            Some((
1924                "Foo/get".to_owned(),
1925                "c7".to_owned(),
1926                json!({"accountId": "a1"})
1927            ))
1928        );
1929    }
1930
1931    /// Oracle: RFC 8620 §5.3 — creates happen "before their creation ids
1932    /// are referenced by another create/update/destroy in the same call",
1933    /// and the server substitutes ids "in later method calls". The
1934    /// dispatcher hands every Foo/set handler update keys and destroy ids
1935    /// that name earlier calls' creations already resolved; an unknown
1936    /// reference, a non-/set method, and a creation id this call creates
1937    /// itself stay as sent.
1938    #[tokio::test]
1939    async fn dispatch_resolves_set_update_keys_and_destroy_ids() {
1940        struct DummyBackend;
1941        let seen: Arc<Mutex<Vec<Value>>> = Arc::new(Mutex::new(Vec::new()));
1942        let seen_clone = Arc::clone(&seen);
1943        let handler = ClosureHandler::new(
1944            Arc::new(DummyBackend),
1945            move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
1946                seen_clone.lock().unwrap().push(cx.args.clone());
1947                Box::pin(async { Ok(HandlerOutput::new(json!({"created": {"k": {"id": "K1"}}}))) })
1948                    as HandlerFuture
1949            },
1950        );
1951        let handler: Arc<dyn JmapHandler<()>> = Arc::new(handler);
1952        let mut d: Dispatcher<()> = Dispatcher::new();
1953        d.register("Foo/set", Arc::clone(&handler));
1954        d.register("Foo/other", handler);
1955        let req = JmapRequest::new(
1956            vec!["urn:ietf:params:jmap:core".into()],
1957            vec![
1958                Invocation::new("Foo/set", json!({"create": {"k": {}}}), "c0"),
1959                Invocation::new(
1960                    "Foo/set",
1961                    json!({"create": {"n": {}}, "update": {"#k": {}, "#n": {}, "#nope": {}},
1962                           "destroy": ["#k", "#n", "#nope"]}),
1963                    "c1",
1964                ),
1965                Invocation::new("Foo/other", json!({"update": {"#k": {}}}), "c2"),
1966            ],
1967            None,
1968        );
1969        d.dispatch(req, (), "s0".into()).await;
1970        let seen = seen.lock().unwrap();
1971        assert_eq!(
1972            seen[1],
1973            json!({"create": {"n": {}}, "update": {"K1": {}, "#n": {}, "#nope": {}},
1974                   "destroy": ["K1", "#n", "#nope"]})
1975        );
1976        assert_eq!(seen[2], json!({"update": {"#k": {}}}));
1977    }
1978
1979    /// Oracle: RFC 8620 §3.3 — the Request object's `using` is "The set
1980    /// of capabilities the client wishes to use"; draft-ietf-jmap-metadata-05
1981    /// §3 makes `Foo/changes` behaviour depend on whether it "includes
1982    /// urn:ietf:params:jmap:metadata", so the dispatcher MUST hand every
1983    /// handler the request's `using` list unchanged.
1984    #[tokio::test]
1985    async fn dispatch_passes_request_using_to_handler() {
1986        struct DummyBackend;
1987        let seen: Arc<Mutex<Option<Vec<String>>>> = Arc::new(Mutex::new(None));
1988        let seen_clone = Arc::clone(&seen);
1989        let handler = ClosureHandler::new(
1990            Arc::new(DummyBackend),
1991            move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
1992                *seen_clone.lock().unwrap() = Some(cx.using);
1993                Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
1994            },
1995        );
1996        let mut d: Dispatcher<()> = Dispatcher::new();
1997        d.register("Foo/changes", Arc::new(handler));
1998        let req = JmapRequest::new(
1999            vec![
2000                "urn:ietf:params:jmap:core".into(),
2001                "urn:ietf:params:jmap:metadata".into(),
2002            ],
2003            vec![Invocation::new(
2004                "Foo/changes",
2005                json!({"accountId": "a1", "sinceState": "s1"}),
2006                "c0",
2007            )],
2008            None,
2009        );
2010        d.dispatch(req, (), "s0".into()).await;
2011        assert_eq!(
2012            seen.lock().unwrap().take(),
2013            Some(vec![
2014                "urn:ietf:params:jmap:core".to_owned(),
2015                "urn:ietf:params:jmap:metadata".to_owned(),
2016            ])
2017        );
2018    }
2019
2020    /// Oracle: ClosureHandler implements JmapHandler<C> and can be
2021    /// registered with Dispatcher<C>.
2022    #[test]
2023    fn closure_handler_is_jmap_handler() {
2024        // Compile-time check: ClosureHandler<B, C> must satisfy JmapHandler<C>.
2025        fn assert_handler<C: Clone + Send + 'static, H: JmapHandler<C>>(_: &H) {}
2026
2027        struct DummyBackend;
2028        #[derive(Clone)]
2029        struct Ctx;
2030
2031        let h = ClosureHandler::new(Arc::new(DummyBackend), |_b, _cx| {
2032            Box::pin(async { Ok(HandlerOutput::new(serde_json::json!({}))) })
2033        });
2034        assert_handler::<Ctx, _>(&h);
2035    }
2036}