Skip to content

Commit

Permalink
Add a seperate cache-store proxy for the redis gem
Browse files Browse the repository at this point in the history
While a cache-store proxy exists for the redis-store gem, no such proxy
existed for using the redis gem itself. This fills that gap by adding
such a proxy.

Resolves #190
  • Loading branch information
bfad committed Feb 6, 2018
1 parent 39c04b3 commit 0f6ef47
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/rack/attack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Rack::Attack
autoload :DalliProxy, 'rack/attack/store_proxy/dalli_proxy'
autoload :MemCacheProxy, 'rack/attack/store_proxy/mem_cache_proxy'
autoload :RedisStoreProxy, 'rack/attack/store_proxy/redis_store_proxy'
autoload :RedisProxy, 'rack/attack/store_proxy/redis_proxy'
autoload :Fail2Ban, 'rack/attack/fail2ban'
autoload :Allow2Ban, 'rack/attack/allow2ban'
autoload :Request, 'rack/attack/request'
Expand Down
4 changes: 2 additions & 2 deletions lib/rack/attack/store_proxy.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
module Rack
class Attack
module StoreProxy
PROXIES = [DalliProxy, MemCacheProxy, RedisStoreProxy].freeze
PROXIES = [DalliProxy, MemCacheProxy, RedisStoreProxy, RedisProxy].freeze

ACTIVE_SUPPORT_WRAPPER_CLASSES = Set.new(['ActiveSupport::Cache::MemCacheStore', 'ActiveSupport::Cache::RedisStore']).freeze
ACTIVE_SUPPORT_CLIENTS = Set.new(['Redis::Store', 'Dalli::Client', 'MemCache']).freeze
ACTIVE_SUPPORT_CLIENTS = Set.new(['Redis::Store', 'Redis', 'Dalli::Client', 'MemCache']).freeze

def self.build(store)
client = unwrap_active_support_stores(store)
Expand Down
44 changes: 44 additions & 0 deletions lib/rack/attack/store_proxy/redis_proxy.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
require 'delegate'

module Rack
class Attack
module StoreProxy
class RedisProxy < SimpleDelegator
def self.handle?(store)
defined?(::Redis) && store.is_a?(::Redis)
end

def initialize(store)
super(store)
end

def read(key)
get(key)
end

def write(key, value, options={})
if (expires_in = options[:expires_in])
setex(key, expires_in, value)
else
set(key, value)
end
end

def increment(key, amount, options={})
count = nil

pipelined do
count = incrby(key, amount)
expire(key, options[:expires_in]) if options[:expires_in]
end

count.value if count
end

def delete(key, options={})
del(key)
end
end
end
end
end
3 changes: 2 additions & 1 deletion spec/integration/rack_attack_cache_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def sleep_until_expired
ActiveSupport::Cache::MemCacheStore.new("127.0.0.1"),
Dalli::Client.new,
ConnectionPool.new { Dalli::Client.new },
Redis::Store.new
Redis::Store.new,
Redis.new
]

cache_stores.each do |store|
Expand Down

0 comments on commit 0f6ef47

Please sign in to comment.