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