ServerStreamingCallHandler.swift 3.5 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. import Logging
  21. /// Handles server-streaming calls. Calls the observer block with the request message.
  22. ///
  23. /// - The observer block is implemented by the framework user and calls `context.sendResponse` as needed.
  24. /// - To close the call and send the status, complete the status future returned by the observer block.
  25. public final class ServerStreamingCallHandler<
  26. RequestPayload: GRPCPayload,
  27. ResponsePayload: GRPCPayload
  28. >: _BaseCallHandler<RequestPayload, ResponsePayload> {
  29. public typealias EventObserver = (RequestPayload) -> EventLoopFuture<GRPCStatus>
  30. private var eventObserver: EventObserver?
  31. private var callContext: StreamingResponseCallContext<ResponsePayload>?
  32. private let eventObserverFactory: (StreamingResponseCallContext<ResponsePayload>) -> EventObserver
  33. public init(
  34. callHandlerContext: CallHandlerContext,
  35. eventObserverFactory: @escaping (StreamingResponseCallContext<ResponsePayload>) -> EventObserver
  36. ) {
  37. // Delay the creation of the event observer until we actually get a request head, otherwise it
  38. // would be possible for the observer to write into the pipeline (by completing the status
  39. // promise) before the pipeline is configured.
  40. self.eventObserverFactory = eventObserverFactory
  41. super.init(callHandlerContext: callHandlerContext)
  42. }
  43. override internal func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  44. let callContext = StreamingResponseCallContextImpl<ResponsePayload>(
  45. channel: context.channel,
  46. request: head,
  47. errorDelegate: self.callHandlerContext.errorDelegate,
  48. logger: self.callHandlerContext.logger
  49. )
  50. self.callContext = callContext
  51. self.eventObserver = eventObserverFactory(callContext)
  52. callContext.statusPromise.futureResult.whenComplete { _ in
  53. // When done, reset references to avoid retain cycles.
  54. self.eventObserver = nil
  55. self.callContext = nil
  56. }
  57. context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil)
  58. }
  59. override internal func processMessage(_ message: RequestPayload) throws {
  60. guard let eventObserver = self.eventObserver,
  61. let callContext = self.callContext else {
  62. self.logger.error("processMessage(_:) called before the call started or after the call completed")
  63. throw GRPCError.StreamCardinalityViolation.request.captureContext()
  64. }
  65. let resultFuture = eventObserver(message)
  66. resultFuture
  67. // Fulfil the status promise with whatever status the framework user has provided.
  68. .cascade(to: callContext.statusPromise)
  69. self.eventObserver = nil
  70. }
  71. override internal func endOfStreamReceived() throws {
  72. if self.eventObserver != nil {
  73. throw GRPCError.StreamCardinalityViolation.request.captureContext()
  74. }
  75. }
  76. override internal func sendErrorStatus(_ status: GRPCStatus) {
  77. self.callContext?.statusPromise.fail(status)
  78. }
  79. }