GRPCAsyncBidirectionalStreamingCall.swift 6.1 KB

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