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
use crate::attributes::{Attributes, MetricId, OnFlush, Prefixed, WithAttributes};
use crate::input::{Input, InputKind, InputMetric, InputScope};
use crate::name::MetricName;
use crate::{Flush, MetricValue};

use std::collections::BTreeMap;

use std::io;
use std::sync::{Arc, RwLock};

/// A BTreeMap wrapper to receive metrics or stats values.
/// Every received value for a metric replaces the previous one (if any).
#[derive(Clone, Default)]
pub struct StatsMap {
    attributes: Attributes,
}

impl WithAttributes for StatsMap {
    fn get_attributes(&self) -> &Attributes {
        &self.attributes
    }
    fn mut_attributes(&mut self) -> &mut Attributes {
        &mut self.attributes
    }
}

impl Input for StatsMap {
    type SCOPE = StatsMapScope;

    fn metrics(&self) -> Self::SCOPE {
        StatsMapScope {
            attributes: self.attributes.clone(),
            inner: Arc::new(RwLock::new(BTreeMap::new())),
        }
    }
}

/// A BTreeMap wrapper to receive metrics or stats values.
/// Every received value for a metric replaces the previous one (if any).
#[derive(Clone, Default)]
pub struct StatsMapScope {
    attributes: Attributes,
    inner: Arc<RwLock<BTreeMap<String, MetricValue>>>,
}

impl WithAttributes for StatsMapScope {
    fn get_attributes(&self) -> &Attributes {
        &self.attributes
    }
    fn mut_attributes(&mut self) -> &mut Attributes {
        &mut self.attributes
    }
}

impl InputScope for StatsMapScope {
    fn new_metric(&self, name: MetricName, _kind: InputKind) -> InputMetric {
        let name = self.prefix_append(name);
        let write_to = self.inner.clone();
        let key: String = name.join(".");
        InputMetric::new(MetricId::forge("map", name), move |value, _labels| {
            let _previous = write_to.write().expect("Lock").insert(key.clone(), value);
        })
    }
}

impl Flush for StatsMapScope {
    fn flush(&self) -> io::Result<()> {
        self.notify_flush_listeners();
        Ok(())
    }
}

impl From<StatsMapScope> for BTreeMap<String, MetricValue> {
    fn from(map: StatsMapScope) -> Self {
        // FIXME this is is possibly a full map copy, for no reason.
        // into_inner() is what we'd really want here but would require some `unsafe`? don't know how to do this yet.
        map.inner.read().unwrap().clone()
    }
}

impl StatsMapScope {
    /// Extract the backing BTreeMap.
    pub fn into_map(self) -> BTreeMap<String, MetricValue> {
        self.into()
    }
}