UnaryResponseCallContext.swift 4.3 KB

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