ServerStreamingServerHandler.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * Copyright 2021, 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 NIO
  17. import NIOHPACK
  18. public final class ServerStreamingServerHandler<
  19. Serializer: MessageSerializer,
  20. Deserializer: MessageDeserializer
  21. >: GRPCServerHandlerProtocol {
  22. public typealias Request = Deserializer.Output
  23. public typealias Response = Serializer.Input
  24. /// A response serializer.
  25. @usableFromInline
  26. internal let serializer: Serializer
  27. /// A request deserializer.
  28. @usableFromInline
  29. internal let deserializer: Deserializer
  30. /// A pipeline of user provided interceptors.
  31. @usableFromInline
  32. internal var interceptors: ServerInterceptorPipeline<Request, Response>!
  33. /// The context required in order create the function.
  34. @usableFromInline
  35. internal let context: CallHandlerContext
  36. /// A reference to a `UserInfo`.
  37. @usableFromInline
  38. internal let userInfoRef: Ref<UserInfo>
  39. /// The user provided function to execute.
  40. @usableFromInline
  41. internal let userFunction: (Request, StreamingResponseCallContext<Response>)
  42. -> EventLoopFuture<GRPCStatus>
  43. /// The state of the handler.
  44. @usableFromInline
  45. internal var state: State = .idle
  46. @usableFromInline
  47. internal enum State {
  48. // Initial state. Nothing has happened yet.
  49. case idle
  50. // Headers have been received and now we're holding a context with which to invoke the user
  51. // function when we receive a message.
  52. case createdContext(_StreamingResponseCallContext<Request, Response>)
  53. // The user function has been invoked, we're waiting for the status promise to be completed.
  54. case invokedFunction(_StreamingResponseCallContext<Request, Response>)
  55. // The function has completed or we are no longer proceeding with execution (because of an error
  56. // or unexpected closure).
  57. case completed
  58. }
  59. @inlinable
  60. public init(
  61. context: CallHandlerContext,
  62. requestDeserializer: Deserializer,
  63. responseSerializer: Serializer,
  64. interceptors: [ServerInterceptor<Request, Response>],
  65. userFunction: @escaping (Request, StreamingResponseCallContext<Response>)
  66. -> EventLoopFuture<GRPCStatus>
  67. ) {
  68. self.serializer = responseSerializer
  69. self.deserializer = requestDeserializer
  70. self.context = context
  71. self.userFunction = userFunction
  72. let userInfoRef = Ref(UserInfo())
  73. self.userInfoRef = userInfoRef
  74. self.interceptors = ServerInterceptorPipeline(
  75. logger: context.logger,
  76. eventLoop: context.eventLoop,
  77. path: context.path,
  78. callType: .serverStreaming,
  79. remoteAddress: context.remoteAddress,
  80. userInfoRef: userInfoRef,
  81. interceptors: interceptors,
  82. onRequestPart: self.receiveInterceptedPart(_:),
  83. onResponsePart: self.sendInterceptedPart(_:promise:)
  84. )
  85. }
  86. // MARK: Public API; gRPC to Handler
  87. @inlinable
  88. public func receiveMetadata(_ headers: HPACKHeaders) {
  89. self.interceptors.receive(.metadata(headers))
  90. }
  91. @inlinable
  92. public func receiveMessage(_ bytes: ByteBuffer) {
  93. do {
  94. let message = try self.deserializer.deserialize(byteBuffer: bytes)
  95. self.interceptors.receive(.message(message))
  96. } catch {
  97. self.handleError(error)
  98. }
  99. }
  100. @inlinable
  101. public func receiveEnd() {
  102. self.interceptors.receive(.end)
  103. }
  104. @inlinable
  105. public func receiveError(_ error: Error) {
  106. self._finish(error: error)
  107. }
  108. @inlinable
  109. public func finish() {
  110. self._finish(error: nil)
  111. }
  112. @inlinable
  113. internal func _finish(error: Error?) {
  114. switch self.state {
  115. case .idle:
  116. self.interceptors = nil
  117. self.state = .completed
  118. case let .createdContext(context),
  119. let .invokedFunction(context):
  120. let error = error ?? GRPCStatus(code: .unavailable, message: nil)
  121. context.statusPromise.fail(error)
  122. case .completed:
  123. self.interceptors = nil
  124. }
  125. }
  126. // MARK: - Interceptors to User Function
  127. @inlinable
  128. internal func receiveInterceptedPart(_ part: GRPCServerRequestPart<Request>) {
  129. switch part {
  130. case let .metadata(headers):
  131. self.receiveInterceptedMetadata(headers)
  132. case let .message(message):
  133. self.receiveInterceptedMessage(message)
  134. case .end:
  135. // Ignored.
  136. ()
  137. }
  138. }
  139. @inlinable
  140. internal func receiveInterceptedMetadata(_ headers: HPACKHeaders) {
  141. switch self.state {
  142. case .idle:
  143. // Make a context to invoke the observer block factory with.
  144. let context = _StreamingResponseCallContext<Request, Response>(
  145. eventLoop: self.context.eventLoop,
  146. headers: headers,
  147. logger: self.context.logger,
  148. userInfoRef: self.userInfoRef,
  149. sendResponse: self.interceptResponse(_:metadata:promise:)
  150. )
  151. // Move to the next state.
  152. self.state = .createdContext(context)
  153. // Register a callback on the status future.
  154. context.statusPromise.futureResult.whenComplete(self.userFunctionCompletedWithResult(_:))
  155. // Send response headers back via the interceptors.
  156. self.interceptors.send(.metadata([:]), promise: nil)
  157. case .createdContext, .invokedFunction:
  158. self.handleError(GRPCError.InvalidState("Protocol violation: already received headers"))
  159. case .completed:
  160. // We may receive headers from the interceptor pipeline if we have already finished (i.e. due
  161. // to an error or otherwise) and an interceptor doing some async work later emitting headers.
  162. // Dropping them is fine.
  163. ()
  164. }
  165. }
  166. @inlinable
  167. internal func receiveInterceptedMessage(_ request: Request) {
  168. switch self.state {
  169. case .idle:
  170. self.handleError(
  171. GRPCError.InvalidState("Protocol violation: message received before headers")
  172. )
  173. case let .createdContext(context):
  174. self.state = .invokedFunction(context)
  175. // Complete the status promise with the function outcome.
  176. context.statusPromise.completeWith(self.userFunction(request, context))
  177. case .invokedFunction:
  178. self.handleError(GRPCError.InvalidState("Protocol violation: already received message"))
  179. case .completed:
  180. // We received a message but we're already done: this may happen if we terminate the RPC
  181. // due to a channel error, for example.
  182. ()
  183. }
  184. }
  185. // MARK: - User Function To Interceptors
  186. @inlinable
  187. internal func interceptResponse(
  188. _ response: Response,
  189. metadata: MessageMetadata,
  190. promise: EventLoopPromise<Void>?
  191. ) {
  192. switch self.state {
  193. case .idle:
  194. // The observer block can't send responses if it doesn't exist.
  195. preconditionFailure()
  196. case .createdContext, .invokedFunction:
  197. // The user has access to the response context before returning a future observer,
  198. // so 'createdContext' is valid here (if a little strange).
  199. self.interceptors.send(.message(response, metadata), promise: promise)
  200. case .completed:
  201. promise?.fail(GRPCError.AlreadyComplete())
  202. }
  203. }
  204. @inlinable
  205. internal func userFunctionCompletedWithResult(_ result: Result<GRPCStatus, Error>) {
  206. switch self.state {
  207. case .idle:
  208. // Invalid state: the user function can only completed if it was created.
  209. preconditionFailure()
  210. case let .createdContext(context),
  211. let .invokedFunction(context):
  212. self.state = .completed
  213. switch result {
  214. case let .success(status):
  215. self.interceptors.send(.end(status, context.trailers), promise: nil)
  216. case let .failure(error):
  217. let (status, trailers) = ServerErrorProcessor.processObserverError(
  218. error,
  219. headers: context.headers,
  220. trailers: context.trailers,
  221. delegate: self.context.errorDelegate
  222. )
  223. self.interceptors.send(.end(status, trailers), promise: nil)
  224. }
  225. case .completed:
  226. // We've already completed. Ignore this.
  227. ()
  228. }
  229. }
  230. @inlinable
  231. internal func sendInterceptedPart(
  232. _ part: GRPCServerResponsePart<Response>,
  233. promise: EventLoopPromise<Void>?
  234. ) {
  235. switch part {
  236. case let .metadata(headers):
  237. self.context.responseWriter.sendMetadata(headers, promise: promise)
  238. case let .message(message, metadata):
  239. do {
  240. let bytes = try self.serializer.serialize(message, allocator: ByteBufferAllocator())
  241. self.context.responseWriter.sendMessage(bytes, metadata: metadata, promise: promise)
  242. } catch {
  243. // Serialization failed: fail the promise and send end.
  244. promise?.fail(error)
  245. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  246. error,
  247. delegate: self.context.errorDelegate
  248. )
  249. // Loop back via the interceptors.
  250. self.interceptors.send(.end(status, trailers), promise: nil)
  251. }
  252. case let .end(status, trailers):
  253. self.context.responseWriter.sendEnd(status: status, trailers: trailers, promise: promise)
  254. }
  255. }
  256. @inlinable
  257. internal func handleError(_ error: Error) {
  258. switch self.state {
  259. case .idle:
  260. // We don't have a promise to fail. Just send back end.
  261. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  262. error,
  263. delegate: self.context.errorDelegate
  264. )
  265. self.interceptors.send(.end(status, trailers), promise: nil)
  266. case let .createdContext(context),
  267. let .invokedFunction(context):
  268. context.statusPromise.fail(error)
  269. case .completed:
  270. ()
  271. }
  272. }
  273. }