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
use std::time::Instant;

use prometheus::{HistogramVec, IntCounterVec, IntGaugeVec};

#[derive(Clone)]
pub struct CacheData {
    cache_read_bytes:  IntCounterVec,
    cache_read_speed:  HistogramVec,
    cache_write_bytes: IntCounterVec,
    cache_write_speed: HistogramVec,
}

impl Default for CacheData {
    fn default() -> Self {
        Self::new()
    }
}
impl CacheData {
    pub fn new() -> Self {
        let buckets = prometheus::exponential_buckets(1.0, 2.0, 15).unwrap();

        let read_speed = prometheus::register_histogram_vec!(
            "libmdbx_cache_read_speed_ns",
            "libmdbx cache speed read",
            &["table"],
            buckets.clone()
        )
        .unwrap();

        let write_speed = prometheus::register_histogram_vec!(
            "libmdbx_cache_write_speed_ns",
            "libmdbx cache speed write",
            &["table"],
            buckets.clone()
        )
        .unwrap();

        let read_count = prometheus::register_int_counter_vec!(
            "libmdbx_cache_read_bytes",
            "cache read bytes",
            &["table"]
        )
        .unwrap();

        let write_bytes = prometheus::register_int_counter_vec!(
            "libmdbx_cache_write_bytes",
            "cache write bytes",
            &["table"]
        )
        .unwrap();

        Self {
            cache_write_speed: write_speed,
            cache_read_speed:  read_speed,
            cache_read_bytes:  read_count,
            cache_write_bytes: write_bytes,
        }
    }

    pub fn cache_read<R, S>(self, table: &str, f: impl FnOnce() -> R) -> R {
        self.cache_read_bytes
            .with_label_values(&[table])
            .inc_by(std::mem::size_of::<S>() as u64);

        let now = Instant::now();
        let res = f();
        let elasped = now.elapsed().as_nanos();

        self.cache_read_speed
            .with_label_values(&[table])
            .observe(elasped as f64);

        res
    }

    pub fn cache_write<R, S>(self, table: &str, f: impl FnOnce() -> R) -> R {
        self.cache_write_bytes
            .with_label_values(&[table])
            .inc_by(std::mem::size_of::<R>() as u64);

        let now = Instant::now();
        let res = f();
        let elasped = now.elapsed().as_nanos();

        self.cache_write_speed
            .with_label_values(&[table])
            .observe(elasped as f64);

        res
    }
}