Class: DeepL::Utils::BackoffTimer

Inherits:
Object
  • Object
show all
Defined in:
lib/deepl/utils/backoff_timer.rb

Constant Summary collapse

BACKOFF_INITIAL =

Implements exponential-backoff strategy. This strategy is based on the GRPC Connection Backoff Protocol: github.com/grpc/grpc/blob/master/doc/connection-backoff.md

1.0
BACKOFF_MAX =
120.0
BACKOFF_JITTER =
0.23
BACKOFF_MULTIPLIER =
1.6

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min_connection_timeout = 10.0) ⇒ BackoffTimer

Returns a new instance of BackoffTimer.



20
21
22
23
24
25
# File 'lib/deepl/utils/backoff_timer.rb', line 20

def initialize(min_connection_timeout = 10.0)
  @num_retries = 0
  @backoff = BACKOFF_INITIAL
  @deadline = Time.now.to_f + @backoff
  @min_connection_timeout = min_connection_timeout
end

Instance Attribute Details

#num_retriesObject (readonly)

Returns the value of attribute num_retries.



18
19
20
# File 'lib/deepl/utils/backoff_timer.rb', line 18

def num_retries
  @num_retries
end

Instance Method Details

#current_request_timeoutObject



27
28
29
# File 'lib/deepl/utils/backoff_timer.rb', line 27

def current_request_timeout
  [time_until_deadline, @min_connection_timeout].max
end

#sleep_until_deadlineObject



35
36
37
38
39
40
41
42
43
# File 'lib/deepl/utils/backoff_timer.rb', line 35

def sleep_until_deadline
  sleep(time_until_deadline)
  # Apply multiplier to current backoff time
  @backoff = [@backoff * BACKOFF_MULTIPLIER, BACKOFF_MAX].min
  # Get deadline by applying jitter as a proportion of backoff:
  # if jitter is 0.1, then multiply backoff by random value in [0.9, 1.1]
  @deadline = Time.now.to_f + (@backoff * (1 + (BACKOFF_JITTER * rand(-1.0..1.0))))
  @num_retries += 1
end

#time_until_deadlineObject



31
32
33
# File 'lib/deepl/utils/backoff_timer.rb', line 31

def time_until_deadline
  [@deadline - Time.now.to_f, 0.0].max
end