GRPCAsyncServerStreamingCall.swift 4.5 KB

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