ClientConnectionBackoffTests.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 makeClientConfiguration() -> ClientConnection.Configuration {
  110. return .init(
  111. target: .hostAndPort("localhost", self.port),
  112. eventLoopGroup: self.clientGroup,
  113. connectivityStateDelegate: self.stateDelegate,
  114. connectionBackoff: ConnectionBackoff(maximumBackoff: 0.1,
  115. minimumConnectionTimeout: 0.1))
  116. }
  117. func testClientConnectionFailsWithNoBackoff() throws {
  118. var configuration = self.makeClientConfiguration()
  119. configuration.connectionBackoff = nil
  120. let connectionShutdown = self.expectation(description: "client shutdown")
  121. self.stateDelegate.expectations[.shutdown] = connectionShutdown
  122. self.client = ClientConnection(configuration: configuration)
  123. self.wait(for: [connectionShutdown], timeout: 1.0)
  124. XCTAssertEqual(self.stateDelegate.states, [.connecting, .shutdown])
  125. }
  126. func testClientEventuallyConnects() throws {
  127. let transientFailure = self.expectation(description: "connection transientFailure")
  128. let connectionReady = self.expectation(description: "connection ready")
  129. self.stateDelegate.expectations[.transientFailure] = transientFailure
  130. self.stateDelegate.expectations[.ready] = connectionReady
  131. // Start the client first.
  132. self.client = ClientConnection(configuration: self.makeClientConfiguration())
  133. self.wait(for: [transientFailure], timeout: 1.0)
  134. self.stateDelegate.expectations[.transientFailure] = nil
  135. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .transientFailure])
  136. self.server = self.makeServer()
  137. let serverStarted = self.expectation(description: "server started")
  138. self.server.assertSuccess(fulfill: serverStarted)
  139. self.wait(for: [serverStarted, connectionReady], timeout: 2.0, enforceOrder: true)
  140. // We can have other transient failures and connection attempts while the server starts, we only
  141. // care about the last two.
  142. XCTAssertEqual(self.stateDelegate.states.suffix(2), [.connecting, .ready])
  143. }
  144. func testClientReconnectsAutomatically() throws {
  145. // Wait for the server to start.
  146. self.server = self.makeServer()
  147. let server = try self.server.wait()
  148. // Configure the client backoff to have a short backoff.
  149. var configuration = self.makeClientConfiguration()
  150. configuration.connectionBackoff!.maximumBackoff = 2.0
  151. // Prepare the delegate so it expects the connection to hit `.ready`.
  152. let connectionReady = self.expectation(description: "connection ready")
  153. self.stateDelegate.expectations[.ready] = connectionReady
  154. // Start the connection.
  155. self.client = ClientConnection(configuration: configuration)
  156. // Wait for the connection to be ready.
  157. self.wait(for: [connectionReady], timeout: 1.0)
  158. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  159. // Now that we have a healthy connectiony, prepare for two transient failures:
  160. // 1. when the server has been killed, and
  161. // 2. when the client attempts to reconnect.
  162. let transientFailure = self.expectation(description: "connection transientFailure")
  163. transientFailure.expectedFulfillmentCount = 2
  164. self.stateDelegate.expectations[.transientFailure] = transientFailure
  165. self.stateDelegate.expectations[.ready] = nil
  166. // Okay, kill the server!
  167. try server.close().wait()
  168. try self.serverGroup.syncShutdownGracefully()
  169. self.server = nil
  170. self.serverGroup = nil
  171. // Our connection should fail now.
  172. self.wait(for: [transientFailure], timeout: 1.0)
  173. XCTAssertEqual(self.stateDelegate.clearStates(), [.transientFailure, .connecting, .transientFailure])
  174. self.stateDelegate.expectations[.transientFailure] = nil
  175. // Prepare an expectation for a new healthy connection.
  176. let reconnectionReady = self.expectation(description: "(re)connection ready")
  177. self.stateDelegate.expectations[.ready] = reconnectionReady
  178. let echo = Echo_EchoServiceClient(connection: self.client)
  179. // This should succeed once we get a connection again.
  180. let get = echo.get(.with { $0.text = "hello" })
  181. // Start a new server.
  182. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  183. self.server = self.makeServer()
  184. self.wait(for: [reconnectionReady], timeout: 2.0)
  185. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  186. // The call should be able to succeed now.
  187. XCTAssertEqual(try get.status.map { $0.code }.wait(), .ok)
  188. try self.client.close().wait()
  189. XCTAssertEqual(self.stateDelegate.clearStates(), [.shutdown])
  190. }
  191. }