ConnectionPoolTests.swift 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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,
  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) {
  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) {
  157. $0.eventLoop.makeSucceededVoidFuture()
  158. }
  159. }
  160. let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  411. $0.eventLoop.makeSucceededVoidFuture()
  412. }
  413. let waiter2 = pool.makeStream(deadline: .uptimeNanoseconds(15), logger: self.logger) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  572. $0.eventLoop.makeSucceededVoidFuture()
  573. }
  574. let w3 = pool.makeStream(
  575. deadline: .uptimeNanoseconds(UInt64(TimeAmount.milliseconds(500).nanoseconds)),
  576. logger: self.logger
  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) {
  619. $0.eventLoop.makeSucceededVoidFuture()
  620. }
  621. let w2 = pool.makeStream(deadline: .uptimeNanoseconds(20), logger: self.logger) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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. XCTAssertEqual(event, event.id.map { .connectionRemoved($0) })
  876. } else {
  877. XCTFail("Expected .connectionRemoved")
  878. }
  879. }
  880. }
  881. func testConnectionPoolErrorDescription() {
  882. var error = GRPCConnectionPoolError(code: .deadlineExceeded)
  883. XCTAssertEqual(String(describing: error), "deadlineExceeded")
  884. error.code = .shutdown
  885. XCTAssertEqual(String(describing: error), "shutdown")
  886. error.code = .tooManyWaiters
  887. XCTAssertEqual(String(describing: error), "tooManyWaiters")
  888. struct DummyError: Error {}
  889. error.underlyingError = DummyError()
  890. XCTAssertEqual(String(describing: error), "tooManyWaiters (DummyError())")
  891. }
  892. func testConnectionPoolErrorCodeEquality() {
  893. let error = GRPCConnectionPoolError(code: .deadlineExceeded)
  894. XCTAssertEqual(error.code, .deadlineExceeded)
  895. XCTAssertNotEqual(error.code, .shutdown)
  896. }
  897. func testMinimumConnectionsAreOpenRightAfterInitializing() {
  898. let controller = ChannelController()
  899. let pool = self.makePool(minConnections: 5, channelProvider: controller)
  900. pool.initialize(connections: 20)
  901. self.eventLoop.run()
  902. XCTAssertEqual(pool.sync.connections, 20)
  903. XCTAssertEqual(pool.sync.idleConnections, 15)
  904. XCTAssertEqual(pool.sync.activeConnections, 5)
  905. XCTAssertEqual(pool.sync.waiters, 0)
  906. XCTAssertEqual(pool.sync.availableStreams, 0)
  907. XCTAssertEqual(pool.sync.reservedStreams, 0)
  908. XCTAssertEqual(pool.sync.transientFailureConnections, 0)
  909. }
  910. func testMinimumConnectionsAreOpenAfterOneIsQuiesced() {
  911. let controller = ChannelController()
  912. let pool = self.makePool(
  913. minConnections: 1,
  914. assumedMaxConcurrentStreams: 1,
  915. channelProvider: controller
  916. )
  917. // Initialize two connections, and make sure that only one of them is active,
  918. // since we have set minConnections to 1.
  919. pool.initialize(connections: 2)
  920. self.eventLoop.run()
  921. XCTAssertEqual(pool.sync.connections, 2)
  922. XCTAssertEqual(pool.sync.idleConnections, 1)
  923. XCTAssertEqual(pool.sync.activeConnections, 1)
  924. XCTAssertEqual(pool.sync.transientFailureConnections, 0)
  925. // Open two streams, which, because the maxConcurrentStreams is 1, will
  926. // create two channels.
  927. let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger) {
  928. $0.eventLoop.makeSucceededVoidFuture()
  929. }
  930. let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger) {
  931. $0.eventLoop.makeSucceededVoidFuture()
  932. }
  933. // Start creating the channels.
  934. self.eventLoop.run()
  935. // Make both connections ready.
  936. controller.connectChannel(atIndex: 0)
  937. controller.sendSettingsToChannel(atIndex: 0)
  938. controller.connectChannel(atIndex: 1)
  939. controller.sendSettingsToChannel(atIndex: 1)
  940. // Run the loop to create the streams/connections.
  941. self.eventLoop.run()
  942. XCTAssertNoThrow(try w1.wait())
  943. controller.openStreamInChannel(atIndex: 0)
  944. XCTAssertNoThrow(try w2.wait())
  945. controller.openStreamInChannel(atIndex: 1)
  946. XCTAssertEqual(pool.sync.connections, 2)
  947. XCTAssertEqual(pool.sync.idleConnections, 0)
  948. XCTAssertEqual(pool.sync.activeConnections, 2)
  949. XCTAssertEqual(pool.sync.transientFailureConnections, 0)
  950. // Quiesce the connection that should be kept alive.
  951. // Another connection should be brought back up immediately after, to maintain
  952. // the minimum number of active connections that won't go idle.
  953. controller.sendGoAwayToChannel(atIndex: 0)
  954. XCTAssertEqual(pool.sync.connections, 3)
  955. XCTAssertEqual(pool.sync.idleConnections, 1)
  956. XCTAssertEqual(pool.sync.activeConnections, 2)
  957. XCTAssertEqual(pool.sync.transientFailureConnections, 0)
  958. // Now quiesce the other one. This will add a new idle connection, but it
  959. // won't connect it right away.
  960. controller.sendGoAwayToChannel(atIndex: 1)
  961. XCTAssertEqual(pool.sync.connections, 4)
  962. XCTAssertEqual(pool.sync.idleConnections, 2)
  963. XCTAssertEqual(pool.sync.activeConnections, 2)
  964. XCTAssertEqual(pool.sync.transientFailureConnections, 0)
  965. }
  966. }
  967. extension ConnectionPool {
  968. // For backwards compatibility, to avoid large diffs in these tests.
  969. fileprivate func shutdown() -> EventLoopFuture<Void> {
  970. return self.shutdown(mode: .forceful)
  971. }
  972. }
  973. // MARK: - Helpers
  974. internal final class ChannelController {
  975. private var channels: [EmbeddedChannel] = []
  976. internal var count: Int {
  977. return self.channels.count
  978. }
  979. internal func finish() {
  980. while let channel = self.channels.popLast() {
  981. // We're okay with this throwing: some channels are left in a bad state (i.e. with errors).
  982. _ = try? channel.finish()
  983. }
  984. }
  985. private func isValidIndex(
  986. _ index: Int,
  987. file: StaticString = #filePath,
  988. line: UInt = #line
  989. ) -> Bool {
  990. let isValid = self.channels.indices.contains(index)
  991. XCTAssertTrue(isValid, "Invalid connection index '\(index)'", file: file, line: line)
  992. return isValid
  993. }
  994. internal func connectChannel(
  995. atIndex index: Int,
  996. file: StaticString = #filePath,
  997. line: UInt = #line
  998. ) {
  999. guard self.isValidIndex(index, file: file, line: line) else { return }
  1000. XCTAssertNoThrow(
  1001. try self.channels[index].connect(to: .init(unixDomainSocketPath: "/")),
  1002. file: file,
  1003. line: line
  1004. )
  1005. }
  1006. internal func fireChannelInactiveForChannel(
  1007. atIndex index: Int,
  1008. file: StaticString = #filePath,
  1009. line: UInt = #line
  1010. ) {
  1011. guard self.isValidIndex(index, file: file, line: line) else { return }
  1012. self.channels[index].pipeline.fireChannelInactive()
  1013. }
  1014. internal func throwError(
  1015. _ error: Error,
  1016. inChannelAtIndex index: Int,
  1017. file: StaticString = #filePath,
  1018. line: UInt = #line
  1019. ) {
  1020. guard self.isValidIndex(index, file: file, line: line) else { return }
  1021. self.channels[index].pipeline.fireErrorCaught(error)
  1022. }
  1023. internal func sendSettingsToChannel(
  1024. atIndex index: Int,
  1025. maxConcurrentStreams: Int = 100,
  1026. file: StaticString = #filePath,
  1027. line: UInt = #line
  1028. ) {
  1029. guard self.isValidIndex(index, file: file, line: line) else { return }
  1030. let settings = [HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)]
  1031. let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
  1032. XCTAssertNoThrow(try self.channels[index].writeInbound(settingsFrame), file: file, line: line)
  1033. }
  1034. internal func sendGoAwayToChannel(
  1035. atIndex index: Int,
  1036. file: StaticString = #filePath,
  1037. line: UInt = #line
  1038. ) {
  1039. guard self.isValidIndex(index, file: file, line: line) else { return }
  1040. let goAwayFrame = HTTP2Frame(
  1041. streamID: .rootStream,
  1042. payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil)
  1043. )
  1044. XCTAssertNoThrow(try self.channels[index].writeInbound(goAwayFrame), file: file, line: line)
  1045. }
  1046. internal func openStreamInChannel(
  1047. atIndex index: Int,
  1048. file: StaticString = #filePath,
  1049. line: UInt = #line
  1050. ) {
  1051. guard self.isValidIndex(index, file: file, line: line) else { return }
  1052. // The details don't matter here.
  1053. let event = NIOHTTP2StreamCreatedEvent(
  1054. streamID: .rootStream,
  1055. localInitialWindowSize: nil,
  1056. remoteInitialWindowSize: nil
  1057. )
  1058. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  1059. }
  1060. internal func closeStreamInChannel(
  1061. atIndex index: Int,
  1062. file: StaticString = #filePath,
  1063. line: UInt = #line
  1064. ) {
  1065. guard self.isValidIndex(index, file: file, line: line) else { return }
  1066. // The details don't matter here.
  1067. let event = StreamClosedEvent(streamID: .rootStream, reason: nil)
  1068. self.channels[index].pipeline.fireUserInboundEventTriggered(event)
  1069. }
  1070. }
  1071. extension ChannelController: ConnectionManagerChannelProvider {
  1072. internal func makeChannel(
  1073. managedBy connectionManager: ConnectionManager,
  1074. onEventLoop eventLoop: EventLoop,
  1075. connectTimeout: TimeAmount?,
  1076. logger: Logger
  1077. ) -> EventLoopFuture<Channel> {
  1078. let channel = EmbeddedChannel(loop: eventLoop as! EmbeddedEventLoop)
  1079. self.channels.append(channel)
  1080. let multiplexer = HTTP2StreamMultiplexer(
  1081. mode: .client,
  1082. channel: channel,
  1083. inboundStreamInitializer: nil
  1084. )
  1085. let idleHandler = GRPCIdleHandler(
  1086. connectionManager: connectionManager,
  1087. multiplexer: multiplexer,
  1088. idleTimeout: .minutes(5),
  1089. keepalive: ClientConnectionKeepalive(),
  1090. logger: logger
  1091. )
  1092. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(idleHandler))
  1093. XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(multiplexer))
  1094. return eventLoop.makeSucceededFuture(channel)
  1095. }
  1096. }
  1097. internal struct HookedStreamLender: StreamLender {
  1098. internal var onReturnStreams: (Int) -> Void
  1099. internal var onUpdateMaxAvailableStreams: (Int) -> Void
  1100. internal func returnStreams(_ count: Int, to pool: ConnectionPool) {
  1101. self.onReturnStreams(count)
  1102. }
  1103. internal func changeStreamCapacity(by delta: Int, for: ConnectionPool) {
  1104. self.onUpdateMaxAvailableStreams(delta)
  1105. }
  1106. }
  1107. extension Optional where Wrapped == GRPCConnectionPoolError {
  1108. internal var isTooManyWaiters: Bool {
  1109. self?.code == .tooManyWaiters
  1110. }
  1111. internal var isDeadlineExceeded: Bool {
  1112. self?.code == .deadlineExceeded
  1113. }
  1114. internal var isShutdown: Bool {
  1115. self?.code == .shutdown
  1116. }
  1117. }