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'
21 # Helper class to contain a response to an individual batched call.
22 class BatchedCallResponse
24 attr_accessor :status, :headers, :body
26 def initialize(call_id, status = nil, headers = nil, body = nil)
27 @call_id, @status, @headers, @body = call_id, status, headers, body
32 # Wraps multiple API calls into a single over-the-wire HTTP request.
35 BATCH_BOUNDARY = "-----------RubyApiBatchRequest".freeze
37 attr_accessor :options
38 attr_reader :calls, :callbacks
41 # Creates a new batch request.
43 # @param [Hash] options
44 # Set of options for this request, the only important one being
45 # :connection, which specifies an HTTP connection to use.
47 # Callback for every call's response. Won't be called if a call defined
48 # a callback of its own.
50 # @return [Google::APIClient::BatchRequest] The constructed object.
51 def initialize(options = {}, &block)
52 # Request options, ignoring method and parameters.
54 # Batched calls to be made, indexed by call ID.
56 # Callbacks per batched call, indexed by call ID.
58 # Order for the call IDs, since Ruby 1.8 hashes are unordered.
60 # Global callback to be used for every call. If a specific callback
61 # has been defined for a request, this won't be called.
62 @global_callback = block if block_given?
63 # The last auto generated ID.
65 # Base ID for the batch request.
70 # Add a new call to the batch request.
71 # Each call must have its own call ID; if not provided, one will
72 # automatically be generated, avoiding collisions. If duplicate call IDs
73 # are provided, an error will be thrown.
75 # @param [Hash, Google::APIClient::Reference] call: the call to be added.
76 # @param [String] call_id: the ID to be used for this call. Must be unique
77 # @param [Proc] block: callback for this call's response.
79 # @return [Google::APIClient::BatchRequest] The BatchRequest, for chaining
80 def add(call, call_id = nil, &block)
81 unless call.kind_of?(Google::APIClient::Reference)
82 call = Google::APIClient::Reference.new(call)
87 if @calls.include?(call_id)
89 'A call with this ID already exists: %s' % call_id
91 @calls[call_id] = call
94 @callbacks[call_id] = block
95 elsif @global_callback
96 @callbacks[call_id] = @global_callback
102 # Convert this batch request into an HTTP request.
104 # @return [Array<String, String, Hash, String>]
105 # An array consisting of, in order: HTTP method, request path, request
106 # headers and request body.
108 return ['POST', request_uri, request_headers, request_body]
112 # Processes the HTTP response to the batch request, issuing callbacks.
114 # @param [Faraday::Response] response: the HTTP response.
115 def process_response(response)
116 content_type = find_header('Content-Type', response.headers)
117 boundary = /.*boundary=(.+)/.match(content_type)[1]
118 parts = response.body.split(/--#{Regexp.escape(boundary)}/)
119 parts = parts[1...-1]
121 call_response = deserialize_call_response(part)
122 callback = @callbacks[call_response.call_id]
123 call = @calls[call_response.call_id]
124 result = Google::APIClient::Result.new(call, nil, call_response)
125 callback.call(result) if callback
132 # Helper method to find a header from its name, regardless of case.
134 # @param [String] name: The name of the header to find.
135 # @param [Hash] headers: The hash of headers and their values.
137 # @return [String] The value of the desired header.
138 def find_header(name, headers)
139 _, header = headers.detect do |h, v|
140 h.downcase == name.downcase
146 # Create a new call ID. Uses an auto-incrementing, conflict-avoiding ID.
148 # @return [String] the new, unique ID.
151 while @calls.include?(@last_auto_id)
154 return @last_auto_id.to_s
158 # Convert an id to a Content-ID header value.
160 # @param [String] call_id: identifier of individual call.
163 # A Content-ID header with the call_id encoded into it. A UUID is
164 # prepended to the value because Content-ID headers are supposed to be
165 # universally unique.
166 def id_to_header(call_id)
168 # TODO(sgomes): Use SecureRandom.uuid, drop UUIDTools when we drop 1.8
169 @base_id = UUIDTools::UUID.random_create.to_s
172 return '<%s+%s>' % [@base_id, Addressable::URI.encode(call_id)]
176 # Convert a Content-ID header value to an id. Presumes the Content-ID
177 # header conforms to the format that id_to_header() returns.
179 # @param [String] header: Content-ID header value.
181 # @return [String] The extracted ID value.
182 def header_to_id(header)
183 if !header.start_with?('<') || !header.end_with?('>') ||
184 !header.include?('+')
185 raise BatchError, 'Invalid value for Content-ID: "%s"' % header
188 base, call_id = header[1...-1].split('+')
189 return Addressable::URI.unencode(call_id)
193 # Convert a single batched call into a string.
195 # @param [Google::APIClient::Reference] call: the call to serialize.
197 # @return [String] The request as a string in application/http format.
198 def serialize_call(call)
199 http_request = call.to_request
200 method = http_request.method.to_s.upcase
201 path = http_request.path.to_s
202 status_line = method + " " + path + " HTTP/1.1"
203 serialized_call = status_line
204 if http_request.headers
205 http_request.headers.each do |header, value|
206 serialized_call << "\r\n%s: %s" % [header, value]
210 serialized_call << "\r\n\r\n"
211 serialized_call << http_request.body
213 return serialized_call
217 # Auxiliary method to split the headers from the body in an HTTP response.
219 # @param [String] response: the response to parse.
221 # @return [Array<Hash>, String] The headers and the body, separately.
222 def split_headers_and_body(response)
224 payload = response.lstrip
226 line, payload = payload.split("\n", 2)
227 line.sub!(/\s+\z/, '')
229 match = /\A([^:]+):\s*/.match(line)
231 headers[match[1]] = match.post_match
233 raise BatchError, 'Invalid header line in response: %s' % line
236 return headers, payload
240 # Convert a single batched response into a BatchedCallResponse object.
242 # @param [Google::APIClient::Reference] response:
243 # the request to deserialize.
245 # @return [BatchedCallResponse] The parsed and converted response.
246 def deserialize_call_response(call_response)
247 outer_headers, outer_body = split_headers_and_body(call_response)
248 status_line, payload = outer_body.split("\n", 2)
249 protocol, status, reason = status_line.split(' ', 3)
251 headers, body = split_headers_and_body(payload)
252 content_id = find_header('Content-ID', outer_headers)
253 call_id = header_to_id(content_id)
254 return BatchedCallResponse.new(call_id, status.to_i, headers, body)
258 # Return the request headers for the BatchRequest's HTTP request.
260 # @return [Hash] The HTTP headers.
263 'Content-Type' => 'multipart/mixed; boundary=%s' % BATCH_BOUNDARY
268 # Return the request path for the BatchRequest's HTTP request.
270 # @return [String] The request path.
272 if @calls.nil? || @calls.empty?
273 raise BatchError, 'Cannot make an empty batch request'
275 # All APIs have the same batch path, so just get the first one.
276 return @calls.first[1].api_method.api.batch_path
280 # Return the request body for the BatchRequest's HTTP request.
282 # @return [String] The request body.
285 @order.each do |call_id|
286 body << "--" + BATCH_BOUNDARY + "\r\n"
287 body << "Content-Type: application/http\r\n"
288 body << "Content-ID: %s\r\n\r\n" % id_to_header(call_id)
289 body << serialize_call(@calls[call_id]) + "\r\n\r\n"
291 body << "--" + BATCH_BOUNDARY + "--"