Skip to main content

twilight_http_ratelimiting/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(
3    clippy::missing_const_for_fn,
4    clippy::missing_docs_in_private_items,
5    clippy::pedantic,
6    missing_docs,
7    unsafe_code
8)]
9#![allow(clippy::module_name_repetitions, clippy::must_use_candidate)]
10
11mod actor;
12
13use std::{
14    future::Future,
15    hash::{Hash as _, Hasher},
16    num::NonZero,
17    pin::Pin,
18    task::{Context, Poll},
19    time::{Duration, Instant},
20};
21use tokio::sync::{mpsc, oneshot};
22
23/// Duration from the first globally limited request until the remaining count
24/// resets to the global limit count.
25pub const GLOBAL_LIMIT_PERIOD: Duration = Duration::from_secs(1);
26
27/// HTTP request [method].
28///
29/// [method]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
30#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
31#[non_exhaustive]
32pub enum Method {
33    /// Delete a resource.
34    Delete,
35    /// Retrieve a resource.
36    Get,
37    /// Update a resource.
38    Patch,
39    /// Create a resource.
40    Post,
41    /// Replace a resource.
42    Put,
43}
44
45impl Method {
46    /// Name of the method.
47    pub const fn name(self) -> &'static str {
48        match self {
49            Method::Delete => "DELETE",
50            Method::Get => "GET",
51            Method::Patch => "PATCH",
52            Method::Post => "POST",
53            Method::Put => "PUT",
54        }
55    }
56}
57
58/// Rate limited endpoint.
59///
60/// The rate limiter dynamically supports new or unknown API paths, but is consequently unable to
61/// catch invalid arguments. Invalidly structured endpoints may be permitted at an improper time.
62///
63/// # Example
64///
65/// ```no_run
66/// # let rt = tokio::runtime::Builder::new_current_thread()
67/// #     .enable_time()
68/// #     .build()
69/// #     .unwrap();
70/// # rt.block_on(async {
71/// # let rate_limiter = twilight_http_ratelimiting::RateLimiter::default();
72/// use twilight_http_ratelimiting::{Endpoint, Method};
73///
74/// let url = "https://discord.com/api/v10/guilds/745809834183753828/audit-logs?limit=10";
75/// let endpoint = Endpoint {
76///     method: Method::Get,
77///     path: String::from("guilds/745809834183753828/audit-logs"),
78/// };
79/// let permit = rate_limiter.acquire(endpoint).await;
80/// let headers = unimplemented!("GET {url}");
81/// permit.complete(headers);
82/// # });
83/// ```
84#[derive(Clone, Debug, Eq, Hash, PartialEq)]
85pub struct Endpoint {
86    /// Method of the endpoint.
87    pub method: Method,
88    /// API path of the endpoint.
89    ///
90    /// Should not start with a slash (`/`) or include query parameters (`?key=value`).
91    pub path: String,
92}
93
94impl Endpoint {
95    /// Whether the endpoint is properly structured.
96    fn is_valid(&self) -> bool {
97        !self.path.as_bytes().starts_with(b"/") && !self.path.as_bytes().contains(&b'?')
98    }
99
100    /// Whether the endpoint is an interaction.
101    fn is_interaction(&self) -> bool {
102        self.path.as_bytes().starts_with(b"webhooks")
103            || self.path.as_bytes().starts_with(b"interactions")
104    }
105
106    /// Feeds the top-level resources of this endpoint into the given [`Hasher`].
107    ///
108    /// Top-level resources represent the bucket namespace in which they are unique.
109    ///
110    /// Top-level resources are currently:
111    /// - `channels/<channel_id>`
112    /// - `guilds/<guild_id>`
113    /// - `webhooks/<webhook_id>`
114    /// - `webhooks/<webhook_id>/<webhook_token>`
115    fn hash_resources(&self, state: &mut impl Hasher) {
116        let mut segments = self.path.as_bytes().split(|&s| s == b'/');
117        match segments.next().unwrap_or_default() {
118            b"channels" => {
119                if let Some(s) = segments.next() {
120                    "channels".hash(state);
121                    s.hash(state);
122                }
123            }
124            b"guilds" => {
125                if let Some(s) = segments.next() {
126                    "guilds".hash(state);
127                    s.hash(state);
128                }
129            }
130            b"webhooks" => {
131                if let Some(s) = segments.next() {
132                    "webhooks".hash(state);
133                    s.hash(state);
134                }
135                if let Some(s) = segments.next() {
136                    s.hash(state);
137                }
138            }
139            _ => {}
140        }
141    }
142}
143
144/// Parsed user response rate limit headers.
145///
146/// A `limit` of zero marks the [`Bucket`] as exhausted until `reset_at` elapses.
147///
148/// # Global limits
149///
150/// Please open an issue if the [`RateLimiter`] exceeded the global limit.
151///
152/// # Shared limits
153///
154/// You may preemptively exhaust the bucket until `Reset-After` by completing
155/// the [`Permit`] with [`RateLimitHeaders::shared`], but are not required to
156/// since these limits do not count towards the invalid request limit.
157#[derive(Clone, Debug, Eq, Hash, PartialEq)]
158pub struct RateLimitHeaders {
159    /// Bucket identifier.
160    pub bucket: Vec<u8>,
161    /// Total number of requests until the bucket becomes exhausted.
162    pub limit: u16,
163    /// Number of remaining requests until the bucket becomes exhausted.
164    pub remaining: u16,
165    /// Time at which the bucket resets.
166    pub reset_at: Instant,
167}
168
169impl RateLimitHeaders {
170    /// Lowercased name for the bucket header.
171    pub const BUCKET: &'static str = "x-ratelimit-bucket";
172
173    /// Lowercased name for the limit header.
174    pub const LIMIT: &'static str = "x-ratelimit-limit";
175
176    /// Lowercased name for the remaining header.
177    pub const REMAINING: &'static str = "x-ratelimit-remaining";
178
179    /// Lowercased name for the reset-after header.
180    pub const RESET_AFTER: &'static str = "x-ratelimit-reset-after";
181
182    /// Lowercased name for the scope header.
183    pub const SCOPE: &'static str = "x-ratelimit-scope";
184
185    /// Emulates a shared resource limit as a user limit by setting `limit` and
186    /// `remaining` to zero.
187    pub fn shared(bucket: Vec<u8>, retry_after: u16) -> Self {
188        Self {
189            bucket,
190            limit: 0,
191            remaining: 0,
192            reset_at: Instant::now() + Duration::from_secs(retry_after.into()),
193        }
194    }
195}
196
197/// Permit to send a Discord HTTP API request to the acquired endpoint.
198#[derive(Debug)]
199#[must_use = "dropping the permit immediately cancels itself"]
200pub struct Permit(oneshot::Sender<Option<RateLimitHeaders>>);
201
202impl Permit {
203    /// Update the [`RateLimiter`] based on the response headers.
204    ///
205    /// Non-completed permits are regarded as cancelled, so only call this
206    /// on receiving a response.
207    pub fn complete(self, headers: Option<RateLimitHeaders>) {
208        if self.0.send(headers).is_err() {
209            actor_panic()
210        }
211    }
212}
213
214/// Future that completes when a permit is ready.
215#[derive(Debug)]
216#[must_use = "futures do nothing unless you `.await` or poll them"]
217pub struct PermitFuture(oneshot::Receiver<oneshot::Sender<Option<RateLimitHeaders>>>);
218
219impl Future for PermitFuture {
220    type Output = Permit;
221
222    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
223        Pin::new(&mut self.0).poll(cx).map(|r| match r {
224            Ok(sender) => Permit(sender),
225            Err(_) => actor_panic(),
226        })
227    }
228}
229
230/// Future that completes when a permit is ready or cancelled.
231#[derive(Debug)]
232#[must_use = "futures do nothing unless you `.await` or poll them"]
233pub struct MaybePermitFuture(oneshot::Receiver<oneshot::Sender<Option<RateLimitHeaders>>>);
234
235impl Future for MaybePermitFuture {
236    type Output = Option<Permit>;
237
238    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
239        Pin::new(&mut self.0).poll(cx).map(|r| r.ok().map(Permit))
240    }
241}
242
243/// Future that completes when a bucket is retrieved.
244#[derive(Debug)]
245#[must_use = "futures do nothing unless you `.await` or poll them"]
246pub struct BucketFuture {
247    /// Bucket receiver.
248    rx: oneshot::Receiver<Option<Bucket>>,
249    /// Permit future.
250    #[expect(dead_code, reason = "must be alive to not cancel `rx`")]
251    permit_future: MaybePermitFuture,
252}
253
254impl Future for BucketFuture {
255    type Output = Option<Bucket>;
256
257    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
258        Pin::new(&mut self.rx).poll(cx).map(|r| match r {
259            Ok(bucket) => bucket,
260            Err(_) => actor_panic(),
261        })
262    }
263}
264
265/// Rate limit information for one or more paths from previous
266/// [`RateLimitHeaders`].
267#[non_exhaustive]
268#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
269pub struct Bucket {
270    /// Total number of permits until the bucket becomes exhausted.
271    pub limit: u16,
272    /// Number of remaining permits until the bucket becomes exhausted.
273    pub remaining: u16,
274    /// Time at which the bucket resets.
275    pub reset_at: Instant,
276}
277
278/// Actor run closure pre-enqueue for early [`MaybePermitFuture`] cancellation.
279type Predicate = Box<dyn FnOnce(Option<Bucket>) -> bool + Send>;
280
281/// Discord HTTP client API rate limiter.
282///
283/// The [`RateLimiter`] runs an associated actor task to concurrently handle permit
284/// requests and responses.
285///
286/// Cloning a [`RateLimiter`] increments just the amount of senders for the actor.
287/// The actor completes when there are no senders and non-completed permits left.
288#[derive(Clone, Debug)]
289pub struct RateLimiter {
290    /// Actor message sender.
291    tx: mpsc::UnboundedSender<(actor::Message, Option<Predicate>)>,
292}
293
294impl RateLimiter {
295    /// Create a new [`RateLimiter`] with a custom global limit.
296    ///
297    /// Note that the global limit may be practically disabled by passing `u16::MAX`.
298    ///
299    /// # Panics
300    ///
301    /// Panics if the global limit is 0.
302    #[track_caller]
303    pub fn new(global_limit: u16) -> Self {
304        let global_limit = NonZero::new(global_limit).expect("global limit is non-zero");
305        let (tx, rx) = mpsc::unbounded_channel();
306        tokio::spawn(actor::runner(global_limit, rx));
307
308        Self { tx }
309    }
310
311    /// Await a single permit for this endpoint.
312    ///
313    /// Permits are queued per endpoint in the order they were requested.
314    pub fn acquire(&self, endpoint: Endpoint) -> PermitFuture {
315        PermitFuture(self.acquire_inner(endpoint, None))
316    }
317
318    /// Await a single permit for this endpoint, but only if the predicate evaluates
319    /// to `true`.
320    ///
321    /// Permits are queued per endpoint in the order they were requested.
322    ///
323    /// Note that the predicate is asynchronously called in the actor task.
324    ///
325    /// # Example
326    ///
327    /// ```no_run
328    /// # let rt = tokio::runtime::Builder::new_current_thread()
329    /// #     .enable_time()
330    /// #     .build()
331    /// #     .unwrap();
332    /// # rt.block_on(async {
333    /// # let rate_limiter = twilight_http_ratelimiting::RateLimiter::default();
334    /// use twilight_http_ratelimiting::{Endpoint, Method};
335    ///
336    /// let endpoint = Endpoint {
337    ///     method: Method::Get,
338    ///     path: String::from("applications/@me"),
339    /// };
340    /// if let Some(permit) = rate_limiter
341    ///     .acquire_if(endpoint, |b| b.is_none_or(|b| b.remaining > 10))
342    ///     .await
343    /// {
344    ///     let headers = unimplemented!("GET /applications/@me");
345    ///     permit.complete(headers);
346    /// }
347    /// # });
348    /// ```
349    pub fn acquire_if<P>(&self, endpoint: Endpoint, predicate: P) -> MaybePermitFuture
350    where
351        P: FnOnce(Option<Bucket>) -> bool + Send + 'static,
352    {
353        MaybePermitFuture(self.acquire_inner(endpoint, Some(Box::new(predicate))))
354    }
355
356    /// Requests a permit for this endpoint.
357    fn acquire_inner(
358        &self,
359        endpoint: Endpoint,
360        predicate: Option<Predicate>,
361    ) -> oneshot::Receiver<oneshot::Sender<Option<RateLimitHeaders>>> {
362        let (notifier, rx) = oneshot::channel();
363        let message = actor::Message { endpoint, notifier };
364
365        if self.tx.send((message, predicate)).is_err() {
366            actor_panic();
367        }
368
369        rx
370    }
371
372    /// Retrieve the [`Bucket`] for this endpoint.
373    ///
374    /// The bucket is internally retrieved via [`acquire_if`][Self::acquire_if].
375    pub fn bucket(&self, endpoint: Endpoint) -> BucketFuture {
376        let (tx, rx) = oneshot::channel();
377        let permit_future = self.acquire_if(endpoint, |bucket| {
378            // Ignore cancellation error.
379            _ = tx.send(bucket);
380            false
381        });
382
383        BucketFuture { rx, permit_future }
384    }
385}
386
387impl Default for RateLimiter {
388    /// Create a new [`RateLimiter`] with Discord's default global limit.
389    ///
390    /// Currently this is `50`.
391    fn default() -> Self {
392        Self::new(50)
393    }
394}
395
396/// Report an actor panic.
397// Produces a single panic location compared to inline `panic` calls.
398#[inline(never)]
399const fn actor_panic() -> ! {
400    panic!("actor task panicked: report its panic message to the maintainers")
401}
402
403#[cfg(test)]
404mod tests {
405    use super::{
406        Bucket, Endpoint, MaybePermitFuture, Method, Permit, PermitFuture, RateLimitHeaders,
407        RateLimiter,
408    };
409    use static_assertions::assert_impl_all;
410    use std::{
411        fmt::Debug,
412        future::Future,
413        hash::{DefaultHasher, Hash, Hasher as _},
414        time::{Duration, Instant},
415    };
416    use tokio::task;
417
418    assert_impl_all!(Bucket: Clone, Copy, Debug, Eq, Hash, PartialEq, Send, Sync);
419    assert_impl_all!(Endpoint: Clone, Debug, Eq, Hash, PartialEq, Send, Sync);
420    assert_impl_all!(MaybePermitFuture: Debug, Future<Output = Option<Permit>>);
421    assert_impl_all!(Method: Clone, Copy, Debug, Eq, PartialEq);
422    assert_impl_all!(Permit: Debug, Send, Sync);
423    assert_impl_all!(PermitFuture: Debug, Future<Output = Permit>);
424    assert_impl_all!(RateLimitHeaders: Clone, Debug, Eq, Hash, PartialEq, Send, Sync);
425    assert_impl_all!(RateLimiter: Clone, Debug, Default, Send, Sync);
426
427    const ENDPOINT: fn() -> Endpoint = || Endpoint {
428        method: Method::Get,
429        path: String::from("applications/@me"),
430    };
431
432    #[tokio::test]
433    async fn acquire_if() {
434        let rate_limiter = RateLimiter::default();
435
436        assert!(
437            rate_limiter
438                .acquire_if(ENDPOINT(), |_| false)
439                .await
440                .is_none()
441        );
442        assert!(
443            rate_limiter
444                .acquire_if(ENDPOINT(), |_| true)
445                .await
446                .is_some()
447        );
448    }
449
450    #[tokio::test]
451    async fn bucket() {
452        let rate_limiter = RateLimiter::default();
453
454        let limit = 2;
455        let remaining = 1;
456        let reset_at = Instant::now() + Duration::from_secs(1);
457        let headers = RateLimitHeaders {
458            bucket: vec![1, 2, 3],
459            limit,
460            remaining,
461            reset_at,
462        };
463
464        rate_limiter
465            .acquire(ENDPOINT())
466            .await
467            .complete(Some(headers));
468        task::yield_now().await;
469
470        let bucket = rate_limiter.bucket(ENDPOINT()).await.unwrap();
471        assert_eq!(bucket.limit, limit);
472        assert_eq!(bucket.remaining, remaining);
473        assert!(
474            bucket.reset_at.saturating_duration_since(reset_at) < Duration::from_millis(1)
475                && reset_at.saturating_duration_since(bucket.reset_at) < Duration::from_millis(1)
476        );
477    }
478
479    fn with_hasher(f: impl FnOnce(&mut DefaultHasher)) -> u64 {
480        let mut hasher = DefaultHasher::new();
481        f(&mut hasher);
482        hasher.finish()
483    }
484
485    #[test]
486    fn endpoint() {
487        let invalid = Endpoint {
488            method: Method::Get,
489            path: String::from("/guilds/745809834183753828/audit-logs?limit=10"),
490        };
491        let delete_webhook = Endpoint {
492            method: Method::Delete,
493            path: String::from("webhooks/1"),
494        };
495        let interaction_response = Endpoint {
496            method: Method::Post,
497            path: String::from("interactions/1/abc/callback"),
498        };
499
500        assert!(!invalid.is_valid());
501        assert!(delete_webhook.is_valid());
502        assert!(interaction_response.is_valid());
503
504        assert!(delete_webhook.is_interaction());
505        assert!(interaction_response.is_interaction());
506
507        assert_eq!(
508            with_hasher(|state| invalid.hash_resources(state)),
509            with_hasher(|_| {})
510        );
511        assert_eq!(
512            with_hasher(|state| delete_webhook.hash_resources(state)),
513            with_hasher(|state| {
514                "webhooks".hash(state);
515                b"1".hash(state);
516            })
517        );
518        assert_eq!(
519            with_hasher(|state| interaction_response.hash_resources(state)),
520            with_hasher(|_| {})
521        );
522    }
523
524    #[test]
525    fn method_conversions() {
526        assert_eq!("DELETE", Method::Delete.name());
527        assert_eq!("GET", Method::Get.name());
528        assert_eq!("PATCH", Method::Patch.name());
529        assert_eq!("POST", Method::Post.name());
530        assert_eq!("PUT", Method::Put.name());
531    }
532}