Class: SmartyStreets::RetrySender

Inherits:
Object
  • Object
show all
Defined in:
lib/smartystreets_ruby_sdk/retry_sender.rb

Constant Summary collapse

MAX_BACKOFF_DURATION =
10
STATUS_TOO_MANY_REQUESTS =
429
STATUS_TO_RETRY =
[408, 429, 500, 502, 503, 504]

Instance Method Summary collapse

Constructor Details

#initialize(max_retries, inner, sleeper, logger) ⇒ RetrySender

Returns a new instance of RetrySender.



7
8
9
10
11
12
# File 'lib/smartystreets_ruby_sdk/retry_sender.rb', line 7

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

Instance Method Details

#backoff(attempt) ⇒ Object



38
39
40
41
42
43
# File 'lib/smartystreets_ruby_sdk/retry_sender.rb', line 38

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

#rate_limit_backoff(backoff_duration) ⇒ Object



45
46
47
48
# File 'lib/smartystreets_ruby_sdk/retry_sender.rb', line 45

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

#send(request) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/smartystreets_ruby_sdk/retry_sender.rb', line 14

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