Skip to main content

a2a_protocol_client/
origin.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Per-origin state: calls in flight, ejection (the circuit breaker), an
5//! in-flight cap and a retry-budget ledger (ADR 0032 decision 5, ADR 0050
6//! decision 6).
7//!
8//! An origin is a scheme, host and port, and the address an endpoint is
9//! pinned to, if any. Its state is held by an [`HttpPool`](crate::HttpPool),
10//! shared by every client of the pool, or by one balanced client for itself.
11//!
12//! # Ejection
13//!
14//! `consecutive_failures` failures in a row eject the origin; the n-th
15//! ejection in a row lasts `base * 2^(n-1)`, capped at `max`. When it ends,
16//! one call is let through as a probe: its success closes the origin and its
17//! failure ejects it again. A balancer that must keep an ejected origin in
18//! rotation sends it *forced* calls: a success closes it, a failure changes
19//! nothing (it is already out).
20
21pub mod transport;
22
23use std::collections::HashMap;
24use std::sync::atomic::{AtomicUsize, Ordering};
25use std::sync::{Arc, Mutex, PoisonError};
26use std::time::Duration;
27
28use tokio::sync::{OwnedSemaphorePermit, Semaphore};
29use tokio::time::Instant;
30
31use crate::balance::Ejection;
32use crate::error::ClientError;
33use crate::retry::RetryBudget;
34use crate::retry::budget::Ledger;
35
36pub use transport::OriginTransport;
37
38/// How many origins a registry keeps before it forgets idle, healthy ones.
39const PRUNE_ABOVE: usize = 1024;
40
41/// What one call to an origin is, for its ejection state.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum Ticket {
44    /// An ordinary call to an origin in rotation.
45    Normal,
46    /// The one call let through when an ejection has ended.
47    Probe,
48    /// A call to an ejected origin a balancer kept in rotation.
49    Forced,
50}
51
52/// What a call's result says about the origin.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum Outcome {
55    /// The origin answered (an error answer included).
56    Success,
57    /// The origin could not be reached or could not answer.
58    Failure,
59    /// Nothing was learned: the call was refused locally, never sent, or
60    /// cancelled.
61    Neutral,
62}
63
64/// What `result` says about the origin it came from (ADR 0050 decision 3).
65pub const fn outcome_of<T>(result: &Result<T, ClientError>) -> Outcome {
66    match result {
67        Ok(_) => Outcome::Success,
68        Err(e) => match e {
69            ClientError::Http(_) | ClientError::HttpClient(_) | ClientError::Timeout(_) => {
70                Outcome::Failure
71            }
72            ClientError::UnexpectedStatus {
73                status: 502..=504, ..
74            } => Outcome::Failure,
75            ClientError::TooManyPendingRequests { .. }
76            | ClientError::CircuitOpen { .. }
77            | ClientError::Config(_)
78            | ClientError::InvalidEndpoint(_)
79            | ClientError::InsecureTransport(_)
80            | ClientError::InsecureWebhook(_)
81            | ClientError::CapabilityNotDeclared { .. }
82            | ClientError::InvalidAuthScheme(_) => Outcome::Neutral,
83            _ => Outcome::Success,
84        },
85    }
86}
87
88/// The ejection state of one origin.
89#[derive(Debug, Default)]
90struct Health {
91    failures: u32,
92    ejected_until: Option<Instant>,
93    ejections: u32,
94    probing: bool,
95}
96
97/// What a recorded outcome changed, for the log.
98enum Change {
99    None,
100    Closed,
101    Ejected(Duration),
102}
103
104/// Where an origin stands for a balancer choosing among several.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum Standing {
107    /// In rotation; a call to it is the ticket given.
108    Available(Ticket),
109    /// Ejected until then (or, with `None`, while its probe is running).
110    Ejected(Option<Instant>),
111}
112
113/// The state of one origin.
114pub struct OriginState {
115    key: String,
116    ejection: Option<Ejection>,
117    health: Mutex<Health>,
118    in_flight: AtomicUsize,
119    cap: Option<(Arc<Semaphore>, usize)>,
120    budget: Option<Ledger>,
121}
122
123impl OriginState {
124    fn new(
125        key: String,
126        ejection: Option<Ejection>,
127        cap: Option<usize>,
128        budget: Option<RetryBudget>,
129    ) -> Self {
130        Self {
131            key,
132            ejection,
133            health: Mutex::new(Health::default()),
134            in_flight: AtomicUsize::new(0),
135            cap: cap.map(|n| (Arc::new(Semaphore::new(n)), n)),
136            budget: budget.map(Ledger::new),
137        }
138    }
139
140    fn health(&self) -> std::sync::MutexGuard<'_, Health> {
141        self.health.lock().unwrap_or_else(PoisonError::into_inner)
142    }
143
144    /// Calls in flight to this origin (a stream counts until it is dropped).
145    pub fn in_flight(&self) -> usize {
146        self.in_flight.load(Ordering::SeqCst)
147    }
148
149    /// Where the origin stands at `now`. Taking a probe slot is a side
150    /// effect: `Available(Probe)` claims it, so only one caller gets it.
151    pub fn standing(&self, now: Instant) -> Standing {
152        // Without a policy nothing is ever ejected, and this is the first arm.
153        let mut health = self.health();
154        match health.ejected_until {
155            None => Standing::Available(Ticket::Normal),
156            Some(until) if now < until => Standing::Ejected(Some(until)),
157            Some(_) if health.probing => Standing::Ejected(None),
158            Some(_) => {
159                health.probing = true;
160                drop(health);
161                Standing::Available(Ticket::Probe)
162            }
163        }
164    }
165
166    /// Whether the origin is out of rotation at `now` (ejected, or ended
167    /// and its probe running), without claiming anything.
168    pub fn is_ejected(&self, now: Instant) -> bool {
169        let health = self.health();
170        health
171            .ejected_until
172            .is_some_and(|until| now < until || health.probing)
173    }
174
175    /// When the current ejection ends; `None` when not ejected.
176    pub fn ejected_until(&self) -> Option<Instant> {
177        self.health().ejected_until
178    }
179
180    /// Hands back a probe slot claimed by [`standing`](Self::standing) and
181    /// not used.
182    pub fn release_probe(&self) {
183        self.health().probing = false;
184    }
185
186    /// Admits a call to an origin used on its own (not balanced): refused
187    /// with [`ClientError::CircuitOpen`] while it is ejected.
188    pub fn admit(&self, now: Instant) -> Result<Ticket, ClientError> {
189        match self.standing(now) {
190            Standing::Available(ticket) => Ok(ticket),
191            Standing::Ejected(until) => Err(ClientError::CircuitOpen {
192                origin: self.key.clone(),
193                retry_after: until.map(|until| until.saturating_duration_since(now)),
194            }),
195        }
196    }
197
198    /// Starts a call under `ticket`: takes a place under the in-flight cap,
199    /// if any, and counts the call in flight until the guard is dropped.
200    ///
201    /// # Errors
202    ///
203    /// [`ClientError::TooManyPendingRequests`] when the cap is reached; a
204    /// probe slot the ticket held is handed back.
205    pub fn enter(self: &Arc<Self>, ticket: Ticket) -> Result<CallGuard, ClientError> {
206        let permit = match &self.cap {
207            Some((sem, limit)) => {
208                let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
209                    if ticket == Ticket::Probe {
210                        self.release_probe();
211                    }
212                    return Err(ClientError::TooManyPendingRequests { limit: *limit });
213                };
214                Some(permit)
215            }
216            None => None,
217        };
218        self.in_flight.fetch_add(1, Ordering::SeqCst);
219        Ok(CallGuard {
220            state: Arc::clone(self),
221            ticket,
222            recorded: false,
223            permit,
224        })
225    }
226
227    /// Records what a call under `ticket` ended in.
228    fn record(&self, ticket: Ticket, outcome: Outcome, now: Instant) {
229        let Some(policy) = self.ejection else {
230            return;
231        };
232        let mut health = self.health();
233        let change = Self::apply(&mut health, ticket, outcome, policy, now);
234        drop(health);
235        match change {
236            Change::None => {}
237            Change::Closed => {
238                trace_info!(origin = %self.key, "origin back in rotation");
239            }
240            Change::Ejected(_lasts) => {
241                trace_warn!(origin = %self.key, ?_lasts, "origin ejected after failing in a row");
242            }
243        }
244    }
245
246    /// The state machine: what `outcome` of a call under `ticket` does to
247    /// `health`.
248    fn apply(
249        health: &mut Health,
250        ticket: Ticket,
251        outcome: Outcome,
252        policy: Ejection,
253        now: Instant,
254    ) -> Change {
255        if ticket == Ticket::Probe {
256            health.probing = false;
257        }
258        match (ticket, outcome) {
259            (_, Outcome::Neutral) | (Ticket::Forced, Outcome::Failure) => Change::None,
260            (Ticket::Normal, Outcome::Success) => {
261                health.failures = 0;
262                Change::None
263            }
264            (Ticket::Probe | Ticket::Forced, Outcome::Success) => {
265                let was_ejected = health.ejected_until.is_some();
266                *health = Health::default();
267                if was_ejected {
268                    Change::Closed
269                } else {
270                    Change::None
271                }
272            }
273            (Ticket::Normal, Outcome::Failure) => {
274                if health.ejected_until.is_some() {
275                    return Change::None;
276                }
277                health.failures += 1;
278                if health.failures < policy.consecutive_failures {
279                    return Change::None;
280                }
281                Change::Ejected(Self::eject(health, policy, now))
282            }
283            (Ticket::Probe, Outcome::Failure) => Change::Ejected(Self::eject(health, policy, now)),
284        }
285    }
286
287    /// Ejects the origin for its next ejection's length, which it returns.
288    fn eject(health: &mut Health, policy: Ejection, now: Instant) -> Duration {
289        health.ejections = health.ejections.saturating_add(1);
290        let lasts = ejection_length(policy, health.ejections);
291        health.ejected_until = Some(now + lasts);
292        health.failures = 0;
293        lasts
294    }
295
296    /// The pool's retry ledger for this origin, if it has one.
297    pub const fn budget(&self) -> Option<&Ledger> {
298        self.budget.as_ref()
299    }
300
301    /// A snapshot for [`HttpPool::origins`](crate::HttpPool::origins).
302    pub fn snapshot(&self, now: Instant) -> OriginSnapshot {
303        let health = self.health();
304        OriginSnapshot {
305            origin: self.key.clone(),
306            in_flight: self.in_flight(),
307            ejected_for: health
308                .ejected_until
309                .map(|until| until.saturating_duration_since(now)),
310            consecutive_failures: health.failures,
311            consecutive_ejections: health.ejections,
312        }
313    }
314}
315
316impl std::fmt::Debug for OriginState {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        f.debug_struct("OriginState")
319            .field("origin", &self.key)
320            .field("in_flight", &self.in_flight())
321            .field("health", &*self.health())
322            .finish_non_exhaustive()
323    }
324}
325
326/// How long the `n`-th ejection in a row lasts: `base * 2^(n-1)`, at most
327/// `max`.
328pub fn ejection_length(policy: Ejection, n: u32) -> Duration {
329    let doublings = n.saturating_sub(1).min(31);
330    policy
331        .base
332        .checked_mul(1_u32 << doublings)
333        .map_or(policy.max, |d| d.min(policy.max))
334}
335
336/// One call to an origin: counted in flight until dropped. A guard dropped
337/// without [`record`](Self::record) records nothing learned.
338pub struct CallGuard {
339    state: Arc<OriginState>,
340    ticket: Ticket,
341    recorded: bool,
342    permit: Option<OwnedSemaphorePermit>,
343}
344
345impl CallGuard {
346    /// Records what the call ended in. A stream's guard is kept after this,
347    /// and counts the stream in flight until it is dropped.
348    pub fn record(&mut self, outcome: Outcome) {
349        if !self.recorded {
350            self.recorded = true;
351            self.state.record(self.ticket, outcome, Instant::now());
352        }
353    }
354
355    /// Gives back the place under the in-flight cap (a stream's, once it has
356    /// opened), keeping the call counted in flight.
357    pub fn release_permit(&mut self) {
358        self.permit = None;
359    }
360}
361
362impl Drop for CallGuard {
363    fn drop(&mut self) {
364        self.record(Outcome::Neutral);
365        self.state.in_flight.fetch_sub(1, Ordering::SeqCst);
366    }
367}
368
369impl std::fmt::Debug for CallGuard {
370    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
371        f.debug_struct("CallGuard")
372            .field("origin", &self.state.key)
373            .field("ticket", &self.ticket)
374            .field("recorded", &self.recorded)
375            .finish_non_exhaustive()
376    }
377}
378
379/// The state of one origin at one moment, from
380/// [`HttpPool::origins`](crate::HttpPool::origins).
381#[derive(Clone, Debug, PartialEq, Eq)]
382#[non_exhaustive]
383pub struct OriginSnapshot {
384    /// `scheme://host:port`, and ` via ADDR` for an endpoint pinned to an
385    /// address. Never a user name, password, path or query.
386    pub origin: String,
387    /// Calls in flight (a stream counts until it is dropped).
388    pub in_flight: usize,
389    /// How much longer the origin stays ejected: `Some(ZERO)` once the
390    /// ejection has ended and the probe has not yet closed it; `None` when
391    /// it is in rotation.
392    pub ejected_for: Option<Duration>,
393    /// Failures in a row since the last success or ejection.
394    pub consecutive_failures: u32,
395    /// Ejections in a row since the last success.
396    pub consecutive_ejections: u32,
397}
398
399/// The origins of a pool, or of one balanced client.
400pub struct Origins {
401    ejection: Option<Ejection>,
402    cap: Option<usize>,
403    budget: Option<RetryBudget>,
404    map: Mutex<HashMap<String, Arc<OriginState>>>,
405}
406
407impl Origins {
408    pub fn new(
409        ejection: Option<Ejection>,
410        cap: Option<usize>,
411        budget: Option<RetryBudget>,
412    ) -> Self {
413        Self {
414            ejection,
415            cap,
416            budget,
417            map: Mutex::new(HashMap::new()),
418        }
419    }
420
421    /// Whether a client that is not balanced needs its calls to pass
422    /// through the origin's state: there is a breaker or a cap to apply.
423    pub const fn enforces(&self) -> bool {
424        self.ejection.is_some() || self.cap.is_some()
425    }
426
427    /// Whether the origins keep a retry ledger.
428    pub const fn has_budget(&self) -> bool {
429        self.budget.is_some()
430    }
431
432    /// The state of the origin named `key`, made on first use.
433    pub fn get(&self, key: &str) -> Arc<OriginState> {
434        let mut map = self.map.lock().unwrap_or_else(PoisonError::into_inner);
435        if let Some(state) = map.get(key) {
436            return Arc::clone(state);
437        }
438        if map.len() >= PRUNE_ABOVE {
439            // Forget origins nothing holds and nothing has against them.
440            map.retain(|_, s| Arc::strong_count(s) > 1 || s.ejected_until().is_some());
441        }
442        let state = Arc::new(OriginState::new(
443            key.to_owned(),
444            self.ejection,
445            self.cap,
446            self.budget,
447        ));
448        map.insert(key.to_owned(), Arc::clone(&state));
449        drop(map);
450        state
451    }
452
453    /// Every origin's state, sorted by origin.
454    pub fn snapshot(&self) -> Vec<OriginSnapshot> {
455        let now = Instant::now();
456        let map = self.map.lock().unwrap_or_else(PoisonError::into_inner);
457        let mut all: Vec<OriginSnapshot> = map.values().map(|s| s.snapshot(now)).collect();
458        drop(map);
459        all.sort_by(|a, b| a.origin.cmp(&b.origin));
460        all
461    }
462}
463
464impl std::fmt::Debug for Origins {
465    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        f.debug_struct("Origins")
467            .field("ejection", &self.ejection)
468            .field("cap", &self.cap)
469            .field("budget", &self.budget)
470            .field("origins", &self.snapshot())
471            .finish_non_exhaustive()
472    }
473}
474
475/// The origin of `url`: `scheme://host:port`, the port defaulted by the
476/// scheme, and ` via ADDR` when pinned. `None` when `url` has no host.
477pub fn origin_key(url: &str, pinned: Option<std::net::SocketAddr>) -> Option<String> {
478    let uri: hyper::Uri = url.parse().ok()?;
479    let scheme = uri.scheme_str()?.to_ascii_lowercase();
480    let host = uri.host()?.to_ascii_lowercase();
481    let port = uri
482        .port_u16()
483        .unwrap_or(if scheme == "https" { 443 } else { 80 });
484    let origin = format!("{scheme}://{host}:{port}");
485    Some(pinned.map_or_else(|| origin.clone(), |addr| format!("{origin} via {addr}")))
486}
487
488#[cfg(test)]
489mod tests;