GRPCAsyncServerStreamingCall.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. import NIOCore
  17. import NIOHPACK
  18. /// Async-await variant of ``ServerStreamingCall``.
  19. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  20. public struct GRPCAsyncServerStreamingCall<Request: Sendable, Response: Sendable> {
  21. private let call: Call<Request, Response>
  22. private let responseParts: StreamingResponseParts<Response>
  23. private let responseSource: NIOThrowingAsyncSequenceProducer<
  24. Response,
  25. Error,
  26. NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
  27. GRPCAsyncSequenceProducerDelegate
  28. >.Source
  29. /// The stream of responses from the server.
  30. public let responseStream: GRPCAsyncResponseStream<Response>
  31. /// The options used to make the RPC.
  32. public var options: CallOptions {
  33. return self.call.options
  34. }
  35. /// The path used to make the RPC.
  36. public var path: String {
  37. return self.call.path
  38. }
  39. /// Cancel this RPC if it hasn't already completed.
  40. public func cancel() {
  41. self.call.cancel(promise: nil)
  42. }
  43. // MARK: - Response Parts
  44. private func withRPCCancellation<R: Sendable>(_ fn: () async throws -> R) async rethrows -> R {
  45. return try await withTaskCancellationHandler(operation: fn) {
  46. self.cancel()
  47. }
  48. }
  49. /// The initial metadata returned from the server.
  50. ///
  51. /// - Important: The initial metadata will only be available when the first response has been
  52. /// received. However, it is not necessary for the response to have been consumed before reading
  53. /// this property.
  54. public var initialMetadata: HPACKHeaders {
  55. get async throws {
  56. try await self.withRPCCancellation {
  57. try await self.responseParts.initialMetadata.get()
  58. }
  59. }
  60. }
  61. /// The trailing metadata returned from the server.
  62. ///
  63. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  64. public var trailingMetadata: HPACKHeaders {
  65. get async throws {
  66. try await self.withRPCCancellation {
  67. try await self.responseParts.trailingMetadata.get()
  68. }
  69. }
  70. }
  71. /// The final status of the the RPC.
  72. ///
  73. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  74. public var status: GRPCStatus {
  75. get async {
  76. // force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
  77. await self.withRPCCancellation {
  78. try! await self.responseParts.status.get()
  79. }
  80. }
  81. }
  82. private init(call: Call<Request, Response>) {
  83. self.call = call
  84. // We ignore messages in the closure and instead feed them into the response source when we
  85. // invoke the `call`.
  86. self.responseParts = StreamingResponseParts(on: call.eventLoop) { _ in }
  87. let backpressureStrategy = NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark(
  88. lowWatermark: 10,
  89. highWatermark: 50
  90. )
  91. let sequenceProducer = NIOThrowingAsyncSequenceProducer.makeSequence(
  92. elementType: Response.self,
  93. failureType: Error.self,
  94. backPressureStrategy: backpressureStrategy,
  95. delegate: GRPCAsyncSequenceProducerDelegate()
  96. )
  97. self.responseSource = sequenceProducer.source
  98. self.responseStream = .init(sequenceProducer.sequence)
  99. }
  100. /// We expose this as the only non-private initializer so that the caller
  101. /// knows that invocation is part of initialisation.
  102. internal static func makeAndInvoke(
  103. call: Call<Request, Response>,
  104. _ request: Request
  105. ) -> Self {
  106. let asyncCall = Self(call: call)
  107. asyncCall.call.invokeUnaryRequest(
  108. request,
  109. onStart: {},
  110. onError: { error in
  111. asyncCall.responseParts.handleError(error)
  112. asyncCall.responseSource.finish(error)
  113. },
  114. onResponsePart: AsyncCall.makeResponsePartHandler(
  115. responseParts: asyncCall.responseParts,
  116. responseSource: asyncCall.responseSource,
  117. requestStream: nil,
  118. requestType: Request.self
  119. )
  120. )
  121. return asyncCall
  122. }
  123. }