2
0

ServerThrowingTests.swift 9.3 KB

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