HTTP1ToRawGRPCClientCodec.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. /// Outgoing gRPC package with an unknown message type (represented as the serialized protobuf message).
  20. public enum RawGRPCClientRequestPart {
  21. case head(HTTPRequestHead)
  22. case message(Data)
  23. case end
  24. }
  25. /// Incoming gRPC package with an unknown message type (represented by a byte buffer).
  26. public enum RawGRPCClientResponsePart {
  27. case headers(HTTPHeaders)
  28. case message(ByteBuffer)
  29. case status(GRPCStatus)
  30. }
  31. /// Codec for translating HTTP/1 responses from the server into untyped gRPC packages
  32. /// and vice-versa.
  33. ///
  34. /// Most of the inbound processing is done by `LengthPrefixedMessageReader`; which
  35. /// reads length-prefxied gRPC messages into `ByteBuffer`s containing serialized
  36. /// Protobuf messages.
  37. ///
  38. /// The outbound processing transforms serialized Protobufs into length-prefixed
  39. /// gRPC messages stored in `ByteBuffer`s.
  40. ///
  41. /// See `HTTP1ToRawGRPCServerCodec` for the corresponding server codec.
  42. public final class HTTP1ToRawGRPCClientCodec {
  43. public init() {}
  44. private enum State {
  45. case expectingHeaders
  46. case expectingBodyOrTrailers
  47. case ignore
  48. }
  49. private var state: State = .expectingHeaders
  50. private let messageReader = LengthPrefixedMessageReader(mode: .client, compressionMechanism: .none)
  51. private let messageWriter = LengthPrefixedMessageWriter()
  52. private var inboundCompression: CompressionMechanism = .none
  53. }
  54. extension HTTP1ToRawGRPCClientCodec: ChannelInboundHandler {
  55. public typealias InboundIn = HTTPClientResponsePart
  56. public typealias InboundOut = RawGRPCClientResponsePart
  57. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  58. if case .ignore = state { return }
  59. do {
  60. switch self.unwrapInboundIn(data) {
  61. case .head(let head):
  62. state = try processHead(context: context, head: head)
  63. case .body(var message):
  64. state = try processBody(context: context, messageBuffer: &message)
  65. case .end(let trailers):
  66. state = try processTrailers(context: context, trailers: trailers)
  67. }
  68. } catch {
  69. context.fireErrorCaught(error)
  70. state = .ignore
  71. }
  72. }
  73. /// Forwards the headers from the request head to the next handler.
  74. ///
  75. /// - note: Requires the `.expectingHeaders` state.
  76. private func processHead(context: ChannelHandlerContext, head: HTTPResponseHead) throws -> State {
  77. guard case .expectingHeaders = state else {
  78. throw GRPCError.client(.invalidState("received headers while in state \(state)"))
  79. }
  80. // Trailers-Only response.
  81. if head.headers.contains(name: GRPCHeaderName.statusCode) {
  82. self.state = .expectingBodyOrTrailers
  83. return try self.processTrailers(context: context, trailers: head.headers)
  84. }
  85. // This should be checked *after* the trailers-only response is handled since any status code
  86. // and message we already have should take precedence over one we generate from the HTTP status
  87. // code and reason.
  88. //
  89. // Source: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
  90. guard head.status == .ok else {
  91. throw GRPCError.client(.HTTPStatusNotOk(head.status))
  92. }
  93. let inboundCompression: CompressionMechanism = head.headers[GRPCHeaderName.encoding]
  94. .first
  95. .map { CompressionMechanism(rawValue: $0) ?? .unknown } ?? .none
  96. guard inboundCompression.supported else {
  97. throw GRPCError.client(.unsupportedCompressionMechanism(inboundCompression.rawValue))
  98. }
  99. self.messageReader.compressionMechanism = inboundCompression
  100. context.fireChannelRead(self.wrapInboundOut(.headers(head.headers)))
  101. return .expectingBodyOrTrailers
  102. }
  103. /// Processes the given buffer; if a complete message is read then it is forwarded to the
  104. /// next channel handler.
  105. ///
  106. /// - note: Requires the `.expectingBodyOrTrailers` state.
  107. private func processBody(context: ChannelHandlerContext, messageBuffer: inout ByteBuffer) throws -> State {
  108. guard case .expectingBodyOrTrailers = state else {
  109. throw GRPCError.client(.invalidState("received body while in state \(state)"))
  110. }
  111. self.messageReader.append(buffer: &messageBuffer)
  112. while let message = try self.messageReader.nextMessage() {
  113. context.fireChannelRead(self.wrapInboundOut(.message(message)))
  114. }
  115. return .expectingBodyOrTrailers
  116. }
  117. /// Forwards a `GRPCStatus` to the next handler. The status and message are extracted
  118. /// from the trailers if they exist; the `.unknown` status code is used if no status exists.
  119. private func processTrailers(context: ChannelHandlerContext, trailers: HTTPHeaders?) throws -> State {
  120. guard case .expectingBodyOrTrailers = state else {
  121. throw GRPCError.client(.invalidState("received trailers while in state \(state)"))
  122. }
  123. let statusCode = trailers?[GRPCHeaderName.statusCode].first.flatMap {
  124. Int($0)
  125. }.flatMap {
  126. StatusCode(rawValue: $0)
  127. } ?? .unknown
  128. let statusMessage = trailers?[GRPCHeaderName.statusMessage].first.map {
  129. GRPCStatusMessageMarshaller.unmarshall($0)
  130. }
  131. let status = GRPCStatus(code: statusCode, message: statusMessage, trailingMetadata: trailers ?? HTTPHeaders())
  132. context.fireChannelRead(wrapInboundOut(.status(status)))
  133. return .ignore
  134. }
  135. }
  136. extension HTTP1ToRawGRPCClientCodec: ChannelOutboundHandler {
  137. public typealias OutboundIn = RawGRPCClientRequestPart
  138. public typealias OutboundOut = HTTPClientRequestPart
  139. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  140. switch self.unwrapOutboundIn(data) {
  141. case .head(let requestHead):
  142. context.write(self.wrapOutboundOut(.head(requestHead)), promise: promise)
  143. case .message(let message):
  144. var request = context.channel.allocator.buffer(capacity: LengthPrefixedMessageWriter.metadataLength)
  145. messageWriter.write(message, into: &request, usingCompression: .none)
  146. context.write(self.wrapOutboundOut(.body(.byteBuffer(request))), promise: promise)
  147. case .end:
  148. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  149. }
  150. }
  151. }