blob: ff474650122deade3b14d902b1bb2c018b55cab3 [file] [log] [blame]
Jorge Canizales9409ad82015-02-18 16:19:56 -08001/*
2 *
Craig Tiller6169d5f2016-03-31 07:46:18 -07003 * 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>
Muxi Yan61274ca2016-10-28 12:09:59 -070038#import <RxLibrary/GRXConcurrentWriteable.h>
Muxi Yana40ccd82016-11-05 21:39:44 -070039#import <RxLibrary/GRXImmediateSingleWriter.h>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080040
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070041#import "private/GRPCConnectivityMonitor.h"
42#import "private/GRPCHost.h"
Jorge Canizales2f101272015-09-02 21:55:37 -070043#import "private/GRPCRequestHeaders.h"
murgatroid9969927d62015-04-24 13:32:48 -070044#import "private/GRPCWrappedCall.h"
Jorge Canizales5e0efd92015-02-17 18:23:58 -080045#import "private/NSData+GRPC.h"
46#import "private/NSDictionary+GRPC.h"
47#import "private/NSError+GRPC.h"
48
Muxi Yan016d1082017-03-07 18:26:42 -080049// At most 6 ops can be in an op batch for a client: SEND_INITIAL_METADATA,
50// SEND_MESSAGE, SEND_CLOSE_FROM_CLIENT, RECV_INITIAL_METADATA, RECV_MESSAGE,
51// and RECV_STATUS_ON_CLIENT.
52NSInteger kMaxClientBatch = 6;
53
Muxi Yan61274ca2016-10-28 12:09:59 -070054NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey";
55NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey";
Muxi Yan22f79732016-09-30 14:24:56 -070056static NSMutableDictionary *callFlags;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070057
Muxi Yan61274ca2016-10-28 12:09:59 -070058@interface GRPCCall () <GRXWriteable>
Jorge Canizales0b34c892015-08-12 20:19:20 -070059// Make them read-write.
60@property(atomic, strong) NSDictionary *responseHeaders;
61@property(atomic, strong) NSDictionary *responseTrailers;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080062@end
63
64// The following methods of a C gRPC call object aren't reentrant, and thus
65// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070066// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080067// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080068//
murgatroid99b5c076f2015-04-27 17:25:36 -070069// start_batch with a SEND_MESSAGE argument can only be called after the
70// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080071// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070072// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080073//
murgatroid99b5c076f2015-04-27 17:25:36 -070074// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
75// the OP_COMPLETE event for any previous read is received.This is easier to
76// enforce, as we're writing the received messages into the writeable:
77// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
78// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
79// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080080@implementation GRPCCall {
81 dispatch_queue_t _callQueue;
82
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070083 NSString *_host;
84 NSString *_path;
murgatroid9930b7d4e2015-04-24 10:36:43 -070085 GRPCWrappedCall *_wrappedCall;
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070086 GRPCConnectivityMonitor *_connectivityMonitor;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080087
Jorge Canizales5e0efd92015-02-17 18:23:58 -080088 // The C gRPC library has less guarantees on the ordering of events than we
89 // do. Particularly, in the face of errors, there's no ordering guarantee at
90 // all. This wrapper over our actual writeable ensures thread-safety and
91 // correct ordering.
Jorge Canizales35f003b2015-07-17 21:14:36 -070092 GRXConcurrentWriteable *_responseWriteable;
Jorge Canizales238ad782015-08-07 23:11:29 -070093
Muxi Yan61274ca2016-10-28 12:09:59 -070094 // The network thread wants the requestWriter to resume (when the server is ready for more input),
95 // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
96 // it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
97 // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
98 // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
99 // pause the writer immediately on writeValue:, so we need our locking to be recursive.
Jorge Canizales56047122015-07-17 12:18:08 -0700100 GRXWriter *_requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700101
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700102 // To create a retain cycle when a call is started, up until it finishes. See
Muxi Yan61274ca2016-10-28 12:09:59 -0700103 // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
104 // reference to the call object if all they're interested in is the handler being executed when
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700105 // the response arrives.
106 GRPCCall *_retainSelf;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700107
murgatroid9984fa5312015-08-28 10:55:55 -0700108 GRPCRequestHeaders *_requestHeaders;
Muxi Yana40ccd82016-11-05 21:39:44 -0700109
110 BOOL _unaryCall;
111
112 NSMutableArray *_unaryOpBatch;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800113}
114
115@synthesize state = _state;
116
Muxi Yan61274ca2016-10-28 12:09:59 -0700117// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize.
Jorge Canizales7603d642016-08-24 18:23:24 -0700118+ (void)load {
119 grpc_init();
Muxi Yan22f79732016-09-30 14:24:56 -0700120 callFlags = [NSMutableDictionary dictionary];
121}
122
Muxi Yan61274ca2016-10-28 12:09:59 -0700123+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path {
Muxi Yan6c0b9602016-10-02 14:32:06 -0700124 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
125 switch (callSafety) {
126 case GRPCCallSafetyDefault:
Muxi Yan22f79732016-09-30 14:24:56 -0700127 callFlags[hostAndPath] = @0;
128 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700129 case GRPCCallSafetyIdempotentRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700130 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
131 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700132 case GRPCCallSafetyCacheableRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700133 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
134 break;
135 default:
136 break;
137 }
138}
139
Muxi Yan6c0b9602016-10-02 14:32:06 -0700140+ (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path {
141 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
142 return [callFlags[hostAndPath] intValue];
Jorge Canizales7603d642016-08-24 18:23:24 -0700143}
144
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800145- (instancetype)init {
Muxi Yan22f79732016-09-30 14:24:56 -0700146 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800147}
148
149// Designated initializer
150- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700151 path:(NSString *)path
Muxi Yan22f79732016-09-30 14:24:56 -0700152 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700153 if (!host || !path) {
Muxi Yan61274ca2016-10-28 12:09:59 -0700154 [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800155 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700156 if (requestWriter.state != GRXWriterStateNotStarted) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700157 [NSException raise:NSInvalidArgumentException
158 format:@"The requests writer can't be already started."];
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700159 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800160 if ((self = [super init])) {
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700161 _host = [host copy];
162 _path = [path copy];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800163
164 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700165 _callQueue = dispatch_queue_create("io.grpc.call", NULL);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800166
167 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700168
murgatroid9984fa5312015-08-28 10:55:55 -0700169 _requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
Muxi Yana40ccd82016-11-05 21:39:44 -0700170
171 if ([requestWriter isKindOfClass:[GRXImmediateSingleWriter class]]) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800172 _unaryCall = YES;
Muxi Yan016d1082017-03-07 18:26:42 -0800173 _unaryOpBatch = [NSMutableArray arrayWithCapacity:kMaxClientBatch];
Muxi Yana40ccd82016-11-05 21:39:44 -0700174 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800175 }
176 return self;
177}
178
179#pragma mark Finish
180
181- (void)finishWithError:(NSError *)errorOrNil {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700182 @synchronized(self) {
Muxi Yana40ccd82016-11-05 21:39:44 -0700183 if (_state == GRXWriterStateFinished) {
184 return;
185 }
Jorge Canizales0803bb02016-04-30 10:40:18 -0700186 _state = GRXWriterStateFinished;
187 }
188
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700189 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700190 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700191
192 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700193 @synchronized(_requestWriter) {
194 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700195 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700196
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800197 if (errorOrNil) {
198 [_responseWriteable cancelWithError:errorOrNil];
199 } else {
200 [_responseWriteable enqueueSuccessfulCompletion];
201 }
202}
203
204- (void)cancelCall {
205 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700206 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800207}
208
209- (void)cancel {
210 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
211 code:GRPCErrorCodeCancelled
Muxi Yan61274ca2016-10-28 12:09:59 -0700212 userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800213 [self cancelCall];
214}
215
216- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700217 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800218 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700219 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800220 });
221}
222
223#pragma mark Read messages
224
225// Only called from the call queue.
226// The handler will be called from the network queue.
Muxi Yan61274ca2016-10-28 12:09:59 -0700227- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700228 // TODO(jcanizales): Add error handlers for async failures
Muxi Yan61274ca2016-10-28 12:09:59 -0700229 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800230}
231
232// Called initially from the network queue once response headers are received,
Muxi Yan61274ca2016-10-28 12:09:59 -0700233// then "recursively" from the responseWriteable queue after each response from the
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800234// server has been written.
Muxi Yan61274ca2016-10-28 12:09:59 -0700235// If the call is currently paused, this is a noop. Restarting the call will invoke this
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800236// method.
237// TODO(jcanizales): Rename to readResponseIfNotPaused.
238- (void)startNextRead {
239 if (self.state == GRXWriterStatePaused) {
240 return;
241 }
242 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700243 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700244
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800245 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700246 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
247 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700248 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800249 return;
250 }
murgatroid996cc46802015-04-28 09:35:48 -0700251 NSData *data = [NSData grpc_dataWithByteBuffer:message];
252 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800253 if (!data) {
254 // The app doesn't have enough memory to hold the server response. We
255 // don't want to throw, because the app shouldn't crash for a behavior
256 // that's on the hands of any server to have. Instead we finish and ask
257 // the server to cancel.
Muxi Yan61274ca2016-10-28 12:09:59 -0700258 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
259 code:GRPCErrorCodeResourceExhausted
260 userInfo:@{NSLocalizedDescriptionKey: @"Client does not have enough memory to hold the server response."}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800261 [weakSelf cancelCall];
262 return;
263 }
Muxi Yan61274ca2016-10-28 12:09:59 -0700264 [weakWriteable enqueueValue:data completionHandler:^{
265 [weakSelf startNextRead];
266 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800267 }];
268 });
269}
270
271#pragma mark Send headers
272
Jorge Canizalesf4f150f2015-11-01 22:31:12 -0800273- (void)sendHeaders:(NSDictionary *)headers {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700274 // TODO(jcanizales): Add error handlers for async failures
Muxi Yanbf803b92017-02-08 11:31:26 -0800275 GRPCOpSendMetadata *op = [[GRPCOpSendMetadata alloc] initWithMetadata:headers
276 flags:[GRPCCall callFlagsForHost:_host path:_path]
Muxi Yand5bac0d2017-03-07 18:44:19 -0800277 handler:nil]; // No clean-up needed after SEND_INITIAL_METADATA
Muxi Yana40ccd82016-11-05 21:39:44 -0700278 if (!_unaryCall) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800279 [_wrappedCall startBatchWithOperations:@[op]];
Muxi Yana40ccd82016-11-05 21:39:44 -0700280 } else {
Muxi Yanbf803b92017-02-08 11:31:26 -0800281 [_unaryOpBatch addObject:op];
Muxi Yana40ccd82016-11-05 21:39:44 -0700282 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800283}
284
285#pragma mark GRXWriteable implementation
286
287// Only called from the call queue. The error handler will be called from the
288// network queue if the write didn't succeed.
Muxi Yan35653012017-03-07 18:54:24 -0800289// If the call is a unary call, parameter \a errorHandler will be ignored and
290// the error handler of GRPCOpSendClose will be executed in case of error.
Muxi Yan61274ca2016-10-28 12:09:59 -0700291- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
292
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800293 __weak GRPCCall *weakSelf = self;
Muxi Yan61274ca2016-10-28 12:09:59 -0700294 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700295 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800296 GRPCCall *strongSelf = weakSelf;
297 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700298 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700299 strongSelf->_requestWriter.state = GRXWriterStateStarted;
300 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800301 }
302 };
Muxi Yanbf803b92017-02-08 11:31:26 -0800303
304 GRPCOpSendMessage *op = [[GRPCOpSendMessage alloc] initWithMessage:message
305 handler:resumingHandler];
Muxi Yana40ccd82016-11-05 21:39:44 -0700306 if (!_unaryCall) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800307 [_wrappedCall startBatchWithOperations:@[op]
Muxi Yana40ccd82016-11-05 21:39:44 -0700308 errorHandler:errorHandler];
309 } else {
Muxi Yanbf803b92017-02-08 11:31:26 -0800310 [_unaryOpBatch addObject:op];
Muxi Yana40ccd82016-11-05 21:39:44 -0700311 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800312}
313
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700314- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800315 // TODO(jcanizales): Throw/assert if value isn't NSData.
316
317 // Pause the input and only resume it when the C layer notifies us that writes
318 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700319 @synchronized(_requestWriter) {
320 _requestWriter.state = GRXWriterStatePaused;
321 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800322
323 __weak GRPCCall *weakSelf = self;
324 dispatch_async(_callQueue, ^{
Muxi Yan61274ca2016-10-28 12:09:59 -0700325 [weakSelf writeMessage:value withErrorHandler:^{
326 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800327 code:GRPCErrorCodeInternal
328 userInfo:nil]];
Muxi Yan61274ca2016-10-28 12:09:59 -0700329 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800330 });
331}
332
333// Only called from the call queue. The error handler will be called from the
334// network queue if the requests stream couldn't be closed successfully.
335- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
Muxi Yand5bac0d2017-03-07 18:44:19 -0800336 if (!_unaryCall) {
Muxi Yana40ccd82016-11-05 21:39:44 -0700337 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
338 errorHandler:errorHandler];
339 } else {
340 [_unaryOpBatch addObject:[[GRPCOpSendClose alloc] init]];
341 [_wrappedCall startBatchWithOperations:_unaryOpBatch
342 errorHandler:errorHandler];
343 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800344}
345
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700346- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800347 if (errorOrNil) {
348 [self cancel];
349 } else {
350 __weak GRPCCall *weakSelf = self;
351 dispatch_async(_callQueue, ^{
352 [weakSelf finishRequestWithErrorHandler:^{
353 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
354 code:GRPCErrorCodeInternal
355 userInfo:nil]];
356 }];
357 });
358 }
359}
360
361#pragma mark Invoke
362
Muxi Yan61274ca2016-10-28 12:09:59 -0700363// Both handlers will eventually be called, from the network queue. Writes can start immediately
364// after this.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700365// The first one (headersHandler), when the response headers are received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800366// The second one (completionHandler), whenever the RPC finishes for any reason.
Muxi Yan61274ca2016-10-28 12:09:59 -0700367- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
368 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700369 // TODO(jcanizales): Add error handlers for async failures
Muxi Yan61274ca2016-10-28 12:09:59 -0700370 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
371 initWithHandler:headersHandler]]];
372 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
373 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800374}
375
376- (void)invokeCall {
Jorge Canizales0b34c892015-08-12 20:19:20 -0700377 [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700378 // Response headers received.
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100379 self.responseHeaders = headers;
380 [self startNextRead];
Muxi Yan61274ca2016-10-28 12:09:59 -0700381 } completionHandler:^(NSError *error, NSDictionary *trailers) {
382 self.responseTrailers = trailers;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700383
Muxi Yan61274ca2016-10-28 12:09:59 -0700384 if (error) {
385 NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
386 if (error.userInfo) {
387 [userInfo addEntriesFromDictionary:error.userInfo];
388 }
389 userInfo[kGRPCTrailersKey] = self.responseTrailers;
390 // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
391 // called before this one, so an error might end up with trailers but no headers. We
392 // shouldn't call finishWithError until ater both blocks are called. It is also when this is
393 // done that we can provide a merged view of response headers and trailers in a thread-safe
394 // way.
395 if (self.responseHeaders) {
396 userInfo[kGRPCHeadersKey] = self.responseHeaders;
397 }
398 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
399 }
400 [self finishWithError:error];
401 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800402 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700403 @synchronized(_requestWriter) {
404 [_requestWriter startWithWriteable:self];
405 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800406}
407
408#pragma mark GRXWriter implementation
409
410- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700411 @synchronized(self) {
412 _state = GRXWriterStateStarted;
413 }
414
Muxi Yan61274ca2016-10-28 12:09:59 -0700415 // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
416 // This makes RPCs in which the call isn't externally retained possible (as long as it is started
417 // before being autoreleased).
418 // Care is taken not to retain self strongly in any of the blocks used in this implementation, so
419 // that the life of the instance is determined by this retain cycle.
Muxi Yane1443b12016-10-20 11:53:13 -0700420 _retainSelf = self;
421
Muxi Yan61274ca2016-10-28 12:09:59 -0700422 _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
Muxi Yane1443b12016-10-20 11:53:13 -0700423
424 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path];
425 NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?");
426
427 [self sendHeaders:_requestHeaders];
428 [self invokeCall];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700429
430 // TODO(jcanizales): Extract this logic somewhere common.
Muxi Yan61274ca2016-10-28 12:09:59 -0700431 NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host;
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700432 if (!host) {
433 // TODO(jcanizales): Check this on init.
Muxi Yan61274ca2016-10-28 12:09:59 -0700434 [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700435 }
436 __weak typeof(self) weakSelf = self;
437 _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host];
438 void (^handler)() = ^{
439 typeof(self) strongSelf = weakSelf;
440 if (strongSelf) {
Muxi Yan61274ca2016-10-28 12:09:59 -0700441 [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
442 code:GRPCErrorCodeUnavailable
443 userInfo:@{ NSLocalizedDescriptionKey : @"Connectivity lost." }]];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700444 }
445 };
446 [_connectivityMonitor handleLossWithHandler:handler
Muxi Yan2a25f332016-10-28 13:27:04 -0700447 wifiStatusChangeHandler:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800448}
449
450- (void)setState:(GRXWriterState)newState {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700451 @synchronized(self) {
452 // Manual transitions are only allowed from the started or paused states.
Muxi Yan61274ca2016-10-28 12:09:59 -0700453 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700454 return;
455 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800456
Jorge Canizales0803bb02016-04-30 10:40:18 -0700457 switch (newState) {
458 case GRXWriterStateFinished:
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800459 _state = newState;
Jorge Canizales0803bb02016-04-30 10:40:18 -0700460 // Per GRXWriter's contract, setting the state to Finished manually
461 // means one doesn't wish the writeable to be messaged anymore.
462 [_responseWriteable cancelSilently];
463 _responseWriteable = nil;
464 return;
465 case GRXWriterStatePaused:
466 _state = newState;
467 return;
468 case GRXWriterStateStarted:
469 if (_state == GRXWriterStatePaused) {
470 _state = newState;
471 [self startNextRead];
472 }
473 return;
474 case GRXWriterStateNotStarted:
475 return;
476 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800477 }
478}
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700479
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800480@end