Class: Chain::Connection

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

Constant Summary collapse

MAX_RETRIES =

Parameters to the retry exponential backoff function.

10
RETRY_BASE_DELAY_MS =
40
RETRY_MAX_DELAY_MS =
4000
NETWORK_ERRORS =
[
  InvalidRequestIDError,
  SocketError,
  EOFError,
  IOError,
  Timeout::Error,
  Errno::ECONNABORTED,
  Errno::ECONNRESET,
  Errno::ETIMEDOUT,
  Errno::EHOSTUNREACH,
  Errno::ECONNREFUSED,
]

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Connection

Returns a new instance of Connection.



32
33
34
35
36
37
# File 'lib/chain/connection.rb', line 32

def initialize(opts)
  @opts = opts
  @url = URI(@opts[:url])
  @access_token = @opts[:access_token] || @url.userinfo
  @http_mutex = Mutex.new
end

Instance Method Details

#batch_request(path, body = {}, &translate) ⇒ Object



48
49
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/chain/connection.rb', line 48

def batch_request(path, body = {}, &translate)
  res = _request_with_retries(path, body)
  body = res[:body]
  response = res[:response]

  successes = {}
  errors = {}

  body.each_with_index do |item, i|
    if !!item['code']
      errors[i] = APIError.new(item, response)
    else
      if translate
        successes[i] = translate.call(item)
      else
        successes[i] = item
      end
    end
  end

  BatchResponse.new(
    successes: successes,
    errors: errors,
    response: response,
  )
end

#optsObject

Returns a copy of the configuration options



40
41
42
# File 'lib/chain/connection.rb', line 40

def opts
  @opts.dup
end

#request(path, body = {}) ⇒ Object



44
45
46
# File 'lib/chain/connection.rb', line 44

def request(path, body = {})
  _request_with_retries(path, body)[:body]
end

#singleton_batch_request(path, body = {}, &translate) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/chain/connection.rb', line 75

def singleton_batch_request(path, body = {}, &translate)
  batch = batch_request(path, body, &translate)

  if batch.size != 1
    raise "Invalid response, expected a single response object but got #{batch.items.size}"
  end

  raise batch.errors.values.first if batch.errors.size == 1

  batch.successes.values.first
end