ConnectionManager.swift 32 KB

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