blob: 2186ea4242446ae57492edfff5833fdbb20a6cf7 [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>
37#include <grpc/support/grpc_time.h>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080038
39#import "GRPCMethodName.h"
40#import "private/GRPCChannel.h"
41#import "private/GRPCCompletionQueue.h"
42#import "private/GRPCDelegateWrapper.h"
43#import "private/GRPCMethodName+HTTP2Encoding.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
Jorge Canizales5e0efd92015-02-17 18:23:58 -080049@interface GRPCCall () <GRXWriteable>
50// Makes it readwrite.
51@property(atomic, strong) NSDictionary *responseMetadata;
52@end
53
54// The following methods of a C gRPC call object aren't reentrant, and thus
55// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070056// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080057// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080058//
murgatroid99b5c076f2015-04-27 17:25:36 -070059// start_batch with a SEND_MESSAGE argument can only be called after the
60// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080061// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070062// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080063//
murgatroid99b5c076f2015-04-27 17:25:36 -070064// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
65// the OP_COMPLETE event for any previous read is received.This is easier to
66// enforce, as we're writing the received messages into the writeable:
67// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
68// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
69// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080070@implementation GRPCCall {
71 dispatch_queue_t _callQueue;
72
murgatroid9930b7d4e2015-04-24 10:36:43 -070073 GRPCWrappedCall *_wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080074 dispatch_once_t _callAlreadyInvoked;
75
76 GRPCChannel *_channel;
77 GRPCCompletionQueue *_completionQueue;
78
79 // The C gRPC library has less guarantees on the ordering of events than we
80 // do. Particularly, in the face of errors, there's no ordering guarantee at
81 // all. This wrapper over our actual writeable ensures thread-safety and
82 // correct ordering.
83 GRPCDelegateWrapper *_responseWriteable;
84 id<GRXWriter> _requestWriter;
85}
86
87@synthesize state = _state;
88
89- (instancetype)init {
90 return [self initWithHost:nil method:nil requestsWriter:nil];
91}
92
93// Designated initializer
94- (instancetype)initWithHost:(NSString *)host
95 method:(GRPCMethodName *)method
96 requestsWriter:(id<GRXWriter>)requestWriter {
97 if (!host || !method) {
98 [NSException raise:NSInvalidArgumentException format:@"Neither host nor method can be nil."];
99 }
100 // TODO(jcanizales): Throw if the requestWriter was already started.
101 if ((self = [super init])) {
102 static dispatch_once_t initialization;
103 dispatch_once(&initialization, ^{
104 grpc_init();
105 });
106
107 _completionQueue = [GRPCCompletionQueue completionQueue];
108
109 _channel = [GRPCChannel channelToHost:host];
murgatroid9930b7d4e2015-04-24 10:36:43 -0700110
murgatroid996cc46802015-04-28 09:35:48 -0700111 _wrappedCall = [[GRPCWrappedCall alloc] initWithChannel:_channel
112 method:method.HTTP2Path
113 host:host];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800114
115 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
116 _callQueue = dispatch_queue_create("org.grpc.call", NULL);
117
118 _requestWriter = requestWriter;
119 }
120 return self;
121}
122
123#pragma mark Finish
124
125- (void)finishWithError:(NSError *)errorOrNil {
126 _requestWriter.state = GRXWriterStateFinished;
127 _requestWriter = nil;
128 if (errorOrNil) {
129 [_responseWriteable cancelWithError:errorOrNil];
130 } else {
131 [_responseWriteable enqueueSuccessfulCompletion];
132 }
133}
134
135- (void)cancelCall {
136 // Can be called from any thread, any number of times.
murgatroid9930b7d4e2015-04-24 10:36:43 -0700137 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800138}
139
140- (void)cancel {
141 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
142 code:GRPCErrorCodeCancelled
143 userInfo:nil]];
144 [self cancelCall];
145}
146
147- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700148 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800149 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700150 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800151 });
152}
153
154#pragma mark Read messages
155
156// Only called from the call queue.
157// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700158- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid9954e93d42015-04-27 09:29:49 -0700159 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800160}
161
162// Called initially from the network queue once response headers are received,
163// then "recursively" from the responseWriteable queue after each response from the
164// server has been written.
165// If the call is currently paused, this is a noop. Restarting the call will invoke this
166// method.
167// TODO(jcanizales): Rename to readResponseIfNotPaused.
168- (void)startNextRead {
169 if (self.state == GRXWriterStatePaused) {
170 return;
171 }
172 __weak GRPCCall *weakSelf = self;
173 __weak GRPCDelegateWrapper *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700174
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800175 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700176 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
177 if (message == NULL) {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800178 return;
179 }
murgatroid996cc46802015-04-28 09:35:48 -0700180 NSData *data = [NSData grpc_dataWithByteBuffer:message];
181 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800182 if (!data) {
183 // The app doesn't have enough memory to hold the server response. We
184 // don't want to throw, because the app shouldn't crash for a behavior
185 // that's on the hands of any server to have. Instead we finish and ask
186 // the server to cancel.
187 //
188 // TODO(jcanizales): No canonical code is appropriate for this situation
189 // (because it's just a client problem). Use another domain and an
190 // appropriately-documented code.
191 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
192 code:GRPCErrorCodeInternal
193 userInfo:nil]];
194 [weakSelf cancelCall];
195 return;
196 }
197 [weakWriteable enqueueMessage:data completionHandler:^{
198 [weakSelf startNextRead];
199 }];
200 }];
201 });
202}
203
204#pragma mark Send headers
205
murgatroid9969927d62015-04-24 13:32:48 -0700206// TODO(jcanizales): Rename to commitHeaders.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800207- (void)sendHeaders:(NSDictionary *)metadata {
murgatroid996cc46802015-04-28 09:35:48 -0700208 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc]
209 initWithMetadata:metadata ?: @{} handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800210}
211
212#pragma mark GRXWriteable implementation
213
214// Only called from the call queue. The error handler will be called from the
215// network queue if the write didn't succeed.
216- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
217
218 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700219 void(^resumingHandler)(void) = ^{
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800220 // Resume the request writer (even in the case of error).
221 // TODO(jcanizales): No need to do it in the case of errors anymore?
222 GRPCCall *strongSelf = weakSelf;
223 if (strongSelf) {
224 strongSelf->_requestWriter.state = GRXWriterStateStarted;
225 }
226 };
murgatroid996cc46802015-04-28 09:35:48 -0700227 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc]
228 initWithMessage:message
229 handler:resumingHandler]] errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800230}
231
232- (void)didReceiveValue:(id)value {
233 // TODO(jcanizales): Throw/assert if value isn't NSData.
234
235 // Pause the input and only resume it when the C layer notifies us that writes
236 // can proceed.
237 _requestWriter.state = GRXWriterStatePaused;
238
239 __weak GRPCCall *weakSelf = self;
240 dispatch_async(_callQueue, ^{
241 [weakSelf writeMessage:value withErrorHandler:^{
242 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
243 code:GRPCErrorCodeInternal
244 userInfo:nil]];
245 }];
246 });
247}
248
249// Only called from the call queue. The error handler will be called from the
250// network queue if the requests stream couldn't be closed successfully.
251- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700252 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
253 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800254}
255
256- (void)didFinishWithError:(NSError *)errorOrNil {
257 if (errorOrNil) {
258 [self cancel];
259 } else {
260 __weak GRPCCall *weakSelf = self;
261 dispatch_async(_callQueue, ^{
262 [weakSelf finishRequestWithErrorHandler:^{
263 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
264 code:GRPCErrorCodeInternal
265 userInfo:nil]];
266 }];
267 });
268 }
269}
270
271#pragma mark Invoke
272
273// Both handlers will eventually be called, from the network queue. Writes can start immediately
274// after this.
275// The first one (metadataHandler), when the response headers are received.
276// The second one (completionHandler), whenever the RPC finishes for any reason.
murgatroid9954e93d42015-04-27 09:29:49 -0700277- (void)invokeCallWithMetadataHandler:(void(^)(NSDictionary *))metadataHandler
278 completionHandler:(void(^)(NSError *))completionHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700279 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
280 initWithHandler:metadataHandler]]];
281 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
282 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800283}
284
285- (void)invokeCall {
286 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700287 [self invokeCallWithMetadataHandler:^(NSDictionary *metadata) {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800288 // Response metadata received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800289 GRPCCall *strongSelf = weakSelf;
290 if (strongSelf) {
murgatroid9954e93d42015-04-27 09:29:49 -0700291 strongSelf.responseMetadata = metadata;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800292 [strongSelf startNextRead];
293 }
murgatroid9954e93d42015-04-27 09:29:49 -0700294 } completionHandler:^(NSError *error) {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800295 // TODO(jcanizales): Merge HTTP2 trailers into response metadata.
murgatroid9930b7d4e2015-04-24 10:36:43 -0700296 [weakSelf finishWithError:error];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800297 }];
298 // Now that the RPC has been initiated, request writes can start.
299 [_requestWriter startWithWriteable:self];
300}
301
302#pragma mark GRXWriter implementation
303
304- (void)startWithWriteable:(id<GRXWriteable>)writeable {
305 // The following produces a retain cycle self:_responseWriteable:self, which is only
306 // broken when didFinishWithError: is sent to the wrapped writeable.
307 // Care is taken not to retain self strongly in any of the blocks used in
308 // the implementation of GRPCCall, so that the life of the instance is
309 // determined by this retain cycle.
310 _responseWriteable = [[GRPCDelegateWrapper alloc] initWithWriteable:writeable writer:self];
311 [self sendHeaders:_requestMetadata];
312 [self invokeCall];
313}
314
315- (void)setState:(GRXWriterState)newState {
316 // Manual transitions are only allowed from the started or paused states.
317 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
318 return;
319 }
320
321 switch (newState) {
322 case GRXWriterStateFinished:
323 _state = newState;
324 // Per GRXWriter's contract, setting the state to Finished manually
325 // means one doesn't wish the writeable to be messaged anymore.
326 [_responseWriteable cancelSilently];
327 _responseWriteable = nil;
328 return;
329 case GRXWriterStatePaused:
330 _state = newState;
331 return;
332 case GRXWriterStateStarted:
333 if (_state == GRXWriterStatePaused) {
334 _state = newState;
335 [self startNextRead];
336 }
337 return;
338 case GRXWriterStateNotStarted:
339 return;
340 }
341}
342@end