Skip to main content

a2a_protocol_server/otel/telemetry/
prometheus.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! `OTEL_METRICS_EXPORTER=prometheus`: the metrics, served at `/metrics` in
5//! the Prometheus text format for a Prometheus that scrapes this process,
6//! with no collector in between.
7//!
8//! `OTEL_METRICS_EXPORTER=prometheus` used to be refused, which left a
9//! Prometheus-scrape deployment without a collector no way to get these
10//! metrics out. The names and units are `opentelemetry-prometheus`'s — the
11//! translation the book's "What these become in Prometheus" table was
12//! measured through — so a dashboard built for the OTLP path reads the same
13//! series here.
14//!
15//! The listener is plain HTTP, unauthenticated, and bound where
16//! `OTEL_EXPORTER_PROMETHEUS_HOST` says: `localhost` by default (the
17//! specification's default), so a scraper on another machine needs
18//! `0.0.0.0` or an address, and then anyone who can reach the port can read
19//! the metrics. It runs on the export runtime and stops with it.
20//!
21//! It serves at most [`MAX_CONNECTIONS`] connections at once, one request
22//! each, within [`EXCHANGE_TIMEOUT`]: until 2026-11-04 it took every
23//! connection offered and kept each open as long as the client liked, so a
24//! client that opened connections and sent nothing held the port (audit
25//! C-16). To serve `/metrics` on the application's own port instead, behind
26//! its authentication and connection limits, take
27//! [`Telemetry::prometheus`](super::Telemetry::prometheus) and build with
28//! `TelemetryBuilder::without_prometheus_listener` (ADR 0038 §3).
29
30use std::convert::Infallible;
31use std::net::{SocketAddr, TcpListener};
32use std::sync::Arc;
33use std::time::Duration;
34
35use bytes::Bytes;
36use http_body_util::Full;
37use hyper::body::Incoming;
38use hyper::{Method, Request, Response, StatusCode};
39use hyper_util::rt::{TokioIo, TokioTimer};
40use opentelemetry_prometheus::PrometheusExporter;
41use prometheus::{Registry, TextEncoder};
42
43use super::TelemetryError;
44use super::config::{Env, Notes};
45use super::runtime::ExportRuntime;
46
47/// The specification's default port for the Prometheus exporter.
48const DEFAULT_PORT: u16 = 9464;
49
50/// A scraper must send its request line and headers within this.
51const HEADER_TIMEOUT: Duration = Duration::from_secs(10);
52
53/// The most scrape connections served at once; a further one waits in the
54/// listen backlog until one ends. A Prometheus server uses one per target.
55pub(super) const MAX_CONNECTIONS: usize = 16;
56
57/// A connection carries one request and its response, and is closed after
58/// this however far it got.
59pub(super) const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(30);
60
61/// The reader to give the meter provider, where it is served (none without
62/// the listener), and the handle that renders the same text.
63pub(super) struct Started {
64    pub(super) reader: PrometheusExporter,
65    pub(super) addr: Option<SocketAddr>,
66    pub(super) scrape: PrometheusScrape,
67}
68
69/// The metrics in the Prometheus text format, for an application to serve.
70///
71/// It serves them at `/metrics` on a port of its own — behind its own
72/// authentication and connection limits — instead of, or beside, the
73/// listener on `OTEL_EXPORTER_PROMETHEUS_PORT`. From
74/// [`Telemetry::prometheus`](super::Telemetry::prometheus).
75#[derive(Clone)]
76pub struct PrometheusScrape {
77    registry: Registry,
78}
79
80impl std::fmt::Debug for PrometheusScrape {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("PrometheusScrape").finish_non_exhaustive()
83    }
84}
85
86impl PrometheusScrape {
87    /// The `Content-Type` to send [`render`](Self::render)'s text with.
88    pub const CONTENT_TYPE: &'static str = "text/plain; version=0.0.4; charset=utf-8";
89
90    /// Everything recorded so far, in the text format: what a scrape of the
91    /// listener returns.
92    ///
93    /// # Errors
94    ///
95    /// [`TelemetryError::Export`] when the metrics cannot be encoded.
96    pub fn render(&self) -> Result<String, TelemetryError> {
97        TextEncoder::new()
98            .encode_to_string(&self.registry.gather())
99            .map_err(|e| TelemetryError::Export(vec![format!("metrics: {e}")]))
100    }
101}
102
103/// `OTEL_EXPORTER_PROMETHEUS_PORT`: the default when unset, and when it is not
104/// a port number (noted).
105fn port(env: &Env, notes: &Notes) -> u16 {
106    const PORT: &str = "OTEL_EXPORTER_PROMETHEUS_PORT";
107    let Some(value) = env(PORT) else {
108        return DEFAULT_PORT;
109    };
110    value.trim().parse::<u16>().unwrap_or_else(|_| {
111        notes.ignored(
112            PORT,
113            &value,
114            "is not a port number",
115            &format!("{DEFAULT_PORT} is used"),
116        );
117        DEFAULT_PORT
118    })
119}
120
121/// Binds `OTEL_EXPORTER_PROMETHEUS_HOST`:`_PORT` and starts serving, when
122/// `listen`; otherwise only builds the reader and the [`PrometheusScrape`].
123///
124/// A port that is not a number is noted and the default used (audit C-08).
125///
126/// # Errors
127///
128/// An address that cannot be listened on (the port in use, say) or an exporter
129/// that cannot be built, naming what to change.
130pub(super) fn start(
131    env: &Env,
132    runtime: &ExportRuntime,
133    notes: &Notes,
134    listen: bool,
135) -> Result<Started, TelemetryError> {
136    const HOST: &str = "OTEL_EXPORTER_PROMETHEUS_HOST";
137    const PORT: &str = "OTEL_EXPORTER_PROMETHEUS_PORT";
138    let registry = Registry::new();
139    let reader = opentelemetry_prometheus::exporter()
140        .with_registry(registry.clone())
141        .build()
142        .map_err(|e| {
143            TelemetryError::config("OTEL_METRICS_EXPORTER", "prometheus", e.to_string())
144        })?;
145    let scrape = PrometheusScrape {
146        registry: registry.clone(),
147    };
148    if !listen {
149        return Ok(Started {
150            reader,
151            addr: None,
152            scrape,
153        });
154    }
155    let host = env(HOST).unwrap_or_else(|| "localhost".to_owned());
156    let port = port(env, notes);
157    // Bound here, not in the serving task, so a port in use fails the build
158    // — where it is seen — and not the first scrape.
159    let listener = TcpListener::bind((host.as_str(), port)).map_err(|e| {
160        TelemetryError::config(
161            PORT,
162            &format!("{host}:{port}"),
163            format!("cannot listen there: {e}; set {HOST} and {PORT}"),
164        )
165    })?;
166    listener
167        .set_nonblocking(true)
168        .map_err(|e| TelemetryError::config(PORT, &port.to_string(), e.to_string()))?;
169    let addr = listener
170        .local_addr()
171        .map_err(|e| TelemetryError::config(PORT, &port.to_string(), e.to_string()))?;
172    drop(runtime.handle().spawn(serve(listener, registry)));
173    Ok(Started {
174        reader,
175        addr: Some(addr),
176        scrape,
177    })
178}
179
180async fn serve(listener: TcpListener, registry: Registry) {
181    let Ok(listener) = tokio::net::TcpListener::from_std(listener) else {
182        return;
183    };
184    let slots = Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS));
185    loop {
186        // A slot first, then the connection: past the cap, connections wait
187        // in the backlog rather than being taken and held.
188        let Ok(slot) = Arc::clone(&slots).acquire_owned().await else {
189            return;
190        };
191        let Ok((stream, _)) = listener.accept().await else {
192            // Out of descriptors, or the like: wait rather than spin.
193            tokio::time::sleep(Duration::from_millis(100)).await;
194            continue;
195        };
196        let registry = registry.clone();
197        drop(tokio::spawn(async move {
198            let _slot = slot;
199            let service = hyper::service::service_fn(move |req: Request<Incoming>| {
200                let response = respond(&registry, &req);
201                async move { Ok::<_, Infallible>(response) }
202            });
203            let connection = hyper::server::conn::http1::Builder::new()
204                .timer(TokioTimer::new())
205                .header_read_timeout(HEADER_TIMEOUT)
206                .keep_alive(false)
207                .serve_connection(TokioIo::new(stream), service);
208            let _ = tokio::time::timeout(EXCHANGE_TIMEOUT, connection).await;
209        }));
210    }
211}
212
213fn plain(status: StatusCode, body: &'static str) -> Response<Full<Bytes>> {
214    let mut response = Response::new(Full::new(Bytes::from_static(body.as_bytes())));
215    *response.status_mut() = status;
216    response
217}
218
219/// `/metrics` answers `GET` and `HEAD` with the registry in the text format;
220/// anything else is refused for what it is.
221fn respond(registry: &Registry, req: &Request<Incoming>) -> Response<Full<Bytes>> {
222    if req.uri().path() != "/metrics" {
223        return plain(StatusCode::NOT_FOUND, "the metrics are at /metrics\n");
224    }
225    if req.method() != Method::GET && req.method() != Method::HEAD {
226        let mut refused = plain(StatusCode::METHOD_NOT_ALLOWED, "GET /metrics\n");
227        refused.headers_mut().insert(
228            hyper::header::ALLOW,
229            hyper::header::HeaderValue::from_static("GET, HEAD"),
230        );
231        return refused;
232    }
233    TextEncoder::new()
234        .encode_to_string(&registry.gather())
235        .map_or_else(
236            |_| {
237                plain(
238                    StatusCode::INTERNAL_SERVER_ERROR,
239                    "could not encode the metrics\n",
240                )
241            },
242            |text| {
243                let mut response = Response::new(Full::new(Bytes::from(text)));
244                response.headers_mut().insert(
245                    hyper::header::CONTENT_TYPE,
246                    hyper::header::HeaderValue::from_static(PrometheusScrape::CONTENT_TYPE),
247                );
248                response
249            },
250        )
251}
252
253#[cfg(test)]
254mod tests;