Skip to main content

tiny_proxy/metrics/
server.rs

1//! Prometheus HTTP server setup.
2
3use std::net::SocketAddr;
4
5#[cfg(feature = "metrics")]
6use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
7
8/// Latency histogram buckets (seconds). Chosen for proxy workloads:
9/// sub-millisecond fast paths up to slow upstream timeouts.
10#[cfg(feature = "metrics")]
11const LATENCY_BUCKETS: &[f64] = &[
12    0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
13];
14
15/// Start the Prometheus metrics HTTP server on the given address.
16///
17/// Installs a global metrics recorder, registers metric descriptions (`# HELP`),
18/// configures latency histogram buckets, and spawns an HTTP listener
19/// that serves `/metrics` in Prometheus text format.
20#[cfg(feature = "metrics")]
21pub fn start_metrics_server(addr: SocketAddr) -> anyhow::Result<()> {
22    use metrics::{describe_counter, describe_gauge, describe_histogram};
23
24    PrometheusBuilder::new()
25        .set_buckets_for_metric(
26            Matcher::Full("http_request_duration_seconds".to_string()),
27            LATENCY_BUCKETS,
28        )?
29        .with_http_listener(addr)
30        .install()?;
31
32    describe_counter!(
33        "http_requests_total",
34        "Total number of HTTP requests processed"
35    );
36    describe_histogram!(
37        "http_request_duration_seconds",
38        "HTTP request processing duration in seconds"
39    );
40    describe_gauge!(
41        "http_active_requests",
42        "Number of HTTP requests currently in flight"
43    );
44    describe_counter!(
45        "tls_handshakes_total",
46        "Total number of TLS handshakes (labelled by outcome)"
47    );
48
49    tracing::info!("Metrics server listening on http://{}/metrics", addr);
50    Ok(())
51}
52
53/// No-op when `metrics` feature is disabled.
54#[cfg(not(feature = "metrics"))]
55pub fn start_metrics_server(_addr: SocketAddr) -> anyhow::Result<()> {
56    Ok(())
57}