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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//! Metric.
use std;
use std::fmt;

pub use aggregated_metrics::{
    AggregatedCounter, AggregatedGauge, AggregatedHistogram, AggregatedSummary,
};

use label::Labels;
use metrics::{Counter, Gauge, Histogram, Summary};
use {ErrorKind, Result};

/// Metric.
///
/// # References
///
/// - [Metric types](https://prometheus.io/docs/concepts/metric_types/)
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum Metric {
    Counter(Counter),
    Gauge(Gauge),
    Summary(Summary),
    Histogram(Histogram),
}
impl Metric {
    /// Returns the name of this metric.
    pub fn name(&self) -> &MetricName {
        match *self {
            Metric::Counter(ref m) => m.metric_name(),
            Metric::Gauge(ref m) => m.metric_name(),
            Metric::Summary(ref m) => m.metric_name(),
            Metric::Histogram(ref m) => m.metric_name(),
        }
    }

    /// Returns the kind of this metric.
    pub fn kind(&self) -> MetricKind {
        match *self {
            Metric::Counter(_) => MetricKind::Counter,
            Metric::Gauge(_) => MetricKind::Gauge,
            Metric::Summary(_) => MetricKind::Summary,
            Metric::Histogram(_) => MetricKind::Histogram,
        }
    }

    /// Returns the labels of this metric.
    pub fn labels(&self) -> &Labels {
        match *self {
            Metric::Counter(ref m) => m.labels(),
            Metric::Gauge(ref m) => m.labels(),
            Metric::Summary(ref m) => m.labels(),
            Metric::Histogram(ref m) => m.labels(),
        }
    }
}
impl From<Counter> for Metric {
    fn from(f: Counter) -> Self {
        Metric::Counter(f)
    }
}
impl From<Gauge> for Metric {
    fn from(f: Gauge) -> Self {
        Metric::Gauge(f)
    }
}
impl From<Histogram> for Metric {
    fn from(f: Histogram) -> Self {
        Metric::Histogram(f)
    }
}
impl From<Summary> for Metric {
    fn from(f: Summary) -> Self {
        Metric::Summary(f)
    }
}

/// Metric name.
///
/// A metric name is a sequence of characters that match the regex `[a-zA-Z_:][a-zA-Z0-9_:]*`.
/// It consists of three parts: `{namespace}_{subsystem}_{name}` of which only the `name` is mandatory.
///
/// # References
///
/// - [Metric name and labels](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels)
/// - [Metric names](https://prometheus.io/docs/instrumenting/writing_clientlibs/#metric-names)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MetricName {
    namespace: Option<String>,
    subsystem: Option<String>,
    name: String,
}
impl MetricName {
    /// Returns the namespace part of this.
    pub fn namespace(&self) -> Option<&str> {
        self.namespace.as_ref().map(|s| s.as_ref())
    }

    /// Returns the subsystem part of this.
    pub fn subsystem(&self) -> Option<&str> {
        self.subsystem.as_ref().map(|s| s.as_ref())
    }

    /// Returns the name part of this.
    pub fn name(&self) -> &str {
        &self.name
    }

    pub(crate) fn new(
        namespace: Option<&str>,
        subsystem: Option<&str>,
        name: &str,
    ) -> Result<Self> {
        if let Some(s) = namespace {
            track!(Self::validate_name(s), "{:?}", s)?;
        }
        if let Some(s) = subsystem {
            track!(Self::validate_name(s), "{:?}", s)?;
        }
        track!(Self::validate_name(name), "{:?}", name)?;

        Ok(MetricName {
            namespace: namespace.map(|s| s.to_owned()),
            subsystem: subsystem.map(|s| s.to_owned()),
            name: name.to_string(),
        })
    }
    fn validate_name(name: &str) -> Result<()> {
        // REGEX: [a-zA-Z_:][a-zA-Z0-9_:]*
        track_assert!(!name.is_empty(), ErrorKind::InvalidInput);
        match name.as_bytes()[0] as char {
            'a'..='z' | 'A'..='Z' | '_' | ':' => {}
            _ => track_panic!(ErrorKind::InvalidInput),
        }
        for c in name.chars().skip(1) {
            match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | ':' => {}
                _ => track_panic!(ErrorKind::InvalidInput),
            }
        }
        Ok(())
    }
}
impl fmt::Display for MetricName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref s) = self.namespace {
            write!(f, "{}_", s)?;
        }
        if let Some(ref s) = self.subsystem {
            write!(f, "{}_", s)?;
        }
        write!(f, "{}", self.name)?;
        Ok(())
    }
}

/// Metric kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum MetricKind {
    Counter,
    Gauge,
    Summary,
    Histogram,
}
impl fmt::Display for MetricKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MetricKind::Counter => write!(f, "counter"),
            MetricKind::Gauge => write!(f, "gauge"),
            MetricKind::Summary => write!(f, "summary"),
            MetricKind::Histogram => write!(f, "histogram"),
        }
    }
}

pub(crate) struct MetricValue(pub f64);
impl fmt::Display for MetricValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.0.is_finite() {
            write!(f, "{}", self.0)
        } else if self.0.is_nan() {
            write!(f, "Nan")
        } else if self.0.is_sign_positive() {
            write!(f, "+Inf")
        } else {
            write!(f, "-Inf")
        }
    }
}

/// Metric families.
#[derive(Debug, Clone)]
pub struct MetricFamilies(pub(crate) Vec<MetricFamily>);
impl MetricFamilies {
    /// Consumes the `MetricFamilies` and returns the underlying vector.
    pub fn into_vec(self) -> Vec<MetricFamily> {
        self.0
    }

