diff --git a/Sources/NIOFS/BufferedReader.swift b/Sources/NIOFS/BufferedReader.swift index d5cac6da4..8c03c948e 100644 --- a/Sources/NIOFS/BufferedReader.swift +++ b/Sources/NIOFS/BufferedReader.swift @@ -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 { /// 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 { ) 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 { /// 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 + } } } diff --git a/Sources/NIOFS/BufferedWriter.swift b/Sources/NIOFS/BufferedWriter.swift index c78954515..3972e4b6f 100644 --- a/Sources/NIOFS/BufferedWriter.swift +++ b/Sources/NIOFS/BufferedWriter.swift @@ -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 { 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 { ) 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 { 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. diff --git a/Sources/NIOFS/CMakeLists.txt b/Sources/NIOFS/CMakeLists.txt index 5fe98c8d7..15d69ece7 100644 --- a/Sources/NIOFS/CMakeLists.txt +++ b/Sources/NIOFS/CMakeLists.txt @@ -37,6 +37,7 @@ add_library(NIOFS "Internal/BufferedStream.swift" "Internal/Cancellation.swift" "Internal/Concurrency Primitives/TokenBucket.swift" + "Internal/FileCursor.swift" "Internal/ParallelDirCopy.swift" "Internal/ParallelRemoval.swift" "Internal/String+UnsafeUnititializedCapacity.swift" diff --git a/Sources/NIOFS/FileChunks.swift b/Sources/NIOFS/FileChunks.swift index 85871c731..650a6fa03 100644 --- a/Sources/NIOFS/FileChunks.swift +++ b/Sources/NIOFS/FileChunks.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) - } - public typealias Element = ByteBuffer /// The underlying buffered stream. @@ -42,20 +37,13 @@ public struct FileChunks: AsyncSequence, Sendable { chunkLength: ByteCount, range: Range ) { - 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, 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, 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 { + // 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? + /// 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.. + + /// 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?) { - if let range, range.isEmpty { + init(handle: SystemFileHandle, range: Range) { + 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?)?, FileSystemError> { + mutating func fileReadingState() -> Result< + (FileDescriptor, Range, 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..= self.range.upperBound { + self.range = self.range.upperBound.. maximumSizeAllowed.bytes { throw FileSystemError( diff --git a/Sources/NIOFS/FileType.swift b/Sources/NIOFS/FileType.swift index 16f67ef70..f4a5fbf55 100644 --- a/Sources/NIOFS/FileType.swift +++ b/Sources/NIOFS/FileType.swift @@ -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 + } +} diff --git a/Sources/NIOFS/Internal/FileCursor.swift b/Sources/NIOFS/Internal/FileCursor.swift new file mode 100644 index 000000000..7e1b725e0 --- /dev/null +++ b/Sources/NIOFS/Internal/FileCursor.swift @@ -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() + ) + } + } +} diff --git a/Sources/NIOFS/Internal/SystemFileHandle.swift b/Sources/NIOFS/Internal/SystemFileHandle.swift index 10fd7b617..9224411c3 100644 --- a/Sources/NIOFS/Internal/SystemFileHandle.swift +++ b/Sources/NIOFS/Internal/SystemFileHandle.swift @@ -1198,7 +1198,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol { forReadingAt path: NIOFilePath, 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.underlying, @@ -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.underlying, @@ -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.underlying, diff --git a/Sources/_NIOFileSystem/BufferedReader.swift b/Sources/_NIOFileSystem/BufferedReader.swift index d222c3a88..4c8377102 100644 --- a/Sources/_NIOFileSystem/BufferedReader.swift +++ b/Sources/_NIOFileSystem/BufferedReader.swift @@ -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 { /// 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 { ) 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 { /// 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 + } } } diff --git a/Sources/_NIOFileSystem/BufferedWriter.swift b/Sources/_NIOFileSystem/BufferedWriter.swift index 95c05d0bf..9fd7589d3 100644 --- a/Sources/_NIOFileSystem/BufferedWriter.swift +++ b/Sources/_NIOFileSystem/BufferedWriter.swift @@ -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 { 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 { ) 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 { 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. diff --git a/Sources/_NIOFileSystem/CMakeLists.txt b/Sources/_NIOFileSystem/CMakeLists.txt index a27ee2706..2a354fde3 100644 --- a/Sources/_NIOFileSystem/CMakeLists.txt +++ b/Sources/_NIOFileSystem/CMakeLists.txt @@ -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" diff --git a/Sources/_NIOFileSystem/FileChunks.swift b/Sources/_NIOFileSystem/FileChunks.swift index 1ff4b717c..dd52079e0 100644 --- a/Sources/_NIOFileSystem/FileChunks.swift +++ b/Sources/_NIOFileSystem/FileChunks.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) - } - public typealias Element = ByteBuffer /// The buffered stream. @@ -42,20 +37,13 @@ public struct FileChunks: AsyncSequence, Sendable { chunkLength: ByteCount, range: Range ) { - 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, 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, 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 { + // 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? + /// 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.. + + /// 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?) { - if let range, range.isEmpty { + init(handle: SystemFileHandle, range: Range) { + 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?)?, FileSystemError> { + mutating func fileReadingState() -> Result< + (FileDescriptor, Range, 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..= self.range.upperBound { + self.range = self.range.upperBound.. maximumSizeAllowed.bytes { throw FileSystemError( diff --git a/Sources/_NIOFileSystem/FileType.swift b/Sources/_NIOFileSystem/FileType.swift index 16f67ef70..f4a5fbf55 100644 --- a/Sources/_NIOFileSystem/FileType.swift +++ b/Sources/_NIOFileSystem/FileType.swift @@ -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 + } +} diff --git a/Sources/_NIOFileSystem/Internal/FileCursor.swift b/Sources/_NIOFileSystem/Internal/FileCursor.swift new file mode 100644 index 000000000..7e1b725e0 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/FileCursor.swift @@ -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() + ) + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift b/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift index e12f37089..72574d35a 100644 --- a/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift +++ b/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift @@ -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, diff --git a/Tests/NIOFSIntegrationTests/BufferedReaderTests.swift b/Tests/NIOFSIntegrationTests/BufferedReaderTests.swift index 00b020c1e..4dbbaf681 100644 --- a/Tests/NIOFSIntegrationTests/BufferedReaderTests.swift +++ b/Tests/NIOFSIntegrationTests/BufferedReaderTests.swift @@ -284,4 +284,241 @@ final class BufferedReaderTests: XCTestCase { XCTAssertEqual(words, expected) } } + + // These tests use FIFOs and pipes, which are created with POSIX calls that are unavailable on Windows. + #if !os(Windows) + func testBufferedReaderOnFIFOWithSplitWrites() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader() + + // The peer has only written part of what it will write. A read which is shorter than + // we asked for isn't the end of the file. + let first = try await reader.read(.bytes(3)) + XCTAssertEqual(String(buffer: first), "hel") + + peer.release() + + let (bytes, readEOF) = try await reader.read(while: { $0 != UInt8(ascii: "\n") }) + XCTAssertEqual(String(buffer: bytes), "lo world") + XCTAssertFalse(readEOF) + + // The newline remains, and the peer then closes its end. + let newline = try await reader.read(.bytes(64)) + XCTAssertEqual(String(buffer: newline), "\n") + + let (rest, restReadEOF) = try await reader.read(while: { _ in true }) + XCTAssertEqual(rest.readableBytes, 0) + XCTAssertTrue(restReadEOF) + } + } + } + + func testBufferedReaderOnPipeWithSplitWrites() async throws { + try await withPipePeer(peerEnd: .write) { peer, fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } test: { peer, path in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(path)) { handle in + // The reader relies on a pipe being reported as a FIFO to know that it can't seek. + let info = try await handle.info() + XCTAssertEqual(info.type, .fifo) + + var reader = handle.bufferedReader() + + // The peer has only written part of what it will write. A read which is shorter than + // we asked for isn't the end of the file. + let first = try await reader.read(.bytes(3)) + XCTAssertEqual(String(buffer: first), "hel") + + peer.release() + + let (bytes, readEOF) = try await reader.read(while: { $0 != UInt8(ascii: "\n") }) + XCTAssertEqual(String(buffer: bytes), "lo world") + XCTAssertFalse(readEOF) + + // The newline remains, and the peer then closes its end. + let (rest, restReadEOF) = try await reader.read(while: { _ in true }) + XCTAssertEqual(String(buffer: rest), "\n") + XCTAssertTrue(restReadEOF) + } + } + } + + func testBufferedReaderDropOnFIFOConsumesBytes() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "0123456789ABCDEF")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader(capacity: .bytes(4)) + + let head = try await reader.read(.bytes(2)) + XCTAssertEqual(String(buffer: head), "01") + + // This is more than the reader has buffered so some of the bytes to drop must be read + // from the FIFO and thrown away: there's no way to skip ahead by changing the offset. + try await reader.drop(10) + + let tail = try await reader.read(.bytes(2)) + XCTAssertEqual(String(buffer: tail), "CD") + } + } + } + + func testBufferedReaderOnFIFOWithNonZeroInitialOffsetThrows() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.waitForRelease() + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader(startingAtAbsoluteOffset: 5) + + await XCTAssertThrowsFileSystemErrorAsync { + try await reader.read(.bytes(1)) + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + } + + peer.release() + } + } + } + + func testBufferedReaderDropOnFIFOWithNonZeroInitialOffsetThrows() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.waitForRelease() + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader(startingAtAbsoluteOffset: 5) + + // Dropping before anything has been read can't skip ahead in an unseekable file. + await XCTAssertThrowsFileSystemErrorAsync { + try await reader.drop(10) + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + } + + peer.release() + } + } + } + + func testBufferedReaderReadReturnsWhatIsAvailableOnFIFO() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + // The peer writes less than will be asked for, then stays connected without writing anything else: + // a further read of the FIFO blocks until the peer is released. + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "abc")) + try peer.waitForRelease(timeout: .seconds(10)) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader() + + // The reader returns the bytes which are available. A short result doesn't mean the end of + // the file, so it mustn't wait for the 61 other bytes. + let start = NIODeadline.now() + let bytes = try await reader.read(.bytes(64)) + let elapsed = NIODeadline.now() - start + XCTAssertEqual(String(buffer: bytes), "abc") + XCTAssertLessThan(elapsed, .seconds(2), "Reading took \(elapsed)") + + peer.release() + } + } + } + + func testBufferedReaderDropPastEndOfFileOnFIFO() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader() + + // There are fewer bytes than are being dropped: dropping stops at the end of the file. + try await reader.drop(100) + + let (bytes, readEOF) = try await reader.read(while: { _ in true }) + XCTAssertEqual(bytes.readableBytes, 0) + XCTAssertTrue(readEOF) + } + } + } + + func testBufferedReaderDropWhileAcrossSplitWritesOnFIFO() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "aaa")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "aab")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var reader = handle.bufferedReader() + + let first = try await reader.read(.bytes(1)) + XCTAssertEqual(String(buffer: first), "a") + + peer.release() + + // The predicate holds for everything which has been written so far, and for the start of + // what the peer writes next. + try await reader.drop(while: { $0 == UInt8(ascii: "a") }) + + let rest = try await reader.read(.bytes(64)) + XCTAssertEqual(String(buffer: rest), "b") + } + } + } + #endif // !os(Windows) + + #if os(Linux) + func testBufferedReaderReadsLinesOfProcFile() async throws { + // Procfs files return no more than about a page for each read. A short read isn't the end of the file, + // and the file is much larger than a page: a test process has far more memory mappings than fit in one. + try await FileSystem.shared.withFileHandle(forReadingAt: "/proc/self/maps") { handle in + var reader = handle.bufferedReader() + var byteCount = 0 + while true { + let (line, readEOF) = try await reader.read(while: { $0 != UInt8(ascii: "\n") }) + if readEOF { + // The file ends with a newline, so nothing follows the last one. + XCTAssertEqual(line.readableBytes, 0, "The last line is incomplete") + break + } + byteCount += line.readableBytes + 1 + try await reader.drop(1) + } + XCTAssertGreaterThan(byteCount, 4096) + } + } + #endif // os(Linux) } diff --git a/Tests/NIOFSIntegrationTests/BufferedWriterTests.swift b/Tests/NIOFSIntegrationTests/BufferedWriterTests.swift index 72adf37da..b5bbf23ca 100644 --- a/Tests/NIOFSIntegrationTests/BufferedWriterTests.swift +++ b/Tests/NIOFSIntegrationTests/BufferedWriterTests.swift @@ -258,4 +258,76 @@ final class BufferedWriterTests: XCTestCase { XCTAssertEqual(writer.bufferCapacity, 0) } } + + // These tests use FIFOs and pipes, which are created with POSIX calls that are unavailable on Windows. + #if !os(Windows) + func testBufferedWriterOnFIFO() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + let received = try await withFIFOPeer(at: fifoPath, returning: ByteBuffer.self) { peer in + try peer.withOpenFIFO(.read) { fd in + try peer.readToEOF(fd) + } + } test: { peer in + try await FileSystem.shared.withFileHandle( + forWritingAt: NIOFilePath(fifoPath), + options: .modifyFile(createIfNecessary: false) + ) { handle in + // With a small capacity these writes cause several flushes, of which only the first is + // at offset zero. + var writer = handle.bufferedWriter(capacity: .bytes(4)) + for piece in ["abc", "defgh", "ij", "klmnop", "q"] { + try await writer.write(contentsOf: Array(piece.utf8)) + } + try await writer.flush() + } + } + XCTAssertEqual(String(buffer: received), "abcdefghijklmnopq") + } + + func testBufferedWriterOnPipe() async throws { + let received = try await withPipePeer(peerEnd: .read, returning: ByteBuffer.self) { peer, fd in + try peer.readToEOF(fd) + } test: { _, path in + try await FileSystem.shared.withFileHandle( + forWritingAt: NIOFilePath(path), + options: .modifyFile(createIfNecessary: false) + ) { handle in + // With a small capacity these writes cause several flushes, of which only the first is + // at offset zero. + var writer = handle.bufferedWriter(capacity: .bytes(4)) + for piece in ["abc", "defgh", "ij", "klmnop", "q"] { + try await writer.write(contentsOf: Array(piece.utf8)) + } + try await writer.flush() + } + } + XCTAssertEqual(String(buffer: received), "abcdefghijklmnopq") + } + + func testBufferedWriterOnFIFOWithNonZeroInitialOffsetThrows() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + let received = try await withFIFOPeer(at: fifoPath, returning: ByteBuffer.self) { peer in + try peer.withOpenFIFO(.read) { fd in + try peer.readToEOF(fd) + } + } test: { peer in + try await FileSystem.shared.withFileHandle( + forWritingAt: NIOFilePath(fifoPath), + options: .modifyFile(createIfNecessary: false) + ) { handle in + var writer = handle.bufferedWriter(startingAtAbsoluteOffset: 5) + try await writer.write(contentsOf: Array("hello".utf8)) + + await XCTAssertThrowsFileSystemErrorAsync { + try await writer.flush() + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + } + } + } + XCTAssertEqual(received.readableBytes, 0) + } + #endif // !os(Windows) } diff --git a/Tests/NIOFSIntegrationTests/FIFOTestSupport.swift b/Tests/NIOFSIntegrationTests/FIFOTestSupport.swift new file mode 100644 index 000000000..df3b68535 --- /dev/null +++ b/Tests/NIOFSIntegrationTests/FIFOTestSupport.swift @@ -0,0 +1,566 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// FIFOs are created with `mkfifo`, which is unavailable on Windows. +#if !os(Windows) +import NIOConcurrencyHelpers +import NIOCore +import NIOFS +import NIOPosix +import XCTest + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +// Writing to a FIFO or pipe which has no reader raises SIGPIPE, which would take down the whole test process. +// Tests which fail part way through can leave the peer writing after the test has closed its end, so the +// peer's writes mustn't raise it: the peer sees `EPIPE` instead. +// +// As in NIOPosix, that's set on each descriptor on Darwin. Linux has no way to do that, so SIGPIPE is +// blocked on the peer's thread instead. That's enough on Linux, which raises SIGPIPE on the thread which +// wrote, but not on Darwin. + +/// Stops writes to `descriptor` from raising SIGPIPE. +/// +/// This only has an effect on Darwin: other platforms can't do this for a descriptor, see +/// ``blockSIGPIPEOnThisThread()``. +private func disableSIGPIPE(_ descriptor: FileDescriptor) throws { + #if canImport(Darwin) + guard fcntl(descriptor.rawValue, F_SETNOSIGPIPE, 1) == 0 else { + throw FIFOPeerError.posix(call: "fcntl(F_SETNOSIGPIPE)", errno: errno) + } + #endif +} + +/// Stops writes on the calling thread from raising SIGPIPE. +/// +/// This has no effect on Darwin, where blocking SIGPIPE on the thread which writes doesn't stop it being +/// raised: see ``disableSIGPIPE(_:)``. +private func blockSIGPIPEOnThisThread() { + #if !canImport(Darwin) + var signals = sigset_t() + sigemptyset(&signals) + sigaddset(&signals, SIGPIPE) + pthread_sigmask(SIG_BLOCK, &signals, nil) + #endif +} + +enum FIFOPeerError: Error, CustomStringConvertible { + case posix(call: String, errno: Int32) + case timedOut(String) + case finishedEarly + case testFinishedFirst(String) + + var description: String { + switch self { + case .posix(let call, let errno): + return "\(call) failed: \(String(cString: strerror(errno))) (errno \(errno))" + case .timedOut(let what): + return "timed out: \(what)" + case .finishedEarly: + return "the peer finished before reaching the milestone" + case .testFinishedFirst(let what): + return "the test finished before \(what)" + } + } +} + +/// Runs `peer` as the other end of the FIFO at `fifoPath` while running `test`, then waits for `peer` to +/// finish and returns what it produced. +/// +/// The peer runs on a thread from a thread pool of its own, which is shut down before this returns. It +/// mustn't share a thread pool with the code under test: blocking opens of a FIFO would tie up threads that +/// the code under test needs to open the other end, which could deadlock. +/// +/// Code under test which fails early can leave the peer blocked, either waiting to be released or in a +/// blocking `open`, which would otherwise cause the test to stop indefinitely. So if `test` throws, or +/// the peer doesn't finish in a timely fashion, the peer is forced to stop before this throws. If it +/// can't be stopped then its thread pool can't be shut down, which fails the test. +/// +/// - Parameters: +/// - fifoPath: The path of the FIFO. +/// - outputType: The type of value returned by `peer`. +/// - peer: The work to do on the peer thread. +/// - test: The test, which may coordinate with the peer using the ``FIFOPeer`` passed to it. +/// - Returns: The value returned by `peer`. +func withFIFOPeer( + at fifoPath: FilePath, + returning outputType: Output.Type = Output.self, + file: StaticString = #filePath, + line: UInt = #line, + peer: @escaping @Sendable (FIFOPeer) throws -> Output, + test: (FIFOPeer) async throws -> Void +) async throws -> Output { + try await withPeer(FIFOPeer(fifoPath: fifoPath), file: file, line: line, peer: peer, test: test) +} + +/// An end of a pipe. +enum PipeEnd { + case read + case write +} + +/// Creates a pipe, then runs `peer` with one end of it while running `test` with the other, then waits for +/// `peer` to finish and returns what it produced. +/// +/// `test` is given a path in `/dev/fd` for its end of the pipe, which it can open in the same way that a +/// program might open `/dev/stdin`. Opening it gives the test a descriptor of its own: the pipe's original +/// descriptor for that end is closed once `test` has finished. +/// +/// The peer runs and is stopped in the same way as for ``withFIFOPeer(at:returning:file:line:peer:test:)``. +/// +/// - Parameters: +/// - peerEnd: The end of the pipe to give to `peer`. The other end is used by `test`. +/// - outputType: The type of value returned by `peer`. +/// - peer: The work to do on the peer thread. It's given the descriptor of its end of the pipe, which is +/// closed when it returns. +/// - test: The test, which may coordinate with the peer using the ``FIFOPeer`` passed to it. +/// - Returns: The value returned by `peer`. +func withPipePeer( + peerEnd: PipeEnd, + returning outputType: Output.Type = Output.self, + file: StaticString = #filePath, + line: UInt = #line, + peer: @escaping @Sendable (FIFOPeer, FileDescriptor) throws -> Output, + test: (FIFOPeer, _ path: FilePath) async throws -> Void +) async throws -> Output { + let (readEnd, writeEnd) = try FileDescriptor.pipe() + + // This is the write end, whichever side has it. It covers the test's writes too: on Darwin, opening a + // descriptor's path in `/dev/fd` shares its open file description, and so this setting. + do { + try disableSIGPIPE(writeEnd) + } catch { + try? readEnd.close() + try? writeEnd.close() + throw error + } + + let peerDescriptor: FileDescriptor + let testDescriptor: FileDescriptor + switch peerEnd { + case .read: + (peerDescriptor, testDescriptor) = (readEnd, writeEnd) + case .write: + (peerDescriptor, testDescriptor) = (writeEnd, readEnd) + } + + let testPath = FilePath("/dev/fd/\(testDescriptor.rawValue)") + return try await withPeer(FIFOPeer(pipeTestEnd: testDescriptor), file: file, line: line) { fifoPeer in + defer { try? peerDescriptor.close() } + return try peer(fifoPeer, peerDescriptor) + } test: { fifoPeer in + try await test(fifoPeer, testPath) + } +} + +private func withPeer( + _ fifoPeer: FIFOPeer, + file: StaticString, + line: UInt, + peer: @escaping @Sendable (FIFOPeer) throws -> Output, + test: (FIFOPeer) async throws -> Void +) async throws -> Output { + let threadPool = NIOThreadPool(numberOfThreads: 1) + threadPool.start() + + threadPool.submit { workItemState in + fifoPeer.run(peer, workItemState: workItemState) + } + + let result: Result + do { + try await test(fifoPeer) + fifoPeer.testDidFinish() + result = .success(try await fifoPeer.waitForOutcome()) + } catch { + fifoPeer.testDidFinish() + await fifoPeer.abort() + result = .failure(error) + } + + if fifoPeer.hasFinished { + try await threadPool.shutdownGracefully() + } else { + // Shutting down waits for the peer to finish, so it would stop indefinitely. No test leaves its peer + // stuck on purpose, so this is always a failure. The peer's thread is left behind, and keeps the + // thread pool alive: the pool is never deinitialized without having been shut down. + XCTFail("The peer couldn't be stopped, so its thread pool was leaked", file: file, line: line) + } + + return try result.get() +} + +/// The other end of a FIFO or pipe, driven by blocking system calls on a thread of its own: see +/// ``withFIFOPeer(at:returning:file:line:peer:test:)`` and +/// ``withPipePeer(peerEnd:returning:file:line:peer:test:)``. +/// +/// The peer doesn't use `FileSystem`, so that it doesn't depend on the code under test. +/// +/// Coordination between the test and the peer is explicit: +/// - the test calls ``release()`` to let the peer continue past ``waitForRelease(timeout:)``; +/// - the peer calls ``reachMilestone()`` to let the test continue past ``waitForMilestone(timeout:)``; +/// - the peer can wait for the test to have finished with ``waitForTestToFinish(timeout:)``. +/// +/// The peer blocks its own thread while it waits. The test side never blocks a thread: it polls with +/// `Task.sleep`, so it is safe to use from the Swift concurrency cooperative pool. +final class FIFOPeer: Sendable { + private struct State { + var milestones = 0 + var outcome: Result? + /// For a pipe: the pipe's original descriptor for the test's end, until it's closed. + var pipeTestEnd: FileDescriptor? + } + + private enum Connection { + /// The peer opens the FIFO at this path. + case fifo(path: FilePath) + /// The peer was given one end of a pipe. + case pipe + } + + private let state: NIOLockedValueBox + + /// Whether the test has released the peer. + private let released = ConditionLock(value: false) + + /// Whether the test has finished. + private let testFinished = ConditionLock(value: false) + + private let connection: Connection + + fileprivate init(fifoPath: FilePath) { + self.state = NIOLockedValueBox(State()) + self.connection = .fifo(path: fifoPath) + } + + fileprivate init(pipeTestEnd: FileDescriptor) { + self.state = NIOLockedValueBox(State(pipeTestEnd: pipeTestEnd)) + self.connection = .pipe + } + + /// Runs the peer's work and records what it produced. This is called on the peer thread. + fileprivate func run( + _ body: @Sendable (FIFOPeer) throws -> Output, + workItemState: NIOThreadPool.WorkItemState + ) { + // This thread belongs to the peer's own thread pool, so this doesn't affect anything else. + blockSIGPIPEOnThisThread() + + let outcome: Result + switch workItemState { + case .active: + outcome = Result { try body(self) } + case .cancelled: + outcome = .failure(CancellationError()) + } + self.state.withLockedValue { $0.outcome = outcome } + } + + // MARK: Peer side: these block, so only call them from the peer thread. + + /// Blocks until the test calls ``release()``. + /// + /// The peer is only released once: after that, this returns immediately. + func waitForRelease(timeout: TimeAmount = .seconds(30)) throws { + let timeoutSeconds = Double(timeout.nanoseconds) / 1_000_000_000 + guard self.released.lock(whenValue: true, timeoutSeconds: timeoutSeconds) else { + throw FIFOPeerError.timedOut("waiting for the test to release the peer") + } + self.released.unlock() + } + + /// Blocks until the test has finished. For a pipe, the pipe's original descriptor for the test's end has + /// been closed by then. + func waitForTestToFinish(timeout: TimeAmount = .seconds(30)) throws { + let timeoutSeconds = Double(timeout.nanoseconds) / 1_000_000_000 + guard self.testFinished.lock(whenValue: true, timeoutSeconds: timeoutSeconds) else { + throw FIFOPeerError.timedOut("waiting for the test to finish") + } + self.testFinished.unlock() + } + + /// Tells the test that the peer has reached a point it is waiting for. + func reachMilestone() { + self.state.withLockedValue { $0.milestones += 1 } + } + + /// Blocks until the FIFO is full, so that writing to it blocks. + /// + /// The peer must already have opened the FIFO for reading. There's no event for a FIFO becoming full, so + /// this polls a spare non-blocking descriptor for writing to it, which is writable until the FIFO is full. + func waitForFIFOToFill(timeout: TimeAmount = .seconds(10)) throws { + guard case .fifo(let path) = self.connection else { + preconditionFailure("Only the peer of a FIFO can wait for it to fill") + } + + // This never writes: it only stands in for the test's descriptor, which is writing. + let spare = try FileDescriptor.open(path, .writeOnly, options: .nonBlocking) + defer { try? spare.close() } + + let deadline = NIODeadline.now() + timeout + while true { + // We set a timeout on `poll` to 0 becuase we are waiting for this fd to become _not_ + // readable, and we can't set a timeout for that. + var pollDescriptor = pollfd(fd: spare.rawValue, events: Int16(POLLOUT), revents: 0) + if poll(&pollDescriptor, 1, 0) < 0 { + guard errno == EINTR else { + throw FIFOPeerError.posix(call: "poll", errno: errno) + } + } else if pollDescriptor.revents & Int16(POLLOUT) == 0 { + return + } + + if self.testFinished.value { + throw FIFOPeerError.testFinishedFirst("the FIFO filled up") + } + if NIODeadline.now() > deadline { + throw FIFOPeerError.timedOut("waiting for the FIFO to fill up") + } + usleep(1000) + } + } + + enum OpenMode { + case read + case write + } + + /// Opens the FIFO and runs `body` with the descriptor, then closes it. + /// + /// The FIFO is opened with a blocking `open(2)`: this blocks until the other end is opened. + func withOpenFIFO(_ mode: OpenMode, _ body: (FileDescriptor) throws -> Result) throws -> Result { + let descriptor = try self.openFIFO(mode) + defer { try? descriptor.close() } + return try body(descriptor) + } + + private func openFIFO(_ mode: OpenMode) throws -> FileDescriptor { + guard case .fifo(let path) = self.connection else { + preconditionFailure("The peer of a pipe is given its end of the pipe") + } + + switch mode { + case .read: + return try FileDescriptor.open(path, .readOnly) + case .write: + let descriptor = try FileDescriptor.open(path, .writeOnly) + do { + try disableSIGPIPE(descriptor) + } catch { + try? descriptor.close() + throw error + } + return descriptor + } + } + + /// Writes all of `buffer`, blocking as required. + func writeAll(_ descriptor: FileDescriptor, _ buffer: ByteBuffer) throws { + try descriptor.writeAll(buffer.readableBytesView) + } + + /// Reads until end-of-file, blocking as required. + func readToEOF(_ descriptor: FileDescriptor) throws -> ByteBuffer { + var buffer = ByteBuffer() + while true { + let bytesRead = try buffer.writeWithUnsafeMutableBytes(minimumWritableBytes: 4096) { bytes in + try descriptor.read(into: bytes) + } + if bytesRead == 0 { + return buffer + } + } + } + + // MARK: Test side: these never block a thread. + + /// Lets the peer continue past a call to ``waitForRelease(timeout:)``. + func release() { + self.released.lock() + self.released.unlock(withValue: true) + } + + /// Suspends until the peer reaches a milestone. + func waitForMilestone(timeout: TimeAmount = .seconds(10)) async throws { + let deadline = NIODeadline.now() + timeout + while true { + let reached = self.state.withLockedValue { state -> Bool in + if state.milestones > 0 { + state.milestones -= 1 + return true + } + return false + } + if reached { + return + } + if self.state.withLockedValue({ $0.outcome != nil }) { + throw FIFOPeerError.finishedEarly + } + if NIODeadline.now() > deadline { + throw FIFOPeerError.timedOut("waiting for the peer to reach a milestone") + } + try await Task.sleep(nanoseconds: 2_000_000) + } + } + + /// Whether the peer has finished. + fileprivate var hasFinished: Bool { + self.state.withLockedValue { $0.outcome != nil } + } + + /// Suspends until the peer has finished and returns what it produced. + /// + /// This throws if the peer doesn't finish in a timely fashion. + fileprivate func waitForOutcome(timeout: TimeAmount = .seconds(5)) async throws -> Output { + let deadline = NIODeadline.now() + timeout + while true { + if let outcome = self.state.withLockedValue({ $0.outcome }) { + return try outcome.get() + } + if NIODeadline.now() > deadline { + throw FIFOPeerError.timedOut("waiting for the peer to finish") + } + try await Task.sleep(nanoseconds: 2_000_000) + } + } + + /// Unblocks the peer, however it is stuck, and waits for it to finish. + /// + /// This gives up waiting if the peer doesn't finish in a timely fashion. + fileprivate func abort() async { + // Let the peer continue past any wait for the test, now and in future. + self.release() + + // The peer of a pipe can't be stuck opening it. Once the test's end of the pipe is closed, which + // has already happened, the peer can't be stuck reading or writing it either. The peer of a FIFO + // may be stuck in a blocking `open`: unblock it by briefly opening the other end of the FIFO + // ourselves. This is retried: the peer might not have reached its `open` yet. + let deadline = NIODeadline.now() + .seconds(10) + while self.state.withLockedValue({ $0.outcome == nil }), NIODeadline.now() < deadline { + if case .fifo(let path) = self.connection, + let descriptor = try? FileDescriptor.open(path, .readWrite, options: .nonBlocking) + { + try? descriptor.close() + } + try? await Task.sleep(nanoseconds: 10_000_000) + } + } + + /// Called once the test has finished, whether or not it succeeded. + /// + /// For a pipe, this closes the pipe's original descriptor for the test's end, so that the peer sees the + /// end of the pipe once the test has closed its own descriptor. Then it lets the peer continue past + /// ``waitForTestToFinish(timeout:)``. + fileprivate func testDidFinish() { + let descriptor = self.state.withLockedValue { state -> FileDescriptor? in + defer { state.pipeTestEnd = nil } + return state.pipeTestEnd + } + try? descriptor?.close() + + self.testFinished.lock() + self.testFinished.unlock(withValue: true) + } +} + +extension XCTestCase { + /// Creates a FIFO called `fifo` inside a new temporary directory which is removed when the test finishes. + func makeTemporaryFIFO() async throws -> FilePath { + let directory = try await FileSystem.shared.createTemporaryDirectory(template: "test-XXX") + self.addTeardownBlock { + try await FileSystem.shared.removeItem(at: directory, recursively: true) + } + + let fifoPath = FilePath(directory).appending("fifo") + try makeFIFO(at: fifoPath) + return fifoPath + } +} + +/// Creates a FIFO at `path`. +func makeFIFO(at path: FilePath) throws { + guard mkfifo(path.string, 0o644) == 0 else { + throw FIFOPeerError.posix(call: "mkfifo", errno: errno) + } +} + +#if canImport(Darwin) +/// A pseudo-terminal: what's written to it can be read from its terminal device. +struct PseudoTerminal: Sendable { + /// The path of the terminal device. + let path: FilePath + + /// The controlling side of the pseudo-terminal. + fileprivate let controller: FileDescriptor + + /// Writes all of `buffer` to the terminal's input. + func write(_ buffer: ByteBuffer) throws { + try self.controller.writeAll(buffer.readableBytesView) + } +} + +/// Creates a pseudo-terminal and runs `body` with it, then closes it. +/// +/// Glibc only declares the functions which create a pseudo-terminal for X/Open applications, and so they aren't +/// available to Swift: this is only available on Darwin. +func withPseudoTerminal(_ body: (PseudoTerminal) async throws -> Result) async throws -> Result { + let rawController = posix_openpt(O_RDWR | O_NOCTTY) + guard rawController >= 0 else { + throw FIFOPeerError.posix(call: "posix_openpt", errno: errno) + } + let controller = FileDescriptor(rawValue: rawController) + defer { try? controller.close() } + + guard grantpt(rawController) == 0 else { + throw FIFOPeerError.posix(call: "grantpt", errno: errno) + } + guard unlockpt(rawController) == 0 else { + throw FIFOPeerError.posix(call: "unlockpt", errno: errno) + } + guard let name = ptsname(rawController) else { + throw FIFOPeerError.posix(call: "ptsname", errno: errno) + } + let path = FilePath(String(cString: name)) + + // Hold the terminal open while `body` runs, with echo turned off. Otherwise what's written to the terminal + // is echoed back to the controlling side, where nothing reads it, and closing the terminal waits more than + // half a second for it to drain. Holding the terminal open also stops its settings being reset when the + // test opens it. + let terminal = try FileDescriptor.open( + path, + .readWrite, + options: FileDescriptor.OpenOptions(rawValue: O_NOCTTY) + ) + defer { try? terminal.close() } + + var attributes = termios() + guard tcgetattr(terminal.rawValue, &attributes) == 0 else { + throw FIFOPeerError.posix(call: "tcgetattr", errno: errno) + } + attributes.c_lflag &= ~tcflag_t(ECHO) + guard tcsetattr(terminal.rawValue, TCSANOW, &attributes) == 0 else { + throw FIFOPeerError.posix(call: "tcsetattr", errno: errno) + } + + return try await body(PseudoTerminal(path: path, controller: controller)) +} +#endif +#endif // !os(Windows) diff --git a/Tests/NIOFSIntegrationTests/FileHandleTests.swift b/Tests/NIOFSIntegrationTests/FileHandleTests.swift index a0ffbd700..50bde29f4 100644 --- a/Tests/NIOFSIntegrationTests/FileHandleTests.swift +++ b/Tests/NIOFSIntegrationTests/FileHandleTests.swift @@ -322,10 +322,16 @@ final class FileHandleTests: XCTestCase { return } - try await self.withHandle(forFileAtPath: fifoPath, accessMode: .readWrite) { + // Only reading no bytes at all is end-of-file, so for 'readToEnd' to return the FIFO must have no + // writers left once the bytes have been read. A handle opened for reading and writing is itself a + // writer, so read from a read-only handle and write with a separate descriptor which is closed. + try await self.withHandle(forFileAtPath: fifoPath, accessMode: .readOnly, options: .nonBlocking) { handle in let someBytes = ByteBuffer(repeating: 42, count: 1546) - try await handle.write(contentsOf: someBytes.readableBytesView, toAbsoluteOffset: 0) + let writer = try FileDescriptor.open(fifoPath, .writeOnly) + _ = try writer.closeAfter { + try writer.writeAll(someBytes.readableBytesView) + } let readSomeBytes = try await handle.readToEnd(maximumSizeAllowed: .bytes(1546)) XCTAssertEqual(readSomeBytes, someBytes) @@ -344,10 +350,16 @@ final class FileHandleTests: XCTestCase { return } - try await self.withHandle(forFileAtPath: fifoPath, accessMode: .readWrite) { + // Reading continues until there are no bytes left and no writers, so don't hold the FIFO open for + // writing in the handle being read: read from a read-only handle and write with a separate + // descriptor which is closed. + try await self.withHandle(forFileAtPath: fifoPath, accessMode: .readOnly, options: .nonBlocking) { handle in let someBytes = [UInt8](repeating: 42, count: 10) - try await handle.write(contentsOf: someBytes, toAbsoluteOffset: 0) + let writer = try FileDescriptor.open(fifoPath, .writeOnly) + _ = try writer.closeAfter { + try writer.writeAll(someBytes) + } await XCTAssertThrowsFileSystemErrorAsync { try await handle.readToEnd(maximumSizeAllowed: .bytes(9)) @@ -394,6 +406,564 @@ final class FileHandleTests: XCTestCase { } #endif // !os(Windows) + // MARK: - Pipes, FIFOs and repeated chunked reads + + #if !os(Windows) + func testReadChunksOnFIFOWithSplitWrites() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + var iterator = handle.readChunks().makeAsyncIterator() + + // The peer has only written part of what it will write. A chunk which is shorter than + // we asked for isn't the end of the file. + let first = try await iterator.next() + XCTAssertEqual(first.map { String(buffer: $0) }, "hello ") + + peer.release() + + var rest = ByteBuffer() + while let chunk = try await iterator.next() { + XCTAssertGreaterThan(chunk.readableBytes, 0, "Chunks must not be empty") + rest.writeImmutableBuffer(chunk) + } + XCTAssertEqual(String(buffer: rest), "world\n") + + // The sequence is finished. + let end = try await iterator.next() + XCTAssertNil(end) + } + } + } + + func testReadChunksOnPipeWithSplitWrites() async throws { + try await withPipePeer(peerEnd: .write) { peer, fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } test: { peer, path in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(path)) { handle in + var iterator = handle.readChunks().makeAsyncIterator() + + // The peer has only written part of what it will write. A chunk which is shorter than + // we asked for isn't the end of the file. + let first = try await iterator.next() + XCTAssertEqual(first.map { String(buffer: $0) }, "hello ") + + peer.release() + + var rest = ByteBuffer() + while let chunk = try await iterator.next() { + XCTAssertGreaterThan(chunk.readableBytes, 0, "Chunks must not be empty") + rest.writeImmutableBuffer(chunk) + } + XCTAssertEqual(String(buffer: rest), "world\n") + } + } + } + + #if canImport(Darwin) + func testReadChunksWithRangeOnTerminal() async throws { + // Reading a terminal at an offset fails with ENXIO on Darwin, rather than the ESPIPE which pipes and + // FIFOs give (and terminals give on Linux). Like a pipe, a terminal can still be read from the start. + try await withPseudoTerminal { terminal in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(terminal.path)) { handle in + // A terminal is a character device, so it's only found to be unseekable when it's read. + let info = try await handle.info() + XCTAssertEqual(info.type, .character) + + try terminal.write(ByteBuffer(string: "hello\n")) + + // A terminal doesn't end until it's closed, so only read as much as was written. + var bytes = ByteBuffer() + for try await chunk in handle.readChunks(in: 0..<6) { + bytes.writeImmutableBuffer(chunk) + } + XCTAssertEqual(String(buffer: bytes), "hello\n") + } + } + } + + func testReadingTerminalAtNonZeroOffsetThrows() async throws { + // Like a FIFO, a terminal can only be read from offset zero. Reading it at another offset fails with + // ENXIO on Darwin, rather than the ESPIPE which FIFOs give. + try await withPseudoTerminal { terminal in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(terminal.path)) { handle in + // There's something to read, so an implementation which read the terminal regardless of the + // offset wouldn't block. + try terminal.write(ByteBuffer(string: "hello\n")) + + await XCTAssertThrowsFileSystemErrorAsync { + try await handle.readChunk(fromAbsoluteOffset: 5, length: .bytes(6)) + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + XCTAssertEqual(error.message, "File is unseekable.") + } + + await XCTAssertThrowsFileSystemErrorAsync { + for try await _ in handle.readChunks(in: 5..<10) {} + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + } + } + } + } + #endif + + func testReadChunksWithRangeOnFIFO() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello world\n")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + // A FIFO can't seek, but a range which starts at zero is fine: it limits the number of + // bytes which are read. + var bytes = ByteBuffer() + for try await chunk in handle.readChunks(in: 0..<8, chunkLength: .bytes(5)) { + XCTAssertLessThanOrEqual(chunk.readableBytes, 5) + bytes.writeImmutableBuffer(chunk) + } + XCTAssertEqual(String(buffer: bytes), "hello wo") + } + } + } + + func testReadChunksWithRangeNotStartingAtZeroOnFIFOThrows() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello world")) + } + } test: { _ in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + // A FIFO can only be read from the start, so a range which doesn't start at zero can't be read. + // There's something to read, so an implementation which read the FIFO regardless of the range + // wouldn't block. + await XCTAssertThrowsFileSystemErrorAsync { + for try await _ in handle.readChunks(in: 5..<10) {} + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + } + } + } + } + + func testReadChunkAtNonZeroOffsetOnFIFOThrows() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello world")) + } + } test: { _ in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + let first = try await handle.readChunk(fromAbsoluteOffset: 0, length: .bytes(5)) + XCTAssertEqual(String(buffer: first), "hello") + + // A FIFO can't seek, so it can only be read from offset zero. Any other offset throws, even + // the one which follows on from the last read. There's more to read, so an implementation which + // read the FIFO regardless of the offset wouldn't block. + for offset: Int64 in [5, 100] { + await XCTAssertThrowsFileSystemErrorAsync { + try await handle.readChunk(fromAbsoluteOffset: offset, length: .bytes(6)) + } onError: { error in + XCTAssertEqual(error.code, .unsupported) + XCTAssertEqual(error.message, "File is unseekable.") + } + } + + // Reading from offset zero again reads the next bytes, not the start of the FIFO. + let next = try await handle.readChunk(fromAbsoluteOffset: 0, length: .bytes(6)) + XCTAssertEqual(String(buffer: next), " world") + } + } + } + + func testReadToEndOnFIFOWithSplitWrites() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } + } test: { peer in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(fifoPath)) { handle in + async let contents = handle.readToEnd(maximumSizeAllowed: .mebibytes(1)) + + // 'readToEnd' can't be signalled part way through, so the peer's second write has to be + // released after a delay instead. This test may pass spuriously for an implementation + // which stops at the first short read if the delay is shorter than the time it takes + // to start reading, but that's unlikely with this much time. + try await Task.sleep(nanoseconds: 250_000_000) + peer.release() + + let result = try await contents + XCTAssertEqual(String(buffer: result), "hello world\n") + } + } + } + + func testReadToEndOnFIFOThatExceedsMaximumSizeDoesNotLeaveAReadInFlight() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + // The peer writes more than is allowed, then stays connected without writing anything else: any + // further read of the FIFO blocks until the peer is released. + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "0123456789")) + try peer.waitForRelease(timeout: .seconds(10)) + } + } test: { peer in + let handle = try await FileSystem.shared.openFile(forReadingAt: NIOFilePath(fifoPath)) + + await XCTAssertThrowsFileSystemErrorAsync { + try await handle.readToEnd(maximumSizeAllowed: .bytes(5)) + } onError: { error in + XCTAssertEqual(error.code, .resourceExhausted) + } + + // On some platforms closing a file waits for reads which are in progress to finish. Reading the + // FIFO further than necessary to find that it has too many bytes would leave a read in progress + // which doesn't finish until the peer writes or disconnects. + let start = NIODeadline.now() + try await handle.close() + let elapsed = NIODeadline.now() - start + XCTAssertLessThan(elapsed, .seconds(2), "Closing the handle took \(elapsed)") + + peer.release() + } + } + + func testReadToEndOnPipeWithSplitWrites() async throws { + try await withPipePeer(peerEnd: .write) { peer, fd in + try peer.writeAll(fd, ByteBuffer(string: "hello ")) + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "world\n")) + } test: { peer, path in + try await FileSystem.shared.withFileHandle(forReadingAt: NIOFilePath(path)) { handle in + async let contents = handle.readToEnd(maximumSizeAllowed: .mebibytes(1)) + + // As for a FIFO, the peer's second write is released after a delay, which is long enough + // for reading to have started. + try await Task.sleep(nanoseconds: 250_000_000) + peer.release() + + let result = try await contents + XCTAssertEqual(String(buffer: result), "hello world\n") + } + } + } + + func testDirectoryHandleReadFIFOWaitsForDataFromConnectedWriter() async throws { + try await FileSystem.shared.withTemporaryDirectory { directory, directoryPath in + let fifoPath = FilePath(directoryPath).appending("fifo") + try makeFIFO(at: fifoPath) + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + peer.reachMilestone() + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "hello")) + } + } test: { peer in + let handle = try await directory.openFile(forReadingAt: "fifo", options: OpenOptions.Read()) + + let bytes: ByteBuffer + do { + // Make sure that the writer is connected before reading. Whether or not opening the + // file waits for it, there is now a writer and it hasn't written anything. + try await peer.waitForMilestone() + + // Reading must wait for the writer, it mustn't fail because there's nothing to read yet. + // The peer is released after a delay as the read is blocked until then: an implementation + // which fails the read does so immediately, well within the delay. + async let chunk = handle.readChunk(fromAbsoluteOffset: 0, length: .bytes(64)) + try await Task.sleep(nanoseconds: 100_000_000) + peer.release() + bytes = try await chunk + } catch { + try? await handle.close() + throw error + } + try await handle.close() + + XCTAssertEqual(String(buffer: bytes), "hello") + } + } + } + + func testDirectoryHandleReadFIFOBeforeWriterConnects() async throws { + try await FileSystem.shared.withTemporaryDirectory { directory, directoryPath in + let fifoPath = FilePath(directoryPath).appending("fifo") + try makeFIFO(at: fifoPath) + + try await withFIFOPeer(at: fifoPath) { peer in + try peer.waitForRelease() + try peer.withOpenFIFO(.write) { fd in + try peer.writeAll(fd, ByteBuffer(string: "hello")) + } + } test: { peer in + // Let the writer connect once the test is opening the read end. The test may not have started + // to open it by the time the writer connects, so this can't show that opening waits for the + // writer: 'testDirectoryHandleOpensFilesInBlockingMode' checks that instead. + peer.release() + let handle = try await directory.openFile(forReadingAt: "fifo", options: OpenOptions.Read()) + + let bytes: ByteBuffer + do { + // The writer may not have written anything yet: that's not the same as the end of the file. + bytes = try await handle.readChunk(fromAbsoluteOffset: 0, length: .bytes(64)) + } catch { + try? await handle.close() + throw error + } + try await handle.close() + + XCTAssertEqual(String(buffer: bytes), "hello") + } + } + } + + func testDirectoryHandleOpenFIFOForWritingWaitsForReader() async throws { + try await FileSystem.shared.withTemporaryDirectory { directory, directoryPath in + let fifoPath = FilePath(directoryPath).appending("fifo") + try makeFIFO(at: fifoPath) + + let received = try await withFIFOPeer(at: fifoPath, returning: ByteBuffer.self) { peer in + try peer.waitForRelease() + return try peer.withOpenFIFO(.read) { fd in + try peer.readToEOF(fd) + } + } test: { peer in + // Let the reader connect once the test is opening the write end. Opening must wait for the + // reader rather than fail. The test may not have started to open it by the time the reader + // connects, so this can't show that: 'testDirectoryHandleOpensFilesInBlockingMode' checks + // that instead. + peer.release() + let handle = try await directory.openFile( + forWritingAt: "fifo", + options: .modifyFile(createIfNecessary: false) + ) + + do { + try await handle.write(contentsOf: Array("hello".utf8), toAbsoluteOffset: 0) + } catch { + try? await handle.close() + throw error + } + try await handle.close() + } + XCTAssertEqual(String(buffer: received), "hello") + } + } + + func testDirectoryHandleWriteToFullFIFOWaitsForReader() async throws { + try await FileSystem.shared.withTemporaryDirectory { directory, directoryPath in + let fifoPath = FilePath(directoryPath).appending("fifo") + try makeFIFO(at: fifoPath) + + // This is much larger than the capacity of a pipe. + let payload = ByteBuffer(bytes: (0..<(1024 * 1024)).map { UInt8(truncatingIfNeeded: $0 &* 7) }) + + let received = try await withFIFOPeer(at: fifoPath, returning: ByteBuffer.self) { peer in + try peer.withOpenFIFO(.read) { fd in + // Leave the FIFO to fill up before draining it. + try peer.waitForFIFOToFill() + return try peer.readToEOF(fd) + } + } test: { peer in + let handle = try await directory.openFile( + forWritingAt: "fifo", + options: .modifyFile(createIfNecessary: false) + ) + + do { + // Writing must wait for space in the pipe rather than fail when it's full. + let written = try await handle.write(contentsOf: payload, toAbsoluteOffset: 0) + XCTAssertEqual(written, Int64(payload.readableBytes)) + } catch { + try? await handle.close() + throw error + } + try await handle.close() + } + XCTAssertEqual(received.readableBytes, payload.readableBytes) + XCTAssertTrue(received == payload, "The bytes received weren't the bytes written") + } + } + + func testDirectoryHandleOpensFilesInBlockingMode() async throws { + // Opening, reading and writing a FIFO must wait for the other end. In non-blocking mode they would + // instead fail, or report the end of the file early. Whether a test of a FIFO catches that depends + // on whether the test or its peer acts first, which a test can't control, so check the mode itself. + func isNonBlocking(_ handle: some FileHandleProtocol) async throws -> Bool { + try await handle.withUnsafeDescriptor { descriptor in + fcntl(descriptor.rawValue, F_GETFL) & O_NONBLOCK != 0 + } + } + + try await FileSystem.shared.withTemporaryDirectory { directory, _ in + try await directory.withFileHandle( + forReadingAndWritingAt: "file", + options: .modifyFile(createIfNecessary: true) + ) { handle in + let nonBlocking = try await isNonBlocking(handle) + XCTAssertFalse(nonBlocking, "Opened for reading and writing in non-blocking mode") + } + + try await directory.withFileHandle( + forWritingAt: "file", + options: .modifyFile(createIfNecessary: false) + ) { handle in + let nonBlocking = try await isNonBlocking(handle) + XCTAssertFalse(nonBlocking, "Opened for writing in non-blocking mode") + } + + try await directory.withFileHandle(forReadingAt: "file") { handle in + let nonBlocking = try await isNonBlocking(handle) + XCTAssertFalse(nonBlocking, "Opened for reading in non-blocking mode") + } + } + } + + // These check the test support rather than NIOFS. If the peer of a FIFO or pipe raised SIGPIPE when it + // wrote without a reader, a test which failed part way through would terminate the whole test process. + func testFIFOPeerWritingWithoutAReaderDoesNotRaiseSIGPIPE() async throws { + let fifoPath = try await self.makeTemporaryFIFO() + + do { + try await withFIFOPeer(at: fifoPath) { peer in + try peer.withOpenFIFO(.write) { fd in + try peer.waitForRelease() + try peer.writeAll(fd, ByteBuffer(string: "nobody is listening")) + } + } test: { peer in + // Connect to the peer, then disconnect before it writes. + let handle = try await FileSystem.shared.openFile(forReadingAt: NIOFilePath(fifoPath)) + try await handle.close() + peer.release() + } + XCTFail("The peer's write should have failed") + } catch let error as Errno { + XCTAssertEqual(error, .brokenPipe) + } + } + + func testPipePeerWritingWithoutAReaderDoesNotRaiseSIGPIPE() async throws { + do { + try await withPipePeer(peerEnd: .write) { peer, fd in + // The pipe has no reader once the test has finished. + try peer.waitForTestToFinish() + try peer.writeAll(fd, ByteBuffer(string: "nobody is listening")) + } test: { _, path in + let handle = try await FileSystem.shared.openFile(forReadingAt: NIOFilePath(path)) + try await handle.close() + } + XCTFail("The peer's write should have failed") + } catch let error as Errno { + XCTAssertEqual(error, .brokenPipe) + } + } + + func testReadChunksTwiceOnRegularFile() async throws { + let fs = FileSystem.shared + let path = try await fs.temporaryFilePath() + self.addTeardownBlock { + try await fs.removeItem(at: path) + } + + let contents = (0..<(4 * 1024 + 123)).map { UInt8(truncatingIfNeeded: $0) } + try await fs.withFileHandle( + forWritingAt: path, + options: .newFile(replaceExisting: false) + ) { handle in + _ = try await handle.write(contentsOf: contents, toAbsoluteOffset: 0) + } + + try await fs.withFileHandle(forReadingAt: path) { handle in + for iteration in 1...2 { + var bytes = ByteBuffer() + for try await chunk in handle.readChunks(chunkLength: .bytes(512)) { + XCTAssertLessThanOrEqual(chunk.readableBytes, 512) + bytes.writeImmutableBuffer(chunk) + } + + XCTAssertEqual(bytes.readableBytes, contents.count, "Wrong number of bytes in iteration \(iteration)") + XCTAssertTrue( + Array(bytes.readableBytesView) == contents, + "The bytes read in iteration \(iteration) weren't the bytes written" + ) + } + } + } + + func testReadChunksReadsFromTheStartRegardlessOfDescriptorPosition() async throws { + let fs = FileSystem.shared + let path = try await fs.temporaryFilePath() + self.addTeardownBlock { + try await fs.removeItem(at: path) + } + + let contents = (0..<(4 * 1024 + 123)).map { UInt8(truncatingIfNeeded: $0) } + try await fs.withFileHandle( + forWritingAt: path, + options: .newFile(replaceExisting: false) + ) { handle in + _ = try await handle.write(contentsOf: contents, toAbsoluteOffset: 0) + } + + try await fs.withFileHandle(forReadingAt: path) { handle in + // Move the file position, which is shared by everything using the descriptor. + _ = try await handle.withUnsafeDescriptor { descriptor in + try descriptor.seek(offset: 1000, from: .start) + } + + var bytes = ByteBuffer() + for try await chunk in handle.readChunks(chunkLength: .bytes(512)) { + bytes.writeImmutableBuffer(chunk) + } + + XCTAssertEqual(bytes.readableBytes, contents.count) + XCTAssertTrue( + Array(bytes.readableBytesView) == contents, + "The bytes read weren't the bytes written" + ) + } + } + + #if os(Linux) + func testReadToEndOfProcFile() async throws { + // Procfs files report a size of zero and return no more than about a page for each read. A short read + // isn't the end of the file, and the file is much larger than a page: a test process has far more + // memory mappings than fit in one. + let path: NIOFilePath = "/proc/self/maps" + + let contents = try await FileSystem.shared.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd(maximumSizeAllowed: .mebibytes(16)) + } + XCTAssertGreaterThan(contents.readableBytes, 4096) + XCTAssertEqual(contents.readableBytesView.last, UInt8(ascii: "\n")) + + let string = try await String(contentsOf: path, maximumSizeAllowed: .mebibytes(16)) + XCTAssertGreaterThan(string.utf8.count, 4096) + XCTAssertTrue(string.hasSuffix("\n")) + } + #endif // os(Linux) + #endif // !os(Windows) + func testReadWholeFileWithOffsets() async throws { try await self.withHandle(forFileAtPath: Self.thisFile) { handle in let info = try await handle.info()