Skip to main content

RateLimit

Struct RateLimit 

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

A rate limiter, usable as a plugin or as scoped middleware.

Construct with per_second, per_minute, per_hour or per, then refine with burst and by.

Cloning shares the underlying table, so the same limiter can be installed in several places and still count one budget.

Implementations§

Source§

impl RateLimit

Source

pub fn per(limit: u32, period: Duration) -> Self

Allow limit requests per period, per key.

The initial burst equals limit: a key that has been quiet may spend its whole allowance at once and then refills at limit / period. Narrow that with burst.

§Panics

If limit is zero, or period is zero. Both describe a limiter that can never admit anything, which is a configuration mistake rather than a policy, and failing at startup is the repo’s rule for those.

Source

pub fn per_second(limit: u32) -> Self

Allow limit requests per second, per key.

Source

pub fn per_minute(limit: u32) -> Self

Allow limit requests per minute, per key.

Source

pub fn per_hour(limit: u32) -> Self

Allow limit requests per hour, per key.

Source

pub fn burst(self, burst: u32) -> Self

Cap the instantaneous burst at burst requests.

The sustained rate is unchanged. burst(1) admits no burst at all: requests must be spaced by a full emission interval.

§Panics

If burst is zero.

Source

pub fn by<F>(self, f: F) -> Self
where F: Fn(&Call) -> Option<String> + Send + Sync + 'static,

Derive the bucket key from the call instead of using the peer IP.

Returning None exempts the request from limiting entirely, which is how you let health checks or an authenticated internal caller through.

The key is hashed and dropped rather than kept, so its length costs nothing beyond the one call and a caller-supplied value needs no length check of its own before it is handed over.

use churust_ratelimit::RateLimit;

// Per API key, falling back to no limit for unauthenticated callers.
let limiter = RateLimit::per_minute(60)
    .by(|call| call.header("x-api-key").map(str::to_owned));
Source

pub fn max_keys(self, n: usize) -> Self

Set how many keys are tracked before the table is pruned.

The table holds a 64-bit digest of the key and one timestamp per active client, so an entry costs the same whatever the key is and the default of 100,000 is a few megabytes for any by function. Raise it for a large fleet, lower it for a memory-constrained deployment.

§Panics

If n is zero.

Trait Implementations§

Source§

impl Clone for RateLimit

Source§

fn clone(&self) -> RateLimit

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for RateLimit

Source§

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

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

impl Middleware for RateLimit

Source§

fn handle<'life0, 'async_trait>( &'life0 self, call: Call, next: Next, ) -> Pin<Box<dyn Future<Output = Response> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Handle the call: optionally inspect/modify it, call next.run(call) to proceed, and return the (possibly post-processed) response.
Source§

impl Plugin for RateLimit

Source§

fn install(self: Box<Self>, app: &mut AppBuilder)

Installed in Phase::Plugins, so a rejected request is still logged by a CallLogging plugin sitting in Phase::Monitoring outside it.

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, dest: *mut u8)

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

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Same for T

Source§

type Output = T

Should always be Self
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<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more