Skip to main content

adk_server/awp/
limits.rs

1//! Rate limits at the edge (spec 3.5 §7.3; AWP 2.0 §6.6).
2//!
3//! Limits key on [`EdgeCaller::limit_key`]: the verified requester id, else a digest of the
4//! presented credential, else the peer address. Each caller has a rate class — the class its
5//! owner rule names, else its tier's default — with two fixed windows:
6//!
7//! | Window | Counts | Applies to |
8//! |---|---|---|
9//! | One minute | Every edge request | `requestsPerMinute` |
10//! | One day | Capability calls, per class | `callsPerDay` |
11//!
12//! A capability's own `rateClass` replaces the caller's for its calls. A request over a limit
13//! is refused with `rate_limit_exceeded` and `Retry-After`.
14//!
15//! The windows are counted in the process unless [`EdgeLimits::store`] shares them through a
16//! [`RateLimitStore`]: the SQLite, PostgreSQL and Redis edge stores implement it, so edge
17//! replicas and a restarted edge count against one window (spec 3.5 §7.9). A store that
18//! fails is logged and the process's own counters answer until it recovers.
19
20use 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
32/// How many counters the limiter keeps before it drops expired windows.
33const PURGE_THRESHOLD: usize = 10_000;
34
35/// A refused request: the class whose limit it passed and when to retry.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RateLimited {
38    /// The rate class.
39    pub class: String,
40    /// The limit.
41    pub limit: u32,
42    /// Seconds until the window resets.
43    pub retry_after: u64,
44}
45
46/// Where a caller stands in its request window, for the `RateLimit` response fields.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct RateStanding {
49    /// The rate class.
50    pub class: String,
51    /// The limit per minute.
52    pub limit: u32,
53    /// Requests left in the window.
54    pub remaining: u32,
55    /// Seconds until the window resets.
56    pub reset: u64,
57}
58
59/// A counter's key: the caller's limit key, the class and the window.
60type 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/// One caller's fixed window for one rate class (spec 3.5 §7.3, §7.9).
85#[derive(Debug, Clone, PartialEq, Eq, Hash)]
86pub struct RateWindow {
87    /// The caller's limit key, such as `ip:203.0.113.9` or `id:{requester}`.
88    pub key: String,
89    /// The rate class.
90    pub class: String,
91    /// `minute` for requests, `day` for capability calls.
92    pub period: String,
93    /// When the window began, in Unix seconds.
94    pub start: i64,
95    /// How long it lasts, in seconds.
96    pub seconds: i64,
97}
98
99/// Where the edge counts its rate-limit windows, shared by every replica and kept across a
100/// restart (spec 3.5 §7.9).
101///
102/// [`InMemoryRateLimitStore`] keeps them in the process; the SQLite, PostgreSQL and Redis
103/// edge stores (`awp-sqlite`, `awp-postgres`, `awp-redis`) share them. Every implementation
104/// passes [`rate_limit_conformance_tests!`](crate::rate_limit_conformance_tests).
105///
106/// # Example
107///
108/// ```rust
109/// use adk_server::awp::limits::{InMemoryRateLimitStore, RateLimitStore, RateWindow};
110///
111/// # #[tokio::main(flavor = "current_thread")]
112/// # async fn main() -> Result<(), adk_awp::v2::store::StoreError> {
113/// let store = InMemoryRateLimitStore::default();
114/// let window = RateWindow {
115///     key: "ip:203.0.113.9".into(),
116///     class: "tier-public".into(),
117///     period: "minute".into(),
118///     start: 1_761_465_600,
119///     seconds: 60,
120/// };
121/// assert_eq!(store.hit(&window, 1).await?, Some(1));
122/// assert_eq!(store.hit(&window, 1).await?, None, "the second request passes the limit");
123/// # Ok(())
124/// # }
125/// ```
126#[async_trait]
127pub trait RateLimitStore: Send + Sync {
128    /// Counts one hit in `window` unless its count has reached `limit`: the count after the
129    /// hit, or `None` when the hit is refused. A window that began later than the stored one
130    /// for the same key, class and period starts again from zero. Atomic: concurrent hits
131    /// never pass the limit together.
132    ///
133    /// # Errors
134    ///
135    /// The backend's failure.
136    async fn hit(&self, window: &RateWindow, limit: u32) -> StoreResult<Option<u32>>;
137
138    /// Drops the windows that began before `before`, in Unix seconds; returns how many. A
139    /// backend whose windows expire by themselves drops none.
140    ///
141    /// # Errors
142    ///
143    /// The backend's failure.
144    async fn purge_before(&self, before: i64) -> StoreResult<usize>;
145}
146
147/// A window's key in memory: the caller's limit key, the class and the period.
148type WindowKey = (String, String, String);
149
150/// A [`RateLimitStore`] in the process, shared by its clones.
151#[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
181/// Fixed-window rate limits per caller and class (spec 3.5 §7.3).
182///
183/// # Example
184///
185/// ```rust
186/// use adk_server::awp::limits::EdgeLimits;
187/// use adk_server::awp::tiers::EdgeCaller;
188/// use awp_types::{RateClass, TrustTier};
189///
190/// let limits = EdgeLimits::default().tier_default(
191///     TrustTier::Public,
192///     RateClass { requests_per_minute: 1, calls_per_day: 10 },
193/// );
194/// let caller = EdgeCaller::public("ip:203.0.113.9");
195/// assert!(limits.check_request(&caller).is_ok());
196/// assert!(limits.check_request(&caller).is_err());
197/// ```
198pub 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    /// Public 60 requests a minute and 200 calls a day; known 120 and 2,000; verified 300 and
218    /// 10,000; partner 600 and 50,000.
219    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    /// Sets the default class of `tier`.
239    #[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    /// Defines the classes owner rules and capabilities name.
246    #[must_use]
247    pub fn classes(mut self, classes: BTreeMap<String, RateClass>) -> Self {
248        self.classes.extend(classes);
249        self
250    }
251
252    /// Counts the windows in `store`, shared by every edge over it and kept across a restart
253    /// (spec 3.5 §7.9); the edge calls [`admit_request`](Self::admit_request) and
254    /// [`admit_call`](Self::admit_call), which read it.
255    ///
256    /// # Example
257    ///
258    /// ```rust
259    /// use std::sync::Arc;
260    /// use adk_server::awp::limits::{EdgeLimits, InMemoryRateLimitStore};
261    /// use adk_server::awp::tiers::EdgeCaller;
262    /// use awp_types::{RateClass, TrustTier};
263    ///
264    /// # #[tokio::main(flavor = "current_thread")]
265    /// # async fn main() {
266    /// let windows = Arc::new(InMemoryRateLimitStore::default());
267    /// let class = RateClass { requests_per_minute: 1, calls_per_day: 10 };
268    /// let first = EdgeLimits::default().tier_default(TrustTier::Public, class).store(windows.clone());
269    /// let second = EdgeLimits::default().tier_default(TrustTier::Public, class).store(windows);
270    /// let caller = EdgeCaller::public("ip:203.0.113.9");
271    /// assert!(first.admit_request(&caller).await.is_ok());
272    /// assert!(second.admit_request(&caller).await.is_err(), "one window across both edges");
273    /// # }
274    /// ```
275    #[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    /// Counts one hit in the store's window, else in the process's: the shared windows when
323    /// the limits have a [`store`](Self::store).
324    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    /// Counts one edge request against the caller's per-minute limit, in the shared windows
368    /// when the limits have a [`store`](Self::store) (spec 3.5 §7.9).
369    ///
370    /// # Errors
371    ///
372    /// [`RateLimited`] when the caller passed it.
373    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    /// Counts one capability call against the daily limit of the caller's class, or of
388    /// `capability_class`, in the shared windows when the limits have a
389    /// [`store`](Self::store) (spec 3.5 §7.9).
390    ///
391    /// # Errors
392    ///
393    /// [`RateLimited`] when the caller passed it.
394    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    /// Counts one edge request against the caller's per-minute limit in the process's own
406    /// windows; [`admit_request`](Self::admit_request) also reads a shared store.
407    ///
408    /// # Errors
409    ///
410    /// [`RateLimited`] when the caller passed it.
411    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    /// Counts one capability call against the daily limit of the caller's class, or of
424    /// `capability_class` when the capability names one, in the process's own windows;
425    /// [`admit_call`](Self::admit_call) also reads a shared store.
426    ///
427    /// # Errors
428    ///
429    /// [`RateLimited`] when the caller passed it.
430    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}