2
0

ClientConnectionBackoffTests.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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_EchoNIOClient(
  79. channel: self.client,
  80. defaultCallOptions: self.callOptionsWithLogger
  81. )
  82. _ = echo.get(.with { $0.text = "foo" })
  83. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  84. }
  85. func testClientConnectionFailureIsLimited() throws {
  86. self.connectionStateRecorder.expectChanges(4) { changes in
  87. XCTAssertEqual(changes, [
  88. Change(from: .idle, to: .connecting),
  89. Change(from: .connecting, to: .transientFailure),
  90. Change(from: .transientFailure, to: .connecting),
  91. Change(from: .connecting, to: .shutdown),
  92. ])
  93. }
  94. self.client = self.connectionBuilder()
  95. .withConnectionBackoff(retries: .upTo(1))
  96. .connect(host: "localhost", port: self.port)
  97. // Start an RPC to trigger creating a channel.
  98. let echo = Echo_EchoNIOClient(
  99. channel: self.client,
  100. defaultCallOptions: self.callOptionsWithLogger
  101. )
  102. _ = echo.get(.with { $0.text = "foo" })
  103. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  104. }
  105. func testClientEventuallyConnects() throws {
  106. self.connectionStateRecorder.expectChanges(2) { changes in
  107. XCTAssertEqual(changes, [
  108. Change(from: .idle, to: .connecting),
  109. Change(from: .connecting, to: .transientFailure),
  110. ])
  111. }
  112. // Start the client first.
  113. self.client = self.connectionBuilder()
  114. .connect(host: "localhost", port: self.port)
  115. // Start an RPC to trigger creating a channel.
  116. let echo = Echo_EchoNIOClient(
  117. channel: self.client,
  118. defaultCallOptions: self.callOptionsWithLogger
  119. )
  120. _ = echo.get(.with { $0.text = "foo" })
  121. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  122. self.connectionStateRecorder.expectChanges(2) { changes in
  123. XCTAssertEqual(changes, [
  124. Change(from: .transientFailure, to: .connecting),
  125. Change(from: .connecting, to: .ready),
  126. ])
  127. }
  128. self.server = self.makeServer()
  129. let serverStarted = self.expectation(description: "server started")
  130. self.server.assertSuccess(fulfill: serverStarted)
  131. self.wait(for: [serverStarted], timeout: 5.0)
  132. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  133. }
  134. func testClientReconnectsAutomatically() throws {
  135. // Wait for the server to start.
  136. self.server = self.makeServer()
  137. let server = try self.server.wait()
  138. // Prepare the delegate so it expects the connection to hit `.ready`.
  139. self.connectionStateRecorder.expectChanges(2) { changes in
  140. XCTAssertEqual(changes, [
  141. Change(from: .idle, to: .connecting),
  142. Change(from: .connecting, to: .ready),
  143. ])
  144. }
  145. // Configure the client backoff to have a short backoff.
  146. self.client = self.connectionBuilder()
  147. .withConnectionBackoff(maximum: .seconds(2))
  148. .connect(host: "localhost", port: self.port)
  149. // Start an RPC to trigger creating a channel, it's a streaming RPC so that when the server is
  150. // killed, the client still has one active RPC and transitions to transient failure (rather than
  151. // idle if there were no active RPCs).
  152. let echo = Echo_EchoNIOClient(
  153. channel: self.client,
  154. defaultCallOptions: self.callOptionsWithLogger
  155. )
  156. _ = echo.update { _ in }
  157. // Wait for the connection to be ready.
  158. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  159. // Now that we have a healthy connection, prepare for two transient failures:
  160. // 1. when the server has been killed, and
  161. // 2. when the client attempts to reconnect.
  162. self.connectionStateRecorder.expectChanges(3) { changes in
  163. XCTAssertEqual(changes, [
  164. Change(from: .ready, to: .transientFailure),
  165. Change(from: .transientFailure, to: .connecting),
  166. Change(from: .connecting, to: .transientFailure),
  167. ])
  168. }
  169. // Okay, kill the server!
  170. try server.close().wait()
  171. try self.serverGroup.syncShutdownGracefully()
  172. self.server = nil
  173. self.serverGroup = nil
  174. // Our connection should fail now.
  175. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  176. // Get ready for the new healthy connection.
  177. self.connectionStateRecorder.expectChanges(2) { changes in
  178. XCTAssertEqual(changes, [
  179. Change(from: .transientFailure, to: .connecting),
  180. Change(from: .connecting, to: .ready),
  181. ])
  182. }
  183. // This should succeed once we get a connection again.
  184. let get = echo.get(.with { $0.text = "hello" })
  185. // Start a new server.
  186. self.serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  187. self.server = self.makeServer()
  188. self.connectionStateRecorder.waitForExpectedChanges(timeout: .seconds(5))
  189. // The call should be able to succeed now.
  190. XCTAssertEqual(try get.status.map { $0.code }.wait(), .ok)
  191. try self.client.close().wait()
  192. }
  193. }