Class: Algolia::Transport::Transport

Inherits:
Object
  • Object
show all
Includes:
CallType, RetryOutcomeType
Defined in:
lib/algolia/transport/transport.rb

Constant Summary

Constants included from CallType

CallType::READ, CallType::WRITE

Constants included from RetryOutcomeType

RetryOutcomeType::FAILURE, RetryOutcomeType::RETRY, RetryOutcomeType::SUCCESS

Instance Method Summary collapse

Constructor Details

#initialize(config, requester) ⇒ Transport

Returns a new instance of Transport.

Parameters:

  • config (Configuration)
  • requester (Object)

    requester used for sending requests. Uses Algolia::Http::HttpRequester by default



27
28
29
30
31
# File 'lib/algolia/transport/transport.rb', line 27

def initialize(config, requester)
  @config = config
  @requester = requester
  @retry_strategy = RetryStrategy.new(config.hosts)
end

Instance Method Details

#request(call_type, method, path, body, opts = {}) ⇒ Response

Returns response of the request.

Parameters:

  • call_type (Binary)

    READ or WRITE operation

  • method (Symbol)

    method used for request

  • path (String)

    path of the request

  • body (Hash)

    request body

  • opts (Hash) (defaults to: {})

    contains extra parameters to send with your query

Returns:

  • (Response)

    response of the request

Raises:



41
42
43
44
45
46
47
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
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/algolia/transport/transport.rb', line 41

def request(call_type, method, path, body, opts = {})
  retry_errors = []

  @retry_strategy.get_tryable_hosts(call_type).each do |host|
    opts[:timeout] ||= get_timeout(call_type) * (host.retry_count + 1)
    opts[:connect_timeout] ||= @config.connect_timeout * (host.retry_count + 1)

    request_options = RequestOptions.new(@config)
    request_options.create(opts)
    # TODO: what is this merge for ?
    # request_options.query_params.merge!(request_options.data) if method == :GET

    request = build_request(method, path, body, request_options)
    response = @requester.send_request(
      host,
      request[:method],
      request[:path],
      request[:body],
      request[:query_params],
      request[:header_params],
      request[:timeout],
      request[:connect_timeout]
    )

    outcome = @retry_strategy.decide(
      host,
      http_response_code: response.status,
      is_timed_out: response.has_timed_out,
      network_failure: response.network_failure
    )
    if outcome == FAILURE
      decoded_error = JSON.parse(response.error, :symbolize_names => true)
      raise Algolia::AlgoliaHttpError.new(response.status, decoded_error[:message])
    end

    if outcome == RETRY
      retry_errors << {host: host.url, error: response.error}
    else
      return response
    end
  end

  raise Algolia::AlgoliaUnreachableHostError.new("Unreachable hosts.", retry_errors)
end