ConnectionManager.swift 30 KB

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