ConnectionManager.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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. // These cases are purposefully separated: some crash reporting services provide stack traces
  353. // which don't include the precondition failure message (which contain the invalid state we were
  354. // in). Keeping the cases separate allows us work out the state from the line number.
  355. case .idle:
  356. self.invalidState()
  357. case .active:
  358. self.invalidState()
  359. case .ready:
  360. self.invalidState()
  361. case .transientFailure:
  362. self.invalidState()
  363. }
  364. }
  365. /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect?
  366. /// Must be called on the `EventLoop`.
  367. internal func channelInactive() {
  368. self.eventLoop.preconditionInEventLoop()
  369. self.logger.debug("deactivating connection", metadata: [
  370. "connectivity_state": "\(self.state.label)",
  371. ])
  372. switch self.state {
  373. // The channel is `active` but not `ready`. Should we try again?
  374. case let .active(active):
  375. switch active.reconnect {
  376. // No, shutdown instead.
  377. case .none:
  378. self.logger.debug("shutting down connection")
  379. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  380. active.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  381. // Yes, after some time.
  382. case let .after(delay):
  383. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  384. self.startConnecting()
  385. }
  386. self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"])
  387. self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled))
  388. }
  389. // The channel was ready and working fine but something went wrong. Should we try to replace
  390. // the channel?
  391. case let .ready(ready):
  392. // No, no backoff is configured.
  393. if ready.configuration.connectionBackoff == nil {
  394. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  395. self.state = .shutdown(ShutdownState(closeFuture: ready.channel.closeFuture))
  396. } else {
  397. // Yes, start connecting now. We should go via `transientFailure`, however.
  398. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) {
  399. self.startConnecting()
  400. }
  401. self.logger.debug("scheduling connection attempt", metadata: ["delay": "0"])
  402. self.state = .transientFailure(TransientFailureState(from: ready, scheduled: scheduled))
  403. }
  404. // This is fine: we expect the channel to become inactive after becoming idle.
  405. case .idle:
  406. ()
  407. // We're already shutdown, that's fine.
  408. case .shutdown:
  409. ()
  410. // These cases are purposefully separated: some crash reporting services provide stack traces
  411. // which don't include the precondition failure message (which contain the invalid state we were
  412. // in). Keeping the cases separate allows us work out the state from the line number.
  413. case .connecting:
  414. self.invalidState()
  415. case .transientFailure:
  416. self.invalidState()
  417. }
  418. }
  419. /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be
  420. /// called on the `EventLoop`.
  421. internal func ready() {
  422. self.eventLoop.preconditionInEventLoop()
  423. self.logger.debug("connection ready", metadata: [
  424. "connectivity_state": "\(self.state.label)",
  425. ])
  426. switch self.state {
  427. case let .active(connected):
  428. self.state = .ready(ReadyState(from: connected))
  429. connected.readyChannelPromise.succeed(connected.candidate)
  430. case .shutdown:
  431. ()
  432. // These cases are purposefully separated: some crash reporting services provide stack traces
  433. // which don't include the precondition failure message (which contain the invalid state we were
  434. // in). Keeping the cases separate allows us work out the state from the line number.
  435. case .idle:
  436. self.invalidState()
  437. case .transientFailure:
  438. self.invalidState()
  439. case .connecting:
  440. self.invalidState()
  441. case .ready:
  442. self.invalidState()
  443. }
  444. }
  445. /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on
  446. /// the `EventLoop`.
  447. internal func idle() {
  448. self.eventLoop.preconditionInEventLoop()
  449. self.logger.debug("idling connection", metadata: [
  450. "connectivity_state": "\(self.state.label)",
  451. ])
  452. switch self.state {
  453. case let .active(state):
  454. // This state is reachable if the keepalive timer fires before we reach the ready state.
  455. self.state = .idle(IdleState(configuration: state.configuration))
  456. state.readyChannelPromise
  457. .fail(GRPCStatus(code: .unavailable, message: "Idled before reaching ready state"))
  458. case let .ready(state):
  459. self.state = .idle(IdleState(configuration: state.configuration))
  460. case .shutdown:
  461. // This is expected when the connection is closed by the user: when the channel becomes
  462. // inactive and there are no outstanding RPCs, 'idle()' will be called instead of
  463. // 'channelInactive()'.
  464. ()
  465. // These cases are purposefully separated: some crash reporting services provide stack traces
  466. // which don't include the precondition failure message (which contain the invalid state we were
  467. // in). Keeping the cases separate allows us work out the state from the line number.
  468. case .idle:
  469. self.invalidState()
  470. case .connecting:
  471. self.invalidState()
  472. case .transientFailure:
  473. self.invalidState()
  474. }
  475. }
  476. }
  477. extension ConnectionManager {
  478. // A connection attempt failed; we never established a connection.
  479. private func connectionFailed(withError error: Error) {
  480. self.eventLoop.preconditionInEventLoop()
  481. switch self.state {
  482. case let .connecting(connecting):
  483. // Should we reconnect?
  484. switch connecting.reconnect {
  485. // No, shutdown.
  486. case .none:
  487. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  488. connecting.readyChannelPromise.fail(error)
  489. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  490. // Yes, after a delay.
  491. case let .after(delay):
  492. self.logger.debug("scheduling connection attempt", metadata: ["delay": "\(delay)"])
  493. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  494. self.startConnecting()
  495. }
  496. self
  497. .state = .transientFailure(TransientFailureState(from: connecting, scheduled: scheduled))
  498. }
  499. // The application must have called shutdown while we were trying to establish a connection
  500. // which was doomed to fail anyway. That's fine, we can ignore this.
  501. case .shutdown:
  502. ()
  503. // We can't fail to connect if we aren't trying.
  504. //
  505. // These cases are purposefully separated: some crash reporting services provide stack traces
  506. // which don't include the precondition failure message (which contain the invalid state we were
  507. // in). Keeping the cases separate allows us work out the state from the line number.
  508. case .idle:
  509. self.invalidState()
  510. case .active:
  511. self.invalidState()
  512. case .ready:
  513. self.invalidState()
  514. case .transientFailure:
  515. self.invalidState()
  516. }
  517. }
  518. }
  519. extension ConnectionManager {
  520. // Start establishing a connection: we can only do this from the `idle` and `transientFailure`
  521. // states. Must be called on the `EventLoop`.
  522. private func startConnecting() {
  523. switch self.state {
  524. case let .idle(state):
  525. let iterator = state.configuration.connectionBackoff?.makeIterator()
  526. self.startConnecting(
  527. configuration: state.configuration,
  528. backoffIterator: iterator,
  529. channelPromise: self.eventLoop.makePromise()
  530. )
  531. case let .transientFailure(pending):
  532. self.startConnecting(
  533. configuration: pending.configuration,
  534. backoffIterator: pending.backoffIterator,
  535. channelPromise: pending.readyChannelPromise
  536. )
  537. // We shutdown before a scheduled connection attempt had started.
  538. case .shutdown:
  539. ()
  540. // These cases are purposefully separated: some crash reporting services provide stack traces
  541. // which don't include the precondition failure message (which contain the invalid state we were
  542. // in). Keeping the cases separate allows us work out the state from the line number.
  543. case .connecting:
  544. self.invalidState()
  545. case .active:
  546. self.invalidState()
  547. case .ready:
  548. self.invalidState()
  549. }
  550. }
  551. private func startConnecting(
  552. configuration: ClientConnection.Configuration,
  553. backoffIterator: ConnectionBackoffIterator?,
  554. channelPromise: EventLoopPromise<Channel>
  555. ) {
  556. let timeoutAndBackoff = backoffIterator?.next()
  557. // We're already on the event loop: submit the connect so it starts after we've made the
  558. // state change to `.connecting`.
  559. self.eventLoop.assertInEventLoop()
  560. let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit {
  561. let channel = self.makeChannel(
  562. configuration: configuration,
  563. connectTimeout: timeoutAndBackoff?.timeout
  564. )
  565. channel.whenFailure { error in
  566. self.connectionFailed(withError: error)
  567. }
  568. return channel
  569. }
  570. // Should we reconnect if the candidate channel fails?
  571. let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none
  572. let connecting = ConnectingState(
  573. configuration: configuration,
  574. backoffIterator: backoffIterator,
  575. reconnect: reconnect,
  576. readyChannelPromise: channelPromise,
  577. candidate: candidate
  578. )
  579. self.state = .connecting(connecting)
  580. }
  581. }
  582. extension ConnectionManager {
  583. private func invalidState(
  584. function: StaticString = #function,
  585. file: StaticString = #file,
  586. line: UInt = #line
  587. ) -> Never {
  588. preconditionFailure("Invalid state \(self.state) for \(function)", file: file, line: line)
  589. }
  590. }
  591. extension ConnectionManager {
  592. private func makeBootstrap(
  593. configuration: ClientConnection.Configuration,
  594. connectTimeout: TimeInterval?
  595. ) -> ClientBootstrapProtocol {
  596. let serverHostname: String? = configuration.tls.flatMap { tls -> String? in
  597. if let hostnameOverride = tls.hostnameOverride {
  598. return hostnameOverride
  599. } else {
  600. return configuration.target.host
  601. }
  602. }.flatMap { hostname in
  603. if hostname.isIPAddress {
  604. return nil
  605. } else {
  606. return hostname
  607. }
  608. }
  609. let bootstrap = PlatformSupport.makeClientBootstrap(group: self.eventLoop, logger: self.logger)
  610. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  611. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  612. .channelInitializer { channel in
  613. let initialized = channel.configureGRPCClient(
  614. httpTargetWindowSize: configuration.httpTargetWindowSize,
  615. tlsConfiguration: configuration.tls?.configuration,
  616. tlsServerHostname: serverHostname,
  617. connectionManager: self,
  618. connectionKeepalive: configuration.connectionKeepalive,
  619. connectionIdleTimeout: configuration.connectionIdleTimeout,
  620. errorDelegate: configuration.errorDelegate,
  621. requiresZeroLengthWriteWorkaround: PlatformSupport.requiresZeroLengthWriteWorkaround(
  622. group: self.eventLoop,
  623. hasTLS: configuration.tls != nil
  624. ),
  625. logger: self.logger
  626. )
  627. // Run the debug initializer, if there is one.
  628. if let debugInitializer = configuration.debugChannelInitializer {
  629. return initialized.flatMap {
  630. debugInitializer(channel)
  631. }
  632. } else {
  633. return initialized
  634. }
  635. }
  636. if let connectTimeout = connectTimeout {
  637. return bootstrap.connectTimeout(.seconds(timeInterval: connectTimeout))
  638. } else {
  639. return bootstrap
  640. }
  641. }
  642. private func makeChannel(
  643. configuration: ClientConnection.Configuration,
  644. connectTimeout: TimeInterval?
  645. ) -> EventLoopFuture<Channel> {
  646. if let provider = self.channelProvider {
  647. return provider()
  648. } else {
  649. let bootstrap = self.makeBootstrap(
  650. configuration: configuration,
  651. connectTimeout: connectTimeout
  652. )
  653. return bootstrap.connect(to: configuration.target)
  654. }
  655. }
  656. }