HTTP1ToGRPCServerCodec.swift 22 KB

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