GRPCAsyncResponseStream.swift 1.9 KB

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