Class: Airrecord::FaradayRateLimiter
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Airrecord::FaradayRateLimiter
- Defined in:
- lib/airrecord/faraday_rate_limiter.rb
Class Attribute Summary collapse
-
.requests ⇒ Object
Returns the value of attribute requests.
Instance Method Summary collapse
- #call(env) ⇒ Object
- #clear ⇒ Object
-
#initialize(app, requests_per_second: nil, sleeper: nil) ⇒ FaradayRateLimiter
constructor
A new instance of FaradayRateLimiter.
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
.requests ⇒ Object
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 |
#clear ⇒ Object
27 28 29 |
# File 'lib/airrecord/faraday_rate_limiter.rb', line 27 def clear self.class.requests = [] end |