GRPCAsyncBidirectionalStreamingCall.swift 6.5 KB

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