Class: SSE::Backoff

Inherits:
Object
  • Object
show all
Defined in:
lib/sse_client/backoff.rb

Overview

A simple backoff algorithm that can be reset at any time, or reset itself after a given interval has passed without errors.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_interval, max_interval, auto_reset_interval = 60) ⇒ Backoff

Returns a new instance of Backoff.



8
9
10
11
12
13
14
15
# File 'lib/sse_client/backoff.rb', line 8

def initialize(base_interval, max_interval, auto_reset_interval = 60)
  @base_interval = base_interval
  @max_interval = max_interval
  @auto_reset_interval = auto_reset_interval
  @attempts = 0
  @last_good_time = nil
  @jitter_rand = Random.new
end

Instance Attribute Details

#base_intervalObject

Returns the value of attribute base_interval.



17
18
19
# File 'lib/sse_client/backoff.rb', line 17

def base_interval
  @base_interval
end

Instance Method Details

#mark_successObject



34
35
36
# File 'lib/sse_client/backoff.rb', line 34

def mark_success
  @last_good_time = Time.now.to_i if @last_good_time.nil?
end

#next_intervalObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sse_client/backoff.rb', line 19

def next_interval
  if !@last_good_time.nil? && (Time.now.to_i - @last_good_time) >= @auto_reset_interval
    @attempts = 0
  end
  @last_good_time = nil
  if @attempts == 0
    @attempts += 1
    return 0
  end
  @last_good_time = nil
  target = ([@base_interval * (2 ** @attempts), @max_interval].min).to_f
  @attempts += 1
  (target / 2) + @jitter_rand.rand(target / 2)
end