From d9d2735efae31b4bf3732ca524cd6e4a398bcee6 Mon Sep 17 00:00:00 2001 From: Paul Makles Date: Wed, 18 Jan 2023 18:26:00 +0000 Subject: [PATCH] fix(ratelimiter): re-calculate reset time closes #204 Co-authored-by: TheBobBobs <84781603+TheBobBobs@users.noreply.github.com> --- crates/quark/src/web/ratelimiter.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/quark/src/web/ratelimiter.rs b/crates/quark/src/web/ratelimiter.rs index f7e0dd62..d77701db 100644 --- a/crates/quark/src/web/ratelimiter.rs +++ b/crates/quark/src/web/ratelimiter.rs @@ -51,7 +51,7 @@ impl Entry { } /// Deduct one unit from the bucket and save - pub fn deduct(mut self, key: u64) { + pub fn deduct(mut self) { let current_time = now().as_millis(); if current_time > self.reset { self.used = 1; @@ -59,7 +59,10 @@ impl Entry { } else { self.used += 1; } + } + /// Save information + pub fn save(self, key: u64) { MAP.insert(key, self); } @@ -189,10 +192,12 @@ impl Ratelimiter { let entry = Entry::from(key); let remaining = entry.get_remaining(limit); - let reset = entry.left_until_reset(); - if remaining > 0 { - entry.deduct(key); + entry.deduct(); + + let reset = entry.left_until_reset(); + entry.save(key); + Ok(Ratelimiter { key, limit, @@ -200,7 +205,7 @@ impl Ratelimiter { reset, }) } else { - Err(reset) + Err(entry.left_until_reset()) } } }