Skip to main content

confluent_kafka/common/metrics/stats/
windowed_sum.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 sum maintained over the sample windows
16//! (`org.apache.kafka.common.metrics.stats.WindowedSum`).
17
18use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
19use crate::common::metrics::{Measurable, MetricConfig, Stat};
20
21/// A [`SampledStat`] that maintains the sum of what it has seen. This is a
22/// sampled version of [`crate::common::metrics::stats::CumulativeSum`].
23///
24/// See also [`crate::common::metrics::stats::WindowedCount`] if you want to
25/// increment the value by 1 on each recording.
26#[derive(Debug)]
27#[doc(alias = "org.apache.kafka.common.metrics.stats.WindowedSum")]
28pub struct WindowedSum {
29    inner: SampledStat,
30}
31
32/// The per-subclass behaviour shared by `WindowedSum` (and used as the base
33/// behaviour for `WindowedCount`, which records `1.0`).
34pub(crate) struct WindowedSumKind;
35
36impl SampledStatKind for WindowedSumKind {
37    fn update(&self, sample: &mut Sample, _config: &MetricConfig, value: f64, _now: i64) {
38        sample.value += value;
39    }
40
41    fn combine(&self, samples: &[Sample], _config: &MetricConfig, _now: i64) -> f64 {
42        let mut total = 0.0;
43        for sample in samples {
44            total += sample.value;
45        }
46        total
47    }
48
49    fn is_windowed_sum(&self) -> bool {
50        true
51    }
52}
53
54impl WindowedSum {
55    /// Create a `WindowedSum`.
56    #[doc(alias = "org.apache.kafka.common.metrics.stats.WindowedSum#WindowedSum")]
57    pub fn new() -> Self {
58        Self { inner: SampledStat::new(0.0, Box::new(WindowedSumKind)) }
59    }
60
61    /// Consume this `WindowedSum`, yielding its backing [`SampledStat`].
62    ///
63    /// Used by [`crate::common::metrics::stats::Rate`] /
64    /// [`crate::common::metrics::stats::Meter`], which hold the `SampledStat`
65    /// directly (Java `Rate.stat` is a `SampledStat`).
66    pub(crate) fn into_sampled_stat(self) -> SampledStat {
67        self.inner
68    }
69}
70
71impl Default for WindowedSum {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77impl Stat for WindowedSum {
78    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
79        self.inner.record(config, value, time_ms);
80    }
81}
82
83impl Measurable for WindowedSum {
84    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
85        self.inner.measure(config, now)
86    }
87}
88
89impl std::fmt::Display for WindowedSum {
90    /// Java's `SampledStat.toString()`, which `WindowedSum` inherits.
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        std::fmt::Display::fmt(&self.inner, f)
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn to_string_follows_java() {
102        assert_eq!(
103            WindowedSum::new().to_string(),
104            "SampledStat(initialValue=0.0, current=0, samples=[])"
105        );
106    }
107
108    #[test]
109    fn sums_over_window() {
110        let config = MetricConfig::new();
111        let s = WindowedSum::new();
112        s.record(&config, 1.0, 0);
113        s.record(&config, 2.0, 0);
114        s.record(&config, 3.0, 0);
115        assert_eq!(6.0, s.measure(&config, 0));
116    }
117}