BidirectionalStreamingCall.swift 7.6 KB

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