Skip to main content

aurelin_framework/
events.rs

1use serde::{Serialize, de::DeserializeOwned};
2use std::{
3    any::{Any, TypeId, type_name},
4    collections::HashMap,
5    error::Error,
6    fmt,
7    future::Future,
8    pin::Pin,
9    sync::Arc,
10};
11
12type BoxError = Box<dyn Error + Send + Sync + 'static>;
13type ErasedEvent = Arc<dyn Any + Send + Sync>;
14type ListenerFuture = Pin<Box<dyn Future<Output = Result<ListenerControl, BoxError>> + Send + 'static>>;
15type Listener = dyn Fn(ErasedEvent) -> ListenerFuture + Send + Sync;
16
17/// Controls whether dispatch continues to later listeners.
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum ListenerControl {
20    /// Continue dispatching to the next registered listener.
21    Continue,
22    /// Stop dispatching this event without treating the stop as a failure.
23    Stop,
24}
25
26impl From<()> for ListenerControl {
27    fn from((): ()) -> Self {
28        Self::Continue
29    }
30}
31
32/// Describes how an event dispatch completed.
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum DispatchOutcome {
35    /// Every registered listener completed, including the case where none exist.
36    Completed,
37    /// A listener explicitly stopped propagation.
38    Stopped,
39}
40
41/// Builds an immutable registry of typed event listeners.
42#[derive(Default)]
43pub struct EventDispatcherBuilder {
44    listeners: HashMap<TypeId, Vec<Arc<Listener>>>,
45}
46
47impl EventDispatcherBuilder {
48    /// Create an empty listener registry builder.
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Register a typed listener after all listeners already registered for this event.
54    pub fn listen<Event, Callback, CallbackFuture, Outcome, ListenerError>(&mut self, listener: Callback) -> &mut Self
55    where
56        Event: Send + Sync + 'static,
57        Callback: Fn(Arc<Event>) -> CallbackFuture + Send + Sync + 'static,
58        CallbackFuture: Future<Output = Result<Outcome, ListenerError>> + Send + 'static,
59        Outcome: Into<ListenerControl> + 'static,
60        ListenerError: Error + Send + Sync + 'static,
61    {
62        let listener = Arc::new(listener);
63        let callback = move |event: ErasedEvent| {
64            let listener = Arc::clone(&listener);
65            Box::pin(async move {
66                let event = Arc::downcast::<Event>(event)
67                    .map_err(|_| Box::new(EventTypeMismatch { expected: type_name::<Event>() }) as BoxError)?;
68                listener(event).await.map(Into::into).map_err(|error| Box::new(error) as BoxError)
69            }) as ListenerFuture
70        };
71
72        self.listeners.entry(TypeId::of::<Event>()).or_default().push(Arc::new(callback));
73        self
74    }
75
76    /// Enqueue an application-owned job when an event is dispatched.
77    ///
78    /// The mapper selects the data stored in SQLite; the worker and handler are
79    /// registered separately. Enqueue errors stop subsequent listeners.
80    pub fn listen_queued<Event, Job, Map>(&mut self, queue: apalis_sqlite::SqliteStorage<Job>, map: Map) -> &mut Self
81    where
82        Event: Send + Sync + 'static,
83        Job: Serialize + DeserializeOwned + Send + Sync + 'static,
84        Map: Fn(&Event) -> Job + Send + Sync + 'static,
85    {
86        use crate::queue::TaskSink;
87        self.listen(move |event: Arc<Event>| {
88            let mut queue = queue.clone();
89            let job = map(&event);
90            async move { queue.push(job).await }
91        })
92    }
93
94    /// Finish configuring the immutable dispatcher.
95    pub fn build(&self) -> EventDispatcher {
96        EventDispatcher { inner: Arc::new(EventDispatcherInner { listeners: self.listeners.clone() }) }
97    }
98}
99
100struct EventDispatcherInner {
101    listeners: HashMap<TypeId, Vec<Arc<Listener>>>,
102}
103
104/// A shared, immutable registry that dispatches typed events sequentially.
105#[derive(Clone)]
106pub struct EventDispatcher {
107    inner: Arc<EventDispatcherInner>,
108}
109
110impl fmt::Debug for EventDispatcher {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        formatter.debug_struct("EventDispatcher").field("event_types", &self.inner.listeners.len()).finish()
113    }
114}
115
116impl EventDispatcher {
117    /// Configure a new event dispatcher.
118    pub fn builder() -> EventDispatcherBuilder {
119        EventDispatcherBuilder::new()
120    }
121
122    /// Dispatch an event to its listeners in registration order.
123    ///
124    /// Listeners are awaited one at a time. A listener error is returned immediately,
125    /// and later listeners are not invoked.
126    pub async fn dispatch<Event>(&self, event: Event) -> Result<DispatchOutcome, DispatchError>
127    where
128        Event: Send + Sync + 'static,
129    {
130        let Some(listeners) = self.inner.listeners.get(&TypeId::of::<Event>()) else {
131            return Ok(DispatchOutcome::Completed);
132        };
133        let event: ErasedEvent = Arc::new(event);
134
135        for (index, listener) in listeners.iter().enumerate() {
136            let control = listener(Arc::clone(&event)).await.map_err(|source| DispatchError {
137                event_type: type_name::<Event>(),
138                listener_position: index + 1,
139                source,
140            })?;
141            if control == ListenerControl::Stop {
142                return Ok(DispatchOutcome::Stopped);
143            }
144        }
145
146        Ok(DispatchOutcome::Completed)
147    }
148}
149
150/// A listener failed while handling an event.
151#[derive(Debug, thiserror::Error)]
152#[error("listener {listener_position} for event [{event_type}] failed: {source}")]
153pub struct DispatchError {
154    event_type: &'static str,
155    listener_position: usize,
156    #[source]
157    source: BoxError,
158}
159
160impl DispatchError {
161    /// The Rust type name of the dispatched event.
162    pub fn event_type(&self) -> &'static str {
163        self.event_type
164    }
165
166    /// The one-based position of the failing listener in registration order.
167    pub fn listener_position(&self) -> usize {
168        self.listener_position
169    }
170}
171
172#[derive(Debug, thiserror::Error)]
173#[error("event payload did not match registered type [{expected}]")]
174struct EventTypeMismatch {
175    expected: &'static str,
176}