twilight_http_ratelimiting/
lib.rs1#![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
23pub const GLOBAL_LIMIT_PERIOD: Duration = Duration::from_secs(1);
26
27#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
31#[non_exhaustive]
32pub enum Method {
33 Delete,
35 Get,
37 Patch,
39 Post,
41 Put,
43}
44
45impl Method {
46 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#[derive(Clone, Debug, Eq, Hash, PartialEq)]
85pub struct Endpoint {
86 pub method: Method,
88 pub path: String,
92}
93
94impl Endpoint {
95 fn is_valid(&self) -> bool {
97 !self.path.as_bytes().starts_with(b"/") && !self.path.as_bytes().contains(&b'?')
98 }
99
100 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 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#[derive(Clone, Debug, Eq, Hash, PartialEq)]
158pub struct RateLimitHeaders {
159 pub bucket: Vec<u8>,
161 pub limit: u16,
163 pub remaining: u16,
165 pub reset_at: Instant,
167}
168
169impl RateLimitHeaders {
170 pub const BUCKET: &'static str = "x-ratelimit-bucket";
172
173 pub const LIMIT: &'static str = "x-ratelimit-limit";
175
176 pub const REMAINING: &'static str = "x-ratelimit-remaining";
178
179 pub const RESET_AFTER: &'static str = "x-ratelimit-reset-after";
181
182 pub const SCOPE: &'static str = "x-ratelimit-scope";
184
185 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#[derive(Debug)]
199#[must_use = "dropping the permit immediately cancels itself"]
200pub struct Permit(oneshot::Sender<Option<RateLimitHeaders>>);
201
202impl Permit {
203 pub fn complete(self, headers: Option<RateLimitHeaders>) {
208 if self.0.send(headers).is_err() {
209 actor_panic()
210 }
211 }
212}
213
214#[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#[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#[derive(Debug)]
245#[must_use = "futures do nothing unless you `.await` or poll them"]
246pub struct BucketFuture {
247 rx: oneshot::Receiver<Option<Bucket>>,
249 #[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#[non_exhaustive]
268#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
269pub struct Bucket {
270 pub limit: u16,
272 pub remaining: u16,
274 pub reset_at: Instant,
276}
277
278type Predicate = Box<dyn FnOnce(Option<Bucket>) -> bool + Send>;
280
281#[derive(Clone, Debug)]
289pub struct RateLimiter {
290 tx: mpsc::UnboundedSender<(actor::Message, Option<Predicate>)>,
292}
293
294impl RateLimiter {
295 #[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 pub fn acquire(&self, endpoint: Endpoint) -> PermitFuture {
315 PermitFuture(self.acquire_inner(endpoint, None))
316 }
317
318 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 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 pub fn bucket(&self, endpoint: Endpoint) -> BucketFuture {
376 let (tx, rx) = oneshot::channel();
377 let permit_future = self.acquire_if(endpoint, |bucket| {
378 _ = tx.send(bucket);
380 false
381 });
382
383 BucketFuture { rx, permit_future }
384 }
385}
386
387impl Default for RateLimiter {
388 fn default() -> Self {
392 Self::new(50)
393 }
394}
395
396#[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}