tokio-events 0.2.1

A modern, type-safe async event bus for Rust applications
Documentation
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! The main EventBus implementation.
//!
//! The EventBus is the primary interface for publishing and subscribing to events.
//! It coordinates between the registry, subscription manager, and dispatcher.

use crate::dispatcher::EventDispatcher;
use crate::registry::EventRegistry;
use crate::subscription::{EventHandler, SubscriptionHandle, SubscriptionManager};
use crate::{Error, Event, EventEnvelope, EventMetadata, Result};
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{debug, error, info, trace, warn};
use uuid::Uuid;

pub mod builder;
pub mod config;

pub use builder::EventBusBuilder;
pub use config::EventBusConfig;

/// Shutdown hook function type
type ShutdownHook = Box<dyn Fn() -> futures::future::BoxFuture<'static, Result<()>> + Send + Sync>;

/// The main event bus for publishing and subscribing to events.
///
/// The EventBus provides a high-level API for event-driven communication
/// between different parts of an application.
///
/// # Sharing
///
/// `EventBus` is designed to be shared across tasks. Wrap it in `Arc<EventBus>`
/// and clone the `Arc` to pass it around. Shutdown works via `&self`.
///
/// # Example
///
/// ```rust,ignore
/// use tokio_events::{EventBus, Event};
///
/// #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
/// struct MyEvent { data: String }
///
/// impl Event for MyEvent {
///     fn event_type() -> &'static str { "MyEvent" }
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let bus = Arc::new(EventBus::builder().build().await?);
///     
///     // Subscribe to events
///     let handle = bus.subscribe(|event: MyEvent| async move {
///         println!("Received: {}", event.data);
///     }).await?;
///     
///     // Publish an event
///     bus.publish(MyEvent { data: "Hello".into() }).await?;
///     
///     // Shutdown works via &self — no need to unwrap the Arc
///     bus.shutdown_gracefully().await?;
///     
///     Ok(())
/// }
/// ```
#[derive(Clone)]
#[allow(missing_debug_implementations)]
pub struct EventBus {
    pub(crate) config: EventBusConfig,
    pub(crate) registry: Arc<dyn EventRegistry>,
    pub(crate) subscription_manager: Arc<SubscriptionManager>,
    pub(crate) dispatcher: Arc<tokio::sync::Mutex<Option<Box<dyn EventDispatcher>>>>,
    pub(crate) shutdown_hooks: Arc<Mutex<Vec<ShutdownHook>>>,
    pub(crate) is_shutting_down: Arc<AtomicBool>,
    pub(crate) dlq_rx: Arc<tokio::sync::Mutex<Option<tokio::sync::mpsc::Receiver<Arc<EventEnvelope>>>>>,
}

impl EventBus {
    /// Create a new EventBus builder
    pub fn builder() -> EventBusBuilder {
        EventBusBuilder::new()
    }

    /// Take the Dead Letter Queue (DLQ) receiver.
    /// 
    /// This can only be called once. Returns `None` if it has already been taken.
    pub async fn take_dlq_receiver(&self) -> Option<tokio::sync::mpsc::Receiver<Arc<EventEnvelope>>> {
        self.dlq_rx.lock().await.take()
    }

    /// Publish an event to all subscribers
    pub async fn publish<T: Event>(&self, event: T) -> Result<Uuid> {
        self.publish_with_metadata(event, EventMetadata::new())
            .await
    }

    /// Publish an event with custom metadata
    pub async fn publish_with_metadata<T: Event>(
        &self,
        event: T,
        metadata: EventMetadata,
    ) -> Result<Uuid> {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(Error::ShuttingDown);
        }

        let event_id = metadata.event_id;

        trace!(
            event_id = %event_id,
            event_type = T::event_type(),
            "Publishing event"
        );

        let envelope = EventEnvelope::with_metadata(event, metadata);

        // Dispatch the event
        {
            let guard = self.dispatcher.lock().await;
            let dispatcher = guard.as_ref().ok_or(Error::ShuttingDown)?;
            dispatcher.dispatch(envelope).await?;
        }

