From 554f1d6f57cbab8c1600100f8be61f1388f25878 Mon Sep 17 00:00:00 2001 From: Mingwei Samuel Date: Sat, 24 Feb 2024 20:49:36 -0800 Subject: [PATCH] refactor: avoid `Instant` underflow in wasm `web-time` (#63) --- riven/src/req/token_bucket.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/riven/src/req/token_bucket.rs b/riven/src/req/token_bucket.rs index f1825b0..ac44a73 100644 --- a/riven/src/req/token_bucket.rs +++ b/riven/src/req/token_bucket.rs @@ -112,10 +112,13 @@ impl VectorTokenBucket { fn update_get_timestamps(&self) -> MutexGuard> { let mut timestamps = self.timestamps.lock(); - let cutoff = Instant::now() - self.duration - self.duration_overhead; - // Pop off timestamps that are beyound the bucket duration. - while timestamps.back().map_or(false, |ts| *ts < cutoff) { - timestamps.pop_back(); + // Only `None` in wasm, for some implementation reason. Probably sets time 0 at the first + // `Instant::now()` call or something. + if let Some(cutoff) = Instant::now().checked_sub(self.duration + self.duration_overhead) { + // Pop off timestamps that are beyound the bucket duration. + while timestamps.back().map_or(false, |ts| *ts < cutoff) { + timestamps.pop_back(); + } } timestamps }