a2a_protocol_client/discovery/
cache.rs1use 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
16pub const DEFAULT_MAX_ENTRIES: usize = 1024;
18
19const DEFAULT_JITTER: f64 = 0.1;
21
22#[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 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 #[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 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 #[must_use]
128 pub fn with_options(self, options: CardFetchOptions) -> Self {
129 self.with(|s| s.options = options)
130 }
131
132 #[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 #[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 #[must_use]
149 pub fn with_always_revalidate(self, always: bool) -> Self {
150 self.with(|s| s.always_revalidate = always)
151 }
152
153 #[must_use]
155 pub fn with_default_freshness(self, lifetime: Duration) -> Self {
156 self.with(|s| s.default_freshness = Some(lifetime))
157 }
158
159 #[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 #[must_use]
168 pub fn with_refresh_jitter(self, fraction: f64) -> Self {
169 self.with(|s| s.jitter = fraction)
170 }
171
172 #[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 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 let built = self.new_resolver(base_url)?;
194 Ok(self.touch(&url, Some(built.clone())).unwrap_or(built))
195 }
196
197 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 pub async fn resolve(&self, base_url: &str) -> ClientResult<AgentCard> {
255 self.resolver(base_url)?.resolve().await
256 }
257
258 #[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 #[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 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}