Class: Prop::IntervalStrategy

Inherits:
Object
  • Object
show all
Defined in:
lib/prop/interval_strategy.rb

Class Method Summary collapse

Class Method Details

.build(options) ⇒ Object

Builds the expiring cache key



28
29
30
31
32
33
34
35
36
37
# File 'lib/prop/interval_strategy.rb', line 28

def build(options)
  key       = options.fetch(:key)
  handle    = options.fetch(:handle)
  interval  = options.fetch(:interval)

  window    = (Time.now.to_i / interval)
  cache_key = Prop::Key.normalize([ handle, key, window ])

  "prop/v2/#{Digest::MD5.hexdigest(cache_key)}"
end

.compare_threshold?(counter, operator, options) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/prop/interval_strategy.rb', line 23

def compare_threshold?(counter, operator, options)
  counter.send operator, options.fetch(:threshold)
end

.counter(cache_key, options) ⇒ Object



8
9
10
# File 'lib/prop/interval_strategy.rb', line 8

def counter(cache_key, options)
  Prop::Limiter.cache.read(cache_key).to_i
end

.increment(cache_key, options) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
# File 'lib/prop/interval_strategy.rb', line 12

def increment(cache_key, options)
  increment = options.fetch(:increment, 1)
  raise ArgumentError, "Increment must be a Fixnum, was #{increment.class}" unless increment.is_a?(Fixnum)
  cache = Prop::Limiter.cache
  cache.increment(cache_key, increment) || (cache.write(cache_key, increment, raw: true) && increment) # WARNING: potential race condition
end

.reset(cache_key) ⇒ Object



19
20
21
# File 'lib/prop/interval_strategy.rb', line 19

def reset(cache_key)
  Prop::Limiter.cache.write(cache_key, 0, raw: true)
end

.threshold_reached(options) ⇒ Object



39
40
41
42
43
# File 'lib/prop/interval_strategy.rb', line 39

def threshold_reached(options)
  threshold = options.fetch(:threshold)

  "#{options[:handle]} threshold of #{threshold} tries per #{options[:interval]}s exceeded for key #{options[:key].inspect}, hash #{options[:cache_key]}"
end

.validate_options!(options) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/prop/interval_strategy.rb', line 45

def validate_options!(options)
  validate_positive_integer(options[:threshold], :threshold)
  validate_positive_integer(options[:interval], :interval)

  if options.key?(:increment)
    raise ArgumentError.new(":increment must be zero or a positive Integer") if !options[:increment].is_a?(Fixnum) || options[:increment] < 0
  end
end