BidirectionalStreamingCallHandler.swift 4.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. RequestPayload: GRPCPayload,
  29. ResponsePayload: GRPCPayload
  30. >: _BaseCallHandler<RequestPayload, ResponsePayload> {
  31. public typealias Context = StreamingResponseCallContext<ResponsePayload>
  32. public typealias EventObserver = (StreamEvent<RequestPayload>) -> Void
  33. public typealias EventObserverFactory = (Context) -> EventLoopFuture<EventObserver>
  34. private var callContext: Context?
  35. private var eventObserver: EventLoopFuture<EventObserver>?
  36. private let eventObserverFactory: (StreamingResponseCallContext<ResponsePayload>) -> EventLoopFuture<EventObserver>
  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(
  40. callHandlerContext: CallHandlerContext,
  41. eventObserverFactory: @escaping (StreamingResponseCallContext<ResponsePayload>) -> EventLoopFuture<EventObserver>
  42. ) {
  43. // Delay the creation of the event observer until we actually get a request head, otherwise it
  44. // would be possible for the observer to write into the pipeline (by completing the status
  45. // promise) before the pipeline is configured.
  46. self.eventObserverFactory = eventObserverFactory
  47. super.init(callHandlerContext: callHandlerContext)
  48. }
  49. internal override func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  50. let callContext = StreamingResponseCallContextImpl<ResponsePayload>(
  51. channel: context.channel,
  52. request: head,
  53. errorDelegate: self.callHandlerContext.errorDelegate,
  54. logger: self.callHandlerContext.logger
  55. )
  56. self.callContext = callContext
  57. let eventObserver = self.eventObserverFactory(callContext)
  58. eventObserver.cascadeFailure(to: callContext.statusPromise)
  59. self.eventObserver = eventObserver
  60. callContext.statusPromise.futureResult.whenComplete { _ in
  61. // When done, reset references to avoid retain cycles.
  62. self.eventObserver = nil
  63. self.callContext = nil
  64. }
  65. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  66. }
  67. internal override func processMessage(_ message: RequestPayload) {
  68. guard let eventObserver = self.eventObserver else {
  69. self.logger.warning("eventObserver is nil; ignoring message")
  70. return
  71. }
  72. eventObserver.whenSuccess { observer in
  73. observer(.message(message))
  74. }
  75. }
  76. internal override func endOfStreamReceived() throws {
  77. guard let eventObserver = self.eventObserver else {
  78. self.logger.warning("eventObserver is nil; ignoring end-of-stream")
  79. return
  80. }
  81. eventObserver.whenSuccess { observer in
  82. observer(.end)
  83. }
  84. }
  85. internal override func sendErrorStatus(_ status: GRPCStatus) {
  86. self.callContext?.statusPromise.fail(status)
  87. }
  88. }