StreamingResponseCallContext.swift 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  22. ///
  23. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  24. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  25. /// the result of `error.asGRPCStatus()` will be returned to the client.
  26. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  27. open class StreamingResponseCallContext<ResponseMessage: Message>: ServerCallContextBase {
  28. public typealias WrappedResponse = GRPCServerResponsePart<ResponseMessage>
  29. public let statusPromise: EventLoopPromise<GRPCStatus>
  30. public override init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  31. self.statusPromise = eventLoop.makePromise()
  32. super.init(eventLoop: eventLoop, request: request, logger: logger)
  33. }
  34. open func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  35. fatalError("needs to be overridden")
  36. }
  37. }
  38. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  39. open class StreamingResponseCallContextImpl<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  40. public let channel: Channel
  41. /// - Parameters:
  42. /// - channel: The NIO channel the call is handled on.
  43. /// - request: The headers provided with this call.
  44. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  45. /// sending them to the client.
  46. ///
  47. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  48. public init(channel: Channel, request: HTTPRequestHead, errorDelegate: ServerErrorDelegate?, logger: Logger) {
  49. self.channel = channel
  50. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  51. statusPromise.futureResult
  52. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  53. .recover { [weak errorDelegate] error in
  54. errorDelegate?.observeRequestHandlerError(error, request: request)
  55. return errorDelegate?.transformRequestHandlerError(error, request: request)
  56. ?? (error as? GRPCStatusTransformable)?.asGRPCStatus()
  57. ?? .processingError
  58. }
  59. // Finish the call by returning the final status.
  60. .whenSuccess {
  61. self.channel.writeAndFlush(NIOAny(WrappedResponse.statusAndTrailers($0, self.trailingMetadata)), promise: nil)
  62. }
  63. }
  64. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  65. let promise: EventLoopPromise<Void> = eventLoop.makePromise()
  66. channel.writeAndFlush(NIOAny(WrappedResponse.message(message)), promise: promise)
  67. return promise.futureResult
  68. }
  69. }
  70. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  71. ///
  72. /// Simply records all sent messages.
  73. open class StreamingResponseCallContextTestStub<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  74. open var recordedResponses: [ResponseMessage] = []
  75. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  76. recordedResponses.append(message)
  77. return eventLoop.makeSucceededFuture(())
  78. }
  79. }