ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Event dispatcher, shaped like Laravel's events: listeners are keyed by event type and
//! run in registration order.
//!
//! ```
//! # #[tokio::main] async fn main() {
//! use ryuk::events::Dispatcher;
//!
//! struct UserRegistered { email: String }
//!
//! let events = Dispatcher::new();
//! events.listen(|e: std::sync::Arc<UserRegistered>| async move {
//!     println!("welcome {}", e.email);
//! });
//! events.dispatch(UserRegistered { email: "a@b.c".into() }).await;
//! # }
//! ```

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

/// Boxed error a listener may return.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// What a listener future may resolve to: `()` or `Result<(), impl Into<BoxError>>`.
pub trait ListenerResult {
    /// Converts into a plain result.
    fn into_result(self) -> Result<(), BoxError>;
}
impl ListenerResult for () {
    fn into_result(self) -> Result<(), BoxError> {
        Ok(())
    }
}
impl<Er: Into<BoxError>> ListenerResult for Result<(), Er> {
    fn into_result(self) -> Result<(), BoxError> {
        self.map_err(Into::into)
    }
}

type Handler = Arc<
    dyn Fn(Arc<dyn Any + Send + Sync>) -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>>
        + Send
        + Sync,
>;

/// Cheaply clonable event dispatcher (an `Arc` inside); clones share listeners.
#[derive(Clone, Default)]
pub struct Dispatcher {
    listeners: Arc<RwLock<HashMap<TypeId, Vec<Handler>>>>,
}

impl Dispatcher {
    /// An empty dispatcher.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a listener for event type `E`. The closure receives the event in an `Arc`
    /// and may return `()` or a `Result`.
    ///
    /// ```
    /// use ryuk::events::Dispatcher;
    /// struct Ping;
    /// let d = Dispatcher::new();
    /// d.listen(|_: std::sync::Arc<Ping>| async { Err::<(), _>("nope") });
    /// assert!(d.has_listeners::<Ping>());
    /// ```
    pub fn listen<E, F, Fut>(&self, f: F)
    where
        E: Send + Sync + 'static,
        F: Fn(Arc<E>) -> Fut + Send + Sync + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: ListenerResult,
    {
        let handler: Handler = Arc::new(move |any| {
            // listeners are stored under E's TypeId, so the downcast cannot fail
            let ev = any.downcast::<E>().expect("event type matches its TypeId");
            let fut = f(ev);
            Box::pin(async move { fut.await.into_result() })
        });
        self.listeners
            .write()
            .unwrap()
            .entry(TypeId::of::<E>())
            .or_default()
            .push(handler);
    }

    /// Runs every listener of `E` in registration order, awaiting each. A listener that
    /// returns `Err` is logged with `tracing` and never stops the remaining listeners.
    /// With no listeners this does nothing. (A panicking listener does propagate; use
    /// [`dispatch_spawned`](Self::dispatch_spawned) if that matters.)
    pub async fn dispatch<E: Send + Sync + 'static>(&self, event: E) {
        let handlers: Vec<Handler> = self
            .listeners
            .read()
            .unwrap()
            .get(&TypeId::of::<E>())
            .cloned()
            .unwrap_or_default();
        let event: Arc<dyn Any + Send + Sync> = Arc::new(event);
        for (i, h) in handlers.iter().enumerate() {
            if let Err(err) = h(event.clone()).await {
                tracing::error!(event = std::any::type_name::<E>(), listener = i, %err, "event listener failed");
            }
        }
    }

    /// Like [`dispatch`](Self::dispatch) but in a background task; returns its handle.
    pub fn dispatch_spawned<E: Send + Sync + 'static>(
        &self,
        event: E,
    ) -> tokio::task::JoinHandle<()> {
        let this = self.clone();
        tokio::spawn(async move { this.dispatch(event).await })
    }

    /// Removes all listeners of `E`.
    pub fn forget<E: 'static>(&self) {
        self.listeners.write().unwrap().remove(&TypeId::of::<E>());
    }

    /// Whether `E` has at least one listener.
    pub fn has_listeners<E: 'static>(&self) -> bool {
        self.listeners
            .read()
            .unwrap()
            .get(&TypeId::of::<E>())
            .is_some_and(|v| !v.is_empty())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    struct A(u32);
    struct B;

    #[tokio::test]
    async fn runs_in_order_and_isolates_errors() {
        let d = Dispatcher::new();
        let log = Arc::new(Mutex::new(Vec::new()));
        for n in 0..3u32 {
            let log = log.clone();
            d.listen(move |e: Arc<A>| {
                let log = log.clone();
                async move {
                    log.lock().unwrap().push((n, e.0));
                    if n == 1 { Err("boom") } else { Ok(()) }
                }
            });
        }
        d.clone().dispatch(A(7)).await;
        assert_eq!(*log.lock().unwrap(), vec![(0, 7), (1, 7), (2, 7)]);
    }

    #[tokio::test]
    async fn no_listeners_and_forget() {
        let d = Dispatcher::new();
        d.dispatch(B).await;
        assert!(!d.has_listeners::<B>());
        d.listen(|_: Arc<B>| async {});
        assert!(d.has_listeners::<B>() && !d.has_listeners::<A>());
        d.forget::<B>();
        assert!(!d.has_listeners::<B>());
    }

    #[tokio::test]
    async fn spawned_dispatch() {
        let d = Dispatcher::new();
        let hit = Arc::new(Mutex::new(0));
        let h = hit.clone();
        d.listen(move |e: Arc<A>| {
            let h = h.clone();
            async move { *h.lock().unwrap() = e.0 }
        });
        d.dispatch_spawned(A(3)).await.unwrap();
        assert_eq!(*hit.lock().unwrap(), 3);
    }
}