Sha256: 9b4f6422ee2f20b7364d9d33524f2466179d4a524f3fef3bf925ce2aead7b74c

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

module Mihari
  module Concerns
    #
    # Retriable concern
    #
    module Retriable
      extend ActiveSupport::Concern

      RETRIABLE_ERRORS = [
        OpenSSL::SSL::SSLError,
        Timeout::Error,
        ::HTTP::ConnectionError,
        ::HTTP::ResponseError,
        ::HTTP::TimeoutError
      ].freeze

      DEFAULT_CONDITION = lambda do |error|
        return true if RETRIABLE_ERRORS.any? { |klass| error.is_a? klass }

        case error
        when StatusCodeError
          error.status_code != 404
        else
          false
        end
      end

      #
      # Retry on error
      #
      # @param [Integer] times
      # @param [Integer] interval
      # @param [Boolean] exponential_backoff
      # @param [Proc] condition
      #
      # @param [Object] on
      def retry_on_error(times: 3, interval: 5, exponential_backoff: true, condition: DEFAULT_CONDITION)
        try = 0
        begin
          try += 1
          yield
        rescue StandardError => e
          # Raise error if it's not a retriable error
          raise e unless condition.call(e)

          sleep_seconds = exponential_backoff ? interval * (2**(try - 1)) : interval
          sleep sleep_seconds
          retry if try < times

          # Raise error if retry times exceed a given times
          raise e
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mihari-7.0.5 lib/mihari/concerns/retriable.rb