Skip to main content

a2a_protocol_server/otel/telemetry/
config.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! How `Telemetry` reads the `OTEL_*` environment.
5//!
6//! Only what `opentelemetry-otlp` and `opentelemetry_sdk` do not already
7//! read is read here: which signals to export, the transport (so the right
8//! exporter is built), the export timeout and CA certificate (which the
9//! exporter's HTTP client and TLS need up front), and whether the environment
10//! names the service. Endpoints, headers, the sampler, the batch processor's
11//! limits and `OTEL_RESOURCE_ATTRIBUTES` are left to those crates, which read
12//! them as the specification defines.
13//!
14//! Every read goes through an [`Env`], so the rules are testable: writing the
15//! process environment is `unsafe` in edition 2024, and this crate forbids
16//! `unsafe`.
17
18use std::sync::{Mutex, PoisonError};
19use std::time::Duration;
20
21use super::TelemetryError;
22
23// Where variables come from (the process environment, or a test's table) and
24// how the process environment is read; shared with the outbound clients.
25pub(super) use crate::net::proxy::{Env, process_env};
26
27/// What the environment said that this crate did not act on, one line each,
28/// and what it did instead.
29///
30/// The OpenTelemetry specification has an SDK warn and ignore a value it
31/// cannot use, and a fleet shares one `OTEL_*` preset among SDKs that do not
32/// all know the same exporters, so a process that refused to start over a
33/// name it does not know (`zipkin`) took the whole fleet down for it (audit
34/// C-08, maintainer's decision of 2026-11-01). `Telemetry` has no subscriber
35/// yet when it parses, so the lines wait here for
36/// [`Telemetry::notices`](super::Telemetry::notices) and
37/// `install_subscriber`, which prints them at WARN. A line is kept once however
38/// many signals read the variable.
39#[derive(Debug, Default)]
40pub(super) struct Notes(Mutex<Vec<String>>);
41
42impl Notes {
43    /// `variable` was set to `value`, which `why` says this crate cannot use;
44    /// `instead` is what it did.
45    pub(super) fn ignored(&self, variable: &str, value: &str, why: &str, instead: &str) {
46        let line = format!("{variable}={value:?} {why}; {instead}");
47        let mut lines = self.0.lock().unwrap_or_else(PoisonError::into_inner);
48        if !lines.contains(&line) {
49            lines.push(line);
50        }
51    }
52
53    /// The lines so far, leaving none.
54    pub(super) fn take(&self) -> Vec<String> {
55        std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
56    }
57}
58
59/// One of the three signals.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub(super) enum Signal {
62    Traces,
63    Metrics,
64    Logs,
65}
66
67impl Signal {
68    /// `traces`, `metrics` or `logs`.
69    pub(super) const fn name(self) -> &'static str {
70        match self {
71            Self::Traces => "traces",
72            Self::Metrics => "metrics",
73            Self::Logs => "logs",
74        }
75    }
76
77    /// `OTEL_{TRACES,METRICS,LOGS}_EXPORTER`.
78    pub(super) const fn exporter_var(self) -> &'static str {
79        match self {
80            Self::Traces => "OTEL_TRACES_EXPORTER",
81            Self::Metrics => "OTEL_METRICS_EXPORTER",
82            Self::Logs => "OTEL_LOGS_EXPORTER",
83        }
84    }
85
86    /// The infix of the signal-specific OTLP variables.
87    const fn upper(self) -> &'static str {
88        match self {
89            Self::Traces => "TRACES",
90            Self::Metrics => "METRICS",
91            Self::Logs => "LOGS",
92        }
93    }
94
95    /// The path OTLP/HTTP appends to a base endpoint for this signal.
96    pub(super) const fn http_path(self) -> &'static str {
97        match self {
98            Self::Traces => "v1/traces",
99            Self::Metrics => "v1/metrics",
100            Self::Logs => "v1/logs",
101        }
102    }
103
104    /// Whether an OTLP endpoint is configured for this signal in the
105    /// environment: its own `OTEL_EXPORTER_OTLP_{SIGNAL}_ENDPOINT`, or the
106    /// general `OTEL_EXPORTER_OTLP_ENDPOINT`.
107    pub(super) fn endpoint_in_env(self, env: &Env) -> bool {
108        self.otlp_var(env, "ENDPOINT").is_some()
109    }
110
111    /// The OTLP/gRPC endpoint the environment configures for this signal,
112    /// as `opentelemetry-otlp` reads it: the signal's own variable, then the
113    /// general one, used as given. One with no scheme gets `http://` when
114    /// `OTEL_EXPORTER_OTLP_{SIGNAL_}INSECURE` is `true` and `https://`
115    /// otherwise.
116    pub(super) fn grpc_endpoint_in_env(self, env: &Env) -> Option<String> {
117        let (_, endpoint) = self.otlp_var(env, "ENDPOINT")?;
118        if endpoint.contains("://") {
119            return Some(endpoint);
120        }
121        let insecure = self
122            .otlp_var(env, "INSECURE")
123            .is_some_and(|(_, v)| v.trim().eq_ignore_ascii_case("true"));
124        let scheme = if insecure { "http" } else { "https" };
125        Some(format!("{scheme}://{endpoint}"))
126    }
127
128    /// The signal-specific variable, falling back to the general one.
129    pub(super) fn otlp_var(self, env: &Env, suffix: &str) -> Option<(String, String)> {
130        let specific = format!("OTEL_EXPORTER_OTLP_{}_{suffix}", self.upper());
131        if let Some(v) = env(&specific) {
132            return Some((specific, v));
133        }
134        let general = format!("OTEL_EXPORTER_OTLP_{suffix}");
135        env(&general).map(|v| (general, v))
136    }
137}
138
139/// The OTLP transport.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum OtlpProtocol {
143    /// OTLP/gRPC, conventionally on port 4317.
144    Grpc,
145    /// OTLP/HTTP with protobuf bodies, conventionally on port 4318 — the
146    /// specification's default, and the one Langfuse accepts.
147    HttpProtobuf,
148    /// OTLP/HTTP with JSON bodies, on the same port as protobuf. Needs the
149    /// `otlp-json` feature.
150    #[cfg(feature = "otlp-json")]
151    HttpJson,
152}
153
154impl OtlpProtocol {
155    /// The name `OTEL_EXPORTER_OTLP_PROTOCOL` gives it.
156    pub(super) const fn label(self) -> &'static str {
157        match self {
158            Self::Grpc => "grpc",
159            Self::HttpProtobuf => "http/protobuf",
160            #[cfg(feature = "otlp-json")]
161            Self::HttpJson => "http/json",
162        }
163    }
164
165    /// Whether the transport is OTLP/HTTP, whose endpoint is per signal.
166    pub(super) const fn is_http(self) -> bool {
167        !matches!(self, Self::Grpc)
168    }
169}
170
171/// `OTEL_SDK_DISABLED=true` turns every signal off.
172pub(super) fn sdk_disabled(env: &Env) -> bool {
173    env("OTEL_SDK_DISABLED").is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
174}
175
176/// A note when `OTEL_SDK_DISABLED` is set to something that is not `true` or
177/// `false`: `1` and `yes` do not disable the SDK, and said nothing about it
178/// (audit NEW-c-5). The specification reads only `true` (any case).
179pub(super) fn note_misread_sdk_disabled(env: &Env, notes: &Notes) {
180    const VAR: &str = "OTEL_SDK_DISABLED";
181    if let Some(value) = env(VAR)
182        && !["true", "false"]
183            .iter()
184            .any(|ok| value.trim().eq_ignore_ascii_case(ok))
185    {
186        notes.ignored(
187            VAR,
188            &value,
189            "is not `true` or `false`, and only `true` disables the SDK",
190            "the SDK is not disabled",
191        );
192    }
193}
194
195/// The transport for `signal`: `explicit` when given, else
196/// `OTEL_EXPORTER_OTLP_{SIGNAL}_PROTOCOL` or `OTEL_EXPORTER_OTLP_PROTOCOL`
197/// (matched without regard to case), else HTTP/protobuf, the specification's
198/// default. A value that is none of the three is noted and HTTP/protobuf used.
199pub(super) fn protocol(
200    env: &Env,
201    signal: Signal,
202    explicit: Option<OtlpProtocol>,
203    notes: &Notes,
204) -> OtlpProtocol {
205    if let Some(p) = explicit {
206        return p;
207    }
208    let Some((var, value)) = signal.otlp_var(env, "PROTOCOL") else {
209        return OtlpProtocol::HttpProtobuf;
210    };
211    match value.trim().to_ascii_lowercase().as_str() {
212        "grpc" => OtlpProtocol::Grpc,
213        "http/protobuf" => OtlpProtocol::HttpProtobuf,
214        "http/json" => http_json(notes, &var, &value),
215        _ => {
216            notes.ignored(
217                &var,
218                &value,
219                "is not `grpc`, `http/protobuf` or `http/json`",
220                "`http/protobuf` is used",
221            );
222            OtlpProtocol::HttpProtobuf
223        }
224    }
225}
226
227/// `http/json`, which only the `otlp-json` feature can export.
228///
229/// One function with the feature split inside it rather than two `#[cfg]`
230/// match arms, for the reason `build_jwks_client` gives: under
231/// `--all-features` the `not(otlp-json)` arm is compiled out, so deleting it
232/// builds and passes every test, and the mutation gate reported it as a
233/// survivor no test could reach.
234#[cfg_attr(feature = "otlp-json", allow(clippy::missing_const_for_fn))]
235fn http_json(notes: &Notes, var: &str, value: &str) -> OtlpProtocol {
236    #[cfg(feature = "otlp-json")]
237    {
238        let _ = (notes, var, value);
239        OtlpProtocol::HttpJson
240    }
241    #[cfg(not(feature = "otlp-json"))]
242    {
243        notes.ignored(
244            var,
245            value,
246            "needs the `otlp-json` feature, which is not compiled in",
247            "`http/protobuf` is used",
248        );
249        OtlpProtocol::HttpProtobuf
250    }
251}
252
253/// The export timeout for `signal`, in milliseconds per the specification;
254/// 10 s when unset, and when the value is not a number of milliseconds (noted).
255pub(super) fn timeout(env: &Env, signal: Signal, notes: &Notes) -> Duration {
256    const DEFAULT: Duration = Duration::from_secs(10);
257    let Some((var, value)) = signal.otlp_var(env, "TIMEOUT") else {
258        return DEFAULT;
259    };
260    value.trim().parse::<u64>().map_or_else(
261        |_| {
262            notes.ignored(
263                &var,
264                &value,
265                "is not a number of milliseconds",
266                "10000 is used",
267            );
268            DEFAULT
269        },
270        Duration::from_millis,
271    )
272}
273
274/// The PEM file of extra CA certificates to trust for `signal`, if any:
275/// `OTEL_EXPORTER_OTLP_{SIGNAL}_CERTIFICATE` or
276/// `OTEL_EXPORTER_OTLP_CERTIFICATE`.
277pub(super) fn certificate_file(env: &Env, signal: Signal) -> Option<(String, String)> {
278    signal.otlp_var(env, "CERTIFICATE")
279}
280
281/// The client certificate and key files for mutual TLS with the collector,
282/// if any, each as `(variable, path)`:
283/// `OTEL_EXPORTER_OTLP_{SIGNAL}_CLIENT_CERTIFICATE` and `..._CLIENT_KEY`, each
284/// falling back to its general variable on its own, as the specification
285/// defines them.
286///
287/// # Errors
288///
289/// One without the other: a certificate cannot be presented without its key,
290/// and a key alone names nothing to present, so either is a misconfiguration
291/// that would otherwise connect without a client certificate and say nothing.
292pub(super) fn client_identity_files(
293    env: &Env,
294    signal: Signal,
295) -> Result<Option<[(String, String); 2]>, TelemetryError> {
296    match (
297        signal.otlp_var(env, "CLIENT_CERTIFICATE"),
298        signal.otlp_var(env, "CLIENT_KEY"),
299    ) {
300        (None, None) => Ok(None),
301        (Some(cert), Some(key)) => Ok(Some([cert, key])),
302        (Some((var, value)), None) => Err(TelemetryError::config(
303            &var,
304            &value,
305            "a client certificate needs its key: set OTEL_EXPORTER_OTLP_CLIENT_KEY too",
306        )),
307        (None, Some((var, value))) => Err(TelemetryError::config(
308            &var,
309            &value,
310            "a client key needs its certificate: set OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE too",
311        )),
312    }
313}
314
315/// Whether the environment names the service, in which case it wins over
316/// [`TelemetryBuilder::with_default_service_name`](super::TelemetryBuilder::with_default_service_name).
317pub(super) fn service_name_from_env(env: &Env) -> bool {
318    env("OTEL_SERVICE_NAME").is_some() || resource_attribute_from_env(env, "service.name")
319}
320
321/// Whether `OTEL_RESOURCE_ATTRIBUTES` sets `key`.
322pub(super) fn resource_attribute_from_env(env: &Env, key: &str) -> bool {
323    env("OTEL_RESOURCE_ATTRIBUTES").is_some_and(|attrs| {
324        attrs
325            .split(',')
326            .filter_map(|kv| kv.split_once('='))
327            .any(|(k, _)| k.trim() == key)
328    })
329}
330
331#[cfg(test)]
332#[path = "config_tests.rs"]
333mod tests;