a2a_protocol_client/balance.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Calls spread over several endpoints of one agent, with failing ones
5//! ejected and idempotent calls optionally hedged (ADR 0050, audit H12).
6//!
7//! A client built with [`ClientBuilder::new(url)`](crate::ClientBuilder::new)
8//! sends every call to `url`, and over `https://` all of them share one
9//! HTTP/2 connection. Behind a layer-4 balancer, which picks a replica per
10//! connection, they all reach one replica. With
11//! [`ClientBuilder::with_balancing`](crate::ClientBuilder::with_balancing)
12//! a client sends each call to the endpoint of a set with the fewest calls
13//! in flight, keeps an endpoint that keeps failing out of rotation for a
14//! while, and can send a slow idempotent call to a second endpoint.
15//!
16//! ```no_run
17//! use std::time::Duration;
18//! use a2a_protocol_client::ClientBuilder;
19//! use a2a_protocol_client::balance::{BalancePolicy, DnsEndpoints, Hedge};
20//!
21//! # fn main() -> a2a_protocol_client::ClientResult<()> {
22//! // A Kubernetes headless Service: one name, one address per pod.
23//! let url = "https://agent.ns.svc.cluster.local:8443";
24//! let client = ClientBuilder::new(url)
25//! .with_balancing(
26//! DnsEndpoints::new(url)?,
27//! BalancePolicy::new().with_hedge(Hedge::after(Duration::from_millis(200))),
28//! )
29//! .build()?;
30//! # drop(client);
31//! # Ok(())
32//! # }
33//! ```
34
35mod members;
36mod selection;
37mod transport;
38
39use std::future::Future;
40use std::net::SocketAddr;
41use std::pin::Pin;
42use std::time::Duration;
43
44use a2a_protocol_types::AgentCard;
45
46use crate::error::{ClientError, ClientResult};
47use crate::retry::RetryBudget;
48
49pub(crate) use transport::BalancedTransport;
50
51/// How often [`DnsEndpoints`] resolves its name again, by default.
52pub const DEFAULT_DNS_REFRESH: Duration = Duration::from_secs(30);
53
54/// One endpoint of an agent: a URL, optionally pinned to a socket address.
55///
56/// A pinned endpoint is still named by its URL (the `Host` header, TLS
57/// server name and certificate check use the URL's host); only the TCP
58/// connection goes to the address. Pinning needs the `tls-rustls` feature.
59#[derive(Clone, Debug, PartialEq, Eq, Hash)]
60pub struct Endpoint {
61 url: String,
62 addr: Option<SocketAddr>,
63}
64
65impl Endpoint {
66 /// An endpoint at `url`, resolved the usual way.
67 #[must_use]
68 pub fn new(url: impl Into<String>) -> Self {
69 Self {
70 url: url.into(),
71 addr: None,
72 }
73 }
74
75 /// An endpoint named by `url` whose connections go to `addr`.
76 #[must_use]
77 pub fn pinned(url: impl Into<String>, addr: SocketAddr) -> Self {
78 Self {
79 url: url.into(),
80 addr: Some(addr),
81 }
82 }
83
84 /// The URL.
85 #[must_use]
86 pub fn url(&self) -> &str {
87 &self.url
88 }
89
90 /// The address connections go to, when pinned.
91 #[must_use]
92 pub const fn addr(&self) -> Option<SocketAddr> {
93 self.addr
94 }
95}
96
97/// The boxed future an [`EndpointSource`] returns.
98pub type EndpointsFuture<'a> =
99 Pin<Box<dyn Future<Output = ClientResult<Vec<Endpoint>>> + Send + 'a>>;
100
101/// Where a balanced client's endpoints come from.
102///
103/// [`endpoints`](Self::endpoints) is asked on the client's first call and
104/// again once [`refresh_every`](Self::refresh_every) has passed since the
105/// last answer, by one caller at a time while the others use the set they
106/// have. An error, or an empty set, keeps the set there was.
107pub trait EndpointSource: Send + Sync + 'static {
108 /// The endpoints now.
109 fn endpoints(&self) -> EndpointsFuture<'_>;
110
111 /// How long an answer holds; `None`: for ever (the default).
112 fn refresh_every(&self) -> Option<Duration> {
113 None
114 }
115}
116
117/// A fixed set of endpoints.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct StaticEndpoints {
120 endpoints: Vec<Endpoint>,
121}
122
123impl StaticEndpoints {
124 /// The replicas at `urls`.
125 #[must_use]
126 pub fn new<I, S>(urls: I) -> Self
127 where
128 I: IntoIterator<Item = S>,
129 S: Into<String>,
130 {
131 Self {
132 endpoints: urls.into_iter().map(Endpoint::new).collect(),
133 }
134 }
135
136 /// Exactly these endpoints, pinned or not.
137 #[must_use]
138 pub const fn from_endpoints(endpoints: Vec<Endpoint>) -> Self {
139 Self { endpoints }
140 }
141
142 /// The URLs of `card`'s interfaces of `binding` (matched as the builder
143 /// matches bindings: ignoring case, `REST` for `HTTP+JSON`) for this
144 /// SDK's protocol major, with the tenant of the first of them; for an
145 /// agent that publishes one interface per replica.
146 ///
147 /// # Errors
148 ///
149 /// [`ClientError::Config`] when the card has no such interface.
150 pub fn from_card(card: &AgentCard, binding: &str) -> ClientResult<Self> {
151 use crate::builder::selection::{canonical_binding, is_compatible};
152 let wanted = canonical_binding(binding);
153 let matching: Vec<_> = card
154 .supported_interfaces
155 .iter()
156 .filter(|i| {
157 wanted.is_some()
158 && canonical_binding(&i.protocol_binding) == wanted
159 && is_compatible(&i.protocol_version)
160 })
161 .collect();
162 let Some(first) = matching.first() else {
163 return Err(ClientError::Config(format!(
164 "the agent card has no {binding} interface for this SDK's protocol major"
165 )));
166 };
167 let tenant = first.tenant.clone();
168 Ok(Self::new(
169 matching
170 .iter()
171 .filter(|i| i.tenant == tenant)
172 .map(|i| i.url.clone()),
173 ))
174 }
175
176 /// The endpoints.
177 #[must_use]
178 pub fn endpoints(&self) -> &[Endpoint] {
179 &self.endpoints
180 }
181}
182
183impl EndpointSource for StaticEndpoints {
184 fn endpoints(&self) -> EndpointsFuture<'_> {
185 let endpoints = self.endpoints.clone();
186 Box::pin(async move { Ok(endpoints) })
187 }
188}
189
190/// Every address a URL's host resolves to, one pinned endpoint each,
191/// resolved again every 30 s: a Kubernetes headless Service, or any name
192/// with one address per replica.
193///
194/// Resolution is the system's (`getaddrinfo`), which reports no record
195/// lifetimes; [`with_refresh_every`](Self::with_refresh_every) sets how long
196/// an answer is kept. A host that is an IP address gives one endpoint. Over
197/// a proxy, the proxy resolves the name, so every endpoint reaches whatever
198/// replica the proxy picks.
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub struct DnsEndpoints {
201 url: String,
202 host: String,
203 port: u16,
204 refresh: Duration,
205}
206
207impl DnsEndpoints {
208 /// The addresses of `url`'s host.
209 ///
210 /// # Errors
211 ///
212 /// [`ClientError::InvalidEndpoint`] when `url` has no host.
213 pub fn new(url: impl Into<String>) -> ClientResult<Self> {
214 let url = url.into();
215 let uri: hyper::Uri = url
216 .parse()
217 .map_err(|e| ClientError::InvalidEndpoint(format!("{url}: {e}")))?;
218 let host = uri
219 .host()
220 .ok_or_else(|| ClientError::InvalidEndpoint(format!("{url} has no host")))?
221 .trim_start_matches('[')
222 .trim_end_matches(']')
223 .to_owned();
224 let port = uri.port_u16().unwrap_or_else(|| {
225 if uri.scheme_str() == Some("https") {
226 443
227 } else {
228 80
229 }
230 });
231 Ok(Self {
232 url,
233 host,
234 port,
235 refresh: DEFAULT_DNS_REFRESH,
236 })
237 }
238
239 /// How long an answer is kept before the name is resolved again.
240 /// Default: [`DEFAULT_DNS_REFRESH`].
241 #[must_use]
242 pub const fn with_refresh_every(mut self, every: Duration) -> Self {
243 self.refresh = every;
244 self
245 }
246}
247
248impl EndpointSource for DnsEndpoints {
249 fn endpoints(&self) -> EndpointsFuture<'_> {
250 Box::pin(async move {
251 if self.host.parse::<std::net::IpAddr>().is_ok() {
252 return Ok(vec![Endpoint::new(self.url.clone())]);
253 }
254 let addrs = tokio::net::lookup_host((self.host.as_str(), self.port))
255 .await
256 .map_err(|e| ClientError::HttpClient(format!("resolving {}: {e}", self.host)))?;
257 // A repeated address is one member of the set: the set drops
258 // repeated endpoints.
259 Ok(addrs
260 .map(|addr| Endpoint::pinned(self.url.clone(), addr))
261 .collect())
262 })
263 }
264
265 fn refresh_every(&self) -> Option<Duration> {
266 Some(self.refresh)
267 }
268}
269
270/// When an endpoint is taken out of rotation (ADR 0050 decision 3), and, on
271/// an [`HttpPool`](crate::HttpPool), when its circuit opens.
272///
273/// `consecutive_failures` failures in a row (a connection error, a timeout,
274/// `502`, `503`, `504`) eject an endpoint for `base`; the n-th ejection in a
275/// row lasts `base * 2^(n-1)`, at most `max`. When an ejection ends, one call
276/// is let through: its success returns the endpoint, its failure ejects it
277/// again.
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279#[non_exhaustive]
280pub struct Ejection {
281 /// Failures in a row that eject. At least 1.
282 pub consecutive_failures: u32,
283 /// How long the first ejection lasts.
284 pub base: Duration,
285 /// The longest an ejection lasts.
286 pub max: Duration,
287}
288
289impl Default for Ejection {
290 /// Five failures in a row; 30 s, doubling to at most 300 s.
291 fn default() -> Self {
292 Self {
293 consecutive_failures: 5,
294 base: Duration::from_secs(30),
295 max: Duration::from_secs(300),
296 }
297 }
298}
299
300impl Ejection {
301 /// Ejection after `failures` in a row (at least 1), for `base` doubling
302 /// up to `max` (at least `base`).
303 #[must_use]
304 pub fn new(failures: u32, base: Duration, max: Duration) -> Self {
305 Self {
306 consecutive_failures: failures.max(1),
307 base,
308 max: max.max(base),
309 }
310 }
311}
312
313/// Opt-in hedging: a second copy of a slow idempotent call (ADR 0050
314/// decision 5).
315///
316/// A unary call that has had no answer after `delay` is sent to a second
317/// endpoint as well, and the first answer that is not an error is returned;
318/// the other call is dropped. Only idempotent methods are hedged (`GetTask`,
319/// `ListTasks`, `CancelTask`, `GetExtendedAgentCard`, the push-config reads
320/// and delete), and a `SendMessage` that carries an idempotency key to a
321/// peer known to honour it; a send without a key never is, and nor is a
322/// stream. Each hedge is paid from `budget`.
323#[derive(Clone, Copy, Debug, PartialEq)]
324#[non_exhaustive]
325pub struct Hedge {
326 /// How long a call waits for an answer before its copy is sent.
327 pub delay: Duration,
328 /// What pays for the copies: by default 5% of calls, with a reserve of
329 /// one.
330 pub budget: RetryBudget,
331}
332
333impl Hedge {
334 /// Hedge after `delay`, with the default budget.
335 #[must_use]
336 pub const fn after(delay: Duration) -> Self {
337 Self {
338 delay,
339 budget: RetryBudget::new(0.05, 0.0).with_reserve(1.0),
340 }
341 }
342
343 /// Pays for the copies from `budget`.
344 #[must_use]
345 pub const fn with_budget(mut self, budget: RetryBudget) -> Self {
346 self.budget = budget;
347 self
348 }
349}
350
351/// How a balanced client chooses and ejects endpoints.
352#[derive(Clone, Copy, Debug, PartialEq)]
353#[non_exhaustive]
354pub struct BalancePolicy {
355 /// When an endpoint is taken out of rotation; `None`: never. Default:
356 /// [`Ejection::default`]. A client on an [`HttpPool`](crate::HttpPool)
357 /// uses the pool's instead (`HttpPoolBuilder::with_ejection`).
358 pub ejection: Option<Ejection>,
359 /// The largest share of the set, in percent, kept out of rotation at
360 /// once (rounded down); past it the endpoints whose ejection ends soonest
361 /// are used. Default 50; 100 lets every endpoint be ejected, and calls
362 /// then fail with [`ClientError::CircuitOpen`].
363 pub max_ejected_percent: u8,
364 /// Hedging; `None` (the default): off.
365 pub hedge: Option<Hedge>,
366 /// Whether [`with_ejection`](Self::with_ejection) or
367 /// [`without_ejection`](Self::without_ejection) was called, which a
368 /// pool's own policy conflicts with.
369 ejection_set: bool,
370}
371
372impl Default for BalancePolicy {
373 fn default() -> Self {
374 Self::new()
375 }
376}
377
378impl BalancePolicy {
379 /// Ejection on with its defaults, at most half the set ejected, no
380 /// hedging.
381 #[must_use]
382 pub fn new() -> Self {
383 Self {
384 ejection: Some(Ejection::default()),
385 max_ejected_percent: 50,
386 hedge: None,
387 ejection_set: false,
388 }
389 }
390
391 /// Ejects as `ejection` says.
392 #[must_use]
393 pub const fn with_ejection(mut self, ejection: Ejection) -> Self {
394 self.ejection = Some(ejection);
395 self.ejection_set = true;
396 self
397 }
398
399 /// Never ejects.
400 #[must_use]
401 pub const fn without_ejection(mut self) -> Self {
402 self.ejection = None;
403 self.ejection_set = true;
404 self
405 }
406
407 /// The largest share of the set kept out at once, in percent (at most
408 /// 100).
409 #[must_use]
410 pub fn with_max_ejected_percent(mut self, percent: u8) -> Self {
411 self.max_ejected_percent = percent.min(100);
412 self
413 }
414
415 /// Hedges idempotent calls as `hedge` says.
416 #[must_use]
417 pub const fn with_hedge(mut self, hedge: Hedge) -> Self {
418 self.hedge = Some(hedge);
419 self
420 }
421
422 /// Whether the caller chose the ejection policy.
423 pub(crate) const fn ejection_set(&self) -> bool {
424 self.ejection_set
425 }
426}
427
428#[cfg(test)]
429mod tests;