mirror of
https://github.com/apple/swift-nio
synced 2026-11-30 05:28:44 +00:00
Adopt NIOThrowingAsyncSequenceProducer (#2879)
### Motivation: Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code duplication. ### Modifications: Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem `DirectoryEntryProducer` and `FileChunkProducer` ### Result: No functional changes. Internal changes reduce code duplication.
This commit is contained in:
1 parent
530aa8d304
commit
282f5935cf
4 files changed
+337
-165
No files matched your search
@@ -16,6 +16,7 @@
|
||||
import CNIODarwin
|
||||
import CNIOLinux
|
||||
import NIOConcurrencyHelpers
|
||||
import NIOCore
|
||||
import NIOPosix
|
||||
@preconcurrency import SystemPackage
|
||||
|
||||
@@ -89,17 +90,17 @@ extension DirectoryEntries {
|
||||
public typealias AsyncIterator = BatchedIterator
|
||||
public typealias Element = [DirectoryEntry]
|
||||
|
||||
private let stream: BufferedOrAnyStream<[DirectoryEntry]>
|
||||
private let stream: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>
|
||||
|
||||
/// Creates a ``DirectoryEntries/Batched`` sequence by wrapping an `AsyncSequence`
|
||||
/// of directory entry batches.
|
||||
public init<S: AsyncSequence>(wrapping sequence: S) where S.Element == Element {
|
||||
self.stream = BufferedOrAnyStream(wrapping: sequence)
|
||||
self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence)
|
||||
}
|
||||
|
||||
fileprivate init(handle: SystemFileHandle, recursive: Bool) {
|
||||
// Expanding the batches yields watermarks of 256 and 512 directory entries.
|
||||
let stream = BufferedStream.makeBatchedDirectoryEntryStream(
|
||||
let stream = NIOThrowingAsyncSequenceProducer.makeBatchedDirectoryEntryStream(
|
||||
handle: handle,
|
||||
recursive: recursive,
|
||||
entriesPerBatch: 64,
|
||||
@@ -116,9 +117,11 @@ extension DirectoryEntries {
|
||||
|
||||
/// An `AsyncIteratorProtocol` of `Array<DirectoryEntry>`.
|
||||
public struct BatchedIterator: AsyncIteratorProtocol {
|
||||
private var iterator: BufferedOrAnyStream<[DirectoryEntry]>.AsyncIterator
|
||||
private var iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator
|
||||
|
||||
init(wrapping iterator: BufferedOrAnyStream<[DirectoryEntry]>.AsyncIterator) {
|
||||
fileprivate init(
|
||||
wrapping iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator
|
||||
) {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
@@ -135,52 +138,95 @@ extension DirectoryEntries.Batched.AsyncIterator: Sendable {}
|
||||
// MARK: - Internal
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension BufferedStream where Element == [DirectoryEntry] {
|
||||
extension NIOThrowingAsyncSequenceProducer
|
||||
where
|
||||
Element == [DirectoryEntry],
|
||||
Failure == (any Error),
|
||||
Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
Delegate == DirectoryEntryProducer
|
||||
{
|
||||
fileprivate static func makeBatchedDirectoryEntryStream(
|
||||
handle: SystemFileHandle,
|
||||
recursive: Bool,
|
||||
entriesPerBatch: Int,
|
||||
lowWatermark: Int,
|
||||
highWatermark: Int
|
||||
) -> BufferedStream<[DirectoryEntry]> {
|
||||
let state = DirectoryEnumerator(handle: handle, recursive: recursive)
|
||||
let protectedState = NIOLockedValueBox(state)
|
||||
|
||||
var (stream, source) = BufferedStream.makeStream(
|
||||
of: [DirectoryEntry].self,
|
||||
backPressureStrategy: .watermark(low: lowWatermark, high: highWatermark)
|
||||
)
|
||||
|
||||
source.onTermination = {
|
||||
guard let threadPool = protectedState.withLockedValue({ $0.threadPoolForClosing() }) else {
|
||||
return
|
||||
}
|
||||
|
||||
threadPool.submit { _ in // always run, even if cancelled
|
||||
protectedState.withLockedValue { state in
|
||||
state.closeIfNecessary()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
) -> NIOThrowingAsyncSequenceProducer<
|
||||
[DirectoryEntry], any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
DirectoryEntryProducer
|
||||
> {
|
||||
let producer = DirectoryEntryProducer(
|
||||
state: protectedState,
|
||||
source: source,
|
||||
handle: handle,
|
||||
recursive: recursive,
|
||||
entriesPerBatch: entriesPerBatch
|
||||
)
|
||||
// Start producing immediately.
|
||||
producer.produceMore()
|
||||
|
||||
return stream
|
||||
let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence(
|
||||
elementType: [DirectoryEntry].self,
|
||||
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark(
|
||||
lowWatermark: lowWatermark,
|
||||
highWatermark: highWatermark
|
||||
),
|
||||
finishOnDeinit: false,
|
||||
delegate: producer
|
||||
)
|
||||
|
||||
producer.setSequenceProducerSource(nioThrowingAsyncSequence.source)
|
||||
|
||||
return nioThrowingAsyncSequence.sequence
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct DirectoryEntryProducer {
|
||||
private typealias DirectoryEntrySequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
[DirectoryEntry], Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, DirectoryEntryProducer
|
||||
>
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private final class DirectoryEntryProducer: NIOAsyncSequenceProducerDelegate {
|
||||
let state: NIOLockedValueBox<DirectoryEnumerator>
|
||||
let source: BufferedStream<[DirectoryEntry]>.Source
|
||||
let entriesPerBatch: Int
|
||||
|
||||
init(handle: SystemFileHandle, recursive: Bool, entriesPerBatch: Int) {
|
||||
let state = DirectoryEnumerator(handle: handle, recursive: recursive)
|
||||
self.state = NIOLockedValueBox(state)
|
||||
self.entriesPerBatch = entriesPerBatch
|
||||
}
|
||||
|
||||
func didTerminate() {
|
||||
guard let threadPool = self.state.withLockedValue({ $0.threadPoolForClosing() }) else {
|
||||
return
|
||||
}
|
||||
|
||||
threadPool.submit { _ in // always run, even if cancelled
|
||||
self.state.withLockedValue { state in
|
||||
state.closeIfNecessary()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// sets the source within the producer state
|
||||
func setSequenceProducerSource(_ sequenceProducerSource: DirectoryEntrySequenceProducer.Source) {
|
||||
self.state.withLockedValue { state in
|
||||
switch state.state {
|
||||
case .idle:
|
||||
state.sequenceProducerSource = sequenceProducerSource
|
||||
case .done:
|
||||
sequenceProducerSource.finish()
|
||||
case .open, .openPausedProducing:
|
||||
fatalError()
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clearSource() {
|
||||
self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The 'entry point' for producing elements.
|
||||
///
|
||||
/// Calling this function will start producing directory entries asynchronously by dispatching
|
||||
@@ -207,6 +253,12 @@ private struct DirectoryEntryProducer {
|
||||
}
|
||||
}
|
||||
|
||||
func pauseProducing() {
|
||||
self.state.withLockedValue { state in
|
||||
state.pauseProducing()
|
||||
}
|
||||
}
|
||||
|
||||
private func nextBatch() throws -> [DirectoryEntry] {
|
||||
try self.state.withLockedValue { state in
|
||||
try state.next(self.entriesPerBatch)
|
||||
@@ -221,14 +273,28 @@ private struct DirectoryEntryProducer {
|
||||
// Failed to read more entries: close and notify the stream so consumers receive the
|
||||
// error.
|
||||
self.close()
|
||||
self.source.finish(throwing: error)
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource
|
||||
}
|
||||
source?.finish(error)
|
||||
self.clearSource()
|
||||
}
|
||||
}
|
||||
|
||||
private func onNextBatch(_ entries: [DirectoryEntry]) {
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource
|
||||
}
|
||||
|
||||
guard let source else {
|
||||
assertionFailure("unexpectedly missing source")
|
||||
return
|
||||
}
|
||||
|
||||
// No entries were read: this must be the end (as the batch size must be greater than zero).
|
||||
if entries.isEmpty {
|
||||
self.source.finish(throwing: nil)
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -236,30 +302,22 @@ private struct DirectoryEntryProducer {
|
||||
let readEOF = entries.count < self.entriesPerBatch
|
||||
|
||||
// Entries were produced: yield them and maybe produce more.
|
||||
do {
|
||||
let writeResult = try self.source.write(contentsOf: CollectionOfOne(entries))
|
||||
// Exit early if EOF was read; no use in trying to produce more.
|
||||
if readEOF {
|
||||
self.source.finish(throwing: nil)
|
||||
return
|
||||
}
|
||||
let writeResult = source.yield(contentsOf: CollectionOfOne(entries))
|
||||
|
||||
switch writeResult {
|
||||
case .produceMore:
|
||||
self.produceMore()
|
||||
case let .enqueueCallback(token):
|
||||
self.source.enqueueCallback(callbackToken: token) {
|
||||
switch $0 {
|
||||
case .success:
|
||||
self.produceMore()
|
||||
case .failure:
|
||||
self.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Failure to write means the source is already done, that's okay we just need to
|
||||
// update our state and stop producing.
|
||||
// Exit early if EOF was read; no use in trying to produce more.
|
||||
if readEOF {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
switch writeResult {
|
||||
case .produceMore:
|
||||
self.produceMore()
|
||||
case .stopProducing:
|
||||
self.pauseProducing()
|
||||
case .dropped:
|
||||
// The source is finished; mark ourselves as done.
|
||||
self.close()
|
||||
}
|
||||
}
|
||||
@@ -282,25 +340,30 @@ private struct DirectoryEntryProducer {
|
||||
/// Note that this is not a `Sequence` because we allow for errors to be thrown on `next()`.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct DirectoryEnumerator: Sendable {
|
||||
private enum State: @unchecked Sendable {
|
||||
internal enum State: @unchecked Sendable {
|
||||
case modifying
|
||||
case idle(SystemFileHandle.SendableView, recursive: Bool)
|
||||
case open(NIOThreadPool, Source, [DirectoryEntry])
|
||||
case openPausedProducing(NIOThreadPool, Source, [DirectoryEntry])
|
||||
case done
|
||||
}
|
||||
|
||||
/// The source of directory entries.
|
||||
private enum Source {
|
||||
internal enum Source {
|
||||
case readdir(CInterop.DirPointer)
|
||||
case fts(CInterop.FTSPointer)
|
||||
}
|
||||
|
||||
/// The current state of enumeration.
|
||||
private var state: State
|
||||
internal var state: State
|
||||
|
||||
/// The path to the directory being enumerated.
|
||||
private let path: FilePath
|
||||
|
||||
/// The route via which directory entry batches are yielded,
|
||||
/// the sourcing end of the `DirectoryEntrySequenceProducer`
|
||||
internal var sequenceProducerSource: DirectoryEntrySequenceProducer.Source?
|
||||
|
||||
/// Information about an entry returned by FTS. See 'fts(3)'.
|
||||
private enum FTSInfo: Hashable, Sendable {
|
||||
case directoryPreOrder
|
||||
@@ -353,12 +416,15 @@ private struct DirectoryEnumerator: Sendable {
|
||||
self.path = handle.path
|
||||
}
|
||||
|
||||
internal func produceMore() -> NIOThreadPool? {
|
||||
internal mutating func produceMore() -> NIOThreadPool? {
|
||||
switch self.state {
|
||||
case let .idle(handle, _):
|
||||
return handle.threadPool
|
||||
case let .open(threadPool, _, _):
|
||||
return threadPool
|
||||
case .openPausedProducing(let threadPool, let source, let array):
|
||||
self.state = .open(threadPool, source, array)
|
||||
return threadPool
|
||||
case .done:
|
||||
return nil
|
||||
case .modifying:
|
||||
@@ -366,9 +432,22 @@ private struct DirectoryEnumerator: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func pauseProducing() {
|
||||
switch self.state {
|
||||
case .open(let threadPool, let source, let array):
|
||||
self.state = .openPausedProducing(threadPool, source, array)
|
||||
case .idle:
|
||||
() // we won't apply back pressure until something has been read
|
||||
case .openPausedProducing, .done:
|
||||
() // no-op
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
internal func threadPoolForClosing() -> NIOThreadPool? {
|
||||
switch self.state {
|
||||
case let .open(threadPool, _, _):
|
||||
case .open(let threadPool, _, _), .openPausedProducing(let threadPool, _, _):
|
||||
return threadPool
|
||||
case .idle, .done:
|
||||
// Don't need to close in the idle state: we don't own the handle.
|
||||
@@ -397,7 +476,7 @@ private struct DirectoryEnumerator: Sendable {
|
||||
// We don't own the handle so don't close it.
|
||||
self.state = .done
|
||||
|
||||
case let .open(_, mode, _):
|
||||
case .open(_, let mode, _), .openPausedProducing(_, let mode, _):
|
||||
self.state = .done
|
||||
switch mode {
|
||||
case .readdir(let dir):
|
||||
@@ -631,6 +710,9 @@ private struct DirectoryEnumerator: Sendable {
|
||||
return result
|
||||
}
|
||||
|
||||
case .openPausedProducing:
|
||||
return .yield(.success([]))
|
||||
|
||||
case .done:
|
||||
return .yield(.success([]))
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ public struct FileChunks: AsyncSequence, Sendable {
|
||||
public typealias Element = ByteBuffer
|
||||
|
||||
/// The underlying buffered stream.
|
||||
private let stream: BufferedOrAnyStream<ByteBuffer>
|
||||
private let stream: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>
|
||||
|
||||
/// Create a ``FileChunks`` sequence backed by wrapping an `AsyncSequence`.
|
||||
public init<S: AsyncSequence & Sendable>(wrapping sequence: S) where S.Element == ByteBuffer {
|
||||
@@ -50,7 +50,7 @@ public struct FileChunks: AsyncSequence, Sendable {
|
||||
|
||||
// TODO: choose reasonable watermarks; this should likely be at least somewhat dependent
|
||||
// on the chunk size.
|
||||
let stream = BufferedStream.makeFileChunksStream(
|
||||
let stream = NIOThrowingAsyncSequenceProducer.makeFileChunksStream(
|
||||
of: ByteBuffer.self,
|
||||
handle: handle,
|
||||
chunkLength: chunkLength.bytes,
|
||||
@@ -67,9 +67,9 @@ public struct FileChunks: AsyncSequence, Sendable {
|
||||
}
|
||||
|
||||
public struct FileChunkIterator: AsyncIteratorProtocol {
|
||||
private var iterator: BufferedOrAnyStream<ByteBuffer>.AsyncIterator
|
||||
private var iterator: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>.AsyncIterator
|
||||
|
||||
fileprivate init(wrapping iterator: BufferedOrAnyStream<ByteBuffer>.AsyncIterator) {
|
||||
fileprivate init(wrapping iterator: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>.AsyncIterator) {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
@@ -85,7 +85,18 @@ extension FileChunks.FileChunkIterator: Sendable {}
|
||||
// MARK: - Internal
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension BufferedStream where Element == ByteBuffer {
|
||||
private typealias FileChunkSequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
ByteBuffer, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, FileChunkProducer
|
||||
>
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension NIOThrowingAsyncSequenceProducer
|
||||
where
|
||||
Element == ByteBuffer,
|
||||
Failure == Error,
|
||||
Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
Delegate == FileChunkProducer
|
||||
{
|
||||
static func makeFileChunksStream(
|
||||
of: Element.Type = Element.self,
|
||||
handle: SystemFileHandle,
|
||||
@@ -93,53 +104,77 @@ extension BufferedStream where Element == ByteBuffer {
|
||||
range: FileChunks.ChunkRange,
|
||||
lowWatermark: Int,
|
||||
highWatermark: Int
|
||||
) -> BufferedStream<ByteBuffer> {
|
||||
let state: ProducerState
|
||||
switch range {
|
||||
case .entireFile:
|
||||
state = ProducerState(handle: handle, range: nil)
|
||||
case .partial(let partialRange):
|
||||
state = ProducerState(handle: handle, range: partialRange)
|
||||
}
|
||||
let protectedState = NIOLockedValueBox(state)
|
||||
) -> FileChunkSequenceProducer {
|
||||
|
||||
var (stream, source) = BufferedStream.makeStream(
|
||||
of: ByteBuffer.self,
|
||||
backPressureStrategy: .watermark(low: lowWatermark, high: highWatermark)
|
||||
)
|
||||
|
||||
source.onTermination = {
|
||||
protectedState.withLockedValue { state in
|
||||
state.done()
|
||||
}
|
||||
}
|
||||
|
||||
// Start producing immediately.
|
||||
let producer = FileChunkProducer(
|
||||
state: protectedState,
|
||||
source: source,
|
||||
path: handle.path,
|
||||
range: range,
|
||||
handle: handle,
|
||||
length: chunkLength
|
||||
)
|
||||
producer.produceMore()
|
||||
|
||||
return stream
|
||||
let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence(
|
||||
elementType: ByteBuffer.self,
|
||||
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark(
|
||||
lowWatermark: 4,
|
||||
highWatermark: 8
|
||||
),
|
||||
finishOnDeinit: false,
|
||||
delegate: producer
|
||||
)
|
||||
|
||||
producer.setSource(nioThrowingAsyncSequence.source)
|
||||
|
||||
return nioThrowingAsyncSequence.sequence
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct FileChunkProducer: Sendable {
|
||||
private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendable {
|
||||
let state: NIOLockedValueBox<ProducerState>
|
||||
let source: BufferedStream<ByteBuffer>.Source
|
||||
|
||||
let path: FilePath
|
||||
let length: Int64
|
||||
|
||||
init(range: FileChunks.ChunkRange, handle: SystemFileHandle, length: Int64) {
|
||||
let state: ProducerState
|
||||
switch range {
|
||||
case .entireFile:
|
||||
state = .init(handle: handle, range: nil)
|
||||
case .partial(let partialRange):
|
||||
state = .init(handle: handle, range: partialRange)
|
||||
}
|
||||
|
||||
self.state = NIOLockedValueBox(state)
|
||||
self.path = handle.path
|
||||
self.length = length
|
||||
}
|
||||
|
||||
/// sets the source within the producer state
|
||||
func setSource(_ source: FileChunkSequenceProducer.Source) {
|
||||
self.state.withLockedValue { state in
|
||||
switch state.state {
|
||||
case .producing, .pausedProducing:
|
||||
state.source = source
|
||||
case .done(let emptyRange):
|
||||
if emptyRange {
|
||||
source.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clearSource() {
|
||||
self.state.withLockedValue { state in
|
||||
state.source = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The 'entry point' for producing elements.
|
||||
///
|
||||
/// Calling this function will start producing file chunks asynchronously by dispatching work
|
||||
/// to the IO executor and feeding the result back to the stream source. On yielding to the
|
||||
/// source it will either produce more or be scheduled to produce more. Stopping production
|
||||
/// is signalled via the stream's 'onTermination' handler.
|
||||
/// is signaled via the stream's 'onTermination' handler.
|
||||
func produceMore() {
|
||||
let threadPool = self.state.withLockedValue { state in
|
||||
state.shouldProduceMore()
|
||||
@@ -193,65 +228,74 @@ private struct FileChunkProducer: Sendable {
|
||||
case let .failure(error):
|
||||
// Failed to read: update our state then notify the stream so consumers receive the
|
||||
// error.
|
||||
self.state.withLockedValue { state in state.done() }
|
||||
self.source.finish(throwing: error)
|
||||
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.done()
|
||||
return state.source
|
||||
}
|
||||
source?.finish(error)
|
||||
self.clearSource()
|
||||
}
|
||||
}
|
||||
|
||||
private func onReadNextChunk(_ bytes: ByteBuffer) {
|
||||
private func onReadNextChunk(_ buffer: ByteBuffer) {
|
||||
// Reading short means EOF.
|
||||
let readEOF = bytes.readableBytes < self.length
|
||||
assert(bytes.readableBytes <= self.length)
|
||||
let readEOF = buffer.readableBytes < self.length
|
||||
assert(buffer.readableBytes <= self.length)
|
||||
|
||||
self.state.withLockedValue { state in
|
||||
let source = self.state.withLockedValue { state in
|
||||
if readEOF {
|
||||
state.readEnd()
|
||||
state.didReadEnd()
|
||||
} else {
|
||||
state.readBytes(bytes.readableBytes)
|
||||
state.didReadBytes(buffer.readableBytes)
|
||||
}
|
||||
return state.source
|
||||
}
|
||||
|
||||
guard let source else {
|
||||
assertionFailure("unexpectedly missing source")
|
||||
return
|
||||
}
|
||||
|
||||
// No bytes were read: this must be the end as length is required to be greater than zero.
|
||||
if bytes.readableBytes == 0 {
|
||||
if buffer.readableBytes == 0 {
|
||||
assert(readEOF, "read zero bytes but did not read EOF")
|
||||
self.source.finish(throwing: nil)
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
// Bytes were produced: yield them and maybe produce more.
|
||||
do {
|
||||
let writeResult = try self.source.write(contentsOf: CollectionOfOne(bytes))
|
||||
// Exit early if EOF was read; no use in trying to produce more.
|
||||
if readEOF {
|
||||
self.source.finish(throwing: nil)
|
||||
return
|
||||
}
|
||||
let writeResult = source.yield(contentsOf: CollectionOfOne(buffer))
|
||||
|
||||
switch writeResult {
|
||||
case .produceMore:
|
||||
self.produceMore()
|
||||
case let .enqueueCallback(token):
|
||||
self.source.enqueueCallback(callbackToken: token) {
|
||||
switch $0 {
|
||||
case .success:
|
||||
self.produceMore()
|
||||
case .failure:
|
||||
// The source is finished; mark ourselves as done.
|
||||
self.state.withLockedValue { state in state.done() }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Failure to write means the source is already done, that's okay we just need to
|
||||
// update our state and stop producing.
|
||||
// Exit early if EOF was read; no use in trying to produce more.
|
||||
if readEOF {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
switch writeResult {
|
||||
case .produceMore:
|
||||
self.produceMore()
|
||||
case .stopProducing:
|
||||
self.state.withLockedValue { state in state.pauseProducing() }
|
||||
case .dropped:
|
||||
// The source is finished; mark ourselves as done.
|
||||
self.state.withLockedValue { state in state.done() }
|
||||
}
|
||||
}
|
||||
|
||||
func didTerminate() {
|
||||
self.state.withLockedValue { state in
|
||||
state.done()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct ProducerState: Sendable {
|
||||
private struct Producing {
|
||||
fileprivate struct Producing {
|
||||
/// The handle to read from.
|
||||
var handle: SystemFileHandle.SendableView
|
||||
|
||||
@@ -262,18 +306,24 @@ private struct ProducerState: Sendable {
|
||||
var range: Range<Int64>?
|
||||
}
|
||||
|
||||
private enum State {
|
||||
internal enum State {
|
||||
/// Can potentially produce values (if the handle is not closed).
|
||||
case producing(Producing)
|
||||
/// Backpressure policy means that we should stop producing new values for now
|
||||
case pausedProducing(Producing)
|
||||
/// Done producing values either by reaching EOF, some error or the stream terminating.
|
||||
case done
|
||||
case done(emptyRange: Bool)
|
||||
}
|
||||
|
||||
private var state: State
|
||||
internal var state: State
|
||||
|
||||
/// The route via which file chunks are yielded,
|
||||
/// the sourcing end of the `FileChunkSequenceProducer`
|
||||
internal var source: FileChunkSequenceProducer.Source?
|
||||
|
||||
init(handle: SystemFileHandle, range: Range<Int64>?) {
|
||||
if let range, range.isEmpty {
|
||||
self.state = .done
|
||||
self.state = .done(emptyRange: true)
|
||||
} else {
|
||||
self.state = .producing(.init(handle: handle.sendableView, range: range))
|
||||
}
|
||||
@@ -283,6 +333,8 @@ private struct ProducerState: Sendable {
|
||||
switch self.state {
|
||||
case let .producing(state):
|
||||
return state.handle.threadPool
|
||||
case .pausedProducing:
|
||||
return nil
|
||||
case .done:
|
||||
return nil
|
||||
}
|
||||
@@ -302,45 +354,77 @@ private struct ProducerState: Sendable {
|
||||
)
|
||||
return .failure(error)
|
||||
}
|
||||
case .pausedProducing:
|
||||
return .success(nil)
|
||||
case .done:
|
||||
return .success(nil)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func readBytes(_ count: Int) {
|
||||
mutating func didReadBytes(_ count: Int) {
|
||||
switch self.state {
|
||||
case var .producing(state):
|
||||
if let currentRange = state.range {
|
||||
let newRange = (currentRange.lowerBound + Int64(count))..<currentRange.upperBound
|
||||
if newRange.lowerBound >= newRange.upperBound {
|
||||
assert(newRange.lowerBound == newRange.upperBound)
|
||||
self.state = .done
|
||||
} else {
|
||||
state.range = newRange
|
||||
self.state = .producing(state)
|
||||
}
|
||||
if state.didReadBytes(count) {
|
||||
self.state = .done(emptyRange: false)
|
||||
} else {
|
||||
if count == 0 {
|
||||
self.state = .done
|
||||
}
|
||||
self.state = .producing(state)
|
||||
}
|
||||
case var .pausedProducing(state):
|
||||
if state.didReadBytes(count) {
|
||||
self.state = .done(emptyRange: false)
|
||||
} else {
|
||||
self.state = .pausedProducing(state)
|
||||
}
|
||||
case .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func readEnd() {
|
||||
mutating func didReadEnd() {
|
||||
switch self.state {
|
||||
case .producing:
|
||||
self.state = .done
|
||||
case .pausedProducing, .producing:
|
||||
self.state = .done(emptyRange: false)
|
||||
case .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func pauseProducing() {
|
||||
switch self.state {
|
||||
case .producing(let state):
|
||||
self.state = .pausedProducing(state)
|
||||
case .pausedProducing, .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func done() {
|
||||
self.state = .done
|
||||
self.state = .done(emptyRange: false)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension ProducerState.Producing {
|
||||
/// Updates the range (the offsets to read from and up to) to reflect the number of bytes which have been read.
|
||||
/// - Parameter count: The number of bytes which have been read.
|
||||
/// - Returns: Returns `True` if there are no remaining bytes to read, `False` otherwise.
|
||||
mutating func didReadBytes(_ count: Int) -> Bool {
|
||||
guard let currentRange = self.range else {
|
||||
// if we read 0 bytes we are done
|
||||
return count == 0
|
||||
}
|
||||
|
||||
let newLowerBound = currentRange.lowerBound + Int64(count)
|
||||
|
||||
// we have run out of bytes to read, we are done
|
||||
if newLowerBound >= currentRange.upperBound {
|
||||
self.range = currentRange.upperBound..<currentRange.upperBound
|
||||
return true
|
||||
}
|
||||
|
||||
// update range, we are not done
|
||||
self.range = newLowerBound..<currentRange.upperBound
|
||||
return false
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -12,15 +12,21 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
|
||||
/// Wraps a ``BufferedStream<Element>`` or ``AnyAsyncSequence<Element>``.
|
||||
/// Wraps a ``NIOThrowingAsyncSequenceProducer<Element>`` or ``AnyAsyncSequence<Element>``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal enum BufferedOrAnyStream<Element> {
|
||||
case bufferedStream(BufferedStream<Element>)
|
||||
internal enum BufferedOrAnyStream<Element, Delegate: NIOAsyncSequenceProducerDelegate> {
|
||||
typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate
|
||||
>
|
||||
|
||||
case nioThrowingAsyncSequenceProducer(AsyncSequenceProducer)
|
||||
case anyAsyncSequence(AnyAsyncSequence<Element>)
|
||||
|
||||
internal init(wrapping stream: BufferedStream<Element>) {
|
||||
self = .bufferedStream(stream)
|
||||
internal init(wrapping stream: AsyncSequenceProducer) {
|
||||
self = .nioThrowingAsyncSequenceProducer(stream)
|
||||
}
|
||||
|
||||
internal init<S: AsyncSequence>(wrapping stream: S) where S.Element == Element {
|
||||
@@ -29,7 +35,7 @@ internal enum BufferedOrAnyStream<Element> {
|
||||
|
||||
internal func makeAsyncIterator() -> AsyncIterator {
|
||||
switch self {
|
||||
case let .bufferedStream(stream):
|
||||
case let .nioThrowingAsyncSequenceProducer(stream):
|
||||
return AsyncIterator(wrapping: stream.makeAsyncIterator())
|
||||
case let .anyAsyncSequence(stream):
|
||||
return AsyncIterator(wrapping: stream.makeAsyncIterator())
|
||||
@@ -37,13 +43,13 @@ internal enum BufferedOrAnyStream<Element> {
|
||||
}
|
||||
|
||||
internal enum AsyncIterator: AsyncIteratorProtocol {
|
||||
case bufferedStream(BufferedStream<Element>.AsyncIterator)
|
||||
case bufferedStream(AsyncSequenceProducer.AsyncIterator)
|
||||
case anyAsyncSequence(AnyAsyncSequence<Element>.AsyncIterator)
|
||||
|
||||
internal mutating func next() async throws -> Element? {
|
||||
let element: Element?
|
||||
switch self {
|
||||
case var .bufferedStream(iterator):
|
||||
case let .bufferedStream(iterator):
|
||||
defer { self = .bufferedStream(iterator) }
|
||||
element = try await iterator.next()
|
||||
case var .anyAsyncSequence(iterator):
|
||||
@@ -53,7 +59,7 @@ internal enum BufferedOrAnyStream<Element> {
|
||||
return element
|
||||
}
|
||||
|
||||
internal init(wrapping iterator: BufferedStream<Element>.AsyncIterator) {
|
||||
internal init(wrapping iterator: AsyncSequenceProducer.AsyncIterator) {
|
||||
self = .bufferedStream(iterator)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user