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