ClientStreamingCallHandler.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. /// For calls which support client streaming we need to delay the creation of the event observer
  22. /// until the handler has been added to the pipeline.
  23. enum ClientStreamingHandlerObserverState<Factory, Observer> {
  24. case pendingCreation(Factory)
  25. case created(EventLoopFuture<Observer>)
  26. case notRequired
  27. }
  28. /// Handles client-streaming calls. Forwards incoming messages and end-of-stream events to the observer block.
  29. ///
  30. /// - The observer block is implemented by the framework user and fulfills `context.responsePromise` when done.
  31. /// If the framework user wants to return a call error (e.g. in case of authentication failure),
  32. /// they can fail the observer block future.
  33. /// - To close the call and send the response, complete `context.responsePromise`.
  34. public class ClientStreamingCallHandler<RequestMessage: Message, ResponseMessage: Message>: BaseCallHandler<RequestMessage, ResponseMessage> {
  35. public typealias Context = UnaryResponseCallContext<ResponseMessage>
  36. public typealias EventObserver = (StreamEvent<RequestMessage>) -> Void
  37. public typealias EventObserverFactory = (Context) -> EventLoopFuture<EventObserver>
  38. private var observerState: ClientStreamingHandlerObserverState<EventObserverFactory, EventObserver> {
  39. willSet(newState) {
  40. self.logger.info("observerState changed from \(self.observerState) to \(newState)")
  41. }
  42. }
  43. private var callContext: UnaryResponseCallContext<ResponseMessage>?
  44. // We ask for a future of type `EventObserver` to allow the framework user to e.g. asynchronously authenticate a call.
  45. // If authentication fails, they can simply fail the observer future, which causes the call to be terminated.
  46. public init(callHandlerContext: CallHandlerContext, eventObserverFactory: @escaping EventObserverFactory) {
  47. // Delay the creation of the event observer until `handlerAdded(context:)`, otherwise it is
  48. // possible for the service to write into the pipeline (by fulfilling the response promise
  49. // of the call context outside of the observer) before it has been configured.
  50. self.observerState = .pendingCreation(eventObserverFactory)
  51. super.init(callHandlerContext: callHandlerContext)
  52. let callContext = UnaryResponseCallContextImpl<ResponseMessage>(
  53. channel: self.callHandlerContext.channel,
  54. request: self.callHandlerContext.request,
  55. errorDelegate: self.callHandlerContext.errorDelegate,
  56. logger: self.callHandlerContext.logger
  57. )
  58. self.callContext = callContext
  59. callContext.responsePromise.futureResult.whenComplete { _ in
  60. // When done, reset references to avoid retain cycles.
  61. self.callContext = nil
  62. self.observerState = .notRequired
  63. }
  64. }
  65. public override func handlerAdded(context: ChannelHandlerContext) {
  66. guard let callContext = self.callContext,
  67. case let .pendingCreation(factory) = self.observerState else {
  68. self.logger.warning("handlerAdded(context:) called but handler already has a call context")
  69. return
  70. }
  71. let eventObserver = factory(callContext)
  72. self.observerState = .created(eventObserver)
  73. // Terminate the call if the future providing an observer fails.
  74. // This is being done _after_ we have been added as a handler to ensure that the `GRPCServerCodec` required to
  75. // translate our outgoing `GRPCServerResponsePart<ResponseMessage>` message is already present on the channel.
  76. // Otherwise, our `OutboundOut` type would not match the `OutboundIn` type of the next handler on the channel.
  77. eventObserver.cascadeFailure(to: callContext.responsePromise)
  78. }
  79. public override func processMessage(_ message: RequestMessage) {
  80. guard case .created(let eventObserver) = self.observerState else {
  81. self.logger.warning("expecting observerState to be .created but was \(self.observerState), ignoring message \(message)")
  82. return
  83. }
  84. eventObserver.whenSuccess { observer in
  85. observer(.message(message))
  86. }
  87. }
  88. public override func endOfStreamReceived() throws {
  89. guard case .created(let eventObserver) = self.observerState else {
  90. self.logger.warning("expecting observerState to be .created but was \(self.observerState), ignoring end-of-stream call")
  91. return
  92. }
  93. eventObserver.whenSuccess { observer in
  94. observer(.end)
  95. }
  96. }
  97. override func sendErrorStatus(_ status: GRPCStatus) {
  98. self.callContext?.responsePromise.fail(status)
  99. }
  100. }