Skip to main content

confluent_kafka/common/metrics/
measurable.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 measurable quantity that can be registered as a metric
16//! (`org.apache.kafka.common.metrics.Measurable`).
17
18use crate::common::metrics::MetricConfig;
19
20/// A measurable quantity that can be registered as a metric.
21///
22/// # Translation notes
23///
24/// Blanket-implements [`MetricValueProvider`](crate::common::metrics::MetricValueProvider).
25// Java's `Measurable extends MetricValueProvider<Double>` with a default
26// `value` delegating to `measure`; the blanket impl makes every `Measurable` a
27// `MetricValueProvider` whose `value` is `measure`.
28#[doc(alias = "org.apache.kafka.common.metrics.Measurable")]
29pub trait Measurable: Send + Sync {
30    /// Measure this quantity and return the result as a double.
31    ///
32    /// # Arguments
33    ///
34    /// - `config` - The configuration for this metric
35    /// - `now` - The POSIX time in milliseconds the measurement is being taken
36    ///
37    /// # Returns
38    ///
39    /// The measured value
40    #[doc(alias = "org.apache.kafka.common.metrics.Measurable#measure")]
41    fn measure(&self, config: &MetricConfig, now: i64) -> f64;
42
43    /// Returns the provider's type name, as `KafkaMetric`'s `Display` reports
44    /// it, or `None` for a provider that is a closure.
45    ///
46    /// Java's `KafkaMetric.toString` reads the provider's class name
47    /// reflectively and omits it for a lambda. Rust has no reflection, so the
48    /// provider reports it: the default is the implementing type's
49    /// [`std::any::type_name`], and the closure adapters answer `None`.
50    // stands in for Java's reflective `getClass().getName()` in `KafkaMetric.toString`
51    #[doc(alias = "rust-only")]
52    fn type_name(&self) -> Option<&'static str> {
53        Some(std::any::type_name::<Self>())
54    }
55}
56
57/// A boxed measurable is a measurable, so `Box<dyn Measurable>` is a
58/// [`crate::common::metrics::MetricValueProvider`] too.
59impl<M: Measurable + ?Sized> Measurable for Box<M> {
60    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
61        (**self).measure(config, now)
62    }
63
64    fn type_name(&self) -> Option<&'static str> {
65        (**self).type_name()
66    }
67}
68
69/// A [`Measurable`] backed by a closure, mirroring Java's functional-interface
70/// usage of `Measurable` (e.g. `(config, now) -> TimeUnit.SECONDS.convert(...)`
71/// in `KafkaConsumerMetrics` / `HeartbeatMetricsManager`). The symmetric
72/// counterpart of [`crate::common::metrics::gauge::new`].
73// a Measurable from a closure, standing in for a Java lambda
74#[doc(alias = "rust-only")]
75pub struct ClosureMeasurable<F>(F)
76where
77    F: Fn(&MetricConfig, i64) -> f64 + Send + Sync;
78
79impl<F> ClosureMeasurable<F>
80where
81    F: Fn(&MetricConfig, i64) -> f64 + Send + Sync,
82{
83    /// Wraps a closure as a measurable.
84    ///
85    /// # Arguments
86    ///
87    /// - `f` - the closure computing the value from the config and the time in milliseconds
88    pub fn new(f: F) -> Self {
89        Self(f)
90    }
91}
92
93impl<F> std::fmt::Debug for ClosureMeasurable<F>
94where
95    F: Fn(&MetricConfig, i64) -> f64 + Send + Sync,
96{
97    // A closure has nothing to print.
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("ClosureMeasurable").finish_non_exhaustive()
100    }
101}
102
103impl<F> Measurable for ClosureMeasurable<F>
104where
105    F: Fn(&MetricConfig, i64) -> f64 + Send + Sync,
106{
107    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
108        (self.0)(config, now)
109    }
110
111    // A closure is Rust's lambda, which Java's `KafkaMetric.toString` omits.
112    fn type_name(&self) -> Option<&'static str> {
113        None
114    }
115}