GRPCClientStreamHandler.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import NIOCore
  18. import NIOHTTP2
  19. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  20. final class GRPCClientStreamHandler: ChannelDuplexHandler {
  21. typealias InboundIn = HTTP2Frame.FramePayload
  22. typealias InboundOut = RPCResponsePart
  23. typealias OutboundIn = RPCRequestPart
  24. typealias OutboundOut = HTTP2Frame.FramePayload
  25. private var stateMachine: GRPCStreamStateMachine
  26. private var isReading = false
  27. private var flushPending = false
  28. init(
  29. methodDescriptor: MethodDescriptor,
  30. scheme: Scheme,
  31. outboundEncoding: CompressionAlgorithm,
  32. acceptedEncodings: [CompressionAlgorithm],
  33. maximumPayloadSize: Int,
  34. skipStateMachineAssertions: Bool = false
  35. ) {
  36. self.stateMachine = .init(
  37. configuration: .client(
  38. .init(
  39. methodDescriptor: methodDescriptor,
  40. scheme: scheme,
  41. outboundEncoding: outboundEncoding,
  42. acceptedEncodings: acceptedEncodings
  43. )
  44. ),
  45. maximumPayloadSize: maximumPayloadSize,
  46. skipAssertions: skipStateMachineAssertions
  47. )
  48. }
  49. }
  50. // - MARK: ChannelInboundHandler
  51. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  52. extension GRPCClientStreamHandler {
  53. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  54. self.isReading = true
  55. let frame = self.unwrapInboundIn(data)
  56. switch frame {
  57. case .data(let frameData):
  58. let endStream = frameData.endStream
  59. switch frameData.data {
  60. case .byteBuffer(let buffer):
  61. do {
  62. switch try self.stateMachine.receive(buffer: buffer, endStream: endStream) {
  63. case .endRPCAndForwardErrorStatus(let status):
  64. context.fireChannelRead(self.wrapInboundOut(.status(status, [:])))
  65. context.close(promise: nil)
  66. case .readInbound:
  67. loop: while true {
  68. switch self.stateMachine.nextInboundMessage() {
  69. case .receiveMessage(let message):
  70. context.fireChannelRead(self.wrapInboundOut(.message(message)))
  71. case .awaitMoreMessages:
  72. break loop
  73. case .noMoreMessages:
  74. // This could only happen if the server sends a data frame with EOS
  75. // set, without sending status and trailers.
  76. // If this happens, we should have forwarded an error status above
  77. // so we should never reach this point. Do nothing.
  78. break loop
  79. }
  80. }
  81. }
  82. } catch {
  83. context.fireErrorCaught(error)
  84. }
  85. case .fileRegion:
  86. preconditionFailure("Unexpected IOData.fileRegion")
  87. }
  88. case .headers(let headers):
  89. do {
  90. let action = try self.stateMachine.receive(
  91. headers: headers.headers,
  92. endStream: headers.endStream
  93. )
  94. switch action {
  95. case .receivedMetadata(let metadata):
  96. context.fireChannelRead(self.wrapInboundOut(.metadata(metadata)))
  97. case .rejectRPC:
  98. throw RPCError(
  99. code: .internalError,
  100. message: "Client cannot get rejectRPC."
  101. )
  102. case .receivedStatusAndMetadata(let status, let metadata):
  103. context.fireChannelRead(self.wrapInboundOut(.status(status, metadata)))
  104. context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
  105. case .doNothing:
  106. ()
  107. }
  108. } catch {
  109. context.fireErrorCaught(error)
  110. }
  111. case .ping, .goAway, .priority, .rstStream, .settings, .pushPromise, .windowUpdate,
  112. .alternativeService, .origin:
  113. ()
  114. }
  115. }
  116. func channelReadComplete(context: ChannelHandlerContext) {
  117. self.isReading = false
  118. if self.flushPending {
  119. self.flushPending = false
  120. self.flush(context: context)
  121. }
  122. context.fireChannelReadComplete()
  123. }
  124. func handlerRemoved(context: ChannelHandlerContext) {
  125. self.stateMachine.tearDown()
  126. }
  127. }
  128. // - MARK: ChannelOutboundHandler
  129. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  130. extension GRPCClientStreamHandler {
  131. func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  132. switch self.unwrapOutboundIn(data) {
  133. case .metadata(let metadata):
  134. do {
  135. self.flushPending = true
  136. let headers = try self.stateMachine.send(metadata: metadata)
  137. context.write(self.wrapOutboundOut(.headers(.init(headers: headers))), promise: promise)
  138. } catch {
  139. promise?.fail(error)
  140. context.fireErrorCaught(error)
  141. }
  142. case .message(let message):
  143. do {
  144. try self.stateMachine.send(message: message, promise: promise)
  145. } catch {
  146. promise?.fail(error)
  147. context.fireErrorCaught(error)
  148. }
  149. }
  150. }
  151. func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
  152. switch mode {
  153. case .input:
  154. context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
  155. promise?.succeed()
  156. case .output:
  157. // We flush all pending messages and update the internal state machine's
  158. // state, but we don't close the outbound end of the channel, because
  159. // forwarding the close in this case would cause the HTTP2 stream handler
  160. // to close the whole channel (as the mode is ignored in its implementation).
  161. do {
  162. try self.stateMachine.closeOutbound()
  163. // Force a flush by calling _flush instead of flush
  164. // (otherwise, we'd skip flushing if we're in a read loop)
  165. self._flush(context: context)
  166. promise?.succeed()
  167. } catch {
  168. promise?.fail(error)
  169. context.fireErrorCaught(error)
  170. }
  171. case .all:
  172. // Since we're closing the whole channel here, we *do* forward the close
  173. // down the pipeline.
  174. do {
  175. try self.stateMachine.closeOutbound()
  176. // Force a flush by calling _flush
  177. // (otherwise, we'd skip flushing if we're in a read loop)
  178. self._flush(context: context)
  179. context.close(mode: mode, promise: promise)
  180. } catch {
  181. promise?.fail(error)
  182. context.fireErrorCaught(error)
  183. }
  184. }
  185. }
  186. func flush(context: ChannelHandlerContext) {
  187. if self.isReading {
  188. // We don't want to flush yet if we're still in a read loop.
  189. self.flushPending = true
  190. return
  191. }
  192. self._flush(context: context)
  193. }
  194. private func _flush(context: ChannelHandlerContext) {
  195. do {
  196. loop: while true {
  197. switch try self.stateMachine.nextOutboundFrame() {
  198. case .sendFrame(let byteBuffer, let promise):
  199. self.flushPending = true
  200. context.write(
  201. self.wrapOutboundOut(.data(.init(data: .byteBuffer(byteBuffer)))),
  202. promise: promise
  203. )
  204. case .noMoreMessages:
  205. // Write an empty data frame with the EOS flag set, to signal the RPC
  206. // request is now finished.
  207. context.write(
  208. self.wrapOutboundOut(
  209. HTTP2Frame.FramePayload.data(
  210. .init(
  211. data: .byteBuffer(.init()),
  212. endStream: true
  213. )
  214. )
  215. ),
  216. promise: nil
  217. )
  218. context.flush()
  219. break loop
  220. case .awaitMoreMessages:
  221. if self.flushPending {
  222. self.flushPending = false
  223. context.flush()
  224. }
  225. break loop
  226. }
  227. }
  228. } catch {
  229. context.fireErrorCaught(error)
  230. }
  231. }
  232. }