Skip to main content

a2a_protocol_server/otel/
control.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The control plane's instruments, and the opt-in tenant and agent
5//! dimensions (audit H11; ADR 0038 §4).
6//!
7//! Every label value here is bounded: a constant from
8//! [`crate::metrics::control`], a tenant from the operator's allow-list or
9//! `_OTHER`, an agent name the operator configured. No task, context,
10//! root, job or message id is ever a label (ADR 0034 §4): those belong on
11//! spans, where a per-job view is a trace query, not a series.
12
13use std::sync::Arc;
14
15use opentelemetry::KeyValue;
16use opentelemetry::metrics::{Counter, Meter};
17
18/// What a tenant outside the allow-list is recorded as.
19pub const OTHER_TENANT: &str = "_OTHER";
20
21/// The control plane's counters.
22pub(super) struct Control {
23    pub(super) refusals: Counter<u64>,
24    pub(super) lease_events: Counter<u64>,
25    pub(super) halts: Counter<u64>,
26    pub(super) halt_stopped: Counter<u64>,
27    pub(super) claim_events: Counter<u64>,
28    pub(super) subscribe_wakes: Counter<u64>,
29    pub(super) steering_events: Counter<u64>,
30}
31
32impl Control {
33    pub(super) fn build(meter: &Meter) -> Self {
34        Self {
35            refusals: meter
36                .u64_counter("a2a.server.refusals")
37                .with_description("Requests refused before any work, by cause")
38                .with_unit("{request}")
39                .build(),
40            lease_events: meter
41                .u64_counter("a2a.server.lease.events")
42                .with_description("Task lease events, by event")
43                .with_unit("{event}")
44                .build(),
45            halts: meter
46                .u64_counter("a2a.server.halts")
47                .with_description("Halts and resumes applied, by scope and action")
48                .with_unit("{action}")
49                .build(),
50            halt_stopped: meter
51                .u64_counter("a2a.server.halt.stopped_tasks")
52                .with_description("Running tasks a halt stopped, by scope")
53                .with_unit("{task}")
54                .build(),
55            claim_events: meter
56                .u64_counter("a2a.server.claim.events")
57                .with_description("Turn-claim events, by event")
58                .with_unit("{event}")
59                .build(),
60            subscribe_wakes: meter
61                .u64_counter("a2a.server.subscribe.wakes")
62                .with_description(
63                    "Times a subscribe stream stopped waiting on a task's event log, by cause",
64                )
65                .with_unit("{wake}")
66                .build(),
67            steering_events: meter
68                .u64_counter("a2a.server.steering")
69                .with_description("Steering messages, by how they ended")
70                .with_unit("{message}")
71                .build(),
72        }
73    }
74}
75
76/// Which optional dimensions the metrics carry. Both off by default, so the
77/// series an existing dashboard reads do not change.
78#[derive(Clone, Debug, Default)]
79pub(super) struct Dimensions {
80    /// The tenants recorded by name; any other non-empty tenant is
81    /// [`OTHER_TENANT`]. `None`: no `a2a.tenant` label at all.
82    pub(super) tenants: Option<Arc<[String]>>,
83    /// The `gen_ai.agent.name` every metric carries, when set: the agent
84    /// this handler serves, one value per `OtelMetrics`.
85    pub(super) agent: Option<Arc<str>>,
86}
87
88impl Dimensions {
89    /// The `a2a.tenant` value for `tenant`, when the dimension is on and
90    /// there is a tenant.
91    pub(super) fn tenant(&self, tenant: Option<&str>) -> Option<KeyValue> {
92        let allowed = self.tenants.as_ref()?;
93        let tenant = tenant.filter(|t| !t.is_empty())?;
94        let value = if allowed.iter().any(|a| a == tenant) {
95            tenant.to_owned()
96        } else {
97            OTHER_TENANT.to_owned()
98        };
99        Some(KeyValue::new("a2a.tenant", value))
100    }
101
102    /// Adds the dimensions that are on to `attributes`.
103    pub(super) fn extend(&self, attributes: &mut Vec<KeyValue>, tenant: Option<&str>) {
104        attributes.extend(self.tenant(tenant));
105        if let Some(agent) = &self.agent {
106            attributes.push(KeyValue::new("gen_ai.agent.name", agent.to_string()));
107        }
108    }
109}
110
111impl Control {
112    pub(super) fn refusal(&self, dims: &Dimensions, cause: &str) {
113        let mut attributes = vec![KeyValue::new("cause", cause.to_owned())];
114        let tenant = crate::store::tenant::TenantContext::current();
115        dims.extend(&mut attributes, Some(&tenant));
116        self.refusals.add(1, &attributes);
117    }
118
119    pub(super) fn lease(&self, dims: &Dimensions, event: &str) {
120        let mut attributes = vec![KeyValue::new("event", event.to_owned())];
121        dims.extend(&mut attributes, None);
122        self.lease_events.add(1, &attributes);
123    }
124
125    pub(super) fn halt(&self, dims: &Dimensions, scope: &str, action: &str, stopped: usize) {
126        let mut attributes = vec![
127            KeyValue::new("scope", scope.to_owned()),
128            KeyValue::new("action", action.to_owned()),
129        ];
130        dims.extend(&mut attributes, None);
131        self.halts.add(1, &attributes);
132        if stopped > 0 {
133            attributes.retain(|kv| kv.key.as_str() != "action");
134            self.halt_stopped
135                .add(u64::try_from(stopped).unwrap_or(u64::MAX), &attributes);
136        }
137    }
138
139    pub(super) fn claim(&self, dims: &Dimensions, event: &str) {
140        let mut attributes = vec![KeyValue::new("event", event.to_owned())];
141        dims.extend(&mut attributes, None);
142        self.claim_events.add(1, &attributes);
143    }
144
145    pub(super) fn subscribe_wake(&self, dims: &Dimensions, cause: &str) {
146        let mut attributes = vec![KeyValue::new("cause", cause.to_owned())];
147        dims.extend(&mut attributes, None);
148        self.subscribe_wakes.add(1, &attributes);
149    }
150
151    pub(super) fn steering(&self, dims: &Dimensions, outcome: &str) {
152        let mut attributes = vec![KeyValue::new("outcome", outcome.to_owned())];
153        dims.extend(&mut attributes, None);
154        self.steering_events.add(1, &attributes);
155    }
156}
157
158impl super::OtelMetrics {
159    /// Labels `rpc.server.call.duration`, `a2a.server.executor.duration` and
160    /// `a2a.server.refusals` with `a2a.tenant`: the tenant's name when it is
161    /// one of `allowed`, `_OTHER` for any other tenant, and
162    /// no label for a request with none. Off by default; the series grow by
163    /// at most `allowed.len() + 1` per existing series, which is the bound an
164    /// operator chooses here (audit H11).
165    #[must_use]
166    pub fn with_tenant_dimension<S: Into<String>>(
167        mut self,
168        allowed: impl IntoIterator<Item = S>,
169    ) -> Self {
170        self.dims.tenants = Some(allowed.into_iter().map(Into::into).collect());
171        self
172    }
173
174    /// Labels every `a2a.server.*` instrument this records, and
175    /// `rpc.server.call.duration`, with `gen_ai.agent.name` = `name`: for a
176    /// process serving several agents, one `OtelMetrics` per handler. Off by
177    /// default.
178    #[must_use]
179    pub fn with_agent_name(mut self, name: impl Into<String>) -> Self {
180        self.dims.agent = Some(Arc::from(name.into()));
181        self
182    }
183}