ConnectionManager.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. import NIOHTTP2
  21. internal final class ConnectionManager {
  22. internal enum Reconnect {
  23. case none
  24. case after(TimeInterval)
  25. }
  26. internal struct ConnectingState {
  27. var backoffIterator: ConnectionBackoffIterator?
  28. var reconnect: Reconnect
  29. var candidate: EventLoopFuture<Channel>
  30. var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  31. var candidateMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  32. }
  33. internal struct ConnectedState {
  34. var backoffIterator: ConnectionBackoffIterator?
  35. var reconnect: Reconnect
  36. var candidate: Channel
  37. var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  38. var multiplexer: HTTP2StreamMultiplexer
  39. var error: Error?
  40. init(from state: ConnectingState, candidate: Channel, multiplexer: HTTP2StreamMultiplexer) {
  41. self.backoffIterator = state.backoffIterator
  42. self.reconnect = state.reconnect
  43. self.candidate = candidate
  44. self.readyChannelMuxPromise = state.readyChannelMuxPromise
  45. self.multiplexer = multiplexer
  46. }
  47. }
  48. internal struct ReadyState {
  49. var channel: Channel
  50. var multiplexer: HTTP2StreamMultiplexer
  51. var error: Error?
  52. init(from state: ConnectedState) {
  53. self.channel = state.candidate
  54. self.multiplexer = state.multiplexer
  55. }
  56. }
  57. internal struct TransientFailureState {
  58. var backoffIterator: ConnectionBackoffIterator?
  59. var readyChannelMuxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  60. var scheduled: Scheduled<Void>
  61. var reason: Error?
  62. init(from state: ConnectingState, scheduled: Scheduled<Void>, reason: Error) {
  63. self.backoffIterator = state.backoffIterator
  64. self.readyChannelMuxPromise = state.readyChannelMuxPromise
  65. self.scheduled = scheduled
  66. self.reason = reason
  67. }
  68. init(from state: ConnectedState, scheduled: Scheduled<Void>) {
  69. self.backoffIterator = state.backoffIterator
  70. self.readyChannelMuxPromise = state.readyChannelMuxPromise
  71. self.scheduled = scheduled
  72. self.reason = state.error
  73. }
  74. init(
  75. from state: ReadyState,
  76. scheduled: Scheduled<Void>,
  77. backoffIterator: ConnectionBackoffIterator?
  78. ) {
  79. self.backoffIterator = backoffIterator
  80. self.readyChannelMuxPromise = state.channel.eventLoop.makePromise()
  81. self.scheduled = scheduled
  82. self.reason = state.error
  83. }
  84. }
  85. internal struct ShutdownState {
  86. var closeFuture: EventLoopFuture<Void>
  87. /// The reason we are shutdown. Any requests for a `Channel` in this state will be failed with
  88. /// this error.
  89. var reason: Error
  90. init(closeFuture: EventLoopFuture<Void>, reason: Error) {
  91. self.closeFuture = closeFuture
  92. self.reason = reason
  93. }
  94. static func shutdownByUser(closeFuture: EventLoopFuture<Void>) -> ShutdownState {
  95. return ShutdownState(
  96. closeFuture: closeFuture,
  97. reason: GRPCStatus(code: .unavailable, message: "Connection was shutdown by the user")
  98. )
  99. }
  100. }
  101. internal enum State {
  102. /// No `Channel` is required.
  103. ///
  104. /// Valid next states:
  105. /// - `connecting`
  106. /// - `shutdown`
  107. case idle
  108. /// We're actively trying to establish a connection.
  109. ///
  110. /// Valid next states:
  111. /// - `active`
  112. /// - `transientFailure` (if our attempt fails and we're going to try again)
  113. /// - `shutdown`
  114. case connecting(ConnectingState)
  115. /// We've established a `Channel`, it might not be suitable (TLS handshake may fail, etc.).
  116. /// Our signal to be 'ready' is the initial HTTP/2 SETTINGS frame.
  117. ///
  118. /// Valid next states:
  119. /// - `ready`
  120. /// - `transientFailure` (if we our handshake fails or other error happens and we can attempt
  121. /// to re-establish the connection)
  122. /// - `shutdown`
  123. case active(ConnectedState)
  124. /// We have an active `Channel` which has seen the initial HTTP/2 SETTINGS frame. We can use
  125. /// the channel for making RPCs.
  126. ///
  127. /// Valid next states:
  128. /// - `idle` (we're not serving any RPCs, we can drop the connection for now)
  129. /// - `transientFailure` (we encountered an error and will re-establish the connection)
  130. /// - `shutdown`
  131. case ready(ReadyState)
  132. /// A `Channel` is desired, we'll attempt to create one in the future.
  133. ///
  134. /// Valid next states:
  135. /// - `connecting`
  136. /// - `shutdown`
  137. case transientFailure(TransientFailureState)
  138. /// We never want another `Channel`: this state is terminal.
  139. case shutdown(ShutdownState)
  140. fileprivate var label: String {
  141. switch self {
  142. case .idle:
  143. return "idle"
  144. case .connecting:
  145. return "connecting"
  146. case .active:
  147. return "active"
  148. case .ready:
  149. return "ready"
  150. case .transientFailure:
  151. return "transientFailure"
  152. case .shutdown:
  153. return "shutdown"
  154. }
  155. }
  156. }
  157. private var state: State {
  158. didSet {
  159. switch self.state {
  160. case .idle:
  161. self.monitor.updateState(to: .idle, logger: self.logger)
  162. self.updateConnectionID()
  163. case .connecting:
  164. self.monitor.updateState(to: .connecting, logger: self.logger)
  165. // This is an internal state.
  166. case .active:
  167. ()
  168. case .ready:
  169. self.monitor.updateState(to: .ready, logger: self.logger)
  170. case .transientFailure:
  171. self.monitor.updateState(to: .transientFailure, logger: self.logger)
  172. self.updateConnectionID()
  173. case .shutdown:
  174. self.monitor.updateState(to: .shutdown, logger: self.logger)
  175. }
  176. }
  177. }
  178. /// The `EventLoop` that the managed connection will run on.
  179. internal let eventLoop: EventLoop
  180. /// A connectivity state monitor.
  181. internal let monitor: ConnectivityStateMonitor
  182. /// An `EventLoopFuture<Channel>` provider.
  183. private let channelProvider: ConnectionManagerChannelProvider
  184. /// The behavior for starting a call, i.e. how patient is the caller when asking for a
  185. /// multiplexer.
  186. private let callStartBehavior: CallStartBehavior.Behavior
  187. /// The configuration to use when backing off between connection attempts, if reconnection
  188. /// attempts should be made at all.
  189. private let connectionBackoff: ConnectionBackoff?
  190. /// A logger.
  191. internal var logger: Logger
  192. private let connectionID: String
  193. private var channelNumber: UInt64
  194. private var channelNumberLock = Lock()
  195. private var _connectionIDAndNumber: String {
  196. return "\(self.connectionID)/\(self.channelNumber)"
  197. }
  198. private var connectionIDAndNumber: String {
  199. return self.channelNumberLock.withLock {
  200. return self._connectionIDAndNumber
  201. }
  202. }
  203. private func updateConnectionID() {
  204. self.channelNumberLock.withLockVoid {
  205. self.channelNumber &+= 1
  206. self.logger[metadataKey: MetadataKey.connectionID] = "\(self._connectionIDAndNumber)"
  207. }
  208. }
  209. internal func appendMetadata(to logger: inout Logger) {
  210. logger[metadataKey: MetadataKey.connectionID] = "\(self.connectionIDAndNumber)"
  211. }
  212. internal convenience init(configuration: ClientConnection.Configuration, logger: Logger) {
  213. self.init(
  214. configuration: configuration,
  215. channelProvider: DefaultChannelProvider(configuration: configuration),
  216. logger: logger
  217. )
  218. }
  219. /// Create a `ConnectionManager` for testing: uses the given `channelProvider` to create channels.
  220. internal static func testingOnly(
  221. configuration: ClientConnection.Configuration,
  222. logger: Logger,
  223. channelProvider: @escaping () -> EventLoopFuture<Channel>
  224. ) -> ConnectionManager {
  225. struct Wrapper: ConnectionManagerChannelProvider {
  226. var callback: () -> EventLoopFuture<Channel>
  227. func makeChannel(
  228. managedBy connectionManager: ConnectionManager,
  229. onEventLoop eventLoop: EventLoop,
  230. connectTimeout: TimeAmount?,
  231. logger: Logger
  232. ) -> EventLoopFuture<Channel> {
  233. return self.callback().hop(to: eventLoop)
  234. }
  235. }
  236. return ConnectionManager(
  237. configuration: configuration,
  238. channelProvider: Wrapper(callback: channelProvider),
  239. logger: logger
  240. )
  241. }
  242. private convenience init(
  243. configuration: ClientConnection.Configuration,
  244. channelProvider: ConnectionManagerChannelProvider,
  245. logger: Logger
  246. ) {
  247. self.init(
  248. eventLoop: configuration.eventLoopGroup.next(),
  249. channelProvider: channelProvider,
  250. callStartBehavior: configuration.callStartBehavior.wrapped,
  251. connectionBackoff: configuration.connectionBackoff,
  252. connectivityStateDelegate: configuration.connectivityStateDelegate,
  253. connectivityStateDelegateQueue: configuration.connectivityStateDelegateQueue,
  254. logger: logger
  255. )
  256. }
  257. internal init(
  258. eventLoop: EventLoop,
  259. channelProvider: ConnectionManagerChannelProvider,
  260. callStartBehavior: CallStartBehavior.Behavior,
  261. connectionBackoff: ConnectionBackoff?,
  262. connectivityStateDelegate: ConnectivityStateDelegate?,
  263. connectivityStateDelegateQueue: DispatchQueue?,
  264. logger: Logger
  265. ) {
  266. // Setup the logger.
  267. var logger = logger
  268. let connectionID = UUID().uuidString
  269. let channelNumber: UInt64 = 0
  270. logger[metadataKey: MetadataKey.connectionID] = "\(connectionID)/\(channelNumber)"
  271. self.eventLoop = eventLoop
  272. self.state = .idle
  273. self.channelProvider = channelProvider
  274. self.callStartBehavior = callStartBehavior
  275. self.connectionBackoff = connectionBackoff
  276. self.monitor = ConnectivityStateMonitor(
  277. delegate: connectivityStateDelegate,
  278. queue: connectivityStateDelegateQueue
  279. )
  280. self.connectionID = connectionID
  281. self.channelNumber = channelNumber
  282. self.logger = logger
  283. }
  284. /// Get the multiplexer from the underlying channel handling gRPC calls.
  285. /// if the `ConnectionManager` was configured to be `fastFailure` this will have
  286. /// one chance to connect - if not reconnections are managed here.
  287. internal func getHTTP2Multiplexer() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  288. func getHTTP2Multiplexer0() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  289. switch self.callStartBehavior {
  290. case .waitsForConnectivity:
  291. return self.getHTTP2MultiplexerPatient()
  292. case .fastFailure:
  293. return self.getHTTP2MultiplexerOptimistic()
  294. }
  295. }
  296. if self.eventLoop.inEventLoop {
  297. return getHTTP2Multiplexer0()
  298. } else {
  299. return self.eventLoop.flatSubmit {
  300. getHTTP2Multiplexer0()
  301. }
  302. }
  303. }
  304. /// Returns a future for the multiplexer which succeeded when the channel is connected.
  305. /// Reconnects are handled if necessary.
  306. private func getHTTP2MultiplexerPatient() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  307. let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  308. switch self.state {
  309. case .idle:
  310. self.startConnecting()
  311. // We started connecting so we must transition to the `connecting` state.
  312. guard case let .connecting(connecting) = self.state else {
  313. self.invalidState()
  314. }
  315. multiplexer = connecting.readyChannelMuxPromise.futureResult
  316. case let .connecting(state):
  317. multiplexer = state.readyChannelMuxPromise.futureResult
  318. case let .active(state):
  319. multiplexer = state.readyChannelMuxPromise.futureResult
  320. case let .ready(state):
  321. multiplexer = self.eventLoop.makeSucceededFuture(state.multiplexer)
  322. case let .transientFailure(state):
  323. multiplexer = state.readyChannelMuxPromise.futureResult
  324. case let .shutdown(state):
  325. multiplexer = self.eventLoop.makeFailedFuture(state.reason)
  326. }
  327. self.logger.debug("vending multiplexer future", metadata: [
  328. "connectivity_state": "\(self.state.label)",
  329. ])
  330. return multiplexer
  331. }
  332. /// Returns a future for the current HTTP/2 stream multiplexer, or future HTTP/2 stream multiplexer from the current connection
  333. /// attempt, or if the state is 'idle' returns the future for the next connection attempt.
  334. ///
  335. /// Note: if the state is 'transientFailure' or 'shutdown' then a failed future will be returned.
  336. private func getHTTP2MultiplexerOptimistic() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  337. // `getHTTP2Multiplexer` makes sure we're on the event loop but let's just be sure.
  338. self.eventLoop.preconditionInEventLoop()
  339. let muxFuture: EventLoopFuture<HTTP2StreamMultiplexer> = { () in
  340. switch self.state {
  341. case .idle:
  342. self.startConnecting()
  343. // We started connecting so we must transition to the `connecting` state.
  344. guard case let .connecting(connecting) = self.state else {
  345. self.invalidState()
  346. }
  347. return connecting.candidateMuxPromise.futureResult
  348. case let .connecting(state):
  349. return state.candidateMuxPromise.futureResult
  350. case let .active(active):
  351. return self.eventLoop.makeSucceededFuture(active.multiplexer)
  352. case let .ready(ready):
  353. return self.eventLoop.makeSucceededFuture(ready.multiplexer)
  354. case let .transientFailure(state):
  355. // Provide the reason we failed transiently, if we can.
  356. let error = state.reason ?? GRPCStatus(
  357. code: .unavailable,
  358. message: "Connection multiplexer requested while backing off"
  359. )
  360. return self.eventLoop.makeFailedFuture(error)
  361. case let .shutdown(state):
  362. return self.eventLoop.makeFailedFuture(state.reason)
  363. }
  364. }()
  365. self.logger.debug("vending fast-failing multiplexer future", metadata: [
  366. "connectivity_state": "\(self.state.label)",
  367. ])
  368. return muxFuture
  369. }
  370. /// Shutdown any connection which exists. This is a request from the application.
  371. internal func shutdown() -> EventLoopFuture<Void> {
  372. return self.eventLoop.flatSubmit {
  373. self.logger.debug("shutting down connection", metadata: [
  374. "connectivity_state": "\(self.state.label)",
  375. ])
  376. let shutdown: ShutdownState
  377. switch self.state {
  378. // We don't have a channel and we don't want one, easy!
  379. case .idle:
  380. shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(()))
  381. self.state = .shutdown(shutdown)
  382. // We're mid-connection: the application doesn't have any 'ready' channels so we'll succeed
  383. // the shutdown future and deal with any fallout from the connecting channel without the
  384. // application knowing.
  385. case let .connecting(state):
  386. shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(()))
  387. self.state = .shutdown(shutdown)
  388. // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully
  389. // connect the application shouldn't have access to the channel or multiplexer.
  390. state.readyChannelMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  391. state.candidateMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  392. // In case we do successfully connect, close immediately.
  393. state.candidate.whenSuccess {
  394. $0.close(mode: .all, promise: nil)
  395. }
  396. // We have an active channel but the application doesn't know about it yet. We'll do the same
  397. // as for `.connecting`.
  398. case let .active(state):
  399. shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(()))
  400. self.state = .shutdown(shutdown)
  401. // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully
  402. // connect the application shouldn't have access to the channel or multiplexer.
  403. state.readyChannelMuxPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  404. // We have a channel, close it.
  405. state.candidate.close(mode: .all, promise: nil)
  406. // The channel is up and running: the application could be using it. We can close it and
  407. // return the `closeFuture`.
  408. case let .ready(state):
  409. shutdown = .shutdownByUser(closeFuture: state.channel.closeFuture)
  410. self.state = .shutdown(shutdown)
  411. // We have a channel, close it.
  412. state.channel.close(mode: .all, promise: nil)
  413. // Like `.connecting` and `.active` the application does not have a `.ready` channel. We'll
  414. // do the same but also cancel any scheduled connection attempts and deal with any fallout
  415. // if we cancelled too late.
  416. case let .transientFailure(state):
  417. shutdown = .shutdownByUser(closeFuture: self.eventLoop.makeSucceededFuture(()))
  418. self.state = .shutdown(shutdown)
  419. // Stop the creation of a new channel, if we can. If we can't then the task to
  420. // `startConnecting()` will see our new `shutdown` state and ignore the request to connect.
  421. state.scheduled.cancel()
  422. // Fail the ready channel mux promise: we're shutting down so even if we manage to successfully
  423. // connect the application shouldn't should have access to the channel.
  424. state.readyChannelMuxPromise.fail(shutdown.reason)
  425. // We're already shutdown; nothing to do.
  426. case let .shutdown(state):
  427. shutdown = state
  428. }
  429. return shutdown.closeFuture
  430. }
  431. }
  432. // MARK: - State changes from the channel handler.
  433. /// The channel caught an error. Hold on to it until the channel becomes inactive, it may provide
  434. /// some context.
  435. internal func channelError(_ error: Error) {
  436. self.eventLoop.preconditionInEventLoop()
  437. switch self.state {
  438. // Hitting an error in idle is a surprise, but not really something we do anything about. Either the
  439. // error is channel fatal, in which case we'll see channelInactive soon (acceptable), or it's not,
  440. // and future I/O will either fail fast or work. In either case, all we do is log this and move on.
  441. case .idle:
  442. self.logger.warning("ignoring unexpected error in idle", metadata: [
  443. MetadataKey.error: "\(error)",
  444. ])
  445. case .connecting:
  446. self.invalidState()
  447. case var .active(state):
  448. state.error = error
  449. self.state = .active(state)
  450. case var .ready(state):
  451. state.error = error
  452. self.state = .ready(state)
  453. // If we've already in one of these states, then additional errors aren't helpful to us.
  454. case .transientFailure, .shutdown:
  455. ()
  456. }
  457. }
  458. /// The connecting channel became `active`. Must be called on the `EventLoop`.
  459. internal func channelActive(channel: Channel, multiplexer: HTTP2StreamMultiplexer) {
  460. self.eventLoop.preconditionInEventLoop()
  461. self.logger.debug("activating connection", metadata: [
  462. "connectivity_state": "\(self.state.label)",
  463. ])
  464. switch self.state {
  465. case let .connecting(connecting):
  466. let connected = ConnectedState(from: connecting, candidate: channel, multiplexer: multiplexer)
  467. self.state = .active(connected)
  468. // Optimistic connections are happy this this level of setup.
  469. connecting.candidateMuxPromise.succeed(multiplexer)
  470. // Application called shutdown before the channel become active; we should close it.
  471. case .shutdown:
  472. channel.close(mode: .all, promise: nil)
  473. // These cases are purposefully separated: some crash reporting services provide stack traces
  474. // which don't include the precondition failure message (which contain the invalid state we were
  475. // in). Keeping the cases separate allows us work out the state from the line number.
  476. case .idle:
  477. self.invalidState()
  478. case .active:
  479. self.invalidState()
  480. case .ready:
  481. self.invalidState()
  482. case .transientFailure:
  483. self.invalidState()
  484. }
  485. }
  486. /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect?
  487. /// Must be called on the `EventLoop`.
  488. internal func channelInactive() {
  489. self.eventLoop.preconditionInEventLoop()
  490. self.logger.debug("deactivating connection", metadata: [
  491. "connectivity_state": "\(self.state.label)",
  492. ])
  493. switch self.state {
  494. // The channel is `active` but not `ready`. Should we try again?
  495. case let .active(active):
  496. let error = GRPCStatus(
  497. code: .unavailable,
  498. message: "The connection was dropped and connection re-establishment is disabled"
  499. )
  500. switch active.reconnect {
  501. // No, shutdown instead.
  502. case .none:
  503. self.logger.debug("shutting down connection")
  504. let shutdownState = ShutdownState(
  505. closeFuture: self.eventLoop.makeSucceededFuture(()),
  506. reason: error
  507. )
  508. self.state = .shutdown(shutdownState)
  509. active.readyChannelMuxPromise.fail(error)
  510. // Yes, after some time.
  511. case let .after(delay):
  512. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  513. self.startConnecting()
  514. }
  515. self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"])
  516. self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled))
  517. }
  518. // The channel was ready and working fine but something went wrong. Should we try to replace
  519. // the channel?
  520. case let .ready(ready):
  521. // No, no backoff is configured.
  522. if self.connectionBackoff == nil {
  523. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  524. self.state = .shutdown(
  525. ShutdownState(
  526. closeFuture: ready.channel.closeFuture,
  527. reason: GRPCStatus(
  528. code: .unavailable,
  529. message: "The connection was dropped and a reconnect was not configured"
  530. )
  531. )
  532. )
  533. } else {
  534. // Yes, start connecting now. We should go via `transientFailure`, however.
  535. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) {
  536. self.startConnecting()
  537. }
  538. self.logger.debug("scheduling connection attempt", metadata: ["delay": "0"])
  539. let backoffIterator = self.connectionBackoff?.makeIterator()
  540. self.state = .transientFailure(TransientFailureState(
  541. from: ready,
  542. scheduled: scheduled,
  543. backoffIterator: backoffIterator
  544. ))
  545. }
  546. // This is fine: we expect the channel to become inactive after becoming idle.
  547. case .idle:
  548. ()
  549. // We're already shutdown, that's fine.
  550. case .shutdown:
  551. ()
  552. // These cases are purposefully separated: some crash reporting services provide stack traces
  553. // which don't include the precondition failure message (which contain the invalid state we were
  554. // in). Keeping the cases separate allows us work out the state from the line number.
  555. case .connecting:
  556. self.invalidState()
  557. case .transientFailure:
  558. self.invalidState()
  559. }
  560. }
  561. /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be
  562. /// called on the `EventLoop`.
  563. internal func ready() {
  564. self.eventLoop.preconditionInEventLoop()
  565. self.logger.debug("connection ready", metadata: [
  566. "connectivity_state": "\(self.state.label)",
  567. ])
  568. switch self.state {
  569. case let .active(connected):
  570. self.state = .ready(ReadyState(from: connected))
  571. connected.readyChannelMuxPromise.succeed(connected.multiplexer)
  572. case .shutdown:
  573. ()
  574. // These cases are purposefully separated: some crash reporting services provide stack traces
  575. // which don't include the precondition failure message (which contain the invalid state we were
  576. // in). Keeping the cases separate allows us work out the state from the line number.
  577. case .idle:
  578. self.invalidState()
  579. case .transientFailure:
  580. self.invalidState()
  581. case .connecting:
  582. self.invalidState()
  583. case .ready:
  584. self.invalidState()
  585. }
  586. }
  587. /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on
  588. /// the `EventLoop`.
  589. internal func idle() {
  590. self.eventLoop.preconditionInEventLoop()
  591. self.logger.debug("idling connection", metadata: [
  592. "connectivity_state": "\(self.state.label)",
  593. ])
  594. switch self.state {
  595. case let .active(state):
  596. // This state is reachable if the keepalive timer fires before we reach the ready state.
  597. self.state = .idle
  598. state.readyChannelMuxPromise
  599. .fail(GRPCStatus(code: .unavailable, message: "Idled before reaching ready state"))
  600. case .ready:
  601. self.state = .idle
  602. case .shutdown:
  603. // This is expected when the connection is closed by the user: when the channel becomes
  604. // inactive and there are no outstanding RPCs, 'idle()' will be called instead of
  605. // 'channelInactive()'.
  606. ()
  607. // These cases are purposefully separated: some crash reporting services provide stack traces
  608. // which don't include the precondition failure message (which contain the invalid state we were
  609. // in). Keeping the cases separate allows us work out the state from the line number.
  610. case .idle:
  611. self.invalidState()
  612. case .connecting:
  613. self.invalidState()
  614. case .transientFailure:
  615. self.invalidState()
  616. }
  617. }
  618. /// The connection has started quiescing: notify the connectivity monitor of this.
  619. internal func beginQuiescing() {
  620. self.monitor.beginQuiescing()
  621. }
  622. }
  623. extension ConnectionManager {
  624. // A connection attempt failed; we never established a connection.
  625. private func connectionFailed(withError error: Error) {
  626. self.eventLoop.preconditionInEventLoop()
  627. switch self.state {
  628. case let .connecting(connecting):
  629. // Should we reconnect?
  630. switch connecting.reconnect {
  631. // No, shutdown.
  632. case .none:
  633. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  634. self.state = .shutdown(
  635. ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()), reason: error)
  636. )
  637. connecting.readyChannelMuxPromise.fail(error)
  638. connecting.candidateMuxPromise.fail(error)
  639. // Yes, after a delay.
  640. case let .after(delay):
  641. self.logger.debug("scheduling connection attempt", metadata: ["delay": "\(delay)"])
  642. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  643. self.startConnecting()
  644. }
  645. self.state = .transientFailure(
  646. TransientFailureState(from: connecting, scheduled: scheduled, reason: error)
  647. )
  648. // Candidate mux users are not willing to wait.
  649. connecting.candidateMuxPromise.fail(error)
  650. }
  651. // The application must have called shutdown while we were trying to establish a connection
  652. // which was doomed to fail anyway. That's fine, we can ignore this.
  653. case .shutdown:
  654. ()
  655. // We can't fail to connect if we aren't trying.
  656. //
  657. // These cases are purposefully separated: some crash reporting services provide stack traces
  658. // which don't include the precondition failure message (which contain the invalid state we were
  659. // in). Keeping the cases separate allows us work out the state from the line number.
  660. case .idle:
  661. self.invalidState()
  662. case .active:
  663. self.invalidState()
  664. case .ready:
  665. self.invalidState()
  666. case .transientFailure:
  667. self.invalidState()
  668. }
  669. }
  670. }
  671. extension ConnectionManager {
  672. // Start establishing a connection: we can only do this from the `idle` and `transientFailure`
  673. // states. Must be called on the `EventLoop`.
  674. private func startConnecting() {
  675. switch self.state {
  676. case .idle:
  677. let iterator = self.connectionBackoff?.makeIterator()
  678. self.startConnecting(
  679. backoffIterator: iterator,
  680. muxPromise: self.eventLoop.makePromise()
  681. )
  682. case let .transientFailure(pending):
  683. self.startConnecting(
  684. backoffIterator: pending.backoffIterator,
  685. muxPromise: pending.readyChannelMuxPromise
  686. )
  687. // We shutdown before a scheduled connection attempt had started.
  688. case .shutdown:
  689. ()
  690. // These cases are purposefully separated: some crash reporting services provide stack traces
  691. // which don't include the precondition failure message (which contain the invalid state we were
  692. // in). Keeping the cases separate allows us work out the state from the line number.
  693. case .connecting:
  694. self.invalidState()
  695. case .active:
  696. self.invalidState()
  697. case .ready:
  698. self.invalidState()
  699. }
  700. }
  701. private func startConnecting(
  702. backoffIterator: ConnectionBackoffIterator?,
  703. muxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  704. ) {
  705. let timeoutAndBackoff = backoffIterator?.next()
  706. // We're already on the event loop: submit the connect so it starts after we've made the
  707. // state change to `.connecting`.
  708. self.eventLoop.assertInEventLoop()
  709. let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit {
  710. let channel: EventLoopFuture<Channel> = self.channelProvider.makeChannel(
  711. managedBy: self,
  712. onEventLoop: self.eventLoop,
  713. connectTimeout: timeoutAndBackoff.map { .seconds(timeInterval: $0.timeout) },
  714. logger: self.logger
  715. )
  716. channel.whenFailure { error in
  717. self.connectionFailed(withError: error)
  718. }
  719. return channel
  720. }
  721. // Should we reconnect if the candidate channel fails?
  722. let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none
  723. let connecting = ConnectingState(
  724. backoffIterator: backoffIterator,
  725. reconnect: reconnect,
  726. candidate: candidate,
  727. readyChannelMuxPromise: muxPromise,
  728. candidateMuxPromise: self.eventLoop.makePromise()
  729. )
  730. self.state = .connecting(connecting)
  731. }
  732. }
  733. extension ConnectionManager {
  734. private func invalidState(
  735. function: StaticString = #function,
  736. file: StaticString = #file,
  737. line: UInt = #line
  738. ) -> Never {
  739. preconditionFailure("Invalid state \(self.state) for \(function)", file: file, line: line)
  740. }
  741. }