ClientTimeoutTests.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 EchoModel
  17. import Foundation
  18. import Logging
  19. import NIOCore
  20. import NIOEmbedded
  21. import NIOHTTP2
  22. import SwiftProtobuf
  23. import XCTest
  24. @testable import GRPC
  25. class ClientTimeoutTests: GRPCTestCase {
  26. var channel: EmbeddedChannel!
  27. var client: Echo_EchoNIOClient!
  28. let timeout = TimeAmount.milliseconds(100)
  29. var callOptions: CallOptions {
  30. // We use a deadline here because internally we convert timeouts into deadlines by diffing
  31. // with `DispatchTime.now()`. We therefore need the deadline to be known in advance. Note we
  32. // use zero because `EmbeddedEventLoop`s time starts at zero.
  33. var options = self.callOptionsWithLogger
  34. options.timeLimit = .deadline(.uptimeNanoseconds(0) + self.timeout)
  35. return options
  36. }
  37. // Note: this is not related to the call timeout since we're using an EmbeddedChannel. We require
  38. // this in case the timeout doesn't work.
  39. let testTimeout: TimeInterval = 0.1
  40. override func setUp() {
  41. super.setUp()
  42. let connection = EmbeddedGRPCChannel(logger: self.clientLogger)
  43. XCTAssertNoThrow(
  44. try connection.embeddedChannel
  45. .connect(to: SocketAddress(unixDomainSocketPath: "/foo"))
  46. )
  47. let client = Echo_EchoNIOClient(channel: connection, defaultCallOptions: self.callOptions)
  48. self.channel = connection.embeddedChannel
  49. self.client = client
  50. }
  51. override func tearDown() {
  52. XCTAssertNoThrow(try self.channel.finish())
  53. super.tearDown()
  54. }
  55. func assertRPCTimedOut(
  56. _ response: EventLoopFuture<Echo_EchoResponse>,
  57. expectation: XCTestExpectation
  58. ) {
  59. response.whenComplete { result in
  60. switch result {
  61. case let .success(response):
  62. XCTFail("unexpected response: \(response)")
  63. case let .failure(error):
  64. XCTAssertTrue(error is GRPCError.RPCTimedOut)
  65. }
  66. expectation.fulfill()
  67. }
  68. }
  69. func assertDeadlineExceeded(
  70. _ status: EventLoopFuture<GRPCStatus>,
  71. expectation: XCTestExpectation
  72. ) {
  73. status.whenComplete { result in
  74. switch result {
  75. case let .success(status):
  76. XCTAssertEqual(status.code, .deadlineExceeded)
  77. case let .failure(error):
  78. XCTFail("unexpected error: \(error)")
  79. }
  80. expectation.fulfill()
  81. }
  82. }
  83. func testUnaryTimeoutAfterSending() throws {
  84. let statusExpectation = self.expectation(description: "status fulfilled")
  85. let call = self.client.get(Echo_EchoRequest(text: "foo"))
  86. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  87. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  88. self.wait(for: [statusExpectation], timeout: self.testTimeout)
  89. }
  90. func testServerStreamingTimeoutAfterSending() throws {
  91. let statusExpectation = self.expectation(description: "status fulfilled")
  92. let call = self.client.expand(Echo_EchoRequest(text: "foo bar baz")) { _ in }
  93. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  94. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  95. self.wait(for: [statusExpectation], timeout: self.testTimeout)
  96. }
  97. func testClientStreamingTimeoutBeforeSending() throws {
  98. let responseExpectation = self.expectation(description: "response fulfilled")
  99. let statusExpectation = self.expectation(description: "status fulfilled")
  100. let call = self.client.collect()
  101. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  102. self.assertRPCTimedOut(call.response, expectation: responseExpectation)
  103. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  104. self.wait(for: [responseExpectation, statusExpectation], timeout: self.testTimeout)
  105. }
  106. func testClientStreamingTimeoutAfterSending() throws {
  107. let responseExpectation = self.expectation(description: "response fulfilled")
  108. let statusExpectation = self.expectation(description: "status fulfilled")
  109. let call = self.client.collect()
  110. self.assertRPCTimedOut(call.response, expectation: responseExpectation)
  111. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  112. call.sendMessage(Echo_EchoRequest(text: "foo"), promise: nil)
  113. call.sendEnd(promise: nil)
  114. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  115. self.wait(for: [responseExpectation, statusExpectation], timeout: 1.0)
  116. }
  117. func testBidirectionalStreamingTimeoutBeforeSending() {
  118. let statusExpectation = self.expectation(description: "status fulfilled")
  119. let call = self.client.update { _ in }
  120. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  121. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  122. self.wait(for: [statusExpectation], timeout: self.testTimeout)
  123. }
  124. func testBidirectionalStreamingTimeoutAfterSending() {
  125. let statusExpectation = self.expectation(description: "status fulfilled")
  126. let call = self.client.update { _ in }
  127. self.assertDeadlineExceeded(call.status, expectation: statusExpectation)
  128. call.sendMessage(Echo_EchoRequest(text: "foo"), promise: nil)
  129. call.sendEnd(promise: nil)
  130. self.channel.embeddedEventLoop.advanceTime(by: self.timeout)
  131. self.wait(for: [statusExpectation], timeout: self.testTimeout)
  132. }
  133. }
  134. // Unchecked as it uses an 'EmbeddedChannel'.
  135. extension EmbeddedGRPCChannel: @unchecked Sendable {}
  136. private final class EmbeddedGRPCChannel: GRPCChannel {
  137. let embeddedChannel: EmbeddedChannel
  138. let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  139. let logger: Logger
  140. let scheme: String
  141. let authority: String
  142. let errorDelegate: ClientErrorDelegate?
  143. func close() -> EventLoopFuture<Void> {
  144. return self.embeddedChannel.close()
  145. }
  146. var eventLoop: EventLoop {
  147. return self.embeddedChannel.eventLoop
  148. }
  149. init(
  150. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  151. errorDelegate: ClientErrorDelegate? = nil
  152. ) {
  153. let embeddedChannel = EmbeddedChannel()
  154. self.embeddedChannel = embeddedChannel
  155. self.logger = logger
  156. self.multiplexer = embeddedChannel.configureGRPCClient(
  157. errorDelegate: errorDelegate,
  158. logger: logger
  159. ).flatMap {
  160. embeddedChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  161. }
  162. self.scheme = "http"
  163. self.authority = "localhost"
  164. self.errorDelegate = errorDelegate
  165. }
  166. internal func makeCall<Request: Message, Response: Message>(
  167. path: String,
  168. type: GRPCCallType,
  169. callOptions: CallOptions,
  170. interceptors: [ClientInterceptor<Request, Response>]
  171. ) -> Call<Request, Response> {
  172. return Call(
  173. path: path,
  174. type: type,
  175. eventLoop: self.eventLoop,
  176. options: callOptions,
  177. interceptors: interceptors,
  178. transportFactory: .http2(
  179. channel: self.makeStreamChannel(),
  180. authority: self.authority,
  181. scheme: self.scheme,
  182. // This is internal and only for testing, so max is fine here.
  183. maximumReceiveMessageLength: .max,
  184. errorDelegate: self.errorDelegate
  185. )
  186. )
  187. }
  188. internal func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  189. path: String,
  190. type: GRPCCallType,
  191. callOptions: CallOptions,
  192. interceptors: [ClientInterceptor<Request, Response>]
  193. ) -> Call<Request, Response> {
  194. return Call(
  195. path: path,
  196. type: type,
  197. eventLoop: self.eventLoop,
  198. options: callOptions,
  199. interceptors: interceptors,
  200. transportFactory: .http2(
  201. channel: self.makeStreamChannel(),
  202. authority: self.authority,
  203. scheme: self.scheme,
  204. // This is internal and only for testing, so max is fine here.
  205. maximumReceiveMessageLength: .max,
  206. errorDelegate: self.errorDelegate
  207. )
  208. )
  209. }
  210. private func makeStreamChannel() -> EventLoopFuture<Channel> {
  211. let promise = self.eventLoop.makePromise(of: Channel.self)
  212. self.multiplexer.whenSuccess {
  213. $0.createStreamChannel(promise: promise) {
  214. $0.eventLoop.makeSucceededVoidFuture()
  215. }
  216. }
  217. return promise.futureResult
  218. }
  219. }