Class: Rapidity::Limiter

Inherits:
Object
  • Object
show all
Defined in:
lib/rapidity/limiter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#intervalObject (readonly)

Returns the value of attribute interval.



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

def interval
  @interval
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



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

def namespace
  @namespace
end

#poolObject (readonly)

Returns the value of attribute pool.



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

def pool
  @pool
end

#thresholdObject (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

Returns:

  • count succesfuly obtained send slots



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

#remainsObject

Get current counter

Returns:

  • remaining counter value



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