Skip to main content

confluent_kafka/common/metrics/stats/
avg.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 average (`org.apache.kafka.common.metrics.stats.Avg`).
16
17use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
18use crate::common::metrics::{Measurable, MetricConfig, Stat};
19
20/// A [`SampledStat`] that maintains a simple average over its samples.
21#[derive(Debug)]
22#[doc(alias = "org.apache.kafka.common.metrics.stats.Avg")]
23pub struct Avg {
24    inner: SampledStat,
25}
26
27struct AvgKind;
28
29impl SampledStatKind for AvgKind {
30    fn update(&self, sample: &mut Sample, _config: &MetricConfig, value: f64, _now: i64) {
31        sample.value += value;
32    }
33
34    fn combine(&self, samples: &[Sample], _config: &MetricConfig, _now: i64) -> f64 {
35        let mut total = 0.0;
36        let mut count: i64 = 0;
37        for s in samples {
38            total += s.value;
39            count += s.event_count;
40        }
41        if count == 0 { f64::NAN } else { total / count as f64 }
42    }
43}
44
45impl Avg {
46    /// Create an `Avg`.
47    #[doc(alias = "org.apache.kafka.common.metrics.stats.Avg#Avg")]
48    pub fn new() -> Self {
49        Self { inner: SampledStat::new(0.0, Box::new(AvgKind)) }
50    }
51}
52
53impl Default for Avg {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl Stat for Avg {
60    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
61        self.inner.record(config, value, time_ms);
62    }
63}
64
65impl Measurable for Avg {
66    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
67        self.inner.measure(config, now)
68    }
69}
70
71impl std::fmt::Display for Avg {
72    /// Java's `SampledStat.toString()`, which `Avg` inherits.
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        std::fmt::Display::fmt(&self.inner, f)
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn average_of_records() {
84        let config = MetricConfig::new();
85        let avg = Avg::new();
86        for i in 0..10 {
87            avg.record(&config, i as f64, 0);
88        }
89        assert_eq!(4.5, avg.measure(&config, 0));
90    }
91
92    #[test]
93    fn nan_when_no_events() {
94        let config = MetricConfig::new();
95        let avg = Avg::new();
96        assert!(avg.measure(&config, 0).is_nan());
97    }
98}