Class: Limiter::RateQueue

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

Constant Summary collapse

EPOCH =
0.0

Instance Method Summary collapse

Constructor Details

#initialize(size, interval: 60, balanced: false, &blk) ⇒ RateQueue

Returns a new instance of RateQueue.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/limiter/rate_queue.rb', line 7

def initialize(size, interval: 60, balanced: false, &blk)
  @size = size
  @interval = interval

  @balanced = balanced

  @mutex = Mutex.new
  @blk = blk

  reset
end

Instance Method Details

#resetObject



19
20
21
22
23
24
# File 'lib/limiter/rate_queue.rb', line 19

def reset
  @mutex.synchronize do
    @ring = @balanced ? balanced_ring : unbalanced_ring
    @head = 0
  end
end

#shiftObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/limiter/rate_queue.rb', line 26

def shift
  time = nil

  @mutex.synchronize do
    time = @ring[@head]

    sleep_until(time + @interval)

    @ring[@head] = clock.time
    @head = (@head + 1) % @size
  end

  time
end