Class: SourceMonitor::Fetching::RetryPolicy

Inherits:
Object
  • Object
show all
Defined in:
lib/source_monitor/fetching/retry_policy.rb

Defined Under Namespace

Classes: Decision

Constant Summary collapse

DEFAULTS =
{
  timeout: { attempts: 2, wait: 2.minutes, circuit_wait: 1.hour },
  connection: { attempts: 3, wait: 5.minutes, circuit_wait: 1.hour },
  http_429: { attempts: 2, wait: 15.minutes, circuit_wait: 90.minutes },
  http_5xx: { attempts: 2, wait: 10.minutes, circuit_wait: 90.minutes },
  http_4xx: { attempts: 1, wait: 45.minutes, circuit_wait: 2.hours },
  parsing: { attempts: 1, wait: 30.minutes, circuit_wait: 2.hours },
  blocked: { attempts: 1, wait: 1.hour, circuit_wait: 4.hours },
  authentication: { attempts: 1, wait: 1.hour, circuit_wait: 4.hours },
  unexpected: { attempts: 1, wait: 30.minutes, circuit_wait: 2.hours },
  fallback: { attempts: 2, wait: 10.minutes, circuit_wait: 90.minutes }
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source:, error:, now: Time.current) ⇒ RetryPolicy

Returns a new instance of RetryPolicy.



32
33
34
35
36
# File 'lib/source_monitor/fetching/retry_policy.rb', line 32

def initialize(source:, error:, now: Time.current)
  @source = source
  @error = error
  @now = now
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



30
31
32
# File 'lib/source_monitor/fetching/retry_policy.rb', line 30

def error
  @error
end

#nowObject (readonly)

Returns the value of attribute now.



30
31
32
# File 'lib/source_monitor/fetching/retry_policy.rb', line 30

def now
  @now
end

#sourceObject (readonly)

Returns the value of attribute source.



30
31
32
# File 'lib/source_monitor/fetching/retry_policy.rb', line 30

def source
  @source
end

Instance Method Details

#decisionObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/source_monitor/fetching/retry_policy.rb', line 38

def decision
  policy = DEFAULTS[policy_key]
  attempts = policy.fetch(:attempts)
  wait_duration = policy.fetch(:wait)
  circuit_duration = policy.fetch(:circuit_wait)

  current_attempt = source.fetch_retry_attempt.to_i
  next_attempt = current_attempt + 1

  if next_attempt <= attempts
    Decision.new(
      retry?: true,
      wait: wait_duration,
      next_attempt: next_attempt,
      open_circuit?: false,
      circuit_until: nil
    )
  else
    circuit_until = now + circuit_duration
    Decision.new(
      retry?: false,
      wait: circuit_duration,
      next_attempt: 0,
      open_circuit?: true,
      circuit_until: circuit_until
    )
  end
end