BidirectionalStreamingCall.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 Logging
  17. import NIO
  18. import NIOHPACK
  19. import NIOHTTP2
  20. /// A bidirectional-streaming gRPC call. Each response is passed to the provided observer block.
  21. ///
  22. /// Messages should be sent via the `sendMessage` and `sendMessages` methods; the stream of messages
  23. /// must be terminated by calling `sendEnd` to indicate the final message has been sent.
  24. public final class BidirectionalStreamingCall<
  25. RequestPayload,
  26. ResponsePayload
  27. >: StreamingRequestClientCall {
  28. private let transport: ChannelTransport<RequestPayload, ResponsePayload>
  29. /// The options used to make the RPC.
  30. public let options: CallOptions
  31. /// The `Channel` used to transport messages for this RPC.
  32. public var subchannel: EventLoopFuture<Channel> {
  33. return self.transport.streamChannel()
  34. }
  35. /// The `EventLoop` this call is running on.
  36. public var eventLoop: EventLoop {
  37. return self.transport.eventLoop
  38. }
  39. /// Cancel this RPC if it hasn't already completed.
  40. public func cancel(promise: EventLoopPromise<Void>?) {
  41. self.transport.cancel(promise: promise)
  42. }
  43. // MARK: - Response Parts
  44. /// The initial metadata returned from the server.
  45. public var initialMetadata: EventLoopFuture<HPACKHeaders> {
  46. if self.eventLoop.inEventLoop {
  47. return self.transport.responseContainer.lazyInitialMetadataPromise.getFutureResult()
  48. } else {
  49. return self.eventLoop.flatSubmit {
  50. return self.transport.responseContainer.lazyInitialMetadataPromise.getFutureResult()
  51. }
  52. }
  53. }
  54. /// The trailing metadata returned from the server.
  55. public var trailingMetadata: EventLoopFuture<HPACKHeaders> {
  56. if self.eventLoop.inEventLoop {
  57. return self.transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult()
  58. } else {
  59. return self.eventLoop.flatSubmit {
  60. return self.transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult()
  61. }
  62. }
  63. }
  64. /// The final status of the the RPC.
  65. public var status: EventLoopFuture<GRPCStatus> {
  66. if self.eventLoop.inEventLoop {
  67. return self.transport.responseContainer.lazyStatusPromise.getFutureResult()
  68. } else {
  69. return self.eventLoop.flatSubmit {
  70. return self.transport.responseContainer.lazyStatusPromise.getFutureResult()
  71. }
  72. }
  73. }
  74. // MARK: - Requests
  75. /// Sends a message to the service.
  76. ///
  77. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or
  78. /// `sendEnd(promise:)`.
  79. ///
  80. /// - Parameters:
  81. /// - message: The message to send.
  82. /// - compression: Whether compression should be used for this message. Ignored if compression
  83. /// was not enabled for the RPC.
  84. /// - promise: A promise to fulfill with the outcome of the send operation.
  85. public func sendMessage(
  86. _ message: RequestPayload,
  87. compression: Compression = .deferToCallDefault,
  88. promise: EventLoopPromise<Void>?
  89. ) {
  90. let compressed = compression
  91. .isEnabled(callDefault: self.options.messageEncoding.enabledForRequests)
  92. let messageContext = _MessageContext(message, compressed: compressed)
  93. self.transport.sendRequest(.message(messageContext), promise: promise)
  94. }
  95. /// Sends a sequence of messages to the service.
  96. ///
  97. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or
  98. /// `sendEnd(promise:)`.
  99. ///
  100. /// - Parameters:
  101. /// - messages: The sequence of messages to send.
  102. /// - compression: Whether compression should be used for this message. Ignored if compression
  103. /// was not enabled for the RPC.
  104. /// - promise: A promise to fulfill with the outcome of the send operation. It will only succeed
  105. /// if all messages were written successfully.
  106. public func sendMessages<S>(
  107. _ messages: S,
  108. compression: Compression = .deferToCallDefault,
  109. promise: EventLoopPromise<Void>?
  110. ) where S: Sequence, S.Element == RequestPayload {
  111. let compressed = compression
  112. .isEnabled(callDefault: self.options.messageEncoding.enabledForRequests)
  113. self.transport.sendRequests(messages.map {
  114. .message(_MessageContext($0, compressed: compressed))
  115. }, promise: promise)
  116. }
  117. /// Terminates a stream of messages sent to the service.
  118. ///
  119. /// - Important: This should only ever be called once.
  120. /// - Parameter promise: A promise to be fulfilled when the end has been sent.
  121. public func sendEnd(promise: EventLoopPromise<Void>?) {
  122. self.transport.sendRequest(.end, promise: promise)
  123. }
  124. internal init(
  125. transport: ChannelTransport<RequestPayload, ResponsePayload>,
  126. options: CallOptions
  127. ) {
  128. self.transport = transport
  129. self.options = options
  130. }
  131. internal func sendHead(_ head: _GRPCRequestHead) {
  132. self.transport.sendRequest(.head(head), promise: nil)
  133. }
  134. }
  135. extension BidirectionalStreamingCall {
  136. internal static func makeOnHTTP2Stream<
  137. Serializer: MessageSerializer,
  138. Deserializer: MessageDeserializer
  139. >(
  140. multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>,
  141. serializer: Serializer,
  142. deserializer: Deserializer,
  143. callOptions: CallOptions,
  144. errorDelegate: ClientErrorDelegate?,
  145. logger: Logger,
  146. responseHandler: @escaping (ResponsePayload) -> Void
  147. ) -> BidirectionalStreamingCall<RequestPayload, ResponsePayload>
  148. where Serializer.Input == RequestPayload, Deserializer.Output == ResponsePayload {
  149. let eventLoop = multiplexer.eventLoop
  150. let transport = ChannelTransport<RequestPayload, ResponsePayload>(
  151. multiplexer: multiplexer,
  152. serializer: serializer,
  153. deserializer: deserializer,
  154. responseContainer: .init(eventLoop: eventLoop, streamingResponseHandler: responseHandler),
  155. callType: .bidirectionalStreaming,
  156. timeLimit: callOptions.timeLimit,
  157. errorDelegate: errorDelegate,
  158. logger: logger
  159. )
  160. return BidirectionalStreamingCall(transport: transport, options: callOptions)
  161. }
  162. internal static func make<Serializer: MessageSerializer, Deserializer: MessageDeserializer>(
  163. serializer: Serializer,
  164. deserializer: Deserializer,
  165. fakeResponse: FakeStreamingResponse<RequestPayload, ResponsePayload>?,
  166. callOptions: CallOptions,
  167. logger: Logger,
  168. responseHandler: @escaping (ResponsePayload) -> Void
  169. ) -> BidirectionalStreamingCall<RequestPayload, ResponsePayload>
  170. where Serializer.Input == RequestPayload, Deserializer.Output == ResponsePayload {
  171. let eventLoop = fakeResponse?.channel.eventLoop ?? EmbeddedEventLoop()
  172. let responseContainer = ResponsePartContainer(
  173. eventLoop: eventLoop,
  174. streamingResponseHandler: responseHandler
  175. )
  176. let transport: ChannelTransport<RequestPayload, ResponsePayload>
  177. if let fakeResponse = fakeResponse {
  178. transport = .init(
  179. fakeResponse: fakeResponse,
  180. responseContainer: responseContainer,
  181. timeLimit: callOptions.timeLimit,
  182. logger: logger
  183. )
  184. fakeResponse.activate()
  185. } else {
  186. transport = .makeTransportForMissingFakeResponse(
  187. eventLoop: eventLoop,
  188. responseContainer: responseContainer,
  189. logger: logger
  190. )
  191. }
  192. return BidirectionalStreamingCall(transport: transport, options: callOptions)
  193. }
  194. }