GRPCAsyncBidirectionalStreamingCall.swift 5.6 KB

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