confluent_kafka/common/metrics/stats/
windowed_sum.rs1use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
19use crate::common::metrics::{Measurable, MetricConfig, Stat};
20
21#[derive(Debug)]
27#[doc(alias = "org.apache.kafka.common.metrics.stats.WindowedSum")]
28pub struct WindowedSum {
29 inner: SampledStat,
30}
31
32pub(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 #[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 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 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}