2
0

ClientConnectionBackoffTests.swift 7.7 KB

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