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
use chrono::prelude::*;
use crossbeam_channel::*;
use holochain_locksmith::RwLock;
/// Metric suppport for holochain. Provides metric representations to
/// sample, publish, aggregate, and analyze metric data.
use std::sync::Arc;

/// Represents a single sample of a numerical metric determined by `name`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Metric {
    pub name: String,
    pub stream_id: Option<String>,
    pub timestamp: Option<DateTime<Utc>>,
    pub value: f64,
}

impl Metric {
    pub fn new<S: Into<String>, S2: Into<Option<String>>>(
        name: S,
        stream_id: S2,
        timestamp: Option<DateTime<Utc>>,
        value: f64,
    ) -> Self {
        Self {
            name: name.into(),
            stream_id: stream_id.into(),
            timestamp,
            value,
        }
    }

    pub fn new_timestamped_now<S: Into<String>, S2: Into<Option<String>>>(
        name: S,
        stream_id: S2,
        value: f64,
    ) -> Self {
        Self {
            name: name.into(),
            stream_id: stream_id.into(),
            timestamp: Some(Utc::now()),
            value,
        }
    }
}

/// Give a csv reader produce an iterator over metric.
/// Panics if any records are invalid from the csv source.
#[macro_export]
macro_rules! metrics_from_reader {
    ($read: expr) => {{
        $read.deserialize().map(|record| {
            let metric: Metric = record.unwrap();
            metric
        })
    }};
}

/// An object capable of publishing metric data.
pub trait MetricPublisher: Sync + Send {
    /// Publish a single metric.
    fn publish(&mut self, metric: &Metric);
}

/// WIP: Wraps another publisher and dedicates a processing thread to do actual publishing.
pub struct ChannelPublisher {
    sender: Sender<Metric>,
}

impl ChannelPublisher {
    pub fn new(mut metric_publisher: Box<dyn MetricPublisher>) -> Self {
        let (sender, receiver) = unbounded();
        let _join_handle: std::thread::JoinHandle<()> = std::thread::spawn(move || loop {
            match receiver.try_recv() {
                Ok(metric) => metric_publisher.publish(&metric),
                Err(TryRecvError::Disconnected) => break,
                Err(_) => (),
            }
        });

        Self { sender }
    }
}

impl MetricPublisher for ChannelPublisher {
    fn publish(&mut self, metric: &Metric) {
        self.sender.send(metric.clone()).unwrap();
    }
}

/// The default metric publisher trait implementation
pub type DefaultMetricPublisher = crate::logger::LoggerMetricPublisher;

/// Wraps a standard rust function with latency timing that is published to
/// $publisher upon completion of $f($args,*). The latency metric name will
/// be "$metric_prefix.latency".
#[macro_export]
macro_rules! with_latency_publishing {
    ($metric_prefix:expr, $publisher:expr, $f:expr) => {{
        let clock = std::time::SystemTime::now();

        let ret = $f();
        let latency = clock.elapsed().unwrap().as_millis();

        if latency == 0 {
            ret
        } else {
            let metric_name = format!("{}.latency", $metric_prefix);

            // TODO pass in stream id or not?
            let metric = $crate::Metric::new(metric_name.as_str(), None,
            Some(clock.into()), latency as f64);
            $publisher.write().unwrap().publish(&metric);
            ret
        }
    }};
    ($metric_prefix:expr, $publisher:expr, $f:expr, $($args:expr),+ ) => {{
        let clock = std::time::SystemTime::now();

        let ret = ($f)($($args),+);
        let latency = clock.elapsed().unwrap().as_millis();

        if latency == 0 {
            ret
        } else {
            let metric_name = format!("{}.latency", $metric_prefix);

            // TODO pass in stream id or not?
            let metric = $crate::Metric::new(metric_name.as_str(), None,
            Some(clock.into()), latency as f64);
            $publisher.write().unwrap().publish(&metric);
            ret
        }
    }}
}

/// Composes a collection of publishers which are all called for one metric sample.
pub struct MetricPublishers(Vec<Arc<RwLock<dyn MetricPublisher>>>);

impl MetricPublisher for MetricPublishers {
    fn publish(&mut self, metric: &Metric) {
        for publisher in &self.0 {
            publisher.write().unwrap().publish(&metric);
        }
    }
}

impl MetricPublishers {
    pub fn new(publishers: Vec<Arc<RwLock<dyn MetricPublisher>>>) -> Self {
        MetricPublishers(publishers)
    }

    /// No-op metric publisher since the publisher list is empty
    pub fn empty() -> Self {
        Self::new(vec![])
    }
}

impl Default for MetricPublishers {
    fn default() -> Self {
        let publishers = vec![
            crate::config::MetricPublisherConfig::default_logger().create_metric_publisher(),
            crate::config::MetricPublisherConfig::default_cloudwatch_logs()
                .create_metric_publisher(),
        ];
        Self(publishers)
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use std::sync::{Arc, RwLock};
    #[test]
    fn can_publish_to_logger() {
        let mut publisher = crate::logger::LoggerMetricPublisher;
        let timestamp = Utc.timestamp(1_500_000_000, 0);
        let metric = Metric::new("latency", None, Some(timestamp), 100.0);

        publisher.publish(&metric);
    }

    fn test_latency_fn(x: bool) -> bool {
        x
    }

    #[test]
    fn can_publish_latencies() {
        let publisher = Arc::new(RwLock::new(crate::logger::LoggerMetricPublisher));

        let ret = with_latency_publishing!("test", publisher, test_latency_fn, true);

        assert!(ret)
    }
}