UnaryCallHandler.swift 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import SwiftProtobuf
  18. import NIO
  19. import NIOHTTP1
  20. import Logging
  21. /// Handles unary calls. Calls the observer block with the request message.
  22. ///
  23. /// - The observer block is implemented by the framework user and returns a future containing the call result.
  24. /// - To return a response to the client, the framework user should complete that future
  25. /// (similar to e.g. serving regular HTTP requests in frameworks such as Vapor).
  26. public final class UnaryCallHandler<
  27. RequestMessage: Message,
  28. ResponseMessage: Message
  29. >: _BaseCallHandler<RequestMessage, ResponseMessage> {
  30. public typealias EventObserver = (RequestMessage) -> EventLoopFuture<ResponseMessage>
  31. private var eventObserver: EventObserver?
  32. private var callContext: UnaryResponseCallContext<ResponseMessage>?
  33. public init(
  34. callHandlerContext: CallHandlerContext,
  35. eventObserverFactory: (UnaryResponseCallContext<ResponseMessage>) -> EventObserver
  36. ) {
  37. super.init(callHandlerContext: callHandlerContext)
  38. let callContext = UnaryResponseCallContextImpl<ResponseMessage>(
  39. channel: self.callHandlerContext.channel,
  40. request: self.callHandlerContext.request,
  41. errorDelegate: self.callHandlerContext.errorDelegate,
  42. logger: self.callHandlerContext.logger
  43. )
  44. self.callContext = callContext
  45. self.eventObserver = eventObserverFactory(callContext)
  46. callContext.responsePromise.futureResult.whenComplete { _ in
  47. // When done, reset references to avoid retain cycles.
  48. self.eventObserver = nil
  49. self.callContext = nil
  50. }
  51. }
  52. internal override func processMessage(_ message: RequestMessage) throws {
  53. guard let eventObserver = self.eventObserver,
  54. let context = self.callContext else {
  55. self.logger.error("processMessage(_:) called before the call started or after the call completed")
  56. throw GRPCError.server(.tooManyRequests)
  57. }
  58. let resultFuture = eventObserver(message)
  59. resultFuture
  60. // Fulfil the response promise with whatever response (or error) the framework user has provided.
  61. .cascade(to: context.responsePromise)
  62. self.eventObserver = nil
  63. }
  64. internal override func endOfStreamReceived() throws {
  65. if self.eventObserver != nil {
  66. throw GRPCError.server(.noRequestsButOneExpected)
  67. }
  68. }
  69. internal override func sendErrorStatus(_ status: GRPCStatus) {
  70. callContext?.responsePromise.fail(status)
  71. }
  72. }