ConnectionManager.swift 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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 = reason ?? GRPCStatus(
  72. code: .unavailable,
  73. message: "Unexpected connection drop"
  74. )
  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.unreachableState()
  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.unreachableState()
  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. case .idle, .transientFailure:
  577. // Received a channelActive when not connecting. Can happen if channelActive and
  578. // channelInactive are reordered. Ignore.
  579. ()
  580. case .active, .ready:
  581. // Received a second 'channelActive', already active so ignore.
  582. ()
  583. }
  584. }
  585. /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect?
  586. /// Must be called on the `EventLoop`.
  587. internal func channelInactive() {
  588. self.eventLoop.preconditionInEventLoop()
  589. self.logger.debug("deactivating connection", metadata: [
  590. "connectivity_state": "\(self.state.label)",
  591. ])
  592. switch self.state {
  593. // We can hit inactive in connecting if we see channelInactive before channelActive; that's not
  594. // common but we should tolerate it.
  595. case let .connecting(connecting):
  596. // Should we try connecting again?
  597. switch connecting.reconnect {
  598. // No, shutdown instead.
  599. case .none:
  600. self.logger.debug("shutting down connection")
  601. let error = GRPCStatus(
  602. code: .unavailable,
  603. message: "The connection was dropped and connection re-establishment is disabled"
  604. )
  605. let shutdownState = ShutdownState(
  606. closeFuture: self.eventLoop.makeSucceededFuture(()),
  607. reason: error
  608. )
  609. self.state = .shutdown(shutdownState)
  610. // Shutting down, so fail the outstanding promises.
  611. connecting.readyChannelMuxPromise.fail(error)
  612. connecting.candidateMuxPromise.fail(error)
  613. // Yes, after some time.
  614. case let .after(delay):
  615. let error = GRPCStatus(code: .unavailable, message: "Connection closed while connecting")
  616. // Fail the candidate mux promise. KEep the 'readyChannelMuxPromise' as we'll try again.
  617. connecting.candidateMuxPromise.fail(error)
  618. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  619. self.startConnecting()
  620. }
  621. self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"])
  622. self.state = .transientFailure(.init(from: connecting, scheduled: scheduled, reason: nil))
  623. }
  624. // The channel is `active` but not `ready`. Should we try again?
  625. case let .active(active):
  626. switch active.reconnect {
  627. // No, shutdown instead.
  628. case .none:
  629. self.logger.debug("shutting down connection")
  630. let error = GRPCStatus(
  631. code: .unavailable,
  632. message: "The connection was dropped and connection re-establishment is disabled"
  633. )
  634. let shutdownState = ShutdownState(
  635. closeFuture: self.eventLoop.makeSucceededFuture(()),
  636. reason: error
  637. )
  638. self.state = .shutdown(shutdownState)
  639. active.readyChannelMuxPromise.fail(error)
  640. // Yes, after some time.
  641. case let .after(delay):
  642. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  643. self.startConnecting()
  644. }
  645. self.logger.debug("scheduling connection attempt", metadata: ["delay_secs": "\(delay)"])
  646. self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled))
  647. }
  648. // The channel was ready and working fine but something went wrong. Should we try to replace
  649. // the channel?
  650. case let .ready(ready):
  651. // No, no backoff is configured.
  652. if self.connectionBackoff == nil {
  653. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  654. self.state = .shutdown(
  655. ShutdownState(
  656. closeFuture: ready.channel.closeFuture,
  657. reason: GRPCStatus(
  658. code: .unavailable,
  659. message: "The connection was dropped and a reconnect was not configured"
  660. )
  661. )
  662. )
  663. } else {
  664. // Yes, start connecting now. We should go via `transientFailure`, however.
  665. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) {
  666. self.startConnecting()
  667. }
  668. self.logger.debug("scheduling connection attempt", metadata: ["delay": "0"])
  669. let backoffIterator = self.connectionBackoff?.makeIterator()
  670. self.state = .transientFailure(TransientFailureState(
  671. from: ready,
  672. scheduled: scheduled,
  673. backoffIterator: backoffIterator
  674. ))
  675. }
  676. // This is fine: we expect the channel to become inactive after becoming idle.
  677. case .idle:
  678. ()
  679. // We're already shutdown, that's fine.
  680. case .shutdown:
  681. ()
  682. // Received 'channelInactive' twice; fine, ignore.
  683. case .transientFailure:
  684. ()
  685. }
  686. }
  687. /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be
  688. /// called on the `EventLoop`.
  689. internal func ready() {
  690. self.eventLoop.preconditionInEventLoop()
  691. self.logger.debug("connection ready", metadata: [
  692. "connectivity_state": "\(self.state.label)",
  693. ])
  694. switch self.state {
  695. case let .active(connected):
  696. self.state = .ready(ReadyState(from: connected))
  697. connected.readyChannelMuxPromise.succeed(connected.multiplexer)
  698. case .shutdown:
  699. ()
  700. case .idle, .transientFailure:
  701. // No connection or connection attempt exists but connection was marked as ready. This is
  702. // strange. Ignore it in release mode as there's nothing to close and nowehere to fire an
  703. // error to.
  704. assertionFailure("received initial HTTP/2 SETTINGS frame in \(self.state.label) state")
  705. case .connecting:
  706. // No channel exists to receive initial HTTP/2 SETTINGS frame on... weird. Ignore in release
  707. // mode.
  708. assertionFailure("received initial HTTP/2 SETTINGS frame in \(self.state.label) state")
  709. case .ready:
  710. // Already received initial HTTP/2 SETTINGS frame; ignore in release mode.
  711. assertionFailure("received initial HTTP/2 SETTINGS frame in \(self.state.label) state")
  712. }
  713. }
  714. /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on
  715. /// the `EventLoop`.
  716. internal func idle() {
  717. self.eventLoop.preconditionInEventLoop()
  718. self.logger.debug("idling connection", metadata: [
  719. "connectivity_state": "\(self.state.label)",
  720. ])
  721. switch self.state {
  722. case let .active(state):
  723. // This state is reachable if the keepalive timer fires before we reach the ready state.
  724. self.state = .idle(lastError: state.error)
  725. state.readyChannelMuxPromise
  726. .fail(GRPCStatus(code: .unavailable, message: "Idled before reaching ready state"))
  727. case let .ready(state):
  728. self.state = .idle(lastError: state.error)
  729. case .shutdown:
  730. // This is expected when the connection is closed by the user: when the channel becomes
  731. // inactive and there are no outstanding RPCs, 'idle()' will be called instead of
  732. // 'channelInactive()'.
  733. ()
  734. case .idle, .transientFailure:
  735. // There's no connection to idle; ignore.
  736. ()
  737. case .connecting:
  738. // The idle watchdog is started when the connection is active, this shouldn't happen
  739. // in the connecting state. Ignore it in release mode.
  740. assertionFailure("tried to idle a connection in the \(self.state.label) state")
  741. }
  742. }
  743. internal func streamOpened() {
  744. self.eventLoop.assertInEventLoop()
  745. self.http2Delegate?.streamOpened(self)
  746. }
  747. internal func streamClosed() {
  748. self.eventLoop.assertInEventLoop()
  749. self.http2Delegate?.streamClosed(self)
  750. }
  751. internal func maxConcurrentStreamsChanged(_ maxConcurrentStreams: Int) {
  752. self.eventLoop.assertInEventLoop()
  753. self.http2Delegate?.receivedSettingsMaxConcurrentStreams(
  754. self, maxConcurrentStreams: maxConcurrentStreams
  755. )
  756. }
  757. /// The connection has started quiescing: notify the connectivity monitor of this.
  758. internal func beginQuiescing() {
  759. self.eventLoop.assertInEventLoop()
  760. self.connectivityDelegate?.connectionIsQuiescing(self)
  761. }
  762. }
  763. extension ConnectionManager {
  764. // A connection attempt failed; we never established a connection.
  765. private func connectionFailed(withError error: Error) {
  766. self.eventLoop.preconditionInEventLoop()
  767. switch self.state {
  768. case let .connecting(connecting):
  769. // Should we reconnect?
  770. switch connecting.reconnect {
  771. // No, shutdown.
  772. case .none:
  773. self.logger.debug("shutting down connection, no reconnect configured/remaining")
  774. self.state = .shutdown(
  775. ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()), reason: error)
  776. )
  777. connecting.readyChannelMuxPromise.fail(error)
  778. connecting.candidateMuxPromise.fail(error)
  779. // Yes, after a delay.
  780. case let .after(delay):
  781. self.logger.debug("scheduling connection attempt", metadata: ["delay": "\(delay)"])
  782. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  783. self.startConnecting()
  784. }
  785. self.state = .transientFailure(
  786. TransientFailureState(from: connecting, scheduled: scheduled, reason: error)
  787. )
  788. // Candidate mux users are not willing to wait.
  789. connecting.candidateMuxPromise.fail(error)
  790. }
  791. // The application must have called shutdown while we were trying to establish a connection
  792. // which was doomed to fail anyway. That's fine, we can ignore this.
  793. case .shutdown:
  794. ()
  795. // Connection attempt failed, but no connection attempt is in progress.
  796. case .idle, .active, .ready, .transientFailure:
  797. // Nothing we can do other than ignore in release mode.
  798. assertionFailure("connect promise failed in \(self.state.label) state")
  799. }
  800. }
  801. }
  802. extension ConnectionManager {
  803. // Start establishing a connection: we can only do this from the `idle` and `transientFailure`
  804. // states. Must be called on the `EventLoop`.
  805. private func startConnecting() {
  806. self.eventLoop.assertInEventLoop()
  807. switch self.state {
  808. case .idle:
  809. let iterator = self.connectionBackoff?.makeIterator()
  810. self.startConnecting(
  811. backoffIterator: iterator,
  812. muxPromise: self.eventLoop.makePromise()
  813. )
  814. case let .transientFailure(pending):
  815. self.startConnecting(
  816. backoffIterator: pending.backoffIterator,
  817. muxPromise: pending.readyChannelMuxPromise
  818. )
  819. // We shutdown before a scheduled connection attempt had started.
  820. case .shutdown:
  821. ()
  822. // We only call startConnecting() if the connection does not exist and after checking what the
  823. // current state is, so none of these states should be reachable.
  824. case .connecting:
  825. self.unreachableState()
  826. case .active:
  827. self.unreachableState()
  828. case .ready:
  829. self.unreachableState()
  830. }
  831. }
  832. private func startConnecting(
  833. backoffIterator: ConnectionBackoffIterator?,
  834. muxPromise: EventLoopPromise<HTTP2StreamMultiplexer>
  835. ) {
  836. let timeoutAndBackoff = backoffIterator?.next()
  837. // We're already on the event loop: submit the connect so it starts after we've made the
  838. // state change to `.connecting`.
  839. self.eventLoop.assertInEventLoop()
  840. let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit {
  841. let channel: EventLoopFuture<Channel> = self.channelProvider.makeChannel(
  842. managedBy: self,
  843. onEventLoop: self.eventLoop,
  844. connectTimeout: timeoutAndBackoff.map { .seconds(timeInterval: $0.timeout) },
  845. logger: self.logger
  846. )
  847. channel.whenFailure { error in
  848. self.connectionFailed(withError: error)
  849. }
  850. return channel
  851. }
  852. // Should we reconnect if the candidate channel fails?
  853. let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none
  854. let connecting = ConnectingState(
  855. backoffIterator: backoffIterator,
  856. reconnect: reconnect,
  857. candidate: candidate,
  858. readyChannelMuxPromise: muxPromise,
  859. candidateMuxPromise: self.eventLoop.makePromise()
  860. )
  861. self.state = .connecting(connecting)
  862. }
  863. }
  864. extension ConnectionManager {
  865. /// Returns a synchronous view of the connection manager; each operation requires the caller to be
  866. /// executing on the same `EventLoop` as the connection manager.
  867. internal var sync: Sync {
  868. return Sync(self)
  869. }
  870. internal struct Sync {
  871. private let manager: ConnectionManager
  872. fileprivate init(_ manager: ConnectionManager) {
  873. self.manager = manager
  874. }
  875. /// A delegate for connectivity changes.
  876. internal var connectivityDelegate: ConnectionManagerConnectivityDelegate? {
  877. get {
  878. self.manager.eventLoop.assertInEventLoop()
  879. return self.manager.connectivityDelegate
  880. }
  881. nonmutating set {
  882. self.manager.eventLoop.assertInEventLoop()
  883. self.manager.connectivityDelegate = newValue
  884. }
  885. }
  886. /// A delegate for HTTP/2 connection changes.
  887. internal var http2Delegate: ConnectionManagerHTTP2Delegate? {
  888. get {
  889. self.manager.eventLoop.assertInEventLoop()
  890. return self.manager.http2Delegate
  891. }
  892. nonmutating set {
  893. self.manager.eventLoop.assertInEventLoop()
  894. self.manager.http2Delegate = newValue
  895. }
  896. }
  897. /// Returns `true` if the connection is in the idle state.
  898. internal var isIdle: Bool {
  899. return self.manager.isIdle
  900. }
  901. /// Returne `true` if the connection is in the shutdown state.
  902. internal var isShutdown: Bool {
  903. return self.manager.isShutdown
  904. }
  905. /// Returns the `multiplexer` from a connection in the `ready` state or `nil` if it is any
  906. /// other state.
  907. internal var multiplexer: HTTP2StreamMultiplexer? {
  908. return self.manager.multiplexer
  909. }
  910. // Start establishing a connection. Must only be called when `isIdle` is `true`.
  911. internal func startConnecting() {
  912. self.manager.startConnecting()
  913. }
  914. }
  915. }
  916. extension ConnectionManager {
  917. private func unreachableState(
  918. function: StaticString = #function,
  919. file: StaticString = #fileID,
  920. line: UInt = #line
  921. ) -> Never {
  922. fatalError("Invalid state \(self.state) for \(function)", file: file, line: line)
  923. }
  924. }