blob: 1a8fc2e2ef6ee1c9ca374c827bac8fb6888490c1 [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 Yan61274ca2016-10-28 12:09:59 -070049NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey";
50NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey";
Muxi Yan22f79732016-09-30 14:24:56 -070051static NSMutableDictionary *callFlags;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070052
Muxi Yan61274ca2016-10-28 12:09:59 -070053@interface GRPCCall () <GRXWriteable>
Jorge Canizales0b34c892015-08-12 20:19:20 -070054// Make them read-write.
55@property(atomic, strong) NSDictionary *responseHeaders;
56@property(atomic, strong) NSDictionary *responseTrailers;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080057@end
58
59// The following methods of a C gRPC call object aren't reentrant, and thus
60// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070061// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080062// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080063//
murgatroid99b5c076f2015-04-27 17:25:36 -070064// start_batch with a SEND_MESSAGE argument can only be called after the
65// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080066// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070067// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080068//
murgatroid99b5c076f2015-04-27 17:25:36 -070069// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
70// the OP_COMPLETE event for any previous read is received.This is easier to
71// enforce, as we're writing the received messages into the writeable:
72// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
73// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
74// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080075@implementation GRPCCall {
76 dispatch_queue_t _callQueue;
77
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070078 NSString *_host;
79 NSString *_path;
murgatroid9930b7d4e2015-04-24 10:36:43 -070080 GRPCWrappedCall *_wrappedCall;
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070081 GRPCConnectivityMonitor *_connectivityMonitor;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080082
Jorge Canizales5e0efd92015-02-17 18:23:58 -080083 // The C gRPC library has less guarantees on the ordering of events than we
84 // do. Particularly, in the face of errors, there's no ordering guarantee at
85 // all. This wrapper over our actual writeable ensures thread-safety and
86 // correct ordering.
Jorge Canizales35f003b2015-07-17 21:14:36 -070087 GRXConcurrentWriteable *_responseWriteable;
Jorge Canizales238ad782015-08-07 23:11:29 -070088
Muxi Yan61274ca2016-10-28 12:09:59 -070089 // The network thread wants the requestWriter to resume (when the server is ready for more input),
90 // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
91 // it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
92 // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
93 // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
94 // pause the writer immediately on writeValue:, so we need our locking to be recursive.
Jorge Canizales56047122015-07-17 12:18:08 -070095 GRXWriter *_requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -070096
Jorge Canizales6531b2b2015-07-18 00:19:14 -070097 // To create a retain cycle when a call is started, up until it finishes. See
Muxi Yan61274ca2016-10-28 12:09:59 -070098 // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
99 // reference to the call object if all they're interested in is the handler being executed when
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700100 // the response arrives.
101 GRPCCall *_retainSelf;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700102
murgatroid9984fa5312015-08-28 10:55:55 -0700103 GRPCRequestHeaders *_requestHeaders;
Muxi Yana40ccd82016-11-05 21:39:44 -0700104
105 BOOL _unaryCall;
106
107 NSMutableArray *_unaryOpBatch;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800108}
109
110@synthesize state = _state;
111
Muxi Yan61274ca2016-10-28 12:09:59 -0700112// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize.
Jorge Canizales7603d642016-08-24 18:23:24 -0700113+ (void)load {
114 grpc_init();
Muxi Yan22f79732016-09-30 14:24:56 -0700115 callFlags = [NSMutableDictionary dictionary];
116}
117
Muxi Yan61274ca2016-10-28 12:09:59 -0700118+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path {
Muxi Yan6c0b9602016-10-02 14:32:06 -0700119 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
120 switch (callSafety) {
121 case GRPCCallSafetyDefault:
Muxi Yan22f79732016-09-30 14:24:56 -0700122 callFlags[hostAndPath] = @0;
123 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700124 case GRPCCallSafetyIdempotentRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700125 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
126 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700127 case GRPCCallSafetyCacheableRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700128 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
129 break;
130 default:
131 break;
132 }
133}
134
Muxi Yan6c0b9602016-10-02 14:32:06 -0700135+ (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path {
136 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
137 return [callFlags[hostAndPath] intValue];
Jorge Canizales7603d642016-08-24 18:23:24 -0700138}
139
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800140- (instancetype)init {
Muxi Yan22f79732016-09-30 14:24:56 -0700141 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800142}
143
144// Designated initializer
145- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700146 path:(NSString *)path
Muxi Yan22f79732016-09-30 14:24:56 -0700147 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700148 if (!host || !path) {
Muxi Yan61274ca2016-10-28 12:09:59 -0700149 [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800150 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700151 if (requestWriter.state != GRXWriterStateNotStarted) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700152 [NSException raise:NSInvalidArgumentException
153 format:@"The requests writer can't be already started."];
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700154 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800155 if ((self = [super init])) {
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700156 _host = [host copy];
157 _path = [path copy];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800158
159 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700160 _callQueue = dispatch_queue_create("io.grpc.call", NULL);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800161
162 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700163
murgatroid9984fa5312015-08-28 10:55:55 -0700164 _requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
Muxi Yana40ccd82016-11-05 21:39:44 -0700165
166 if ([requestWriter isKindOfClass:[GRXImmediateSingleWriter class]]) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800167 _unaryCall = YES;
168 _unaryOpBatch = [NSMutableArray arrayWithCapacity:6];
Muxi Yana40ccd82016-11-05 21:39:44 -0700169 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800170 }
171 return self;
172}
173
174#pragma mark Finish
175
176- (void)finishWithError:(NSError *)errorOrNil {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700177 @synchronized(self) {
Muxi Yana40ccd82016-11-05 21:39:44 -0700178 if (_state == GRXWriterStateFinished) {
179 return;
180 }
Jorge Canizales0803bb02016-04-30 10:40:18 -0700181 _state = GRXWriterStateFinished;
182 }
183
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700184 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700185 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700186
187 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700188 @synchronized(_requestWriter) {
189 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700190 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700191
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800192 if (errorOrNil) {
193 [_responseWriteable cancelWithError:errorOrNil];
194 } else {
195 [_responseWriteable enqueueSuccessfulCompletion];
196 }
197}
198
199- (void)cancelCall {
200 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700201 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800202}
203
204- (void)cancel {
205 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
206 code:GRPCErrorCodeCancelled
Muxi Yan61274ca2016-10-28 12:09:59 -0700207 userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800208 [self cancelCall];
209}
210
211- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700212 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800213 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700214 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800215 });
216}
217
218#pragma mark Read messages
219
220// Only called from the call queue.
221// The handler will be called from the network queue.
Muxi Yan61274ca2016-10-28 12:09:59 -0700222- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700223 // TODO(jcanizales): Add error handlers for async failures
Muxi Yan61274ca2016-10-28 12:09:59 -0700224 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800225}
226
227// Called initially from the network queue once response headers are received,
Muxi Yan61274ca2016-10-28 12:09:59 -0700228// then "recursively" from the responseWriteable queue after each response from the
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800229// server has been written.
Muxi Yan61274ca2016-10-28 12:09:59 -0700230// If the call is currently paused, this is a noop. Restarting the call will invoke this
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800231// method.
232// TODO(jcanizales): Rename to readResponseIfNotPaused.
233- (void)startNextRead {
234 if (self.state == GRXWriterStatePaused) {
235 return;
236 }
237 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700238 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700239
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800240 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700241 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
242 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700243 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800244 return;
245 }
murgatroid996cc46802015-04-28 09:35:48 -0700246 NSData *data = [NSData grpc_dataWithByteBuffer:message];
247 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800248 if (!data) {
249 // The app doesn't have enough memory to hold the server response. We
250 // don't want to throw, because the app shouldn't crash for a behavior
251 // that's on the hands of any server to have. Instead we finish and ask
252 // the server to cancel.
Muxi Yan61274ca2016-10-28 12:09:59 -0700253 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
254 code:GRPCErrorCodeResourceExhausted
255 userInfo:@{NSLocalizedDescriptionKey: @"Client does not have enough memory to hold the server response."}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800256 [weakSelf cancelCall];
257 return;
258 }
Muxi Yan61274ca2016-10-28 12:09:59 -0700259 [weakWriteable enqueueValue:data completionHandler:^{
260 [weakSelf startNextRead];
261 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800262 }];
263 });
264}
265
266#pragma mark Send headers
267
Jorge Canizalesf4f150f2015-11-01 22:31:12 -0800268- (void)sendHeaders:(NSDictionary *)headers {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700269 // TODO(jcanizales): Add error handlers for async failures
Muxi Yanbf803b92017-02-08 11:31:26 -0800270 GRPCOpSendMetadata *op = [[GRPCOpSendMetadata alloc] initWithMetadata:headers
271 flags:[GRPCCall callFlagsForHost:_host path:_path]
272 handler:nil];
Muxi Yana40ccd82016-11-05 21:39:44 -0700273 if (!_unaryCall) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800274 [_wrappedCall startBatchWithOperations:@[op]];
Muxi Yana40ccd82016-11-05 21:39:44 -0700275 } else {
Muxi Yanbf803b92017-02-08 11:31:26 -0800276 [_unaryOpBatch addObject:op];
Muxi Yana40ccd82016-11-05 21:39:44 -0700277 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800278}
279
280#pragma mark GRXWriteable implementation
281
282// Only called from the call queue. The error handler will be called from the
283// network queue if the write didn't succeed.
Muxi Yan61274ca2016-10-28 12:09:59 -0700284- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
285
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800286 __weak GRPCCall *weakSelf = self;
Muxi Yan61274ca2016-10-28 12:09:59 -0700287 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700288 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800289 GRPCCall *strongSelf = weakSelf;
290 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700291 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700292 strongSelf->_requestWriter.state = GRXWriterStateStarted;
293 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800294 }
295 };
Muxi Yanbf803b92017-02-08 11:31:26 -0800296
297 GRPCOpSendMessage *op = [[GRPCOpSendMessage alloc] initWithMessage:message
298 handler:resumingHandler];
Muxi Yana40ccd82016-11-05 21:39:44 -0700299 if (!_unaryCall) {
Muxi Yanbf803b92017-02-08 11:31:26 -0800300 [_wrappedCall startBatchWithOperations:@[op]
Muxi Yana40ccd82016-11-05 21:39:44 -0700301 errorHandler:errorHandler];
302 } else {
Muxi Yanbf803b92017-02-08 11:31:26 -0800303 [_unaryOpBatch addObject:op];
Muxi Yana40ccd82016-11-05 21:39:44 -0700304 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800305}
306
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700307- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800308 // TODO(jcanizales): Throw/assert if value isn't NSData.
309
310 // Pause the input and only resume it when the C layer notifies us that writes
311 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700312 @synchronized(_requestWriter) {
313 _requestWriter.state = GRXWriterStatePaused;
314 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800315
316 __weak GRPCCall *weakSelf = self;
317 dispatch_async(_callQueue, ^{
Muxi Yan61274ca2016-10-28 12:09:59 -0700318 [weakSelf writeMessage:value withErrorHandler:^{
319 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800320 code:GRPCErrorCodeInternal
321 userInfo:nil]];
Muxi Yan61274ca2016-10-28 12:09:59 -0700322 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800323 });
324}
325
326// Only called from the call queue. The error handler will be called from the
327// network queue if the requests stream couldn't be closed successfully.
328- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
Muxi Yana40ccd82016-11-05 21:39:44 -0700329 if (!_unaryOpBatch) {
330 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
331 errorHandler:errorHandler];
332 } else {
333 [_unaryOpBatch addObject:[[GRPCOpSendClose alloc] init]];
334 [_wrappedCall startBatchWithOperations:_unaryOpBatch
335 errorHandler:errorHandler];
336 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800337}
338
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700339- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800340 if (errorOrNil) {
341 [self cancel];
342 } else {
343 __weak GRPCCall *weakSelf = self;
344 dispatch_async(_callQueue, ^{
345 [weakSelf finishRequestWithErrorHandler:^{
346 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
347 code:GRPCErrorCodeInternal
348 userInfo:nil]];
349 }];
350 });
351 }
352}
353
354#pragma mark Invoke
355
Muxi Yan61274ca2016-10-28 12:09:59 -0700356// Both handlers will eventually be called, from the network queue. Writes can start immediately
357// after this.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700358// The first one (headersHandler), when the response headers are received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800359// The second one (completionHandler), whenever the RPC finishes for any reason.
Muxi Yan61274ca2016-10-28 12:09:59 -0700360- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
361 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700362 // TODO(jcanizales): Add error handlers for async failures
Muxi Yan61274ca2016-10-28 12:09:59 -0700363 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
364 initWithHandler:headersHandler]]];
365 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
366 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800367}
368
369- (void)invokeCall {
Jorge Canizales0b34c892015-08-12 20:19:20 -0700370 [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700371 // Response headers received.
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100372 self.responseHeaders = headers;
373 [self startNextRead];
Muxi Yan61274ca2016-10-28 12:09:59 -0700374 } completionHandler:^(NSError *error, NSDictionary *trailers) {
375 self.responseTrailers = trailers;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700376
Muxi Yan61274ca2016-10-28 12:09:59 -0700377 if (error) {
378 NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
379 if (error.userInfo) {
380 [userInfo addEntriesFromDictionary:error.userInfo];
381 }
382 userInfo[kGRPCTrailersKey] = self.responseTrailers;
383 // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
384 // called before this one, so an error might end up with trailers but no headers. We
385 // shouldn't call finishWithError until ater both blocks are called. It is also when this is
386 // done that we can provide a merged view of response headers and trailers in a thread-safe
387 // way.
388 if (self.responseHeaders) {
389 userInfo[kGRPCHeadersKey] = self.responseHeaders;
390 }
391 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
392 }
393 [self finishWithError:error];
394 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800395 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700396 @synchronized(_requestWriter) {
397 [_requestWriter startWithWriteable:self];
398 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800399}
400
401#pragma mark GRXWriter implementation
402
403- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700404 @synchronized(self) {
405 _state = GRXWriterStateStarted;
406 }
407
Muxi Yan61274ca2016-10-28 12:09:59 -0700408 // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
409 // This makes RPCs in which the call isn't externally retained possible (as long as it is started
410 // before being autoreleased).
411 // Care is taken not to retain self strongly in any of the blocks used in this implementation, so
412 // that the life of the instance is determined by this retain cycle.
Muxi Yane1443b12016-10-20 11:53:13 -0700413 _retainSelf = self;
414
Muxi Yan61274ca2016-10-28 12:09:59 -0700415 _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
Muxi Yane1443b12016-10-20 11:53:13 -0700416
417 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path];
418 NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?");
419
420 [self sendHeaders:_requestHeaders];
421 [self invokeCall];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700422
423 // TODO(jcanizales): Extract this logic somewhere common.
Muxi Yan61274ca2016-10-28 12:09:59 -0700424 NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host;
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700425 if (!host) {
426 // TODO(jcanizales): Check this on init.
Muxi Yan61274ca2016-10-28 12:09:59 -0700427 [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700428 }
429 __weak typeof(self) weakSelf = self;
430 _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host];
431 void (^handler)() = ^{
432 typeof(self) strongSelf = weakSelf;
433 if (strongSelf) {
Muxi Yan61274ca2016-10-28 12:09:59 -0700434 [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
435 code:GRPCErrorCodeUnavailable
436 userInfo:@{ NSLocalizedDescriptionKey : @"Connectivity lost." }]];
Muxi Yan4f6a19b2016-10-25 14:40:06 -0700437 }
438 };
439 [_connectivityMonitor handleLossWithHandler:handler
Muxi Yan2a25f332016-10-28 13:27:04 -0700440 wifiStatusChangeHandler:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800441}
442
443- (void)setState:(GRXWriterState)newState {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700444 @synchronized(self) {
445 // Manual transitions are only allowed from the started or paused states.
Muxi Yan61274ca2016-10-28 12:09:59 -0700446 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700447 return;
448 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800449
Jorge Canizales0803bb02016-04-30 10:40:18 -0700450 switch (newState) {
451 case GRXWriterStateFinished:
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800452 _state = newState;
Jorge Canizales0803bb02016-04-30 10:40:18 -0700453 // Per GRXWriter's contract, setting the state to Finished manually
454 // means one doesn't wish the writeable to be messaged anymore.
455 [_responseWriteable cancelSilently];
456 _responseWriteable = nil;
457 return;
458 case GRXWriterStatePaused:
459 _state = newState;
460 return;
461 case GRXWriterStateStarted:
462 if (_state == GRXWriterStatePaused) {
463 _state = newState;
464 [self startNextRead];
465 }
466 return;
467 case GRXWriterStateNotStarted:
468 return;
469 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800470 }
471}
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700472
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800473@end