GRPCAsyncBidirectionalStreamingCall.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. },
  80. onResponsePart: AsyncCall.makeResponsePartHandler(
  81. responseParts: asyncCall.responseParts,
  82. responseSource: asyncCall.responseSource
  83. )
  84. )
  85. return asyncCall
  86. }
  87. }
  88. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  89. internal enum AsyncCall {
  90. internal static func makeResponsePartHandler<Response>(
  91. responseParts: StreamingResponseParts<Response>,
  92. responseSource: PassthroughMessageSource<Response, Error>
  93. ) -> (GRPCClientResponsePart<Response>) -> Void {
  94. return { responsePart in
  95. // Handle the metadata, trailers and status.
  96. responseParts.handle(responsePart)
  97. // Handle the response messages and status.
  98. switch responsePart {
  99. case .metadata:
  100. ()
  101. case let .message(response):
  102. // TODO: when we support backpressure we will need to stop ignoring the return value.
  103. _ = responseSource.yield(response)
  104. case let .end(status, _):
  105. if status.isOk {
  106. responseSource.finish()
  107. } else {
  108. responseSource.finish(throwing: status)
  109. }
  110. }
  111. }
  112. }
  113. }
  114. #endif