hyprstream_core/services/oauth/
cimd_cache.rs1use std::time::Duration;
27
28use hyprstream_util::TtlCache;
29
30use super::state::RegisteredClient;
31
32#[derive(Debug, Clone)]
34pub struct CimdCacheConfig {
35 pub min_ttl: Duration,
39 pub max_ttl: Duration,
42 pub max_entries: usize,
45 pub reap_budget: usize,
48}
49
50impl Default for CimdCacheConfig {
51 fn default() -> Self {
52 Self {
53 min_ttl: Duration::from_secs(300), max_ttl: Duration::from_secs(86_400), max_entries: 10_000,
56 reap_budget: 16,
57 }
58 }
59}
60
61pub struct CimdCache {
63 cache: TtlCache<String, RegisteredClient>,
64 config: CimdCacheConfig,
65}
66
67impl CimdCache {
68 #[must_use]
69 pub fn new(config: CimdCacheConfig) -> Self {
70 let cache = TtlCache::new(config.max_entries, config.reap_budget);
71 Self { cache, config }
72 }
73
74 #[must_use]
77 pub fn clamp_ttl(&self, http_max_age: Option<Duration>) -> Duration {
78 let ttl = http_max_age.unwrap_or(self.config.min_ttl);
79 ttl.clamp(self.config.min_ttl, self.config.max_ttl)
80 }
81
82 pub async fn get(&self, client_id: &str) -> Option<RegisteredClient> {
87 self.cache.get(client_id)
88 }
89
90 pub async fn insert(&self, client: RegisteredClient, ttl: Duration) {
96 let client_id = client.client_id.clone();
97 self.cache.insert(client_id, client, ttl);
98 }
99
100 pub async fn len(&self) -> usize {
102 self.cache.len()
103 }
104
105 pub async fn is_empty(&self) -> bool {
107 self.cache.is_empty()
108 }
109}
110
111#[cfg(test)]
112#[allow(clippy::unwrap_used, clippy::expect_used)]
113mod tests {
114 use super::*;
115 use std::time::Instant;
116
117 fn make_client(id: &str) -> RegisteredClient {
118 RegisteredClient {
119 client_id: id.to_owned(),
120 redirect_uris: vec!["http://localhost/cb".to_owned()],
121 client_name: None,
122 client_uri: None,
123 logo_uri: None,
124 grant_types: vec![],
125 response_types: vec![],
126 token_endpoint_auth_method: None,
127 jwks: None,
128 jwks_uri: None,
129 hyprstream_node_did: None,
130 scope: None,
131 dpop_bound_access_tokens: None,
132 is_cimd: true,
133 registered_at: Instant::now(),
134 }
135 }
136
137 #[tokio::test]
138 async fn insert_and_get_roundtrip() {
139 let cache = CimdCache::new(CimdCacheConfig::default());
140 cache
141 .insert(make_client("https://a.test/c"), Duration::from_secs(60))
142 .await;
143 let got = cache.get("https://a.test/c").await;
144 assert!(got.is_some());
145 assert_eq!(got.unwrap().client_id, "https://a.test/c");
146 }
147
148 #[tokio::test]
149 async fn expired_entry_returns_none() {
150 let cache = CimdCache::new(CimdCacheConfig::default());
151 cache
152 .insert(make_client("https://a.test/c"), Duration::from_millis(10))
153 .await;
154 tokio::time::sleep(Duration::from_millis(50)).await;
155 assert!(cache.get("https://a.test/c").await.is_none());
156 }
157
158 #[tokio::test]
159 async fn ttl_is_clamped_to_min_and_max() {
160 let cache = CimdCache::new(CimdCacheConfig {
161 min_ttl: Duration::from_secs(60),
162 max_ttl: Duration::from_secs(3600),
163 ..CimdCacheConfig::default()
164 });
165 assert_eq!(cache.clamp_ttl(None), Duration::from_secs(60));
167 assert_eq!(
169 cache.clamp_ttl(Some(Duration::from_secs(10))),
170 Duration::from_secs(60)
171 );
172 assert_eq!(
174 cache.clamp_ttl(Some(Duration::from_secs(600))),
175 Duration::from_secs(600)
176 );
177 assert_eq!(
179 cache.clamp_ttl(Some(Duration::from_secs(99_999))),
180 Duration::from_secs(3600)
181 );
182 }
183
184 #[tokio::test]
185 async fn reinsert_does_not_leak_heap_after_reap() {
186 let cache = CimdCache::new(CimdCacheConfig {
187 reap_budget: 32,
188 ..CimdCacheConfig::default()
189 });
190 for _ in 0..5 {
192 cache
193 .insert(make_client("https://a.test/c"), Duration::from_millis(10))
194 .await;
195 }
196 tokio::time::sleep(Duration::from_millis(50)).await;
200 cache
201 .insert(make_client("https://a.test/c"), Duration::from_secs(60))
202 .await;
203 assert_eq!(cache.len().await, 1);
204 assert!(cache.get("https://a.test/c").await.is_some());
205 }
206
207 #[tokio::test]
208 async fn evict_one_terminates_under_stale_heap_pressure() {
209 let cache = CimdCache::new(CimdCacheConfig {
214 max_entries: 2,
215 reap_budget: 4, min_ttl: Duration::from_secs(60),
217 max_ttl: Duration::from_secs(3600),
218 });
219
220 for _ in 0..50 {
222 cache
223 .insert(make_client("https://a.test/c"), Duration::from_secs(120))
224 .await;
225 }
226 cache
228 .insert(make_client("https://b.test/c"), Duration::from_secs(60))
229 .await;
230 assert_eq!(cache.len().await, 2, "A + B at capacity");
231
232 cache
235 .insert(make_client("https://c.test/c"), Duration::from_secs(180))
236 .await;
237 assert_eq!(cache.len().await, 2, "still 2 after eviction");
238 assert!(
240 cache.get("https://b.test/c").await.is_none(),
241 "B (shortest TTL) should have been the victim"
242 );
243 assert!(
244 cache.get("https://a.test/c").await.is_some(),
245 "A still present"
246 );
247 assert!(
248 cache.get("https://c.test/c").await.is_some(),
249 "C just inserted"
250 );
251 }
252
253 #[tokio::test]
254 async fn capacity_bound_evicts_next_to_expire() {
255 let cache = CimdCache::new(CimdCacheConfig {
256 max_entries: 2,
257 ..CimdCacheConfig::default()
258 });
259 cache
260 .insert(make_client("https://a.test/c1"), Duration::from_secs(10))
261 .await;
262 cache
263 .insert(make_client("https://b.test/c2"), Duration::from_secs(60))
264 .await;
265 cache
267 .insert(make_client("https://c.test/c3"), Duration::from_secs(30))
268 .await;
269 assert_eq!(cache.len().await, 2);
270 assert!(cache.get("https://a.test/c1").await.is_none());
271 assert!(cache.get("https://b.test/c2").await.is_some());
272 assert!(cache.get("https://c.test/c3").await.is_some());
273 }
274}