Sha256: 8eea42bf33a57a3570f2001c034d7770645768cf1e2d8002c6e4988756035fc0

Contents?: true

Size: 1.14 KB

Versions: 66

Compression:

Stored size: 1.14 KB

Contents

require "faraday/middleware"

module ZendeskAPI
  module Middleware
    # @private
    module Request
      # Faraday middleware to handle HTTP Status 429 (rate limiting) / 503 (maintenance)
      # @private
      class Retry < Faraday::Middleware
        DEFAULT_RETRY_AFTER = 10
        ERROR_CODES = [429, 503]

        def initialize(app, options={})
          super(app)
          @logger = options[:logger]
        end

        def call(env)
          original_env = env.dup
          response = @app.call(env)

          if ERROR_CODES.include?(response.env[:status])
            seconds_left = (response.env[:response_headers][:retry_after] || DEFAULT_RETRY_AFTER).to_i
            @logger.warn "You have been rate limited. Retrying in #{seconds_left} seconds..." if @logger

            seconds_left.times do |i|
              sleep 1
              time_left = seconds_left - i
              @logger.warn "#{time_left}..." if time_left > 0 && time_left % 5 == 0 && @logger
            end

            @logger.warn "" if @logger

            @app.call(original_env)
          else
            response
          end
        end
      end
    end
  end
end

Version data entries

66 entries across 66 versions & 1 rubygems

Version Path
zendesk_api-1.13.4 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.13.3 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.13.2 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.13.1 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.12.1 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.12.0 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.7 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.6 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.5 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.4 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.3 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.2 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.1 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.11.0 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.10.0 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.9.6 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.9.5 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.9.4 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.9.3 lib/zendesk_api/middleware/request/retry.rb
zendesk_api-1.9.2 lib/zendesk_api/middleware/request/retry.rb