Skip to main content

amalgam/
observability.rs

1//! Metrics, exposed as a [`Plugin`](crate::plugins::Plugin) (feature `metrics`).
2//!
3//! `MetricsPlugin` records counters via the [`metrics`](https://docs.rs/metrics)
4//! facade, so any compatible exporter (Prometheus, OTLP, …) can surface them.
5//! Attach it with `Cache::builder().plugin(Arc::new(MetricsPlugin::new()))`.
6
7#[cfg(feature = "metrics")]
8mod imp {
9    use crate::events::CacheEvent;
10    use crate::plugins::Plugin;
11
12    /// Records cache metrics via the `metrics` facade.
13    #[derive(Debug)]
14    pub struct MetricsPlugin {
15        name: String,
16    }
17
18    impl MetricsPlugin {
19        /// Creates the plugin.
20        #[must_use]
21        pub fn new() -> Self {
22            Self {
23                name: "amalgam-metrics".to_owned(),
24            }
25        }
26    }
27
28    impl Default for MetricsPlugin {
29        fn default() -> Self {
30            Self::new()
31        }
32    }
33
34    impl Plugin for MetricsPlugin {
35        fn name(&self) -> &str {
36            &self.name
37        }
38
39        fn on_event(&self, event: &CacheEvent) {
40            match event {
41                CacheEvent::Hit { stale, .. } => {
42                    if *stale {
43                        metrics::counter!("amalgam_hits_stale_total").increment(1);
44                    } else {
45                        metrics::counter!("amalgam_hits_total").increment(1);
46                    }
47                }
48                CacheEvent::Miss { .. } => metrics::counter!("amalgam_misses_total").increment(1),
49                CacheEvent::Set { .. } => metrics::counter!("amalgam_sets_total").increment(1),
50                CacheEvent::FactoryError { .. } => {
51                    metrics::counter!("amalgam_factory_errors_total").increment(1);
52                }
53                CacheEvent::FailSafeActivate { .. } => {
54                    metrics::counter!("amalgam_failsafe_activations_total").increment(1);
55                }
56                CacheEvent::FactorySyntheticTimeout { .. } => {
57                    metrics::counter!("amalgam_factory_timeouts_total").increment(1);
58                }
59                CacheEvent::EagerRefresh { .. } => {
60                    metrics::counter!("amalgam_eager_refreshes_total").increment(1);
61                }
62                _ => {}
63            }
64        }
65    }
66}
67
68#[cfg(feature = "metrics")]
69pub use imp::MetricsPlugin;