ServerStreamingServerHandler.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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.handleError(error)
  107. self.finish()
  108. }
  109. @inlinable
  110. public func finish() {
  111. switch self.state {
  112. case .idle:
  113. self.interceptors = nil
  114. self.state = .completed
  115. case let .createdContext(context),
  116. let .invokedFunction(context):
  117. context.statusPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  118. case .completed:
  119. self.interceptors = nil
  120. }
  121. }
  122. // MARK: - Interceptors to User Function
  123. @inlinable
  124. internal func receiveInterceptedPart(_ part: GRPCServerRequestPart<Request>) {
  125. switch part {
  126. case let .metadata(headers):
  127. self.receiveInterceptedMetadata(headers)
  128. case let .message(message):
  129. self.receiveInterceptedMessage(message)
  130. case .end:
  131. self.receiveInterceptedEnd()
  132. }
  133. }
  134. @inlinable
  135. internal func receiveInterceptedMetadata(_ headers: HPACKHeaders) {
  136. switch self.state {
  137. case .idle:
  138. // Make a context to invoke the observer block factory with.
  139. let context = _StreamingResponseCallContext<Request, Response>(
  140. eventLoop: self.context.eventLoop,
  141. headers: headers,
  142. logger: self.context.logger,
  143. userInfoRef: self.userInfoRef,
  144. compressionIsEnabled: self.context.encoding.isEnabled,
  145. closeFuture: self.context.closeFuture,
  146. sendResponse: self.interceptResponse(_:metadata:promise:)
  147. )
  148. // Move to the next state.
  149. self.state = .createdContext(context)
  150. // Register a callback on the status future.
  151. context.statusPromise.futureResult.whenComplete(self.userFunctionCompletedWithResult(_:))
  152. // Send response headers back via the interceptors.
  153. self.interceptors.send(.metadata([:]), promise: nil)
  154. case .createdContext, .invokedFunction:
  155. self.handleError(GRPCError.InvalidState("Protocol violation: already received headers"))
  156. case .completed:
  157. // We may receive headers from the interceptor pipeline if we have already finished (i.e. due
  158. // to an error or otherwise) and an interceptor doing some async work later emitting headers.
  159. // Dropping them is fine.
  160. ()
  161. }
  162. }
  163. @inlinable
  164. internal func receiveInterceptedMessage(_ request: Request) {
  165. switch self.state {
  166. case .idle:
  167. self.handleError(GRPCError.ProtocolViolation("Message received before headers"))
  168. case let .createdContext(context):
  169. self.state = .invokedFunction(context)
  170. // Complete the status promise with the function outcome.
  171. context.statusPromise.completeWith(self.userFunction(request, context))
  172. case .invokedFunction:
  173. let error = GRPCError.ProtocolViolation("Multiple messages received on server streaming RPC")
  174. self.handleError(error)
  175. case .completed:
  176. // We received a message but we're already done: this may happen if we terminate the RPC
  177. // due to a channel error, for example.
  178. ()
  179. }
  180. }
  181. @inlinable
  182. internal func receiveInterceptedEnd() {
  183. switch self.state {
  184. case .idle:
  185. self.handleError(GRPCError.ProtocolViolation("End received before headers"))
  186. case .createdContext:
  187. self.handleError(GRPCError.ProtocolViolation("End received before message"))
  188. case .invokedFunction, .completed:
  189. ()
  190. }
  191. }
  192. // MARK: - User Function To Interceptors
  193. @inlinable
  194. internal func interceptResponse(
  195. _ response: Response,
  196. metadata: MessageMetadata,
  197. promise: EventLoopPromise<Void>?
  198. ) {
  199. switch self.state {
  200. case .idle:
  201. // The observer block can't send responses if it doesn't exist.
  202. preconditionFailure()
  203. case .createdContext, .invokedFunction:
  204. // The user has access to the response context before returning a future observer,
  205. // so 'createdContext' is valid here (if a little strange).
  206. self.interceptors.send(.message(response, metadata), promise: promise)
  207. case .completed:
  208. promise?.fail(GRPCError.AlreadyComplete())
  209. }
  210. }
  211. @inlinable
  212. internal func userFunctionCompletedWithResult(_ result: Result<GRPCStatus, Error>) {
  213. switch self.state {
  214. case .idle:
  215. // Invalid state: the user function can only completed if it was created.
  216. preconditionFailure()
  217. case let .createdContext(context),
  218. let .invokedFunction(context):
  219. switch result {
  220. case let .success(status):
  221. // We're sending end back, we're done.
  222. self.state = .completed
  223. self.interceptors.send(.end(status, context.trailers), promise: nil)
  224. case let .failure(error):
  225. self.handleError(error, thrownFromHandler: true)
  226. }
  227. case .completed:
  228. // We've already completed. Ignore this.
  229. ()
  230. }
  231. }
  232. @inlinable
  233. internal func sendInterceptedPart(
  234. _ part: GRPCServerResponsePart<Response>,
  235. promise: EventLoopPromise<Void>?
  236. ) {
  237. switch part {
  238. case let .metadata(headers):
  239. self.context.responseWriter.sendMetadata(headers, flush: true, promise: promise)
  240. case let .message(message, metadata):
  241. do {
  242. let bytes = try self.serializer.serialize(message, allocator: self.context.allocator)
  243. self.context.responseWriter.sendMessage(bytes, metadata: metadata, promise: promise)
  244. } catch {
  245. // Serialization failed: fail the promise and send end.
  246. promise?.fail(error)
  247. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  248. error,
  249. delegate: self.context.errorDelegate
  250. )
  251. // Loop back via the interceptors.
  252. self.interceptors.send(.end(status, trailers), promise: nil)
  253. }
  254. case let .end(status, trailers):
  255. self.context.responseWriter.sendEnd(status: status, trailers: trailers, promise: promise)
  256. }
  257. }
  258. @inlinable
  259. internal func handleError(_ error: Error, thrownFromHandler isHandlerError: Bool = false) {
  260. switch self.state {
  261. case .idle:
  262. assert(!isHandlerError)
  263. self.state = .completed
  264. // We don't have a promise to fail. Just send back end.
  265. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  266. error,
  267. delegate: self.context.errorDelegate
  268. )
  269. self.interceptors.send(.end(status, trailers), promise: nil)
  270. case let .createdContext(context),
  271. let .invokedFunction(context):
  272. // We don't have a promise to fail. Just send back end.
  273. self.state = .completed
  274. let status: GRPCStatus
  275. let trailers: HPACKHeaders
  276. if isHandlerError {
  277. (status, trailers) = ServerErrorProcessor.processObserverError(
  278. error,
  279. headers: context.headers,
  280. trailers: context.trailers,
  281. delegate: self.context.errorDelegate
  282. )
  283. } else {
  284. (status, trailers) = ServerErrorProcessor.processLibraryError(
  285. error,
  286. delegate: self.context.errorDelegate
  287. )
  288. }
  289. self.interceptors.send(.end(status, trailers), promise: nil)
  290. // We're already in the 'completed' state so failing the promise will be a no-op in the
  291. // callback to 'userFunctionCompletedWithResult' (but we also need to avoid leaking the
  292. // promise.)
  293. context.statusPromise.fail(error)
  294. case .completed:
  295. ()
  296. }
  297. }
  298. }