blob: 53e5abe177bae77d210547d6dc74b6cc63ddb312 [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 Canizales5e0efd92015-02-17 18:23:58 -080038
Jorge Canizales5e0efd92015-02-17 18:23:58 -080039#import "private/GRPCChannel.h"
40#import "private/GRPCCompletionQueue.h"
41#import "private/GRPCDelegateWrapper.h"
murgatroid9969927d62015-04-24 13:32:48 -070042#import "private/GRPCWrappedCall.h"
Jorge Canizales5e0efd92015-02-17 18:23:58 -080043#import "private/NSData+GRPC.h"
44#import "private/NSDictionary+GRPC.h"
45#import "private/NSError+GRPC.h"
46
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070047NSString * const kGRPCStatusMetadataKey = @"io.grpc.StatusMetadataKey";
48
Jorge Canizales5e0efd92015-02-17 18:23:58 -080049@interface GRPCCall () <GRXWriteable>
Jorge Canizales5e0efd92015-02-17 18:23:58 -080050@end
51
52// The following methods of a C gRPC call object aren't reentrant, and thus
53// calls to them must be serialized:
murgatroid99b5c076f2015-04-27 17:25:36 -070054// - start_batch
Jorge Canizales5e0efd92015-02-17 18:23:58 -080055// - destroy
Jorge Canizales5e0efd92015-02-17 18:23:58 -080056//
murgatroid99b5c076f2015-04-27 17:25:36 -070057// start_batch with a SEND_MESSAGE argument can only be called after the
58// OP_COMPLETE event for any previous write is received. This is achieved by
Jorge Canizales5e0efd92015-02-17 18:23:58 -080059// pausing the requests writer immediately every time it writes a value, and
murgatroid99b5c076f2015-04-27 17:25:36 -070060// resuming it again when OP_COMPLETE is received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080061//
murgatroid99b5c076f2015-04-27 17:25:36 -070062// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
63// the OP_COMPLETE event for any previous read is received.This is easier to
64// enforce, as we're writing the received messages into the writeable:
65// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
66// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
67// each RECV_MESSAGE batch.
Jorge Canizales5e0efd92015-02-17 18:23:58 -080068@implementation GRPCCall {
69 dispatch_queue_t _callQueue;
70
murgatroid9930b7d4e2015-04-24 10:36:43 -070071 GRPCWrappedCall *_wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080072 dispatch_once_t _callAlreadyInvoked;
73
74 GRPCChannel *_channel;
75 GRPCCompletionQueue *_completionQueue;
76
77 // The C gRPC library has less guarantees on the ordering of events than we
78 // do. Particularly, in the face of errors, there's no ordering guarantee at
79 // all. This wrapper over our actual writeable ensures thread-safety and
80 // correct ordering.
81 GRPCDelegateWrapper *_responseWriteable;
Jorge Canizales56047122015-07-17 12:18:08 -070082 GRXWriter *_requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -070083
84 NSMutableDictionary *_requestMetadata;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -070085 NSMutableDictionary *_responseMetadata;
Jorge Canizales5e0efd92015-02-17 18:23:58 -080086}
87
88@synthesize state = _state;
89
90- (instancetype)init {
Jorge Canizalesbe808e32015-07-04 14:37:58 -070091 return [self initWithHost:nil path:nil requestsWriter:nil];
Jorge Canizales5e0efd92015-02-17 18:23:58 -080092}
93
94// Designated initializer
95- (instancetype)initWithHost:(NSString *)host
Jorge Canizalesbe808e32015-07-04 14:37:58 -070096 path:(NSString *)path
Jorge Canizales56047122015-07-17 12:18:08 -070097 requestsWriter:(GRXWriter *)requestWriter {
Jorge Canizalesbe808e32015-07-04 14:37:58 -070098 if (!host || !path) {
Jorge Canizales5e0efd92015-02-17 18:23:58 -080099 [NSException raise:NSInvalidArgumentException format:@"Neither host nor method can be nil."];
100 }
Jorge Canizales6bbfcc32015-06-17 14:10:52 -0700101 if (requestWriter.state != GRXWriterStateNotStarted) {
102 [NSException raise:NSInvalidArgumentException format:@"The requests writer can't be already started."];
103 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800104 if ((self = [super init])) {
105 static dispatch_once_t initialization;
106 dispatch_once(&initialization, ^{
107 grpc_init();
108 });
109
110 _completionQueue = [GRPCCompletionQueue completionQueue];
111
112 _channel = [GRPCChannel channelToHost:host];
murgatroid99b56609c2015-04-28 16:41:11 -0700113
114 _wrappedCall = [[GRPCWrappedCall alloc] initWithChannel:_channel
Jorge Canizalesbe808e32015-07-04 14:37:58 -0700115 path:path
murgatroid99b56609c2015-04-28 16:41:11 -0700116 host:host];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800117
118 // Serial queue to invoke the non-reentrant methods of the grpc_call object.
119 _callQueue = dispatch_queue_create("org.grpc.call", NULL);
120
121 _requestWriter = requestWriter;
Jorge Canizales544963e2015-06-12 19:46:27 -0700122
123 _requestMetadata = [NSMutableDictionary dictionary];
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700124 _responseMetadata = [NSMutableDictionary dictionary];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800125 }
126 return self;
127}
128
Jorge Canizales544963e2015-06-12 19:46:27 -0700129#pragma mark Metadata
130
131- (NSMutableDictionary *)requestMetadata {
132 return _requestMetadata;
133}
134
135- (void)setRequestMetadata:(NSDictionary *)requestMetadata {
136 _requestMetadata = [NSMutableDictionary dictionaryWithDictionary:requestMetadata];
137}
138
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700139- (NSDictionary *)responseMetadata {
140 return _responseMetadata;
141}
142
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800143#pragma mark Finish
144
145- (void)finishWithError:(NSError *)errorOrNil {
146 _requestWriter.state = GRXWriterStateFinished;
147 _requestWriter = nil;
148 if (errorOrNil) {
149 [_responseWriteable cancelWithError:errorOrNil];
150 } else {
151 [_responseWriteable enqueueSuccessfulCompletion];
152 }
153}
154
155- (void)cancelCall {
156 // Can be called from any thread, any number of times.
murgatroid99b56609c2015-04-28 16:41:11 -0700157 [_wrappedCall cancel];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800158}
159
160- (void)cancel {
161 [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
162 code:GRPCErrorCodeCancelled
163 userInfo:nil]];
164 [self cancelCall];
165}
166
167- (void)dealloc {
murgatroid996cc46802015-04-28 09:35:48 -0700168 __block GRPCWrappedCall *wrappedCall = _wrappedCall;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800169 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700170 wrappedCall = nil;
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800171 });
172}
173
174#pragma mark Read messages
175
176// Only called from the call queue.
177// The handler will be called from the network queue.
murgatroid996cc46802015-04-28 09:35:48 -0700178- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700179 // TODO(jcanizales): Add error handlers for async failures
murgatroid9954e93d42015-04-27 09:29:49 -0700180 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800181}
182
183// Called initially from the network queue once response headers are received,
184// then "recursively" from the responseWriteable queue after each response from the
185// server has been written.
186// If the call is currently paused, this is a noop. Restarting the call will invoke this
187// method.
188// TODO(jcanizales): Rename to readResponseIfNotPaused.
189- (void)startNextRead {
190 if (self.state == GRXWriterStatePaused) {
191 return;
192 }
193 __weak GRPCCall *weakSelf = self;
194 __weak GRPCDelegateWrapper *weakWriteable = _responseWriteable;
murgatroid9969927d62015-04-24 13:32:48 -0700195
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800196 dispatch_async(_callQueue, ^{
murgatroid996cc46802015-04-28 09:35:48 -0700197 [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) {
198 if (message == NULL) {
murgatroid99b56609c2015-04-28 16:41:11 -0700199 // No more messages from the server
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800200 return;
201 }
murgatroid996cc46802015-04-28 09:35:48 -0700202 NSData *data = [NSData grpc_dataWithByteBuffer:message];
203 grpc_byte_buffer_destroy(message);
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800204 if (!data) {
205 // The app doesn't have enough memory to hold the server response. We
206 // don't want to throw, because the app shouldn't crash for a behavior
207 // that's on the hands of any server to have. Instead we finish and ask
208 // the server to cancel.
209 //
210 // TODO(jcanizales): No canonical code is appropriate for this situation
211 // (because it's just a client problem). Use another domain and an
212 // appropriately-documented code.
213 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
214 code:GRPCErrorCodeInternal
215 userInfo:nil]];
216 [weakSelf cancelCall];
217 return;
218 }
219 [weakWriteable enqueueMessage:data completionHandler:^{
220 [weakSelf startNextRead];
221 }];
222 }];
223 });
224}
225
226#pragma mark Send headers
227
murgatroid9969927d62015-04-24 13:32:48 -0700228// TODO(jcanizales): Rename to commitHeaders.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800229- (void)sendHeaders:(NSDictionary *)metadata {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700230 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700231 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc]
232 initWithMetadata:metadata ?: @{} handler:nil]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800233}
234
235#pragma mark GRXWriteable implementation
236
237// Only called from the call queue. The error handler will be called from the
238// network queue if the write didn't succeed.
239- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler {
240
241 __weak GRPCCall *weakSelf = self;
murgatroid9954e93d42015-04-27 09:29:49 -0700242 void(^resumingHandler)(void) = ^{
murgatroid99ca38ddb2015-04-29 13:16:42 -0700243 // Resume the request writer.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800244 GRPCCall *strongSelf = weakSelf;
245 if (strongSelf) {
246 strongSelf->_requestWriter.state = GRXWriterStateStarted;
247 }
248 };
murgatroid996cc46802015-04-28 09:35:48 -0700249 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc]
250 initWithMessage:message
251 handler:resumingHandler]] 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.
259 _requestWriter.state = GRXWriterStatePaused;
260
261 __weak GRPCCall *weakSelf = self;
262 dispatch_async(_callQueue, ^{
263 [weakSelf writeMessage:value withErrorHandler:^{
264 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
265 code:GRPCErrorCodeInternal
266 userInfo:nil]];
267 }];
268 });
269}
270
271// Only called from the call queue. The error handler will be called from the
272// network queue if the requests stream couldn't be closed successfully.
273- (void)finishRequestWithErrorHandler:(void (^)())errorHandler {
murgatroid996cc46802015-04-28 09:35:48 -0700274 [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]]
275 errorHandler:errorHandler];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800276}
277
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700278- (void)writesFinishedWithError:(NSError *)errorOrNil {
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800279 if (errorOrNil) {
280 [self cancel];
281 } else {
282 __weak GRPCCall *weakSelf = self;
283 dispatch_async(_callQueue, ^{
284 [weakSelf finishRequestWithErrorHandler:^{
285 [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
286 code:GRPCErrorCodeInternal
287 userInfo:nil]];
288 }];
289 });
290 }
291}
292
293#pragma mark Invoke
294
295// Both handlers will eventually be called, from the network queue. Writes can start immediately
296// after this.
297// The first one (metadataHandler), when the response headers are received.
298// The second one (completionHandler), whenever the RPC finishes for any reason.
murgatroid9954e93d42015-04-27 09:29:49 -0700299- (void)invokeCallWithMetadataHandler:(void(^)(NSDictionary *))metadataHandler
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700300 completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler {
murgatroid99ca38ddb2015-04-29 13:16:42 -0700301 // TODO(jcanizales): Add error handlers for async failures
murgatroid996cc46802015-04-28 09:35:48 -0700302 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc]
303 initWithHandler:metadataHandler]]];
304 [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc]
305 initWithHandler:completionHandler]]];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800306}
307
308- (void)invokeCall {
309 __weak GRPCCall *weakSelf = self;
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700310 [self invokeCallWithMetadataHandler:^(NSDictionary *headers) {
311 // Response headers received.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800312 GRPCCall *strongSelf = weakSelf;
313 if (strongSelf) {
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700314 [strongSelf->_responseMetadata addEntriesFromDictionary:headers];
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800315 [strongSelf startNextRead];
316 }
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700317 } completionHandler:^(NSError *error, NSDictionary *trailers) {
318 GRPCCall *strongSelf = weakSelf;
319 if (strongSelf) {
320 [strongSelf->_responseMetadata addEntriesFromDictionary:trailers];
321
Jorge Canizalesc58a1102015-06-15 19:03:41 -0700322 if (error) {
323 NSMutableDictionary *userInfo =
324 [NSMutableDictionary dictionaryWithDictionary:error.userInfo];
325 userInfo[kGRPCStatusMetadataKey] = strongSelf->_responseMetadata;
326 error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
327 }
Jorge Canizalesf3a4f2c2015-06-12 22:12:50 -0700328 [strongSelf finishWithError:error];
329 }
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800330 }];
331 // Now that the RPC has been initiated, request writes can start.
332 [_requestWriter startWithWriteable:self];
333}
334
335#pragma mark GRXWriter implementation
336
337- (void)startWithWriteable:(id<GRXWriteable>)writeable {
338 // The following produces a retain cycle self:_responseWriteable:self, which is only
Jorge Canizalesb2c300c2015-05-18 17:19:16 -0700339 // broken when writesFinishedWithError: is sent to the wrapped writeable.
Jorge Canizales5e0efd92015-02-17 18:23:58 -0800340 // Care is taken not to retain self strongly in any of the blocks used in
341 // the implementation of GRPCCall, so that the life of the instance is
342 // determined by this retain cycle.
343 _responseWriteable = [[GRPCDelegateWrapper alloc] initWithWriteable:writeable writer:self];
344 [self sendHeaders:_requestMetadata];
345 [self invokeCall];
346}
347
348- (void)setState:(GRXWriterState)newState {
349 // Manual transitions are only allowed from the started or paused states.
350 if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
351 return;
352 }
353
354 switch (newState) {
355 case GRXWriterStateFinished:
356 _state = newState;
357 // Per GRXWriter's contract, setting the state to Finished manually
358 // means one doesn't wish the writeable to be messaged anymore.
359 [_responseWriteable cancelSilently];
360 _responseWriteable = nil;
361 return;
362 case GRXWriterStatePaused:
363 _state = newState;
364 return;
365 case GRXWriterStateStarted:
366 if (_state == GRXWriterStatePaused) {
367 _state = newState;
368 [self startNextRead];
369 }
370 return;
371 case GRXWriterStateNotStarted:
372 return;
373 }
374}
375@end