UnaryResponseCallContext.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 Logging
  18. import NIO
  19. import NIOHTTP1
  20. import SwiftProtobuf
  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>: ServerCallContextBase, StatusOnlyCallContext {
  31. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  32. public let responsePromise: EventLoopPromise<ResponsePayload>
  33. public var responseStatus: GRPCStatus = .ok
  34. override public 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>: 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(
  61. channel: Channel,
  62. request: HTTPRequestHead,
  63. errorDelegate: ServerErrorDelegate?,
  64. logger: Logger
  65. ) {
  66. self.channel = channel
  67. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  68. responsePromise.futureResult
  69. .whenComplete { [self, weak errorDelegate] result in
  70. let statusAndMetadata: GRPCStatusAndMetadata
  71. switch result {
  72. case let .success(responseMessage):
  73. self.channel.write(
  74. NIOAny(
  75. WrappedResponse
  76. .message(.init(responseMessage, compressed: self.compressionEnabled))
  77. ),
  78. promise: nil
  79. )
  80. statusAndMetadata = GRPCStatusAndMetadata(status: self.responseStatus, metadata: nil)
  81. case let .failure(error):
  82. errorDelegate?.observeRequestHandlerError(error, request: request)
  83. if let transformed: GRPCStatusAndMetadata = errorDelegate?.transformRequestHandlerError(
  84. error,
  85. request: request
  86. ) {
  87. statusAndMetadata = transformed
  88. } else if let grpcStatusTransformable = error as? GRPCStatusTransformable {
  89. statusAndMetadata = GRPCStatusAndMetadata(
  90. status: grpcStatusTransformable.makeGRPCStatus(),
  91. metadata: nil
  92. )
  93. } else {
  94. statusAndMetadata = GRPCStatusAndMetadata(status: .processingError, metadata: nil)
  95. }
  96. }
  97. if let metadata = statusAndMetadata.metadata {
  98. self.trailingMetadata.add(contentsOf: metadata)
  99. }
  100. self.channel.writeAndFlush(
  101. NIOAny(
  102. WrappedResponse
  103. .statusAndTrailers(statusAndMetadata.status, self.trailingMetadata)
  104. ),
  105. promise: nil
  106. )
  107. }
  108. }
  109. }
  110. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  111. ///
  112. /// Only provided to make it clear in tests that no "real" implementation is used.
  113. open class UnaryResponseCallContextTestStub<ResponsePayload>: UnaryResponseCallContext<ResponsePayload> {}