init4_bin_base/utils/
metrics.rs

1use crate::utils::from_env::{FromEnv, FromEnvErr, FromEnvVar};
2use metrics_exporter_prometheus::PrometheusBuilder;
3
4/// Metrics port env var
5const METRICS_PORT: &str = "METRICS_PORT";
6
7/// Prometheus metrics configuration struct.
8///
9/// Uses the following environment variables:
10/// - `METRICS_PORT` - optional. Defaults to 9000 if missing or unparseable.
11///   The port to bind the metrics server to.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct MetricsConfig {
15    /// `METRICS_PORT` - The port on which to bind the metrics server. Defaults
16    /// to `9000` if missing or unparseable.
17    pub port: u16,
18}
19
20impl Default for MetricsConfig {
21    fn default() -> Self {
22        Self { port: 9000 }
23    }
24}
25
26impl From<Option<u16>> for MetricsConfig {
27    fn from(port: Option<u16>) -> Self {
28        Self {
29            port: port.unwrap_or(9000),
30        }
31    }
32}
33
34impl From<u16> for MetricsConfig {
35    fn from(port: u16) -> Self {
36        Self { port }
37    }
38}
39
40impl FromEnv for MetricsConfig {
41    type Error = std::num::ParseIntError;
42
43    fn from_env() -> Result<Self, FromEnvErr<Self::Error>> {
44        match u16::from_env_var(METRICS_PORT).map(Self::from) {
45            Ok(cfg) => Ok(cfg),
46            Err(_) => Ok(Self::default()),
47        }
48    }
49}
50
51/// Initialize a [`metrics_exporter_prometheus`] exporter.
52///
53/// Reads the `METRICS_PORT` environment variable to determine the port to bind
54/// the exporter to. If the variable is missing or unparseable, it defaults to
55/// 9000.
56///
57/// See [`MetricsConfig`] for more information.
58///
59/// # Panics
60///
61/// This function will panic if the exporter fails to install, e.g. if the port
62/// is in use.
63pub fn init_metrics() {
64    let cfg = MetricsConfig::from_env().unwrap();
65
66    PrometheusBuilder::new()
67        .with_http_listener(([0, 0, 0, 0], cfg.port))
68        .install()
69        .expect("failed to install prometheus exporter");
70}