From 87f628d0c10c8df5d042e27e8fd5c5ae3ae50d7e Mon Sep 17 00:00:00 2001 From: Will Kimeria Date: Fri, 14 Mar 2014 11:50:59 -0700 Subject: [PATCH] If redis client throws exception, don't raise it For throttling, when the redis client throws an exception, the request ends up getting rate limited. Modify this to be similar to how ActiveSupport.MemCacheStore functions (the read, write and increment methods do not raise exceptions) --- lib/rack/attack/store_proxy.rb | 6 ++++++ spec/rack_attack_cache_spec.rb | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/rack/attack/store_proxy.rb b/lib/rack/attack/store_proxy.rb index 0c65aee..6f6a507 100644 --- a/lib/rack/attack/store_proxy.rb +++ b/lib/rack/attack/store_proxy.rb @@ -26,6 +26,8 @@ module Rack def read(key) self.get(key) + rescue Redis::BaseError + nil end def write(key, value, options={}) @@ -34,6 +36,8 @@ module Rack else self.set(key, value) end + rescue Redis::BaseError + nil end def increment(key, amount, options={}) @@ -43,6 +47,8 @@ module Rack self.expire(key, options[:expires_in]) if options[:expires_in] end count.value if count + rescue Redis::BaseError + nil end end diff --git a/spec/rack_attack_cache_spec.rb b/spec/rack_attack_cache_spec.rb index 3f7fac9..0016ff9 100644 --- a/spec/rack_attack_cache_spec.rb +++ b/spec/rack_attack_cache_spec.rb @@ -78,6 +78,34 @@ if ENV['TEST_INTEGRATION'] end + describe "should not error if redis is not running" do + before { + @cache = Rack::Attack::Cache.new + @key = "rack::attack:cache-test-key" + @expires_in = 1 + # Use ip reserved for documentation to ensure it does not exist + # http://tools.ietf.org/html/rfc5737 + @cache.store = ActiveSupport::Cache::RedisStore.new(:host => '203.0.113.0', :port => 3333) + } + describe "write" do + it "should not raise exception" do + @cache.write("cache-test-key", "foobar", 1) + end + end + + describe "read" do + it "should not raise exception" do + @cache.read("cache-test-key") + end + end + + describe "do_count" do + it "should not raise exception" do + @cache.send(:do_count, @key, @expires_in) + end + end + end + end else puts 'Skipping cache store integration tests (set ENV["TEST_INTEGRATION"] to enable)'