BidirectionalStreamingCallHandler.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 bidirectional 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 calls `context.sendResponse` as needed.
  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 status, complete `context.statusPromise`.
  27. public class BidirectionalStreamingCallHandler<RequestMessage: Message, ResponseMessage: Message>: BaseCallHandler<RequestMessage, ResponseMessage> {
  28. public typealias Context = StreamingResponseCallContext<ResponseMessage>
  29. public typealias EventObserver = (StreamEvent<RequestMessage>) -> Void
  30. public typealias EventObserverFactory = (Context) -> EventLoopFuture<EventObserver>
  31. private var observerState: ClientStreamingHandlerObserverState<EventObserverFactory, EventObserver> {
  32. willSet(newState) {
  33. self.logger.info("observerState changed from \(self.observerState) to \(newState)")
  34. }
  35. }
  36. private var callContext: Context?
  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 (StreamingResponseCallContext<ResponseMessage>) -> EventLoopFuture<EventObserver>) {
  40. // Delay the creation of the event observer until `handlerAdded(context:)`, otherwise it is
  41. // possible for the service to write into the pipeline (by fulfilling the status promise
  42. // of the call context outside of the observer) before it has been configured.
  43. self.observerState = .pendingCreation(eventObserverFactory)
  44. super.init(callHandlerContext: callHandlerContext)
  45. let context = StreamingResponseCallContextImpl<ResponseMessage>(
  46. channel: self.callHandlerContext.channel,
  47. request: self.callHandlerContext.request,
  48. errorDelegate: self.callHandlerContext.errorDelegate,
  49. logger: self.callHandlerContext.logger
  50. )
  51. self.callContext = context
  52. context.statusPromise.futureResult.whenComplete { _ in
  53. // When done, reset references to avoid retain cycles.
  54. self.callContext = nil
  55. self.observerState = .notRequired
  56. }
  57. }
  58. public override func handlerAdded(context: ChannelHandlerContext) {
  59. guard let callContext = self.callContext,
  60. case let .pendingCreation(factory) = self.observerState else {
  61. self.logger.warning("handlerAdded(context:) called but handler already has a call context")
  62. return
  63. }
  64. let eventObserver = factory(callContext)
  65. self.observerState = .created(eventObserver)
  66. // Terminate the call if the future providing an observer fails.
  67. // This is being done _after_ we have been added as a handler to ensure that the `GRPCServerCodec` required to
  68. // translate our outgoing `GRPCServerResponsePart<ResponseMessage>` message is already present on the channel.
  69. // Otherwise, our `OutboundOut` type would not match the `OutboundIn` type of the next handler on the channel.
  70. eventObserver.cascadeFailure(to: callContext.statusPromise)
  71. }
  72. public override func processMessage(_ message: RequestMessage) {
  73. guard case .created(let eventObserver) = self.observerState else {
  74. self.logger.warning("expecting observerState to be .created but was \(self.observerState), ignoring message \(message)")
  75. return
  76. }
  77. eventObserver.whenSuccess { observer in
  78. observer(.message(message))
  79. }
  80. }
  81. public override func endOfStreamReceived() throws {
  82. guard case .created(let eventObserver) = self.observerState else {
  83. self.logger.warning("expecting observerState to be .created but was \(self.observerState), ignoring end-of-stream call")
  84. return
  85. }
  86. eventObserver.whenSuccess { observer in
  87. observer(.end)
  88. }
  89. }
  90. override func sendErrorStatus(_ status: GRPCStatus) {
  91. self.callContext?.statusPromise.fail(status)
  92. }
  93. }