Class: Berater::Limiter

Inherits:
Object
  • Object
show all
Defined in:
lib/berater/limiter.rb,
lib/berater/test_mode.rb

Defined Under Namespace

Modules: TestMode

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#capacityObject

Returns the value of attribute capacity.



4
5
6
# File 'lib/berater/limiter.rb', line 4

def capacity
  @capacity
end

#keyObject (readonly)

Returns the value of attribute key.



4
5
6
# File 'lib/berater/limiter.rb', line 4

def key
  @key
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/berater/limiter.rb', line 4

def options
  @options
end

Class Method Details

.newObject

Raises:

  • (NoMethodError)


55
56
57
58
59
60
# File 'lib/berater/limiter.rb', line 55

def self.new(*)
  # can only call via subclass
  raise NoMethodError if self == Berater::Limiter

  super
end

Instance Method Details

#==(other) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/berater/limiter.rb', line 46

def ==(other)
  self.class == other.class &&
  self.key == other.key &&
  self.capacity == other.capacity &&
  self.args == other.args &&
  self.options == other.options &&
  self.redis.connection == other.redis.connection
end

#limit(capacity: nil, cost: 1, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/berater/limiter.rb', line 10

def limit(capacity: nil, cost: 1, &block)
  capacity ||= @capacity

  unless capacity.is_a?(Numeric) && capacity >= 0
    raise ArgumentError, "invalid capacity: #{capacity}"
  end

  unless cost.is_a?(Numeric) && cost >= 0 && cost < Float::INFINITY
    raise ArgumentError, "invalid cost: #{cost}"
  end

  lock = acquire_lock(capacity, cost)

  if block_given?
    begin
      yield lock
    ensure
      lock.release
    end
  else
    lock
  end
end

#redisObject



6
7
8
# File 'lib/berater/limiter.rb', line 6

def redis
  options[:redis] || Berater.redis
end

#utilizationObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/berater/limiter.rb', line 34

def utilization
  lock = limit(cost: 0)

  if lock.capacity == 0
    1.0
  else
    lock.contention.to_f / lock.capacity
  end
rescue Berater::Overloaded
  1.0
end