6617e5225756386ec265a25a6314975a36423cf2
[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 'uuidtools'
17
18 module Google
19   class APIClient
20
21     # Helper class to contain a response to an individual batched call.
22     class BatchedCallResponse
23       attr_reader :call_id
24       attr_accessor :status, :headers, :body
25
26       def initialize(call_id, status = nil, headers = nil, body = nil)
27         @call_id, @status, @headers, @body = call_id, status, headers, body
28       end
29     end
30
31     ##
32     # Wraps multiple API calls into a single over-the-wire HTTP request.
33     class BatchRequest
34
35       BATCH_BOUNDARY = "-----------RubyApiBatchRequest".freeze
36
37       attr_accessor :options
38       attr_reader :calls, :callbacks
39
40       ##
41       # Creates a new batch request.
42       #
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.
46       # @param [Proc] block
47       #   Callback for every call's response. Won't be called if a call defined
48       #   a callback of its own.
49       #
50       # @return [Google::APIClient::BatchRequest] The constructed object.
51       def initialize(options = {}, &block)
52         # Request options, ignoring method and parameters.
53         @options = options
54         # Batched calls to be made, indexed by call ID.
55         @calls = {}
56         # Callbacks per batched call, indexed by call ID.
57         @callbacks = {}
58         # Order for the call IDs, since Ruby 1.8 hashes are unordered.
59         @order = []
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.
64         @last_auto_id = 0
65         # Base ID for the batch request.
66         @base_id = nil
67       end
68
69       ##
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.
74       #
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.
78       #
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)
83         end
84         if call_id.nil?
85           call_id = new_id
86         end
87         if @calls.include?(call_id)
88           raise BatchError,
89               'A call with this ID already exists: %s' % call_id
90         end
91         @calls[call_id] = call
92         @order << call_id
93         if block_given?
94           @callbacks[call_id] = block
95         elsif @global_callback
96           @callbacks[call_id] = @global_callback
97         end
98         return self
99       end
100
101       ##
102       # Convert this batch request into an HTTP request.
103       #
104       # @return [Array<String, String, Hash, String>]
105       #   An array consisting of, in order: HTTP method, request path, request
106       #   headers and request body.
107       def to_http_request
108         return ['POST', request_uri, request_headers, request_body]
109       end
110
111       ##
112       # Processes the HTTP response to the batch request, issuing callbacks.
113       #
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]
120         parts.each do |part|
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, call_response)
125           callback.call(result) if callback
126         end
127       end
128
129       private
130
131       ##
132       # Helper method to find a header from its name, regardless of case.
133       #
134       # @param [String] name: The name of the header to find.
135       # @param [Hash] headers: The hash of headers and their values.
136       #
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
141         end
142         return header
143       end
144
145       ##
146       # Create a new call ID. Uses an auto-incrementing, conflict-avoiding ID.
147       #
148       # @return [String] the new, unique ID.
149       def new_id
150         @last_auto_id += 1
151         while @calls.include?(@last_auto_id)
152           @last_auto_id += 1
153         end
154         return @last_auto_id.to_s
155       end
156
157       ##
158       # Convert an id to a Content-ID header value.
159       #
160       # @param [String] call_id: identifier of individual call.
161       #
162       # @return [String]
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)
167         if @base_id.nil?
168           # TODO(sgomes): Use SecureRandom.uuid, drop UUIDTools when we drop 1.8
169           @base_id = UUIDTools::UUID.random_create.to_s
170         end
171
172         return '<%s+%s>' % [@base_id, Addressable::URI.encode(call_id)]
173       end
174
175       ##
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.
178       #
179       # @param [String] header: Content-ID header value.
180       #
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
186         end
187
188         base, call_id = header[1...-1].split('+')
189         return Addressable::URI.unencode(call_id)
190       end
191
192       ##
193       # Convert a single batched call into a string.
194       #
195       # @param [Google::APIClient::Reference] call: the call to serialize.
196       #
197       # @return [String] The request as a string in application/http format.
198       def serialize_call(call)
199         http_request = call.to_http_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]
207           end
208         end
209         if http_request.body
210           serialized_call << "\r\n\r\n"
211           serialized_call << http_request.body
212         end
213         return serialized_call
214       end
215
216       ##
217       # Auxiliary method to split the headers from the body in an HTTP response.
218       #
219       # @param [String] response: the response to parse.
220       #
221       # @return [Array<Hash>, String] The headers and the body, separately.
222       def split_headers_and_body(response)
223         headers = {}
224         payload = response.lstrip
225         while payload
226           line, payload = payload.split("\n", 2)
227           line.sub!(/\s+\z/, '')
228           break if line.empty?
229           match = /\A([^:]+):\s*/.match(line)
230           if match
231             headers[match[1]] = match.post_match
232           else
233             raise BatchError, 'Invalid header line in response: %s' % line
234           end
235         end
236         return headers, payload
237       end
238
239       ##
240       # Convert a single batched response into a BatchedCallResponse object.
241       #
242       # @param [Google::APIClient::Reference] response:
243       #   the request to deserialize.
244       #
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)
250
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)
255       end
256
257       ##
258       # Return the request headers for the BatchRequest's HTTP request.
259       #
260       # @return [Hash] The HTTP headers.
261       def request_headers
262         return {
263           'Content-Type' => 'multipart/mixed; boundary=%s' % BATCH_BOUNDARY
264         }
265       end
266
267       ##
268       # Return the request path for the BatchRequest's HTTP request.
269       #
270       # @return [String] The request path.
271       def request_uri
272         if @calls.nil? || @calls.empty?
273           raise BatchError, 'Cannot make an empty batch request'
274         end
275         # All APIs have the same batch path, so just get the first one.
276         return @calls.first[1].api_method.api.batch_path
277       end
278
279       ##
280       # Return the request body for the BatchRequest's HTTP request.
281       #
282       # @return [String] The request body.
283       def request_body
284         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"
290         end
291         body << "--" + BATCH_BOUNDARY + "--"
292         return body
293       end
294     end
295   end
296 end