blob: bbfb5aa45f36229ce75c3c04b0ff1b465cee8171 [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>
Jorge Canizales35f003b2015-07-17 21:14:36 -070038#import <RxLibrary/GRXConcurrentWriteable.h>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080039
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070040#import "private/GRPCConnectivityMonitor.h"
41#import "private/GRPCHost.h"
Jorge Canizales2f101272015-09-02 21:55:37 -070042#import "private/GRPCRequestHeaders.h"
murgatroid9969927d62015-04-24 13:32:48 -070043#import "private/GRPCWrappedCall.h"
Jorge Canizales5e0efd92015-02-17 18:23:58 -080044#import "private/NSData+GRPC.h"
45#import "private/NSDictionary+GRPC.h"
46#import "private/NSError+GRPC.h"
47
Jorge Canizales1ab2a712015-08-12 20:32:11 -070048NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey";
49NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey";
Muxi Yan22f79732016-09-30 14:24:56 -070050static NSMutableDictionary *callFlags;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070051
Jorge Canizales5e0efd92015-02-17 18:23:58 -080052@interface GRPCCall () <GRXWriteable>
Jorge Canizales0b34c892015-08-12 20:19:20 -070053// Make them read-write.
54@property(atomic, strong) NSDictionary *responseHeaders;
55@property(atomic, strong) NSDictionary *responseTrailers;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080056@end
57
58// The following methods of a C gRPC call object aren't reentrant, and thus
59// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070060// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080061// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080062//
murgatroid99b5c076f2015-04-27 17:25:36 -070063// start_batch with a SEND_MESSAGE argument can only be called after the
64// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080065// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070066// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080067//
murgatroid99b5c076f2015-04-27 17:25:36 -070068// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
69// the OP_COMPLETE event for any previous read is received.This is easier to
70// enforce, as we're writing the received messages into the writeable:
71// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
72// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
73// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080074@implementation GRPCCall {
75 dispatch_queue_t _callQueue;
76
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070077 NSString *_host;
78 NSString *_path;
murgatroid9930b7d4e2015-04-24 10:36:43 -070079 GRPCWrappedCall *_wrappedCall;
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070080 GRPCConnectivityMonitor *_connectivityMonitor;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080081
Jorge Canizales5e0efd92015-02-17 18:23:58 -080082 // The C gRPC library has less guarantees on the ordering of events than we
83 // do. Particularly, in the face of errors, there's no ordering guarantee at
84 // all. This wrapper over our actual writeable ensures thread-safety and
85 // correct ordering.
Jorge Canizales35f003b2015-07-17 21:14:36 -070086 GRXConcurrentWriteable *_responseWriteable;
Jorge Canizales238ad782015-08-07 23:11:29 -070087
88 // The network thread wants the requestWriter to resume (when the server is ready for more input),
89 // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
90 // it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
91 // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
92 // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
93 // pause the writer immediately on writeValue:, so we need our locking to be recursive.
Jorge Canizales56047122015-07-17 12:18:08 -070094 GRXWriter *_requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -070095
Jorge Canizales6531b2b2015-07-18 00:19:14 -070096 // To create a retain cycle when a call is started, up until it finishes. See
Jorge Canizaleseb87b462015-08-08 16:16:43 -070097 // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
98 // reference to the call object if all they're interested in is the handler being executed when
99 // the response arrives.
100 GRPCCall *_retainSelf;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700101
murgatroid9984fa5312015-08-28 10:55:55 -0700102 GRPCRequestHeaders *_requestHeaders;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800103}
104
105@synthesize state = _state;
106
Jorge Canizales7603d642016-08-24 18:23:24 -0700107// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize.
108+ (void)load {
109 grpc_init();
Muxi Yan22f79732016-09-30 14:24:56 -0700110 callFlags = [NSMutableDictionary dictionary];
111}
112
Muxi Yan6c0b9602016-10-02 14:32:06 -0700113+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path {
114 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
115 switch (callSafety) {
116 case GRPCCallSafetyDefault:
Muxi Yan22f79732016-09-30 14:24:56 -0700117 callFlags[hostAndPath] = @0;
118 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700119 case GRPCCallSafetyIdempotentRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700120 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
121 break;
Muxi Yan6c0b9602016-10-02 14:32:06 -0700122 case GRPCCallSafetyCacheableRequest:
Muxi Yan22f79732016-09-30 14:24:56 -0700123 callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
124 break;
125 default:
126 break;
127 }
128}
129
Muxi Yan6c0b9602016-10-02 14:32:06 -0700130+ (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path {
131 NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
132 return [callFlags[hostAndPath] intValue];
Jorge Canizales7603d642016-08-24 18:23:24 -0700133}
134
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800135- (instancetype)init {
Muxi Yan22f79732016-09-30 14:24:56 -0700136 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800137}
138
139// Designated initializer
140- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700141 path:(NSString *)path
Muxi Yan22f79732016-09-30 14:24:56 -0700142 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700143 if (!host || !path) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700144 [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800145 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700146 if (requestWriter.state != GRXWriterStateNotStarted) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700147 [NSException raise:NSInvalidArgumentException
148 format:@"The requests writer can't be already started."];
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700149 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800150 if ((self = [super init])) {
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700151 _host = [host copy];
152 _path = [path copy];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800153
154 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700155 _callQueue = dispatch_queue_create("io.grpc.call", NULL);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800156
157 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700158
murgatroid9984fa5312015-08-28 10:55:55 -0700159 _requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800160 }
161 return self;
162}
163
164#pragma mark Finish
165
166- (void)finishWithError:(NSError *)errorOrNil {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700167 @synchronized(self) {
168 _state = GRXWriterStateFinished;
169 }
170
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700171 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700172 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700173
174 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700175 @synchronized(_requestWriter) {
176 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700177 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700178
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800179 if (errorOrNil) {
180 [_responseWriteable cancelWithError:errorOrNil];
181 } else {
182 [_responseWriteable enqueueSuccessfulCompletion];
183 }
184}
185
186- (void)cancelCall {
187 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700188 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800189}
190
191- (void)cancel {
192 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
193 code:GRPCErrorCodeCancelled
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700194 userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800195 [self cancelCall];
196}
197
198- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700199 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800200 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700201 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800202 });
203}
204
205#pragma mark Read messages
206
207// Only called from the call queue.
208// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700209- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700210 // TODO(jcanizales): Add error handlers for async failures
murgatroid9954e93d42015-04-27 09:29:49 -0700211 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800212}
213
214// Called initially from the network queue once response headers are received,
215// then "recursively" from the responseWriteable queue after each response from the
216// server has been written.
217// If the call is currently paused, this is a noop. Restarting the call will invoke this
218// method.
219// TODO(jcanizales): Rename to readResponseIfNotPaused.
220- (void)startNextRead {
221 if (self.state == GRXWriterStatePaused) {
222 return;
223 }
224 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700225 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700226
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800227 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700228 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
229 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700230 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800231 return;
232 }
murgatroid996cc46802015-04-28 09:35:48 -0700233 NSData *data = [NSData grpc_dataWithByteBuffer:message];
234 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800235 if (!data) {
236 // The app doesn't have enough memory to hold the server response. We
237 // don't want to throw, because the app shouldn't crash for a behavior
238 // that's on the hands of any server to have. Instead we finish and ask
239 // the server to cancel.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800240 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
Muxi Yanfc99ff62016-07-06 15:08:30 -0700241 code:GRPCErrorCodeResourceExhausted
Muxi Yanff6cd702016-07-07 09:57:54 -0700242 userInfo:@{NSLocalizedDescriptionKey: @"Client does not have enough memory to hold the server response."}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800243 [weakSelf cancelCall];
244 return;
245 }
Jorge Canizales4c6f7782015-07-17 23:13:36 -0700246 [weakWriteable enqueueValue:data completionHandler:^{
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800247 [weakSelf startNextRead];
248 }];
249 }];
250 });
251}
252
253#pragma mark Send headers
254
Jorge Canizalesf4f150f2015-11-01 22:31:12 -0800255- (void)sendHeaders:(NSDictionary *)headers {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700256 // TODO(jcanizales): Add error handlers for async failures
Jorge Canizales5c339d12015-09-02 17:41:43 -0700257 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc] initWithMetadata:headers
Muxi Yan6c0b9602016-10-02 14:32:06 -0700258 flags:[GRPCCall callFlagsForHost:_host path:_path]
Jorge Canizales5c339d12015-09-02 17:41:43 -0700259 handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800260}
261
262#pragma mark GRXWriteable implementation
263
264// Only called from the call queue. The error handler will be called from the
265// network queue if the write didn't succeed.
266- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
267
268 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700269 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700270 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800271 GRPCCall *strongSelf = weakSelf;
272 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700273 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700274 strongSelf->_requestWriter.state = GRXWriterStateStarted;
275 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800276 }
277 };
Jorge Canizales238ad782015-08-07 23:11:29 -0700278 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc] initWithMessage:message
279 handler:resumingHandler]]
280 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800281}
282
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700283- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800284 // TODO(jcanizales): Throw/assert if value isn't NSData.
285
286 // Pause the input and only resume it when the C layer notifies us that writes
287 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700288 @synchronized(_requestWriter) {
289 _requestWriter.state = GRXWriterStatePaused;
290 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800291
292 __weak GRPCCall *weakSelf = self;
293 dispatch_async(_callQueue, ^{
294 [weakSelf writeMessage:value withErrorHandler:^{
295 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
296 code:GRPCErrorCodeInternal
297 userInfo:nil]];
298 }];
299 });
300}
301
302// Only called from the call queue. The error handler will be called from the
303// network queue if the requests stream couldn't be closed successfully.
304- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700305 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
306 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800307}
308
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700309- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800310 if (errorOrNil) {
311 [self cancel];
312 } else {
313 __weak GRPCCall *weakSelf = self;
314 dispatch_async(_callQueue, ^{
315 [weakSelf finishRequestWithErrorHandler:^{
316 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
317 code:GRPCErrorCodeInternal
318 userInfo:nil]];
319 }];
320 });
321 }
322}
323
324#pragma mark Invoke
325
326// Both handlers will eventually be called, from the network queue. Writes can start immediately
327// after this.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700328// The first one (headersHandler), when the response headers are received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800329// The second one (completionHandler), whenever the RPC finishes for any reason.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700330- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700331 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700332 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700333 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
Jorge Canizales0b34c892015-08-12 20:19:20 -0700334 initWithHandler:headersHandler]]];
murgatroid996cc46802015-04-28 09:35:48 -0700335 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
336 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800337}
338
339- (void)invokeCall {
Jorge Canizales0b34c892015-08-12 20:19:20 -0700340 [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700341 // Response headers received.
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100342 self.responseHeaders = headers;
343 [self startNextRead];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700344 } completionHandler:^(NSError *error, NSDictionary *trailers) {
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100345 self.responseTrailers = trailers;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700346
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100347 if (error) {
348 NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
349 if (error.userInfo) {
350 [userInfo addEntriesFromDictionary:error.userInfo];
Jorge Canizalesc58a1102015-06-15 19:03:41 -0700351 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100352 userInfo[kGRPCTrailersKey] = self.responseTrailers;
353 // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
354 // called before this one, so an error might end up with trailers but no headers. We
355 // shouldn't call finishWithError until ater both blocks are called. It is also when this is
356 // done that we can provide a merged view of response headers and trailers in a thread-safe
357 // way.
358 if (self.responseHeaders) {
359 userInfo[kGRPCHeadersKey] = self.responseHeaders;
360 }
361 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700362 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100363 [self finishWithError:error];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800364 }];
365 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700366 @synchronized(_requestWriter) {
367 [_requestWriter startWithWriteable:self];
368 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800369}
370
371#pragma mark GRXWriter implementation
372
373- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700374 @synchronized(self) {
375 _state = GRXWriterStateStarted;
376 }
377
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700378 // TODO(jcanizales): Extract this logic somewhere common.
379 NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host;
380 if (!host) {
381 // TODO(jcanizales): Check this on init.
382 [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host];
383 }
384 __weak typeof(self) weakSelf = self;
385 _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host];
Muxi Yane1443b12016-10-20 11:53:13 -0700386 void (^handler)() = ^{
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700387 typeof(self) strongSelf = weakSelf;
388 if (strongSelf) {
389 [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
390 code:GRPCErrorCodeUnavailable
391 userInfo:@{NSLocalizedDescriptionKey: @"Connectivity lost."}]];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700392 }
Muxi Yane1443b12016-10-20 11:53:13 -0700393 };
394 [_connectivityMonitor handleLossWithHandler:handler
395 wifiStatusChangeHandler:handler];
396
397 // Create a retain cycle so that this instance lives until the RPC finishes
398 // (or is cancelled).
399 // This makes RPCs in which the call isn't externally retained possible (as
400 // long as it is started
401 // before being autoreleased).
402 // Care is taken not to retain self strongly in any of the blocks used in this
403 // implementation, so
404 // that the life of the instance is determined by this retain cycle.
405 _retainSelf = self;
406
407 _responseWriteable =
408 [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
409
410 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path];
411 NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?");
412
413 [self sendHeaders:_requestHeaders];
414 [self invokeCall];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800415}
416
417- (void)setState:(GRXWriterState)newState {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700418 @synchronized(self) {
419 // Manual transitions are only allowed from the started or paused states.
420 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
421 return;
422 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800423
Jorge Canizales0803bb02016-04-30 10:40:18 -0700424 switch (newState) {
425 case GRXWriterStateFinished:
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800426 _state = newState;
Jorge Canizales0803bb02016-04-30 10:40:18 -0700427 // Per GRXWriter's contract, setting the state to Finished manually
428 // means one doesn't wish the writeable to be messaged anymore.
429 [_responseWriteable cancelSilently];
430 _responseWriteable = nil;
431 return;
432 case GRXWriterStatePaused:
433 _state = newState;
434 return;
435 case GRXWriterStateStarted:
436 if (_state == GRXWriterStatePaused) {
437 _state = newState;
438 [self startNextRead];
439 }
440 return;
441 case GRXWriterStateNotStarted:
442 return;
443 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800444 }
445}
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700446
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800447@end