GRPCAsyncResponseStream.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 NIOCore
  18. /// This is currently a wrapper around AsyncThrowingStream because we want to be
  19. /// able to swap out the implementation for something else in the future.
  20. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  21. public struct GRPCAsyncResponseStream<Element: Sendable>: AsyncSequence {
  22. @usableFromInline
  23. internal typealias WrappedStream = NIOThrowingAsyncSequenceProducer<
  24. Element,
  25. Error,
  26. NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
  27. GRPCAsyncSequenceProducerDelegate
  28. >
  29. @usableFromInline
  30. internal let stream: WrappedStream
  31. @inlinable
  32. internal init(_ stream: WrappedStream) {
  33. self.stream = stream
  34. }
  35. public func makeAsyncIterator() -> Iterator {
  36. Self.AsyncIterator(self.stream)
  37. }
  38. public struct Iterator: AsyncIteratorProtocol {
  39. @usableFromInline
  40. internal var iterator: WrappedStream.AsyncIterator
  41. fileprivate init(_ stream: WrappedStream) {
  42. self.iterator = stream.makeAsyncIterator()
  43. }
  44. @inlinable
  45. public mutating func next() async throws -> Element? {
  46. if Task.isCancelled { throw GRPCStatus(code: .cancelled) }
  47. return try await self.iterator.next()
  48. }
  49. }
  50. }
  51. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  52. extension GRPCAsyncResponseStream: Sendable {}
  53. #endif