Class: Rapidity::Limiter
- Inherits:
-
Object
- Object
- Rapidity::Limiter
- Defined in:
- lib/rapidity/limiter.rb
Instance Attribute Summary collapse
-
#interval ⇒ Object
readonly
Returns the value of attribute interval.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#namespace ⇒ Object
readonly
Returns the value of attribute namespace.
-
#pool ⇒ Object
readonly
Returns the value of attribute pool.
-
#threshold ⇒ Object
readonly
Returns the value of attribute threshold.
Instance Method Summary collapse
-
#initialize(pool, name:, interval: 10, threshold: 10, namespace: 'rapidity') ⇒ Limiter
constructor
Convert message to given class.
- #key(path) ⇒ Object
-
#obtain(count = 5) ⇒ Object
Obtain values from counter.
-
#remains ⇒ Object
Get current counter.
Constructor Details
#initialize(pool, name:, interval: 10, threshold: 10, namespace: 'rapidity') ⇒ Limiter
Convert message to given class
16 17 18 19 20 21 22 23 |
# File 'lib/rapidity/limiter.rb', line 16 def initialize(pool, name:, interval: 10, threshold: 10, namespace: 'rapidity') @pool = pool @interval = interval @threshold = threshold @name = name @namespace = namespace end |
Instance Attribute Details
#interval ⇒ Object (readonly)
Returns the value of attribute interval.
7 8 9 |
# File 'lib/rapidity/limiter.rb', line 7 def interval @interval end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
7 8 9 |
# File 'lib/rapidity/limiter.rb', line 7 def name @name end |
#namespace ⇒ Object (readonly)
Returns the value of attribute namespace.
7 8 9 |
# File 'lib/rapidity/limiter.rb', line 7 def namespace @namespace end |
#pool ⇒ Object (readonly)
Returns the value of attribute pool.
7 8 9 |
# File 'lib/rapidity/limiter.rb', line 7 def pool @pool end |
#threshold ⇒ Object (readonly)
Returns the value of attribute threshold.
7 8 9 |
# File 'lib/rapidity/limiter.rb', line 7 def threshold @threshold end |
Instance Method Details
#key(path) ⇒ Object
25 26 27 |
# File 'lib/rapidity/limiter.rb', line 25 def key(path) "#{namespace}:#{name}_#{path}" end |
#obtain(count = 5) ⇒ Object
Obtain values from counter
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/rapidity/limiter.rb', line 43 def obtain(count = 5) count = count.abs _, taken = @pool.with do |conn| conn.multi do conn.set(key('remains'), threshold, ex: interval, nx: true) conn.decrby(key('remains'), count) end end if taken < 0 overflow = taken.abs to_return = [count, overflow].min @pool.with do |conn| conn.multi do conn.set(key('remains'), threshold - to_return, ex: interval, nx: true) conn.incrby(key('remains'), to_return) end end count - to_return else count end end |
#remains ⇒ Object
Get current counter
31 32 33 34 35 36 37 38 39 |
# File 'lib/rapidity/limiter.rb', line 31 def remains _, result = @pool.with do |conn| conn.multi do conn.set(key('remains'), threshold, ex: interval, nx: true) conn.get(key('remains')) end end result.to_i end |