Skip to main content

a2a_protocol_client/discovery/
cache.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`CardCache`]: one [`CachingCardResolver`] per card URL, shared by every
5//! client that asks (ADR 0051, audit H8).
6
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex, PoisonError};
9use std::time::Duration;
10
11use a2a_protocol_types::AgentCard;
12
13use super::{AGENT_CARD_PATH, CachingCardResolver, CardFetchOptions, build_card_url};
14use crate::error::ClientResult;
15
16/// The default bound on the URLs a [`CardCache`] keeps.
17pub const DEFAULT_MAX_ENTRIES: usize = 1024;
18
19/// The refresh jitter a [`CardCache`]'s resolvers use by default.
20const DEFAULT_JITTER: f64 = 0.1;
21
22/// A cache of agent cards for many agents: one [`CachingCardResolver`] per
23/// card URL, each with this cache's settings.
24///
25/// A supervisor that calls fifty peers holds one of these instead of fifty
26/// resolvers, and every lookup of one URL, from any clone and any task,
27/// shares that URL's stored card and its single fetch in flight. Clones share
28/// the cache.
29///
30/// ```no_run
31/// use std::time::Duration;
32/// use a2a_protocol_client::ClientBuilder;
33/// use a2a_protocol_client::discovery::CardCache;
34///
35/// # async fn demo() -> a2a_protocol_client::ClientResult<()> {
36/// let cards = CardCache::new()
37///     .with_default_freshness(Duration::from_secs(300))
38///     .with_stale_if_error(Duration::from_secs(600));
39/// for peer in ["https://alpha.example", "https://beta.example"] {
40///     let client = ClientBuilder::from_card(&cards.resolve(peer).await?)?.build()?;
41///     # drop(client);
42/// }
43/// # Ok(())
44/// # }
45/// ```
46///
47/// Every resolver of one cache sends the same request headers (its
48/// [`CardFetchOptions`]), so a card fetched under one credential is never
49/// returned for another (RFC 9111 ยง4.1): a second credential needs a second
50/// cache. Each `with_*` call starts a new, empty cache.
51///
52/// Past [`with_max_entries`](Self::with_max_entries) URLs (default 1024), the
53/// least recently used one is dropped; a resolver already handed out keeps
54/// working, alone.
55#[derive(Clone)]
56pub struct CardCache {
57    inner: Arc<Inner>,
58}
59
60#[derive(Clone)]
61struct Settings {
62    options: CardFetchOptions,
63    #[cfg(feature = "tls-rustls")]
64    pool: Option<crate::HttpPool>,
65    path: String,
66    always_revalidate: bool,
67    default_freshness: Option<Duration>,
68    stale_if_error: Option<Duration>,
69    jitter: f64,
70    max_entries: usize,
71}
72
73struct Inner {
74    settings: Settings,
75    entries: Mutex<Entries>,
76}
77
78#[derive(Default)]
79struct Entries {
80    /// Card URL to its resolver and the tick it was last used at.
81    map: HashMap<String, (CachingCardResolver, u64)>,
82    tick: u64,
83}
84
85impl Default for CardCache {
86    fn default() -> Self {
87        Self::new()
88    }
89}
90
91impl CardCache {
92    /// A cache with the default options, the well-known card path, a 10%
93    /// refresh jitter and room for 1024 URLs.
94    #[must_use]
95    pub fn new() -> Self {
96        Self::from_settings(Settings {
97            options: CardFetchOptions::default(),
98            #[cfg(feature = "tls-rustls")]
99            pool: None,
100            path: AGENT_CARD_PATH.to_owned(),
101            always_revalidate: false,
102            default_freshness: None,
103            stale_if_error: None,
104            jitter: DEFAULT_JITTER,
105            max_entries: DEFAULT_MAX_ENTRIES,
106        })
107    }
108
109    fn from_settings(settings: Settings) -> Self {
110        Self {
111            inner: Arc::new(Inner {
112                settings,
113                entries: Mutex::new(Entries::default()),
114            }),
115        }
116    }
117
118    /// A new, empty cache with `change` applied to this one's settings.
119    fn with(&self, change: impl FnOnce(&mut Settings)) -> Self {
120        let mut settings = self.inner.settings.clone();
121        change(&mut settings);
122        Self::from_settings(settings)
123    }
124
125    /// Every fetch sends and checks `options`
126    /// ([`CachingCardResolver::with_options`]).
127    #[must_use]
128    pub fn with_options(self, options: CardFetchOptions) -> Self {
129        self.with(|s| s.options = options)
130    }
131
132    /// Every fetch goes through `pool` ([`CachingCardResolver::with_pool`]).
133    #[cfg(feature = "tls-rustls")]
134    #[must_use]
135    pub fn with_pool(self, pool: &crate::HttpPool) -> Self {
136        self.with(|s| s.pool = Some(pool.clone()))
137    }
138
139    /// The path of the card under each base URL. Default:
140    /// [`AGENT_CARD_PATH`].
141    #[must_use]
142    pub fn with_path(self, path: impl Into<String>) -> Self {
143        let path = path.into();
144        self.with(|s| s.path = path)
145    }
146
147    /// [`CachingCardResolver::with_always_revalidate`] for every URL.
148    #[must_use]
149    pub fn with_always_revalidate(self, always: bool) -> Self {
150        self.with(|s| s.always_revalidate = always)
151    }
152
153    /// [`CachingCardResolver::with_default_freshness`] for every URL.
154    #[must_use]
155    pub fn with_default_freshness(self, lifetime: Duration) -> Self {
156        self.with(|s| s.default_freshness = Some(lifetime))
157    }
158
159    /// [`CachingCardResolver::with_stale_if_error`] for every URL.
160    #[must_use]
161    pub fn with_stale_if_error(self, window: Duration) -> Self {
162        self.with(|s| s.stale_if_error = Some(window))
163    }
164
165    /// [`CachingCardResolver::with_refresh_jitter`] for every URL. Default
166    /// here: `0.1`.
167    #[must_use]
168    pub fn with_refresh_jitter(self, fraction: f64) -> Self {
169        self.with(|s| s.jitter = fraction)
170    }
171
172    /// The most URLs kept; at least 1. Default: [`DEFAULT_MAX_ENTRIES`].
173    #[must_use]
174    pub fn with_max_entries(self, max: usize) -> Self {
175        self.with(|s| s.max_entries = max.max(1))
176    }
177
178    /// The resolver for the card under `base_url`: the one this cache
179    /// already holds for that URL, or a new one with the cache's settings.
180    ///
181    /// # Errors
182    ///
183    /// [`ClientError::InvalidEndpoint`](crate::ClientError::InvalidEndpoint)
184    /// when `base_url` is malformed.
185    pub fn resolver(&self, base_url: &str) -> ClientResult<CachingCardResolver> {
186        let s = &self.inner.settings;
187        let url = build_card_url(base_url, &s.path)?;
188        if let Some(resolver) = self.touch(&url, None) {
189            return Ok(resolver);
190        }
191        // Built outside the lock: a resolver builds an HTTP client. Two
192        // callers that race here keep whichever was stored first.
193        let built = self.new_resolver(base_url)?;
194        Ok(self.touch(&url, Some(built.clone())).unwrap_or(built))
195    }
196
197    /// The resolver stored for `url`, marked as just used; with `insert`,
198    /// stores it first when none is, dropping the least recently used URL
199    /// past the bound.
200    fn touch(&self, url: &str, insert: Option<CachingCardResolver>) -> Option<CachingCardResolver> {
201        let mut entries = self
202            .inner
203            .entries
204            .lock()
205            .unwrap_or_else(PoisonError::into_inner);
206        entries.tick += 1;
207        let tick = entries.tick;
208        if let Some((resolver, used)) = entries.map.get_mut(url) {
209            *used = tick;
210            return Some(resolver.clone());
211        }
212        let resolver = insert?;
213        entries.map.insert(url.to_owned(), (resolver.clone(), tick));
214        if entries.map.len() > self.inner.settings.max_entries
215            && let Some(oldest) = entries
216                .map
217                .iter()
218                .min_by_key(|(_, (_, used))| *used)
219                .map(|(url, _)| url.clone())
220        {
221            entries.map.remove(&oldest);
222        }
223        drop(entries);
224        Some(resolver)
225    }
226
227    fn new_resolver(&self, base_url: &str) -> ClientResult<CachingCardResolver> {
228        let s = &self.inner.settings;
229        let resolver = CachingCardResolver::with_path(base_url, &s.path)?
230            .with_options(s.options.clone())
231            .with_always_revalidate(s.always_revalidate)
232            .with_refresh_jitter(s.jitter);
233        #[cfg(feature = "tls-rustls")]
234        let resolver = match &s.pool {
235            Some(pool) => resolver.with_pool(pool),
236            None => resolver,
237        };
238        let resolver = match s.default_freshness {
239            Some(lifetime) => resolver.with_default_freshness(lifetime),
240            None => resolver,
241        };
242        Ok(match s.stale_if_error {
243            Some(window) => resolver.with_stale_if_error(window),
244            None => resolver,
245        })
246    }
247
248    /// The card under `base_url`: [`resolver`](Self::resolver), then
249    /// [`CachingCardResolver::resolve`].
250    ///
251    /// # Errors
252    ///
253    /// Those of the two calls.
254    pub async fn resolve(&self, base_url: &str) -> ClientResult<AgentCard> {
255        self.resolver(base_url)?.resolve().await
256    }
257
258    /// How many URLs the cache holds.
259    #[must_use]
260    pub fn len(&self) -> usize {
261        self.inner
262            .entries
263            .lock()
264            .unwrap_or_else(PoisonError::into_inner)
265            .map
266            .len()
267    }
268
269    /// Whether the cache holds no URL.
270    #[must_use]
271    pub fn is_empty(&self) -> bool {
272        self.len() == 0
273    }
274}
275
276impl std::fmt::Debug for CardCache {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        // URLs are left out: a card URL may carry a key in its query.
279        let s = &self.inner.settings;
280        let mut d = f.debug_struct("CardCache");
281        d.field("entries", &self.len())
282            .field("max_entries", &s.max_entries)
283            .field("options", &s.options)
284            .field("path", &s.path)
285            .field("always_revalidate", &s.always_revalidate)
286            .field("default_freshness", &s.default_freshness)
287            .field("stale_if_error", &s.stale_if_error)
288            .field("jitter", &s.jitter);
289        #[cfg(feature = "tls-rustls")]
290        d.field("pooled", &s.pool.is_some());
291        d.finish()
292    }
293}