Class: Prop::IntervalStrategy

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

Class Method Summary collapse

Class Method Details

.at_threshold?(counter, options) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/prop/interval_strategy.rb', line 21

def at_threshold?(counter, options)
  counter >= options.fetch(:threshold)
end

.build(options) ⇒ Object

Builds the expiring cache key



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

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/#{Digest::MD5.hexdigest(cache_key)}"
end

.counter(cache_key, options) ⇒ Object



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

def counter(cache_key, options)
  Prop::Limiter.reader.call(cache_key).to_i
end

.increment(cache_key, options, counter) ⇒ Object



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

def increment(cache_key, options, counter)
  increment = options.fetch(:increment, 1)
  Prop::Limiter.writer.call(cache_key, counter + increment)
end

.reset(cache_key) ⇒ Object



17
18
19
# File 'lib/prop/interval_strategy.rb', line 17

def reset(cache_key)
  Prop::Limiter.writer.call(cache_key, 0)
end

.threshold_reached(options) ⇒ Object



37
38
39
40
41
# File 'lib/prop/interval_strategy.rb', line 37

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



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

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