HTTP1ToRawGRPCServerCodecTests.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 = GRPCError.CompressionUnsupported()
  41. XCTAssertEqual(expectedError, errorCollector.errors.first as? GRPCError.CompressionUnsupported)
  42. responses[0].assertHeaders()
  43. responses[1].assertStatus { status in
  44. XCTAssertEqual(status, expectedError.makeGRPCStatus())
  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 = GRPCError.DeserializationFailure()
  78. XCTAssertEqual(expectedError, errorCollector.errors.first as? GRPCError.DeserializationFailure)
  79. responses[0].assertHeaders()
  80. responses[1].assertStatus { status in
  81. XCTAssertEqual(status, expectedError.makeGRPCStatus())
  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. let expected = GRPCError.InvalidState("unexpected trailers received")
  98. XCTAssertEqual(expected, errorCollector.errors.first as? GRPCError.InvalidState)
  99. responses[0].assertHeaders()
  100. responses[1].assertStatus { status in
  101. XCTAssertEqual(status, expected.makeGRPCStatus())
  102. }
  103. }
  104. func testOnlyOneStatusIsReturned() throws {
  105. let responses = try waitForGRPCChannelHandlerResponses(count: 3) { channel in
  106. let requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/echo.Echo/Get")
  107. try channel.writeInbound(HTTPServerRequestPart.head(requestHead))
  108. try channel.writeInbound(HTTPServerRequestPart.body(gRPCMessage(channel: channel)))
  109. // Sending trailers with `.end` should trigger an error. However, writing a message to a unary call
  110. // will trigger a response and status to be sent back. Since we're using `EmbeddedChannel` this will
  111. // be done before the trailers are sent. If a 4th response were to be sent (for the error status) then
  112. // the test would fail.
  113. var trailers = HTTPHeaders()
  114. trailers.add(name: "foo", value: "bar")
  115. try channel.writeInbound(HTTPServerRequestPart.end(trailers))
  116. }
  117. responses[0].assertHeaders()
  118. responses[1].assertMessage()
  119. responses[2].assertStatus { status in
  120. XCTAssertEqual(status, .ok)
  121. }
  122. }
  123. override func waitForGRPCChannelHandlerResponses(
  124. count: Int,
  125. servicesByName: [String: CallHandlerProvider] = GRPCChannelHandlerResponseCapturingTestCase.echoProvider,
  126. callback: @escaping (EmbeddedChannel) throws -> Void
  127. ) throws -> [_RawGRPCServerResponsePart] {
  128. return try super.waitForGRPCChannelHandlerResponses(count: count, servicesByName: servicesByName) { channel in
  129. _ = channel.pipeline.addHandlers(HTTP1ToRawGRPCServerCodec(logger: Logger(label: "io.grpc.testing")), position: .first)
  130. .flatMapThrowing { _ in try callback(channel) }
  131. }
  132. }
  133. }