File: retryable.rb

package info (click to toggle)
ruby-faraday-retry 2.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 104 kB
  • sloc: ruby: 204; makefile: 4
file content (46 lines) | stat: -rw-r--r-- 1,189 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true

module Faraday
  # Adds the ability to retry a request based on settings and errors that have occurred.
  module Retryable
    def with_retries(env:, options:, retries:, body:, errmatch:)
      yield
    rescue errmatch => e
      exhausted_retries(options, env, e) if retries_zero?(retries, env, e)

      if retries.positive? && retry_request?(env, e)
        retries -= 1
        rewind_files(body)
        if (sleep_amount = calculate_sleep_amount(retries + 1, env))
          options.retry_block.call(
            env: env,
            options: options,
            retry_count: options.max - (retries + 1),
            exception: e,
            will_retry_in: sleep_amount
          )
          sleep sleep_amount
          retry
        end
      end

      raise unless e.is_a?(Faraday::RetriableResponse)

      e.response
    end

    private

    def retries_zero?(retries, env, exception)
      retries.zero? && retry_request?(env, exception)
    end

    def exhausted_retries(options, env, exception)
      options.exhausted_retries_block.call(
        env: env,
        exception: exception,
        options: options
      )
    end
  end
end