GRPCAsyncBidirectionalStreamingCall.swift 5.4 KB

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