Class: HttpThreshold::Throttle

Inherits:
Object
  • Object
show all
Defined in:
lib/http_threshold/throttle.rb

Constant Summary collapse

MANDATORY_OPTIONS =
[:limit, :period]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options) ⇒ Throttle

Returns a new instance of Throttle.



6
7
8
9
10
11
12
13
# File 'lib/http_threshold/throttle.rb', line 6

def initialize(name, options)
  @name = name
  MANDATORY_OPTIONS.each do |opt|
    raise ArgumentError.new("Must pass #{opt.inspect} option") unless options[opt]
  end
  @limit  = options[:limit]
  @period = options[:period].to_i
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



5
6
7
# File 'lib/http_threshold/throttle.rb', line 5

def block
  @block
end

#limitObject (readonly)

Returns the value of attribute limit.



5
6
7
# File 'lib/http_threshold/throttle.rb', line 5

def limit
  @limit
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/http_threshold/throttle.rb', line 5

def name
  @name
end

#periodObject (readonly)

Returns the value of attribute period.



5
6
7
# File 'lib/http_threshold/throttle.rb', line 5

def period
  @period
end

#typeObject (readonly)

Returns the value of attribute type.



5
6
7
# File 'lib/http_threshold/throttle.rb', line 5

def type
  @type
end

Instance Method Details

#cacheObject



15
16
17
# File 'lib/http_threshold/throttle.rb', line 15

def cache
  HttpThreshold::Client.cache
end

#incr_countObject

similar as method #[]



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/http_threshold/throttle.rb', line 24

def incr_count
  begin
    result = lock_manager.lock!("lock:#{name}", 2000) do
      if reach_limit?
        false
      else
        cache.count(threshold_key, period)
        true
      end
    end
    result
  rescue Redlock::LockError
    sleep 0.25
    retry
  end
end

#lock_managerObject



19
20
21
# File 'lib/http_threshold/throttle.rb', line 19

def lock_manager
  HttpThreshold::Client.lock_manager
end

#reach_limit?Boolean

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/http_threshold/throttle.rb', line 41

def reach_limit?
  count = cache.read_count(threshold_key, period)
  count >= limit
end

#statusObject



46
47
48
49
# File 'lib/http_threshold/throttle.rb', line 46

def status
  count = cache.read_count(threshold_key, period)
  "#{count}/#{limit}"
end

#threshold_keyObject



51
52
53
# File 'lib/http_threshold/throttle.rb', line 51

def threshold_key
  "threshold:#{name}"
end