ClientStreamingCallHandler.swift 4.4 KB

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