Skip to content
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

Can't seem to conditionally wait with a 429 #41

Open
jesseduffield opened this issue Aug 1, 2024 · 0 comments
Open

Can't seem to conditionally wait with a 429 #41

jesseduffield opened this issue Aug 1, 2024 · 0 comments

Comments

@jesseduffield
Copy link

Basic Version Info

Faraday Version: 2.9.0
Ruby Version: 3.2.2

Issue description

I'm using faraday in a background job via ActiveJob. I would like to conditionally sleep inline depending on how large the 429 retry-after header's value is. If the value is sufficiently large, I want to re-raise the error and have ActiveJob catch it and reschedule the job in the future, using the retry-after header from the exception.

But, I can't see how to tell faraday-retry that I want to re-raise an error. It seems that faraday will wait after the retry block anyway.

Actual behavior

error is not re-raised

Expected behavior

error is re-raised.

Steps to reproduce

I don't know of a way to easily reproduce because httpbin doesn't return a retry-after header, but here's the general idea:

#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/inline"

gemfile do
  source "https://rubygems.org"

  gem "faraday"
  gem "faraday-retry"
end

retry_options = {
  max: 1,
  exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [Faraday::TooManyRequestsError],
  retry_block: ->(env:, options:, retry_count:, exception:, will_retry_in:) {
    if exception.is_a?(Faraday::TooManyRequestsError)
      retry_after = exception.response[:headers]["retry-after"].to_i
      if retry_after < 10
        sleep retry_after
      else
        # This will be caught at the top level and used to reschedule the job
        # in the future
        raise(exception)
      end
    end
  },
}
faraday = Faraday.new do |conn|
  conn.request :retry, **retry_options
end

faraday.get("https://httpbin.org/status/429")

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant