HTTP1ToGRPCServerCodec.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. import SwiftProtobuf
  22. /// Incoming gRPC package with a fixed message type.
  23. ///
  24. /// - Important: This is **NOT** part of the public API.
  25. public enum _GRPCServerRequestPart<Request> {
  26. case head(HTTPRequestHead)
  27. case message(Request)
  28. case end
  29. }
  30. public typealias _RawGRPCServerRequestPart = _GRPCServerRequestPart<ByteBuffer>
  31. /// Outgoing gRPC package with a fixed message type.
  32. ///
  33. /// - Important: This is **NOT** part of the public API.
  34. public enum _GRPCServerResponsePart<Response> {
  35. case headers(HTTPHeaders)
  36. case message(_MessageContext<Response>)
  37. case statusAndTrailers(GRPCStatus, HTTPHeaders)
  38. }
  39. public typealias _RawGRPCServerResponsePart = _GRPCServerResponsePart<ByteBuffer>
  40. /// A simple channel handler that translates HTTP1 data types into gRPC packets, and vice versa.
  41. ///
  42. /// We use HTTP1 (instead of HTTP2) primitives, as these are easier to work with than raw HTTP2
  43. /// primitives while providing all the functionality we need. In addition, it allows us to support
  44. /// gRPC-Web (gRPC over HTTP1).
  45. ///
  46. /// The translation from HTTP2 to HTTP1 is done by `HTTP2ToHTTP1ServerCodec`.
  47. public final class HTTP1ToGRPCServerCodec {
  48. public init(encoding: ServerMessageEncoding, logger: Logger) {
  49. self.encoding = encoding
  50. self.encodingHeaderValidator = MessageEncodingHeaderValidator(encoding: encoding)
  51. self.logger = logger
  52. var accessLog = Logger(subsystem: .serverAccess)
  53. accessLog[metadataKey: MetadataKey.requestID] = logger[metadataKey: MetadataKey.requestID]
  54. self.accessLog = accessLog
  55. self.messageReader = LengthPrefixedMessageReader()
  56. self.messageWriter = LengthPrefixedMessageWriter()
  57. }
  58. private var contentType: ContentType?
  59. private let encoding: ServerMessageEncoding
  60. private let encodingHeaderValidator: MessageEncodingHeaderValidator
  61. private var acceptEncodingHeader: String? = nil
  62. private var responseEncodingHeader: String? = nil
  63. private let logger: Logger
  64. private let accessLog: Logger
  65. private var stopwatch: Stopwatch?
  66. // The following buffers use force unwrapping explicitly. With optionals, developers
  67. // are encouraged to unwrap them using guard-else statements. These don't work cleanly
  68. // with structs, since the guard-else would create a new copy of the struct, which
  69. // would then have to be re-assigned into the class variable for the changes to take effect.
  70. // By force unwrapping, we avoid those reassignments, and the code is a bit cleaner.
  71. // Buffer to store binary encoded protos as they're being received if the proto is split across
  72. // multiple buffers.
  73. private var binaryRequestBuffer: NIO.ByteBuffer!
  74. // Buffers to store text encoded protos. Only used when content-type is application/grpc-web-text.
  75. // TODO(kaipi): Extract all gRPC Web processing logic into an independent handler only added on
  76. // the HTTP1.1 pipeline, as it's starting to get in the way of readability.
  77. private var requestTextBuffer: NIO.ByteBuffer!
  78. private var responseTextBuffers: CircularBuffer<ByteBuffer> = []
  79. var inboundState = InboundState.expectingHeaders {
  80. willSet {
  81. guard newValue != self.inboundState else { return }
  82. self.logger.debug("inbound state changed", metadata: ["old_state": "\(self.inboundState)", "new_state": "\(newValue)"])
  83. }
  84. }
  85. var outboundState = OutboundState.expectingHeaders {
  86. willSet {
  87. guard newValue != self.outboundState else { return }
  88. self.logger.debug("outbound state changed", metadata: ["old_state": "\(self.outboundState)", "new_state": "\(newValue)"])
  89. }
  90. }
  91. var messageReader: LengthPrefixedMessageReader
  92. var messageWriter: LengthPrefixedMessageWriter
  93. }
  94. extension HTTP1ToGRPCServerCodec {
  95. enum InboundState {
  96. case expectingHeaders
  97. case expectingBody
  98. // ignore any additional messages; e.g. we've seen .end or we've sent an error and are waiting for the stream to close.
  99. case ignore
  100. }
  101. enum OutboundState {
  102. case expectingHeaders
  103. case expectingBodyOrStatus
  104. case ignore
  105. }
  106. }
  107. extension HTTP1ToGRPCServerCodec: ChannelInboundHandler {
  108. public typealias InboundIn = HTTPServerRequestPart
  109. public typealias InboundOut = _RawGRPCServerRequestPart
  110. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  111. if case .ignore = inboundState {
  112. self.logger.notice("ignoring read data", metadata: ["data": "\(data)"])
  113. return
  114. }
  115. do {
  116. switch self.unwrapInboundIn(data) {
  117. case .head(let requestHead):
  118. inboundState = try processHead(context: context, requestHead: requestHead)
  119. case .body(var body):
  120. inboundState = try processBody(context: context, body: &body)
  121. case .end(let trailers):
  122. inboundState = try processEnd(context: context, trailers: trailers)
  123. }
  124. } catch {
  125. context.fireErrorCaught(error)
  126. inboundState = .ignore
  127. }
  128. }
  129. func processHead(context: ChannelHandlerContext, requestHead: HTTPRequestHead) throws -> InboundState {
  130. self.logger.debug("processing request head", metadata: ["head": "\(requestHead)"])
  131. guard case .expectingHeaders = inboundState else {
  132. self.logger.error("invalid state while processing request head",
  133. metadata: ["state": "\(inboundState)", "head": "\(requestHead)"])
  134. throw GRPCError.InvalidState("expected state .expectingHeaders, got \(inboundState)").captureContext()
  135. }
  136. self.stopwatch = .start()
  137. self.accessLog.debug("rpc call started", metadata: [
  138. "path": "\(requestHead.uri)",
  139. "method": "\(requestHead.method)",
  140. "version": "\(requestHead.version)"
  141. ])
  142. if let contentType = requestHead.headers.first(name: GRPCHeaderName.contentType).flatMap(ContentType.init) {
  143. self.contentType = contentType
  144. } else {
  145. self.logger.debug("no 'content-type' header, assuming content type is 'application/grpc'")
  146. // If the Content-Type is not present, assume the request is binary encoded gRPC.
  147. self.contentType = .protobuf
  148. }
  149. if self.contentType == .webTextProtobuf {
  150. requestTextBuffer = context.channel.allocator.buffer(capacity: 0)
  151. }
  152. // What compression was used for sending requests?
  153. let encodingHeader = requestHead.headers.first(name: GRPCHeaderName.encoding)
  154. switch self.encodingHeaderValidator.validate(requestEncoding: encodingHeader) {
  155. case let .supported(algorithm, limit, acceptableEncoding):
  156. self.messageReader = LengthPrefixedMessageReader(compression: algorithm, decompressionLimit: limit)
  157. if acceptableEncoding.isEmpty {
  158. self.acceptEncodingHeader = nil
  159. } else {
  160. self.acceptEncodingHeader = acceptableEncoding.joined(separator: ",")
  161. }
  162. case .noCompression:
  163. self.messageReader = LengthPrefixedMessageReader()
  164. self.acceptEncodingHeader = nil
  165. case let .unsupported(header, acceptableEncoding):
  166. let message: String
  167. let headers: HTTPHeaders
  168. if acceptableEncoding.isEmpty {
  169. message = "compression is not supported"
  170. headers = .init()
  171. } else {
  172. let advertised = acceptableEncoding.joined(separator: ",")
  173. message = "'\(header)' compression is not supported, supported: \(advertised)"
  174. headers = [GRPCHeaderName.acceptEncoding: advertised]
  175. }
  176. let status = GRPCStatus(code: .unimplemented, message: message)
  177. defer {
  178. self.write(context: context, data: NIOAny(OutboundIn.statusAndTrailers(status, headers)), promise: nil)
  179. self.flush(context: context)
  180. }
  181. // We're about to fast-fail, so ignore any following inbound messages.
  182. return .ignore
  183. }
  184. // What compression should we use for writing responses?
  185. let clientAcceptableEncoding = requestHead.headers[canonicalForm: GRPCHeaderName.acceptEncoding]
  186. if let responseEncoding = self.selectResponseEncoding(from: clientAcceptableEncoding) {
  187. self.messageWriter = LengthPrefixedMessageWriter(compression: responseEncoding)
  188. self.responseEncodingHeader = responseEncoding.name
  189. } else {
  190. self.messageWriter = LengthPrefixedMessageWriter(compression: .none)
  191. self.responseEncodingHeader = nil
  192. }
  193. context.fireChannelRead(self.wrapInboundOut(.head(requestHead)))
  194. return .expectingBody
  195. }
  196. func processBody(context: ChannelHandlerContext, body: inout ByteBuffer) throws -> InboundState {
  197. self.logger.debug("processing body: \(body)")
  198. guard case .expectingBody = inboundState else {
  199. self.logger.error("invalid state while processing body",
  200. metadata: ["state": "\(inboundState)", "body": "\(body)"])
  201. throw GRPCError.InvalidState("expected state .expectingBody, got \(inboundState)").captureContext()
  202. }
  203. // If the contentType is text, then decode the incoming bytes as base64 encoded, and append
  204. // it to the binary buffer. If the request is chunked, this section will process the text
  205. // in the biggest chunk that is multiple of 4, leaving the unread bytes in the textBuffer
  206. // where it will expect a new incoming chunk.
  207. if self.contentType == .webTextProtobuf {
  208. precondition(requestTextBuffer != nil)
  209. requestTextBuffer.writeBuffer(&body)
  210. // Read in chunks of 4 bytes as base64 encoded strings will always be multiples of 4.
  211. let readyBytes = requestTextBuffer.readableBytes - (requestTextBuffer.readableBytes % 4)
  212. guard let base64Encoded = requestTextBuffer.readString(length: readyBytes),
  213. let decodedData = Data(base64Encoded: base64Encoded) else {
  214. throw GRPCError.Base64DecodeError().captureContext()
  215. }
  216. body.writeBytes(decodedData)
  217. }
  218. self.messageReader.append(buffer: &body)
  219. var requests: [ByteBuffer] = []
  220. do {
  221. while let buffer = try self.messageReader.nextMessage() {
  222. requests.append(buffer)
  223. }
  224. } catch let grpcError as GRPCError.WithContext {
  225. context.fireErrorCaught(grpcError)
  226. return .ignore
  227. } catch {
  228. context.fireErrorCaught(GRPCError.DeserializationFailure().captureContext())
  229. return .ignore
  230. }
  231. requests.forEach {
  232. context.fireChannelRead(self.wrapInboundOut(.message($0)))
  233. }
  234. return .expectingBody
  235. }
  236. private func processEnd(context: ChannelHandlerContext, trailers: HTTPHeaders?) throws -> InboundState {
  237. self.logger.debug("processing end")
  238. if let trailers = trailers {
  239. self.logger.error("unexpected trailers when processing stream end", metadata: ["trailers": "\(trailers)"])
  240. throw GRPCError.InvalidState("unexpected trailers received").captureContext()
  241. }
  242. context.fireChannelRead(self.wrapInboundOut(.end))
  243. return .ignore
  244. }
  245. }
  246. extension HTTP1ToGRPCServerCodec: ChannelOutboundHandler {
  247. public typealias OutboundIn = _RawGRPCServerResponsePart
  248. public typealias OutboundOut = HTTPServerResponsePart
  249. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  250. if case .ignore = self.outboundState {
  251. self.logger.notice("ignoring written data: \(data)")
  252. promise?.fail(GRPCError.InvalidState("rpc has already finished").captureContext())
  253. return
  254. }
  255. switch self.unwrapOutboundIn(data) {
  256. case .headers(var headers):
  257. guard case .expectingHeaders = self.outboundState else {
  258. self.logger.error("invalid state while writing headers",
  259. metadata: ["state": "\(self.outboundState)", "headers": "\(headers)"])
  260. return
  261. }
  262. var version = HTTPVersion(major: 2, minor: 0)
  263. if let contentType = self.contentType {
  264. headers.add(name: GRPCHeaderName.contentType, value: contentType.canonicalValue)
  265. if contentType != .protobuf {
  266. version = .init(major: 1, minor: 1)
  267. }
  268. }
  269. // Are we compressing responses?
  270. if let responseEncoding = self.responseEncodingHeader {
  271. headers.add(name: GRPCHeaderName.encoding, value: responseEncoding)
  272. }
  273. // The client may have sent us a message using an encoding we didn't advertise; we'll send
  274. // an accept-encoding header back if that's the case.
  275. if let acceptEncoding = self.acceptEncodingHeader {
  276. headers.add(name: GRPCHeaderName.acceptEncoding, value: acceptEncoding)
  277. }
  278. context.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: version, status: .ok, headers: headers))), promise: promise)
  279. self.outboundState = .expectingBodyOrStatus
  280. case .message(let messageContext):
  281. guard case .expectingBodyOrStatus = self.outboundState else {
  282. self.logger.error("invalid state while writing message", metadata: ["state": "\(self.outboundState)"])
  283. return
  284. }
  285. do {
  286. if contentType == .webTextProtobuf {
  287. // Store the response into an independent buffer. We can't return the message directly as
  288. // it needs to be aggregated with all the responses plus the trailers, in order to have
  289. // the base64 response properly encoded in a single byte stream.
  290. let buffer = try self.messageWriter.write(
  291. buffer: messageContext.message,
  292. allocator: context.channel.allocator,
  293. compressed: messageContext.compressed
  294. )
  295. self.responseTextBuffers.append(buffer)
  296. // Since we stored the written data, mark the write promise as successful so that the
  297. // ServerStreaming provider continues sending the data.
  298. promise?.succeed(())
  299. } else {
  300. let messageBuffer = try self.messageWriter.write(
  301. buffer: messageContext.message,
  302. allocator: context.channel.allocator,
  303. compressed: messageContext.compressed
  304. )
  305. context.write(self.wrapOutboundOut(.body(.byteBuffer(messageBuffer))), promise: promise)
  306. }
  307. } catch {
  308. let error = GRPCError.SerializationFailure().captureContext()
  309. promise?.fail(error)
  310. context.fireErrorCaught(error)
  311. self.outboundState = .ignore
  312. return
  313. }
  314. self.outboundState = .expectingBodyOrStatus
  315. case let .statusAndTrailers(status, trailers):
  316. // If we error before sending the initial headers then we won't have sent the request head.
  317. // NIOHTTP2 doesn't support sending a single frame as a "Trailers-Only" response so we still
  318. // need to loop back and send the request head first.
  319. if case .expectingHeaders = self.outboundState {
  320. self.write(context: context, data: NIOAny(OutboundIn.headers(HTTPHeaders())), promise: nil)
  321. }
  322. var trailers = trailers
  323. trailers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  324. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  325. trailers.add(name: GRPCHeaderName.statusMessage, value: message)
  326. }
  327. if contentType == .webTextProtobuf {
  328. // Encode the trailers into the response byte stream as a length delimited message, as per
  329. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
  330. let textTrailers = trailers.map { name, value in "\(name): \(value)" }.joined(separator: "\r\n")
  331. var trailersBuffer = context.channel.allocator.buffer(capacity: 5 + textTrailers.utf8.count)
  332. trailersBuffer.writeInteger(UInt8(0x80))
  333. trailersBuffer.writeInteger(UInt32(textTrailers.utf8.count))
  334. trailersBuffer.writeString(textTrailers)
  335. self.responseTextBuffers.append(trailersBuffer)
  336. // The '!' is fine, we know it's not empty since we just added a buffer.
  337. var responseTextBuffer = self.responseTextBuffers.popFirst()!
  338. // Read the data from the first buffer.
  339. var accumulatedData = responseTextBuffer.readData(length: responseTextBuffer.readableBytes)!
  340. // Reserve enough capacity and append the remaining buffers.
  341. let requiredExtraCapacity = self.responseTextBuffers.lazy.map { $0.readableBytes }.reduce(0, +)
  342. accumulatedData.reserveCapacity(accumulatedData.count + requiredExtraCapacity)
  343. while let buffer = self.responseTextBuffers.popFirst() {
  344. accumulatedData.append(contentsOf: buffer.readableBytesView)
  345. }
  346. // TODO: Binary responses that are non multiples of 3 will end = or == when encoded in
  347. // base64. Investigate whether this might have any effect on the transport mechanism and
  348. // client decoding. Initial results say that they are innocuous, but we might have to keep
  349. // an eye on this in case something trips up.
  350. let encodedData = accumulatedData.base64EncodedString()
  351. // Reuse our first buffer.
  352. responseTextBuffer.clear(minimumCapacity: numericCast(encodedData.utf8.count))
  353. responseTextBuffer.writeString(encodedData)
  354. // After collecting all response for gRPC Web connections, send one final aggregated
  355. // response.
  356. context.write(self.wrapOutboundOut(.body(.byteBuffer(responseTextBuffer))), promise: promise)
  357. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  358. } else {
  359. context.write(self.wrapOutboundOut(.end(trailers)), promise: promise)
  360. }
  361. // Log the call duration and status
  362. if let stopwatch = self.stopwatch {
  363. self.stopwatch = nil
  364. let millis = stopwatch.elapsedMillis()
  365. self.accessLog.debug("rpc call finished", metadata: [
  366. "duration_ms": "\(millis)",
  367. "status_code": "\(status.code.rawValue)"
  368. ])
  369. }
  370. self.outboundState = .ignore
  371. self.inboundState = .ignore
  372. }
  373. }
  374. }
  375. fileprivate extension HTTP1ToGRPCServerCodec {
  376. /// Selects an appropriate response encoding from the list of encodings sent to us by the client.
  377. /// Returns `nil` if there were no appropriate algorithms, in which case the server will send
  378. /// messages uncompressed.
  379. func selectResponseEncoding(from acceptableEncoding: [Substring]) -> CompressionAlgorithm? {
  380. guard case .enabled(let configuration) = self.encoding else {
  381. return nil
  382. }
  383. return acceptableEncoding.compactMap {
  384. CompressionAlgorithm(rawValue: String($0))
  385. }.first {
  386. configuration.enabledAlgorithms.contains($0)
  387. }
  388. }
  389. }
  390. struct MessageEncodingHeaderValidator {
  391. var encoding: ServerMessageEncoding
  392. enum ValidationResult {
  393. /// The requested compression is supported.
  394. case supported(algorithm: CompressionAlgorithm, decompressionLimit: DecompressionLimit, acceptEncoding: [String])
  395. /// The `requestEncoding` is not supported; `acceptEncoding` contains all algorithms we do
  396. /// support.
  397. case unsupported(requestEncoding: String, acceptEncoding: [String])
  398. /// No compression was requested.
  399. case noCompression
  400. }
  401. /// Validates the value of the 'grpc-encoding' header against compression algorithms supported and
  402. /// advertised by this peer.
  403. ///
  404. /// - Parameter requestEncoding: The value of the 'grpc-encoding' header.
  405. func validate(requestEncoding: String?) -> ValidationResult {
  406. switch (self.encoding, requestEncoding) {
  407. // Compression is enabled and the client sent a message encoding header. Do we support it?
  408. case (.enabled(let configuration), .some(let header)):
  409. guard let algorithm = CompressionAlgorithm(rawValue: header) else {
  410. return .unsupported(
  411. requestEncoding: header,
  412. acceptEncoding: configuration.enabledAlgorithms.map { $0.name }
  413. )
  414. }
  415. if configuration.enabledAlgorithms.contains(algorithm) {
  416. return .supported(
  417. algorithm: algorithm,
  418. decompressionLimit: configuration.decompressionLimit,
  419. acceptEncoding: []
  420. )
  421. } else {
  422. // From: https://github.com/grpc/grpc/blob/master/doc/compression.md
  423. //
  424. // Note that a peer MAY choose to not disclose all the encodings it supports. However, if
  425. // it receives a message compressed in an undisclosed but supported encoding, it MUST
  426. // include said encoding in the response's grpc-accept-encoding header.
  427. return .supported(
  428. algorithm: algorithm,
  429. decompressionLimit: configuration.decompressionLimit,
  430. acceptEncoding: configuration.enabledAlgorithms.map { $0.name } + CollectionOfOne(header)
  431. )
  432. }
  433. // Compression is disabled and the client sent a message encoding header. We clearly don't
  434. // support this. Note this is different to the supported but not advertised case since we have
  435. // explicitly not enabled compression.
  436. case (.disabled, .some(let header)):
  437. return .unsupported(requestEncoding: header, acceptEncoding: [])
  438. // The client didn't send a message encoding header.
  439. case (_, .none):
  440. return .noCompression
  441. }
  442. }
  443. }