1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/// Custom metric value types for tracking domain-specific statistics
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum CustomMetricValue {
Accumulator(f64),
Histogram {
min: f64,
max: f64,
count: u64,
sum: f64, // Track sum for efficient average calculation
avg: f64,
median: f64,
entropy: f64,
#[serde(skip)]
values: Vec<f64>,
},
}
impl CustomMetricValue {
pub fn add_to_accumulator(&mut self, value: f64) {
match self {
Self::Accumulator(accumulator) => *accumulator += value,
_ => panic!("Cannot add to non-accumulator metric"),
}
}
pub fn add_to_histogram(&mut self, value: f64) {
match self {
Self::Histogram {
min,
max,
count,
sum,
values,
..
} => {
*min = min.min(value);
*max = max.max(value);
*sum += value;
*count += 1;
values.push(value);
if values.len() == values.capacity() {
values.reserve(10_000);
}
// Note: We don't sort here! Only when needed for median calculation
}
_ => panic!("Cannot add to non-histogram metric"),
}
}
/// Calculate average efficiently from sum and count
pub fn get_avg(&self) -> f64 {
match self {
Self::Histogram { count, sum, .. } => {
if *count > 0 {
*sum / (*count as f64)
} else {
0.0
}
}
_ => panic!("Cannot get average from non-histogram metric"),
}
}
/// Calculate median (sorts values only when needed)
pub fn get_median(&self) -> f64 {
match self {
Self::Histogram { values, .. } => {
if values.is_empty() {
return 0.0;
}
let mut sorted_values = values.clone();
sorted_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
let len = sorted_values.len();
if len % 2 == 0 {
(sorted_values[len / 2 - 1] + sorted_values[len / 2]) / 2.0
} else {
sorted_values[len / 2]
}
}
_ => panic!("Cannot get median from non-histogram metric"),
}
}
/// Calculate Shannon's entropy for a list of values
/// Shannon entropy: H(X) = -Σ p(x) * log2(p(x))
/// where p(x) is the probability of value x occurring
pub fn calculate_shannon_entropy(values: &[f64]) -> f64 {
if values.is_empty() {
return 0.0;
}
// Create frequency map
let mut frequency_map = std::collections::HashMap::new();
for &value in values {
*frequency_map.entry(value.to_bits()).or_insert(0) += 1;
}
let total_count = values.len() as f64;
let mut entropy = 0.0;
for &count in frequency_map.values() {
let probability = count as f64 / total_count;
if probability > 0.0 {
entropy -= probability * probability.log2();
}
}
entropy
}
/// Update computed values for serialization
pub fn finalize_histogram(&mut self) {
if let Self::Histogram {
count,
sum,
values,
avg,
median,
entropy,
..
} = self
{
// Calculate average efficiently from sum and count
*avg = if *count > 0 {
*sum / (*count as f64)
} else {
0.0
};
// Calculate median (sorts values only when needed)
*median = if values.is_empty() {
0.0
} else {
let mut sorted_values = values.clone();
sorted_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
let len = sorted_values.len();
if len % 2 == 0 {
(sorted_values[len / 2 - 1] + sorted_values[len / 2]) / 2.0
} else {
sorted_values[len / 2]
}
};
// Calculate entropy (only when needed for dashboard)
*entropy = Self::calculate_shannon_entropy(values);
}
}
}