Class: Sbmt::Outbox::V1::Throttler

Inherits:
Object
  • Object
show all
Defined in:
lib/sbmt/outbox/v1/throttler.rb

Overview

Based on github.com/Shopify/limiter/blob/master/lib/limiter/rate_queue.rb We cannot use that gem because we have to support Ruby 2.5, but Shopify’s limiter requires minimum Ruby 2.6

Instance Method Summary collapse

Constructor Details

#initialize(limit: nil, interval: nil) ⇒ Throttler

Returns a new instance of Throttler.



10
11
12
13
14
15
16
# File 'lib/sbmt/outbox/v1/throttler.rb', line 10

def initialize(limit: nil, interval: nil)
  @limit = limit
  @interval = limit
  @map = (0...@limit).map { |i| base_time + (gap * i) }
  @index = 0
  @mutex = Mutex.new
end

Instance Method Details

#waitObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sbmt/outbox/v1/throttler.rb', line 18

def wait
  time = nil

  @mutex.synchronize do
    time = @map[@index]

    sleep_until(time + @interval)

    @map[@index] = now
    @index = (@index + 1) % @limit
  end

  time
end