Skip to main content

a2a_protocol_server/otel/telemetry/
builder.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`TelemetryBuilder`]: what to export, where, and how, read from the
5//! environment and overridden in code.
6
7use super::selection::{self, Selection};
8use super::{
9    Arc, ClientIdentity, Env, ExportRuntime, Langfuse, OtlpCompression, OtlpProtocol, ProxySetting,
10    Resource, SdkLoggerProvider, SdkMeterProvider, SdkTracerProvider, Signal, Target, Telemetry,
11    TelemetryError, compression, config, detect, exporters, proxy, resource_env,
12};
13
14mod assemble;
15mod options;
16mod resource;
17
18/// Configures and builds a [`Telemetry`]; see [`Telemetry::builder`].
19#[allow(clippy::struct_excessive_bools)] // independent switches, each set by its own method
20pub struct TelemetryBuilder {
21    default_service_name: Option<String>,
22    traces: Option<bool>,
23    metrics: Option<bool>,
24    logs: Option<bool>,
25    log_level: tracing::Level,
26    span_level: tracing::Level,
27    endpoint: Option<String>,
28    protocol: Option<OtlpProtocol>,
29    headers: Vec<(String, String)>,
30    compression: Option<OtlpCompression>,
31    proxy: ProxySetting,
32    detect_resource: bool,
33    startup_summary: bool,
34    /// Set in code; `A2A_LOG_FORMAT` otherwise.
35    console_format: Option<super::ConsoleFormat>,
36    ca_pem: Vec<u8>,
37    client_identity: Option<ClientIdentity>,
38    langfuse: Option<Langfuse>,
39    install_globally: bool,
40    where_configured: bool,
41    /// Whether `OTEL_METRICS_EXPORTER=prometheus` binds a listener of its own.
42    #[cfg(feature = "otel-prometheus")]
43    prometheus_listener: bool,
44    /// Whether process and runtime metrics are reported (audit C-13).
45    process_metrics: bool,
46    /// The runtime whose metrics are reported; the one `build` runs in when
47    /// `None`.
48    runtime: Option<tokio::runtime::Handle>,
49    env: Arc<Env>,
50    /// What the environment said that was not acted on; see [`config::Notes`].
51    notes: config::Notes,
52}
53
54impl std::fmt::Debug for TelemetryBuilder {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        // Headers and the proxy URL are not printed: they carry credentials.
57        f.debug_struct("TelemetryBuilder")
58            .field("default_service_name", &self.default_service_name)
59            .field("traces", &self.traces)
60            .field("metrics", &self.metrics)
61            .field("logs", &self.logs)
62            .field("endpoint", &self.endpoint)
63            .field("protocol", &self.protocol)
64            .field("compression", &self.compression)
65            .field("langfuse", &self.langfuse)
66            .field("where_configured", &self.where_configured)
67            .finish_non_exhaustive()
68    }
69}
70
71impl TelemetryBuilder {
72    pub(super) fn new(env: Arc<Env>) -> Self {
73        Self {
74            default_service_name: None,
75            traces: None,
76            metrics: None,
77            logs: None,
78            log_level: tracing::Level::INFO,
79            span_level: tracing::Level::INFO,
80            endpoint: None,
81            protocol: None,
82            headers: Vec::new(),
83            compression: None,
84            proxy: ProxySetting::default(),
85            detect_resource: true,
86            startup_summary: true,
87            console_format: None,
88            ca_pem: Vec::new(),
89            client_identity: None,
90            langfuse: None,
91            install_globally: true,
92            where_configured: false,
93            #[cfg(feature = "otel-prometheus")]
94            prometheus_listener: true,
95            process_metrics: true,
96            runtime: None,
97            env,
98            notes: config::Notes::default(),
99        }
100    }
101
102    /// The `service.name` to report when the environment names none.
103    /// `OTEL_SERVICE_NAME`, or `service.name` in `OTEL_RESOURCE_ATTRIBUTES`,
104    /// wins over it, as the OpenTelemetry environment specification has it —
105    /// unlike [`init_otlp_pipeline`](crate::otel::init_otlp_pipeline)'s argument.
106    #[must_use]
107    pub fn with_default_service_name(mut self, name: impl Into<String>) -> Self {
108        self.default_service_name = Some(name.into());
109        self
110    }
111
112    /// Whether traces are exported when `OTEL_TRACES_EXPORTER` is unset
113    /// (default: yes). The variable, `otlp` or `none`, wins.
114    #[must_use]
115    pub const fn with_traces(mut self, on: bool) -> Self {
116        self.traces = Some(on);
117        self
118    }
119
120    /// Whether metrics are exported when `OTEL_METRICS_EXPORTER` is unset
121    /// (default: yes, or no with [`with_langfuse`](Self::with_langfuse)).
122    #[must_use]
123    pub const fn with_metrics(mut self, on: bool) -> Self {
124        self.metrics = Some(on);
125        self
126    }
127
128    /// Whether `tracing` events are exported as OpenTelemetry log records
129    /// when `OTEL_LOGS_EXPORTER` is unset (default: yes, or no with
130    /// [`with_langfuse`](Self::with_langfuse)).
131    #[must_use]
132    pub const fn with_logs(mut self, on: bool) -> Self {
133        self.logs = Some(on);
134        self
135    }
136
137    /// Exports each signal only where an endpoint is configured for it: in
138    /// code ([`with_otlp_endpoint`](Self::with_otlp_endpoint), or
139    /// [`with_langfuse`](Self::with_langfuse) for traces), or in
140    /// `OTEL_EXPORTER_OTLP_ENDPOINT`, or in the signal's own
141    /// `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` /
142    /// `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` /
143    /// `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`. A signal with none is not built:
144    /// no exporter, no export thread. For a binary that must run as well
145    /// with a collector as without one; without this, every signal is
146    /// exported, to `localhost` when nothing names an endpoint, as the
147    /// OpenTelemetry environment specification has it.
148    ///
149    /// [`with_traces`](Self::with_traces) and its siblings, set in code,
150    /// still win, and `OTEL_TRACES_EXPORTER` and its siblings win over both.
151    #[must_use]
152    pub const fn with_export_where_configured(mut self) -> Self {
153        self.where_configured = true;
154        self
155    }
156
157    /// The least severe event exported as a log record (default `INFO`).
158    #[must_use]
159    pub const fn with_log_level(mut self, level: tracing::Level) -> Self {
160        self.log_level = level;
161        self
162    }
163
164    /// The least severe span exported, and event recorded on one (default
165    /// `INFO`, the level of every span this SDK makes).
166    ///
167    /// Until 2026-10-29 spans had no level filter: every `DEBUG` and `TRACE`
168    /// event of every crate in the process (h2's frames, hyper's, sqlx's)
169    /// that happened inside an exported span was exported as a span event,
170    /// and `RUST_LOG`, which filters only what is printed, could not turn
171    /// them off (audit C-01). Each layer now tells `tracing` its most
172    /// verbose level, so callsites below it are not even evaluated.
173    #[must_use]
174    pub const fn with_span_level(mut self, level: tracing::Level) -> Self {
175        self.span_level = level;
176        self
177    }
178
179    /// The collector's base URL for every signal, as
180    /// `OTEL_EXPORTER_OTLP_ENDPOINT` would give it: OTLP/HTTP appends
181    /// `/v1/traces`, `/v1/metrics` or `/v1/logs`. Set in code, it wins over
182    /// the variable.
183    #[must_use]
184    pub fn with_otlp_endpoint(mut self, base_url: impl Into<String>) -> Self {
185        self.endpoint = Some(base_url.into());
186        self
187    }
188
189    /// The transport for every signal. Set in code, it wins over
190    /// `OTEL_EXPORTER_OTLP_PROTOCOL`; unset, that variable decides, and
191    /// HTTP/protobuf is the default.
192    #[must_use]
193    pub const fn with_otlp_protocol(mut self, protocol: OtlpProtocol) -> Self {
194        self.protocol = Some(protocol);
195        self
196    }
197
198    /// A header sent with every export, alongside
199    /// `OTEL_EXPORTER_OTLP_HEADERS`.
200    #[must_use]
201    pub fn with_otlp_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
202        self.headers.push((name.into(), value.into()));
203        self
204    }
205
206    /// Compresses every export body. `OTEL_EXPORTER_OTLP_COMPRESSION` (and
207    /// the per-signal forms) asks for the same from the environment, and
208    /// this wins over it. Code cannot turn off what the variable turned on:
209    /// unset the variable, or set it to `none`. Without either, bodies are
210    /// sent as they are.
211    #[must_use]
212    pub const fn with_compression(mut self, compression: OtlpCompression) -> Self {
213        self.compression = Some(compression);
214        self
215    }
216
217    /// Sends every export through this HTTP proxy, as `ALL_PROXY` would, and
218    /// wins over `ALL_PROXY`, `HTTPS_PROXY` and `HTTP_PROXY`. `NO_PROXY` does
219    /// not apply to it: a proxy chosen in code is explicit, and does not
220    /// change with the machine's environment. Credentials go in the URL
221    /// (`http://user:pass@proxy:3128`). Only `http://` proxies are spoken; an
222    /// `https://` or `socks5://` one is ignored with a warning, and the
223    /// export goes direct.
224    #[must_use]
225    pub fn with_proxy(mut self, url: impl Into<String>) -> Self {
226        self.proxy = ProxySetting::Url(url.into());
227        self
228    }
229
230    /// Sends exports straight to the collector, ignoring `HTTP_PROXY`,
231    /// `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY`. Without this, and without
232    /// [`with_proxy`](Self::with_proxy), those variables apply as they do to
233    /// curl.
234    #[must_use]
235    pub fn without_proxy(mut self) -> Self {
236        self.proxy = ProxySetting::Off;
237        self
238    }
239
240    /// Leaves the process's own description out of the resource. By default
241    /// it carries `host.name`, `host.arch`, `os.type`, `process.pid` and
242    /// `process.executable.name`, each only when `OTEL_RESOURCE_ATTRIBUTES`
243    /// does not name it; turn this off for an export to a party that should
244    /// not learn them. `service.name`, `service.instance.id` and
245    /// `telemetry.sdk.*` stay.
246    #[must_use]
247    pub const fn without_resource_detection(mut self) -> Self {
248        self.detect_resource = false;
249        self
250    }
251
252    /// Leaves the startup line (`describe()`) out of what
253    /// [`Telemetry::install_subscriber`] logs. By default it logs where each
254    /// signal goes, or that nothing is exported and how to change that, once
255    /// at INFO: what a server's operator wants and a one-shot command-line tool
256    /// does not, where it would be a line on standard error of every run.
257    /// Warnings and errors (a lost export, a setting that was not honoured)
258    /// are still printed, and `describe()` still returns the line.
259    #[must_use]
260    pub const fn without_startup_summary(mut self) -> Self {
261        self.startup_summary = false;
262        self
263    }
264
265    /// CA certificates, PEM, to trust alongside the bundled Mozilla roots —
266    /// for a collector behind a private CA. `OTEL_EXPORTER_OTLP_CERTIFICATE`
267    /// names a file of them and is read too.
268    #[must_use]
269    pub fn with_ca_certificate_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
270        self.ca_pem.extend_from_slice(pem.as_ref());
271        self.ca_pem.push(b'\n');
272        self
273    }
274
275    /// A client certificate chain (leaf first) and its private key, PEM,
276    /// presented to a collector that requires mutual TLS, over either
277    /// transport. `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` and
278    /// `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or their per-signal forms, name files
279    /// of them and win over this, as a variable wins over a header set in
280    /// code. Both are checked when the exporters are built: a certificate or
281    /// key that does not parse, or a key that is not the certificate's on
282    /// OTLP/HTTP, fails [`build`](Self::build).
283    #[must_use]
284    pub fn with_client_certificate_pem(
285        mut self,
286        cert_chain: impl AsRef<[u8]>,
287        key: impl AsRef<[u8]>,
288    ) -> Self {
289        self.client_identity = Some(ClientIdentity {
290            cert_pem: cert_chain.as_ref().to_vec(),
291            key_pem: key.as_ref().to_vec(),
292        });
293        self
294    }
295
296    /// Sends traces to Langfuse; see [`Langfuse`] for exactly what it sets.
297    #[must_use]
298    pub fn with_langfuse(mut self, langfuse: Langfuse) -> Self {
299        self.langfuse = Some(langfuse);
300        self
301    }
302
303    /// Whether to install the tracer and meter providers, and the W3C
304    /// `tracecontext` and `baggage` propagators, as the process-global ones
305    /// (default: yes). Off, nothing global changes — for a test, or a
306    /// process with providers of its own.
307    #[must_use]
308    pub const fn install_globally(mut self, on: bool) -> Self {
309        self.install_globally = on;
310        self
311    }
312
313    /// Reads variables from `env` instead of the process environment.
314    #[cfg(test)]
315    pub(super) fn with_env(
316        mut self,
317        env: impl Fn(&str) -> Option<String> + Send + Sync + 'static,
318    ) -> Self {
319        self.env = Arc::new(env);
320        self
321    }
322
323    fn selection(&self, signal: Signal) -> Selection {
324        if config::sdk_disabled(&*self.env) {
325            return Selection::OFF;
326        }
327        let (explicit, preset_default) = match signal {
328            Signal::Traces => (self.traces, true),
329            Signal::Metrics => (self.metrics, self.langfuse.is_none()),
330            Signal::Logs => (self.logs, self.langfuse.is_none()),
331        };
332        let default = if self.where_configured {
333            let in_code =
334                self.endpoint.is_some() || (signal == Signal::Traces && self.langfuse.is_some());
335            preset_default && (in_code || signal.endpoint_in_env(&*self.env))
336        } else {
337            preset_default
338        };
339        selection::from_env(&*self.env, signal, explicit.unwrap_or(default), &self.notes)
340    }
341
342    /// OTLP/HTTP's endpoint must carry a scheme. `opentelemetry-otlp` answers
343    /// `127.0.0.1:4318` with "invalid format", naming nothing to change; the
344    /// gRPC path accepts it (`https://`, or `http://` under
345    /// `OTEL_EXPORTER_OTLP_INSECURE`), but OTLP/HTTP has no such variable, so
346    /// guessing `http` or `https` for the user would be a guess about TLS.
347    fn require_scheme(&self, signal: Signal) -> Result<(), TelemetryError> {
348        let given = self.endpoint.as_deref().map_or_else(
349            || signal.otlp_var(&*self.env, "ENDPOINT"),
350            |base| Some(("the endpoint given in code".to_owned(), base.to_owned())),
351        );
352        match given {
353            Some((var, value)) if !value.contains("://") => Err(TelemetryError::config(
354                &var,
355                &value,
356                format!("OTLP/HTTP needs a scheme: write `http://{value}` or `https://{value}`"),
357            )),
358            _ => Ok(()),
359        }
360    }
361
362    /// A warning when the base endpoint over OTLP/HTTP already ends in one of
363    /// the paths the exporter appends to it.
364    ///
365    /// `OTEL_EXPORTER_OTLP_ENDPOINT` is a base: the specification has the
366    /// exporter add `/v1/traces`, `/v1/metrics` or `/v1/logs`, so a value
367    /// copied from a signal's full URL (`http://c:4318/v1/traces`) posts to
368    /// `/v1/traces/v1/traces`, which a collector answers with a 404. The
369    /// signal's own `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is the full URL, and
370    /// is not checked. `otlp` says which signals go over OTLP.
371    pub(super) fn base_endpoint_notice(&self, otlp: [bool; 3]) -> Option<String> {
372        const SIGNALS: [Signal; 3] = [Signal::Traces, Signal::Metrics, Signal::Logs];
373        const PATHS: [&str; 3] = ["/v1/traces", "/v1/metrics", "/v1/logs"];
374        for (signal, over_otlp) in SIGNALS.into_iter().zip(otlp) {
375            let protocol = config::protocol(&*self.env, signal, self.protocol, &self.notes);
376            if !over_otlp || !protocol.is_http() {
377                continue;
378            }
379            let (origin, base) = match self.endpoint.as_deref() {
380                Some(base) => ("the endpoint given in code".to_owned(), base.to_owned()),
381                None => match signal.otlp_var(&*self.env, "ENDPOINT") {
382                    Some((var, value)) if var == "OTEL_EXPORTER_OTLP_ENDPOINT" => (var, value),
383                    _ => continue,
384                },
385            };
386            let trimmed = base.trim_end_matches('/');
387            let Some(suffix) = PATHS.iter().find(|p| trimmed.ends_with(**p)) else {
388                continue;
389            };
390            let root = &trimmed[..trimmed.len() - suffix.len()];
391            return Some(format!(
392                "{origin} is {base}, which already ends in {suffix}: over OTLP/HTTP the exporter \
393                 appends /v1/traces, /v1/metrics or /v1/logs to it, so {} would go to {}. Give the \
394                 base URL ({root}), or a complete URL in OTEL_EXPORTER_OTLP_{}_ENDPOINT.",
395                signal.name(),
396                Target::endpoint_from_base(&base, signal, protocol),
397                signal.name().to_uppercase(),
398            ));
399        }
400        None
401    }
402
403    /// The client certificate and key the environment names for `signal`,
404    /// else the ones given to the builder.
405    fn client_identity_for(
406        &self,
407        signal: Signal,
408    ) -> Result<Option<ClientIdentity>, TelemetryError> {
409        Ok(match config::client_identity_files(&*self.env, signal)? {
410            Some([(cert_var, cert_path), (key_var, key_path)]) => Some(ClientIdentity {
411                cert_pem: read_file(&cert_var, &cert_path)?,
412                key_pem: read_file(&key_var, &key_path)?,
413            }),
414            None => self.client_identity.clone(),
415        })
416    }
417
418    pub(super) fn target(&self, signal: Signal) -> Result<Target, TelemetryError> {
419        let env = &*self.env;
420        let mut ca_pem = self.ca_pem.clone();
421        if let Some((var, path)) = config::certificate_file(env, signal) {
422            ca_pem.extend_from_slice(&read_file(&var, &path)?);
423        }
424        let client_identity = self.client_identity_for(signal)?;
425        let timeout = config::timeout(env, signal, &self.notes);
426        let proxy = Arc::new(proxy::matcher(env, &self.proxy));
427        let compression = self
428            .compression
429            .map_or_else(|| compression::from_env(env, signal, &self.notes), Some);
430        if let (Signal::Traces, Some(lf)) = (signal, &self.langfuse) {
431            let endpoint = lf.traces_endpoint();
432            return Ok(Target {
433                signal,
434                protocol: OtlpProtocol::HttpProtobuf,
435                destination: Target::destination_for(
436                    env,
437                    signal,
438                    OtlpProtocol::HttpProtobuf,
439                    Some(&endpoint),
440                ),
441                endpoint: Some(endpoint),
442                headers: lf.headers(),
443                compression,
444                proxy,
445                cause: Arc::default(),
446                timeout,
447                ca_pem,
448                client_identity,
449            });
450        }
451        let protocol = config::protocol(env, signal, self.protocol, &self.notes);
452        if protocol.is_http() {
453            self.require_scheme(signal)?;
454        }
455        // OTLP/HTTP leaves an unset endpoint to `opentelemetry-otlp`. gRPC
456        // resolves it here, because an `https://` one is dialled over this
457        // crate's own TLS connector, which needs the endpoint to build.
458        let endpoint = match self.endpoint.as_deref() {
459            Some(base) => Some(Target::endpoint_from_base(base, signal, protocol)),
460            None if protocol == OtlpProtocol::Grpc => signal.grpc_endpoint_in_env(env),
461            None => None,
462        };
463        Ok(Target {
464            signal,
465            protocol,
466            destination: Target::destination_for(env, signal, protocol, endpoint.as_deref()),
467            endpoint,
468            headers: self.headers.clone(),
469            compression,
470            proxy,
471            cause: Arc::default(),
472            timeout,
473            ca_pem,
474            client_identity,
475        })
476    }
477}
478
479/// The contents of the file `path`, which variable `var` named.
480fn read_file(var: &str, path: &str) -> Result<Vec<u8>, TelemetryError> {
481    std::fs::read(path)
482        .map_err(|e| TelemetryError::config(var, path, format!("cannot be read: {e}")))
483}