GRPCAsyncBidirectionalStreamingCall.swift 6.5 KB

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