Class: Incognia::Client

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/incognia_api/client.rb

Constant Summary collapse

LATENCY_HEADER =
"X-Incognia-Latency".freeze

Instance Method Summary collapse

Constructor Details

#initializeClient

TODO: (ok) http/adapter specific code (ok) raises network/authentication errors (ok) handles token refreshing ok future: handles retrying



16
17
18
19
# File 'lib/incognia_api/client.rb', line 16

def initialize
  @last_latency_ms = nil
  @last_latency_mutex = Mutex.new
end

Instance Method Details

#connectionObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/incognia_api/client.rb', line 50

def connection
  return @connection if @connection

  headers = { 'User-Agent' => "incognia-ruby/#{Incognia::VERSION} " \
                      "({#{RbConfig::CONFIG['host']}}) " \
                      "{#{RbConfig::CONFIG['arch']}} " \
                      "Ruby/#{RbConfig::CONFIG['ruby_version']}" }

  @connection = Faraday.new(Incognia.config.host, headers: headers) do |faraday|
    faraday.request :json
    faraday.response :json, content_type: /\bjson$/
    faraday.response :raise_error

    if Incognia.config.keep_alive
      adapter_options = {
        pool_size: Incognia.config.max_connections
      }.compact

      faraday.adapter :net_http_persistent, **adapter_options
    else
      faraday.adapter Faraday.default_adapter
    end
  end
end

#credentialsObject



38
39
40
41
42
# File 'lib/incognia_api/client.rb', line 38

def credentials
  @credentials = request_credentials if @credentials.nil? || @credentials.stale?

  @credentials
end

#request(method, endpoint = nil, data = nil, headers = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/incognia_api/client.rb', line 21

def request(method, endpoint = nil, data = nil, headers = {})
  json_data = JSON.generate(data) if data
  request_headers = Faraday::Utils::Headers.new.update(headers)
  request_headers[Faraday::Request::Authorization::KEY] ||= "Bearer #{credentials.access_token}"
  request_headers[LATENCY_HEADER] = last_latency_ms&.to_s

  start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
  response = connection.send(method, endpoint, json_data, request_headers.compact)
  store_last_latency(Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) - start) if response.success?

  response
rescue Faraday::ClientError, Faraday::ServerError => e
  raise APIError.new(e.to_s, e.response)
rescue Faraday::Error => e
  raise APIError.new(e.to_s)
end

#reset!Object



44
45
46
47
48
# File 'lib/incognia_api/client.rb', line 44

def reset!
  @connection&.close
  @connection = nil
  @credentials = nil
end