Added example to Service#to_h method.
[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       def to_h
125         return @hash ||= (begin
126           methods_hash = {}
127           self.methods.each do |method|
128             methods_hash[method.rpc_name] = method
129           end
130           self.resources.each do |resource|
131             methods_hash.merge!(resource.to_h)
132           end
133           methods_hash
134         end)
135       end
136
137       ##
138       # Returns a <code>String</code> representation of the service's state.
139       #
140       # @return [String] The service's state, as a <code>String</code>.
141       #
142       # @example
143       #   # Discover available methods
144       #   method_names = client.discovered_service('buzz').to_h.keys
145       def inspect
146         sprintf(
147           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
148         )
149       end
150     end
151
152     ##
153     # A resource that has been described by a discovery document.
154     class Resource
155
156       ##
157       # Creates a description of a particular version of a resource.
158       #
159       # @param [Addressable::URI] base
160       #   The base URI for the service.
161       # @param [String] resource_name
162       #   The identifier for the resource.
163       # @param [Hash] resource_description
164       #   The section of the discovery document that applies to this resource.
165       #
166       # @return [Google::APIClient::Resource] The constructed resource object.
167       def initialize(base, resource_name, resource_description)
168         @base = base
169         @name = resource_name
170         @description = resource_description
171         metaclass = (class <<self; self; end)
172         self.resources.each do |resource|
173           method_name = Extlib::Inflection.underscore(resource.name).to_sym
174           if !self.respond_to?(method_name)
175             metaclass.send(:define_method, method_name) { resource }
176           end
177         end
178         self.methods.each do |method|
179           method_name = Extlib::Inflection.underscore(method.name).to_sym
180           if !self.respond_to?(method_name)
181             metaclass.send(:define_method, method_name) { method }
182           end
183         end
184       end
185
186       ##
187       # Returns the identifier for the resource.
188       #
189       # @return [String] The resource identifier.
190       attr_reader :name
191
192       ##
193       # Returns the parsed section of the discovery document that applies to
194       # this resource.
195       #
196       # @return [Hash] The resource description.
197       attr_reader :description
198
199       ##
200       # Returns the base URI for this resource.
201       #
202       # @return [Addressable::URI] The base URI that methods are joined to.
203       attr_reader :base
204
205       ##
206       # A list of sub-resources available on this resource.
207       #
208       # @return [Array] A list of {Google::APIClient::Resource} objects.
209       def resources
210         return @resources ||= (
211           (self.description['resources'] || []).inject([]) do |accu, (k, v)|
212             accu << ::Google::APIClient::Resource.new(self.base, k, v)
213             accu
214           end
215         )
216       end
217
218       ##
219       # A list of methods available on this resource.
220       #
221       # @return [Array] A list of {Google::APIClient::Method} objects.
222       def methods
223         return @methods ||= (
224           (self.description['methods'] || []).inject([]) do |accu, (k, v)|
225             accu << ::Google::APIClient::Method.new(self.base, k, v)
226             accu
227           end
228         )
229       end
230
231       ##
232       # Converts the resource to a flat mapping of RPC names and method
233       # objects.
234       #
235       # @return [Hash] All methods available on the resource.
236       def to_h
237         return @hash ||= (begin
238           methods_hash = {}
239           self.methods.each do |method|
240             methods_hash[method.rpc_name] = method
241           end
242           self.resources.each do |resource|
243             methods_hash.merge!(resource.to_h)
244           end
245           methods_hash
246         end)
247       end
248
249       ##
250       # Returns a <code>String</code> representation of the resource's state.
251       #
252       # @return [String] The resource's state, as a <code>String</code>.
253       def inspect
254         sprintf(
255           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
256         )
257       end
258     end
259
260     ##
261     # A method that has been described by a discovery document.
262     class Method
263
264       ##
265       # Creates a description of a particular method.
266       #
267       # @param [Addressable::URI] base
268       #   The base URI for the service.
269       # @param [String] method_name
270       #   The identifier for the method.
271       # @param [Hash] method_description
272       #   The section of the discovery document that applies to this method.
273       #
274       # @return [Google::APIClient::Method] The constructed method object.
275       def initialize(base, method_name, method_description)
276         @base = base
277         @name = method_name
278         @description = method_description
279       end
280
281       ##
282       # Returns the identifier for the method.
283       #
284       # @return [String] The method identifier.
285       attr_reader :name
286
287       ##
288       # Returns the parsed section of the discovery document that applies to
289       # this method.
290       #
291       # @return [Hash] The method description.
292       attr_reader :description
293
294       ##
295       # Returns the base URI for the method.
296       #
297       # @return [Addressable::URI]
298       #   The base URI that this method will be joined to.
299       attr_reader :base
300
301       ##
302       # Returns the RPC name for the method.
303       #
304       # @return [String] The RPC name.
305       def rpc_name
306         return self.description['rpcName']
307       end
308
309       ##
310       # Returns the URI template for the method.  A parameter list can be
311       # used to expand this into a URI.
312       #
313       # @return [Addressable::Template] The URI template.
314       def uri_template
315         # TODO(bobaman) We shouldn't be calling #to_s here, this should be
316         # a join operation on a URI, but we have to treat these as Strings
317         # because of the way the discovery document provides the URIs.
318         # This should be fixed soon.
319         return @uri_template ||=
320           Addressable::Template.new(base.to_s + self.description['pathUrl'])
321       end
322
323       ##
324       # Normalizes parameters, converting to the appropriate types.
325       #
326       # @param [Hash, Array] parameters
327       #   The parameters to normalize.
328       #
329       # @return [Hash] The normalized parameters.
330       def normalize_parameters(parameters={})
331         # Convert keys to Strings when appropriate
332         if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
333           # Is a Hash or an Array a better return type?  Do we ever need to
334           # worry about the same parameter being sent twice with different
335           # values?
336           parameters = parameters.inject({}) do |accu, (k, v)|
337             k = k.to_s if k.kind_of?(Symbol)
338             k = k.to_str if k.respond_to?(:to_str)
339             unless k.kind_of?(String)
340               raise TypeError, "Expected String, got #{k.class}."
341             end
342             accu[k] = v
343             accu
344           end
345         else
346           raise TypeError,
347             "Expected Hash or Array, got #{parameters.class}."
348         end
349         return parameters
350       end
351
352       ##
353       # Expands the method's URI template using a parameter list.
354       #
355       # @param [Hash, Array] parameters
356       #   The parameter list to use.
357       #
358       # @return [Addressable::URI] The URI after expansion.
359       def generate_uri(parameters={})
360         parameters = self.normalize_parameters(parameters)
361         self.validate_parameters(parameters)
362         template_variables = self.uri_template.variables
363         uri = self.uri_template.expand(parameters)
364         query_parameters = parameters.reject do |k, v|
365           template_variables.include?(k)
366         end
367         if query_parameters.size > 0
368           uri.query_values = (uri.query_values || {}).merge(query_parameters)
369         end
370         # Normalization is necessary because of undesirable percent-escaping
371         # during URI template expansion
372         return uri.normalize
373       end
374
375       ##
376       # Generates an HTTP request for this method.
377       #
378       # @param [Hash, Array] parameters
379       #   The parameters to send.
380       # @param [String] body The body for the HTTP request.
381       # @param [Hash, Array] headers The HTTP headers for the request.
382       #
383       # @return [Array] The generated HTTP request.
384       def generate_request(parameters={}, body='', headers=[])
385         method = self.description['httpMethod'] || 'GET'
386         uri = self.generate_uri(parameters)
387         return [method, uri.to_str, headers, [body]]
388       end
389
390       ##
391       # Verifies that the parameters are valid for this method.  Raises an
392       # exception if validation fails.
393       #
394       # @param [Hash, Array] parameters
395       #   The parameters to verify.
396       #
397       # @return [NilClass] <code>nil</code> if validation passes.
398       def validate_parameters(parameters={})
399         parameters = self.normalize_parameters(parameters)
400         parameter_description = self.description['parameters'] || {}
401         required_variables = Hash[parameter_description.select do |k, v|
402           v['required']
403         end].keys
404         missing_variables = required_variables - parameters.keys
405         if missing_variables.size > 0
406           raise ArgumentError,
407             "Missing required parameters: #{missing_variables.join(', ')}."
408         end
409         parameters.each do |k, v|
410           if parameter_description[k]
411             pattern = parameter_description[k]['pattern']
412             if pattern
413               regexp = Regexp.new("^#{pattern}$")
414               if v !~ regexp
415                 raise ArgumentError,
416                   "Parameter '#{k}' has an invalid value: #{v}. " +
417                   "Must match: /^#{pattern}$/."
418               end
419             end
420           end
421         end
422         return nil
423       end
424
425       ##
426       # Returns a <code>String</code> representation of the method's state.
427       #
428       # @return [String] The method's state, as a <code>String</code>.
429       def inspect
430         sprintf(
431           "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.rpc_name
432         )
433       end
434     end
435   end
436 end