Skip to main content

djs_rs/
handler.rs

1//! Type-erased storage of event handlers.
2
3use std::{future::Future, marker::PhantomData, pin::Pin, sync::Arc};
4
5use djs_cache::Backend;
6
7use crate::{
8    Context,
9    event::{Dispatch, Event, EventKind},
10    router::Routes,
11};
12
13/// The error type event handlers may return. Any error type converts into it with `?`.
14pub type HandlerError = Box<dyn std::error::Error + Send + Sync>;
15
16pub(crate) type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
17
18/// A registered handler with its event type erased.
19pub(crate) trait ErasedHandler<B: Backend>: Send + Sync {
20    /// Spawns the handler on the tokio runtime if `dispatch` is its event. The handler future is
21    /// spawned directly (no extra boxing).
22    fn spawn(&self, ctx: &Context<B>, dispatch: &Dispatch);
23
24    /// Returns the handler future for sequential execution, if `dispatch` is its event.
25    fn call(&self, ctx: &Context<B>, dispatch: &Dispatch) -> Option<BoxFuture>;
26}
27
28pub(crate) struct Handler<E, F> {
29    handler: F,
30    event: PhantomData<fn() -> E>,
31}
32
33impl<E, F> Handler<E, F> {
34    pub(crate) const fn new(handler: F) -> Self {
35        Self {
36            handler,
37            event: PhantomData,
38        }
39    }
40}
41
42/// Runs a handler future and reports its error, if any.
43async fn run<E: Event>(future: impl Future<Output = Result<(), HandlerError>>) {
44    if let Err(error) = future.await {
45        tracing::error!(event = E::NAME, %error, "event handler returned an error");
46    }
47}
48
49impl<B, E, F, Fut> ErasedHandler<B> for Handler<E, F>
50where
51    B: Backend,
52    E: Event,
53    F: Fn(Context<B>, Arc<E::Payload>) -> Fut + Send + Sync + 'static,
54    Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
55{
56    fn spawn(&self, ctx: &Context<B>, dispatch: &Dispatch) {
57        if let Some(payload) = E::payload(dispatch) {
58            tokio::spawn(run::<E>((self.handler)(ctx.clone(), Arc::clone(payload))));
59        }
60    }
61
62    fn call(&self, ctx: &Context<B>, dispatch: &Dispatch) -> Option<BoxFuture> {
63        let payload = E::payload(dispatch)?;
64        Some(Box::pin(run::<E>((self.handler)(
65            ctx.clone(),
66            Arc::clone(payload),
67        ))))
68    }
69}
70
71/// Handlers per event kind. Replaced as a whole (copy-on-write) when a handler is added, so
72/// dispatching only needs to clone an `Arc`.
73pub(crate) struct Registry<B: Backend> {
74    handlers: [Vec<Arc<dyn ErasedHandler<B>>>; EventKind::COUNT],
75    /// The interaction routes (D-251).
76    pub(crate) routes: Routes<B>,
77}
78
79impl<B: Backend> Default for Registry<B> {
80    fn default() -> Self {
81        Self {
82            handlers: core::array::from_fn(|_| Vec::new()),
83            routes: Routes::default(),
84        }
85    }
86}
87
88impl<B: Backend> Clone for Registry<B> {
89    fn clone(&self) -> Self {
90        Self {
91            handlers: self.handlers.clone(),
92            routes: self.routes.clone(),
93        }
94    }
95}
96
97impl<B: Backend> Registry<B> {
98    pub(crate) fn with(&self, kind: EventKind, handler: Arc<dyn ErasedHandler<B>>) -> Self {
99        let mut registry = self.clone();
100        registry.handlers[kind as usize].push(handler);
101        registry
102    }
103
104    pub(crate) fn get(&self, kind: EventKind) -> &[Arc<dyn ErasedHandler<B>>] {
105        &self.handlers[kind as usize]
106    }
107}