Class: FlatApi::RetryPolicy

Inherits:
Object
  • Object
show all
Defined in:
lib/flat_api/retry.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attempts: 3, backoff_base: 0.5, backoff_max: 30.0, jitter: 0.25, respect_rate_limit_reset: true) ⇒ RetryPolicy

Returns a new instance of RetryPolicy.



19
20
21
22
23
24
25
26
# File 'lib/flat_api/retry.rb', line 19

def initialize(attempts: 3, backoff_base: 0.5, backoff_max: 30.0, jitter: 0.25,
               respect_rate_limit_reset: true)
  @attempts = attempts
  @backoff_base = backoff_base
  @backoff_max = backoff_max
  @jitter = jitter
  @respect_rate_limit_reset = respect_rate_limit_reset
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



17
18
19
# File 'lib/flat_api/retry.rb', line 17

def attempts
  @attempts
end

#backoff_baseObject (readonly)

Returns the value of attribute backoff_base.



17
18
19
# File 'lib/flat_api/retry.rb', line 17

def backoff_base
  @backoff_base
end

#backoff_maxObject (readonly)

Returns the value of attribute backoff_max.



17
18
19
# File 'lib/flat_api/retry.rb', line 17

def backoff_max
  @backoff_max
end

#jitterObject (readonly)

Returns the value of attribute jitter.



17
18
19
# File 'lib/flat_api/retry.rb', line 17

def jitter
  @jitter
end

#respect_rate_limit_resetObject (readonly)

Returns the value of attribute respect_rate_limit_reset.



17
18
19
# File 'lib/flat_api/retry.rb', line 17

def respect_rate_limit_reset
  @respect_rate_limit_reset
end

Class Method Details

.disabledObject

No retries. Errors still arrive typed, and a rate-limit error still carries its reset.



29
30
31
# File 'lib/flat_api/retry.rb', line 29

def self.disabled
  new(attempts: 1)
end

Instance Method Details

#delay_for(error, attempt) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/flat_api/retry.rb', line 47

def delay_for(error, attempt)
  if respect_rate_limit_reset && error.is_a?(FlatRateLimitError) && error.reset
    wait = error.reset - Time.now.to_i
    return [wait + rand * jitter, MAX_RATE_LIMIT_WAIT].min if wait.positive?
  end
  exponential = [backoff_base * (2**(attempt - 1)), backoff_max].min
  exponential + (rand * jitter * exponential)
end

#enabled?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/flat_api/retry.rb', line 33

def enabled?
  attempts > 1
end

#should_retry?(error, method, attempt) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
# File 'lib/flat_api/retry.rb', line 37

def should_retry?(error, method, attempt)
  return false if attempt >= attempts
  return false unless IDEMPOTENT_METHODS.include?(method.to_s.upcase)
  return true if error.is_a?(FlatRateLimitError)
  return true if error.is_a?(FlatServerError)

  # A transport failure before the request was sent is safe to replay.
  error.is_a?(IOError) || error.is_a?(SystemCallError)
end