ConnectionPool.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. /*
  2. * Copyright 2021, 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 Logging
  17. import NIOConcurrencyHelpers
  18. import NIOCore
  19. import NIOHTTP2
  20. @usableFromInline
  21. internal final class ConnectionPool {
  22. /// The event loop all connections in this pool are running on.
  23. @usableFromInline
  24. internal let eventLoop: EventLoop
  25. @usableFromInline
  26. internal enum State {
  27. case active
  28. case shuttingDown(EventLoopFuture<Void>)
  29. case shutdown
  30. }
  31. /// The state of the connection pool.
  32. @usableFromInline
  33. internal var _state: State = .active
  34. /// The most recent connection error we have observed.
  35. ///
  36. /// This error is used to provide additional context to failed waiters. A waiter may, for example,
  37. /// timeout because the pool is busy, or because no connection can be established because of an
  38. /// underlying connection error. In the latter case it's useful for the caller to know why the
  39. /// connection is failing at the RPC layer.
  40. ///
  41. /// This value is cleared when a connection becomes 'available'. That is, when we receive an
  42. /// http/2 SETTINGS frame.
  43. ///
  44. /// This value is set whenever an underlying connection transitions to the transient failure state
  45. /// or to the idle state and has an associated error.
  46. @usableFromInline
  47. internal var _mostRecentError: Error? = nil
  48. /// Connection managers and their stream availability state keyed by the ID of the connection
  49. /// manager.
  50. ///
  51. /// Connections are accessed by their ID for connection state changes (infrequent) and when
  52. /// streams are closed (frequent). However when choosing which connection to succeed a waiter
  53. /// with (frequent) requires the connections to be ordered by their availability. A dictionary
  54. /// might not be the most efficient data structure (a queue prioritised by stream availability may
  55. /// be a better choice given the number of connections is likely to be very low in practice).
  56. @usableFromInline
  57. internal var _connections: [ConnectionManagerID: PerConnectionState]
  58. /// The threshold which if exceeded when creating a stream determines whether the pool will
  59. /// start connecting an idle connection (if one exists).
  60. ///
  61. /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of waiters
  62. /// and the number of reserved streams) and the total number of streams which non-idle connections
  63. /// could support (this includes the streams that a connection in the connecting state could
  64. /// support).
  65. @usableFromInline
  66. internal let reservationLoadThreshold: Double
  67. /// The assumed value for the maximum number of concurrent streams a connection can support. We
  68. /// assume a connection will support this many streams until we know better.
  69. @usableFromInline
  70. internal let assumedMaxConcurrentStreams: Int
  71. /// A queue of waiters which may or may not get a stream in the future.
  72. @usableFromInline
  73. internal var waiters: CircularBuffer<Waiter>
  74. /// The maximum number of waiters allowed, the size of `waiters` must not exceed this value. If
  75. /// there are this many waiters in the queue then the next waiter will be failed immediately.
  76. @usableFromInline
  77. internal let maxWaiters: Int
  78. /// Configuration for backoff between subsequence connection attempts.
  79. @usableFromInline
  80. internal let connectionBackoff: ConnectionBackoff
  81. /// Provides a channel factory to the `ConnectionManager`.
  82. @usableFromInline
  83. internal let channelProvider: ConnectionManagerChannelProvider
  84. /// The object to notify about changes to stream reservations; in practice this is usually
  85. /// the `PoolManager`.
  86. @usableFromInline
  87. internal let streamLender: StreamLender
  88. /// A logger which always sets "GRPC" as its source.
  89. @usableFromInline
  90. internal let logger: GRPCLogger
  91. /// Returns `NIODeadline` representing 'now'. This is useful for testing.
  92. @usableFromInline
  93. internal let now: () -> NIODeadline
  94. /// Logging metadata keys.
  95. @usableFromInline
  96. internal enum Metadata {
  97. /// The ID of this pool.
  98. @usableFromInline
  99. static let id = "pool.id"
  100. /// The number of stream reservations (i.e. number of open streams + number of waiters).
  101. @usableFromInline
  102. static let reservationsCount = "pool.reservations.count"
  103. /// The number of streams this pool can support with non-idle connections at this time.
  104. @usableFromInline
  105. static let reservationsCapacity = "pool.reservations.capacity"
  106. /// The current reservation load (i.e. reservation count / reservation capacity)
  107. @usableFromInline
  108. static let reservationsLoad = "pool.reservations.load"
  109. /// The reservation load threshold, above which a new connection will be created (if possible).
  110. @usableFromInline
  111. static let reservationsLoadThreshold = "pool.reservations.loadThreshold"
  112. /// The current number of waiters in the pool.
  113. @usableFromInline
  114. static let waitersCount = "pool.waiters.count"
  115. /// The maximum number of waiters the pool is configured to allow.
  116. @usableFromInline
  117. static let waitersMax = "pool.waiters.max"
  118. /// The number of waiters which were successfully serviced.
  119. @usableFromInline
  120. static let waitersServiced = "pool.waiters.serviced"
  121. /// The ID of waiter.
  122. @usableFromInline
  123. static let waiterID = "pool.waiter.id"
  124. }
  125. @usableFromInline
  126. init(
  127. eventLoop: EventLoop,
  128. maxWaiters: Int,
  129. reservationLoadThreshold: Double,
  130. assumedMaxConcurrentStreams: Int,
  131. connectionBackoff: ConnectionBackoff,
  132. channelProvider: ConnectionManagerChannelProvider,
  133. streamLender: StreamLender,
  134. logger: GRPCLogger,
  135. now: @escaping () -> NIODeadline = NIODeadline.now
  136. ) {
  137. precondition(
  138. (0.0 ... 1.0).contains(reservationLoadThreshold),
  139. "reservationLoadThreshold must be within the range 0.0 ... 1.0"
  140. )
  141. self.reservationLoadThreshold = reservationLoadThreshold
  142. self.assumedMaxConcurrentStreams = assumedMaxConcurrentStreams
  143. self._connections = [:]
  144. self.maxWaiters = maxWaiters
  145. self.waiters = CircularBuffer(initialCapacity: 16)
  146. self.eventLoop = eventLoop
  147. self.connectionBackoff = connectionBackoff
  148. self.channelProvider = channelProvider
  149. self.streamLender = streamLender
  150. self.logger = logger
  151. self.now = now
  152. }
  153. /// Initialize the connection pool.
  154. ///
  155. /// - Parameter connections: The number of connections to add to the pool.
  156. internal func initialize(connections: Int) {
  157. assert(self._connections.isEmpty)
  158. self._connections.reserveCapacity(connections)
  159. while self._connections.count < connections {
  160. self.addConnectionToPool()
  161. }
  162. }
  163. /// Make and add a new connection to the pool.
  164. private func addConnectionToPool() {
  165. let manager = ConnectionManager(
  166. eventLoop: self.eventLoop,
  167. channelProvider: self.channelProvider,
  168. callStartBehavior: .waitsForConnectivity,
  169. connectionBackoff: self.connectionBackoff,
  170. connectivityDelegate: self,
  171. http2Delegate: self,
  172. logger: self.logger.unwrapped
  173. )
  174. self._connections[manager.id] = PerConnectionState(manager: manager)
  175. }
  176. // MARK: - Called from the pool manager
  177. /// Make and initialize an HTTP/2 stream `Channel`.
  178. ///
  179. /// - Parameters:
  180. /// - deadline: The point in time by which the `promise` must have been resolved.
  181. /// - promise: A promise for a `Channel`.
  182. /// - logger: A request logger.
  183. /// - initializer: A closure to initialize the `Channel` with.
  184. @inlinable
  185. internal func makeStream(
  186. deadline: NIODeadline,
  187. promise: EventLoopPromise<Channel>,
  188. logger: GRPCLogger,
  189. initializer: @escaping (Channel) -> EventLoopFuture<Void>
  190. ) {
  191. if self.eventLoop.inEventLoop {
  192. self._makeStream(
  193. deadline: deadline,
  194. promise: promise,
  195. logger: logger,
  196. initializer: initializer
  197. )
  198. } else {
  199. self.eventLoop.execute {
  200. self._makeStream(
  201. deadline: deadline,
  202. promise: promise,
  203. logger: logger,
  204. initializer: initializer
  205. )
  206. }
  207. }
  208. }
  209. /// See `makeStream(deadline:promise:logger:initializer:)`.
  210. @inlinable
  211. internal func makeStream(
  212. deadline: NIODeadline,
  213. logger: GRPCLogger,
  214. initializer: @escaping (Channel) -> EventLoopFuture<Void>
  215. ) -> EventLoopFuture<Channel> {
  216. let promise = self.eventLoop.makePromise(of: Channel.self)
  217. self.makeStream(deadline: deadline, promise: promise, logger: logger, initializer: initializer)
  218. return promise.futureResult
  219. }
  220. /// Shutdown the connection pool.
  221. ///
  222. /// Existing waiters will be failed and all underlying connections will be shutdown. Subsequent
  223. /// calls to `makeStream` will be failed immediately.
  224. internal func shutdown() -> EventLoopFuture<Void> {
  225. let promise = self.eventLoop.makePromise(of: Void.self)
  226. if self.eventLoop.inEventLoop {
  227. self._shutdown(promise: promise)
  228. } else {
  229. self.eventLoop.execute {
  230. self._shutdown(promise: promise)
  231. }
  232. }
  233. return promise.futureResult
  234. }
  235. /// See `makeStream(deadline:promise:logger:initializer:)`.
  236. ///
  237. /// - Important: Must be called on the pool's `EventLoop`.
  238. @inlinable
  239. internal func _makeStream(
  240. deadline: NIODeadline,
  241. promise: EventLoopPromise<Channel>,
  242. logger: GRPCLogger,
  243. initializer: @escaping (Channel) -> EventLoopFuture<Void>
  244. ) {
  245. self.eventLoop.assertInEventLoop()
  246. guard case .active = self._state else {
  247. // Fail the promise right away if we're shutting down or already shut down.
  248. promise.fail(ConnectionPoolError.shutdown)
  249. return
  250. }
  251. // Try to make a stream on an existing connection.
  252. let streamCreated = self._tryMakeStream(promise: promise, initializer: initializer)
  253. if !streamCreated {
  254. // No stream was created, wait for one.
  255. self._enqueueWaiter(
  256. deadline: deadline,
  257. promise: promise,
  258. logger: logger,
  259. initializer: initializer
  260. )
  261. }
  262. }
  263. /// Try to find an existing connection on which we can make a stream.
  264. ///
  265. /// - Parameters:
  266. /// - promise: A promise to succeed if we can make a stream.
  267. /// - initializer: A closure to initialize the stream with.
  268. /// - Returns: A boolean value indicating whether the stream was created or not.
  269. @inlinable
  270. internal func _tryMakeStream(
  271. promise: EventLoopPromise<Channel>,
  272. initializer: @escaping (Channel) -> EventLoopFuture<Void>
  273. ) -> Bool {
  274. // We shouldn't jump the queue.
  275. guard self.waiters.isEmpty else {
  276. return false
  277. }
  278. // Reserve a stream, if we can.
  279. guard let multiplexer = self._reserveStreamFromMostAvailableConnection() else {
  280. return false
  281. }
  282. multiplexer.createStreamChannel(promise: promise, initializer)
  283. // Has reserving another stream tipped us over the limit for needing another connection?
  284. if self._shouldBringUpAnotherConnection() {
  285. self._startConnectingIdleConnection()
  286. }
  287. return true
  288. }
  289. /// Enqueue a waiter to be provided with a stream at some point in the future.
  290. ///
  291. /// - Parameters:
  292. /// - deadline: The point in time by which the promise should have been completed.
  293. /// - promise: The promise to complete with the `Channel`.
  294. /// - logger: A logger.
  295. /// - initializer: A closure to initialize the `Channel` with.
  296. @inlinable
  297. internal func _enqueueWaiter(
  298. deadline: NIODeadline,
  299. promise: EventLoopPromise<Channel>,
  300. logger: GRPCLogger,
  301. initializer: @escaping (Channel) -> EventLoopFuture<Void>
  302. ) {
  303. // Don't overwhelm the pool with too many waiters.
  304. guard self.waiters.count < self.maxWaiters else {
  305. logger.trace("connection pool has too many waiters", metadata: [
  306. Metadata.waitersMax: "\(self.maxWaiters)",
  307. ])
  308. promise.fail(ConnectionPoolError.tooManyWaiters(connectionError: self._mostRecentError))
  309. return
  310. }
  311. let waiter = Waiter(deadline: deadline, promise: promise, channelInitializer: initializer)
  312. // Fail the waiter and punt it from the queue when it times out. It's okay that we schedule the
  313. // timeout before appending it to the waiters, it wont run until the next event loop tick at the
  314. // earliest (even if the deadline has already passed).
  315. waiter.scheduleTimeout(on: self.eventLoop) {
  316. waiter.fail(ConnectionPoolError.deadlineExceeded(connectionError: self._mostRecentError))
  317. if let index = self.waiters.firstIndex(where: { $0.id == waiter.id }) {
  318. self.waiters.remove(at: index)
  319. logger.trace("timed out waiting for a connection", metadata: [
  320. Metadata.waiterID: "\(waiter.id)",
  321. Metadata.waitersCount: "\(self.waiters.count)",
  322. ])
  323. }
  324. }
  325. // request logger
  326. logger.debug("waiting for a connection to become available", metadata: [
  327. Metadata.waiterID: "\(waiter.id)",
  328. Metadata.waitersCount: "\(self.waiters.count)",
  329. ])
  330. self.waiters.append(waiter)
  331. // pool logger
  332. self.logger.trace("enqueued connection waiter", metadata: [
  333. Metadata.waitersCount: "\(self.waiters.count)",
  334. ])
  335. if self._shouldBringUpAnotherConnection() {
  336. self._startConnectingIdleConnection()
  337. }
  338. }
  339. /// Compute the current demand and capacity for streams.
  340. ///
  341. /// The 'demand' for streams is the number of reserved streams and the number of waiters. The
  342. /// capacity for streams is the product of max concurrent streams and the number of non-idle
  343. /// connections.
  344. ///
  345. /// - Returns: A tuple of the demand and capacity for streams.
  346. @usableFromInline
  347. internal func _computeStreamDemandAndCapacity() -> (demand: Int, capacity: Int) {
  348. let demand = self.sync.reservedStreams + self.sync.waiters
  349. // TODO: make this cheaper by storing and incrementally updating the number of idle connections
  350. let capacity = self._connections.values.reduce(0) { sum, state in
  351. if state.manager.sync.isIdle {
  352. // Idle connection, no capacity.
  353. return sum
  354. } else if let knownMaxAvailableStreams = state.maxAvailableStreams {
  355. // A known value of max concurrent streams, i.e. the connection is active.
  356. return sum + knownMaxAvailableStreams
  357. } else {
  358. // Not idle and no known value, the connection must be connecting so use our assumed value.
  359. return sum + self.assumedMaxConcurrentStreams
  360. }
  361. }
  362. return (demand, capacity)
  363. }
  364. /// Returns whether the pool should start connecting an idle connection (if one exists).
  365. @usableFromInline
  366. internal func _shouldBringUpAnotherConnection() -> Bool {
  367. let (demand, capacity) = self._computeStreamDemandAndCapacity()
  368. // Infinite -- i.e. all connections are idle or no connections exist -- is okay here as it
  369. // will always be greater than the threshold and a new connection will be spun up.
  370. let load = Double(demand) / Double(capacity)
  371. let loadExceedsThreshold = load >= self.reservationLoadThreshold
  372. if loadExceedsThreshold {
  373. self.logger.debug(
  374. "stream reservation load factor greater than or equal to threshold, bringing up additional connection if available",
  375. metadata: [
  376. Metadata.reservationsCount: "\(demand)",
  377. Metadata.reservationsCapacity: "\(capacity)",
  378. Metadata.reservationsLoad: "\(load)",
  379. Metadata.reservationsLoadThreshold: "\(self.reservationLoadThreshold)",
  380. ]
  381. )
  382. }
  383. return loadExceedsThreshold
  384. }
  385. /// Starts connecting an idle connection, if one exists.
  386. @usableFromInline
  387. internal func _startConnectingIdleConnection() {
  388. if let index = self._connections.values.firstIndex(where: { $0.manager.sync.isIdle }) {
  389. self._connections.values[index].manager.sync.startConnecting()
  390. }
  391. }
  392. /// Returns the index in `self.connections.values` of the connection with the most available
  393. /// streams. Returns `self.connections.endIndex` if no connection has at least one stream
  394. /// available.
  395. ///
  396. /// - Note: this is linear in the number of connections.
  397. @usableFromInline
  398. internal func _mostAvailableConnectionIndex(
  399. ) -> Dictionary<ConnectionManagerID, PerConnectionState>.Index {
  400. var index = self._connections.values.startIndex
  401. var selectedIndex = self._connections.values.endIndex
  402. var mostAvailableStreams = 0
  403. while index != self._connections.values.endIndex {
  404. let availableStreams = self._connections.values[index].availableStreams
  405. if availableStreams > mostAvailableStreams {
  406. mostAvailableStreams = availableStreams
  407. selectedIndex = index
  408. }
  409. self._connections.values.formIndex(after: &index)
  410. }
  411. return selectedIndex
  412. }
  413. /// Reserves a stream from the connection with the most available streams, if one exists.
  414. ///
  415. /// - Returns: The `HTTP2StreamMultiplexer` from the connection the stream was reserved from,
  416. /// or `nil` if no stream could be reserved.
  417. @usableFromInline
  418. internal func _reserveStreamFromMostAvailableConnection() -> HTTP2StreamMultiplexer? {
  419. let index = self._mostAvailableConnectionIndex()
  420. if index != self._connections.endIndex {
  421. // '!' is okay here; the most available connection must have at least one stream available
  422. // to reserve.
  423. return self._connections.values[index].reserveStream()!
  424. } else {
  425. return nil
  426. }
  427. }
  428. /// See `shutdown()`.
  429. ///
  430. /// - Parameter promise: A `promise` to complete when the pool has been shutdown.
  431. @usableFromInline
  432. internal func _shutdown(promise: EventLoopPromise<Void>) {
  433. self.eventLoop.assertInEventLoop()
  434. switch self._state {
  435. case .active:
  436. self.logger.debug("shutting down connection pool")
  437. // We're shutting down now and when that's done we'll be fully shutdown.
  438. self._state = .shuttingDown(promise.futureResult)
  439. promise.futureResult.whenComplete { _ in
  440. self._state = .shutdown
  441. self.logger.trace("finished shutting down connection pool")
  442. }
  443. // Shutdown all the connections and remove them from the pool.
  444. let allShutdown: [EventLoopFuture<Void>] = self._connections.values.map {
  445. return $0.manager.shutdown()
  446. }
  447. self._connections.removeAll()
  448. // Fail the outstanding waiters.
  449. while let waiter = self.waiters.popFirst() {
  450. waiter.fail(ConnectionPoolError.shutdown)
  451. }
  452. // Cascade the result of the shutdown into the promise.
  453. EventLoopFuture.andAllSucceed(allShutdown, promise: promise)
  454. case let .shuttingDown(future):
  455. // We're already shutting down, cascade the result.
  456. promise.completeWith(future)
  457. case .shutdown:
  458. // Already shutdown, fine.
  459. promise.succeed(())
  460. }
  461. }
  462. }
  463. extension ConnectionPool: ConnectionManagerConnectivityDelegate {
  464. // We're interested in a few different situations here:
  465. //
  466. // 1. The connection was usable ('ready') and is no longer usable (either it became idle or
  467. // encountered an error. If this happens we need to notify any connections of the change as
  468. // they may no longer be used for new RPCs.
  469. // 2. The connection was not usable but moved to a different unusable state. If this happens and
  470. // we know the cause of the state transition (i.e. the error) then we need to update our most
  471. // recent error with the error. This information is used when failing waiters to provide some
  472. // context as to why they may be failing.
  473. func connectionStateDidChange(
  474. _ manager: ConnectionManager,
  475. from oldState: _ConnectivityState,
  476. to newState: _ConnectivityState
  477. ) {
  478. switch (oldState, newState) {
  479. case let (.ready, .transientFailure(error)),
  480. let (.ready, .idle(.some(error))):
  481. self.updateMostRecentError(error)
  482. self.connectionUnavailable(manager.id)
  483. case (.ready, .idle(.none)),
  484. (.ready, .shutdown):
  485. self.connectionUnavailable(manager.id)
  486. case let (_, .transientFailure(error)),
  487. let (_, .idle(.some(error))):
  488. self.updateMostRecentError(error)
  489. default:
  490. ()
  491. }
  492. }
  493. func connectionIsQuiescing(_ manager: ConnectionManager) {
  494. self.eventLoop.assertInEventLoop()
  495. guard let removed = self._connections.removeValue(forKey: manager.id) else {
  496. return
  497. }
  498. // Drop any delegates. We're no longer interested in these events.
  499. removed.manager.sync.connectivityDelegate = nil
  500. removed.manager.sync.http2Delegate = nil
  501. // Replace the connection with a new idle one.
  502. self.addConnectionToPool()
  503. // Since we're removing this connection from the pool, the pool manager can ignore any streams
  504. // reserved against this connection.
  505. //
  506. // Note: we don't need to adjust the number of available streams as the number of connections
  507. // hasn't changed.
  508. self.streamLender.returnStreams(removed.reservedStreams, to: self)
  509. }
  510. private func updateMostRecentError(_ error: Error) {
  511. self.eventLoop.assertInEventLoop()
  512. // Update the last known error if there is one. We will use it to provide some context to
  513. // waiters which may fail.
  514. self._mostRecentError = error
  515. }
  516. /// A connection has become unavailable.
  517. private func connectionUnavailable(_ id: ConnectionManagerID) {
  518. self.eventLoop.assertInEventLoop()
  519. // The connection is no longer available: any streams which haven't been closed will be counted
  520. // as a dropped reservation, we need to tell the pool manager about them.
  521. if let droppedReservations = self._connections[id]?.unavailable(), droppedReservations > 0 {
  522. self.streamLender.returnStreams(droppedReservations, to: self)
  523. }
  524. }
  525. }
  526. extension ConnectionPool: ConnectionManagerHTTP2Delegate {
  527. internal func streamClosed(_ manager: ConnectionManager) {
  528. self.eventLoop.assertInEventLoop()
  529. // Return the stream the connection and to the pool manager.
  530. self._connections[manager.id]?.returnStream()
  531. self.streamLender.returnStreams(1, to: self)
  532. // A stream was returned: we may be able to service a waiter now.
  533. self.tryServiceWaiters()
  534. }
  535. internal func receivedSettingsMaxConcurrentStreams(
  536. _ manager: ConnectionManager,
  537. maxConcurrentStreams: Int
  538. ) {
  539. self.eventLoop.assertInEventLoop()
  540. // If we received a SETTINGS update then a connection is okay: drop the last known error.
  541. self._mostRecentError = nil
  542. let previous = self._connections[manager.id]?.updateMaxConcurrentStreams(maxConcurrentStreams)
  543. let delta: Int
  544. if let previousValue = previous {
  545. // There was a previous value of max concurrent streams, i.e. a change in value for an
  546. // existing connection.
  547. delta = maxConcurrentStreams - previousValue
  548. } else {
  549. // There was no previous value so this must be a new connection. We'll compare against our
  550. // assumed default.
  551. delta = maxConcurrentStreams - self.assumedMaxConcurrentStreams
  552. }
  553. if delta != 0 {
  554. self.streamLender.changeStreamCapacity(by: delta, for: self)
  555. }
  556. // We always check, even if `delta` isn't greater than zero as this might be a new connection.
  557. self.tryServiceWaiters()
  558. }
  559. }
  560. extension ConnectionPool {
  561. // MARK: - Waiters
  562. /// Try to service as many waiters as possible.
  563. ///
  564. /// This an expensive operation, in the worst case it will be `O(W ⨉ N)` where `W` is the number
  565. /// of waiters and `N` is the number of connections.
  566. private func tryServiceWaiters() {
  567. if self.waiters.isEmpty { return }
  568. self.logger.trace("servicing waiters", metadata: [
  569. Metadata.waitersCount: "\(self.waiters.count)",
  570. ])
  571. let now = self.now()
  572. var serviced = 0
  573. while !self.waiters.isEmpty {
  574. if self.waiters.first!.deadlineIsAfter(now) {
  575. if let multiplexer = self._reserveStreamFromMostAvailableConnection() {
  576. // The waiter's deadline is in the future, and we have a suitable connection. Remove and
  577. // succeed the waiter.
  578. let waiter = self.waiters.removeFirst()
  579. serviced &+= 1
  580. waiter.succeed(with: multiplexer)
  581. } else {
  582. // There are waiters but no available connections, we're done.
  583. break
  584. }
  585. } else {
  586. // The waiter's deadline has already expired, there's no point completing it. Remove it and
  587. // let its scheduled timeout fail the promise.
  588. self.waiters.removeFirst()
  589. }
  590. }
  591. self.logger.trace("done servicing waiters", metadata: [
  592. Metadata.waitersCount: "\(self.waiters.count)",
  593. Metadata.waitersServiced: "\(serviced)",
  594. ])
  595. }
  596. }
  597. extension ConnectionPool {
  598. /// Synchronous operations for the pool, mostly used by tests.
  599. internal struct Sync {
  600. private let pool: ConnectionPool
  601. fileprivate init(_ pool: ConnectionPool) {
  602. self.pool = pool
  603. }
  604. /// The number of outstanding connection waiters.
  605. internal var waiters: Int {
  606. self.pool.eventLoop.assertInEventLoop()
  607. return self.pool.waiters.count
  608. }
  609. /// The number of connection currently in the pool (in any state).
  610. internal var connections: Int {
  611. self.pool.eventLoop.assertInEventLoop()
  612. return self.pool._connections.count
  613. }
  614. /// The number of idle connections in the pool.
  615. internal var idleConnections: Int {
  616. self.pool.eventLoop.assertInEventLoop()
  617. return self.pool._connections.values.reduce(0) { $0 &+ ($1.manager.sync.isIdle ? 1 : 0) }
  618. }
  619. /// The number of streams currently available to reserve across all connections in the pool.
  620. internal var availableStreams: Int {
  621. self.pool.eventLoop.assertInEventLoop()
  622. return self.pool._connections.values.reduce(0) { $0 + $1.availableStreams }
  623. }
  624. /// The number of streams which have been reserved across all connections in the pool.
  625. internal var reservedStreams: Int {
  626. self.pool.eventLoop.assertInEventLoop()
  627. return self.pool._connections.values.reduce(0) { $0 + $1.reservedStreams }
  628. }
  629. }
  630. internal var sync: Sync {
  631. return Sync(self)
  632. }
  633. }
  634. @usableFromInline
  635. internal enum ConnectionPoolError: Error {
  636. /// The pool is shutdown or shutting down.
  637. case shutdown
  638. /// There are too many waiters in the pool.
  639. case tooManyWaiters(connectionError: Error?)
  640. /// The deadline for creating a stream has passed.
  641. case deadlineExceeded(connectionError: Error?)
  642. }
  643. extension ConnectionPoolError: GRPCStatusTransformable {
  644. @usableFromInline
  645. internal func makeGRPCStatus() -> GRPCStatus {
  646. switch self {
  647. case .shutdown:
  648. return GRPCStatus(
  649. code: .unavailable,
  650. message: "The connection pool is shutdown"
  651. )
  652. case let .tooManyWaiters(error):
  653. return GRPCStatus(
  654. code: .resourceExhausted,
  655. message: "The connection pool has no capacity for new RPCs or RPC waiters",
  656. cause: error
  657. )
  658. case let .deadlineExceeded(error):
  659. return GRPCStatus(
  660. code: .deadlineExceeded,
  661. message: "Timed out waiting for an HTTP/2 stream from the connection pool",
  662. cause: error
  663. )
  664. }
  665. }
  666. }