pub struct Dispatcher<CallerCtx> { /* private fields */ }Expand description
Dispatches a JmapRequest to registered method handlers.
Register handlers with Dispatcher::register, then call
Dispatcher::dispatch per request. CallerCtx is cloned for each
method call in the batch, so it must be Clone.
CallerCtx must also be 'static because each handler call is spawned as
a tokio::task. To share non-static data (e.g. a database connection),
wrap it in Arc<T> — Arc is Clone + Send + 'static when T: Send + Sync.
§Thread safety
Dispatcher is both Send and Sync. Register handlers on one thread,
then wrap in Arc and share across tasks — dispatch takes &self and is
safe to call concurrently.
Implementations§
Source§impl<C: Clone + Send + 'static> Dispatcher<C>
impl<C: Clone + Send + 'static> Dispatcher<C>
Sourcepub fn attach_set_support(
&mut self,
method: &str,
support: SetSupport<C>,
) -> Result<(), RegistrationError>
pub fn attach_set_support( &mut self, method: &str, support: SetSupport<C>, ) -> Result<(), RegistrationError>
Attach conditional support to the registered Foo/set method.
Replaces support attached before. A later Dispatcher::register
of method drops it, so an overriding handler must opt in again;
until then the method shows in conditional_gaps.
§Errors
RegistrationError when method is not registered, does not end
in /set, or is not "<support's data type>/set".
Sourcepub fn conditional_gaps(&self) -> Vec<String>
pub fn conditional_gaps(&self) -> Vec<String>
The registered Foo/set methods conditional-02 cannot serve yet: those
without attached SetSupport, or whose "<type>/get" is not
registered (the dispatcher reads preconditions through it). Sorted.
Sourcepub fn conditional_ready(&self) -> bool
pub fn conditional_ready(&self) -> bool
Whether conditional-02 can be advertised: some support is attached
and conditional_gaps is empty.
A server MUST NOT put urn:ietf:params:jmap:conditional in its
Session unless this is true: the capability covers “every Foo/set”
(§2.1).
Source§impl<C: Clone + Send + 'static> Dispatcher<C>
impl<C: Clone + Send + 'static> Dispatcher<C>
Sourcepub fn register_history_aware(
&mut self,
method: impl Into<String>,
handler: Arc<dyn JmapHandler<C>>,
)
pub fn register_history_aware( &mut self, method: impl Into<String>, handler: Arc<dyn JmapHandler<C>>, )
Register a history-aware handler for method and mark it, for
object_history_gaps. A later plain
register of the same name clears the mark.
Sourcepub fn object_history_gaps(&self, supported_types: &[&str]) -> Vec<String>
pub fn object_history_gaps(&self, supported_types: &[&str]) -> Vec<String>
The registered /get, /set, /query and /queryChanges methods
of supported_types that are not history-aware, sorted. A server
MUST NOT list a type in supportedTypes while it has a gap here,
for example after a plain register_<x>_handlers ran last and
silently dropped restore.
Source§impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx>
impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx>
Sourcepub fn set_guard(
&mut self,
guard: impl Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync + 'static,
)
pub fn set_guard( &mut self, guard: impl Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync + 'static, )
Install a guard that every method call must pass before its handler runs.
Dispatcher::dispatch calls guard with the method name and the
caller after resolving the call’s result references and before
looking up its handler. An Err becomes that call’s error response
(RFC 8620 §3.6.2), in its place in methodResponses; the handler
does not run, and later calls in the batch are still processed.
A rejected call produces no result for later references to resolve
against (RFC 8620 §3.7).
Without a guard every call reaches its handler. Setting a guard again replaces the previous one.
Sourcepub fn register(
&mut self,
method: impl Into<String>,
handler: Arc<dyn JmapHandler<CallerCtx>>,
)
pub fn register( &mut self, method: impl Into<String>, handler: Arc<dyn JmapHandler<CallerCtx>>, )
Register a handler for the given method name.
Registering the same name twice silently replaces the earlier
handler. This is a real foot-gun in the workspace pattern where
each extension crate ships a register_*_handlers macro that
registers ~10 method names against a single Dispatcher: a typo
or accidental double-registration drops one binding with no
diagnostic, and the handler that “never fires” is hard to debug
(bd:JMAP-jfia.4). Prefer Dispatcher::try_register in new
code; register is kept for ergonomic call sites where the
silent-overwrite is the deliberate choice (e.g. a test fixture
that overrides a handler for a specific scenario).
Using Arc rather than Box allows the same handler instance to be
shared across multiple method name registrations (via Arc::clone).
Drops any conditional support attached to method
(Dispatcher::attach_set_support) and any history-aware mark
(Dispatcher::register_history_aware): the new handler must opt
in again.
Sourcepub fn try_register(
&mut self,
method: impl Into<String>,
handler: Arc<dyn JmapHandler<CallerCtx>>,
) -> Result<(), DuplicateMethodError>
pub fn try_register( &mut self, method: impl Into<String>, handler: Arc<dyn JmapHandler<CallerCtx>>, ) -> Result<(), DuplicateMethodError>
Register a handler for the given method name, returning an error if the method name is already registered.
This is the recommended registration entry point for production
code paths (bd:JMAP-jfia.4). Unlike Dispatcher::register, a
duplicate method name produces
DuplicateMethodError rather than silently replacing the
existing handler, surfacing the collision at the call site that
caused it.
On Err(DuplicateMethodError) the dispatcher’s handler map is
left unchanged — the existing handler is preserved and the
would-be registration is dropped.
Using Arc rather than Box allows the same handler instance to be
shared across multiple method name registrations (via Arc::clone).
§Errors
Returns DuplicateMethodError when method is already
registered.
Sourcepub fn methods(&self) -> impl Iterator<Item = &str> + '_
pub fn methods(&self) -> impl Iterator<Item = &str> + '_
The names of the methods registered on this dispatcher, in sorted
order: every name Self::register or Self::try_register took,
including those an extension crate’s register_*_handlers added.
For a front dispatcher that bridges every method an inner one serves, or a Session object that lists what is served.
use jmap_server::Dispatcher;
let dispatcher: Dispatcher<()> = Dispatcher::new();
assert_eq!(dispatcher.methods().count(), 0);Sourcepub async fn dispatch(
&self,
request: JmapRequest,
caller: CallerCtx,
session_state: State,
) -> JmapResponse
pub async fn dispatch( &self, request: JmapRequest, caller: CallerCtx, session_state: State, ) -> JmapResponse
Process a validated JmapRequest and return a JmapResponse.
Method calls are processed sequentially per RFC 8620 §3.3. Each
handler runs in a tokio::task::spawn for panic isolation: a panicking
handler returns a serverFail invocation rather than crashing the
connection task, and emits one tracing::error! event with only the
method and call_id fields (never the panic payload or arguments).
CallerCtx must be Clone + Send + 'static; see the struct-level doc.
§Runtime requirement (bd:JMAP-jfia.24)
dispatch invokes tokio::task::spawn internally and
therefore requires a Tokio runtime in scope at the call
site. The async-fn signature itself does not advertise this
requirement — there is no ?Send async-trait bound and no
Spawner parameter — but calling dispatch without a Tokio
runtime will panic at the first method call with a
there is no reactor running error.
This is a structural coupling to the Tokio ecosystem.
Production consumers running under tokio::main /
Runtime::block_on already satisfy this; consumers
experimenting with alternative runtimes (async-std,
smol, embassy, etc.) cannot use Dispatcher without
either a Tokio compat shim or a custom dispatcher
re-implementation. Decoupling the spawn mechanism is a
major-bump API change tracked separately.
§Cancellation
Dropping the future returned by dispatch does not cancel
method calls that are already running (bd:JMAP-wlip.34). Each
call runs in its own tokio::task::spawned task, and tokio
does not abort a task when its JoinHandle is dropped, so a
running call finishes and only its response is lost. Calls
later in the batch that had not started yet are never run.
This is deliberate: a client that disconnects (for example,
the HTTP connection closes) can never interrupt a backend
mid-write and leave a /set half applied. dispatch takes no
cancellation token, and JmapHandler::call receives none.
The cost is that a disconnected client cannot stop an
expensive call (a large Email/query, a slow full-text
search): the backend does the full work anyway, and a client
that opens and drops many requests can use this to consume
server resources. Bound that cost in the backend, for example
with tokio::time::timeout or an RPC deadline around each
storage call, and limit request concurrency per client.
For a clean shutdown, stop accepting new requests and let
in-flight dispatch calls and their spawned tasks finish; a
shutdown signal that drops dispatch futures does not reach
the spawned tasks.