GRPCAsyncBidirectionalStreamingCall.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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> {
  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. // swiftformat:disable:next redundantGet
  44. get async throws {
  45. try await self.responseParts.initialMetadata.get()
  46. }
  47. }
  48. /// The trailing metadata returned from the server.
  49. ///
  50. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  51. public var trailingMetadata: HPACKHeaders {
  52. // swiftformat:disable:next redundantGet
  53. get async throws {
  54. try await self.responseParts.trailingMetadata.get()
  55. }
  56. }
  57. /// The final status of the the RPC.
  58. ///
  59. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  60. public var status: GRPCStatus {
  61. // swiftformat:disable:next redundantGet
  62. get async {
  63. // force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
  64. try! await self.responseParts.status.get()
  65. }
  66. }
  67. private init(call: Call<Request, Response>) {
  68. self.call = call
  69. self.responseParts = StreamingResponseParts(on: call.eventLoop) { _ in }
  70. self.responseSource = PassthroughMessageSource<Response, Error>()
  71. self.responseStream = .init(PassthroughMessageSequence(consuming: self.responseSource))
  72. self.requestStream = call.makeRequestStreamWriter()
  73. }
  74. /// We expose this as the only non-private initializer so that the caller
  75. /// knows that invocation is part of initialisation.
  76. internal static func makeAndInvoke(call: Call<Request, Response>) -> Self {
  77. let asyncCall = Self(call: call)
  78. asyncCall.call.invokeStreamingRequests(
  79. onError: { error in
  80. asyncCall.responseParts.handleError(error)
  81. asyncCall.responseSource.finish(throwing: error)
  82. },
  83. onResponsePart: AsyncCall.makeResponsePartHandler(
  84. responseParts: asyncCall.responseParts,
  85. responseSource: asyncCall.responseSource
  86. )
  87. )
  88. return asyncCall
  89. }
  90. }
  91. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  92. internal enum AsyncCall {
  93. internal static func makeResponsePartHandler<Response>(
  94. responseParts: StreamingResponseParts<Response>,
  95. responseSource: PassthroughMessageSource<Response, Error>
  96. ) -> (GRPCClientResponsePart<Response>) -> Void {
  97. return { responsePart in
  98. // Handle the metadata, trailers and status.
  99. responseParts.handle(responsePart)
  100. // Handle the response messages and status.
  101. switch responsePart {
  102. case .metadata:
  103. ()
  104. case let .message(response):
  105. // TODO: when we support backpressure we will need to stop ignoring the return value.
  106. _ = responseSource.yield(response)
  107. case let .end(status, _):
  108. if status.isOk {
  109. responseSource.finish()
  110. } else {
  111. responseSource.finish(throwing: status)
  112. }
  113. }
  114. }
  115. }
  116. }
  117. #endif