StreamingResponseCallContext.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. public convenience init(
  32. eventLoop: EventLoop,
  33. headers: HPACKHeaders,
  34. logger: Logger,
  35. userInfo: UserInfo = UserInfo()
  36. ) {
  37. self.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: .init(userInfo))
  38. }
  39. @inlinable
  40. override internal init(
  41. eventLoop: EventLoop,
  42. headers: HPACKHeaders,
  43. logger: Logger,
  44. userInfoRef: Ref<UserInfo>
  45. ) {
  46. self.statusPromise = eventLoop.makePromise()
  47. super.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: userInfoRef)
  48. }
  49. @available(*, deprecated, renamed: "init(eventLoop:path:headers:logger:userInfo:)")
  50. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  51. self.statusPromise = eventLoop.makePromise()
  52. super.init(eventLoop: eventLoop, request: request, logger: logger)
  53. }
  54. /// Send a response to the client.
  55. ///
  56. /// - Parameters:
  57. /// - message: The message to send to the client.
  58. /// - compression: Whether compression should be used for this response. If compression
  59. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  60. /// deferring to the value set on the call context.
  61. /// - promise: A promise to complete once the message has been sent.
  62. open func sendResponse(
  63. _ message: ResponsePayload,
  64. compression: Compression = .deferToCallDefault,
  65. promise: EventLoopPromise<Void>?
  66. ) {
  67. fatalError("needs to be overridden")
  68. }
  69. /// Send a response to the client.
  70. ///
  71. /// - Parameters:
  72. /// - message: The message 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. open func sendResponse(
  77. _ message: ResponsePayload,
  78. compression: Compression = .deferToCallDefault
  79. ) -> EventLoopFuture<Void> {
  80. let promise = self.eventLoop.makePromise(of: Void.self)
  81. self.sendResponse(message, compression: compression, promise: promise)
  82. return promise.futureResult
  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. /// - promise: A promise to complete once the messages have been sent.
  91. open func sendResponses<Messages: Sequence>(
  92. _ messages: Messages,
  93. compression: Compression = .deferToCallDefault,
  94. promise: EventLoopPromise<Void>?
  95. ) where Messages.Element == ResponsePayload {
  96. fatalError("needs to be overridden")
  97. }
  98. /// Sends a sequence of responses to the client.
  99. /// - Parameters:
  100. /// - messages: The messages to send to the client.
  101. /// - compression: Whether compression should be used for this response. If compression
  102. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  103. /// deferring to the value set on the call context.
  104. open func sendResponses<Messages: Sequence>(
  105. _ messages: Messages,
  106. compression: Compression = .deferToCallDefault
  107. ) -> EventLoopFuture<Void> where Messages.Element == ResponsePayload {
  108. let promise = self.eventLoop.makePromise(of: Void.self)
  109. self.sendResponses(messages, compression: compression, promise: promise)
  110. return promise.futureResult
  111. }
  112. }
  113. @usableFromInline
  114. internal final class _StreamingResponseCallContext<Request, Response>:
  115. StreamingResponseCallContext<Response> {
  116. @usableFromInline
  117. internal let _sendResponse: (Response, MessageMetadata, EventLoopPromise<Void>?) -> Void
  118. @usableFromInline
  119. internal let _compressionEnabledOnServer: Bool
  120. @inlinable
  121. internal init(
  122. eventLoop: EventLoop,
  123. headers: HPACKHeaders,
  124. logger: Logger,
  125. userInfoRef: Ref<UserInfo>,
  126. compressionIsEnabled: Bool,
  127. sendResponse: @escaping (Response, MessageMetadata, EventLoopPromise<Void>?) -> Void
  128. ) {
  129. self._sendResponse = sendResponse
  130. self._compressionEnabledOnServer = compressionIsEnabled
  131. super.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: userInfoRef)
  132. }
  133. @inlinable
  134. internal func shouldCompress(_ compression: Compression) -> Bool {
  135. guard self._compressionEnabledOnServer else {
  136. return false
  137. }
  138. return compression.isEnabled(callDefault: self.compressionEnabled)
  139. }
  140. @inlinable
  141. override func sendResponse(
  142. _ message: Response,
  143. compression: Compression = .deferToCallDefault,
  144. promise: EventLoopPromise<Void>?
  145. ) {
  146. if self.eventLoop.inEventLoop {
  147. let compress = self.shouldCompress(compression)
  148. self._sendResponse(message, .init(compress: compress, flush: true), promise)
  149. } else {
  150. self.eventLoop.execute {
  151. let compress = self.shouldCompress(compression)
  152. self._sendResponse(message, .init(compress: compress, flush: true), promise)
  153. }
  154. }
  155. }
  156. @inlinable
  157. override func sendResponses<Messages: Sequence>(
  158. _ messages: Messages,
  159. compression: Compression = .deferToCallDefault,
  160. promise: EventLoopPromise<Void>?
  161. ) where Response == Messages.Element {
  162. if self.eventLoop.inEventLoop {
  163. self._sendResponses(messages, compression: compression, promise: promise)
  164. } else {
  165. self.eventLoop.execute {
  166. self._sendResponses(messages, compression: compression, promise: promise)
  167. }
  168. }
  169. }
  170. @inlinable
  171. internal func _sendResponses<Messages: Sequence>(
  172. _ messages: Messages,
  173. compression: Compression,
  174. promise: EventLoopPromise<Void>?
  175. ) where Response == Messages.Element {
  176. let compress = self.shouldCompress(compression)
  177. var iterator = messages.makeIterator()
  178. var next = iterator.next()
  179. while let current = next {
  180. next = iterator.next()
  181. // Attach the promise, if present, to the last message.
  182. let isLast = next == nil
  183. self._sendResponse(current, .init(compress: compress, flush: isLast), isLast ? promise : nil)
  184. }
  185. }
  186. }
  187. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  188. open class StreamingResponseCallContextImpl<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  189. public let channel: Channel
  190. /// - Parameters:
  191. /// - channel: The NIO channel the call is handled on.
  192. /// - headers: The headers provided with this call.
  193. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  194. /// sending them to the client.
  195. /// - logger: A logger.
  196. ///
  197. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  198. public init(
  199. channel: Channel,
  200. headers: HPACKHeaders,
  201. errorDelegate: ServerErrorDelegate?,
  202. logger: Logger
  203. ) {
  204. self.channel = channel
  205. super.init(
  206. eventLoop: channel.eventLoop,
  207. headers: headers,
  208. logger: logger,
  209. userInfoRef: Ref(UserInfo())
  210. )
  211. self.statusPromise.futureResult.whenComplete { result in
  212. switch result {
  213. case let .success(status):
  214. self.channel.writeAndFlush(
  215. self.wrap(.end(status, self.trailers)),
  216. promise: nil
  217. )
  218. case let .failure(error):
  219. let (status, trailers) = self.processObserverError(error, delegate: errorDelegate)
  220. self.channel.writeAndFlush(self.wrap(.end(status, trailers)), promise: nil)
  221. }
  222. }
  223. }
  224. /// Wrap the response part in a `NIOAny`. This is useful in order to avoid explicitly spelling
  225. /// out `NIOAny(WrappedResponse(...))`.
  226. private func wrap(_ response: WrappedResponse) -> NIOAny {
  227. return NIOAny(response)
  228. }
  229. @available(*, deprecated, renamed: "init(channel:headers:errorDelegate:logger:)")
  230. public convenience init(
  231. channel: Channel,
  232. request: HTTPRequestHead,
  233. errorDelegate: ServerErrorDelegate?,
  234. logger: Logger
  235. ) {
  236. self.init(
  237. channel: channel,
  238. headers: HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false),
  239. errorDelegate: errorDelegate,
  240. logger: logger
  241. )
  242. }
  243. override open func sendResponse(
  244. _ message: ResponsePayload,
  245. compression: Compression = .deferToCallDefault,
  246. promise: EventLoopPromise<Void>?
  247. ) {
  248. let compress = compression.isEnabled(callDefault: self.compressionEnabled)
  249. self.channel.write(
  250. self.wrap(.message(message, .init(compress: compress, flush: true))),
  251. promise: promise
  252. )
  253. }
  254. override open func sendResponses<Messages: Sequence>(
  255. _ messages: Messages,
  256. compression: Compression = .deferToCallDefault,
  257. promise: EventLoopPromise<Void>?
  258. ) where ResponsePayload == Messages.Element {
  259. let compress = compression.isEnabled(callDefault: self.compressionEnabled)
  260. var iterator = messages.makeIterator()
  261. var next = iterator.next()
  262. while let current = next {
  263. next = iterator.next()
  264. // Attach the promise, if present, to the last message.
  265. let isLast = next == nil
  266. self.channel.write(
  267. self.wrap(.message(current, .init(compress: compress, flush: isLast))),
  268. promise: isLast ? promise : nil
  269. )
  270. }
  271. }
  272. }
  273. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  274. ///
  275. /// Simply records all sent messages.
  276. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  277. open var recordedResponses: [ResponsePayload] = []
  278. override open func sendResponse(
  279. _ message: ResponsePayload,
  280. compression: Compression = .deferToCallDefault,
  281. promise: EventLoopPromise<Void>?
  282. ) {
  283. self.recordedResponses.append(message)
  284. promise?.succeed(())
  285. }
  286. override open func sendResponses<Messages: Sequence>(
  287. _ messages: Messages,
  288. compression: Compression = .deferToCallDefault,
  289. promise: EventLoopPromise<Void>?
  290. ) where ResponsePayload == Messages.Element {
  291. self.recordedResponses.append(contentsOf: messages)
  292. promise?.succeed(())
  293. }
  294. }