blob: 0f4c811ce419e485589a611770ea6876bf4e0e64 [file] [log] [blame]
Jorge Canizales9409ad82015-02-18 16:19:56 -08001/*
2 *
Yang Gao5fc90292015-02-20 09:46:22 -08003 * Copyright 2015, Google Inc.
Jorge Canizales9409ad82015-02-18 16:19:56 -08004 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
15 * distribution.
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
Jorge Canizales5e0efd92015-02-17 18:23:58 -080034#import "GRPCCall.h"
35
Jorge Canizalesc2d7ecb2015-02-27 01:22:41 -080036#include <grpc/grpc.h>
Jorge Canizales59bb9d72015-06-22 19:04:15 -070037#include <grpc/support/time.h>
Jorge Canizales35f003b2015-07-17 21:14:36 -070038#import <RxLibrary/GRXConcurrentWriteable.h>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080039
murgatroid9969927d62015-04-24 13:32:48 -070040#import "private/GRPCWrappedCall.h"
Jorge Canizales5e0efd92015-02-17 18:23:58 -080041#import "private/NSData+GRPC.h"
42#import "private/NSDictionary+GRPC.h"
43#import "private/NSError+GRPC.h"
44
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070045NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
46
Jorge Canizales5e0efd92015-02-17 18:23:58 -080047@interface GRPCCall () <GRXWriteable>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080048@end
49
50// The following methods of a C gRPC call object aren't reentrant, and thus
51// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070052// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080053// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080054//
murgatroid99b5c076f2015-04-27 17:25:36 -070055// start_batch with a SEND_MESSAGE argument can only be called after the
56// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080057// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070058// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080059//
murgatroid99b5c076f2015-04-27 17:25:36 -070060// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
61// the OP_COMPLETE event for any previous read is received.This is easier to
62// enforce, as we're writing the received messages into the writeable:
63// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
64// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
65// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080066@implementation GRPCCall {
67 dispatch_queue_t _callQueue;
68
murgatroid9930b7d4e2015-04-24 10:36:43 -070069 GRPCWrappedCall *_wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080070 dispatch_once_t _callAlreadyInvoked;
71
Jorge Canizales5e0efd92015-02-17 18:23:58 -080072 // The C gRPC library has less guarantees on the ordering of events than we
73 // do. Particularly, in the face of errors, there's no ordering guarantee at
74 // all. This wrapper over our actual writeable ensures thread-safety and
75 // correct ordering.
Jorge Canizales35f003b2015-07-17 21:14:36 -070076 GRXConcurrentWriteable *_responseWriteable;
Jorge Canizales238ad782015-08-07 23:11:29 -070077
78 // The network thread wants the requestWriter to resume (when the server is ready for more input),
79 // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
80 // it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
81 // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
82 // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
83 // pause the writer immediately on writeValue:, so we need our locking to be recursive.
Jorge Canizales56047122015-07-17 12:18:08 -070084 GRXWriter *_requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -070085
Jorge Canizales6531b2b2015-07-18 00:19:14 -070086 // To create a retain cycle when a call is started, up until it finishes. See
Jorge Canizaleseb87b462015-08-08 16:16:43 -070087 // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
88 // reference to the call object if all they're interested in is the handler being executed when
89 // the response arrives.
90 GRPCCall *_retainSelf;
Jorge Canizales6531b2b2015-07-18 00:19:14 -070091
Jorge Canizales544963e2015-06-12 19:46:27 -070092 NSMutableDictionary *_requestMetadata;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070093 NSMutableDictionary *_responseMetadata;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080094}
95
96@synthesize state = _state;
97
98- (instancetype)init {
Jorge Canizalesbe808e32015-07-04 14:37:58 -070099 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800100}
101
102// Designated initializer
103- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700104 path:(NSString *)path
Jorge Canizales56047122015-07-17 12:18:08 -0700105 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700106 if (!host || !path) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700107 [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800108 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700109 if (requestWriter.state != GRXWriterStateNotStarted) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700110 [NSException raise:NSInvalidArgumentException
111 format:@"The requests writer can't be already started."];
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700112 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800113 if ((self = [super init])) {
Jorge Canizales3a5253e2015-07-31 23:48:56 -0700114 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:host path:path];
Jorge Canizales8c5318a2015-08-05 18:50:08 -0700115 if (!_wrappedCall) {
116 return nil;
117 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800118
119 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
120 _callQueue = dispatch_queue_create("org.grpc.call", NULL);
121
122 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700123
124 _requestMetadata = [NSMutableDictionary dictionary];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700125 _responseMetadata = [NSMutableDictionary dictionary];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800126 }
127 return self;
128}
129
Jorge Canizales544963e2015-06-12 19:46:27 -0700130#pragma mark Metadata
131
132- (NSMutableDictionary *)requestMetadata {
133 return _requestMetadata;
134}
135
136- (void)setRequestMetadata:(NSDictionary *)requestMetadata {
137 _requestMetadata = [NSMutableDictionary dictionaryWithDictionary:requestMetadata];
138}
139
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700140- (NSDictionary *)responseMetadata {
141 return _responseMetadata;
142}
143
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800144#pragma mark Finish
145
146- (void)finishWithError:(NSError *)errorOrNil {
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700147 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700148 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700149
150 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700151 @synchronized(_requestWriter) {
152 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700153 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700154
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800155 if (errorOrNil) {
156 [_responseWriteable cancelWithError:errorOrNil];
157 } else {
158 [_responseWriteable enqueueSuccessfulCompletion];
159 }
160}
161
162- (void)cancelCall {
163 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700164 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800165}
166
167- (void)cancel {
168 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
169 code:GRPCErrorCodeCancelled
170 userInfo:nil]];
171 [self cancelCall];
172}
173
174- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700175 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800176 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700177 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800178 });
179}
180
181#pragma mark Read messages
182
183// Only called from the call queue.
184// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700185- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700186 // TODO(jcanizales): Add error handlers for async failures
murgatroid9954e93d42015-04-27 09:29:49 -0700187 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800188}
189
190// Called initially from the network queue once response headers are received,
191// then "recursively" from the responseWriteable queue after each response from the
192// server has been written.
193// If the call is currently paused, this is a noop. Restarting the call will invoke this
194// method.
195// TODO(jcanizales): Rename to readResponseIfNotPaused.
196- (void)startNextRead {
197 if (self.state == GRXWriterStatePaused) {
198 return;
199 }
200 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700201 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700202
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800203 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700204 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
205 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700206 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800207 return;
208 }
murgatroid996cc46802015-04-28 09:35:48 -0700209 NSData *data = [NSData grpc_dataWithByteBuffer:message];
210 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800211 if (!data) {
212 // The app doesn't have enough memory to hold the server response. We
213 // don't want to throw, because the app shouldn't crash for a behavior
214 // that's on the hands of any server to have. Instead we finish and ask
215 // the server to cancel.
216 //
217 // TODO(jcanizales): No canonical code is appropriate for this situation
218 // (because it's just a client problem). Use another domain and an
219 // appropriately-documented code.
220 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
221 code:GRPCErrorCodeInternal
222 userInfo:nil]];
223 [weakSelf cancelCall];
224 return;
225 }
Jorge Canizales4c6f7782015-07-17 23:13:36 -0700226 [weakWriteable enqueueValue:data completionHandler:^{
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800227 [weakSelf startNextRead];
228 }];
229 }];
230 });
231}
232
233#pragma mark Send headers
234
murgatroid9969927d62015-04-24 13:32:48 -0700235// TODO(jcanizales): Rename to commitHeaders.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800236- (void)sendHeaders:(NSDictionary *)metadata {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700237 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700238 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc]
239 initWithMetadata:metadata ?: @{} handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800240}
241
242#pragma mark GRXWriteable implementation
243
244// Only called from the call queue. The error handler will be called from the
245// network queue if the write didn't succeed.
246- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
247
248 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700249 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700250 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800251 GRPCCall *strongSelf = weakSelf;
252 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700253 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700254 strongSelf->_requestWriter.state = GRXWriterStateStarted;
255 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800256 }
257 };
Jorge Canizales238ad782015-08-07 23:11:29 -0700258 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc] initWithMessage:message
259 handler:resumingHandler]]
260 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800261}
262
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700263- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800264 // TODO(jcanizales): Throw/assert if value isn't NSData.
265
266 // Pause the input and only resume it when the C layer notifies us that writes
267 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700268 @synchronized(_requestWriter) {
269 _requestWriter.state = GRXWriterStatePaused;
270 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800271
272 __weak GRPCCall *weakSelf = self;
273 dispatch_async(_callQueue, ^{
274 [weakSelf writeMessage:value withErrorHandler:^{
275 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
276 code:GRPCErrorCodeInternal
277 userInfo:nil]];
278 }];
279 });
280}
281
282// Only called from the call queue. The error handler will be called from the
283// network queue if the requests stream couldn't be closed successfully.
284- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700285 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
286 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800287}
288
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700289- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800290 if (errorOrNil) {
291 [self cancel];
292 } else {
293 __weak GRPCCall *weakSelf = self;
294 dispatch_async(_callQueue, ^{
295 [weakSelf finishRequestWithErrorHandler:^{
296 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
297 code:GRPCErrorCodeInternal
298 userInfo:nil]];
299 }];
300 });
301 }
302}
303
304#pragma mark Invoke
305
306// Both handlers will eventually be called, from the network queue. Writes can start immediately
307// after this.
308// The first one (metadataHandler), when the response headers are received.
309// The second one (completionHandler), whenever the RPC finishes for any reason.
murgatroid9954e93d42015-04-27 09:29:49 -0700310- (void)invokeCallWithMetadataHandler:(void(^)(NSDictionary *))metadataHandler
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700311 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700312 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700313 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
314 initWithHandler:metadataHandler]]];
315 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
316 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800317}
318
319- (void)invokeCall {
320 __weak GRPCCall *weakSelf = self;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700321 [self invokeCallWithMetadataHandler:^(NSDictionary *headers) {
322 // Response headers received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800323 GRPCCall *strongSelf = weakSelf;
324 if (strongSelf) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700325 [strongSelf->_responseMetadata addEntriesFromDictionary:headers];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800326 [strongSelf startNextRead];
327 }
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700328 } completionHandler:^(NSError *error, NSDictionary *trailers) {
329 GRPCCall *strongSelf = weakSelf;
330 if (strongSelf) {
331 [strongSelf->_responseMetadata addEntriesFromDictionary:trailers];
332
Jorge Canizalesc58a1102015-06-15 19:03:41 -0700333 if (error) {
334 NSMutableDictionary *userInfo =
335 [NSMutableDictionary dictionaryWithDictionary:error.userInfo];
336 userInfo[kGRPCStatusMetadataKey] = strongSelf->_responseMetadata;
337 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
338 }
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700339 [strongSelf finishWithError:error];
340 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800341 }];
342 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700343 @synchronized(_requestWriter) {
344 [_requestWriter startWithWriteable:self];
345 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800346}
347
348#pragma mark GRXWriter implementation
349
350- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700351 // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
352 // This makes RPCs in which the call isn't externally retained possible (as long as it is started
353 // before being autoreleased).
354 // Care is taken not to retain self strongly in any of the blocks used in this implementation, so
355 // that the life of the instance is determined by this retain cycle.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700356 _retainSelf = self;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700357
358 _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800359 [self sendHeaders:_requestMetadata];
360 [self invokeCall];
361}
362
363- (void)setState:(GRXWriterState)newState {
364 // Manual transitions are only allowed from the started or paused states.
365 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
366 return;
367 }
368
369 switch (newState) {
370 case GRXWriterStateFinished:
371 _state = newState;
372 // Per GRXWriter's contract, setting the state to Finished manually
373 // means one doesn't wish the writeable to be messaged anymore.
374 [_responseWriteable cancelSilently];
375 _responseWriteable = nil;
376 return;
377 case GRXWriterStatePaused:
378 _state = newState;
379 return;
380 case GRXWriterStateStarted:
381 if (_state == GRXWriterStatePaused) {
382 _state = newState;
383 [self startNextRead];
384 }
385 return;
386 case GRXWriterStateNotStarted:
387 return;
388 }
389}
390@end