GRPCClientStreamHandler.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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: GRPCStreamStateMachineConfiguration.Scheme,
  31. outboundEncoding: CompressionAlgorithm,
  32. acceptedEncodings: CompressionAlgorithmSet,
  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. case .doNothing:
  82. ()
  83. }
  84. } catch {
  85. context.fireErrorCaught(error)
  86. }
  87. case .fileRegion:
  88. preconditionFailure("Unexpected IOData.fileRegion")
  89. }
  90. case .headers(let headers):
  91. do {
  92. let action = try self.stateMachine.receive(
  93. headers: headers.headers,
  94. endStream: headers.endStream
  95. )
  96. switch action {
  97. case .receivedMetadata(let metadata, _):
  98. context.fireChannelRead(self.wrapInboundOut(.metadata(metadata)))
  99. case .rejectRPC:
  100. throw RPCError(
  101. code: .internalError,
  102. message: "Client cannot get rejectRPC."
  103. )
  104. case .receivedStatusAndMetadata(let status, let metadata):
  105. context.fireChannelRead(self.wrapInboundOut(.status(status, metadata)))
  106. context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
  107. case .protocolViolation:
  108. // Should only happen for servers
  109. assertionFailure("Unexpected protocol violation")
  110. case .doNothing:
  111. ()
  112. }
  113. } catch {
  114. context.fireErrorCaught(error)
  115. }
  116. case .ping, .goAway, .priority, .rstStream, .settings, .pushPromise, .windowUpdate,
  117. .alternativeService, .origin:
  118. ()
  119. }
  120. }
  121. func channelReadComplete(context: ChannelHandlerContext) {
  122. self.isReading = false
  123. if self.flushPending {
  124. self.flushPending = false
  125. self.flush(context: context)
  126. }
  127. context.fireChannelReadComplete()
  128. }
  129. func handlerRemoved(context: ChannelHandlerContext) {
  130. self.stateMachine.tearDown()
  131. }
  132. }
  133. // - MARK: ChannelOutboundHandler
  134. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  135. extension GRPCClientStreamHandler {
  136. func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  137. switch self.unwrapOutboundIn(data) {
  138. case .metadata(let metadata):
  139. do {
  140. self.flushPending = true
  141. let headers = try self.stateMachine.send(metadata: metadata)
  142. context.write(self.wrapOutboundOut(.headers(.init(headers: headers))), promise: promise)
  143. } catch {
  144. promise?.fail(error)
  145. context.fireErrorCaught(error)
  146. }
  147. case .message(let message):
  148. do {
  149. try self.stateMachine.send(message: message, promise: promise)
  150. } catch {
  151. promise?.fail(error)
  152. context.fireErrorCaught(error)
  153. }
  154. }
  155. }
  156. func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
  157. switch mode {
  158. case .input:
  159. context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
  160. promise?.succeed()
  161. case .output:
  162. // We flush all pending messages and update the internal state machine's
  163. // state, but we don't close the outbound end of the channel, because
  164. // forwarding the close in this case would cause the HTTP2 stream handler
  165. // to close the whole channel (as the mode is ignored in its implementation).
  166. do {
  167. try self.stateMachine.closeOutbound()
  168. // Force a flush by calling _flush instead of flush
  169. // (otherwise, we'd skip flushing if we're in a read loop)
  170. self._flush(context: context)
  171. promise?.succeed()
  172. } catch {
  173. promise?.fail(error)
  174. context.fireErrorCaught(error)
  175. }
  176. case .all:
  177. // Since we're closing the whole channel here, we *do* forward the close
  178. // down the pipeline.
  179. do {
  180. try self.stateMachine.closeOutbound()
  181. // Force a flush by calling _flush
  182. // (otherwise, we'd skip flushing if we're in a read loop)
  183. self._flush(context: context)
  184. context.close(mode: mode, promise: promise)
  185. } catch {
  186. promise?.fail(error)
  187. context.fireErrorCaught(error)
  188. }
  189. }
  190. }
  191. func flush(context: ChannelHandlerContext) {
  192. if self.isReading {
  193. // We don't want to flush yet if we're still in a read loop.
  194. self.flushPending = true
  195. return
  196. }
  197. self._flush(context: context)
  198. }
  199. private func _flush(context: ChannelHandlerContext) {
  200. do {
  201. loop: while true {
  202. switch try self.stateMachine.nextOutboundFrame() {
  203. case .sendFrame(let byteBuffer, let promise):
  204. self.flushPending = true
  205. context.write(
  206. self.wrapOutboundOut(.data(.init(data: .byteBuffer(byteBuffer)))),
  207. promise: promise
  208. )
  209. case .noMoreMessages:
  210. // Write an empty data frame with the EOS flag set, to signal the RPC
  211. // request is now finished.
  212. context.write(
  213. self.wrapOutboundOut(
  214. HTTP2Frame.FramePayload.data(
  215. .init(
  216. data: .byteBuffer(.init()),
  217. endStream: true
  218. )
  219. )
  220. ),
  221. promise: nil
  222. )
  223. context.flush()
  224. break loop
  225. case .awaitMoreMessages:
  226. if self.flushPending {
  227. self.flushPending = false
  228. context.flush()
  229. }
  230. break loop
  231. }
  232. }
  233. } catch {
  234. context.fireErrorCaught(error)
  235. }
  236. }
  237. }