blob: 0eb10656ddc3ea916ebe4fe02d5e54185ad48461 [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";
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070050
Jorge Canizales5e0efd92015-02-17 18:23:58 -080051@interface GRPCCall () <GRXWriteable>
Jorge Canizales0b34c892015-08-12 20:19:20 -070052// Make them read-write.
53@property(atomic, strong) NSDictionary *responseHeaders;
54@property(atomic, strong) NSDictionary *responseTrailers;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080055@end
56
57// The following methods of a C gRPC call object aren't reentrant, and thus
58// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070059// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080060// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080061//
murgatroid99b5c076f2015-04-27 17:25:36 -070062// start_batch with a SEND_MESSAGE argument can only be called after the
63// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080064// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070065// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080066//
murgatroid99b5c076f2015-04-27 17:25:36 -070067// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
68// the OP_COMPLETE event for any previous read is received.This is easier to
69// enforce, as we're writing the received messages into the writeable:
70// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
71// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
72// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080073@implementation GRPCCall {
74 dispatch_queue_t _callQueue;
75
Jorge Canizalesf1d084a2015-10-30 11:14:09 -070076 NSString *_host;
77 NSString *_path;
murgatroid9930b7d4e2015-04-24 10:36:43 -070078 GRPCWrappedCall *_wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080079 dispatch_once_t _callAlreadyInvoked;
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
107- (instancetype)init {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700108 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800109}
110
111// Designated initializer
112- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700113 path:(NSString *)path
Jorge Canizales56047122015-07-17 12:18:08 -0700114 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700115 if (!host || !path) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700116 [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800117 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700118 if (requestWriter.state != GRXWriterStateNotStarted) {
Jorge Canizales597ef982015-07-31 23:31:56 -0700119 [NSException raise:NSInvalidArgumentException
120 format:@"The requests writer can't be already started."];
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700121 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800122 if ((self = [super init])) {
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700123 _host = [host copy];
124 _path = [path copy];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800125
126 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700127 _callQueue = dispatch_queue_create("io.grpc.call", NULL);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800128
129 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700130
murgatroid9984fa5312015-08-28 10:55:55 -0700131 _requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800132 }
133 return self;
134}
135
136#pragma mark Finish
137
138- (void)finishWithError:(NSError *)errorOrNil {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700139 @synchronized(self) {
140 _state = GRXWriterStateFinished;
141 }
142
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700143 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700144 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700145
146 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700147 @synchronized(_requestWriter) {
148 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700149 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700150
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800151 if (errorOrNil) {
152 [_responseWriteable cancelWithError:errorOrNil];
153 } else {
154 [_responseWriteable enqueueSuccessfulCompletion];
155 }
156}
157
158- (void)cancelCall {
159 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700160 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800161}
162
163- (void)cancel {
164 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
165 code:GRPCErrorCodeCancelled
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700166 userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800167 [self cancelCall];
168}
169
170- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700171 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800172 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700173 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800174 });
175}
176
177#pragma mark Read messages
178
179// Only called from the call queue.
180// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700181- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700182 // TODO(jcanizales): Add error handlers for async failures
murgatroid9954e93d42015-04-27 09:29:49 -0700183 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800184}
185
186// Called initially from the network queue once response headers are received,
187// then "recursively" from the responseWriteable queue after each response from the
188// server has been written.
189// If the call is currently paused, this is a noop. Restarting the call will invoke this
190// method.
191// TODO(jcanizales): Rename to readResponseIfNotPaused.
192- (void)startNextRead {
193 if (self.state == GRXWriterStatePaused) {
194 return;
195 }
196 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700197 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700198
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800199 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700200 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
201 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700202 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800203 return;
204 }
murgatroid996cc46802015-04-28 09:35:48 -0700205 NSData *data = [NSData grpc_dataWithByteBuffer:message];
206 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800207 if (!data) {
208 // The app doesn't have enough memory to hold the server response. We
209 // don't want to throw, because the app shouldn't crash for a behavior
210 // that's on the hands of any server to have. Instead we finish and ask
211 // the server to cancel.
212 //
213 // TODO(jcanizales): No canonical code is appropriate for this situation
214 // (because it's just a client problem). Use another domain and an
215 // appropriately-documented code.
216 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
217 code:GRPCErrorCodeInternal
218 userInfo:nil]];
219 [weakSelf cancelCall];
220 return;
221 }
Jorge Canizales4c6f7782015-07-17 23:13:36 -0700222 [weakWriteable enqueueValue:data completionHandler:^{
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800223 [weakSelf startNextRead];
224 }];
225 }];
226 });
227}
228
229#pragma mark Send headers
230
Jorge Canizalesf4f150f2015-11-01 22:31:12 -0800231- (void)sendHeaders:(NSDictionary *)headers {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700232 // TODO(jcanizales): Add error handlers for async failures
Jorge Canizales5c339d12015-09-02 17:41:43 -0700233 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc] initWithMetadata:headers
234 handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800235}
236
237#pragma mark GRXWriteable implementation
238
239// Only called from the call queue. The error handler will be called from the
240// network queue if the write didn't succeed.
241- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
242
243 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700244 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700245 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800246 GRPCCall *strongSelf = weakSelf;
247 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700248 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700249 strongSelf->_requestWriter.state = GRXWriterStateStarted;
250 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800251 }
252 };
Jorge Canizales238ad782015-08-07 23:11:29 -0700253 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc] initWithMessage:message
254 handler:resumingHandler]]
255 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800256}
257
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700258- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800259 // TODO(jcanizales): Throw/assert if value isn't NSData.
260
261 // Pause the input and only resume it when the C layer notifies us that writes
262 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700263 @synchronized(_requestWriter) {
264 _requestWriter.state = GRXWriterStatePaused;
265 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800266
267 __weak GRPCCall *weakSelf = self;
268 dispatch_async(_callQueue, ^{
269 [weakSelf writeMessage:value withErrorHandler:^{
270 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
271 code:GRPCErrorCodeInternal
272 userInfo:nil]];
273 }];
274 });
275}
276
277// Only called from the call queue. The error handler will be called from the
278// network queue if the requests stream couldn't be closed successfully.
279- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700280 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
281 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800282}
283
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700284- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800285 if (errorOrNil) {
286 [self cancel];
287 } else {
288 __weak GRPCCall *weakSelf = self;
289 dispatch_async(_callQueue, ^{
290 [weakSelf finishRequestWithErrorHandler:^{
291 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
292 code:GRPCErrorCodeInternal
293 userInfo:nil]];
294 }];
295 });
296 }
297}
298
299#pragma mark Invoke
300
301// Both handlers will eventually be called, from the network queue. Writes can start immediately
302// after this.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700303// The first one (headersHandler), when the response headers are received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800304// The second one (completionHandler), whenever the RPC finishes for any reason.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700305- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700306 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700307 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700308 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
Jorge Canizales0b34c892015-08-12 20:19:20 -0700309 initWithHandler:headersHandler]]];
murgatroid996cc46802015-04-28 09:35:48 -0700310 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
311 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800312}
313
314- (void)invokeCall {
Jorge Canizales0b34c892015-08-12 20:19:20 -0700315 [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700316 // Response headers received.
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100317 self.responseHeaders = headers;
318 [self startNextRead];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700319 } completionHandler:^(NSError *error, NSDictionary *trailers) {
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100320 self.responseTrailers = trailers;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700321
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100322 if (error) {
323 NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
324 if (error.userInfo) {
325 [userInfo addEntriesFromDictionary:error.userInfo];
Jorge Canizalesc58a1102015-06-15 19:03:41 -0700326 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100327 userInfo[kGRPCTrailersKey] = self.responseTrailers;
328 // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
329 // called before this one, so an error might end up with trailers but no headers. We
330 // shouldn't call finishWithError until ater both blocks are called. It is also when this is
331 // done that we can provide a merged view of response headers and trailers in a thread-safe
332 // way.
333 if (self.responseHeaders) {
334 userInfo[kGRPCHeadersKey] = self.responseHeaders;
335 }
336 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700337 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100338 [self finishWithError:error];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800339 }];
340 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700341 @synchronized(_requestWriter) {
342 [_requestWriter startWithWriteable:self];
343 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800344}
345
346#pragma mark GRXWriter implementation
347
348- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700349 @synchronized(self) {
350 _state = GRXWriterStateStarted;
351 }
352
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700353 // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
354 // This makes RPCs in which the call isn't externally retained possible (as long as it is started
355 // before being autoreleased).
356 // Care is taken not to retain self strongly in any of the blocks used in this implementation, so
357 // that the life of the instance is determined by this retain cycle.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700358 _retainSelf = self;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700359
360 _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700361
362 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path];
363 NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?");
364
Jorge Canizales6512d262015-08-12 17:33:23 -0700365 [self sendHeaders:_requestHeaders];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800366 [self invokeCall];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700367 // TODO(jcanizales): Extract this logic somewhere common.
368 NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host;
369 if (!host) {
370 // TODO(jcanizales): Check this on init.
371 [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host];
372 }
373 __weak typeof(self) weakSelf = self;
374 _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host];
375 [_connectivityMonitor handleLossWithHandler:^{
376 typeof(self) strongSelf = weakSelf;
377 if (strongSelf) {
378 [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
379 code:GRPCErrorCodeUnavailable
380 userInfo:@{NSLocalizedDescriptionKey: @"Connectivity lost."}]];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700381 }
382 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800383}
384
385- (void)setState:(GRXWriterState)newState {
Jorge Canizales0803bb02016-04-30 10:40:18 -0700386 @synchronized(self) {
387 // Manual transitions are only allowed from the started or paused states.
388 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
389 return;
390 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800391
Jorge Canizales0803bb02016-04-30 10:40:18 -0700392 switch (newState) {
393 case GRXWriterStateFinished:
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800394 _state = newState;
Jorge Canizales0803bb02016-04-30 10:40:18 -0700395 // Per GRXWriter's contract, setting the state to Finished manually
396 // means one doesn't wish the writeable to be messaged anymore.
397 [_responseWriteable cancelSilently];
398 _responseWriteable = nil;
399 return;
400 case GRXWriterStatePaused:
401 _state = newState;
402 return;
403 case GRXWriterStateStarted:
404 if (_state == GRXWriterStatePaused) {
405 _state = newState;
406 [self startNextRead];
407 }
408 return;
409 case GRXWriterStateNotStarted:
410 return;
411 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800412 }
413}
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700414
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800415@end