HTTP1ToRawGRPCClientCodec.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. guard head.status == .ok else {
  81. throw GRPCError.client(.HTTPStatusNotOk(head.status))
  82. }
  83. // Trailers-Only response.
  84. if head.headers.contains(name: GRPCHeaderName.statusCode) {
  85. self.state = .expectingBodyOrTrailers
  86. return try self.processTrailers(context: context, trailers: head.headers)
  87. }
  88. let inboundCompression: CompressionMechanism = head.headers[GRPCHeaderName.encoding]
  89. .first
  90. .map { CompressionMechanism(rawValue: $0) ?? .unknown } ?? .none
  91. guard inboundCompression.supported else {
  92. throw GRPCError.client(.unsupportedCompressionMechanism(inboundCompression.rawValue))
  93. }
  94. self.messageReader.compressionMechanism = inboundCompression
  95. context.fireChannelRead(self.wrapInboundOut(.headers(head.headers)))
  96. return .expectingBodyOrTrailers
  97. }
  98. /// Processes the given buffer; if a complete message is read then it is forwarded to the
  99. /// next channel handler.
  100. ///
  101. /// - note: Requires the `.expectingBodyOrTrailers` state.
  102. private func processBody(context: ChannelHandlerContext, messageBuffer: inout ByteBuffer) throws -> State {
  103. guard case .expectingBodyOrTrailers = state else {
  104. throw GRPCError.client(.invalidState("received body while in state \(state)"))
  105. }
  106. self.messageReader.append(buffer: &messageBuffer)
  107. while let message = try self.messageReader.nextMessage() {
  108. context.fireChannelRead(self.wrapInboundOut(.message(message)))
  109. }
  110. return .expectingBodyOrTrailers
  111. }
  112. /// Forwards a `GRPCStatus` to the next handler. The status and message are extracted
  113. /// from the trailers if they exist; the `.unknown` status code is used if no status exists.
  114. private func processTrailers(context: ChannelHandlerContext, trailers: HTTPHeaders?) throws -> State {
  115. guard case .expectingBodyOrTrailers = state else {
  116. throw GRPCError.client(.invalidState("received trailers while in state \(state)"))
  117. }
  118. let statusCode = trailers?[GRPCHeaderName.statusCode].first.flatMap {
  119. Int($0)
  120. }.flatMap {
  121. StatusCode(rawValue: $0)
  122. } ?? .unknown
  123. let statusMessage = trailers?[GRPCHeaderName.statusMessage].first.map {
  124. GRPCStatusMessageMarshaller.unmarshall($0)
  125. }
  126. var trailingCustomMetadata = trailers ?? HTTPHeaders()
  127. trailingCustomMetadata.remove(name: GRPCHeaderName.statusCode)
  128. trailingCustomMetadata.remove(name: GRPCHeaderName.statusMessage)
  129. let status = GRPCStatus(code: statusCode, message: statusMessage, trailingMetadata: trailingCustomMetadata)
  130. context.fireChannelRead(wrapInboundOut(.status(status)))
  131. return .ignore
  132. }
  133. }
  134. extension HTTP1ToRawGRPCClientCodec: ChannelOutboundHandler {
  135. public typealias OutboundIn = RawGRPCClientRequestPart
  136. public typealias OutboundOut = HTTPClientRequestPart
  137. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  138. switch self.unwrapOutboundIn(data) {
  139. case .head(let requestHead):
  140. context.write(self.wrapOutboundOut(.head(requestHead)), promise: promise)
  141. case .message(let message):
  142. var request = context.channel.allocator.buffer(capacity: LengthPrefixedMessageWriter.metadataLength)
  143. messageWriter.write(message, into: &request, usingCompression: .none)
  144. context.write(self.wrapOutboundOut(.body(.byteBuffer(request))), promise: promise)
  145. case .end:
  146. context.write(self.wrapOutboundOut(.end(nil)), promise: promise)
  147. }
  148. }
  149. }