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



39
40
41
42
43
44
45
46
47
48
# File 'lib/prop/interval_strategy.rb', line 39

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

.change(cache_key, options) ⇒ Object

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
23
# File 'lib/prop/interval_strategy.rb', line 16

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

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

Returns:

  • (Boolean)


29
30
31
32
# File 'lib/prop/interval_strategy.rb', line 29

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

.counter(cache_key, options) ⇒ Object



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

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

.first_throttled?(counter, options) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/prop/interval_strategy.rb', line 34

def first_throttled?(counter, options)
  (counter - options.fetch(:increment, 1)) <= options.fetch(:threshold)
end

.reset(cache_key) ⇒ Object



25
26
27
# File 'lib/prop/interval_strategy.rb', line 25

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

.threshold_reached(options) ⇒ Object



50
51
52
53
54
# File 'lib/prop/interval_strategy.rb', line 50

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



56
57
58
59
60
61
62
63
64
# File 'lib/prop/interval_strategy.rb', line 56

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

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

.zero_counterObject



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

def zero_counter
  0
end