HTTP1ToRawGRPCServerCodecTests.swift 6.8 KB

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