GRPCServerStreamHandler.swift 11 KB

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