Skip to main content

confluent_kafka/common/metrics/stats/
meter.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 compound stat combining a rate and a cumulative total
16//! (`org.apache.kafka.common.metrics.stats.Meter`).
17
18use std::sync::Arc;
19
20use crate::common::MetricName;
21use crate::common::metrics::TimeUnit;
22use crate::common::metrics::stats::WindowedSum;
23use crate::common::metrics::stats::{CumulativeSum, Rate, SampledStat};
24use crate::common::metrics::{CompoundStat, Measurable, MetricConfig, NamedMeasurable, Stat};
25
26/// A compound stat that includes a rate metric and a cumulative total metric.
27#[derive(Debug)]
28#[doc(alias = "org.apache.kafka.common.metrics.stats.Meter")]
29pub struct Meter {
30    rate_metric_name: MetricName,
31    total_metric_name: MetricName,
32    rate: Arc<Rate>,
33    total: Arc<CumulativeSum>,
34    // Whether the rate's underlying stat is a WindowedCount (Java
35    // `rate.stat instanceof WindowedCount`): then the total records 1.0.
36    rate_stat_is_windowed_count: bool,
37}
38
39impl Meter {
40    /// Construct a `Meter` with seconds as time unit, backed by a `WindowedSum`.
41    ///
42    /// # Arguments
43    ///
44    /// - `rate_metric_name` - the name of the rate metric
45    /// - `total_metric_name` - the name of the cumulative total metric
46    #[doc(alias = "org.apache.kafka.common.metrics.stats.Meter#Meter")]
47    pub fn new(rate_metric_name: MetricName, total_metric_name: MetricName) -> Self {
48        Self::with_unit_rate_stat(
49            TimeUnit::Seconds,
50            Arc::new(WindowedSum::new().into_sampled_stat()),
51            rate_metric_name,
52            total_metric_name,
53        )
54    }
55
56    /// Construct a `Meter` with the provided time unit, backed by a `WindowedSum`.
57    ///
58    /// # Arguments
59    ///
60    /// - `unit` - the time unit of the rate
61    /// - `rate_metric_name` - the name of the rate metric
62    /// - `total_metric_name` - the name of the cumulative total metric
63    #[doc(alias = "org.apache.kafka.common.metrics.stats.Meter#Meter")]
64    pub fn with_unit(unit: TimeUnit, rate_metric_name: MetricName, total_metric_name: MetricName) -> Self {
65        Self::with_unit_rate_stat(
66            unit,
67            Arc::new(WindowedSum::new().into_sampled_stat()),
68            rate_metric_name,
69            total_metric_name,
70        )
71    }
72
73    /// Construct a `Meter` with seconds as time unit.
74    ///
75    /// # Arguments
76    ///
77    /// - `rate_stat` - the sampled stat of the rate, a `WindowedSum` or `WindowedCount`
78    /// - `rate_metric_name` - the name of the rate metric
79    /// - `total_metric_name` - the name of the cumulative total metric
80    ///
81    /// # Panics
82    ///
83    /// If `rate_stat` is not a `WindowedSum` or `WindowedCount`.
84    #[doc(alias = "org.apache.kafka.common.metrics.stats.Meter#Meter")]
85    pub fn with_rate_stat(
86        rate_stat: Arc<SampledStat>,
87        rate_metric_name: MetricName,
88        total_metric_name: MetricName,
89    ) -> Self {
90        Self::with_unit_rate_stat(TimeUnit::Seconds, rate_stat, rate_metric_name, total_metric_name)
91    }
92
93    /// Construct a `Meter` with provided time unit.
94    ///
95    /// # Arguments
96    ///
97    /// - `unit` - the time unit of the rate
98    /// - `rate_stat` - the sampled stat of the rate, a `WindowedSum` or `WindowedCount`
99    /// - `rate_metric_name` - the name of the rate metric
100    /// - `total_metric_name` - the name of the cumulative total metric
101    ///
102    /// # Panics
103    ///
104    /// If `rate_stat` is not a `WindowedSum` or `WindowedCount`, with the
105    /// message of Java's `IllegalArgumentException`: a construction-time
106    /// programming error.
107    #[doc(alias = "org.apache.kafka.common.metrics.stats.Meter#Meter")]
108    pub fn with_unit_rate_stat(
109        unit: TimeUnit,
110        rate_stat: Arc<SampledStat>,
111        rate_metric_name: MetricName,
112        total_metric_name: MetricName,
113    ) -> Self {
114        assert!(
115            rate_stat.is_windowed_sum(),
116            "Meter is supported only for WindowedCount or WindowedSum."
117        );
118        let rate_stat_is_windowed_count = rate_stat.is_windowed_count();
119        Self {
120            rate_metric_name,
121            total_metric_name,
122            rate: Arc::new(Rate::with_unit_stat(unit, rate_stat)),
123            total: Arc::new(CumulativeSum::new()),
124            rate_stat_is_windowed_count,
125        }
126    }
127}
128
129impl Stat for Meter {
130    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
131        self.rate.record(config, value, time_ms);
132        // Total metrics with Count stat should record 1.0 (as recorded in the count)
133        let total_value = if self.rate_stat_is_windowed_count { 1.0 } else { value };
134        self.total.record(config, total_value, time_ms);
135    }
136}
137
138impl CompoundStat for Meter {
139    fn stats(&self) -> Vec<NamedMeasurable> {
140        vec![
141            NamedMeasurable::new(self.total_metric_name.clone(), Arc::clone(&self.total) as Arc<dyn Measurable>),
142            NamedMeasurable::new(self.rate_metric_name.clone(), Arc::clone(&self.rate) as Arc<dyn Measurable>),
143        ]
144    }
145}
146
147impl std::fmt::Display for Meter {
148    /// Java's `toString()`.
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        write!(
151            f,
152            "Meter(rate={}, total={}, rateMetricName={}, totalMetricName={})",
153            self.rate, self.total, self.rate_metric_name, self.total_metric_name
154        )
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn to_string_follows_java() {
164        let name = |n: &str| MetricName::new(n, "g", "d", std::collections::BTreeMap::new());
165        assert_eq!(
166            Meter::new(name("rate"), name("total")).to_string(),
167            "Meter(rate=Rate(unit=SECONDS, stat=SampledStat(initialValue=0.0, current=0, samples=[])), total=CumulativeSum(total=0.0), \
168             rateMetricName=MetricName [name=rate, group=g, description=d, tags={}], \
169             totalMetricName=MetricName [name=total, group=g, description=d, tags={}])"
170        );
171    }
172    use crate::common::metrics::stats::WindowedCount;
173    use std::collections::BTreeMap;
174
175    const EPS: f64 = 0.0000001;
176
177    fn name(n: &str) -> MetricName {
178        MetricName::new(n, "test", "", BTreeMap::new())
179    }
180
181    // MeterTest.testMeter
182    #[test]
183    #[doc(alias = "org.apache.kafka.common.metrics.stats.MeterTest#testMeter")]
184    fn test_meter() {
185        let rate_metric_name = name("rate");
186        let total_metric_name = name("total");
187        let meter = Meter::new(rate_metric_name.clone(), total_metric_name.clone());
188        let stats = meter.stats();
189        assert_eq!(2, stats.len());
190        let total = &stats[0];
191        let rate = &stats[1];
192        assert_eq!(&rate_metric_name, rate.name());
193        assert_eq!(&total_metric_name, total.name());
194        let rate_stat = rate.stat();
195        let total_stat = total.stat();
196
197        let config = MetricConfig::new();
198        let mut next_value = 0.0;
199        let mut expected_total = 0.0;
200        let mut now: i64 = 0;
201        let interval_ms = 100;
202        let delta = 5.0;
203
204        // Record values in multiple windows and verify that rates are reported for
205        // time windows and that the total is cumulative.
206        for i in 1..=100i64 {
207            while now < i * 1000 {
208                expected_total += next_value;
209                meter.record(&config, next_value, now);
210                now += interval_ms;
211                next_value += delta;
212            }
213            assert!((expected_total - total_stat.measure(&config, now)).abs() <= EPS);
214            let window_size_ms = meter.rate.window_size(&config, now);
215            let window_start_ms = (now - window_size_ms).max(0);
216            let mut sampled_total = 0.0;
217            let mut prev_value = next_value - delta;
218            let mut time_ms = now - 100;
219            while time_ms >= window_start_ms {
220                sampled_total += prev_value;
221                time_ms -= interval_ms;
222                prev_value -= delta;
223            }
224            assert!(
225                (sampled_total * 1000.0 / window_size_ms as f64 - rate_stat.measure(&config, now)).abs() <= EPS,
226                "i={i}"
227            );
228        }
229    }
230
231    #[test]
232    fn record_routes_count_total_as_one() {
233        let meter =
234            Meter::with_rate_stat(Arc::new(WindowedCount::new().into_sampled_stat()), name("rate"), name("total"));
235        let config = MetricConfig::new();
236        meter.record(&config, 42.0, 0);
237        meter.record(&config, 7.0, 0);
238        // total is a count, so it records 1.0 per invocation -> 2.0
239        let total = meter.stats()[0].stat();
240        assert_eq!(2.0, total.measure(&config, 0));
241    }
242
243    #[test]
244    #[should_panic(expected = "Meter is supported only for WindowedCount or WindowedSum.")]
245    fn rejects_non_windowed_sum_stat() {
246        use crate::common::metrics::stats::Max;
247        // Build a SampledStat that is not a WindowedSum (Max) and feed it to Meter.
248        let _ = Max::new(); // Max wraps a private SampledStat; build directly instead.
249        // A SampledStat whose kind is not a windowed sum:
250        use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
251        struct NotSum;
252        impl SampledStatKind for NotSum {
253            fn update(&self, _s: &mut Sample, _c: &MetricConfig, _v: f64, _t: i64) {}
254            fn combine(&self, _s: &[Sample], _c: &MetricConfig, _n: i64) -> f64 {
255                0.0
256            }
257        }
258        let stat = Arc::new(SampledStat::new(0.0, Box::new(NotSum)));
259        let _ = Meter::with_rate_stat(stat, name("rate"), name("total"));
260    }
261}