1 # Copyright 2012 Google Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 require 'addressable/uri'
16 require 'google/api_client/reference'
23 # Helper class to contain a response to an individual batched call.
26 class BatchedCallResponse
27 # @return [String] UUID of the call
29 # @return [Fixnum] HTTP status code
31 # @return [Hash] HTTP response headers
32 attr_accessor :headers
33 # @return [String] HTTP response body
37 # Initialize the call response
39 # @param [String] call_id
40 # UUID of the original call
41 # @param [Fixnum] status
43 # @param [Hash] headers
44 # HTTP response headers
45 # @param [#read, #to_str] body
47 def initialize(call_id, status = nil, headers = nil, body = nil)
48 @call_id, @status, @headers, @body = call_id, status, headers, body
52 # Wraps multiple API calls into a single over-the-wire HTTP request.
56 # client = Google::APIClient.new
57 # urlshortener = client.discovered_api('urlshortener')
58 # batch = Google::APIClient::BatchRequest.new do |result|
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' })
65 # client.execute(batch)
67 class BatchRequest < Request
68 BATCH_BOUNDARY = "-----------RubyApiBatchRequest".freeze
71 # @return [Array<(String,Google::APIClient::Request,Proc)] List of API calls in the batch
75 # Creates a new batch request.
77 # @param [Hash] options
78 # Set of options for this request.
80 # Callback for every call's response. Won't be called if a call defined
81 # a callback of its own.
83 # @return [Google::APIClient::BatchRequest]
84 # The constructed object.
86 # @yield [Google::APIClient::Result]
87 # block to be called when result ready
88 def initialize(options = {}, &block)
90 @global_callback = block if block_given?
93 # TODO(sgomes): Use SecureRandom.uuid, drop UUIDTools when we drop 1.8
94 @base_id = UUIDTools::UUID.random_create.to_s
96 options[:uri] ||= 'https://www.googleapis.com/batch'
97 options[:http_method] ||= 'POST'
103 # Add a new call to the batch request.
104 # Each call must have its own call ID; if not provided, one will
105 # automatically be generated, avoiding collisions. If duplicate call IDs
106 # are provided, an error will be thrown.
108 # @param [Hash, Google::APIClient::Request] call
109 # the call to be added.
110 # @param [String] call_id
111 # the ID to be used for this call. Must be unique
112 # @param [Proc] block
113 # callback for this call's response.
115 # @return [Google::APIClient::BatchRequest]
116 # the BatchRequest, for chaining
118 # @yield [Google::APIClient::Result]
119 # block to be called when result ready
120 def add(call, call_id = nil, &block)
121 unless call.kind_of?(Google::APIClient::Reference)
122 call = Google::APIClient::Reference.new(call)
125 if @calls.assoc(call_id)
127 'A call with this ID already exists: %s' % call_id
129 callback = block_given? ? block : @global_callback
130 @calls << [call_id, call, callback]
135 # Processes the HTTP response to the batch request, issuing callbacks.
139 # @param [Faraday::Response] response
141 def process_http_response(response)
142 content_type = find_header('Content-Type', response.headers)
143 boundary = /.*boundary=(.+)/.match(content_type)[1]
144 parts = response.body.split(/--#{Regexp.escape(boundary)}/)
145 parts = parts[1...-1]
147 call_response = deserialize_call_response(part)
148 _, call, callback = @calls.assoc(call_response.call_id)
149 result = Google::APIClient::Result.new(call, call_response)
150 callback.call(result) if callback
152 Google::APIClient::Result.new(self, response)
156 # Return the request body for the BatchRequest's HTTP request.
163 if @calls.nil? || @calls.empty?
164 raise BatchError, 'Cannot make an empty batch request'
166 parts = @calls.map {|(call_id, call, callback)| serialize_call(call_id, call)}
167 build_multipart(parts, 'multipart/mixed', BATCH_BOUNDARY)
175 # Helper method to find a header from its name, regardless of case.
179 # @param [String] name
180 # the name of the header to find.
181 # @param [Hash] headers
182 # the hash of headers and their values.
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
194 # Create a new call ID. Uses an auto-incrementing, conflict-avoiding ID.
199 # the new, unique ID.
202 while @calls.assoc(@last_auto_id)
205 return @last_auto_id.to_s
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.
214 # @param [String] header
215 # Content-ID header value.
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
225 base, call_id = header[1...-1].split('+')
226 return Addressable::URI.unencode(call_id)
230 # Auxiliary method to split the headers from the body in an HTTP response.
234 # @param [String] response
235 # the response to parse.
237 # @return [Array<Hash>, String]
238 # the headers and the body, separately.
239 def split_headers_and_body(response)
241 payload = response.lstrip
243 line, payload = payload.split("\n", 2)
244 line.sub!(/\s+\z/, '')
246 match = /\A([^:]+):\s*/.match(line)
248 headers[match[1]] = match.post_match
250 raise BatchError, 'Invalid header line in response: %s' % line
253 return headers, payload
257 # Convert a single batched response into a BatchedCallResponse object.
261 # @param [String] call_response
262 # the request to deserialize.
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)
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)
278 # Serialize a single batched call for assembling the multipart message
282 # @param [Google::APIClient::Request] call
283 # the call to serialize.
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).request_uri} HTTP/1.1"
290 headers.each do |header, value|
291 request << "\r\n%s: %s" % [header, value]
294 # TODO - CompositeIO if body is a stream
295 request << "\r\n\r\n"
296 if body.respond_to?(:read)
302 Faraday::UploadIO.new(StringIO.new(request), 'application/http', 'ruby-api-request', 'Content-ID' => id_to_header(call_id))
306 # Convert an id to a Content-ID header value.
310 # @param [String] call_id
311 # identifier of individual call.
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)]