ih_muse_core/buffer/
metric_buffer.rs

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
// crates/ih-muse-core/src/buffer/metric_buffer.rs

use std::collections::HashMap;

use tokio::sync::Mutex;

use ih_muse_proto::{LocalElementId, MetricValue};

pub struct MetricBuffer {
    buffer: Mutex<HashMap<LocalElementId, HashMap<String, MetricValue>>>,
}

impl Default for MetricBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl MetricBuffer {
    pub fn new() -> Self {
        Self {
            buffer: Mutex::new(HashMap::new()),
        }
    }

    /// Adds a metric to the buffer.
    pub async fn add_metric(
        &self,
        local_elem_id: LocalElementId,
        metric_code: String,
        value: MetricValue,
    ) {
        let mut buffer = self.buffer.lock().await;
        buffer
            .entry(local_elem_id)
            .or_insert_with(HashMap::new)
            .insert(metric_code, value);
    }

    /// Retrieves and clears all buffered metrics.
    pub async fn get_and_clear(&self) -> HashMap<LocalElementId, HashMap<String, MetricValue>> {
        let mut buffer = self.buffer.lock().await;
        let data = buffer.clone();
        buffer.clear();
        data
    }
}