fulfil_api 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b1e3793aadb8a9615fdddb8970acbc23564eec7965e8655558cc9062bdb43c00
4
- data.tar.gz: fbae55d2bec65240dbbb44370411b452bb2461a8021668f70be3af67ee1decfe
3
+ metadata.gz: b4a1af5f0e0aa9d60e13ec0be44860ab87c2b97e6f2d8e496d9a4c49780fbdde
4
+ data.tar.gz: 55b82d99265591de47a5bd006ff383ae42c017b8844e7034af0822c3cd490631
5
5
  SHA512:
6
- metadata.gz: 4cd81653bfe993a17a6552adfaceef0c0ea22f351ae900cc63dd436eb8461767c9d494d372cdc9458f44b5e5af0f6e4860aad49eabdca079ce5e59a32df15c53
7
- data.tar.gz: cbf055f30acca04e2eeaf6aa510d90345ca603e50e016154626e363adca1e92f9a8f4e01f98bb238e32bb656a9d39b597071fb94f20d62cf1f98e09974e523ff
6
+ metadata.gz: 04c8bf6fd039af73ccaff8ae72a2e7b1b5a14b47f556b0c8b7194115b2d5f8b0fcfc6d73402cb26462c84d8260d6273e577a3f812087396500436427fab32105
7
+ data.tar.gz: 0a4d2797729704cdbd7de566bfc5bd4cf16a4c4f134b228440a355ecff4572c2f85c9280184c0b72832375084b27bbe5630f6d4b86bc7fbcf1b9926facff41a5
data/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  ## [Unreleased]
2
2
 
3
+ - Add an optional cooldown for Fulfil's rate limit. With `config.rate_limit_cooldown` set to a cache store, every thread and process that shares the store stops sending requests to a Fulfil instance once a response says its rate limit budget is spent (`x-ratelimit-remaining: 0`) or a request gets a 429, until the budget resets according to `x-ratelimit-reset` (two seconds when Fulfil doesn't say, at most 30). Requests during the cooldown raise `FulfilApi::HttpError::TooManyRequests` without touching the network, with the seconds left in their `retry-after` header.
4
+
5
+ - Back off between the retries of `in_batches` (and `find_each`) when Fulfil answers with a 429. It used to retry every 0.25 seconds for as long as it took, which kept a rate limited application calling Fulfil four times a second per thread. It now waits until Fulfil's rate limit resets according to its `Retry-After` or `x-ratelimit-reset` header, and otherwise doubles the wait from half a second, never longer than 30 seconds and with some jitter so threads that were rate limited together don't retry together.
6
+
3
7
  - Send the `grant_type` and `redirect_uri` in the form body when exchanging an authorization code, the way OAuth 2.0 defines the token request. The grant type used to travel in the query string and the redirect URI was left out, which Fulfil accepts today but isn't required to.
4
8
 
5
9
  - Separate the requested OAuth scopes with spaces instead of commas. Fulfil didn't recognize the comma separated list, and a workspace granted every scope the approving user had rather than the ones that were asked for.
data/README.md CHANGED
@@ -92,6 +92,8 @@ end
92
92
 
