blob: 1847d6016ff92b2c247bc1a996818c33e11886aa [file] [log] [blame]
Jorge Canizales9409ad82015-02-18 16:19:56 -08001/*
2 *
Yang Gao5fc90292015-02-20 09:46:22 -08003 * Copyright 2015, Google Inc.
Jorge Canizales9409ad82015-02-18 16:19:56 -08004 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
15 * distribution.
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
Jorge Canizales5e0efd92015-02-17 18:23:58 -080034#import "GRPCCall.h"
35
Jorge Canizalesc2d7ecb2015-02-27 01:22:41 -080036#include <grpc/grpc.h>
Jorge Canizales59bb9d72015-06-22 19:04:15 -070037#include <grpc/support/time.h>
Jorge Canizales35f003b2015-07-17 21:14:36 -070038#import <RxLibrary/GRXConcurrentWriteable.h>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080039
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 Canizales6531b2b2015-07-18 00:19:14 -0700139 // If the call isn't retained anywhere else, it can be deallocated now.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700140 _retainSelf = nil;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700141
142 // If there were still request messages coming, stop them.
Jorge Canizales238ad782015-08-07 23:11:29 -0700143 @synchronized(_requestWriter) {
144 _requestWriter.state = GRXWriterStateFinished;
Jorge Canizales238ad782015-08-07 23:11:29 -0700145 }
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700146
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800147 if (errorOrNil) {
148 [_responseWriteable cancelWithError:errorOrNil];
149 } else {
150 [_responseWriteable enqueueSuccessfulCompletion];
151 }
152}
153
154- (void)cancelCall {
155 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700156 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800157}
158
159- (void)cancel {
160 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
161 code:GRPCErrorCodeCancelled
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700162 userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800163 [self cancelCall];
164}
165
166- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700167 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800168 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700169 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800170 });
171}
172
173#pragma mark Read messages
174
175// Only called from the call queue.
176// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700177- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700178 // TODO(jcanizales): Add error handlers for async failures
murgatroid9954e93d42015-04-27 09:29:49 -0700179 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800180}
181
182// Called initially from the network queue once response headers are received,
183// then "recursively" from the responseWriteable queue after each response from the
184// server has been written.
185// If the call is currently paused, this is a noop. Restarting the call will invoke this
186// method.
187// TODO(jcanizales): Rename to readResponseIfNotPaused.
188- (void)startNextRead {
189 if (self.state == GRXWriterStatePaused) {
190 return;
191 }
192 __weak GRPCCall *weakSelf = self;
Jorge Canizales35f003b2015-07-17 21:14:36 -0700193 __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700194
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800195 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700196 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
197 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700198 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800199 return;
200 }
murgatroid996cc46802015-04-28 09:35:48 -0700201 NSData *data = [NSData grpc_dataWithByteBuffer:message];
202 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800203 if (!data) {
204 // The app doesn't have enough memory to hold the server response. We
205 // don't want to throw, because the app shouldn't crash for a behavior
206 // that's on the hands of any server to have. Instead we finish and ask
207 // the server to cancel.
208 //
209 // TODO(jcanizales): No canonical code is appropriate for this situation
210 // (because it's just a client problem). Use another domain and an
211 // appropriately-documented code.
212 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
213 code:GRPCErrorCodeInternal
214 userInfo:nil]];
215 [weakSelf cancelCall];
216 return;
217 }
Jorge Canizales4c6f7782015-07-17 23:13:36 -0700218 [weakWriteable enqueueValue:data completionHandler:^{
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800219 [weakSelf startNextRead];
220 }];
221 }];
222 });
223}
224
225#pragma mark Send headers
226
Jorge Canizalesf4f150f2015-11-01 22:31:12 -0800227- (void)sendHeaders:(NSDictionary *)headers {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700228 // TODO(jcanizales): Add error handlers for async failures
Jorge Canizales5c339d12015-09-02 17:41:43 -0700229 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc] initWithMetadata:headers
230 handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800231}
232
233#pragma mark GRXWriteable implementation
234
235// Only called from the call queue. The error handler will be called from the
236// network queue if the write didn't succeed.
237- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
238
239 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700240 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700241 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800242 GRPCCall *strongSelf = weakSelf;
243 if (strongSelf) {
Jorge Canizales578ab162015-08-08 17:11:43 -0700244 @synchronized(strongSelf->_requestWriter) {
Jorge Canizales238ad782015-08-07 23:11:29 -0700245 strongSelf->_requestWriter.state = GRXWriterStateStarted;
246 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800247 }
248 };
Jorge Canizales238ad782015-08-07 23:11:29 -0700249 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc] initWithMessage:message
250 handler:resumingHandler]]
251 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800252}
253
Jorge Canizalesa90a9c32015-05-18 17:12:41 -0700254- (void)writeValue:(id)value {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800255 // TODO(jcanizales): Throw/assert if value isn't NSData.
256
257 // Pause the input and only resume it when the C layer notifies us that writes
258 // can proceed.
Jorge Canizales238ad782015-08-07 23:11:29 -0700259 @synchronized(_requestWriter) {
260 _requestWriter.state = GRXWriterStatePaused;
261 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800262
263 __weak GRPCCall *weakSelf = self;
264 dispatch_async(_callQueue, ^{
265 [weakSelf writeMessage:value withErrorHandler:^{
266 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
267 code:GRPCErrorCodeInternal
268 userInfo:nil]];
269 }];
270 });
271}
272
273// Only called from the call queue. The error handler will be called from the
274// network queue if the requests stream couldn't be closed successfully.
275- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700276 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
277 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800278}
279
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700280- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800281 if (errorOrNil) {
282 [self cancel];
283 } else {
284 __weak GRPCCall *weakSelf = self;
285 dispatch_async(_callQueue, ^{
286 [weakSelf finishRequestWithErrorHandler:^{
287 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
288 code:GRPCErrorCodeInternal
289 userInfo:nil]];
290 }];
291 });
292 }
293}
294
295#pragma mark Invoke
296
297// Both handlers will eventually be called, from the network queue. Writes can start immediately
298// after this.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700299// The first one (headersHandler), when the response headers are received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800300// The second one (completionHandler), whenever the RPC finishes for any reason.
Jorge Canizales0b34c892015-08-12 20:19:20 -0700301- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700302 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700303 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700304 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
Jorge Canizales0b34c892015-08-12 20:19:20 -0700305 initWithHandler:headersHandler]]];
murgatroid996cc46802015-04-28 09:35:48 -0700306 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
307 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800308}
309
310- (void)invokeCall {
Jorge Canizales0b34c892015-08-12 20:19:20 -0700311 [self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700312 // Response headers received.
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100313 self.responseHeaders = headers;
314 [self startNextRead];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700315 } completionHandler:^(NSError *error, NSDictionary *trailers) {
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100316 self.responseTrailers = trailers;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700317
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100318 if (error) {
319 NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
320 if (error.userInfo) {
321 [userInfo addEntriesFromDictionary:error.userInfo];
Jorge Canizalesc58a1102015-06-15 19:03:41 -0700322 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100323 userInfo[kGRPCTrailersKey] = self.responseTrailers;
324 // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be
325 // called before this one, so an error might end up with trailers but no headers. We
326 // shouldn't call finishWithError until ater both blocks are called. It is also when this is
327 // done that we can provide a merged view of response headers and trailers in a thread-safe
328 // way.
329 if (self.responseHeaders) {
330 userInfo[kGRPCHeadersKey] = self.responseHeaders;
331 }
332 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700333 }
Nicolas "Pixel" Noble70224362016-03-21 22:19:43 +0100334 [self finishWithError:error];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800335 }];
336 // Now that the RPC has been initiated, request writes can start.
Jorge Canizales238ad782015-08-07 23:11:29 -0700337 @synchronized(_requestWriter) {
338 [_requestWriter startWithWriteable:self];
339 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800340}
341
342#pragma mark GRXWriter implementation
343
344- (void)startWithWriteable:(id<GRXWriteable>)writeable {
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700345 // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
346 // This makes RPCs in which the call isn't externally retained possible (as long as it is started
347 // before being autoreleased).
348 // Care is taken not to retain self strongly in any of the blocks used in this implementation, so
349 // that the life of the instance is determined by this retain cycle.
Jorge Canizaleseb87b462015-08-08 16:16:43 -0700350 _retainSelf = self;
Jorge Canizales6531b2b2015-07-18 00:19:14 -0700351
352 _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700353
354 _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path];
355 NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?");
356
Jorge Canizales6512d262015-08-12 17:33:23 -0700357 [self sendHeaders:_requestHeaders];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800358 [self invokeCall];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700359 // TODO(jcanizales): Extract this logic somewhere common.
360 NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host;
361 if (!host) {
362 // TODO(jcanizales): Check this on init.
363 [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host];
364 }
365 __weak typeof(self) weakSelf = self;
366 _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host];
367 [_connectivityMonitor handleLossWithHandler:^{
368 typeof(self) strongSelf = weakSelf;
369 if (strongSelf) {
370 [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
371 code:GRPCErrorCodeUnavailable
372 userInfo:@{NSLocalizedDescriptionKey: @"Connectivity lost."}]];
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700373 }
374 }];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800375}
376
377- (void)setState:(GRXWriterState)newState {
378 // Manual transitions are only allowed from the started or paused states.
379 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
380 return;
381 }
382
383 switch (newState) {
384 case GRXWriterStateFinished:
385 _state = newState;
386 // Per GRXWriter's contract, setting the state to Finished manually
387 // means one doesn't wish the writeable to be messaged anymore.
388 [_responseWriteable cancelSilently];
389 _responseWriteable = nil;
390 return;
391 case GRXWriterStatePaused:
392 _state = newState;
393 return;
394 case GRXWriterStateStarted:
395 if (_state == GRXWriterStatePaused) {
396 _state = newState;
397 [self startNextRead];
398 }
399 return;
400 case GRXWriterStateNotStarted:
401 return;
402 }
403}
Jorge Canizalesf1d084a2015-10-30 11:14:09 -0700404
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800405@end