Skip to main content

common_cache/
metrics.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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/// Caller-bound metrics for native cache loading. No collectors are registered here.
23/// Requests count only `try_get_with` calls, including its cache hits and callers sharing
24/// another request's load. Plain `get` calls are not counted. Loads count
25/// only loader futures actually polled by the backend; their difference is not a waiter count.
26#[derive(Clone)]
27pub struct CacheMetrics {
28    pub requests: OperationMetrics,
29    pub loads: OperationMetrics,
30}
31
32/// Metrics for one operation, with labels bound once when constructing a cache.
33/// Completion counters are mutually exclusive. Dropping an unfinished future is cancellation.
34#[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    /// Wall-clock lifetime, including suspended time, for every outcome.
42    pub elapsed: Histogram,
43}
44
45impl OperationMetrics {
46    /// Measures a fallible operation, including cancellation before completion.
47    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    /// Starts tracking an operation and its elapsed time.
58    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
69/// Tracks an operation, recording cancellation if dropped before completion.
70pub(crate) struct OperationGuard<'a> {
71    metrics: &'a OperationMetrics,
72    started: Instant,
73    completed: bool,
74}
75
76impl OperationGuard<'_> {
77    /// Records success or failure and completes the operation.
78    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/// Cache byte metrics combining manually maintained gauges and sampled cache weights.
101/// Sampling does not force backend maintenance or include pending loader values.
102#[derive(Clone)]
103pub struct CacheSizeMetrics {
104    gauges: IntGaugeVec,
105    sources: Arc<Mutex<Vec<CacheSizeSource>>>,
106}
107
108/// A byte metric with labels bound for one or more cache instances.
109#[derive(Clone)]
110pub struct CacheSizeMetric {
111    metrics: CacheSizeMetrics,
112    gauge: IntGauge,
113}
114
115/// Keeps a cache instance registered for size sampling while any owner remains.
116#[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    /// Creates an unregistered collector. Register a clone with the caller's registry.
128    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    /// Returns the backing gauges for callers retaining manual accounting.
136    pub fn gauges(&self) -> &IntGaugeVec {
137        &self.gauges
138    }
139
140    /// Returns a manually maintained gauge for existing non-cache accounting.
141    pub fn with_label_values(&self, labels: &[&str]) -> IntGauge {
142        self.gauges.with_label_values(labels)
143    }
144
145    /// Binds labels for sampled cache weights. Instances sharing labels are summed.
146    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    /// Registers a cache-level weight reader without retaining it in the collector.
156    /// Keep the returned registration alongside the cache, including in its clones.
157    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}