UnaryResponseCallContext.swift 4.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. public 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` field, but not
  40. /// `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. }
  51. /// Concrete implementation of `UnaryResponseCallContext` used by our generated code.
  52. open class UnaryResponseCallContextImpl<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> {
  53. public let channel: Channel
  54. /// - Parameters:
  55. /// - channel: The NIO channel the call is handled on.
  56. /// - request: The headers provided with this call.
  57. /// - errorDelegate: Provides a means for transforming response promise failures to `GRPCStatusTransformable` before
  58. /// sending them to the client.
  59. public init(channel: Channel, request: HTTPRequestHead, errorDelegate: ServerErrorDelegate?, logger: Logger) {
  60. self.channel = channel
  61. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  62. responsePromise.futureResult
  63. // Send the response provided to the promise.
  64. .map { responseMessage in
  65. self.channel.writeAndFlush(NIOAny(WrappedResponse.message(responseMessage)))
  66. }
  67. .map { _ in
  68. self.responseStatus
  69. }
  70. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  71. .recover { [weak errorDelegate] error in
  72. errorDelegate?.observeRequestHandlerError(error, request: request)
  73. return errorDelegate?.transformRequestHandlerError(error, request: request)
  74. ?? (error as? GRPCStatusTransformable)?.asGRPCStatus()
  75. ?? .processingError
  76. }
  77. // Finish the call by returning the final status.
  78. .whenSuccess { status in
  79. self.channel.writeAndFlush(NIOAny(WrappedResponse.status(status)), promise: nil)
  80. }
  81. }
  82. }
  83. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  84. ///
  85. /// Only provided to make it clear in tests that no "real" implementation is used.
  86. open class UnaryResponseCallContextTestStub<ResponseMessage: Message>: UnaryResponseCallContext<ResponseMessage> { }