PoolManagerStateMachineTests.swift 11 KB

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