        debug!(
            event_id = %event_id,
            event_type = T::event_type(),
            "Event published successfully"
        );

        Ok(event_id)
    }

    /// Subscribe to events of a specific type
    pub async fn subscribe<T, F, Fut>(&self, handler: F) -> Result<SubscriptionHandle>
    where
        T: Event,
        F: Fn(T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(Error::ShuttingDown);
        }

        self.subscription_manager.subscribe_fn(handler).await
    }

    /// Subscribe to events of a specific type with a handler that can fail.
    ///
    /// If the handler returns an `Err`, the event bus will use its retry mechanism
    /// (with exponential backoff) before routing the event to the Dead Letter Queue.
    pub async fn subscribe_fallible<T, F, Fut>(&self, handler: F) -> Result<SubscriptionHandle>
    where
        T: Event,
        F: Fn(T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(Error::ShuttingDown);
        }

        let function_handler = crate::subscription::handler::FallibleFunctionHandler::new(handler);
        self.subscription_manager.subscribe::<T, _>(function_handler).await
    }

    /// Subscribe with a custom handler implementation
    pub async fn subscribe_handler<T, H>(&self, handler: H) -> Result<SubscriptionHandle>
    where
        T: Event,
        H: EventHandler,
    {
        if self.is_shutting_down.load(Ordering::SeqCst) {
            return Err(Error::ShuttingDown);
        }

        self.subscription_manager.subscribe::<T, H>(handler).await
    }

    /// Unsubscribe a handler
    pub async fn unsubscribe(&self, handle: SubscriptionHandle) -> Result<()> {
        self.subscription_manager.unsubscribe(handle).await
    }

    /// Replay unacknowledged events from persistent storage
    ///
    /// This should be called manually *after* setting up all your `.subscribe(...)`
    /// routes. The dispatcher will scan the persistent database for orphaned events
    /// and inject them into the memory queues of the currently active subscribers.
    /// If you do not use the `persistence` feature, this method does nothing.
    pub async fn replay_pending(&self) -> Result<()> {
        let guard = self.dispatcher.lock().await;
        if let Some(dispatcher) = guard.as_ref() {
            dispatcher.replay_pending().await
        } else {
            Err(Error::ShuttingDown)
        }
    }

    /// Get statistics about the event bus
    pub fn stats(&self) -> EventBusStats {
        // Try to get dispatcher stats; if shutdown already took it, use defaults
        let dispatcher_stats = self.dispatcher.try_lock()
            .ok()
            .and_then(|guard| guard.as_ref().map(|d| d.stats()))
            .unwrap_or_default();

        EventBusStats {
            total_subscriptions: self.registry.total_subscriptions(),
            event_types: self.registry.event_types().len(),
            dispatcher_stats,
            subscription_stats: self.subscription_manager.stats(),
        }
    }

    /// Register a shutdown hook
    pub async fn register_shutdown_hook<F, Fut>(&self, hook: F) -> Result<()>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let hook = Box::new(move || -> futures::future::BoxFuture<'static, Result<()>> {
            Box::pin(hook())
        });

        self.shutdown_hooks.lock().await.push(hook);
        Ok(())
    }

    /// Check if the event bus is shutting down
    pub fn is_shutting_down(&self) -> bool {
        self.is_shutting_down.load(Ordering::SeqCst)
    }

    /// Shutdown the event bus abruptly
    ///
    /// This method works via `&self` so you can call it on an `Arc<EventBus>`.
    pub async fn shutdown(&self) -> Result<()> {
        info!("Shutting down EventBus (abruptly)");

        // Mark as shutting down
        self.is_shutting_down.store(true, Ordering::SeqCst);

        // Run shutdown hooks
        let hooks = self.shutdown_hooks.lock().await;
        for hook in hooks.iter() {
            if let Err(e) = hook().await {
                error!("Shutdown hook failed: {}", e);
            }
        }
        drop(hooks);

        // Take and stop the dispatcher with timeout
        let dispatcher_shutdown = tokio::time::timeout(self.config.shutdown_timeout, async {
            let mut guard = self.dispatcher.lock().await;
            if let Some(mut dispatcher) = guard.take() {
                dispatcher.stop().await
            } else {
                Ok(())
            }
        });

        if dispatcher_shutdown.await.is_err() {
            warn!("Dispatcher shutdown timed out");
        }

        // Shutdown subscription manager
        self.subscription_manager.shutdown().await?;

        info!("EventBus abrupt shutdown complete");
        Ok(())
    }

    /// Shutdown the event bus gracefully
    /// 
    /// This will prevent new events from being published, wait for the dispatcher to route
    /// all buffered events, and wait for all handler tasks to finish processing their events.
    ///
    /// This method works via `&self` so you can call it on an `Arc<EventBus>`.
    pub async fn shutdown_gracefully(&self) -> Result<()> {
        info!("Shutting down EventBus gracefully");

        // Mark as shutting down, preventing new publishes
        self.is_shutting_down.store(true, Ordering::SeqCst);

        // Run shutdown hooks
        let hooks = self.shutdown_hooks.lock().await;
        for hook in hooks.iter() {
            if let Err(e) = hook().await {
                error!("Shutdown hook failed: {}", e);
            }
        }
        drop(hooks);

        // Take and gracefully drain the dispatcher
        {
            let mut guard = self.dispatcher.lock().await;
            if let Some(mut dispatcher) = guard.take() {
                if let Err(e) = dispatcher.shutdown_gracefully().await {
                    error!("Dispatcher graceful shutdown failed: {}", e);
                }
            }
        }

        // Wait for subscription manager to finish processing handler tasks
        self.subscription_manager.shutdown_gracefully().await;

        info!("EventBus graceful shutdown complete");
        Ok(())
    }
}

