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
//! Data model
//!
use chrono::Utc;
use metrics::{Key, Label};
use metrics_util::{Handle, MetricKind};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

static LAMBDA_HOSTNAME: &str = "lambda";

/// Metric type
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub enum DataDogMetricType {
    /// Counter
    #[serde(rename = "count")]
    Count,
    /// Gauge
    #[serde(rename = "gauge")]
    Gauge,
    /// Histogram
    #[serde(rename = "histogram")]
    Histogram,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialOrd, PartialEq)]
#[serde(untagged)]
/// Metric value
pub enum DataDogMetricValue {
    /// Float
    Float(f64),
    /// Int
    Int(u64),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialOrd, PartialEq)]
/// DataDog formatted metric
pub struct DataDogMetric {
    /// Metric name
    pub metric_name: String,
    /// Metric type
    pub metric_type: DataDogMetricType,
    /// Metric values
    pub points: Vec<DataDogMetricValue>,
    /// Timestamp
    pub timestamp: i64,
    /// Tags
    pub tags: Vec<String>,
}

impl DataDogMetric {
    pub(crate) fn from_metric(
        kind: &MetricKind,
        key: &Key,
        handle: &Handle,
        global_tags: &[Label],
    ) -> Self {
        match kind {
            MetricKind::Counter => DataDogMetric::from_metric_value(
                DataDogMetricType::Count,
                key,
                vec![DataDogMetricValue::Int(handle.read_counter())],
                global_tags,
            ),
            MetricKind::Gauge => DataDogMetric::from_metric_value(
                DataDogMetricType::Gauge,
                key,
                vec![DataDogMetricValue::Float(handle.read_gauge())],
                global_tags,
            ),
            MetricKind::Histogram => {
                let mut values = vec![];
                handle.read_histogram_with_clear(|v| values.extend_from_slice(v));
                DataDogMetric::from_metric_value(
                    DataDogMetricType::Histogram,
                    key,
                    values.into_iter().map(DataDogMetricValue::Float).collect(),
                    global_tags,
                )
            }
        }
    }

    fn from_metric_value(
        metric_type: DataDogMetricType,
        key: &Key,
        values: Vec<DataDogMetricValue>,
        global_tags: &[Label],
    ) -> Self {
        DataDogMetric {
            metric_name: key.name().to_string(),
            metric_type,
            points: values,
            timestamp: Utc::now().timestamp(),
            tags: global_tags
                .iter()
                .chain(key.labels())
                .map(|l| format!("{}:{}", l.key(), l.value()))
                .collect(),
        }
    }

    pub(crate) fn to_metric_lines(&self) -> Vec<DataDogMetricLine> {
        self.points
            .iter()
            .map(|v| DataDogMetricLine {
                metric_name: self.metric_name.to_string(),
                value: v.clone(),
                timestamp: self.timestamp,
                tags: self.tags.clone(),
            })
            .collect()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DataDogMetricLine {
    #[serde(rename = "m")]
    pub metric_name: String,
    #[serde(rename = "v")]
    pub value: DataDogMetricValue,
    #[serde(rename = "e")]
    pub timestamp: i64,
    #[serde(rename = "t")]
    pub tags: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DataDogApiPost {
    pub series: Vec<DataDogSeries>,
}

#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DataDogSeries {
    pub host: String,
    pub interval: Option<i64>,
    pub metric: String,
    pub points: Vec<(i64, DataDogMetricValue)>,
    pub tags: Vec<String>,
    #[serde(rename = "type")]
    pub metric_type: DataDogMetricType,
}

impl From<&DataDogMetric> for DataDogSeries {
    fn from(m: &DataDogMetric) -> Self {
        DataDogSeries {
            host: LAMBDA_HOSTNAME.to_string(),
            interval: None,
            metric: m.metric_name.clone(),
            points: m.points.iter().map(|v| (m.timestamp, v.clone())).collect(),
            tags: m.tags.clone(),
            metric_type: m.metric_type.clone(),
        }
    }
}