HTTP1ToRawGRPCServerCodec.swift 14 KB

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