HTTP1ToRawGRPCServerCodecTests.swift 6.8 KB

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