#160 - Add option to set encoding of response body
[arvados.git] / lib / google / api_client.rb
index dd8be6ab027bb690815200c9134fbfd96e2dfe0b..eeaf2593398889bdad84d3c04dcb62a416f389d4 100644 (file)
@@ -31,8 +31,9 @@ require 'google/api_client/media'
 require 'google/api_client/service_account'
 require 'google/api_client/batch'
 require 'google/api_client/gzip'
+require 'google/api_client/charset'
 require 'google/api_client/client_secrets'
-require 'google/api_client/railtie' if defined?(Rails::Railtie)
+require 'google/api_client/railtie' if defined?(Rails)
 
 module Google
 
@@ -75,6 +76,11 @@ module Google
     # @option options [String] :ca_file
     #   Optional set of root certificates to use when validating SSL connections.
     #   By default, a bundled set of trusted roots will be used.
+    # @options options[Hash] :force_encoding
+    #   Experimental option. True if response body should be force encoded into the charset
+    #   specified in the Content-Type header. Mostly intended for compressed content.
+    # @options options[Hash] :faraday_options
+    #   Pass through of options to set on the Faraday connection
     def initialize(options={})
       logger.debug { "#{self.class} - Initializing client with options #{options}" }
       
@@ -97,6 +103,9 @@ module Google
       else
         logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
       end
+
+      proxy = options[:proxy] || Object::ENV["http_proxy"]
+
       self.user_agent = options[:user_agent] || (
         "#{application_string} " +
         "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
@@ -114,12 +123,19 @@ module Google
       @discovered_apis = {}
       ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
       self.connection = Faraday.new do |faraday|
+        faraday.response :charset if options[:force_encoding]
         faraday.response :gzip
         faraday.options.params_encoder = Faraday::FlatParamsEncoder
         faraday.ssl.ca_file = ca_file
         faraday.ssl.verify = true
+        faraday.proxy proxy
         faraday.adapter Faraday.default_adapter
-      end      
+        if options[:faraday_option].is_a?(Hash)
+          options[:faraday_option].each_pair do |option, value|
+            faraday.options.send("#{option}=", value)
+          end
+        end
+      end
       return self
     end
 
@@ -254,10 +270,12 @@ module Google
     # @param [String, Symbol] api The API name.
     # @param [String] version The desired version of the API.
     # @param [Addressable::URI] uri The URI of the discovery document.
+    # @return [Google::APIClient::API] The service object.
     def register_discovery_uri(api, version, uri)
       api = api.to_s
       version = version || 'v1'
       @discovery_uris["#{api}:#{version}"] = uri
+      discovered_api(api, version)
     end
 
     ##
@@ -286,6 +304,7 @@ module Google
     # @param [String] version The desired version of the API.
     # @param [String, StringIO] discovery_document
     #   The contents of the discovery document.
+    # @return [Google::APIClient::API] The service object.
     def register_discovery_document(api, version, discovery_document)
       api = api.to_s
       version = version || 'v1'
@@ -300,6 +319,7 @@ module Google
       end
       @discovery_documents["#{api}:#{version}"] =
         MultiJson.load(discovery_document)
+      discovered_api(api, version)
     end
 
     ##
@@ -591,9 +611,12 @@ module Google
 
       connection = options[:connection] || self.connection
       request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
+      
       tries = 1 + (options[:retries] || self.retries)
+
       Retriable.retriable :tries => tries, 
-                          :on => [TransmissionError], 
+                          :on => [TransmissionError],
+                          :on_retry => client_error_handler(request.authorization),
                           :interval => lambda {|attempts| (2 ** attempts) + rand} do
         result = request.send(connection, true)
 
@@ -607,14 +630,6 @@ module Google
             }))
             raise RedirectError.new(result.headers['location'], result)
           when 400...500
-            if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
-              begin
-                logger.debug("Attempting refresh of access token & retry of request")
-                request.authorization.fetch_access_token!
-              rescue Signet::AuthorizationError
-                 # Ignore since we want the original error
-              end
-            end
             raise ClientError.new(result.error_message || "A client error has occurred", result)
           when 500...600
             raise ServerError.new(result.error_message || "A server error has occurred", result)
@@ -665,8 +680,31 @@ module Google
       return Addressable::Template.new(@base_uri + template).expand(mapping)
     end
     
+
+    ##
+    # Returns on proc for special processing of retries as not all client errors
+    # are recoverable. Only 401s should be retried and only if the credentials
+    # are refreshable
+    #
+    # @param [#fetch_access_token!] authorization
+    #   OAuth 2 credentials
+    # @return [Proc] 
+    def client_error_handler(authorization)  
+      can_refresh = authorization.respond_to?(:refresh_token) && auto_refresh_token 
+      Proc.new do |exception, tries|
+        next unless exception.kind_of?(ClientError)
+        if exception.result.status == 401 && can_refresh && tries == 1
+          begin
+            logger.debug("Attempting refresh of access token & retry of request")
+            authorization.fetch_access_token!
+            next
+          rescue Signet::AuthorizationError
+          end
+        end
+        raise exception
+      end
+    end
+
   end
 
 end
-
-require 'google/api_client/version'