pub struct RateLimiter { /* private fields */ }Expand description
Thread-safe rate limiter.
Implementations§
Source§impl RateLimiter
impl RateLimiter
Sourcepub fn new(config: RateLimitConfig) -> Self
pub fn new(config: RateLimitConfig) -> Self
Create a new rate limiter.
Sourcepub fn is_enabled(&self) -> bool
pub fn is_enabled(&self) -> bool
Check if rate limiting is enabled.
Sourcepub fn check(&self, ip: IpAddr) -> RateLimitDecision
pub fn check(&self, ip: IpAddr) -> RateLimitDecision
Check if a request from the given IP should be allowed.
Sourcepub fn refund(&self, ip: IpAddr, charge: RateLimitCharge)
pub fn refund(&self, ip: IpAddr, charge: RateLimitCharge)
Give back the exact slot charge took.
For a request whose legitimacy is only established after the limiter has already had to decide. A device proves its enrolment token in the first WebSocket frame, long after the middleware ran on the upgrade request, so the choice is between not limiting those routes at all — which is where an enrolment token could be guessed at line speed — and charging every attempt and refunding the ones that turn out to be authenticated. This is the second: what accumulates in the bucket is failed and abandoned attempts, which is exactly what the limit is for.
Removing the slot by identity rather than dropping the newest one is what keeps this from handing out credit. The two differ whenever the charge being refunded has already aged out of the window — a device may take seconds to send its first frame — and dropping the newest would then free a live slot belonging to whoever else is calling from that address. A charge that is already gone refunds nothing, which is right: the window has released it once already.
Sourcepub fn stats(&self) -> RateLimitStats
pub fn stats(&self) -> RateLimitStats
Get current stats.