2
0

ClientConnectionBackoffTests.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 NIO
  19. import XCTest
  20. import NIOConcurrencyHelpers
  21. class ConnectivityStateCollectionDelegate: ConnectivityStateDelegate {
  22. private var _states: [ConnectivityState] = []
  23. private var lock = Lock()
  24. var states: [ConnectivityState] {
  25. get {
  26. return self.lock.withLock {
  27. return self._states
  28. }
  29. }
  30. }
  31. func clearStates() -> [ConnectivityState] {
  32. self.lock.lock()
  33. defer {
  34. self._states.removeAll()
  35. self.lock.unlock()
  36. }
  37. return self._states
  38. }
  39. private var _expectations: [ConnectivityState: XCTestExpectation] = [:]
  40. var expectations: [ConnectivityState: XCTestExpectation] {
  41. get {
  42. return self.lock.withLock {
  43. self._expectations
  44. }
  45. }
  46. set {
  47. self.lock.withLockVoid {
  48. self._expectations = newValue
  49. }
  50. }
  51. }
  52. init(
  53. idle: XCTestExpectation? = nil,
  54. connecting: XCTestExpectation? = nil,
  55. ready: XCTestExpectation? = nil,
  56. transientFailure: XCTestExpectation? = nil,
  57. shutdown: XCTestExpectation? = nil
  58. ) {
  59. self.expectations[.idle] = idle
  60. self.expectations[.connecting] = connecting
  61. self.expectations[.ready] = ready
  62. self.expectations[.transientFailure] = transientFailure
  63. self.expectations[.shutdown] = shutdown
  64. }
  65. func connectivityStateDidChange(from oldState: ConnectivityState, to newState: ConnectivityState) {
  66. self.lock.withLockVoid {
  67. self._states.append(newState)
  68. self._expectations[newState]?.fulfill()
  69. }
  70. }
  71. }
  72. class ClientConnectionBackoffTests: GRPCTestCase {
  73. let port = 8080
  74. var client: ClientConnection!
  75. var server: EventLoopFuture<Server>!
  76. var serverGroup: EventLoopGroup!
  77. var clientGroup: EventLoopGroup!
  78. var stateDelegate = ConnectivityStateCollectionDelegate()
  79. override func setUp() {
  80. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  81. self.clientGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  82. }
  83. override func tearDown() {
  84. // We have additional state changes during tear down, in some cases we can over-fulfill a test
  85. // expectation which causes false negatives.
  86. self.client.connectivity.delegate = nil
  87. if let server = self.server {
  88. XCTAssertNoThrow(try server.flatMap { $0.channel.close() }.wait())
  89. }
  90. XCTAssertNoThrow(try? self.serverGroup.syncShutdownGracefully())
  91. self.server = nil
  92. self.serverGroup = nil
  93. // We don't always expect a client to be closed cleanly, since in some cases we deliberately
  94. // timeout the connection.
  95. try? self.client.close().wait()
  96. XCTAssertNoThrow(try self.clientGroup.syncShutdownGracefully())
  97. self.client = nil
  98. self.clientGroup = nil
  99. }
  100. func makeServer() -> EventLoopFuture<Server> {
  101. let configuration = Server.Configuration(
  102. target: .hostAndPort("localhost", self.port),
  103. eventLoopGroup: self.serverGroup,
  104. serviceProviders: [EchoProvider()])
  105. return Server.start(configuration: configuration)
  106. }
  107. func makeClientConfiguration() -> ClientConnection.Configuration {
  108. return .init(
  109. target: .hostAndPort("localhost", self.port),
  110. eventLoopGroup: self.clientGroup,
  111. connectivityStateDelegate: self.stateDelegate,
  112. connectionBackoff: ConnectionBackoff(maximumBackoff: 0.1,
  113. minimumConnectionTimeout: 0.1))
  114. }
  115. func testClientConnectionFailsWithNoBackoff() throws {
  116. var configuration = self.makeClientConfiguration()
  117. configuration.connectionBackoff = nil
  118. let connectionShutdown = self.expectation(description: "client shutdown")
  119. self.stateDelegate.expectations[.shutdown] = connectionShutdown
  120. self.client = ClientConnection(configuration: configuration)
  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 = ClientConnection(configuration: self.makeClientConfiguration())
  131. self.wait(for: [transientFailure], timeout: 1.0)
  132. self.stateDelegate.expectations[.transientFailure] = nil
  133. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .transientFailure])
  134. self.server = self.makeServer()
  135. let serverStarted = self.expectation(description: "server started")
  136. self.server.assertSuccess(fulfill: serverStarted)
  137. self.wait(for: [serverStarted, connectionReady], timeout: 2.0, enforceOrder: true)
  138. // We can have other transient failures and connection attempts while the server starts, we only
  139. // care about the last two.
  140. XCTAssertEqual(self.stateDelegate.states.suffix(2), [.connecting, .ready])
  141. }
  142. func testClientReconnectsAutomatically() throws {
  143. self.server = self.makeServer()
  144. let server = try self.server.wait()
  145. var configuration = self.makeClientConfiguration()
  146. configuration.connectionBackoff!.maximumBackoff = 2.0
  147. let connectionReady = self.expectation(description: "connection ready")
  148. let transientFailure = self.expectation(description: "connection transientFailure")
  149. self.stateDelegate.expectations[.ready] = connectionReady
  150. self.stateDelegate.expectations[.transientFailure] = transientFailure
  151. self.client = ClientConnection(configuration: configuration)
  152. // Once the connection is ready we can kill the server.
  153. self.wait(for: [connectionReady], timeout: 1.0)
  154. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  155. try server.close().wait()
  156. try self.serverGroup.syncShutdownGracefully()
  157. self.server = nil
  158. self.serverGroup = nil
  159. self.wait(for: [transientFailure], timeout: 1.0)
  160. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .transientFailure])
  161. // Replace the ready expectation (since it's already been fulfilled).
  162. let reconnectionReady = self.expectation(description: "(re)connection ready")
  163. self.stateDelegate.expectations[.ready] = reconnectionReady
  164. let echo = Echo_EchoServiceClient(connection: self.client)
  165. // This should succeed once we get a connection again.
  166. let get = echo.get(.with { $0.text = "hello" })
  167. // Start a new server.
  168. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  169. self.server = self.makeServer()
  170. self.wait(for: [reconnectionReady], timeout: 2.0)
  171. XCTAssertEqual(self.stateDelegate.clearStates(), [.connecting, .ready])
  172. // The call should be able to succeed now.
  173. XCTAssertEqual(try get.status.map { $0.code }.wait(), .ok)
  174. try self.client.close().wait()
  175. XCTAssertEqual(self.stateDelegate.clearStates(), [.shutdown])
  176. }
  177. }