Skip to main content

Dispatcher

Struct Dispatcher 

Source
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<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx>

Source

pub fn new() -> Self

Create an empty dispatcher with no registered handlers.

Source

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.

Source

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).

Source

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.

Source

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.

Trait Implementations§

Source§

impl<CallerCtx> Debug for Dispatcher<CallerCtx>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<CallerCtx: Clone + Send + 'static> Default for Dispatcher<CallerCtx>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<CallerCtx> !RefUnwindSafe for Dispatcher<CallerCtx>

§

impl<CallerCtx> !UnwindSafe for Dispatcher<CallerCtx>

§

impl<CallerCtx> Freeze for Dispatcher<CallerCtx>
where HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>: Freeze, Option<Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Sync + Send>>: Freeze,

§

impl<CallerCtx> Send for Dispatcher<CallerCtx>
where HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>: Send, Option<Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Sync + Send>>: Send,

§

impl<CallerCtx> Sync for Dispatcher<CallerCtx>
where HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>: Sync, Option<Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Sync + Send>>: Sync,

§

impl<CallerCtx> Unpin for Dispatcher<CallerCtx>
where HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>: Unpin, Option<Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Sync + Send>>: Unpin,

§

impl<CallerCtx> UnsafeUnpin for Dispatcher<CallerCtx>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more