Added option to support manually specified discovery URI.
[arvados.git] / lib / google / api_client / discovery.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 require 'json'
16 require 'addressable/uri'
17 require 'addressable/template'
18 require 'extlib/inflection'
19
20 module Google
21   class APIClient
22     ##
23     # An exception that is raised if a method is called with missing or
24     # invalid parameter values.
25     class ValidationError < StandardError
26     end
27
28     ##
29     # A service that has been described by a discovery document.
30     class Service
31
32       ##
33       # Creates a description of a particular version of a service.
34       #
35       # @param [String] service_name
36       #   The identifier for the service.  Note that while this frequently
37       #   matches the first segment of all of the service's RPC names, this
38       #   should not be assumed.  There is no requirement that these match.
39       # @param [String] service_version
40       #   The identifier for the service version.
41       # @param [Hash] service_description
42       #   The section of the discovery document that applies to this service
43       #   version.
44       #
45       # @return [Google::APIClient::Service] The constructed service object.
46       def initialize(service_name, service_version, service_description)
47         @name = service_name
48         @version = service_version
49         @description = service_description
50         metaclass = (class <<self; self; end)
51         self.resources.each do |resource|
52           method_name = Extlib::Inflection.underscore(resource.name).to_sym
53           if !self.respond_to?(method_name)
54             metaclass.send(:define_method, method_name) { resource }
55           end
56         end
57         self.methods.each do |method|
58           method_name = Extlib::Inflection.underscore(method.name).to_sym
59           if !self.respond_to?(method_name)
60             metaclass.send(:define_method, method_name) { method }
61           end
62         end
63       end
64
65       ##
66       # Returns the identifier for the service.
67       #
68       # @return [String] The service identifier.
69       attr_reader :name
70
71       ##
72       # Returns the version of the service.
73       #
74       # @return [String] The service version.
75       attr_reader :version
76
77       ##
78       # Returns the parsed section of the discovery document that applies to
79       # this version of the service.
80       #
81       # @return [Hash] The service description.
82       attr_reader :description
83
84       ##
85       # Returns the base URI for this version of the service.
86       #
87       # @return [Addressable::URI] The base URI that methods are joined to.
88       def base
89         return @base ||= Addressable::URI.parse(self.description['baseUrl'])
90       end
91
92       ##
93       # A list of resources available at the root level of this version of the
94       # service.
95       #
96       # @return [Array] A list of {Google::APIClient::Resource} objects.
97       def resources
98         return @resources ||= (
99           (self.description['resources'] || []).inject([]) do |accu, (k, v)|
100             accu << ::Google::APIClient::Resource.new(self.base, k, v)
101             accu
102           end
103         )
104       end
105
106       ##
107       # A list of methods available at the root level of this version of the
108       # service.
109       #
110       # @return [Array] A list of {Google::APIClient::Method} objects.
111       def methods
112         return @methods ||= (
113           (self.description['methods'] || []).inject([]) do |accu, (k, v)|
114             accu << ::Google::APIClient::Method.new(self.base, k, v)
115             accu
116           end
117         )
118       end
119
120       ##
121       # Converts the service to a flat mapping of RPC names and method objects.
122       #
123       # @return [Hash] All methods available on the service.
124       #
125       # @example
126       #   # Discover available methods
127       #   method_names = client.discovered_service('buzz').to_h.keys
128       def to_h
129         return @hash ||= (begin
130           methods_hash = {}
131           self.methods.each do |method|
132             methods_hash[method.rpc_name] = method
133           end
134           self.resources.each do |resource|
135             methods_hash.merge!(resource.to_h)
136           end
137           methods_hash
138         end)
139       end
140
141       ##
142       # Compares two versions of a service.
143       #
144       # @param [Object] other The service to compare.
145       #
146       # @return [Integer]
147       #   <code>-1</code> if the service is older than <code>other</code>.
148       #   <code>0</code> if the service is the same as <code>other</code>.
149       #   <code>1</code> if the service is newer than <code>other</code>.
150       #   <code>nil</code> if the service cannot be compared to
151       #   <code>other</code>.
152       def <=>(other)
153         # We can only compare versions of the same service
154         if other.kind_of?(self.class) && self.name == other.name
155           split_version = lambda do |version|
156             dotted_version = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 1]
157             suffix = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 3]
158             if dotted_version && suffix
159               [dotted_version.split('.').map { |v| v.to_i }, suffix]
160             else
161               [[-1], version]
162             end
163           end
164           self_sortable, self_suffix = split_version.call(self.version)
165           other_sortable, other_suffix = split_version.call(other.version)
166           result = self_sortable <=> other_sortable
167           if result != 0
168             return result
169           # If the dotted versions are equal, check the suffix.
170           # An omitted suffix should be sorted after an included suffix.
171           elsif self_suffix == ''
172             return 1
173           elsif other_suffix == ''
174             return -1
175           else
176             return self_suffix <=> other_suffix
177           end
178         else
179           return nil
180         end
181       end
182
183       ##
184       # Returns a <code>String</code> representation of the service's state.
185       #
186       # @return [String] The service's state, as a <code>String</code>.
187       def inspect
188         sprintf(
189           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
190         )
191       end
192     end
193
194     ##
195     # A resource that has been described by a discovery document.
196     class Resource
197
198       ##
199       # Creates a description of a particular version of a resource.
200       #
201       # @param [Addressable::URI] base
202       #   The base URI for the service.
203       # @param [String] resource_name
204       #   The identifier for the resource.
205       # @param [Hash] resource_description
206       #   The section of the discovery document that applies to this resource.
207       #
208       # @return [Google::APIClient::Resource] The constructed resource object.
209       def initialize(base, resource_name, resource_description)
210         @base = base
211         @name = resource_name
212         @description = resource_description
213         metaclass = (class <<self; self; end)
214         self.resources.each do |resource|
215           method_name = Extlib::Inflection.underscore(resource.name).to_sym
216           if !self.respond_to?(method_name)
217             metaclass.send(:define_method, method_name) { resource }
218           end
219         end
220         self.methods.each do |method|
221           method_name = Extlib::Inflection.underscore(method.name).to_sym
222           if !self.respond_to?(method_name)
223             metaclass.send(:define_method, method_name) { method }
224           end
225         end
226       end
227
228       ##
229       # Returns the identifier for the resource.
230       #
231       # @return [String] The resource identifier.
232       attr_reader :name
233
234       ##
235       # Returns the parsed section of the discovery document that applies to
236       # this resource.
237       #
238       # @return [Hash] The resource description.
239       attr_reader :description
240
241       ##
242       # Returns the base URI for this resource.
243       #
244       # @return [Addressable::URI] The base URI that methods are joined to.
245       attr_reader :base
246
247       ##
248       # A list of sub-resources available on this resource.
249       #
250       # @return [Array] A list of {Google::APIClient::Resource} objects.
251       def resources
252         return @resources ||= (
253           (self.description['resources'] || []).inject([]) do |accu, (k, v)|
254             accu << ::Google::APIClient::Resource.new(self.base, k, v)
255             accu
256           end
257         )
258       end
259
260       ##
261       # A list of methods available on this resource.
262       #
263       # @return [Array] A list of {Google::APIClient::Method} objects.
264       def methods
265         return @methods ||= (
266           (self.description['methods'] || []).inject([]) do |accu, (k, v)|
267             accu << ::Google::APIClient::Method.new(self.base, k, v)
268             accu
269           end
270         )
271       end
272
273       ##
274       # Converts the resource to a flat mapping of RPC names and method
275       # objects.
276       #
277       # @return [Hash] All methods available on the resource.
278       def to_h
279         return @hash ||= (begin
280           methods_hash = {}
281           self.methods.each do |method|
282             methods_hash[method.rpc_name] = method
283           end
284           self.resources.each do |resource|
285             methods_hash.merge!(resource.to_h)
286           end
287           methods_hash
288         end)
289       end
290
291       ##
292       # Returns a <code>String</code> representation of the resource's state.
293       #
294       # @return [String] The resource's state, as a <code>String</code>.
295       def inspect
296         sprintf(
297           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
298         )
299       end
300     end
301
302     ##
303     # A method that has been described by a discovery document.
304     class Method
305
306       ##
307       # Creates a description of a particular method.
308       #
309       # @param [Addressable::URI] base
310       #   The base URI for the service.
311       # @param [String] method_name
312       #   The identifier for the method.
313       # @param [Hash] method_description
314       #   The section of the discovery document that applies to this method.
315       #
316       # @return [Google::APIClient::Method] The constructed method object.
317       def initialize(base, method_name, method_description)
318         @base = base
319         @name = method_name
320         @description = method_description
321       end
322
323       ##
324       # Returns the identifier for the method.
325       #
326       # @return [String] The method identifier.
327       attr_reader :name
328
329       ##
330       # Returns the parsed section of the discovery document that applies to
331       # this method.
332       #
333       # @return [Hash] The method description.
334       attr_reader :description
335
336       ##
337       # Returns the base URI for the method.
338       #
339       # @return [Addressable::URI]
340       #   The base URI that this method will be joined to.
341       attr_reader :base
342
343       ##
344       # Returns the RPC name for the method.
345       #
346       # @return [String] The RPC name.
347       def rpc_name
348         return self.description['rpcName']
349       end
350
351       ##
352       # Returns the URI template for the method.  A parameter list can be
353       # used to expand this into a URI.
354       #
355       # @return [Addressable::Template] The URI template.
356       def uri_template
357         # TODO(bobaman) We shouldn't be calling #to_s here, this should be
358         # a join operation on a URI, but we have to treat these as Strings
359         # because of the way the discovery document provides the URIs.
360         # This should be fixed soon.
361         return @uri_template ||=
362           Addressable::Template.new(base.to_s + self.description['pathUrl'])
363       end
364
365       ##
366       # Normalizes parameters, converting to the appropriate types.
367       #
368       # @param [Hash, Array] parameters
369       #   The parameters to normalize.
370       #
371       # @return [Hash] The normalized parameters.
372       def normalize_parameters(parameters={})
373         # Convert keys to Strings when appropriate
374         if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
375           # Is a Hash or an Array a better return type?  Do we ever need to
376           # worry about the same parameter being sent twice with different
377           # values?
378           parameters = parameters.inject({}) do |accu, (k, v)|
379             k = k.to_s if k.kind_of?(Symbol)
380             k = k.to_str if k.respond_to?(:to_str)
381             unless k.kind_of?(String)
382               raise TypeError, "Expected String, got #{k.class}."
383             end
384             accu[k] = v
385             accu
386           end
387         else
388           raise TypeError,
389             "Expected Hash or Array, got #{parameters.class}."
390         end
391         return parameters
392       end
393
394       ##
395       # Expands the method's URI template using a parameter list.
396       #
397       # @param [Hash, Array] parameters
398       #   The parameter list to use.
399       #
400       # @return [Addressable::URI] The URI after expansion.
401       def generate_uri(parameters={})
402         parameters = self.normalize_parameters(parameters)
403         self.validate_parameters(parameters)
404         template_variables = self.uri_template.variables
405         uri = self.uri_template.expand(parameters)
406         query_parameters = parameters.reject do |k, v|
407           template_variables.include?(k)
408         end
409         if query_parameters.size > 0
410           uri.query_values = (uri.query_values || {}).merge(query_parameters)
411         end
412         # Normalization is necessary because of undesirable percent-escaping
413         # during URI template expansion
414         return uri.normalize
415       end
416
417       ##
418       # Generates an HTTP request for this method.
419       #
420       # @param [Hash, Array] parameters
421       #   The parameters to send.
422       # @param [String, StringIO] body The body for the HTTP request.
423       # @param [Hash, Array] headers The HTTP headers for the request.
424       #
425       # @return [Array] The generated HTTP request.
426       def generate_request(parameters={}, body='', headers=[])
427         if body.respond_to?(:string)
428           body = body.string
429         elsif body.respond_to?(:to_str)
430           body = body.to_str
431         else
432           raise TypeError, "Expected String or StringIO, got #{body.class}."
433         end
434         if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
435           raise TypeError, "Expected Hash or Array, got #{headers.class}."
436         end
437         method = self.description['httpMethod'] || 'GET'
438         uri = self.generate_uri(parameters)
439         headers = headers.to_a if headers.kind_of?(Hash)
440         return [method, uri.to_str, headers, [body]]
441       end
442
443       ##
444       # Returns a <code>Hash</code> of the parameter descriptions for
445       # this method.
446       #
447       # @return [Hash] The parameter descriptions.
448       def parameter_descriptions
449         @parameter_descriptions ||= (
450           self.description['parameters'] || {}
451         ).inject({}) { |h,(k,v)| h[k]=v; h }
452       end
453
454       ##
455       # Returns an <code>Array</code> of the parameters for this method.
456       #
457       # @return [Array] The parameters.
458       def parameters
459         @parameters ||= ((
460           self.description['parameters'] || {}
461         ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
462       end
463
464       ##
465       # Returns an <code>Array</code> of the required parameters for this
466       # method.
467       #
468       # @return [Array] The required parameters.
469       #
470       # @example
471       #   # A list of all required parameters.
472       #   method.required_parameters
473       def required_parameters
474         @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
475           v['required']
476         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
477       end
478
479       ##
480       # Returns an <code>Array</code> of the optional parameters for this
481       # method.
482       #
483       # @return [Array] The optional parameters.
484       #
485       # @example
486       #   # A list of all optional parameters.
487       #   method.optional_parameters
488       def optional_parameters
489         @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
490           v['required']
491         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
492       end
493
494       ##
495       # Verifies that the parameters are valid for this method.  Raises an
496       # exception if validation fails.
497       #
498       # @param [Hash, Array] parameters
499       #   The parameters to verify.
500       #
501       # @return [NilClass] <code>nil</code> if validation passes.
502       def validate_parameters(parameters={})
503         parameters = self.normalize_parameters(parameters)
504         required_variables = ((self.parameter_descriptions.select do |k, v|
505           v['required']
506         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
507         missing_variables = required_variables - parameters.keys
508         if missing_variables.size > 0
509           raise ArgumentError,
510             "Missing required parameters: #{missing_variables.join(', ')}."
511         end
512         parameters.each do |k, v|
513           if self.parameter_descriptions[k]
514             pattern = self.parameter_descriptions[k]['pattern']
515             if pattern
516               regexp = Regexp.new("^#{pattern}$")
517               if v !~ regexp
518                 raise ArgumentError,
519                   "Parameter '#{k}' has an invalid value: #{v}. " +
520                   "Must match: /^#{pattern}$/."
521               end
522             end
523           end
524         end
525         return nil
526       end
527
528       ##
529       # Returns a <code>String</code> representation of the method's state.
530       #
531       # @return [String] The method's state, as a <code>String</code>.
532       def inspect
533         sprintf(
534           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.rpc_name
535         )
536       end
537     end
538   end
539 end