Class: Airrecord::FaradayRateLimiter

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/airrecord/faraday_rate_limiter.rb

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, requests_per_second: nil, sleeper: nil) ⇒ FaradayRateLimiter

Returns a new instance of FaradayRateLimiter.



9
10
11
12
13
14
15
# File 'lib/airrecord/faraday_rate_limiter.rb', line 9

def initialize(app, requests_per_second: nil, sleeper: nil)
  super(app)
  @rps = requests_per_second
  @sleeper = sleeper || ->(seconds) { sleep(seconds) }
  @mutex = Mutex.new
  clear
end

Class Attribute Details

.requestsObject

Returns the value of attribute requests.



6
7
8
# File 'lib/airrecord/faraday_rate_limiter.rb', line 6

def requests
  @requests
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/airrecord/faraday_rate_limiter.rb', line 17

def call(env)
  @mutex.synchronize do
    wait if too_many_requests_in_last_second?
    @app.call(env).on_complete do |_response_env|
      requests << Process.clock_gettime(Process::CLOCK_MONOTONIC)
      requests.shift if requests.size > @rps
    end
  end
end

#clearObject



27
28
29
# File 'lib/airrecord/faraday_rate_limiter.rb', line 27

def clear
  self.class.requests = []
end