Skip to main content

confluent_kafka/common/metrics/stats/
windowed_count.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 sampled count of recordings (`org.apache.kafka.common.metrics.stats.WindowedCount`).
16
17use crate::common::metrics::stats::WindowedSumKind;
18use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
19use crate::common::metrics::{Measurable, MetricConfig, Stat};
20
21/// A [`SampledStat`] that maintains a simple count of what it has seen. This is
22/// a special kind of [`crate::common::metrics::stats::WindowedSum`] that always
23/// records a value of `1` instead of the provided value. In other words, it
24/// counts the number of `record` invocations, instead of summing the recorded
25/// values.
26///
27/// See also [`crate::common::metrics::stats::CumulativeCount`] for a non-sampled
28/// version of this metric.
29#[derive(Debug)]
30#[doc(alias = "org.apache.kafka.common.metrics.stats.WindowedCount")]
31pub struct WindowedCount {
32    inner: SampledStat,
33}
34
35struct WindowedCountKind;
36
37impl SampledStatKind for WindowedCountKind {
38    fn update(&self, sample: &mut Sample, config: &MetricConfig, _value: f64, now: i64) {
39        // super.update(sample, config, 1.0, now)
40        WindowedSumKind.update(sample, config, 1.0, now);
41    }
42
43    fn combine(&self, samples: &[Sample], config: &MetricConfig, now: i64) -> f64 {
44        WindowedSumKind.combine(samples, config, now)
45    }
46
47    // WindowedCount extends WindowedSum in Java, so it is both a WindowedSum
48    // and a WindowedCount for the `instanceof` checks in Meter.
49    fn is_windowed_sum(&self) -> bool {
50        true
51    }
52
53    fn is_windowed_count(&self) -> bool {
54        true
55    }
56}
57
58impl WindowedCount {
59    /// Create a `WindowedCount`.
60    #[doc(alias = "org.apache.kafka.common.metrics.stats.WindowedCount#WindowedCount")]
61    pub fn new() -> Self {
62        Self { inner: SampledStat::new(0.0, Box::new(WindowedCountKind)) }
63    }
64
65    /// Consume this `WindowedCount`, yielding its backing [`SampledStat`].
66    /// See [`crate::common::metrics::stats::WindowedSum::into_sampled_stat`].
67    ///
68    /// Used to build a count-based [`crate::common::metrics::stats::Meter`]
69    /// (`Meter::with_rate_stat(WindowedCount::new().into_sampled_stat(), ...)`), as the
70    /// consumer fetch/commit "occurrences" meters do. The production callers land
71    /// with the FetchMetricsManager wiring in Phase M3; exercised here by the
72    /// Meter tests. Kept `pub(crate)` API now to mirror Java's
73    /// `new Meter(unit, new WindowedCount(), ...)`.
74    pub(crate) fn into_sampled_stat(self) -> SampledStat {
75        self.inner
76    }
77}
78
79impl Default for WindowedCount {
80    fn default() -> Self {
81        Self::new()
82    }
83}
84
85impl Stat for WindowedCount {
86    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
87        self.inner.record(config, value, time_ms);
88    }
89}
90
91impl Measurable for WindowedCount {
92    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
93        self.inner.measure(config, now)
94    }
95}
96
97impl std::fmt::Display for WindowedCount {
98    /// Java's `SampledStat.toString()`, which `WindowedCount` inherits.
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        std::fmt::Display::fmt(&self.inner, f)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn to_string_follows_java() {
110        assert_eq!(
111            WindowedCount::new().to_string(),
112            "SampledStat(initialValue=0.0, current=0, samples=[])"
113        );
114    }
115    use crate::common::metrics::TimeUnit;
116    use crate::common::utils::MockTime;
117    use crate::common::utils::Time;
118
119    #[test]
120    fn counts_invocations() {
121        let config = MetricConfig::new();
122        let c = WindowedCount::new();
123        c.record(&config, 5.0, 0);
124        c.record(&config, 99.0, 0);
125        assert_eq!(2.0, c.measure(&config, 0));
126    }
127
128    // MetricsTest.testTimeWindowing
129    #[test]
130    fn test_time_windowing() {
131        let count = WindowedCount::new();
132        let config = MetricConfig::new().set_time_window(1, TimeUnit::Milliseconds).set_samples(2);
133        let time = MockTime::new();
134        count.record(&config, 1.0, time.milliseconds());
135        time.sleep(1);
136        count.record(&config, 1.0, time.milliseconds());
137        assert_eq!(2.0, count.measure(&config, time.milliseconds()));
138        time.sleep(1);
139        count.record(&config, 1.0, time.milliseconds()); // oldest event times out
140        assert_eq!(2.0, count.measure(&config, time.milliseconds()));
141    }
142}