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