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
use log::trace;
use prometheus::HistogramOpts;
use prometheus::{HistogramVec, Registry};

#[derive(Debug, Clone)]
pub struct Metrics {
    http_timer: HistogramVec,
    include_path_labels: Vec<String>,
}

impl Metrics {
    pub fn new(cr: &Registry, include_path_labels: &Vec<String>) -> Self {
        let internal_http_timer_opts = HistogramOpts::new(
            "server_response_duration_seconds",
            "Route response time in seconds.",
        );
        let internal_http_timer =
            HistogramVec::new(internal_http_timer_opts, &["classifier", "status"]).unwrap();
        cr.register(Box::new(internal_http_timer.clone())).unwrap();

        Self {
            http_timer: internal_http_timer,
            include_path_labels: include_path_labels.clone(),
        }
    }

    fn sanitize_path_segments(&self, path: &str) -> String {
        let path_segments: Vec<&str> = path.split('/').collect();
        path_segments.iter().fold(String::new(), |acc, &path| {
            if self.include_path_labels.contains(&path.to_string()) {
                format!("{}/{}", acc, path)
            } else if path == "" {
                acc.to_string()
            } else {
                format!("{}/*", acc)
            }
        })
    }

    /// Get prometheus metrics per-route and how long each route takes.
    /// ```
    /// use prometheus::Registry;
    /// use warp::Filter;
    /// use warp_prometheus::Metrics;
    ///
    ///
    /// let registry: &Registry = prometheus::default_registry();
    /// let path_includes: Vec<String> = vec![String::from("hello")];
    ///
    /// let route_one = warp::path("hello")
    ///    .and(warp::path::param())
    ///    .and(warp::header("user-agent"))
    ///    .map(|param: String, agent: String| {
    ///        format!("Hello {}, whose agent is {}", param, agent)
    ///    });
    /// let metrics = Metrics::new(&registry, &path_includes);
    ///
    /// let test_routes = route_one.with(warp::log::custom(move |log| {
    ///            metrics.http_metrics(log)
    ///        }));
    ///
    /// ```
    pub fn http_metrics(&self, info: warp::log::Info) {
        trace!(
            "Metric Status: {} - Method: {} - Path: {}",
            &info.status().as_u16().to_string(),
            &info.method(),
            &info.path()
        );
        let sanitized_classifier = format!(
            "{} - {}",
            info.method(),
            self.sanitize_path_segments(info.path())
        );
        self.http_timer
            .with_label_values(&[&sanitized_classifier, info.status().as_str()])
            .observe(info.elapsed().as_secs_f64());

    }
}

#[cfg(test)]
mod test {

    use super::*;

    #[test]
    fn test_sanitize_path() {
        let registry: Registry = Registry::new();
        let path_includes: Vec<String> = vec![String::from("users"), String::from("registration")];

        let metrics = Metrics::new(&registry, &path_includes);
        let path = "/users/12345/registration/9797731279";
        let sanitized_path = metrics.sanitize_path_segments(path);

        assert_eq!("/users/*/registration/*".to_string(), sanitized_path)
    }

    #[test]
    fn test_sanitize_path_with_value_first() {
        let registry: Registry = Registry::new();
        let path_includes: Vec<String> = vec![String::from("users"), String::from("registration")];

        let metrics = Metrics::new(&registry, &path_includes);
        let path = "12344235/users/12345/12314151252/registration";
        let sanitized_path = metrics.sanitize_path_segments(path);

        assert_eq!("/*/users/*/*/registration".to_string(), sanitized_path)
    }

    #[test]
    fn test_sanitize_path_with_multiple_segments_in_order() {
        let registry: Registry = Registry::new();
        let path_includes: Vec<String> = vec![String::from("users"), String::from("registration")];

        let metrics = Metrics::new(&registry, &path_includes);
        let path = "/users/12345/12314151252/registration";
        let sanitized_path = metrics.sanitize_path_segments(path);

        assert_eq!("/users/*/*/registration".to_string(), sanitized_path)
    }

    #[test]
    fn test_totally_wrong_path() {

        let registry: Registry = Registry::new();
        let path_includes: Vec<String> = vec![String::from("users"), String::from("registration")];

        let metrics = Metrics::new(&registry, &path_includes);
        let path = "12344235/12141242/12345/12314151252/235235235";
        let sanitized_path = metrics.sanitize_path_segments(path);

        assert_eq!("/*/*/*/*/*".to_string(), sanitized_path)
    }
}