2
0

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.writeContiguousBytes(decodedData)
  235. }
  236. self.messageReader.append(buffer: &body)
  237. do {
  238. // We may be re-entrantly called, and that re-entrant call may error. If the state changed for any reason,
  239. // stop looping.
  240. while self.inboundState == .expectingBody,
  241. let buffer = try self.messageReader.nextMessage() {
  242. context.fireChannelRead(self.wrapInboundOut(.message(buffer)))
  243. }
  244. } catch let grpcError as GRPCError.WithContext {
  245. context.fireErrorCaught(grpcError)
  246. return .ignore
  247. } catch {
  248. context.fireErrorCaught(GRPCError.DeserializationFailure().captureContext())
  249. return .ignore
  250. }
  251. // We may have been called re-entrantly and transitioned out of the state we were in (e.g. because of an
  252. // error). In all cases, if we get here we want to persist the current state.
  253. return self.inboundState
  254. }
  255. private func processEnd(context: ChannelHandlerContext,
  256. trailers: HTTPHeaders?) throws -> InboundState {
  257. self.logger.debug("processing end")
  258. if let trailers = trailers {
  259. self.logger.error(
  260. "unexpected trailers when processing stream end",
  261. metadata: ["trailers": "\(trailers)"]
  262. )
  263. throw GRPCError.InvalidState("unexpected trailers received").captureContext()
  264. }
  265. context.fireChannelRead(self.wrapInboundOut(.end))
  266. return .ignore
  267. }
  268. }
  269. extension HTTP1ToGRPCServerCodec: ChannelOutboundHandler {
  270. public typealias OutboundIn = _RawGRPCServerResponsePart
  271. public typealias OutboundOut = HTTPServerResponsePart
  272. public func write(context: ChannelHandlerContext, data: NIOAny,
  273. promise: EventLoopPromise<Void>?) {
  274. if case .ignore = self.outboundState {
  275. self.logger.notice("ignoring written data: \(data)")
  276. promise?.fail(GRPCError.InvalidState("rpc has already finished").captureContext())
  277. return
  278. }
  279. switch self.unwrapOutboundIn(data) {
  280. case var .headers(headers):
  281. guard case .expectingHeaders = self.outboundState else {
  282. self.logger.error(
  283. "invalid state while writing headers",
  284. metadata: ["state": "\(self.outboundState)", "headers": "\(headers)"]
  285. )
  286. return
  287. }
  288. var version = HTTPVersion(major: 2, minor: 0)
  289. if let contentType = self.contentType {
  290. headers.add(name: GRPCHeaderName.contentType, value: contentType.canonicalValue)
  291. if contentType != .protobuf {
  292. version = .init(major: 1, minor: 1)
  293. }
  294. }
  295. // Are we compressing responses?
  296. if let responseEncoding = self.responseEncodingHeader {
  297. headers.add(name: GRPCHeaderName.encoding, value: responseEncoding)
  298. }
  299. // The client may have sent us a message using an encoding we didn't advertise; we'll send
  300. // an accept-encoding header back if that's the case.
  301. if let acceptEncoding = self.acceptEncodingHeader {
  302. headers.add(name: GRPCHeaderName.acceptEncoding, value: acceptEncoding)
  303. }
  304. context.write(
  305. self
  306. .wrapOutboundOut(.head(HTTPResponseHead(
  307. version: version,
  308. status: .ok,
  309. headers: headers
  310. ))),
  311. promise: promise
  312. )
  313. self.outboundState = .expectingBodyOrStatus
  314. case let .message(messageContext):
  315. guard case .expectingBodyOrStatus = self.outboundState else {
  316. self.logger.error(
  317. "invalid state while writing message",
  318. metadata: ["state": "\(self.outboundState)"]
  319. )
  320. return
  321. }
  322. do {
  323. if self.contentType == .webTextProtobuf {
  324. // Store the response into an independent buffer. We can't return the message directly as
  325. // it needs to be aggregated with all the responses plus the trailers, in order to have
  326. // the base64 response properly encoded in a single byte stream.
  327. let buffer = try self.messageWriter.write(
  328. buffer: messageContext.message,
  329. allocator: context.channel.allocator,
  330. compressed: messageContext.compressed
  331. )
  332. self.appendResponseText(buffer)
  333. // Since we stored the written data, mark the write promise as successful so that the
  334. // ServerStreaming provider continues sending the data.
  335. promise?.succeed(())
  336. } else {
  337. let messageBuffer = try self.messageWriter.write(
  338. buffer: messageContext.message,
  339. allocator: context.channel.allocator,
  340. compressed: messageContext.compressed
  341. )
  342. context.write(self.wrapOutboundOut(.body(.byteBuffer(messageBuffer))), promise: promise)
  343. }
  344. } catch {
  345. let error = GRPCError.SerializationFailure().captureContext()
  346. promise?.fail(error)
  347. context.fireErrorCaught(error)
  348. self.outboundState = .ignore
  349. return
  350. }
  351. self.outboundState = .expectingBodyOrStatus
  352. case let .statusAndTrailers(status, trailers):
  353. // If we error before sending the initial headers then we won't have sent the request head.
  354. // NIOHTTP2 doesn't support sending a single frame as a "Trailers-Only" response so we still
  355. // need to loop back and send the request head first.
  356. if case .expectingHeaders = self.outboundState {
  357. self.write(context: context, data: NIOAny(OutboundIn.headers(HTTPHeaders())), promise: nil)
  358. }
  359. var trailers = trailers
  360. trailers.add(name: GRPCHeaderName.statusCode, value: String(describing: status.code.rawValue))
  361. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  362. trailers.add(name: GRPCHeaderName.statusMessage, value: message)
  363. }
  364. if self.contentType == .webTextProtobuf {
  365. // Encode the trailers into the response byte stream as a length delimited message, as per
  366. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
  367. let textTrailers = trailers.map { name, value in "\(name): \(value)" }
  368. .joined(separator: "\r\n")
  369. var trailersBuffer = context.channel.allocator.buffer(capacity: 5 + textTrailers.utf8.count)
  370. trailersBuffer.writeInteger(UInt8(0x80))
  371. trailersBuffer.writeInteger(UInt32(textTrailers.utf8.count))
  372. trailersBuffer.writeString(textTrailers)
  373. self.appendResponseText(trailersBuffer)
  374. // This code can only be called on the grpc-web path, so we know the response text buffers must be non-nil
  375. // and must contain at least one element.
  376. guard var buffers = self.responseTextBuffers else {
  377. preconditionFailure("Building web response text but responseTextBuffers are nil")
  378. }
  379. // Avoid a CoW
  380. self.responseTextBuffers = nil
  381. var responseTextBuffer = buffers.popFirst()!
  382. // Read the data from the first buffer.
  383. var accumulatedData = responseTextBuffer.readData(length: responseTextBuffer.readableBytes)!
  384. // Reserve enough capacity and append the remaining buffers.
  385. let requiredExtraCapacity = buffers.lazy.map { $0.readableBytes }.reduce(0, +)
  386. accumulatedData.reserveCapacity(accumulatedData.count + requiredExtraCapacity)
  387. while let buffer = buffers.popFirst() {
  388. accumulatedData.append(contentsOf: buffer.readableBytesView)
  389. }
  390. // Restore the buffers.
  391. self.responseTextBuffers = buffers
  392. // TODO: Binary responses that are non multiples of 3 will end = or == when encoded in
  393. // base64. Investigate whether this might have any effect on the transport mechanism and
  394. // client decoding. Initial results say that they are innocuous, but we might have to keep
  395. // an eye on this in case something trips up.
  396. let encodedData = accumulatedData.base64EncodedString()
  397. // Reuse our first buffer.
  398. responseTextBuffer.clear(minimumCapacity: Int(encodedData.utf8.count))
  399. responseTextBuffer.writeString(encodedData)
  400. // After collecting all response for gRPC Web connections, send one final aggregated
  401. // response.
  402. context.write(
  403. self.wrapOutboundOut(.body(.byteBuffer(responseTextBuffer))),
  404. promise: promise
  405. )
  406. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  407. } else {
  408. context.write(self.wrapOutboundOut(.end(trailers)), promise: promise)
  409. }
  410. // Log the call duration and status
  411. if let stopwatch = self.stopwatch {
  412. self.stopwatch = nil
  413. let millis = stopwatch.elapsedMillis()
  414. self.logger.debug("rpc call finished", metadata: [
  415. "duration_ms": "\(millis)",
  416. "status_code": "\(status.code.rawValue)",
  417. ])
  418. }
  419. self.outboundState = .ignore
  420. self.inboundState = .ignore
  421. }
  422. }
  423. private func appendResponseText(_ buffer: ByteBuffer) {
  424. if self.responseTextBuffers == nil {
  425. self.responseTextBuffers = CircularBuffer()
  426. }
  427. self.responseTextBuffers!.append(buffer)
  428. }
  429. }
  430. private extension HTTP1ToGRPCServerCodec {
  431. /// Selects an appropriate response encoding from the list of encodings sent to us by the client.
  432. /// Returns `nil` if there were no appropriate algorithms, in which case the server will send
  433. /// messages uncompressed.
  434. func selectResponseEncoding(from acceptableEncoding: [Substring]) -> CompressionAlgorithm? {
  435. guard case let .enabled(configuration) = self.encoding else {
  436. return nil
  437. }
  438. return acceptableEncoding.compactMap {
  439. CompressionAlgorithm(rawValue: String($0))
  440. }.first {
  441. configuration.enabledAlgorithms.contains($0)
  442. }
  443. }
  444. }
  445. struct MessageEncodingHeaderValidator {
  446. var encoding: ServerMessageEncoding
  447. enum ValidationResult {
  448. /// The requested compression is supported.
  449. case supported(
  450. algorithm: CompressionAlgorithm,
  451. decompressionLimit: DecompressionLimit,
  452. acceptEncoding: [String]
  453. )
  454. /// The `requestEncoding` is not supported; `acceptEncoding` contains all algorithms we do
  455. /// support.
  456. case unsupported(requestEncoding: String, acceptEncoding: [String])
  457. /// No compression was requested.
  458. case noCompression
  459. }
  460. /// Validates the value of the 'grpc-encoding' header against compression algorithms supported and
  461. /// advertised by this peer.
  462. ///
  463. /// - Parameter requestEncoding: The value of the 'grpc-encoding' header.
  464. func validate(requestEncoding: String?) -> ValidationResult {
  465. switch (self.encoding, requestEncoding) {
  466. // Compression is enabled and the client sent a message encoding header. Do we support it?
  467. case let (.enabled(configuration), .some(header)):
  468. guard let algorithm = CompressionAlgorithm(rawValue: header) else {
  469. return .unsupported(
  470. requestEncoding: header,
  471. acceptEncoding: configuration.enabledAlgorithms.map { $0.name }
  472. )
  473. }
  474. if configuration.enabledAlgorithms.contains(algorithm) {
  475. return .supported(
  476. algorithm: algorithm,
  477. decompressionLimit: configuration.decompressionLimit,
  478. acceptEncoding: []
  479. )
  480. } else {
  481. // From: https://github.com/grpc/grpc/blob/master/doc/compression.md
  482. //
  483. // Note that a peer MAY choose to not disclose all the encodings it supports. However, if
  484. // it receives a message compressed in an undisclosed but supported encoding, it MUST
  485. // include said encoding in the response's grpc-accept-encoding header.
  486. return .supported(
  487. algorithm: algorithm,
  488. decompressionLimit: configuration.decompressionLimit,
  489. acceptEncoding: configuration.enabledAlgorithms.map { $0.name } + CollectionOfOne(header)
  490. )
  491. }
  492. // Compression is disabled and the client sent a message encoding header. We clearly don't
  493. // support this. Note this is different to the supported but not advertised case since we have
  494. // explicitly not enabled compression.
  495. case let (.disabled, .some(header)):
  496. return .unsupported(requestEncoding: header, acceptEncoding: [])
  497. // The client didn't send a message encoding header.
  498. case (_, .none):
  499. return .noCompression
  500. }
  501. }
  502. }