PoolManagerStateMachineTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * Copyright 2021, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. @testable import GRPC
  17. import NIO
  18. import NIOConcurrencyHelpers
  19. import XCTest
  20. class PoolManagerStateMachineTests: GRPCTestCase {
  21. private func makeConnectionPool(
  22. on eventLoop: EventLoop,
  23. maxWaiters: Int = 100,
  24. maxConcurrentStreams: Int = 100,
  25. loadThreshold: Double = 0.9,
  26. makeChannel: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
  27. ) -> ConnectionPool {
  28. return ConnectionPool(
  29. eventLoop: eventLoop,
  30. maxWaiters: maxWaiters,
  31. reservationLoadThreshold: loadThreshold,
  32. assumedMaxConcurrentStreams: maxConcurrentStreams,
  33. channelProvider: HookedChannelProvider(makeChannel),
  34. streamLender: HookedStreamLender(
  35. onReturnStreams: { _ in },
  36. onUpdateMaxAvailableStreams: { _ in }
  37. ),
  38. logger: self.logger.wrapped
  39. )
  40. }
  41. private func makeInitializedPools(
  42. group: EmbeddedEventLoopGroup,
  43. connectionsPerPool: Int = 1
  44. ) -> [ConnectionPool] {
  45. let pools = group.loops.map {
  46. self.makeConnectionPool(on: $0) { _, _ in fatalError() }
  47. }
  48. for pool in pools {
  49. pool.initialize(connections: 1)
  50. }
  51. return pools
  52. }
  53. private func makeConnectionPoolKeys(
  54. for pools: [ConnectionPool]
  55. ) -> [PoolManager.ConnectionPoolKey] {
  56. return pools.enumerated().map { index, pool in
  57. return .init(index: .init(index), eventLoopID: pool.eventLoop.id)
  58. }
  59. }
  60. func testReserveStreamOnPreferredEventLoop() {
  61. let group = EmbeddedEventLoopGroup(loops: 5)
  62. defer {
  63. XCTAssertNoThrow(try group.syncShutdownGracefully())
  64. }
  65. let pools = self.makeInitializedPools(group: group, connectionsPerPool: 1)
  66. let keys = self.makeConnectionPoolKeys(for: pools)
  67. var state = PoolManagerStateMachine(
  68. .active(.init(poolKeys: keys, assumedMaxAvailableStreamsPerPool: 100))
  69. )
  70. for (index, loop) in group.loops.enumerated() {
  71. let reservePreferredLoop = state.reserveStream(preferringPoolWithEventLoopID: loop.id)
  72. reservePreferredLoop.assertSuccess {
  73. XCTAssertEqual($0, PoolManager.ConnectionPoolIndex(index))
  74. }
  75. }
  76. }
  77. func testReserveStreamOnPreferredEventLoopWhichNoPoolUses() {
  78. let group = EmbeddedEventLoopGroup(loops: 1)
  79. defer {
  80. XCTAssertNoThrow(try group.syncShutdownGracefully())
  81. }
  82. let pools = self.makeInitializedPools(group: group, connectionsPerPool: 1)
  83. let keys = self.makeConnectionPoolKeys(for: pools)
  84. var state = PoolManagerStateMachine(
  85. .active(.init(poolKeys: keys, assumedMaxAvailableStreamsPerPool: 100))
  86. )
  87. let anotherLoop = EmbeddedEventLoop()
  88. let reservePreferredLoop = state.reserveStream(preferringPoolWithEventLoopID: anotherLoop.id)
  89. reservePreferredLoop.assertSuccess {
  90. XCTAssert((0 ..< pools.count).contains($0.value))
  91. }
  92. }
  93. func testReserveStreamWithNoPreferenceReturnsPoolWithHighestAvailability() {
  94. let group = EmbeddedEventLoopGroup(loops: 5)
  95. defer {
  96. XCTAssertNoThrow(try group.syncShutdownGracefully())
  97. }
  98. let pools = self.makeInitializedPools(group: group, connectionsPerPool: 1)
  99. let keys = self.makeConnectionPoolKeys(for: pools)
  100. var state = PoolManagerStateMachine(.inactive)
  101. state.activatePools(keyedBy: keys, assumingPerPoolCapacity: 100)
  102. // Reserve some streams.
  103. for (index, loop) in group.loops.enumerated() {
  104. for _ in 0 ..< 2 * index {
  105. state.reserveStream(preferringPoolWithEventLoopID: loop.id).assertSuccess()
  106. }
  107. }
  108. // We expect pools[0] to be reserved.
  109. // index: 0 1 2 3 4
  110. // available: 100 98 96 94 92
  111. state.reserveStream(preferringPoolWithEventLoopID: nil).assertSuccess { poolIndex in
  112. XCTAssertEqual(poolIndex.value, 0)
  113. }
  114. // We expect pools[0] to be reserved again.
  115. // index: 0 1 2 3 4
  116. // available: 99 98 96 94 92
  117. state.reserveStream(preferringPoolWithEventLoopID: nil).assertSuccess { poolIndex in
  118. XCTAssertEqual(poolIndex.value, 0)
  119. }
  120. // Return some streams to pools[3].
  121. state.returnStreams(5, toPoolOnEventLoopWithID: pools[3].eventLoop.id)
  122. // As we returned streams to pools[3] we expect this to be the current state:
  123. // index: 0 1 2 3 4
  124. // available: 98 98 96 99 92
  125. state.reserveStream(preferringPoolWithEventLoopID: nil).assertSuccess { poolIndex in
  126. XCTAssertEqual(poolIndex.value, 3)
  127. }
  128. // Give an event loop preference for a pool which has more streams reserved.
  129. state.reserveStream(
  130. preferringPoolWithEventLoopID: pools[2].eventLoop.id
  131. ).assertSuccess { poolIndex in
  132. XCTAssertEqual(poolIndex.value, 2)
  133. }
  134. // Update the capacity for one pool, this makes it relatively more available.
  135. state.changeStreamCapacity(by: 900, forPoolOnEventLoopWithID: pools[4].eventLoop.id)
  136. // pools[4] has a bunch more streams now:
  137. // index: 0 1 2 3 4
  138. // available: 98 98 96 99 992
  139. state.reserveStream(preferringPoolWithEventLoopID: nil).assertSuccess { poolIndex in
  140. XCTAssertEqual(poolIndex.value, 4)
  141. }
  142. }
  143. func testReserveStreamWithNoEventLoopPreference() {
  144. let group = EmbeddedEventLoopGroup(loops: 1)
  145. defer {
  146. XCTAssertNoThrow(try group.syncShutdownGracefully())
  147. }
  148. let pools = self.makeInitializedPools(group: group, connectionsPerPool: 1)
  149. let keys = self.makeConnectionPoolKeys(for: pools)
  150. var state = PoolManagerStateMachine(
  151. .active(.init(poolKeys: keys, assumedMaxAvailableStreamsPerPool: 100))
  152. )
  153. let reservePreferredLoop = state.reserveStream(preferringPoolWithEventLoopID: nil)
  154. reservePreferredLoop.assertSuccess()
  155. }
  156. func testReserveStreamWhenInactive() {
  157. var state = PoolManagerStateMachine(.inactive)
  158. let action = state.reserveStream(preferringPoolWithEventLoopID: nil)
  159. action.assertFailure { error in
  160. XCTAssertEqual(error, .notInitialized)
  161. }
  162. }
  163. func testReserveStreamWhenShuttingDown() {
  164. let future = EmbeddedEventLoop().makeSucceededFuture(())
  165. var state = PoolManagerStateMachine(.shuttingDown(future))
  166. let action = state.reserveStream(preferringPoolWithEventLoopID: nil)
  167. action.assertFailure { error in
  168. XCTAssertEqual(error, .shutdown)
  169. }
  170. }
  171. func testReserveStreamWhenShutdown() {
  172. var state = PoolManagerStateMachine(.shutdown)
  173. let action = state.reserveStream(preferringPoolWithEventLoopID: nil)
  174. action.assertFailure { error in
  175. XCTAssertEqual(error, .shutdown)
  176. }
  177. }
  178. func testShutdownWhenInactive() {
  179. let loop = EmbeddedEventLoop()
  180. let promise = loop.makePromise(of: Void.self)
  181. var state = PoolManagerStateMachine(.inactive)
  182. let action = state.shutdown(promise: promise)
  183. action.assertAlreadyShutdown()
  184. // Don't leak the promise.
  185. promise.succeed(())
  186. }
  187. func testShutdownWhenActive() {
  188. let group = EmbeddedEventLoopGroup(loops: 5)
  189. defer {
  190. XCTAssertNoThrow(try group.syncShutdownGracefully())
  191. }
  192. let pools = self.makeInitializedPools(group: group, connectionsPerPool: 1)
  193. let keys = self.makeConnectionPoolKeys(for: pools)
  194. var state = PoolManagerStateMachine(
  195. .active(.init(poolKeys: keys, assumedMaxAvailableStreamsPerPool: 100))
  196. )
  197. let promise = group.loops[0].makePromise(of: Void.self)
  198. promise.succeed(())
  199. state.shutdown(promise: promise).assertShutdownPools()
  200. }
  201. func testShutdownWhenShuttingDown() {
  202. let loop = EmbeddedEventLoop()
  203. let future = loop.makeSucceededVoidFuture()
  204. var state = PoolManagerStateMachine(.shuttingDown(future))
  205. let promise = loop.makePromise(of: Void.self)
  206. promise.succeed(())
  207. let action = state.shutdown(promise: promise)
  208. action.assertAlreadyShuttingDown {
  209. XCTAssert($0 === future)
  210. }
  211. // Fully shutdown.
  212. state.shutdownComplete()
  213. state.shutdown(promise: promise).assertAlreadyShutdown()
  214. }
  215. func testShutdownWhenShutdown() {
  216. let loop = EmbeddedEventLoop()
  217. var state = PoolManagerStateMachine(.shutdown)
  218. let promise = loop.makePromise(of: Void.self)
  219. promise.succeed(())
  220. let action = state.shutdown(promise: promise)
  221. action.assertAlreadyShutdown()
  222. }
  223. }
  224. // MARK: - Test Helpers
  225. extension Result {
  226. internal func assertSuccess(
  227. file: StaticString = #file,
  228. line: UInt = #line,
  229. verify: (Success) -> Void = { _ in }
  230. ) {
  231. if case let .success(value) = self {
  232. verify(value)
  233. } else {
  234. XCTFail("Expected '.success' but got '\(self)'", file: file, line: line)
  235. }
  236. }
  237. internal func assertFailure(
  238. file: StaticString = #file,
  239. line: UInt = #line,
  240. verify: (Failure) -> Void = { _ in }
  241. ) {
  242. if case let .failure(value) = self {
  243. verify(value)
  244. } else {
  245. XCTFail("Expected '.failure' but got '\(self)'", file: file, line: line)
  246. }
  247. }
  248. }
  249. extension PoolManagerStateMachine.ShutdownAction {
  250. internal func assertShutdownPools(
  251. file: StaticString = #file,
  252. line: UInt = #line
  253. ) {
  254. if case .shutdownPools = self {
  255. ()
  256. } else {
  257. XCTFail("Expected '.shutdownPools' but got '\(self)'", file: file, line: line)
  258. }
  259. }
  260. internal func assertAlreadyShuttingDown(
  261. file: StaticString = #file,
  262. line: UInt = #line,
  263. verify: (EventLoopFuture<Void>) -> Void = { _ in }
  264. ) {
  265. if case let .alreadyShuttingDown(future) = self {
  266. verify(future)
  267. } else {
  268. XCTFail("Expected '.alreadyShuttingDown' but got '\(self)'", file: file, line: line)
  269. }
  270. }
  271. internal func assertAlreadyShutdown(file: StaticString = #file, line: UInt = #line) {
  272. if case .alreadyShutdown = self {
  273. ()
  274. } else {
  275. XCTFail("Expected '.alreadyShutdown' but got '\(self)'", file: file, line: line)
  276. }
  277. }
  278. }
  279. /// An `EventLoopGroup` of `EmbeddedEventLoop`s.
  280. private final class EmbeddedEventLoopGroup: EventLoopGroup {
  281. internal let loops: [EmbeddedEventLoop]
  282. internal let lock = Lock()
  283. internal var index = 0
  284. internal init(loops: Int) {
  285. self.loops = (0 ..< loops).map { _ in EmbeddedEventLoop() }
  286. }
  287. internal func next() -> EventLoop {
  288. let index: Int = self.lock.withLock {
  289. let index = self.index
  290. self.index += 1
  291. return index
  292. }
  293. return self.loops[index % self.loops.count]
  294. }
  295. internal func makeIterator() -> EventLoopIterator {
  296. return EventLoopIterator(self.loops)
  297. }
  298. internal func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
  299. var shutdownError: Error?
  300. for loop in self.loops {
  301. loop.shutdownGracefully(queue: queue) { error in
  302. if let error = error {
  303. shutdownError = error
  304. }
  305. }
  306. }
  307. queue.sync {
  308. callback(shutdownError)
  309. }
  310. }
  311. }