HTTP1ToRawGRPCServerCodecTests.swift 6.8 KB

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