ServerStreamingServerHandler.swift 11 KB

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