ConnectionPoolTests.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. @testable import GRPC
  17. import Logging
  18. import NIOCore
  19. import NIOEmbedded
  20. import NIOHTTP2
  21. import XCTest
  22. final class ConnectionPoolTests: GRPCTestCase {
  23. private enum TestError: Error {
  24. case noChannelExpected
  25. }
  26. private var eventLoop: EmbeddedEventLoop!
  27. private var tearDownBlocks: [() throws -> Void] = []
  28. override func setUp() {
  29. super.setUp()
  30. self.eventLoop = EmbeddedEventLoop()
  31. }
  32. override func tearDown() {
  33. XCTAssertNoThrow(try self.eventLoop.close())
  34. self.tearDownBlocks.forEach { try? $0() }
  35. super.tearDown()
  36. }
  37. private func noChannelExpected(
  38. _: ConnectionManager,
  39. _ eventLoop: EventLoop,
  40. line: UInt = #line
  41. ) -> EventLoopFuture<Channel> {
  42. XCTFail("Channel unexpectedly created", line: line)
  43. return eventLoop.makeFailedFuture(TestError.noChannelExpected)
  44. }
  45. private func makePool(
  46. waiters: Int = 1000,
  47. reservationLoadThreshold: Double = 0.9,
  48. now: @escaping () -> NIODeadline = { .now() },
  49. connectionBackoff: ConnectionBackoff = ConnectionBackoff(),
  50. delegate: GRPCConnectionPoolDelegate? = nil,
  51. onReservationReturned: @escaping (Int) -> Void = { _ in },
  52. onMaximumReservationsChange: @escaping (Int) -> Void = { _ in },
  53. channelProvider: ConnectionManagerChannelProvider
  54. ) -> ConnectionPool {
  55. return ConnectionPool(
  56. eventLoop: self.eventLoop,
  57. maxWaiters: waiters,
  58. reservationLoadThreshold: reservationLoadThreshold,
  59. assumedMaxConcurrentStreams: 100,
  60. connectionBackoff: connectionBackoff,
  61. channelProvider: channelProvider,
  62. streamLender: HookedStreamLender(
  63. onReturnStreams: onReservationReturned,
  64. onUpdateMaxAvailableStreams: onMaximumReservationsChange
  65. ),
  66. delegate: delegate,
  67. logger: self.logger.wrapped,
  68. now: now
  69. )
  70. }
  71. private func makePool(
  72. waiters: Int = 1000,
  73. delegate: GRPCConnectionPoolDelegate? = nil,
  74. makeChannel: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
  75. ) -> ConnectionPool {
  76. return self.makePool(
  77. waiters: waiters,
  78. delegate: delegate,
  79. channelProvider: HookedChannelProvider(makeChannel)
  80. )
  81. }
  82. private func setUpPoolAndController(
  83. waiters: Int = 1000,
  84. reservationLoadThreshold: Double = 0.9,
  85. now: @escaping () -> NIODeadline = { .now() },
  86. connectionBackoff: ConnectionBackoff = ConnectionBackoff(),
  87. delegate: GRPCConnectionPoolDelegate? = nil,
  88. onReservationReturned: @escaping (Int) -> Void = { _ in },
  89. onMaximumReservationsChange: @escaping (Int) -> Void = { _ in }
  90. ) -> (ConnectionPool, ChannelController) {
  91. let controller = ChannelController()
  92. let pool = self.makePool(
  93. waiters: waiters,
  94. reservationLoadThreshold: reservationLoadThreshold,
  95. now: now,
  96. connectionBackoff: connectionBackoff,
  97. delegate: delegate,
  98. onReservationReturned: onReservationReturned,
  99. onMaximumReservationsChange: onMaximumReservationsChange,
  100. channelProvider: controller
  101. )
  102. self.tearDownBlocks.append {
  103. let shutdown = pool.shutdown()
  104. self.eventLoop.run()
  105. XCTAssertNoThrow(try shutdown.wait())
  106. controller.finish()
  107. }
  108. return (pool, controller)
  109. }
  110. func testEmptyConnectionPool() {
  111. let pool = self.makePool {
  112. self.noChannelExpected($0, $1)
  113. }
  114. XCTAssertEqual(pool.sync.connections, 0)
  115. XCTAssertEqual(pool.sync.waiters, 0)
  116. XCTAssertEqual(pool.sync.availableStreams, 0)
  117. XCTAssertEqual(pool.sync.reservedStreams, 0)
  118. pool.initialize(connections: 20)
  119. XCTAssertEqual(pool.sync.connections, 20)
  120. XCTAssertEqual(pool.sync.waiters, 0)
  121. XCTAssertEqual(pool.sync.availableStreams, 0)
  122. XCTAssertEqual(pool.sync.reservedStreams, 0)
  123. let shutdownFuture = pool.shutdown()
  124. self.eventLoop.run()
  125. XCTAssertNoThrow(try shutdownFuture.wait())
  126. }
  127. func testShutdownEmptyPool() {
  128. let pool = self.makePool {
  129. self.noChannelExpected($0, $1)
  130. }
  131. XCTAssertNoThrow(try pool.shutdown().wait())
  132. // Shutting down twice should also be fine.
  133. XCTAssertNoThrow(try pool.shutdown().wait())
  134. }
  135. func testMakeStreamWhenShutdown() {
  136. let pool = self.makePool {
  137. self.noChannelExpected($0, $1)
  138. }
  139. XCTAssertNoThrow(try pool.shutdown().wait())
  140. let stream = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  141. $0.eventLoop.makeSucceededVoidFuture()
  142. }
  143. XCTAssertThrowsError(try stream.wait()) { error in
  144. XCTAssert((error as? ConnectionPoolError).isShutdown)
  145. }
  146. }
  147. func testMakeStreamWhenWaiterQueueIsFull() {
  148. let maxWaiters = 5
  149. let pool = self.makePool(waiters: maxWaiters) {
  150. self.noChannelExpected($0, $1)
  151. }
  152. let waiting = (0 ..< maxWaiters).map { _ in
  153. return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  154. $0.eventLoop.makeSucceededVoidFuture()
  155. }
  156. }
  157. let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  158. $0.eventLoop.makeSucceededVoidFuture()
  159. }
  160. XCTAssertThrowsError(try tooManyWaiters.wait()) { error in
  161. XCTAssert((error as? ConnectionPoolError).isTooManyWaiters)
  162. }
  163. XCTAssertNoThrow(try pool.shutdown().wait())
  164. // All 'waiting' futures will be failed by the shutdown promise.
  165. for waiter in waiting {
  166. XCTAssertThrowsError(try waiter.wait()) { error in
  167. XCTAssert((error as? ConnectionPoolError).isShutdown)
  168. }
  169. }
  170. }
  171. func testWaiterTimingOut() {
  172. let pool = self.makePool {
  173. self.noChannelExpected($0, $1)
  174. }
  175. let waiter = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
  176. $0.eventLoop.makeSucceededVoidFuture()
  177. }
  178. XCTAssertEqual(pool.sync.waiters, 1)
  179. self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
  180. XCTAssertThrowsError(try waiter.wait()) { error in
  181. XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
  182. }
  183. XCTAssertEqual(pool.sync.waiters, 0)
  184. }
  185. func testWaiterTimingOutInPast() {
  186. let pool = self.makePool {
  187. self.noChannelExpected($0, $1)
  188. }
  189. self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
  190. let waiter = pool.makeStream(deadline: .uptimeNanoseconds(5), logger: self.logger.wrapped) {
  191. $0.eventLoop.makeSucceededVoidFuture()
  192. }
  193. XCTAssertEqual(pool.sync.waiters, 1)
  194. self.eventLoop.run()
  195. XCTAssertThrowsError(try waiter.wait()) { error in
  196. XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
  197. }
  198. XCTAssertEqual(pool.sync.waiters, 0)
  199. }
  200. func testMakeStreamTriggersChannelCreation() {
  201. let (pool, controller) = self.setUpPoolAndController()
  202. pool.initialize(connections: 1)
  203. XCTAssertEqual(pool.sync.connections, 1)
  204. // No channels yet.
  205. XCTAssertEqual(controller.count, 0)
  206. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  207. $0.eventLoop.makeSucceededVoidFuture()
  208. }
  209. // Start creating the channel.
  210. self.eventLoop.run()
  211. // We should have been asked for a channel now.
  212. XCTAssertEqual(controller.count, 1)
  213. // The connection isn't ready yet though, so no streams available.
  214. XCTAssertEqual(pool.sync.availableStreams, 0)
  215. // Make the connection 'ready'.
  216. controller.connectChannel(atIndex: 0)
  217. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  218. // We have a multiplexer and a 'ready' connection.
  219. XCTAssertEqual(pool.sync.reservedStreams, 1)
  220. XCTAssertEqual(pool.sync.availableStreams, 9)
  221. XCTAssertEqual(pool.sync.waiters, 0)
  222. // Run the loop to create the stream, we need to fire the event too.
  223. self.eventLoop.run()
  224. XCTAssertNoThrow(try waiter.wait())
  225. controller.openStreamInChannel(atIndex: 0)
  226. // Now close the stream.
  227. controller.closeStreamInChannel(atIndex: 0)
  228. XCTAssertEqual(pool.sync.reservedStreams, 0)
  229. XCTAssertEqual(pool.sync.availableStreams, 10)
  230. }
  231. func testMakeStreamWhenConnectionIsAlreadyAvailable() {
  232. let (pool, controller) = self.setUpPoolAndController()
  233. pool.initialize(connections: 1)
  234. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  235. $0.eventLoop.makeSucceededVoidFuture()
  236. }
  237. // Start creating the channel.
  238. self.eventLoop.run()
  239. XCTAssertEqual(controller.count, 1)
  240. // Fire up the connection.
  241. controller.connectChannel(atIndex: 0)
  242. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  243. // Run the loop to create the stream, we need to fire the stream creation event too.
  244. self.eventLoop.run()
  245. XCTAssertNoThrow(try waiter.wait())
  246. controller.openStreamInChannel(atIndex: 0)
  247. // Now we can create another stream, but as there's already an available stream on an active
  248. // connection we won't have to wait.
  249. XCTAssertEqual(pool.sync.waiters, 0)
  250. XCTAssertEqual(pool.sync.reservedStreams, 1)
  251. let notWaiting = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  252. $0.eventLoop.makeSucceededVoidFuture()
  253. }
  254. // Still no waiters.
  255. XCTAssertEqual(pool.sync.waiters, 0)
  256. XCTAssertEqual(pool.sync.reservedStreams, 2)
  257. // Run the loop to create the stream, we need to fire the stream creation event too.
  258. self.eventLoop.run()
  259. XCTAssertNoThrow(try notWaiting.wait())
  260. controller.openStreamInChannel(atIndex: 0)
  261. }
  262. func testMakeMoreWaitersThanConnectionCanHandle() {
  263. var returnedStreams: [Int] = []
  264. let (pool, controller) = self.setUpPoolAndController(onReservationReturned: {
  265. returnedStreams.append($0)
  266. })
  267. pool.initialize(connections: 1)
  268. // Enqueue twice as many waiters as the connection will be able to handle.
  269. let maxConcurrentStreams = 10
  270. let waiters = (0 ..< maxConcurrentStreams * 2).map { _ in
  271. return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  272. $0.eventLoop.makeSucceededVoidFuture()
  273. }
  274. }
  275. XCTAssertEqual(pool.sync.waiters, 2 * maxConcurrentStreams)
  276. // Fire up the connection.
  277. self.eventLoop.run()
  278. controller.connectChannel(atIndex: 0)
  279. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: maxConcurrentStreams)
  280. // We should have assigned a bunch of streams to waiters now.
  281. XCTAssertEqual(pool.sync.waiters, maxConcurrentStreams)
  282. XCTAssertEqual(pool.sync.reservedStreams, maxConcurrentStreams)
  283. XCTAssertEqual(pool.sync.availableStreams, 0)
  284. // Do the stream creation and make sure the first batch are succeeded.
  285. self.eventLoop.run()
  286. let firstBatch = waiters.prefix(maxConcurrentStreams)
  287. var others = waiters.dropFirst(maxConcurrentStreams)
  288. for waiter in firstBatch {
  289. XCTAssertNoThrow(try waiter.wait())
  290. controller.openStreamInChannel(atIndex: 0)
  291. }
  292. // Close a stream.
  293. controller.closeStreamInChannel(atIndex: 0)
  294. XCTAssertEqual(returnedStreams, [1])
  295. // We have another stream so a waiter should be succeeded.
  296. XCTAssertEqual(pool.sync.waiters, maxConcurrentStreams - 1)
  297. self.eventLoop.run()
  298. XCTAssertNoThrow(try others.popFirst()?.wait())
  299. // Shutdown the pool: the remaining waiters should be failed.
  300. let shutdown = pool.shutdown()
  301. self.eventLoop.run()
  302. XCTAssertNoThrow(try shutdown.wait())
  303. for waiter in others {
  304. XCTAssertThrowsError(try waiter.wait()) { error in
  305. XCTAssert((error as? ConnectionPoolError).isShutdown)
  306. }
  307. }
  308. }
  309. func testDropConnectionWithOutstandingReservations() {
  310. var streamsReturned: [Int] = []
  311. let (pool, controller) = self.setUpPoolAndController(
  312. onReservationReturned: { streamsReturned.append($0) }
  313. )
  314. pool.initialize(connections: 1)
  315. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  316. $0.eventLoop.makeSucceededVoidFuture()
  317. }
  318. // Start creating the channel.
  319. self.eventLoop.run()
  320. XCTAssertEqual(controller.count, 1)
  321. // Fire up the connection.
  322. controller.connectChannel(atIndex: 0)
  323. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  324. // Run the loop to create the stream, we need to fire the stream creation event too.
  325. self.eventLoop.run()
  326. XCTAssertNoThrow(try waiter.wait())
  327. controller.openStreamInChannel(atIndex: 0)
  328. // Create a handful of streams.
  329. XCTAssertEqual(pool.sync.availableStreams, 9)
  330. for _ in 0 ..< 5 {
  331. let notWaiting = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  332. $0.eventLoop.makeSucceededVoidFuture()
  333. }
  334. self.eventLoop.run()
  335. XCTAssertNoThrow(try notWaiting.wait())
  336. controller.openStreamInChannel(atIndex: 0)
  337. }
  338. XCTAssertEqual(pool.sync.availableStreams, 4)
  339. XCTAssertEqual(pool.sync.reservedStreams, 6)
  340. // Blast the connection away. We'll be notified about dropped reservations.
  341. XCTAssertEqual(streamsReturned, [])
  342. controller.throwError(ChannelError.ioOnClosedChannel, inChannelAtIndex: 0)
  343. controller.fireChannelInactiveForChannel(atIndex: 0)
  344. XCTAssertEqual(streamsReturned, [6])
  345. XCTAssertEqual(pool.sync.availableStreams, 0)
  346. XCTAssertEqual(pool.sync.reservedStreams, 0)
  347. }
  348. func testDropConnectionWithOutstandingReservationsAndWaiters() {
  349. var streamsReturned: [Int] = []
  350. let (pool, controller) = self.setUpPoolAndController(
  351. onReservationReturned: { streamsReturned.append($0) }
  352. )
  353. pool.initialize(connections: 1)
  354. // Reserve a bunch of streams.
  355. let waiters = (0 ..< 10).map { _ in
  356. return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  357. $0.eventLoop.makeSucceededVoidFuture()
  358. }
  359. }
  360. // Connect and setup all the streams.
  361. self.eventLoop.run()
  362. controller.connectChannel(atIndex: 0)
  363. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  364. self.eventLoop.run()
  365. for waiter in waiters {
  366. XCTAssertNoThrow(try waiter.wait())
  367. controller.openStreamInChannel(atIndex: 0)
  368. }
  369. // All streams should be reserved.
  370. XCTAssertEqual(pool.sync.availableStreams, 0)
  371. XCTAssertEqual(pool.sync.reservedStreams, 10)
  372. // Add a waiter.
  373. XCTAssertEqual(pool.sync.waiters, 0)
  374. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  375. $0.eventLoop.makeSucceededVoidFuture()
  376. }
  377. XCTAssertEqual(pool.sync.waiters, 1)
  378. // Now bork the connection. We'll be notified about the 10 dropped reservation but not the one
  379. // waiter .
  380. XCTAssertEqual(streamsReturned, [])
  381. controller.throwError(ChannelError.ioOnClosedChannel, inChannelAtIndex: 0)
  382. controller.fireChannelInactiveForChannel(atIndex: 0)
  383. XCTAssertEqual(streamsReturned, [10])
  384. // The connection dropped, let the reconnect kick in.
  385. self.eventLoop.run()
  386. XCTAssertEqual(controller.count, 2)
  387. controller.connectChannel(atIndex: 1)
  388. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
  389. self.eventLoop.run()
  390. XCTAssertNoThrow(try waiter.wait())
  391. controller.openStreamInChannel(atIndex: 1)
  392. controller.closeStreamInChannel(atIndex: 1)
  393. XCTAssertEqual(streamsReturned, [10, 1])
  394. XCTAssertEqual(pool.sync.availableStreams, 10)
  395. XCTAssertEqual(pool.sync.reservedStreams, 0)
  396. }
  397. func testDeadlineExceededInSameTickAsSucceedingWaiters() {
  398. // deadline must be exceeded just as servicing waiter is done
  399. // - setup waiter with deadline x
  400. // - start connecting
  401. // - set time to x
  402. // - finish connecting
  403. let (pool, controller) = self.setUpPoolAndController(now: {
  404. return NIODeadline.uptimeNanoseconds(12)
  405. })
  406. pool.initialize(connections: 1)
  407. let waiter1 = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
  408. $0.eventLoop.makeSucceededVoidFuture()
  409. }
  410. let waiter2 = pool.makeStream(deadline: .uptimeNanoseconds(15), logger: self.logger.wrapped) {
  411. $0.eventLoop.makeSucceededVoidFuture()
  412. }
  413. // Start creating the channel.
  414. self.eventLoop.run()
  415. XCTAssertEqual(controller.count, 1)
  416. // Fire up the connection.
  417. controller.connectChannel(atIndex: 0)
  418. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  419. // The deadline for the first waiter is already after 'now', so it'll fail with deadline
  420. // exceeded.
  421. self.eventLoop.run()
  422. // We need to advance the time to fire the timeout to fail the waiter.
  423. self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
  424. XCTAssertThrowsError(try waiter1.wait()) { error in
  425. XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
  426. }
  427. self.eventLoop.run()
  428. XCTAssertNoThrow(try waiter2.wait())
  429. controller.openStreamInChannel(atIndex: 0)
  430. XCTAssertEqual(pool.sync.waiters, 0)
  431. XCTAssertEqual(pool.sync.reservedStreams, 1)
  432. XCTAssertEqual(pool.sync.availableStreams, 9)
  433. controller.closeStreamInChannel(atIndex: 0)
  434. XCTAssertEqual(pool.sync.waiters, 0)
  435. XCTAssertEqual(pool.sync.reservedStreams, 0)
  436. XCTAssertEqual(pool.sync.availableStreams, 10)
  437. }
  438. func testConnectionsAreBroughtUpAtAppropriateTimes() {
  439. let (pool, controller) = self.setUpPoolAndController(reservationLoadThreshold: 0.2)
  440. // We'll allow 3 connections and configure max concurrent streams to 10. With our reservation
  441. // threshold we'll bring up a new connection after enqueueing the 1st, 2nd and 4th waiters.
  442. pool.initialize(connections: 3)
  443. let maxConcurrentStreams = 10
  444. // No demand so all three connections are idle.
  445. XCTAssertEqual(pool.sync.idleConnections, 3)
  446. let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  447. $0.eventLoop.makeSucceededVoidFuture()
  448. }
  449. // demand=1, available=0, load=infinite, one connection should be non-idle
  450. XCTAssertEqual(pool.sync.idleConnections, 2)
  451. // Connect the first channel and write the first settings frame; this allows us to lower the
  452. // default max concurrent streams value (from 100).
  453. self.eventLoop.run()
  454. controller.connectChannel(atIndex: 0)
  455. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: maxConcurrentStreams)
  456. self.eventLoop.run()
  457. XCTAssertNoThrow(try w1.wait())
  458. controller.openStreamInChannel(atIndex: 0)
  459. let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  460. $0.eventLoop.makeSucceededVoidFuture()
  461. }
  462. self.eventLoop.run()
  463. XCTAssertNoThrow(try w2.wait())
  464. controller.openStreamInChannel(atIndex: 0)
  465. // demand=2, available=10, load=0.2; only one idle connection now.
  466. XCTAssertEqual(pool.sync.idleConnections, 1)
  467. // Add more demand before the second connection comes up.
  468. let w3 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  469. $0.eventLoop.makeSucceededVoidFuture()
  470. }
  471. // demand=3, available=20, load=0.15; still one idle connection.
  472. XCTAssertEqual(pool.sync.idleConnections, 1)
  473. // Connection the next channel
  474. self.eventLoop.run()
  475. controller.connectChannel(atIndex: 1)
  476. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: maxConcurrentStreams)
  477. XCTAssertNoThrow(try w3.wait())
  478. controller.openStreamInChannel(atIndex: 1)
  479. }
  480. func testQuiescingConnectionIsReplaced() {
  481. var reservationsReturned: [Int] = []
  482. let (pool, controller) = self.setUpPoolAndController(onReservationReturned: {
  483. reservationsReturned.append($0)
  484. })
  485. pool.initialize(connections: 1)
  486. XCTAssertEqual(pool.sync.connections, 1)
  487. let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  488. $0.eventLoop.makeSucceededVoidFuture()
  489. }
  490. // Start creating the channel.
  491. self.eventLoop.run()
  492. // Make the connection 'ready'.
  493. controller.connectChannel(atIndex: 0)
  494. controller.sendSettingsToChannel(atIndex: 0)
  495. // Run the loop to create the stream.
  496. self.eventLoop.run()
  497. XCTAssertNoThrow(try w1.wait())
  498. controller.openStreamInChannel(atIndex: 0)
  499. // One stream reserved by 'w1' on the only connection in the pool (which isn't idle).
  500. XCTAssertEqual(pool.sync.reservedStreams, 1)
  501. XCTAssertEqual(pool.sync.connections, 1)
  502. XCTAssertEqual(pool.sync.idleConnections, 0)
  503. // Quiesce the connection. It should be punted from the pool and any active RPCs allowed to run
  504. // their course. A new (idle) connection should replace it in the pool.
  505. controller.sendGoAwayToChannel(atIndex: 0)
  506. // The quiescing connection had 1 stream reserved, it's now returned to the outer pool and we
  507. // have a new idle connection in place of the old one.
  508. XCTAssertEqual(reservationsReturned, [1])
  509. // The inner pool still knows about the reserved stream.
  510. XCTAssertEqual(pool.sync.reservedStreams, 1)
  511. XCTAssertEqual(pool.sync.availableStreams, 0)
  512. XCTAssertEqual(pool.sync.idleConnections, 1)
  513. // Ask for another stream: this will be on the new idle connection.
  514. let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  515. $0.eventLoop.makeSucceededVoidFuture()
  516. }
  517. self.eventLoop.run()
  518. XCTAssertEqual(controller.count, 2)
  519. // Make the connection 'ready'.
  520. controller.connectChannel(atIndex: 1)
  521. controller.sendSettingsToChannel(atIndex: 1)
  522. self.eventLoop.run()
  523. XCTAssertNoThrow(try w2.wait())
  524. controller.openStreamInChannel(atIndex: 1)
  525. // The stream on the quiescing connection is still reserved.
  526. XCTAssertEqual(pool.sync.reservedStreams, 2)
  527. XCTAssertEqual(pool.sync.availableStreams, 99)
  528. // Return a stream for the _quiescing_ connection: nothing should change in the pool.
  529. controller.closeStreamInChannel(atIndex: 0)
  530. XCTAssertEqual(pool.sync.reservedStreams, 1)
  531. XCTAssertEqual(pool.sync.availableStreams, 99)
  532. // Return a stream for the new connection.
  533. controller.closeStreamInChannel(atIndex: 1)
  534. XCTAssertEqual(reservationsReturned, [1, 1])
  535. XCTAssertEqual(pool.sync.reservedStreams, 0)
  536. XCTAssertEqual(pool.sync.availableStreams, 100)
  537. }
  538. func testBackoffIsUsedForReconnections() {
  539. // Fix backoff to always be 1 second.
  540. let backoff = ConnectionBackoff(
  541. initialBackoff: 1.0,
  542. maximumBackoff: 1.0,
  543. multiplier: 1.0,
  544. jitter: 0.0
  545. )
  546. let (pool, controller) = self.setUpPoolAndController(connectionBackoff: backoff)
  547. pool.initialize(connections: 1)
  548. XCTAssertEqual(pool.sync.connections, 1)
  549. let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  550. $0.eventLoop.makeSucceededVoidFuture()
  551. }
  552. // Start creating the channel.
  553. self.eventLoop.run()
  554. // Make the connection 'ready'.
  555. controller.connectChannel(atIndex: 0)
  556. controller.sendSettingsToChannel(atIndex: 0)
  557. self.eventLoop.run()
  558. XCTAssertNoThrow(try w1.wait())
  559. controller.openStreamInChannel(atIndex: 0)
  560. // Close the connection. It should hit the transient failure state.
  561. controller.fireChannelInactiveForChannel(atIndex: 0)
  562. // Now nothing is available in the pool.
  563. XCTAssertEqual(pool.sync.waiters, 0)
  564. XCTAssertEqual(pool.sync.availableStreams, 0)
  565. XCTAssertEqual(pool.sync.reservedStreams, 0)
  566. XCTAssertEqual(pool.sync.idleConnections, 0)
  567. // Enqueue two waiters. One to time out before the reconnect happens.
  568. let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  569. $0.eventLoop.makeSucceededVoidFuture()
  570. }
  571. let w3 = pool.makeStream(
  572. deadline: .uptimeNanoseconds(UInt64(TimeAmount.milliseconds(500).nanoseconds)),
  573. logger: self.logger.wrapped
  574. ) {
  575. $0.eventLoop.makeSucceededVoidFuture()
  576. }
  577. XCTAssertEqual(pool.sync.waiters, 2)
  578. // Time out w3.
  579. self.eventLoop.advanceTime(by: .milliseconds(500))
  580. XCTAssertThrowsError(try w3.wait())
  581. XCTAssertEqual(pool.sync.waiters, 1)
  582. // Wait a little more for the backoff to pass. The controller should now have a second channel.
  583. self.eventLoop.advanceTime(by: .milliseconds(500))
  584. XCTAssertEqual(controller.count, 2)
  585. // Start up the next channel.
  586. controller.connectChannel(atIndex: 1)
  587. controller.sendSettingsToChannel(atIndex: 1)
  588. self.eventLoop.run()
  589. XCTAssertNoThrow(try w2.wait())
  590. controller.openStreamInChannel(atIndex: 1)
  591. }
  592. func testFailedWaiterWithError() throws {
  593. // We want to check a few things in this test:
  594. //
  595. // 1. When an active channel throws an error that any waiter in the connection pool which has
  596. // its deadline exceeded or any waiter which exceeds the waiter limit fails with an error
  597. // which includes the underlying channel error.
  598. // 2. When a reconnect happens and the pool is just busy, no underlying error is passed through
  599. // to failing waiters.
  600. // Fix backoff to always be 1 second. This is necessary to figure out timings later on when
  601. // we try to establish a new connection.
  602. let backoff = ConnectionBackoff(
  603. initialBackoff: 1.0,
  604. maximumBackoff: 1.0,
  605. multiplier: 1.0,
  606. jitter: 0.0
  607. )
  608. let (pool, controller) = self.setUpPoolAndController(waiters: 10, connectionBackoff: backoff)
  609. pool.initialize(connections: 1)
  610. // First we'll create two streams which will fail for different reasons.
  611. // - w1 will fail because of a timeout (no channel came up before the waiters own deadline
  612. // passed but no connection has previously failed)
  613. // - w2 will fail because of a timeout but after the underlying channel has failed to connect so
  614. // should have that additional failure information.
  615. let w1 = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
  616. $0.eventLoop.makeSucceededVoidFuture()
  617. }
  618. let w2 = pool.makeStream(deadline: .uptimeNanoseconds(20), logger: self.logger.wrapped) {
  619. $0.eventLoop.makeSucceededVoidFuture()
  620. }
  621. // Start creating the channel.
  622. self.eventLoop.run()
  623. XCTAssertEqual(controller.count, 1)
  624. // Fire up the connection.
  625. controller.connectChannel(atIndex: 0)
  626. // Advance time to fail the w1.
  627. self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
  628. XCTAssertThrowsError(try w1.wait()) { error in
  629. switch error as? ConnectionPoolError {
  630. case .some(.deadlineExceeded(.none)):
  631. // Deadline exceeded but no underlying error, as expected.
  632. ()
  633. default:
  634. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
  635. }
  636. }
  637. // Now fail the connection and timeout w2.
  638. struct DummyError: Error {}
  639. controller.throwError(DummyError(), inChannelAtIndex: 0)
  640. controller.fireChannelInactiveForChannel(atIndex: 0)
  641. self.eventLoop.advanceTime(to: .uptimeNanoseconds(20))
  642. XCTAssertThrowsError(try w2.wait()) { error in
  643. switch error as? ConnectionPoolError {
  644. case let .some(.deadlineExceeded(.some(wrappedError))):
  645. // Deadline exceeded and we have the underlying error.
  646. XCTAssert(wrappedError is DummyError)
  647. default:
  648. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.some) but got \(error)")
  649. }
  650. }
  651. // For the next part of the test we want to validate that when a new channel is created after
  652. // the backoff period passes that no additional errors are attached when the pool is just busy
  653. // but otherwise operational.
  654. //
  655. // To do this we'll create a bunch of waiters. These will be succeeded when the new connection
  656. // comes up and, importantly, use up all available streams on that connection.
  657. //
  658. // We'll then enqueue enough waiters to fill the waiter queue. We'll then validate that one more
  659. // waiter trips over the queue limit but does not include the connection error we saw earlier.
  660. // We'll then timeout the waiters in the queue and validate the same thing.
  661. // These streams should succeed when the new connection is up. We'll limit the connection to 10
  662. // streams when we bring it up.
  663. let streams = (0 ..< 10).map { _ in
  664. pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  665. $0.eventLoop.makeSucceededVoidFuture()
  666. }
  667. }
  668. // The connection is backing off; advance time to create another channel.
  669. XCTAssertEqual(controller.count, 1)
  670. self.eventLoop.advanceTime(by: .seconds(1))
  671. XCTAssertEqual(controller.count, 2)
  672. controller.connectChannel(atIndex: 1)
  673. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
  674. self.eventLoop.run()
  675. // Make sure the streams are succeeded.
  676. for stream in streams {
  677. XCTAssertNoThrow(try stream.wait())
  678. controller.openStreamInChannel(atIndex: 1)
  679. }
  680. // All streams should be reserved.
  681. XCTAssertEqual(pool.sync.availableStreams, 0)
  682. XCTAssertEqual(pool.sync.reservedStreams, 10)
  683. XCTAssertEqual(pool.sync.waiters, 0)
  684. // We configured the pool to allow for 10 waiters, so let's enqueue that many which will time
  685. // out at a known point in time.
  686. let now = NIODeadline.now()
  687. self.eventLoop.advanceTime(to: now)
  688. let waiters = (0 ..< 10).map { _ in
  689. pool.makeStream(deadline: now + .seconds(1), logger: self.logger.wrapped) {
  690. $0.eventLoop.makeSucceededVoidFuture()
  691. }
  692. }
  693. // This is one waiter more than is allowed so it should hit too-many-waiters. We don't expect
  694. // an inner error though, the connection is just busy.
  695. let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  696. $0.eventLoop.makeSucceededVoidFuture()
  697. }
  698. XCTAssertThrowsError(try tooManyWaiters.wait()) { error in
  699. switch error as? ConnectionPoolError {
  700. case .some(.tooManyWaiters(.none)):
  701. ()
  702. default:
  703. XCTFail("Expected ConnectionPoolError.tooManyWaiters(.none) but got \(error)")
  704. }
  705. }
  706. // Finally, timeout the remaining waiters. Again, no inner error, the connection is just busy.
  707. self.eventLoop.advanceTime(by: .seconds(1))
  708. for waiter in waiters {
  709. XCTAssertThrowsError(try waiter.wait()) { error in
  710. switch error as? ConnectionPoolError {
  711. case .some(.deadlineExceeded(.none)):
  712. ()
  713. default:
  714. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
  715. }
  716. }
  717. }
  718. }
  719. func testWaiterStoresItsScheduledTask() throws {
  720. let deadline = NIODeadline.uptimeNanoseconds(42)
  721. let promise = self.eventLoop.makePromise(of: Channel.self)
  722. let waiter = ConnectionPool.Waiter(deadline: deadline, promise: promise) {
  723. return $0.eventLoop.makeSucceededVoidFuture()
  724. }
  725. XCTAssertNil(waiter._scheduledTimeout)
  726. waiter.scheduleTimeout(on: self.eventLoop) {
  727. waiter.fail(ConnectionPoolError.deadlineExceeded(connectionError: nil))
  728. }
  729. XCTAssertNotNil(waiter._scheduledTimeout)
  730. self.eventLoop.advanceTime(to: deadline)
  731. XCTAssertThrowsError(try promise.futureResult.wait())
  732. XCTAssertNil(waiter._scheduledTimeout)
  733. }
  734. func testConnectionPoolDelegate() throws {
  735. let recorder = EventRecordingConnectionPoolDelegate()
  736. let (pool, controller) = self.setUpPoolAndController(delegate: recorder)
  737. pool.initialize(connections: 2)
  738. func assertConnectionAdded(
  739. _ event: EventRecordingConnectionPoolDelegate.Event?
  740. ) throws -> GRPCConnectionID {
  741. let unwrappedEvent = try XCTUnwrap(event)
  742. switch unwrappedEvent {
  743. case let .connectionAdded(id):
  744. return id
  745. default:
  746. throw EventRecordingConnectionPoolDelegate.UnexpectedEvent(unwrappedEvent)
  747. }
  748. }
  749. let connID1 = try assertConnectionAdded(recorder.popFirst())
  750. let connID2 = try assertConnectionAdded(recorder.popFirst())
  751. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  752. $0.eventLoop.makeSucceededVoidFuture()
  753. }
  754. // Start creating the channel.
  755. self.eventLoop.run()
  756. let startedConnecting = recorder.popFirst()
  757. let firstConn: GRPCConnectionID
  758. let secondConn: GRPCConnectionID
  759. if startedConnecting == .startedConnecting(connID1) {
  760. firstConn = connID1
  761. secondConn = connID2
  762. } else if startedConnecting == .startedConnecting(connID2) {
  763. firstConn = connID2
  764. secondConn = connID1
  765. } else {
  766. return XCTFail("Unexpected event")
  767. }
  768. // Connect the connection.
  769. self.eventLoop.run()
  770. controller.connectChannel(atIndex: 0)
  771. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  772. XCTAssertEqual(recorder.popFirst(), .connectSucceeded(firstConn, 10))
  773. // Open a stream for the waiter.
  774. controller.openStreamInChannel(atIndex: 0)
  775. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 1, 10))
  776. self.eventLoop.run()
  777. XCTAssertNoThrow(try waiter.wait())
  778. // Okay, more utilization!
  779. for n in 2 ... 8 {
  780. let w = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  781. $0.eventLoop.makeSucceededVoidFuture()
  782. }
  783. controller.openStreamInChannel(atIndex: 0)
  784. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, n, 10))
  785. self.eventLoop.run()
  786. XCTAssertNoThrow(try w.wait())
  787. }
  788. // The utilisation threshold before bringing up a new connection is 0.9; we have 8 open streams
  789. // (out of 10) now so opening the next should trigger a connect on the other connection.
  790. let w9 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  791. $0.eventLoop.makeSucceededVoidFuture()
  792. }
  793. XCTAssertEqual(recorder.popFirst(), .startedConnecting(secondConn))
  794. // Deal with the 9th stream.
  795. controller.openStreamInChannel(atIndex: 0)
  796. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 9, 10))
  797. self.eventLoop.run()
  798. XCTAssertNoThrow(try w9.wait())
  799. // Bring up the next connection.
  800. controller.connectChannel(atIndex: 1)
  801. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
  802. XCTAssertEqual(recorder.popFirst(), .connectSucceeded(secondConn, 10))
  803. // The next stream should be on the new connection.
  804. let w10 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  805. $0.eventLoop.makeSucceededVoidFuture()
  806. }
  807. // Deal with the 10th stream.
  808. controller.openStreamInChannel(atIndex: 1)
  809. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(secondConn, 1, 10))
  810. self.eventLoop.run()
  811. XCTAssertNoThrow(try w10.wait())
  812. // Close the streams.
  813. for i in 1 ... 9 {
  814. controller.closeStreamInChannel(atIndex: 0)
  815. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 9 - i, 10))
  816. }
  817. controller.closeStreamInChannel(atIndex: 1)
  818. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(secondConn, 0, 10))
  819. // Close the connections.
  820. controller.fireChannelInactiveForChannel(atIndex: 0)
  821. XCTAssertEqual(recorder.popFirst(), .connectionClosed(firstConn))
  822. controller.fireChannelInactiveForChannel(atIndex: 1)
  823. XCTAssertEqual(recorder.popFirst(), .connectionClosed(secondConn))
  824. // All conns are already closed.
  825. let shutdownFuture = pool.shutdown()
  826. self.eventLoop.run()
  827. XCTAssertNoThrow(try shutdownFuture.wait())
  828. // Two connections must be removed.
  829. for _ in 0 ..< 2 {
  830. if let event = recorder.popFirst() {
  831. let id = event.id
  832. XCTAssertEqual(event, .connectionRemoved(id))
  833. } else {
  834. XCTFail("Expected .connectionRemoved")
  835. }
  836. }
  837. }
  838. }
  839. extension ConnectionPool {
  840. // For backwards compatibility, to avoid large diffs in these tests.
  841. fileprivate func shutdown() -> EventLoopFuture<Void> {
  842. return self.shutdown(mode: .forceful)
  843. }
  844. }
  845. // MARK: - Helpers
  846. internal final class ChannelController {
  847. private var channels: [EmbeddedChannel] = []
  848. internal var count: Int {
  849. return self.channels.count
  850. }
  851. internal func finish() {
  852. while let channel = self.channels.popLast() {
  853. // We're okay with this throwing: some channels are left in a bad state (i.e. with errors).
  854. _ = try? channel.finish()
  855. }
  856. }
  857. private func isValidIndex(
  858. _ index: Int,
  859. file: StaticString = #filePath,
  860. line: UInt = #line
  861. ) -> Bool {
  862. let isValid = self.channels.indices.contains(index)
  863. XCTAssertTrue(isValid, "Invalid connection index '\(index)'", file: file, line: line)
  864. return isValid
  865. }
  866. internal func connectChannel(
  867. atIndex index: Int,
  868. file: StaticString = #filePath,
  869. line: UInt = #line
  870. ) {
  871. guard self.isValidIndex(index, file: file, line: line) else { return }
  872. XCTAssertNoThrow(
  873. try self.channels[index].connect(to: .init(unixDomainSocketPath: "/")),
  874. file: file,
  875. line: line
  876. )
  877. }
  878. internal func fireChannelInactiveForChannel(
  879. atIndex index: Int,
  880. file: StaticString = #filePath,
  881. line: UInt = #line
  882. ) {
  883. guard self.isValidIndex(index, file: file, line: line) else { return }
  884. self.channels[index].pipeline.fireChannelInactive()
  885. }
  886. internal func throwError(
  887. _ error: Error,
  888. inChannelAtIndex index: Int,
  889. file: StaticString = #filePath,
  890. line: UInt = #line
  891. ) {
  892. guard self.isValidIndex(index, file: file, line: line) else { return }
  893. self.channels[index].pipeline.fireErrorCaught(error)
  894. }
  895. internal func sendSettingsToChannel(
  896. atIndex index: Int,
  897. maxConcurrentStreams: Int = 100,
  898. file: StaticString = #filePath,
  899. line: UInt = #line
  900. ) {
  901. guard self.isValidIndex(index, file: file, line: line) else { return }
  902. let settings = [HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)]
  903. let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
  904. XCTAssertNoThrow(try self.channels[index].writeInbound(settingsFrame), file: file, line: line)
  905. }
  906. internal func sendGoAwayToChannel(
  907. atIndex index: Int,
  908. file: StaticString = #filePath,
  909. line: UInt = #line
  910. ) {
  911. guard self.isValidIndex(index, file: file, line: line) else { return }
  912. let goAwayFrame = HTTP2Frame(
  913. streamID: .rootStream,
  914. payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil)
  915. )
  916. XCTAssertNoThrow(try self.channels[index].writeInbound(goAwayFrame), file: file, line: line)
  917. }
  918. internal func openStreamInChannel(
  919. atIndex index: Int,
  920. file: StaticString = #filePath,
  921. line: UInt = #line
  922. ) {
  923. guard self.isValidIndex(index, file: file, line: line) else { return }
  924. // The details don't matter here.
  925. let event = NIOHTTP2StreamCreatedEvent(
  926. streamID: .rootStream,
  927. localInitialWindowSize: nil,
  928. remoteInitialWindowSize: nil
  929. )
  930. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  931. }
  932. internal func closeStreamInChannel(
  933. atIndex index: Int,
  934. file: StaticString = #filePath,
  935. line: UInt = #line
  936. ) {
  937. guard self.isValidIndex(index, file: file, line: line) else { return }
  938. // The details don't matter here.
  939. let event = StreamClosedEvent(streamID: .rootStream, reason: nil)
  940. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  941. }
  942. }
  943. extension ChannelController: ConnectionManagerChannelProvider {
  944. internal func makeChannel(
  945. managedBy connectionManager: ConnectionManager,
  946. onEventLoop eventLoop: EventLoop,
  947. connectTimeout: TimeAmount?,
  948. logger: Logger
  949. ) -> EventLoopFuture<Channel> {
  950. let channel = EmbeddedChannel(loop: eventLoop as! EmbeddedEventLoop)
  951. self.channels.append(channel)
  952. let multiplexer = HTTP2StreamMultiplexer(
  953. mode: .client,
  954. channel: channel,
  955. inboundStreamInitializer: nil
  956. )
  957. let idleHandler = GRPCIdleHandler(
  958. connectionManager: connectionManager,
  959. multiplexer: multiplexer,
  960. idleTimeout: .minutes(5),
  961. keepalive: ClientConnectionKeepalive(),
  962. logger: logger
  963. )
  964. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(idleHandler))
  965. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(multiplexer))
  966. return eventLoop.makeSucceededFuture(channel)
  967. }
  968. }
  969. internal struct HookedStreamLender: StreamLender {
  970. internal var onReturnStreams: (Int) -> Void
  971. internal var onUpdateMaxAvailableStreams: (Int) -> Void
  972. internal func returnStreams(_ count: Int, to pool: ConnectionPool) {
  973. self.onReturnStreams(count)
  974. }
  975. internal func changeStreamCapacity(by delta: Int, for: ConnectionPool) {
  976. self.onUpdateMaxAvailableStreams(delta)
  977. }
  978. }
  979. extension Optional where Wrapped == ConnectionPoolError {
  980. internal var isTooManyWaiters: Bool {
  981. switch self {
  982. case .some(.tooManyWaiters):
  983. return true
  984. case .some(.deadlineExceeded), .some(.shutdown), .none:
  985. return false
  986. }
  987. }
  988. internal var isDeadlineExceeded: Bool {
  989. switch self {
  990. case .some(.deadlineExceeded):
  991. return true
  992. case .some(.tooManyWaiters), .some(.shutdown), .none:
  993. return false
  994. }
  995. }
  996. internal var isShutdown: Bool {
  997. switch self {
  998. case .some(.shutdown):
  999. return true
  1000. case .some(.tooManyWaiters), .some(.deadlineExceeded), .none:
  1001. return false
  1002. }
  1003. }
  1004. }