2
0

HTTP1ToRawGRPCClientCodec.swift 5.8 KB

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