UnaryResponseCallContext.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 that exposes a promise for the RPC response.
  22. ///
  23. /// - When `responsePromise` is fulfilled, the call is closed and the provided response transmitted with status `responseStatus` (`.ok` by default).
  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. ///
  28. /// For unary calls, the response is not actually provided by fulfilling `responsePromise`, but instead by completing
  29. /// the future returned by `UnaryCallHandler.EventObserver`.
  30. open class UnaryResponseCallContext<ResponseMessage: Message>: ServerCallContextBase, StatusOnlyCallContext {
  31. typealias WrappedResponse = _GRPCServerResponsePart<ResponseMessage>
  32. public let responsePromise: EventLoopPromise<ResponseMessage>
  33. public var responseStatus: GRPCStatus = .ok
  34. public override init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  35. self.responsePromise = eventLoop.makePromise()
  36. super.init(eventLoop: eventLoop, request: request, logger: logger)
  37. }
  38. }
  39. /// Protocol variant of `UnaryResponseCallContext` that only exposes the `responseStatus` and `trailingMetadata`
  40. /// fields, but not `responsePromise`.
  41. ///
  42. /// Motivation: `UnaryCallHandler` already asks the call handler return an `EventLoopFuture<ResponseMessage>` which
  43. /// is automatically cascaded into `UnaryResponseCallContext.responsePromise`, so that promise does not (and should not)
  44. /// be fulfilled by the user.
  45. ///
  46. /// We can use a protocol (instead of an abstract base class) here because removing the generic `responsePromise` field
  47. /// lets us avoid associated-type requirements on the protocol.
  48. public protocol StatusOnlyCallContext: ServerCallContext {
  49. var responseStatus: GRPCStatus { get set }
  50. var trailingMetadata: HTTPHeaders { get set }
  51. }
  52. /// Concrete implementation of `UnaryResponseCallContext` used by our generated code.
  53. open class UnaryResponseCallContextImpl<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> {
  54. public let channel: Channel
  55. /// - Parameters:
  56. /// - channel: The NIO channel the call is handled on.
  57. /// - request: The headers provided with this call.
  58. /// - errorDelegate: Provides a means for transforming response promise failures to `GRPCStatusTransformable` before
  59. /// sending them to the client.
  60. public init(channel: Channel, request: HTTPRequestHead, errorDelegate: ServerErrorDelegate?, logger: Logger) {
  61. self.channel = channel
  62. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  63. responsePromise.futureResult
  64. // Send the response provided to the promise.
  65. .map { responseMessage in
  66. self.channel.writeAndFlush(NIOAny(WrappedResponse.message(responseMessage)))
  67. }
  68. .map { _ in
  69. self.responseStatus
  70. }
  71. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  72. .recover { [weak errorDelegate] error in
  73. errorDelegate?.observeRequestHandlerError(error, request: request)
  74. return errorDelegate?.transformRequestHandlerError(error, request: request)
  75. ?? (error as? GRPCStatusTransformable)?.makeGRPCStatus()
  76. ?? .processingError
  77. }
  78. // Finish the call by returning the final status.
  79. .whenSuccess { status in
  80. self.channel.writeAndFlush(NIOAny(WrappedResponse.statusAndTrailers(status, self.trailingMetadata)), promise: nil)
  81. }
  82. }
  83. }
  84. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  85. ///
  86. /// Only provided to make it clear in tests that no "real" implementation is used.
  87. open class UnaryResponseCallContextTestStub<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> { }