HTTP1ToRawGRPCServerCodec.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 NIO
  18. import NIOHTTP1
  19. import NIOFoundationCompat
  20. /// Incoming gRPC package with an unknown message type (represented by a byte buffer).
  21. public enum RawGRPCServerRequestPart {
  22. case head(HTTPRequestHead)
  23. case message(ByteBuffer)
  24. case end
  25. }
  26. /// Outgoing gRPC package with an unknown message type (represented by `Data`).
  27. public enum RawGRPCServerResponsePart {
  28. case headers(HTTPHeaders)
  29. case message(Data)
  30. case status(GRPCStatus)
  31. }
  32. /// A simple channel handler that translates HTTP1 data types into gRPC packets, and vice versa.
  33. ///
  34. /// This codec allows us to use the "raw" gRPC protocol on a low level, with further handlers operationg the protocol
  35. /// on a "higher" level.
  36. ///
  37. /// We use HTTP1 (instead of HTTP2) primitives, as these are easier to work with than raw HTTP2
  38. /// primitives while providing all the functionality we need. In addition, this should make implementing gRPC-over-HTTP1
  39. /// (sometimes also called pPRC) easier in the future.
  40. ///
  41. /// The translation from HTTP2 to HTTP1 is done by `HTTP2ToHTTP1ServerCodec`.
  42. public final class HTTP1ToRawGRPCServerCodec {
  43. public init() {}
  44. // 1-byte for compression flag, 4-bytes for message length.
  45. private let protobufMetadataSize = 5
  46. private var contentType: ContentType?
  47. // The following buffers use force unwrapping explicitly. With optionals, developers
  48. // are encouraged to unwrap them using guard-else statements. These don't work cleanly
  49. // with structs, since the guard-else would create a new copy of the struct, which
  50. // would then have to be re-assigned into the class variable for the changes to take effect.
  51. // By force unwrapping, we avoid those reassignments, and the code is a bit cleaner.
  52. // Buffer to store binary encoded protos as they're being received if the proto is split across
  53. // multiple buffers.
  54. private var binaryRequestBuffer: NIO.ByteBuffer!
  55. // Buffers to store text encoded protos. Only used when content-type is application/grpc-web-text.
  56. // TODO(kaipi): Extract all gRPC Web processing logic into an independent handler only added on
  57. // the HTTP1.1 pipeline, as it's starting to get in the way of readability.
  58. private var requestTextBuffer: NIO.ByteBuffer!
  59. private var responseTextBuffer: NIO.ByteBuffer!
  60. var inboundState = InboundState.expectingHeaders
  61. var outboundState = OutboundState.expectingHeaders
  62. var messageWriter = LengthPrefixedMessageWriter()
  63. var messageReader = LengthPrefixedMessageReader(mode: .server, compressionMechanism: .none)
  64. }
  65. extension HTTP1ToRawGRPCServerCodec {
  66. /// Expected content types for incoming requests.
  67. private enum ContentType: String {
  68. /// Binary encoded gRPC request.
  69. case binary = "application/grpc"
  70. /// Base64 encoded gRPC-Web request.
  71. case text = "application/grpc-web-text"
  72. /// Binary encoded gRPC-Web request.
  73. case web = "application/grpc-web"
  74. }
  75. enum InboundState {
  76. case expectingHeaders
  77. case expectingBody
  78. // ignore any additional messages; e.g. we've seen .end or we've sent an error and are waiting for the stream to close.
  79. case ignore
  80. }
  81. enum OutboundState {
  82. case expectingHeaders
  83. case expectingBodyOrStatus
  84. case ignore
  85. }
  86. }
  87. extension HTTP1ToRawGRPCServerCodec: ChannelInboundHandler {
  88. public typealias InboundIn = HTTPServerRequestPart
  89. public typealias InboundOut = RawGRPCServerRequestPart
  90. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  91. if case .ignore = inboundState { return }
  92. do {
  93. switch self.unwrapInboundIn(data) {
  94. case .head(let requestHead):
  95. inboundState = try processHead(context: context, requestHead: requestHead)
  96. case .body(var body):
  97. inboundState = try processBody(context: context, body: &body)
  98. case .end(let trailers):
  99. inboundState = try processEnd(context: context, trailers: trailers)
  100. }
  101. } catch {
  102. context.fireErrorCaught(error)
  103. inboundState = .ignore
  104. }
  105. }
  106. func processHead(context: ChannelHandlerContext, requestHead: HTTPRequestHead) throws -> InboundState {
  107. guard case .expectingHeaders = inboundState else {
  108. throw GRPCError.server(.invalidState("expecteded state .expectingHeaders, got \(inboundState)"))
  109. }
  110. if let contentTypeHeader = requestHead.headers["content-type"].first {
  111. contentType = ContentType(rawValue: contentTypeHeader)
  112. } else {
  113. // If the Content-Type is not present, assume the request is binary encoded gRPC.
  114. contentType = .binary
  115. }
  116. if contentType == .text {
  117. requestTextBuffer = context.channel.allocator.buffer(capacity: 0)
  118. }
  119. context.fireChannelRead(self.wrapInboundOut(.head(requestHead)))
  120. return .expectingBody
  121. }
  122. func processBody(context: ChannelHandlerContext, body: inout ByteBuffer) throws -> InboundState {
  123. guard case .expectingBody = inboundState else {
  124. throw GRPCError.server(.invalidState("expecteded state .expectingBody, got \(inboundState)"))
  125. }
  126. // If the contentType is text, then decode the incoming bytes as base64 encoded, and append
  127. // it to the binary buffer. If the request is chunked, this section will process the text
  128. // in the biggest chunk that is multiple of 4, leaving the unread bytes in the textBuffer
  129. // where it will expect a new incoming chunk.
  130. if contentType == .text {
  131. precondition(requestTextBuffer != nil)
  132. requestTextBuffer.writeBuffer(&body)
  133. // Read in chunks of 4 bytes as base64 encoded strings will always be multiples of 4.
  134. let readyBytes = requestTextBuffer.readableBytes - (requestTextBuffer.readableBytes % 4)
  135. guard let base64Encoded = requestTextBuffer.readString(length: readyBytes),
  136. let decodedData = Data(base64Encoded: base64Encoded) else {
  137. throw GRPCError.server(.base64DecodeError)
  138. }
  139. body.writeBytes(decodedData)
  140. }
  141. self.messageReader.append(buffer: &body)
  142. while let message = try self.messageReader.nextMessage() {
  143. context.fireChannelRead(self.wrapInboundOut(.message(message)))
  144. }
  145. return .expectingBody
  146. }
  147. private func processEnd(context: ChannelHandlerContext, trailers: HTTPHeaders?) throws -> InboundState {
  148. if let trailers = trailers {
  149. throw GRPCError.server(.invalidState("unexpected trailers received \(trailers)"))
  150. }
  151. context.fireChannelRead(self.wrapInboundOut(.end))
  152. return .ignore
  153. }
  154. }
  155. extension HTTP1ToRawGRPCServerCodec: ChannelOutboundHandler {
  156. public typealias OutboundIn = RawGRPCServerResponsePart
  157. public typealias OutboundOut = HTTPServerResponsePart
  158. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  159. if case .ignore = outboundState { return }
  160. switch self.unwrapOutboundIn(data) {
  161. case .headers(var headers):
  162. guard case .expectingHeaders = outboundState else { return }
  163. var version = HTTPVersion(major: 2, minor: 0)
  164. if let contentType = contentType {
  165. headers.add(name: "content-type", value: contentType.rawValue)
  166. if contentType != .binary {
  167. version = .init(major: 1, minor: 1)
  168. }
  169. }
  170. if contentType == .text {
  171. responseTextBuffer = context.channel.allocator.buffer(capacity: 0)
  172. }
  173. context.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: version, status: .ok, headers: headers))), promise: promise)
  174. outboundState = .expectingBodyOrStatus
  175. case .message(let messageBytes):
  176. guard case .expectingBodyOrStatus = outboundState else { return }
  177. if contentType == .text {
  178. precondition(self.responseTextBuffer != nil)
  179. // Store the response into an independent buffer. We can't return the message directly as
  180. // it needs to be aggregated with all the responses plus the trailers, in order to have
  181. // the base64 response properly encoded in a single byte stream.
  182. messageWriter.write(messageBytes, into: &self.responseTextBuffer, usingCompression: .none)
  183. // Since we stored the written data, mark the write promise as successful so that the
  184. // ServerStreaming provider continues sending the data.
  185. promise?.succeed(())
  186. } else {
  187. var responseBuffer = context.channel.allocator.buffer(capacity: LengthPrefixedMessageWriter.metadataLength)
  188. messageWriter.write(messageBytes, into: &responseBuffer, usingCompression: .none)
  189. context.write(self.wrapOutboundOut(.body(.byteBuffer(responseBuffer))), promise: promise)
  190. }
  191. outboundState = .expectingBodyOrStatus
  192. case .status(let status):
  193. // If we error before sending the initial headers (e.g. unimplemented method) then we won't have sent the request head.
  194. // NIOHTTP2 doesn't support sending a single frame as a "Trailers-Only" response so we still need to loop back and
  195. // send the request head first.
  196. if case .expectingHeaders = outboundState {
  197. self.write(context: context, data: NIOAny(RawGRPCServerResponsePart.headers(HTTPHeaders())), promise: nil)
  198. }
  199. var trailers = status.trailingMetadata
  200. trailers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  201. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  202. trailers.add(name: GRPCHeaderName.statusMessage, value: message)
  203. }
  204. if contentType == .text {
  205. precondition(responseTextBuffer != nil)
  206. // Encode the trailers into the response byte stream as a length delimited message, as per
  207. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
  208. let textTrailers = trailers.map { name, value in "\(name): \(value)" }.joined(separator: "\r\n")
  209. responseTextBuffer.writeInteger(UInt8(0x80))
  210. responseTextBuffer.writeInteger(UInt32(textTrailers.utf8.count))
  211. responseTextBuffer.writeString(textTrailers)
  212. // TODO: Binary responses that are non multiples of 3 will end = or == when encoded in
  213. // base64. Investigate whether this might have any effect on the transport mechanism and
  214. // client decoding. Initial results say that they are inocuous, but we might have to keep
  215. // an eye on this in case something trips up.
  216. if let binaryData = responseTextBuffer.readData(length: responseTextBuffer.readableBytes) {
  217. let encodedData = binaryData.base64EncodedString()
  218. responseTextBuffer.clear()
  219. responseTextBuffer.reserveCapacity(encodedData.utf8.count)
  220. responseTextBuffer.writeString(encodedData)
  221. }
  222. // After collecting all response for gRPC Web connections, send one final aggregated
  223. // response.
  224. context.write(self.wrapOutboundOut(.body(.byteBuffer(responseTextBuffer))), promise: promise)
  225. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  226. } else {
  227. context.write(self.wrapOutboundOut(.end(trailers)), promise: promise)
  228. }
  229. outboundState = .ignore
  230. inboundState = .ignore
  231. }
  232. }
  233. }