HTTP1ToRawGRPCServerCodecTests.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import Foundation
  2. import XCTest
  3. import NIO
  4. import NIOHTTP1
  5. @testable import GRPC
  6. func gRPCMessage(channel: EmbeddedChannel, compression: Bool = false, message: Data? = nil) -> ByteBuffer {
  7. let messageLength = message?.count ?? 0
  8. var buffer = channel.allocator.buffer(capacity: 5 + messageLength)
  9. buffer.writeInteger(Int8(compression ? 1 : 0))
  10. buffer.writeInteger(UInt32(messageLength))
  11. if let bytes = message {
  12. buffer.writeBytes(bytes)
  13. }
  14. return buffer
  15. }
  16. class HTTP1ToRawGRPCServerCodecTests: GRPCChannelHandlerResponseCapturingTestCase {
  17. func testInternalErrorStatusReturnedWhenCompressionFlagIsSet() throws {
  18. let responses = try waitForGRPCChannelHandlerResponses(count: 2) { channel in
  19. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Get")
  20. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  21. try channel.writeInbound(HTTPServerRequestPart.body(gRPCMessage(channel: channel, compression: true)))
  22. }
  23. let expectedError = GRPCCommonError.unexpectedCompression
  24. XCTAssertEqual([expectedError], errorCollector.asGRPCCommonErrors)
  25. responses[0].assertHeaders()
  26. responses[1].assertStatus { status in
  27. assertEqualStatusIgnoringTrailers(status, expectedError.asGRPCStatus())
  28. }
  29. }
  30. func testMessageCanBeSentAcrossMultipleByteBuffers() throws {
  31. let responses = try waitForGRPCChannelHandlerResponses(count: 3) { channel in
  32. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Get")
  33. // Sending the header allocates a buffer.
  34. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  35. let request = Echo_EchoRequest.with { $0.text = "echo!" }
  36. let requestAsData = try request.serializedData()
  37. var buffer = channel.allocator.buffer(capacity: 1)
  38. buffer.writeInteger(Int8(0))
  39. try channel.writeInbound(HTTPServerRequestPart.body(buffer))
  40. buffer = channel.allocator.buffer(capacity: 4)
  41. buffer.writeInteger(Int32(requestAsData.count))
  42. try channel.writeInbound(HTTPServerRequestPart.body(buffer))
  43. buffer = channel.allocator.buffer(capacity: requestAsData.count)
  44. buffer.writeBytes(requestAsData)
  45. try channel.writeInbound(HTTPServerRequestPart.body(buffer))
  46. }
  47. responses[0].assertHeaders()
  48. responses[1].assertMessage()
  49. responses[2].assertStatus { status in
  50. assertEqualStatusIgnoringTrailers(status, .ok)
  51. }
  52. }
  53. func testInternalErrorStatusIsReturnedIfMessageCannotBeDeserialized() throws {
  54. let responses = try waitForGRPCChannelHandlerResponses(count: 2) { channel in
  55. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Get")
  56. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  57. let buffer = gRPCMessage(channel: channel, message: Data([42]))
  58. try channel.writeInbound(HTTPServerRequestPart.body(buffer))
  59. }
  60. let expectedError = GRPCServerError.requestProtoDeserializationFailure
  61. XCTAssertEqual([expectedError], errorCollector.asGRPCServerErrors)
  62. responses[0].assertHeaders()
  63. responses[1].assertStatus { status in
  64. assertEqualStatusIgnoringTrailers(status, expectedError.asGRPCStatus())
  65. }
  66. }
  67. func testInternalErrorStatusIsReturnedWhenSendingTrailersInRequest() throws {
  68. let responses = try waitForGRPCChannelHandlerResponses(count: 2) { channel in
  69. // We have to use "Collect" (client streaming) as the tests rely on `EmbeddedChannel` which runs in this thread.
  70. // In the current server implementation, responses from unary calls send a status immediately after sending the response.
  71. // As such, a unary "Get" would return an "ok" status before the trailers would be sent.
  72. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Collect")
  73. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  74. try channel.writeInbound(HTTPServerRequestPart.body(gRPCMessage(channel: channel)))
  75. var trailers = HTTPHeaders()
  76. trailers.add(name: "foo", value: "bar")
  77. try channel.writeInbound(HTTPServerRequestPart.end(trailers))
  78. }
  79. XCTAssertEqual(errorCollector.errors.count, 1)
  80. if case .some(.invalidState(let message)) = errorCollector.asGRPCCommonErrors?.first {
  81. XCTAssert(message.contains("trailers"))
  82. } else {
  83. XCTFail("\(String(describing: errorCollector.errors.first)) was not .invalidState")
  84. }
  85. responses[0].assertHeaders()
  86. responses[1].assertStatus { status in
  87. assertEqualStatusIgnoringTrailers(status, .processingError)
  88. }
  89. }
  90. func testOnlyOneStatusIsReturned() throws {
  91. let responses = try waitForGRPCChannelHandlerResponses(count: 3) { channel in
  92. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Get")
  93. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  94. try channel.writeInbound(HTTPServerRequestPart.body(gRPCMessage(channel: channel)))
  95. // Sending trailers with `.end` should trigger an error. However, writing a message to a unary call
  96. // will trigger a response and status to be sent back. Since we're using `EmbeddedChannel` this will
  97. // be done before the trailers are sent. If a 4th resposne were to be sent (for the error status) then
  98. // the test would fail.
  99. var trailers = HTTPHeaders()
  100. trailers.add(name: "foo", value: "bar")
  101. try channel.writeInbound(HTTPServerRequestPart.end(trailers))
  102. }
  103. responses[0].assertHeaders()
  104. responses[1].assertMessage()
  105. responses[2].assertStatus { status in
  106. assertEqualStatusIgnoringTrailers(status, .ok)
  107. }
  108. }
  109. override func waitForGRPCChannelHandlerResponses(
  110. count: Int,
  111. servicesByName: [String: CallHandlerProvider] = GRPCChannelHandlerResponseCapturingTestCase.echoProvider,
  112. callback: @escaping (EmbeddedChannel) throws -> Void
  113. ) throws -> [RawGRPCServerResponsePart] {
  114. return try super.waitForGRPCChannelHandlerResponses(count: count, servicesByName: servicesByName) { channel in
  115. _ = channel.pipeline.addHandlers(HTTP1ToRawGRPCServerCodec(), position: .first)
  116. .flatMapThrowing { _ in try callback(channel) }
  117. }
  118. }
  119. }