Class: JayAPI::Abstract::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/jay_api/abstract/connection.rb

Overview

A class for an abstract ‘Connection’. It is responsible for yielding a block for max_attempts times at most, or until a specified error is no longer raised. The reason the class is specifically called ‘Connection’, is because it contains logging that describes a connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_attempts:, wait_strategy:, logger:) ⇒ Connection

Returns a new instance of Connection.

Parameters:

  • max_attempts (Integer)

    The maximum number of connection attempts to be made.

  • wait_strategy (JayAPI::Elasticsearch::WaitStrategy)

    The waiting strategy for reconnections.

  • logger (Logging::Logger)


15
16
17
18
19
20
# File 'lib/jay_api/abstract/connection.rb', line 15

def initialize(max_attempts:, wait_strategy:, logger:)
  @max_attempts = max_attempts
  @wait_strategy = wait_strategy
  @logger = logger
  @attempts = 0
end

Instance Attribute Details

#attemptsObject

Returns the value of attribute attempts.



10
11
12
# File 'lib/jay_api/abstract/connection.rb', line 10

def attempts
  @attempts
end

#loggerObject (readonly)

Returns the value of attribute logger.



10
11
12
# File 'lib/jay_api/abstract/connection.rb', line 10

def logger
  @logger
end

#max_attemptsObject (readonly)

Returns the value of attribute max_attempts.



10
11
12
# File 'lib/jay_api/abstract/connection.rb', line 10

def max_attempts
  @max_attempts
end

#wait_strategyObject (readonly)

Returns the value of attribute wait_strategy.



10
11
12
# File 'lib/jay_api/abstract/connection.rb', line 10

def wait_strategy
  @wait_strategy
end

Instance Method Details

#retry(errors:, except: []) ⇒ Object

Yields the passed block and if the specified ‘error’ is raised, a new yield attempt will be made until the max_attempts limit is reached.

Parameters:

  • errors (Class, Array<Class>)

    Some error Class, or a list of them.

  • except (Array<Class>) (defaults to: [])

    An array of exceptions for which no retry should happen even if they are subclasses of the exception(s) passed in errors.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/jay_api/abstract/connection.rb', line 28

def retry(errors:, except: [])
  self.attempts += 1
  yield
rescue *errors => e
  raise if except.any? { |exception| e.is_a?(exception) }

  logger.info("#{e} occurred")
  if attempts < max_attempts
    wait_strategy.wait
    logger.info("Retrying... (There are #{max_attempts - attempts} retries left)")
    retry
  end

  logger.info('No more attempts to connect will be made')
  raise
end