ClientConnectionBackoffTests.swift 7.8 KB

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