2
0

UnaryResponseCallContext.swift 4.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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<ResponsePayload: GRPCPayload>: ServerCallContextBase, StatusOnlyCallContext {
  31. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  32. public let responsePromise: EventLoopPromise<ResponsePayload>
  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<ResponsePayload>` 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<ResponsePayload: GRPCPayload>: UnaryResponseCallContext<ResponsePayload> {
  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 -> EventLoopFuture<Void> in
  66. let message = _MessageContext<ResponsePayload>(responseMessage, compressed: self.compressionEnabled)
  67. return self.channel.writeAndFlush(NIOAny(WrappedResponse.message(message)))
  68. }
  69. .map { _ in
  70. self.responseStatus
  71. }
  72. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  73. .recover { [weak errorDelegate] error in
  74. errorDelegate?.observeRequestHandlerError(error, request: request)
  75. return errorDelegate?.transformRequestHandlerError(error, request: request)
  76. ?? (error as? GRPCStatusTransformable)?.makeGRPCStatus()
  77. ?? .processingError
  78. }
  79. // Finish the call by returning the final status.
  80. .whenSuccess { status in
  81. self.channel.writeAndFlush(NIOAny(WrappedResponse.statusAndTrailers(status, self.trailingMetadata)), promise: nil)
  82. }
  83. }
  84. }
  85. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  86. ///
  87. /// Only provided to make it clear in tests that no "real" implementation is used.
  88. open class UnaryResponseCallContextTestStub<ResponsePayload: GRPCPayload>: UnaryResponseCallContext<ResponsePayload> { }