GRPCClientCodec.swift 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. import SwiftProtobuf
  20. /// Outgoing gRPC package with a fixed message type.
  21. public enum GRPCClientRequestPart<RequestMessage: Message> {
  22. case head(HTTPRequestHead)
  23. // We box the message to keep the enum small enough to fit in `NIOAny` and avoid unnecessary
  24. // allocations.
  25. case message(_Box<RequestMessage>)
  26. case end
  27. }
  28. /// Incoming gRPC package with a fixed message type.
  29. public enum GRPCClientResponsePart<ResponseMessage: Message> {
  30. case headers(HTTPHeaders)
  31. // We box the message to keep the enum small enough to fit in `NIOAny` and avoid unnecessary
  32. // allocations.
  33. case message(_Box<ResponseMessage>)
  34. case status(GRPCStatus)
  35. }
  36. /// This channel handler simply encodes and decodes protobuf messages into typed messages
  37. /// and `Data`.
  38. public final class GRPCClientCodec<RequestMessage: Message, ResponseMessage: Message> {
  39. public init() {}
  40. }
  41. extension GRPCClientCodec: ChannelInboundHandler {
  42. public typealias InboundIn = RawGRPCClientResponsePart
  43. public typealias InboundOut = GRPCClientResponsePart<ResponseMessage>
  44. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  45. let response = self.unwrapInboundIn(data)
  46. switch response {
  47. case .headers(let headers):
  48. context.fireChannelRead(self.wrapInboundOut(.headers(headers)))
  49. case .message(var messageBuffer):
  50. // Force unwrapping is okay here; we're reading the readable bytes.
  51. let messageAsData = messageBuffer.readData(length: messageBuffer.readableBytes)!
  52. do {
  53. let box = _Box(try ResponseMessage(serializedData: messageAsData))
  54. context.fireChannelRead(self.wrapInboundOut(.message(box)))
  55. } catch {
  56. context.fireErrorCaught(GRPCError.client(.responseProtoDeserializationFailure))
  57. }
  58. case .status(let status):
  59. context.fireChannelRead(self.wrapInboundOut(.status(status)))
  60. }
  61. }
  62. }
  63. extension GRPCClientCodec: ChannelOutboundHandler {
  64. public typealias OutboundIn = GRPCClientRequestPart<RequestMessage>
  65. public typealias OutboundOut = RawGRPCClientRequestPart
  66. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  67. let request = self.unwrapOutboundIn(data)
  68. switch request {
  69. case .head(let head):
  70. context.write(self.wrapOutboundOut(.head(head)), promise: promise)
  71. case .message(let box):
  72. do {
  73. context.write(self.wrapOutboundOut(.message(try box.value.serializedData())), promise: promise)
  74. } catch {
  75. let error = GRPCError.client(.requestProtoSerializationFailure)
  76. promise?.fail(error)
  77. context.fireErrorCaught(error)
  78. }
  79. case .end:
  80. context.write(self.wrapOutboundOut(.end), promise: promise)
  81. }
  82. }
  83. }