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