lib/pause/redis/adapter.rb in pause-0.2.1 vs lib/pause/redis/adapter.rb in pause-0.4.0
- old
+ new
@@ -3,32 +3,46 @@
module Pause
module Redis
# This class encapsulates Redis operations used by Pause
class Adapter
+ class << self
+ def redis
+ @redis_conn ||= ::Redis.new(redis_connection_opts)
+ end
+ def redis_connection_opts
+ { host: Pause.config.redis_host,
+ port: Pause.config.redis_port,
+ db: Pause.config.redis_db }
+ end
+ end
+
include Pause::Helper::Timing
attr_accessor :resolution, :time_blocks_to_keep, :history
def initialize(config)
- @resolution = config.resolution
+ @resolution = config.resolution
@time_blocks_to_keep = config.history / @resolution
- @history = config.history
+ @history = config.history
end
+ # Override in subclasses to disable
+ def with_multi
+ redis.multi do |redis|
+ yield(redis) if block_given?
+ end
+ end
+
def increment(scope, identifier, timestamp, count = 1)
k = tracked_key(scope, identifier)
- redis.multi do |redis|
+ with_multi do |redis|
redis.zincrby k, count, period_marker(resolution, timestamp)
redis.expire k, history
end
- if redis.zcard(k) > time_blocks_to_keep
- list = extract_set_elements(k)
- to_remove = list.slice(0, (list.size - time_blocks_to_keep))
- redis.zrem(k, to_remove.map(&:ts))
- end
+ truncate_set_for(k)
end
def key_history(scope, identifier)
extract_set_elements(tracked_key(scope, identifier))
end
@@ -76,11 +90,11 @@
def enable(scope)
redis.del("internal:|#{scope}|:disabled")
end
def disabled?(scope)
- ! enabled?(scope)
+ !enabled?(scope)
end
def enabled?(scope)
redis.get("internal:|#{scope}|:disabled").nil?
end
@@ -89,21 +103,27 @@
redis.zremrangebyscore rate_limited_list(scope), '-inf', Time.now.to_i
end
private
- def delete_tracking_keys(scope, ids)
- increment_keys = ids.map{ |key| tracked_key(scope, key) }
- redis.del(increment_keys)
+ def redis
+ self.class.redis
end
- def redis
- @redis_conn ||= ::Redis.new(host: Pause.config.redis_host,
- port: Pause.config.redis_port,
- db: Pause.config.redis_db)
+ def truncate_set_for(k)
+ if redis.zcard(k) > time_blocks_to_keep
+ list = extract_set_elements(k)
+ to_remove = list.slice(0, (list.size - time_blocks_to_keep)).map(&:ts)
+ redis.zrem(k, to_remove) if k && to_remove && to_remove.size > 0
+ end
end
+ def delete_tracking_keys(scope, ids)
+ increment_keys = ids.map { |key| tracked_key(scope, key) }
+ redis.del(increment_keys)
+ end
+
def tracked_scope(scope)
['i', scope].join(':')
end
def tracked_key(scope, identifier)
@@ -115,10 +135,10 @@
"b:|#{scope}|"
end
def keys(key_scope)
redis.keys("#{key_scope}:*").map do |key|
- key.gsub(/^#{key_scope}:/, "").tr('|','')
+ key.gsub(/^#{key_scope}:/, "").tr('|', '')
end
end
def extract_set_elements(key)
(redis.zrange key, 0, -1, with_scores: true).map do |slice|