mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
Better handling of pipes, FIFOs, and terminals. (#3804)
Motivation: NIOFS is able to handle a number of data types that aren't exactly files, like pipes and FIFOs. However, its code mishandles them. These types can read short, unlike files, and several branches in the code don't handle that properly and end up misinterpreting the short read as an EOF. Along the way, there are a number of other bugs on these file types, so we should clean all of those up as well. Modifications: - BufferedReader - Short reads no longer count as EOF. - read() will return whatever is available, potentially returning short. - Non-seekable types always read sequentially. - Non-seekable types now `drop` properly by doing read-and-discard. - Non-zero initial offsets on non-seekable types are now rejected. - BufferedWriter - Non-seekable files now flush sequentially. - Non-zero initial offsets on non-seekable types are now rejected. - Factored out positioning logic to a FileCursor helper - Fixed readChunks to behave better - Fixed readToEnd to avoid over-reading. - No longer add O_NONBLOCK to directory openFile. - Cleaned up some docs. - Added extensive testing of pipes and FIFOs. Result: Much better behaviour around pipes and FIFOs.
This commit is contained in:
1 parent
57b45c9f30
commit
039d70fe60
20 files changed
+2217
-192
No files matched your search
@@ -24,13 +24,24 @@ import NIOCore
|
||||
///
|
||||
/// You can also read bytes without returning them to caller by calling ``drop(_:)`` and
|
||||
/// ``drop(while:)``.
|
||||
///
|
||||
/// - Important: Unseekable files, such as pipes, FIFOs and sockets, are read sequentially. The
|
||||
/// reader must start at offset zero for these files: reading an unseekable file from any other
|
||||
/// starting offset throws an error with code ``FileSystemError/Code-swift.struct/unsupported``.
|
||||
/// Character devices such as terminals aren't detected as unseekable: only reading them at
|
||||
/// offset zero is supported, which means a single chunk.
|
||||
///
|
||||
/// - Important: Reading from some files returns fewer bytes than requested even though the end of
|
||||
/// the file hasn't been reached. This happens for unseekable files when fewer bytes are currently
|
||||
/// available, and for some special files which can be seeked, such as files in Linux's procfs.
|
||||
/// Only an empty read means the end of the file; see ``read(_:)``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct BufferedReader<Handle: ReadableFileHandleProtocol> {
|
||||
/// The handle to read from.
|
||||
private let handle: Handle
|
||||
|
||||
/// The offset for the next read from the file.
|
||||
private var offset: Int64
|
||||
/// Tracks the offset for the next read from the file.
|
||||
private var cursor: FileCursor
|
||||
|
||||
/// Whether the reader has read to the end of the file.
|
||||
private var readEOF = false
|
||||
@@ -53,23 +64,36 @@ public struct BufferedReader<Handle: ReadableFileHandleProtocol> {
|
||||
)
|
||||
precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero")
|
||||
self.handle = readableHandle
|
||||
self.offset = initialOffset
|
||||
self.cursor = FileCursor(initialOffset: initialOffset)
|
||||
self.capacity = capacity
|
||||
self.buffer = ByteBuffer()
|
||||
}
|
||||
|
||||
private mutating func readFromFile(_ count: Int) async throws -> ByteBuffer {
|
||||
let readOffset = try await self.cursor.nextOffset(for: self.handle)
|
||||
let bytes = try await self.handle.readChunk(
|
||||
fromAbsoluteOffset: self.offset,
|
||||
fromAbsoluteOffset: readOffset,
|
||||
length: .bytes(Int64(count))
|
||||
)
|
||||
// Reading short means reading end-of-file.
|
||||
self.readEOF = bytes.readableBytes < count
|
||||
self.offset += Int64(bytes.readableBytes)
|
||||
// Reading short doesn't mean reading end-of-file: not every file returns as many bytes as
|
||||
// were asked for, for example if it's a pipe and fewer bytes are available. Only reading
|
||||
// no bytes at all means end-of-file.
|
||||
self.readEOF = bytes.readableBytes == 0
|
||||
self.cursor.advance(by: Int64(bytes.readableBytes))
|
||||
return bytes
|
||||
}
|
||||
|
||||
/// Read at most `count` bytes from the file; reads short if not enough bytes are available.
|
||||
/// Read at most `count` bytes from the file, returning whatever is available.
|
||||
///
|
||||
/// If the buffer holds `count` bytes they're returned. Otherwise the reader makes a single read from
|
||||
/// the file and returns the bytes it has, which may be fewer than `count`.
|
||||
///
|
||||
/// - Important: The result may be shorter than `count` even though the end of the file hasn't been
|
||||
/// reached. This happens for pipes, FIFOs and sockets when fewer bytes are currently available,
|
||||
/// and for some special files such as files in Linux's procfs. A short result therefore doesn't
|
||||
/// mean the end of the file: only an empty result does, after which `read(while:)` reports
|
||||
/// `readEOF`. To read exactly `count` bytes, keep reading until you have them or get an empty
|
||||
/// result.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - count: The number of bytes to read.
|
||||
@@ -166,13 +190,28 @@ public struct BufferedReader<Handle: ReadableFileHandleProtocol> {
|
||||
|
||||
/// Reads and discards the given number of bytes.
|
||||
///
|
||||
/// For an unseekable file the bytes are read and thrown away, stopping early if the end of the
|
||||
/// file is reached.
|
||||
///
|
||||
/// - Parameter count: The number of bytes to read and discard.
|
||||
public mutating func drop(_ count: Int) async throws {
|
||||
if count > self.buffer.readableBytes {
|
||||
self.offset += Int64(count &- self.buffer.readableBytes)
|
||||
self.buffer.clear()
|
||||
} else {
|
||||
guard count > self.buffer.readableBytes else {
|
||||
self.buffer.moveReaderIndex(forwardBy: count)
|
||||
return
|
||||
}
|
||||
|
||||
var remaining = count &- self.buffer.readableBytes
|
||||
|
||||
// A seekable file is skipped over by moving the offset.
|
||||
let skipped = try await self.cursor.skipIfSeekable(Int64(remaining), for: self.handle)
|
||||
self.buffer.clear()
|
||||
|
||||
if !skipped {
|
||||
// An unseekable file can't be skipped over: the bytes must be read and thrown away.
|
||||
while remaining > 0, !self.readEOF {
|
||||
let chunk = try await self.readFromFile(min(remaining, self.capacity))
|
||||
remaining &-= chunk.readableBytes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,11 +34,19 @@ import NIOCore
|
||||
///
|
||||
/// - Important: You should you call ``BufferedWriter/flush()`` when you have finished appending
|
||||
/// to write any remaining data to the file system.
|
||||
///
|
||||
/// - Important: Unseekable files, such as pipes, FIFOs and sockets, are written sequentially. The
|
||||
/// writer must start at offset zero for these files: writing to an unseekable file from any other
|
||||
/// starting offset throws an error with code ``FileSystemError/Code-swift.struct/unsupported``
|
||||
/// when the buffer is flushed. Character devices such as terminals aren't detected as unseekable:
|
||||
/// only writing them at offset zero is supported, which means a single flush.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
|
||||
private let handle: Handle
|
||||
/// Offset for the next write.
|
||||
private var offset: Int64
|
||||
|
||||
/// Tracks the offset for the next write.
|
||||
private var cursor: FileCursor
|
||||
|
||||
/// A buffer of bytes to write.
|
||||
private var buffer: [UInt8] = []
|
||||
|
||||
@@ -65,7 +73,7 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
|
||||
)
|
||||
precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero")
|
||||
self.handle = writableHandle
|
||||
self.offset = initialOffset
|
||||
self.cursor = FileCursor(initialOffset: initialOffset)
|
||||
self.capacity = capacity
|
||||
}
|
||||
|
||||
@@ -191,8 +199,9 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
|
||||
public mutating func flush() async throws {
|
||||
if self.buffer.isEmpty { return }
|
||||
|
||||
try await self.handle.write(contentsOf: self.buffer, toAbsoluteOffset: self.offset)
|
||||
self.offset += Int64(self.buffer.count)
|
||||
let writeOffset = try await self.cursor.nextOffset(for: self.handle)
|
||||
try await self.handle.write(contentsOf: self.buffer, toAbsoluteOffset: writeOffset)
|
||||
self.cursor.advance(by: Int64(self.buffer.count))
|
||||
|
||||
// The buffer may grow beyond the specified buffer size. Keep the capacity if it's less than
|
||||
// double the intended size, otherwise reclaim the memory.
|
||||
|
||||
@@ -37,6 +37,7 @@ add_library(_NIOFileSystem
|
||||
"Internal/BufferedStream.swift"
|
||||
"Internal/Cancellation.swift"
|
||||
"Internal/Concurrency Primitives/TokenBucket.swift"
|
||||
"Internal/FileCursor.swift"
|
||||
"Internal/ParallelDirCopy.swift"
|
||||
"Internal/ParallelRemoval.swift"
|
||||
"Internal/String+UnsafeUnititializedCapacity.swift"
|
||||
|
||||
@@ -20,11 +20,6 @@ import SystemPackage
|
||||
/// An `AsyncSequence` of ordered chunks read from a file.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct FileChunks: AsyncSequence, Sendable {
|
||||
enum ChunkRange {
|
||||
case entireFile
|
||||
case partial(Range<Int64>)
|
||||
}
|
||||
|
||||
public typealias Element = ByteBuffer
|
||||
|
||||
/// The buffered stream.
|
||||
@@ -42,20 +37,13 @@ public struct FileChunks: AsyncSequence, Sendable {
|
||||
chunkLength: ByteCount,
|
||||
range: Range<Int64>
|
||||
) {
|
||||
let chunkRange: ChunkRange
|
||||
if range.lowerBound == 0, range.upperBound == .max {
|
||||
chunkRange = .entireFile
|
||||
} else {
|
||||
chunkRange = .partial(range)
|
||||
}
|
||||
|
||||
// TODO: choose reasonable watermarks; this should likely be at least somewhat dependent
|
||||
// on the chunk size.
|
||||
let stream = NIOThrowingAsyncSequenceProducer.makeFileChunksStream(
|
||||
of: ByteBuffer.self,
|
||||
handle: handle,
|
||||
chunkLength: chunkLength.bytes,
|
||||
range: chunkRange,
|
||||
range: range,
|
||||
lowWatermark: 4,
|
||||
highWatermark: 8
|
||||
)
|
||||
@@ -102,7 +90,7 @@ where
|
||||
of: Element.Type = Element.self,
|
||||
handle: SystemFileHandle,
|
||||
chunkLength: Int64,
|
||||
range: FileChunks.ChunkRange,
|
||||
range: Range<Int64>,
|
||||
lowWatermark: Int,
|
||||
highWatermark: Int
|
||||
) -> FileChunkSequenceProducer {
|
||||
@@ -136,16 +124,8 @@ private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendabl
|
||||
let path: FilePath
|
||||
let chunkLength: Int64
|
||||
|
||||
init(range: FileChunks.ChunkRange, handle: SystemFileHandle, chunkLength: 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)
|
||||
init(range: Range<Int64>, handle: SystemFileHandle, chunkLength: Int64) {
|
||||
self.state = NIOLockedValueBox(ProducerState(handle: handle, range: range))
|
||||
self.path = handle.path
|
||||
self.chunkLength = chunkLength
|
||||
}
|
||||
@@ -236,18 +216,31 @@ private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendabl
|
||||
try self.state.withLockedValue { state in
|
||||
state.fileReadingState()
|
||||
}.flatMap {
|
||||
if let (descriptor, range) = $0 {
|
||||
if let range {
|
||||
let remainingBytes = range.upperBound - range.lowerBound
|
||||
let clampedLength = min(self.chunkLength, remainingBytes)
|
||||
if let (descriptor, range, readMode) = $0 {
|
||||
// The upper bound of the range is the number of bytes which may still be read; never
|
||||
// read more than that, regardless of how the file is being read.
|
||||
let remainingBytes = range.upperBound - range.lowerBound
|
||||
let clampedLength = min(self.chunkLength, remainingBytes)
|
||||
switch readMode {
|
||||
case .positional:
|
||||
return descriptor.readChunk(
|
||||
fromAbsoluteOffset: range.lowerBound,
|
||||
length: clampedLength
|
||||
).mapError { error in
|
||||
.read(usingSyscall: .pread, error: error, path: self.path, location: .here())
|
||||
).flatMapError { error in
|
||||
// Unseekable files (pipes, FIFOs, sockets) can only be read sequentially,
|
||||
// which is only possible when starting from the beginning of the file.
|
||||
if range.lowerBound == 0, let errno = error as? Errno,
|
||||
errno == .illegalSeek || errno == .noSuchAddressOrDevice
|
||||
{
|
||||
return self.readNextChunkSequentiallyFromNowOn(length: clampedLength)
|
||||
} else {
|
||||
return .failure(
|
||||
.read(usingSyscall: .pread, error: error, path: self.path, location: .here())
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return descriptor.readChunk(length: self.chunkLength).mapError { error in
|
||||
case .sequential:
|
||||
return descriptor.readChunk(length: clampedLength).mapError { error in
|
||||
.read(usingSyscall: .read, error: error, path: self.path, location: .here())
|
||||
}
|
||||
}
|
||||
@@ -258,45 +251,74 @@ private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendabl
|
||||
}.get()
|
||||
}
|
||||
|
||||
private func didReadNextChunk(_ buffer: ByteBuffer) {
|
||||
let chunkLength = self.chunkLength
|
||||
assert(buffer.readableBytes <= chunkLength)
|
||||
private func readNextChunkSequentiallyFromNowOn(length: Int64) -> Result<ByteBuffer, FileSystemError> {
|
||||
// The handle may have been closed, or the stream terminated, while the first read was in
|
||||
// progress, so get the descriptor again.
|
||||
self.state.withLockedValue { state in
|
||||
state.switchToSequentialReads()
|
||||
return state.fileReadingState()
|
||||
}.flatMap {
|
||||
if let (descriptor, _, _) = $0 {
|
||||
return descriptor.readChunk(length: length).mapError { error in
|
||||
.read(usingSyscall: .read, error: error, path: self.path, location: .here())
|
||||
}
|
||||
} else {
|
||||
// nil means done: don't start a read which might block, there's nobody to read
|
||||
// for. Return empty to indicate the stream should finish.
|
||||
return .success(ByteBuffer())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (source, initialState): (FileChunkSequenceProducer.Source?, ProducerState.State) = self.state
|
||||
private func didReadNextChunk(_ buffer: ByteBuffer) {
|
||||
assert(buffer.readableBytes <= self.chunkLength)
|
||||
|
||||
let (source, wasDone, isDone): (FileChunkSequenceProducer.Source?, Bool, Bool) = self.state
|
||||
.withLockedValue { state in
|
||||
// The stream may have been terminated while the read was in progress.
|
||||
let wasDone = state.isDone
|
||||
|
||||
state.didReadBytes(buffer.readableBytes)
|
||||
|
||||
// finishing short indicates the file is done
|
||||
if buffer.readableBytes < chunkLength {
|
||||
state.state = .done(emptyRange: false)
|
||||
// Reading no bytes means the end of the file has been reached. Reading fewer bytes
|
||||
// than requested does not: for a pipe or FIFO it just means that fewer bytes were
|
||||
// available. If the requested range has been exhausted then 'didReadBytes' has
|
||||
// already marked the state as done.
|
||||
if buffer.readableBytes == 0 {
|
||||
state.done()
|
||||
}
|
||||
return (state.source, state.state)
|
||||
|
||||
return (state.source, wasDone, state.isDone)
|
||||
}
|
||||
|
||||
guard let source else {
|
||||
return
|
||||
}
|
||||
|
||||
// No bytes were produced, nothing more to do.
|
||||
if buffer.readableBytes == 0 {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
}
|
||||
|
||||
// Yield bytes and maybe produce more.
|
||||
let yieldResult = source.yield(contentsOf: CollectionOfOne(buffer))
|
||||
|
||||
switch initialState {
|
||||
case .done:
|
||||
// Nothing is wanted any more: don't yield to a source which is finished.
|
||||
if wasDone {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
// Never yield an empty chunk: it isn't meaningful to consumers.
|
||||
let yieldResult: FileChunkSequenceProducer.Source.YieldResult?
|
||||
if buffer.readableBytes > 0 {
|
||||
yieldResult = source.yield(contentsOf: CollectionOfOne(buffer))
|
||||
} else {
|
||||
yieldResult = nil
|
||||
}
|
||||
|
||||
// Finish only after yielding the final chunk, and never yield to a finished source.
|
||||
if isDone {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
case .producing, .pausedProducing:
|
||||
()
|
||||
}
|
||||
|
||||
switch yieldResult {
|
||||
case .produceMore:
|
||||
case .produceMore, .none:
|
||||
()
|
||||
case .stopProducing:
|
||||
self.state.withLockedValue { state in state.pauseProducing() }
|
||||
@@ -328,14 +350,29 @@ private struct ProducerState: Sendable {
|
||||
case activeAndQueued
|
||||
}
|
||||
|
||||
/// How the file is being read.
|
||||
internal enum ReadMode {
|
||||
/// Read from the absolute offset given by the lower bound of the range (with `pread`).
|
||||
/// This is how every file is read to begin with.
|
||||
case positional
|
||||
/// Read from the file's current position (with `read`). The file turned out to be
|
||||
/// unseekable (a pipe, FIFO or socket) so the lower bound of the range is only used to
|
||||
/// track how many bytes have been read.
|
||||
case sequential
|
||||
}
|
||||
|
||||
/// The handle to read from.
|
||||
var handle: SystemFileHandle.SendableView
|
||||
|
||||
/// An optional range containing the offsets to read from and up to (exclusive)
|
||||
/// The lower bound should be updated after each successful read.
|
||||
/// The upper bound should be used to check if producer should stop.
|
||||
/// If no range is present, then read entire file.
|
||||
var range: Range<Int64>?
|
||||
/// The range containing the offsets to read from and up to (exclusive).
|
||||
/// The lower bound should be updated after each successful read, in either read mode.
|
||||
/// The upper bound should be used to check if producer should stop; for a sequential read
|
||||
/// it's the budget of bytes which may be read.
|
||||
/// Reading the entire file is represented by `0..<Int64.max`.
|
||||
var range: Range<Int64>
|
||||
|
||||
/// How the file is being read.
|
||||
var readMode: ReadMode = .positional
|
||||
|
||||
/// Keep track of whether or not we are currently actively engaged in a read
|
||||
/// to protect against re-entrant behavior.
|
||||
@@ -357,8 +394,8 @@ private struct ProducerState: Sendable {
|
||||
/// the sourcing end of the `FileChunkSequenceProducer`
|
||||
internal var source: FileChunkSequenceProducer.Source?
|
||||
|
||||
init(handle: SystemFileHandle, range: Range<Int64>?) {
|
||||
if let range, range.isEmpty {
|
||||
init(handle: SystemFileHandle, range: Range<Int64>) {
|
||||
if range.isEmpty {
|
||||
self.state = .done(emptyRange: true)
|
||||
} else {
|
||||
self.state = .producing(.init(handle: handle.sendableView, range: range))
|
||||
@@ -462,11 +499,13 @@ private struct ProducerState: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
mutating func fileReadingState() -> Result<(FileDescriptor, Range<Int64>?)?, FileSystemError> {
|
||||
mutating func fileReadingState() -> Result<
|
||||
(FileDescriptor, Range<Int64>, Producing.ReadMode)?, FileSystemError
|
||||
> {
|
||||
switch self.state {
|
||||
case .producing(let producingState), .pausedProducing(let producingState):
|
||||
if let descriptor = producingState.handle.descriptorIfAvailable() {
|
||||
return .success((descriptor, producingState.range))
|
||||
return .success((descriptor, producingState.range, producingState.readMode))
|
||||
} else {
|
||||
let error = FileSystemError(
|
||||
code: .closed,
|
||||
@@ -502,6 +541,20 @@ private struct ProducerState: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the rest of the file from its current position instead of from absolute offsets.
|
||||
mutating func switchToSequentialReads() {
|
||||
switch self.state {
|
||||
case .producing(var state):
|
||||
state.readMode = .sequential
|
||||
self.state = .producing(state)
|
||||
case .pausedProducing(var state):
|
||||
state.readMode = .sequential
|
||||
self.state = .pausedProducing(state)
|
||||
case .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func pauseProducing() {
|
||||
switch self.state {
|
||||
case .producing(let state):
|
||||
@@ -514,6 +567,16 @@ private struct ProducerState: Sendable {
|
||||
mutating func done() {
|
||||
self.state = .done(emptyRange: false)
|
||||
}
|
||||
|
||||
/// Whether the producer has finished producing values.
|
||||
var isDone: Bool {
|
||||
switch self.state {
|
||||
case .done:
|
||||
return true
|
||||
case .producing, .pausedProducing:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
@@ -527,21 +590,16 @@ extension ProducerState.Producing {
|
||||
/// - Parameter count: The number of bytes which have been read.
|
||||
/// - Returns: Returns `.moreToRead` if there are no remaining bytes to read, `.cannotReadMore` otherwise.
|
||||
mutating func updateRangeWithReadBytes(_ count: Int) -> RangeUpdateOutcome {
|
||||
guard let currentRange = self.range else {
|
||||
// we are reading the whole file, just keep going
|
||||
return .moreToRead
|
||||
}
|
||||
|
||||
let newLowerBound = currentRange.lowerBound + Int64(count)
|
||||
let newLowerBound = self.range.lowerBound + Int64(count)
|
||||
|
||||
// we have run out of bytes to read, we are done
|
||||
if newLowerBound >= currentRange.upperBound {
|
||||
self.range = currentRange.upperBound..<currentRange.upperBound
|
||||
if newLowerBound >= self.range.upperBound {
|
||||
self.range = self.range.upperBound..<self.range.upperBound
|
||||
return .cannotReadMore
|
||||
}
|
||||
|
||||
// update range, we are not done
|
||||
self.range = newLowerBound..<currentRange.upperBound
|
||||
self.range = newLowerBound..<self.range.upperBound
|
||||
return .moreToRead
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,15 @@ public protocol ReadableFileHandleProtocol: FileHandleProtocol {
|
||||
/// may be. The slice may be shorter than the given `length` if there are fewer bytes from the
|
||||
/// `offset` to the end of the file.
|
||||
///
|
||||
/// The slice may also be shorter than `length` when the end of the file hasn't been reached but
|
||||
/// fewer bytes are currently available, even though more may arrive later. This happens for
|
||||
/// unseekable files, such as pipes, FIFOs and sockets, and for some special files which can be
|
||||
/// seeked, such as files in Linux's procfs. A short slice therefore doesn't mean the end of the
|
||||
/// file: only an empty slice does.
|
||||
///
|
||||
/// Unseekable files can only be read sequentially so `offset` must be zero, otherwise a
|
||||
/// ``FileSystemError`` with code ``FileSystemError/Code-swift.struct/unsupported`` is thrown.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The absolute offset into the file to read from.
|
||||
/// - length: The maximum number of bytes to read as a ``ByteCount``.
|
||||
@@ -196,6 +205,20 @@ public protocol ReadableFileHandleProtocol: FileHandleProtocol {
|
||||
|
||||
/// Returns an asynchronous sequence of chunks read from the file.
|
||||
///
|
||||
/// The sequence ends once the whole range has been read or when the end of the file is reached,
|
||||
/// whichever comes first. A chunk which is shorter than `chunkLength` doesn't mean the end of the
|
||||
/// file has been reached.
|
||||
///
|
||||
/// Unseekable files, such as pipes, FIFOs and sockets, are read sequentially so `range` must start
|
||||
/// at zero, otherwise iterating the sequence throws a ``FileSystemError`` with code
|
||||
/// ``FileSystemError/Code-swift.struct/unsupported``. The upper bound of the range limits the
|
||||
/// number of bytes that are read.
|
||||
///
|
||||
/// Each read of an unseekable file blocks a thread of the file system's I/O thread pool until data is
|
||||
/// available or every writer has closed. The sequence reads ahead of its consumer, so if iteration
|
||||
/// stops before the end of the file a read may still be in progress, and on some platforms, Darwin
|
||||
/// included, closing the handle then waits for that read to finish.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - range: The absolute offsets into the file to read.
|
||||
/// - chunkLength: The maximum length of the chunk to read as a ``ByteCount``.
|
||||
@@ -358,7 +381,7 @@ extension ReadableFileHandleProtocol {
|
||||
)
|
||||
}
|
||||
|
||||
let isSeekable = !(info.type == .fifo || info.type == .socket)
|
||||
let isSeekable = !info.type.isUnseekable
|
||||
if isSeekable {
|
||||
// Limit the size of single shot reads. If the system is busy then avoid slowing down other
|
||||
// work by blocking an I/O executor thread while doing a large read. The limit is somewhat
|
||||
@@ -420,7 +443,24 @@ extension ReadableFileHandleProtocol {
|
||||
var accumulator = ByteBuffer()
|
||||
accumulator.reserveCapacity(readSize)
|
||||
|
||||
for try await chunk in self.readChunks(in: ..., chunkLength: .mebibytes(8)) {
|
||||
// Read on demand rather than with 'readChunks'. A sequence of chunks reads ahead of its
|
||||
// consumer, which for an unseekable file can leave a read waiting for more data from the
|
||||
// other end when this function has already stopped, for example by throwing below. On some
|
||||
// platforms closing the file then waits for that read to finish.
|
||||
let maximumChunkLength: Int64 = 8 * 1024 * 1024
|
||||
while true {
|
||||
// Never read more than is needed to find out that there are more bytes than allowed: at
|
||||
// most one byte over the maximum. 'maximumSizeAllowed' is no more than the capacity of a
|
||||
// 'ByteBuffer' so this can't overflow.
|
||||
let remainingBytes = maximumSizeAllowed.bytes - Int64(accumulator.readableBytes)
|
||||
let chunkLength = max(1, min(maximumChunkLength, remainingBytes + 1))
|
||||
let chunk = try await self.readChunk(fromAbsoluteOffset: 0, length: .bytes(chunkLength))
|
||||
|
||||
// Only an empty chunk means that the end of the file has been reached.
|
||||
if chunk.readableBytes == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
accumulator.writeImmutableBuffer(chunk)
|
||||
if accumulator.readableBytes > maximumSizeAllowed.bytes {
|
||||
throw FileSystemError(
|
||||
|
||||
@@ -169,3 +169,17 @@ extension FileType {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileType {
|
||||
/// Whether files of this type are streams which can't be seeked.
|
||||
///
|
||||
/// Reads and writes of an unseekable file always happen at the file's current position, and
|
||||
/// positional I/O such as `pread` and `pwrite` fails with `ESPIPE` or `ENXIO`. A read may also
|
||||
/// return fewer bytes than were requested without having reached the end of the file.
|
||||
///
|
||||
/// - Important: Character devices aren't included. Some can seek, for example raw disk devices
|
||||
/// on macOS, and treating them as unseekable would mean reading the same offset forever.
|
||||
internal var isUnseekable: Bool {
|
||||
self == .fifo || self == .socket
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Tracks where the next read or write through a file handle should happen, accounting for unseekable
|
||||
/// files which can only be accessed sequentially.
|
||||
///
|
||||
/// Reading or writing at offset zero works for every kind of file, so the cursor only finds out whether
|
||||
/// the file is seekable, by asking the handle for its type, when something needs a different offset. An
|
||||
/// unseekable file (a pipe, FIFO or socket) is always accessed at offset zero, so a cursor which was
|
||||
/// created with a different starting offset can't be used with one.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal struct FileCursor: Sendable {
|
||||
/// How the cursor addresses the bytes it reads or writes.
|
||||
private enum Positioning: Sendable {
|
||||
/// Not yet known. Accessing the file at offset zero works for every kind of file so there's no need
|
||||
/// to find out until a different offset is needed.
|
||||
case unknown
|
||||
/// The file is seekable: accesses are made at the cursor's offset.
|
||||
case positional
|
||||
/// The file is unseekable: it can only be accessed sequentially, so accesses are always made at
|
||||
/// offset zero.
|
||||
case sequential
|
||||
}
|
||||
|
||||
/// The offset the cursor was created with.
|
||||
private let initialOffset: Int64
|
||||
|
||||
/// The logical offset of the next read or write.
|
||||
///
|
||||
/// For an unseekable file this counts the bytes which have been transferred, but isn't used for
|
||||
/// reading or writing.
|
||||
private var offset: Int64
|
||||
|
||||
/// How the cursor addresses the file.
|
||||
private var positioning: Positioning = .unknown
|
||||
|
||||
/// Creates a cursor.
|
||||
///
|
||||
/// - Parameter initialOffset: The offset of the first read or write.
|
||||
init(initialOffset: Int64) {
|
||||
self.initialOffset = initialOffset
|
||||
self.offset = initialOffset
|
||||
}
|
||||
|
||||
/// The offset to pass to the handle for the next read or write.
|
||||
///
|
||||
/// - Parameter handle: The handle which is being read from or written to.
|
||||
/// - Returns: The offset to read from or write at. This is always zero for an unseekable file.
|
||||
/// - Throws: A ``FileSystemError`` with code ``FileSystemError/Code-swift.struct/unsupported`` if the
|
||||
/// file is unseekable and the cursor didn't start at offset zero.
|
||||
mutating func nextOffset(for handle: some FileHandleProtocol) async throws -> Int64 {
|
||||
// Offset zero works for every kind of file, so only find out whether the file is seekable when
|
||||
// a different offset is needed.
|
||||
if self.offset != 0 {
|
||||
try await self.resolvePositioning(for: handle)
|
||||
}
|
||||
|
||||
switch self.positioning {
|
||||
case .unknown, .positional:
|
||||
return self.offset
|
||||
case .sequential:
|
||||
try self.checkCanAccessSequentially()
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that bytes were read or written.
|
||||
///
|
||||
/// - Parameter count: The number of bytes which were transferred.
|
||||
mutating func advance(by count: Int64) {
|
||||
self.offset += count
|
||||
}
|
||||
|
||||
/// Skips over bytes without reading or writing them, if the file can seek.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - count: The number of bytes to skip.
|
||||
/// - handle: The handle which is being read from or written to.
|
||||
/// - Returns: `true` if the file is seekable, in which case the offset has been advanced by `count`.
|
||||
/// `false` if the file is unseekable: the offset is unchanged and the bytes can only be skipped by
|
||||
/// reading and discarding them, which the caller must do. The offset advances as they're transferred.
|
||||
/// - Throws: A ``FileSystemError`` with code ``FileSystemError/Code-swift.struct/unsupported`` if the
|
||||
/// file is unseekable and the cursor didn't start at offset zero.
|
||||
mutating func skipIfSeekable(_ count: Int64, for handle: some FileHandleProtocol) async throws -> Bool {
|
||||
try await self.resolvePositioning(for: handle)
|
||||
|
||||
switch self.positioning {
|
||||
case .unknown, .positional:
|
||||
self.advance(by: count)
|
||||
return true
|
||||
case .sequential:
|
||||
try self.checkCanAccessSequentially()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Works out whether the file is seekable, if that isn't already known.
|
||||
private mutating func resolvePositioning(for handle: some FileHandleProtocol) async throws {
|
||||
guard self.positioning == .unknown else {
|
||||
return
|
||||
}
|
||||
|
||||
let info = try await handle.info()
|
||||
self.positioning = info.type.isUnseekable ? .sequential : .positional
|
||||
}
|
||||
|
||||
/// An unseekable file can only be accessed from the beginning.
|
||||
private func checkCanAccessSequentially() throws {
|
||||
guard self.initialOffset == 0 else {
|
||||
throw FileSystemError(
|
||||
code: .unsupported,
|
||||
message: "File is unseekable.",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1198,7 +1198,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
forReadingAt path: FilePath,
|
||||
options: OpenOptions.Read
|
||||
) async throws -> SystemFileHandle {
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let opts = options.descriptorOptions
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
@@ -1217,7 +1217,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
options: OpenOptions.Write
|
||||
) async throws -> SystemFileHandle {
|
||||
let perms = options.permissionsForRegularFile
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let opts = options.descriptorOptions
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
@@ -1237,7 +1237,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
options: OpenOptions.Write
|
||||
) async throws -> SystemFileHandle {
|
||||
let perms = options.permissionsForRegularFile
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let opts = options.descriptorOptions
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
|
||||
Reference in new issue
Block a user