StreamingResponseCallContext.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 to send multiple messages over the wire and a promise for the final RPC status.
  23. ///
  24. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  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. open class StreamingResponseCallContext<ResponsePayload>: ServerCallContextBase {
  29. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  30. public let statusPromise: EventLoopPromise<GRPCStatus>
  31. override public init(eventLoop: EventLoop, headers: HPACKHeaders, logger: Logger) {
  32. self.statusPromise = eventLoop.makePromise()
  33. super.init(eventLoop: eventLoop, headers: headers, logger: logger)
  34. }
  35. @available(*, deprecated, renamed: "init(eventLoop:path:headers:logger:)")
  36. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  37. self.statusPromise = eventLoop.makePromise()
  38. super.init(eventLoop: eventLoop, request: request, logger: logger)
  39. }
  40. /// Send a response to the client.
  41. ///
  42. /// - Parameters:
  43. /// - message: The message to send to the client.
  44. /// - compression: Whether compression should be used for this response. If compression
  45. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  46. /// deferring to the value set on the call context.
  47. /// - promise: A promise to complete once the message has been sent.
  48. open func sendResponse(
  49. _ message: ResponsePayload,
  50. compression: Compression = .deferToCallDefault,
  51. promise: EventLoopPromise<Void>?
  52. ) {
  53. fatalError("needs to be overridden")
  54. }
  55. /// Send a response to the client.
  56. ///
  57. /// - Parameters:
  58. /// - message: The message to send to the client.
  59. /// - compression: Whether compression should be used for this response. If compression
  60. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  61. /// deferring to the value set on the call context.
  62. open func sendResponse(
  63. _ message: ResponsePayload,
  64. compression: Compression = .deferToCallDefault
  65. ) -> EventLoopFuture<Void> {
  66. let promise = self.eventLoop.makePromise(of: Void.self)
  67. self.sendResponse(message, compression: compression, promise: promise)
  68. return promise.futureResult
  69. }
  70. /// Sends a sequence of responses to the client.
  71. /// - Parameters:
  72. /// - messages: The messages to send to the client.
  73. /// - compression: Whether compression should be used for this response. If compression
  74. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  75. /// deferring to the value set on the call context.
  76. /// - promise: A promise to complete once the messages have been sent.
  77. open func sendResponses<Messages: Sequence>(
  78. _ messages: Messages,
  79. compression: Compression = .deferToCallDefault,
  80. promise: EventLoopPromise<Void>?
  81. ) where Messages.Element == ResponsePayload {
  82. fatalError("needs to be overridden")
  83. }
  84. /// Sends a sequence of responses to the client.
  85. /// - Parameters:
  86. /// - messages: The messages to send to the client.
  87. /// - compression: Whether compression should be used for this response. If compression
  88. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  89. /// deferring to the value set on the call context.
  90. open func sendResponses<Messages: Sequence>(
  91. _ messages: Messages,
  92. compression: Compression = .deferToCallDefault
  93. ) -> EventLoopFuture<Void> where Messages.Element == ResponsePayload {
  94. let promise = self.eventLoop.makePromise(of: Void.self)
  95. self.sendResponses(messages, compression: compression, promise: promise)
  96. return promise.futureResult
  97. }
  98. }
  99. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  100. open class StreamingResponseCallContextImpl<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  101. public let channel: Channel
  102. /// - Parameters:
  103. /// - channel: The NIO channel the call is handled on.
  104. /// - headers: The headers provided with this call.
  105. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  106. /// sending them to the client.
  107. /// - logger: A logger.
  108. ///
  109. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  110. public init(
  111. channel: Channel,
  112. headers: HPACKHeaders,
  113. errorDelegate: ServerErrorDelegate?,
  114. logger: Logger
  115. ) {
  116. self.channel = channel
  117. super.init(eventLoop: channel.eventLoop, headers: headers, logger: logger)
  118. self.statusPromise.futureResult.whenComplete { result in
  119. switch result {
  120. case let .success(status):
  121. self.channel.writeAndFlush(
  122. self.wrap(.statusAndTrailers(status, self.trailers)),
  123. promise: nil
  124. )
  125. case let .failure(error):
  126. let (status, trailers) = self.processError(error, delegate: errorDelegate)
  127. self.channel.writeAndFlush(self.wrap(.statusAndTrailers(status, trailers)), promise: nil)
  128. }
  129. }
  130. }
  131. /// Wrap the response part in a `NIOAny`. This is useful in order to avoid explicitly spelling
  132. /// out `NIOAny(WrappedResponse(...))`.
  133. private func wrap(_ response: WrappedResponse) -> NIOAny {
  134. return NIOAny(response)
  135. }
  136. @available(*, deprecated, renamed: "init(channel:headers:errorDelegate:logger:)")
  137. public convenience init(
  138. channel: Channel,
  139. request: HTTPRequestHead,
  140. errorDelegate: ServerErrorDelegate?,
  141. logger: Logger
  142. ) {
  143. self.init(
  144. channel: channel,
  145. headers: HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false),
  146. errorDelegate: errorDelegate,
  147. logger: logger
  148. )
  149. }
  150. override open func sendResponse(
  151. _ message: ResponsePayload,
  152. compression: Compression = .deferToCallDefault,
  153. promise: EventLoopPromise<Void>?
  154. ) {
  155. let response = _MessageContext(
  156. message,
  157. compressed: compression.isEnabled(callDefault: self.compressionEnabled)
  158. )
  159. self.channel.writeAndFlush(self.wrap(.message(response)), promise: promise)
  160. }
  161. override open func sendResponses<Messages: Sequence>(
  162. _ messages: Messages,
  163. compression: Compression = .deferToCallDefault,
  164. promise: EventLoopPromise<Void>?
  165. ) where ResponsePayload == Messages.Element {
  166. let compress = compression.isEnabled(callDefault: self.compressionEnabled)
  167. var iterator = messages.makeIterator()
  168. var next = iterator.next()
  169. while let current = next {
  170. next = iterator.next()
  171. // Attach the promise, if present, to the last message.
  172. let isLast = next == nil
  173. self.channel.write(
  174. self.wrap(.message(.init(current, compressed: compress))),
  175. promise: isLast ? promise : nil
  176. )
  177. }
  178. self.channel.flush()
  179. }
  180. }
  181. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  182. ///
  183. /// Simply records all sent messages.
  184. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  185. open var recordedResponses: [ResponsePayload] = []
  186. override open func sendResponse(
  187. _ message: ResponsePayload,
  188. compression: Compression = .deferToCallDefault,
  189. promise: EventLoopPromise<Void>?
  190. ) {
  191. self.recordedResponses.append(message)
  192. promise?.succeed(())
  193. }
  194. override open func sendResponses<Messages: Sequence>(
  195. _ messages: Messages,
  196. compression: Compression = .deferToCallDefault,
  197. promise: EventLoopPromise<Void>?
  198. ) where ResponsePayload == Messages.Element {
  199. self.recordedResponses.append(contentsOf: messages)
  200. promise?.succeed(())
  201. }
  202. }