-
Notifications
You must be signed in to change notification settings - Fork 0
Retry KB transport failures once, and wrap Listable connection failures in KB::Error (1.3.0) #108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
55bbd29
fix(listable): wrap Faraday::ConnectionFailed in KB::Error like every…
fatbeard2 cd87a5a
feat(client): retry transport failures once, by whether the request c…
fatbeard2 f73bd4b
fix(retries): don't double a call's own read budget; address review nits
fatbeard2 872a455
docs(retries): explain root_cause's one-level wrapped_exception lookup
fatbeard2 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| require 'socket' | ||
| require 'net/http' | ||
| require 'faraday/retry' | ||
|
|
||
| module KB | ||
| # Decides which failed KB calls the client retries. | ||
| # | ||
| # Two classes of transport failure, told apart by the underlying Ruby error | ||
| # rather than the Faraday class (adapters disagree on the Faraday class: the | ||
| # net_http adapter wraps Net::OpenTimeout as ConnectionFailed, the persistent | ||
| # one as TimeoutError): | ||
| # | ||
| # - never sent: TCP connect / TLS handshake did not complete, so KB cannot have | ||
| # seen the request. Safe to retry for every verb, POST included. | ||
| # - maybe sent: anything else the transport raises (read/write timeout, reset, | ||
| # EOF, TLS error mid-stream). KB may have processed it, so only GET/HEAD are | ||
| # retried. PUT/DELETE are left out on purpose: `upsert` and `merge!` are PUTs | ||
| # whose second run is not a no-op on KB's side, and a repeated DELETE would | ||
| # turn a success into a 404. | ||
| # A call that raised its own read budget (`read_timeout:`, e.g. 30s for | ||
| # birthdays) is not retried on these either, so its worst case isn't doubled. | ||
| # | ||
| # HTTP responses (4xx/5xx) are never retried: KB answered. | ||
| module RetryPolicy | ||
| NOT_SENT_ERRORS = [ | ||
| Net::OpenTimeout, | ||
| Errno::ECONNREFUSED, | ||
| Errno::EHOSTUNREACH, | ||
| Errno::ENETUNREACH, | ||
| Errno::EADDRNOTAVAIL, | ||
| SocketError # DNS resolution | ||
| ].freeze | ||
| TRANSPORT_ERRORS = [Faraday::ConnectionFailed, Faraday::TimeoutError, Faraday::SSLError].freeze | ||
| MAYBE_SENT_VERBS = %i[get head].freeze | ||
|
|
||
| module_function | ||
|
|
||
| def retry?(verb, error, own_read_budget: false) | ||
| return false unless TRANSPORT_ERRORS.any? { |klass| error.is_a?(klass) } | ||
|
|
||
| not_sent?(error) || (MAYBE_SENT_VERBS.include?(verb) && !own_read_budget) | ||
| end | ||
|
|
||
| def not_sent?(error) | ||
| cause = root_cause(error) | ||
| NOT_SENT_ERRORS.any? { |klass| cause.is_a?(klass) } | ||
| end | ||
|
|
||
| # The Ruby error behind a Faraday error. `wrapped_exception` is Faraday's own | ||
| # explicit link to it (Ruby's `cause` is only whatever was being rescued at | ||
| # the raise, usually the same object). Faraday's adapters wrap the Ruby error | ||
| # one level deep, so one level is enough. | ||
| def root_cause(error) | ||
| (error.respond_to?(:wrapped_exception) && error.wrapped_exception) || error.cause || error | ||
| end | ||
|
|
||
| # Options for faraday-retry's middleware, read from KB.config.request. | ||
| def middleware_options | ||
| { | ||
| max: KB.config.request.retries, | ||
| interval: KB.config.request.retry_interval, | ||
| interval_randomness: 1, # 1x-2x the interval, so a burst of callers doesn't retry in lockstep | ||
| exceptions: TRANSPORT_ERRORS, | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤖 [nit] faraday-retry is declared as a dependency but never required. The gem relies on Faraday 1.10's |
||
| methods: [], # always ask retry_if | ||
| retry_if: lambda do |env, error| | ||
| retry?(env[:method], error, own_read_budget: env[:request].context&.dig(:kb_own_read_budget)) | ||
| end, | ||
| retry_block: ->(env, _options, _retries_left, error) { record(env, error) } | ||
| } | ||
| end | ||
|
|
||
| # Hands the request.kb_client event payload (and whether the call set its own | ||
| # read budget) to the middleware through the request context, so each retry | ||
| # is reported on the call's own event. | ||
| def track(request, event, read_timeout = nil) | ||
| tracking = { kb_event: event, kb_own_read_budget: !read_timeout.nil? } | ||
| request.options.context = (request.options.context || {}).merge(tracking) | ||
| end | ||
|
|
||
| def record(env, error) | ||
| event = env[:request].context&.dig(:kb_event) | ||
| return unless event | ||
|
|
||
| event[:retries] = event.fetch(:retries, 0) + 1 | ||
| (event[:retry_errors] ||= []) << root_cause(error).class.name | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| module KB | ||
| VERSION = '1.2.0'.freeze | ||
| VERSION = '1.3.0'.freeze | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| require 'spec_helper' | ||
|
|
||
| RSpec.describe KB::Client, '#request retries' do | ||
| subject(:client) { described_class.new('http://kb.test/v1/pets', api_key: 'test') } | ||
|
|
||
| let(:json) { { status: 200, body: '{"key":"k"}', headers: { 'Content-Type' => 'application/json' } } } | ||
| let(:events) { [] } | ||
|
|
||
| around do |example| | ||
| KB.config.request.retry_interval = 0 | ||
| subscriber = ActiveSupport::Notifications.subscribe(described_class::REQUEST_EVENT) { |*, p| events << p } | ||
| example.run | ||
| ensure | ||
| ActiveSupport::Notifications.unsubscribe(subscriber) | ||
| KB.config.request.retry_interval = 0.1 | ||
| KB.config.request.retries = 1 | ||
| end | ||
|
|
||
| # Runs the call and returns what the caller saw plus how many HTTP attempts reached the stub. | ||
| def call(stub) | ||
| result = begin | ||
| yield | ||
| :ok | ||
| rescue Faraday::Error => e | ||
| e.class | ||
| end | ||
| { result: result, attempts: WebMock::RequestRegistry.instance.times_executed(stub.request_pattern) } | ||
| end | ||
|
|
||
| it 'retries a GET after a connect timeout and reports the retry in the event' do | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/k').to_raise(Net::OpenTimeout).then.to_return(json) | ||
|
|
||
| outcome = call(stub) { client.find('k') } | ||
|
|
||
| expect(outcome.merge(event: events.last.slice(:status, :retries, :retry_errors))) | ||
| .to eq(result: :ok, attempts: 2, event: { status: 200, retries: 1, retry_errors: ['Net::OpenTimeout'] }) | ||
| end | ||
|
|
||
| it 'retries a POST when the request never reached KB' do | ||
| stub = stub_request(:post, 'http://kb.test/v1/pets').to_raise(Errno::ECONNREFUSED).then.to_return(json) | ||
|
|
||
| expect(call(stub) { client.create(name: 'Rex') }).to eq(result: :ok, attempts: 2) | ||
| end | ||
|
|
||
| it 'does not retry a POST that may have reached KB' do | ||
| stub = stub_request(:post, 'http://kb.test/v1/pets').to_raise(Net::ReadTimeout).then.to_return(json) | ||
|
|
||
| expect(call(stub) { client.create(name: 'Rex') }).to eq(result: Faraday::TimeoutError, attempts: 1) | ||
| end | ||
|
|
||
| it 'retries a GET after a read timeout' do | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/k').to_raise(Net::ReadTimeout).then.to_return(json) | ||
|
|
||
| expect(call(stub) { client.find('k') }).to eq(result: :ok, attempts: 2) | ||
| end | ||
|
|
||
| it 'does not retry a read timeout on a call that set its own read_timeout' do | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/birthdays').to_raise(Net::ReadTimeout).then.to_return(json) | ||
|
|
||
| expect(call(stub) { client.request('birthdays', read_timeout: 30) }) | ||
| .to eq(result: Faraday::TimeoutError, attempts: 1) | ||
| end | ||
|
|
||
| it 'does not retry HTTP error responses' do | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/k').to_return(status: 503, body: '') | ||
|
|
||
| expect(call(stub) { client.find('k') }).to eq(result: Faraday::ServerError, attempts: 1) | ||
| end | ||
|
|
||
| it 'gives up after the configured retries and records the last error on the event' do | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/k').to_raise(Net::OpenTimeout) | ||
|
|
||
| outcome = call(stub) { client.find('k') } | ||
|
|
||
| expect(outcome.merge(retries: events.last[:retries], recorded: events.last[:exception_object].class)) | ||
| .to eq(result: Faraday::ConnectionFailed, attempts: 2, retries: 1, recorded: Faraday::ConnectionFailed) | ||
| end | ||
|
|
||
| it 'does not retry when retries are set to 0' do | ||
| KB.config.request.retries = 0 | ||
| stub = stub_request(:get, 'http://kb.test/v1/pets/k').to_raise(Net::OpenTimeout).then.to_return(json) | ||
|
|
||
| expect(call(stub) { client.find('k') }).to eq(result: Faraday::ConnectionFailed, attempts: 1) | ||
| end | ||
|
|
||
| it 'leaves the event untouched when the first attempt succeeds' do | ||
| stub_request(:get, 'http://kb.test/v1/pets/k').to_return(json) | ||
|
|
||
| client.find('k') | ||
|
|
||
| expect(events.last).not_to include(:retries, :retry_errors) | ||
| end | ||
| end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖 [should-fix] The retry also applies to per-call
read_timeout:overrides. The README's ownrequest('birthdays', ..., read_timeout: 30)example can now take about 2 × 30s plus the connect/write budgets before it fails. Either skip the maybe-sent retry whenread_timeoutis overridden, or at least document the doubled worst case next to that example.