UnaryResponseCallContext.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. public convenience init(
  36. eventLoop: EventLoop,
  37. headers: HPACKHeaders,
  38. logger: Logger,
  39. userInfo: UserInfo = UserInfo()
  40. ) {
  41. self.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: .init(userInfo))
  42. }
  43. override internal init(
  44. eventLoop: EventLoop,
  45. headers: HPACKHeaders,
  46. logger: Logger,
  47. userInfoRef: Ref<UserInfo>
  48. ) {
  49. self.responsePromise = eventLoop.makePromise()
  50. super.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: userInfoRef)
  51. }
  52. @available(*, deprecated, renamed: "init(eventLoop:headers:logger:userInfo:)")
  53. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  54. self.responsePromise = eventLoop.makePromise()
  55. super.init(eventLoop: eventLoop, request: request, logger: logger)
  56. }
  57. }
  58. /// Protocol variant of `UnaryResponseCallContext` that only exposes the `responseStatus` and `trailingMetadata`
  59. /// fields, but not `responsePromise`.
  60. ///
  61. /// Motivation: `UnaryCallHandler` already asks the call handler return an `EventLoopFuture<ResponsePayload>` which
  62. /// is automatically cascaded into `UnaryResponseCallContext.responsePromise`, so that promise does not (and should not)
  63. /// be fulfilled by the user.
  64. ///
  65. /// We can use a protocol (instead of an abstract base class) here because removing the generic `responsePromise` field
  66. /// lets us avoid associated-type requirements on the protocol.
  67. public protocol StatusOnlyCallContext: ServerCallContext {
  68. var responseStatus: GRPCStatus { get set }
  69. var trailers: HPACKHeaders { get set }
  70. }
  71. extension StatusOnlyCallContext {
  72. @available(*, deprecated, renamed: "trailers")
  73. public var trailingMetadata: HTTPHeaders {
  74. get {
  75. return HTTPHeaders(self.trailers.map { ($0.name, $0.value) })
  76. }
  77. set {
  78. self.trailers = HPACKHeaders(httpHeaders: newValue)
  79. }
  80. }
  81. }
  82. /// Concrete implementation of `UnaryResponseCallContext` used by our generated code.
  83. open class UnaryResponseCallContextImpl<ResponsePayload>: UnaryResponseCallContext<ResponsePayload> {
  84. public let channel: Channel
  85. /// - Parameters:
  86. /// - channel: The NIO channel the call is handled on.
  87. /// - headers: The headers provided with this call.
  88. /// - errorDelegate: Provides a means for transforming response promise failures to `GRPCStatusTransformable` before
  89. /// sending them to the client.
  90. /// - logger: A logger.
  91. public init(
  92. channel: Channel,
  93. headers: HPACKHeaders,
  94. errorDelegate: ServerErrorDelegate?,
  95. logger: Logger
  96. ) {
  97. self.channel = channel
  98. super.init(
  99. eventLoop: channel.eventLoop,
  100. headers: headers,
  101. logger: logger,
  102. userInfoRef: .init(UserInfo())
  103. )
  104. self.responsePromise.futureResult.whenComplete { [self, weak errorDelegate] result in
  105. switch result {
  106. case let .success(message):
  107. self.handleResponse(message)
  108. case let .failure(error):
  109. self.handleError(error, delegate: errorDelegate)
  110. }
  111. }
  112. }
  113. /// Handle the response from the service provider.
  114. private func handleResponse(_ response: ResponsePayload) {
  115. self.channel.write(
  116. self.wrap(.message(response, .init(compress: self.compressionEnabled, flush: false))),
  117. promise: nil
  118. )
  119. self.channel.writeAndFlush(
  120. self.wrap(.end(self.responseStatus, self.trailers)),
  121. promise: nil
  122. )
  123. }
  124. /// Handle an error from the service provider.
  125. private func handleError(_ error: Error, delegate: ServerErrorDelegate?) {
  126. let (status, trailers) = self.processObserverError(error, delegate: delegate)
  127. self.channel.writeAndFlush(self.wrap(.end(status, trailers)), promise: nil)
  128. }
  129. /// Wrap the response part in a `NIOAny`. This is useful in order to avoid explicitly spelling
  130. /// out `NIOAny(WrappedResponse(...))`.
  131. private func wrap(_ response: WrappedResponse) -> NIOAny {
  132. return NIOAny(response)
  133. }
  134. @available(*, deprecated, renamed: "init(channel:headers:errorDelegate:logger:)")
  135. public convenience init(
  136. channel: Channel,
  137. request: HTTPRequestHead,
  138. errorDelegate: ServerErrorDelegate?,
  139. logger: Logger
  140. ) {
  141. self.init(
  142. channel: channel,
  143. headers: HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false),
  144. errorDelegate: errorDelegate,
  145. logger: logger
  146. )
  147. }
  148. }
  149. /// Concrete implementation of `UnaryResponseCallContext` used for testing.
  150. ///
  151. /// Only provided to make it clear in tests that no "real" implementation is used.
  152. open class UnaryResponseCallContextTestStub<ResponsePayload>: UnaryResponseCallContext<ResponsePayload> {}