ConnectionPool.swift 25 KB

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