BidirectionalStreamingCall.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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<
  25. RequestPayload: GRPCPayload,
  26. ResponsePayload: GRPCPayload
  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.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  91. let messageContext = _MessageContext(message, compressed: compressed)
  92. self.transport.sendRequest(.message(messageContext), promise: promise)
  93. }
  94. /// Sends a sequence of messages to the service.
  95. ///
  96. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or
  97. /// `sendEnd(promise:)`.
  98. ///
  99. /// - Parameters:
  100. /// - messages: The sequence of messages to send.
  101. /// - compression: Whether compression should be used for this message. Ignored if compression
  102. /// was not enabled for the RPC.
  103. /// - promise: A promise to fulfill with the outcome of the send operation. It will only succeed
  104. /// if all messages were written successfully.
  105. public func sendMessages<S>(
  106. _ messages: S,
  107. compression: Compression = .deferToCallDefault,
  108. promise: EventLoopPromise<Void>?
  109. ) where S: Sequence, S.Element == RequestPayload {
  110. let compressed = compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  111. self.transport.sendRequests(messages.map {
  112. .message(_MessageContext($0, compressed: compressed))
  113. }, promise: promise)
  114. }
  115. /// Terminates a stream of messages sent to the service.
  116. ///
  117. /// - Important: This should only ever be called once.
  118. /// - Parameter promise: A promise to be fulfilled when the end has been sent.
  119. public func sendEnd(promise: EventLoopPromise<Void>?) {
  120. self.transport.sendRequest(.end, promise: promise)
  121. }
  122. internal init(
  123. transport: ChannelTransport<RequestPayload, ResponsePayload>,
  124. options: CallOptions
  125. ) {
  126. self.transport = transport
  127. self.options = options
  128. }
  129. internal func sendHead(_ head: _GRPCRequestHead) {
  130. self.transport.sendRequest(.head(head), promise: nil)
  131. }
  132. }
  133. extension BidirectionalStreamingCall {
  134. internal static func makeOnHTTP2Stream(
  135. multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>,
  136. callOptions: CallOptions,
  137. errorDelegate: ClientErrorDelegate?,
  138. logger: Logger,
  139. responseHandler: @escaping (ResponsePayload) -> Void
  140. ) -> BidirectionalStreamingCall<RequestPayload, ResponsePayload> {
  141. let eventLoop = multiplexer.eventLoop
  142. let transport = ChannelTransport<RequestPayload, ResponsePayload>(
  143. multiplexer: multiplexer,
  144. responseContainer: .init(eventLoop: eventLoop, streamingResponseHandler: responseHandler),
  145. callType: .bidirectionalStreaming,
  146. timeLimit: callOptions.timeLimit,
  147. errorDelegate: errorDelegate,
  148. logger: logger
  149. )
  150. return BidirectionalStreamingCall(transport: transport, options: callOptions)
  151. }
  152. internal static func make(
  153. fakeResponse: FakeStreamingResponse<RequestPayload, ResponsePayload>?,
  154. callOptions: CallOptions,
  155. logger: Logger,
  156. responseHandler: @escaping (ResponsePayload) -> Void
  157. ) -> BidirectionalStreamingCall<RequestPayload, ResponsePayload> {
  158. let eventLoop = fakeResponse?.channel.eventLoop ?? EmbeddedEventLoop()
  159. let responseContainer = ResponsePartContainer(eventLoop: eventLoop, streamingResponseHandler: responseHandler)
  160. let transport: ChannelTransport<RequestPayload, ResponsePayload>
  161. if let fakeResponse = fakeResponse {
  162. transport = .init(
  163. fakeResponse: fakeResponse,
  164. responseContainer: responseContainer,
  165. timeLimit: callOptions.timeLimit,
  166. logger: logger
  167. )
  168. fakeResponse.activate()
  169. } else {
  170. transport = .makeTransportForMissingFakeResponse(
  171. eventLoop: eventLoop,
  172. responseContainer: responseContainer,
  173. logger: logger
  174. )
  175. }
  176. return BidirectionalStreamingCall(transport: transport, options: callOptions)
  177. }
  178. }