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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::sync::{
    atomic::{AtomicI64, AtomicU64, Ordering},
    Arc,
};

use serde::{
    ser::{SerializeSeq, SerializeStruct},
    Serialize, Serializer,
};

use super::prometheus::Encoder;

pub const BASIC_LE_CALCULATOR: [f64; 10] =
    [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0];

pub const HISTOGRAM_MODIFIER: i64 = 100_000;

#[derive(Debug, Clone)]
pub struct HistogramVec {
    pub metrics: Vec<Histogram>,
}

#[derive(Debug, Clone)]
pub struct Histogram {
    pub sum: Arc<AtomicI64>,
    pub count: Arc<AtomicU64>,
    pub counters: HistogramBucket,
    pub labels: Vec<(&'static str, &'static str)>,
}

#[derive(Debug, Clone)]
pub struct HistogramBucket {
    pub observations: Vec<Observation>,
}

#[derive(Debug, Clone)]
pub struct Observation {
    pub le: f64,
    pub value: Arc<AtomicU64>,
}
impl Observation {
    pub fn new(le: f64) -> Self {
        Self {
            value: Arc::new(AtomicU64::new(0)),
            le,
        }
    }
}

impl HistogramBucket {
    pub fn new(le: &[f64]) -> Self {
        Self {
            observations: le.iter().map(|v| Observation::new(*v)).collect(),
        }
    }
    pub fn observe(&self, value: f64) {
        for observation in &self.observations {
            if value > observation.le {
                continue;
            }
            observation.value.fetch_add(1, Ordering::SeqCst);
            
        }
    }
    pub fn get_count(&self, le: f64) -> Option<u64> {
        for observation in &self.observations {
            if le >= observation.le {
                return Some(observation.value.load(Ordering::Relaxed));
            }
        }
        None
    }
}

fn normalize_f64(numb: f64) -> i64 {
    (numb * (HISTOGRAM_MODIFIER as f64)) as i64
}
fn normalize_i64(numb: i64) -> f64 {
    (numb as f64 / HISTOGRAM_MODIFIER as f64) as f64
}

impl HistogramVec {
    /// Creates a new histogram with static labels. The metric won't accept a new label once created.
    pub fn new(labels: Vec<Vec<(&'static str, &'static str)>>) -> Self {
        Self::with_le(labels, &BASIC_LE_CALCULATOR)
    }
    /// Creates a new histogram with static labels and custom values for the LE (lesser than or equals) parameter. The metric won't accept a new label once created.
    pub fn with_le(labels: Vec<Vec<(&'static str, &'static str)>>, le: &[f64]) -> Self {
        let mut metrics = Vec::with_capacity(labels.len());
        for label in labels {
            metrics.push(Histogram::with_le(label, le));
        }
        Self { metrics }
    }
    /// Obtains a histogram with the specified labels
    pub fn with_labels(&self, labels: &[(&str, &str)]) -> Option<&Histogram> {
        'cnt: for hist in &self.metrics {
            if hist.labels.len() != labels.len() {
                continue;
            }
            for ((name1, value1), (name2, value2)) in hist.labels.iter().zip(labels.iter()) {
                if name1 != name2 || value1 != value2 {
                    continue 'cnt;
                }
            }
            return Some(hist);
        }
        None
    }
}

impl Histogram {
    /// Creates a new Histogram with static labels and the default le params: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
    pub fn new(labels: Vec<(&'static str, &'static str)>) -> Self {
        Self::with_le(labels, &BASIC_LE_CALCULATOR[..])
    }
    /// Creates a new Histogram with static labels and a custom LE
    pub fn with_le(labels: Vec<(&'static str, &'static str)>, le: &[f64]) -> Self {
        Self {
            sum: Arc::new(AtomicI64::new(0)),
            count: Arc::new(AtomicU64::new(0)),
            counters: HistogramBucket::new(le),
            labels,
        }
    }
    /// Observe a value
    pub fn observe(&self, value: f64) {
        self.count.fetch_add(1, Ordering::SeqCst);
        self.sum.fetch_add(normalize_f64(value), Ordering::SeqCst);
        self.counters.observe(value);
    }
    /// Get the number of samples
    pub fn get_sample_count(&self) -> u64 {
        self.count.load(Ordering::Relaxed)
    }
    /// Get the acumulated sample value
    pub fn get_sample_sum(&self) -> f64 {
        normalize_i64(self.sum.load(Ordering::Relaxed))
    }
}

