Allow options when executing batch requests (#48)
[arvados.git] / lib / google / api_client.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 require 'faraday'
17 require 'faraday/utils'
18 require 'multi_json'
19 require 'compat/multi_json'
20 require 'stringio'
21
22 require 'google/api_client/version'
23 require 'google/api_client/logging'
24 require 'google/api_client/errors'
25 require 'google/api_client/environment'
26 require 'google/api_client/discovery'
27 require 'google/api_client/request'
28 require 'google/api_client/reference'
29 require 'google/api_client/result'
30 require 'google/api_client/media'
31 require 'google/api_client/service_account'
32 require 'google/api_client/batch'
33 require 'google/api_client/railtie' if defined?(Rails::Railtie)
34
35 module Google
36
37   ##
38   # This class manages APIs communication.
39   class APIClient
40     include Google::APIClient::Logging
41     
42     ##
43     # Creates a new Google API client.
44     #
45     # @param [Hash] options The configuration parameters for the client.
46     # @option options [Symbol, #generate_authenticated_request] :authorization
47     #   (:oauth_1)
48     #   The authorization mechanism used by the client.  The following
49     #   mechanisms are supported out-of-the-box:
50     #   <ul>
51     #     <li><code>:two_legged_oauth_1</code></li>
52     #     <li><code>:oauth_1</code></li>
53     #     <li><code>:oauth_2</code></li>
54     #   </ul>
55     # @option options [Boolean] :auto_refresh_token (true)
56     #   The setting that controls whether or not the api client attempts to
57     #   refresh authorization when a 401 is hit in #execute. If the token does 
58     #   not support it, this option is ignored.
59     # @option options [String] :application_name
60     #   The name of the application using the client.
61     # @option options [String] :application_version
62     #   The version number of the application using the client.
63     # @option options [String] :user_agent
64     #   ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
65     #   The user agent used by the client.  Most developers will want to
66     #   leave this value alone and use the `:application_name` option instead.
67     # @option options [String] :host ("www.googleapis.com")
68     #   The API hostname used by the client. This rarely needs to be changed.
69     # @option options [String] :port (443)
70     #   The port number used by the client. This rarely needs to be changed.
71     # @option options [String] :discovery_path ("/discovery/v1")
72     #   The discovery base path. This rarely needs to be changed.
73     def initialize(options={})
74       logger.debug { "#{self.class} - Initializing client with options #{options}" }
75       
76       # Normalize key to String to allow indifferent access.
77       options = options.inject({}) do |accu, (key, value)|
78         accu[key.to_sym] = value
79         accu
80       end
81       # Almost all API usage will have a host of 'www.googleapis.com'.
82       self.host = options[:host] || 'www.googleapis.com'
83       self.port = options[:port] || 443
84       self.discovery_path = options[:discovery_path] || '/discovery/v1'
85
86       # Most developers will want to leave this value alone and use the
87       # application_name option.
88       if options[:application_name]
89         app_name = options[:application_name]
90         app_version = options[:application_version]
91         application_string = "#{app_name}/#{app_version || '0.0.0'}"
92       else
93         logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
94       end
95       self.user_agent = options[:user_agent] || (
96         "#{application_string} " +
97         "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} " +
98          ENV::OS_VERSION
99       ).strip
100       # The writer method understands a few Symbols and will generate useful
101       # default authentication mechanisms.
102       self.authorization =
103         options.key?(:authorization) ? options[:authorization] : :oauth_2
104       self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
105       self.key = options[:key]
106       self.user_ip = options[:user_ip]
107       @discovery_uris = {}
108       @discovery_documents = {}
109       @discovered_apis = {}
110       
111       self.connection = Faraday.new do |faraday|
112         faraday.adapter  Faraday.default_adapter
113         faraday.options.params_encoder = Faraday::FlatParamsEncoder
114       end      
115
116       return self
117     end
118
119     ##
120     # Returns the authorization mechanism used by the client.
121     #
122     # @return [#generate_authenticated_request] The authorization mechanism.
123     attr_reader :authorization
124
125     ##
126     # Sets the authorization mechanism used by the client.
127     #
128     # @param [#generate_authenticated_request] new_authorization
129     #   The new authorization mechanism.
130     def authorization=(new_authorization)
131       case new_authorization
132       when :oauth_1, :oauth
133         require 'signet/oauth_1/client'
134         # NOTE: Do not rely on this default value, as it may change
135         new_authorization = Signet::OAuth1::Client.new(
136           :temporary_credential_uri =>
137             'https://www.google.com/accounts/OAuthGetRequestToken',
138           :authorization_uri =>
139             'https://www.google.com/accounts/OAuthAuthorizeToken',
140           :token_credential_uri =>
141             'https://www.google.com/accounts/OAuthGetAccessToken',
142           :client_credential_key => 'anonymous',
143           :client_credential_secret => 'anonymous'
144         )
145       when :two_legged_oauth_1, :two_legged_oauth
146         require 'signet/oauth_1/client'
147         # NOTE: Do not rely on this default value, as it may change
148         new_authorization = Signet::OAuth1::Client.new(
149           :client_credential_key => nil,
150           :client_credential_secret => nil,
151           :two_legged => true
152         )
153       when :oauth_2
154         require 'signet/oauth_2/client'
155         # NOTE: Do not rely on this default value, as it may change
156         new_authorization = Signet::OAuth2::Client.new(
157           :authorization_uri =>
158             'https://accounts.google.com/o/oauth2/auth',
159           :token_credential_uri =>
160             'https://accounts.google.com/o/oauth2/token'
161         )
162       when nil
163         # No authorization mechanism
164       else
165         if !new_authorization.respond_to?(:generate_authenticated_request)
166           raise TypeError,
167             'Expected authorization mechanism to respond to ' +
168             '#generate_authenticated_request.'
169         end
170       end
171       @authorization = new_authorization
172       return @authorization
173     end
174
175
176     ##
177     # Default Faraday/HTTP connection.
178     #
179     # @return [Faraday::Connection]
180     attr_accessor :connection
181
182     ##
183     # The setting that controls whether or not the api client attempts to
184     # refresh authorization when a 401 is hit in #execute. 
185     #
186     # @return [Boolean]
187     attr_accessor :auto_refresh_token
188
189     ##
190     # The application's API key issued by the API console.
191     #
192     # @return [String] The API key.
193     attr_accessor :key
194
195     ##
196     # The IP address of the user this request is being performed on behalf of.
197     #
198     # @return [String] The user's IP address.
199     attr_accessor :user_ip
200
201     ##
202     # The user agent used by the client.
203     #
204     # @return [String]
205     #   The user agent string used in the User-Agent header.
206     attr_accessor :user_agent
207
208     ##
209     # The API hostname used by the client.
210     #
211     # @return [String]
212     #   The API hostname. Should almost always be 'www.googleapis.com'.
213     attr_accessor :host
214
215     ##
216     # The port number used by the client.
217     #
218     # @return [String]
219     #   The port number. Should almost always be 443.
220     attr_accessor :port
221
222     ##
223     # The base path used by the client for discovery.
224     #
225     # @return [String]
226     #   The base path. Should almost always be '/discovery/v1'.
227     attr_accessor :discovery_path
228
229     ##
230     # Returns the URI for the directory document.
231     #
232     # @return [Addressable::URI] The URI of the directory document.
233     def directory_uri
234       return resolve_uri(self.discovery_path + '/apis')
235     end
236
237     ##
238     # Manually registers a URI as a discovery document for a specific version
239     # of an API.
240     #
241     # @param [String, Symbol] api The API name.
242     # @param [String] version The desired version of the API.
243     # @param [Addressable::URI] uri The URI of the discovery document.
244     def register_discovery_uri(api, version, uri)
245       api = api.to_s
246       version = version || 'v1'
247       @discovery_uris["#{api}:#{version}"] = uri
248     end
249
250     ##
251     # Returns the URI for the discovery document.
252     #
253     # @param [String, Symbol] api The API name.
254     # @param [String] version The desired version of the API.
255     # @return [Addressable::URI] The URI of the discovery document.
256     def discovery_uri(api, version=nil)
257       api = api.to_s
258       version = version || 'v1'
259       return @discovery_uris["#{api}:#{version}"] ||= (
260         resolve_uri(
261           self.discovery_path + '/apis/{api}/{version}/rest',
262           'api' => api,
263           'version' => version
264         )
265       )
266     end
267
268     ##
269     # Manually registers a pre-loaded discovery document for a specific version
270     # of an API.
271     #
272     # @param [String, Symbol] api The API name.
273     # @param [String] version The desired version of the API.
274     # @param [String, StringIO] discovery_document
275     #   The contents of the discovery document.
276     def register_discovery_document(api, version, discovery_document)
277       api = api.to_s
278       version = version || 'v1'
279       if discovery_document.kind_of?(StringIO)
280         discovery_document.rewind
281         discovery_document = discovery_document.string
282       elsif discovery_document.respond_to?(:to_str)
283         discovery_document = discovery_document.to_str
284       else
285         raise TypeError,
286           "Expected String or StringIO, got #{discovery_document.class}."
287       end
288       @discovery_documents["#{api}:#{version}"] =
289         MultiJson.load(discovery_document)
290     end
291
292     ##
293     # Returns the parsed directory document.
294     #
295     # @return [Hash] The parsed JSON from the directory document.
296     def directory_document
297       return @directory_document ||= (begin
298         response = self.execute!(
299           :http_method => :get,
300           :uri => self.directory_uri,
301           :authenticated => false
302         )
303         response.data
304       end)
305     end
306
307     ##
308     # Returns the parsed discovery document.
309     #
310     # @param [String, Symbol] api The API name.
311     # @param [String] version The desired version of the API.
312     # @return [Hash] The parsed JSON from the discovery document.
313     def discovery_document(api, version=nil)
314       api = api.to_s
315       version = version || 'v1'
316       return @discovery_documents["#{api}:#{version}"] ||= (begin
317         response = self.execute!(
318           :http_method => :get,
319           :uri => self.discovery_uri(api, version),
320           :authenticated => false
321         )
322         response.data
323       end)
324     end
325
326     ##
327     # Returns all APIs published in the directory document.
328     #
329     # @return [Array] The list of available APIs.
330     def discovered_apis
331       @directory_apis ||= (begin
332         document_base = self.directory_uri
333         if self.directory_document && self.directory_document['items']
334           self.directory_document['items'].map do |discovery_document|
335             Google::APIClient::API.new(
336               document_base,
337               discovery_document
338             )
339           end
340         else
341           []
342         end
343       end)
344     end
345
346     ##
347     # Returns the service object for a given service name and service version.
348     #
349     # @param [String, Symbol] api The API name.
350     # @param [String] version The desired version of the API.
351     #
352     # @return [Google::APIClient::API] The service object.
353     def discovered_api(api, version=nil)
354       if !api.kind_of?(String) && !api.kind_of?(Symbol)
355         raise TypeError,
356           "Expected String or Symbol, got #{api.class}."
357       end
358       api = api.to_s
359       version = version || 'v1'
360       return @discovered_apis["#{api}:#{version}"] ||= begin
361         document_base = self.discovery_uri(api, version)
362         discovery_document = self.discovery_document(api, version)
363         if document_base && discovery_document
364           Google::APIClient::API.new(
365             document_base,
366             discovery_document
367           )
368         else
369           nil
370         end
371       end
372     end
373
374     ##
375     # Returns the method object for a given RPC name and service version.
376     #
377     # @param [String, Symbol] rpc_name The RPC name of the desired method.
378     # @param [String, Symbol] api The API the method is within.
379     # @param [String] version The desired version of the API.
380     #
381     # @return [Google::APIClient::Method] The method object.
382     def discovered_method(rpc_name, api, version=nil)
383       if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
384         raise TypeError,
385           "Expected String or Symbol, got #{rpc_name.class}."
386       end
387       rpc_name = rpc_name.to_s
388       api = api.to_s
389       version = version || 'v1'
390       service = self.discovered_api(api, version)
391       if service.to_h[rpc_name]
392         return service.to_h[rpc_name]
393       else
394         return nil
395       end
396     end
397
398     ##
399     # Returns the service object with the highest version number.
400     #
401     # @note <em>Warning</em>: This method should be used with great care.
402     # As APIs are updated, minor differences between versions may cause
403     # incompatibilities. Requesting a specific version will avoid this issue.
404     #
405     # @param [String, Symbol] api The name of the service.
406     #
407     # @return [Google::APIClient::API] The service object.
408     def preferred_version(api)
409       if !api.kind_of?(String) && !api.kind_of?(Symbol)
410         raise TypeError,
411           "Expected String or Symbol, got #{api.class}."
412       end
413       api = api.to_s
414       return self.discovered_apis.detect do |a|
415         a.name == api && a.preferred == true
416       end
417     end
418
419     ##
420     # Verifies an ID token against a server certificate. Used to ensure that
421     # an ID token supplied by an untrusted client-side mechanism is valid.
422     # Raises an error if the token is invalid or missing.
423     def verify_id_token!
424       require 'jwt'
425       require 'openssl'
426       @certificates ||= {}
427       if !self.authorization.respond_to?(:id_token)
428         raise ArgumentError, (
429           "Current authorization mechanism does not support ID tokens: " +
430           "#{self.authorization.class.to_s}"
431         )
432       elsif !self.authorization.id_token
433         raise ArgumentError, (
434           "Could not verify ID token, ID token missing. " +
435           "Scopes were: #{self.authorization.scope.inspect}"
436         )
437       else
438         check_cached_certs = lambda do
439           valid = false
440           for key, cert in @certificates
441             begin
442               self.authorization.decoded_id_token(cert.public_key)
443               valid = true
444             rescue JWT::DecodeError, Signet::UnsafeOperationError
445               # Expected exception. Ignore, ID token has not been validated.
446             end
447           end
448           valid
449         end
450         if check_cached_certs.call()
451           return true
452         end
453         response = self.execute!(
454           :http_method => :get,
455           :uri => 'https://www.googleapis.com/oauth2/v1/certs',
456           :authenticated => false
457         )
458         @certificates.merge!(
459           Hash[MultiJson.load(response.body).map do |key, cert|
460             [key, OpenSSL::X509::Certificate.new(cert)]
461           end]
462         )
463         if check_cached_certs.call()
464           return true
465         else
466           raise InvalidIDTokenError,
467             "Could not verify ID token against any available certificate."
468         end
469       end
470       return nil
471     end
472
473     ##
474     # Generates a request.
475     #
476     # @option options [Google::APIClient::Method] :api_method
477     #   The method object or the RPC name of the method being executed.
478     # @option options [Hash, Array] :parameters
479     #   The parameters to send to the method.
480     # @option options [Hash, Array] :headers The HTTP headers for the request.
481     # @option options [String] :body The body of the request.
482     # @option options [String] :version ("v1")
483     #   The service version. Only used if `api_method` is a `String`.
484     # @option options [#generate_authenticated_request] :authorization
485     #   The authorization mechanism for the response. Used only if
486     #   `:authenticated` is `true`.
487     # @option options [TrueClass, FalseClass] :authenticated (true)
488     #   `true` if the request must be signed or somehow
489     #   authenticated, `false` otherwise.
490     #
491     # @return [Google::APIClient::Reference] The generated request.
492     #
493     # @example
494     #   request = client.generate_request(
495     #     :api_method => 'plus.activities.list',
496     #     :parameters =>
497     #       {'collection' => 'public', 'userId' => 'me'}
498     #   )
499     def generate_request(options={})
500       options = {
501         :api_client => self
502       }.merge(options)
503       return Google::APIClient::Request.new(options)
504     end
505
506     ##
507     # Executes a request, wrapping it in a Result object.
508     #
509     # @param [Google::APIClient::Request, Hash, Array] params
510     #   Either a Google::APIClient::Request, a Hash, or an Array.
511     #
512     #   If a Google::APIClient::Request, no other parameters are expected.
513     #
514     #   If a Hash, the below parameters are handled. If an Array, the
515     #   parameters are assumed to be in the below order:
516     #
517     #   - (Google::APIClient::Method) api_method:
518     #     The method object or the RPC name of the method being executed.
519     #   - (Hash, Array) parameters:
520     #     The parameters to send to the method.
521     #   - (String) body: The body of the request.
522     #   - (Hash, Array) headers: The HTTP headers for the request.
523     #   - (Hash) options: A set of options for the request, of which:
524     #     - (#generate_authenticated_request) :authorization (default: true) -
525     #       The authorization mechanism for the response. Used only if
526     #       `:authenticated` is `true`.
527     #     - (TrueClass, FalseClass) :authenticated (default: true) -
528     #       `true` if the request must be signed or somehow
529     #       authenticated, `false` otherwise.
530     #
531     # @return [Google::APIClient::Result] The result from the API, nil if batch.
532     #
533     # @example
534     #   result = client.execute(batch_request)
535     #
536     # @example
537     #   plus = client.discovered_api('plus')
538     #   result = client.execute(
539     #     :api_method => plus.activities.list,
540     #     :parameters => {'collection' => 'public', 'userId' => 'me'}
541     #   )
542     #
543     # @see Google::APIClient#generate_request
544     def execute(*params)
545       if params.first.kind_of?(Google::APIClient::Request)
546         request = params.shift
547         options = params.shift || {}
548       else
549         # This block of code allows us to accept multiple parameter passing
550         # styles, and maintaining some backwards compatibility.
551         #
552         # Note: I'm extremely tempted to deprecate this style of execute call.
553         if params.last.respond_to?(:to_hash) && params.size == 1
554           options = params.pop
555         else
556           options = {}
557         end
558
559         options[:api_method] = params.shift if params.size > 0
560         options[:parameters] = params.shift if params.size > 0
561         options[:body] = params.shift if params.size > 0
562         options[:headers] = params.shift if params.size > 0
563         options.update(params.shift) if params.size > 0
564         request = self.generate_request(options)
565       end
566       
567       request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
568       request.parameters['key'] ||= self.key unless self.key.nil?
569       request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
570
571       connection = options[:connection] || self.connection
572       request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
573
574       result = request.send(connection)
575       if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
576         begin
577           logger.debug("Attempting refresh of access token & retry of request")
578           request.authorization.fetch_access_token!
579           result = request.send(connection)
580         rescue Signet::AuthorizationError
581            # Ignore since we want the original error
582         end
583       end
584       
585       return result
586     end
587
588     ##
589     # Same as Google::APIClient#execute, but raises an exception if there was
590     # an error.
591     #
592     # @see Google::APIClient#execute
593     def execute!(*params)
594       result = self.execute(*params)
595       if result.error?
596         error_message = result.error_message
597         case result.response.status
598           when 400...500
599             exception_type = ClientError
600             error_message ||= "A client error has occurred."
601           when 500...600
602             exception_type = ServerError
603             error_message ||= "A server error has occurred."
604           else
605             exception_type = TransmissionError
606             error_message ||= "A transmission error has occurred."
607         end
608         raise exception_type, error_message
609       end
610       return result
611     end
612     
613     protected
614     
615     ##
616     # Resolves a URI template against the client's configured base.
617     #
618     # @api private
619     # @param [String, Addressable::URI, Addressable::Template] template
620     #   The template to resolve.
621     # @param [Hash] mapping The mapping that corresponds to the template.
622     # @return [Addressable::URI] The expanded URI.
623     def resolve_uri(template, mapping={})
624       @base_uri ||= Addressable::URI.new(
625         :scheme => 'https',
626         :host => self.host,
627         :port => self.port
628       ).normalize
629       template = if template.kind_of?(Addressable::Template)
630         template.pattern
631       elsif template.respond_to?(:to_str)
632         template.to_str
633       else
634         raise TypeError,
635           "Expected String, Addressable::URI, or Addressable::Template, " +
636           "got #{template.class}."
637       end
638       return Addressable::Template.new(@base_uri + template).expand(mapping)
639     end
640     
641   end
642 end
643
644 require 'google/api_client/version'