From 6e862e0e59163cf79e020e176ffff81758d6dd12 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Thu, 29 Jan 2015 11:44:51 -0500 Subject: [PATCH] FIX: Should flush rate limit keys before testing it --- lib/discourse_redis.rb | 4 ++-- lib/rate_limiter.rb | 16 +++++++++++----- spec/models/topic_spec.rb | 1 + 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/discourse_redis.rb b/lib/discourse_redis.rb index fe5a6950967..a41f05c1a59 100644 --- a/lib/discourse_redis.rb +++ b/lib/discourse_redis.rb @@ -63,9 +63,9 @@ class DiscourseRedis @redis.del k end - def keys + def keys(pattern=nil) len = DiscourseRedis.namespace.length + 1 - @redis.keys("#{DiscourseRedis.namespace}:*").map{ + @redis.keys("#{DiscourseRedis.namespace}:#{pattern || '*'}").map{ |k| k[len..-1] } end diff --git a/lib/rate_limiter.rb b/lib/rate_limiter.rb index 817d7389a46..4a93982711c 100644 --- a/lib/rate_limiter.rb +++ b/lib/rate_limiter.rb @@ -4,6 +4,8 @@ require_dependency 'rate_limiter/on_create_record' # A redis backed rate limiter. class RateLimiter + KEY_PREFIX = "l-rate-limit:" + def self.disable @disabled = true end @@ -17,9 +19,13 @@ class RateLimiter @disabled || Rails.env.test? end + def self.clear_all! + $redis.keys("#{KEY_PREFIX}:*").each { |k| $redis.del(k) } + end + def initialize(user, key, max, secs) @user = user - @key = "l-rate-limit:#{@user && @user.id}:#{key}" + @key = "#{KEY_PREFIX}:#{@user && @user.id}:#{key}" @max = max @secs = secs end @@ -64,10 +70,10 @@ class RateLimiter end def is_under_limit? - # number of events in buffer less than max allowed? OR - ($redis.llen(@key) < @max) || - # age bigger than silding window size? - (age_of_oldest > @secs) + # number of events in buffer less than max allowed? OR + ($redis.llen(@key) < @max) || + # age bigger than silding window size? + (age_of_oldest > @secs) end def rate_unlimited? diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index 8f0f9594ba4..6bafe639a9b 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -1245,6 +1245,7 @@ describe Topic do SiteSetting.stubs(:client_settings_json).returns(SiteSetting.client_settings_json_uncached) RateLimiter.stubs(:rate_limit_create_topic).returns(100) RateLimiter.stubs(:disabled?).returns(false) + RateLimiter.clear_all! start = Time.now.tomorrow.beginning_of_day