HTTP1ToRawGRPCServerCodecTests.swift 6.8 KB

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