Class: Latitude::API::RequestExecutor

Inherits:
Object
  • Object
show all
Defined in:
lib/latitude/api/request_executor.rb

Constant Summary collapse

RETRIABLE_STATUSES =
[429, 500, 502, 503, 504].freeze
RETRIABLE_EXCEPTIONS =
[
  EOFError,
  Errno::ECONNREFUSED,
  Errno::ECONNRESET,
  Errno::EPIPE,
  Net::OpenTimeout,
  Net::ReadTimeout,
  OpenSSL::SSL::SSLError,
  SocketError,
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ RequestExecutor

Returns a new instance of RequestExecutor.



20
21
22
# File 'lib/latitude/api/request_executor.rb', line 20

def initialize(config)
  @config = config
end

Instance Method Details

#execute(method:, path:, query: nil, body: nil, headers: {}, idempotency_key: nil, extra_headers: {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/latitude/api/request_executor.rb', line 24

def execute(method:, path:, query: nil, body: nil, headers: {}, idempotency_key: nil, extra_headers: {})
  @config.validate_api_key!

  url = build_url(path, query)
  request_headers = build_headers(method, headers, idempotency_key, extra_headers)
  options = build_httparty_options(request_headers, body)

  attempts = 0
  max_retries = @config.max_network_retries

  loop do
    attempts += 1
    started = Time.now
    response = nil
    begin
      response = HTTParty.send(method.to_sym, url.to_s, options)
    rescue *RETRIABLE_EXCEPTIONS => e
      log_exception(e, method, path, attempts)
      raise ConnectionError.new("Network error talking to #{url}: #{e.message}", cause: e) if attempts > max_retries

      sleep(backoff_delay(attempts, nil))
      next
    end

    duration = ((Time.now - started) * 1000).round
    log_response(method, path, response, duration)

    if retriable_status?(response.code) && attempts <= max_retries
      sleep(backoff_delay(attempts, response))
      next
    end

    return handle_response(response, method: method, path: path)
  end
end