1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//! 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);
}
}