mod_events/metrics.rs
1//! Event dispatch metrics and monitoring.
2//!
3//! The dispatcher records per-event-type counts (dispatches, listeners)
4//! and a last-dispatch timestamp. The hot dispatch path increments
5//! atomic counters and updates a tiny per-type [`parking_lot::Mutex`]
6//! protecting the timestamp; it never takes a write lock on the
7//! aggregate metrics map. [`EventDispatcher::metrics`](crate::EventDispatcher::metrics)
8//! returns an immutable [`EventMetadata`] snapshot per event type.
9
10use crate::Event;
11use parking_lot::Mutex;
12use std::any::TypeId;
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::time::Instant;
15
16/// Per-event-type counters held inside the dispatcher.
17///
18/// All increment paths are lock-free except the timestamp swap, which
19/// uses a `parking_lot::Mutex<Instant>` because `std::time::Instant`
20/// has no public atomic representation. The mutex critical section
21/// stores a single `Instant` and never blocks on user code, so
22/// contention is bounded by how often the same event fires.
23///
24/// `listener_count` deliberately lives outside this struct: it is
25/// derived from the live listener vecs at snapshot time, so it can
26/// never disagree with the actual registry — there is no atomic to
27/// keep in sync across `subscribe`, `unsubscribe`, and `clear`.
28pub(crate) struct EventMetricsCounters {
29 pub(crate) event_name: &'static str,
30 pub(crate) type_id: TypeId,
31 pub(crate) dispatch_count: AtomicU64,
32 pub(crate) last_dispatch: Mutex<Instant>,
33}
34
35impl EventMetricsCounters {
36 pub(crate) fn new<T: Event>() -> Self {
37 Self {
38 event_name: std::any::type_name::<T>(),
39 type_id: TypeId::of::<T>(),
40 dispatch_count: AtomicU64::new(0),
41 last_dispatch: Mutex::new(Instant::now()),
42 }
43 }
44
45 pub(crate) fn record_dispatch(&self) {
46 let _previous = self.dispatch_count.fetch_add(1, Ordering::Relaxed);
47 *self.last_dispatch.lock() = Instant::now();
48 }
49
50 /// Snapshot the counters this struct owns. Listener count is not
51 /// tracked here; the dispatcher fills it in from the live registry
52 /// when assembling the public [`EventMetadata`].
53 pub(crate) fn snapshot(&self) -> EventMetadata {
54 EventMetadata {
55 event_name: self.event_name,
56 type_id: self.type_id,
57 last_dispatch: *self.last_dispatch.lock(),
58 dispatch_count: self.dispatch_count.load(Ordering::Relaxed),
59 listener_count: 0,
60 }
61 }
62}
63
64/// Immutable snapshot of an event type's metrics.
65///
66/// Returned by [`crate::EventDispatcher::metrics`]. Each field reflects
67/// the value at the moment the snapshot was taken; subsequent dispatches
68/// do not mutate it.
69#[derive(Debug, Clone)]
70pub struct EventMetadata {
71 /// Fully qualified name of the event type, as reported by
72 /// [`std::any::type_name`].
73 pub event_name: &'static str,
74 /// `TypeId` of the event type. Stable for a given type within a
75 /// single process run.
76 pub type_id: TypeId,
77 /// Timestamp of the most recent dispatch of this event type.
78 pub last_dispatch: Instant,
79 /// Total number of times this event type has been dispatched
80 /// since the dispatcher was created.
81 pub dispatch_count: u64,
82 /// Number of listeners (sync + async) registered for this event
83 /// type at the moment the snapshot was taken.
84 pub listener_count: usize,
85}
86
87impl EventMetadata {
88 /// How long ago the most recent dispatch of this event type was.
89 #[must_use]
90 pub fn time_since_last_dispatch(&self) -> std::time::Duration {
91 self.last_dispatch.elapsed()
92 }
93}