HTTP1ToRawGRPCServerCodec.swift 11 KB

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