1use std::collections::{BTreeMap, HashMap};
21use std::sync::Arc;
22use std::sync::Mutex;
23use std::sync::atomic::{AtomicU64, Ordering};
24
25use adk_awp::v2::store::StoreResult;
26use async_trait::async_trait;
27use awp_types::{RateClass, TrustTier};
28use chrono::{DateTime, Utc};
29
30use super::tiers::EdgeCaller;
31
32const PURGE_THRESHOLD: usize = 10_000;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RateLimited {
38 pub class: String,
40 pub limit: u32,
42 pub retry_after: u64,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct RateStanding {
49 pub class: String,
51 pub limit: u32,
53 pub remaining: u32,
55 pub reset: u64,
57}
58
59type CounterKey = (String, String, Window);
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63enum Window {
64 Minute,
65 Day,
66}
67
68impl Window {
69 fn seconds(self) -> i64 {
70 match self {
71 Window::Minute => 60,
72 Window::Day => 86_400,
73 }
74 }
75
76 fn name(self) -> &'static str {
77 match self {
78 Window::Minute => "minute",
79 Window::Day => "day",
80 }
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Hash)]
86pub struct RateWindow {
87 pub key: String,
89 pub class: String,
91 pub period: String,
93 pub start: i64,
95 pub seconds: i64,
97}
98
99#[async_trait]
127pub trait RateLimitStore: Send + Sync {
128 async fn hit(&self, window: &RateWindow, limit: u32) -> StoreResult<Option<u32>>;
137
138 async fn purge_before(&self, before: i64) -> StoreResult<usize>;
145}
146
147type WindowKey = (String, String, String);
149
150#[derive(Debug, Clone, Default)]
152pub struct InMemoryRateLimitStore {
153 windows: Arc<Mutex<HashMap<WindowKey, (i64, u32)>>>,
154}
155
156#[async_trait]
157impl RateLimitStore for InMemoryRateLimitStore {
158 async fn hit(&self, window: &RateWindow, limit: u32) -> StoreResult<Option<u32>> {
159 let mut windows = self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
160 let entry = windows
161 .entry((window.key.clone(), window.class.clone(), window.period.clone()))
162 .or_insert((window.start, 0));
163 if entry.0 != window.start {
164 *entry = (window.start, 0);
165 }
166 if entry.1 >= limit {
167 return Ok(None);
168 }
169 entry.1 += 1;
170 Ok(Some(entry.1))
171 }
172
173 async fn purge_before(&self, before: i64) -> StoreResult<usize> {
174 let mut windows = self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
175 let count = windows.len();
176 windows.retain(|_, (start, _)| *start >= before);
177 Ok(count - windows.len())
178 }
179}
180
181pub struct EdgeLimits {
199 defaults: BTreeMap<TrustTier, RateClass>,
200 classes: BTreeMap<String, RateClass>,
201 counters: Mutex<HashMap<CounterKey, (i64, u32)>>,
202 store: Option<Arc<dyn RateLimitStore>>,
203 store_hits: AtomicU64,
204}
205
206impl std::fmt::Debug for EdgeLimits {
207 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 f.debug_struct("EdgeLimits")
209 .field("defaults", &self.defaults)
210 .field("classes", &self.classes)
211 .field("shared", &self.store.is_some())
212 .finish_non_exhaustive()
213 }
214}
215
216impl Default for EdgeLimits {
217 fn default() -> Self {
220 let class =
221 |requests_per_minute, calls_per_day| RateClass { requests_per_minute, calls_per_day };
222 Self {
223 defaults: BTreeMap::from([
224 (TrustTier::Public, class(60, 200)),
225 (TrustTier::Known, class(120, 2_000)),
226 (TrustTier::Verified, class(300, 10_000)),
227 (TrustTier::Partner, class(600, 50_000)),
228 ]),
229 classes: BTreeMap::new(),
230 counters: Mutex::new(HashMap::new()),
231 store: None,
232 store_hits: AtomicU64::new(0),
233 }
234 }
235}
236
237impl EdgeLimits {
238 #[must_use]
240 pub fn tier_default(mut self, tier: TrustTier, class: RateClass) -> Self {
241 self.defaults.insert(tier, class);
242 self
243 }
244
245 #[must_use]
247 pub fn classes(mut self, classes: BTreeMap<String, RateClass>) -> Self {
248 self.classes.extend(classes);
249 self
250 }
251
252 #[must_use]
276 pub fn store(mut self, store: Arc<dyn RateLimitStore>) -> Self {
277 self.store = Some(store);
278 self
279 }
280
281 fn class_for(&self, caller: &EdgeCaller, override_class: Option<&str>) -> (String, RateClass) {
282 let named = override_class
283 .or(caller.rate_class.as_deref())
284 .and_then(|name| self.classes.get(name).map(|class| (name.to_owned(), *class)));
285 named.unwrap_or_else(|| {
286 let class = self
287 .defaults
288 .get(&caller.tier)
289 .copied()
290 .unwrap_or(RateClass { requests_per_minute: 60, calls_per_day: 200 });
291 (format!("tier-{}", caller.tier), class)
292 })
293 }
294
295 fn hit(
296 &self,
297 key: &str,
298 class: &str,
299 window: Window,
300 limit: u32,
301 now: DateTime<Utc>,
302 ) -> Result<(u32, u64), RateLimited> {
303 let start = now.timestamp() - now.timestamp().rem_euclid(window.seconds());
304 let reset = u64::try_from(start + window.seconds() - now.timestamp()).unwrap_or(1).max(1);
305 let mut counters = self.counters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
306 if counters.len() > PURGE_THRESHOLD {
307 counters
308 .retain(|(_, _, window), (began, _)| *began + window.seconds() > now.timestamp());
309 }
310 let entry =
311 counters.entry((key.to_owned(), class.to_owned(), window)).or_insert((start, 0));
312 if entry.0 != start {
313 *entry = (start, 0);
314 }
315 if entry.1 >= limit {
316 return Err(RateLimited { class: class.to_owned(), limit, retry_after: reset });
317 }
318 entry.1 += 1;
319 Ok((limit - entry.1, reset))
320 }
321
322 async fn hit_shared(
325 &self,
326 key: &str,
327 class: &str,
328 window: Window,
329 limit: u32,
330 now: DateTime<Utc>,
331 ) -> Result<(u32, u64), RateLimited> {
332 let Some(store) = &self.store else {
333 return self.hit(key, class, window, limit, now);
334 };
335 let start = now.timestamp() - now.timestamp().rem_euclid(window.seconds());
336 let reset = u64::try_from(start + window.seconds() - now.timestamp()).unwrap_or(1).max(1);
337 if limit == 0 {
338 return Err(RateLimited { class: class.to_owned(), limit, retry_after: reset });
339 }
340 let shared = RateWindow {
341 key: key.to_owned(),
342 class: class.to_owned(),
343 period: window.name().to_owned(),
344 start,
345 seconds: window.seconds(),
346 };
347 match store.hit(&shared, limit).await {
348 Ok(Some(count)) => {
349 if self.store_hits.fetch_add(1, Ordering::Relaxed) % PURGE_THRESHOLD as u64
350 == PURGE_THRESHOLD as u64 - 1
351 {
352 let before = now.timestamp() - Window::Day.seconds();
353 if let Err(error) = store.purge_before(before).await {
354 tracing::warn!(error = %error, "awp rate windows could not be purged");
355 }
356 }
357 Ok((limit.saturating_sub(count), reset))
358 }
359 Ok(None) => Err(RateLimited { class: class.to_owned(), limit, retry_after: reset }),
360 Err(error) => {
361 tracing::warn!(error = %error, "the shared rate-limit store failed; counting in the process");
362 self.hit(key, class, window, limit, now)
363 }
364 }
365 }
366
367 pub async fn admit_request(&self, caller: &EdgeCaller) -> Result<RateStanding, RateLimited> {
374 let (class, limits) = self.class_for(caller, None);
375 let (remaining, reset) = self
376 .hit_shared(
377 &caller.limit_key,
378 &class,
379 Window::Minute,
380 limits.requests_per_minute,
381 Utc::now(),
382 )
383 .await?;
384 Ok(RateStanding { class, limit: limits.requests_per_minute, remaining, reset })
385 }
386
387 pub async fn admit_call(
395 &self,
396 caller: &EdgeCaller,
397 capability_class: Option<&str>,
398 ) -> Result<(), RateLimited> {
399 let (class, limits) = self.class_for(caller, capability_class);
400 self.hit_shared(&caller.limit_key, &class, Window::Day, limits.calls_per_day, Utc::now())
401 .await
402 .map(|_| ())
403 }
404
405 pub fn check_request(&self, caller: &EdgeCaller) -> Result<RateStanding, RateLimited> {
412 let (class, limits) = self.class_for(caller, None);
413 let (remaining, reset) = self.hit(
414 &caller.limit_key,
415 &class,
416 Window::Minute,
417 limits.requests_per_minute,
418 Utc::now(),
419 )?;
420 Ok(RateStanding { class, limit: limits.requests_per_minute, remaining, reset })
421 }
422
423 pub fn check_call(
431 &self,
432 caller: &EdgeCaller,
433 capability_class: Option<&str>,
434 ) -> Result<(), RateLimited> {
435 let (class, limits) = self.class_for(caller, capability_class);
436 self.hit(&caller.limit_key, &class, Window::Day, limits.calls_per_day, Utc::now())
437 .map(|_| ())
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444
445 #[test]
446 fn limits_key_on_the_caller_and_class() {
447 let limits = EdgeLimits::default()
448 .tier_default(TrustTier::Known, RateClass { requests_per_minute: 2, calls_per_day: 1 })
449 .classes(BTreeMap::from([(
450 "bulk".to_owned(),
451 RateClass { requests_per_minute: 1, calls_per_day: 5 },
452 )]));
453 let known = |id: &str| EdgeCaller {
454 tier: TrustTier::Known,
455 requester: Some(awp_types::RequesterId::new(id)),
456 limit_key: format!("id:{id}"),
457 rate_class: None,
458 claimed_agent: None,
459 visitor: None,
460 };
461 let (a, b) = (known("a"), known("b"));
462 assert!(limits.check_request(&a).is_ok());
463 assert!(limits.check_request(&a).is_ok());
464 let refused = limits.check_request(&a).unwrap_err();
465 assert_eq!(refused.class, "tier-known");
466 assert!(refused.retry_after >= 1 && refused.retry_after <= 60);
467 assert!(limits.check_request(&b).is_ok(), "another requester has its own window");
468
469 assert!(limits.check_call(&a, None).is_ok());
470 assert!(limits.check_call(&a, None).is_err());
471 assert!(
472 limits.check_call(&a, Some("bulk")).is_ok(),
473 "a capability's class has its own window"
474 );
475 }
476
477 struct Broken;
478
479 #[async_trait]
480 impl RateLimitStore for Broken {
481 async fn hit(&self, _: &RateWindow, _: u32) -> StoreResult<Option<u32>> {
482 Err(adk_awp::v2::store::StoreError::Backend("down".into()))
483 }
484 async fn purge_before(&self, _: i64) -> StoreResult<usize> {
485 Ok(0)
486 }
487 }
488
489 #[tokio::test]
490 async fn shared_windows_hold_across_edges_and_a_failed_store_falls_back() {
491 let class = RateClass { requests_per_minute: 1, calls_per_day: 1 };
492 let windows = Arc::new(InMemoryRateLimitStore::default());
493 let edge = |store: Arc<dyn RateLimitStore>| {
494 EdgeLimits::default().tier_default(TrustTier::Public, class).store(store)
495 };
496 let (first, second) = (edge(windows.clone()), edge(windows.clone()));
497 let caller = EdgeCaller::public("ip:203.0.113.9");
498 assert!(first.admit_request(&caller).await.is_ok());
499 assert!(second.admit_request(&caller).await.is_err(), "one window across both edges");
500 assert!(second.admit_call(&caller, None).await.is_ok());
501 assert!(first.admit_call(&caller, None).await.is_err());
502 assert!(
503 first.check_request(&caller).is_ok(),
504 "the synchronous check counts in the process only"
505 );
506
507 let degraded = edge(Arc::new(Broken));
508 assert!(degraded.admit_request(&caller).await.is_ok(), "the process counts instead");
509 assert!(degraded.admit_request(&caller).await.is_err());
510 }
511}