BidirectionalStreamingCallHandler.swift 4.1 KB

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