    /// Converts to the text format.
    pub fn to_text(&self) -> String {
        use std::fmt::Write;

        let mut buf = String::new();
        for m in &self.0 {
            write!(buf, "{}", m).expect("Never fails");
        }
        buf
    }
}
impl AsRef<[MetricFamily]> for MetricFamilies {
    fn as_ref(&self) -> &[MetricFamily] {
        &self.0
    }
}
impl IntoIterator for MetricFamilies {
    type Item = MetricFamily;
    type IntoIter = std::vec::IntoIter<Self::Item>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Metric family.
///
/// # References
///
/// - [metrics.proto](https://github.com/prometheus/client_model/blob/086fe7ca28bde6cec2acd5223423c1475a362858/metrics.proto#L76-%20%20L81)
#[derive(Debug, Clone)]
pub struct MetricFamily {
    name: MetricName,
    help: Option<String>,
    metrics: Metrics,
}
impl MetricFamily {
    /// Returns the name of this metric family.
    pub fn name(&self) -> &MetricName {
        &self.name
    }

    /// Returns the help of this metric family.
    pub fn help(&self) -> Option<&str> {
        self.help.as_ref().map(|h| h.as_ref())
    }

    /// Returns the kind of this metric family.
    pub fn kind(&self) -> MetricKind {
        match self.metrics {
            Metrics::Counter(_) => MetricKind::Counter,
            Metrics::Gauge(_) => MetricKind::Gauge,
            Metrics::Summary(_) => MetricKind::Summary,
            Metrics::Histogram(_) => MetricKind::Histogram,
        }
    }

    /// Returns the metrics that belongs to this family.
    pub fn metrics(&self) -> &Metrics {
        &self.metrics
    }

    pub(crate) fn new(metric: Metric) -> Self {
        match metric {
            Metric::Counter(m) => MetricFamily {
                name: m.metric_name().clone(),
                help: m.help().map(|h| h.to_string()),
                metrics: Metrics::Counter(vec![AggregatedCounter::new(m)]),
            },
            Metric::Gauge(m) => MetricFamily {
                name: m.metric_name().clone(),
                help: m.help().map(|h| h.to_string()),
                metrics: Metrics::Gauge(vec![AggregatedGauge::new(m)]),
            },
            Metric::Summary(m) => MetricFamily {
                name: m.metric_name().clone(),
                help: m.help().map(|h| h.to_string()),
                metrics: Metrics::Summary(vec![AggregatedSummary::new(m)]),
            },
            Metric::Histogram(m) => MetricFamily {
                name: m.metric_name().clone(),
                help: m.help().map(|h| h.to_string()),
                metrics: Metrics::Histogram(vec![AggregatedHistogram::new(m)]),
            },
        }
    }
    pub(crate) fn same_family(&self, metric: &Metric) -> bool {
        (self.name(), self.kind()) == (metric.name(), metric.kind())
    }
    pub(crate) fn push(&mut self, metric: Metric) {
        match metric {
            Metric::Counter(m) => {
                if let Metrics::Counter(ref mut v) = self.metrics {
                    let m = AggregatedCounter::new(m);
                    if v.last_mut().map_or(true, |x| !x.try_merge(&m)) {
                        v.push(m);
                    }
                }
            }
            Metric::Gauge(m) => {
                if let Metrics::Gauge(ref mut v) = self.metrics {
                    let m = AggregatedGauge::new(m);
                    if v.last_mut().map_or(true, |x| !x.try_merge(&m)) {
                        v.push(m);
                    }
                }
            }
            Metric::Summary(m) => {
                if let Metrics::Summary(ref mut v) = self.metrics {
                    let m = AggregatedSummary::new(m);
                    if v.last_mut().map_or(true, |x| !x.try_merge(&m)) {
                        v.push(m);
                    }
                }
            }
            Metric::Histogram(m) => {
                if let Metrics::Histogram(ref mut v) = self.metrics {
                    let m = AggregatedHistogram::new(m);
                    if v.last_mut().map_or(true, |x| !x.try_merge(&m)) {
                        v.push(m);
                    }
                }
            }
        }
    }
}
impl fmt::Display for MetricFamily {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(help) = self.help() {
            // > HELP lines may contain any sequence of UTF-8 characters (after the metric name),
            // > but the backslash and the line-feed characters have to be escaped as \\ and \n, respectively
            write!(f, "# HELP {} ", self.name())?;
            for c in help.chars() {
                match c {
                    '\\' => write!(f, "\\\\")?,
                    '\n' => write!(f, "\\\\n")?,
                    _ => write!(f, "{}", c)?,
                }
            }
            writeln!(f, "")?;
        }
        writeln!(f, "# TYPE {} {}", self.name(), self.kind())?;
        write!(f, "{}", self.metrics)?;
        Ok(())
    }
}

/// Sequence of the same metric.
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum Metrics {
    Counter(Vec<AggregatedCounter>),
    Gauge(Vec<AggregatedGauge>),
    Summary(Vec<AggregatedSummary>),
    Histogram(Vec<AggregatedHistogram>),
}
impl fmt::Display for Metrics {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Metrics::Counter(ref v) => {
                for m in v.iter() {
                    writeln!(f, "{}", m)?;
                }
            }
            Metrics::Gauge(ref v) => {
                for m in v.iter() {
                    writeln!(f, "{}", m)?;
                }
            }
            Metrics::Summary(ref v) => {
                for m in v.iter() {
                    writeln!(f, "{}", m)?;
                }
            }
            Metrics::Histogram(ref v) => {
                for m in v.iter() {
                    writeln!(f, "{}", m)?;
                }
            }
        }
        Ok(())
    }
}