1use std::sync::{Arc, Mutex, Weak};
16use std::time::Instant;
17
18use prometheus::core::{Collector, Desc};
19use prometheus::proto::{Gauge, MetricFamily};
20use prometheus::{Histogram, IntCounter, IntGauge, IntGaugeVec, Opts};
21
22#[derive(Clone)]
27pub struct CacheMetrics {
28 pub requests: OperationMetrics,
29 pub loads: OperationMetrics,
30}
31
32#[derive(Clone)]
35pub struct OperationMetrics {
36 pub started: IntCounter,
37 pub succeeded: IntCounter,
38 pub failed: IntCounter,
39 pub cancelled: IntCounter,
40 pub active: IntGauge,
41 pub elapsed: Histogram,
43}
44
45impl OperationMetrics {
46 pub async fn observe<T, E>(
48 &self,
49 operation: impl Future<Output = Result<T, E>>,
50 ) -> Result<T, E> {
51 let guard = self.start();
52 let result = operation.await;
53 guard.finish(&result);
54 result
55 }
56
57 pub(crate) fn start(&self) -> OperationGuard<'_> {
59 self.started.inc();
60 self.active.inc();
61 OperationGuard {
62 metrics: self,
63 started: Instant::now(),
64 completed: false,
65 }
66 }
67}
68
69pub(crate) struct OperationGuard<'a> {
71 metrics: &'a OperationMetrics,
72 started: Instant,
73 completed: bool,
74}
75
76impl OperationGuard<'_> {
77 pub(crate) fn finish<T, E>(mut self, result: &Result<T, E>) {
79 if result.is_ok() {
80 self.metrics.succeeded.inc();
81 } else {
82 self.metrics.failed.inc();
83 }
84 self.completed = true;
85 }
86}
87
88impl Drop for OperationGuard<'_> {
89 fn drop(&mut self) {
90 if !self.completed {
91 self.metrics.cancelled.inc();
92 }
93 self.metrics.active.dec();
94 self.metrics
95 .elapsed
96 .observe(self.started.elapsed().as_secs_f64());
97 }
98}
99
100#[derive(Clone)]
103pub struct CacheSizeMetrics {
104 gauges: IntGaugeVec,
105 sources: Arc<Mutex<Vec<CacheSizeSource>>>,
106}
107
108#[derive(Clone)]
110pub struct CacheSizeMetric {
111 metrics: CacheSizeMetrics,
112 gauge: IntGauge,
113}
114
115#[derive(Clone)]
117pub struct CacheSizeRegistration {
118 _reader: Arc<dyn Fn() -> u64 + Send + Sync>,
119}
120
121struct CacheSizeSource {
122 gauge: IntGauge,
123 read: Weak<dyn Fn() -> u64 + Send + Sync>,
124}
125
126impl CacheSizeMetrics {
127 pub fn new(opts: Opts, labels: &[&str]) -> prometheus::Result<Self> {
129 Ok(Self {
130 gauges: IntGaugeVec::new(opts, labels)?,
131 sources: Arc::new(Mutex::new(Vec::new())),
132 })
133 }
134
135 pub fn gauges(&self) -> &IntGaugeVec {
137 &self.gauges
138 }
139
140 pub fn with_label_values(&self, labels: &[&str]) -> IntGauge {
142 self.gauges.with_label_values(labels)
143 }
144
145 pub fn bind(&self, labels: &[&str]) -> CacheSizeMetric {
147 CacheSizeMetric {
148 metrics: self.clone(),
149 gauge: self.gauges.with_label_values(labels),
150 }
151 }
152}
153
154impl CacheSizeMetric {
155 pub fn register(
158 &self,
159 read: impl Fn() -> u64 + Send + Sync + 'static,
160 ) -> CacheSizeRegistration {
161 let read: Arc<dyn Fn() -> u64 + Send + Sync> = Arc::new(read);
162 self.metrics
163 .sources
164 .lock()
165 .unwrap_or_else(|e| e.into_inner())
166 .push(CacheSizeSource {
167 gauge: self.gauge.clone(),
168 read: Arc::downgrade(&read),
169 });
170 CacheSizeRegistration { _reader: read }
171 }
172}
173
174impl Collector for CacheSizeMetrics {
175 fn desc(&self) -> Vec<&Desc> {
176 self.gauges.desc()
177 }
178
179 fn collect(&self) -> Vec<MetricFamily> {
180 let mut families = self.gauges.collect();
181 let mut sources = self.sources.lock().unwrap_or_else(|e| e.into_inner());
182 sources.retain(|source| {
183 let Some(read) = source.read.upgrade() else {
184 return false;
185 };
186 let labels = source.gauge.collect();
187 for family in &mut families {
188 for metric in family.mut_metric() {
189 if metric.get_label() == labels[0].get_metric()[0].get_label() {
190 let bytes = metric
191 .get_gauge()
192 .as_ref()
193 .map_or(0.0, |gauge| gauge.value())
194 + read() as f64;
195 let mut gauge = Gauge::default();
196 gauge.set_value(bytes);
197 metric.set_gauge(gauge);
198 }
199 }
200 }
201 true
202 });
203 families
204 }
205}