Skip to main content

confluent_kafka/common/metrics/stats/
simple_rate.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 simple incremental rate (`org.apache.kafka.common.metrics.stats.SimpleRate`).
16
17use crate::common::metrics::TimeUnit;
18use crate::common::metrics::internals::MetricsUtils;
19use crate::common::metrics::stats::Rate;
20use crate::common::metrics::{Measurable, MetricConfig, Stat};
21
22/// A simple rate: the rate is incrementally calculated based on the elapsed time
23/// between the earliest reading and now.
24///
25/// An exception is made for the first window, which is considered of fixed size.
26/// This avoids the issue of an artificially high rate when the gap between
27/// readings is close to 0.
28///
29/// # Translation notes
30///
31/// Composes a [`Rate`] instead of extending it.
32#[derive(Debug)]
33#[doc(alias = "org.apache.kafka.common.metrics.stats.SimpleRate")]
34// Java's `SimpleRate extends Rate` and overrides only `windowSize`; Rust
35// re-implements `measure` using the overridden `window_size`.
36pub struct SimpleRate {
37    rate: Rate,
38}
39
40impl SimpleRate {
41    /// Create a `SimpleRate` over seconds backed by a `WindowedSum`.
42    #[doc(alias = "org.apache.kafka.common.metrics.stats.SimpleRate#SimpleRate")]
43    pub fn new() -> Self {
44        Self { rate: Rate::new() }
45    }
46
47    /// Compute the window size in milliseconds, overriding [`Rate::window_size`]:
48    /// `max(elapsed, config.timeWindowMs())`.
49    ///
50    /// # Arguments
51    ///
52    /// - `config` - the metric's configuration
53    /// - `now` - the current POSIX time in milliseconds
54    ///
55    /// # Returns
56    ///
57    /// The window size in milliseconds.
58    #[doc(alias = "org.apache.kafka.common.metrics.stats.SimpleRate#windowSize")]
59    pub fn window_size(&self, config: &MetricConfig, now: i64) -> i64 {
60        let stat = self.rate.stat();
61        stat.purge_obsolete_samples(config, now);
62        let elapsed = now - stat.oldest_start_time_ms(now);
63        elapsed.max(config.time_window_ms())
64    }
65}
66
67impl Default for SimpleRate {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl Stat for SimpleRate {
74    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
75        self.rate.record(config, value, time_ms);
76    }
77}
78
79impl Measurable for SimpleRate {
80    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
81        // Rate.measure: value / convert(windowSize, unit). The unit is SECONDS
82        // for the default SimpleRate constructor (matching Java).
83        let value = self.rate.stat().measure(config, now);
84        value / MetricsUtils::convert(self.window_size(config, now), TimeUnit::Seconds)
85    }
86}
87
88impl std::fmt::Display for SimpleRate {
89    /// Java's `Rate.toString()`, which `SimpleRate` inherits.
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        std::fmt::Display::fmt(&self.rate, f)
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn to_string_follows_java() {
101        assert_eq!(
102            SimpleRate::new().to_string(),
103            "Rate(unit=SECONDS, stat=SampledStat(initialValue=0.0, current=0, samples=[]))"
104        );
105    }
106    use crate::common::utils::MockTime;
107    use crate::common::utils::Time;
108
109    fn record(rate: &SimpleRate, config: &MetricConfig, time: &MockTime, value: f64) {
110        rate.record(config, value, time.milliseconds());
111    }
112    fn measure(rate: &SimpleRate, config: &MetricConfig, time: &MockTime) -> f64 {
113        rate.measure(config, time.milliseconds())
114    }
115
116    // MetricsTest.testSimpleRate
117    #[test]
118    fn test_simple_rate() {
119        let rate = SimpleRate::new();
120        let config = MetricConfig::new().set_time_window(1, TimeUnit::Seconds).set_samples(10);
121        let time = MockTime::new();
122
123        // In the first window the rate is a fraction of the whole (1s) window.
124        // So when we record 1000 at t0, the rate should be 1000 until the window
125        // completes, or more data is recorded.
126        record(&rate, &config, &time, 1000.0);
127        assert_eq!(1000.0, measure(&rate, &config, &time)); // 1000B / 0s -> first window fixed
128        time.sleep(100);
129        assert_eq!(1000.0, measure(&rate, &config, &time)); // 1000B / 0.1s
130        time.sleep(100);
131        assert_eq!(1000.0, measure(&rate, &config, &time)); // 1000B / 0.2s
132        time.sleep(200);
133        assert_eq!(1000.0, measure(&rate, &config, &time)); // 1000B / 0.4s
134
135        // In the second (and subsequent) window(s), the rate will be in proportion
136        // to the elapsed time.
137        time.sleep(600);
138        assert_eq!(1000.0, measure(&rate, &config, &time)); // 1000B / 1.0s
139        time.sleep(200);
140        assert_eq!(1000.0 / 1.2, measure(&rate, &config, &time)); // 1000B / 1.2s
141        time.sleep(200);
142        assert_eq!(1000.0 / 1.4, measure(&rate, &config, &time)); // 1000B / 1.4s
143
144        // Adding another value, inside the same window should double the rate.
145        record(&rate, &config, &time, 1000.0);
146        assert_eq!(2000.0 / 1.4, measure(&rate, &config, &time)); // 2000B / 1.4s
147
148        // Going over the next window should not change behaviour.
149        time.sleep(1100);
150        assert_eq!(2000.0 / 2.5, measure(&rate, &config, &time)); // 2000B / 2.5s
151        record(&rate, &config, &time, 1000.0);
152        assert_eq!(3000.0 / 2.5, measure(&rate, &config, &time)); // 3000B / 2.5s
153
154        // Sleeping for another 6.5 windows also should be the same (tolerance 1).
155        time.sleep(6500);
156        assert!((3000.0 / 9.0 - measure(&rate, &config, &time)).abs() <= 1.0); // 3000B / 9s
157        record(&rate, &config, &time, 1000.0);
158        assert!((4000.0 / 9.0 - measure(&rate, &config, &time)).abs() <= 1.0); // 4000B / 9s
159
160        // Going over the 10 window boundary should purge the first window's
161        // values (1000). So the rate is calculated based on the oldest reading,
162        // which is inside the second window, at 1.4s.
163        time.sleep(1500);
164        assert!(((4000.0 - 1000.0) / (10.5 - 1.4) - measure(&rate, &config, &time)).abs() <= 1.0);
165        record(&rate, &config, &time, 1000.0);
166        assert!(((5000.0 - 1000.0) / (10.5 - 1.4) - measure(&rate, &config, &time)).abs() <= 1.0);
167    }
168}