impl Encoder for HistogramVec {
    fn encode<W: std::fmt::Write>(
        &self,
        f: &mut W,
        name: &str,
        description: &str,
        help: bool,
    ) -> Result<(), std::fmt::Error> {
        if self.metrics.len() == 0 {
            return Ok(())
        }
        if help {
            f.write_str("# HELP ")?;
            f.write_str(name)?;
            f.write_str(" ")?;
            f.write_str(description)?;
            f.write_str("\n")?;
        }
        f.write_str("# TYPE ")?;
        f.write_str(name)?;
        f.write_str(" histogram \n")?;
        for counter in &self.metrics {
            counter.encode(f, name, description, help)?;
        }
        Ok(())
    }
}

impl Encoder for Histogram {
    fn encode<W: std::fmt::Write>(
        &self,
        f: &mut W,
        name: &str,
        _description: &str,
        _help: bool,
    ) -> Result<(), std::fmt::Error> {
        let count = self.get_sample_count();
        if count == 0 {
            return Ok(());
        }
        for observation in &self.counters.observations {
            f.write_str(name)?;
            f.write_str("_bucket{")?;
            for (name, value) in &self.labels {
                if value.is_empty() {
                    continue;
                }
                f.write_str(name)?;
                f.write_str("=\"")?;
                f.write_str(value)?;
                f.write_str("\",")?;
            }
            f.write_str("le=")?;
            f.write_fmt(format_args!("{}", observation.le))?;
            f.write_str("} ")?;
            f.write_fmt(format_args!(
                "{}",
                observation.value.load(Ordering::Relaxed)
            ))?;
            f.write_str("\n")?;
        }
        f.write_str(name)?;
        f.write_str("_sum{")?;
        let mut i = 0;
        for (name, value) in &self.labels {
            i += 1;
            if value.is_empty() {
                continue;
            }
            f.write_str(name)?;
            f.write_str("=\"")?;
            f.write_str(value)?;
            f.write_str("\"")?;
            if i != self.labels.len() {
                f.write_str(",")?;
            }
        }
        f.write_str("} ")?;
        f.write_fmt(format_args!("{}", self.get_sample_sum()))?;
        f.write_str("\n")?;
        f.write_str(name)?;
        f.write_str("_count{")?;
        let mut i = 0;
        for (name, value) in &self.labels {
            i += 1;
            if value.is_empty() {
                continue;
            }
            f.write_str(name)?;
            f.write_str("=\"")?;
            f.write_str(value)?;
            f.write_str("\"")?;
            if i != self.labels.len() {
                f.write_str(",")?;
            }
        }
        f.write_str("} ")?;
        f.write_fmt(format_args!("{}", count))?;
        f.write_str("\n")?;
        Ok(())
    }
}

impl Serialize for HistogramVec {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_seq(Some(self.metrics.len()))?;
        for metric in &self.metrics {
            state.serialize_element(metric)?;
        }
        state.end()
    }
}

impl Serialize for Histogram {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Histogram", 4)?;
        state.serialize_field("labels", &self.labels)?;
        state.serialize_field("count", &self.get_sample_count())?;
        state.serialize_field("sum", &self.get_sample_sum())?;
        state.serialize_field("buckets", &self.counters)?;
        state.end()
    }
}

impl Serialize for HistogramBucket {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_seq(Some(self.observations.len()))?;
        for observation in &self.observations {
            state.serialize_element(observation)?;
        }
        state.end()
    }
}

