ClientStreamingCallHandler.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 Logging
  18. import NIO
  19. import NIOHTTP1
  20. import SwiftProtobuf
  21. /// Handles client-streaming calls. Forwards incoming messages and end-of-stream events to the observer block.
  22. ///
  23. /// - The observer block is implemented by the framework user and fulfills `context.responsePromise` when done.
  24. /// If the framework user wants to return a call error (e.g. in case of authentication failure),
  25. /// they can fail the observer block future.
  26. /// - To close the call and send the response, complete `context.responsePromise`.
  27. public final class ClientStreamingCallHandler<
  28. RequestPayload,
  29. ResponsePayload
  30. >: _BaseCallHandler<RequestPayload, ResponsePayload> {
  31. public typealias Context = UnaryResponseCallContext<ResponsePayload>
  32. public typealias EventObserver = (StreamEvent<RequestPayload>) -> Void
  33. public typealias EventObserverFactory = (Context) -> EventLoopFuture<EventObserver>
  34. private var callContext: UnaryResponseCallContext<ResponsePayload>?
  35. private var eventObserver: EventLoopFuture<EventObserver>?
  36. private let eventObserverFactory: EventObserverFactory
  37. // We ask for a future of type `EventObserver` to allow the framework user to e.g. asynchronously authenticate a call.
  38. // If authentication fails, they can simply fail the observer future, which causes the call to be terminated.
  39. internal init<Serializer: MessageSerializer, Deserializer: MessageDeserializer>(
  40. serializer: Serializer,
  41. deserializer: Deserializer,
  42. callHandlerContext: CallHandlerContext,
  43. eventObserverFactory: @escaping EventObserverFactory
  44. ) where Serializer.Input == ResponsePayload, Deserializer.Output == RequestPayload {
  45. self.eventObserverFactory = eventObserverFactory
  46. super.init(
  47. callHandlerContext: callHandlerContext,
  48. codec: GRPCServerCodecHandler(serializer: serializer, deserializer: deserializer)
  49. )
  50. }
  51. override internal func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  52. let callContext = UnaryResponseCallContextImpl<ResponsePayload>(
  53. channel: context.channel,
  54. request: head,
  55. errorDelegate: self.errorDelegate,
  56. logger: self.logger
  57. )
  58. self.callContext = callContext
  59. let eventObserver = self.eventObserverFactory(callContext)
  60. eventObserver.cascadeFailure(to: callContext.responsePromise)
  61. self.eventObserver = eventObserver
  62. callContext.responsePromise.futureResult.whenComplete { _ in
  63. // When done, reset references to avoid retain cycles.
  64. self.eventObserver = nil
  65. self.callContext = nil
  66. }
  67. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  68. }
  69. override internal func processMessage(_ message: RequestPayload) {
  70. guard let eventObserver = self.eventObserver else {
  71. self.logger.warning("eventObserver is nil; ignoring message", source: "GRPC")
  72. return
  73. }
  74. eventObserver.whenSuccess { observer in
  75. observer(.message(message))
  76. }
  77. }
  78. override internal func endOfStreamReceived() throws {
  79. guard let eventObserver = self.eventObserver else {
  80. self.logger.warning("eventObserver is nil; ignoring end-of-stream", source: "GRPC")
  81. return
  82. }
  83. eventObserver.whenSuccess { observer in
  84. observer(.end)
  85. }
  86. }
  87. override internal func sendErrorStatusAndMetadata(_ statusAndMetadata: GRPCStatusAndMetadata) {
  88. if let metadata = statusAndMetadata.metadata {
  89. self.callContext?.trailingMetadata.add(contentsOf: metadata)
  90. }
  91. self.callContext?.responsePromise.fail(statusAndMetadata.status)
  92. }
  93. }