Class: ShopifyClient::Throttling::RedisStrategy
- Inherits:
-
Strategy
- Object
- Faraday::Middleware
- Strategy
- ShopifyClient::Throttling::RedisStrategy
- Defined in:
- lib/shopify-client/throttling/redis_strategy.rb
Overview
Use Redis to maintain API call limit throttling across threads/processes.
No delay for requests up to half of the call limit.
Instance Method Summary collapse
- #after_sleep(env, interval_key) ⇒ Object
- #interval(interval_key) ⇒ Object
-
#leak(num_requests, header_timestamp) ⇒ Integer
Find the actual number of requests by subtracting requests leaked by the leaky bucket algorithm since the last header timestamp.
-
#leak_rate ⇒ Object
Leak rate of the leaky bucket algorithm in milliseconds.
Methods inherited from Strategy
#build_interval_key, #on_request, #timestamp
Instance Method Details
#after_sleep(env, interval_key) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 29 def after_sleep(env, interval_key) header = env[:response_headers]['X-Shopify-Shop-Api-Call-Limit'] return if header.nil? num_requests, max_requests = header.split('/') Redis.current.mapped_hmset(interval_key, num_requests: num_requests, max_requests: max_requests, header_timestamp: , ) end |
#interval(interval_key) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 10 def interval(interval_key) num_requests, max_requests, = Redis.current.hmget(interval_key, :num_requests, :max_requests, :header_timestamp, ).map(&:to_i) num_requests = leak(num_requests, ) max_unthrottled_requests = max_requests / 2 if num_requests > num_unthrottled_requests Rational((num_requests - num_unthrottled_requests) * leak_rate, 1000) else 0 end end |
#leak(num_requests, header_timestamp) ⇒ Integer
Find the actual number of requests by subtracting requests leaked by the leaky bucket algorithm since the last header timestamp.
50 51 52 53 54 |
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 50 def leak(num_requests, ) n = Rational( - , leak_rate).floor n > num_requests ? 0 : num_requests - n end |
#leak_rate ⇒ Object
Leak rate of the leaky bucket algorithm in milliseconds.
57 58 59 |
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 57 def leak_rate 500 end |