Class: Berater::Limiter
- Inherits:
-
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
#capacity ⇒ Object
Returns the value of attribute capacity.
5
6
7
|
# File 'lib/berater/limiter.rb', line 5
def capacity
@capacity
end
|
#key ⇒ Object
Returns the value of attribute key.
5
6
7
|
# File 'lib/berater/limiter.rb', line 5
def key
@key
end
|
#options ⇒ Object
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
135
136
137
138
|
# File 'lib/berater/limiter.rb', line 135
def cache_key(key)
klass = to_s.split(':')[-1]
"Berater:#{klass}:#{key}"
end
|
.new(*args, **kwargs) ⇒ Object
123
124
125
126
127
128
129
130
131
132
133
|
# File 'lib/berater/limiter.rb', line 123
def new(*args, **kwargs)
raise NoMethodError if self == Berater::Limiter
if RUBY_VERSION < '3' && kwargs.empty?
super(*args)
else
super
end
end
|
Instance Method Details
#==(other) ⇒ Object
73
74
75
76
77
78
79
80
|
# File 'lib/berater/limiter.rb', line 73
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
|
#redis ⇒ Object
7
8
9
|
# File 'lib/berater/limiter.rb', line 7
def redis
options[:redis] || Berater.redis
end
|
#utilization ⇒ Object
61
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/berater/limiter.rb', line 61
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
|