Class: Berater::Limiter

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

Defined Under Namespace

Modules: TestMode

Constant Summary collapse

DEFAULT_COST =
1

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#capacityObject

Returns the value of attribute capacity.



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

def capacity
  @capacity
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

Class Method Details

.cache_key(key) ⇒ Object



132
133
134
135
# File 'lib/berater/limiter.rb', line 132

def cache_key(key)
  klass = to_s.split(':')[-1]
  "Berater:#{klass}:#{key}"
end

.new(*args, **kwargs) ⇒ Object

Raises:

  • (NoMethodError)


125
126
127
128
129
130
# File 'lib/berater/limiter.rb', line 125

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

  super
end

Instance Method Details

#==(other) ⇒ Object



75
76
77
78
79
80
81
82
# File 'lib/berater/limiter.rb', line 75

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(**opts, &block) ⇒ Object



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

def limit(**opts, &block)
  opts[:capacity] ||= @capacity
  opts[:cost] ||= DEFAULT_COST

  lock = Berater.middleware.call(self, **opts) do |limiter, **opts|
    limiter.inner_limit(**opts)
  end

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

#redisObject



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

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

#utilizationObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/berater/limiter.rb', line 63

def utilization
  lock = limit(cost: 0)

  if lock.capacity == 0
    100.0
  else
    lock.contention.to_f / lock.capacity * 100
  end
rescue Berater::Overloaded
  100.0
end