Class: Pinot::JsonHttpTransport

Inherits:
Object
  • Object
show all
Defined in:
lib/pinot/transport.rb

Constant Summary collapse

DEFAULT_HEADERS =
{
  "Content-Type" => "application/json; charset=utf-8"
}.freeze
RETRYABLE_ERRORS =
[
  Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ETIMEDOUT,
  Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(http_client:, extra_headers: {}, timeout_ms: nil, logger: nil, max_retries: 0, retry_interval_ms: 200) ⇒ JsonHttpTransport

Returns a new instance of JsonHttpTransport.



160
161
162
163
164
165
166
167
168
# File 'lib/pinot/transport.rb', line 160

def initialize(http_client:, extra_headers: {}, timeout_ms: nil, logger: nil,
               max_retries: 0, retry_interval_ms: 200)
  @http_client = http_client
  @extra_headers = extra_headers
  @timeout_ms = timeout_ms
  @logger = logger
  @max_retries = max_retries
  @retry_interval_ms = retry_interval_ms
end

Instance Method Details

#execute(broker_address, request) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/pinot/transport.rb', line 170

def execute(broker_address, request)
  logger.debug "Pinot query to #{broker_address}: #{request.query}"

  attempts = 0
  max_attempts = (@max_retries || 0) + 1

  begin
    attempts += 1

    url = build_url(broker_address, request.query_format)
    body = build_body(request)
    headers = DEFAULT_HEADERS
      .merge(@extra_headers)
      .merge("X-Correlation-Id" => SecureRandom.uuid)

    resp = @http_client.post(url, body: body, headers: headers)

    if resp.code == "503"
      logger.error "Pinot broker returned HTTP #{resp.code}"
      raise TransportError, "http exception with HTTP status code #{resp.code}"
    end

    unless resp.code.to_i == 200
      logger.error "Pinot broker returned HTTP #{resp.code}"
      raise TransportError, "http exception with HTTP status code #{resp.code}"
    end

    begin
      BrokerResponse.from_json(resp.body)
    rescue JSON::ParserError => e
      raise e.message
    end
  rescue TransportError, *RETRYABLE_ERRORS => e
    if attempts < max_attempts
      sleep_ms = (@retry_interval_ms || 200) * (2 ** (attempts - 1))
      sleep(sleep_ms / 1000.0)
      retry
    end
    raise
  end
end