use crate::{AppContext, AppError, Result};
use sea_orm::DatabaseTransaction;
use std::{
any::{Any, TypeId},
collections::HashMap,
future::Future,
pin::Pin,
sync::Arc,
};
pub trait Event: Send + Sync + 'static {}
pub type EventFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
#[derive(Clone, Copy)]
pub struct EventContext<'a> {
pub app: &'a AppContext,
pub transaction: &'a DatabaseTransaction,
}
type Listener = Arc<
dyn for<'a> Fn(&'a (dyn Any + Send + Sync), EventContext<'a>) -> EventFuture<'a> + Send + Sync,
>;
#[derive(Clone, Default)]
pub struct Events {
listeners: HashMap<TypeId, Vec<Listener>>,
}
impl Events {
pub fn new() -> Self {
Self::default()
}
pub fn on<E: Event>(
mut self,
listener: impl for<'a> Fn(&'a E, EventContext<'a>) -> EventFuture<'a> + Send + Sync + 'static,
) -> Self {
self.listeners
.entry(TypeId::of::<E>())
.or_default()
.push(Arc::new(move |event, ctx| {
match event.downcast_ref::<E>() {
Some(event) => listener(event, ctx),
None => Box::pin(async { Err(AppError::Lifecycle) }),
}
}));
self
}
pub async fn dispatch_in<E: Event>(
&self,
transaction: &DatabaseTransaction,
app: &AppContext,
event: E,
) -> Result<()> {
if let Some(listeners) = self.listeners.get(&TypeId::of::<E>()) {
for (index, listener) in listeners.iter().enumerate() {
if let Err(error) = listener(&event, EventContext { app, transaction }).await {
tracing::warn!(
event = "lifecycle.handler.failed",
event_type = std::any::type_name::<E>(),
listener_index = index,
error_kind = error.kind()
);
return Err(AppError::Lifecycle);
}
}
}
Ok(())
}
}
#[derive(Clone)]
pub struct EventBus(pub Events);
impl<S: Send + Sync> axum::extract::FromRequestParts<S> for EventBus {
type Rejection = AppError;
async fn from_request_parts(parts: &mut axum::http::request::Parts, _: &S) -> Result<Self> {
parts
.extensions
.get::<Events>()
.cloned()
.map(Self)
.ok_or_else(|| AppError::Configuration("Install App before using EventBus.".into()))
}
}