BidirectionalStreamingCallHandler.swift 4.7 KB

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