Class: LookerSDK::Client::StreamingClient

Inherits:
Object
  • Object
show all
Defined in:
lib/looker-sdk/client.rb

Overview

Since Faraday currently won’t do streaming for us, we use Net::HTTP. Still, we go to the trouble to go through the Sawyer/Faraday codepath so that we can leverage all the header and param processing they do in order to be as consistent as we can with the normal non-streaming codepath. This class replaces the default Faraday ‘builder’ that Faraday uses to do the actual request after all the setup is done.

Defined Under Namespace

Classes: Progress

Instance Method Summary collapse

Constructor Details

#initialize(client, &block) ⇒ StreamingClient

Returns a new instance of StreamingClient.



325
326
327
# File 'lib/looker-sdk/client.rb', line 325

def initialize(client, &block)
  @client, @block = client, block
end

Instance Method Details

#build_response(connection, request) ⇒ Object

This is the method that faraday calls on a builder to do the actual request and build a response.



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/looker-sdk/client.rb', line 330

def build_response(connection, request)
  full_path = connection.build_exclusive_url(request.path, request.params,
                                             request.options.params_encoder).to_s
  uri = URI(full_path)
  path_with_query = uri.query ? "#{uri.path}?#{uri.query}" : uri.path

  http_request = (
    case request.method
    when :get     then Net::HTTP::Get
    when :post    then Net::HTTP::Post
    when :put     then Net::HTTP::Put
    when :patch   then Net::HTTP::Patch
    else raise "Stream to block not supported for '#{request.method}'"
    end
  ).new(path_with_query, request.headers)

  http_request.body = request.body

  connect_opts = {
    :use_ssl => !!connection.ssl,
    :verify_mode => (connection.ssl.verify rescue true) ?
      OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE,
  }

  # TODO: figure out how/if to support proxies
  # TODO: figure out how to test this comprehensively

  progress = nil
  Net::HTTP.start(uri.host, uri.port, connect_opts) do |http|
    http.open_timeout = connection.options.open_timeout rescue 30
    http.read_timeout = connection.options.timeout rescue 60

    http.request(http_request) do |response|
      progress = Progress.new(response)
      if response.code == "200"
        response.read_body do |chunk|
          next unless chunk.length > 0
          progress.add_chunk(chunk)
          @block.call(chunk, progress)
          return OpenStruct.new(status:"0", headers:{}, env:nil, body:nil) if progress.stopped?
        end
      end
    end
  end

  return OpenStruct.new(status:"500", headers:{}, env:nil, body:nil) unless progress

  OpenStruct.new(status:progress.response.code, headers:progress.response, env:nil, body:nil)
end