2
0

GRPCAsyncBidirectionalStreamingCall.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. * Copyright 2021, 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. #if compiler(>=5.6)
  17. import NIOCore
  18. import NIOHPACK
  19. /// Async-await variant of ``BidirectionalStreamingCall``.
  20. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  21. public struct GRPCAsyncBidirectionalStreamingCall<Request: Sendable, Response: Sendable>: Sendable {
  22. private let call: Call<Request, Response>
  23. private let responseParts: StreamingResponseParts<Response>
  24. private let responseSource: NIOThrowingAsyncSequenceProducer<
  25. Response,
  26. Error,
  27. NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
  28. GRPCAsyncSequenceProducerDelegate
  29. >.Source
  30. private let requestSink: AsyncSink<(Request, Compression)>
  31. /// A request stream writer for sending messages to the server.
  32. public let requestStream: GRPCAsyncRequestStreamWriter<Request>
  33. /// The stream of responses from the server.
  34. public let responseStream: GRPCAsyncResponseStream<Response>
  35. /// The options used to make the RPC.
  36. public var options: CallOptions {
  37. return self.call.options
  38. }
  39. /// The path used to make the RPC.
  40. public var path: String {
  41. return self.call.path
  42. }
  43. /// Cancel this RPC if it hasn't already completed.
  44. public func cancel() {
  45. self.call.cancel(promise: nil)
  46. }
  47. // MARK: - Response Parts
  48. /// The initial metadata returned from the server.
  49. ///
  50. /// - Important: The initial metadata will only be available when the first response has been
  51. /// received. However, it is not necessary for the response to have been consumed before reading
  52. /// this property.
  53. public var initialMetadata: HPACKHeaders {
  54. get async throws {
  55. try await self.responseParts.initialMetadata.get()
  56. }
  57. }
  58. /// The trailing metadata returned from the server.
  59. ///
  60. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  61. public var trailingMetadata: HPACKHeaders {
  62. get async throws {
  63. try await self.responseParts.trailingMetadata.get()
  64. }
  65. }
  66. /// The final status of the the RPC.
  67. ///
  68. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  69. public var status: GRPCStatus {
  70. get async {
  71. // force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
  72. try! await self.responseParts.status.get()
  73. }
  74. }
  75. private init(call: Call<Request, Response>) {
  76. self.call = call
  77. self.responseParts = StreamingResponseParts(on: call.eventLoop) { _ in }
  78. let sequenceProducer = NIOThrowingAsyncSequenceProducer<
  79. Response,
  80. Error,
  81. NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
  82. GRPCAsyncSequenceProducerDelegate
  83. >.makeSequence(
  84. backPressureStrategy: .init(lowWatermark: 10, highWatermark: 50),
  85. delegate: GRPCAsyncSequenceProducerDelegate()
  86. )
  87. self.responseSource = sequenceProducer.source
  88. self.responseStream = .init(sequenceProducer.sequence)
  89. let (requestStream, requestSink) = call.makeRequestStreamWriter()
  90. self.requestStream = requestStream
  91. self.requestSink = AsyncSink(wrapping: requestSink)
  92. }
  93. /// We expose this as the only non-private initializer so that the caller
  94. /// knows that invocation is part of initialisation.
  95. internal static func makeAndInvoke(call: Call<Request, Response>) -> Self {
  96. let asyncCall = Self(call: call)
  97. asyncCall.call.invokeStreamingRequests(
  98. onStart: {
  99. asyncCall.requestSink.setWritability(to: true)
  100. },
  101. onError: { error in
  102. asyncCall.responseParts.handleError(error)
  103. asyncCall.responseSource.finish(error)
  104. asyncCall.requestSink.finish(error: error)
  105. },
  106. onResponsePart: AsyncCall.makeResponsePartHandler(
  107. responseParts: asyncCall.responseParts,
  108. responseSource: asyncCall.responseSource,
  109. requestStream: asyncCall.requestStream
  110. )
  111. )
  112. return asyncCall
  113. }
  114. }
  115. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  116. internal enum AsyncCall {
  117. internal static func makeResponsePartHandler<Response, Request>(
  118. responseParts: StreamingResponseParts<Response>,
  119. responseSource: NIOThrowingAsyncSequenceProducer<
  120. Response,
  121. Error,
  122. NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
  123. GRPCAsyncSequenceProducerDelegate
  124. >.Source,
  125. requestStream: GRPCAsyncRequestStreamWriter<Request>?,
  126. requestType: Request.Type = Request.self
  127. ) -> (GRPCClientResponsePart<Response>) -> Void {
  128. return { responsePart in
  129. // Handle the metadata, trailers and status.
  130. responseParts.handle(responsePart)
  131. // Handle the response messages and status.
  132. switch responsePart {
  133. case .metadata:
  134. ()
  135. case let .message(response):
  136. // TODO: when we support backpressure we will need to stop ignoring the return value.
  137. _ = responseSource.yield(response)
  138. case let .end(status, _):
  139. if status.isOk {
  140. responseSource.finish()
  141. } else {
  142. responseSource.finish(status)
  143. }
  144. requestStream?.finish(status)
  145. }
  146. }
  147. }
  148. internal static func makeResponsePartHandler<Response, Request>(
  149. responseParts: UnaryResponseParts<Response>,
  150. requestStream: GRPCAsyncRequestStreamWriter<Request>?,
  151. requestType: Request.Type = Request.self,
  152. responseType: Response.Type = Response.self
  153. ) -> (GRPCClientResponsePart<Response>) -> Void {
  154. return { responsePart in
  155. // Handle (most of) all parts.
  156. responseParts.handle(responsePart)
  157. // Handle the status.
  158. switch responsePart {
  159. case .metadata, .message:
  160. ()
  161. case let .end(status, _):
  162. requestStream?.finish(status)
  163. }
  164. }
  165. }
  166. }
  167. #endif