Sha256: 3e054097dd6df96d417cd8c50cf3ed87bf16f133672b5b18f0ad6bf26bd70ca3

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

module Faraday
  module Conductivity
    class Repeater < Faraday::Middleware

      PATTERNS = {
        :rapid       => lambda { |n| 0 },
        :one         => lambda { |n| 1 },
        :linear      => lambda { |n| n },
        :exponential => lambda { |n| n ** 2 },
      }

      def initialize(app, options = {})
        @app = app
        @retries = options[:retries] || 10

        if mode = options[:mode]
          @pattern = build_pattern(PATTERNS.fetch(mode))
        elsif pattern = options[:pattern]
          @pattern = build_pattern(pattern)
        else
          @pattern = build_pattern(PATTERNS.fetch(:exponential))
        end
      end

      def call(env)
        tries = 0
        begin
          @app.call(env)
        rescue Faraday::Error::ClientError
          if tries < @retries
            tries += 1
            @pattern.wait(tries)
            retry
          else
            raise
          end
        end
      end

      def build_pattern(pattern)
        Pattern.new(pattern)
      end

      class Pattern

        def initialize(pattern)
          @pattern = pattern
        end

        def wait(num)
          seconds = @pattern.call(num)
          if seconds != 0
            sleep num
          end
        end

      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
faraday-conductivity-0.1.0 lib/faraday/conductivity/repeater.rb