Skip to main content

confluent_kafka/common/metrics/
metric_value_provider.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//! Super-interface for `Measurable` or `Gauge` that provides metric values
16//! (`org.apache.kafka.common.metrics.MetricValueProvider`).
17
18use crate::common::MetricValue;
19use crate::common::metrics::{Measurable, MetricConfig};
20
21/// Super-interface for [`Measurable`] or [`Gauge`](crate::common::metrics::Gauge)
22/// that provides metric values.
23///
24/// # Translation notes
25///
26/// It yields a [`MetricValue`].
27// Java's `MetricValueProvider<T>` is generic over the produced value type
28// (`Double` for `Measurable`, `T` for `Gauge<T>`); the public
29// `Metric::metric_value` returns an erased value, so the Rust provider produces
30// the type-erased `MetricValue`. Rust cannot default a supertrait's method from
31// a subtrait, so every `Measurable` implements `MetricValueProvider` through a
32// blanket impl whose `value` is `MetricValue::Double` of `measure`.
33#[doc(alias = "org.apache.kafka.common.metrics.MetricValueProvider")]
34pub trait MetricValueProvider: Send + Sync {
35    /// Returns the current value associated with this metric.
36    ///
37    /// # Arguments
38    ///
39    /// - `config` - The configuration for this metric
40    /// - `now` - The POSIX time in milliseconds the measurement is being taken
41    ///
42    /// # Returns
43    ///
44    /// the current metric value
45    #[doc(alias = "org.apache.kafka.common.metrics.MetricValueProvider#value")]
46    fn value(&self, config: &MetricConfig, now: i64) -> MetricValue;
47
48    /// Returns the provider's type name, as `KafkaMetric`'s `Display` reports
49    /// it, or `None` for a provider that is a closure.
50    ///
51    /// Java's `KafkaMetric.toString` reads the provider's class name
52    /// reflectively and omits it for a lambda. Rust has no reflection, so the
53    /// provider reports it: the default is the implementing type's
54    /// [`std::any::type_name`], and the closure adapters answer `None`.
55    // stands in for Java's reflective `getClass().getName()` in `KafkaMetric.toString`
56    #[doc(alias = "rust-only")]
57    fn type_name(&self) -> Option<&'static str> {
58        Some(std::any::type_name::<Self>())
59    }
60
61    /// Returns this provider as a [`Measurable`], or `None` when it is not one.
62    ///
63    /// It stands in for Java's `metricValueProvider instanceof Measurable` in
64    /// `KafkaMetric`, which a trait object cannot answer by itself. The
65    /// [`Measurable`] blanket impl answers `Some`; nothing else should override
66    /// it.
67    // public only because a trait method cannot be narrower than its trait;
68    // hidden, it stands in for Java's `instanceof Measurable` in `KafkaMetric`
69    #[doc(hidden)]
70    #[doc(alias = "rust-only")]
71    fn as_measurable(&self) -> Option<&dyn Measurable> {
72        None
73    }
74}
75
76/// Java's `Measurable.value` default: the measured quantity as a double.
77impl<M: Measurable> MetricValueProvider for M {
78    fn value(&self, config: &MetricConfig, now: i64) -> MetricValue {
79        MetricValue::Double(self.measure(config, now))
80    }
81
82    fn type_name(&self) -> Option<&'static str> {
83        Measurable::type_name(self)
84    }
85
86    fn as_measurable(&self) -> Option<&dyn Measurable> {
87        Some(self)
88    }
89}
90
91/// A [`MetricValueProvider`] that calls `function`, standing in for a Java
92/// lambda implementing `MetricValueProvider`: `function` is
93/// [`value`](MetricValueProvider::value). A method Java adds later as an
94/// overload of `value` gets its own factory, `with_<parameter>`.
95///
96/// # Arguments
97///
98/// - `function` - computes the value from the config and the time in milliseconds
99///
100/// # Returns
101///
102/// The provider calling `function`.
103///
104/// ```
105/// use confluent_kafka::common::MetricValue;
106/// use confluent_kafka::common::metrics::{metric_value_provider, Metrics};
107///
108/// let metrics = Metrics::new();
109/// let name = metrics.metric_name("uptime-ms", "example");
110/// let provider = metric_value_provider::new(|_config, now| MetricValue::Double(now as f64));
111/// metrics.add_metric_with_metric_value_provider(name, Box::new(provider)).unwrap();
112/// ```
113// stands in for a Java lambda implementing `MetricValueProvider`
114#[doc(alias = "rust-only")]
115pub fn new<F>(function: F) -> impl MetricValueProvider
116where
117    F: Fn(&MetricConfig, i64) -> MetricValue + Send + Sync,
118{
119    struct FunctionMetricValueProvider<F>(F);
120
121    impl<F> MetricValueProvider for FunctionMetricValueProvider<F>
122    where
123        F: Fn(&MetricConfig, i64) -> MetricValue + Send + Sync,
124    {
125        fn value(&self, config: &MetricConfig, now: i64) -> MetricValue {
126            (self.0)(config, now)
127        }
128
129        // A function is Rust's lambda, which Java's `KafkaMetric.toString` omits.
130        fn type_name(&self) -> Option<&'static str> {
131            None
132        }
133    }
134
135    FunctionMetricValueProvider(function)
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn new_calls_the_function_and_is_neither_named_nor_measurable() {
144        let provider = new(|_config, now| MetricValue::Long(now * 2));
145        assert_eq!(provider.value(&MetricConfig::default(), 21), MetricValue::Long(42));
146        assert_eq!(provider.type_name(), None);
147        assert!(provider.as_measurable().is_none());
148    }
149}