async_rate_limit::sliding_window

Struct SlidingWindowRateLimiter

Source
pub struct SlidingWindowRateLimiter { /* private fields */ }
Expand description

A rate limiter that records calls (optionally with a specified cost) during a sliding window Duration.

SlidingWindowRateLimiter implements both [RateLimiter] and [VariableCostRateLimiter], so both SlidingWindowRateLimiter::wait_until_ready() and SlidingWindowRateLimiter::wait_with_cost() can be used (even together). For instance, limiter.wait_until_ready().await and limiter.wait_with_cost(1).await would have the same effect.

§Example: Simple Rate Limiter

A method that calls an external API with a rate limit should not be called more than three times per second.

use tokio::time::{Instant, Duration};
use async_rate_limit::limiters::RateLimiter;
use async_rate_limit::sliding_window::SlidingWindowRateLimiter;

#[tokio::main]
async fn main() -> () {
    let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);
     
    for _ in 0..4 {
        // the 4th call will take place ~1 second after the first call
        limited_method(&mut limiter).await;
    }
}

// note the use of the `RateLimiter` trait, rather than the direct type
async fn limited_method<T>(limiter: &mut T) where T: RateLimiter {
    limiter.wait_until_ready().await;
    println!("{:?}", Instant::now());
}

Implementations§

Source§

impl SlidingWindowRateLimiter

Source

pub fn new(window: Duration, limit: usize) -> Self

Creates a new SlidingWindowRateLimiter that allows limit calls during any window Duration.

Source

pub fn new_with_permits(window: Duration, permits: Arc<Semaphore>) -> Self

Creates a new SlidingWindowRateLimiter with an externally provided Arc<Semaphore> for permits.

§Example: A Shared Variable Cost Rate Limiter
use std::sync::Arc;
use tokio::sync::Semaphore;
use async_rate_limit::limiters::VariableCostRateLimiter;
use async_rate_limit::sliding_window::SlidingWindowRateLimiter;
use tokio::time::{Instant, Duration};

#[tokio::main]
async fn main() -> () {
    let permits = Arc::new(Semaphore::new(5));
    let mut limiter1 =
    SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());
    let mut limiter2 =
    SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());

    // Note: the above is semantically equivalent to creating `limiter1` with
    //  `SlidingWindowRateLimiter::new`, then cloning it.

    limiter1.wait_with_cost(3).await;
    // the second call will wait 2s, since the first call consumed 3/5 shared permits
    limiter2.wait_with_cost(3).await;
}

Trait Implementations§

Source§

impl Clone for SlidingWindowRateLimiter

Source§

fn clone(&self) -> SlidingWindowRateLimiter

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SlidingWindowRateLimiter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl ThreadsafeRateLimiter for SlidingWindowRateLimiter

Source§

async fn wait_until_ready(&self)

Wait with an implied cost of 1, see the initial example

Source§

impl ThreadsafeVariableRateLimiter for SlidingWindowRateLimiter

Source§

async fn wait_with_cost(&self, cost: usize)

Wait with some variable cost per usage.

§Example: A Shared Variable Cost Rate Limiter

An API specifies that you may make 5 “calls” per second, but some endpoints cost more than one call.

  • /lite costs 1 unit per call
  • /heavy costs 3 units per call
use tokio::time::{Instant, Duration};
use async_rate_limit::limiters::VariableCostRateLimiter;
use async_rate_limit::sliding_window::SlidingWindowRateLimiter;

#[tokio::main]
async fn main() -> () {
    let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 5);
     
    for _ in 0..3 {
        // these will proceed immediately, spending 3 units
        get_lite(&mut limiter).await;
    }

    // 3/5 units are spent, so this will wait for ~1s to proceed since it costs another 3
    get_heavy(&mut limiter).await;
}

// note the use of the `VariableCostRateLimiter` trait, rather than the direct type
async fn get_lite<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(1).await;
    println!("Lite: {:?}", Instant::now());
}

async fn get_heavy<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(3).await;
    println!("Heavy: {:?}", Instant::now());
}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<L> RateLimiter for L

Source§

fn wait_until_ready(&mut self) -> impl Future<Output = ()> + Send

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<L> VariableCostRateLimiter for L

Source§

fn wait_with_cost(&mut self, cost: usize) -> impl Future<Output = ()> + Send