use crate::{AppConfig, AppContext, AppError, EventError, EventResult, Result, Services};
use futures_util::FutureExt;
use sea_orm::DatabaseTransaction;
use std::{
any::{Any, TypeId},
collections::HashMap,
future::Future,
panic::AssertUnwindSafe,
pin::Pin,
sync::Arc,
};
pub trait Event: Send + Sync + 'static {}
pub type EventFuture<'a> = Pin<Box<dyn Future<Output = EventResult> + Send + 'a>>;
#[derive(Clone, Copy)]
pub struct EventContext<'a> {
pub config: &'a AppConfig,
pub transaction: &'a DatabaseTransaction,
pub services: &'a Services,
}
impl EventContext<'_> {
pub fn service<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
self.services.get::<T>()
}
}
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>>,
services: Services,
}
impl Events {
pub fn new() -> Self {
Self::default()
}
pub fn with_services(mut self, services: Services) -> Self {
self.services = services;
self
}
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.into()) }),
}
}));
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() {
let outcome = AssertUnwindSafe(async {
listener(
&event,
EventContext {
config: &app.config,
transaction,
services: &self.services,
},
)
.await
})
.catch_unwind()
.await;
if let Ok(Err(EventError::Reject(problem))) = outcome {
tracing::info!(
event = "lifecycle.handler.rejected",
event_type = std::any::type_name::<E>(),
listener_index = index
);
return Err(problem.into());
}
if !matches!(outcome, Ok(Ok(()))) {
let error_kind = match &outcome {
Ok(Err(EventError::Failure(error))) => error.kind(),
_ => "panic",
};
tracing::warn!(
event = "lifecycle.handler.failed",
event_type = std::any::type_name::<E>(),
listener_index = index,
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()))
}
}