1mod builder;
54mod control;
55mod global;
56mod instrument;
57#[cfg(feature = "otlp")]
58mod pipeline;
59#[cfg(feature = "otlp")]
60mod telemetry;
61
62use std::sync::atomic::{AtomicU64, Ordering};
63use std::time::Duration;
64
65use opentelemetry::KeyValue;
66use opentelemetry::metrics::{Counter, Gauge, Histogram, Meter};
67
68use crate::metrics::{ConnectionPoolStats, Metrics, RpcCall};
69
70pub use builder::OtelMetricsBuilder;
71pub(crate) use global::GlobalOtelMetrics;
72pub(crate) use instrument::GlobalInstrument;
73#[cfg(feature = "otlp")]
74#[allow(deprecated)] pub use pipeline::{init_otlp_pipeline, init_otlp_pipeline_with_endpoint};
76#[cfg(feature = "otel-prometheus")]
77pub use telemetry::PrometheusScrape;
78#[cfg(feature = "otlp")]
79pub use telemetry::{
80 ConsoleFormat, LANGFUSE_SELF_HOSTED, Langfuse, OtlpCompression, OtlpProtocol, Telemetry,
81 TelemetryBuilder, TelemetryError,
82};
83
84pub struct OtelMetrics {
113 rpc_call_histogram: Histogram<f64>,
114 request_counter: Counter<u64>,
115 response_counter: Counter<u64>,
116 error_counter: Counter<u64>,
117 latency_histogram: Histogram<f64>,
118 queue_depth_gauge: Gauge<u64>,
119 pool_active_gauge: Gauge<u64>,
120 pool_idle_gauge: Gauge<u64>,
121 pool_created_counter: Counter<u64>,
122 pool_closed_counter: Counter<u64>,
123 pool_created_seen: AtomicU64,
126 pool_closed_seen: AtomicU64,
127 persistence_error_counter: Counter<u64>,
128 store_retry_counter: Counter<u64>,
129 push_delivery_counter: Counter<u64>,
130 executor_histogram: Histogram<f64>,
131 control: control::Control,
133 dims: control::Dimensions,
135}
136
137impl std::fmt::Debug for OtelMetrics {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.debug_struct("OtelMetrics").finish_non_exhaustive()
140 }
141}
142
143impl OtelMetrics {
144 #[must_use]
148 pub fn from_meter(meter: &Meter) -> Self {
149 let request_counter = meter
150 .u64_counter("a2a.server.requests")
151 .with_description("Total number of inbound A2A requests")
152 .with_unit("{request}")
153 .build();
154
155 let response_counter = meter
156 .u64_counter("a2a.server.responses")
157 .with_description("Total number of outbound A2A responses")
158 .with_unit("{response}")
159 .build();
160
161 let error_counter = meter
162 .u64_counter("a2a.server.errors")
163 .with_description("Total number of A2A request errors")
164 .with_unit("{error}")
165 .build();
166
167 let (rpc_call_histogram, latency_histogram) = Self::duration_instruments(meter);
168
169 let queue_depth_gauge = meter
170 .u64_gauge("a2a.server.queue_depth")
171 .with_description("Number of active event queues")
172 .with_unit("{queue}")
173 .build();
174
175 let (pool_active_gauge, pool_idle_gauge, pool_created_counter, pool_closed_counter) =
176 Self::pool_instruments(meter);
177
178 let (persistence_error_counter, push_delivery_counter, store_retry_counter) =
179 Self::failure_instruments(meter);
180
181 let executor_histogram = Self::executor_instrument(meter);
182
183 Self {
184 rpc_call_histogram,
185 request_counter,
186 response_counter,
187 error_counter,
188 latency_histogram,
189 queue_depth_gauge,
190 pool_active_gauge,
191 pool_idle_gauge,
192 pool_created_counter,
193 pool_closed_counter,
194 pool_created_seen: AtomicU64::new(0),
195 pool_closed_seen: AtomicU64::new(0),
196 persistence_error_counter,
197 store_retry_counter,
198 push_delivery_counter,
199 executor_histogram,
200 control: control::Control::build(meter),
201 dims: control::Dimensions::default(),
202 }
203 }
204
205 fn duration_instruments(meter: &Meter) -> (Histogram<f64>, Histogram<f64>) {
207 let rpc_call_histogram = meter
208 .f64_histogram("rpc.server.call.duration")
209 .with_description("Measures the duration of an incoming Remote Procedure Call (RPC).")
210 .with_unit("s")
211 .with_boundaries(RPC_DURATION_BUCKETS.to_vec())
212 .build();
213
214 let latency_histogram = meter
218 .f64_histogram("a2a.server.request.duration")
219 .with_description("Duration of an inbound A2A request")
220 .with_unit("s")
221 .with_boundaries(RPC_DURATION_BUCKETS.to_vec())
222 .build();
223
224 (rpc_call_histogram, latency_histogram)
225 }
226
227 fn executor_instrument(meter: &Meter) -> Histogram<f64> {
233 meter
234 .f64_histogram("a2a.server.executor.duration")
235 .with_description(
236 "How long an agent executor's run took, by how it ended \
237 (completed / error / budget_exhausted / canceled / aborted)",
238 )
239 .with_unit("s")
240 .with_boundaries(RPC_DURATION_BUCKETS.to_vec())
241 .build()
242 }
243
244 fn pool_instruments(meter: &Meter) -> (Gauge<u64>, Gauge<u64>, Counter<u64>, Counter<u64>) {
247 let pool_active_gauge = meter
248 .u64_gauge("a2a.server.pool.active")
249 .with_description("Number of active (in-use) HTTP connections")
250 .with_unit("{connection}")
251 .build();
252
253 let pool_idle_gauge = meter
254 .u64_gauge("a2a.server.pool.idle")
255 .with_description("Number of idle HTTP connections")
256 .with_unit("{connection}")
257 .build();
258
259 let pool_created_counter = meter
260 .u64_counter("a2a.server.pool.created")
261 .with_description("Total HTTP connections created since process start")
262 .with_unit("{connection}")
263 .build();
264
265 let pool_closed_counter = meter
266 .u64_counter("a2a.server.pool.closed")
267 .with_description("HTTP connections closed due to errors or timeouts")
268 .with_unit("{connection}")
269 .build();
270 (
271 pool_active_gauge,
272 pool_idle_gauge,
273 pool_created_counter,
274 pool_closed_counter,
275 )
276 }
277
278 fn failure_instruments(meter: &Meter) -> (Counter<u64>, Counter<u64>, Counter<u64>) {
286 let persistence_error_counter = meter
287 .u64_counter("a2a.server.persistence_errors")
288 .with_description(
289 "Task writes the background processor could not persist. \
290 Non-zero means data loss: the streaming client already \
291 received the event.",
292 )
293 .with_unit("{error}")
294 .build();
295
296 let push_delivery_counter = meter
297 .u64_counter("a2a.server.push_deliveries")
298 .with_description(
299 "Push notification delivery attempts, by outcome \
300 (delivered / failed / timeout / timeout_truncated)",
301 )
302 .with_unit("{delivery}")
303 .build();
304
305 let store_retry_counter = meter
306 .u64_counter("a2a.server.store_retries")
307 .with_description(
308 "Store operations run again after a failure that passed: the \
309 store said not now, or a connection was lost. Nothing was \
310 lost; a rising rate is a store degrading.",
311 )
312 .with_unit("{retry}")
313 .build();
314 (
315 persistence_error_counter,
316 push_delivery_counter,
317 store_retry_counter,
318 )
319 }
320}
321
322impl Metrics for OtelMetrics {
323 fn on_request(&self, method: &str) {
324 self.request_counter
325 .add(1, &[KeyValue::new("method", method.to_owned())]);
326 }
327
328 fn on_response(&self, method: &str) {
329 self.response_counter
330 .add(1, &[KeyValue::new("method", method.to_owned())]);
331 }
332
333 fn on_error(&self, method: &str, error: &str) {
334 self.error_counter.add(
335 1,
336 &[
337 KeyValue::new("method", method.to_owned()),
338 KeyValue::new("error", error.to_owned()),
339 ],
340 );
341 }
342
343 fn on_latency(&self, method: &str, duration: Duration) {
344 self.latency_histogram.record(
345 duration.as_secs_f64(),
346 &[KeyValue::new("method", method.to_owned())],
347 );
348 }
349
350 fn on_queue_depth_change(&self, active_queues: usize) {
351 #[allow(clippy::cast_possible_truncation)]
352 self.queue_depth_gauge.record(active_queues as u64, &[]);
353 }
354
355 fn on_persistence_error(&self, operation: &str, error_kind: &str) {
356 self.persistence_error_counter.add(
357 1,
358 &[
359 KeyValue::new("operation", operation.to_owned()),
360 KeyValue::new("error", error_kind.to_owned()),
361 ],
362 );
363 }
364
365 fn on_store_retry(&self, operation: &str, cause: &str) {
366 self.store_retry_counter.add(
367 1,
368 &[
369 KeyValue::new("operation", operation.to_owned()),
370 KeyValue::new("cause", cause.to_owned()),
371 ],
372 );
373 }
374
375 fn on_push_delivery(&self, outcome: &str) {
376 self.push_delivery_counter
377 .add(1, &[KeyValue::new("outcome", outcome.to_owned())]);
378 }
379
380 fn on_connection_pool_stats(&self, stats: &ConnectionPoolStats) {
381 self.pool_active_gauge
382 .record(u64::from(stats.active_connections), &[]);
383 self.pool_idle_gauge
384 .record(u64::from(stats.idle_connections), &[]);
385 let created = self
391 .pool_created_seen
392 .fetch_max(stats.total_connections_created, Ordering::Relaxed);
393 self.pool_created_counter
394 .add(stats.total_connections_created.saturating_sub(created), &[]);
395 let closed = self
396 .pool_closed_seen
397 .fetch_max(stats.connections_closed, Ordering::Relaxed);
398 self.pool_closed_counter
399 .add(stats.connections_closed.saturating_sub(closed), &[]);
400 }
401
402 fn on_rpc_call(&self, call: &RpcCall<'_>) {
403 let mut attributes = Vec::with_capacity(6);
404 attributes.push(KeyValue::new("rpc.system.name", call.system.to_owned()));
405 if let Some(method) = call.method {
406 attributes.push(KeyValue::new("rpc.method", method.to_owned()));
407 }
408 if let Some(status) = call.status_code {
409 attributes.push(KeyValue::new("rpc.status_code", status.to_owned()));
410 }
411 if let Some(error) = call.error_type {
412 attributes.push(KeyValue::new("error.type", error.to_owned()));
413 }
414 self.dims.extend(&mut attributes, call.tenant);
415 self.rpc_call_histogram
416 .record(call.duration.as_secs_f64(), &attributes);
417 }
418
419 fn on_executor_run(&self, outcome: &str, duration: Duration) {
420 let mut attributes = vec![KeyValue::new("outcome", outcome.to_owned())];
421 let tenant = crate::store::tenant::TenantContext::current();
422 self.dims.extend(&mut attributes, Some(&tenant));
423 self.executor_histogram
424 .record(duration.as_secs_f64(), &attributes);
425 }
426
427 fn on_refusal(&self, cause: &str) {
428 self.control.refusal(&self.dims, cause);
429 }
430
431 fn on_lease(&self, event: &str) {
432 self.control.lease(&self.dims, event);
433 }
434
435 fn on_halt(&self, scope: &str, action: &str, stopped: usize) {
436 self.control.halt(&self.dims, scope, action, stopped);
437 }
438
439 fn on_steering(&self, outcome: &str) {
440 self.control.steering(&self.dims, outcome);
441 }
442
443 fn on_claim(&self, event: &str) {
444 self.control.claim(&self.dims, event);
445 }
446
447 fn on_subscribe_wake(&self, cause: &str) {
448 self.control.subscribe_wake(&self.dims, cause);
449 }
450}
451
452pub const RPC_DURATION_BUCKETS: [f64; 13] = [
460 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 50.0, 100.0,
461];
462
463#[cfg(test)]
466mod control_tests;
467#[cfg(test)]
468mod rpc_tests;
469#[cfg(test)]
470pub(crate) mod test_reader;
471#[cfg(test)]
472mod tests;