From 3209f628b002b6f30db68b17d5be050897f69304 Mon Sep 17 00:00:00 2001 From: Matt Madigan Date: Thu, 26 May 2022 10:32:34 +1200 Subject: [PATCH] Change to using UTC time stamps, Add TTL to keys --- RateLimit.Redis/Decepticon.RateLimit.Redis.csproj | 2 +- RateLimit.Redis/Helpers/DateTimeHelpers.cs | 2 +- RateLimit.Redis/RateLimiter.cs | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/RateLimit.Redis/Decepticon.RateLimit.Redis.csproj b/RateLimit.Redis/Decepticon.RateLimit.Redis.csproj index 38822c7..0c25571 100644 --- a/RateLimit.Redis/Decepticon.RateLimit.Redis.csproj +++ b/RateLimit.Redis/Decepticon.RateLimit.Redis.csproj @@ -19,7 +19,7 @@ Donate via Paypal: dekcodeofficial@gmail.com icon.png true - 1.0.0 + 1.1.0 diff --git a/RateLimit.Redis/Helpers/DateTimeHelpers.cs b/RateLimit.Redis/Helpers/DateTimeHelpers.cs index f56774f..ef3414d 100644 --- a/RateLimit.Redis/Helpers/DateTimeHelpers.cs +++ b/RateLimit.Redis/Helpers/DateTimeHelpers.cs @@ -17,7 +17,7 @@ internal static class DateTimeHelpers public static DateTime UnixTimeStampToDateTime(double unixTimeStampInSeconds) { // Unix timestamp is seconds past epoch - return _Epoch.AddSeconds(unixTimeStampInSeconds).ToLocalTime(); + return _Epoch.AddSeconds(unixTimeStampInSeconds).ToUniversalTime(); } } } diff --git a/RateLimit.Redis/RateLimiter.cs b/RateLimit.Redis/RateLimiter.cs index 74997d3..3526208 100644 --- a/RateLimit.Redis/RateLimiter.cs +++ b/RateLimit.Redis/RateLimiter.cs @@ -176,6 +176,7 @@ public ThrottleRateLimitResult Validate(ThrottleRateLimitRequest request) local count = tonumber(ARGV[3]) local ticks = currentTimeTicks local result = 1 + local ttl = 86400 -- Try getting tracking config from existing record local countStr = redis.call('GET', KEYS[1]) @@ -206,6 +207,9 @@ public ThrottleRateLimitResult Validate(ThrottleRateLimitRequest request) -- Consume a token count = count - 1 + + -- Get seconds for a complete refill, and then add 1hr to prevent deleting keys too frequently + ttl = (capacity / refillRate) + 3600 -- Determine the outcome if count < 0 then @@ -213,8 +217,8 @@ public ThrottleRateLimitResult Validate(ThrottleRateLimitRequest request) count = 0 end - redis.call('SET', KEYS[1], count) - redis.call('SET', KEYS[2], ticks) + redis.call('SET', KEYS[1], count, 'EX', ttl) + redis.call('SET', KEYS[2], ticks, 'EX', ttl) return result .. ',' .. math.abs(10000000 / refillRate) ";