mod_events/
middleware.rs

1//! Middleware system for event processing
2
3use crate::Event;
4
5/// Middleware function type
6///
7/// Middleware functions receive an event and return `true` to allow
8/// the event to continue processing, or `false` to block it.
9pub type MiddlewareFunction = Box<dyn Fn(&dyn Event) -> bool + Send + Sync>;
10
11/// Middleware manager for event processing
12///
13/// Middleware allows you to intercept events before they reach listeners.
14/// This is useful for logging, filtering, or transforming events.
15pub struct MiddlewareManager {
16    middleware: Vec<MiddlewareFunction>,
17}
18
19impl std::fmt::Debug for MiddlewareManager {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.debug_struct("MiddlewareManager")
22            .field("middleware_count", &self.middleware.len())
23            .finish()
24    }
25}
26
27impl Default for MiddlewareManager {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33impl MiddlewareManager {
34    /// Create a new middleware manager
35    pub fn new() -> Self {
36        Self {
37            middleware: Vec::new(),
38        }
39    }
40
41    /// Add middleware to the chain
42    ///
43    /// Middleware is executed in the order it was added.
44    /// If any middleware returns `false`, the event is blocked.
45    pub fn add<F>(&mut self, middleware: F)
46    where
47        F: Fn(&dyn Event) -> bool + Send + Sync + 'static,
48    {
49        self.middleware.push(Box::new(middleware));
50    }
51
52    /// Process an event through all middleware
53    ///
54    /// Returns `true` if the event should continue, `false` if blocked.
55    pub fn process(&self, event: &dyn Event) -> bool {
56        self.middleware.iter().all(|m| m(event))
57    }
58
59    /// Get the number of middleware functions
60    pub fn count(&self) -> usize {
61        self.middleware.len()
62    }
63
64    /// Clear all middleware
65    pub fn clear(&mut self) {
66        self.middleware.clear();
67    }
68}