Module: HttpRetriable

Extended by:
HttpRetriable
Included in:
HttpRetriable
Defined in:
lib/http_retriable.rb,
lib/http_retriable/version.rb

Constant Summary collapse

VERSION =
"0.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(*args, &block) ⇒ Object



60
61
62
# File 'lib/http_retriable.rb', line 60

def self.call(*args, &block)
  self.retry_http(*args, &block)
end

Instance Method Details

#retry_http(*args, &block) ⇒ Object



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
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/http_retriable.rb', line 6

def retry_http(*args, &block)
  options = args.extract_options!
  default_exceptions = [
    EOFError,
    Errno::ECONNREFUSED,
    Errno::ECONNRESET,
    Errno::EHOSTUNREACH,
    Errno::EINVAL,
    Errno::EPIPE,
    Errno::ETIMEDOUT]
  if defined?(RestClient)
    default_exceptions += [RestClient::RequestTimeout, RestClient::ServerBrokeConnection]
  end

  retries = options.fetch(:retries, 5)
  should_sleep = options.fetch(:sleep, false)
  backoff = !should_sleep # if sleep is provided by the user, don't backoff
  exceptions = options.fetch(:exceptions, default_exceptions)
  quick_retries = options.fetch(:quick_retries, 2)
  logger = options.fetch(:logger, Logger.new($stderr))

  retried = 0
  quick_retried = 0
  seconds_to_sleep = should_sleep ? should_sleep : 2
  begin
    yield
  rescue *exceptions => e
    if backoff
      if quick_retried < quick_retries
        quick_retried += 1
        logger.debug("[HTTP_RETRIABLE] quick retry: #{quick_retried}/#{quick_retries}") 
        retry
      elsif retried < retries
        retried += 1
        seconds_to_sleep = 2 ** retried
        logger.debug("[HTTP_RETRIABLE] backoff retry: #{retried}/#{retries} sleeping for: #{seconds_to_sleep}s") 
        sleep seconds_to_sleep
        retry
      else
        raise e
      end
    else
      if retried < retries
        logger.debug("[HTTP_RETRIABLE] retry: #{retried}/#{retries} sleeping for: #{seconds_to_sleep}s") 
        retried += 1
        sleep seconds_to_sleep
        retry
      else
        raise e
      end
    end
  end
end