RateLimiter

Struct RateLimiter 

Source
pub struct RateLimiter<B: CacheBackend> {
    pub cache: Arc<B>,
    pub limit: u32,
    pub ttl: Duration,
}
Expand description

The RateLimiter struct for distributed, IP-based rate limiting.

§Type Parameters:

  • B: A type that implements the CacheBackend trait.

Fields§

§cache: Arc<B>

The caching backend instance (e.g., Redis, in-memory, etc.).

§limit: u32

Maximum allowed requests within a TTL window.

§ttl: Duration

Duration of the rate limiting window.

Implementations§

Source§

impl<B: CacheBackend> RateLimiter<B>

Source

pub fn new(cache: Arc<B>, limit: u32, ttl: Duration) -> Self

Constructs a new RateLimiter.

§Arguments
  • cache - A caching backend instance wrapped in Arc.
  • limit - Maximum number of allowed requests in the TTL window.
  • ttl - Duration for the rate limiting window.
Source

pub fn allow(&self, ip: &str) -> bool

Checks whether a request from the given IP is allowed.

This method does the following:

  1. Builds a key using the client’s IP.
  2. Retrieves the current request count from the cache.
  3. If under the limit, increments the count.
    • If this is the first request, sets the TTL for that key.
  4. Returns true if the request is allowed, or false if the limit is exceeded.
§Arguments
  • ip - A string slice representing the client’s IP address.
§Returns
  • true if the request is allowed; false otherwise.

Auto Trait Implementations§

§

impl<B> Freeze for RateLimiter<B>

§

impl<B> RefUnwindSafe for RateLimiter<B>
where B: RefUnwindSafe,

§

impl<B> Send for RateLimiter<B>

§

impl<B> Sync for RateLimiter<B>

§

impl<B> Unpin for RateLimiter<B>

§

impl<B> UnwindSafe for RateLimiter<B>
where B: RefUnwindSafe,

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> 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<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.