Doc improvements
[arvados.git] / lib / google / api_client / batch.rb
1 # Copyright 2012 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 'addressable/uri'
16 require 'google/api_client/reference'
17 require 'uuidtools'
18
19 module Google
20   class APIClient
21
22     ##
23     # Helper class to contain a response to an individual batched call.
24     #
25     # @api private
26     class BatchedCallResponse
27       # @return [String] UUID of the call
28       attr_reader :call_id
29       # @return [Fixnum] HTTP status code
30       attr_accessor :status
31       # @return [Hash] HTTP response headers
32       attr_accessor :headers
33       # @return [String] HTTP response body
34       attr_accessor :body
35
36       ##
37       # Initialize the call response
38       # 
39       # @param [String] call_id
40       #   UUID of the original call
41       # @param [Fixnum] status
42       #   HTTP status
43       # @param [Hash] headers
44       #   HTTP response headers
45       # @param [#read, #to_str] body
46       #   Response body
47       def initialize(call_id, status = nil, headers = nil, body = nil)
48         @call_id, @status, @headers, @body = call_id, status, headers, body
49       end
50     end
51     
52     # Wraps multiple API calls into a single over-the-wire HTTP request.
53     #
54     # @example
55     #
56     #     client = Google::APIClient.new
57     #     urlshortener = client.discovered_api('urlshortener')
58     #     batch = Google::APIClient::BatchRequest.new do |result|
59     #        puts result.data
60     #     end
61     # 
62     #     batch.add(:api_method=>urlshortener.url.insert, :body_object => { 'longUrl' => 'http://example.com/foo' })
63     #     batch.add(:api_method=>urlshortener.url.insert, :body_object => { 'longUrl' => 'http://example.com/bar' })
64     #
65     #     client.execute(batch)
66     #
67     
68     class BatchRequest < Request
69       BATCH_BOUNDARY = "-----------RubyApiBatchRequest".freeze
70
71       # @api private
72       # @return [Array<(String,Google::APIClient::Request,Proc)] List of API calls in the batch
73       attr_reader :calls
74
75       ##
76       # Creates a new batch request.
77       #
78       # @param [Hash] options
79       #   Set of options for this request.
80       # @param [Proc] block
81       #   Callback for every call's response. Won't be called if a call defined
82       #   a callback of its own.
83       #
84       # @return [Google::APIClient::BatchRequest] 
85       #   The constructed object.
86       #
87       # @yield [Google::APIClient::Result]
88       #   block to be called when result ready
89       def initialize(options = {}, &block)
90         @calls = []
91         @global_callback = block if block_given?
92         @last_auto_id = 0
93         
94         # TODO(sgomes): Use SecureRandom.uuid, drop UUIDTools when we drop 1.8
95         @base_id = UUIDTools::UUID.random_create.to_s
96
97         options[:uri] ||= 'https://www.googleapis.com/batch'
98         options[:http_method] ||= 'POST'
99
100         super options
101       end
102
103       ##
104       # Add a new call to the batch request.
105       # Each call must have its own call ID; if not provided, one will
106       # automatically be generated, avoiding collisions. If duplicate call IDs
107       # are provided, an error will be thrown.
108       #
109       # @param [Hash, Google::APIClient::Request] call 
110       #   the call to be added.
111       # @param [String] call_id
112       #   the ID to be used for this call. Must be unique
113       # @param [Proc] block
114       #   callback for this call's response.
115       #
116       # @return [Google::APIClient::BatchRequest]
117       #   the BatchRequest, for chaining
118       #
119       # @yield [Google::APIClient::Result]
120       #   block to be called when result ready
121       def add(call, call_id = nil, &block)
122         unless call.kind_of?(Google::APIClient::Reference)
123           call = Google::APIClient::Reference.new(call)
124         end
125         call_id ||= new_id
126         if @calls.assoc(call_id)
127           raise BatchError,
128               'A call with this ID already exists: %s' % call_id
129         end
130         callback = block_given? ? block : @global_callback
131         @calls << [call_id, call, callback]        
132         return self
133       end
134
135       ##
136       # Processes the HTTP response to the batch request, issuing callbacks.
137       #
138       # @api private
139       #
140       # @param [Faraday::Response] response
141       #   the HTTP response.
142       def process_http_response(response)
143         content_type = find_header('Content-Type', response.headers)
144         boundary = /.*boundary=(.+)/.match(content_type)[1]
145         parts = response.body.split(/--#{Regexp.escape(boundary)}/)
146         parts = parts[1...-1]
147         parts.each do |part|
148           call_response = deserialize_call_response(part)
149           _, call, callback = @calls.assoc(call_response.call_id)
150           result = Google::APIClient::Result.new(call, call_response)
151           callback.call(result) if callback
152         end
153         Google::APIClient::Result.new(self, response)
154       end
155
156       ##
157       # Return the request body for the BatchRequest's HTTP request.
158       #
159       # @api private
160       #
161       # @return [String]
162       #   the request body.
163       def to_http_request
164         if @calls.nil? || @calls.empty?
165           raise BatchError, 'Cannot make an empty batch request'
166         end
167         parts = @calls.map {|(call_id, call, callback)| serialize_call(call_id, call)}
168         build_multipart(parts, 'multipart/mixed', BATCH_BOUNDARY)
169         super
170       end
171       
172       
173       protected
174
175       ##
176       # Helper method to find a header from its name, regardless of case.
177       #
178       # @api private
179       #
180       # @param [String] name
181       #   the name of the header to find.
182       # @param [Hash] headers
183       #   the hash of headers and their values.
184       #
185       # @return [String] 
186       #   the value of the desired header.
187       def find_header(name, headers)
188         _, header = headers.detect do |h, v|
189           h.downcase == name.downcase
190         end
191         return header
192       end
193
194       ##
195       # Create a new call ID. Uses an auto-incrementing, conflict-avoiding ID.
196       #
197       # @api private
198       #
199       # @return [String] 
200       #  the new, unique ID.
201       def new_id
202         @last_auto_id += 1
203         while @calls.assoc(@last_auto_id)
204           @last_auto_id += 1
205         end
206         return @last_auto_id.to_s
207       end
208
209       ##
210       # Convert a Content-ID header value to an id. Presumes the Content-ID
211       # header conforms to the format that id_to_header() returns.
212       #
213       # @api private
214       #
215       # @param [String] header
216       #   Content-ID header value.
217       #
218       # @return [String] 
219       #   The extracted ID value.
220       def header_to_id(header)
221         if !header.start_with?('<') || !header.end_with?('>') ||
222             !header.include?('+')
223           raise BatchError, 'Invalid value for Content-ID: "%s"' % header
224         end
225
226         base, call_id = header[1...-1].split('+')
227         return Addressable::URI.unencode(call_id)
228       end
229
230       ##
231       # Auxiliary method to split the headers from the body in an HTTP response.
232       #
233       # @api private
234       #
235       # @param [String] response
236       #   the response to parse.
237       #
238       # @return [Array<Hash>, String] 
239       #   the headers and the body, separately.
240       def split_headers_and_body(response)
241         headers = {}
242         payload = response.lstrip
243         while payload
244           line, payload = payload.split("\n", 2)
245           line.sub!(/\s+\z/, '')
246           break if line.empty?
247           match = /\A([^:]+):\s*/.match(line)
248           if match
249             headers[match[1]] = match.post_match
250           else
251             raise BatchError, 'Invalid header line in response: %s' % line
252           end
253         end
254         return headers, payload
255       end
256
257       ##
258       # Convert a single batched response into a BatchedCallResponse object.
259       #
260       # @api private
261       #
262       # @param [String] call_response
263       #   the request to deserialize.
264       #
265       # @return [Google::APIClient::BatchedCallResponse] 
266       #   the parsed and converted response.
267       def deserialize_call_response(call_response)
268         outer_headers, outer_body = split_headers_and_body(call_response)
269         status_line, payload = outer_body.split("\n", 2)
270         protocol, status, reason = status_line.split(' ', 3)
271
272         headers, body = split_headers_and_body(payload)
273         content_id = find_header('Content-ID', outer_headers)
274         call_id = header_to_id(content_id)
275         return BatchedCallResponse.new(call_id, status.to_i, headers, body)
276       end
277
278       ##
279       # Serialize a single batched call for assembling the multipart message
280       #
281       # @api private
282       #
283       # @param [Google::APIClient::Request] call
284       #   the call to serialize.
285       #
286       # @return [Faraday::UploadIO] 
287       #   the serialized request
288       def serialize_call(call_id, call)
289         method, uri, headers, body = call.to_http_request
290         request = "#{method.to_s.upcase} #{Addressable::URI.parse(uri).path} HTTP/1.1"
291         headers.each do |header, value|
292           request << "\r\n%s: %s" % [header, value]
293         end
294         if body
295           # TODO - CompositeIO if body is a stream 
296           request << "\r\n\r\n"
297           if body.respond_to?(:read)
298             request << body.read
299           else
300             request << body.to_s
301           end
302         end
303         Faraday::UploadIO.new(StringIO.new(request), 'application/http', 'ruby-api-request', 'Content-ID' => id_to_header(call_id))
304       end
305       
306       ##
307       # Convert an id to a Content-ID header value.
308       #
309       # @api private
310       #
311       # @param [String] call_id
312       #   identifier of individual call.
313       #
314       # @return [String]
315       #   A Content-ID header with the call_id encoded into it. A UUID is
316       #   prepended to the value because Content-ID headers are supposed to be
317       #   universally unique.
318       def id_to_header(call_id)
319         return '<%s+%s>' % [@base_id, Addressable::URI.encode(call_id)]
320       end
321       
322     end
323   end
324 end