93
93
  - `circuit_breaker` (`Faulty`, optional): A [Faulty](https://github.com/ParentSquare/faulty) instance to stop sending requests to a Fulfil instance that keeps failing. Off by default. See [Stopping requests to a failing Fulfil instance](#stopping-requests-to-a-failing-fulfil-instance).
94
94
 
95
+ - `rate_limit_cooldown` (`ActiveSupport::Cache::Store`, optional): A cache store to share a cooldown after Fulfil rate limits a request, so the rest of the application stops calling it for a moment. Off by default. See [Cooling down after a rate limit](#cooling-down-after-a-rate-limit).
96
+
95
97
  - `connection_options` (`Hash`): Tuning for the persistent (keep-alive) connection. Supported keys:
96
98
  - `max_retries` (optional): Re-enables Ruby's built-in retry, which retries **every** idempotent request (`GET`/`HEAD`/`PUT`/`DELETE`/`OPTIONS`) whatever its endpoint, writes through `PUT` included. Off by default; prefer `retry_options`.
97
99
  - `idle_timeout` (`Integer`, optional): Seconds a pooled socket may sit idle before it is recycled. Lower this towards your server's keep-alive window to shrink the stale-socket window for non-idempotent requests.
@@ -124,6 +126,20 @@ Every Fulfil instance gets its own circuit, so one failing instance never stops
124
126
 
125
127
  While a circuit is closed, failed requests raise the same `FulfilApi::HttpError` they always do. Once it opens, requests raise a `FulfilApi::CircuitOpen` without touching the network, until Faulty's cool-down lets a test request through.
126
128
 
129
+ ### Cooling down after a rate limit
130
+
131
+ Fulfil limits how many requests an application can send with the same credentials, and reports the budget on every response: `x-ratelimit-limit` (the tokens in the budget), `x-ratelimit-remaining` (the tokens left) and `x-ratelimit-reset` (the epoch second it resets at). Every thread and process using the same credentials draws from that one budget, so once it's spent, sending more right away only earns 429s.
132
+
133
+ The gem can share a cooldown across all of them instead. Once a response says the budget is spent, or a request gets a 429, the cooldown starts, and until the budget resets, requests to that Fulfil instance raise the same `FulfilApi::HttpError::TooManyRequests` without being sent.
134
+
135
+ ```ruby
136
+ FulfilApi.configure do |config|
137
+ config.rate_limit_cooldown = Rails.cache # any ActiveSupport::Cache::Store
138
+ end
139
+ ```
140
+
141
+ The cooldown lasts until Fulfil's rate limit resets (or as long as a `Retry-After` header asks), two seconds when Fulfil doesn't say, and never longer than 30 seconds. A refused request carries the seconds left in its `retry-after` header, so `in_batches` (and `find_each`) wait just long enough before retrying. Use a store every process shares, like Redis, for the cooldown to reach all of them; a memory store only covers the threads of one process.
142
+
127
143
  ### Authenticating with OAuth (Rails)
128
144
 
129
145
  Fulfil caps the lifetime of personal access tokens, so an application that has to keep working unattended needs an OAuth token instead. The gem ships the whole flow as a Rails engine: a user is sent to Fulfil's consent screen, comes back with an authorization code, and the resulting token is stored as a `FulfilApi::Installation`.
@@ -15,6 +15,12 @@ module FulfilApi
15
15
  # {FulfilApi::Middleware::CircuitBreaker}.
16
16
  attr_accessor :circuit_breaker
17
17
 
18
+ # @!attribute [rw] rate_limit_cooldown
19
+ # @return [ActiveSupport::Cache::Store, nil] The store that shares the cooldown after a
20
+ # 429 of Fulfil across threads and processes, or nil to turn the cooldown off. See
21
+ # {FulfilApi::Middleware::RateLimitCooldown}.
22
+ attr_accessor :rate_limit_cooldown
23
+
18
24
  DEFAULT_API_VERSION = "v2"
19
25
  DEFAULT_REQUEST_OPTIONS = { open_timeout: 1, read_timeout: 5, write_timeout: 5, timeout: 5 }.freeze
20
26
 
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FulfilApi
4
+ module Middleware
5
+ # The {FulfilApi::Middleware::RateLimitCooldown} keeps every thread and process of an
6
+ # application from calling a Fulfil instance whose rate limit is used up.
7
+ #
8
+ # Fulfil's token budget is shared by every request made with the same credentials, and
9
+ # it reports what's left on every response (see {FulfilApi::RateLimit}). Once a response
10
+ # says the budget is spent, or a request is rate limited with a 429, the cooldown starts
11
+ # for that Fulfil instance in a shared store. Until the budget resets, requests are
12
+ # refused locally with the same 429 instead of being sent. The refusal carries a
13
+ # `retry-after` header with the seconds left, so the retries of
14
+ # {FulfilApi::Relation::Batchable#in_batches} (and any retry an application has for
15
+ # {FulfilApi::HttpError::TooManyRequests}) wait just long enough.
16
+ #
17
+ # The cooldown lasts until Fulfil's rate limit resets, or {DEFAULT_WAIT} seconds when it
18
+ # doesn't say, and never longer than {MAX_WAIT}. The store is any
19
+ # `ActiveSupport::Cache::Store`; use one every process shares (e.g. Redis) for the
20
+ # cooldown to reach all of them.
21
+ class RateLimitCooldown < Faraday::Middleware
22
+ # The cooldown in seconds when Fulfil's 429 doesn't come with a `Retry-After` header.
23
+ DEFAULT_WAIT = 2
24
+
25
+ # The longest cooldown in seconds, also when Fulfil asks for longer.
26
+ MAX_WAIT = 30
27
+
28
+ # @param env [Faraday::Env] The environment of the request.
29
+ # @raise [Faraday::TooManyRequestsError] While the Fulfil instance is cooling down.
30
+ # @return [Faraday::Response]
31
+ def call(env)
32
+ refuse!(env) if cooling_down?(env)
33
+
34
+ @app.call(env).on_complete { |response_env| cool_down_when_spent(env, response_env.response_headers) }
35
+ rescue Faraday::TooManyRequestsError => e
36
+ start_cooldown(env, e.response_headers) unless refused?(e)
37
+ raise
38
+ end
39
+
40
+ private
41
+
42
+ # @param env [Faraday::Env]
43
+ # @return [String] The key of the cooldown of the Fulfil instance in the store.
44
+ def cache_key(env)
45
+ "fulfil_api:rate_limit_cooldown:#{env.url.host}"
46
+ end
47
+
48
+ # @param env [Faraday::Env]
49
+ # @return [Boolean]
50
+ def cooling_down?(env)
51
+ remaining_wait(env).positive?
52
+ end
53
+
54
+ # @param env [Faraday::Env]
55
+ # @return [Float] The seconds left in the cooldown of the Fulfil instance.
56
+ def remaining_wait(env)
57
+ cooldown_until = store.read(cache_key(env)).to_f
58
+ [cooldown_until - Time.now.to_f, 0].max
59
+ end
60
+
61
+ # @param env [Faraday::Env]
62
+ # @raise [Faraday::TooManyRequestsError]
63
+ def refuse!(env)
64
+ response = {
65
+ status: 429,
66
+ headers: { "retry-after" => remaining_wait(env).ceil.to_s, "x-fulfil-api-cooldown" => "true" },
67
+ body: { "error" => "#{env.url.host} rate limited an earlier request, waiting for its cooldown" }
68
+ }
69
+
70
+ raise Faraday::TooManyRequestsError.new("the rate limit cooldown of #{env.url.host} is active", response)
71
+ end
72
+
73
+ # @param error [Faraday::TooManyRequestsError]
74
+ # @return [Boolean] Whether the error is a refusal of this middleware.
75
+ def refused?(error)
76
+ error.response_headers.to_h.key?("x-fulfil-api-cooldown")
77
+ end
78
+
79
+ # Starts the cooldown before Fulfil has to rate limit anyone, once a response says the
80
+ # budget is spent.
81
+ #
82
+ # @param env [Faraday::Env]
83
+ # @param headers [Hash, nil] The response headers of Fulfil.
84
+ # @return [void]
85
+ def cool_down_when_spent(env, headers)
86
+ start_cooldown(env, headers) if FulfilApi::RateLimit.remaining(headers)&.zero?
87
+ end
88
+
89
+ # Starts (or extends, never shortens) the cooldown of the Fulfil instance.
90
+ #
91
+ # @param env [Faraday::Env]
92
+ # @param headers [Hash, nil] The response headers of Fulfil.
93
+ # @return [void]
94
+ def start_cooldown(env, headers)
95
+ wait = [FulfilApi::RateLimit.wait(headers) || DEFAULT_WAIT, MAX_WAIT].min
96
+ cooldown_until = Time.now.to_f + wait
97
+ return if store.read(cache_key(env)).to_f >= cooldown_until
98
+
99
+ store.write(cache_key(env), cooldown_until, expires_in: wait.ceil)
100
+ end
101
+
102
+ # @return [ActiveSupport::Cache::Store]
103
+ def store
104
+ options[:store]
105
+ end
106
+ end
107
+ end
108
+ end
@@ -16,6 +16,7 @@ module FulfilApi
16
16
  # @param configuration [FulfilApi::Configuration] The configuration of the client.
17
17
  # @return [void]
18
18
  def apply(connection, configuration)
19
+ connection.use RateLimitCooldown, store: configuration.rate_limit_cooldown if configuration.rate_limit_cooldown
19
20
  connection.use CircuitBreaker, faulty: configuration.circuit_breaker if configuration.circuit_breaker
20
21
  connection.request :retry, retry_middleware_options(configuration.retry_options)
21
22
  end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FulfilApi
4
+ # The {FulfilApi::RateLimit} reads Fulfil's rate limit headers.
5
+ #
6
+ # Fulfil reports its rate limit on every response: `x-ratelimit-limit` (the token budget),
7
+ # `x-ratelimit-remaining` (the tokens left) and `x-ratelimit-reset` (the epoch second the
8
+ # budget resets at). The budget is shared by every request made with the same credentials.
9
+ module RateLimit
10
+ class << self
11
+ # @param headers [Hash, nil] The response headers of Fulfil.
12
+ # @return [Integer, nil] The tokens left in the budget, or nil when Fulfil didn't say.
13
+ def remaining(headers)
14
+ value = header(headers, "x-ratelimit-remaining")
15
+ value.to_i if value.to_s.match?(/\A\d+\z/)
16
+ end
17
+
18
+ # The seconds to wait before sending another request: as long as Fulfil's `Retry-After`
19
+ # asks, or else until the budget resets according to `x-ratelimit-reset`.
20
+ #
21
+ # @param headers [Hash, nil] The response headers of Fulfil.
22
+ # @param now [Time]
23
+ # @return [Integer, nil] The seconds to wait, or nil when Fulfil didn't say.
24
+ def wait(headers, now: Time.now)
25
+ retry_after(headers, now) || until_reset(headers, now)
26
+ end
27
+
28
+ private
29
+
30
+ # @return [String, nil] The value of the header, whatever the casing of its name.
31
+ def header(headers, name)
32
+ headers.to_h.find { |key, _| key.to_s.casecmp?(name) }&.last
33
+ end
34
+
35
+ def retry_after(headers, now)
36
+ value = header(headers, "retry-after").to_s
37
+ return if value.empty?
38
+ return value.to_i if value.match?(/\A\d+\z/)
39
+
40
+ [(Time.httpdate(value) - now).ceil, 0].max
41
+ rescue ArgumentError
42
+ nil
43
+ end
44
+
45
+ def until_reset(headers, now)
46
+ value = header(headers, "x-ratelimit-reset").to_s
47
+ return unless value.match?(/\A\d+\z/)
48
+
49
+ # The reset is given in whole seconds, so wait at least one to not retry inside the
50
+ # second that was just rate limited.
51
+ [value.to_i - now.to_i, 1].max
52
+ end
53
+ end
54
+ end
55
+ end
@@ -9,6 +9,21 @@ module FulfilApi
9
9
  # been exceeded and we have no other option to cut off the retry mechanism.
10
10
  class RetryLimitExceeded < Error; end
11
11
 
12
+ # How long {#in_batches} waits before its first retry after a 429. Every next retry
13
+ # waits twice as long, up to {RETRY_MAX_WAIT}.
14
+ RETRY_BASE_WAIT = 0.5
15
+
16
+ # The longest {#in_batches} waits between two retries, also when Fulfil asks for longer.
17
+ RETRY_MAX_WAIT = 30
18
+
19
+ # Pauses the current thread. Separate from {#in_batches} so the wait can be stubbed.
20
+ #
21
+ # @param seconds [Numeric]
22
+ # @return [void]
23
+ def self.pause(seconds)
24
+ sleep(seconds)
25
+ end
26
+
12
27
  # The {#find_each} is a shorthand for iterating over individual API resources
13
28
  # in a memory effective way.
14
29
  #
@@ -42,7 +57,10 @@ module FulfilApi
42
57
  # end
43
58
  #
44
59
  # @note the {#in_batches} automatically retries when it encounters a 429
45
- # (TooManyRequests) HTTP error to ensure the lookup can be completed.
60
+ # (TooManyRequests) HTTP error to ensure the lookup can be completed. It waits until
61
+ # Fulfil's rate limit resets (see {FulfilApi::RateLimit.wait}), or backs off
62
+ # exponentially (with jitter) when Fulfil doesn't say, so a rate limited lookup
63
+ # doesn't keep hammering Fulfil.
46
64
  #
47
65
  # @param of [Integer] The maximum number of resources in a batch.
48
66
  # @param retries [Symbol, Integer] The maximum number of retries before raising.
@@ -64,18 +82,42 @@ module FulfilApi
64
82
 
65
83
  current_offset += 1
66
84
  current_retry = 0 # Reset the retries back to the default
67
- rescue FulfilApi::HttpError::TooManyRequests
68
- if retries != :unlimited && current_retry > retries
69
- raise RetryLimitExceeded, "the maximum number of #{retries} retries has been reached."
70
- end
85
+ rescue FulfilApi::HttpError::TooManyRequests => e
86
+ ensure_retry_allowed!(current_retry, retries)
71
87
 
72
88
  current_retry += 1
73
- sleep 0.25
89
+ Batchable.pause(retry_wait(current_retry, e))
74
90
  retry
75
91
  end
76
92
 
77
93
  self
78
94
  end
95
+
96
+ private
97
+
98
+ # @param current_retry [Integer] The number of retries so far.
99
+ # @param retries [Symbol, Integer] The maximum number of retries.
100
+ # @raise [RetryLimitExceeded] When no retries are left.
101
+ # @return [void]
102
+ def ensure_retry_allowed!(current_retry, retries)
103
+ return if retries == :unlimited || current_retry <= retries
104
+
105
+ raise RetryLimitExceeded, "the maximum number of #{retries} retries has been reached."
106
+ end
107
+
108
+ # @param attempt [Integer] The number of the upcoming retry, starting at 1.
109
+ # @param error [FulfilApi::HttpError::TooManyRequests] The rate limit error of Fulfil.
110
+ # @return [Numeric] The number of seconds to wait before retrying.
111
+ def retry_wait(attempt, error)
112
+ requested_wait = FulfilApi::RateLimit.wait(error.response_headers)
113
+ return [requested_wait, RETRY_MAX_WAIT].min if requested_wait
114
+
115
+ backoff = [RETRY_BASE_WAIT * (2**(attempt - 1)), RETRY_MAX_WAIT].min
116
+
117
+ # Wait somewhere between half and the full backoff, so threads that were rate limited at
118
+ # the same moment don't all retry at the same moment too.
119
+ backoff * rand(0.5..1.0)
120
+ end
79
121
  end
80
122
  end
81
123
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FulfilApi
4
- VERSION = "0.8.1"
4
+ VERSION = "0.9.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fulfil_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.1
4
+ version: 0.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stefan Vermaas
@@ -112,10 +112,12 @@ files:
112
112
  - lib/fulfil_api/http_error.rb
113
113
  - lib/fulfil_api/middleware.rb
114
114
  - lib/fulfil_api/middleware/circuit_breaker.rb
115
+ - lib/fulfil_api/middleware/rate_limit_cooldown.rb
115
116
  - lib/fulfil_api/oauth.rb
116
117
  - lib/fulfil_api/oauth/authorization.rb
117
118
  - lib/fulfil_api/oauth/configuration.rb
118
119
  - lib/fulfil_api/oauth/token.rb
120
+ - lib/fulfil_api/rate_limit.rb
119
121
  - lib/fulfil_api/relation.rb
120
122
  - lib/fulfil_api/relation/batchable.rb
121
123
  - lib/fulfil_api/relation/countable.rb