ClientConnectionBackoffTests.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import GRPC
  18. import EchoModel
  19. import EchoImplementation
  20. import NIO
  21. import XCTest
  22. import NIOConcurrencyHelpers
  23. class ConnectivityStateCollectionDelegate: ConnectivityStateDelegate {
  24. private var _states: [ConnectivityState] = []
  25. private var lock = Lock()
  26. var states: [ConnectivityState] {
  27. get {
  28. return self.lock.withLock {
  29. return self._states
  30. }
  31. }
  32. }
  33. func clearStates() -> [ConnectivityState] {
  34. self.lock.lock()
  35. defer {
  36. self._states.removeAll()
  37. self.lock.unlock()
  38. }
  39. return self._states
  40. }
  41. private var _expectations: [ConnectivityState: XCTestExpectation] = [:]
  42. var expectations: [ConnectivityState: XCTestExpectation] {
  43. get {
  44. return self.lock.withLock {
  45. self._expectations
  46. }
  47. }
  48. set {
  49. self.lock.withLockVoid {
  50. self._expectations = newValue
  51. }
  52. }
  53. }
  54. init(
  55. idle: XCTestExpectation? = nil,
  56. connecting: XCTestExpectation? = nil,
  57. ready: XCTestExpectation? = nil,
  58. transientFailure: XCTestExpectation? = nil,
  59. shutdown: XCTestExpectation? = nil
  60. ) {
  61. self.expectations[.idle] = idle
  62. self.expectations[.connecting] = connecting
  63. self.expectations[.ready] = ready
  64. self.expectations[.transientFailure] = transientFailure
  65. self.expectations[.shutdown] = shutdown
  66. }
  67. func connectivityStateDidChange(from oldState: ConnectivityState, to newState: ConnectivityState) {
  68. self.lock.withLockVoid {
  69. self._states.append(newState)
  70. self._expectations[newState]?.fulfill()
  71. }
  72. }
  73. }
  74. class ClientConnectionBackoffTests: GRPCTestCase {
  75. let port = 8080
  76. var client: ClientConnection!
  77. var server: EventLoopFuture<Server>!
  78. var serverGroup: EventLoopGroup!
  79. var clientGroup: EventLoopGroup!
  80. var stateDelegate = ConnectivityStateCollectionDelegate()
  81. override func setUp() {
  82. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  83. self.clientGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  84. }
  85. override func tearDown() {
  86. // We have additional state changes during tear down, in some cases we can over-fulfill a test
  87. // expectation which causes false negatives.
  88. self.client.connectivity.delegate = nil
  89. if let server = self.server {
  90. XCTAssertNoThrow(try server.flatMap { $0.channel.close() }.wait())
  91. }
  92. XCTAssertNoThrow(try? self.serverGroup.syncShutdownGracefully())
  93. self.server = nil
  94. self.serverGroup = nil
  95. // We don't always expect a client to be closed cleanly, since in some cases we deliberately
  96. // timeout the connection.
  97. try? self.client.close().wait()
  98. XCTAssertNoThrow(try self.clientGroup.syncShutdownGracefully())
  99. self.client = nil
  100. self.clientGroup = nil
  101. }
  102. func makeServer() -> EventLoopFuture<Server> {
  103. let configuration = Server.Configuration(
  104. target: .hostAndPort("localhost", self.port),
  105. eventLoopGroup: self.serverGroup,
  106. serviceProviders: [EchoProvider()])
  107. return Server.start(configuration: configuration)
  108. }
  109. func connectionBuilder() -> ClientConnection.Builder {
  110. return ClientConnection.insecure(group: self.clientGroup)
  111. .withConnectivityStateDelegate(self.stateDelegate)
  112. .withConnectionBackoff(maximum: .milliseconds(100))
  113. .withConnectionTimeout(minimum: .milliseconds(100))
  114. }
  115. func testClientConnectionFailsWithNoBackoff() throws {
  116. let connectionShutdown = self.expectation(description: "client shutdown")
  117. self.stateDelegate.expectations[.shutdown] = connectionShutdown
  118. self.client = self.connectionBuilder()
  119. .withConnectionReestablishment(enabled: false)
  120. .connect(host: "localhost", port: self.port)
  121. self.wait(for: [connectionShutdown], timeout: 1.0)
  122. XCTAssertEqual(self.stateDelegate.states, [.connecting, .shutdown])
  123. }
  124. func testClientEventuallyConnects() throws {
  125. let transientFailure = self.expectation(description: "connection transientFailure")
  126. let connectionReady = self.expectation(description: "connection ready")
  127. self.stateDelegate.expectations[.transientFailure] = transientFailure
  128. self.stateDelegate.expectations[.ready] = connectionReady
  129. // Start the client first.
  130. self.client = self.connectionBuilder()
  131. .connect(host: "localhost", port: self.port)
  132. self.wait(for: [transientFailure], timeout: 1.0)
  133. self.stateDelegate.expectations[.transientFailure] = nil
  134. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .transientFailure])
  135. self.server = self.makeServer()
  136. let serverStarted = self.expectation(description: "server started")
  137. self.server.assertSuccess(fulfill: serverStarted)
  138. self.wait(for: [serverStarted, connectionReady], timeout: 2.0, enforceOrder: true)
  139. // We can have other transient failures and connection attempts while the server starts, we only
  140. // care about the last two.
  141. XCTAssertEqual(self.stateDelegate.states.suffix(2), [.connecting, .ready])
  142. }
  143. func testClientReconnectsAutomatically() throws {
  144. // Wait for the server to start.
  145. self.server = self.makeServer()
  146. let server = try self.server.wait()
  147. // Prepare the delegate so it expects the connection to hit `.ready`.
  148. let connectionReady = self.expectation(description: "connection ready")
  149. self.stateDelegate.expectations[.ready] = connectionReady
  150. // Configure the client backoff to have a short backoff.
  151. self.client = self.connectionBuilder()
  152. .withConnectionBackoff(maximum: .seconds(2))
  153. .connect(host: "localhost", port: self.port)
  154. // Wait for the connection to be ready.
  155. self.wait(for: [connectionReady], timeout: 1.0)
  156. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  157. // Now that we have a healthy connectiony, prepare for two transient failures:
  158. // 1. when the server has been killed, and
  159. // 2. when the client attempts to reconnect.
  160. let transientFailure = self.expectation(description: "connection transientFailure")
  161. transientFailure.expectedFulfillmentCount = 2
  162. self.stateDelegate.expectations[.transientFailure] = transientFailure
  163. self.stateDelegate.expectations[.ready] = nil
  164. // Okay, kill the server!
  165. try server.close().wait()
  166. try self.serverGroup.syncShutdownGracefully()
  167. self.server = nil
  168. self.serverGroup = nil
  169. // Our connection should fail now.
  170. self.wait(for: [transientFailure], timeout: 1.0)
  171. XCTAssertEqual(self.stateDelegate.clearStates(), [.transientFailure, .connecting, .transientFailure])
  172. self.stateDelegate.expectations[.transientFailure] = nil
  173. // Prepare an expectation for a new healthy connection.
  174. let reconnectionReady = self.expectation(description: "(re)connection ready")
  175. self.stateDelegate.expectations[.ready] = reconnectionReady
  176. let echo = Echo_EchoClient(channel: self.client)
  177. // This should succeed once we get a connection again.
  178. let get = echo.get(.with { $0.text = "hello" })
  179. // Start a new server.
  180. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  181. self.server = self.makeServer()
  182. self.wait(for: [reconnectionReady], timeout: 2.0)
  183. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  184. // The call should be able to succeed now.
  185. XCTAssertEqual(try get.status.map { $0.code }.wait(), .ok)
  186. try self.client.close().wait()
  187. XCTAssertEqual(self.stateDelegate.clearStates(), [.shutdown])
  188. }
  189. }