2
0

ClientStreamingCallHandler.swift 5.0 KB

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