More documentation cleanup
[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('urlshortner')
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       end
154
155       ##
156       # Return the request body for the BatchRequest's HTTP request.
157       #
158       # @api private
159       #
160       # @return [String]
161       #   the request body.
162       def to_http_request
163         if @calls.nil? || @calls.empty?
164           raise BatchError, 'Cannot make an empty batch request'
165         end
166         parts = @calls.map {|(call_id, call, callback)| serialize_call(call_id, call)}
167         build_multipart(parts, 'multipart/mixed', BATCH_BOUNDARY)
168         super
169       end
170       
171       
172       protected
173
174       ##
175       # Helper method to find a header from its name, regardless of case.
176       #
177       # @api private
178       #
179       # @param [String] name
180       #   the name of the header to find.
181       # @param [Hash] headers
182       #   the hash of headers and their values.
183       #
184       # @return [String] 
185       #   the value of the desired header.
186       def find_header(name, headers)
187         _, header = headers.detect do |h, v|
188           h.downcase == name.downcase
189         end
190         return header
191       end
192
193       ##
194       # Create a new call ID. Uses an auto-incrementing, conflict-avoiding ID.
195       #
196       # @api private
197       #
198       # @return [String] 
199       #  the new, unique ID.
200       def new_id
201         @last_auto_id += 1
202         while @calls.assoc(@last_auto_id)
203           @last_auto_id += 1
204         end
205         return @last_auto_id.to_s
206       end
207
208       ##
209       # Convert a Content-ID header value to an id. Presumes the Content-ID
210       # header conforms to the format that id_to_header() returns.
211       #
212       # @api private
213       #
214       # @param [String] header
215       #   Content-ID header value.
216       #
217       # @return [String] 
218       #   The extracted ID value.
219       def header_to_id(header)
220         if !header.start_with?('<') || !header.end_with?('>') ||
221             !header.include?('+')
222           raise BatchError, 'Invalid value for Content-ID: "%s"' % header
223         end
224
225         base, call_id = header[1...-1].split('+')
226         return Addressable::URI.unencode(call_id)
227       end
228
229       ##
230       # Auxiliary method to split the headers from the body in an HTTP response.
231       #
232       # @api private
233       #
234       # @param [String] response
235       #   the response to parse.
236       #
237       # @return [Array<Hash>, String] 
238       #   the headers and the body, separately.
239       def split_headers_and_body(response)
240         headers = {}
241         payload = response.lstrip
242         while payload
243           line, payload = payload.split("\n", 2)
244           line.sub!(/\s+\z/, '')
245           break if line.empty?
246           match = /\A([^:]+):\s*/.match(line)
247           if match
248             headers[match[1]] = match.post_match
249           else
250             raise BatchError, 'Invalid header line in response: %s' % line
251           end
252         end
253         return headers, payload
254       end
255
256       ##
257       # Convert a single batched response into a BatchedCallResponse object.
258       #
259       # @api private
260       #
261       # @param [String] call_response
262       #   the request to deserialize.
263       #
264       # @return [Google::APIClient::BatchedCallResponse] 
265       #   the parsed and converted response.
266       def deserialize_call_response(call_response)
267         outer_headers, outer_body = split_headers_and_body(call_response)
268         status_line, payload = outer_body.split("\n", 2)
269         protocol, status, reason = status_line.split(' ', 3)
270
271         headers, body = split_headers_and_body(payload)
272         content_id = find_header('Content-ID', outer_headers)
273         call_id = header_to_id(content_id)
274         return BatchedCallResponse.new(call_id, status.to_i, headers, body)
275       end
276
277       ##
278       # Serialize a single batched call for assembling the multipart message
279       #
280       # @api private
281       #
282       # @param [Google::APIClient::Request] call
283       #   the call to serialize.
284       #
285       # @return [Faraday::UploadIO] 
286       #   the serialized request
287       def serialize_call(call_id, call)
288         method, uri, headers, body = call.to_http_request
289         request = "#{method.to_s.upcase} #{Addressable::URI.parse(uri).path} HTTP/1.1"
290         headers.each do |header, value|
291           request << "\r\n%s: %s" % [header, value]
292         end
293         if body
294           # TODO - CompositeIO if body is a stream 
295           request << "\r\n\r\n"
296           if body.respond_to?(:read)
297             request << body.read
298           else
299             request << body.to_s
300           end
301         end
302         Faraday::UploadIO.new(StringIO.new(request), 'application/http', 'ruby-api-request', 'Content-ID' => id_to_header(call_id))
303       end
304       
305       ##
306       # Convert an id to a Content-ID header value.
307       #
308       # @api private
309       #
310       # @param [String] call_id
311       #   identifier of individual call.
312       #
313       # @return [String]
314       #   A Content-ID header with the call_id encoded into it. A UUID is
315       #   prepended to the value because Content-ID headers are supposed to be
316       #   universally unique.
317       def id_to_header(call_id)
318         return '<%s+%s>' % [@base_id, Addressable::URI.encode(call_id)]
319       end
320       
321     end
322   end
323 end