aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/objective-c/GRPCClient/private/GRPCChannel.m
blob: 6b5d1fe07190f03cbcbb95c15f468940b8a038ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#import "GRPCChannel.h"

#include <grpc/support/log.h>

#import "ChannelArgsUtil.h"
#import "GRPCChannelFactory.h"
#import "GRPCChannelPool.h"
#import "GRPCCompletionQueue.h"
#import "GRPCCronetChannelFactory.h"
#import "GRPCInsecureChannelFactory.h"
#import "GRPCSecureChannelFactory.h"
#import "version.h"

#import <GRPCClient/GRPCCall+Cronet.h>
#import <GRPCClient/GRPCCallOptions.h>

// When all calls of a channel are destroyed, destroy the channel after this much seconds.
NSTimeInterval kChannelDestroyDelay = 30;

/**
 * Time the channel destroy when the channel's calls are unreffed. If there's new call, reset the
 * timer.
 */
@interface GRPCChannelRef : NSObject

- (instancetype)initWithDestroyDelay:(NSTimeInterval)destroyDelay
              destroyChannelCallback:(void (^)())destroyChannelCallback;

/** Add call ref count to the channel and maybe reset the timer. */
- (void)refChannel;

/** Reduce call ref count to the channel and maybe set the timer. */
- (void)unrefChannel;

/** Disconnect the channel immediately. */
- (void)disconnect;

@end

@implementation GRPCChannelRef {
  NSTimeInterval _destroyDelay;
  void (^_destroyChannelCallback)();

  NSUInteger _refCount;
  BOOL _disconnected;
  dispatch_queue_t _dispatchQueue;
  dispatch_queue_t _timerQueue;
  NSDate *_lastDispatch;
}

- (instancetype)initWithDestroyDelay:(NSTimeInterval)destroyDelay
              destroyChannelCallback:(void (^)())destroyChannelCallback {
  if ((self = [super init])) {
    _destroyDelay = destroyDelay;
    _destroyChannelCallback = destroyChannelCallback;

    _refCount = 1;
    _disconnected = NO;
    if (@available(iOS 8.0, *)) {
      _dispatchQueue = dispatch_queue_create(
          NULL,
          dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, -1));
      _timerQueue =
          dispatch_queue_create(NULL, dispatch_queue_attr_make_with_qos_class(
                                          DISPATCH_QUEUE_CONCURRENT, QOS_CLASS_DEFAULT, -1));
    } else {
      _dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
      _timerQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT);
    }
    _lastDispatch = nil;
  }
  return self;
}

- (void)refChannel {
  dispatch_async(_dispatchQueue, ^{
    if (!self->_disconnected) {
      self->_refCount++;
      self->_lastDispatch = nil;
    }
  });
}

- (void)unrefChannel {
  dispatch_async(_dispatchQueue, ^{
    if (!self->_disconnected) {
      self->_refCount--;
      if (self->_refCount == 0) {
        self->_lastDispatch = [NSDate date];
        dispatch_time_t delay =
            dispatch_time(DISPATCH_TIME_NOW, (int64_t)kChannelDestroyDelay * 1e9);
        dispatch_after(delay, self->_timerQueue, ^{
          [self timerFire];
        });
      }
    }
  });
}

- (void)disconnect {
  dispatch_async(_dispatchQueue, ^{
    if (!self->_disconnected) {
      self->_lastDispatch = nil;
      self->_disconnected = YES;
      // Break retain loop
      self->_destroyChannelCallback = nil;
    }
  });
}

- (void)timerFire {
  dispatch_async(_dispatchQueue, ^{
    if (self->_disconnected || self->_lastDispatch == nil ||
        -[self->_lastDispatch timeIntervalSinceNow] < -kChannelDestroyDelay) {
      return;
    }
    self->_lastDispatch = nil;
    self->_disconnected = YES;
    self->_destroyChannelCallback();
    // Break retain loop
    self->_destroyChannelCallback = nil;
  });
}

@end

@implementation GRPCChannel {
  GRPCChannelConfiguration *_configuration;
  grpc_channel *_unmanagedChannel;
  GRPCChannelRef *_channelRef;
  dispatch_queue_t _dispatchQueue;
}

