RoundRobinLoadBalancerTests.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import GRPCHTTP2Core
  18. import NIOHTTP2
  19. import NIOPosix
  20. import XCTest
  21. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  22. final class RoundRobinLoadBalancerTests: XCTestCase {
  23. func testMultipleConnectionsAreEstablished() async throws {
  24. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  25. switch event {
  26. case .connectivityStateChanged(.idle):
  27. // Update the addresses for the load balancer, this will trigger subchannels to be created
  28. // for each.
  29. let endpoints = context.servers.map { Endpoint(addresses: [$0.address]) }
  30. context.roundRobin!.updateAddresses(endpoints)
  31. case .connectivityStateChanged(.ready):
  32. // Poll until each server has one connected client.
  33. try await XCTPoll(every: .milliseconds(10)) {
  34. context.servers.allSatisfy { server, _ in server.clients.count == 1 }
  35. }
  36. // Close to end the test.
  37. context.loadBalancer.close()
  38. default:
  39. ()
  40. }
  41. } verifyEvents: { events in
  42. let expected: [LoadBalancerEvent] = [
  43. .connectivityStateChanged(.idle),
  44. .connectivityStateChanged(.connecting),
  45. .connectivityStateChanged(.ready),
  46. .connectivityStateChanged(.shutdown),
  47. ]
  48. XCTAssertEqual(events, expected)
  49. }
  50. }
  51. func testSubchannelsArePickedEvenly() async throws {
  52. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  53. switch event {
  54. case .connectivityStateChanged(.idle):
  55. // Update the addresses for the load balancer, this will trigger subchannels to be created
  56. // for each.
  57. let endpoints = context.servers.map { Endpoint(addresses: [$0.address]) }
  58. context.roundRobin!.updateAddresses(endpoints)
  59. case .connectivityStateChanged(.ready):
  60. // Subchannel is ready. This happens when any subchannel becomes ready. Loop until
  61. // we can pick three distinct subchannels.
  62. try await XCTPoll(every: .milliseconds(10)) {
  63. var subchannelIDs = Set<SubchannelID>()
  64. for _ in 0 ..< 3 {
  65. let subchannel = try XCTUnwrap(context.loadBalancer.pickSubchannel())
  66. subchannelIDs.insert(subchannel.id)
  67. }
  68. return subchannelIDs.count == 3
  69. }
  70. // Now that all are ready, load should be distributed evenly among them.
  71. var counts = [SubchannelID: Int]()
  72. for round in 1 ... 10 {
  73. for _ in 1 ... 3 {
  74. if let subchannel = context.loadBalancer.pickSubchannel() {
  75. counts[subchannel.id, default: 0] += 1
  76. } else {
  77. XCTFail("Didn't pick subchannel from ready load balancer")
  78. }
  79. }
  80. XCTAssertEqual(counts.count, 3, "\(counts)")
  81. XCTAssert(counts.values.allSatisfy({ $0 == round }), "\(counts)")
  82. }
  83. // Close to finish the test.
  84. context.loadBalancer.close()
  85. default:
  86. ()
  87. }
  88. } verifyEvents: { events in
  89. let expected: [LoadBalancerEvent] = [
  90. .connectivityStateChanged(.idle),
  91. .connectivityStateChanged(.connecting),
  92. .connectivityStateChanged(.ready),
  93. .connectivityStateChanged(.shutdown),
  94. ]
  95. XCTAssertEqual(events, expected)
  96. }
  97. }
  98. func testAddressUpdatesAreHandledGracefully() async throws {
  99. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  100. switch event {
  101. case .connectivityStateChanged(.idle):
  102. // Do the first connect.
  103. let endpoints = [Endpoint(addresses: [context.servers[0].address])]
  104. context.roundRobin!.updateAddresses(endpoints)
  105. case .connectivityStateChanged(.ready):
  106. // Now the first connection should be established.
  107. do {
  108. try await XCTPoll(every: .milliseconds(10)) {
  109. context.servers[0].server.clients.count == 1
  110. }
  111. }
  112. // First connection is okay, add a second.
  113. do {
  114. let endpoints = [
  115. Endpoint(addresses: [context.servers[0].address]),
  116. Endpoint(addresses: [context.servers[1].address]),
  117. ]
  118. context.roundRobin!.updateAddresses(endpoints)
  119. try await XCTPoll(every: .milliseconds(10)) {
  120. context.servers.prefix(2).allSatisfy { $0.server.clients.count == 1 }
  121. }
  122. }
  123. // Remove those two endpoints and add a third.
  124. do {
  125. let endpoints = [Endpoint(addresses: [context.servers[2].address])]
  126. context.roundRobin!.updateAddresses(endpoints)
  127. try await XCTPoll(every: .milliseconds(10)) {
  128. let disconnected = context.servers.prefix(2).allSatisfy { $0.server.clients.isEmpty }
  129. let connected = context.servers.last!.server.clients.count == 1
  130. return disconnected && connected
  131. }
  132. }
  133. context.loadBalancer.close()
  134. default:
  135. ()
  136. }
  137. } verifyEvents: { events in
  138. // Transitioning to new addresses should be graceful, i.e. a complete change shouldn't
  139. // result in dropping away from the ready state.
  140. let expected: [LoadBalancerEvent] = [
  141. .connectivityStateChanged(.idle),
  142. .connectivityStateChanged(.connecting),
  143. .connectivityStateChanged(.ready),
  144. .connectivityStateChanged(.shutdown),
  145. ]
  146. XCTAssertEqual(events, expected)
  147. }
  148. }
  149. func testSameAddressUpdatesAreIgnored() async throws {
  150. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  151. switch event {
  152. case .connectivityStateChanged(.idle):
  153. let endpoints = context.servers.map { _, address in Endpoint(addresses: [address]) }
  154. context.roundRobin!.updateAddresses(endpoints)
  155. case .connectivityStateChanged(.ready):
  156. // Update with the same addresses, these should be ignored.
  157. let endpoints = context.servers.map { _, address in Endpoint(addresses: [address]) }
  158. context.roundRobin!.updateAddresses(endpoints)
  159. // We should still have three connections.
  160. try await XCTPoll(every: .milliseconds(10)) {
  161. context.servers.allSatisfy { $0.server.clients.count == 1 }
  162. }
  163. context.loadBalancer.close()
  164. default:
  165. ()
  166. }
  167. } verifyEvents: { events in
  168. let expected: [LoadBalancerEvent] = [
  169. .connectivityStateChanged(.idle),
  170. .connectivityStateChanged(.connecting),
  171. .connectivityStateChanged(.ready),
  172. .connectivityStateChanged(.shutdown),
  173. ]
  174. XCTAssertEqual(events, expected)
  175. }
  176. }
  177. func testEmptyAddressUpdatesAreIgnored() async throws {
  178. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  179. switch event {
  180. case .connectivityStateChanged(.idle):
  181. let endpoints = context.servers.map { _, address in Endpoint(addresses: [address]) }
  182. context.roundRobin!.updateAddresses(endpoints)
  183. case .connectivityStateChanged(.ready):
  184. // Update with no-addresses, should be ignored so a subchannel can still be picked.
  185. context.roundRobin!.updateAddresses([])
  186. // We should still have three connections.
  187. try await XCTPoll(every: .milliseconds(10)) {
  188. context.servers.allSatisfy { $0.server.clients.count == 1 }
  189. }
  190. context.loadBalancer.close()
  191. default:
  192. ()
  193. }
  194. } verifyEvents: { events in
  195. let expected: [LoadBalancerEvent] = [
  196. .connectivityStateChanged(.idle),
  197. .connectivityStateChanged(.connecting),
  198. .connectivityStateChanged(.ready),
  199. .connectivityStateChanged(.shutdown),
  200. ]
  201. XCTAssertEqual(events, expected)
  202. }
  203. }
  204. func testSubchannelReceivesGoAway() async throws {
  205. try await LoadBalancerTest.roundRobin(servers: 3, connector: .posix()) { context, event in
  206. switch event {
  207. case .connectivityStateChanged(.idle):
  208. // Trigger the connect.
  209. let endpoints = context.servers.map { Endpoint(addresses: [$0.address]) }
  210. context.roundRobin!.updateAddresses(endpoints)
  211. case .connectivityStateChanged(.ready):
  212. // Wait for all servers to become ready.
  213. try await XCTPoll(every: .milliseconds(10)) {
  214. context.servers.allSatisfy { $0.server.clients.count == 1 }
  215. }
  216. // The above only checks whether each server has a client, the test relies on all three
  217. // subchannels being ready, poll until we get three distinct IDs.
  218. var ids = Set<SubchannelID>()
  219. try await XCTPoll(every: .milliseconds(10)) {
  220. for _ in 1 ... 3 {
  221. if let subchannel = context.loadBalancer.pickSubchannel() {
  222. ids.insert(subchannel.id)
  223. }
  224. }
  225. return ids.count == 3
  226. }
  227. // Pick the first server and send a GOAWAY to the client.
  228. let client = context.servers[0].server.clients[0]
  229. let goAway = HTTP2Frame(
  230. streamID: .rootStream,
  231. payload: .goAway(lastStreamID: 0, errorCode: .cancel, opaqueData: nil)
  232. )
  233. // Send a GOAWAY, this should eventually close the subchannel and trigger a name
  234. // resolution.
  235. client.writeAndFlush(goAway, promise: nil)
  236. case .requiresNameResolution:
  237. // One subchannel should've been taken out, meaning we can only pick from the remaining two:
  238. let id1 = try XCTUnwrap(context.loadBalancer.pickSubchannel()?.id)
  239. let id2 = try XCTUnwrap(context.loadBalancer.pickSubchannel()?.id)
  240. let id3 = try XCTUnwrap(context.loadBalancer.pickSubchannel()?.id)
  241. XCTAssertNotEqual(id1, id2)
  242. XCTAssertEqual(id1, id3)
  243. // End the test.
  244. context.loadBalancer.close()
  245. default:
  246. ()
  247. }
  248. } verifyEvents: { events in
  249. let expected: [LoadBalancerEvent] = [
  250. .connectivityStateChanged(.idle),
  251. .connectivityStateChanged(.connecting),
  252. .connectivityStateChanged(.ready),
  253. .requiresNameResolution,
  254. .connectivityStateChanged(.shutdown),
  255. ]
  256. XCTAssertEqual(events, expected)
  257. }
  258. }
  259. func testPickSubchannelWhenNotReady() {
  260. let loadBalancer = RoundRobinLoadBalancer(
  261. connector: .never,
  262. backoff: .defaults,
  263. defaultCompression: .none,
  264. enabledCompression: .none
  265. )
  266. XCTAssertNil(loadBalancer.pickSubchannel())
  267. }
  268. func testPickSubchannelWhenClosed() async {
  269. let loadBalancer = RoundRobinLoadBalancer(
  270. connector: .never,
  271. backoff: .defaults,
  272. defaultCompression: .none,
  273. enabledCompression: .none
  274. )
  275. loadBalancer.close()
  276. await loadBalancer.run()
  277. XCTAssertNil(loadBalancer.pickSubchannel())
  278. }
  279. func testPickOnIdleLoadBalancerTriggersConnect() async throws {
  280. let idle = AtomicCounter()
  281. let ready = AtomicCounter()
  282. try await LoadBalancerTest.roundRobin(
  283. servers: 1,
  284. connector: .posix(maxIdleTime: .milliseconds(25)) // Aggressively idle the connection
  285. ) { context, event in
  286. switch event {
  287. case .connectivityStateChanged(.idle):
  288. let (_, newIdleCount) = idle.increment()
  289. switch newIdleCount {
  290. case 1:
  291. // The first idle happens when the load balancer in started, give it a set of addresses
  292. // which it will connect to. Wait for it to be ready and then idle again.
  293. let address = context.servers[0].address
  294. let endpoints = [Endpoint(addresses: [address])]
  295. context.roundRobin!.updateAddresses(endpoints)
  296. case 2:
  297. // Load-balancer has the endpoints but all are idle. Picking will trigger a connect.
  298. XCTAssertNil(context.loadBalancer.pickSubchannel())
  299. case 3:
  300. // Connection idled again. Shut it down.
  301. context.loadBalancer.close()
  302. default:
  303. XCTFail("Became idle too many times")
  304. }
  305. case .connectivityStateChanged(.ready):
  306. let (_, newReadyCount) = ready.increment()
  307. if newReadyCount == 2 {
  308. XCTAssertNotNil(context.loadBalancer.pickSubchannel())
  309. }
  310. default:
  311. ()
  312. }
  313. } verifyEvents: { events in
  314. let expected: [LoadBalancerEvent] = [
  315. .connectivityStateChanged(.idle),
  316. .connectivityStateChanged(.connecting),
  317. .connectivityStateChanged(.ready),
  318. .connectivityStateChanged(.idle),
  319. .connectivityStateChanged(.connecting),
  320. .connectivityStateChanged(.ready),
  321. .connectivityStateChanged(.idle),
  322. .connectivityStateChanged(.shutdown),
  323. ]
  324. XCTAssertEqual(events, expected)
  325. }
  326. }
  327. }