Sha256: d3c3b97d6d69de75a0ed10f682f1f32028bcc0fa1a722436a51f9a691c679e7e

Contents?: true

Size: 1.38 KB

Versions: 17

Compression:

Stored size: 1.38 KB

Contents

module SmartyStreets
  class RetrySender
    MAX_BACKOFF_DURATION = 10
    STATUS_TOO_MANY_REQUESTS = 429
    STATUS_TO_RETRY = [408, 429, 500, 502, 503, 504]

    def initialize(max_retries, inner, sleeper, logger)
      @max_retries = max_retries
      @inner = inner
      @sleeper = sleeper
      @logger = logger
    end

    def send(request)
      response = @inner.send(request)

      (1..@max_retries).each do |i|

        break if STATUS_TO_RETRY.include?(response.status_code.to_i) == false

        if response.status_code.to_i == STATUS_TOO_MANY_REQUESTS
          seconds_to_backoff = 10
          if response.header.nil? == false
            if Integer(response.header["Retry-After"], exception: false)
              seconds_to_backoff = response.header["Retry-After"].to_i
            end
          end
          rate_limit_backoff(seconds_to_backoff)
        else
          backoff(i)
        end
        response = @inner.send(request)
      end

      response
    end

    def backoff(attempt)
      backoff_duration = [attempt, MAX_BACKOFF_DURATION].min

      @logger.log("There was an error processing the request. Retrying in #{backoff_duration} seconds...")
      @sleeper.sleep(backoff_duration)
    end

    def rate_limit_backoff(backoff_duration)
      @logger.log("Rate limit reached. Retrying in #{backoff_duration} seconds...")
      @sleeper.sleep(backoff_duration)
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
smartystreets_ruby_sdk-5.20.6 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.20.4 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.20.3 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.20.2 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.19.0 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.18.1 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.18.0 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.17.2 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.17.1 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.17.0 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.16.2 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.16.1 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.16.0 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.15.4 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.15.3 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.15.2 lib/smartystreets_ruby_sdk/retry_sender.rb
smartystreets_ruby_sdk-5.15.1 lib/smartystreets_ruby_sdk/retry_sender.rb