- (grpc_call *)unmanagedCallWithPath:(NSString *)path
                     completionQueue:(GRPCCompletionQueue *)queue
                         callOptions:(GRPCCallOptions *)callOptions {
  NSAssert(path.length, @"path must not be empty.");
  NSAssert(queue, @"completionQueue must not be empty.");
  NSAssert(callOptions, @"callOptions must not be empty.");
  __block grpc_call *call = nil;
  dispatch_sync(_dispatchQueue, ^{
    if (self->_unmanagedChannel) {
      NSString *serverAuthority = callOptions.serverAuthority;
      NSTimeInterval timeout = callOptions.timeout;
      NSAssert(timeout >= 0, @"Invalid timeout");
      grpc_slice host_slice = grpc_empty_slice();
      if (serverAuthority) {
        host_slice = grpc_slice_from_copied_string(serverAuthority.UTF8String);
      }
      grpc_slice path_slice = grpc_slice_from_copied_string(path.UTF8String);
      gpr_timespec deadline_ms =
          timeout == 0
              ? gpr_inf_future(GPR_CLOCK_REALTIME)
              : gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
                             gpr_time_from_millis((int64_t)(timeout * 1000), GPR_TIMESPAN));
      call = grpc_channel_create_call(self->_unmanagedChannel, NULL, GRPC_PROPAGATE_DEFAULTS,
                                      queue.unmanagedQueue, path_slice,
                                      serverAuthority ? &host_slice : NULL, deadline_ms, NULL);
      if (serverAuthority) {
        grpc_slice_unref(host_slice);
      }
      grpc_slice_unref(path_slice);
    }
  });
  return call;
}

- (void)ref {
  dispatch_async(_dispatchQueue, ^{
    if (self->_unmanagedChannel) {
      [self->_channelRef refChannel];
    }
  });
}

- (void)unref {
  dispatch_async(_dispatchQueue, ^{
    if (self->_unmanagedChannel) {
      [self->_channelRef unrefChannel];
    }
  });
}

- (void)disconnect {
  dispatch_async(_dispatchQueue, ^{
    if (self->_unmanagedChannel) {
      grpc_channel_destroy(self->_unmanagedChannel);
      self->_unmanagedChannel = nil;
      [self->_channelRef disconnect];
    }
  });
}

- (void)destroyChannel {
  dispatch_async(_dispatchQueue, ^{
    if (self->_unmanagedChannel) {
      grpc_channel_destroy(self->_unmanagedChannel);
      self->_unmanagedChannel = nil;
      [gChannelPool removeChannel:self];
    }
  });
}

- (nullable instancetype)initWithUnmanagedChannel:(grpc_channel * _Nullable)unmanagedChannel
                                    configuration:(GRPCChannelConfiguration *)configuration {
  NSAssert(configuration, @"Configuration must not be empty.");
  if (!unmanagedChannel) {
    return nil;
  }
  if ((self = [super init])) {
    _unmanagedChannel = unmanagedChannel;
    _configuration = [configuration copy];
    _channelRef = [[GRPCChannelRef alloc] initWithDestroyDelay:kChannelDestroyDelay
                                        destroyChannelCallback:^{
                                          [self destroyChannel];
                                        }];
    if (@available(iOS 8.0, *)) {
      _dispatchQueue = dispatch_queue_create(
          NULL,
          dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, -1));
    } else {
      _dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
    }
  }
  return self;
}

- (void)dealloc {
  if (_unmanagedChannel) {
    grpc_channel_destroy(_unmanagedChannel);
  }
}

+ (nullable instancetype)createChannelWithConfiguration:(GRPCChannelConfiguration *)config {
  NSString *host = config.host;
  if (host.length == 0) {
    return nil;
  }

  NSDictionary *channelArgs;
  if (config.callOptions.additionalChannelArgs.count != 0) {
    NSMutableDictionary *args = [config.channelArgs mutableCopy];
    [args addEntriesFromDictionary:config.callOptions.additionalChannelArgs];
    channelArgs = args;
  } else {
    channelArgs = config.channelArgs;
  }
  id<GRPCChannelFactory> factory = config.channelFactory;
  grpc_channel *unmanaged_channel = [factory createChannelWithHost:host channelArgs:channelArgs];
  return [[GRPCChannel alloc] initWithUnmanagedChannel:unmanaged_channel configuration:config];
}

static dispatch_once_t initChannelPool;
static GRPCChannelPool *gChannelPool;

+ (nullable instancetype)channelWithHost:(NSString *)host
                             callOptions:(GRPCCallOptions *)callOptions {
  dispatch_once(&initChannelPool, ^{
    gChannelPool = [[GRPCChannelPool alloc] init];
  });

  NSURL *hostURL = [NSURL URLWithString:[@"https://" stringByAppendingString:host]];
  if (hostURL.host && !hostURL.port) {
    host = [hostURL.host stringByAppendingString:@":443"];
  }

  GRPCChannelConfiguration *channelConfig =
      [[GRPCChannelConfiguration alloc] initWithHost:host callOptions:callOptions];

  return [gChannelPool channelWithConfiguration:channelConfig];
}

+ (void)closeOpenConnections {
  [gChannelPool removeAndCloseAllChannels];
}

@end