Jorge Canizales | 9409ad8 | 2015-02-18 16:19:56 -0800 | [diff] [blame] | 1 | /* |
| 2 | * |
Craig Tiller | 6169d5f | 2016-03-31 07:46:18 -0700 | [diff] [blame] | 3 | * Copyright 2015, Google Inc. |
Jorge Canizales | 9409ad8 | 2015-02-18 16:19:56 -0800 | [diff] [blame] | 4 | * 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 Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 34 | #import "GRPCCall.h" |
| 35 | |
Jorge Canizales | c2d7ecb | 2015-02-27 01:22:41 -0800 | [diff] [blame] | 36 | #include <grpc/grpc.h> |
Jorge Canizales | 59bb9d7 | 2015-06-22 19:04:15 -0700 | [diff] [blame] | 37 | #include <grpc/support/time.h> |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 38 | #import <RxLibrary/GRXConcurrentWriteable.h> |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 39 | #import <RxLibrary/GRXImmediateSingleWriter.h> |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 40 | |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 41 | #import "private/GRPCConnectivityMonitor.h" |
| 42 | #import "private/GRPCHost.h" |
Jorge Canizales | 2f10127 | 2015-09-02 21:55:37 -0700 | [diff] [blame] | 43 | #import "private/GRPCRequestHeaders.h" |
murgatroid99 | 69927d6 | 2015-04-24 13:32:48 -0700 | [diff] [blame] | 44 | #import "private/GRPCWrappedCall.h" |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 45 | #import "private/NSData+GRPC.h" |
| 46 | #import "private/NSDictionary+GRPC.h" |
| 47 | #import "private/NSError+GRPC.h" |
| 48 | |
Muxi Yan | 016d108 | 2017-03-07 18:26:42 -0800 | [diff] [blame] | 49 | // At most 6 ops can be in an op batch for a client: SEND_INITIAL_METADATA, |
| 50 | // SEND_MESSAGE, SEND_CLOSE_FROM_CLIENT, RECV_INITIAL_METADATA, RECV_MESSAGE, |
| 51 | // and RECV_STATUS_ON_CLIENT. |
| 52 | NSInteger kMaxClientBatch = 6; |
| 53 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 54 | NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey"; |
| 55 | NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey"; |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 56 | static NSMutableDictionary *callFlags; |
Jorge Canizales | f3a4f2c | 2015-06-12 22:12:50 -0700 | [diff] [blame] | 57 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 58 | @interface GRPCCall () <GRXWriteable> |
Jorge Canizales | 0b34c89 | 2015-08-12 20:19:20 -0700 | [diff] [blame] | 59 | // Make them read-write. |
| 60 | @property(atomic, strong) NSDictionary *responseHeaders; |
| 61 | @property(atomic, strong) NSDictionary *responseTrailers; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 62 | @end |
| 63 | |
| 64 | // The following methods of a C gRPC call object aren't reentrant, and thus |
| 65 | // calls to them must be serialized: |
murgatroid99 | b5c076f | 2015-04-27 17:25:36 -0700 | [diff] [blame] | 66 | // - start_batch |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 67 | // - destroy |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 68 | // |
murgatroid99 | b5c076f | 2015-04-27 17:25:36 -0700 | [diff] [blame] | 69 | // start_batch with a SEND_MESSAGE argument can only be called after the |
| 70 | // OP_COMPLETE event for any previous write is received. This is achieved by |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 71 | // pausing the requests writer immediately every time it writes a value, and |
murgatroid99 | b5c076f | 2015-04-27 17:25:36 -0700 | [diff] [blame] | 72 | // resuming it again when OP_COMPLETE is received. |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 73 | // |
murgatroid99 | b5c076f | 2015-04-27 17:25:36 -0700 | [diff] [blame] | 74 | // Similarly, start_batch with a RECV_MESSAGE argument can only be called after |
| 75 | // the OP_COMPLETE event for any previous read is received.This is easier to |
| 76 | // enforce, as we're writing the received messages into the writeable: |
| 77 | // start_batch is enqueued once upon receiving the OP_COMPLETE event for the |
| 78 | // RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for |
| 79 | // each RECV_MESSAGE batch. |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 80 | @implementation GRPCCall { |
| 81 | dispatch_queue_t _callQueue; |
| 82 | |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 83 | NSString *_host; |
| 84 | NSString *_path; |
murgatroid99 | 30b7d4e | 2015-04-24 10:36:43 -0700 | [diff] [blame] | 85 | GRPCWrappedCall *_wrappedCall; |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 86 | GRPCConnectivityMonitor *_connectivityMonitor; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 87 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 88 | // The C gRPC library has less guarantees on the ordering of events than we |
| 89 | // do. Particularly, in the face of errors, there's no ordering guarantee at |
| 90 | // all. This wrapper over our actual writeable ensures thread-safety and |
| 91 | // correct ordering. |
Jorge Canizales | 35f003b | 2015-07-17 21:14:36 -0700 | [diff] [blame] | 92 | GRXConcurrentWriteable *_responseWriteable; |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 93 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 94 | // The network thread wants the requestWriter to resume (when the server is ready for more input), |
| 95 | // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop |
| 96 | // it. Because a writer isn't thread-safe, we'll synchronize those operations on it. |
| 97 | // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or |
| 98 | // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to |
| 99 | // pause the writer immediately on writeValue:, so we need our locking to be recursive. |
Jorge Canizales | 5604712 | 2015-07-17 12:18:08 -0700 | [diff] [blame] | 100 | GRXWriter *_requestWriter; |
Jorge Canizales | 544963e | 2015-06-12 19:46:27 -0700 | [diff] [blame] | 101 | |
Jorge Canizales | 6531b2b | 2015-07-18 00:19:14 -0700 | [diff] [blame] | 102 | // To create a retain cycle when a call is started, up until it finishes. See |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 103 | // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a |
| 104 | // reference to the call object if all they're interested in is the handler being executed when |
Jorge Canizales | eb87b46 | 2015-08-08 16:16:43 -0700 | [diff] [blame] | 105 | // the response arrives. |
| 106 | GRPCCall *_retainSelf; |
Jorge Canizales | 6531b2b | 2015-07-18 00:19:14 -0700 | [diff] [blame] | 107 | |
murgatroid99 | 84fa531 | 2015-08-28 10:55:55 -0700 | [diff] [blame] | 108 | GRPCRequestHeaders *_requestHeaders; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 109 | |
Muxi Yan | c2e53b5 | 2017-03-22 14:30:16 -0700 | [diff] [blame] | 110 | // In the case that the call is a unary call (i.e. the writer to GRPCCall is of type |
| 111 | // GRXImmediateSingleWriter), GRPCCall will delay sending ops (not send them to C core |
| 112 | // immediately) and buffer them into a batch _unaryOpBatch. The batch is sent to C core when |
| 113 | // the SendClose op is added. |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 114 | BOOL _unaryCall; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 115 | NSMutableArray *_unaryOpBatch; |
Muxi Yan | 895f3d8 | 2017-04-05 13:12:30 -0700 | [diff] [blame] | 116 | |
| 117 | // The dispatch queue to be used for enqueuing responses to user. Defaulted to the main dispatch |
| 118 | // queue |
| 119 | dispatch_queue_t _responseQueue; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 120 | } |
| 121 | |
| 122 | @synthesize state = _state; |
| 123 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 124 | // TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize. |
Jorge Canizales | 7603d64 | 2016-08-24 18:23:24 -0700 | [diff] [blame] | 125 | + (void)load { |
| 126 | grpc_init(); |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 127 | callFlags = [NSMutableDictionary dictionary]; |
| 128 | } |
| 129 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 130 | + (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path { |
Muxi Yan | 6c0b960 | 2016-10-02 14:32:06 -0700 | [diff] [blame] | 131 | NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path]; |
| 132 | switch (callSafety) { |
| 133 | case GRPCCallSafetyDefault: |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 134 | callFlags[hostAndPath] = @0; |
| 135 | break; |
Muxi Yan | 6c0b960 | 2016-10-02 14:32:06 -0700 | [diff] [blame] | 136 | case GRPCCallSafetyIdempotentRequest: |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 137 | callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST; |
| 138 | break; |
Muxi Yan | 6c0b960 | 2016-10-02 14:32:06 -0700 | [diff] [blame] | 139 | case GRPCCallSafetyCacheableRequest: |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 140 | callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST; |
| 141 | break; |
| 142 | default: |
| 143 | break; |
| 144 | } |
| 145 | } |
| 146 | |
Muxi Yan | 6c0b960 | 2016-10-02 14:32:06 -0700 | [diff] [blame] | 147 | + (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path { |
| 148 | NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path]; |
| 149 | return [callFlags[hostAndPath] intValue]; |
Jorge Canizales | 7603d64 | 2016-08-24 18:23:24 -0700 | [diff] [blame] | 150 | } |
| 151 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 152 | - (instancetype)init { |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 153 | return [self initWithHost:nil path:nil requestsWriter:nil]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 154 | } |
| 155 | |
| 156 | // Designated initializer |
| 157 | - (instancetype)initWithHost:(NSString *)host |
Jorge Canizales | be808e3 | 2015-07-04 14:37:58 -0700 | [diff] [blame] | 158 | path:(NSString *)path |
Muxi Yan | 22f7973 | 2016-09-30 14:24:56 -0700 | [diff] [blame] | 159 | requestsWriter:(GRXWriter *)requestWriter { |
Jorge Canizales | be808e3 | 2015-07-04 14:37:58 -0700 | [diff] [blame] | 160 | if (!host || !path) { |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 161 | [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 162 | } |
Jorge Canizales | 6bbfcc3 | 2015-06-17 14:10:52 -0700 | [diff] [blame] | 163 | if (requestWriter.state != GRXWriterStateNotStarted) { |
Jorge Canizales | 597ef98 | 2015-07-31 23:31:56 -0700 | [diff] [blame] | 164 | [NSException raise:NSInvalidArgumentException |
| 165 | format:@"The requests writer can't be already started."]; |
Jorge Canizales | 6bbfcc3 | 2015-06-17 14:10:52 -0700 | [diff] [blame] | 166 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 167 | if ((self = [super init])) { |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 168 | _host = [host copy]; |
| 169 | _path = [path copy]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 170 | |
| 171 | // Serial queue to invoke the non-reentrant methods of the grpc_call object. |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 172 | _callQueue = dispatch_queue_create("io.grpc.call", NULL); |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 173 | |
| 174 | _requestWriter = requestWriter; |
Jorge Canizales | 544963e | 2015-06-12 19:46:27 -0700 | [diff] [blame] | 175 | |
murgatroid99 | 84fa531 | 2015-08-28 10:55:55 -0700 | [diff] [blame] | 176 | _requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 177 | |
| 178 | if ([requestWriter isKindOfClass:[GRXImmediateSingleWriter class]]) { |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 179 | _unaryCall = YES; |
Muxi Yan | 016d108 | 2017-03-07 18:26:42 -0800 | [diff] [blame] | 180 | _unaryOpBatch = [NSMutableArray arrayWithCapacity:kMaxClientBatch]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 181 | } |
Muxi Yan | 895f3d8 | 2017-04-05 13:12:30 -0700 | [diff] [blame] | 182 | |
| 183 | _responseQueue = dispatch_get_main_queue(); |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 184 | } |
| 185 | return self; |
| 186 | } |
| 187 | |
Muxi Yan | 895f3d8 | 2017-04-05 13:12:30 -0700 | [diff] [blame] | 188 | - (void)setResponseDispatchQueue:(dispatch_queue_t)queue { |
| 189 | if (_state != GRXWriterStateNotStarted) { |
| 190 | return; |
| 191 | } |
| 192 | _responseQueue = queue; |
| 193 | } |
| 194 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 195 | #pragma mark Finish |
| 196 | |
| 197 | - (void)finishWithError:(NSError *)errorOrNil { |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 198 | @synchronized(self) { |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 199 | if (_state == GRXWriterStateFinished) { |
| 200 | return; |
| 201 | } |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 202 | _state = GRXWriterStateFinished; |
| 203 | } |
| 204 | |
Jorge Canizales | 6531b2b | 2015-07-18 00:19:14 -0700 | [diff] [blame] | 205 | // If the call isn't retained anywhere else, it can be deallocated now. |
Jorge Canizales | eb87b46 | 2015-08-08 16:16:43 -0700 | [diff] [blame] | 206 | _retainSelf = nil; |
Jorge Canizales | 6531b2b | 2015-07-18 00:19:14 -0700 | [diff] [blame] | 207 | |
| 208 | // If there were still request messages coming, stop them. |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 209 | @synchronized(_requestWriter) { |
| 210 | _requestWriter.state = GRXWriterStateFinished; |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 211 | } |
Jorge Canizales | 6531b2b | 2015-07-18 00:19:14 -0700 | [diff] [blame] | 212 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 213 | if (errorOrNil) { |
| 214 | [_responseWriteable cancelWithError:errorOrNil]; |
| 215 | } else { |
| 216 | [_responseWriteable enqueueSuccessfulCompletion]; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | - (void)cancelCall { |
| 221 | // Can be called from any thread, any number of times. |
murgatroid99 | b56609c | 2015-04-28 16:41:11 -0700 | [diff] [blame] | 222 | [_wrappedCall cancel]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 223 | } |
| 224 | |
| 225 | - (void)cancel { |
| 226 | [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain |
| 227 | code:GRPCErrorCodeCancelled |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 228 | userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 229 | [self cancelCall]; |
| 230 | } |
| 231 | |
| 232 | - (void)dealloc { |
murgatroid99 | 6cc4680 | 2015-04-28 09:35:48 -0700 | [diff] [blame] | 233 | __block GRPCWrappedCall *wrappedCall = _wrappedCall; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 234 | dispatch_async(_callQueue, ^{ |
murgatroid99 | 6cc4680 | 2015-04-28 09:35:48 -0700 | [diff] [blame] | 235 | wrappedCall = nil; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 236 | }); |
| 237 | } |
| 238 | |
| 239 | #pragma mark Read messages |
| 240 | |
| 241 | // Only called from the call queue. |
| 242 | // The handler will be called from the network queue. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 243 | - (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler { |
murgatroid99 | ca38ddb | 2015-04-29 13:16:42 -0700 | [diff] [blame] | 244 | // TODO(jcanizales): Add error handlers for async failures |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 245 | [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 246 | } |
| 247 | |
| 248 | // Called initially from the network queue once response headers are received, |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 249 | // then "recursively" from the responseWriteable queue after each response from the |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 250 | // server has been written. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 251 | // If the call is currently paused, this is a noop. Restarting the call will invoke this |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 252 | // method. |
| 253 | // TODO(jcanizales): Rename to readResponseIfNotPaused. |
| 254 | - (void)startNextRead { |
| 255 | if (self.state == GRXWriterStatePaused) { |
| 256 | return; |
| 257 | } |
| 258 | __weak GRPCCall *weakSelf = self; |
Jorge Canizales | 35f003b | 2015-07-17 21:14:36 -0700 | [diff] [blame] | 259 | __weak GRXConcurrentWriteable *weakWriteable = _responseWriteable; |
murgatroid99 | 69927d6 | 2015-04-24 13:32:48 -0700 | [diff] [blame] | 260 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 261 | dispatch_async(_callQueue, ^{ |
murgatroid99 | 6cc4680 | 2015-04-28 09:35:48 -0700 | [diff] [blame] | 262 | [weakSelf startReadWithHandler:^(grpc_byte_buffer *message) { |
| 263 | if (message == NULL) { |
murgatroid99 | b56609c | 2015-04-28 16:41:11 -0700 | [diff] [blame] | 264 | // No more messages from the server |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 265 | return; |
| 266 | } |
murgatroid99 | 6cc4680 | 2015-04-28 09:35:48 -0700 | [diff] [blame] | 267 | NSData *data = [NSData grpc_dataWithByteBuffer:message]; |
| 268 | grpc_byte_buffer_destroy(message); |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 269 | if (!data) { |
| 270 | // The app doesn't have enough memory to hold the server response. We |
| 271 | // don't want to throw, because the app shouldn't crash for a behavior |
| 272 | // that's on the hands of any server to have. Instead we finish and ask |
| 273 | // the server to cancel. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 274 | [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain |
| 275 | code:GRPCErrorCodeResourceExhausted |
| 276 | userInfo:@{NSLocalizedDescriptionKey: @"Client does not have enough memory to hold the server response."}]]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 277 | [weakSelf cancelCall]; |
| 278 | return; |
| 279 | } |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 280 | [weakWriteable enqueueValue:data completionHandler:^{ |
| 281 | [weakSelf startNextRead]; |
| 282 | }]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 283 | }]; |
| 284 | }); |
| 285 | } |
| 286 | |
| 287 | #pragma mark Send headers |
| 288 | |
Jorge Canizales | f4f150f | 2015-11-01 22:31:12 -0800 | [diff] [blame] | 289 | - (void)sendHeaders:(NSDictionary *)headers { |
murgatroid99 | ca38ddb | 2015-04-29 13:16:42 -0700 | [diff] [blame] | 290 | // TODO(jcanizales): Add error handlers for async failures |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 291 | GRPCOpSendMetadata *op = [[GRPCOpSendMetadata alloc] initWithMetadata:headers |
| 292 | flags:[GRPCCall callFlagsForHost:_host path:_path] |
Muxi Yan | d5bac0d | 2017-03-07 18:44:19 -0800 | [diff] [blame] | 293 | handler:nil]; // No clean-up needed after SEND_INITIAL_METADATA |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 294 | if (!_unaryCall) { |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 295 | [_wrappedCall startBatchWithOperations:@[op]]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 296 | } else { |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 297 | [_unaryOpBatch addObject:op]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 298 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 299 | } |
| 300 | |
| 301 | #pragma mark GRXWriteable implementation |
| 302 | |
| 303 | // Only called from the call queue. The error handler will be called from the |
| 304 | // network queue if the write didn't succeed. |
Muxi Yan | 3565301 | 2017-03-07 18:54:24 -0800 | [diff] [blame] | 305 | // If the call is a unary call, parameter \a errorHandler will be ignored and |
| 306 | // the error handler of GRPCOpSendClose will be executed in case of error. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 307 | - (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler { |
| 308 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 309 | __weak GRPCCall *weakSelf = self; |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 310 | void(^resumingHandler)(void) = ^{ |
murgatroid99 | ca38ddb | 2015-04-29 13:16:42 -0700 | [diff] [blame] | 311 | // Resume the request writer. |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 312 | GRPCCall *strongSelf = weakSelf; |
| 313 | if (strongSelf) { |
Jorge Canizales | 578ab16 | 2015-08-08 17:11:43 -0700 | [diff] [blame] | 314 | @synchronized(strongSelf->_requestWriter) { |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 315 | strongSelf->_requestWriter.state = GRXWriterStateStarted; |
| 316 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 317 | } |
| 318 | }; |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 319 | |
| 320 | GRPCOpSendMessage *op = [[GRPCOpSendMessage alloc] initWithMessage:message |
| 321 | handler:resumingHandler]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 322 | if (!_unaryCall) { |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 323 | [_wrappedCall startBatchWithOperations:@[op] |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 324 | errorHandler:errorHandler]; |
| 325 | } else { |
Muxi Yan | 44e1837 | 2017-03-10 14:52:51 -0800 | [diff] [blame] | 326 | // Ignored errorHandler since it is the same as the one for GRPCOpSendClose. |
| 327 | // TODO (mxyan): unify the error handlers of all Ops into a single closure. |
Muxi Yan | bf803b9 | 2017-02-08 11:31:26 -0800 | [diff] [blame] | 328 | [_unaryOpBatch addObject:op]; |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 329 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 330 | } |
| 331 | |
Jorge Canizales | a90a9c3 | 2015-05-18 17:12:41 -0700 | [diff] [blame] | 332 | - (void)writeValue:(id)value { |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 333 | // TODO(jcanizales): Throw/assert if value isn't NSData. |
| 334 | |
| 335 | // Pause the input and only resume it when the C layer notifies us that writes |
| 336 | // can proceed. |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 337 | @synchronized(_requestWriter) { |
| 338 | _requestWriter.state = GRXWriterStatePaused; |
| 339 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 340 | |
| 341 | __weak GRPCCall *weakSelf = self; |
| 342 | dispatch_async(_callQueue, ^{ |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 343 | [weakSelf writeMessage:value withErrorHandler:^{ |
| 344 | [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 345 | code:GRPCErrorCodeInternal |
| 346 | userInfo:nil]]; |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 347 | }]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 348 | }); |
| 349 | } |
| 350 | |
| 351 | // Only called from the call queue. The error handler will be called from the |
| 352 | // network queue if the requests stream couldn't be closed successfully. |
| 353 | - (void)finishRequestWithErrorHandler:(void (^)())errorHandler { |
Muxi Yan | d5bac0d | 2017-03-07 18:44:19 -0800 | [diff] [blame] | 354 | if (!_unaryCall) { |
Muxi Yan | a40ccd8 | 2016-11-05 21:39:44 -0700 | [diff] [blame] | 355 | [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]] |
| 356 | errorHandler:errorHandler]; |
| 357 | } else { |
| 358 | [_unaryOpBatch addObject:[[GRPCOpSendClose alloc] init]]; |
| 359 | [_wrappedCall startBatchWithOperations:_unaryOpBatch |
| 360 | errorHandler:errorHandler]; |
| 361 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 362 | } |
| 363 | |
Jorge Canizales | b2c300c | 2015-05-18 17:19:16 -0700 | [diff] [blame] | 364 | - (void)writesFinishedWithError:(NSError *)errorOrNil { |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 365 | if (errorOrNil) { |
| 366 | [self cancel]; |
| 367 | } else { |
| 368 | __weak GRPCCall *weakSelf = self; |
| 369 | dispatch_async(_callQueue, ^{ |
| 370 | [weakSelf finishRequestWithErrorHandler:^{ |
| 371 | [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain |
| 372 | code:GRPCErrorCodeInternal |
| 373 | userInfo:nil]]; |
| 374 | }]; |
| 375 | }); |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | #pragma mark Invoke |
| 380 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 381 | // Both handlers will eventually be called, from the network queue. Writes can start immediately |
| 382 | // after this. |
Jorge Canizales | 0b34c89 | 2015-08-12 20:19:20 -0700 | [diff] [blame] | 383 | // The first one (headersHandler), when the response headers are received. |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 384 | // The second one (completionHandler), whenever the RPC finishes for any reason. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 385 | - (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler |
| 386 | completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler { |
murgatroid99 | ca38ddb | 2015-04-29 13:16:42 -0700 | [diff] [blame] | 387 | // TODO(jcanizales): Add error handlers for async failures |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 388 | [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc] |
| 389 | initWithHandler:headersHandler]]]; |
| 390 | [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc] |
| 391 | initWithHandler:completionHandler]]]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 392 | } |
| 393 | |
| 394 | - (void)invokeCall { |
Jorge Canizales | 0b34c89 | 2015-08-12 20:19:20 -0700 | [diff] [blame] | 395 | [self invokeCallWithHeadersHandler:^(NSDictionary *headers) { |
Jorge Canizales | f3a4f2c | 2015-06-12 22:12:50 -0700 | [diff] [blame] | 396 | // Response headers received. |
Nicolas "Pixel" Noble | 7022436 | 2016-03-21 22:19:43 +0100 | [diff] [blame] | 397 | self.responseHeaders = headers; |
| 398 | [self startNextRead]; |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 399 | } completionHandler:^(NSError *error, NSDictionary *trailers) { |
| 400 | self.responseTrailers = trailers; |
Jorge Canizales | f3a4f2c | 2015-06-12 22:12:50 -0700 | [diff] [blame] | 401 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 402 | if (error) { |
| 403 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; |
| 404 | if (error.userInfo) { |
| 405 | [userInfo addEntriesFromDictionary:error.userInfo]; |
| 406 | } |
| 407 | userInfo[kGRPCTrailersKey] = self.responseTrailers; |
| 408 | // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be |
| 409 | // called before this one, so an error might end up with trailers but no headers. We |
| 410 | // shouldn't call finishWithError until ater both blocks are called. It is also when this is |
| 411 | // done that we can provide a merged view of response headers and trailers in a thread-safe |
| 412 | // way. |
| 413 | if (self.responseHeaders) { |
| 414 | userInfo[kGRPCHeadersKey] = self.responseHeaders; |
| 415 | } |
| 416 | error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; |
| 417 | } |
| 418 | [self finishWithError:error]; |
| 419 | }]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 420 | // Now that the RPC has been initiated, request writes can start. |
Jorge Canizales | 238ad78 | 2015-08-07 23:11:29 -0700 | [diff] [blame] | 421 | @synchronized(_requestWriter) { |
| 422 | [_requestWriter startWithWriteable:self]; |
| 423 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 424 | } |
| 425 | |
| 426 | #pragma mark GRXWriter implementation |
| 427 | |
| 428 | - (void)startWithWriteable:(id<GRXWriteable>)writeable { |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 429 | @synchronized(self) { |
| 430 | _state = GRXWriterStateStarted; |
| 431 | } |
| 432 | |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 433 | // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled). |
| 434 | // This makes RPCs in which the call isn't externally retained possible (as long as it is started |
| 435 | // before being autoreleased). |
| 436 | // Care is taken not to retain self strongly in any of the blocks used in this implementation, so |
| 437 | // that the life of the instance is determined by this retain cycle. |
Muxi Yan | e1443b1 | 2016-10-20 11:53:13 -0700 | [diff] [blame] | 438 | _retainSelf = self; |
| 439 | |
Muxi Yan | 895f3d8 | 2017-04-05 13:12:30 -0700 | [diff] [blame] | 440 | _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable |
| 441 | dispatchQueue:_responseQueue]; |
Muxi Yan | e1443b1 | 2016-10-20 11:53:13 -0700 | [diff] [blame] | 442 | |
| 443 | _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path]; |
| 444 | NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?"); |
| 445 | |
| 446 | [self sendHeaders:_requestHeaders]; |
| 447 | [self invokeCall]; |
Muxi Yan | 4f6a19b | 2016-10-25 14:40:06 -0700 | [diff] [blame] | 448 | |
| 449 | // TODO(jcanizales): Extract this logic somewhere common. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 450 | NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host; |
Muxi Yan | 4f6a19b | 2016-10-25 14:40:06 -0700 | [diff] [blame] | 451 | if (!host) { |
| 452 | // TODO(jcanizales): Check this on init. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 453 | [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host]; |
Muxi Yan | 4f6a19b | 2016-10-25 14:40:06 -0700 | [diff] [blame] | 454 | } |
| 455 | __weak typeof(self) weakSelf = self; |
| 456 | _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host]; |
| 457 | void (^handler)() = ^{ |
| 458 | typeof(self) strongSelf = weakSelf; |
| 459 | if (strongSelf) { |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 460 | [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain |
| 461 | code:GRPCErrorCodeUnavailable |
| 462 | userInfo:@{ NSLocalizedDescriptionKey : @"Connectivity lost." }]]; |
Muxi Yan | 4f6a19b | 2016-10-25 14:40:06 -0700 | [diff] [blame] | 463 | } |
| 464 | }; |
| 465 | [_connectivityMonitor handleLossWithHandler:handler |
Muxi Yan | 2a25f33 | 2016-10-28 13:27:04 -0700 | [diff] [blame] | 466 | wifiStatusChangeHandler:nil]; |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 467 | } |
| 468 | |
| 469 | - (void)setState:(GRXWriterState)newState { |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 470 | @synchronized(self) { |
| 471 | // Manual transitions are only allowed from the started or paused states. |
Muxi Yan | 61274ca | 2016-10-28 12:09:59 -0700 | [diff] [blame] | 472 | if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) { |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 473 | return; |
| 474 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 475 | |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 476 | switch (newState) { |
| 477 | case GRXWriterStateFinished: |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 478 | _state = newState; |
Jorge Canizales | 0803bb0 | 2016-04-30 10:40:18 -0700 | [diff] [blame] | 479 | // Per GRXWriter's contract, setting the state to Finished manually |
| 480 | // means one doesn't wish the writeable to be messaged anymore. |
| 481 | [_responseWriteable cancelSilently]; |
| 482 | _responseWriteable = nil; |
| 483 | return; |
| 484 | case GRXWriterStatePaused: |
| 485 | _state = newState; |
| 486 | return; |
| 487 | case GRXWriterStateStarted: |
| 488 | if (_state == GRXWriterStatePaused) { |
| 489 | _state = newState; |
| 490 | [self startNextRead]; |
| 491 | } |
| 492 | return; |
| 493 | case GRXWriterStateNotStarted: |
| 494 | return; |
| 495 | } |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 496 | } |
| 497 | } |
Jorge Canizales | f1d084a | 2015-10-30 11:14:09 -0700 | [diff] [blame] | 498 | |
Jorge Canizales | 5e0efd9 | 2015-02-17 18:23:58 -0800 | [diff] [blame] | 499 | @end |