Skip to main content

confluent_kafka/common/metrics/
metrics_view.rs

1// Copyright 2025 Confluent Inc.
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
15//! A live, read-only view of a metrics registry, the Rust form of the
16//! `Collections.unmodifiableMap(metrics.metrics())` the Java clients return.
17
18use std::collections::HashMap;
19use std::sync::{Arc, RwLock};
20
21use crate::common::MetricName;
22use crate::common::metrics::KafkaMetric;
23
24/// The map a metrics registry holds: every metric, indexed by its name.
25pub(crate) type MetricMap = HashMap<MetricName, Arc<KafkaMetric>>;
26
27/// The metrics map shared by a registry and the views it hands out.
28///
29/// Copy-on-write: a reader clones the inner `Arc` under the read lock, a
30/// writer goes through `Arc::make_mut` under the write lock, which copies the
31/// map only while a reader still holds the previous version. So a reader never
32/// blocks a writer for longer than an `Arc` clone, and a held version never
33/// changes, as Java's weakly consistent `ConcurrentHashMap` iteration never
34/// fails.
35///
36/// Rust-only (DoD #7): Java's `Metrics` keeps a `ConcurrentHashMap` that
37/// `unmodifiableMap` wraps; the standard library has no concurrent map, so the
38/// registry and its views share this one instead.
39#[derive(Clone, Default)]
40pub(crate) struct SharedMetricMap(Arc<RwLock<Arc<MetricMap>>>);
41
42impl SharedMetricMap {
43    /// The map as it is now: one `Arc` clone, no entry copied.
44    pub(crate) fn current(&self) -> Arc<MetricMap> {
45        Arc::clone(&self.0.read().expect("metrics lock poisoned"))
46    }
47
48    /// Inserts `metric` under `name` unless a metric is already registered
49    /// there, which it returns instead.
50    pub(crate) fn insert_if_absent(&self, name: MetricName, metric: Arc<KafkaMetric>) -> Option<Arc<KafkaMetric>> {
51        let mut map = self.0.write().expect("metrics lock poisoned");
52        if let Some(existing) = map.get(&name) {
53            return Some(Arc::clone(existing));
54        }
55        Arc::make_mut(&mut map).insert(name, metric);
56        None
57    }
58
59    /// Registers `metric` under `name`, replacing any metric already there.
60    pub(crate) fn insert(&self, name: MetricName, metric: Arc<KafkaMetric>) {
61        Arc::make_mut(&mut self.0.write().expect("metrics lock poisoned")).insert(name, metric);
62    }
63
64    /// Removes the metric registered under `name` and returns it.
65    pub(crate) fn remove(&self, name: &MetricName) -> Option<Arc<KafkaMetric>> {
66        let mut map = self.0.write().expect("metrics lock poisoned");
67        if !map.contains_key(name) {
68            // No write, so no copy of a map a reader still holds.
69            return None;
70        }
71        Arc::make_mut(&mut map).remove(name)
72    }
73
74    /// Replaces the whole map.
75    pub(crate) fn replace(&self, metrics: MetricMap) {
76        *self.0.write().expect("metrics lock poisoned") = Arc::new(metrics);
77    }
78
79    /// The metric registered under `name`.
80    pub(crate) fn get(&self, name: &MetricName) -> Option<Arc<KafkaMetric>> {
81        self.0.read().expect("metrics lock poisoned").get(name).cloned()
82    }
83
84    /// Whether a metric is registered under `name`.
85    pub(crate) fn contains_key(&self, name: &MetricName) -> bool {
86        self.0.read().expect("metrics lock poisoned").contains_key(name)
87    }
88
89    /// How many metrics are registered.
90    pub(crate) fn len(&self) -> usize {
91        self.0.read().expect("metrics lock poisoned").len()
92    }
93}
94
95/// A live, read-only view of the metrics of a client, indexed by metric name:
96/// what Java's clients return from `metrics()` as
97/// `Collections.unmodifiableMap(metrics.metrics())`.
98///
99/// Every lookup reads the registry as it is at the time of the call, so a
100/// metric registered after the view was returned is visible through it and a
101/// removed one is not. [`Self::snapshot`] gives the whole map as it is now, to
102/// iterate without blocking the registry, as Java's weakly consistent iteration
103/// does. A view stays valid after its client is closed.
104///
105/// A view can also stand alone, built from a map ([`From`]) or empty
106/// ([`Default`]), for a test double or a user implementation of `Producer` or
107/// `Consumer`.
108///
109/// A clone is a second view of the same map, as copying a Java reference is.
110///
111/// Java's `Map` interface lets `unmodifiableMap` stand for a live map; Rust has
112/// no read-only map trait in its standard library, and returning a `HashMap`
113/// would copy the registry on every call.
114#[derive(Clone, Default)]
115#[non_exhaustive]
116// Rust's form of the java.util.Map view the Java clients' public metrics() returns
117#[doc(alias = "rust-only")]
118pub struct MetricsView {
119    map: SharedMetricMap,
120}
121
122impl MetricsView {
123    /// A view of the registry map `map`.
124    pub(crate) fn of(map: SharedMetricMap) -> Self {
125        Self { map }
126    }
127
128    /// Returns the metric registered under `name`, if any, as the registry is
129    /// at the time of the call.
130    ///
131    /// # Arguments
132    ///
133    /// - `name` - the name of the metric
134    pub fn get(&self, name: &MetricName) -> Option<Arc<KafkaMetric>> {
135        self.map.get(name)
136    }
137
138    /// Returns whether a metric is registered under `name`, as the registry is
139    /// at the time of the call.
140    ///
141    /// # Arguments
142    ///
143    /// - `name` - the name of the metric
144    pub fn contains_key(&self, name: &MetricName) -> bool {
145        self.map.contains_key(name)
146    }
147
148    /// Returns how many metrics the registry holds at the time of the call.
149    pub fn len(&self) -> usize {
150        self.map.len()
151    }
152
153    /// Returns whether the registry holds no metric at the time of the call.
154    pub fn is_empty(&self) -> bool {
155        self.len() == 0
156    }
157
158    /// Returns the map as it is now, indexed by metric name.
159    ///
160    /// The returned map never changes: a metric registered or removed later
161    /// shows in the view, not in the snapshot. Taking it copies no entry and
162    /// never blocks the registry; a later registration copies the map once
163    /// while a snapshot of the old version is held.
164    pub fn snapshot(&self) -> Arc<HashMap<MetricName, Arc<KafkaMetric>>> {
165        self.map.current()
166    }
167}
168
169impl From<HashMap<MetricName, Arc<KafkaMetric>>> for MetricsView {
170    /// A view of `metrics`, tied to no registry.
171    ///
172    /// # Arguments
173    ///
174    /// - `metrics` - the metrics the view holds, indexed by metric name
175    fn from(metrics: HashMap<MetricName, Arc<KafkaMetric>>) -> Self {
176        let map = SharedMetricMap::default();
177        map.replace(metrics);
178        Self { map }
179    }
180}
181
182impl std::fmt::Debug for MetricsView {
183    // The names of the metrics, not their values.
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        let snapshot = self.snapshot();
186        f.debug_struct("MetricsView")
187            .field("metrics", &snapshot.keys().collect::<Vec<_>>())
188            .finish()
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate::common::metrics::Metrics;
196    use std::collections::BTreeMap;
197
198    fn name(metrics: &Metrics, n: &str) -> MetricName {
199        metrics.metric_name_with_description_tags(n, "grp", "", BTreeMap::new())
200    }
201
202    #[test]
203    fn test_view_is_live() {
204        let metrics = Metrics::new();
205        let view = metrics.metrics();
206        let before = view.len();
207        let a = name(&metrics, "a");
208        assert!(!view.contains_key(&a));
209        metrics
210            .add_metric_with_measurable(a.clone(), Box::new(crate::common::metrics::stats::Value::new()))
211            .unwrap();
212        assert!(view.contains_key(&a));
213        assert!(view.get(&a).is_some());
214        assert_eq!(before + 1, view.len());
215        assert!(metrics.remove_metric(&a).is_some());
216        assert!(!view.contains_key(&a));
217        assert!(view.get(&a).is_none());
218        assert_eq!(before, view.len());
219    }
220
221    #[test]
222    fn test_snapshot_is_stable_and_copies_once() {
223        let metrics = Metrics::new();
224        let view = metrics.metrics();
225        let held = view.snapshot();
226        let a = name(&metrics, "a");
227        let b = name(&metrics, "b");
228        metrics
229            .add_metric_with_measurable(a.clone(), Box::new(crate::common::metrics::stats::Value::new()))
230            .unwrap();
231        let after_a = view.snapshot();
232        // The first write copied the map, since `held` still holds it.
233        assert!(!Arc::ptr_eq(&held, &after_a));
234        drop(after_a);
235        let ptr_after_a = Arc::as_ptr(&view.snapshot());
236        metrics
237            .add_metric_with_measurable(b.clone(), Box::new(crate::common::metrics::stats::Value::new()))
238            .unwrap();
239        let after_b = view.snapshot();
240        // No snapshot held the second version, so the second write was in place.
241        assert_eq!(ptr_after_a, Arc::as_ptr(&after_b));
242        assert!(!held.contains_key(&a) && !held.contains_key(&b));
243        assert!(view.contains_key(&a) && view.contains_key(&b));
244        assert_eq!(held.len() + 2, view.len());
245    }
246
247    #[test]
248    fn test_standalone_views() {
249        assert!(MetricsView::default().is_empty());
250        let metrics = Metrics::new();
251        let view = MetricsView::from(HashMap::clone(&metrics.metrics().snapshot()));
252        assert_eq!(metrics.metrics().len(), view.len());
253        // Not tied to the registry.
254        metrics
255            .add_metric_with_measurable(name(&metrics, "a"), Box::new(crate::common::metrics::stats::Value::new()))
256            .unwrap();
257        assert_eq!(metrics.metrics().len(), view.len() + 1);
258        assert!(format!("{view:?}").contains("count"));
259    }
260
261    #[test]
262    fn test_view_outlives_registry() {
263        let metrics = Metrics::new();
264        let view = metrics.metrics();
265        let len = view.len();
266        drop(metrics);
267        assert_eq!(len, view.len());
268    }
269}