ServerThrowingTests.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright 2018, 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 Dispatch
  17. import EchoModel
  18. import Foundation
  19. @testable import GRPC
  20. import NIOCore
  21. import NIOHPACK
  22. import NIOHTTP1
  23. import NIOHTTP2
  24. import XCTest
  25. let thrownError = GRPCStatus(code: .internalError, message: "expected error")
  26. let transformedError = GRPCStatus(code: .aborted, message: "transformed error")
  27. let transformedMetadata = HPACKHeaders([("transformed", "header")])
  28. // Motivation for two different providers: Throwing immediately causes the event observer future (in the
  29. // client-streaming and bidi-streaming cases) to throw immediately, _before_ the corresponding handler has even added
  30. // to the channel. We want to test that case as well as the one where we throw only _after_ the handler has been added
  31. // to the channel.
  32. class ImmediateThrowingEchoProvider: Echo_EchoProvider {
  33. var interceptors: Echo_EchoServerInterceptorFactoryProtocol? { return nil }
  34. func get(
  35. request: Echo_EchoRequest,
  36. context: StatusOnlyCallContext
  37. ) -> EventLoopFuture<Echo_EchoResponse> {
  38. return context.eventLoop.makeFailedFuture(thrownError)
  39. }
  40. func expand(
  41. request: Echo_EchoRequest,
  42. context: StreamingResponseCallContext<Echo_EchoResponse>
  43. ) -> EventLoopFuture<GRPCStatus> {
  44. return context.eventLoop.makeFailedFuture(thrownError)
  45. }
  46. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  47. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  48. return context.eventLoop.makeFailedFuture(thrownError)
  49. }
  50. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  51. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  52. return context.eventLoop.makeFailedFuture(thrownError)
  53. }
  54. }
  55. extension EventLoop {
  56. func makeFailedFuture<T>(_ error: Error, delay: TimeInterval) -> EventLoopFuture<T> {
  57. return self.scheduleTask(in: .nanoseconds(Int64(delay * 1000 * 1000 * 1000))) { () }
  58. .futureResult
  59. .flatMapThrowing { _ -> T in throw error }
  60. }
  61. }
  62. /// See `ImmediateThrowingEchoProvider`.
  63. class DelayedThrowingEchoProvider: Echo_EchoProvider {
  64. let interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil
  65. func get(
  66. request: Echo_EchoRequest,
  67. context: StatusOnlyCallContext
  68. ) -> EventLoopFuture<Echo_EchoResponse> {
  69. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  70. }
  71. func expand(
  72. request: Echo_EchoRequest,
  73. context: StreamingResponseCallContext<Echo_EchoResponse>
  74. ) -> EventLoopFuture<GRPCStatus> {
  75. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  76. }
  77. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  78. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  79. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  80. }
  81. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  82. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  83. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  84. }
  85. }
  86. /// Ensures that fulfilling the status promise (where possible) with an error yields the same result as failing the future.
  87. class ErrorReturningEchoProvider: ImmediateThrowingEchoProvider {
  88. // There's no status promise to fulfill for unary calls (only the response promise), so that case is omitted.
  89. override func expand(
  90. request: Echo_EchoRequest,
  91. context: StreamingResponseCallContext<Echo_EchoResponse>
  92. ) -> EventLoopFuture<GRPCStatus> {
  93. return context.eventLoop.makeSucceededFuture(thrownError)
  94. }
  95. override func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  96. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  97. return context.eventLoop.makeSucceededFuture({ _ in
  98. context.responseStatus = thrownError
  99. context.responsePromise.succeed(Echo_EchoResponse())
  100. })
  101. }
  102. override func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  103. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  104. return context.eventLoop.makeSucceededFuture({ _ in
  105. context.statusPromise.succeed(thrownError)
  106. })
  107. }
  108. }
  109. private class ErrorTransformingDelegate: ServerErrorDelegate {
  110. func transformRequestHandlerError(
  111. _ error: Error,
  112. headers: HPACKHeaders
  113. ) -> GRPCStatusAndTrailers? {
  114. return GRPCStatusAndTrailers(status: transformedError, trailers: transformedMetadata)
  115. }
  116. }
  117. class ServerThrowingTests: EchoTestCaseBase {
  118. var expectedError: GRPCStatus { return thrownError }
  119. var expectedMetadata: HPACKHeaders? {
  120. return HPACKHeaders([("grpc-status", "13"), ("grpc-message", "expected error")])
  121. }
  122. override func makeEchoProvider() -> Echo_EchoProvider { return ImmediateThrowingEchoProvider() }
  123. func testUnary() throws {
  124. let call = client.get(Echo_EchoRequest(text: "foo"))
  125. XCTAssertEqual(self.expectedError, try call.status.wait())
  126. let trailers = try call.trailingMetadata.wait()
  127. if let expected = self.expectedMetadata {
  128. for (name, value, _) in expected {
  129. XCTAssertTrue(trailers[name].contains(value))
  130. }
  131. }
  132. XCTAssertThrowsError(try call.response.wait()) {
  133. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  134. }
  135. }
  136. func testClientStreaming() throws {
  137. let call = client.collect()
  138. // This is racing with the server error; it might fail, it might not.
  139. try? call.sendEnd().wait()
  140. XCTAssertEqual(self.expectedError, try call.status.wait())
  141. let trailers = try call.trailingMetadata.wait()
  142. if let expected = self.expectedMetadata {
  143. for (name, value, _) in expected {
  144. XCTAssertTrue(trailers[name].contains(value))
  145. }
  146. }
  147. if type(of: self.makeEchoProvider()) != ErrorReturningEchoProvider.self {
  148. // With `ErrorReturningEchoProvider` we actually _return_ a response, which means that the `response` future
  149. // will _not_ fail, so in that case this test doesn't apply.
  150. XCTAssertThrowsError(try call.response.wait()) {
  151. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  152. }
  153. }
  154. }
  155. func testServerStreaming() throws {
  156. let call = client
  157. .expand(Echo_EchoRequest(text: "foo")) { XCTFail("no message expected, got \($0)") }
  158. // Nothing to throw here, but the `status` should be the expected error.
  159. XCTAssertEqual(self.expectedError, try call.status.wait())
  160. let trailers = try call.trailingMetadata.wait()
  161. if let expected = self.expectedMetadata {
  162. for (name, value, _) in expected {
  163. XCTAssertTrue(trailers[name].contains(value))
  164. }
  165. }
  166. }
  167. func testBidirectionalStreaming() throws {
  168. let call = client.update { XCTFail("no message expected, got \($0)") }
  169. // This is racing with the server error; it might fail, it might not.
  170. try? call.sendEnd().wait()
  171. // Nothing to throw here, but the `status` should be the expected error.
  172. XCTAssertEqual(self.expectedError, try call.status.wait())
  173. let trailers = try call.trailingMetadata.wait()
  174. if let expected = self.expectedMetadata {
  175. for (name, value, _) in expected {
  176. XCTAssertTrue(trailers[name].contains(value))
  177. }
  178. }
  179. }
  180. }
  181. class ServerDelayedThrowingTests: ServerThrowingTests {
  182. override func makeEchoProvider() -> Echo_EchoProvider { return DelayedThrowingEchoProvider() }
  183. override func testUnary() throws {
  184. try super.testUnary()
  185. }
  186. override func testClientStreaming() throws {
  187. try super.testClientStreaming()
  188. }
  189. override func testServerStreaming() throws {
  190. try super.testServerStreaming()
  191. }
  192. override func testBidirectionalStreaming() throws {
  193. try super.testBidirectionalStreaming()
  194. }
  195. }
  196. class ClientThrowingWhenServerReturningErrorTests: ServerThrowingTests {
  197. override func makeEchoProvider() -> Echo_EchoProvider { return ErrorReturningEchoProvider() }
  198. override func testUnary() throws {
  199. try super.testUnary()
  200. }
  201. override func testClientStreaming() throws {
  202. try super.testClientStreaming()
  203. }
  204. override func testServerStreaming() throws {
  205. try super.testServerStreaming()
  206. }
  207. override func testBidirectionalStreaming() throws {
  208. try super.testBidirectionalStreaming()
  209. }
  210. }
  211. class ServerErrorTransformingTests: ServerThrowingTests {
  212. override var expectedError: GRPCStatus { return transformedError }
  213. override var expectedMetadata: HPACKHeaders? {
  214. return HPACKHeaders([("grpc-status", "10"), ("grpc-message", "transformed error"),
  215. ("transformed", "header")])
  216. }
  217. override func makeErrorDelegate() -> ServerErrorDelegate? { return ErrorTransformingDelegate() }
  218. override func testUnary() throws {
  219. try super.testUnary()
  220. }
  221. override func testClientStreaming() throws {
  222. try super.testClientStreaming()
  223. }
  224. override func testServerStreaming() throws {
  225. try super.testServerStreaming()
  226. }
  227. override func testBidirectionalStreaming() throws {
  228. try super.testBidirectionalStreaming()
  229. }
  230. }