ClientStreamingCallHandler.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 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<RequestPayload, ResponsePayload>: _BaseCallHandler<RequestPayload, ResponsePayload> {
  28. public typealias Context = UnaryResponseCallContext<ResponsePayload>
  29. public typealias EventObserver = (StreamEvent<RequestPayload>) -> Void
  30. public typealias EventObserverFactory = (Context) -> EventLoopFuture<EventObserver>
  31. private var callContext: UnaryResponseCallContext<ResponsePayload>?
  32. private var eventObserver: EventLoopFuture<EventObserver>?
  33. private let eventObserverFactory: EventObserverFactory
  34. // We ask for a future of type `EventObserver` to allow the framework user to e.g. asynchronously authenticate a call.
  35. // If authentication fails, they can simply fail the observer future, which causes the call to be terminated.
  36. internal init<Serializer: MessageSerializer, Deserializer: MessageDeserializer>(
  37. serializer: Serializer,
  38. deserializer: Deserializer,
  39. callHandlerContext: CallHandlerContext,
  40. eventObserverFactory: @escaping EventObserverFactory
  41. ) where Serializer.Input == ResponsePayload, Deserializer.Output == RequestPayload {
  42. self.eventObserverFactory = eventObserverFactory
  43. super.init(
  44. callHandlerContext: callHandlerContext,
  45. codec: GRPCServerCodecHandler(serializer: serializer, deserializer: deserializer)
  46. )
  47. }
  48. internal override func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  49. let callContext = UnaryResponseCallContextImpl<ResponsePayload>(
  50. channel: context.channel,
  51. request: head,
  52. errorDelegate: self.errorDelegate,
  53. logger: self.logger
  54. )
  55. self.callContext = callContext
  56. let eventObserver = self.eventObserverFactory(callContext)
  57. eventObserver.cascadeFailure(to: callContext.responsePromise)
  58. self.eventObserver = eventObserver
  59. callContext.responsePromise.futureResult.whenComplete { _ in
  60. // When done, reset references to avoid retain cycles.
  61. self.eventObserver = nil
  62. self.callContext = nil
  63. }
  64. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  65. }
  66. internal override func processMessage(_ message: RequestPayload) {
  67. guard let eventObserver = self.eventObserver else {
  68. self.logger.warning("eventObserver is nil; ignoring message")
  69. return
  70. }
  71. eventObserver.whenSuccess { observer in
  72. observer(.message(message))
  73. }
  74. }
  75. internal override func endOfStreamReceived() throws {
  76. guard let eventObserver = self.eventObserver else {
  77. self.logger.warning("eventObserver is nil; ignoring end-of-stream")
  78. return
  79. }
  80. eventObserver.whenSuccess { observer in
  81. observer(.end)
  82. }
  83. }
  84. internal override func sendErrorStatus(_ status: GRPCStatus) {
  85. self.callContext?.responsePromise.fail(status)
  86. }
  87. }