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
use serde::{Serialize, Deserialize};
use std::fmt::Debug;

// A container type for status information for a given component
pub trait Metrics<'de>: Serialize + Deserialize<'de> + Debug + Clone {
    fn data(&self) -> Vec<(String, Metric)>;
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Metric {
    Gauge(i64),
    Counter(u64)
}

/// Generate a struct: `$struct_name` from a set of metrics
///
/// Generate the impl containing the constructor, `$struct_name::new()`
/// Generate `impl Metrics for $struct_name` constructing the Metric
/// variants returned from `$struct_name::data` based on the type of the struct fields.
macro_rules! metrics {
    ($struct_name:ident {
        $( $field:ident: $ty:ident ),+
    }) => {
        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct $struct_name {
            $( pub $field: $ty ),+
        }

        impl $struct_name {
            pub fn new() -> $struct_name {
                $struct_name {
                    $( $field: 0 ),+
                }
            }
        }

        impl<'de> Metrics<'de> for $struct_name {
            fn data(&self) -> Vec<(String, Metric)> {
                vec![
                    $( (stringify!($field).into(), type_to_metric!($ty)(self.$field)) ),+
                    ]
            }
        }
    }
}

macro_rules! type_to_metric {
    (i64) => { Metric::Gauge };
    (u64) => { Metric::Counter };
}