ClientConnectionBackoffTests.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 ClientConnectionBackoffTests: GRPCTestCase {
  24. let port = 8080
  25. var client: ClientConnection!
  26. var server: EventLoopFuture<Server>!
  27. var serverGroup: EventLoopGroup!
  28. var clientGroup: EventLoopGroup!
  29. var connectionStateRecorder = RecordingConnectivityDelegate()
  30. override func setUp() {
  31. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  32. self.clientGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  33. }
  34. override func tearDown() {
  35. // We have additional state changes during tear down, in some cases we can over-fulfill a test
  36. // expectation which causes false negatives.
  37. self.client.connectivity.delegate = nil
  38. if let server = self.server {
  39. XCTAssertNoThrow(try server.flatMap { $0.channel.close() }.wait())
  40. }
  41. XCTAssertNoThrow(try? self.serverGroup.syncShutdownGracefully())
  42. self.server = nil
  43. self.serverGroup = nil
  44. // We don't always expect a client to be closed cleanly, since in some cases we deliberately
  45. // timeout the connection.
  46. try? self.client.close().wait()
  47. XCTAssertNoThrow(try self.clientGroup.syncShutdownGracefully())
  48. self.client = nil
  49. self.clientGroup = nil
  50. }
  51. func makeServer() -> EventLoopFuture<Server> {
  52. return Server.insecure(group: self.serverGroup)
  53. .withServiceProviders([EchoProvider()])
  54. .bind(host: "localhost", port: self.port)
  55. }
  56. func connectionBuilder() -> ClientConnection.Builder {
  57. return ClientConnection.insecure(group: self.clientGroup)
  58. .withConnectivityStateDelegate(self.connectionStateRecorder)
  59. .withConnectionBackoff(maximum: .milliseconds(100))
  60. .withConnectionTimeout(minimum: .milliseconds(100))
  61. }
  62. func testClientConnectionFailsWithNoBackoff() throws {
  63. self.connectionStateRecorder.expectChanges(2) { changes in
  64. XCTAssertEqual(changes, [
  65. Change(from: .idle, to: .connecting),
  66. Change(from: .connecting, to: .shutdown)
  67. ])
  68. }
  69. self.client = self.connectionBuilder()
  70. .withConnectionReestablishment(enabled: false)
  71. .connect(host: "localhost", port: self.port)
  72. // Start an RPC to trigger creating a channel.
  73. let echo = Echo_EchoClient(channel: self.client)
  74. _ = echo.get(.with { $0.text = "foo" })
  75. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  76. }
  77. func testClientConnectionFailureIsLimited() throws {
  78. self.connectionStateRecorder.expectChanges(4) { changes in
  79. XCTAssertEqual(changes, [
  80. Change(from: .idle, to: .connecting),
  81. Change(from: .connecting, to: .transientFailure),
  82. Change(from: .transientFailure, to: .connecting),
  83. Change(from: .connecting, to: .shutdown),
  84. ])
  85. }
  86. self.client = self.connectionBuilder()
  87. .withConnectionBackoff(retries: .upTo(1))
  88. .connect(host: "localhost", port: self.port)
  89. // Start an RPC to trigger creating a channel.
  90. let echo = Echo_EchoClient(channel: self.client)
  91. _ = echo.get(.with { $0.text = "foo" })
  92. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  93. }
  94. func testClientEventuallyConnects() throws {
  95. self.connectionStateRecorder.expectChanges(2) { changes in
  96. XCTAssertEqual(changes, [
  97. Change(from: .idle, to: .connecting),
  98. Change(from: .connecting, to: .transientFailure)
  99. ])
  100. }
  101. // Start the client first.
  102. self.client = self.connectionBuilder()
  103. .connect(host: "localhost", port: self.port)
  104. // Start an RPC to trigger creating a channel.
  105. let echo = Echo_EchoClient(channel: self.client)
  106. _ = echo.get(.with { $0.text = "foo" })
  107. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  108. self.connectionStateRecorder.expectChanges(2) { changes in
  109. XCTAssertEqual(changes, [
  110. Change(from: .transientFailure, to: .connecting),
  111. Change(from: .connecting, to: .ready)
  112. ])
  113. }
  114. self.server = self.makeServer()
  115. let serverStarted = self.expectation(description: "server started")
  116. self.server.assertSuccess(fulfill: serverStarted)
  117. self.wait(for: [serverStarted], timeout: 5.0)
  118. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  119. }
  120. func testClientReconnectsAutomatically() throws {
  121. // Wait for the server to start.
  122. self.server = self.makeServer()
  123. let server = try self.server.wait()
  124. // Prepare the delegate so it expects the connection to hit `.ready`.
  125. self.connectionStateRecorder.expectChanges(2) { changes in
  126. XCTAssertEqual(changes, [
  127. Change(from: .idle, to: .connecting),
  128. Change(from: .connecting, to: .ready)
  129. ])
  130. }
  131. // Configure the client backoff to have a short backoff.
  132. self.client = self.connectionBuilder()
  133. .withConnectionBackoff(maximum: .seconds(2))
  134. .connect(host: "localhost", port: self.port)
  135. // Start an RPC to trigger creating a channel.
  136. let echo = Echo_EchoClient(channel: self.client)
  137. _ = echo.get(.with { $0.text = "foo" })
  138. // Wait for the connection to be ready.
  139. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  140. // Now that we have a healthy connection, prepare for two transient failures:
  141. // 1. when the server has been killed, and
  142. // 2. when the client attempts to reconnect.
  143. self.connectionStateRecorder.expectChanges(3) { changes in
  144. XCTAssertEqual(changes, [
  145. Change(from: .ready, to: .transientFailure),
  146. Change(from: .transientFailure, to: .connecting),
  147. Change(from: .connecting, to: .transientFailure),
  148. ])
  149. }
  150. // Okay, kill the server!
  151. try server.close().wait()
  152. try self.serverGroup.syncShutdownGracefully()
  153. self.server = nil
  154. self.serverGroup = nil
  155. // Our connection should fail now.
  156. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  157. // Get ready for the new healthy connection.
  158. self.connectionStateRecorder.expectChanges(2) { changes in
  159. XCTAssertEqual(changes, [
  160. Change(from: .transientFailure, to: .connecting),
  161. Change(from: .connecting, to: .ready)
  162. ])
  163. }
  164. // This should succeed once we get a connection again.
  165. let get = echo.get(.with { $0.text = "hello" })
  166. // Start a new server.
  167. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  168. self.server = self.makeServer()
  169. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  170. // The call should be able to succeed now.
  171. XCTAssertEqual(try get.status.map { $0.code }.wait(), .ok)
  172. try self.client.close().wait()
  173. }
  174. }