X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/b869319d1dc8ae68de7994e80d8f80a0dee51ac0..ee6f8ae6f983f2beb1afa94f9332f9e244fbbb9d:/lib/google/api_client.rb diff --git a/lib/google/api_client.rb b/lib/google/api_client.rb index ceb18edb8e..4c9ee03c7a 100644 --- a/lib/google/api_client.rb +++ b/lib/google/api_client.rb @@ -13,23 +13,32 @@ # limitations under the License. -require 'httpadapter' -require 'json' +require 'faraday' +require 'faraday/utils' +require 'multi_json' +require 'compat/multi_json' require 'stringio' +require 'google/api_client/version' +require 'google/api_client/logging' require 'google/api_client/errors' require 'google/api_client/environment' require 'google/api_client/discovery' +require 'google/api_client/request' require 'google/api_client/reference' require 'google/api_client/result' +require 'google/api_client/media' +require 'google/api_client/service_account' +require 'google/api_client/batch' +require 'google/api_client/railtie' if defined?(Rails) module Google - # TODO(bobaman): Document all this stuff. - ## # This class manages APIs communication. class APIClient + include Google::APIClient::Logging + ## # Creates a new Google API client. # @@ -43,48 +52,62 @@ module Google #
:oauth_1
:oauth_2
:version
â
- # The service version. Only used if api_method
is a
- # String
. Defaults to 'v1'
.
- # - :authorization
â
- # The authorization mechanism for the response. Used only if
- # :authenticated
is true
.
- # - :authenticated
â
- # true
if the request must be signed or otherwise
- # authenticated, false
- # otherwise. Defaults to true
if an authorization
- # mechanism has been set, false
otherwise.
- #
- # @return [Array] The generated request.
+ # @option options [Hash, Array] :headers The HTTP headers for the request.
+ # @option options [String] :body The body of the request.
+ # @option options [String] :version ("v1")
+ # The service version. Only used if `api_method` is a `String`.
+ # @option options [#generate_authenticated_request] :authorization
+ # The authorization mechanism for the response. Used only if
+ # `:authenticated` is `true`.
+ # @option options [TrueClass, FalseClass] :authenticated (true)
+ # `true` if the request must be signed or somehow
+ # authenticated, `false` otherwise.
+ #
+ # @return [Google::APIClient::Reference] The generated request.
#
# @example
# request = client.generate_request(
- # :api_method => 'chili.activities.list',
+ # :api_method => 'plus.activities.list',
# :parameters =>
- # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
+ # {'collection' => 'public', 'userId' => 'me'}
# )
- # method, uri, headers, body = request
def generate_request(options={})
- # Note: The merge method on a Hash object will coerce an API Reference
- # object into a Hash and merge with the default options.
- options={
- :version => 'v1',
- :authorization => self.authorization,
- :key => self.key,
- :user_ip => self.user_ip
+ options = {
+ :api_client => self
}.merge(options)
- # The Reference object is going to need this to do method ID lookups.
- options[:client] = self
- # The default value for the :authenticated option depends on whether an
- # authorization mechanism has been set.
- if options[:authorization]
- options = {:authenticated => true}.merge(options)
- else
- options = {:authenticated => false}.merge(options)
- end
- reference = Google::APIClient::Reference.new(options)
- request = reference.to_request
- if options[:authenticated]
- request = self.generate_authenticated_request(:request => request)
- end
- return request
+ return Google::APIClient::Request.new(options)
end
##
- # Signs a request using the current authorization mechanism.
+ # Executes a request, wrapping it in a Result object.
#
- # @param [Hash] options The options to pass through.
+ # @param [Google::APIClient::Request, Hash, Array] params
+ # Either a Google::APIClient::Request, a Hash, or an Array.
#
- # @return [Array] The signed or otherwise authenticated request.
- def generate_authenticated_request(options={})
- return authorization.generate_authenticated_request(options)
- end
-
- ##
- # Transmits the request using the current HTTP adapter.
- #
- # @param [Array] request The request to transmit.
- # @param [#transmit] adapter The HTTP adapter.
- #
- # @return [Array] The response from the server.
- def transmit(request, adapter=self.http_adapter)
- if self.user_agent != nil
- # If there's no User-Agent header, set one.
- method, uri, headers, body = request
- unless headers.kind_of?(Enumerable)
- # We need to use some Enumerable methods, relying on the presence of
- # the #each method.
- class <api_method
is a
- # String
. Defaults to 'v1'
.
- # - :adapter
â
- # The HTTP adapter.
- # - :authorization
â
- # The authorization mechanism for the response. Used only if
- # :authenticated
is true
.
- # - :authenticated
â
- # true
if the request must be signed or otherwise
- # authenticated, false
- # otherwise. Defaults to true
.
- #
- # @return [Array] The response from the API.
+ # If a Hash, the below parameters are handled. If an Array, the
+ # parameters are assumed to be in the below order:
+ #
+ # - (Google::APIClient::Method) api_method:
+ # The method object or the RPC name of the method being executed.
+ # - (Hash, Array) parameters:
+ # The parameters to send to the method.
+ # - (String) body: The body of the request.
+ # - (Hash, Array) headers: The HTTP headers for the request.
+ # - (Hash) options: A set of options for the request, of which:
+ # - (#generate_authenticated_request) :authorization (default: true) -
+ # The authorization mechanism for the response. Used only if
+ # `:authenticated` is `true`.
+ # - (TrueClass, FalseClass) :authenticated (default: true) -
+ # `true` if the request must be signed or somehow
+ # authenticated, `false` otherwise.
+ #
+ # @return [Google::APIClient::Result] The result from the API, nil if batch.
#
# @example
- # request = client.generate_request(
- # :api_method => 'chili.activities.list',
- # :parameters =>
- # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
+ # result = client.execute(batch_request)
+ #
+ # @example
+ # plus = client.discovered_api('plus')
+ # result = client.execute(
+ # :api_method => plus.activities.list,
+ # :parameters => {'collection' => 'public', 'userId' => 'me'}
# )
+ #
+ # @see Google::APIClient#generate_request
def execute(*params)
- # This block of code allows us to accept multiple parameter passing
- # styles, and maintaining some backwards compatibility.
- #
- # Note: I'm extremely tempted to deprecate this style of execute call.
- if params.last.respond_to?(:to_hash) && params.size == 1
- options = params.pop
- else
+ if params.last.kind_of?(Google::APIClient::Request) &&
+ params.size == 1
+ request = params.pop
options = {}
+ else
+ # This block of code allows us to accept multiple parameter passing
+ # styles, and maintaining some backwards compatibility.
+ #
+ # Note: I'm extremely tempted to deprecate this style of execute call.
+ if params.last.respond_to?(:to_hash) && params.size == 1
+ options = params.pop
+ else
+ options = {}
+ end
+
+ options[:api_method] = params.shift if params.size > 0
+ options[:parameters] = params.shift if params.size > 0
+ options[:body] = params.shift if params.size > 0
+ options[:headers] = params.shift if params.size > 0
+ options.update(params.shift) if params.size > 0
+ request = self.generate_request(options)
end
- options[:api_method] = params.shift if params.size > 0
- options[:parameters] = params.shift if params.size > 0
- options[:merged_body] = params.shift if params.size > 0
- options[:headers] = params.shift if params.size > 0
- options[:client] = self
-
- reference = Google::APIClient::Reference.new(options)
- request = self.generate_request(reference)
- response = self.transmit(
- request,
- options[:adapter] || self.http_adapter
- )
- return Google::APIClient::Result.new(reference, request, response)
+
+ request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
+ request.parameters['key'] ||= self.key unless self.key.nil?
+ request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
+
+ connection = options[:connection] || Faraday.default_connection
+ request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
+
+ result = request.send(connection)
+ if result.status == 401 && authorization.respond_to?(:refresh_token) && auto_refresh_token
+ begin
+ logger.debug("Attempting refresh of access token & retry of request")
+ authorization.fetch_access_token!
+ result = request.send(connection)
+ rescue Signet::AuthorizationError
+ # Ignore since we want the original error
+ end
+ end
+
+ return result
end
##
@@ -593,27 +581,52 @@ module Google
# @see Google::APIClient#execute
def execute!(*params)
result = self.execute(*params)
- status, _, _ = result.response
- if result.data.respond_to?(:error) &&
- result.data.error.respond_to?(:message)
- # You're going to get a terrible error message if the response isn't
- # parsed successfully as an error.
- error_message = result.data.error.message
- elsif result.data['error'] && result.data['error']['message']
- error_message = result.data['error']['message']
- end
- if status >= 400 && status < 500
- raise ClientError,
- error_message || "A client error has occurred."
- elsif status >= 500 && status < 600
- raise ServerError,
- error_message || "A server error has occurred."
- elsif status > 600
- raise TransmissionError,
- error_message || "A transmission error has occurred."
+ if result.error?
+ error_message = result.error_message
+ case result.response.status
+ when 400...500
+ exception_type = ClientError
+ error_message ||= "A client error has occurred."
+ when 500...600
+ exception_type = ServerError
+ error_message ||= "A server error has occurred."
+ else
+ exception_type = TransmissionError
+ error_message ||= "A transmission error has occurred."
+ end
+ raise exception_type, error_message
end
return result
end
+
+ protected
+
+ ##
+ # Resolves a URI template against the client's configured base.
+ #
+ # @api private
+ # @param [String, Addressable::URI, Addressable::Template] template
+ # The template to resolve.
+ # @param [Hash] mapping The mapping that corresponds to the template.
+ # @return [Addressable::URI] The expanded URI.
+ def resolve_uri(template, mapping={})
+ @base_uri ||= Addressable::URI.new(
+ :scheme => 'https',
+ :host => self.host,
+ :port => self.port
+ ).normalize
+ template = if template.kind_of?(Addressable::Template)
+ template.pattern
+ elsif template.respond_to?(:to_str)
+ template.to_str
+ else
+ raise TypeError,
+ "Expected String, Addressable::URI, or Addressable::Template, " +
+ "got #{template.class}."
+ end
+ return Addressable::Template.new(@base_uri + template).expand(mapping)
+ end
+
end
end