Skip to main content

Dispatcher

Struct Dispatcher 

Source
pub struct Dispatcher<P, Ctx, D> { /* private fields */ }
Expand description

Builds a compile-time dispatch chain in its type parameter D. The chain is unrolled in Self::sequential_dispatch or Self::dispatch.

Use Self::seq to add sequential handlers (&mut Ctx, !Send future) or Self::on to add concurrent handlers (Ctx: Clone + Send, spawned as tasks).

Implementations§

Source§

impl<P, Ctx, D> Dispatcher<P, Ctx, D>
where D: DispatchEvent<Ctx>,

Source

pub fn seq<Ev, F>(self, f: F) -> Dispatcher<P, Ctx, Intercept<Match<Ev, F>, D>>

Register a sequential event handler.

  • The handler signature is AsyncFnMut(ev: Arc<{EventType}>, ctx: &mut Ctx) -> Result<StreamEvents, {ErrorType}>
  • Ctx is whatever type you pass when creating the dispatcher with events.into_local_dispatcher(ctx). It will be passed by a mutable reference into all handlers
  • {Eventype} is one of the data structs defined in crate::events. Events are dispatched statically so this type links the handler to event. When handlers with the same {EvenType} are set multiple times the last one wins.
  • {ErrorType} can be arbitrary but all handlers must share it and it must implement From<ClientError>.
  • Events are processed one at a time; handlers have exclusive &mut access to Ctx.
§Usage
  • Set async fn
events.into_dispatcher(client)
    .seq(contact_connected)
    .sequential_dispatch()
    .await;

async fn contact_connected(
    ev: Arc<ContactConnected>,
    ctx: &mut ws::Client,
) -> ClientResult<StreamEvents> { ... }
  • Set async closure by fully qualifying types
events.into_local_dispatcher(client)
    .seq_fallback(async |ev, _| log::debug!("{ev:?}"))
    .seq::<ContactConnected, _>(async |ev, &mut client| { ... })
    .sequential_dispatch()
    .await;
  • Set async closure by specifying closure argument type
events.into_local_dispatcher(client)
    .seq_fallback(async |ev, _| log::debug!("{ev:?}"))
    .seq(async |ev: Arc<ContactConnected>, &mut client| {
        //...
    })
    .sequential_dispatch()
    .await;
Source

pub async fn sequential_dispatch( self, ) -> Result<(EventStream<P>, Ctx), D::Error>
where P: EventParser, D::Error: From<P::Error>,

Dispatch events sequentially. Handlers block the event loop, allowing exclusive &mut Ctx access. Returning StreamEvents::Break stops the dispatcher and returns the event stream and ctx for further processing.

Produces a !Send future that can be used with tokio::task::LocalSet, on the main tokio thread, or with a single-threaded runtime.

Source

pub async fn sequential_dispatch_with_cancellation( self, token: CancellationToken, ) -> Result<(EventStream<P>, Ctx), D::Error>
where P: EventParser, D::Error: From<P::Error>,

Available on crate feature cancellation only.

Like Self::sequential_dispatch but stops when token is cancelled. Token cancellation is equivalent to returning StreamEvents::Break.

Source§

impl<P, Ctx, D> Dispatcher<P, Ctx, D>
where P: 'static + EventParser, Ctx: 'static + Send + Clone, D: ConcurrentDispatchEvent<Ctx>, D::Error: From<P::Error>,

Source

pub fn on<Ev, F, Fut>( self, f: F, ) -> Dispatcher<P, Ctx, Intercept<Match<Ev, F>, D>>
where Ev: 'static + EventData, F: Fn(Arc<Ev>, Ctx) -> Fut, Fut: 'static + Send + Future<Output = Result<StreamEvents, D::Error>>,

Register a concurrent event handler.

  • The handler signature is AsyncFn(ev: Arc<{EventType}>, ctx: Ctx) -> Result<StreamEvents, {ErrorType}>;
  • Ctx is whatever is passed into the into_dispatcher call. It is cloned into every handler invocation
  • {Eventype} is one of the data structs defined in crate::events. Events are dispatched statically so this type links the handler to event. When handlers with the same {EvenType} are set multiple times the last one wins.
  • {ErrorType} can be arbitrary but all handlers must share it and it must implement From<ClientError>.
  • All handlers run as tokio tasks so events are processed concurrently(and in parallel on multithreaded runtimes).
§Usage
  • Set async fn
events.into_dispatcher(client)
    .on(contact_connected)
    .dispatch()
    .await;

async fn contact_connected(
    ev: Arc<ContactConnected>,
    ctx: ws::Client,
) -> ClientResult<StreamEvents> { ... }
  • Set async closure by fully qualifying types
events.into_dispatcher(client)
    .fallback(async |ev, _| log::debug!("{ev:?}"))
    .on::<ContactConnected, _, _>(async |ev, client| { ... })
    .dispatch()
    .await;
  • Set async closure by specifying closure argument type
events.into_dispatcher(client)
    .fallback(async |ev, _| log::debug!("{ev:?}"))
    .on(async |ev: Arc<ContactConnected>, client| { ... })
    .dispatch()
    .await;
Source

pub async fn dispatch( self, ) -> Result<(EventStream<P>, Ctx, Vec<Event>), D::Error>

Spawns handlers as tokio tasks. Handlers execute and resolve in arbitrary order. StreamEvents::Break eventually stops the dispatcher after all in-flight handlers finish. The returned EventStream filters should be reset via EventStream::accept_all if you want to query the stream manually and process all events afterwards.

§Errors and panics

If a handler returns an error or panics, the dispatcher stops, waits for in-flight handlers to complete, then returns the first error or resumes the first panic.

Source

pub async fn dispatch_with_cancellation( self, token: CancellationToken, ) -> Result<(EventStream<P>, Ctx, Vec<Event>), D::Error>

Available on crate feature cancellation only.

Like Self::dispatch but stops when token is cancelled. Token cancellation behaviour is equivalent to returning StreamEvents::Break.

Source

pub async fn dispatch_sequentially( self, ) -> Result<(EventStream<P>, Ctx), D::Error>

Runs concurrent handlers one at a time, producing a 'static + Send future.

Unlike Dispatcher::sequential_dispatch this clones Ctx per event (no &mut) and the resulting future is Send. Use when handler execution order matters but you need a sendable future, e.g. inside tokio::spawn.

Source

pub async fn dispatch_sequentially_with_cancellation( self, token: CancellationToken, ) -> Result<(EventStream<P>, Ctx), D::Error>

Available on crate feature cancellation only.

Like Self::dispatch_sequentially but stops when token is cancelled.

Auto Trait Implementations§

§

impl<P, Ctx, D> Freeze for Dispatcher<P, Ctx, D>
where Ctx: Freeze, D: Freeze,

§

impl<P, Ctx, D> !RefUnwindSafe for Dispatcher<P, Ctx, D>

§

impl<P, Ctx, D> !Send for Dispatcher<P, Ctx, D>

§

impl<P, Ctx, D> !Sync for Dispatcher<P, Ctx, D>

§

impl<P, Ctx, D> Unpin for Dispatcher<P, Ctx, D>
where Ctx: Unpin, D: Unpin,

§

impl<P, Ctx, D> UnsafeUnpin for Dispatcher<P, Ctx, D>
where Ctx: UnsafeUnpin, D: UnsafeUnpin,

§

impl<P, Ctx, D> !UnwindSafe for Dispatcher<P, Ctx, D>

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, 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V