UnaryServerHandler.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 UnaryServerHandler<
  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, StatusOnlyCallContext) -> EventLoopFuture<Response>
  42. /// The state of the function invocation.
  43. @usableFromInline
  44. internal var state: State = .idle
  45. @usableFromInline
  46. internal enum State {
  47. // Initial state. Nothing has happened yet.
  48. case idle
  49. // Headers have been received and now we're holding a context with which to invoke the user
  50. // function when we receive a message.
  51. case createdContext(UnaryResponseCallContext<Response>)
  52. // The user function has been invoked, we're waiting for the response.
  53. case invokedFunction(UnaryResponseCallContext<Response>)
  54. // The function has completed or we are no longer proceeding with execution (because of an error
  55. // or unexpected closure).
  56. case completed
  57. }
  58. @inlinable
  59. public init(
  60. context: CallHandlerContext,
  61. requestDeserializer: Deserializer,
  62. responseSerializer: Serializer,
  63. interceptors: [ServerInterceptor<Request, Response>],
  64. userFunction: @escaping (Request, StatusOnlyCallContext) -> EventLoopFuture<Response>
  65. ) {
  66. self.userFunction = userFunction
  67. self.serializer = responseSerializer
  68. self.deserializer = requestDeserializer
  69. self.context = context
  70. let userInfoRef = Ref(UserInfo())
  71. self.userInfoRef = userInfoRef
  72. self.interceptors = ServerInterceptorPipeline(
  73. logger: context.logger,
  74. eventLoop: context.eventLoop,
  75. path: context.path,
  76. callType: .unary,
  77. remoteAddress: context.remoteAddress,
  78. userInfoRef: userInfoRef,
  79. interceptors: interceptors,
  80. onRequestPart: self.receiveInterceptedPart(_:),
  81. onResponsePart: self.sendInterceptedPart(_:promise:)
  82. )
  83. }
  84. // MARK: - Public API: gRPC to Interceptors
  85. @inlinable
  86. public func receiveMetadata(_ metadata: HPACKHeaders) {
  87. self.interceptors.receive(.metadata(metadata))
  88. }
  89. @inlinable
  90. public func receiveMessage(_ bytes: ByteBuffer) {
  91. do {
  92. let message = try self.deserializer.deserialize(byteBuffer: bytes)
  93. self.interceptors.receive(.message(message))
  94. } catch {
  95. self.handleError(error)
  96. }
  97. }
  98. @inlinable
  99. public func receiveEnd() {
  100. self.interceptors.receive(.end)
  101. }
  102. @inlinable
  103. public func receiveError(_ error: Error) {
  104. self.handleError(error)
  105. self.finish()
  106. }
  107. @inlinable
  108. public func finish() {
  109. switch self.state {
  110. case .idle:
  111. self.interceptors = nil
  112. self.state = .completed
  113. case let .createdContext(context),
  114. let .invokedFunction(context):
  115. context.responsePromise.fail(GRPCStatus(code: .unavailable, message: nil))
  116. case .completed:
  117. self.interceptors = nil
  118. }
  119. }
  120. // MARK: - Interceptors to User Function
  121. @inlinable
  122. internal func receiveInterceptedPart(_ part: GRPCServerRequestPart<Request>) {
  123. switch part {
  124. case let .metadata(headers):
  125. self.receiveInterceptedMetadata(headers)
  126. case let .message(message):
  127. self.receiveInterceptedMessage(message)
  128. case .end:
  129. self.receiveInterceptedEnd()
  130. }
  131. }
  132. @inlinable
  133. internal func receiveInterceptedMetadata(_ headers: HPACKHeaders) {
  134. switch self.state {
  135. case .idle:
  136. // Make a context to invoke the user function with.
  137. let context = UnaryResponseCallContext<Response>(
  138. eventLoop: self.context.eventLoop,
  139. headers: headers,
  140. logger: self.context.logger,
  141. userInfoRef: self.userInfoRef,
  142. closeFuture: self.context.closeFuture
  143. )
  144. // Move to the next state.
  145. self.state = .createdContext(context)
  146. // Register a callback on the response future. The user function will complete this promise.
  147. context.responsePromise.futureResult.whenComplete(self.userFunctionCompletedWithResult(_:))
  148. // Send back response headers.
  149. self.interceptors.send(.metadata([:]), promise: nil)
  150. case .createdContext, .invokedFunction:
  151. self.handleError(GRPCError.ProtocolViolation("Multiple header blocks received on RPC"))
  152. case .completed:
  153. // We may receive headers from the interceptor pipeline if we have already finished (i.e. due
  154. // to an error or otherwise) and an interceptor doing some async work later emitting headers.
  155. // Dropping them is fine.
  156. ()
  157. }
  158. }
  159. @inlinable
  160. internal func receiveInterceptedMessage(_ request: Request) {
  161. switch self.state {
  162. case .idle:
  163. self.handleError(GRPCError.ProtocolViolation("Message received before headers"))
  164. case let .createdContext(context):
  165. // Happy path: execute the function; complete the promise with the result.
  166. self.state = .invokedFunction(context)
  167. context.responsePromise.completeWith(self.userFunction(request, context))
  168. case .invokedFunction:
  169. // The function's already been invoked with a message.
  170. self.handleError(GRPCError.ProtocolViolation("Multiple messages received on unary RPC"))
  171. case .completed:
  172. // We received a message but we're already done: this may happen if we terminate the RPC
  173. // due to a channel error, for example.
  174. ()
  175. }
  176. }
  177. @inlinable
  178. internal func receiveInterceptedEnd() {
  179. switch self.state {
  180. case .idle:
  181. self.handleError(GRPCError.ProtocolViolation("End received before headers"))
  182. case .createdContext:
  183. self.handleError(GRPCError.ProtocolViolation("End received before message"))
  184. case .invokedFunction, .completed:
  185. ()
  186. }
  187. }
  188. // MARK: - User Function To Interceptors
  189. @inlinable
  190. internal func userFunctionCompletedWithResult(_ result: Result<Response, Error>) {
  191. switch self.state {
  192. case .idle:
  193. // Invalid state: the user function can only complete if it was executed.
  194. preconditionFailure()
  195. // 'created' is allowed here: we may have to (and tear down) after receiving headers
  196. // but before receiving a message.
  197. case let .createdContext(context),
  198. let .invokedFunction(context):
  199. switch result {
  200. case let .success(response):
  201. // Complete, as we're sending 'end'.
  202. self.state = .completed
  203. // Compression depends on whether it's enabled on the server and the setting in the caller
  204. // context.
  205. let compress = self.context.encoding.isEnabled && context.compressionEnabled
  206. let metadata = MessageMetadata(compress: compress, flush: false)
  207. self.interceptors.send(.message(response, metadata), promise: nil)
  208. self.interceptors.send(.end(context.responseStatus, context.trailers), promise: nil)
  209. case let .failure(error):
  210. self.handleError(error, thrownFromHandler: true)
  211. }
  212. case .completed:
  213. // We've already failed. Ignore this.
  214. ()
  215. }
  216. }
  217. @inlinable
  218. internal func sendInterceptedPart(
  219. _ part: GRPCServerResponsePart<Response>,
  220. promise: EventLoopPromise<Void>?
  221. ) {
  222. switch part {
  223. case let .metadata(headers):
  224. // We can delay this flush until the end of the RPC.
  225. self.context.responseWriter.sendMetadata(headers, flush: false, promise: promise)
  226. case let .message(message, metadata):
  227. do {
  228. let bytes = try self.serializer.serialize(message, allocator: self.context.allocator)
  229. self.context.responseWriter.sendMessage(bytes, metadata: metadata, promise: promise)
  230. } catch {
  231. // Serialization failed: fail the promise and send end.
  232. promise?.fail(error)
  233. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  234. error,
  235. delegate: self.context.errorDelegate
  236. )
  237. // Loop back via the interceptors.
  238. self.interceptors.send(.end(status, trailers), promise: nil)
  239. }
  240. case let .end(status, trailers):
  241. self.context.responseWriter.sendEnd(status: status, trailers: trailers, promise: promise)
  242. }
  243. }
  244. @inlinable
  245. internal func handleError(_ error: Error, thrownFromHandler isHandlerError: Bool = false) {
  246. switch self.state {
  247. case .idle:
  248. assert(!isHandlerError)
  249. self.state = .completed
  250. // We don't have a promise to fail. Just send back end.
  251. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  252. error,
  253. delegate: self.context.errorDelegate
  254. )
  255. self.interceptors.send(.end(status, trailers), promise: nil)
  256. case let .createdContext(context),
  257. let .invokedFunction(context):
  258. // We don't have a promise to fail. Just send back end.
  259. self.state = .completed
  260. let status: GRPCStatus
  261. let trailers: HPACKHeaders
  262. if isHandlerError {
  263. (status, trailers) = ServerErrorProcessor.processObserverError(
  264. error,
  265. headers: context.headers,
  266. trailers: context.trailers,
  267. delegate: self.context.errorDelegate
  268. )
  269. } else {
  270. (status, trailers) = ServerErrorProcessor.processLibraryError(
  271. error,
  272. delegate: self.context.errorDelegate
  273. )
  274. }
  275. self.interceptors.send(.end(status, trailers), promise: nil)
  276. // We're already in the 'completed' state so failing the promise will be a no-op in the
  277. // callback to 'userFunctionCompletedWithResult' (but we also need to avoid leaking the
  278. // promise.)
  279. context.responsePromise.fail(error)
  280. case .completed:
  281. ()
  282. }
  283. }
  284. }