pub mod builtin;
use futures::future::join_all;
use serde_json::Value;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex, RwLock};
pub type EventHandlerFn = Box<
dyn Fn(EventContext) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send>> + Send + Sync,
>;
pub type Priority = i32;
pub type HandlerId = usize;
#[derive(Debug, Clone)]
pub struct EventEmitterConfig {
pub parallel_execution: bool,
pub handler_timeout: Duration,
pub debug_logging: bool,
pub max_concurrent_handlers: usize,
}
impl Default for EventEmitterConfig {
fn default() -> Self {
Self {
parallel_execution: true,
handler_timeout: Duration::from_secs(30),
debug_logging: cfg!(debug_assertions),
max_concurrent_handlers: 0, }
}
}
impl EventEmitterConfig {
pub fn parallel() -> Self {
Self {
parallel_execution: true,
..Default::default()
}
}
pub fn sequential() -> Self {
Self {
parallel_execution: false,
debug_logging: true,
..Default::default()
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.handler_timeout = timeout;
self
}
pub fn with_debug_logging(mut self, enabled: bool) -> Self {
self.debug_logging = enabled;
self
}
pub fn with_max_concurrent(mut self, max: usize) -> Self {
self.max_concurrent_handlers = max;
self
}
}
pub mod events {
pub const READY: &str = "ready"; pub const STARTUP: &str = "startup"; pub const SHUTDOWN: &str = "shutdown"; pub const ERROR: &str = "error";
pub const CONFIG_LOADED: &str = "config.loaded"; pub const DATABASE_READY: &str = "database.ready"; pub const MODULES_READY: &str = "modules.ready"; pub const MIDDLEWARE_READY: &str = "middleware.ready"; pub const ROUTES_READY: &str = "routes.ready";
pub const REQUEST_START: &str = "request.start"; pub const REQUEST_END: &str = "request.end"; pub const REQUEST_ERROR: &str = "request.error";
pub const DB_SEED: &str = "db.seed"; pub const DB_MIGRATE: &str = "db.migrate"; pub const DB_CONNECTED: &str = "db.connected"; pub const DB_DISCONNECTED: &str = "db.disconnected"; }
#[derive(Clone)]
pub struct EventContext {
pub event: String,
pub data: Option<Value>,
pub config: Arc<crate::config::AppConfig>,
pub environment: String,
emitter: Option<Arc<RwLock<EventEmitter>>>,
}
impl EventContext {
pub fn new(event: String, config: Arc<crate::config::AppConfig>) -> Self {
let environment = config.environment.name().to_string();
Self {
event,
data: None,
config,
environment,
emitter: None,
}
}
pub fn with_data(mut self, data: Value) -> Self {
self.data = Some(data);
self
}
#[allow(dead_code)]
pub(crate) fn with_emitter(mut self, emitter: Arc<RwLock<EventEmitter>>) -> Self {
self.emitter = Some(emitter);
self
}
pub fn env(&self) -> &str {
&self.environment
}
pub fn is_development(&self) -> bool {
self.environment == "development" || self.environment == "dev"
}
pub fn is_production(&self) -> bool {
self.environment == "production" || self.environment == "prod"
}
pub async fn emit(&self, event: &str, data: Option<Value>) -> crate::Result<()> {
if let Some(emitter) = &self.emitter {
let emitter = emitter.read().await;
emitter
.emit_internal(event, data, self.config.clone())
.await
} else {
Ok(())
}
}
}
struct EventHandler {
id: HandlerId,
_priority: Priority,
handler: EventHandlerFn,
once: bool,
}
pub struct EventEmitter {
handlers: HashMap<String, BTreeMap<Priority, Vec<EventHandler>>>,
next_id: HandlerId,
config: EventEmitterConfig,
executed_once: Arc<Mutex<HashSet<HandlerId>>>,
}
impl EventEmitter {
pub fn new() -> Self {
Self::with_config(EventEmitterConfig::default())
}
pub fn with_config(config: EventEmitterConfig) -> Self {
Self {
handlers: HashMap::new(),
next_id: 1,
config,
executed_once: Arc::new(Mutex::new(HashSet::new())),
}
}
pub fn config(&self) -> &EventEmitterConfig {
&self.config
}
pub fn set_config(&mut self, config: EventEmitterConfig) {
self.config = config;
}
pub fn on<F>(&mut self, event: &str, handler: F) -> HandlerId
where
F: Fn(EventContext) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send>>
+ Send
+ Sync
+ 'static,
{
self.on_priority(event, 0, handler)
}
pub fn on_priority<F>(&mut self, event: &str, priority: Priority, handler: F) -> HandlerId
where
F: Fn(EventContext) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send>>
+ Send
+ Sync
+ 'static,
{
let id = self.next_id;
self.next_id += 1;
let handler = EventHandler {
id,
_priority: priority,
handler: Box::new(handler),
once: false,
};
self.handlers
.entry(event.to_string())
.or_default()
.entry(priority)
.or_default()
.push(handler);
log::debug!(
"Registered event handler for '{}' with priority {} (id: {})",
event,
priority,
id
);
id
}
pub fn once<F>(&mut self, event: &str, handler: F) -> HandlerId
where
F: Fn(EventContext) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send>>
+ Send
+ Sync
+ 'static,
{
self.once_priority(event, 0, handler)
}
pub fn once_priority<F>(&mut self, event: &str, priority: Priority, handler: F) -> HandlerId
where
F: Fn(EventContext) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send>>
+ Send
+ Sync
+ 'static,
{
let id = self.next_id;
self.next_id += 1;
let handler = EventHandler {
id,
_priority: priority,
handler: Box::new(handler),
once: true,
};
self.handlers
.entry(event.to_string())
.or_default()
.entry(priority)
.or_default()
.push(handler);
log::debug!(
"Registered one-time event handler for '{}' with priority {} (id: {})",
event,
priority,
id
);
id
}
pub fn off(&mut self, event: &str, handler_id: HandlerId) -> bool {
if let Some(priorities) = self.handlers.get_mut(event) {
for handlers in priorities.values_mut() {
if let Some(pos) = handlers.iter().position(|h| h.id == handler_id) {
handlers.remove(pos);
log::debug!("Removed event handler {} for '{}'", handler_id, event);
return true;
}
}
}
false
}
pub fn clear(&mut self, event: &str) {
if self.handlers.remove(event).is_some() {
log::debug!("Cleared all handlers for event '{}'", event);
}
}
pub async fn emit(
&self,
event: &str,
data: Option<Value>,
config: Arc<crate::config::AppConfig>,
) -> crate::Result<()> {
self.emit_internal(event, data, config).await
}
async fn emit_internal(
&self,
event: &str,
data: Option<Value>,
config: Arc<crate::config::AppConfig>,
) -> crate::Result<()> {
if !self.has_handlers(event) {
if self.config.debug_logging {
log::debug!("No handlers registered for event '{}'", event);
}
return Ok(());
}
if self.config.debug_logging {
log::info!(
"Emitting event: '{}' (parallel: {})",
event,
self.config.parallel_execution
);
}
let priorities = self
.handlers
.get(event)
.expect("Event should exist due to has_handlers check");
let mut total_executed = 0;
let mut all_errors = Vec::new();
for (priority, handlers) in priorities.iter() {
if handlers.is_empty() {
continue;
}
if self.config.debug_logging {
log::debug!(
"Executing {} handler(s) for '{}' at priority {} (parallel: {})",
handlers.len(),
event,
priority,
self.config.parallel_execution
);
}
let (executed, errors) = if self.config.parallel_execution && handlers.len() > 1 {
self.execute_handlers_parallel(handlers, event, &data, config.clone())
.await?
} else {
self.execute_handlers_sequential(handlers, event, &data, config.clone())
.await?
};
total_executed += executed;
all_errors.extend(errors);
}
if self.config.debug_logging {
log::info!(
"Event '{}' executed {} handler(s) with {} error(s)",
event,
total_executed,
all_errors.len()
);
}
if let Some(err) = all_errors.into_iter().next() {
return Err(crate::error::Error::internal(err.to_string()));
}
Ok(())
}
async fn execute_handlers_parallel(
&self,
handlers: &[EventHandler],
event: &str,
data: &Option<Value>,
config: Arc<crate::config::AppConfig>,
) -> crate::Result<(usize, Vec<String>)> {
let executed_once = self.executed_once.lock().await;
let handlers_to_execute: Vec<_> = handlers
.iter()
.filter(|h| !h.once || !executed_once.contains(&h.id))
.collect();
drop(executed_once);
let handler_futures: Vec<_> = handlers_to_execute
.iter()
.enumerate()
.map(|(idx, handler)| {
let event_name = event.to_string();
let data_clone = data.clone();
let config_clone = config.clone();
let handler_id = handler.id;
let handler_once = handler.once;
let debug_logging = self.config.debug_logging;
async move {
let mut ctx = EventContext::new(event_name, config_clone);
if let Some(data) = data_clone {
ctx = ctx.with_data(data);
}
if debug_logging {
log::debug!(
"Executing handler {} for '{}' (parallel batch)",
handler_id,
ctx.event
);
}
let start = std::time::Instant::now();
let result = (handler.handler)(ctx).await;
let duration = start.elapsed();
if debug_logging && duration > Duration::from_millis(10) {
log::debug!("Handler {} completed in {:?}", handler_id, duration);
}
(idx, handler_id, handler_once, result)
}
})
.collect();
let results = tokio::time::timeout(self.config.handler_timeout, join_all(handler_futures))
.await
.map_err(|_| {
crate::error::Error::internal(format!(
"Event '{}' handlers timed out after {:?}",
event, self.config.handler_timeout
))
})?;
let mut executed = 0;
let mut errors = Vec::new();
for (idx, handler_id, handler_once, result) in results {
match result {
Ok(()) => {
executed += 1;
if handler_once {
let mut executed_once = self.executed_once.lock().await;
executed_once.insert(handler_id);
}
}
Err(e) => {
let error_msg = format!(
"Error in handler {} (idx {}) for '{}': {}",
handler_id, idx, event, e
);
log::error!("{}", error_msg);
errors.push(error_msg);
}
}
}
Ok((executed, errors))
}
async fn execute_handlers_sequential(
&self,
handlers: &[EventHandler],
event: &str,
data: &Option<Value>,
config: Arc<crate::config::AppConfig>,
) -> crate::Result<(usize, Vec<String>)> {
let mut executed = 0;
let mut errors = Vec::new();
for handler in handlers {
if handler.once {
let executed_once = self.executed_once.lock().await;
if executed_once.contains(&handler.id) {
continue;
}
}
let mut ctx = EventContext::new(event.to_string(), config.clone());
if let Some(ref data) = data {
ctx = ctx.with_data(data.clone());
}
if self.config.debug_logging {
log::debug!(
"Executing handler {} for '{}' (sequential)",
handler.id,
event
);
}
let start = std::time::Instant::now();
let result =
tokio::time::timeout(self.config.handler_timeout, (handler.handler)(ctx)).await;
match result {
Ok(Ok(())) => {
executed += 1;
if handler.once {
let mut executed_once = self.executed_once.lock().await;
executed_once.insert(handler.id);
}
if self.config.debug_logging {
let duration = start.elapsed();
if duration > Duration::from_millis(10) {
log::debug!("Handler {} completed in {:?}", handler.id, duration);
}
}
}
Ok(Err(e)) => {
let error_msg =
format!("Error in handler {} for '{}': {}", handler.id, event, e);
log::error!("{}", error_msg);
errors.push(error_msg);
}
Err(_) => {
let error_msg = format!(
"Handler {} for '{}' timed out after {:?}",
handler.id, event, self.config.handler_timeout
);
log::error!("{}", error_msg);
errors.push(error_msg);
}
}
}
Ok((executed, errors))
}
pub fn has_handlers(&self, event: &str) -> bool {
self.handlers
.get(event)
.map(|p| p.values().any(|h| !h.is_empty()))
.unwrap_or(false)
}
pub fn handler_count(&self, event: &str) -> usize {
self.handlers
.get(event)
.map(|p| p.values().map(|h| h.len()).sum())
.unwrap_or(0)
}
pub fn list_events(&self) -> Vec<&str> {
self.handlers.keys().map(|s| s.as_str()).collect()
}
}
impl Default for EventEmitter {
fn default() -> Self {
Self::new()
}
}
#[macro_export]
macro_rules! handler {
($handler:expr) => {
|ctx| Box::pin($handler(ctx))
};
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_event_emitter() {
let mut emitter = EventEmitter::new();
let config = Arc::new(crate::config::AppConfig::default());
let counter = Arc::new(RwLock::new(0));
let counter_clone = counter.clone();
emitter.on("test", move |_ctx| {
let counter = counter_clone.clone();
Box::pin(async move {
let mut count = counter.write().await;
*count += 1;
Ok(())
})
});
emitter.emit("test", None, config.clone()).await.unwrap();
assert_eq!(*counter.read().await, 1);
let order = Arc::new(RwLock::new(Vec::new()));
let order_clone = order.clone();
emitter.on_priority("priority", 10, move |_ctx| {
let order = order_clone.clone();
Box::pin(async move {
order.write().await.push("second");
Ok(())
})
});
let order_clone = order.clone();
emitter.on_priority("priority", -10, move |_ctx| {
let order = order_clone.clone();
Box::pin(async move {
order.write().await.push("first");
Ok(())
})
});
emitter
.emit("priority", None, config.clone())
.await
.unwrap();
let result = order.read().await.clone();
assert_eq!(result, vec!["first", "second"]);
let once_counter = Arc::new(RwLock::new(0));
let once_clone = once_counter.clone();
emitter.once("once_test", move |_ctx| {
let counter = once_clone.clone();
Box::pin(async move {
let mut count = counter.write().await;
*count += 1;
Ok(())
})
});
emitter
.emit("once_test", None, config.clone())
.await
.unwrap();
emitter
.emit("once_test", None, config.clone())
.await
.unwrap();
assert_eq!(*once_counter.read().await, 1);
}
#[tokio::test]
async fn test_event_context() {
let ctx_dev = EventContext::new(
"test".to_string(),
Arc::new(crate::config::AppConfig::default()),
);
assert!(ctx_dev.is_development());
assert_eq!(ctx_dev.env(), "development");
let prod = crate::config::AppConfig {
environment: crate::config::Environment::Production,
..Default::default()
};
let ctx_prod = EventContext::new("test".to_string(), Arc::new(prod));
assert!(ctx_prod.is_production());
assert!(!ctx_prod.is_development());
assert_eq!(ctx_prod.env(), "production");
}
}