a8a83c4a42ae87c0e7394c42d8693550cdbb273e
[arvados.git] / lib / google / api_client / request.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 'faraday'
16 require 'faraday/request/multipart'
17 require 'multi_json'
18 require 'compat/multi_json'
19 require 'addressable/uri'
20 require 'stringio'
21 require 'google/api_client/discovery'
22 require 'google/api_client/logging'
23
24 module Google
25   class APIClient
26
27     ##
28     # Represents an API request.
29     class Request
30       include Google::APIClient::Logging
31       
32       MULTIPART_BOUNDARY = "-----------RubyApiMultipartPost".freeze
33
34       # @return [Hash] Request parameters
35       attr_reader :parameters
36       # @return [Hash] Additional HTTP headers
37       attr_reader :headers
38       # @return [Google::APIClient::Method] API method to invoke
39       attr_reader :api_method
40       # @return [Google::APIClient::UploadIO] File to upload
41       attr_accessor :media
42       # @return [#generated_authenticated_request] User credentials
43       attr_accessor :authorization
44       # @return [TrueClass,FalseClass] True if request should include credentials
45       attr_accessor :authenticated
46       # @return [#read, #to_str] Request body
47       attr_accessor :body
48
49       ##
50       # Build a request
51       #
52       # @param [Hash] options
53       # @option options [Hash, Array] :parameters
54       #   Request parameters for the API method.
55       # @option options [Google::APIClient::Method] :api_method
56       #   API method to invoke. Either :api_method or :uri must be specified
57       # @option options [TrueClass, FalseClass] :authenticated
58       #   True if request should include credentials. Implicitly true if
59       #   unspecified and :authorization present
60       # @option options [#generate_signed_request] :authorization
61       #   OAuth credentials
62       # @option options [Google::APIClient::UploadIO] :media
63       #   File to upload, if media upload request
64       # @option options [#to_json, #to_hash] :body_object
65       #   Main body of the API request. Typically hash or object that can
66       #   be serialized to JSON
67       # @option options [#read, #to_str] :body
68       #   Raw body to send in POST/PUT requests
69       # @option options [String, Addressable::URI] :uri
70       #   URI to request. Either :api_method or :uri must be specified
71       # @option options [String, Symbol] :http_method
72       #   HTTP method when requesting a URI
73       def initialize(options={})
74         @parameters = Faraday::Utils::ParamsHash.new
75         @headers = Faraday::Utils::Headers.new
76
77         self.parameters.merge!(options[:parameters]) unless options[:parameters].nil?
78         self.headers.merge!(options[:headers]) unless options[:headers].nil?
79         self.api_method = options[:api_method]
80         self.authenticated = options[:authenticated]
81         self.authorization = options[:authorization]
82
83         # These parameters are handled differently because they're not
84         # parameters to the API method, but rather to the API system.
85         self.parameters['key'] ||= options[:key] if options[:key]
86         self.parameters['userIp'] ||= options[:user_ip] if options[:user_ip]
87
88         if options[:media]
89           self.initialize_media_upload(options)
90         elsif options[:body]
91           self.body = options[:body]
92         elsif options[:body_object]
93           self.headers['Content-Type'] ||= 'application/json'
94           self.body = serialize_body(options[:body_object])
95         else
96           self.body = ''
97         end
98
99         unless self.api_method
100           self.http_method = options[:http_method] || 'GET'
101           self.uri = options[:uri]
102         end
103       end
104
105       # @!attribute [r] upload_type
106       # @return [String] protocol used for upload
107       def upload_type
108         return self.parameters['uploadType'] || self.parameters['upload_type']
109       end
110
111       # @!attribute http_method
112       # @return [Symbol] HTTP method if invoking a URI
113       def http_method
114         return @http_method ||= self.api_method.http_method.to_s.downcase.to_sym
115       end
116
117       def http_method=(new_http_method)
118         if new_http_method.kind_of?(Symbol)
119           @http_method = new_http_method.to_s.downcase.to_sym
120         elsif new_http_method.respond_to?(:to_str)
121           @http_method = new_http_method.to_s.downcase.to_sym
122         else
123           raise TypeError,
124             "Expected String or Symbol, got #{new_http_method.class}."
125         end
126       end
127
128       def api_method=(new_api_method)
129         if new_api_method.nil? || new_api_method.kind_of?(Google::APIClient::Method)
130           @api_method = new_api_method
131         else
132           raise TypeError,
133             "Expected Google::APIClient::Method, got #{new_api_method.class}."
134         end
135       end
136
137       # @!attribute uri
138       # @return [Addressable::URI] URI to send request
139       def uri
140         return @uri ||= self.api_method.generate_uri(self.parameters)
141       end
142
143       def uri=(new_uri)
144         @uri = Addressable::URI.parse(new_uri)
145         @parameters.update(@uri.query_values) unless @uri.query_values.nil?
146       end
147
148
149       # Transmits the request with the given connection
150       #
151       # @api private
152       #
153       # @param [Faraday::Connection] connection
154       #   the connection to transmit with
155       # @param [TrueValue,FalseValue] is_retry
156       #   True if request has been previous sent
157       #
158       # @return [Google::APIClient::Result]
159       #   result of API request
160       def send(connection, is_retry = false)
161         self.body.rewind if is_retry && self.body.respond_to?(:rewind)          
162         env = self.to_env(connection)
163         logger.debug  { "#{self.class} Sending API request #{env[:method]} #{env[:url].to_s} #{env[:request_headers]}" }
164         http_response = connection.app.call(env)
165         result = self.process_http_response(http_response)
166
167         logger.debug { "#{self.class} Result: #{result.status} #{result.headers}" }
168
169         # Resumamble slightly different than other upload protocols in that it requires at least
170         # 2 requests.
171         if result.status == 200 && self.upload_type == 'resumable'
172           upload = result.resumable_upload
173           unless upload.complete?
174             logger.debug { "#{self.class} Sending upload body" }
175             result = upload.send(connection)
176           end
177         end
178         return result
179       end
180
181       # Convert to an HTTP request. Returns components in order of method, URI,
182       # request headers, and body
183       #
184       # @api private
185       #
186       # @return [Array<(Symbol, Addressable::URI, Hash, [#read,#to_str])>]
187       def to_http_request
188         request = (
189           if self.api_method
190             self.api_method.generate_request(self.parameters, self.body, self.headers)
191           elsif self.uri
192             unless self.parameters.empty?
193               self.uri.query = Addressable::URI.form_encode(self.parameters)
194             end
195             [self.http_method, self.uri.to_s, self.headers, self.body]
196           end)
197         return request
198       end
199
200       ##
201       # Hashified verison of the API request
202       #
203       # @return [Hash]
204       def to_hash
205         options = {}
206         if self.api_method
207           options[:api_method] = self.api_method
208           options[:parameters] = self.parameters
209         else
210           options[:http_method] = self.http_method
211           options[:uri] = self.uri
212         end
213         options[:headers] = self.headers
214         options[:body] = self.body
215         options[:media] = self.media
216         unless self.authorization.nil?
217           options[:authorization] = self.authorization
218         end
219         return options
220       end
221
222       ##
223       # Prepares the request for execution, building a hash of parts
224       # suitable for sending to Faraday::Connection.
225       #
226       # @api private
227       #
228       # @param [Faraday::Connection] connection
229       #   Connection for building the request
230       #
231       # @return [Hash]
232       #   Encoded request
233       def to_env(connection)
234         method, uri, headers, body = self.to_http_request
235         http_request = connection.build_request(method) do |req|
236           req.url(uri.to_s)
237           req.headers.update(headers)
238           req.body = body
239         end
240
241         if self.authorization.respond_to?(:generate_authenticated_request)
242           http_request = self.authorization.generate_authenticated_request(
243             :request => http_request,
244             :connection => connection
245           )
246         end
247
248         request_env = http_request.to_env(connection)
249       end
250
251       ##
252       # Convert HTTP response to an API Result
253       #
254       # @api private
255       #
256       # @param [Faraday::Response] response
257       #   HTTP response
258       #
259       # @return [Google::APIClient::Result]
260       #   Processed API response
261       def process_http_response(response)
262         Result.new(self, response)
263       end
264
265       protected
266
267       ##
268       # Adjust headers & body for media uploads
269       #
270       # @api private
271       #
272       # @param [Hash] options
273       # @option options [Hash, Array] :parameters
274       #   Request parameters for the API method.
275       # @option options [Google::APIClient::UploadIO] :media
276       #   File to upload, if media upload request
277       # @option options [#to_json, #to_hash] :body_object
278       #   Main body of the API request. Typically hash or object that can
279       #   be serialized to JSON
280       # @option options [#read, #to_str] :body
281       #   Raw body to send in POST/PUT requests
282       def initialize_media_upload(options)
283         self.media = options[:media]
284         case self.upload_type
285         when "media"
286           if options[:body] || options[:body_object]
287             raise ArgumentError, "Can not specify body & body object for simple uploads"
288           end
289           self.headers['Content-Type'] ||= self.media.content_type
290           self.headers['Content-Length'] ||= self.media.length.to_s
291           self.body = self.media
292         when "multipart"
293           unless options[:body_object]
294             raise ArgumentError, "Multipart requested but no body object"
295           end
296           metadata = StringIO.new(serialize_body(options[:body_object]))
297           build_multipart([Faraday::UploadIO.new(metadata, 'application/json', 'file.json'), self.media])
298         when "resumable"
299           file_length = self.media.length
300           self.headers['X-Upload-Content-Type'] = self.media.content_type
301           self.headers['X-Upload-Content-Length'] = file_length.to_s
302           if options[:body_object]
303             self.headers['Content-Type'] ||= 'application/json'
304             self.body = serialize_body(options[:body_object])
305           else
306             self.body = ''
307           end
308         end
309       end
310
311       ##
312       # Assemble a multipart message from a set of parts
313       #
314       # @api private
315       #
316       # @param [Array<[#read,#to_str]>] parts
317       #   Array of parts to encode.
318       # @param [String] mime_type
319       #   MIME type of the message
320       # @param [String] boundary
321       #   Boundary for separating each part of the message
322       def build_multipart(parts, mime_type = 'multipart/related', boundary = MULTIPART_BOUNDARY)
323         env = Faraday::Env.new
324         env.request = Faraday::RequestOptions.new
325         env.request.boundary = boundary
326         env.request_headers = {'Content-Type' => "#{mime_type};boundary=#{boundary}"}
327         multipart = Faraday::Request::Multipart.new
328         self.body = multipart.create_multipart(env, parts.map {|part| [nil, part]})
329         self.headers.update(env[:request_headers])
330       end
331
332       ##
333       # Serialize body object to JSON
334       #
335       # @api private
336       #
337       # @param [#to_json,#to_hash] body
338       #   object to serialize
339       #
340       # @return [String]
341       #   JSON
342       def serialize_body(body)
343         return body.to_json if body.respond_to?(:to_json)
344         return MultiJson.dump(body.to_hash) if body.respond_to?(:to_hash)
345         raise TypeError, 'Could not convert body object to JSON.' +
346                          'Must respond to :to_json or :to_hash.'
347       end
348
349     end
350   end
351 end