impl Serialize for Observation {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Observation", 2)?;
        state.serialize_field("v", &self.value.load(Ordering::Relaxed))?;
        state.serialize_field("le", &self.le)?;
        state.end()
    }
}
#[cfg(test)]
mod tst {
    use crate::components::metrics::{label_combinations, histogram::HistogramVec, prometheus::Encoder};
    #[test]
    fn should_create_complex_static_metric() {
        let name_values = vec!["a", "b", "c"];
        let v1_values = vec!["d", "e", "f"];
        let v2_values = vec!["g", "h", "i"];

        let labels = vec![
            ("name", &name_values[..]),
            ("v1", &v1_values[..]),
            ("v2", &v2_values[..]),
        ];
        let labels = label_combinations(&labels[..]);
        let metric = HistogramVec::new(labels);
        let hist = metric
            .with_labels(&[("name", "a"), ("v1", "d"), ("v2", "g")])
            .unwrap();
        hist.observe(0.001);
        assert_eq!(1, hist.get_sample_count());
        assert_eq!(0.001, hist.get_sample_sum());

        assert_eq!(Some(1), hist.counters.get_count(0.001));
    }

    #[test]
    fn gauge_should_be_encoded_in_prometheus() {
        let name_values = vec!["a", "b", "c"];
        let v1_values = vec!["d", "e", "f"];
        let v2_values = vec!["g", "h", "i"];

        let labels = vec![
            ("name", &name_values[..]),
            ("v1", &v1_values[..]),
            ("v2", &v2_values[..]),
        ];
        let labels = label_combinations(&labels[..]);
        let metric = HistogramVec::new(labels);
        let hist = metric
            .with_labels(&[("name", "a"), ("v1", "d"), ("v2", "g")])
            .unwrap();
        hist.observe(0.001);
        let mut st = String::with_capacity(1_000_000);
        metric
            .encode(&mut st, "simple_gauge", "Simple Gauge metric", true)
            .unwrap();
        assert_eq!(
            r#"# HELP simple_gauge Simple Gauge metric
# TYPE simple_gauge histogram 
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.001} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.005} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.01} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.05} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.1} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=0.5} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=1} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=2} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=5} 1
simple_gauge_bucket{name="a",v1="d",v2="g",le=10} 1
simple_gauge_sum{name="a",v1="d",v2="g"} 0.001
simple_gauge_count{name="a",v1="d",v2="g"} 1
"#,
            st
        );
    }

    #[test]
    fn gauge_should_be_encoded_in_prometheus_without_label_name() {
        let name_values = vec!["", "b", "c"];
        let v1_values = vec!["d", "e", "f"];
        let v2_values = vec!["g", "h", "i"];

        let labels = vec![
            ("name", &name_values[..]),
            ("v1", &v1_values[..]),
            ("v2", &v2_values[..]),
        ];
        let labels = label_combinations(&labels[..]);
        let metric = HistogramVec::new(labels);
        let hist = metric
            .with_labels(&[("name", ""), ("v1", "d"), ("v2", "g")])
            .unwrap();
        hist.observe(0.001);
        let mut st = String::with_capacity(1_000_000);
        metric
            .encode(&mut st, "simple_gauge", "Simple Gauge metric", true)
            .unwrap();
        assert_eq!(
            r#"# HELP simple_gauge Simple Gauge metric
# TYPE simple_gauge histogram 
simple_gauge_bucket{v1="d",v2="g",le=0.001} 1
simple_gauge_bucket{v1="d",v2="g",le=0.005} 1
simple_gauge_bucket{v1="d",v2="g",le=0.01} 1
simple_gauge_bucket{v1="d",v2="g",le=0.05} 1
simple_gauge_bucket{v1="d",v2="g",le=0.1} 1
simple_gauge_bucket{v1="d",v2="g",le=0.5} 1
simple_gauge_bucket{v1="d",v2="g",le=1} 1
simple_gauge_bucket{v1="d",v2="g",le=2} 1
simple_gauge_bucket{v1="d",v2="g",le=5} 1
simple_gauge_bucket{v1="d",v2="g",le=10} 1
simple_gauge_sum{v1="d",v2="g"} 0.001
simple_gauge_count{v1="d",v2="g"} 1
"#,
            st
        );
    }
}