UnaryResponseCallContext.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 NIOHPACK
  20. import NIOHTTP1
  21. import SwiftProtobuf
  22. /// Abstract base class exposing a method that exposes a promise for the RPC response.
  23. ///
  24. /// - When `responsePromise` is fulfilled, the call is closed and the provided response transmitted with status `responseStatus` (`.ok` by default).
  25. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  26. /// the result of `error.asGRPCStatus()` will be returned to the client.
  27. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  28. ///
  29. /// For unary calls, the response is not actually provided by fulfilling `responsePromise`, but instead by completing
  30. /// the future returned by `UnaryCallHandler.EventObserver`.
  31. open class UnaryResponseCallContext<ResponsePayload>: ServerCallContextBase, StatusOnlyCallContext {
  32. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  33. public let responsePromise: EventLoopPromise<ResponsePayload>
  34. public var responseStatus: GRPCStatus = .ok
  35. override public init(eventLoop: EventLoop, headers: HPACKHeaders, logger: Logger) {
  36. self.responsePromise = eventLoop.makePromise()
  37. super.init(eventLoop: eventLoop, headers: headers, logger: logger)
  38. }
  39. @available(*, deprecated, renamed: "init(eventLoop:headers:logger:)")
  40. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  41. self.responsePromise = eventLoop.makePromise()
  42. super.init(eventLoop: eventLoop, request: request, logger: logger)
  43. }
  44. }
  45. /// Protocol variant of `UnaryResponseCallContext` that only exposes the `responseStatus` and `trailingMetadata`
  46. /// fields, but not `responsePromise`.
  47. ///
  48. /// Motivation: `UnaryCallHandler` already asks the call handler return an `EventLoopFuture<ResponsePayload>` which
  49. /// is automatically cascaded into `UnaryResponseCallContext.responsePromise`, so that promise does not (and should not)
  50. /// be fulfilled by the user.
  51. ///
  52. /// We can use a protocol (instead of an abstract base class) here because removing the generic `responsePromise` field
  53. /// lets us avoid associated-type requirements on the protocol.
  54. public protocol StatusOnlyCallContext: ServerCallContext {
  55. var responseStatus: GRPCStatus { get set }
  56. var trailers: HPACKHeaders { get set }
  57. }
  58. extension StatusOnlyCallContext {
  59. @available(*, deprecated, renamed: "trailers")
  60. public var trailingMetadata: HTTPHeaders {
  61. get {
  62. return HTTPHeaders(self.trailers.map { ($0.name, $0.value) })
  63. }
  64. set {
  65. self.trailers = HPACKHeaders(httpHeaders: newValue)
  66. }
  67. }
  68. }
  69. /// Concrete implementation of `UnaryResponseCallContext` used by our generated code.
  70. open class UnaryResponseCallContextImpl<ResponsePayload>: UnaryResponseCallContext<ResponsePayload> {
  71. public let channel: Channel
  72. /// - Parameters:
  73. /// - channel: The NIO channel the call is handled on.
  74. /// - headers: The headers provided with this call.
  75. /// - errorDelegate: Provides a means for transforming response promise failures to `GRPCStatusTransformable` before
  76. /// sending them to the client.
  77. /// - logger: A logger.
  78. public init(
  79. channel: Channel,
  80. headers: HPACKHeaders,
  81. errorDelegate: ServerErrorDelegate?,
  82. logger: Logger
  83. ) {
  84. self.channel = channel
  85. super.init(eventLoop: channel.eventLoop, headers: headers, logger: logger)
  86. self.responsePromise.futureResult.whenComplete { [self, weak errorDelegate] result in
  87. switch result {
  88. case let .success(message):
  89. self.handleResponse(message)
  90. case let .failure(error):
  91. self.handleError(error, delegate: errorDelegate)
  92. }
  93. }
  94. }
  95. /// Handle the response from the service provider.
  96. private func handleResponse(_ response: ResponsePayload) {
  97. self.channel.write(
  98. self.wrap(.message(.init(response, compressed: self.compressionEnabled))),
  99. promise: nil
  100. )
  101. self.channel.writeAndFlush(
  102. self.wrap(.statusAndTrailers(self.responseStatus, self.trailers)),
  103. promise: nil
  104. )
  105. }
  106. /// Handle an error from the service provider.
  107. private func handleError(_ error: Error, delegate: ServerErrorDelegate?) {
  108. let (status, trailers) = self.processError(error, delegate: delegate)
  109. self.channel.writeAndFlush(self.wrap(.statusAndTrailers(status, trailers)), promise: nil)
  110. }
  111. /// Wrap the response part in a `NIOAny`. This is useful in order to avoid explicitly spelling
  112. /// out `NIOAny(WrappedResponse(...))`.
  113. private func wrap(_ response: WrappedResponse) -> NIOAny {
  114. return NIOAny(response)
  115. }
  116. @available(*, deprecated, renamed: "init(channel:headers:errorDelegate:logger:)")
  117. public convenience init(
  118. channel: Channel,
  119. request: HTTPRequestHead,
  120. errorDelegate: ServerErrorDelegate?,
  121. logger: Logger
  122. ) {
  123. self.init(
  124. channel: channel,
  125. headers: HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false),
  126. errorDelegate: errorDelegate,
  127. logger: logger
  128. )
  129. }
  130. }
  131. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  132. ///
  133. /// Only provided to make it clear in tests that no "real" implementation is used.
  134. open class UnaryResponseCallContextTestStub<ResponsePayload>: UnaryResponseCallContext<ResponsePayload> {}