Skip to main content

confluent_kafka/common/metrics/
kafka_metric.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 `KafkaMetric` holds a metric name, config and value provider
16//! (`org.apache.kafka.common.metrics.KafkaMetric`).
17
18use std::sync::{Arc, Mutex};
19
20use crate::common::MetricValue;
21use crate::common::metrics::{Measurable, MetricConfig, MetricValueProvider};
22use crate::common::utils::Time;
23use crate::common::{Error, Metric, MetricName};
24
25/// A metric tracked by the registry. Holds a [`MetricName`], a (mutable)
26/// [`MetricConfig`] and a [`MetricValueProvider`].
27///
28/// In Java the `config` field is `volatile` and `metricValue`/`measurableValue`
29/// read under a per-metric `lock` to make the stat read consistent with sensor
30/// records. Because our simple stats are themselves lock-free (atomic), the
31/// value read needs no extra lock; we still guard `config` with a `Mutex` so the
32/// `config(new)` setter is observed atomically, matching Java's `synchronized`
33/// setter + `volatile` read.
34#[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric")]
35pub struct KafkaMetric {
36    metric_name: MetricName,
37    config: Mutex<Arc<MetricConfig>>,
38    time: Arc<dyn Time>,
39    metric_value_provider: Box<dyn MetricValueProvider>,
40}
41
42impl KafkaMetric {
43    /// Create a metric to monitor an object that provides metric values.
44    ///
45    /// * `metric_name` - The name of the metric
46    /// * `value_provider` - The metric value provider associated with this metric
47    /// * `config` - The configuration of the metric
48    /// * `time` - The time instance to use with the metric
49    ///
50    /// Crate-private: it takes the non-public `Time`. Java keeps it public only
51    /// "for testing"; users obtain metrics from `Metrics`.
52    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#KafkaMetric")]
53    pub(crate) fn new(
54        metric_name: MetricName,
55        value_provider: Box<dyn MetricValueProvider>,
56        config: Arc<MetricConfig>,
57        time: Arc<dyn Time>,
58    ) -> Self {
59        Self {
60            metric_name,
61            config: Mutex::new(config),
62            time,
63            metric_value_provider: value_provider,
64        }
65    }
66
67    /// Get the configuration of this metric.
68    ///
69    /// # Returns
70    ///
71    /// Return the config of this metric
72    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#config")]
73    pub fn config(&self) -> Arc<MetricConfig> {
74        Arc::clone(&self.config.lock().expect("metric config mutex poisoned"))
75    }
76
77    /// Set the metric config.
78    ///
79    /// # Arguments
80    ///
81    /// - `config` - configuration for this metrics
82    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#config")]
83    pub fn set_config(&self, config: Arc<MetricConfig>) {
84        *self.config.lock().expect("metric config mutex poisoned") = config;
85    }
86
87    /// Determine if the metric value provider is of type `Measurable`.
88    ///
89    /// # Returns
90    ///
91    /// true if the metric value provider is of type Measurable, false otherwise.
92    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#isMeasurable")]
93    pub fn is_measurable(&self) -> bool {
94        self.metric_value_provider.as_measurable().is_some()
95    }
96
97    /// Get the underlying metrics provider.
98    ///
99    /// # Returns
100    ///
101    /// Return the metric provider
102    ///
103    /// # Errors
104    ///
105    /// - `Error::is_local_illegal_state_error` if the underlying metric is not a `Measurable`.
106    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#measurable")]
107    // Java's `IllegalStateException` is recoverable, so it becomes a `Result`;
108    // the borrowed trait object stands in for Java's identity-comparable provider.
109    pub fn measurable(&self) -> Result<&dyn Measurable, Error> {
110        self.metric_value_provider.as_measurable().ok_or_else(|| {
111            // Java names the provider's class; a closure has no type name.
112            Error::local_illegal_state(match self.metric_value_provider.type_name() {
113                Some(name) => format!("Not a measurable: class {name}"),
114                None => "Not a measurable: the metric value provider is a closure".to_string(),
115            })
116        })
117    }
118
119    /// Take the metric and return the value, where the underlying metric provider
120    /// should be a measurable. Returns the measured value if measurable,
121    /// otherwise `0`.
122    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#measurableValue")]
123    pub(crate) fn measurable_value(&self, time_ms: i64) -> f64 {
124        let config = self.config();
125        match self.metric_value_provider.as_measurable() {
126            Some(m) => m.measure(&config, time_ms),
127            None => 0.0,
128        }
129    }
130}
131
132impl Metric for KafkaMetric {
133    fn metric_name(&self) -> &MetricName {
134        &self.metric_name
135    }
136
137    fn metric_value(&self) -> MetricValue {
138        let now = self.time.milliseconds();
139        let config = self.config();
140        self.metric_value_provider.value(&config, now)
141    }
142}
143
144impl std::fmt::Debug for KafkaMetric {
145    // What `Display` renders: the metric name and the provider's type, never
146    // the provider's state.
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        std::fmt::Display::fmt(self, f)
149    }
150}
151
152impl std::fmt::Display for KafkaMetric {
153    /// Returns a human-readable representation of this metric.
154    ///
155    /// The metric value provider is represented by its type name rather than its
156    /// own state, to avoid dumping internal stat state (e.g. `SampledStat`'s
157    /// samples) into logs, which could be verbose and is rarely useful for
158    /// identifying which metric changed. A closure provider (Java's lambda or
159    /// anonymous class) is omitted.
160    ///
161    /// Java's `toString()` names the provider's Java class
162    /// (`org.apache.kafka.common.metrics.stats.Avg`); the Rust type name is the
163    /// Rust type path [`std::any::type_name`] reports for the provider.
164    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetric#toString")]
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self.metric_value_provider.type_name() {
167            None => write!(f, "KafkaMetric [metricName={}]", self.metric_name),
168            Some(type_name) => {
169                write!(
170                    f,
171                    "KafkaMetric [metricName={}, metricValueProvider={}]",
172                    self.metric_name, type_name
173                )
174            },
175        }
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::common::metrics::stats::Avg;
183    use crate::common::metrics::stats::Value;
184    use crate::common::metrics::{ClosureMeasurable, Stat, gauge, metric_value_provider};
185    use crate::common::utils::MockTime;
186    use crate::common::utils::SystemTime;
187    use std::collections::BTreeMap;
188
189    fn name() -> MetricName {
190        MetricName::new("m", "g", "", BTreeMap::new())
191    }
192
193    #[test]
194    fn measurable_metric_value_and_measurable_value() {
195        let value = Value::new();
196        value.record(&MetricConfig::new(), 42.0, 0);
197        let metric = KafkaMetric::new(name(), Box::new(value), Arc::new(MetricConfig::new()), Arc::new(SystemTime));
198        assert!(metric.is_measurable());
199        assert_eq!(metric.metric_value(), MetricValue::Double(42.0));
200        assert_eq!(metric.measurable_value(0), 42.0);
201    }
202
203    #[test]
204    fn gauge_metric_value_and_zero_measurable_value() {
205        let gauge = gauge::new(|_, _| MetricValue::String("hello".to_string()));
206        let metric = KafkaMetric::new(name(), Box::new(gauge), Arc::new(MetricConfig::new()), Arc::new(SystemTime));
207        assert!(!metric.is_measurable());
208        assert_eq!(metric.metric_value(), MetricValue::String("hello".to_string()));
209        // Non-measurable returns 0 from measurable_value, matching Java.
210        assert_eq!(metric.measurable_value(0), 0.0);
211    }
212
213    // ---------------------------------------------------------------------
214    // KafkaMetricTest.java translation.
215    //
216    // Java's fixture is `METRIC_NAME = new MetricName("name", "group",
217    // "description", emptyMap())` and a `MockTime`; `name()` above plus
218    // `MockTime` are the equivalents.
219    //
220    // 7 of Java's 8 methods are translated below. `testConstructorWithNullProvider`
221    // is NOT translatable and is intentionally omitted: it asserts
222    // `NullPointerException` when the value provider is `null`, but
223    // `KafkaMetric::new` takes `MetricValueProvider` by value (not
224    // `Option<MetricValueProvider>`), so a null provider is unrepresentable โ€”
225    // the Rust type system enforces at compile time what Java asserts at
226    // runtime. There is no code path to test.
227    // ---------------------------------------------------------------------
228
229    // KafkaMetricTest.testIsMeasurable
230    //
231    // Java also asserts `assertEquals(metricValueProvider, metric.measurable())`
232    // โ€” reference identity on the provider. Rust trait objects have no value
233    // equality, so we assert `measurable()` succeeds and that the returned
234    // borrow measures the same value the provider was seeded with, which is the
235    // behavioral content of the identity check.
236    #[test]
237    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testIsMeasurable")]
238    fn test_is_measurable() {
239        let value = Value::new();
240        value.record(&MetricConfig::new(), 7.0, 0);
241        let metric = KafkaMetric::new(
242            name(),
243            Box::new(value),
244            Arc::new(MetricConfig::new()),
245            Arc::new(MockTime::new()),
246        );
247        assert!(metric.is_measurable());
248        let measurable = metric.measurable().expect("provider is a Measurable");
249        assert_eq!(measurable.measure(&MetricConfig::new(), 0), 7.0);
250    }
251
252    // KafkaMetricTest.testIsMeasurableWithGaugeProvider
253    //
254    // Java: `assertFalse(metric.isMeasurable())` +
255    // `assertThrows(IllegalStateException.class, metric::measurable)`. The Rust
256    // `measurable()` returns `Err(IllegalState)` instead of throwing
257    // (CLAUDE.md ยง12.2). The message is asserted because error text is part of
258    // the behavioral contract (definition-of-done.md #3).
259    #[test]
260    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testIsMeasurableWithGaugeProvider")]
261    fn test_is_measurable_with_gauge_provider() {
262        let gauge = gauge::new(|_, _| MetricValue::Double(0.0));
263        let metric = KafkaMetric::new(
264            name(),
265            Box::new(gauge),
266            Arc::new(MetricConfig::new()),
267            Arc::new(MockTime::new()),
268        );
269        assert!(!metric.is_measurable());
270        // `&dyn Measurable` is not `Debug`, so `expect_err` is unavailable.
271        let err = match metric.measurable() {
272            Ok(_) => panic!("a Gauge provider must not be measurable"),
273            Err(e) => e,
274        };
275        assert!(err.to_string().contains("Not a measurable"), "unexpected message: {err}");
276    }
277
278    // KafkaMetricTest.testMeasurableValueReturnsZeroWhenNotMeasurable
279    #[test]
280    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testMeasurableValueReturnsZeroWhenNotMeasurable")]
281    fn test_measurable_value_returns_zero_when_not_measurable() {
282        let time = Arc::new(MockTime::new());
283        // Java's gauge is `Gauge<Integer> gauge = (c, now) -> 7` โ€” a non-zero
284        // value, so the asserted 0.0 comes from `measurableValue`'s
285        // not-a-measurable branch and not from the gauge's own reading.
286        let gauge = gauge::new(|_, _| MetricValue::Int(7));
287        let metric = KafkaMetric::new(
288            name(),
289            Box::new(gauge),
290            Arc::new(MetricConfig::new()),
291            Arc::clone(&time) as Arc<dyn Time>,
292        );
293        assert_eq!(metric.measurable_value(time.milliseconds()), 0.0);
294    }
295
296    // KafkaMetricTest.testKafkaMetricAcceptsNonMeasurableNonGaugeProvider:
297    // Java's provider is a bare `MetricValueProvider<String>` lambda, neither
298    // `Measurable` nor `Gauge`, which `metric_value_provider::new` builds.
299    #[test]
300    #[doc(
301        alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testKafkaMetricAcceptsNonMeasurableNonGaugeProvider"
302    )]
303    fn test_kafka_metric_accepts_non_measurable_non_gauge_provider() {
304        let provider = metric_value_provider::new(|_, _| MetricValue::String("metric value provider".to_string()));
305        let metric = KafkaMetric::new(
306            name(),
307            Box::new(provider),
308            Arc::new(MetricConfig::new()),
309            Arc::new(MockTime::new()),
310        );
311        assert_eq!(metric.metric_value(), MetricValue::String("metric value provider".to_string()));
312    }
313
314    /// Java's `METRIC_NAME_2`.
315    fn metric_name_2() -> MetricName {
316        MetricName::new(
317            "request-latency-avg",
318            "consumer-fetch-manager-metrics",
319            "The average request latency in ms",
320            BTreeMap::from([("client-id".to_string(), "consumer-1".to_string())]),
321        )
322    }
323
324    /// Java's `testToStringOnLambdaOrAnonymousClass`.
325    fn assert_to_string_on_lambda_or_anonymous_class(metric_value_provider: Box<dyn MetricValueProvider>) {
326        let metric = KafkaMetric::new(
327            metric_name_2(),
328            metric_value_provider,
329            Arc::new(MetricConfig::new()),
330            Arc::new(MockTime::new()),
331        );
332        assert_eq!(
333            "KafkaMetric [metricName=MetricName [name=request-latency-avg, \
334             group=consumer-fetch-manager-metrics, \
335             description=The average request latency in ms, \
336             tags={client-id=consumer-1}]]",
337            metric.to_string()
338        );
339    }
340
341    /// Verifies that `Display` produces a human-readable representation suitable for
342    /// logging. Note that we skip the metric provider in this case.
343    #[test]
344    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testToStringWithLambdaProvider")]
345    fn test_to_string_with_lambda_provider() {
346        let metric_value_provider = ClosureMeasurable::new(|_, _| 0.0);
347        assert_to_string_on_lambda_or_anonymous_class(Box::new(metric_value_provider));
348    }
349
350    /// Java's anonymous `Measurable` subclass. Rust has no anonymous classes: an
351    /// inline provider is a closure behind one of the adapters, so this exercises
352    /// the other adapter, `gauge::new`, which Java's `toString` likewise omits.
353    #[test]
354    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testToStringWithAnonymousClassProvider")]
355    fn test_to_string_with_anonymous_class_provider() {
356        let metric_value_provider = gauge::new(|_, _| MetricValue::Double(0.0));
357        assert_to_string_on_lambda_or_anonymous_class(Box::new(metric_value_provider));
358    }
359
360    #[test]
361    #[doc(alias = "org.apache.kafka.common.metrics.KafkaMetricTest#testToStringWithStatProvider")]
362    fn test_to_string_with_stat_provider() {
363        let avg = Avg::new();
364        let metric = KafkaMetric::new(
365            metric_name_2(),
366            Box::new(avg),
367            Arc::new(MetricConfig::new()),
368            Arc::new(MockTime::new()),
369        );
370        // Java names the Java class; Rust names the type path `type_name` reports.
371        let avg_type = std::any::type_name::<Avg>();
372        assert!(avg_type.starts_with("confluent_kafka::common::metrics::stats::") && avg_type.ends_with("::Avg"));
373        assert_eq!(
374            format!(
375                "KafkaMetric [metricName=MetricName [name=request-latency-avg, \
376                 group=consumer-fetch-manager-metrics, \
377                 description=The average request latency in ms, \
378                 tags={{client-id=consumer-1}}], \
379                 metricValueProvider={avg_type}]"
380            ),
381            metric.to_string()
382        );
383    }
384
385    /// A stat a `Sensor` registers is reported by its own type, not the sensor's
386    /// internal sharing wrapper: Java registers the stat itself as the provider.
387    #[test]
388    fn test_to_string_names_a_sensor_stat_by_its_own_type() {
389        let metrics = crate::common::metrics::Metrics::new();
390        let sensor = metrics.sensor("s").unwrap();
391        sensor
392            .add_with_metric_name(metrics.metric_name("m", "g"), Box::new(Avg::new()))
393            .unwrap();
394        let metric = metrics.metric(&metrics.metric_name("m", "g")).unwrap();
395        let expected_suffix = format!("metricValueProvider={}]", std::any::type_name::<Avg>());
396        assert!(metric.to_string().ends_with(&expected_suffix), "{metric}");
397    }
398}