ConnectionPoolTests.swift 46 KB

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