ConnectionManager.swift 37 KB

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