2
0

StreamingResponseCallContext.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. /// Send a response to the client.
  50. ///
  51. /// - Parameters:
  52. /// - message: The message to send to the client.
  53. /// - compression: Whether compression should be used for this response. If compression
  54. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  55. /// deferring to the value set on the call context.
  56. /// - promise: A promise to complete once the message has been sent.
  57. open func sendResponse(
  58. _ message: ResponsePayload,
  59. compression: Compression = .deferToCallDefault,
  60. promise: EventLoopPromise<Void>?
  61. ) {
  62. fatalError("needs to be overridden")
  63. }
  64. /// Send a response to the client.
  65. ///
  66. /// - Parameters:
  67. /// - message: The message to send to the client.
  68. /// - compression: Whether compression should be used for this response. If compression
  69. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  70. /// deferring to the value set on the call context.
  71. open func sendResponse(
  72. _ message: ResponsePayload,
  73. compression: Compression = .deferToCallDefault
  74. ) -> EventLoopFuture<Void> {
  75. let promise = self.eventLoop.makePromise(of: Void.self)
  76. self.sendResponse(message, compression: compression, promise: promise)
  77. return promise.futureResult
  78. }
  79. /// Sends a sequence of responses to the client.
  80. /// - Parameters:
  81. /// - messages: The messages to send to the client.
  82. /// - compression: Whether compression should be used for this response. If compression
  83. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  84. /// deferring to the value set on the call context.
  85. /// - promise: A promise to complete once the messages have been sent.
  86. open func sendResponses<Messages: Sequence>(
  87. _ messages: Messages,
  88. compression: Compression = .deferToCallDefault,
  89. promise: EventLoopPromise<Void>?
  90. ) where Messages.Element == ResponsePayload {
  91. fatalError("needs to be overridden")
  92. }
  93. /// Sends a sequence of responses to the client.
  94. /// - Parameters:
  95. /// - messages: The messages to send to the client.
  96. /// - compression: Whether compression should be used for this response. If compression
  97. /// is enabled in the call context, the value passed here takes precedence. Defaults to
  98. /// deferring to the value set on the call context.
  99. open func sendResponses<Messages: Sequence>(
  100. _ messages: Messages,
  101. compression: Compression = .deferToCallDefault
  102. ) -> EventLoopFuture<Void> where Messages.Element == ResponsePayload {
  103. let promise = self.eventLoop.makePromise(of: Void.self)
  104. self.sendResponses(messages, compression: compression, promise: promise)
  105. return promise.futureResult
  106. }
  107. }
  108. @usableFromInline
  109. internal final class _StreamingResponseCallContext<Request, Response>:
  110. StreamingResponseCallContext<Response> {
  111. @usableFromInline
  112. internal let _sendResponse: (Response, MessageMetadata, EventLoopPromise<Void>?) -> Void
  113. @usableFromInline
  114. internal let _compressionEnabledOnServer: Bool
  115. @inlinable
  116. internal init(
  117. eventLoop: EventLoop,
  118. headers: HPACKHeaders,
  119. logger: Logger,
  120. userInfoRef: Ref<UserInfo>,
  121. compressionIsEnabled: Bool,
  122. sendResponse: @escaping (Response, MessageMetadata, EventLoopPromise<Void>?) -> Void
  123. ) {
  124. self._sendResponse = sendResponse
  125. self._compressionEnabledOnServer = compressionIsEnabled
  126. super.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: userInfoRef)
  127. }
  128. @inlinable
  129. internal func shouldCompress(_ compression: Compression) -> Bool {
  130. guard self._compressionEnabledOnServer else {
  131. return false
  132. }
  133. return compression.isEnabled(callDefault: self.compressionEnabled)
  134. }
  135. @inlinable
  136. override func sendResponse(
  137. _ message: Response,
  138. compression: Compression = .deferToCallDefault,
  139. promise: EventLoopPromise<Void>?
  140. ) {
  141. if self.eventLoop.inEventLoop {
  142. let compress = self.shouldCompress(compression)
  143. self._sendResponse(message, .init(compress: compress, flush: true), promise)
  144. } else {
  145. self.eventLoop.execute {
  146. let compress = self.shouldCompress(compression)
  147. self._sendResponse(message, .init(compress: compress, flush: true), promise)
  148. }
  149. }
  150. }
  151. @inlinable
  152. override func sendResponses<Messages: Sequence>(
  153. _ messages: Messages,
  154. compression: Compression = .deferToCallDefault,
  155. promise: EventLoopPromise<Void>?
  156. ) where Response == Messages.Element {
  157. if self.eventLoop.inEventLoop {
  158. self._sendResponses(messages, compression: compression, promise: promise)
  159. } else {
  160. self.eventLoop.execute {
  161. self._sendResponses(messages, compression: compression, promise: promise)
  162. }
  163. }
  164. }
  165. @inlinable
  166. internal func _sendResponses<Messages: Sequence>(
  167. _ messages: Messages,
  168. compression: Compression,
  169. promise: EventLoopPromise<Void>?
  170. ) where Response == Messages.Element {
  171. let compress = self.shouldCompress(compression)
  172. var iterator = messages.makeIterator()
  173. var next = iterator.next()
  174. while let current = next {
  175. next = iterator.next()
  176. // Attach the promise, if present, to the last message.
  177. let isLast = next == nil
  178. self._sendResponse(current, .init(compress: compress, flush: isLast), isLast ? promise : nil)
  179. }
  180. }
  181. }
  182. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  183. ///
  184. /// Simply records all sent messages.
  185. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  186. open var recordedResponses: [ResponsePayload] = []
  187. override open func sendResponse(
  188. _ message: ResponsePayload,
  189. compression: Compression = .deferToCallDefault,
  190. promise: EventLoopPromise<Void>?
  191. ) {
  192. self.recordedResponses.append(message)
  193. promise?.succeed(())
  194. }
  195. override open func sendResponses<Messages: Sequence>(
  196. _ messages: Messages,
  197. compression: Compression = .deferToCallDefault,
  198. promise: EventLoopPromise<Void>?
  199. ) where ResponsePayload == Messages.Element {
  200. self.recordedResponses.append(contentsOf: messages)
  201. promise?.succeed(())
  202. }
  203. }