a2a_protocol_server/otel/telemetry/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! One entry point for traces, metrics and logs (ADR 0013, option 5).
5//!
6//! [`Telemetry::init`] reads the `OTEL_*` environment, builds an OTLP
7//! exporter per signal on the transport it names, installs the tracer and
8//! meter providers globally, and returns a guard whose drop flushes all
9//! three. [`Telemetry::layer`] is the `tracing` layer that turns this crate's
10//! spans — and the application's own spans and events — into OpenTelemetry
11//! spans and log records.
12//!
13//! ```rust,no_run
14//! use a2a_protocol_server::otel::Telemetry;
15//! use tracing_subscriber::layer::SubscriberExt as _;
16//! use tracing_subscriber::util::SubscriberInitExt as _;
17//!
18//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
19//! let telemetry = Telemetry::builder()
20//! .with_default_service_name("my-agent") // OTEL_SERVICE_NAME wins
21//! .build()?;
22//! tracing_subscriber::registry().with(telemetry.layer()).init();
23//!
24//! // ... serve, with `.with_metrics(telemetry.otel_metrics())` on the
25//! // handler builder ...
26//!
27//! telemetry.shutdown()?; // or let it drop
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! It can be called from anywhere — a plain `fn main`, a `current_thread`
33//! runtime, a test — because export runs on a private runtime of its own
34//! (`runtime.rs` says why); and with `OTEL_SDK_DISABLED=true` it builds
35//! nothing and the layer records nothing.
36
37mod builder;
38mod compression;
39mod config;
40mod console;
41mod console_format;
42mod counting;
43mod detect;
44mod diagnostics;
45mod error;
46mod exporters;
47mod hints;
48mod http;
49mod langfuse;
50mod process;
51#[cfg(feature = "otel-prometheus")]
52mod prometheus;
53mod propagators;
54mod resource_env;
55mod runtime;
56mod selection;
57mod self_metrics;
58mod subscriber;
59mod upstream;
60
61use std::sync::Arc;
62use std::sync::atomic::{AtomicU64, Ordering};
63
64use opentelemetry_sdk::Resource;
65use opentelemetry_sdk::logs::SdkLoggerProvider;
66use opentelemetry_sdk::metrics::SdkMeterProvider;
67use opentelemetry_sdk::trace::SdkTracerProvider;
68
69pub use builder::TelemetryBuilder;
70pub use compression::OtlpCompression;
71pub use config::OtlpProtocol;
72pub use console_format::ConsoleFormat;
73pub use error::TelemetryError;
74pub use langfuse::{LANGFUSE_SELF_HOSTED, Langfuse};
75#[cfg(feature = "otel-prometheus")]
76pub use prometheus::PrometheusScrape;
77
78use crate::net::proxy::{self, ProxySetting};
79use config::{Env, Signal};
80use counting::Counting;
81use exporters::{ClientIdentity, Target};
82use runtime::ExportRuntime;
83
84/// The instrumentation scope this crate's spans are recorded under.
85const SCOPE: &str = "a2a-protocol-server";
86
87/// Targets whose spans and events are never exported: the exporter's own
88/// stack, and this module's own diagnostics (a lost export, an ignored proxy). Exporting them would make every export produce telemetry that
89/// needs exporting, and an export failure would log a record whose export
90/// fails. They still reach the application's other layers — a `fmt` layer
91/// still shows an export error.
92const SELF_TARGETS: &[&str] = &[
93 "opentelemetry",
94 "opentelemetry_sdk",
95 "opentelemetry_otlp",
96 "opentelemetry_http",
97 "hyper",
98 "hyper_util",
99 "h2",
100 "tonic",
101 "tower",
102 "rustls",
103 "a2a_protocol_server::otel::telemetry",
104];
105
106fn is_self_target(target: &str) -> bool {
107 SELF_TARGETS.iter().any(|t| {
108 target
109 .strip_prefix(t)
110 .is_some_and(|rest| rest.is_empty() || rest.starts_with("::"))
111 })
112}
113
114/// Exporting providers for traces, metrics and logs, and the guard that
115/// flushes them. Built by [`Telemetry::init`] or [`Telemetry::builder`].
116///
117/// Dropping it flushes and shuts every provider down, best-effort;
118/// [`shutdown`](Self::shutdown) does the same and reports what it can see
119/// failed.
120/// Either is safe on any thread, inside a Tokio runtime of either flavour or
121/// outside one, and may block while a collector is slow: each of the three
122/// providers is given the SDK's 5 s shutdown timeout (`opentelemetry_sdk`
123/// 0.33.1), one after the other. Measured on `hello-agent` after `SIGTERM`
124/// (debug build, one run each): 0.1 s to a collector that answers, 1.8 s to a
125/// port that refuses, 15.0 s to one that accepts the connection and never
126/// answers, 4.1 s to that one with `OTEL_EXPORTER_OTLP_TIMEOUT=2000`.
127///
128/// `#[must_use]`: `Telemetry::init()?;` alone on a line drops the guard at
129/// once, which shuts every exporter down before anything is recorded (audit
130/// G-14). Keep it for as long as the process should export.
131#[derive(Debug)]
132#[must_use = "dropping `Telemetry` shuts every exporter down; keep it until the process exits"]
133pub struct Telemetry {
134 tracer: Option<SdkTracerProvider>,
135 meter: Option<SdkMeterProvider>,
136 logger: Option<SdkLoggerProvider>,
137 log_level: tracing::Level,
138 span_level: tracing::Level,
139 /// The default service name as a `tracing` target, whose INFO lines the
140 /// default filter prints.
141 app_target: Option<String>,
142 /// Dropped after the providers, so their final flush still has it.
143 runtime: Option<ExportRuntime>,
144 /// Each signal's count of lost exports since the last report
145 /// (`counting.rs`).
146 failures: Vec<(Signal, Arc<AtomicU64>)>,
147 /// The same, never reset, for `a2a.telemetry.export.failed` (audit C-13).
148 failed_totals: Vec<(Signal, Arc<AtomicU64>)>,
149 /// `OTEL_SDK_DISABLED` was set: nothing is built or exported. The printing
150 /// layer is still installed (audit C-07).
151 disabled: bool,
152 /// Whether `install_subscriber` logs [`describe`](Self::describe).
153 startup_summary: bool,
154 /// What `install_subscriber` prints to standard error.
155 console_format: ConsoleFormat,
156 /// Log records go to standard output (`OTEL_LOGS_EXPORTER=console`), so
157 /// `install_subscriber` need not print them again on standard error.
158 logs_on_console: bool,
159 /// One entry per signal: where it goes, or `off` ([`describe`](Self::describe)).
160 report: Vec<String>,
161 /// What the configuration asked for that this SDK does not do and carried
162 /// on without ([`notices`](Self::notices)).
163 notices: Vec<String>,
164 /// Where the Prometheus endpoint listens ([`prometheus_addr`](Self::prometheus_addr)).
165 #[cfg(feature = "otel-prometheus")]
166 prometheus: Option<std::net::SocketAddr>,
167 /// The same text, for the application to serve ([`prometheus`](Self::prometheus)).
168 #[cfg(feature = "otel-prometheus")]
169 prometheus_scrape: Option<prometheus::PrometheusScrape>,
170}
171
172impl Telemetry {
173 /// Configuration with every default; see [`TelemetryBuilder`].
174 #[must_use]
175 pub fn builder() -> TelemetryBuilder {
176 TelemetryBuilder::new(Arc::new(config::process_env))
177 }
178
179 /// Every signal over OTLP, configured by the environment alone: the same
180 /// as [`Telemetry::builder`] followed by [`TelemetryBuilder::build`].
181 ///
182 /// # Errors
183 ///
184 /// As [`TelemetryBuilder::build`].
185 ///
186 /// Without an endpoint in the environment, every signal is exported to
187 /// `localhost` (4318, or 4317 over gRPC), as the OpenTelemetry environment
188 /// specification has it — what a deployment with a collector beside it
189 /// (a sidecar) and no `OTEL_*` variable relies on. A binary that must run
190 /// as well without a collector wants
191 /// [`init_where_configured`](Self::init_where_configured).
192 pub fn init() -> Result<Self, TelemetryError> {
193 Self::builder().build()
194 }
195
196 /// Like [`init`](Self::init), but a signal is built only where an endpoint
197 /// is configured for it: the same as [`Telemetry::builder`] followed by
198 /// [`TelemetryBuilder::with_export_where_configured`] and
199 /// [`TelemetryBuilder::build`]. With no `OTEL_EXPORTER_OTLP_*ENDPOINT` set,
200 /// nothing is exported and no export thread is started.
201 ///
202 /// # Errors
203 ///
204 /// As [`TelemetryBuilder::build`].
205 pub fn init_where_configured() -> Result<Self, TelemetryError> {
206 Self::builder().with_export_where_configured().build()
207 }
208
209 /// An [`OtelMetrics`](super::OtelMetrics) recording through this
210 /// telemetry's meter provider, for `RequestHandlerBuilder::with_metrics`.
211 /// With metrics off it records into a no-op meter.
212 #[must_use]
213 pub fn otel_metrics(&self) -> super::OtelMetrics {
214 use opentelemetry::metrics::MeterProvider as _;
215 let meter = self.meter.as_ref().map_or_else(
216 || opentelemetry::metrics::noop::NoopMeterProvider::new().meter("a2a.server"),
217 |provider| provider.meter("a2a.server"),
218 );
219 super::OtelMetrics::from_meter(&meter)
220 }
221
222 /// The tracer provider, when traces are exported.
223 #[must_use]
224 pub const fn tracer_provider(&self) -> Option<&SdkTracerProvider> {
225 self.tracer.as_ref()
226 }
227
228 /// The meter provider, when metrics are exported.
229 #[must_use]
230 pub const fn meter_provider(&self) -> Option<&SdkMeterProvider> {
231 self.meter.as_ref()
232 }
233
234 /// The logger provider, when logs are exported.
235 #[must_use]
236 pub const fn logger_provider(&self) -> Option<&SdkLoggerProvider> {
237 self.logger.as_ref()
238 }
239
240 /// `exporter`, counting its lost exports into a new counter for
241 /// `signal` that [`report_failures`](Self::report_failures) reads, and
242 /// saying so, now and then, while they keep being lost.
243 fn counting<E>(&mut self, signal: Signal, exporter: E, target: &Target) -> Counting<E> {
244 let counter = Arc::new(AtomicU64::new(0));
245 self.failures.push((signal, Arc::clone(&counter)));
246 let total = Arc::new(AtomicU64::new(0));
247 self.failed_totals.push((signal, Arc::clone(&total)));
248 Counting::new(exporter, counter)
249 .with_total(total)
250 .reporting(
251 signal,
252 &target.destination,
253 hints::Route::of(target.protocol, &target.destination),
254 target.proxy_display(),
255 Arc::clone(&target.cause),
256 )
257 }
258
259 /// The address `/metrics` is served on under
260 /// `OTEL_METRICS_EXPORTER=prometheus` — the port the operating system
261 /// chose when `OTEL_EXPORTER_PROMETHEUS_PORT` is `0`.
262 #[cfg(feature = "otel-prometheus")]
263 #[must_use]
264 pub const fn prometheus_addr(&self) -> Option<std::net::SocketAddr> {
265 self.prometheus
266 }
267
268 /// Under `OTEL_METRICS_EXPORTER=prometheus`, a handle that renders the
269 /// metrics in the Prometheus text format, for the application to serve at
270 /// `/metrics` on its own port, behind its own authentication; with
271 /// [`TelemetryBuilder::without_prometheus_listener`] it is the only way
272 /// out (audit C-16, ADR 0038 §3). `None` when that exporter is not chosen.
273 #[cfg(feature = "otel-prometheus")]
274 #[must_use]
275 pub fn prometheus(&self) -> Option<prometheus::PrometheusScrape> {
276 self.prometheus_scrape.clone()
277 }
278
279 /// What the environment or the code asked for that this SDK does not do,
280 /// and went on without: an exporter name, protocol or compression it does
281 /// not have, a timeout or port it could not read, a propagator it does not
282 /// have, an `OTEL_SDK_DISABLED` that is not `true` or `false`. Each line
283 /// names the variable and its value and says what was used instead. Each is
284 /// also logged at `warn` by [`install_subscriber`](Self::install_subscriber);
285 /// an application with its own subscriber reads them here. Until
286 /// 2026-11-01 most of these stopped [`build`](TelemetryBuilder::build).
287 #[must_use]
288 pub fn notices(&self) -> &[String] {
289 &self.notices
290 }
291
292 /// Where each signal goes, in one line: the transport, the endpoint
293 /// (with any login removed), gzip, the proxy it is sent through, or
294 /// `off`; or why nothing is exported at all. `install_subscriber` logs it
295 /// at startup; a binary with its own subscriber can log it too.
296 #[must_use]
297 pub fn describe(&self) -> String {
298 if self.disabled {
299 return "telemetry: disabled by OTEL_SDK_DISABLED".to_owned();
300 }
301 if self.tracer.is_none() && self.meter.is_none() && self.logger.is_none() {
302 return "telemetry: nothing is exported; set OTEL_EXPORTER_OTLP_ENDPOINT to send \
303 it to a collector, or OTEL_TRACES_EXPORTER=console to print spans"
304 .to_owned();
305 }
306 format!("telemetry: {}", self.report.join("; "))
307 }
308
309 /// Adds to `failed` each signal with exports lost since the last report
310 /// — telemetry that was dropped, which the SDK's own shutdown result does
311 /// not say (`counting.rs`).
312 fn report_failures(&self, failed: &mut Vec<String>) {
313 for (signal, count) in &self.failures {
314 let n = count.swap(0, Ordering::Relaxed);
315 if n > 0 {
316 failed.push(format!(
317 "{}: {n} export(s) failed after retrying and were dropped",
318 signal.name()
319 ));
320 }
321 }
322 }
323
324 /// Exports everything recorded so far, without shutting down.
325 ///
326 /// # Errors
327 ///
328 /// [`TelemetryError::Export`] naming each signal whose flush failed or
329 /// timed out, or whose exports were lost since the last report — see
330 /// [`shutdown`](Self::shutdown).
331 pub fn force_flush(&self) -> Result<(), TelemetryError> {
332 let mut failed = Vec::new();
333 if let Some(p) = &self.tracer
334 && let Err(e) = p.force_flush()
335 {
336 failed.push(format!("traces: {e}"));
337 }
338 if let Some(p) = &self.meter
339 && let Err(e) = p.force_flush()
340 {
341 failed.push(format!("metrics: {e}"));
342 }
343 if let Some(p) = &self.logger
344 && let Err(e) = p.force_flush()
345 {
346 failed.push(format!("logs: {e}"));
347 }
348 self.report_failures(&mut failed);
349 if failed.is_empty() {
350 Ok(())
351 } else {
352 Err(TelemetryError::Export(failed))
353 }
354 }
355
356 /// Flushes and shuts down every provider, then the export runtime.
357 ///
358 /// # Errors
359 ///
360 /// [`TelemetryError::Export`] naming each signal whose shutdown failed
361 /// or timed out, or whose exports were lost since the last report, on
362 /// either transport: an export the exporter gave up on after its retries
363 /// (`opentelemetry-otlp` makes four attempts by default), whose batch the
364 /// SDK then dropped. An attempt refused and then retried successfully is
365 /// not a loss. Termination should not be blocked on it.
366 ///
367 /// The SDK's batch processors log a lost export and their `shutdown`
368 /// returns `Ok` regardless (`opentelemetry_sdk` 0.33.1,
369 /// `trace/span_processor.rs`); the count is this crate's.
370 pub fn shutdown(mut self) -> Result<(), TelemetryError> {
371 self.shutdown_inner()
372 }
373
374 fn shutdown_inner(&mut self) -> Result<(), TelemetryError> {
375 let mut failed = Vec::new();
376 if let Some(p) = self.tracer.take()
377 && let Err(e) = p.shutdown()
378 {
379 failed.push(format!("traces: {e}"));
380 }
381 if let Some(p) = self.meter.take()
382 && let Err(e) = p.shutdown()
383 {
384 failed.push(format!("metrics: {e}"));
385 }
386 if let Some(p) = self.logger.take()
387 && let Err(e) = p.shutdown()
388 {
389 failed.push(format!("logs: {e}"));
390 }
391 drop(self.runtime.take());
392 self.report_failures(&mut failed);
393 if failed.is_empty() {
394 Ok(())
395 } else {
396 Err(TelemetryError::Export(failed))
397 }
398 }
399}
400
401impl Drop for Telemetry {
402 fn drop(&mut self) {
403 let _ = self.shutdown_inner();
404 }
405}
406
407#[cfg(test)]
408mod notice_tests;
409#[cfg(test)]
410mod report_tests;
411#[cfg(test)]
412mod tests;