UnaryServerHandler.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. )
  143. // Move to the next state.
  144. self.state = .createdContext(context)
  145. // Register a callback on the response future. The user function will complete this promise.
  146. context.responsePromise.futureResult.whenComplete(self.userFunctionCompletedWithResult(_:))
  147. // Send back response headers.
  148. self.interceptors.send(.metadata([:]), promise: nil)
  149. case .createdContext, .invokedFunction:
  150. self.handleError(GRPCError.ProtocolViolation("Multiple header blocks received on RPC"))
  151. case .completed:
  152. // We may receive headers from the interceptor pipeline if we have already finished (i.e. due
  153. // to an error or otherwise) and an interceptor doing some async work later emitting headers.
  154. // Dropping them is fine.
  155. ()
  156. }
  157. }
  158. @inlinable
  159. internal func receiveInterceptedMessage(_ request: Request) {
  160. switch self.state {
  161. case .idle:
  162. self.handleError(GRPCError.ProtocolViolation("Message received before headers"))
  163. case let .createdContext(context):
  164. // Happy path: execute the function; complete the promise with the result.
  165. self.state = .invokedFunction(context)
  166. context.responsePromise.completeWith(self.userFunction(request, context))
  167. case .invokedFunction:
  168. // The function's already been invoked with a message.
  169. self.handleError(GRPCError.ProtocolViolation("Multiple messages received on unary RPC"))
  170. case .completed:
  171. // We received a message but we're already done: this may happen if we terminate the RPC
  172. // due to a channel error, for example.
  173. ()
  174. }
  175. }
  176. @inlinable
  177. internal func receiveInterceptedEnd() {
  178. switch self.state {
  179. case .idle:
  180. self.handleError(GRPCError.ProtocolViolation("End received before headers"))
  181. case .createdContext:
  182. self.handleError(GRPCError.ProtocolViolation("End received before message"))
  183. case .invokedFunction, .completed:
  184. ()
  185. }
  186. }
  187. // MARK: - User Function To Interceptors
  188. @inlinable
  189. internal func userFunctionCompletedWithResult(_ result: Result<Response, Error>) {
  190. switch self.state {
  191. case .idle:
  192. // Invalid state: the user function can only complete if it was executed.
  193. preconditionFailure()
  194. // 'created' is allowed here: we may have to (and tear down) after receiving headers
  195. // but before receiving a message.
  196. case let .createdContext(context),
  197. let .invokedFunction(context):
  198. switch result {
  199. case let .success(response):
  200. // Complete, as we're sending 'end'.
  201. self.state = .completed
  202. // Compression depends on whether it's enabled on the server and the setting in the caller
  203. // context.
  204. let compress = self.context.encoding.isEnabled && context.compressionEnabled
  205. let metadata = MessageMetadata(compress: compress, flush: false)
  206. self.interceptors.send(.message(response, metadata), promise: nil)
  207. self.interceptors.send(.end(context.responseStatus, context.trailers), promise: nil)
  208. case let .failure(error):
  209. self.handleError(error, thrownFromHandler: true)
  210. }
  211. case .completed:
  212. // We've already failed. Ignore this.
  213. ()
  214. }
  215. }
  216. @inlinable
  217. internal func sendInterceptedPart(
  218. _ part: GRPCServerResponsePart<Response>,
  219. promise: EventLoopPromise<Void>?
  220. ) {
  221. switch part {
  222. case let .metadata(headers):
  223. // We can delay this flush until the end of the RPC.
  224. self.context.responseWriter.sendMetadata(headers, flush: false, promise: promise)
  225. case let .message(message, metadata):
  226. do {
  227. let bytes = try self.serializer.serialize(message, allocator: self.context.allocator)
  228. self.context.responseWriter.sendMessage(bytes, metadata: metadata, promise: promise)
  229. } catch {
  230. // Serialization failed: fail the promise and send end.
  231. promise?.fail(error)
  232. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  233. error,
  234. delegate: self.context.errorDelegate
  235. )
  236. // Loop back via the interceptors.
  237. self.interceptors.send(.end(status, trailers), promise: nil)
  238. }
  239. case let .end(status, trailers):
  240. self.context.responseWriter.sendEnd(status: status, trailers: trailers, promise: promise)
  241. }
  242. }
  243. @inlinable
  244. internal func handleError(_ error: Error, thrownFromHandler isHandlerError: Bool = false) {
  245. switch self.state {
  246. case .idle:
  247. assert(!isHandlerError)
  248. self.state = .completed
  249. // We don't have a promise to fail. Just send back end.
  250. let (status, trailers) = ServerErrorProcessor.processLibraryError(
  251. error,
  252. delegate: self.context.errorDelegate
  253. )
  254. self.interceptors.send(.end(status, trailers), promise: nil)
  255. case let .createdContext(context),
  256. let .invokedFunction(context):
  257. // We don't have a promise to fail. Just send back end.
  258. self.state = .completed
  259. let status: GRPCStatus
  260. let trailers: HPACKHeaders
  261. if isHandlerError {
  262. (status, trailers) = ServerErrorProcessor.processObserverError(
  263. error,
  264. headers: context.headers,
  265. trailers: context.trailers,
  266. delegate: self.context.errorDelegate
  267. )
  268. } else {
  269. (status, trailers) = ServerErrorProcessor.processLibraryError(
  270. error,
  271. delegate: self.context.errorDelegate
  272. )
  273. }
  274. self.interceptors.send(.end(status, trailers), promise: nil)
  275. // We're already in the 'completed' state so failing the promise will be a no-op in the
  276. // callback to 'userFunctionCompletedWithResult' (but we also need to avoid leaking the
  277. // promise.)
  278. context.responsePromise.fail(error)
  279. case .completed:
  280. ()
  281. }
  282. }
  283. }