ConnectionManager.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import Logging
  18. import NIO
  19. import NIOConcurrencyHelpers
  20. internal class ConnectionManager {
  21. internal struct IdleState {
  22. var configuration: ClientConnection.Configuration
  23. }
  24. internal enum Reconnect {
  25. case none
  26. case after(TimeInterval)
  27. }
  28. internal struct ConnectingState {
  29. var configuration: ClientConnection.Configuration
  30. var backoffIterator: ConnectionBackoffIterator?
  31. var reconnect: Reconnect
  32. var readyChannelPromise: EventLoopPromise<Channel>
  33. var candidate: EventLoopFuture<Channel>
  34. }
  35. internal struct ConnectedState {
  36. var configuration: ClientConnection.Configuration
  37. var backoffIterator: ConnectionBackoffIterator?
  38. var reconnect: Reconnect
  39. var readyChannelPromise: EventLoopPromise<Channel>
  40. var candidate: Channel
  41. init(from state: ConnectingState, candidate: Channel) {
  42. self.configuration = state.configuration
  43. self.backoffIterator = state.backoffIterator
  44. self.reconnect = state.reconnect
  45. self.readyChannelPromise = state.readyChannelPromise
  46. self.candidate = candidate
  47. }
  48. }
  49. internal struct ReadyState {
  50. var configuration: ClientConnection.Configuration
  51. var channel: Channel
  52. init(from state: ConnectedState) {
  53. self.configuration = state.configuration
  54. self.channel = state.candidate
  55. }
  56. }
  57. internal struct TransientFailureState {
  58. var configuration: ClientConnection.Configuration
  59. var backoffIterator: ConnectionBackoffIterator?
  60. var readyChannelPromise: EventLoopPromise<Channel>
  61. var scheduled: Scheduled<Void>
  62. init(from state: ConnectingState, scheduled: Scheduled<Void>) {
  63. self.configuration = state.configuration
  64. self.backoffIterator = state.backoffIterator
  65. self.readyChannelPromise = state.readyChannelPromise
  66. self.scheduled = scheduled
  67. }
  68. init(from state: ConnectedState, scheduled: Scheduled<Void>) {
  69. self.configuration = state.configuration
  70. self.backoffIterator = state.backoffIterator
  71. self.readyChannelPromise = state.readyChannelPromise
  72. self.scheduled = scheduled
  73. }
  74. init(from state: ReadyState, scheduled: Scheduled<Void>) {
  75. self.configuration = state.configuration
  76. self.backoffIterator = state.configuration.connectionBackoff?.makeIterator()
  77. self.readyChannelPromise = state.channel.eventLoop.makePromise()
  78. self.scheduled = scheduled
  79. }
  80. }
  81. internal struct ShutdownState {
  82. var closeFuture: EventLoopFuture<Void>
  83. }
  84. internal enum State {
  85. /// No `Channel` is required.
  86. ///
  87. /// Valid next states:
  88. /// - `connecting`
  89. /// - `shutdown`
  90. case idle(IdleState)
  91. /// We're actively trying to establish a connection.
  92. ///
  93. /// Valid next states:
  94. /// - `active`
  95. /// - `transientFailure` (if our attempt fails and we're going to try again)
  96. /// - `shutdown`
  97. case connecting(ConnectingState)
  98. /// We've established a `Channel`, it might not be suitable (TLS handshake may fail, etc.).
  99. /// Our signal to be 'ready' is the initial HTTP/2 SETTINGS frame.
  100. ///
  101. /// Valid next states:
  102. /// - `ready`
  103. /// - `transientFailure` (if we our handshake fails or other error happens and we can attempt
  104. /// to re-establish the connection)
  105. /// - `shutdown`
  106. case active(ConnectedState)
  107. /// We have an active `Channel` which has seen the initial HTTP/2 SETTINGS frame. We can use
  108. /// the channel for making RPCs.
  109. ///
  110. /// Valid next states:
  111. /// - `idle` (we're not serving any RPCs, we can drop the connection for now)
  112. /// - `transientFailure` (we encountered an error and will re-establish the connection)
  113. /// - `shutdown`
  114. case ready(ReadyState)
  115. /// A `Channel` is desired, we'll attempt to create one in the future.
  116. ///
  117. /// Valid next states:
  118. /// - `connecting`
  119. /// - `shutdown`
  120. case transientFailure(TransientFailureState)
  121. /// We never want another `Channel`: this state is terminal.
  122. case shutdown(ShutdownState)
  123. fileprivate var label: String {
  124. switch self {
  125. case .idle:
  126. return "idle"
  127. case .connecting:
  128. return "connecting"
  129. case .active:
  130. return "active"
  131. case .ready:
  132. return "ready"
  133. case .transientFailure:
  134. return "transientFailure"
  135. case .shutdown:
  136. return "shutdown"
  137. }
  138. }
  139. }
  140. private var state: State {
  141. didSet {
  142. switch self.state {
  143. case .idle:
  144. self.monitor.updateState(to: .idle, logger: self.logger)
  145. // Create a new id; it'll be used for the *next* channel we create.
  146. self.channelNumberLock.withLockVoid {
  147. self.channelNumber &+= 1
  148. }
  149. self.logger[metadataKey: MetadataKey.connectionID] = "\(self.connectionIDAndNumber)"
  150. case .connecting:
  151. self.monitor.updateState(to: .connecting, logger: self.logger)
  152. // This is an internal state.
  153. case .active:
  154. ()
  155. case .ready:
  156. self.monitor.updateState(to: .ready, logger: self.logger)
  157. case .transientFailure:
  158. self.monitor.updateState(to: .transientFailure, logger: self.logger)
  159. case .shutdown:
  160. self.monitor.updateState(to: .shutdown, logger: self.logger)
  161. }
  162. }
  163. }
  164. internal let eventLoop: EventLoop
  165. internal let monitor: ConnectivityStateMonitor
  166. internal var logger: Logger
  167. private let connectionID: String
  168. private var channelNumber: UInt64
  169. private var channelNumberLock = Lock()
  170. private var connectionIDAndNumber: String {
  171. return self.channelNumberLock.withLock {
  172. return "\(self.connectionID)/\(self.channelNumber)"
  173. }
  174. }
  175. internal func appendMetadata(to logger: inout Logger) {
  176. logger[metadataKey: MetadataKey.connectionID] = "\(self.connectionIDAndNumber)"
  177. }
  178. // Only used for testing.
  179. private var channelProvider: (() -> EventLoopFuture<Channel>)?
  180. internal convenience init(configuration: ClientConnection.Configuration, logger: Logger) {
  181. self.init(configuration: configuration, logger: logger, channelProvider: nil)
  182. }
  183. /// Create a `ConnectionManager` for testing: uses the given `channelProvider` to create channels.
  184. internal static func testingOnly(
  185. configuration: ClientConnection.Configuration,
  186. logger: Logger,
  187. channelProvider: @escaping () -> EventLoopFuture<Channel>
  188. ) -> ConnectionManager {
  189. return ConnectionManager(
  190. configuration: configuration,
  191. logger: logger,
  192. channelProvider: channelProvider
  193. )
  194. }
  195. private init(
  196. configuration: ClientConnection.Configuration,
  197. logger: Logger,
  198. channelProvider: (() -> EventLoopFuture<Channel>)?
  199. ) {
  200. // Setup the logger.
  201. var logger = logger
  202. let connectionID = UUID().uuidString
  203. let channelNumber: UInt64 = 0
  204. logger[metadataKey: MetadataKey.connectionID] = "\(connectionID)/\(channelNumber)"
  205. let eventLoop = configuration.eventLoopGroup.next()
  206. self.eventLoop = eventLoop
  207. self.state = .idle(IdleState(configuration: configuration))
  208. self.monitor = ConnectivityStateMonitor(
  209. delegate: configuration.connectivityStateDelegate,
  210. queue: configuration.connectivityStateDelegateQueue
  211. )
  212. self.channelProvider = channelProvider
  213. self.connectionID = connectionID
  214. self.channelNumber = channelNumber
  215. self.logger = logger
  216. }
  217. /// Returns a future for a connected channel.
  218. internal func getChannel() -> EventLoopFuture<Channel> {
  219. return self.eventLoop.flatSubmit {
  220. let channel: EventLoopFuture<Channel>
  221. switch self.state {
  222. case .idle:
  223. self.startConnecting()
  224. // We started connecting so we must transition to the `connecting` state.
  225. guard case let .connecting(connecting) = self.state else {
  226. self.invalidState()
  227. }
  228. channel = connecting.readyChannelPromise.futureResult
  229. case let .connecting(state):
  230. channel = state.readyChannelPromise.futureResult
  231. case let .active(state):
  232. channel = state.readyChannelPromise.futureResult
  233. case let .ready(state):
  234. channel = state.channel.eventLoop.makeSucceededFuture(state.channel)
  235. case let .transientFailure(state):
  236. channel = state.readyChannelPromise.futureResult
  237. case .shutdown:
  238. channel = self.eventLoop.makeFailedFuture(GRPCStatus(code: .unavailable, message: nil))
  239. }
  240. self.logger.debug("vending channel future", metadata: [
  241. "connectivity_state": "\(self.state.label)",
  242. ])
  243. return channel
  244. }
  245. }
  246. /// Returns a future for the current channel, or future channel from the current connection
  247. /// attempt, or if the state is 'idle' returns the future for the next connection attempt.
  248. ///
  249. /// Note: if the state is 'transientFailure' or 'shutdown' then a failed future will be returned.
  250. internal func getOptimisticChannel() -> EventLoopFuture<Channel> {
  251. return self.eventLoop.flatSubmit {
  252. let channel: EventLoopFuture<Channel>
  253. switch self.state {
  254. case .idle:
  255. self.startConnecting()
  256. // We started connecting so we must transition to the `connecting` state.
  257. guard case let .connecting(connecting) = self.state else {
  258. self.invalidState()
  259. }
  260. channel = connecting.candidate
  261. case let .connecting(state):
  262. channel = state.candidate
  263. case let .active(state):
  264. channel = state.candidate.eventLoop.makeSucceededFuture(state.candidate)
  265. case let .ready(state):
  266. channel = state.channel.eventLoop.makeSucceededFuture(state.channel)
  267. case .transientFailure:
  268. channel = self.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)
  269. case .shutdown:
  270. channel = self.eventLoop.makeFailedFuture(GRPCStatus(code: .unavailable, message: nil))
  271. }
  272. self.logger.debug("vending fast-failing channel future", metadata: [
  273. "connectivity_state": "\(self.state.label)",
  274. ])
  275. return channel
  276. }
  277. }
  278. /// Shutdown any connection which exists. This is a request from the application.
  279. internal func shutdown() -> EventLoopFuture<Void> {
  280. return self.eventLoop.flatSubmit {
  281. self.logger.debug("shutting down connection", metadata: [
  282. "connectivity_state": "\(self.state.label)",
  283. ])
  284. let shutdown: ShutdownState
  285. switch self.state {
  286. // We don't have a channel and we don't want one, easy!
  287. case .idle:
  288. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  289. self.state = .shutdown(shutdown)
  290. // We're mid-connection: the application doesn't have any 'ready' channels so we'll succeed
  291. // the shutdown future and deal with any fallout from the connecting channel without the
  292. // application knowing.
  293. case let .connecting(state):
  294. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  295. self.state = .shutdown(shutdown)
  296. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  297. // connect the application shouldn't should have access to the channel.
  298. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  299. // In case we do successfully connect, close immediately.
  300. state.candidate.whenSuccess {
  301. $0.close(mode: .all, promise: nil)
  302. }
  303. // We have an active channel but the application doesn't know about it yet. We'll do the same
  304. // as for `.connecting`.
  305. case let .active(state):
  306. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  307. self.state = .shutdown(shutdown)
  308. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  309. // connect the application shouldn't should have access to the channel.
  310. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  311. // We have a channel, close it.
  312. state.candidate.close(mode: .all, promise: nil)
  313. // The channel is up and running: the application could be using it. We can close it and
  314. // return the `closeFuture`.
  315. case let .ready(state):
  316. shutdown = ShutdownState(closeFuture: state.channel.closeFuture)
  317. self.state = .shutdown(shutdown)
  318. // We have a channel, close it.
  319. state.channel.close(mode: .all, promise: nil)
  320. // Like `.connecting` and `.active` the application does not have a `.ready` channel. We'll
  321. // do the same but also cancel any scheduled connection attempts and deal with any fallout
  322. // if we cancelled too late.
  323. case let .transientFailure(state):
  324. // Stop the creation of a new channel, if we can. If we can't then the task to
  325. // `startConnecting()` will see our new `shutdown` state and ignore the request to connect.
  326. state.scheduled.cancel()
  327. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  328. self.state = .shutdown(shutdown)
  329. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  330. // connect the application shouldn't should have access to the channel.
  331. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  332. // We're already shutdown; nothing to do.
  333. case let .shutdown(state):
  334. shutdown = state
  335. }
  336. return shutdown.closeFuture
  337. }
  338. }
  339. // MARK: - State changes from the channel handler.
  340. /// The connecting channel became `active`. Must be called on the `EventLoop`.
  341. internal func channelActive(channel: Channel) {
  342. self.eventLoop.preconditionInEventLoop()
  343. self.logger.debug("activating connection", metadata: [
  344. "connectivity_state": "\(self.state.label)",
  345. ])
  346. switch self.state {
  347. case let .connecting(connecting):
  348. self.state = .active(ConnectedState(from: connecting, candidate: channel))
  349. // Application called shutdown before the channel become active; we should close it.
  350. case .shutdown:
  351. channel.close(mode: .all, promise: nil)
  352. case .idle, .active, .ready, .transientFailure:
  353. self.invalidState()
  354. }
  355. }
  356. /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect?
  357. /// Must be called on the `EventLoop`.
  358. internal func channelInactive() {
  359. self.eventLoop.preconditionInEventLoop()
  360. self.logger.debug("deactivating connection", metadata: [
  361. "connectivity_state": "\(self.state.label)",
  362. ])
  363. switch self.state {
  364. // The channel is `active` but not `ready`. Should we try again?
  365. case let .active(active):
  366. switch active.reconnect {
  367. // No, shutdown instead.
  368. case .none:
  369. self.logger.debug("shutting down connection")
  370. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  371. active.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  372. // Yes, after some time.
  373. case let .after(delay):
  374. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  375. self.startConnecting()
  376. }
  377. self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"])
  378. self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled))
  379. }
  380. // The channel was ready and working fine but something went wrong. Should we try to replace
  381. // the channel?
  382. case let .ready(ready):
  383. // No, no backoff is configured.
  384. if ready.configuration.connectionBackoff == nil {
  385. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  386. self.state = .shutdown(ShutdownState(closeFuture: ready.channel.closeFuture))
  387. } else {
  388. // Yes, start connecting now. We should go via `transientFailure`, however.
  389. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) {
  390. self.startConnecting()
  391. }
  392. self.logger.debug("scheduling connection attempt", metadata: ["delay": "0"])
  393. self.state = .transientFailure(TransientFailureState(from: ready, scheduled: scheduled))
  394. }
  395. // This is fine: we expect the channel to become inactive after becoming idle.
  396. case .idle:
  397. ()
  398. // We're already shutdown, that's fine.
  399. case .shutdown:
  400. ()
  401. case .connecting, .transientFailure:
  402. self.invalidState()
  403. }
  404. }
  405. /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be
  406. /// called on the `EventLoop`.
  407. internal func ready() {
  408. self.eventLoop.preconditionInEventLoop()
  409. self.logger.debug("connection ready", metadata: [
  410. "connectivity_state": "\(self.state.label)",
  411. ])
  412. switch self.state {
  413. case let .active(connected):
  414. self.state = .ready(ReadyState(from: connected))
  415. connected.readyChannelPromise.succeed(connected.candidate)
  416. case .shutdown:
  417. ()
  418. case .idle, .transientFailure, .connecting, .ready:
  419. self.invalidState()
  420. }
  421. }
  422. /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on
  423. /// the `EventLoop`.
  424. internal func idle() {
  425. self.eventLoop.preconditionInEventLoop()
  426. self.logger.debug("idling connection", metadata: [
  427. "connectivity_state": "\(self.state.label)",
  428. ])
  429. switch self.state {
  430. case let .active(state):
  431. // This state is reachable if the keepalive timer fires before we reach the ready state.
  432. self.state = .idle(IdleState(configuration: state.configuration))
  433. state.readyChannelPromise
  434. .fail(GRPCStatus(code: .unavailable, message: "Idled before reaching ready state"))
  435. case let .ready(state):
  436. self.state = .idle(IdleState(configuration: state.configuration))
  437. case .idle, .connecting, .transientFailure, .shutdown:
  438. self.invalidState()
  439. }
  440. }
  441. }
  442. extension ConnectionManager {
  443. // A connection attempt failed; we never established a connection.
  444. private func connectionFailed(withError error: Error) {
  445. self.eventLoop.preconditionInEventLoop()
  446. switch self.state {
  447. case let .connecting(connecting):
  448. // Should we reconnect?
  449. switch connecting.reconnect {
  450. // No, shutdown.
  451. case .none:
  452. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  453. connecting.readyChannelPromise.fail(error)
  454. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  455. // Yes, after a delay.
  456. case let .after(delay):
  457. self.logger.debug("scheduling connection attempt", metadata: ["delay": "\(delay)"])
  458. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  459. self.startConnecting()
  460. }
  461. self
  462. .state = .transientFailure(TransientFailureState(from: connecting, scheduled: scheduled))
  463. }
  464. // The application must have called shutdown while we were trying to establish a connection
  465. // which was doomed to fail anyway. That's fine, we can ignore this.
  466. case .shutdown:
  467. ()
  468. // We can't fail to connect if we aren't trying.
  469. case .idle, .active, .ready, .transientFailure:
  470. self.invalidState()
  471. }
  472. }
  473. }
  474. extension ConnectionManager {
  475. // Start establishing a connection: we can only do this from the `idle` and `transientFailure`
  476. // states. Must be called on the `EventLoop`.
  477. private func startConnecting() {
  478. switch self.state {
  479. case let .idle(state):
  480. let iterator = state.configuration.connectionBackoff?.makeIterator()
  481. self.startConnecting(
  482. configuration: state.configuration,
  483. backoffIterator: iterator,
  484. channelPromise: self.eventLoop.makePromise()
  485. )
  486. case let .transientFailure(pending):
  487. self.startConnecting(
  488. configuration: pending.configuration,
  489. backoffIterator: pending.backoffIterator,
  490. channelPromise: pending.readyChannelPromise
  491. )
  492. // We shutdown before a scheduled connection attempt had started.
  493. case .shutdown:
  494. ()
  495. case .connecting, .active, .ready:
  496. self.invalidState()
  497. }
  498. }
  499. private func startConnecting(
  500. configuration: ClientConnection.Configuration,
  501. backoffIterator: ConnectionBackoffIterator?,
  502. channelPromise: EventLoopPromise<Channel>
  503. ) {
  504. let timeoutAndBackoff = backoffIterator?.next()
  505. // We're already on the event loop: submit the connect so it starts after we've made the
  506. // state change to `.connecting`.
  507. self.eventLoop.assertInEventLoop()
  508. let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit {
  509. let channel = self.makeChannel(
  510. configuration: configuration,
  511. connectTimeout: timeoutAndBackoff?.timeout
  512. )
  513. channel.whenFailure { error in
  514. self.connectionFailed(withError: error)
  515. }
  516. return channel
  517. }
  518. // Should we reconnect if the candidate channel fails?
  519. let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none
  520. let connecting = ConnectingState(
  521. configuration: configuration,
  522. backoffIterator: backoffIterator,
  523. reconnect: reconnect,
  524. readyChannelPromise: channelPromise,
  525. candidate: candidate
  526. )
  527. self.state = .connecting(connecting)
  528. }
  529. }
  530. extension ConnectionManager {
  531. private func invalidState(
  532. function: StaticString = #function,
  533. file: StaticString = #file,
  534. line: UInt = #line
  535. ) -> Never {
  536. preconditionFailure("Invalid state \(self.state) for \(function)", file: file, line: line)
  537. }
  538. }
  539. extension ConnectionManager {
  540. private func makeBootstrap(
  541. configuration: ClientConnection.Configuration,
  542. connectTimeout: TimeInterval?
  543. ) -> ClientBootstrapProtocol {
  544. let serverHostname: String? = configuration.tls.flatMap { tls -> String? in
  545. if let hostnameOverride = tls.hostnameOverride {
  546. return hostnameOverride
  547. } else {
  548. return configuration.target.host
  549. }
  550. }.flatMap { hostname in
  551. if hostname.isIPAddress {
  552. return nil
  553. } else {
  554. return hostname
  555. }
  556. }
  557. let bootstrap = PlatformSupport.makeClientBootstrap(group: self.eventLoop, logger: self.logger)
  558. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  559. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  560. .channelInitializer { channel in
  561. let initialized = channel.configureGRPCClient(
  562. httpTargetWindowSize: configuration.httpTargetWindowSize,
  563. tlsConfiguration: configuration.tls?.configuration,
  564. tlsServerHostname: serverHostname,
  565. connectionManager: self,
  566. connectionKeepalive: configuration.connectionKeepalive,
  567. connectionIdleTimeout: configuration.connectionIdleTimeout,
  568. errorDelegate: configuration.errorDelegate,
  569. requiresZeroLengthWriteWorkaround: PlatformSupport.requiresZeroLengthWriteWorkaround(
  570. group: self.eventLoop,
  571. hasTLS: configuration.tls != nil
  572. ),
  573. logger: self.logger
  574. )
  575. // Run the debug initializer, if there is one.
  576. if let debugInitializer = configuration.debugChannelInitializer {
  577. return initialized.flatMap {
  578. debugInitializer(channel)
  579. }
  580. } else {
  581. return initialized
  582. }
  583. }
  584. if let connectTimeout = connectTimeout {
  585. return bootstrap.connectTimeout(.seconds(timeInterval: connectTimeout))
  586. } else {
  587. return bootstrap
  588. }
  589. }
  590. private func makeChannel(
  591. configuration: ClientConnection.Configuration,
  592. connectTimeout: TimeInterval?
  593. ) -> EventLoopFuture<Channel> {
  594. if let provider = self.channelProvider {
  595. return provider()
  596. } else {
  597. let bootstrap = self.makeBootstrap(
  598. configuration: configuration,
  599. connectTimeout: connectTimeout
  600. )
  601. return bootstrap.connect(to: configuration.target)
  602. }
  603. }
  604. }