ConnectionPoolTests.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. 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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError).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? GRPCConnectionPoolError {
  630. case .some(let error):
  631. XCTAssertEqual(error.code, .deadlineExceeded)
  632. XCTAssertNil(error.underlyingError)
  633. // Deadline exceeded but no underlying error, as expected.
  634. ()
  635. default:
  636. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
  637. }
  638. }
  639. // Now fail the connection and timeout w2.
  640. struct DummyError: Error {}
  641. controller.throwError(DummyError(), inChannelAtIndex: 0)
  642. controller.fireChannelInactiveForChannel(atIndex: 0)
  643. self.eventLoop.advanceTime(to: .uptimeNanoseconds(20))
  644. XCTAssertThrowsError(try w2.wait()) { error in
  645. switch error as? GRPCConnectionPoolError {
  646. case let .some(error):
  647. XCTAssertEqual(error.code, .deadlineExceeded)
  648. // Deadline exceeded and we have the underlying error.
  649. XCTAssert(error.underlyingError is DummyError)
  650. default:
  651. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.some) but got \(error)")
  652. }
  653. }
  654. // For the next part of the test we want to validate that when a new channel is created after
  655. // the backoff period passes that no additional errors are attached when the pool is just busy
  656. // but otherwise operational.
  657. //
  658. // To do this we'll create a bunch of waiters. These will be succeeded when the new connection
  659. // comes up and, importantly, use up all available streams on that connection.
  660. //
  661. // We'll then enqueue enough waiters to fill the waiter queue. We'll then validate that one more
  662. // waiter trips over the queue limit but does not include the connection error we saw earlier.
  663. // We'll then timeout the waiters in the queue and validate the same thing.
  664. // These streams should succeed when the new connection is up. We'll limit the connection to 10
  665. // streams when we bring it up.
  666. let streams = (0 ..< 10).map { _ in
  667. pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  668. $0.eventLoop.makeSucceededVoidFuture()
  669. }
  670. }
  671. // The connection is backing off; advance time to create another channel.
  672. XCTAssertEqual(controller.count, 1)
  673. self.eventLoop.advanceTime(by: .seconds(1))
  674. XCTAssertEqual(controller.count, 2)
  675. controller.connectChannel(atIndex: 1)
  676. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
  677. self.eventLoop.run()
  678. // Make sure the streams are succeeded.
  679. for stream in streams {
  680. XCTAssertNoThrow(try stream.wait())
  681. controller.openStreamInChannel(atIndex: 1)
  682. }
  683. // All streams should be reserved.
  684. XCTAssertEqual(pool.sync.availableStreams, 0)
  685. XCTAssertEqual(pool.sync.reservedStreams, 10)
  686. XCTAssertEqual(pool.sync.waiters, 0)
  687. // We configured the pool to allow for 10 waiters, so let's enqueue that many which will time
  688. // out at a known point in time.
  689. let now = NIODeadline.now()
  690. self.eventLoop.advanceTime(to: now)
  691. let waiters = (0 ..< 10).map { _ in
  692. pool.makeStream(deadline: now + .seconds(1), logger: self.logger.wrapped) {
  693. $0.eventLoop.makeSucceededVoidFuture()
  694. }
  695. }
  696. // This is one waiter more than is allowed so it should hit too-many-waiters. We don't expect
  697. // an inner error though, the connection is just busy.
  698. let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  699. $0.eventLoop.makeSucceededVoidFuture()
  700. }
  701. XCTAssertThrowsError(try tooManyWaiters.wait()) { error in
  702. switch error as? GRPCConnectionPoolError {
  703. case .some(let error):
  704. XCTAssertEqual(error.code, .tooManyWaiters)
  705. XCTAssertNil(error.underlyingError)
  706. default:
  707. XCTFail("Expected ConnectionPoolError.tooManyWaiters(.none) but got \(error)")
  708. }
  709. }
  710. // Finally, timeout the remaining waiters. Again, no inner error, the connection is just busy.
  711. self.eventLoop.advanceTime(by: .seconds(1))
  712. for waiter in waiters {
  713. XCTAssertThrowsError(try waiter.wait()) { error in
  714. switch error as? GRPCConnectionPoolError {
  715. case .some(let error):
  716. XCTAssertEqual(error.code, .deadlineExceeded)
  717. XCTAssertNil(error.underlyingError)
  718. default:
  719. XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
  720. }
  721. }
  722. }
  723. }
  724. func testWaiterStoresItsScheduledTask() throws {
  725. let deadline = NIODeadline.uptimeNanoseconds(42)
  726. let promise = self.eventLoop.makePromise(of: Channel.self)
  727. let waiter = ConnectionPool.Waiter(deadline: deadline, promise: promise) {
  728. return $0.eventLoop.makeSucceededVoidFuture()
  729. }
  730. XCTAssertNil(waiter._scheduledTimeout)
  731. waiter.scheduleTimeout(on: self.eventLoop) {
  732. waiter.fail(GRPCConnectionPoolError.deadlineExceeded(connectionError: nil))
  733. }
  734. XCTAssertNotNil(waiter._scheduledTimeout)
  735. self.eventLoop.advanceTime(to: deadline)
  736. XCTAssertThrowsError(try promise.futureResult.wait())
  737. XCTAssertNil(waiter._scheduledTimeout)
  738. }
  739. func testReturnStreamAfterConnectionCloses() throws {
  740. var returnedStreams = 0
  741. let (pool, controller) = self.setUpPoolAndController(onReservationReturned: { returned in
  742. returnedStreams += returned
  743. })
  744. pool.initialize(connections: 1)
  745. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  746. $0.eventLoop.makeSucceededVoidFuture()
  747. }
  748. // Start creating the channel.
  749. self.eventLoop.run()
  750. XCTAssertEqual(controller.count, 1)
  751. // Fire up the connection.
  752. controller.connectChannel(atIndex: 0)
  753. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  754. // Run the loop to create the stream, we need to fire the stream creation event too.
  755. self.eventLoop.run()
  756. XCTAssertNoThrow(try waiter.wait())
  757. controller.openStreamInChannel(atIndex: 0)
  758. XCTAssertEqual(pool.sync.waiters, 0)
  759. XCTAssertEqual(pool.sync.availableStreams, 9)
  760. XCTAssertEqual(pool.sync.reservedStreams, 1)
  761. XCTAssertEqual(pool.sync.connections, 1)
  762. // Close all streams on connection 0.
  763. let error = GRPCStatus(code: .internalError, message: nil)
  764. controller.throwError(error, inChannelAtIndex: 0)
  765. controller.fireChannelInactiveForChannel(atIndex: 0)
  766. XCTAssertEqual(returnedStreams, 1)
  767. XCTAssertEqual(pool.sync.waiters, 0)
  768. XCTAssertEqual(pool.sync.availableStreams, 0)
  769. XCTAssertEqual(pool.sync.reservedStreams, 0)
  770. XCTAssertEqual(pool.sync.connections, 1)
  771. // The connection is closed so the stream shouldn't be returned again.
  772. controller.closeStreamInChannel(atIndex: 0)
  773. XCTAssertEqual(returnedStreams, 1)
  774. }
  775. func testConnectionPoolDelegate() throws {
  776. let recorder = EventRecordingConnectionPoolDelegate()
  777. let (pool, controller) = self.setUpPoolAndController(delegate: recorder)
  778. pool.initialize(connections: 2)
  779. func assertConnectionAdded(
  780. _ event: EventRecordingConnectionPoolDelegate.Event?
  781. ) throws -> GRPCConnectionID {
  782. let unwrappedEvent = try XCTUnwrap(event)
  783. switch unwrappedEvent {
  784. case let .connectionAdded(id):
  785. return id
  786. default:
  787. throw EventRecordingConnectionPoolDelegate.UnexpectedEvent(unwrappedEvent)
  788. }
  789. }
  790. let connID1 = try assertConnectionAdded(recorder.popFirst())
  791. let connID2 = try assertConnectionAdded(recorder.popFirst())
  792. let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  793. $0.eventLoop.makeSucceededVoidFuture()
  794. }
  795. // Start creating the channel.
  796. self.eventLoop.run()
  797. let startedConnecting = recorder.popFirst()
  798. let firstConn: GRPCConnectionID
  799. let secondConn: GRPCConnectionID
  800. if startedConnecting == .startedConnecting(connID1) {
  801. firstConn = connID1
  802. secondConn = connID2
  803. } else if startedConnecting == .startedConnecting(connID2) {
  804. firstConn = connID2
  805. secondConn = connID1
  806. } else {
  807. return XCTFail("Unexpected event")
  808. }
  809. // Connect the connection.
  810. self.eventLoop.run()
  811. controller.connectChannel(atIndex: 0)
  812. controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
  813. XCTAssertEqual(recorder.popFirst(), .connectSucceeded(firstConn, 10))
  814. // Open a stream for the waiter.
  815. controller.openStreamInChannel(atIndex: 0)
  816. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 1, 10))
  817. self.eventLoop.run()
  818. XCTAssertNoThrow(try waiter.wait())
  819. // Okay, more utilization!
  820. for n in 2 ... 8 {
  821. let w = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  822. $0.eventLoop.makeSucceededVoidFuture()
  823. }
  824. controller.openStreamInChannel(atIndex: 0)
  825. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, n, 10))
  826. self.eventLoop.run()
  827. XCTAssertNoThrow(try w.wait())
  828. }
  829. // The utilisation threshold before bringing up a new connection is 0.9; we have 8 open streams
  830. // (out of 10) now so opening the next should trigger a connect on the other connection.
  831. let w9 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  832. $0.eventLoop.makeSucceededVoidFuture()
  833. }
  834. XCTAssertEqual(recorder.popFirst(), .startedConnecting(secondConn))
  835. // Deal with the 9th stream.
  836. controller.openStreamInChannel(atIndex: 0)
  837. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 9, 10))
  838. self.eventLoop.run()
  839. XCTAssertNoThrow(try w9.wait())
  840. // Bring up the next connection.
  841. controller.connectChannel(atIndex: 1)
  842. controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
  843. XCTAssertEqual(recorder.popFirst(), .connectSucceeded(secondConn, 10))
  844. // The next stream should be on the new connection.
  845. let w10 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
  846. $0.eventLoop.makeSucceededVoidFuture()
  847. }
  848. // Deal with the 10th stream.
  849. controller.openStreamInChannel(atIndex: 1)
  850. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(secondConn, 1, 10))
  851. self.eventLoop.run()
  852. XCTAssertNoThrow(try w10.wait())
  853. // Close the streams.
  854. for i in 1 ... 9 {
  855. controller.closeStreamInChannel(atIndex: 0)
  856. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 9 - i, 10))
  857. }
  858. controller.closeStreamInChannel(atIndex: 1)
  859. XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(secondConn, 0, 10))
  860. // Close the connections.
  861. controller.fireChannelInactiveForChannel(atIndex: 0)
  862. XCTAssertEqual(recorder.popFirst(), .connectionClosed(firstConn))
  863. controller.fireChannelInactiveForChannel(atIndex: 1)
  864. XCTAssertEqual(recorder.popFirst(), .connectionClosed(secondConn))
  865. // All conns are already closed.
  866. let shutdownFuture = pool.shutdown()
  867. self.eventLoop.run()
  868. XCTAssertNoThrow(try shutdownFuture.wait())
  869. // Two connections must be removed.
  870. for _ in 0 ..< 2 {
  871. if let event = recorder.popFirst() {
  872. let id = event.id
  873. XCTAssertEqual(event, .connectionRemoved(id))
  874. } else {
  875. XCTFail("Expected .connectionRemoved")
  876. }
  877. }
  878. }
  879. func testConnectionPoolErrorDescription() {
  880. var error = GRPCConnectionPoolError(code: .deadlineExceeded)
  881. XCTAssertEqual(String(describing: error), "deadlineExceeded")
  882. error.code = .shutdown
  883. XCTAssertEqual(String(describing: error), "shutdown")
  884. error.code = .tooManyWaiters
  885. XCTAssertEqual(String(describing: error), "tooManyWaiters")
  886. struct DummyError: Error {}
  887. error.underlyingError = DummyError()
  888. XCTAssertEqual(String(describing: error), "tooManyWaiters (DummyError())")
  889. }
  890. func testConnectionPoolErrorCodeEquality() {
  891. let error = GRPCConnectionPoolError(code: .deadlineExceeded)
  892. XCTAssertEqual(error.code, .deadlineExceeded)
  893. XCTAssertNotEqual(error.code, .shutdown)
  894. }
  895. }
  896. extension ConnectionPool {
  897. // For backwards compatibility, to avoid large diffs in these tests.
  898. fileprivate func shutdown() -> EventLoopFuture<Void> {
  899. return self.shutdown(mode: .forceful)
  900. }
  901. }
  902. // MARK: - Helpers
  903. internal final class ChannelController {
  904. private var channels: [EmbeddedChannel] = []
  905. internal var count: Int {
  906. return self.channels.count
  907. }
  908. internal func finish() {
  909. while let channel = self.channels.popLast() {
  910. // We're okay with this throwing: some channels are left in a bad state (i.e. with errors).
  911. _ = try? channel.finish()
  912. }
  913. }
  914. private func isValidIndex(
  915. _ index: Int,
  916. file: StaticString = #filePath,
  917. line: UInt = #line
  918. ) -> Bool {
  919. let isValid = self.channels.indices.contains(index)
  920. XCTAssertTrue(isValid, "Invalid connection index '\(index)'", file: file, line: line)
  921. return isValid
  922. }
  923. internal func connectChannel(
  924. atIndex index: Int,
  925. file: StaticString = #filePath,
  926. line: UInt = #line
  927. ) {
  928. guard self.isValidIndex(index, file: file, line: line) else { return }
  929. XCTAssertNoThrow(
  930. try self.channels[index].connect(to: .init(unixDomainSocketPath: "/")),
  931. file: file,
  932. line: line
  933. )
  934. }
  935. internal func fireChannelInactiveForChannel(
  936. atIndex index: Int,
  937. file: StaticString = #filePath,
  938. line: UInt = #line
  939. ) {
  940. guard self.isValidIndex(index, file: file, line: line) else { return }
  941. self.channels[index].pipeline.fireChannelInactive()
  942. }
  943. internal func throwError(
  944. _ error: Error,
  945. inChannelAtIndex index: Int,
  946. file: StaticString = #filePath,
  947. line: UInt = #line
  948. ) {
  949. guard self.isValidIndex(index, file: file, line: line) else { return }
  950. self.channels[index].pipeline.fireErrorCaught(error)
  951. }
  952. internal func sendSettingsToChannel(
  953. atIndex index: Int,
  954. maxConcurrentStreams: Int = 100,
  955. file: StaticString = #filePath,
  956. line: UInt = #line
  957. ) {
  958. guard self.isValidIndex(index, file: file, line: line) else { return }
  959. let settings = [HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)]
  960. let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
  961. XCTAssertNoThrow(try self.channels[index].writeInbound(settingsFrame), file: file, line: line)
  962. }
  963. internal func sendGoAwayToChannel(
  964. atIndex index: Int,
  965. file: StaticString = #filePath,
  966. line: UInt = #line
  967. ) {
  968. guard self.isValidIndex(index, file: file, line: line) else { return }
  969. let goAwayFrame = HTTP2Frame(
  970. streamID: .rootStream,
  971. payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil)
  972. )
  973. XCTAssertNoThrow(try self.channels[index].writeInbound(goAwayFrame), file: file, line: line)
  974. }
  975. internal func openStreamInChannel(
  976. atIndex index: Int,
  977. file: StaticString = #filePath,
  978. line: UInt = #line
  979. ) {
  980. guard self.isValidIndex(index, file: file, line: line) else { return }
  981. // The details don't matter here.
  982. let event = NIOHTTP2StreamCreatedEvent(
  983. streamID: .rootStream,
  984. localInitialWindowSize: nil,
  985. remoteInitialWindowSize: nil
  986. )
  987. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  988. }
  989. internal func closeStreamInChannel(
  990. atIndex index: Int,
  991. file: StaticString = #filePath,
  992. line: UInt = #line
  993. ) {
  994. guard self.isValidIndex(index, file: file, line: line) else { return }
  995. // The details don't matter here.
  996. let event = StreamClosedEvent(streamID: .rootStream, reason: nil)
  997. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  998. }
  999. }
  1000. extension ChannelController: ConnectionManagerChannelProvider {
  1001. internal func makeChannel(
  1002. managedBy connectionManager: ConnectionManager,
  1003. onEventLoop eventLoop: EventLoop,
  1004. connectTimeout: TimeAmount?,
  1005. logger: Logger
  1006. ) -> EventLoopFuture<Channel> {
  1007. let channel = EmbeddedChannel(loop: eventLoop as! EmbeddedEventLoop)
  1008. self.channels.append(channel)
  1009. let multiplexer = HTTP2StreamMultiplexer(
  1010. mode: .client,
  1011. channel: channel,
  1012. inboundStreamInitializer: nil
  1013. )
  1014. let idleHandler = GRPCIdleHandler(
  1015. connectionManager: connectionManager,
  1016. multiplexer: multiplexer,
  1017. idleTimeout: .minutes(5),
  1018. keepalive: ClientConnectionKeepalive(),
  1019. logger: logger
  1020. )
  1021. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(idleHandler))
  1022. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(multiplexer))
  1023. return eventLoop.makeSucceededFuture(channel)
  1024. }
  1025. }
  1026. internal struct HookedStreamLender: StreamLender {
  1027. internal var onReturnStreams: (Int) -> Void
  1028. internal var onUpdateMaxAvailableStreams: (Int) -> Void
  1029. internal func returnStreams(_ count: Int, to pool: ConnectionPool) {
  1030. self.onReturnStreams(count)
  1031. }
  1032. internal func changeStreamCapacity(by delta: Int, for: ConnectionPool) {
  1033. self.onUpdateMaxAvailableStreams(delta)
  1034. }
  1035. }
  1036. extension Optional where Wrapped == GRPCConnectionPoolError {
  1037. internal var isTooManyWaiters: Bool {
  1038. self?.code == .tooManyWaiters
  1039. }
  1040. internal var isDeadlineExceeded: Bool {
  1041. self?.code == .deadlineExceeded
  1042. }
  1043. internal var isShutdown: Bool {
  1044. self?.code == .shutdown
  1045. }
  1046. }