Class: PowerTrack::Retrier

Inherits:
Object
  • Object
show all
Defined in:
lib/powertrack/streaming/retrier.rb

Overview

A utility class that manges an exponential backoff retry pattern. Additionally, this king of retrier can be reset or stopped by the code being retried.

Constant Summary collapse

DEFAULT_MIN_INTERVAL =

the default minimum number of seconds b/w 2 attempts

1.0
DEFAULT_MAX_ELAPSED_TIME =

the default maximum number of seconds to wait b/w 2 attempts

30.0
DEFAULT_INTERVAL_MULTIPLIER =

the default interval multiplier

1.5
DEFAULT_RANDOMIZE_FACTOR =

the default randomize factor

0.25
DEFAULT_OPTIONS =

default options used by a retrier unless others specified at initialization

{
  min_interval: DEFAULT_MIN_INTERVAL,
  max_elapsed_time: DEFAULT_MAX_ELAPSED_TIME,
  multiplier: DEFAULT_INTERVAL_MULTIPLIER,
  randomize_factor: DEFAULT_RANDOMIZE_FACTOR
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_retries, options = nil) ⇒ Retrier

Builds a retrier that will retry a maximum retries number of times.



28
29
30
31
32
33
34
35
36
37
# File 'lib/powertrack/streaming/retrier.rb', line 28

def initialize(max_retries, options=nil)
  options = DEFAULT_OPTIONS.merge(options || {})

  @max_retries = max_retries
  @retries = 0
  @continue = true
  @backoff = ExponentialBackoff.new(options[:min_interval], options[:max_elapsed_time])
  @backoff.multiplier = options[:multiplier]
  @backoff.randomize_factor = options[:randomize_factor]
end

Instance Attribute Details

#max_retriesObject (readonly)

Returns the value of attribute max_retries.



8
9
10
# File 'lib/powertrack/streaming/retrier.rb', line 8

def max_retries
  @max_retries
end

#retriesObject (readonly)

Returns the value of attribute retries.



8
9
10
# File 'lib/powertrack/streaming/retrier.rb', line 8

def retries
  @retries
end

Instance Method Details

#reset!Object

Resets the retrier.



40
41
42
43
# File 'lib/powertrack/streaming/retrier.rb', line 40

def reset!
  @retries = 0
  @backoff.clear
end

#retry(&block) ⇒ Object

Retries the block of code provided according to the configuration of the retrier.



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/powertrack/streaming/retrier.rb', line 57

def retry(&block)
  # TODO: manage exceptions
  while @continue && @retries <= @max_retries
    res = yield
    if @continue
      @retries += 1
      sleep(@backoff.next_interval)
    end
  end

  res
end

#retrying?Boolean

Returns true if the retrier is currently retrying.

Returns:

  • (Boolean)


46
47
48
# File 'lib/powertrack/streaming/retrier.rb', line 46

def retrying?
  @retries != 0
end

#stopObject

Stops retrying even after a reset. To be used from the code being retried.



51
52
53
# File 'lib/powertrack/streaming/retrier.rb', line 51

def stop
  @continue = false
end