Skip to main content

confluent_kafka/common/metrics/stats/
cumulative_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 non-sampled cumulative total maintained over all time
16//! (`org.apache.kafka.common.metrics.stats.CumulativeSum`).
17
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use crate::common::metrics::{Measurable, MetricConfig, Stat};
21
22/// A non-sampled cumulative total maintained over all time. This is a
23/// non-sampled version of `WindowedSum`.
24///
25/// See also [`crate::common::metrics::stats::CumulativeCount`] if you just want to
26/// increment the value by 1 on each recording.
27#[derive(Debug)]
28#[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum")]
29// The running total `f64` is held as its bit pattern in an `AtomicU64` and
30// updated with a compare-exchange add loop: the same IEEE-754 addition as Java's
31// `total += value`, the CAS only serializing concurrent recorders as Java's
32// sensor `synchronized` does.
33pub struct CumulativeSum {
34    total: AtomicU64,
35}
36
37impl CumulativeSum {
38    /// Create a `CumulativeSum` initialized to `0.0`.
39    #[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum#CumulativeSum")]
40    pub fn new() -> Self {
41        Self::with_value(0.0)
42    }
43
44    /// Create a `CumulativeSum` initialized to `value`.
45    ///
46    /// # Arguments
47    ///
48    /// - `value` - the initial total
49    #[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum#CumulativeSum")]
50    pub fn with_value(value: f64) -> Self {
51        Self { total: AtomicU64::new(value.to_bits()) }
52    }
53}
54
55impl Default for CumulativeSum {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl Stat for CumulativeSum {
62    fn record(&self, _config: &MetricConfig, value: f64, _now: i64) {
63        let mut current = self.total.load(Ordering::Relaxed);
64        loop {
65            let updated = (f64::from_bits(current) + value).to_bits();
66            match self
67                .total
68                .compare_exchange_weak(current, updated, Ordering::SeqCst, Ordering::Relaxed)
69            {
70                Ok(_) => break,
71                Err(observed) => current = observed,
72            }
73        }
74    }
75}
76
77impl Measurable for CumulativeSum {
78    fn measure(&self, _config: &MetricConfig, _now: i64) -> f64 {
79        f64::from_bits(self.total.load(Ordering::SeqCst))
80    }
81}
82
83impl std::fmt::Display for CumulativeSum {
84    /// Java's `toString()`, the total as Java's `Double.toString`.
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        let total = f64::from_bits(self.total.load(Ordering::SeqCst));
87        write!(
88            f,
89            "CumulativeSum(total={})",
90            crate::common::config::config_def::java_double_to_string(total)
91        )
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn to_string_follows_java() {
101        let sum = CumulativeSum::new();
102        sum.record(&MetricConfig::new(), 1.5, 0);
103        assert_eq!(sum.to_string(), "CumulativeSum(total=1.5)");
104        assert_eq!(CumulativeSum::with_value(1e8).to_string(), "CumulativeSum(total=1.0E8)");
105    }
106
107    #[test]
108    fn test_cumulative_sum() {
109        let config = MetricConfig::new();
110        let s = CumulativeSum::new();
111        assert_eq!(s.measure(&config, 0), 0.0);
112        s.record(&config, 5.0, 0);
113        s.record(&config, 2.5, 1);
114        s.record(&config, -1.0, 2);
115        assert_eq!(s.measure(&config, 2), 6.5);
116    }
117
118    #[test]
119    fn test_with_value_seed() {
120        let config = MetricConfig::new();
121        let s = CumulativeSum::with_value(10.0);
122        assert_eq!(s.measure(&config, 0), 10.0);
123        s.record(&config, 5.0, 0);
124        assert_eq!(s.measure(&config, 0), 15.0);
125    }
126}