ClientTimeoutTests.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. @testable import GRPC
  19. import Logging
  20. import NIOCore
  21. import NIOEmbedded
  22. import NIOHTTP2
  23. import SwiftProtobuf
  24. import XCTest
  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<NIOHTTP2Handler.StreamMultiplexer>
  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: NIOHTTP2Handler.self)
  161. }.flatMap { h2Handler in
  162. h2Handler.multiplexer
  163. }
  164. self.scheme = "http"
  165. self.authority = "localhost"
  166. self.errorDelegate = errorDelegate
  167. }
  168. internal func makeCall<Request: Message, Response: Message>(
  169. path: String,
  170. type: GRPCCallType,
  171. callOptions: CallOptions,
  172. interceptors: [ClientInterceptor<Request, Response>]
  173. ) -> Call<Request, Response> {
  174. return Call(
  175. path: path,
  176. type: type,
  177. eventLoop: self.eventLoop,
  178. options: callOptions,
  179. interceptors: interceptors,
  180. transportFactory: .http2(
  181. channel: self.makeStreamChannel(),
  182. authority: self.authority,
  183. scheme: self.scheme,
  184. // This is internal and only for testing, so max is fine here.
  185. maximumReceiveMessageLength: .max,
  186. errorDelegate: self.errorDelegate
  187. )
  188. )
  189. }
  190. internal func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  191. path: String,
  192. type: GRPCCallType,
  193. callOptions: CallOptions,
  194. interceptors: [ClientInterceptor<Request, Response>]
  195. ) -> Call<Request, Response> {
  196. return Call(
  197. path: path,
  198. type: type,
  199. eventLoop: self.eventLoop,
  200. options: callOptions,
  201. interceptors: interceptors,
  202. transportFactory: .http2(
  203. channel: self.makeStreamChannel(),
  204. authority: self.authority,
  205. scheme: self.scheme,
  206. // This is internal and only for testing, so max is fine here.
  207. maximumReceiveMessageLength: .max,
  208. errorDelegate: self.errorDelegate
  209. )
  210. )
  211. }
  212. private func makeStreamChannel() -> EventLoopFuture<Channel> {
  213. let promise = self.eventLoop.makePromise(of: Channel.self)
  214. self.multiplexer.whenSuccess {
  215. $0.createStreamChannel(promise: promise) {
  216. $0.eventLoop.makeSucceededVoidFuture()
  217. }
  218. }
  219. return promise.futureResult
  220. }
  221. }