/// Statistics about the event bus
#[derive(Debug, Clone)]
pub struct EventBusStats {
    /// Total number of subscriptions
    pub total_subscriptions: usize,

    /// Number of unique event types
    pub event_types: usize,

    /// Dispatcher statistics
    pub dispatcher_stats: crate::dispatcher::DispatcherStats,

    /// Subscription manager statistics
    pub subscription_stats: crate::subscription::SubscriptionStats,
}

impl std::fmt::Display for EventBusStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "EventBus Stats: {} subscriptions, {} event types, {} events dispatched",
            self.total_subscriptions, self.event_types, self.dispatcher_stats.events_dispatched
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
    struct TestEvent {
        value: String,
    }

    impl Event for TestEvent {
        fn event_type() -> &'static str {
            "TestEvent"
        }
    }

    #[tokio::test]
    async fn test_event_bus_basic() {
        let bus = EventBus::builder()
            .configure(|c| c.enable_tracing(false))
            .build()
            .await
            .unwrap();

        let received = Arc::new(Mutex::new(Vec::new()));
        let received_clone = received.clone();

        // Subscribe
        let handle = bus
            .subscribe(move |event: TestEvent| {
                let received = received_clone.clone();
                async move {
                    received.lock().await.push(event.value);
                }
            })
            .await
            .unwrap();

        // Publish events
        bus.publish(TestEvent {
            value: "first".into(),
        })
        .await
        .unwrap();
        bus.publish(TestEvent {
            value: "second".into(),
        })
        .await
        .unwrap();

        // Wait for processing
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Check results
        let messages = received.lock().await;
        assert_eq!(messages.len(), 2);
        assert!(messages.contains(&"first".to_string()));
        assert!(messages.contains(&"second".to_string()));

        // Unsubscribe
        bus.unsubscribe(handle).await.unwrap();

        // Shutdown
        bus.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_event_bus_stats() {
        let bus = EventBus::builder().build().await.unwrap();

        let _handle1 = bus.subscribe(|_: TestEvent| async {}).await.unwrap();
        let _handle2 = bus.subscribe(|_: TestEvent| async {}).await.unwrap();

        let stats = bus.stats();
        assert_eq!(stats.total_subscriptions, 2);
        assert_eq!(stats.event_types, 1);

        bus.shutdown().await.unwrap();
    }
}