From 5a9622163df65a77979ebe24a6bb6e9e12f09400 Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 4 Dec 2017 21:44:16 +1100 Subject: [PATCH] FIX: regression around rate limiter --- lib/rate_limiter.rb | 8 ++++---- lib/rate_limiter/limit_exceeded.rb | 2 +- spec/components/rate_limiter_spec.rb | 14 ++++++++++++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/rate_limiter.rb b/lib/rate_limiter.rb index 06759cbbc48..65edfd64df9 100644 --- a/lib/rate_limiter.rb +++ b/lib/rate_limiter.rb @@ -7,7 +7,7 @@ class RateLimiter attr_reader :max, :secs, :user, :key def self.key_prefix - "l-rate-limit:" + "l-rate-limit2:" end def self.disable @@ -76,7 +76,7 @@ class RateLimiter def performed! return if rate_unlimited? - now = Process.clock_gettime(Process::CLOCK_MONOTONIC) + now = Process.clock_gettime(Process::CLOCK_MONOTONIC).to_i if eval_lua(PERFORM_LUA, PERFORM_LUA_SHA, [prefixed_key], [now, @secs, @max]) == 0 raise RateLimiter::LimitExceeded.new(seconds_to_wait, @type) end @@ -97,7 +97,7 @@ class RateLimiter return @max if @user && @user.staff? arr = redis.lrange(prefixed_key, 0, @max) || [] - t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC) + t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC).to_i arr.reject! { |a| (t0 - a.to_i) > @secs } @max - arr.size end @@ -122,7 +122,7 @@ class RateLimiter def age_of_oldest # age of oldest event in buffer, in seconds - Process.clock_gettime(Process::CLOCK_MONOTONIC) - redis.lrange(prefixed_key, -1, -1).first.to_i + Process.clock_gettime(Process::CLOCK_MONOTONIC).to_i - redis.lrange(prefixed_key, -1, -1).first.to_i end def is_under_limit? diff --git a/lib/rate_limiter/limit_exceeded.rb b/lib/rate_limiter/limit_exceeded.rb index 0836ecd3a7e..67197b1deab 100644 --- a/lib/rate_limiter/limit_exceeded.rb +++ b/lib/rate_limiter/limit_exceeded.rb @@ -2,7 +2,7 @@ class RateLimiter # A rate limit has been exceeded. class LimitExceeded < StandardError - attr_reader :type + attr_reader :type, :available_in def initialize(available_in, type = nil) @available_in = available_in diff --git a/spec/components/rate_limiter_spec.rb b/spec/components/rate_limiter_spec.rb index 76e99b38f5c..9b7877996b8 100644 --- a/spec/components/rate_limiter_spec.rb +++ b/spec/components/rate_limiter_spec.rb @@ -39,12 +39,22 @@ describe RateLimiter do context 'global rate limiter' do it 'can operate in global mode' do - limiter = RateLimiter.new(nil, "test", 2, 10, global: true) + limiter = RateLimiter.new(nil, "test", 2, 30, global: true) limiter.clear! + thrown = false + limiter.performed! limiter.performed! - expect { limiter.performed! }.to raise_error(RateLimiter::LimitExceeded) + begin + limiter.performed! + rescue RateLimiter::LimitExceeded => e + expect(e.available_in.class).to eq(Integer) + expect(e.available_in).to be > 28 + expect(e.available_in).to be < 32 + thrown = true + end + expect(thrown).to be(true) end end