confluent_kafka/common/metrics/stats/
windowed_count.rs1use crate::common::metrics::stats::WindowedSumKind;
18use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
19use crate::common::metrics::{Measurable, MetricConfig, Stat};
20
21#[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 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 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 #[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 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 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 #[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()); assert_eq!(2.0, count.measure(&config, time.milliseconds()));
141 }
142}