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
use std::collections::HashMap;

use async_trait::async_trait;
use reqwest::Url;

#[async_trait]
pub trait MetricsHelper {
    async fn metric(&self, metric_name: &str) -> Result<f64, anyhow::Error>;
    async fn metric_with_url(
        metric: impl AsRef<str> + Send,
        endpoint: impl Into<Url> + Send,
    ) -> Result<f64, anyhow::Error>;
}

pub struct Metrics {
    endpoint: Url,
}

impl Metrics {
    fn new(endpoint: impl Into<Url>) -> Self {
        Self {
            endpoint: endpoint.into(),
        }
    }

    async fn fetch_metrics(
        endpoint: impl AsRef<str>,
    ) -> Result<HashMap<String, f64>, anyhow::Error> {
        let response = reqwest::get(endpoint.as_ref()).await?;
        Ok(prom_metrics_parser::parse(&response.text().await?)?)
    }

    fn get_metric(
        metrics_map: HashMap<String, f64>,
        metric_name: &str,
    ) -> Result<f64, anyhow::Error> {
        let treat_not_found_as_zero = true;
        if let Some(val) = metrics_map.get(metric_name) {
            Ok(*val)
        } else if treat_not_found_as_zero {
            Ok(0_f64)
        } else {
            Err(anyhow::anyhow!("MetricNotFound: {metric_name}"))
        }
    }
}

#[async_trait]
impl MetricsHelper for Metrics {
    async fn metric(&self, metric_name: &str) -> Result<f64, anyhow::Error> {
        let metrics_map = Metrics::fetch_metrics(self.endpoint.as_str()).await?;
        Metrics::get_metric(metrics_map, metric_name)
    }

    async fn metric_with_url(
        metric_name: impl AsRef<str> + Send,
        endpoint: impl Into<Url> + Send,
    ) -> Result<f64, anyhow::Error> {
        let metrics_map = Metrics::fetch_metrics(endpoint.into()).await?;
        Metrics::get_metric(metrics_map, metric_name.as_ref())
    }
}