use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;
pub trait Event: Clone + Send + Sync + 'static {}
impl<T: Clone + Send + Sync + 'static> Event for T {}
type BoxedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
type BoxedListener = Box<dyn Fn(Box<dyn Any + Send + Sync>) -> BoxedFuture + Send + Sync>;
static LISTENERS: OnceLock<HashMap<TypeId, Vec<BoxedListener>>> = OnceLock::new();
pub fn listeners() -> ListenerRegistry {
ListenerRegistry {
map: HashMap::new(),
}
}
#[must_use]
pub struct ListenerRegistry {
map: HashMap<TypeId, Vec<BoxedListener>>,
}
impl ListenerRegistry {
pub fn on<E, F, Fut>(mut self, listener: F) -> Self
where
E: Event,
F: Fn(E) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let boxed: BoxedListener = Box::new(move |event: Box<dyn Any + Send + Sync>| {
let event = *event
.downcast::<E>()
.expect("dispatch() only ever boxes an E under its own TypeId key");
Box::pin(listener(event))
});
self.map.entry(TypeId::of::<E>()).or_default().push(boxed);
self
}
pub fn publish(self) {
if LISTENERS.set(self.map).is_err() {
tracing::warn!(
"event listener registry published more than once in this process; \
dispatch() still uses the first registry's listeners"
);
}
}
}
pub async fn dispatch<E: Event>(event: E) {
let Some(map) = LISTENERS.get() else {
return;
};
let Some(list) = map.get(&TypeId::of::<E>()) else {
return;
};
for listener in list {
listener(Box::new(event.clone())).await;
}
}