UnaryCallHandler.swift 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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<RequestPayload, ResponsePayload>: _BaseCallHandler<RequestPayload, ResponsePayload> {
  27. public typealias EventObserver = (RequestPayload) -> EventLoopFuture<ResponsePayload>
  28. private var eventObserver: EventObserver?
  29. private var callContext: UnaryResponseCallContext<ResponsePayload>?
  30. private let eventObserverFactory: (UnaryResponseCallContext<ResponsePayload>) -> EventObserver
  31. internal init<Serializer: MessageSerializer, Deserializer: MessageDeserializer>(
  32. serializer: Serializer,
  33. deserializer: Deserializer,
  34. callHandlerContext: CallHandlerContext,
  35. eventObserverFactory: @escaping (UnaryResponseCallContext<ResponsePayload>) -> EventObserver
  36. ) where Serializer.Input == ResponsePayload, Deserializer.Output == RequestPayload {
  37. self.eventObserverFactory = eventObserverFactory
  38. super.init(
  39. callHandlerContext: callHandlerContext,
  40. codec: GRPCServerCodecHandler(serializer: serializer, deserializer: deserializer)
  41. )
  42. }
  43. internal override func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  44. let callContext = UnaryResponseCallContextImpl<ResponsePayload>(
  45. channel: context.channel,
  46. request: head,
  47. errorDelegate: self.errorDelegate,
  48. logger: self.logger
  49. )
  50. self.callContext = callContext
  51. self.eventObserver = self.eventObserverFactory(callContext)
  52. callContext.responsePromise.futureResult.whenComplete { _ in
  53. // When done, reset references to avoid retain cycles.
  54. self.eventObserver = nil
  55. self.callContext = nil
  56. }
  57. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  58. }
  59. internal override func processMessage(_ message: RequestPayload) throws {
  60. guard let eventObserver = self.eventObserver,
  61. let context = self.callContext else {
  62. self.logger.error("processMessage(_:) called before the call started or after the call completed")
  63. throw GRPCError.StreamCardinalityViolation.request.captureContext()
  64. }
  65. let resultFuture = eventObserver(message)
  66. resultFuture
  67. // Fulfil the response promise with whatever response (or error) the framework user has provided.
  68. .cascade(to: context.responsePromise)
  69. self.eventObserver = nil
  70. }
  71. internal override func endOfStreamReceived() throws {
  72. if self.eventObserver != nil {
  73. throw GRPCError.StreamCardinalityViolation.request.captureContext()
  74. }
  75. }
  76. internal override func sendErrorStatusAndMetadata(_ statusAndMetadata: GRPCStatusAndMetadata) {
  77. if let metadata = statusAndMetadata.metadata {
  78. self.callContext?.trailingMetadata.add(contentsOf: metadata)
  79. }
  80. self.callContext?.responsePromise.fail(statusAndMetadata.status)
  81. }
  82. }