confluent_kafka/common/metrics/stats/
max.rs1use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
18use crate::common::metrics::{Measurable, MetricConfig, Stat};
19
20#[derive(Debug)]
22#[doc(alias = "org.apache.kafka.common.metrics.stats.Max")]
23pub struct Max {
24 inner: SampledStat,
25}
26
27struct MaxKind;
28
29impl SampledStatKind for MaxKind {
30 fn update(&self, sample: &mut Sample, _config: &MetricConfig, value: f64, _now: i64) {
31 sample.value = sample.value.max(value);
32 }
33
34 fn combine(&self, samples: &[Sample], _config: &MetricConfig, _now: i64) -> f64 {
35 let mut max = f64::NEG_INFINITY;
36 let mut count: i64 = 0;
37 for sample in samples {
38 max = max.max(sample.value);
39 count += sample.event_count;
40 }
41 if count == 0 { f64::NAN } else { max }
42 }
43}
44
45impl Max {
46 #[doc(alias = "org.apache.kafka.common.metrics.stats.Max#Max")]
48 pub fn new() -> Self {
49 Self { inner: SampledStat::new(f64::NEG_INFINITY, Box::new(MaxKind)) }
50 }
51}
52
53impl Default for Max {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl Stat for Max {
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 Max {
66 fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
67 self.inner.measure(config, now)
68 }
69}
70
71impl std::fmt::Display for Max {
72 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 to_string_follows_java() {
84 assert_eq!(
85 Max::new().to_string(),
86 "SampledStat(initialValue=-Infinity, current=0, samples=[])"
87 );
88 }
89 use crate::common::metrics::TimeUnit;
90 use crate::common::utils::MockTime;
91 use crate::common::utils::Time;
92
93 #[test]
94 fn max_of_records() {
95 let config = MetricConfig::new();
96 let max = Max::new();
97 for i in 0..10 {
98 max.record(&config, i as f64, 0);
99 }
100 assert_eq!(9.0, max.measure(&config, 0));
101 }
102
103 #[test]
105 fn test_old_data_has_no_effect() {
106 let max = Max::new();
107 let window_ms = 100i64;
108 let samples = 2;
109 let config = MetricConfig::new()
110 .set_time_window(window_ms, TimeUnit::Milliseconds)
111 .set_samples(samples);
112 let time = MockTime::new();
113 max.record(&config, 50.0, time.milliseconds());
114 time.sleep(samples as i64 * window_ms);
115 assert!(max.measure(&config, time.milliseconds()).is_nan());
116 }
117}