This repository has been archived by the owner on Oct 16, 2018. It is now read-only.
forked from rack/rack-attack
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from deliveroo/support-redis-distributed
Support Redis:DistributedStore
- Loading branch information
Showing
4 changed files
with
44 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
lib/rack/attack/store_proxy/redis_distributed_store_proxy.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
require 'delegate' | ||
require 'rack/attack/store_proxy/redis_store_proxy' | ||
|
||
module Rack | ||
class Attack | ||
module StoreProxy | ||
class RedisDistributedStoreProxy < RedisStoreProxy | ||
def self.handle?(store) | ||
defined?(::Redis::DistributedStore) && store.is_a?(::Redis::DistributedStore) | ||
end | ||
|
||
# overrride #increment to use a Lua script as Redis::Distributed | ||
# does not support pipelining (even when all keys got to the same node) | ||
def increment(key, amount, options={}) | ||
evalsha(script_sha, keys: [key], argv:[amount, options[:expires_in]]) | ||
rescue Redis::BaseError | ||
end | ||
|
||
private | ||
|
||
def script_sha | ||
@script_sha ||= begin | ||
shas = script 'load', %{ | ||
-- KEYS[1]: key to increment | ||
-- ARGV[1]: amount to increment by | ||
-- ARGV[2]: updated TTL if any | ||
local value = redis.call('INCRBY', KEYS[1], tonumber(ARGV[1])) | ||
local ttl = tonumber(ARGV[2]) | ||
if ttl then | ||
redis.call('EXPIRE', KEYS[1], ttl) | ||
end | ||
return value | ||
} | ||
shas.kind_of?(Array) ? shas.first : shas | ||
end | ||
end | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters