GRPCServerStreamHandler.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. package import GRPCCore
  17. package import NIOCore
  18. package import NIOHTTP2
  19. package final class GRPCServerStreamHandler: ChannelDuplexHandler, RemovableChannelHandler {
  20. package typealias InboundIn = HTTP2Frame.FramePayload
  21. package typealias InboundOut = RPCRequestPart<GRPCNIOTransportBytes>
  22. package typealias OutboundIn = RPCResponsePart<GRPCNIOTransportBytes>
  23. package typealias OutboundOut = HTTP2Frame.FramePayload
  24. private var stateMachine: GRPCStreamStateMachine
  25. private let eventLoop: any EventLoop
  26. private var isReading = false
  27. private var flushPending = false
  28. private var isCancelled = false
  29. // We buffer the final status + trailers to avoid reordering issues (i.e.,
  30. // if there are messages still not written into the channel because flush has
  31. // not been called, but the server sends back trailers).
  32. private var pendingTrailers:
  33. (trailers: HTTP2Frame.FramePayload, promise: EventLoopPromise<Void>?)?
  34. private let methodDescriptorPromise: EventLoopPromise<MethodDescriptor>
  35. private var cancellationHandle: Optional<ServerContext.RPCCancellationHandle>
  36. package let connectionManagementHandler: ServerConnectionManagementHandler.SyncView
  37. // Existential errors unconditionally allocate, avoid this per-use allocation by doing it
  38. // statically.
  39. private static let handlerRemovedBeforeDescriptorResolved: any Error = RPCError(
  40. code: .unavailable,
  41. message: "RPC stream was closed before we got any Metadata."
  42. )
  43. package init(
  44. scheme: Scheme,
  45. acceptedEncodings: CompressionAlgorithmSet,
  46. maxPayloadSize: Int,
  47. methodDescriptorPromise: EventLoopPromise<MethodDescriptor>,
  48. eventLoop: any EventLoop,
  49. connectionManagementHandler: ServerConnectionManagementHandler.SyncView,
  50. cancellationHandler: ServerContext.RPCCancellationHandle? = nil,
  51. skipStateMachineAssertions: Bool = false
  52. ) {
  53. self.stateMachine = .init(
  54. configuration: .server(.init(scheme: scheme, acceptedEncodings: acceptedEncodings)),
  55. maxPayloadSize: maxPayloadSize,
  56. skipAssertions: skipStateMachineAssertions
  57. )
  58. self.methodDescriptorPromise = methodDescriptorPromise
  59. self.cancellationHandle = cancellationHandler
  60. self.eventLoop = eventLoop
  61. self.connectionManagementHandler = connectionManagementHandler
  62. }
  63. package func setCancellationHandle(_ handle: ServerContext.RPCCancellationHandle) {
  64. if self.eventLoop.inEventLoop {
  65. self.syncSetCancellationHandle(handle)
  66. } else {
  67. let loopBoundSelf = NIOLoopBound(self, eventLoop: self.eventLoop)
  68. self.eventLoop.execute {
  69. loopBoundSelf.value.syncSetCancellationHandle(handle)
  70. }
  71. }
  72. }
  73. private func syncSetCancellationHandle(_ handle: ServerContext.RPCCancellationHandle) {
  74. assert(self.cancellationHandle == nil, "\(#function) must only be called once")
  75. if self.isCancelled {
  76. handle.cancel()
  77. } else {
  78. self.cancellationHandle = handle
  79. }
  80. }
  81. private func cancelRPC() {
  82. if let handle = self.cancellationHandle.take() {
  83. handle.cancel()
  84. } else {
  85. self.isCancelled = true
  86. }
  87. }
  88. }
  89. // - MARK: ChannelInboundHandler
  90. extension GRPCServerStreamHandler {
  91. package func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  92. switch event {
  93. case is ChannelShouldQuiesceEvent:
  94. self.cancelRPC()
  95. default:
  96. ()
  97. }
  98. context.fireUserInboundEventTriggered(event)
  99. }
  100. package func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  101. self.isReading = true
  102. let frame = self.unwrapInboundIn(data)
  103. switch frame {
  104. case .data(let frameData):
  105. let endStream = frameData.endStream
  106. switch frameData.data {
  107. case .byteBuffer(let buffer):
  108. do {
  109. switch try self.stateMachine.receive(buffer: buffer, endStream: endStream) {
  110. case .endRPCAndForwardErrorStatus_clientOnly:
  111. preconditionFailure(
  112. "OnBufferReceivedAction.endRPCAndForwardErrorStatus should never be returned for the server."
  113. )
  114. case .forwardErrorAndClose_serverOnly(let error):
  115. context.fireErrorCaught(error)
  116. context.close(mode: .all, promise: nil)
  117. case .readInbound:
  118. loop: while true {
  119. switch self.stateMachine.nextInboundMessage() {
  120. case .receiveMessage(let message):
  121. let wrapped = GRPCNIOTransportBytes(message)
  122. context.fireChannelRead(self.wrapInboundOut(.message(wrapped)))
  123. case .awaitMoreMessages:
  124. break loop
  125. case .noMoreMessages:
  126. context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
  127. break loop
  128. }
  129. }
  130. case .doNothing:
  131. ()
  132. }
  133. } catch let invalidState {
  134. let error = RPCError(invalidState)
  135. context.fireErrorCaught(error)
  136. }
  137. case .fileRegion:
  138. preconditionFailure("Unexpected IOData.fileRegion")
  139. }
  140. case .headers(let headers):
  141. do {
  142. let action = try self.stateMachine.receive(
  143. headers: headers.headers,
  144. endStream: headers.endStream
  145. )
  146. switch action {
  147. case .receivedMetadata(let metadata, let methodDescriptor):
  148. if let methodDescriptor = methodDescriptor {
  149. self.methodDescriptorPromise.succeed(methodDescriptor)
  150. context.fireChannelRead(self.wrapInboundOut(.metadata(metadata)))
  151. } else {
  152. assertionFailure("Method descriptor should have been present if we received metadata.")
  153. }
  154. case .rejectRPC_serverOnly(let trailers):
  155. self.flushPending = true
  156. self.methodDescriptorPromise.fail(
  157. RPCError(
  158. code: .unavailable,
  159. message: "RPC was rejected."
  160. )
  161. )
  162. let response = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true))
  163. context.write(self.wrapOutboundOut(response), promise: nil)
  164. case .receivedStatusAndMetadata_clientOnly:
  165. assertionFailure("Unexpected action")
  166. case .protocolViolation_serverOnly:
  167. context.writeAndFlush(self.wrapOutboundOut(.rstStream(.protocolError)), promise: nil)
  168. context.close(promise: nil)
  169. case .doNothing:
  170. ()
  171. }
  172. } catch let invalidState {
  173. let error = RPCError(invalidState)
  174. context.fireErrorCaught(error)
  175. }
  176. case .rstStream:
  177. self.handleUnexpectedInboundClose(context: context, reason: .streamReset)
  178. case .ping, .goAway, .priority, .settings, .pushPromise, .windowUpdate,
  179. .alternativeService, .origin:
  180. ()
  181. }
  182. }
  183. package func channelReadComplete(context: ChannelHandlerContext) {
  184. self.isReading = false
  185. if self.flushPending {
  186. self.flushPending = false
  187. context.flush()
  188. }
  189. context.fireChannelReadComplete()
  190. }
  191. package func handlerRemoved(context: ChannelHandlerContext) {
  192. self.stateMachine.tearDown()
  193. self.methodDescriptorPromise.fail(Self.handlerRemovedBeforeDescriptorResolved)
  194. }
  195. package func channelInactive(context: ChannelHandlerContext) {
  196. self.handleUnexpectedInboundClose(context: context, reason: .channelInactive)
  197. context.fireChannelInactive()
  198. }
  199. package func errorCaught(context: ChannelHandlerContext, error: any Error) {
  200. self.handleUnexpectedInboundClose(context: context, reason: .errorThrown(error))
  201. }
  202. private func handleUnexpectedInboundClose(
  203. context: ChannelHandlerContext,
  204. reason: GRPCStreamStateMachine.UnexpectedInboundCloseReason
  205. ) {
  206. switch self.stateMachine.unexpectedInboundClose(reason: reason) {
  207. case .fireError_serverOnly(let wrappedError):
  208. self.cancelRPC()
  209. context.fireErrorCaught(wrappedError)
  210. case .doNothing:
  211. ()
  212. case .forwardStatus_clientOnly:
  213. assertionFailure(
  214. "`forwardStatus` should only happen on the client side, never on the server."
  215. )
  216. }
  217. }
  218. }
  219. // - MARK: ChannelOutboundHandler
  220. extension GRPCServerStreamHandler {
  221. package func write(
  222. context: ChannelHandlerContext,
  223. data: NIOAny,
  224. promise: EventLoopPromise<Void>?
  225. ) {
  226. let frame = self.unwrapOutboundIn(data)
  227. switch frame {
  228. case .metadata(let metadata):
  229. do {
  230. self.flushPending = true
  231. let headers = try self.stateMachine.send(metadata: metadata)
  232. context.write(self.wrapOutboundOut(.headers(.init(headers: headers))), promise: promise)
  233. self.connectionManagementHandler.wroteHeadersFrame()
  234. } catch let invalidState {
  235. let error = RPCError(invalidState)
  236. promise?.fail(error)
  237. context.fireErrorCaught(error)
  238. }
  239. case .message(let message):
  240. do {
  241. try self.stateMachine.send(message: message.buffer, promise: promise)
  242. self.connectionManagementHandler.wroteDataFrame()
  243. } catch let invalidState {
  244. let error = RPCError(invalidState)
  245. promise?.fail(error)
  246. context.fireErrorCaught(error)
  247. }
  248. case .status(let status, let metadata):
  249. do {
  250. let headers = try self.stateMachine.send(status: status, metadata: metadata)
  251. let response = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: true))
  252. self.pendingTrailers = (response, promise)
  253. } catch let invalidState {
  254. let error = RPCError(invalidState)
  255. promise?.fail(error)
  256. context.fireErrorCaught(error)
  257. }
  258. }
  259. }
  260. package func flush(context: ChannelHandlerContext) {
  261. if self.isReading {
  262. // We don't want to flush yet if we're still in a read loop.
  263. return
  264. }
  265. do {
  266. loop: while true {
  267. switch try self.stateMachine.nextOutboundFrame() {
  268. case .sendFrame(let byteBuffer, let promise):
  269. self.flushPending = true
  270. context.write(
  271. self.wrapOutboundOut(.data(.init(data: .byteBuffer(byteBuffer)))),
  272. promise: promise
  273. )
  274. case .noMoreMessages:
  275. if let pendingTrailers = self.pendingTrailers {
  276. self.flushPending = true
  277. self.pendingTrailers = nil
  278. context.write(
  279. self.wrapOutboundOut(pendingTrailers.trailers),
  280. promise: pendingTrailers.promise
  281. )
  282. }
  283. break loop
  284. case .awaitMoreMessages:
  285. break loop
  286. case .closeAndFailPromise(let promise, let error):
  287. context.close(mode: .all, promise: nil)
  288. promise?.fail(error)
  289. }
  290. }
  291. if self.flushPending {
  292. self.flushPending = false
  293. context.flush()
  294. }
  295. } catch let invalidState {
  296. let error = RPCError(invalidState)
  297. context.fireErrorCaught(error)
  298. }
  299. }
  300. }