Skip to main content

doido_core/
notifications.rs

1//! A lightweight instrumentation bus (Rails `ActiveSupport::Notifications`).
2//!
3//! Subscribe to an event-name prefix and `instrument` events to notify matching
4//! subscribers. Synchronous and dependency-free (payloads are strings).
5
6type Subscriber = Box<dyn Fn(&str, &str) + Send + Sync>;
7
8/// A registry of event subscribers.
9#[derive(Default)]
10pub struct Notifications {
11    subscribers: Vec<(String, Subscriber)>,
12}
13
14impl Notifications {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    /// Subscribe to events whose name starts with `prefix` (e.g. `"sql."`).
20    pub fn subscribe(
21        &mut self,
22        prefix: &str,
23        handler: impl Fn(&str, &str) + Send + Sync + 'static,
24    ) {
25        self.subscribers
26            .push((prefix.to_string(), Box::new(handler)));
27    }
28
29    /// Fire `name` with `payload`, invoking every subscriber whose prefix matches.
30    pub fn instrument(&self, name: &str, payload: &str) {
31        for (prefix, handler) in &self.subscribers {
32            if name.starts_with(prefix.as_str()) {
33                handler(name, payload);
34            }
35        }
36    }
37}