2
0

GRPCAsyncBidirectionalStreamingCall.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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() async throws {
  34. try await self.call.cancel().get()
  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. onError: { error in
  77. asyncCall.responseParts.handleError(error)
  78. asyncCall.responseSource.finish(throwing: error)
  79. asyncCall.requestStream.asyncWriter.cancelAsynchronously()
  80. },
  81. onResponsePart: AsyncCall.makeResponsePartHandler(
  82. responseParts: asyncCall.responseParts,
  83. responseSource: asyncCall.responseSource,
  84. requestStream: asyncCall.requestStream
  85. )
  86. )
  87. return asyncCall
  88. }
  89. }
  90. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  91. internal enum AsyncCall {
  92. internal static func makeResponsePartHandler<Response, Request>(
  93. responseParts: StreamingResponseParts<Response>,
  94. responseSource: PassthroughMessageSource<Response, Error>,
  95. requestStream: GRPCAsyncRequestStreamWriter<Request>?,
  96. requestType: Request.Type = Request.self
  97. ) -> (GRPCClientResponsePart<Response>) -> Void {
  98. return { responsePart in
  99. // Handle the metadata, trailers and status.
  100. responseParts.handle(responsePart)
  101. // Handle the response messages and status.
  102. switch responsePart {
  103. case .metadata:
  104. ()
  105. case let .message(response):
  106. // TODO: when we support backpressure we will need to stop ignoring the return value.
  107. _ = responseSource.yield(response)
  108. case let .end(status, _):
  109. if status.isOk {
  110. responseSource.finish()
  111. } else {
  112. responseSource.finish(throwing: status)
  113. }
  114. requestStream?.asyncWriter.cancelAsynchronously()
  115. }
  116. }
  117. }
  118. internal static func makeResponsePartHandler<Response, Request>(
  119. responseParts: UnaryResponseParts<Response>,
  120. requestStream: GRPCAsyncRequestStreamWriter<Request>?,
  121. requestType: Request.Type = Request.self,
  122. responseType: Response.Type = Response.self
  123. ) -> (GRPCClientResponsePart<Response>) -> Void {
  124. return { responsePart in
  125. // Handle (most of) all parts.
  126. responseParts.handle(responsePart)
  127. // Handle the status.
  128. switch responsePart {
  129. case .metadata, .message:
  130. ()
  131. case .end:
  132. requestStream?.asyncWriter.cancelAsynchronously()
  133. }
  134. }
  135. }
  136. }
  137. #endif