ClientStreamingCallHandler.swift 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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<
  28. RequestPayload: GRPCPayload,
  29. ResponsePayload: GRPCPayload
  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. public init(callHandlerContext: CallHandlerContext, eventObserverFactory: @escaping EventObserverFactory) {
  40. self.eventObserverFactory = eventObserverFactory
  41. super.init(callHandlerContext: callHandlerContext)
  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. let eventObserver = self.eventObserverFactory(callContext)
  52. eventObserver.cascadeFailure(to: callContext.responsePromise)
  53. self.eventObserver = eventObserver
  54. callContext.responsePromise.futureResult.whenComplete { _ in
  55. // When done, reset references to avoid retain cycles.
  56. self.eventObserver = nil
  57. self.callContext = nil
  58. }
  59. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  60. }
  61. internal override func processMessage(_ message: RequestPayload) {
  62. guard let eventObserver = self.eventObserver else {
  63. self.logger.warning("eventObserver is nil; ignoring message")
  64. return
  65. }
  66. eventObserver.whenSuccess { observer in
  67. observer(.message(message))
  68. }
  69. }
  70. internal override func endOfStreamReceived() throws {
  71. guard let eventObserver = self.eventObserver else {
  72. self.logger.warning("eventObserver is nil; ignoring end-of-stream")
  73. return
  74. }
  75. eventObserver.whenSuccess { observer in
  76. observer(.end)
  77. }
  78. }
  79. internal override func sendErrorStatus(_ status: GRPCStatus) {
  80. self.callContext?.responsePromise.fail(status)
  81. }
  82. }