ConnectionManager.swift 38 KB

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