X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/18d3cccd6a471ce4b75460836730ed0918b36439..ee6f8ae6f983f2beb1afa94f9332f9e244fbbb9d:/lib/google/api_client.rb
diff --git a/lib/google/api_client.rb b/lib/google/api_client.rb
index ddf70a12f6..4c9ee03c7a 100644
--- a/lib/google/api_client.rb
+++ b/lib/google/api_client.rb
@@ -20,22 +20,25 @@ 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.
#
@@ -49,6 +52,10 @@ module Google
#
:oauth_1
# :oauth_2
#
+ # @option options [Boolean] :auto_refresh_token (true)
+ # The setting that controls whether or not the api client attempts to
+ # refresh authorization when a 401 is hit in #execute. If the token does
+ # not support it, this option is ignored.
# @option options [String] :application_name
# The name of the application using the client.
# @option options [String] :application_version
@@ -64,38 +71,43 @@ module Google
# @option options [String] :discovery_path ("/discovery/v1")
# The discovery base path. This rarely needs to be changed.
def initialize(options={})
+ logger.debug { "#{self.class} - Initializing client with options #{options}" }
+
# Normalize key to String to allow indifferent access.
options = options.inject({}) do |accu, (key, value)|
- accu[key.to_s] = value
+ accu[key.to_sym] = value
accu
end
# Almost all API usage will have a host of 'www.googleapis.com'.
- self.host = options["host"] || 'www.googleapis.com'
- self.port = options["port"] || 443
- self.discovery_path = options["discovery_path"] || '/discovery/v1'
+ self.host = options[:host] || 'www.googleapis.com'
+ self.port = options[:port] || 443
+ self.discovery_path = options[:discovery_path] || '/discovery/v1'
# Most developers will want to leave this value alone and use the
# application_name option.
- application_string = (
- options["application_name"] ? (
- "#{options["application_name"]}/" +
- "#{options["application_version"] || '0.0.0'}"
- ) : ""
- )
- self.user_agent = options["user_agent"] || (
+ if options[:application_name]
+ app_name = options[:application_name]
+ app_version = options[:application_version]
+ application_string = "#{app_name}/#{app_version || '0.0.0'}"
+ else
+ logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
+ end
+ self.user_agent = options[:user_agent] || (
"#{application_string} " +
- "google-api-ruby-client/#{VERSION::STRING} " +
+ "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} " +
ENV::OS_VERSION
).strip
# The writer method understands a few Symbols and will generate useful
# default authentication mechanisms.
self.authorization =
- options.key?("authorization") ? options["authorization"] : :oauth_2
- self.key = options["key"]
- self.user_ip = options["user_ip"]
+ options.key?(:authorization) ? options[:authorization] : :oauth_2
+ self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
+ self.key = options[:key]
+ self.user_ip = options[:user_ip]
@discovery_uris = {}
@discovery_documents = {}
@discovered_apis = {}
+
return self
end
@@ -155,6 +167,13 @@ module Google
return @authorization
end
+ ##
+ # The setting that controls whether or not the api client attempts to
+ # refresh authorization when a 401 is hit in #execute.
+ #
+ # @return [Boolean]
+ attr_accessor :auto_refresh_token
+
##
# The application's API key issued by the API console.
#
@@ -195,31 +214,6 @@ module Google
# The base path. Should almost always be '/discovery/v1'.
attr_accessor :discovery_path
- ##
- # Resolves a URI template against the client's configured base.
- #
- # @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
-
##
# Returns the URI for the directory document.
#
@@ -292,7 +286,7 @@ module Google
response = self.execute!(
:http_method => :get,
:uri => self.directory_uri,
- :authorization => :none
+ :authenticated => false
)
response.data
end)
@@ -311,7 +305,7 @@ module Google
response = self.execute!(
:http_method => :get,
:uri => self.discovery_uri(api, version),
- :authorization => :none
+ :authenticated => false
)
response.data
end)
@@ -369,7 +363,7 @@ module Google
# Returns the method object for a given RPC name and service version.
#
# @param [String, Symbol] rpc_name The RPC name of the desired method.
- # @param [String, Symbol] rpc_name The API the method is within.
+ # @param [String, Symbol] api The API the method is within.
# @param [String] version The desired version of the API.
#
# @return [Google::APIClient::Method] The method object.
@@ -447,7 +441,7 @@ module Google
response = self.execute!(
:http_method => :get,
:uri => 'https://www.googleapis.com/oauth2/v1/certs',
- :authorization => :none
+ :authenticated => false
)
@certificates.merge!(
Hash[MultiJson.load(response.body).map do |key, cert|
@@ -464,35 +458,10 @@ module Google
return nil
end
- def normalize_api_method(options)
- method = options[:api_method]
- version = options[:version]
- if method.kind_of?(Google::APIClient::Method) || method == nil
- return method
- elsif method.respond_to?(:to_str) || method.kind_of?(Symbol)
- # This method of guessing the API is unreliable. This will fail for
- # APIs where the first segment of the RPC name does not match the
- # service name. However, this is a fallback mechanism anyway.
- # Developers should be passing in a reference to the method, rather
- # than passing in a string or symbol. This should raise an error
- # in the case of a mismatch.
- method = method.to_s
- api = method[/^([^.]+)\./, 1]
- api_method = self.discovered_method(method, api, version)
- if api_method.nil?
- raise ArgumentError, "API method could not be found."
- end
- return api_method
- else
- raise TypeError,
- "Expected Google::APIClient::Method, got #{new_api_method.class}."
- end
- end
-
##
# Generates a request.
#
- # @option options [Google::APIClient::Method, String] :api_method
+ # @option options [Google::APIClient::Method] :api_method
# The method object or the RPC name of the method being executed.
# @option options [Hash, Array] :parameters
# The parameters to send to the method.
@@ -516,59 +485,30 @@ module Google
# {'collection' => 'public', 'userId' => 'me'}
# )
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,
- :connection => Faraday.default_connection
+ options = {
+ :api_client => self
}.merge(options)
-
- options[:api_method] = self.normalize_api_method(options)
- return Google::APIClient::Reference.new(options)
- end
-
- ##
- # Transmits the request using the current HTTP adapter.
- #
- # @option options [Array, Faraday::Request] :request
- # The HTTP request to transmit.
- # @option options [Faraday::Connection] :connection
- # The HTTP connection to use.
- #
- # @return [Faraday::Response] The response from the server.
- def transmit(options={})
- options[:connection] ||= Faraday.default_connection
- request = options[:request]
- request['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
- request_env = request.to_env(options[:connection])
- response = options[:connection].app.call(request_env)
- return response
+ return Google::APIClient::Request.new(options)
end
##
# Executes a request, wrapping it in a Result object.
#
- # @param [Google::APIClient::BatchRequest, Hash, Array] params
- # Either a Google::APIClient::BatchRequest, a Hash, or an Array.
+ # @param [Google::APIClient::Request, Hash, Array] params
+ # Either a Google::APIClient::Request, a Hash, or an Array.
#
- # If a Google::APIClient::BatchRequest, no other parameters are expected.
+ # If a Google::APIClient::Request, no other parameters are expected.
#
# If a Hash, the below parameters are handled. If an Array, the
# parameters are assumed to be in the below order:
#
- # - (Google::APIClient::Method, String) api_method:
+ # - (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:
- # - (String) :version (default: "v1") -
- # The service version. Only used if `api_method` is a `String`.
# - (#generate_authenticated_request) :authorization (default: true) -
# The authorization mechanism for the response. Used only if
# `:authenticated` is `true`.
@@ -582,27 +522,18 @@ module Google
# result = client.execute(batch_request)
#
# @example
+ # plus = client.discovered_api('plus')
# result = client.execute(
- # :api_method => 'plus.activities.list',
+ # :api_method => plus.activities.list,
# :parameters => {'collection' => 'public', 'userId' => 'me'}
# )
#
# @see Google::APIClient#generate_request
def execute(*params)
- if params.last.kind_of?(Google::APIClient::BatchRequest) &&
+ if params.last.kind_of?(Google::APIClient::Request) &&
params.size == 1
- batch = params.pop
- options = batch.options
- method, uri, headers, body = batch.to_http_request
- reference = self.generate_request({
- :uri => uri,
- :http_method => method,
- :headers => headers,
- :body => body
- }.merge(options))
- response = self.transmit(:request => reference.to_http_request, :connection => options[:connection])
- batch.process_response(response)
- return nil
+ request = params.pop
+ options = {}
else
# This block of code allows us to accept multiple parameter passing
# styles, and maintaining some backwards compatibility.
@@ -618,15 +549,29 @@ module Google
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[:client] = self
- reference = self.generate_request(options)
- response = self.transmit(
- :request => reference.to_http_request,
- :connection => options[:connection]
- )
- result = Google::APIClient::Result.new(reference, response)
- return result
+ options.update(params.shift) if params.size > 0
+ request = self.generate_request(options)
end
+
+ 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
##
@@ -653,6 +598,35 @@ module Google
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