From 66a85ba0e233cff9546df2847c8aafd2579eabe7 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Tue, 2 Sep 2025 14:56:58 +0100 Subject: [PATCH] Add back _NIOFileSystem (#3367) Motivation: In #3363 we converted `_NIOFileSystem` to `NIOFileSystem` and removed the (unreleased) overloads for FilePath/NIOFilePath. This change adds back `_NIOFileSystem` such that it matches the API it had at 2.86.0. Modifications: - Add back `_NIOFileSystem` and `_NIOFileSystemFoundationCompat` such that their API is at 2.86.0 Result: - `NIOFileSystem` uses `NIOFilePath` - `_NIOFileSystem` uses `FilePath` --- Package.swift | 30 + Sources/_NIOFileSystem/Array+FileSystem.swift | 54 + .../ArraySlice+FileSystem.swift | 56 + Sources/_NIOFileSystem/BufferedReader.swift | 244 +++ Sources/_NIOFileSystem/BufferedWriter.swift | 248 +++ .../ByteBuffer+FileSystem.swift | 97 + Sources/_NIOFileSystem/ByteCount.swift | 117 ++ Sources/_NIOFileSystem/Convenience.swift | 202 ++ Sources/_NIOFileSystem/DirectoryEntries.swift | 742 +++++++ Sources/_NIOFileSystem/DirectoryEntry.swift | 47 + Sources/_NIOFileSystem/Exports.swift | 21 + Sources/_NIOFileSystem/FileChunks.swift | 547 ++++++ Sources/_NIOFileSystem/FileHandle.swift | 357 ++++ .../_NIOFileSystem/FileHandleProtocol.swift | 769 ++++++++ Sources/_NIOFileSystem/FileInfo.swift | 278 +++ Sources/_NIOFileSystem/FileSystem.swift | 1573 +++++++++++++++ .../FileSystemError+Syscall.swift | 1158 +++++++++++ Sources/_NIOFileSystem/FileSystemError.swift | 280 +++ .../_NIOFileSystem/FileSystemProtocol.swift | 721 +++++++ Sources/_NIOFileSystem/FileType.swift | 171 ++ Sources/_NIOFileSystem/IOStrategy.swift | 184 ++ .../Internal/BufferedOrAnyStream.swift | 98 + .../Internal/BufferedStream.swift | 1732 +++++++++++++++++ .../Internal/Cancellation.swift | 54 + .../Concurrency Primitives/TokenBucket.swift | 88 + .../UnsafeTransfer.swift | 24 + .../Internal/ParallelDirCopy.swift | 165 ++ .../Internal/ParallelRemoval.swift | 72 + .../String+UnsafeUnititializedCapacity.swift | 61 + .../Internal/System Calls/CInterop.swift | 83 + .../Internal/System Calls/Errno.swift | 148 ++ .../FileDescriptor+Syscalls.swift | 326 ++++ .../Internal/System Calls/Mocking.swift | 380 ++++ .../Internal/System Calls/Syscall.swift | 437 +++++ .../Internal/System Calls/Syscalls.swift | 481 +++++ .../Internal/SystemFileHandle.swift | 1537 +++++++++++++++ .../_NIOFileSystem/Internal/Utilities.swift | 48 + Sources/_NIOFileSystem/NIOFilePath.swift | 107 + .../NIOFileSystemSendableMetatype.swift | 19 + Sources/_NIOFileSystem/OpenOptions.swift | 297 +++ Sources/_NIOFileSystem/PrivacyInfo.xcprivacy | 23 + .../_NIOFileSystem/String+FileSystem.swift | 56 + .../Data+FileSystem.swift | 57 + .../Date+FileInfo.swift | 31 + 44 files changed, 14220 insertions(+) create mode 100644 Sources/_NIOFileSystem/Array+FileSystem.swift create mode 100644 Sources/_NIOFileSystem/ArraySlice+FileSystem.swift create mode 100644 Sources/_NIOFileSystem/BufferedReader.swift create mode 100644 Sources/_NIOFileSystem/BufferedWriter.swift create mode 100644 Sources/_NIOFileSystem/ByteBuffer+FileSystem.swift create mode 100644 Sources/_NIOFileSystem/ByteCount.swift create mode 100644 Sources/_NIOFileSystem/Convenience.swift create mode 100644 Sources/_NIOFileSystem/DirectoryEntries.swift create mode 100644 Sources/_NIOFileSystem/DirectoryEntry.swift create mode 100644 Sources/_NIOFileSystem/Exports.swift create mode 100644 Sources/_NIOFileSystem/FileChunks.swift create mode 100644 Sources/_NIOFileSystem/FileHandle.swift create mode 100644 Sources/_NIOFileSystem/FileHandleProtocol.swift create mode 100644 Sources/_NIOFileSystem/FileInfo.swift create mode 100644 Sources/_NIOFileSystem/FileSystem.swift create mode 100644 Sources/_NIOFileSystem/FileSystemError+Syscall.swift create mode 100644 Sources/_NIOFileSystem/FileSystemError.swift create mode 100644 Sources/_NIOFileSystem/FileSystemProtocol.swift create mode 100644 Sources/_NIOFileSystem/FileType.swift create mode 100644 Sources/_NIOFileSystem/IOStrategy.swift create mode 100644 Sources/_NIOFileSystem/Internal/BufferedOrAnyStream.swift create mode 100644 Sources/_NIOFileSystem/Internal/BufferedStream.swift create mode 100644 Sources/_NIOFileSystem/Internal/Cancellation.swift create mode 100644 Sources/_NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift create mode 100644 Sources/_NIOFileSystem/Internal/Concurrency Primitives/UnsafeTransfer.swift create mode 100644 Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift create mode 100644 Sources/_NIOFileSystem/Internal/ParallelRemoval.swift create mode 100644 Sources/_NIOFileSystem/Internal/String+UnsafeUnititializedCapacity.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/CInterop.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/Errno.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/FileDescriptor+Syscalls.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/Mocking.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/Syscall.swift create mode 100644 Sources/_NIOFileSystem/Internal/System Calls/Syscalls.swift create mode 100644 Sources/_NIOFileSystem/Internal/SystemFileHandle.swift create mode 100644 Sources/_NIOFileSystem/Internal/Utilities.swift create mode 100644 Sources/_NIOFileSystem/NIOFilePath.swift create mode 100644 Sources/_NIOFileSystem/NIOFileSystemSendableMetatype.swift create mode 100644 Sources/_NIOFileSystem/OpenOptions.swift create mode 100644 Sources/_NIOFileSystem/PrivacyInfo.xcprivacy create mode 100644 Sources/_NIOFileSystem/String+FileSystem.swift create mode 100644 Sources/_NIOFileSystemFoundationCompat/Data+FileSystem.swift create mode 100644 Sources/_NIOFileSystemFoundationCompat/Date+FileInfo.swift diff --git a/Package.swift b/Package.swift index 41ac1709b..eea93f8c4 100644 --- a/Package.swift +++ b/Package.swift @@ -66,6 +66,8 @@ let package = Package( .library(name: "NIOTestUtils", targets: ["NIOTestUtils"]), .library(name: "NIOFileSystem", targets: ["NIOFileSystem"]), .library(name: "NIOFileSystemFoundationCompat", targets: ["NIOFileSystemFoundationCompat"]), + .library(name: "_NIOFileSystem", targets: ["_NIOFileSystem"]), + .library(name: "_NIOFileSystemFoundationCompat", targets: ["_NIOFileSystemFoundationCompat"]), ], targets: [ // MARK: - Targets @@ -269,6 +271,34 @@ let package = Package( swiftSettings: strictConcurrencySettings ), + .target( + name: "_NIOFileSystem", + dependencies: [ + "NIOCore", + "NIOPosix", + "CNIOLinux", + "CNIODarwin", + swiftAtomics, + swiftCollections, + swiftSystem, + ], + path: "Sources/_NIOFileSystem", + exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"], + resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [], + swiftSettings: strictConcurrencySettings + [ + .define("ENABLE_MOCKING", .when(configuration: .debug)) + ] + ), + .target( + name: "_NIOFileSystemFoundationCompat", + dependencies: [ + "_NIOFileSystem", + "NIOFoundationCompat", + ], + path: "Sources/_NIOFileSystemFoundationCompat", + swiftSettings: strictConcurrencySettings + ), + // MARK: - Examples .executableTarget( diff --git a/Sources/_NIOFileSystem/Array+FileSystem.swift b/Sources/_NIOFileSystem/Array+FileSystem.swift new file mode 100644 index 000000000..59c10f1b9 --- /dev/null +++ b/Sources/_NIOFileSystem/Array+FileSystem.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(Darwin) || os(Linux) || os(Android) +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension Array where Element == UInt8 { + /// Reads the contents of the file at the path. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed) + } + + self = Self(buffer: byteBuffer) + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } +} +#endif diff --git a/Sources/_NIOFileSystem/ArraySlice+FileSystem.swift b/Sources/_NIOFileSystem/ArraySlice+FileSystem.swift new file mode 100644 index 000000000..e319f6f77 --- /dev/null +++ b/Sources/_NIOFileSystem/ArraySlice+FileSystem.swift @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(Darwin) || os(Linux) || os(Android) +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ArraySlice where Element == UInt8 { + /// Reads the contents of the file at the path. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + let bytes = try await Array( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: fileSystem + ) + + self = Self(bytes) + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } +} +#endif diff --git a/Sources/_NIOFileSystem/BufferedReader.swift b/Sources/_NIOFileSystem/BufferedReader.swift new file mode 100644 index 000000000..d222c3a88 --- /dev/null +++ b/Sources/_NIOFileSystem/BufferedReader.swift @@ -0,0 +1,244 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import DequeModule +import NIOCore + +/// A reader which maintains a buffer of bytes read from the file. +/// +/// You can create a reader from a ``ReadableFileHandleProtocol`` by calling +/// ``ReadableFileHandleProtocol/bufferedReader(startingAtAbsoluteOffset:capacity:)``. Call +/// ``read(_:)`` to read a fixed number of bytes from the file or ``read(while:)-8aukk`` to read +/// from the file while the bytes match a predicate. +/// +/// You can also read bytes without returning them to caller by calling ``drop(_:)`` and +/// ``drop(while:)``. +@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 + + /// Whether the reader has read to the end of the file. + private var readEOF = false + + /// A buffer containing the read bytes. + private var buffer: ByteBuffer + + /// The capacity of the buffer. + public let capacity: Int + + /// The number of bytes currently in the buffer. + public var count: Int { + self.buffer.readableBytes + } + + internal init(wrapping readableHandle: Handle, initialOffset: Int64, capacity: Int) { + precondition( + initialOffset >= 0, + "initialOffset (\(initialOffset)) must be greater than or equal to zero" + ) + precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero") + self.handle = readableHandle + self.offset = initialOffset + self.capacity = capacity + self.buffer = ByteBuffer() + } + + private mutating func readFromFile(_ count: Int) async throws -> ByteBuffer { + let bytes = try await self.handle.readChunk( + fromAbsoluteOffset: self.offset, + length: .bytes(Int64(count)) + ) + // Reading short means reading end-of-file. + self.readEOF = bytes.readableBytes < count + self.offset += Int64(bytes.readableBytes) + return bytes + } + + /// Read at most `count` bytes from the file; reads short if not enough bytes are available. + /// + /// - Parameters: + /// - count: The number of bytes to read. + /// - Returns: The bytes read from the buffer. + public mutating func read(_ count: ByteCount) async throws -> ByteBuffer { + let byteCount = Int(count.bytes) + guard byteCount > 0 else { return ByteBuffer() } + + if let bytes = self.buffer.readSlice(length: byteCount) { + return bytes + } else { + // Not enough bytes: read enough for the caller and to fill the buffer back to capacity. + var buffer = self.buffer + self.buffer = ByteBuffer() + + // The bytes to read from the chunk is the difference in what the caller requested + // and is already stored in buffer. Note that if we get to the end of the file this + // number could be larger than the available number of bytes. + let bytesFromChunk = byteCount &- buffer.readableBytes + let bytesToRead = bytesFromChunk + self.capacity + + // Read a chunk from the file and store it. + let chunk = try await self.readFromFile(bytesToRead) + self.buffer.writeImmutableBuffer(chunk) + + // Finally read off the required bytes from the chunk we just read. If we read short + // then the chunk we just appended might not less than 'bytesFromChunk', that's fine, + // just take what's available. + var slice = self.buffer.readSlice(length: min(bytesFromChunk, chunk.readableBytes))! + buffer.writeBuffer(&slice) + + return buffer + } + } + + /// Reads from the current position in the file until `predicate` returns `false` and returns + /// the read bytes. + /// + /// - Parameters: + /// - predicate: A predicate which evaluates to `true` for all bytes returned. + /// - Returns: A tuple containing the bytes read from the file in its first component, and a boolean + /// indicating whether we've stopped reading because EOF has been reached, or because the predicate + /// condition doesn't hold true anymore. + public mutating func read( + while predicate: (UInt8) -> Bool + ) async throws -> (bytes: ByteBuffer, readEOF: Bool) { + // Check if the required bytes are in the buffer already. + let view = self.buffer.readableBytesView + + if let index = view.firstIndex(where: { !predicate($0) }) { + // Got an index; slice off the front of the buffer. + let prefix = view[.. self.buffer.readableBytes { + self.offset += Int64(count &- self.buffer.readableBytes) + self.buffer.clear() + } else { + self.buffer.moveReaderIndex(forwardBy: count) + } + } + + /// Reads and discards bytes until `predicate` returns `false.` + /// + /// - Parameters: + /// - predicate: A predicate which evaluates to `true` for all dropped bytes. + public mutating func drop(while predicate: (UInt8) -> Bool) async throws { + let view = self.buffer.readableBytesView + + if let index = view.firstIndex(where: { !predicate($0) }) { + let slice = view[.. Bool + ) async throws -> ByteBuffer { + try await self.read(while: predicate).bytes + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ReadableFileHandleProtocol { + /// Creates a new ``BufferedReader`` for this file handle. + /// + /// - Parameters: + /// - initialOffset: The offset to begin reading from, defaults to zero. + /// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. Defaults to 512 KiB. + /// - Returns: A ``BufferedReader``. + public func bufferedReader( + startingAtAbsoluteOffset initialOffset: Int64 = 0, + capacity: ByteCount = .kibibytes(512) + ) -> BufferedReader { + BufferedReader(wrapping: self, initialOffset: initialOffset, capacity: Int(capacity.bytes)) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedReader: Sendable where Handle: Sendable {} diff --git a/Sources/_NIOFileSystem/BufferedWriter.swift b/Sources/_NIOFileSystem/BufferedWriter.swift new file mode 100644 index 000000000..95c05d0bf --- /dev/null +++ b/Sources/_NIOFileSystem/BufferedWriter.swift @@ -0,0 +1,248 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +/// A writer which buffers bytes in memory before writing them to the file system. +/// +/// You can create a ``BufferedWriter`` by calling +/// ``WritableFileHandleProtocol/bufferedWriter(startingAtAbsoluteOffset:capacity:)`` on +/// ``WritableFileHandleProtocol`` and write bytes to it with one of the following methods: +/// - ``BufferedWriter/write(contentsOf:)-1rkf6`` +/// - ``BufferedWriter/write(contentsOf:)-7cs3v`` +/// - ``BufferedWriter/write(contentsOf:)-66cts`` +/// +/// If a call to one of the write functions reaches the buffers ``BufferedWriter/capacity`` the +/// buffer automatically writes its contents to the file. +/// +/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the +/// configured size. +/// +/// To write the bytes in the buffer to the file system before the buffer is full +/// use ``BufferedWriter/flush()``. +/// +/// - Important: You should you call ``BufferedWriter/flush()`` when you have finished appending +/// to write any remaining data to the file system. +@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 + /// A buffer of bytes to write. + private var buffer: [UInt8] = [] + + /// The maximum number of bytes to buffer before the buffer is automatically flushed. + public let capacity: Int + + /// The number of bytes in the buffer. + /// + /// You can flush the buffer manually by calling ``flush()``. + public var bufferedBytes: Int { + self.buffer.count + } + + /// The capacity of the buffer. + @_spi(Testing) + public var bufferCapacity: Int { + self.buffer.capacity + } + + internal init(wrapping writableHandle: Handle, initialOffset: Int64, capacity: Int) { + precondition( + initialOffset >= 0, + "initialOffset (\(initialOffset)) must be greater than or equal to zero" + ) + precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero") + self.handle = writableHandle + self.offset = initialOffset + self.capacity = capacity + } + + /// Write the contents of the collection of bytes to the buffer. + /// + /// If the number of bytes in the buffer exceeds the size of the buffer then they're + /// automatically written to the file system. + /// + /// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the + /// configured size. + /// + /// To manually flush bytes use ``flush()``. + /// + /// - Parameter bytes: The bytes to write to the buffer. + /// - Returns: The number of bytes written into the buffered writer. + @discardableResult + public mutating func write(contentsOf bytes: some Sequence) async throws -> Int64 { + let bufferSize = Int64(self.buffer.count) + self.buffer.append(contentsOf: bytes) + let bytesWritten = Int64(self.buffer.count) &- bufferSize + + if self.buffer.count >= self.capacity { + try await self.flush() + } + + return bytesWritten + } + + /// Write the contents of the `ByteBuffer` into the buffer. + /// + /// If the number of bytes in the buffer exceeds the size of the buffer then they're + /// automatically written to the file system. + /// + /// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the + /// configured size. + /// + /// To manually flush bytes use ``flush()``. + /// + /// - Parameter bytes: The bytes to write to the buffer. + /// - Returns: The number of bytes written into the buffered writer. + @discardableResult + public mutating func write(contentsOf bytes: ByteBuffer) async throws -> Int64 { + try await self.write(contentsOf: bytes.readableBytesView) + } + + /// Write the contents of the `AsyncSequence` of byte chunks to the buffer. + /// + /// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the + /// contents of the buffer are automatically written to the file system. + /// + /// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the + /// configured size. + /// + /// To manually flush bytes use ``flush()``. + /// + /// - Parameter chunks: The `AsyncSequence` of byte chunks to write to the buffer. + /// - Returns: The number of bytes written into the buffered writer. + @discardableResult + public mutating func write( + contentsOf chunks: Chunks + ) async throws -> Int64 where Chunks.Element: Sequence { + var bytesWritten: Int64 = 0 + do { + for try await chunk in chunks { + bytesWritten += try await self.write(contentsOf: chunk) + } + } catch let error as FileSystemError { + // From call to 'write'. + throw error + } catch let error { + // From iterating the async sequence. + throw FileSystemError( + code: .unknown, + message: "AsyncSequence of bytes threw error while writing to the buffered writer.", + cause: error, + location: .here() + ) + } + return bytesWritten + } + + /// Write the contents of the `AsyncSequence` of `ByteBuffer`s into the buffer. + /// + /// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the + /// contents of the buffer are automatically written to the file system. + /// + /// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the + /// configured size. + /// + /// To manually flush bytes use ``flush()``. + /// + /// - Parameter chunks: The `AsyncSequence` of `ByteBuffer`s to write. + /// - Returns: The number of bytes written into the buffered writer. + @discardableResult + public mutating func write( + contentsOf chunks: Chunks + ) async throws -> Int64 where Chunks.Element == ByteBuffer { + try await self.write(contentsOf: chunks.map { $0.readableBytesView }) + } + + /// Write the contents of the `AsyncSequence` of bytes the buffer. + /// + /// If appending a byte to the buffer causes it to exceed the capacity of the buffer then the + /// contents of the buffer are automatically written to the file system. + /// + /// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the + /// configured size. + /// + /// To manually flush bytes use ``flush()``. + /// + /// - Parameter bytes: The `AsyncSequence` of bytes to write to the buffer. + @discardableResult + public mutating func write( + contentsOf bytes: Bytes + ) async throws -> Int64 where Bytes.Element == UInt8 { + try await self.write(contentsOf: bytes.map { CollectionOfOne($0) }) + } + + /// Flush any buffered bytes to the file system. + /// + /// - Important: You should you call ``flush()`` when you have finished writing to ensure the + /// buffered writer writes any remaining data to the file system. + 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) + + // 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. + let keepCapacity = self.buffer.capacity <= (self.capacity * 2) + self.buffer.removeAll(keepingCapacity: keepCapacity) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension WritableFileHandleProtocol { + /// Creates a new ``BufferedWriter`` for this file handle. + /// + /// - Parameters: + /// - initialOffset: The offset to begin writing at, defaults to zero. + /// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. The writer writes the contents of its + /// buffer to the file system when it exceeds this capacity. Defaults to 512 KiB. + /// - Returns: A ``BufferedWriter``. + public func bufferedWriter( + startingAtAbsoluteOffset initialOffset: Int64 = 0, + capacity: ByteCount = .kibibytes(512) + ) -> BufferedWriter { + BufferedWriter( + wrapping: self, + initialOffset: initialOffset, + capacity: Int(capacity.bytes) + ) + } + + /// Convenience function that creates a buffered reader, executes + /// the closure that writes the contents into the buffer and calls 'flush()'. + /// + /// - Parameters: + /// - initialOffset: The offset to begin writing at, defaults to zero. + /// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. The writer writes the contents of its + /// buffer to the file system when it exceeds this capacity. Defaults to 512 KiB. + /// - body: The closure that writes the contents to the buffer created in this method. + /// - Returns: The result of the executed closure. + public func withBufferedWriter( + startingAtAbsoluteOffset initialOffset: Int64 = 0, + capacity: ByteCount = .kibibytes(512), + execute body: (inout BufferedWriter) async throws -> Result + ) async throws -> Result { + var bufferedWriter = self.bufferedWriter(startingAtAbsoluteOffset: initialOffset, capacity: capacity) + return try await withUncancellableTearDown { + try await body(&bufferedWriter) + } tearDown: { _ in + try await bufferedWriter.flush() + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedWriter: Sendable where Handle: Sendable {} diff --git a/Sources/_NIOFileSystem/ByteBuffer+FileSystem.swift b/Sources/_NIOFileSystem/ByteBuffer+FileSystem.swift new file mode 100644 index 000000000..f045e8384 --- /dev/null +++ b/Sources/_NIOFileSystem/ByteBuffer+FileSystem.swift @@ -0,0 +1,97 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ByteBuffer { + /// Reads the contents of the file at the path. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + self = try await fileSystem.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd( + fromAbsoluteOffset: 0, + maximumSizeAllowed: maximumSizeAllowed + ) + } + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } + + /// Writes the readable bytes of the ``ByteBuffer`` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - fileSystem: The ``FileSystemProtocol`` instance to use. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false), + fileSystem: some FileSystemProtocol + ) async throws -> Int64 { + try await self.readableBytesView.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: fileSystem + ) + } + + /// Writes the readable bytes of the ``ByteBuffer`` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false) + ) async throws -> Int64 { + try await self.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: .shared + ) + } +} diff --git a/Sources/_NIOFileSystem/ByteCount.swift b/Sources/_NIOFileSystem/ByteCount.swift new file mode 100644 index 000000000..d92f1a356 --- /dev/null +++ b/Sources/_NIOFileSystem/ByteCount.swift @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +/// Represents the number of bytes. +public struct ByteCount: Hashable, Sendable { + /// The number of bytes + public var bytes: Int64 + + /// Returns a ``ByteCount`` with a given number of bytes + /// - Parameter count: The number of bytes + public static func bytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: count) + } + + /// Returns a ``ByteCount`` with a given number of kilobytes + /// + /// One kilobyte is 1000 bytes. + /// + /// - Parameter count: The number of kilobytes + public static func kilobytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1000 * count) + } + + /// Returns a ``ByteCount`` with a given number of megabytes + /// + /// One megabyte is 1,000,000 bytes. + /// + /// - Parameter count: The number of megabytes + public static func megabytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1000 * 1000 * count) + } + + /// Returns a ``ByteCount`` with a given number of gigabytes + /// + /// One gigabyte is 1,000,000,000 bytes. + /// + /// - Parameter count: The number of gigabytes + public static func gigabytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1000 * 1000 * 1000 * count) + } + + /// Returns a ``ByteCount`` with a given number of kibibytes + /// + /// One kibibyte is 1024 bytes. + /// + /// - Parameter count: The number of kibibytes + public static func kibibytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1024 * count) + } + + /// Returns a ``ByteCount`` with a given number of mebibytes + /// + /// One mebibyte is 10,485,760 bytes. + /// + /// - Parameter count: The number of mebibytes + public static func mebibytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1024 * 1024 * count) + } + + /// Returns a ``ByteCount`` with a given number of gibibytes + /// + /// One gibibyte is 10,737,418,240 bytes. + /// + /// - Parameter count: The number of gibibytes + public static func gibibytes(_ count: Int64) -> ByteCount { + ByteCount(bytes: 1024 * 1024 * 1024 * count) + } +} + +extension ByteCount { + /// A ``ByteCount`` for the maximum amount of bytes that can be written to `ByteBuffer`. + internal static var byteBufferCapacity: ByteCount { + #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) + // on 32-bit platforms we can't make use of a whole UInt32.max (as it doesn't fit in an Int) + let byteBufferMaxIndex = UInt32(Int.max) + #else + // on 64-bit platforms we're good + let byteBufferMaxIndex = UInt32.max + #endif + + return ByteCount(bytes: Int64(byteBufferMaxIndex)) + } + + /// A ``ByteCount`` for an unlimited amount of bytes. + public static var unlimited: ByteCount { + ByteCount(bytes: .max) + } +} + +extension ByteCount: AdditiveArithmetic { + public static var zero: ByteCount { ByteCount(bytes: 0) } + + public static func + (lhs: ByteCount, rhs: ByteCount) -> ByteCount { + ByteCount(bytes: lhs.bytes + rhs.bytes) + } + + public static func - (lhs: ByteCount, rhs: ByteCount) -> ByteCount { + ByteCount(bytes: lhs.bytes - rhs.bytes) + } +} + +extension ByteCount: Comparable { + public static func < (lhs: ByteCount, rhs: ByteCount) -> Bool { + lhs.bytes < rhs.bytes + } +} diff --git a/Sources/_NIOFileSystem/Convenience.swift b/Sources/_NIOFileSystem/Convenience.swift new file mode 100644 index 000000000..807d44807 --- /dev/null +++ b/Sources/_NIOFileSystem/Convenience.swift @@ -0,0 +1,202 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +extension String { + /// Writes the UTF8 encoded `String` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the `String` to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - fileSystem: The ``FileSystemProtocol`` instance to use. + /// - Returns: The number of bytes written to the file. + @discardableResult + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false), + fileSystem: some FileSystemProtocol + ) async throws -> Int64 { + try await self.utf8.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: fileSystem + ) + } + + /// Writes the UTF8 encoded `String` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the `String` to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - Returns: The number of bytes written to the file. + @discardableResult + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false) + ) async throws -> Int64 { + try await self.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: .shared + ) + } +} + +extension Sequence where Self: Sendable { + /// Writes the contents of the `Sequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - fileSystem: The ``FileSystemProtocol`` instance to use. + /// - Returns: The number of bytes written to the file. + @discardableResult + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false), + fileSystem: some FileSystemProtocol + ) async throws -> Int64 { + try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in + try await handle.write(contentsOf: self, toAbsoluteOffset: offset) + } + } + + /// Writes the contents of the `Sequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - Returns: The number of bytes written to the file. + @discardableResult + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false) + ) async throws -> Int64 { + try await self.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: .shared + ) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension AsyncSequence where Self.Element: Sequence, Self: Sendable { + /// Writes the contents of the `AsyncSequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - fileSystem: The ``FileSystemProtocol`` instance to use. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false), + fileSystem: some FileSystemProtocol + ) async throws -> Int64 { + try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in + var writer = handle.bufferedWriter(startingAtAbsoluteOffset: offset) + let bytesWritten = try await writer.write(contentsOf: self) + try await writer.flush() + return bytesWritten + } + } + + /// Writes the contents of the `AsyncSequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false) + ) async throws -> Int64 { + try await self.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: .shared + ) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension AsyncSequence where Self.Element == UInt8, Self: Sendable { + /// Writes the contents of the `AsyncSequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - fileSystem: The ``FileSystemProtocol`` instance to use. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false), + fileSystem: some FileSystemProtocol + ) async throws -> Int64 { + try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in + var writer = handle.bufferedWriter(startingAtAbsoluteOffset: offset) + let bytesWritten = try await writer.write(contentsOf: self) + try await writer.flush() + return bytesWritten + } + } + + /// Writes the contents of the `AsyncSequence` to a file. + /// + /// - Parameters: + /// - path: The path of the file to write the contents of the sequence to. + /// - offset: The offset into the file to write to, defaults to zero. + /// - options: Options for opening the file, defaults to creating a new file. + /// - Returns: The number of bytes written to the file. + @discardableResult + public func write( + toFileAt path: FilePath, + absoluteOffset offset: Int64 = 0, + options: OpenOptions.Write = .newFile(replaceExisting: false) + ) async throws -> Int64 { + try await self.write( + toFileAt: path, + absoluteOffset: offset, + options: options, + fileSystem: .shared + ) + } +} diff --git a/Sources/_NIOFileSystem/DirectoryEntries.swift b/Sources/_NIOFileSystem/DirectoryEntries.swift new file mode 100644 index 000000000..f14e4bdea --- /dev/null +++ b/Sources/_NIOFileSystem/DirectoryEntries.swift @@ -0,0 +1,742 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import CNIODarwin +import CNIOLinux +import NIOConcurrencyHelpers +import NIOCore +import NIOPosix +import SystemPackage + +/// An `AsyncSequence` of entries in a directory. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct DirectoryEntries: AsyncSequence, Sendable { + public typealias AsyncIterator = DirectoryIterator + public typealias Element = DirectoryEntry + + /// The sequence. + private let batchedSequence: Batched + + /// Creates a new ``DirectoryEntries`` sequence. + internal init(handle: SystemFileHandle, recursive: Bool) { + self.batchedSequence = Batched(handle: handle, recursive: recursive) + } + + /// Creates a ``DirectoryEntries`` sequence by wrapping an `AsyncSequence` of _batches_ of + /// directory entries. + @preconcurrency + public init(wrapping sequence: S) + where S.Element == Batched.Element, S.AsyncIterator: _NIOFileSystemSendableMetatype { + self.batchedSequence = Batched(wrapping: sequence) + } + + public func makeAsyncIterator() -> DirectoryIterator { + DirectoryIterator(iterator: self.batchedSequence.makeAsyncIterator()) + } + + /// Returns a sequence of directory entry batches. + /// + /// The batched sequence has its element type as `Array` rather + /// than `DirectoryEntry`. This can enable better performance by reducing the number of + /// executor hops. + public func batched() -> Batched { + self.batchedSequence + } + + /// An `AsyncIteratorProtocol` of `DirectoryEntry`. + public struct DirectoryIterator: AsyncIteratorProtocol { + /// The batched iterator to consume from. + private var iterator: Batched.AsyncIterator + /// A slice of the current batch being iterated. + private var currentBatch: ArraySlice + + init(iterator: Batched.AsyncIterator) { + self.iterator = iterator + self.currentBatch = [] + } + + public mutating func next() async throws -> DirectoryEntry? { + if self.currentBatch.isEmpty { + let batch = try await self.iterator.next() + self.currentBatch = (batch ?? [])[...] + } + + return self.currentBatch.popFirst() + } + } +} + +@available(*, unavailable) +extension DirectoryEntries.AsyncIterator: Sendable {} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension DirectoryEntries { + /// An `AsyncSequence` of batches of directory entries. + /// + /// The ``Batched`` sequence uses `Array` as its element type rather + /// than `DirectoryEntry`. This can enable better performance by reducing the number of + /// executor hops at the cost of ease-of-use. + public struct Batched: AsyncSequence, Sendable { + public typealias AsyncIterator = BatchedIterator + public typealias Element = [DirectoryEntry] + + private let stream: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer> + + /// Creates a ``DirectoryEntries/Batched`` sequence by wrapping an `AsyncSequence` + /// of directory entry batches. + @preconcurrency + public init(wrapping sequence: S) + where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype { + self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence) + } + + fileprivate init(handle: SystemFileHandle, recursive: Bool) { + // Expanding the batches yields watermarks of 256 and 512 directory entries. + let stream = NIOThrowingAsyncSequenceProducer.makeBatchedDirectoryEntryStream( + handle: handle, + recursive: recursive, + entriesPerBatch: 64, + lowWatermark: 4, + highWatermark: 8 + ) + + self.stream = BufferedOrAnyStream(wrapping: stream) + } + + public func makeAsyncIterator() -> BatchedIterator { + BatchedIterator(wrapping: self.stream.makeAsyncIterator()) + } + + /// An `AsyncIteratorProtocol` of `Array`. + public struct BatchedIterator: AsyncIteratorProtocol { + private var iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator + + fileprivate init( + wrapping iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator + ) { + self.iterator = iterator + } + + public mutating func next() async throws -> [DirectoryEntry]? { + try await self.iterator.next() + } + } + } +} + +@available(*, unavailable) +extension DirectoryEntries.Batched.AsyncIterator: Sendable {} + +// MARK: - Internal + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension NIOThrowingAsyncSequenceProducer +where + Element == [DirectoryEntry], + Failure == (any Error), + Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, + Delegate == DirectoryEntryProducer +{ + fileprivate static func makeBatchedDirectoryEntryStream( + handle: SystemFileHandle, + recursive: Bool, + entriesPerBatch: Int, + lowWatermark: Int, + highWatermark: Int + ) -> NIOThrowingAsyncSequenceProducer< + [DirectoryEntry], any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, + DirectoryEntryProducer + > { + let producer = DirectoryEntryProducer( + handle: handle, + recursive: recursive, + entriesPerBatch: entriesPerBatch + ) + + let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence( + elementType: [DirectoryEntry].self, + backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark( + lowWatermark: lowWatermark, + highWatermark: highWatermark + ), + finishOnDeinit: false, + delegate: producer + ) + + producer.setSequenceProducerSource(nioThrowingAsyncSequence.source) + + return nioThrowingAsyncSequence.sequence + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private typealias DirectoryEntrySequenceProducer = NIOThrowingAsyncSequenceProducer< + [DirectoryEntry], Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, DirectoryEntryProducer +> + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private final class DirectoryEntryProducer: NIOAsyncSequenceProducerDelegate { + let state: NIOLockedValueBox + let entriesPerBatch: Int + + init(handle: SystemFileHandle, recursive: Bool, entriesPerBatch: Int) { + let state = DirectoryEnumerator(handle: handle, recursive: recursive) + self.state = NIOLockedValueBox(state) + self.entriesPerBatch = entriesPerBatch + } + + func didTerminate() { + guard let threadPool = self.state.withLockedValue({ $0.threadPoolForClosing() }) else { + return + } + + threadPool.submit { _ in // always run, even if cancelled + self.state.withLockedValue { state in + state.closeIfNecessary() + } + } + } + + /// sets the source within the producer state + func setSequenceProducerSource(_ sequenceProducerSource: DirectoryEntrySequenceProducer.Source) { + self.state.withLockedValue { state in + switch state.state { + case .idle: + state.sequenceProducerSource = sequenceProducerSource + case .done: + sequenceProducerSource.finish() + case .open, .openPausedProducing: + fatalError() + case .modifying: + fatalError() + } + } + } + + func clearSource() { + self.state.withLockedValue { state in + state.sequenceProducerSource = nil + } + } + + /// The 'entry point' for producing elements. + /// + /// Calling this function will start producing directory entries asynchronously by dispatching + /// work to the IO executor and feeding the result back to the stream source. On yielding to the + /// source it will either produce more or be scheduled to produce more. Stopping production + /// is signalled via the stream's 'onTermination' handler. + func produceMore() { + let threadPool = self.state.withLockedValue { state in + state.produceMore() + } + + // No thread pool means we're done. + guard let threadPool = threadPool else { return } + + threadPool.submit { + let result: Result<[DirectoryEntry], Error> + switch $0 { + case .active: + result = Result { try self.nextBatch() } + case .cancelled: + result = .failure(CancellationError()) + } + self.onNextBatchResult(result) + } + } + + func pauseProducing() { + self.state.withLockedValue { state in + state.pauseProducing() + } + } + + private func nextBatch() throws -> [DirectoryEntry] { + try self.state.withLockedValue { state in + try state.next(self.entriesPerBatch) + } + } + + private func onNextBatchResult(_ result: Result<[DirectoryEntry], Error>) { + switch result { + case let .success(entries): + self.onNextBatch(entries) + case let .failure(error): + // Failed to read more entries: close and notify the stream so consumers receive the + // error. + self.close() + let source = self.state.withLockedValue { state in + state.sequenceProducerSource + } + source?.finish(error) + self.clearSource() + } + } + + private func onNextBatch(_ entries: [DirectoryEntry]) { + let source = self.state.withLockedValue { state in + state.sequenceProducerSource + } + + guard let source else { + assertionFailure("unexpectedly missing source") + return + } + + // No entries were read: this must be the end (as the batch size must be greater than zero). + if entries.isEmpty { + source.finish() + self.clearSource() + return + } + + // Reading short means reading EOF. The enumerator closes itself in that case. + let readEOF = entries.count < self.entriesPerBatch + + // Entries were produced: yield them and maybe produce more. + let writeResult = source.yield(contentsOf: CollectionOfOne(entries)) + + // Exit early if EOF was read; no use in trying to produce more. + if readEOF { + source.finish() + self.clearSource() + return + } + + switch writeResult { + case .produceMore: + self.produceMore() + case .stopProducing: + self.pauseProducing() + case .dropped: + // The source is finished; mark ourselves as done. + self.close() + } + } + + private func close() { + guard let threadPool = self.state.withLockedValue({ $0.threadPoolForClosing() }) else { + return + } + + threadPool.submit { _ in // always run, even if cancelled + self.state.withLockedValue { state in + state.closeIfNecessary() + } + } + } +} + +/// Enumerates a directory in batches. +/// +/// Note that this is not a `Sequence` because we allow for errors to be thrown on `next()`. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private struct DirectoryEnumerator: Sendable { + internal enum State: @unchecked Sendable { + case modifying + case idle(SystemFileHandle.SendableView, recursive: Bool) + case open(NIOThreadPool, Source, [DirectoryEntry]) + case openPausedProducing(NIOThreadPool, Source, [DirectoryEntry]) + case done + } + + /// The source of directory entries. + internal enum Source { + case readdir(CInterop.DirPointer) + case fts(CInterop.FTSPointer) + } + + /// The current state of enumeration. + internal var state: State + + /// The path to the directory being enumerated. + private let path: FilePath + + /// The route via which directory entry batches are yielded, + /// the sourcing end of the `DirectoryEntrySequenceProducer` + internal var sequenceProducerSource: DirectoryEntrySequenceProducer.Source? + + /// Information about an entry returned by FTS. See 'fts(3)'. + private enum FTSInfo: Hashable, Sendable { + case directoryPreOrder + case directoryCausingCycle + case ftsDefault + case directoryUnreadable + case dotFile + case directoryPostOrder + case error + case regularFile + case noStatInfoAvailable + case noStatInfoRequested + case symbolicLink + case symbolicLinkToNonExistentTarget + + init?(rawValue: UInt16) { + switch Int32(rawValue) { + case FTS_D: + self = .directoryPreOrder + case FTS_DC: + self = .directoryCausingCycle + case FTS_DEFAULT: + self = .ftsDefault + case FTS_DNR: + self = .directoryUnreadable + case FTS_DOT: + self = .dotFile + case FTS_DP: + self = .directoryPostOrder + case FTS_ERR: + self = .error + case FTS_F: + self = .regularFile + case FTS_NS: + self = .noStatInfoAvailable + case FTS_NSOK: + self = .noStatInfoRequested + case FTS_SL: + self = .symbolicLink + case FTS_SLNONE: + self = .symbolicLinkToNonExistentTarget + default: + return nil + } + } + } + + internal init(handle: SystemFileHandle, recursive: Bool) { + self.state = .idle(handle.sendableView, recursive: recursive) + self.path = handle.path + } + + internal mutating func produceMore() -> NIOThreadPool? { + switch self.state { + case let .idle(handle, _): + return handle.threadPool + case let .open(threadPool, _, _): + return threadPool + case .openPausedProducing(let threadPool, let source, let array): + self.state = .open(threadPool, source, array) + return threadPool + case .done: + return nil + case .modifying: + fatalError() + } + } + + internal mutating func pauseProducing() { + switch self.state { + case .open(let threadPool, let source, let array): + self.state = .openPausedProducing(threadPool, source, array) + case .idle: + () // we won't apply back pressure until something has been read + case .openPausedProducing, .done: + () // no-op + case .modifying: + fatalError() + } + } + + internal func threadPoolForClosing() -> NIOThreadPool? { + switch self.state { + case .open(let threadPool, _, _), .openPausedProducing(let threadPool, _, _): + return threadPool + case .idle, .done: + // Don't need to close in the idle state: we don't own the handle. + return nil + case .modifying: + fatalError() + } + } + + /// Returns the next batch of directory entries. + internal mutating func next(_ count: Int) throws -> [DirectoryEntry] { + while true { + switch self.process(count) { + case let .yield(result): + return try result.get() + case .continue: + () + } + } + } + + /// Closes the descriptor, if necessary. + internal mutating func closeIfNecessary() { + switch self.state { + case .idle: + // We don't own the handle so don't close it. + self.state = .done + + case .open(_, let mode, _), .openPausedProducing(_, let mode, _): + self.state = .done + switch mode { + case .readdir(let dir): + _ = Libc.closedir(dir) + case .fts(let fts): + _ = Libc.ftsClose(fts) + } + + case .done: + () + + case .modifying: + fatalError() + } + } + + private enum ProcessResult { + case yield(Result<[DirectoryEntry], FileSystemError>) + case `continue` + } + + private mutating func makeReaddirSource( + _ handle: SystemFileHandle.SendableView + ) -> Result { + handle._duplicate().mapError { dupError in + FileSystemError( + message: "Unable to open directory stream for '\(handle.path)'.", + wrapping: dupError + ) + }.flatMap { descriptor in + // We own the descriptor and cede ownership if 'opendir' succeeds; if it doesn't we need + // to close it. + descriptor.opendir().mapError { errno in + // Close the descriptor on error. + try? descriptor.close() + return FileSystemError.fdopendir(errno: errno, path: handle.path, location: .here()) + } + }.map { + .readdir($0) + } + } + + private mutating func makeFTSSource( + _ handle: SystemFileHandle.SendableView + ) -> Result { + Libc.ftsOpen(handle.path, options: [.noChangeDir, .physical]).mapError { errno in + FileSystemError.open("fts_open", error: errno, path: handle.path, location: .here()) + }.map { + .fts($0) + } + } + + private mutating func processOpenState( + threadPool: NIOThreadPool, + dir: CInterop.DirPointer, + entries: inout [DirectoryEntry], + count: Int + ) -> (State, ProcessResult) { + entries.removeAll(keepingCapacity: true) + entries.reserveCapacity(count) + + while entries.count < count { + switch Libc.readdir(dir) { + case let .success(.some(entry)): + // Skip "." and ".." (and empty paths) + if self.isThisOrParentDirectory(entry.pointee) { + continue + } + + let fileType = FileType(direntType: entry.pointee.d_type) + let name: FilePath.Component + #if canImport(Darwin) + // Safe to force unwrap: may be nil if empty, a root, or more than one component. + // Empty is checked for above, root can't exist within a directory, and directory + // items must be a single path component. + name = FilePath.Component(platformString: CNIODarwin_dirent_dname(entry))! + #else + name = FilePath.Component(platformString: CNIOLinux_dirent_dname(entry))! + #endif + + let fullPath = self.path.appending(name) + // '!' is okay here: the init returns nil if there is an empty path which we know + // isn't the case as 'self.path' is non-empty. + entries.append(DirectoryEntry(path: fullPath, type: fileType)!) + + case .success(.none): + // Nothing we can do on failure so ignore the result. + _ = Libc.closedir(dir) + return (.done, .yield(.success(entries))) + + case let .failure(errno): + // Nothing we can do on failure so ignore the result. + _ = Libc.closedir(dir) + let error = FileSystemError.readdir( + errno: errno, + path: self.path, + location: .here() + ) + return (.done, .yield(.failure(error))) + } + } + + // We must have hit our 'count' limit. + return (.open(threadPool, .readdir(dir), entries), .yield(.success(entries))) + } + + private mutating func processOpenState( + threadPool: NIOThreadPool, + fts: CInterop.FTSPointer, + entries: inout [DirectoryEntry], + count: Int + ) -> (State, ProcessResult) { + entries.removeAll(keepingCapacity: true) + entries.reserveCapacity(count) + + while entries.count < count { + switch Libc.ftsRead(fts) { + case .success(.some(let entry)): + let info = FTSInfo(rawValue: entry.pointee.fts_info) + switch info { + case .directoryPreOrder: + let entry = DirectoryEntry(path: entry.path, type: .directory)! + entries.append(entry) + + case .directoryPostOrder: + () // Don't visit directories twice. + + case .regularFile: + let entry = DirectoryEntry(path: entry.path, type: .regular)! + entries.append(entry) + + case .symbolicLink, .symbolicLinkToNonExistentTarget: + let entry = DirectoryEntry(path: entry.path, type: .symlink)! + entries.append(entry) + + case .ftsDefault: + // File type is unknown. + let entry = DirectoryEntry(path: entry.path, type: .unknown)! + entries.append(entry) + + case .error: + let errno = Errno(rawValue: entry.pointee.fts_errno) + let error = FileSystemError( + code: .unknown, + message: "Can't read file system tree.", + cause: FileSystemError.SystemCallError(systemCall: "fts_read", errno: errno), + location: .here() + ) + _ = Libc.ftsClose(fts) + return (.done, .yield(.failure(error))) + + case .directoryCausingCycle: + () // Cycle found, ignore it and continue. + case .directoryUnreadable: + () // Can't read directory, ignore it and continue iterating. + case .dotFile: + () // Ignore "." and ".." + case .noStatInfoAvailable: + () // No stat info available so we can't list the entry, ignore it. + case .noStatInfoRequested: + () // Shouldn't happen. + + case nil: + () // Unknown, ignore. + } + + case .success(.none): + // No entries left to iterate. + _ = Libc.ftsClose(fts) + return (.done, .yield(.success(entries))) + + case .failure(let errno): + // Nothing we can do on failure so ignore the result. + _ = Libc.ftsClose(fts) + let error = FileSystemError.ftsRead( + errno: errno, + path: self.path, + location: .here() + ) + return (.done, .yield(.failure(error))) + } + } + + // We must have hit our 'count' limit. + return (.open(threadPool, .fts(fts), entries), .yield(.success(entries))) + } + + private mutating func process(_ count: Int) -> ProcessResult { + switch self.state { + case let .idle(handle, recursive): + let result: Result + + if recursive { + result = self.makeFTSSource(handle) + } else { + result = self.makeReaddirSource(handle) + } + + switch result { + case let .success(source): + self.state = .open(handle.threadPool, source, []) + return .continue + + case let .failure(error): + self.state = .done + return .yield(.failure(error)) + } + + case .open(let threadPool, let mode, var entries): + self.state = .modifying + + switch mode { + case .readdir(let dir): + let (state, result) = self.processOpenState( + threadPool: threadPool, + dir: dir, + entries: &entries, + count: count + ) + self.state = state + return result + + case .fts(let fts): + let (state, result) = self.processOpenState( + threadPool: threadPool, + fts: fts, + entries: &entries, + count: count + ) + self.state = state + return result + } + + case .openPausedProducing: + return .yield(.success([])) + + case .done: + return .yield(.success([])) + + case .modifying: + fatalError() + } + } + + private func isThisOrParentDirectory(_ entry: CInterop.DirEnt) -> Bool { + let dot = CChar(bitPattern: UInt8(ascii: ".")) + switch (entry.d_name.0, entry.d_name.1, entry.d_name.2) { + case (0, _, _), (dot, 0, _), (dot, dot, 0): + return true + default: + return false + } + } +} + +extension UnsafeMutablePointer { + fileprivate var path: FilePath { + FilePath(platformString: self.pointee.fts_path!) + } +} diff --git a/Sources/_NIOFileSystem/DirectoryEntry.swift b/Sources/_NIOFileSystem/DirectoryEntry.swift new file mode 100644 index 000000000..95ccabafd --- /dev/null +++ b/Sources/_NIOFileSystem/DirectoryEntry.swift @@ -0,0 +1,47 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +/// Information about an item within a directory. +public struct DirectoryEntry: Sendable, Hashable, Equatable { + /// The path of the directory entry. + /// + /// - Precondition: The path must have at least one component. + public let path: FilePath + + /// The name of the entry; the final component of the ``path``. + /// + /// If `path` is "/Users/tim/path-to-4T.key" then `name` will be "path-to-4T.key". + public var name: FilePath.Component { + self.path.lastComponent! + } + + /// The type of entry. + public var type: FileType + + /// Creates a directory entry; returns `nil` if `path` has no components. + /// + /// - Parameters: + /// - path: The path of the directory entry which must contain at least one component. + /// - type: The type of entry. + public init?(path: FilePath, type: FileType) { + if path.components.isEmpty { + return nil + } + + self.path = path + self.type = type + } +} diff --git a/Sources/_NIOFileSystem/Exports.swift b/Sources/_NIOFileSystem/Exports.swift new file mode 100644 index 000000000..2b73a5878 --- /dev/null +++ b/Sources/_NIOFileSystem/Exports.swift @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +// These types are used in our public API; expose them to make +// life easier for users. +@_exported import enum SystemPackage.CInterop +@_exported import struct SystemPackage.Errno +@_exported import struct SystemPackage.FileDescriptor +@_exported import struct SystemPackage.FilePath +@_exported import struct SystemPackage.FilePermissions diff --git a/Sources/_NIOFileSystem/FileChunks.swift b/Sources/_NIOFileSystem/FileChunks.swift new file mode 100644 index 000000000..1ff4b717c --- /dev/null +++ b/Sources/_NIOFileSystem/FileChunks.swift @@ -0,0 +1,547 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import NIOConcurrencyHelpers +import NIOCore +import NIOPosix +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. + private let stream: BufferedOrAnyStream + + /// Create a ``FileChunks`` sequence backed by wrapping an `AsyncSequence`. + @preconcurrency + public init(wrapping sequence: S) + where S.Element == ByteBuffer, S.AsyncIterator: _NIOFileSystemSendableMetatype { + self.stream = BufferedOrAnyStream(wrapping: sequence) + } + + internal init( + handle: SystemFileHandle, + 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, + lowWatermark: 4, + highWatermark: 8 + ) + + self.stream = BufferedOrAnyStream(wrapping: stream) + } + + public func makeAsyncIterator() -> FileChunkIterator { + FileChunkIterator(wrapping: self.stream.makeAsyncIterator()) + } + + public struct FileChunkIterator: AsyncIteratorProtocol { + private var iterator: BufferedOrAnyStream.AsyncIterator + + fileprivate init(wrapping iterator: BufferedOrAnyStream.AsyncIterator) { + self.iterator = iterator + } + + public mutating func next() async throws -> ByteBuffer? { + try await self.iterator.next() + } + } +} + +@available(*, unavailable) +extension FileChunks.FileChunkIterator: Sendable {} + +// MARK: - Internal + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private typealias FileChunkSequenceProducer = NIOThrowingAsyncSequenceProducer< + ByteBuffer, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, FileChunkProducer +> + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension NIOThrowingAsyncSequenceProducer +where + Element == ByteBuffer, + Failure == Error, + Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, + Delegate == FileChunkProducer +{ + static func makeFileChunksStream( + of: Element.Type = Element.self, + handle: SystemFileHandle, + chunkLength: Int64, + range: FileChunks.ChunkRange, + lowWatermark: Int, + highWatermark: Int + ) -> FileChunkSequenceProducer { + + let producer = FileChunkProducer( + range: range, + handle: handle, + chunkLength: chunkLength + ) + + let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence( + elementType: ByteBuffer.self, + backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark( + lowWatermark: lowWatermark, + highWatermark: highWatermark + ), + finishOnDeinit: false, + delegate: producer + ) + + producer.setSource(nioThrowingAsyncSequence.source) + + return nioThrowingAsyncSequence.sequence + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendable { + let state: NIOLockedValueBox + + 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) + self.path = handle.path + self.chunkLength = chunkLength + } + + /// sets the source within the producer state + func setSource(_ source: FileChunkSequenceProducer.Source) { + self.state.withLockedValue { state in + switch state.state { + case .producing, .pausedProducing: + state.source = source + case .done(let emptyRange): + if emptyRange { + source.finish() + } + } + } + } + + func clearSource() { + self.state.withLockedValue { state in + state.source = nil + } + } + + /// The 'entry point' for producing elements. + /// + /// Calling this function will start producing file chunks asynchronously by dispatching work + /// to the IO executor and feeding the result back to the stream source. On yielding to the + /// source it will either produce more or be scheduled to produce more. Stopping production + /// is signaled via the stream's 'onTermination' handler. + func produceMore() { + let threadPool = self.state.withLockedValue { state in + state.activeThreadPool() + } + // No thread pool means we're done. + guard let threadPool = threadPool else { return } + + threadPool.submit { workItemState in + // update state to reflect that we have been requested to perform a read + // the read may be performed immediately, queued to be performed later or ignored + let requestedReadAction = self.state.withLockedValue { state in + state.requestedProduceMore() + } + + switch requestedReadAction { + case .performRead: + let result: Result + switch workItemState { + case .active: + result = Result { try self.readNextChunk() } + case .cancelled: + result = .failure(CancellationError()) + } + + switch result { + case let .success(bytes): + self.didReadNextChunk(bytes) + case let .failure(error): + // Failed to read: update our state then notify the stream so consumers receive the + // error. + let source = self.state.withLockedValue { state in + state.done() + return state.source + } + source?.finish(error) + self.clearSource() + } + + case .stop: + return + } + + let performedReadAction = self.state.withLockedValue { state in + state.performedProduceMore() + } + + switch performedReadAction { + case .readMore: + self.produceMore() + case .stop: + return + } + + } + } + + private func readNextChunk() throws -> ByteBuffer { + 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) + return descriptor.readChunk( + fromAbsoluteOffset: range.lowerBound, + length: clampedLength + ).mapError { error in + .read(usingSyscall: .pread, error: error, path: self.path, location: .here()) + } + } else { + return descriptor.readChunk(length: self.chunkLength).mapError { error in + .read(usingSyscall: .read, error: error, path: self.path, location: .here()) + } + } + } else { + // nil means done: return empty to indicate the stream should finish. + return .success(ByteBuffer()) + } + }.get() + } + + private func didReadNextChunk(_ buffer: ByteBuffer) { + let chunkLength = self.chunkLength + assert(buffer.readableBytes <= chunkLength) + + let (source, initialState): (FileChunkSequenceProducer.Source?, ProducerState.State) = self.state + .withLockedValue { state in + state.didReadBytes(buffer.readableBytes) + + // finishing short indicates the file is done + if buffer.readableBytes < chunkLength { + state.state = .done(emptyRange: false) + } + return (state.source, state.state) + } + + 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: + source.finish() + self.clearSource() + return + case .producing, .pausedProducing: + () + } + + switch yieldResult { + case .produceMore: + () + case .stopProducing: + self.state.withLockedValue { state in state.pauseProducing() } + case .dropped: + // The source is finished; mark ourselves as done. + self.state.withLockedValue { state in state.done() } + } + } + + func didTerminate() { + self.state.withLockedValue { state in + state.done() + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private struct ProducerState: Sendable { + fileprivate struct Producing { + /// Possible states for activity relating to performing a read from disk + internal enum ActivityState { + /// The producer is not currently performing a read from disk + case inactive + /// The producer is in the critical section for reading from disk + case active + /// The producer is in the critical section for reading from disk and a further read has been requested. + /// This can happen e.g. if a sequence indicates that production should be paused then unpauses and calls + /// back into the code before the initial read block has exited. + case activeAndQueued + } + + /// 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? + + /// Keep track of whether or not we are currently actively engaged in a read + /// to protect against re-entrant behavior. + var activityState: ActivityState = .inactive + } + + internal enum State { + /// Can potentially produce values (if the handle is not closed). + case producing(Producing) + /// Backpressure policy means that we should stop producing new values for now + case pausedProducing(Producing) + /// Done producing values either by reaching EOF, some error or the stream terminating. + case done(emptyRange: Bool) + } + + internal var state: State + + /// The route via which file chunks are yielded, + /// the sourcing end of the `FileChunkSequenceProducer` + internal var source: FileChunkSequenceProducer.Source? + + init(handle: SystemFileHandle, range: Range?) { + if let range, range.isEmpty { + self.state = .done(emptyRange: true) + } else { + self.state = .producing(.init(handle: handle.sendableView, range: range)) + } + } + + /// Actions which may be taken after 'produce more' is requested. + /// + /// Either perform the read immediately or (optionally queue the read then) stop. + internal enum RequestedProduceMoreAction { + case performRead + case stop + } + + /// Update state to reflect that 'produce more' has been requested. + mutating func requestedProduceMore() -> RequestedProduceMoreAction { + switch self.state { + case .producing(var producingState): + switch producingState.activityState { + case .inactive: + producingState.activityState = .active + self.state = .producing(producingState) + return .performRead + case .active: + producingState.activityState = .activeAndQueued + self.state = .producing(producingState) + return .stop + case .activeAndQueued: + return .stop + } + + case .pausedProducing(var producingState): + switch producingState.activityState { + case .inactive: + producingState.activityState = .active + self.state = .producing(producingState) + return .performRead + case .active: + producingState.activityState = .activeAndQueued + self.state = .pausedProducing(producingState) + return .stop + case .activeAndQueued: + return .stop + } + + case .done: + return .stop + } + } + + /// Actions which may be taken after a more data is produced. + /// + /// Either go on to read more or stop. + internal enum PerformedProduceMoreAction { + case readMore + case stop + } + + /// Update state to reflect that a more data has been produced. + mutating func performedProduceMore() -> PerformedProduceMoreAction { + switch self.state { + case .producing(var producingState): + let oldActivityState = producingState.activityState + + producingState.activityState = .inactive + self.state = .producing(producingState) + + switch oldActivityState { + case .inactive: + preconditionFailure() + case .active, .activeAndQueued: + return .readMore + } + + case .pausedProducing(var producingState): + let oldActivityState = producingState.activityState + + producingState.activityState = .inactive + self.state = .pausedProducing(producingState) + + switch oldActivityState { + case .inactive: + preconditionFailure() + case .active: + return .stop + case .activeAndQueued: + return .readMore + } + + case .done: + return .stop + } + } + + mutating func activeThreadPool() -> NIOThreadPool? { + switch self.state { + case .producing(let producingState), .pausedProducing(let producingState): + return producingState.handle.threadPool + case .done: + return nil + } + } + + mutating func fileReadingState() -> Result<(FileDescriptor, Range?)?, FileSystemError> { + switch self.state { + case .producing(let producingState), .pausedProducing(let producingState): + if let descriptor = producingState.handle.descriptorIfAvailable() { + return .success((descriptor, producingState.range)) + } else { + let error = FileSystemError( + code: .closed, + message: "Cannot read from closed file ('\(producingState.handle.path)').", + cause: nil, + location: .here() + ) + return .failure(error) + } + case .done: + return .success(nil) + } + } + + mutating func didReadBytes(_ count: Int) { + switch self.state { + case var .producing(state): + switch state.updateRangeWithReadBytes(count) { + case .moreToRead: + self.state = .producing(state) + case .cannotReadMore: + self.state = .done(emptyRange: false) + } + case var .pausedProducing(state): + switch state.updateRangeWithReadBytes(count) { + case .moreToRead: + self.state = .pausedProducing(state) + case .cannotReadMore: + self.state = .done(emptyRange: false) + } + case .done: + () + } + } + + mutating func pauseProducing() { + switch self.state { + case .producing(let state): + self.state = .pausedProducing(state) + case .pausedProducing, .done: + () + } + } + + mutating func done() { + self.state = .done(emptyRange: false) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ProducerState.Producing { + internal enum RangeUpdateOutcome { + case moreToRead + case cannotReadMore + } + + /// Updates the range (the offsets to read from and up to) to reflect the number of bytes which have been read. + /// - Parameter count: The number of bytes which have been read. + /// - Returns: Returns `.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) + + // we have run out of bytes to read, we are done + if newLowerBound >= currentRange.upperBound { + self.range = currentRange.upperBound.. FileInfo { + try await self.fileHandle.info() + } + + public func replacePermissions(_ permissions: FilePermissions) async throws { + try await self.fileHandle.replacePermissions(permissions) + } + + public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.fileHandle.addPermissions(permissions) + } + + public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.fileHandle.removePermissions(permissions) + } + + public func attributeNames() async throws -> [String] { + try await self.fileHandle.attributeNames() + } + + public func valueForAttribute(_ name: String) async throws -> [UInt8] { + try await self.fileHandle.valueForAttribute(name) + } + + public func updateValueForAttribute( + _ bytes: some (Sendable & RandomAccessCollection), + attribute name: String + ) async throws { + try await self.fileHandle.updateValueForAttribute(bytes, attribute: name) + } + + public func removeValueForAttribute(_ name: String) async throws { + try await self.fileHandle.removeValueForAttribute(name) + } + + public func synchronize() async throws { + try await self.fileHandle.synchronize() + } + + public func withUnsafeDescriptor( + _ execute: @Sendable @escaping (FileDescriptor) throws -> R + ) async throws -> R { + try await self.fileHandle.withUnsafeDescriptor { + try execute($0) + } + } + + public func detachUnsafeFileDescriptor() throws -> FileDescriptor { + try self.fileHandle.detachUnsafeFileDescriptor() + } + + public func close() async throws { + try await self.fileHandle.close() + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } +} + +/// Implements ``FileHandleProtocol`` by making system calls to interact with the local file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct FileHandle: FileHandleProtocol, Sendable { + internal let systemFileHandle: SystemFileHandle + + internal init(wrapping handle: SystemFileHandle) { + self.systemFileHandle = handle + } + + public func info() async throws -> FileInfo { + try await self.systemFileHandle.info() + } + + public func replacePermissions(_ permissions: FilePermissions) async throws { + try await self.systemFileHandle.replacePermissions(permissions) + } + + public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.systemFileHandle.addPermissions(permissions) + } + + public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.systemFileHandle.removePermissions(permissions) + } + + public func attributeNames() async throws -> [String] { + try await self.systemFileHandle.attributeNames() + } + + public func valueForAttribute(_ name: String) async throws -> [UInt8] { + try await self.systemFileHandle.valueForAttribute(name) + } + + public func updateValueForAttribute( + _ bytes: some (Sendable & RandomAccessCollection), + attribute name: String + ) async throws { + try await self.systemFileHandle.updateValueForAttribute(bytes, attribute: name) + } + + public func removeValueForAttribute(_ name: String) async throws { + try await self.systemFileHandle.removeValueForAttribute(name) + } + + public func synchronize() async throws { + try await self.systemFileHandle.synchronize() + } + + public func withUnsafeDescriptor( + _ execute: @Sendable @escaping (FileDescriptor) throws -> R + ) async throws -> R { + try await self.systemFileHandle.withUnsafeDescriptor { + try execute($0) + } + } + + public func detachUnsafeFileDescriptor() throws -> FileDescriptor { + try self.systemFileHandle.detachUnsafeFileDescriptor() + } + + public func close() async throws { + try await self.systemFileHandle.close() + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } +} + +/// Implements ``ReadableFileHandleProtocol`` by making system calls to interact with the local +/// file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct ReadFileHandle: ReadableFileHandleProtocol, _HasFileHandle, Sendable { + public let fileHandle: FileHandle + + internal init(wrapping systemFileHandle: SystemFileHandle) { + self.fileHandle = FileHandle(wrapping: systemFileHandle) + } + + public func readChunk( + fromAbsoluteOffset offset: Int64, + length: ByteCount + ) async throws -> ByteBuffer { + try await self.fileHandle.systemFileHandle.readChunk( + fromAbsoluteOffset: offset, + length: length + ) + } + + public func readChunks(in range: Range, chunkLength: ByteCount) -> FileChunks { + self.fileHandle.systemFileHandle.readChunks(in: range, chunkLength: chunkLength) + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } +} + +/// Implements ``WritableFileHandleProtocol`` by making system calls to interact with the local +/// file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct WriteFileHandle: WritableFileHandleProtocol, _HasFileHandle, Sendable { + public let fileHandle: FileHandle + + internal init(wrapping systemFileHandle: SystemFileHandle) { + self.fileHandle = FileHandle(wrapping: systemFileHandle) + } + + @discardableResult + public func write( + contentsOf bytes: some (Sequence & Sendable), + toAbsoluteOffset offset: Int64 + ) async throws -> Int64 { + try await self.fileHandle.systemFileHandle.write( + contentsOf: bytes, + toAbsoluteOffset: offset + ) + } + + public func resize(to size: ByteCount) async throws { + try await self.fileHandle.systemFileHandle.resize(to: size) + } + + public func close(makeChangesVisible: Bool) async throws { + try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible) + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } +} + +/// Implements ``ReadableAndWritableFileHandleProtocol`` by making system calls to interact with the +/// local file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol, _HasFileHandle, Sendable { + public let fileHandle: FileHandle + + internal init(wrapping systemFileHandle: SystemFileHandle) { + self.fileHandle = FileHandle(wrapping: systemFileHandle) + } + + public func readChunk( + fromAbsoluteOffset offset: Int64, + length: ByteCount + ) async throws -> ByteBuffer { + try await self.fileHandle.systemFileHandle.readChunk( + fromAbsoluteOffset: offset, + length: length + ) + } + + public func readChunks(in offset: Range, chunkLength: ByteCount) -> FileChunks { + self.fileHandle.systemFileHandle.readChunks(in: offset, chunkLength: chunkLength) + } + + @discardableResult + public func write( + contentsOf bytes: some (Sequence & Sendable), + toAbsoluteOffset offset: Int64 + ) async throws -> Int64 { + try await self.fileHandle.systemFileHandle.write( + contentsOf: bytes, + toAbsoluteOffset: offset + ) + } + + public func resize(to size: ByteCount) async throws { + try await self.fileHandle.systemFileHandle.resize(to: size) + } + + public func close(makeChangesVisible: Bool) async throws { + try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible) + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } +} + +/// Implements ``DirectoryFileHandleProtocol`` by making system calls to interact with the local +/// file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct DirectoryFileHandle: DirectoryFileHandleProtocol, _HasFileHandle, Sendable { + public let fileHandle: FileHandle + + internal init(wrapping systemFileHandle: SystemFileHandle) { + self.fileHandle = FileHandle(wrapping: systemFileHandle) + } + + public func listContents(recursive: Bool) -> DirectoryEntries { + self.fileHandle.systemFileHandle.listContents(recursive: recursive) + } + + public func openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) async throws -> ReadFileHandle { + let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile( + forReadingAt: path, + options: options + ) + return ReadFileHandle(wrapping: systemFileHandle) + } + + public func openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> WriteFileHandle { + let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile( + forWritingAt: path, + options: options + ) + return WriteFileHandle(wrapping: systemFileHandle) + } + + public func openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> ReadWriteFileHandle { + let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile( + forReadingAndWritingAt: path, + options: options + ) + return ReadWriteFileHandle(wrapping: systemFileHandle) + } + + public func openDirectory( + atPath path: FilePath, + options: OpenOptions.Directory + ) async throws -> DirectoryFileHandle { + let systemFileHandle = try await self.fileHandle.systemFileHandle.openDirectory( + atPath: path, + options: options + ) + return DirectoryFileHandle(wrapping: systemFileHandle) + } +} diff --git a/Sources/_NIOFileSystem/FileHandleProtocol.swift b/Sources/_NIOFileSystem/FileHandleProtocol.swift new file mode 100644 index 000000000..12edeadb6 --- /dev/null +++ b/Sources/_NIOFileSystem/FileHandleProtocol.swift @@ -0,0 +1,769 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore +import SystemPackage + +/// A handle for a file system object. +/// +/// There is a hierarchy of file handle protocols which allow for different functionality. All +/// file handle protocols refine the base ``FileHandleProtocol`` protocol. +/// +/// ``` +/// ┌────────────────────┐ +/// │ FileHandleProtocol │ +/// │ [Protocol] │ +/// └────────────────────┘ +/// ▲ +/// ┌──────────────────────────────┼────────────────────────────────┐ +/// │ │ │ +/// ┌────────────────────────────┐ ┌────────────────────────────┐ ┌─────────────────────────────┐ +/// │ ReadableFileHandleProtocol │ │ WritableFileHandleProtocol │ │ DirectoryFileHandleProtocol │ +/// │ [Protocol] │ │ [Protocol] │ │ [Protocol] │ +/// └────────────────────────────┘ └────────────────────────────┘ └─────────────────────────────┘ +/// ``` +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public protocol FileHandleProtocol { + /// Returns information about the file. + /// + /// Information is typically gathered by calling `fstat(2)` on the file. + /// + /// - Returns: Information about the open file. + func info() async throws -> FileInfo + + /// Replaces the permissions set on the file. + /// + /// Permissions are typically set using `fchmod(2)`. + /// + /// - Parameters: + /// - permissions: The permissions to set on the file. + func replacePermissions(_ permissions: FilePermissions) async throws + + /// Adds permissions to the existing permissions set for the file. + /// + /// This is equivalent to retrieving the permissions, merging them with the provided + /// permissions and then replacing the permissions on the file. + /// + /// - Parameters: + /// - permissions: The permissions to add to the file. + /// - Returns: The updated permissions. + @discardableResult + func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions + + /// Remove permissions from the existing permissions set for the file. + /// + /// This is equivalent to retrieving the permissions, subtracting any of the provided + /// permissions and then replacing the permissions on the file. + /// + /// - Parameters: + /// - permissions: The permissions to remove from the file. + /// - Returns: The updated permissions. + @discardableResult + func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions + + /// Returns an array containing the names of all extended attributes set on the file. + /// + /// Attributes names are typically fetched using `flistxattr(2)`. + func attributeNames() async throws -> [String] + + /// Returns the value for the named attribute if it exists; `nil` otherwise. + /// + /// Attribute values are typically fetched using `fgetxattr(2)`. + /// + /// - Parameters: + /// - name: The name of the attribute. + /// - Returns: The bytes of the value set for the attribute. If no value is set an empty array + /// is returned. + func valueForAttribute(_ name: String) async throws -> [UInt8] + + /// Replaces the value for the named attribute, creating it if it didn't already exist. + /// + /// Attribute values are typically replaced using `fsetxattr(2)`. + /// + /// - Parameters: + /// - bytes: The bytes to set as the value for the attribute. + /// - name: The name of the attribute. + func updateValueForAttribute( + _ bytes: some (Sendable & RandomAccessCollection), + attribute name: String + ) async throws + + /// Removes the value for the named attribute if it exists. + /// + /// Attribute values are typically removed using `fremovexattr(2)`. + /// + /// - Parameter name: The name of the attribute to remove. + func removeValueForAttribute(_ name: String) async throws + + /// Synchronize modified data and metadata to a permanent storage device. + /// + /// This is typically achieved using `fsync(2)`. + func synchronize() async throws + + /// Runs the provided callback with the file descriptor for this handle. + /// + /// This function should be used with caution: the `FileDescriptor` must not be escaped from + /// the closure nor should it be closed. Where possible make use of the methods defined + /// on ``FileHandleProtocol`` instead; this function is intended as an escape hatch. + /// + /// Note that `execute` is not run if the handle has already been closed. + /// + /// - Parameter execute: A closure to run. + /// - Returns: The result of the closure. + func withUnsafeDescriptor( + _ execute: @Sendable @escaping (FileDescriptor) throws -> R + ) async throws -> R + + /// Detaches and returns the file descriptor from the handle. + /// + /// After detaching the file descriptor the handle is rendered invalid. All methods will throw + /// an appropriate error if called. Detaching the descriptor yields ownerships to the caller. + /// + /// - Returns: The detached `FileDescriptor` + func detachUnsafeFileDescriptor() throws -> FileDescriptor + + /// Closes the file handle. + /// + /// It is important to close a handle once it has been finished with to avoid leaking + /// resources. Prefer using APIs which provided scoped access to a file handle which + /// manage lifecycles on your behalf. Note that if the handle has been detached via + /// ``detachUnsafeFileDescriptor()`` then it is not necessary to close the handle. + /// + /// After closing the handle calls to other functions will throw an appropriate error. + func close() async throws + + /// Sets the file's last access and last data modification times to the given values. + /// + /// If **either** time is `nil`, the current value will not be changed. + /// If **both** times are `nil`, then both times will be set to the current time. + /// + /// > Important: Times are only considered valid if their nanoseconds components are one of the following: + /// > - `UTIME_NOW` (you can use ``FileInfo/Timespec/now`` to get a Timespec set to this value), + /// > - `UTIME_OMIT` (you can use ``FileInfo/Timespec/omit`` to get a Timespec set to this value), + /// > - Greater than zero and no larger than 1000 million: if outside of this range, the value will be clamped to the closest valid value. + /// > The seconds component must also be positive: if it's not, zero will be used as the value instead. + /// + /// - Parameters: + /// - lastAccess: The new value of the file's last access time, as time elapsed since the Epoch. + /// - lastDataModification: The new value of the file's last data modification time, as time elapsed since the Epoch. + /// + /// - Throws: If there's an error updating the times. If this happens, the original values won't be modified. + func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws +} + +// MARK: - Readable + +/// A handle for reading data from an open file. +/// +/// ``ReadableFileHandleProtocol`` refines ``FileHandleProtocol`` to add requirements for reading data from a file. +/// +/// There are two requirements for implementing this protocol: +/// 1. ``readChunk(fromAbsoluteOffset:length:)``, and +/// 2. ``readChunks(chunkLength:) +/// +/// A number of overloads are provided which provide sensible defaults. +/// +/// Conformance to ``ReadableFileHandleProtocol`` also provides +/// ``readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`` (and various overloads with sensible +/// defaults) for reading the contents of a file into memory. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public protocol ReadableFileHandleProtocol: FileHandleProtocol { + /// Returns a slice of bytes read from the file. + /// + /// The length of the slice to read indicates the largest size in bytes that the returned slice + /// may be. The slice may be shorter than the given `length` if there are fewer bytes from the + /// `offset` to the end of the file. + /// + /// - Parameters: + /// - offset: The absolute offset into the file to read from. + /// - length: The maximum number of bytes to read as a ``ByteCount``. + /// - Returns: The bytes read from the file. + func readChunk(fromAbsoluteOffset offset: Int64, length: ByteCount) async throws -> ByteBuffer + + /// Returns an asynchronous sequence of chunks read from the file. + /// + /// - Parameters: + /// - range: The absolute offsets into the file to read. + /// - chunkLength: The maximum length of the chunk to read as a ``ByteCount``. + /// - Returns: A sequence of chunks read from the file. + func readChunks(in range: Range, chunkLength: ByteCount) -> FileChunks +} + +// MARK: - Read chunks with default chunk length + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ReadableFileHandleProtocol { + /// Returns an asynchronous sequence of chunks read from the file. + /// + /// - Parameters: + /// - range: A range of offsets in the file to read. + /// - chunkLength: The length of chunks to read, defaults to 128 KiB. + /// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6`` + /// - Returns: An `AsyncSequence` of chunks read from the file. + public func readChunks( + in range: ClosedRange, + chunkLength: ByteCount = .kibibytes(128) + ) -> FileChunks { + self.readChunks(in: Range(range), chunkLength: chunkLength) + } + + /// Returns an asynchronous sequence of chunks read from the file. + /// + /// - Parameters: + /// - range: A range of offsets in the file to read. + /// - chunkLength: The length of chunks to read, defaults to 128 KiB. + /// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6`` + /// - Returns: An `AsyncSequence` of chunks read from the file. + public func readChunks( + in range: Range, + chunkLength: ByteCount = .kibibytes(128) + ) -> FileChunks { + self.readChunks(in: range, chunkLength: chunkLength) + } + + /// Returns an asynchronous sequence of chunks read from the file. + /// + /// - Parameters: + /// - range: A range of offsets in the file to read. + /// - chunkLength: The length of chunks to read, defaults to 128 KiB. + /// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``. + /// - Returns: An `AsyncSequence` of chunks read from the file. + public func readChunks( + in range: PartialRangeFrom, + chunkLength: ByteCount = .kibibytes(128) + ) -> FileChunks { + let newRange = range.lowerBound.., + chunkLength: ByteCount = .kibibytes(128) + ) -> FileChunks { + let newRange = 0...range.upperBound + return self.readChunks(in: newRange, chunkLength: chunkLength) + } + + /// Returns an asynchronous sequence of chunks read from the file. + /// + /// - Parameters: + /// - range: A range of offsets in the file to read. + /// - chunkLength: The length of chunks to read, defaults to 128 KiB. + /// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``. + /// - Returns: An `AsyncSequence` of chunks read from the file. + public func readChunks( + in range: PartialRangeUpTo, + chunkLength: ByteCount = .kibibytes(128) + ) -> FileChunks { + let newRange = 0.. FileChunks { + self.readChunks(in: 0.. FileChunks { + self.readChunks(in: ..., chunkLength: chunkLength) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension ReadableFileHandleProtocol { + /// Returns the contents of a file by loading it into memory. + /// + /// - Important: This method checks whether the file is seekable or not (i.e., whether it's a socket, + /// pipe or FIFO), and will throw ``FileSystemError/Code-swift.struct/unsupported`` if + /// an offset other than zero is passed. + /// + /// - Parameters: + /// - offset: The absolute offset into the file to read from. Defaults to zero. + /// - maximumSizeAllowed: The maximum size of file to read, as a ``ByteCount``. + /// - Returns: The bytes read from the file. + /// - Throws: ``FileSystemError`` with code ``FileSystemError/Code-swift.struct/resourceExhausted`` + /// if `maximumSizeAllowed` is more than can be written to `ByteBuffer`. Or if there are more bytes to read than + /// `maximumBytesAllowed`. + public func readToEnd( + fromAbsoluteOffset offset: Int64 = 0, + maximumSizeAllowed: ByteCount + ) async throws -> ByteBuffer { + let maximumSizeAllowed = maximumSizeAllowed == .unlimited ? .byteBufferCapacity : maximumSizeAllowed + let info = try await self.info() + let fileSize = Int64(info.size) + let readSize = max(Int(fileSize - offset), 0) + + if maximumSizeAllowed > .byteBufferCapacity { + throw FileSystemError( + code: .resourceExhausted, + message: """ + The maximum size allowed (\(maximumSizeAllowed)) is more than the maximum \ + amount of bytes that can be written to ByteBuffer \ + (\(ByteCount.byteBufferCapacity)). You can read the file in smaller chunks by \ + calling readChunks(). + """, + cause: nil, + location: .here() + ) + } + + if readSize > maximumSizeAllowed.bytes { + throw FileSystemError( + code: .resourceExhausted, + message: """ + There are more bytes to read (\(readSize)) than the maximum size allowed \ + (\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \ + allowed. + """, + cause: nil, + location: .here() + ) + } + + let isSeekable = !(info.type == .fifo || info.type == .socket) + if isSeekable { + // Limit the size of single shot reads. If the system is busy then avoid slowing down other + // work by blocking an I/O executor thread while doing a large read. The limit is somewhat + // arbitrary. + let singleShotReadLimit = 64 * 1024 * 1024 + + // If the file size isn't 0 but the read size is, then it means that + // we are intending to read an empty fragment: we can just return + // fast and skip any reads. + // If the file size is 0, we can't conclude anything about the size + // of the file, as `stat` will return 0 for unbounded files. + // If this happens, just read in chunks to make sure the whole file + // is read (up to `maximumSizeAllowed` bytes). + var forceChunkedRead = false + if fileSize > 0 { + if readSize == 0 { + return ByteBuffer() + } + } else { + forceChunkedRead = true + } + + if !forceChunkedRead, readSize <= singleShotReadLimit { + return try await self.readChunk( + fromAbsoluteOffset: offset, + length: .bytes(Int64(readSize)) + ) + } else { + var accumulator = ByteBuffer() + accumulator.reserveCapacity(readSize) + + for try await chunk in self.readChunks(in: offset..., chunkLength: .mebibytes(8)) { + accumulator.writeImmutableBuffer(chunk) + if accumulator.readableBytes > maximumSizeAllowed.bytes { + throw FileSystemError( + code: .resourceExhausted, + message: """ + There are more bytes to read than the maximum size allowed \ + (\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \ + allowed. + """, + cause: nil, + location: .here() + ) + } + } + + return accumulator + } + } else { + guard offset == 0 else { + throw FileSystemError( + code: .unsupported, + message: "File is unseekable.", + cause: nil, + location: .here() + ) + } + var accumulator = ByteBuffer() + accumulator.reserveCapacity(readSize) + + for try await chunk in self.readChunks(in: ..., chunkLength: .mebibytes(8)) { + accumulator.writeImmutableBuffer(chunk) + if accumulator.readableBytes > maximumSizeAllowed.bytes { + throw FileSystemError( + code: .resourceExhausted, + message: """ + There are more bytes to read than the maximum size allowed \ + (\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \ + allowed. + """, + cause: nil, + location: .here() + ) + } + } + + return accumulator + } + } +} + +// MARK: - Writable + +/// A file handle suitable for writing. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public protocol WritableFileHandleProtocol: FileHandleProtocol { + /// Write the given bytes to the open file. + /// + /// - Important: This method checks whether the file is seekable or not (i.e., whether it's a socket, + /// pipe or FIFO), and will throw ``FileSystemError/Code-swift.struct/unsupported`` + /// if an offset other than zero is passed. + /// + /// - Parameters: + /// - bytes: The bytes to write. + /// - offset: The absolute offset into the file to write the bytes. + /// - Returns: The number of bytes written. + /// - Throws: ``FileSystemError/Code-swift.struct/unsupported`` if file is + /// unseekable and `offset` is not 0. + @discardableResult + func write( + contentsOf bytes: some (Sequence & Sendable), + toAbsoluteOffset offset: Int64 + ) async throws -> Int64 + + /// Resizes a file to the given size. + /// + /// - Parameters: + /// - size: The number of bytes to resize the file to as a ``ByteCount``. + func resize( + to size: ByteCount + ) async throws + + /// Closes the file handle. + /// + /// It is important to close a handle once it has been finished with to avoid leaking + /// resources. Prefer using APIs which provided scoped access to a file handle which + /// manage lifecycles on your behalf. Note that if the handle has been detached via + /// ``FileHandleProtocol/detachUnsafeFileDescriptor()`` then it is not necessary to close + /// the handle. + /// + /// After closing the handle calls to other functions will throw an appropriate error. + /// + /// - Parameters: + /// - makeChangesVisible: Whether the changes made to the file will be made visibile. This + /// parameter is ignored unless ``OpenOptions/NewFile/transactionalCreation`` was + /// set to `true`. When `makeChangesVisible` is `true`, the file will be created on the + /// filesystem with the expected name, otherwise no file will be created or the original + /// file won't be modified (if one existed). + func close(makeChangesVisible: Bool) async throws +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension WritableFileHandleProtocol { + /// Write the readable bytes of the `ByteBuffer` to the open file. + /// + /// - Important: This method checks whether the file is seekable or not (i.e., whether it's a socket, + /// pipe or FIFO), and will throw ``FileSystemError/Code-swift.struct/unsupported`` + /// if an offset other than zero is passed. + /// + /// - Parameters: + /// - buffer: The bytes to write. + /// - offset: The absolute offset into the file to write the bytes. + /// - Returns: The number of bytes written. + /// - Throws: ``FileSystemError/Code-swift.struct/unsupported`` if file is + /// unseekable and `offset` is not 0. + @discardableResult + public func write( + contentsOf buffer: ByteBuffer, + toAbsoluteOffset offset: Int64 + ) async throws -> Int64 { + try await self.write(contentsOf: buffer.readableBytesView, toAbsoluteOffset: offset) + } +} + +// MARK: - File times modifiers + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileHandleProtocol { + /// Sets the file's last access time to the given time. + /// + /// - Parameter time: The time to which the file's last access time should be set. + /// + /// - Throws: If there's an error updating the time. If this happens, the original value won't be modified. + public func setLastAccessTime(to time: FileInfo.Timespec) async throws { + try await self.setTimes(lastAccess: time, lastDataModification: nil) + } + + /// Sets the file's last data modification time to the given time. + /// + /// - Parameter time: The time to which the file's last data modification time should be set. + /// + /// - Throws: If there's an error updating the time. If this happens, the original value won't be modified. + public func setLastDataModificationTime(to time: FileInfo.Timespec) async throws { + try await self.setTimes(lastAccess: nil, lastDataModification: time) + } + + /// Sets the file's last access and last data modification times to the current time. + /// + /// - Throws: If there's an error updating the times. If this happens, the original values won't be modified. + public func touch() async throws { + try await self.setTimes(lastAccess: nil, lastDataModification: nil) + } +} + +/// A file handle which is suitable for reading and writing. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public typealias ReadableAndWritableFileHandleProtocol = ReadableFileHandleProtocol + & WritableFileHandleProtocol + +// MARK: - Directory + +/// A handle suitable for directories. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public protocol DirectoryFileHandleProtocol: FileHandleProtocol { + /// The type of ``ReadableFileHandleProtocol`` to return when opening files for reading. + associatedtype ReadFileHandle: ReadableFileHandleProtocol + + /// The type of ``WritableFileHandleProtocol`` to return when opening files for writing. + associatedtype WriteFileHandle: WritableFileHandleProtocol + + /// The type of ``ReadableAndWritableFileHandleProtocol`` to return when opening files for reading and writing. + associatedtype ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol + + /// Returns an `AsyncSequence` of entries in the open directory. + /// + /// You can recurse into and list the contents of any subdirectories by setting `recursive` + /// to `true`. The current (".") and parent ("..") directory entries are not included. The order + /// of entries is arbitrary and shouldn't be relied upon. + /// + /// - Parameter recursive: Whether subdirectories should be recursively visited. + /// - Returns: An `AsyncSequence` of directory entries. + func listContents(recursive: Bool) -> DirectoryEntries + + /// Opens the file at `path` for reading and returns a handle to it. + /// + /// If `path` is a relative path then it is opened relative to the handle. The file being + /// opened must already exist otherwise this function will throw a ``FileSystemError`` with + /// code ``FileSystemError/Code-swift.struct/notFound``. + /// + /// - Parameters: + /// - path: The path of the directory to open relative to the open file. + /// - options: How the file should be opened. + /// - Returns: A read-only handle to the opened file. + func openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) async throws -> ReadFileHandle + + /// Opens the file at `path` for writing and returns a handle to it. + /// + /// If `path` is a relative path then it is opened relative to the handle. + /// + /// - Parameters: + /// - path: The path of the file to open relative to the open file. + /// - options: How the file should be opened. + /// - Returns: A write-only handle to the opened file. + func openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> WriteFileHandle + + /// Opens the file at `path` for reading and writing and returns a handle to it. + /// + /// If `path` is a relative path then it is opened relative to the handle. + /// + /// - Parameters: + /// - path: The path of the file to open relative to the open file. + /// - options: How the file should be opened. + func openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> ReadWriteFileHandle + + /// Opens the directory at `path` and returns a handle to it. + /// + /// The directory being opened must already exist otherwise this function will throw an error. + /// If `path` is a relative path then it is opened relative to the handle. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - options: How the file should be opened. + /// - Returns: A handle to the opened directory. + func openDirectory( + atPath path: FilePath, + options: OpenOptions.Directory + ) async throws -> Self +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension DirectoryFileHandleProtocol { + /// Returns an `AsyncSequence` of entries in the open directory. + /// + /// The current (".") and parent ("..") directory entries are not included. The order of entries + /// is arbitrary and should not be relied upon. + public func listContents() -> DirectoryEntries { + self.listContents(recursive: false) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension DirectoryFileHandleProtocol { + /// Opens the file at the given path and provides scoped read access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the call returns. Files may also be opened in write-only and read-write + /// mode by calling ``DirectoryFileHandleProtocol/withFileHandle(forWritingAt:options:execute:)-36f0k`` + /// and ``DirectoryFileHandleProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-5j0f3``, + /// respectively. + /// + /// If `path` is a relative path then it is opened relative to the handle. The file being + /// opened must already exist otherwise this function will throw a ``FileSystemError`` with + /// code ``FileSystemError/Code-swift.struct/notFound``. + /// + /// - Parameters: + /// - path: The path of the file to open for reading. + /// - options: How the file should be opened. + /// - body: A closure which provides read-only access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forReadingAt path: FilePath, + options: OpenOptions.Read = OpenOptions.Read(), + execute body: (_ read: ReadFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forReadingAt: path, options: options) + + return try await withUncancellableTearDown { + try await body(handle) + } tearDown: { _ in + try await handle.close() + } + } + + /// Opens the file at the given path and provides scoped write access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the call returns. Files may also be opened in read-only or read-write + /// mode by calling ``DirectoryFileHandleProtocol/withFileHandle(forReadingAt:options:execute:)-52xsn`` and + /// ``DirectoryFileHandleProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-5j0f3``, + /// respectively. + /// + /// If `path` is a relative path then it is opened relative to the handle. + /// + /// - Parameters: + /// - path: The path of the file to open for reading. + /// - options: How the file should be opened. + /// - body: A closure which provides write-only access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forWritingAt path: FilePath, + options: OpenOptions.Write = .newFile(replaceExisting: false), + execute body: (_ write: WriteFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forWritingAt: path, options: options) + + return try await withUncancellableTearDown { + try await body(handle) + } tearDown: { result in + switch result { + case .success: + try await handle.close(makeChangesVisible: true) + case .failure: + try await handle.close(makeChangesVisible: false) + } + } + } + + /// Opens the file at the given path and provides scoped read-write access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the call returns. Files may also be opened in read-only or write-only + /// mode by calling ``DirectoryFileHandleProtocol/withFileHandle(forReadingAt:options:execute:)-52xsn`` and + /// ``DirectoryFileHandleProtocol/withFileHandle(forWritingAt:options:execute:)-36f0k``, respectively. + /// + /// If `path` is a relative path then it is opened relative to the handle. + /// + /// - Parameters: + /// - path: The path of the file to open for reading and writing. + /// - options: How the file should be opened. + /// - body: A closure which provides access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write = .newFile(replaceExisting: false), + execute body: (_ readWrite: ReadWriteFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forReadingAndWritingAt: path, options: options) + + return try await withUncancellableTearDown { + try await body(handle) + } tearDown: { result in + switch result { + case .success: + try await handle.close(makeChangesVisible: true) + case .failure: + try await handle.close(makeChangesVisible: false) + } + } + } + + /// Opens the directory at the given path and provides scoped access to it. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - options: How the directory should be opened. + /// - body: A closure which provides access to the directory. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withDirectoryHandle( + atPath path: FilePath, + options: OpenOptions.Directory = OpenOptions.Directory(), + execute body: (_ directory: Self) async throws -> Result + ) async throws -> Result { + let handle = try await self.openDirectory(atPath: path, options: options) + + return try await withUncancellableTearDown { + try await body(handle) + } tearDown: { _ in + try await handle.close() + } + } +} diff --git a/Sources/_NIOFileSystem/FileInfo.swift b/Sources/_NIOFileSystem/FileInfo.swift new file mode 100644 index 000000000..e5769a8e5 --- /dev/null +++ b/Sources/_NIOFileSystem/FileInfo.swift @@ -0,0 +1,278 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Android) +@preconcurrency import Android +import CNIOLinux +#endif + +/// Information about a file system object. +/// +/// The information available for a file depends on the platform, ``FileInfo`` provides +/// convenient access to a common subset of properties. Using these properties ensures that +/// code is portable. If available, the platform specific information is made available via +/// ``FileInfo/platformSpecificStatus``. However users should take care to ensure their +/// code uses the correct platform checks when using it to ensure their code is portable. +public struct FileInfo: Hashable, Sendable { + /// Wraps `CInterop.Stat` providing `Hashable` and `Equatable` conformance. + private var _platformSpecificStatus: Stat? + + /// The information about the file returned from the filesystem, if available. + /// + /// This value is platform specific: you should be careful when using + /// it as some of its fields vary across platforms. In most cases prefer + /// using other properties on this type instead. + /// + /// See also: the manual pages for 'stat' (`man 2 stat`) + public var platformSpecificStatus: CInterop.Stat? { + get { self._platformSpecificStatus?.stat } + set { self._platformSpecificStatus = newValue.map { Stat($0) } } + } + + /// The type of the file. + public var type: FileType + + /// Permissions currently set on the file. + public var permissions: FilePermissions + + /// The size of the file in bytes. + public var size: Int64 + + /// User ID of the file. + public var userID: UserID + + /// Group ID of the file. + public var groupID: GroupID + + /// The last time the file was accessed. + public var lastAccessTime: Timespec + + /// The last time the files data was last changed. + public var lastDataModificationTime: Timespec + + /// The last time the status of the file was changed. + public var lastStatusChangeTime: Timespec + + /// Creates a ``FileInfo`` by deriving values from a platform-specific value. + public init(platformSpecificStatus: CInterop.Stat) { + self._platformSpecificStatus = Stat(platformSpecificStatus) + self.type = FileType(platformSpecificMode: CInterop.Mode(platformSpecificStatus.st_mode)) + self.permissions = FilePermissions(masking: CInterop.Mode(platformSpecificStatus.st_mode)) + self.size = Int64(platformSpecificStatus.st_size) + self.userID = UserID(rawValue: platformSpecificStatus.st_uid) + self.groupID = GroupID(rawValue: platformSpecificStatus.st_gid) + + #if canImport(Darwin) + self.lastAccessTime = Timespec(platformSpecificStatus.st_atimespec) + self.lastDataModificationTime = Timespec(platformSpecificStatus.st_mtimespec) + self.lastStatusChangeTime = Timespec(platformSpecificStatus.st_ctimespec) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + self.lastAccessTime = Timespec(platformSpecificStatus.st_atim) + self.lastDataModificationTime = Timespec(platformSpecificStatus.st_mtim) + self.lastStatusChangeTime = Timespec(platformSpecificStatus.st_ctim) + #endif + } + + /// Creates a ``FileInfo`` from the provided values. + /// + /// If you have a platform specific status value prefer calling + /// ``init(platformSpecificStatus:)``. + public init( + type: FileType, + permissions: FilePermissions, + size: Int64, + userID: UserID, + groupID: GroupID, + lastAccessTime: Timespec, + lastDataModificationTime: Timespec, + lastStatusChangeTime: Timespec + ) { + self._platformSpecificStatus = nil + self.type = type + self.permissions = permissions + self.size = size + self.userID = userID + self.groupID = groupID + self.lastAccessTime = lastAccessTime + self.lastDataModificationTime = lastDataModificationTime + self.lastStatusChangeTime = lastStatusChangeTime + } +} + +extension FileInfo { + /// The numeric ID of a user. + public struct UserID: Hashable, Sendable, CustomStringConvertible { + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + public var description: String { + String(describing: self.rawValue) + } + } + + /// The numeric ID of a group. + public struct GroupID: Hashable, Sendable, CustomStringConvertible { + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + public var description: String { + String(describing: self.rawValue) + } + } + + /// A time interval consisting of whole seconds and nanoseconds. + public struct Timespec: Hashable, Sendable { + #if canImport(Darwin) + private static let utimeOmit = Int(UTIME_OMIT) + private static let utimeNow = Int(UTIME_NOW) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + private static let utimeOmit = Int(CNIOLinux_UTIME_OMIT) + private static let utimeNow = Int(CNIOLinux_UTIME_NOW) + #endif + + /// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_OMIT`. + /// In syscalls such as `futimens`, this means the time component set to this value will be ignored. + public static let omit = Self( + seconds: 0, + nanoseconds: Self.utimeOmit + ) + + /// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_NOW`. + /// In syscalls such as `futimens`, this means the time component set to this value will be + /// be set to the current time or the largest value supported by the platform, whichever is smaller. + public static let now = Self( + seconds: 0, + nanoseconds: Self.utimeNow + ) + + /// The number of seconds. + public var seconds: Int + + /// The number of nanoseconds. + public var nanoseconds: Int + + init(_ timespec: timespec) { + self.seconds = timespec.tv_sec + self.nanoseconds = timespec.tv_nsec + } + + public init(seconds: Int, nanoseconds: Int) { + self.seconds = seconds + self.nanoseconds = nanoseconds + } + } +} + +/// A wrapper providing `Hashable` and `Equatable` conformance for `CInterop.Stat`. +private struct Stat: Hashable { + var stat: CInterop.Stat + + init(_ stat: CInterop.Stat) { + self.stat = stat + } + + func hash(into hasher: inout Hasher) { + let stat = self.stat + // Different platforms have different values; these are + // common between Darwin and Glibc. + hasher.combine(stat.st_dev) + hasher.combine(stat.st_mode) + hasher.combine(stat.st_nlink) + hasher.combine(stat.st_ino) + hasher.combine(stat.st_uid) + hasher.combine(stat.st_gid) + hasher.combine(stat.st_rdev) + hasher.combine(stat.st_size) + hasher.combine(stat.st_blocks) + hasher.combine(stat.st_blksize) + + #if canImport(Darwin) + hasher.combine(FileInfo.Timespec(stat.st_atimespec)) + hasher.combine(FileInfo.Timespec(stat.st_mtimespec)) + hasher.combine(FileInfo.Timespec(stat.st_ctimespec)) + hasher.combine(FileInfo.Timespec(stat.st_birthtimespec)) + hasher.combine(stat.st_flags) + hasher.combine(stat.st_gen) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + hasher.combine(FileInfo.Timespec(stat.st_atim)) + hasher.combine(FileInfo.Timespec(stat.st_mtim)) + hasher.combine(FileInfo.Timespec(stat.st_ctim)) + #endif + + } + + static func == (lhs: Stat, rhs: Stat) -> Bool { + let lStat = lhs.stat + let rStat = rhs.stat + + // Different platforms have different values; these are + // common between Darwin and Glibc. + var isEqual = lStat.st_dev == rStat.st_dev + isEqual = isEqual && lStat.st_mode == rStat.st_mode + isEqual = isEqual && lStat.st_nlink == rStat.st_nlink + isEqual = isEqual && lStat.st_ino == rStat.st_ino + isEqual = isEqual && lStat.st_uid == rStat.st_uid + isEqual = isEqual && lStat.st_gid == rStat.st_gid + isEqual = isEqual && lStat.st_rdev == rStat.st_rdev + isEqual = isEqual && lStat.st_size == rStat.st_size + isEqual = isEqual && lStat.st_blocks == rStat.st_blocks + isEqual = isEqual && lStat.st_blksize == rStat.st_blksize + + #if canImport(Darwin) + isEqual = + isEqual + && FileInfo.Timespec(lStat.st_atimespec) == FileInfo.Timespec(rStat.st_atimespec) + isEqual = + isEqual + && FileInfo.Timespec(lStat.st_mtimespec) == FileInfo.Timespec(rStat.st_mtimespec) + isEqual = + isEqual + && FileInfo.Timespec(lStat.st_ctimespec) == FileInfo.Timespec(rStat.st_ctimespec) + isEqual = + isEqual + && FileInfo.Timespec(lStat.st_birthtimespec) + == FileInfo.Timespec(rStat.st_birthtimespec) + isEqual = isEqual && lStat.st_flags == rStat.st_flags + isEqual = isEqual && lStat.st_gen == rStat.st_gen + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + isEqual = isEqual && FileInfo.Timespec(lStat.st_atim) == FileInfo.Timespec(rStat.st_atim) + isEqual = isEqual && FileInfo.Timespec(lStat.st_mtim) == FileInfo.Timespec(rStat.st_mtim) + isEqual = isEqual && FileInfo.Timespec(lStat.st_ctim) == FileInfo.Timespec(rStat.st_ctim) + #endif + + return isEqual + } +} + +extension FilePermissions { + internal init(masking rawValue: CInterop.Mode) { + self = .init(rawValue: rawValue & ~S_IFMT) + } +} diff --git a/Sources/_NIOFileSystem/FileSystem.swift b/Sources/_NIOFileSystem/FileSystem.swift new file mode 100644 index 000000000..71f4839c9 --- /dev/null +++ b/Sources/_NIOFileSystem/FileSystem.swift @@ -0,0 +1,1573 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import Atomics +import NIOCore +import NIOPosix +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +#elseif canImport(Musl) +@preconcurrency import Musl +#elseif canImport(Bionic) +@preconcurrency import Bionic +#endif + +/// A file system which interacts with the local system. The file system uses a thread pool to +/// perform system calls. +/// +/// ### Creating a `FileSystem` +/// +/// You should prefer using the `shared` instance of the file system. The `shared` instance uses two +/// threads unless the `SWIFT_FILE_SYSTEM_THREAD_COUNT` environment variable is set. +/// +/// If you require more granular control you can create a ``FileSystem`` with the required number of +/// threads by calling ``withFileSystem(numberOfThreads:_:)`` or by using ``init(threadPool:)``. +/// +/// ### Errors +/// +/// Errors thrown by ``FileSystem`` will be of type: +/// - ``FileSystemError`` if it wasn't possible to complete the operation, or +/// - `CancellationError` if the `Task` was cancelled. +/// +/// ``FileSystemError`` implements `CustomStringConvertible`. The output from the `description` +/// contains basic information including the error code, message and error. You can get +/// more information about the error by calling ``FileSystemError/detailedDescription()`` which +/// returns a structured multi-line string containing information about the error. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct FileSystem: Sendable, FileSystemProtocol { + /// Returns a shared global instance of the ``FileSystem``. + /// + /// The file system executes blocking work in a thread pool which defaults to having two + /// threads. This can be modified by `blockingPoolThreadCountSuggestion` or by setting the + /// `NIO_SINGLETON_BLOCKING_POOL_THREAD_COUNT` environment variable. + public static var shared: FileSystem { globalFileSystem } + + private let threadPool: NIOThreadPool + private let ownsThreadPool: Bool + + fileprivate func shutdown() async { + if self.ownsThreadPool { + try? await self.threadPool.shutdownGracefully() + } + } + + /// Creates a new ``FileSystem`` using the provided thread pool. + /// + /// - Parameter threadPool: A started thread pool to execute blocking system calls on. The + /// ``FileSystem`` doesn't take ownership of the thread pool and you remain responsible for + /// shutting it down when necessary. + public init(threadPool: NIOThreadPool) { + self.init(threadPool: threadPool, ownsThreadPool: false) + } + + fileprivate init(threadPool: NIOThreadPool, ownsThreadPool: Bool) { + self.threadPool = threadPool + self.ownsThreadPool = ownsThreadPool + } + + fileprivate init(numberOfThreads: Int) async { + let threadPool = NIOThreadPool(numberOfThreads: numberOfThreads) + threadPool.start() + // Wait for the thread pool to start. + try? await threadPool.runIfActive {} + self.init(threadPool: threadPool, ownsThreadPool: true) + } + + /// Open the file at `path` for reading. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if `path` doesn't exist. + /// + /// #### Implementation details + /// + /// Uses the `open(2)` system call. + /// + /// - Parameters: + /// - path: The path of the file to open. + /// - options: How the file should be opened. + /// - Returns: A readable handle to the opened file. + public func openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) async throws -> ReadFileHandle { + let handle = try await self.threadPool.runIfActive { + let handle = try self._openFile(forReadingAt: path, options: options).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + /// Open the file at `path` for writing. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/permissionDenied`` if you have insufficient + /// permissions to create the file. + /// - ``FileSystemError/Code-swift.struct/notFound`` if `path` doesn't exist and `options` + /// weren't set to create a file. + /// + /// #### Implementation details + /// + /// Uses the `open(2)` system call. + /// + /// - Parameters: + /// - path: The path of the file to open. + /// - options: How the file should be opened. + /// - Returns: A writable handle to the opened file. + public func openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> WriteFileHandle { + let handle = try await self.threadPool.runIfActive { + let handle = try self._openFile(forWritingAt: path, options: options).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + /// Open the file at `path` for reading and writing. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/permissionDenied`` if you have insufficient + /// permissions to create the file. + /// - ``FileSystemError/Code-swift.struct/notFound`` if `path` doesn't exist and `options` + /// weren't set to create a file. + /// + /// #### Implementation details + /// + /// Uses the `open(2)` system call. + /// + /// - Parameters: + /// - path: The path of the file to open. + /// - options: How the file should be opened. + /// - Returns: A readable and writable handle to the opened file. + public func openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> ReadWriteFileHandle { + let handle = try await self.threadPool.runIfActive { + let handle = try self._openFile(forReadingAndWritingAt: path, options: options).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + /// Open the directory at `path`. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if `path` doesn't exist. + /// + /// #### Implementation details + /// + /// Uses the `open(2)` system call. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - options: How the directory should be opened. + /// - Returns: A handle to the opened directory. + public func openDirectory( + atPath path: FilePath, + options: OpenOptions.Directory + ) async throws -> DirectoryFileHandle { + let handle = try await self.threadPool.runIfActive { + let handle = try self._openDirectory(at: path, options: options).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + /// Create a directory at the given path. + /// + /// If a directory (or file) already exists at `path` a ``FileSystemError`` with code + /// ``FileSystemError/Code-swift.struct/fileAlreadyExists`` is thrown. + /// + /// If the parent directory of the directory to created does not exist a ``FileSystemError`` + /// with ``FileSystemError/Code-swift.struct/invalidArgument`` is thrown. Missing directories + /// can be created by passing `true` to `createIntermediateDirectories`. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if a file or directory already + /// exists . + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if a component in the `path` prefix + /// does not exist and `createIntermediateDirectories` is `false`. + /// + /// #### Implementation details + /// + /// Uses the `mkdir(2)` system call. + /// + /// - Parameters: + /// - path: The directory to create. + /// - createIntermediateDirectories: Whether intermediate directories should be created. + /// - permissions: The permissions to set on the new directory; default permissions will be + /// used if not specified. + public func createDirectory( + at path: FilePath, + withIntermediateDirectories createIntermediateDirectories: Bool, + permissions: FilePermissions? + ) async throws { + try await self.threadPool.runIfActive { + try self._createDirectory( + at: path, + withIntermediateDirectories: createIntermediateDirectories, + permissions: permissions ?? .defaultsForDirectory + ).get() + } + } + + /// Create a temporary directory at the given path, using a template. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the template doesn't end in at + /// least 3 'X's. + /// - ``FileSystemError/Code-swift.struct/permissionDenied`` if the user doesn't have permission + /// to create a directory at the path specified in the template. + /// + /// #### Implementation details + /// + /// Uses the `mkdir(2)` system call. + /// + /// - Parameters: + /// - template: The template for the path of the temporary directory. + /// - Returns: + /// - The path to the new temporary directory. + public func createTemporaryDirectory( + template: FilePath + ) async throws -> FilePath { + try await self.threadPool.runIfActive { + try self._createTemporaryDirectory(template: template).get() + } + } + + /// Returns information about the file at `path` if it exists; nil otherwise. + /// + /// #### Implementation details + /// + /// Uses `lstat(2)` if `infoAboutSymbolicLink` is `true`, `stat(2)` otherwise. + /// + /// - Parameters: + /// - path: The path of the file. + /// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true`, + /// then information about the link will be returned. Otherwise, information about the + /// destination of the symbolic link is returned. + /// - Returns: Information about the file at the given path or `nil` if no file exists. + public func info( + forFileAt path: FilePath, + infoAboutSymbolicLink: Bool + ) async throws -> FileInfo? { + try await self.threadPool.runIfActive { + try self._info(forFileAt: path, infoAboutSymbolicLink: infoAboutSymbolicLink).get() + } + } + + // MARK: - File copying, removal, and moving + + /// See ``FileSystemProtocol/copyItem(at:to:shouldProceedAfterError:shouldCopyFile:)`` + /// + /// The item to be copied must be a: + /// - regular file, + /// - symbolic link, or + /// - directory. + /// + /// `shouldCopyItem` can be used to ignore objects not part of this set. + /// + /// #### Errors + /// + /// In addition to the already documented errors these may be thrown + /// - ``FileSystemError/Code-swift.struct/unsupported`` if an item to be copied is not a regular + /// file, symbolic link or directory. + /// + /// #### Implementation details + /// + /// This function is platform dependent. On Darwin the `copyfile(2)` system call is used and + /// items are cloned where possible. On Linux the `sendfile(2)` system call is used. + public func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy, + shouldProceedAfterError: @escaping @Sendable ( + _ source: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + guard let info = try await self.info(forFileAt: sourcePath, infoAboutSymbolicLink: true) + else { + throw FileSystemError( + code: .notFound, + message: "Unable to copy '\(sourcePath)', it does not exist.", + cause: nil, + location: .here() + ) + } + + // By doing this before looking at the type, we allow callers to decide whether + // unanticipated kinds of entries can be safely ignored without needing changes upstream. + if await shouldCopyItem(.init(path: sourcePath, type: info.type)!, destinationPath) { + switch info.type { + case .regular: + try await self.copyRegularFile(from: sourcePath, to: destinationPath) + + case .symlink: + try await self.copySymbolicLink(from: sourcePath, to: destinationPath) + + case .directory: + try await self.copyDirectory( + from: sourcePath, + to: destinationPath, + strategy: copyStrategy, + shouldProceedAfterError: shouldProceedAfterError + ) { source, destination in + await shouldCopyItem(source, destination) + } + + default: + throw FileSystemError( + code: .unsupported, + message: """ + Can't copy '\(sourcePath)' of type '\(info.type)'; only regular files, \ + symbolic links and directories can be copied. + """, + cause: nil, + location: .here() + ) + } + } + } + + /// See ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` + /// + /// Deletes the file or directory (and its contents) at `path`. + /// + /// Only regular files, symbolic links and directories may be removed. If the file at `path` is + /// a directory then its contents and all of its subdirectories will be removed recursively. + /// Symbolic links are also removed (but their targets are not deleted). If no file exists at + /// `path` this function returns zero. + /// + /// #### Errors + /// + /// Errors codes thrown by this function include: + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the item is not a regular file, + /// symbolic link or directory. This also applies to items within the directory being removed. + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item being removed is a directory + /// which isn't empty and `removeItemRecursively` is false. + /// + /// #### Implementation details + /// + /// Uses the `remove(3)` system call. + /// + /// - Parameters: + /// - path: The path to delete. + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. + /// - removeItemRecursively: Whether or not to remove items recursively. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath, + strategy removalStrategy: RemovalStrategy, + recursively removeItemRecursively: Bool + ) async throws -> Int { + // Try to remove the item: we might just get lucky. + let result = try await self.threadPool.runIfActive { Libc.remove(path) } + + switch result { + case .success: + // Great; we removed an entire item. + return 1 + + case .failure(.noSuchFileOrDirectory): + // Nothing to delete. + return 0 + + case .failure(.directoryNotEmpty): + guard removeItemRecursively else { + throw FileSystemError( + code: .notEmpty, + message: """ + Can't remove directory at path '\(path)', it isn't empty and \ + 'removeItemRecursively' is false. Remove items from the directory first or \ + set 'removeItemRecursively' to true when calling \ + 'removeItem(at:recursively:)'. + """, + cause: nil, + location: .here() + ) + } + + switch removalStrategy.wrapped { + case .sequential: + return try await self.removeItemSequentially(at: path) + case let .parallel(maxDescriptors): + return try await self.removeConcurrently(at: path, maxDescriptors) + } + + case let .failure(errno): + throw FileSystemError.remove(errno: errno, path: path, location: .here()) + } + } + + @discardableResult + private func removeItemSequentially( + at path: FilePath + ) async throws -> Int { + var (subdirectories, filesRemoved) = try await self.withDirectoryHandle( + atPath: path + ) { directory in + var subdirectories = [FilePath]() + var filesRemoved = 0 + + for try await batch in directory.listContents().batched() { + for entry in batch { + switch entry.type { + case .directory: + subdirectories.append(entry.path) + + default: + filesRemoved += try await self.removeOneItem(at: entry.path) + } + } + } + + return (subdirectories, filesRemoved) + } + + for subdirectory in subdirectories { + filesRemoved += try await self.removeItemSequentially(at: subdirectory) + } + + // The directory should be empty now. Remove ourself. + filesRemoved += try await self.removeOneItem(at: path) + + return filesRemoved + + } + + private func removeConcurrently( + at path: FilePath, + _ maxDescriptors: Int + ) async throws -> Int { + let bucket: TokenBucket = .init(tokens: maxDescriptors) + return try await self.discoverAndRemoveItemsInTree(at: path, bucket) + } + + /// Moves the named file or directory to a new location. + /// + /// Only regular files, symbolic links and directories may be moved. If the item to be is a + /// symbolic link then only the link is moved; the target of the link is not moved. + /// + /// If the file is moved within to a different logical partition then the file is copied to the + /// new partition before being removed from old partition. If removing the item fails the copied + /// file will not be removed. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, + /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if an item at `destinationPath` + /// already exists. + /// + /// #### Implementation details + /// + /// Uses the `rename(2)` system call. + /// + /// - Parameters: + /// - sourcePath: The path to the item to move. + /// - destinationPath: The path at which to place the item. + public func moveItem(at sourcePath: FilePath, to destinationPath: FilePath) async throws { + let result = try await self.threadPool.runIfActive { + try self._moveItem(at: sourcePath, to: destinationPath).get() + } + + switch result { + case .moved: + () + case .differentLogicalDevices: + // Fall back to copy and remove. + try await self.copyItem(at: sourcePath, to: destinationPath) + try await self.removeItem(at: sourcePath, strategy: .platformDefault) + } + } + + /// Replaces the item at `destinationPath` with the item at `existingPath`. + /// + /// Only regular files, symbolic links and directories may replace the item at the existing + /// path. The file at the destination path isn't required to exist. If it does exist it does not + /// have to match the type of the file it is being replaced with. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `existingPath` does not + /// exist. + /// + /// #### Implementation details + /// + /// Uses the `rename(2)` system call. + /// + /// - Parameters: + /// - destinationPath: The path of the file or directory to replace. + /// - existingPath: The path of the existing file or directory. + public func replaceItem( + at destinationPath: FilePath, + withItemAt existingPath: FilePath + ) async throws { + do { + try await self.removeItem(at: destinationPath, strategy: .platformDefault) + try await self.moveItem(at: existingPath, to: destinationPath) + try await self.removeItem(at: existingPath, strategy: .platformDefault) + } catch let error as FileSystemError { + throw FileSystemError( + message: "Can't replace '\(destinationPath)' with '\(existingPath)'.", + wrapping: error + ) + } + } + + // MARK: - Symbolic links + + /// Creates a symbolic link between two files. + /// + /// A link is created at `linkPath` which points to `destinationPath`. The destination of a + /// symbolic link can be read with ``destinationOfSymbolicLink(at:)``. + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if a file exists at + /// `destinationPath`. + /// + /// #### Implementation details + /// + /// Uses the `link(2)` system call. + /// + /// - Parameters: + /// - linkPath: The path at which to create the symbolic link. + /// - destinationPath: The path that contains the item that the symbolic link points to.` + public func createSymbolicLink( + at linkPath: FilePath, + withDestination destinationPath: FilePath + ) async throws { + try await self.threadPool.runIfActive { + try self._createSymbolicLink(at: linkPath, withDestination: destinationPath).get() + } + } + + /// Returns the path of the item pointed to by a symbolic link. + /// + /// The destination of the symbolic link is not guaranteed to be a valid path, nor is it + /// guaranteed to be an absolute path. If you need to open a file which is the destination of a + /// symbolic link then the appropriate `open` function: + /// - ``openFile(forReadingAt:)-55z6f`` + /// - ``openFile(forWritingAt:options:)`` + /// - ``openFile(forReadingAndWritingAt:options:)`` + /// - ``openDirectory(atPath:options:)`` + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if `path` does not exist. + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the file at `path` is not a + /// symbolic link. + /// + /// #### Implementation details + /// + /// Uses the `readlink(2)` system call. + /// + /// - Parameter path: The path of a file or directory. + /// - Returns: The path of the file or directory to which the symbolic link points to. + public func destinationOfSymbolicLink( + at path: FilePath + ) async throws -> FilePath { + try await self.threadPool.runIfActive { + try self._destinationOfSymbolicLink(at: path).get() + } + } + + /// Returns the path of the current working directory. + /// + /// #### Implementation details + /// + /// Uses the `getcwd(2)` system call. + /// + /// - Returns: The path to the current working directory. + public var currentWorkingDirectory: FilePath { + get async throws { + let result = try await self.threadPool.runIfActive { + try Libc.getcwd().mapError { errno in + FileSystemError.getcwd(errno: errno, location: .here()) + }.get() + } + return result + } + } + + /// Returns a path to a temporary directory. + /// + /// #### Implementation details + /// + /// On all platforms, this function first attempts to read the `TMPDIR` environment variable and returns that path, omitting trailing slashes. + /// If that fails: + /// - On Darwin this function uses `confstr(3)` and gets the value of `_CS_DARWIN_USER_TEMP_DIR`; + /// the users temporary directory. Typically items are removed after three days if they are not + /// accessed. + /// - On Android this returns "/data/local/tmp". + /// - On other platforms this returns "/tmp". + /// + /// - Returns: The path to a temporary directory. + public var temporaryDirectory: FilePath { + get async throws { + if let tmpdir = getenv("TMPDIR") { + return FilePath(String(cString: tmpdir)) + } + + #if canImport(Darwin) + return try await self.threadPool.runIfActive { + let result = Libc.constr(_CS_DARWIN_USER_TEMP_DIR) + switch result { + case .success(let path): + return FilePath(path) + case .failure(_): + return FilePath("/tmp") + } + } + #elseif os(Android) + return FilePath("/data/local/tmp") + #else + return FilePath("/tmp") + #endif + } + } +} + +// MARK: - Creating FileSystems + +extension NIOSingletons { + /// A suggestion of how many threads the global singleton ``FileSystem`` uses for blocking I/O. + /// + /// The thread count is the system's available core count unless the environment variable + /// `NIO_SINGLETON_FILESYSTEM_THREAD_COUNT` is set or this value was set manually by the user. + /// + /// - Note: This value must be set _before_ any singletons are used and must only be set once. + @available(*, deprecated, renamed: "blockingPoolThreadCountSuggestion") + public static var fileSystemThreadCountSuggestion: Int { + set { Self.blockingPoolThreadCountSuggestion = newValue } + get { Self.blockingPoolThreadCountSuggestion } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private let globalFileSystem: FileSystem = { + guard NIOSingletons.singletonsEnabledSuggestion else { + fatalError( + """ + Cannot create global singleton FileSystem thread pool because the global singletons \ + have been disabled by setting `NIOSingletons.singletonsEnabledSuggestion = false` + """ + ) + } + return FileSystem(threadPool: NIOSingletons.posixBlockingThreadPool, ownsThreadPool: false) +}() + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension NIOSingletons { + /// Returns a shared global instance of the ``FileSystem``. + /// + /// The file system executes blocking work in a thread pool. See + /// `blockingPoolThreadCountSuggestion` for the default behaviour and ways to control it. + public static var fileSystem: FileSystem { globalFileSystem } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystemProtocol where Self == FileSystem { + /// A global shared instance of ``FileSystem``. + public static var shared: FileSystem { + FileSystem.shared + } +} + +/// Provides temporary scoped access to a ``FileSystem`` with the given number of threads. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public func withFileSystem( + numberOfThreads: Int, + _ body: (FileSystem) async throws -> Result +) async throws -> Result { + let fileSystem = await FileSystem(numberOfThreads: numberOfThreads) + return try await withUncancellableTearDown { + try await body(fileSystem) + } tearDown: { _ in + await fileSystem.shutdown() + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystem { + /// Opens `path` for reading and returns ``ReadFileHandle`` or ``FileSystemError``. + private func _openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) -> Result { + SystemFileHandle.syncOpen( + atPath: path, + mode: .readOnly, + options: options.descriptorOptions, + permissions: nil, + transactionalIfPossible: false, + threadPool: self.threadPool + ).map { + ReadFileHandle(wrapping: $0) + } + } + + /// Opens `path` for writing and returns ``WriteFileHandle`` or ``FileSystemError``. + private func _openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) -> Result { + SystemFileHandle.syncOpen( + atPath: path, + mode: .writeOnly, + options: options.descriptorOptions, + permissions: options.permissionsForRegularFile, + transactionalIfPossible: options.newFile?.transactionalCreation ?? false, + threadPool: self.threadPool + ).map { + WriteFileHandle(wrapping: $0) + } + } + + /// Opens `path` for reading and writing and returns ``ReadWriteFileHandle`` or + /// ``FileSystemError``. + private func _openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) -> Result { + SystemFileHandle.syncOpen( + atPath: path, + mode: .readWrite, + options: options.descriptorOptions, + permissions: options.permissionsForRegularFile, + transactionalIfPossible: options.newFile?.transactionalCreation ?? false, + threadPool: self.threadPool + ).map { + ReadWriteFileHandle(wrapping: $0) + } + } + + /// Opens the directory at `path` and returns ``DirectoryFileHandle`` or ``FileSystemError``. + private func _openDirectory( + at path: FilePath, + options: OpenOptions.Directory + ) -> Result { + SystemFileHandle.syncOpen( + atPath: path, + mode: .readOnly, + options: options.descriptorOptions, + permissions: nil, + transactionalIfPossible: false, + threadPool: self.threadPool + ).map { + DirectoryFileHandle(wrapping: $0) + } + } + + /// Creates a directory at `fullPath`, potentially creating other directories along the way. + private func _createDirectory( + at fullPath: FilePath, + withIntermediateDirectories createIntermediateDirectories: Bool, + permissions: FilePermissions + ) -> Result { + // We assume that we will be creating intermediate directories: + // - Try creating the directory. If it fails with ENOENT (no such file or directory), then + // drop the last component and append it to a buffer. + // - Repeat until the path is empty. This means we cannot create the directory or we + // succeed, in which case we can build up our original path and create directories one at + // a time. + var droppedComponents: [FilePath.Component] = [] + var path = fullPath + + // Normalize the path to remove any superflous '..'. + path.lexicallyNormalize() + + if path.isEmpty { + let error = FileSystemError( + code: .invalidArgument, + message: "Path of directory to create must not be empty.", + cause: nil, + location: .here() + ) + return .failure(error) + } + + loop: while true { + switch Syscall.mkdir(at: path, permissions: permissions) { + case .success: + break loop + + case let .failure(errno): + guard createIntermediateDirectories, errno == .noSuchFileOrDirectory else { + return .failure(.mkdir(errno: errno, path: path, location: .here())) + } + + // Drop the last component and loop around. + if let component = path.lastComponent { + path.removeLastComponent() + droppedComponents.append(component) + } else { + // Should only happen if the path is empty or contains just the root. + return .failure(.mkdir(errno: errno, path: path, location: .here())) + } + } + } + + // Successfully made a directory, construct its children. + while let subdirectory = droppedComponents.popLast() { + path.append(subdirectory) + switch Syscall.mkdir(at: path, permissions: permissions) { + case .success: + continue + case let .failure(errno): + return .failure(.mkdir(errno: errno, path: path, location: .here())) + } + } + + return .success(()) + } + + /// Returns info about the file at `path`. + private func _info( + forFileAt path: FilePath, + infoAboutSymbolicLink: Bool + ) -> Result { + let result: Result + if infoAboutSymbolicLink { + result = Syscall.lstat(path: path) + } else { + result = Syscall.stat(path: path) + } + + return result.map { + FileInfo(platformSpecificStatus: $0) + }.flatMapError { errno in + if errno == .noSuchFileOrDirectory { + return .success(nil) + } else { + let name = infoAboutSymbolicLink ? "lstat" : "stat" + return .failure(.stat(name, errno: errno, path: path, location: .here())) + } + } + } + + /// Represents an item in a directory that needs copying, or an explicit indication of the end + /// of items. The provision of the ``endOfDir`` case significantly simplifies the parallel code + enum DirCopyItem: Hashable, Sendable { + case endOfDir + case toCopy(from: DirectoryEntry, to: FilePath) + } + + /// Creates the directory ``destinationPath`` based on the directory at ``sourcePath`` including + /// any permissions/attributes. It does not copy the contents but indicates the items within + /// ``sourcePath`` which should be copied. + /// + /// This is a little cumbersome, because it is used by ``copyDirectorySequential`` and + /// ``copyDirectoryParallel``. It is desirable to use the directories' file descriptor for as + /// little time as possible, and certainly not across asynchronous invocations. The downstream + /// paths in the parallel and sequential paths are very different + /// - Returns: An array of `DirCopyItem` which have passed the ``shouldCopyItem``` filter. The + /// target file paths will all be in ``destinationPath``. The array will always finish with + /// an ``DirCopyItem.endOfDir``. + private func prepareDirectoryForRecusiveCopy( + from sourcePath: FilePath, + to destinationPath: FilePath, + shouldProceedAfterError: @escaping @Sendable ( + _ entry: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws -> [DirCopyItem] { + try await self.withDirectoryHandle(atPath: sourcePath) { dir in + // Grab the directory info to copy permissions. + let info = try await dir.info() + try await self.createDirectory( + at: destinationPath, + withIntermediateDirectories: false, + permissions: info.permissions + ) + + #if !os(Android) + // Copy over extended attributes, if any exist. + do { + let attributes = try await dir.attributeNames() + + if !attributes.isEmpty { + try await self.withDirectoryHandle( + atPath: destinationPath + ) { destinationDir in + for attribute in attributes { + let value = try await dir.valueForAttribute(attribute) + try await destinationDir.updateValueForAttribute( + value, + attribute: attribute + ) + } + } + } + } catch let error as FileSystemError where error.code == .unsupported { + // Not all file systems support extended attributes. Swallow errors indicating this. + () + } + #endif + // Build a list of items the caller needs to deal with, then do any further work after + // closing the current directory. + var contentsToCopy = [DirCopyItem]() + + for try await batch in dir.listContents().batched() { + for entry in batch { + // Any further work is pointless. We are under no obligation to cleanup. Exit as + // fast and cleanly as possible. + try Task.checkCancellation() + let entryDestination = destinationPath.appending(entry.name) + + if await shouldCopyItem(entry, entryDestination) { + // Assume there's a good chance of everything in the batch being included in + // the common case. Let geometric growth go from this point though. + if contentsToCopy.isEmpty { + // Reserve space for the endOfDir entry too. + contentsToCopy.reserveCapacity(batch.count + 1) + } + switch entry.type { + case .regular, .symlink, .directory: + contentsToCopy.append(.toCopy(from: entry, to: entryDestination)) + + default: + let error = FileSystemError( + code: .unsupported, + message: """ + Can't copy '\(entry.path)' of type '\(entry.type)'; only regular \ + files, symbolic links and directories can be copied. + """, + cause: nil, + location: .here() + ) + + try await shouldProceedAfterError(entry, error) + } + } + } + } + + contentsToCopy.append(.endOfDir) + return contentsToCopy + } + } + + /// This could be achieved through quite complicated special casing of the parallel copy. The + /// resulting code is far harder to read and debug, so this is kept as a special case. + private func copyDirectorySequential( + from sourcePath: FilePath, + to destinationPath: FilePath, + shouldProceedAfterError: @escaping @Sendable ( + _ entry: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + // Strategy: find all needed items to copy/recurse into while the directory is open; defer + // actual copying and recursion until after the source directory has been closed to avoid + // consuming too many file descriptors. + let toCopy = try await self.prepareDirectoryForRecusiveCopy( + from: sourcePath, + to: destinationPath, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + + for entry in toCopy { + switch entry { + case .endOfDir: + // Sequential cases doesn't need to worry about this, it uses simple recursion. + continue + case let .toCopy(source, destination): + // Note: The entry type could have changed between finding it and acting on it. This + // is inherent in file systems, just more likely in an asynchronous environment. We + // just accept those coming through as regular errors. + switch source.type { + case .regular: + do { + try await self.copyRegularFile( + from: source.path, + to: destination + ) + } catch { + try await shouldProceedAfterError(source, error) + } + + case .symlink: + do { + try await self.copySymbolicLink( + from: source.path, + to: destination + ) + } catch { + try await shouldProceedAfterError(source, error) + } + + case .directory: + try await self.copyDirectorySequential( + from: source.path, + to: destination, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + + default: + let error = FileSystemError( + code: .unsupported, + message: """ + Can't copy '\(source.path)' of type '\(source.type)'; only regular \ + files, symbolic links and directories can be copied. + """, + cause: nil, + location: .here() + ) + + try await shouldProceedAfterError(source, error) + } + } + } + } + + /// Copies the directory from `sourcePath` to `destinationPath`. + private func copyDirectory( + from sourcePath: FilePath, + to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy, + shouldProceedAfterError: @escaping @Sendable ( + _ entry: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + switch copyStrategy.wrapped { + case .sequential: + return try await self.copyDirectorySequential( + from: sourcePath, + to: destinationPath, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + case let .parallel(maxDescriptors): + // Note that maxDescriptors was validated on construction of CopyStrategy. See notes on + // CopyStrategy about assumptions on descriptor use. For now, we take the worst case + // peak for every operation, which is two file descriptors. This keeps the downstream + // limiting code simple. + // + // We do not preclude the use of more granular limiting in the future (e.g. a directory + // scan requires only a single file descriptor). For now we just drop any excess + // remainder entirely. + let limitValue = maxDescriptors / 2 + return try await self.copyDirectoryParallel( + from: sourcePath, + to: destinationPath, + maxConcurrentOperations: limitValue, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + } + } + + /// Building block of the parallel directory copy implementation. Each invocation of this is + /// allowed to consume two file descriptors. Any further work (if any) should be sent to `yield` + /// for future processing. + func copySelfAndEnqueueChildren( + from: DirectoryEntry, + to: FilePath, + yield: @Sendable ([DirCopyItem]) -> Void, + shouldProceedAfterError: @escaping @Sendable ( + _ source: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + switch from.type { + case .regular: + do { + try await self.copyRegularFile( + from: from.path, + to: to + ) + } catch { + try await shouldProceedAfterError(from, error) + } + + case .symlink: + do { + try await self.copySymbolicLink( + from: from.path, + to: to + ) + } catch { + try await shouldProceedAfterError(from, error) + } + + case .directory: + let addToQueue = try await self.prepareDirectoryForRecusiveCopy( + from: from.path, + to: to, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + yield(addToQueue) + + default: + let error = FileSystemError( + code: .unsupported, + message: """ + Can't copy '\(from.path)' of type '\(from.type)'; only regular \ + files, symbolic links and directories can be copied. + """, + cause: nil, + location: .here() + ) + + try await shouldProceedAfterError(from, error) + } + } + + private func copyRegularFile( + from sourcePath: FilePath, + to destinationPath: FilePath + ) async throws { + try await self.threadPool.runIfActive { + try self._copyRegularFile(from: sourcePath, to: destinationPath).get() + } + } + + private func _copyRegularFile( + from sourcePath: FilePath, + to destinationPath: FilePath + ) -> Result { + func makeOnUnavailableError( + path: FilePath, + location: FileSystemError.SourceLocation + ) -> FileSystemError { + FileSystemError( + code: .closed, + message: "Can't copy '\(sourcePath)' to '\(destinationPath)', '\(path)' is closed.", + cause: nil, + location: location + ) + } + + #if canImport(Darwin) + // COPYFILE_CLONE clones the file if possible and will fallback to doing a copy. + // COPYFILE_ALL is shorthand for: + // COPYFILE_STAT | COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_DATA + let flags = copyfile_flags_t(COPYFILE_CLONE) | copyfile_flags_t(COPYFILE_ALL) + return Libc.copyfile( + from: sourcePath, + to: destinationPath, + state: nil, + flags: flags + ).mapError { errno in + FileSystemError.copyfile( + errno: errno, + from: sourcePath, + to: destinationPath, + location: .here() + ) + } + + #elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) + + let openSourceResult = self._openFile( + forReadingAt: sourcePath, + options: OpenOptions.Read(followSymbolicLinks: true) + ).mapError { + FileSystemError( + message: "Can't copy '\(sourcePath)', it couldn't be opened.", + wrapping: $0 + ) + } + + let source: ReadFileHandle + switch openSourceResult { + case let .success(handle): + source = handle + case let .failure(error): + return .failure(error) + } + + defer { + _ = source.fileHandle.systemFileHandle.sendableView._close(materialize: true) + } + + let sourceInfo: FileInfo + switch source.fileHandle.systemFileHandle.sendableView._info() { + case let .success(info): + sourceInfo = info + case let .failure(error): + return .failure(error) + } + + let options = OpenOptions.Write( + existingFile: .none, + newFile: OpenOptions.NewFile( + permissions: sourceInfo.permissions, + transactionalCreation: false + ) + ) + + let openDestinationResult = self._openFile( + forWritingAt: destinationPath, + options: options + ).mapError { + FileSystemError( + message: "Can't copy '\(sourcePath)' as '\(destinationPath)' couldn't be opened.", + wrapping: $0 + ) + } + + let destination: WriteFileHandle + switch openDestinationResult { + case let .success(handle): + destination = handle + case let .failure(error): + return .failure(error) + } + + let copyResult: Result + copyResult = source.fileHandle.systemFileHandle.sendableView._withUnsafeDescriptorResult { sourceFD in + destination.fileHandle.systemFileHandle.sendableView._withUnsafeDescriptorResult { destinationFD in + var offset = 0 + + while offset < sourceInfo.size { + // sendfile(2) limits writes to 0x7ffff000 in size + let size = min(Int(sourceInfo.size) - offset, 0x7fff_f000) + let result = Syscall.sendfile( + to: destinationFD, + from: sourceFD, + offset: offset, + size: size + ).mapError { errno in + FileSystemError.sendfile( + errno: errno, + from: sourcePath, + to: destinationPath, + location: .here() + ) + } + + switch result { + case let .success(bytesCopied): + offset += bytesCopied + case let .failure(error): + return .failure(error) + } + } + return .success(()) + } onUnavailable: { + makeOnUnavailableError(path: destinationPath, location: .here()) + } + } onUnavailable: { + makeOnUnavailableError(path: sourcePath, location: .here()) + } + + let closeResult = destination.fileHandle.systemFileHandle.sendableView._close(materialize: true) + return copyResult.flatMap { closeResult } + #endif + } + + private func copySymbolicLink( + from sourcePath: FilePath, + to destinationPath: FilePath + ) async throws { + try await self.threadPool.runIfActive { + try self._copySymbolicLink(from: sourcePath, to: destinationPath).get() + } + } + + private func _copySymbolicLink( + from sourcePath: FilePath, + to destinationPath: FilePath + ) -> Result { + self._destinationOfSymbolicLink(at: sourcePath).flatMap { linkDestination in + self._createSymbolicLink(at: destinationPath, withDestination: linkDestination) + } + } + + @_spi(Testing) + public func removeOneItem( + at path: FilePath, + function: String = #function, + file: String = #fileID, + line: Int = #line + ) async throws -> Int { + try await self.threadPool.runIfActive { + switch Libc.remove(path) { + case .success: + return 1 + case .failure(.noSuchFileOrDirectory): + return 0 + case .failure(let errno): + throw FileSystemError.remove( + errno: errno, + path: path, + location: .init(function: function, file: file, line: line) + ) + } + } + } + + private enum MoveResult { + case moved + case differentLogicalDevices + } + + private func _moveItem( + at sourcePath: FilePath, + to destinationPath: FilePath + ) -> Result { + // Check that the destination doesn't exist. 'rename' will remove it otherwise! + switch self._info(forFileAt: destinationPath, infoAboutSymbolicLink: true) { + case .success(.none): + // Doesn't exist: continue + () + + case .success(.some): + let fileSystemError = FileSystemError( + code: .fileAlreadyExists, + message: """ + Unable to move '\(sourcePath)' to '\(destinationPath)', the destination path \ + already exists. + """, + cause: nil, + location: .here() + ) + return .failure(fileSystemError) + + case let .failure(error): + let fileSystemError = FileSystemError( + message: """ + Unable to move '\(sourcePath)' to '\(destinationPath)', could not determine \ + whether the destination path exists or not. + """, + wrapping: error + ) + return .failure(fileSystemError) + } + + switch Syscall.rename(from: sourcePath, to: destinationPath) { + case .success: + return .success(.moved) + + case .failure(.improperLink): + // The two paths are on different logical devices; copy and then remove the original. + return .success(.differentLogicalDevices) + + case let .failure(errno): + let error = FileSystemError.rename( + "rename", + errno: errno, + oldName: sourcePath, + newName: destinationPath, + location: .here() + ) + return .failure(error) + } + } + + private func parseTemporaryDirectoryTemplate( + _ template: FilePath + ) -> Result<(FilePath, String, Int), FileSystemError> { + // Check whether template is valid (i.e. has a `lastComponent`). + guard let lastComponentPath = template.lastComponent else { + let fileSystemError = FileSystemError( + code: .invalidArgument, + message: """ + Can't create temporary directory, the template ('\(template)') is invalid. \ + The template should be a file path ending in at least three 'X's. + """, + cause: nil, + location: .here() + ) + return .failure(fileSystemError) + } + + let lastComponent = lastComponentPath.string + + // Finding the index of the last non-'X' character in `lastComponent.string` and advancing + // it by one. + let prefix: String + var index = lastComponent.lastIndex(where: { $0 != "X" }) + if index != nil { + lastComponent.formIndex(after: &(index!)) + prefix = String(lastComponent[..= 3 else { + let fileSystemError = FileSystemError( + code: .invalidArgument, + message: """ + Can't create temporary directory, the template ('\(template)') is invalid. \ + The template must end in at least three 'X's. + """, + cause: nil, + location: .here() + ) + return .failure(fileSystemError) + } + + return .success((template.removingLastComponent(), prefix, suffixLength)) + } + + private func _createTemporaryDirectory( + template: FilePath + ) -> Result { + let prefix: String + let root: FilePath + let suffixLength: Int + + let parseResult = self.parseTemporaryDirectoryTemplate(template) + switch parseResult { + case let .success((parseRoot, parsePrefix, parseSuffixLength)): + root = parseRoot + prefix = parsePrefix + suffixLength = parseSuffixLength + case let .failure(error): + return .failure(error) + } + + for _ in 1...16 { + let name = prefix + String(randomAlphaNumericOfLength: suffixLength) + + // Trying to create the directory. + let finalPath = root.appending(name) + let createDirectoriesResult = self._createDirectory( + at: finalPath, + withIntermediateDirectories: true, + permissions: FilePermissions.defaultsForDirectory + ) + switch createDirectoriesResult { + case .success: + return .success(finalPath) + case let .failure(error): + if let systemCallError = error.cause as? FileSystemError.SystemCallError { + switch systemCallError.errno { + // If the file at the generated path already exists, we generate a new file + // path. + case .fileExists, .isDirectory: + break + default: + let fileSystemError = FileSystemError( + message: "Unable to create temporary directory '\(template)'.", + wrapping: error + ) + return .failure(fileSystemError) + } + } else { + let fileSystemError = FileSystemError( + message: "Unable to create temporary directory '\(template)'.", + wrapping: error + ) + return .failure(fileSystemError) + } + } + } + let fileSystemError = FileSystemError( + code: .unknown, + message: """ + Could not create a temporary directory from the provided template ('\(template)'). \ + Try adding more 'X's at the end of the template. + """, + cause: nil, + location: .here() + ) + return .failure(fileSystemError) + } + + func _createSymbolicLink( + at linkPath: FilePath, + withDestination destinationPath: FilePath + ) -> Result { + Syscall.symlink(to: destinationPath, from: linkPath).mapError { errno in + FileSystemError.symlink( + errno: errno, + link: linkPath, + target: destinationPath, + location: .here() + ) + } + } + + func _destinationOfSymbolicLink(at path: FilePath) -> Result { + Syscall.readlink(at: path).mapError { errno in + FileSystemError.readlink( + errno: errno, + path: path, + location: .here() + ) + } + } +} diff --git a/Sources/_NIOFileSystem/FileSystemError+Syscall.swift b/Sources/_NIOFileSystem/FileSystemError+Syscall.swift new file mode 100644 index 000000000..280041e5c --- /dev/null +++ b/Sources/_NIOFileSystem/FileSystemError+Syscall.swift @@ -0,0 +1,1158 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +#elseif canImport(Musl) +@preconcurrency import Musl +#endif + +extension FileSystemError { + /// Creates a ``FileSystemError`` by constructing a ``SystemCallError`` as the cause. + internal init( + code: Code, + message: String, + systemCall: String, + errno: Errno, + location: SourceLocation + ) { + self.init( + code: code, + message: message, + cause: SystemCallError(systemCall: systemCall, errno: errno), + location: location + ) + } +} + +extension FileSystemError { + /// Create a file system error appropriate for the `stat`/`lstat`/`fstat` system calls. + @_spi(Testing) + public static func stat( + _ name: String, + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + // See: 'man 2 fstat' + switch errno { + case .badFileDescriptor: + code = .closed + message = "Unable to get information about '\(path)', the file is closed." + default: + code = .unknown + message = "Unable to get information about '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: name, + errno: errno, + location: location + ) + } + + @_spi(Testing) + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public static func fchmod( + operation: SystemFileHandle.UpdatePermissionsOperation, + operand: FilePermissions, + permissions: FilePermissions, + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let message: String + let code: FileSystemError.Code + + // See: 'man 2 fchmod' + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not \(operation) permissions '\(operand)', '\(path)' is closed." + + case .invalidArgument: + // Permissions are invalid so display the raw value in octal. + let rawPermissions = String(permissions.rawValue, radix: 0o10) + let op: String + switch operation { + case .set: + op = "set" + case .add: + op = "added" + case .remove: + op = "removed" + } + code = .invalidArgument + message = """ + Invalid permissions ('\(rawPermissions)') could not be \(op) for file '\(path)'. + """ + + case .notPermitted: + code = .permissionDenied + message = """ + Not permitted to \(operation) permissions '\(operand)' for file '\(path)', \ + the effective user ID does not match the owner of the file and the effective \ + user ID is not the super-user. + """ + + default: + code = .unknown + message = "Could not \(operation) permissions '\(operand)' to '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "fchmod", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func flistxattr(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + let code: FileSystemError.Code + let message: String + + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not list extended attributes, '\(path)' is closed." + + case .notSupported: + code = .unsupported + message = "Extended attributes are disabled or not supported by the filesystem." + + case .notPermitted: + code = .unsupported + message = "Extended attributes are not supported by '\(path)'." + + case .permissionDenied: + code = .permissionDenied + message = "Not permitted to list extended attributes for '\(path)'." + + default: + code = .unknown + message = "Could not to list extended attributes for '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "flistxattr", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func fgetxattr( + attribute name: String, + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + switch errno { + case .badFileDescriptor: + code = .closed + message = """ + Could not get value for extended attribute ('\(name)'), '\(path)' is closed. + """ + case .notSupported: + code = .unsupported + message = "Extended attributes are disabled or not supported by the filesystem." + #if canImport(Darwin) + case .fileNameTooLong: + code = .invalidArgument + message = """ + Length of UTF-8 extended attribute name (\(name.utf8.count)) is greater \ + than the limit (\(XATTR_MAXNAMELEN)). Use a shorter attribute name. + """ + #endif + default: + code = .unknown + message = "Could not get value for extended attribute ('\(name)') for '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "fgetxattr", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func fsetxattr( + attribute name: String, + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + // See: 'man 2 fsetxattr' + switch errno { + case .badFileDescriptor: + code = .closed + message = """ + Could not set value for extended attribute ('\(name)'), '\(path)' is closed. + """ + + case .notSupported: + code = .unsupported + message = """ + Extended attributes are disabled or not supported by the filesystem. + """ + + #if canImport(Darwin) + case .fileNameTooLong: + code = .invalidArgument + message = """ + Length of UTF-8 extended attribute name (\(name.utf8.count)) is greater \ + than the limit limit (\(XATTR_MAXNAMELEN)). Use a shorter attribute \ + name. + """ + #endif + + case .invalidArgument: + code = .invalidArgument + message = """ + Extended attribute name ('\(name)') must be a valid UTF-8 string. + """ + default: + code = .unknown + message = """ + Could not set value for extended attribute ('\(name)') for '\(path)'. + """ + } + + return FileSystemError( + code: code, + message: message, + systemCall: "fsetxattr", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func fremovexattr( + attribute name: String, + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + // See: 'man 2 fremovexattr' + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not remove extended attribute ('\(name)'), '\(path)' is closed." + + case .notSupported: + code = .unsupported + message = "Extended attributes are disabled or not supported by the filesystem." + + #if canImport(Darwin) + case .fileNameTooLong: + code = .invalidArgument + message = """ + Length of UTF-8 extended attribute name (\(name.utf8.count)) is greater \ + than the limit (\(XATTR_MAXNAMELEN)). Use a shorter attribute name. + """ + #endif + + default: + code = .unknown + message = "Could not remove extended attribute ('\(name)') from '\(path)'" + } + + return FileSystemError( + code: code, + message: message, + systemCall: "fremovexattr", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func fsync( + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not synchronize file, '\(path)' is closed." + case .ioError: + code = .io + message = "An I/O error occurred while synchronizing '\(path)'." + default: + code = .unknown + message = "Could not synchronize file '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "fsync", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func dup(error: Error, path: FilePath, location: SourceLocation) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "Unable to duplicate descriptor of closed handle for '\(path)'." + default: + code = .unknown + message = "Unable to duplicate descriptor of handle for '\(path)'." + } + cause = SystemCallError(systemCall: "dup", errno: errno) + } else { + code = .unknown + message = "Unable to duplicate descriptor of handle for '\(path)'." + cause = error + } + + return FileSystemError( + code: code, + message: message, + cause: cause, + location: location + ) + } + + @_spi(Testing) + public static func ftruncate(error: Error, path: FilePath, location: SourceLocation) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "Can't resize '\(path)', it's closed." + case .fileTooLarge: + code = .invalidArgument + message = "The requested size for '\(path)' is too large." + case .invalidArgument: + code = .invalidArgument + message = "The requested size for '\(path)' is negative, therefore invalid." + default: + code = .unknown + message = "Unable to resize '\(path)'." + } + cause = SystemCallError(systemCall: "ftruncate", errno: errno) + } else { + code = .unknown + message = "Unable to resize '\(path)'." + cause = error + } + + return FileSystemError( + code: code, + message: message, + cause: cause, + location: location + ) + } + + @_spi(Testing) + public static func close(error: Error, path: FilePath, location: SourceLocation) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + // See: 'man 2 close' + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "File already closed or file descriptor was invalid ('\(path)')." + case .ioError: + code = .io + message = "I/O error during close, some writes to '\(path)' may have failed." + default: + code = .unknown + message = "Error closing file '\(path)'." + } + cause = SystemCallError(systemCall: "close", errno: errno) + } else { + code = .unknown + message = "Error closing file '\(path)'." + cause = error + } + + return FileSystemError( + code: code, + message: message, + cause: cause, + location: location + ) + } + + @_spi(Testing) + public enum ReadSyscall: String, Sendable { + case read + case pread + } + + @_spi(Testing) + public static func read( + usingSyscall syscall: ReadSyscall, + error: Error, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + // We expect an Errno as 'swift-system' uses result types under-the-hood, + // but don't require that in case something changes. + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not read from closed file '\(path)'." + case .ioError: + code = .io + message = """ + Could not read from file ('\(path)'); an I/O error occurred while reading \ + from the file system. + """ + case .illegalSeek: + code = .unsupported + message = "File is not seekable: '\(path)'." + default: + code = .unknown + message = "Could not read from file '\(path)'." + } + cause = SystemCallError(systemCall: syscall.rawValue, errno: errno) + } else { + code = .unknown + message = "Could not read from file '\(path)'." + cause = error + } + + return FileSystemError( + code: code, + message: message, + cause: cause, + location: location + ) + } + + @_spi(Testing) + public enum WriteSyscall: String, Sendable { + case write + case pwrite + } + + @_spi(Testing) + public static func write( + usingSyscall syscall: WriteSyscall, + error: Error, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + // We expect an Errno as 'swift-system' uses result types under-the-hood, + // but don't require that in case something changes. + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "Could not write to closed file '\(path)'." + case .ioError: + code = .io + message = """ + Could not write to file ('\(path)'); an I/O error occurred while writing to \ + the file system. + """ + case .illegalSeek: + code = .unsupported + message = "File is not seekable: '\(path)'." + default: + code = .unknown + message = "Could not write to file." + } + cause = SystemCallError(systemCall: syscall.rawValue, errno: errno) + } else { + code = .unknown + message = "Could not write to file." + cause = error + } + + return FileSystemError( + code: code, + message: message, + cause: cause, + location: location + ) + } + + @_spi(Testing) + public static func fdopendir(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + FileSystemError( + code: .unknown, + message: "Unable to open directory stream for '\(path)'.", + systemCall: "fdopendir", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func readdir(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + FileSystemError( + code: .unknown, + message: "Unable to read directory stream for '\(path)'.", + systemCall: "readdir", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func ftsRead(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + FileSystemError( + code: .unknown, + message: "Unable to read FTS stream for '\(path)'.", + systemCall: "fts_read", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func open( + _ name: String, + error: Error, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + let cause: Error + + if let errno = error as? Errno { + switch errno { + case .badFileDescriptor: + code = .closed + message = "Unable to open file at path '\(path)', the descriptor is closed." + case .permissionDenied: + code = .permissionDenied + message = "Unable to open file at path '\(path)', permissions denied." + case .fileExists: + code = .fileAlreadyExists + message = """ + Unable to create file at path '\(path)', no existing file options were set \ + which implies that no file should exist but a file already exists at the \ + specified path. + """ + case .ioError: + code = .io + message = """ + Unable to create file at path '\(path)', an I/O error occurred while \ + creating the file. + """ + case .tooManyOpenFiles: + code = .unavailable + message = """ + Unable to open file at path '\(path)', too many file descriptors are open. + """ + case .noSuchFileOrDirectory: + code = .notFound + message = """ + Unable to open or create file at path '\(path)', either a component of the \ + path did not exist or the named file to be opened did not exist. + """ + case .notDirectory: + code = .notFound + message = """ + Unable to open or create file at path '\(path)', an intermediate component of \ + the path was not a directory. + """ + case .tooManySymbolicLinkLevels: + code = .invalidArgument + message = """ + Can't open file at path '\(path)', the target is a symbolic link and \ + 'followSymbolicLinks' was set to 'false'. + """ + default: + code = .unknown + message = "Unable to open file at path '\(path)'." + } + cause = SystemCallError(systemCall: name, errno: errno) + } else { + code = .unknown + message = "Unable to open file at path '\(path)'." + cause = error + } + + return FileSystemError(code: code, message: message, cause: cause, location: location) + } + + @_spi(Testing) + public static func mkdir(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + let code: Code + let message: String + + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Insufficient permissions to create a directory at '\(path)'. Search permissions \ + denied for a component of the path or write permission denied for the parent \ + directory. + """ + case .isDirectory: + code = .invalidArgument + message = "Can't create directory, '\(path)' is the root directory." + case .fileExists: + code = .fileAlreadyExists + message = "Can't create directory, the pathname '\(path)' already exists." + case .notDirectory: + code = .invalidArgument + message = "Can't create directory, a component of '\(path)' is not a directory." + case .noSuchFileOrDirectory: + code = .invalidArgument + message = """ + Can't create directory, a component of '\(path)' does not exist. Ensure all \ + parent directories exist or set 'withIntermediateDirectories' to 'true' when \ + calling 'createDirectory(at:withIntermediateDirectories:permissions)'. + """ + case .ioError: + code = .io + message = "An I/O error occurred when the directory at '\(path)'." + default: + code = .unknown + message = "" + } + + return FileSystemError( + code: code, + message: message, + systemCall: "mkdir", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func rename( + _ name: String, + errno: Errno, + oldName: FilePath, + newName: FilePath, + location: SourceLocation + ) -> Self { + let code: Code + let message: String + + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Insufficient permissions to rename '\(oldName)' to '\(newName)'. Search \ + permissions were denied on a component of either path, or write permissions were \ + denied on the parent directory of either path. + """ + case .fileExists: + code = .fileAlreadyExists + message = "Can't rename '\(oldName)' to '\(newName)' as it already exists." + case .invalidArgument: + code = .invalidArgument + if oldName == "." || oldName == ".." { + message = """ + Can't rename '\(oldName)' to '\(newName)', '.' and '..' can't be renamed. + """ + } else { + message = """ + Can't rename '\(oldName)', it may be a parent directory of '\(newName)'. + """ + } + case .noSuchFileOrDirectory: + code = .notFound + message = """ + Can't rename '\(oldName)' to '\(newName)', a component of '\(oldName)' does \ + not exist. + """ + case .ioError: + code = .io + message = """ + Can't rename '\(oldName)' to '\(newName)', an I/O error occurred while making \ + or updating a directory entry. + """ + default: + code = .unknown + message = "Can't rename '\(oldName)' to '\(newName)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: name, + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func remove(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + let code: Code + let message: String + + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Insufficient permissions to remove '\(path)'. Search permissions denied \ + on a component of the path or write permission denied on the directory \ + containing the item to be removed. + """ + case .notPermitted: + code = .permissionDenied + message = """ + Insufficient permission to remove '\(path)', the effective user ID of the \ + process is not permitted to remove the file. + """ + case .resourceBusy: + code = .unavailable + message = """ + Can't remove '\(path)', it may be being used by another process or is the mount \ + point for a mounted file system. + """ + case .ioError: + code = .io + message = """ + Can't remove '\(path)', an I/O error occurred while deleting its directory entry. + """ + default: + code = .unknown + message = "Can't remove '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "remove", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func symlink( + errno: Errno, + link: FilePath, + target: FilePath, + location: SourceLocation + ) -> Self { + let code: Code + let message: String + + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Can't create symbolic link '\(link)' to '\(target)', write access to the \ + directory containing the link was denied or one of the directories in its path \ + denied search permissions. + """ + case .notPermitted: + code = .permissionDenied + message = """ + Can't create symbolic link '\(link)' to '\(target)', the file system \ + containing '\(link)' doesn't support the creation of symbolic links. + """ + case .fileExists: + code = .fileAlreadyExists + message = """ + Can't create symbolic link '\(link)' to '\(target)', '\(link)' already exists. + """ + case .noSuchFileOrDirectory: + code = .invalidArgument + message = """ + Can't create symbolic link '\(link)' to '\(target)', a component of '\(link)' \ + does not exist or is a dangling symbolic link. + """ + case .notDirectory: + code = .invalidArgument + message = """ + Can't create symbolic link '\(link)' to '\(target)', a component of '\(link)' \ + is not a directory. + """ + case .ioError: + code = .io + message = """ + Can't create symbolic link '\(link)' to '\(target)', an I/O error occurred. + """ + default: + code = .unknown + message = "Can't create symbolic link '\(link)' to '\(target)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "symlink", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func readlink(errno: Errno, path: FilePath, location: SourceLocation) -> Self { + let code: Code + let message: String + + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Can't read symbolic link at '\(path)'; search permission was denied for a \ + component in its prefix. + """ + case .invalidArgument: + code = .invalidArgument + message = """ + Can't read '\(path)'; it is not a symbolic link. + """ + case .ioError: + code = .io + message = """ + Can't read symbolic link at '\(path)'; an I/O error occurred. + """ + case .noSuchFileOrDirectory: + code = .notFound + message = """ + Can't read symbolic link, no file exists at '\(path)'. + """ + default: + code = .unknown + message = "Can't read symbolic link at '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "readlink", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func link( + errno: Errno, + from sourcePath: FilePath, + to destinationPath: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + // See: 'man 2 link' + switch errno { + case .fileExists: + code = .fileAlreadyExists + message = """ + Can't link '\(sourcePath)' to '\(destinationPath)', a file already exists \ + at '\(destinationPath)'. + """ + case .ioError: + code = .io + message = "I/O error while linking '\(sourcePath)' to '\(destinationPath)'." + default: + code = .unknown + message = "Error linking '\(sourcePath)' to '\(destinationPath)'." + } + + return FileSystemError( + code: code, + message: message, + cause: SystemCallError(systemCall: "linkat", errno: errno), + location: location + ) + } + + @_spi(Testing) + public static func unlink( + errno: Errno, + path: FilePath, + location: SourceLocation + ) -> Self { + let code: FileSystemError.Code + let message: String + + // See: 'man 2 unlink' + switch errno { + case .permissionDenied: + code = .permissionDenied + message = """ + Search permission denied for a component of the path ('\(path)') or write \ + permission denied on the directory containing the link to be removed. + """ + case .ioError: + code = .io + message = "I/O error while unlinking '\(path)'." + case .noSuchFileOrDirectory: + code = .notFound + message = "The named file ('\(path)') doesn't exist." + case .notPermitted: + code = .permissionDenied + message = "Insufficient permissions to unlink '\(path)'." + default: + code = .unknown + message = "Error unlinking '\(path)'." + } + + return FileSystemError( + code: code, + message: message, + cause: SystemCallError(systemCall: "unlink", errno: errno), + location: location + ) + } + + @_spi(Testing) + public static func getcwd(errno: Errno, location: SourceLocation) -> Self { + FileSystemError( + code: .unavailable, + message: "Can't get current working directory.", + systemCall: "getcwd", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func confstr(name: String, errno: Errno, location: SourceLocation) -> Self { + FileSystemError( + code: .unavailable, + message: "Can't get configuration value for '\(name)'.", + systemCall: "confstr", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func fcopyfile( + errno: Errno, + from sourcePath: FilePath, + to destinationPath: FilePath, + location: SourceLocation + ) -> Self { + Self._copyfile( + "fcopyfile", + errno: errno, + from: sourcePath, + to: destinationPath, + location: location + ) + } + + @_spi(Testing) + public static func copyfile( + errno: Errno, + from sourcePath: FilePath, + to destinationPath: FilePath, + location: SourceLocation + ) -> Self { + Self._copyfile( + "copyfile", + errno: errno, + from: sourcePath, + to: destinationPath, + location: location + ) + } + + private static func _copyfile( + _ name: String, + errno: Errno, + from sourcePath: FilePath, + to destinationPath: FilePath, + location: SourceLocation + ) -> Self { + let code: Code + let message: String + + switch errno { + case .notSupported: + code = .invalidArgument + message = """ + Can't copy file from '\(sourcePath)' to '\(destinationPath)', the item to copy is \ + not a directory, symbolic link or regular file. + """ + case .permissionDenied: + code = .permissionDenied + message = """ + Can't copy file, search permission was denied for a component of the path \ + prefix for the source ('\(sourcePath)') or destination ('\(destinationPath)'), \ + or write permission was denied for a component of the path prefix for the source. + """ + case .invalidArgument: + code = .invalidArgument + message = """ + Can't copy file from '\(sourcePath)' to '\(destinationPath)', the destination \ + path already exists. + """ + case .fileExists: + code = .fileAlreadyExists + message = """ + Unable to create file at path '\(destinationPath)', no existing file options were set \ + which implies that no file should exist but a file already exists at the \ + specified path. + """ + case .tooManyOpenFiles: + code = .unavailable + message = """ + Unable to open the source ('\(sourcePath)') or destination ('\(destinationPath)') files, \ + too many file descriptors are open. + """ + case .noSuchFileOrDirectory: + code = .notFound + message = """ + Unable to open or create file at path '\(sourcePath)', either a component of the \ + path did not exist or the named file to be opened did not exist. + """ + default: + code = .unknown + message = "Can't copy file from '\(sourcePath)' to '\(destinationPath)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: name, + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func sendfile( + errno: Errno, + from sourcePath: FilePath, + to destinationPath: FilePath, + location: SourceLocation + ) -> FileSystemError { + let code: FileSystemError.Code + let message: String + + switch errno { + case .ioError: + code = .io + message = """ + An I/O error occurred while reading from '\(sourcePath)', can't copy to \ + '\(destinationPath)'. + """ + case .noMemory: + code = .io + message = """ + Insufficient memory to read from '\(sourcePath)', can't copy to \ + '\(destinationPath)'. + """ + default: + code = .unknown + message = "Can't copy file from '\(sourcePath)' to '\(destinationPath)'." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "sendfile", + errno: errno, + location: location + ) + } + + @_spi(Testing) + public static func futimens( + errno: Errno, + path: FilePath, + lastAccessTime: FileInfo.Timespec?, + lastDataModificationTime: FileInfo.Timespec?, + location: SourceLocation + ) -> FileSystemError { + let code: FileSystemError.Code + let message: String + + switch errno { + case .permissionDenied, .notPermitted: + code = .permissionDenied + message = "Not permitted to change last access or last data modification times for \(path)." + + case .readOnlyFileSystem: + code = .unsupported + message = + "Not permitted to change last access or last data modification times for \(path): this is a read-only file system." + + case .badFileDescriptor: + code = .closed + message = "Could not change last access or last data modification dates for \(path): file is closed." + + default: + code = .unknown + message = "Could not change last access or last data modification dates for \(path)." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "futimens", + errno: errno, + location: location + ) + } +} diff --git a/Sources/_NIOFileSystem/FileSystemError.swift b/Sources/_NIOFileSystem/FileSystemError.swift new file mode 100644 index 000000000..f9a106350 --- /dev/null +++ b/Sources/_NIOFileSystem/FileSystemError.swift @@ -0,0 +1,280 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +/// An error thrown as a result of interaction with the file system. +/// +/// All errors have a high-level ``FileSystemError/Code-swift.struct`` which identifies the domain +/// of the error. For example an operation performed on a ``FileHandleProtocol`` which has already been +/// closed will result in a ``FileSystemError/Code-swift.struct/closed`` error code. Errors also +/// include a message describing what went wrong and how to remedy it (if applicable). The +/// ``FileSystemError/message`` is not static and may include dynamic information such as the path +/// of the file for which the operation failed, for example. +/// +/// Errors may have a ``FileSystemError/cause``, an error which caused the operation to +/// fail which may be platform specific. +public struct FileSystemError: Error, Sendable { + /// A high-level error code to provide broad a classification. + public var code: Code + + /// A message describing what went wrong and how it may be remedied. + public var message: String + + /// An error which caused the operation to fail. This may include additional details + /// about the root cause of the failure. + public var cause: Error? + + /// The location from which this error was thrown. + public var location: SourceLocation + + public init( + code: Code, + message: String, + cause: Error?, + location: SourceLocation + ) { + self.code = code + self.message = message + self.cause = cause + self.location = location + } + + /// Creates a ``FileSystemError`` by wrapping the given `cause` and its location and code. + internal init(message: String, wrapping cause: FileSystemError) { + self.init(code: cause.code, message: message, cause: cause, location: cause.location) + } +} + +extension FileSystemError: CustomStringConvertible { + public var description: String { + if let cause = self.cause { + return "\(self.code): \(self.message) (\(cause))" + } else { + return "\(self.code): \(self.message)" + } + } +} + +extension FileSystemError: CustomDebugStringConvertible { + public var debugDescription: String { + if let cause = self.cause { + return """ + \(String(reflecting: self.code)): \(String(reflecting: self.message)) \ + (\(String(reflecting: cause))) + """ + } else { + return "\(String(reflecting: self.code)): \(String(reflecting: self.message))" + } + } +} + +extension FileSystemError { + private func detailedDescriptionLines() -> [String] { + // Build up a tree-like description of the error. This allows nested causes to be formatted + // correctly, especially when they are also FileSystemErrors. + // + // An example is: + // + // FileSystemError: Closed + // ├─ Reason: Unable to open file at path 'foo.swift', the descriptor is closed. + // ├─ Cause: 'openat' system call failed with '(9) Bad file descriptor'. + // └─ Source location: openFile(forReadingAt:_:) (FileSystem.swift:314) + var lines = [ + "FileSystemError: \(self.code)", + "├─ Reason: \(self.message)", + ] + + if let error = self.cause as? FileSystemError { + lines.append("├─ Cause:") + let causeLines = error.detailedDescriptionLines() + // We know this will never be empty. + lines.append("│ └─ \(causeLines.first!)") + lines.append(contentsOf: causeLines.dropFirst().map { "│ \($0)" }) + } else if let error = self.cause { + lines.append("├─ Cause: \(String(reflecting: error))") + } + + lines.append( + "└─ Source location: \(self.location.function) (\(self.location.file):\(self.location.line))" + ) + + return lines + } + + /// A detailed multi-line description of the error. + /// + /// - Returns: A multi-line description of the error. + public func detailedDescription() -> String { + self.detailedDescriptionLines().joined(separator: "\n") + } +} + +extension FileSystemError { + /// A high level indication of the kind of error being thrown. + public struct Code: Hashable, Sendable, CustomStringConvertible { + private enum Wrapped: Hashable, Sendable, CustomStringConvertible { + case closed + case invalidArgument + case io + case permissionDenied + case notEmpty + case notFound + case resourceExhausted + case unavailable + case unknown + case unsupported + case fileAlreadyExists + + var description: String { + switch self { + case .closed: + return "Closed" + case .invalidArgument: + return "Invalid argument" + case .io: + return "I/O error" + case .permissionDenied: + return "Permission denied" + case .resourceExhausted: + return "Resource exhausted" + case .notEmpty: + return "Not empty" + case .notFound: + return "Not found" + case .unavailable: + return "Unavailable" + case .unknown: + return "Unknown" + case .unsupported: + return "Unsupported" + case .fileAlreadyExists: + return "File already exists" + } + } + } + + public var description: String { + String(describing: self.code) + } + + private var code: Wrapped + private init(_ code: Wrapped) { + self.code = code + } + + /// An operation on the file could not be performed because the file is closed + /// (or detached). + public static var closed: Self { + Self(.closed) + } + + /// A provided argument was not valid for the operation. + public static var invalidArgument: Self { + Self(.invalidArgument) + } + + /// An I/O error occurred. + public static var io: Self { + Self(.io) + } + + /// The caller did not have sufficient permission to perform the operation. + public static var permissionDenied: Self { + Self(.permissionDenied) + } + + /// A required resource was exhausted. + public static var resourceExhausted: Self { + Self(.resourceExhausted) + } + + /// The directory wasn't empty. + public static var notEmpty: Self { + Self(.notEmpty) + } + + /// The file could not be found. + public static var notFound: Self { + Self(.notFound) + } + + /// The file system is not currently available, for example if the executor + /// is not running. + public static var unavailable: Self { + Self(.unavailable) + } + + /// The error is not known or may not have an appropriate classification. See + /// ``FileSystemError/cause`` for more information about the error. + public static var unknown: Self { + Self(.unknown) + } + + /// The operation is not supported or is not enabled. + public static var unsupported: Self { + Self(.unsupported) + } + + /// The file already exists. + public static var fileAlreadyExists: Self { + Self(.fileAlreadyExists) + } + } + + /// A location within source code. + public struct SourceLocation: Sendable, Hashable { + /// The function in which the error was thrown. + public var function: String + + /// The file in which the error was thrown. + public var file: String + + /// The line on which the error was thrown. + public var line: Int + + public init(function: String, file: String, line: Int) { + self.function = function + self.file = file + self.line = line + } + + internal static func here( + function: String = #function, + file: String = #fileID, + line: Int = #line + ) -> Self { + SourceLocation(function: function, file: file, line: line) + } + } +} + +extension FileSystemError { + /// An error resulting from a system call. + public struct SystemCallError: Error, Hashable, CustomStringConvertible { + /// The name of the system call which produced the error. + public var systemCall: String + /// The errno set by the system call. + public var errno: Errno + + public init(systemCall: String, errno: Errno) { + self.systemCall = systemCall + self.errno = errno + } + + public var description: String { + "'\(self.systemCall)' system call failed with '(\(self.errno.rawValue)) \(self.errno)'." + } + } +} diff --git a/Sources/_NIOFileSystem/FileSystemProtocol.swift b/Sources/_NIOFileSystem/FileSystemProtocol.swift new file mode 100644 index 000000000..6b122f3be --- /dev/null +++ b/Sources/_NIOFileSystem/FileSystemProtocol.swift @@ -0,0 +1,721 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +/// The interface for interacting with a file system. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public protocol FileSystemProtocol: Sendable { + /// The type of ``ReadableFileHandleProtocol`` to return when opening files for reading. + associatedtype ReadFileHandle: ReadableFileHandleProtocol + + /// The type of ``WritableFileHandleProtocol`` to return when opening files for writing. + associatedtype WriteFileHandle: WritableFileHandleProtocol + + /// The type of ``ReadableAndWritableFileHandleProtocol`` to return when opening files for reading and writing. + associatedtype ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol + + /// The type of ``DirectoryFileHandleProtocol`` to return when opening directories. + associatedtype DirectoryFileHandle: DirectoryFileHandleProtocol + where + DirectoryFileHandle.ReadFileHandle == ReadFileHandle, + DirectoryFileHandle.ReadWriteFileHandle == ReadWriteFileHandle, + DirectoryFileHandle.WriteFileHandle == WriteFileHandle + + // MARK: - File access + + /// Opens the file at `path` for reading and returns a handle to it. + /// + /// The file being opened must exist otherwise this function will throw a ``FileSystemError`` + /// with code ``FileSystemError/Code-swift.struct/notFound``. + /// + /// - Parameters: + /// - path: The path of the file to open. + /// - options: How the file should be opened. + /// - Returns: A readable handle to the opened file. + func openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) async throws -> ReadFileHandle + + /// Opens the file at `path` for writing and returns a handle to it. + /// + /// - Parameters: + /// - path: The path of the file to open relative to the open file. + /// - options: How the file should be opened. + /// - Returns: A writable handle to the opened file. + func openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> WriteFileHandle + + /// Opens the file at `path` for reading and writing and returns a handle to it. + /// + /// - Parameters: + /// - path: The path of the file to open relative to the open file. + /// - options: How the file should be opened. + func openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> ReadWriteFileHandle + + /// Opens the directory at `path` and returns a handle to it. + /// + /// The directory being opened must already exist otherwise this function will throw an error. + /// Use ``createDirectory(at:withIntermediateDirectories:permissions:)`` to create directories. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - options: How the directory should be opened. + /// - Returns: A handle to the opened directory. + func openDirectory( + atPath path: FilePath, + options: OpenOptions.Directory + ) async throws -> DirectoryFileHandle + + /// Create a directory at the given path. + /// + /// If a directory (or file) already exists at `path` then an error will be thrown. If + /// `createIntermediateDirectories` is `false` then the full prefix of `path` must already + /// exist. If set to `true` then all intermediate directories will be created. + /// + /// Related system calls: `mkdir(2)`. + /// + /// - Parameters: + /// - path: The directory to create. + /// - createIntermediateDirectories: Whether intermediate directories should be created. + /// - permissions: The permissions to set on the new directory; default permissions will be + /// used if not specified. + func createDirectory( + at path: FilePath, + withIntermediateDirectories createIntermediateDirectories: Bool, + permissions: FilePermissions? + ) async throws + + // MARK: - Common directories + + /// Returns the current working directory. + var currentWorkingDirectory: FilePath { get async throws } + + /// Returns the path of the temporary directory. + var temporaryDirectory: FilePath { get async throws } + + /// Create a temporary directory at the given path, from a template. + /// + /// The template for the path of the temporary directory must end in at least + /// three 'X's, which will be replaced with a unique alphanumeric combination. + /// The template can contain intermediary directories which will be created + /// if they do not exist already. + /// + /// Related system calls: `mkdir(2)`. + /// + /// - Parameters: + /// - template: The template for the path of the temporary directory. + /// - Returns: + /// - The path to the new temporary directory. + func createTemporaryDirectory( + template: FilePath + ) async throws -> FilePath + + // MARK: - File information + + /// Returns information about the file at the given path, if it exists; nil otherwise. + /// + /// - Parameters: + /// - path: The path to get information about. + /// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true` then + /// information about the link will be returned, otherwise information about the + /// destination of the symbolic link is returned. + /// - Returns: Information about the file at the given path or `nil` if no file exists. + func info( + forFileAt path: FilePath, + infoAboutSymbolicLink: Bool + ) async throws -> FileInfo? + + // MARK: - Symbolic links + + /// Creates a symbolic link that points to the destination. + /// + /// If a file or directory exists at `path` then an error is thrown. + /// + /// - Parameters: + /// - path: The path at which to create the symbolic link. + /// - destinationPath: The path that contains the item that the symbolic link points to.` + func createSymbolicLink( + at path: FilePath, + withDestination destinationPath: FilePath + ) async throws + + /// Returns the path of the item pointed to by a symbolic link. + /// + /// - Parameter path: The path of a file or directory. + /// - Returns: The path of the file or directory to which the symbolic link points to. + func destinationOfSymbolicLink( + at path: FilePath + ) async throws -> FilePath + + // MARK: - File copying, removal, and moving + + /// Copies the item at the specified path to a new location. + /// + /// The following error codes may be thrown: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath` + /// exists prior to the copy or its parent directory does not exist. + /// + /// Note that other errors may also be thrown. + /// + /// If `sourcePath` is a symbolic link then only the link is copied. The copied file will + /// preserve permissions and any extended attributes (if supported by the file system). + /// + /// - Parameters: + /// - sourcePath: The path to the item to copy. + /// - destinationPath: The path at which to place the copy. + /// - copyStrategy: How to deal with concurrent aspects of the copy, only relevant to directories. + /// - shouldProceedAfterError: A closure which is executed to determine whether to continue + /// copying files if an error is encountered during the operation. See Errors section for full details. + /// - shouldCopyItem: A closure which is executed before each copy to determine whether each + /// item should be copied. See Filtering section for full details + /// + /// #### Errors + /// + /// No errors should be throw by implementors without first calling `shouldProceedAfterError`, + /// if that returns without throwing this is taken as permission to continue and the error is swallowed. + /// If instead the closure throws then ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// will throw and copying will stop, though the precise semantics of this can depend on the `strategy`. + /// + /// if using ``CopyStrategy/parallel(maxDescriptors:)`` + /// Already started work may continue for an indefinite period of time. In particular, after throwing an error + /// it is possible that invocations of `shouldCopyItem` may continue to occur! + /// + /// If using ``CopyStrategy/sequential`` only one invocation of any of the `should*` closures will occur at a time, + /// and an error will immediately stop further activity. + /// + /// The specific error thrown from copyItem is undefined, it does not have to be the same error thrown from + /// `shouldProceedAfterError`. + /// In the event of any errors (ignored or otherwise) implementations are under no obbligation to + /// attempt to 'tidy up' after themselves. The state of the file system within `destinationPath` + /// after an aborted copy should is undefined. + /// + /// When calling `shouldProceedAfterError` implementations of this method + /// MUST: + /// - Do so once and only once per item. + /// - Not hold any locks when doing so. + /// MAY: + /// - invoke the function multiple times concurrently (except when using ``CopyStrategy/sequential``) + /// + /// #### Filtering + /// + /// When invoking `shouldCopyItem` implementations of this method + /// MUST: + /// - Do so once and only once per item. + /// - Do so before attempting any operations related to the copy (including determining if they can do so). + /// - Not hold any locks when doing so. + /// - Check parent directories *before* items within them, + /// * if a parent is ignored no items within it should be considered or checked + /// - Skip all contents of a directory which is filtered out. + /// - Invoke it for the `sourcePath` itself. + /// MAY: + /// - invoke the function multiple times concurrently (except when using ``CopyStrategy/sequential``) + /// - invoke the function an arbitrary point before actually trying to copy the file + func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy, + shouldProceedAfterError: @escaping @Sendable ( + _ source: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws + + /// Deletes the file or directory (and its contents) at `path`. + /// + /// The item to be removed must be a regular file, symbolic link or directory. If no file exists + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory and `removeItemRecursively` is `true` then the + /// contents of all of its subdirectories will be removed recursively before the directory at + /// `path`. Symbolic links are removed (but their targets are not deleted). + /// + /// - Parameters: + /// - path: The path to delete. + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. Ignored if + /// the item being removed isn't a directory. + /// - removeItemRecursively: If the item being removed is a directory, remove it by + /// recursively removing its children. Setting this to `true` is synonymous with calling + /// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item + /// being removed isn't a directory. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + func removeItem( + at path: FilePath, + strategy removalStrategy: RemovalStrategy, + recursively removeItemRecursively: Bool + ) async throws -> Int + + /// Moves the file or directory at the specified path to a new location. + /// + /// The following error codes may be thrown: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath` + /// exists prior to the copy or its parent directory does not exist. + /// + /// Note that other errors may also be thrown. + /// + /// If the file at `sourcePath` is a symbolic link then only the link is moved to the new path. + /// + /// - Parameters: + /// - sourcePath: The path to the item to move. + /// - destinationPath: The path at which to place the item. + func moveItem(at sourcePath: FilePath, to destinationPath: FilePath) async throws + + /// Replaces the item at `destinationPath` with the item at `existingPath`. + /// + /// The following error codes may be thrown: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `existingPath` does + /// not exist, + /// - ``FileSystemError/Code-swift.struct/io`` if the file at `existingPath` was successfully + /// copied to `destinationPath` but an error occurred while removing it from `existingPath.` + /// + /// Note that other errors may also be thrown. + /// + /// The item at `destinationPath` is not required to exist. Note that it is possible to replace + /// a file with a directory and vice versa. After the file or directory at `destinationPath` + /// has been replaced, the item at `existingPath` will be removed. + /// + /// - Parameters: + /// - destinationPath: The path of the file or directory to replace. + /// - existingPath: The path of the existing file or directory. + func replaceItem(at destinationPath: FilePath, withItemAt existingPath: FilePath) async throws +} + +// MARK: - Open existing files/directories + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystemProtocol { + /// Opens the file at the given path and provides scoped read-only access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the call returns. Files may also be opened in read-write or write-only + /// mode by calling ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` and + /// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka``. + /// + /// - Parameters: + /// - path: The path of the file to open for reading. + /// - options: How the file should be opened. + /// - execute: A closure which provides read-only access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forReadingAt path: FilePath, + options: OpenOptions.Read = OpenOptions.Read(), + execute: (_ read: ReadFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forReadingAt: path, options: options) + return try await withUncancellableTearDown { + try await execute(handle) + } tearDown: { _ in + try await handle.close() + } + } + + /// Opens the file at the given path and provides scoped write-only access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the call returns. Files may also be opened in read-write or read-only + /// mode by calling ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` and + /// ``FileSystemProtocol/withFileHandle(forReadingAt:options:execute:)-nsue``. + /// + /// - Parameters: + /// - path: The path of the file to open for reading. + /// - options: How the file should be opened. + /// - execute: A closure which provides write-only access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forWritingAt path: FilePath, + options: OpenOptions.Write = .newFile(replaceExisting: false), + execute: (_ write: WriteFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forWritingAt: path, options: options) + return try await withUncancellableTearDown { + try await execute(handle) + } tearDown: { result in + switch result { + case .success: + try await handle.close() + case .failure: + try await handle.close(makeChangesVisible: false) + } + } + } + + /// Opens the file at the given path and provides scoped read-write access to it. + /// + /// The file remains open during lifetime of the `execute` block and will be closed + /// automatically before the function returns. Files may also be opened in read-only or + /// write-only mode by with ``FileSystemProtocol/withFileHandle(forReadingAt:options:execute:)-nsue`` and + /// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka``. + /// + /// - Parameters: + /// - path: The path of the file to open for reading and writing. + /// - options: How the file should be opened. + /// - execute: A closure which provides access to the open file. The file is closed + /// automatically after the closure exits. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withFileHandle( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write = .newFile(replaceExisting: false), + execute: (_ readWrite: ReadWriteFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openFile(forReadingAndWritingAt: path, options: options) + return try await withUncancellableTearDown { + try await execute(handle) + } tearDown: { _ in + try await handle.close() + } + } + + /// Opens the directory at the given path and provides scoped access to it. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - options: How the file should be opened. + /// - execute: A closure which provides access to the directory. + /// - Important: The handle passed to `execute` must not escape the closure. + /// - Returns: The result of the `execute` closure. + public func withDirectoryHandle( + atPath path: FilePath, + options: OpenOptions.Directory = OpenOptions.Directory(), + execute: (_ directory: DirectoryFileHandle) async throws -> Result + ) async throws -> Result { + let handle = try await self.openDirectory(atPath: path, options: options) + return try await withUncancellableTearDown { + try await execute(handle) + } tearDown: { _ in + try await handle.close() + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystemProtocol { + /// Opens the file at `path` for reading and returns a handle to it. + /// + /// The file being opened must exist otherwise this function will throw a ``FileSystemError`` + /// with code ``FileSystemError/Code-swift.struct/notFound``. + /// + /// - Parameters: + /// - path: The path of the file to open. + /// - Returns: A readable handle to the opened file. + public func openFile( + forReadingAt path: FilePath + ) async throws -> ReadFileHandle { + try await self.openFile(forReadingAt: path, options: OpenOptions.Read()) + } + + /// Opens the directory at `path` and returns a handle to it. + /// + /// The directory being opened must already exist otherwise this function will throw an error. + /// Use ``createDirectory(at:withIntermediateDirectories:permissions:)`` to create directories. + /// + /// - Parameters: + /// - path: The path of the directory to open. + /// - Returns: A handle to the opened directory. + public func openDirectory( + atPath path: FilePath + ) async throws -> DirectoryFileHandle { + try await self.openDirectory(atPath: path, options: OpenOptions.Directory()) + } + + /// Returns information about the file at the given path, if it exists; nil otherwise. + /// + /// Calls ``info(forFileAt:infoAboutSymbolicLink:)`` setting `infoAboutSymbolicLink` to `false`. + /// + /// - Parameters: + /// - path: The path to get information about. + /// - Returns: Information about the file at the given path or `nil` if no file exists. + public func info(forFileAt path: FilePath) async throws -> FileInfo? { + try await self.info(forFileAt: path, infoAboutSymbolicLink: false) + } + + /// Copies the item at the specified path to a new location. + /// + /// The following error codes may be thrown: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath` + /// exists prior to the copy or its parent directory does not exist. + /// + /// Note that other errors may also be thrown. If any error is encountered during the copy + /// then the copy is aborted. You can modify the behaviour with the `shouldProceedAfterError` + /// parameter of ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``. + /// + /// If the file at `sourcePath` is a symbolic link then only the link is copied to the new path. + /// + /// - Parameters: + /// - sourcePath: The path to the item to copy. + /// - destinationPath: The path at which to place the copy. + /// - copyStrategy: This controls the concurrency used if the file at `sourcePath` is a directory. + public func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy = .platformDefault + ) async throws { + try await self.copyItem(at: sourcePath, to: destinationPath, strategy: copyStrategy) { path, error in + throw error + } shouldCopyItem: { source, destination in + true + } + } + + /// Copies the item at the specified path to a new location. + /// + /// The item to be copied must be a: + /// - regular file, + /// - symbolic link, or + /// - directory. + /// + /// If `sourcePath` is a symbolic link then only the link is copied. The copied file will + /// preserve permissions and any extended attributes (if supported by the file system). + /// + /// #### Errors + /// + /// Error codes thrown include: + /// - ``FileSystemError/Code-swift.struct/notFound`` if `sourcePath` doesn't exist. + /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if `destinationPath` exists. + /// + /// #### Backward Compatibility details + /// + /// This is implemented in terms of ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// using ``CopyStrategy/sequential`` to avoid changing the concurrency semantics of the should callbacks + /// + /// - Parameters: + /// - sourcePath: The path to the item to copy. + /// - destinationPath: The path at which to place the copy. + /// - shouldProceedAfterError: Determines whether to continue copying files if an error is + /// thrown during the operation. This error does not have to match the error passed + /// to the closure. + /// - shouldCopyFile: A closure which is executed before each file to determine whether the + /// file should be copied. + @available(*, deprecated, message: "please use copyItem overload taking CopyStrategy") + public func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + shouldProceedAfterError: @escaping @Sendable ( + _ entry: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyFile: @escaping @Sendable ( + _ source: FilePath, + _ destination: FilePath + ) async -> Bool + ) async throws { + try await self.copyItem( + at: sourcePath, + to: destinationPath, + strategy: .sequential, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: { (source, destination) in + await shouldCopyFile(source.path, destination) + } + ) + } + + /// Copies the item at the specified path to a new location. + /// + /// The following error codes may be thrown: + /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath` + /// exists prior to the copy or its parent directory does not exist. + /// + /// Note that other errors may also be thrown. + /// + /// If `sourcePath` is a symbolic link then only the link is copied. The copied file will + /// preserve permissions and any extended attributes (if supported by the file system). + /// + /// - Parameters: + /// - sourcePath: The path to the item to copy. + /// - destinationPath: The path at which to place the copy. + /// - shouldProceedAfterError: A closure which is executed to determine whether to continue + /// copying files if an error is encountered during the operation. See Errors section for full details. + /// - shouldCopyItem: A closure which is executed before each copy to determine whether each + /// item should be copied. See Filtering section for full details + /// + /// #### Parallelism + /// + /// This overload uses ``CopyStrategy/platformDefault`` which is likely to result in multiple concurrency domains being used + /// in the event of copying a directory. + /// See the detailed description on ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// for the implications of this with respect to the `shouldProceedAfterError` and `shouldCopyItem` callbacks + public func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + shouldProceedAfterError: @escaping @Sendable ( + _ source: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + try await self.copyItem( + at: sourcePath, + to: destinationPath, + strategy: .platformDefault, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + } + + /// Deletes the file or directory (and its contents) at `path`. + /// + /// The item to be removed must be a regular file, symbolic link or directory. If no file exists + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// The strategy for deletion will be determined automatically depending on the discovered + /// platform. + /// + /// - Parameters: + /// - path: The path to delete. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath + ) async throws -> Int { + try await self.removeItem(at: path, strategy: .platformDefault, recursively: true) + } + + /// Deletes the file or directory (and its contents) at `path`. + /// + /// The item to be removed must be a regular file, symbolic link or directory. If no file exists + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// The strategy for deletion will be determined automatically depending on the discovered + /// platform. + /// + /// - Parameters: + /// - path: The path to delete. + /// - removeItemRecursively: If the item being removed is a directory, remove it by + /// recursively removing its children. Setting this to `true` is synonymous with calling + /// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item + /// being removed isn't a directory. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath, + recursively removeItemRecursively: Bool + ) async throws -> Int { + try await self.removeItem(at: path, strategy: .platformDefault, recursively: removeItemRecursively) + } + + /// Deletes the file or directory (and its contents) at `path`. + /// + /// The item to be removed must be a regular file, symbolic link or directory. If no file exists + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// - Parameters: + /// - path: The path to delete. + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath, + strategy removalStrategy: RemovalStrategy + ) async throws -> Int { + try await self.removeItem(at: path, strategy: removalStrategy, recursively: true) + } + + /// Create a directory at the given path. + /// + /// If a directory (or file) already exists at `path` then an error will be thrown. If + /// `createIntermediateDirectories` is `false` then the full prefix of `path` must already + /// exist. If set to `true` then all intermediate directories will be created. + /// + /// New directories will be given read-write-execute owner permissions and read-execute group + /// and other permissions. + /// + /// Related system calls: `mkdir(2)`. + /// + /// - Parameters: + /// - path: The directory to create. + /// - createIntermediateDirectories: Whether intermediate directories should be created. + public func createDirectory( + at path: FilePath, + withIntermediateDirectories createIntermediateDirectories: Bool + ) async throws { + try await self.createDirectory( + at: path, + withIntermediateDirectories: createIntermediateDirectories, + permissions: .defaultsForDirectory + ) + } + + /// Create a temporary directory and removes it once the function returns. + /// + /// You can use `prefix` to specify the directory in which the temporary directory should + /// be created. If `prefix` is `nil` then the value of ``temporaryDirectory`` is used as + /// the prefix. + /// + /// The temporary directory, and all of its contents, is removed once `execute` returns. + /// + /// - Parameters: + /// - prefix: The prefix to use for the path of the temporary directory. + /// - options: Options used to create the directory. + /// - execute: A closure which provides access to the directory and its path. + /// - Returns: The result of `execute`. + public func withTemporaryDirectory( + prefix: FilePath? = nil, + options: OpenOptions.Directory = OpenOptions.Directory(), + execute: (_ directory: DirectoryFileHandle, _ path: FilePath) async throws -> Result + ) async throws -> Result { + let template: FilePath + + if let prefix = prefix { + template = prefix.appending("XXXXXXXX") + } else { + template = try await self.temporaryDirectory.appending("XXXXXXXX") + } + + let directory = try await self.createTemporaryDirectory(template: template) + return try await withUncancellableTearDown { + try await withDirectoryHandle(atPath: directory, options: options) { handle in + try await execute(handle, directory) + } + } tearDown: { _ in + try await self.removeItem(at: directory, strategy: .platformDefault, recursively: true) + } + } +} diff --git a/Sources/_NIOFileSystem/FileType.swift b/Sources/_NIOFileSystem/FileType.swift new file mode 100644 index 000000000..ba0c63407 --- /dev/null +++ b/Sources/_NIOFileSystem/FileType.swift @@ -0,0 +1,171 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +#elseif canImport(Musl) +@preconcurrency import Musl +#elseif canImport(Android) +@preconcurrency import Android +#endif + +/// The type of a file system object. +public struct FileType: Hashable, Sendable { + internal enum Wrapped: Hashable, Sendable, CaseIterable { + case regular + case block + case character + case fifo + case directory + case symlink + case socket + case whiteout + case unknown + } + + internal let wrapped: Wrapped + private init(_ wrapped: Wrapped) { + self.wrapped = wrapped + } +} + +extension FileType { + /// Regular file. + public static var regular: Self { Self(.regular) } + + /// Directory. + public static var directory: Self { Self(.directory) } + + /// Symbolic link. + public static var symlink: Self { Self(.symlink) } + + /// Hardware block device. + public static var block: Self { Self(.block) } + + /// Hardware character device. + public static var character: Self { Self(.character) } + + /// FIFO (or named pipe). + public static var fifo: Self { Self(.fifo) } + + /// Socket. + public static var socket: Self { Self(.socket) } + + /// Whiteout file. + public static var whiteout: Self { Self(.whiteout) } + + /// A file of unknown type. + public static var unknown: Self { Self(.unknown) } +} + +extension FileType: CustomStringConvertible { + public var description: String { + switch self.wrapped { + case .regular: + return "regular" + case .block: + return "block" + case .character: + return "character" + case .fifo: + return "fifo" + case .directory: + return "directory" + case .symlink: + return "symlink" + case .socket: + return "socket" + case .whiteout: + return "whiteout" + case .unknown: + return "unknown" + } + } +} + +extension FileType: CaseIterable { + public static var allCases: [FileType] { + Self.Wrapped.allCases.map { FileType($0) } + } +} + +extension FileType { + /// Initializes a file type from a `CInterop.Mode`. + /// + /// Note: an appropriate mask is applied to `mode`. + public init(platformSpecificMode: CInterop.Mode) { + // See: `man 2 stat` + switch platformSpecificMode & S_IFMT { + case S_IFIFO: + self = .fifo + case S_IFCHR: + self = .character + case S_IFDIR: + self = .directory + case S_IFBLK: + self = .block + case S_IFREG: + self = .regular + case S_IFLNK: + self = .symlink + case S_IFSOCK: + self = .socket + #if canImport(Darwin) + case S_IFWHT: + self = .whiteout + #endif + default: + self = .unknown + } + } + + /// Initializes a file type from the `d_type` from `dirent`. + @_spi(Testing) + public init(direntType: UInt8) { + #if canImport(Darwin) || canImport(Musl) || os(Android) + let value = Int32(direntType) + #elseif canImport(Glibc) + let value = Int(direntType) + #endif + + switch value { + case DT_FIFO: + self = .fifo + case DT_CHR: + self = .character + case DT_DIR: + self = .directory + case DT_BLK: + self = .block + case DT_REG: + self = .regular + case DT_LNK: + self = .symlink + case DT_SOCK: + self = .socket + #if canImport(Darwin) + case DT_WHT: + self = .whiteout + #endif + case DT_UNKNOWN: + self = .unknown + default: + self = .unknown + } + } +} diff --git a/Sources/_NIOFileSystem/IOStrategy.swift b/Sources/_NIOFileSystem/IOStrategy.swift new file mode 100644 index 000000000..4c88476aa --- /dev/null +++ b/Sources/_NIOFileSystem/IOStrategy.swift @@ -0,0 +1,184 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +/// How many file descriptors to open when performing I/O operations. +enum IOStrategy: Hashable, Sendable { + // platformDefault is reified into one of the concrete options below: + case sequential + case parallel(_ maxDescriptors: Int) + + // These selections are relatively arbitrary but the rationale is as follows: + // + // - Never exceed the default OS limits even if 4 such operations were happening at once. + // - Sufficient to enable significant speed up from parallelism + // - Not wasting effort by pushing contention to the storage device. Further we + // assume an SSD or similar storage tech. Users on spinning rust need to account + // for that themselves anyway. + // + // That said, empirical testing for this has not been performed, suggestions welcome. + // + // Note: The directory scan is modelled after a copy strategy needing two handles: during the + // creation of the destination directory we hold the handle while copying attributes. A much + // more complex internal state machine could allow doing two of these if desired. This may not + // result in a faster copy though so things are left simple. + internal static func determinePlatformDefault() -> Self { + #if os(macOS) || os(Linux) || os(Windows) + // Eight file descriptors allow for four concurrent file copies/directory scans. Avoiding + // storage system contention is of utmost importance. + // + // Testing was performed on an SSD, while copying objects (a dense directory of small files + // and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed + // improvements in elapsed time for (expected) increases in CPU time up to parallel(8). + // Beyond this, the increases in CPU led to only moderate gains. + // + // Anyone tuning this is encouraged to cover worst case scenarios. + return .parallel(8) + #elseif (canImport(Darwin) && !os(macOS)) || os(Android) + // Reduced maximum descriptors in embedded world. This is chosen based on biasing towards + // safety, not empirical testing. + return .parallel(4) + #else + // Safety first. If we do not know what system we run on, we keep it simple. + return .sequential + #endif + } +} + +/// How to perform copies. Currently only relevant to directory level copies when using +/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other +/// overloads that use the default behaviour. +public struct CopyStrategy: Hashable, Sendable { + internal let wrapped: IOStrategy + private init(_ strategy: IOStrategy) { + switch strategy { + case .sequential: + self.wrapped = .sequential + case let .parallel(maxDescriptors): + self.wrapped = .parallel(maxDescriptors) + } + } + + // A copy fundamentally can't work without two descriptors unless you copy everything into + // memory which is infeasible/inefficient for large copies. + private static let minDescriptorsAllowed = 2 + + /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit + /// the maximum file descriptors usage based on reasonable defaults. + /// + /// Current assumptions (which are subject to change): + /// - Only one copy operation would be performed at once + /// - The copy operation is not intended to be the primary activity on the device + public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault()) + + /// The copy is done asynchronously, but only one operation will occur at a time. This is the + /// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time. + public static let sequential: Self = Self(.sequential) + + /// Allow multiple I/O operations to run concurrently, including file copies/directory creation + /// and scanning. + /// + /// - Parameter maxDescriptors: a conservative limit on the number of concurrently open file + /// descriptors involved in the copy. This number must be >= 2 though, if you are using a + /// value that low you should use ``sequential`` + /// + /// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` is less + /// than 2. + /// + public static func parallel(maxDescriptors: Int) throws -> Self { + guard maxDescriptors >= Self.minDescriptorsAllowed else { + // 2 is not quite the same as sequential, you could have two concurrent directory + // listings for example less than 2 and you can't actually do a _copy_ though so it's + // non-sensical. + throw FileSystemError( + code: .invalidArgument, + message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal", + cause: nil, + location: .here() + ) + } + return .init(.parallel(maxDescriptors)) + } +} + +extension CopyStrategy: CustomStringConvertible { + public var description: String { + switch self.wrapped { + case .sequential: + return "sequential" + case let .parallel(maxDescriptors): + return "parallel with max \(maxDescriptors) descriptors" + } + } +} + +/// How to perform file deletions. Currently only relevant to directory level deletions when using +/// ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` or other overloads that use the +/// default behaviour. +public struct RemovalStrategy: Hashable, Sendable { + internal let wrapped: IOStrategy + private init(_ strategy: IOStrategy) { + switch strategy { + case .sequential: + self.wrapped = .sequential + case let .parallel(maxDescriptors): + self.wrapped = .parallel(maxDescriptors) + } + } + + // A deletion requires no file descriptors. We only consume a file descriptor while scanning the + // contents of a directory, so the minimum is 1. + private static let minRequiredDescriptors = 1 + + /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit + /// the maximum file descriptors usage based on reasonable defaults. + /// + /// Current assumptions (which are subject to change): + /// - Only one delete operation would be performed at once + /// - The delete operation is not intended to be the primary activity on the device + public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault()) + + /// Traversal of directories and removal of files will be done sequentially without any + /// parallelization. + public static let sequential: Self = Self(.sequential) + + /// Allow for one or more directory scans to run at the same time. Removal of files will happen + /// on asynchronous tasks in parallel. + /// + /// Setting `maxDescriptors` to 1, will limit the speed of directory discovery. Deletion of + /// files within that directory will run in parallel, but discovery of subdirectories will be + /// limited to one at a time. + public static func parallel(maxDescriptors: Int) throws -> Self { + guard maxDescriptors >= Self.minRequiredDescriptors else { + throw FileSystemError( + code: .invalidArgument, + message: + "Can't do a remove operation without at least one file descriptor '\(maxDescriptors)' is illegal", + cause: nil, + location: .here() + ) + } + return .init(.parallel(maxDescriptors)) + } +} + +extension RemovalStrategy: CustomStringConvertible { + public var description: String { + switch self.wrapped { + case .sequential: + return "sequential" + case let .parallel(maxDescriptors): + return "parallel with max \(maxDescriptors) descriptors" + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/BufferedOrAnyStream.swift b/Sources/_NIOFileSystem/Internal/BufferedOrAnyStream.swift new file mode 100644 index 000000000..7e307a160 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/BufferedOrAnyStream.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +/// Wraps a ``NIOThrowingAsyncSequenceProducer`` or ``AnyAsyncSequence``. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +internal enum BufferedOrAnyStream: Sendable { + typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer< + Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate + > + + case nioThrowingAsyncSequenceProducer(AsyncSequenceProducer) + case anyAsyncSequence(AnyAsyncSequence) + + internal init(wrapping stream: AsyncSequenceProducer) { + self = .nioThrowingAsyncSequenceProducer(stream) + } + + internal init(wrapping stream: S) + where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype { + self = .anyAsyncSequence(AnyAsyncSequence(wrapping: stream)) + } + + internal func makeAsyncIterator() -> AsyncIterator { + switch self { + case let .nioThrowingAsyncSequenceProducer(stream): + return AsyncIterator(wrapping: stream.makeAsyncIterator()) + case let .anyAsyncSequence(stream): + return AsyncIterator(wrapping: stream.makeAsyncIterator()) + } + } + + internal enum AsyncIterator: AsyncIteratorProtocol { + case bufferedStream(AsyncSequenceProducer.AsyncIterator) + case anyAsyncSequence(AnyAsyncSequence.AsyncIterator) + + internal mutating func next() async throws -> Element? { + let element: Element? + switch self { + case let .bufferedStream(iterator): + defer { self = .bufferedStream(iterator) } + element = try await iterator.next() + case var .anyAsyncSequence(iterator): + defer { self = .anyAsyncSequence(iterator) } + element = try await iterator.next() + } + return element + } + + internal init(wrapping iterator: AsyncSequenceProducer.AsyncIterator) { + self = .bufferedStream(iterator) + } + + internal init(wrapping iterator: AnyAsyncSequence.AsyncIterator) { + self = .anyAsyncSequence(iterator) + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +internal struct AnyAsyncSequence: AsyncSequence, Sendable { + private let _makeAsyncIterator: @Sendable () -> AsyncIterator + + internal init(wrapping sequence: S) + where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype { + self._makeAsyncIterator = { + AsyncIterator(wrapping: sequence.makeAsyncIterator()) + } + } + + internal func makeAsyncIterator() -> AsyncIterator { + self._makeAsyncIterator() + } + + internal struct AsyncIterator: AsyncIteratorProtocol, _NIOFileSystemSendableMetatype { + private var iterator: any AsyncIteratorProtocol + + init(wrapping iterator: I) where I.Element == Element { + self.iterator = iterator + } + + internal mutating func next() async throws -> Element? { + try await self.iterator.next() as? Element + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/BufferedStream.swift b/Sources/_NIOFileSystem/Internal/BufferedStream.swift new file mode 100644 index 000000000..21fa48949 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/BufferedStream.swift @@ -0,0 +1,1732 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import DequeModule +import NIOConcurrencyHelpers + +/// An asynchronous sequence generated from an error-throwing closure that +/// calls a continuation to produce new elements. +/// +/// `BufferedStream` conforms to `AsyncSequence`, providing a convenient +/// way to create an asynchronous sequence without manually implementing an +/// asynchronous iterator. In particular, an asynchronous stream is well-suited +/// to adapt callback- or delegation-based APIs to participate with +/// `async`-`await`. +/// +/// In contrast to `AsyncStream`, this type can throw an error from the awaited +/// `next()`, which terminates the stream with the thrown error. +/// +/// You initialize an `BufferedStream` with a closure that receives an +/// `BufferedStream.Continuation`. Produce elements in this closure, then +/// provide them to the stream by calling the continuation's `yield(_:)` method. +/// When there are no further elements to produce, call the continuation's +/// `finish()` method. This causes the sequence iterator to produce a `nil`, +/// which terminates the sequence. If an error occurs, call the continuation's +/// `finish(throwing:)` method, which causes the iterator's `next()` method to +/// throw the error to the awaiting call point. The continuation is `Sendable`, +/// which permits calling it from concurrent contexts external to the iteration +/// of the `BufferedStream`. +/// +/// An arbitrary source of elements can produce elements faster than they are +/// consumed by a caller iterating over them. Because of this, `BufferedStream` +/// defines a buffering behavior, allowing the stream to buffer a specific +/// number of oldest or newest elements. By default, the buffer limit is +/// `Int.max`, which means it's unbounded. +/// +/// ### Adapting Existing Code to Use Streams +/// +/// To adapt existing callback code to use `async`-`await`, use the callbacks +/// to provide values to the stream, by using the continuation's `yield(_:)` +/// method. +/// +/// Consider a hypothetical `QuakeMonitor` type that provides callers with +/// `Quake` instances every time it detects an earthquake. To receive callbacks, +/// callers set a custom closure as the value of the monitor's +/// `quakeHandler` property, which the monitor calls back as necessary. Callers +/// can also set an `errorHandler` to receive asynchronous error notifications, +/// such as the monitor service suddenly becoming unavailable. +/// +/// class QuakeMonitor { +/// var quakeHandler: ((Quake) -> Void)? +/// var errorHandler: ((Error) -> Void)? +/// +/// func startMonitoring() {…} +/// func stopMonitoring() {…} +/// } +/// +/// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a +/// `quakes` property, of type `BufferedStream`. In the getter for +/// this property, return an `BufferedStream`, whose `build` closure -- +/// called at runtime to create the stream -- uses the continuation to +/// perform the following steps: +/// +/// 1. Creates a `QuakeMonitor` instance. +/// 2. Sets the monitor's `quakeHandler` property to a closure that receives +/// each `Quake` instance and forwards it to the stream by calling the +/// continuation's `yield(_:)` method. +/// 3. Sets the monitor's `errorHandler` property to a closure that receives +/// any error from the monitor and forwards it to the stream by calling the +/// continuation's `finish(throwing:)` method. This causes the stream's +/// iterator to throw the error and terminate the stream. +/// 4. Sets the continuation's `onTermination` property to a closure that +/// calls `stopMonitoring()` on the monitor. +/// 5. Calls `startMonitoring` on the `QuakeMonitor`. +/// +/// ``` +/// extension QuakeMonitor { +/// +/// static var throwingQuakes: BufferedStream { +/// BufferedStream { continuation in +/// let monitor = QuakeMonitor() +/// monitor.quakeHandler = { quake in +/// continuation.yield(quake) +/// } +/// monitor.errorHandler = { error in +/// continuation.finish(throwing: error) +/// } +/// continuation.onTermination = { @Sendable _ in +/// monitor.stopMonitoring() +/// } +/// monitor.startMonitoring() +/// } +/// } +/// } +/// ``` +/// +/// +/// Because the stream is an `AsyncSequence`, the call point uses the +/// `for`-`await`-`in` syntax to process each `Quake` instance as produced by the stream: +/// +/// do { +/// for try await quake in quakeStream { +/// print("Quake: \(quake.date)") +/// } +/// print("Stream done.") +/// } catch { +/// print("Error: \(error)") +/// } +/// +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +internal struct BufferedStream { + final class _Backing: Sendable { + let storage: _BackPressuredStorage + + init(storage: _BackPressuredStorage) { + self.storage = storage + } + + deinit { + self.storage.sequenceDeinitialized() + } + } + + enum _Implementation: Sendable { + /// This is the implementation with backpressure based on the Source + case backpressured(_Backing) + } + + let implementation: _Implementation +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream: AsyncSequence { + /// The asynchronous iterator for iterating an asynchronous stream. + /// + /// This type is not `Sendable`. Don't use it from multiple + /// concurrent contexts. It is a programmer error to invoke `next()` from a + /// concurrent context that contends with another such call, which + /// results in a call to `fatalError()`. + internal struct Iterator: AsyncIteratorProtocol { + final class _Backing { + let storage: _BackPressuredStorage + + init(storage: _BackPressuredStorage) { + self.storage = storage + self.storage.iteratorInitialized() + } + + deinit { + self.storage.iteratorDeinitialized() + } + } + enum _Implementation { + /// This is the implementation with backpressure based on the Source + case backpressured(_Backing) + } + + var implementation: _Implementation + + /// The next value from the asynchronous stream. + /// + /// When `next()` returns `nil`, this signifies the end of the + /// `BufferedStream`. + /// + /// It is a programmer error to invoke `next()` from a concurrent context + /// that contends with another such call, which results in a call to + /// `fatalError()`. + /// + /// If you cancel the task this iterator is running in while `next()` is + /// awaiting a value, the `BufferedStream` terminates. In this case, + /// `next()` may return `nil` immediately, or else return `nil` on + /// subsequent calls. + internal mutating func next() async throws -> Element? { + switch self.implementation { + case .backpressured(let backing): + return try await backing.storage.next() + } + } + } + + /// Creates the asynchronous iterator that produces elements of this + /// asynchronous sequence. + internal func makeAsyncIterator() -> Iterator { + switch self.implementation { + case .backpressured(let backing): + return Iterator(implementation: .backpressured(.init(storage: backing.storage))) + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream: Sendable {} + +internal struct _ManagedCriticalState: @unchecked Sendable { + let lock: NIOLockedValueBox + + internal init(_ initial: State) { + self.lock = .init(initial) + } + + internal func withCriticalRegion( + _ critical: (inout State) throws -> R + ) rethrows -> R { + try self.lock.withLockedValue(critical) + } +} + +internal struct AlreadyFinishedError: Error {} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream { + /// A mechanism to interface between producer code and an asynchronous stream. + /// + /// Use this source to provide elements to the stream by calling one of the `write` methods, then terminate the stream normally + /// by calling the `finish()` method. You can also use the source's `finish(throwing:)` method to terminate the stream by + /// throwing an error. + internal struct Source: Sendable { + /// A strategy that handles the backpressure of the asynchronous stream. + internal struct BackPressureStrategy: Sendable { + /// When the high watermark is reached producers will be suspended. All producers will be resumed again once + /// the low watermark is reached. + internal static func watermark(low: Int, high: Int) -> BackPressureStrategy { + BackPressureStrategy( + internalBackPressureStrategy: .watermark(.init(low: low, high: high)) + ) + } + + private init(internalBackPressureStrategy: _InternalBackPressureStrategy) { + self._internalBackPressureStrategy = internalBackPressureStrategy + } + + fileprivate let _internalBackPressureStrategy: _InternalBackPressureStrategy + } + + /// A type that indicates the result of writing elements to the source. + internal enum WriteResult: Sendable { + /// A token that is returned when the asynchronous stream's backpressure strategy indicated that production should + /// be suspended. Use this token to enqueue a callback by calling the ``enqueueCallback(_:)`` method. + internal struct CallbackToken: Sendable { + let id: UInt + } + + /// Indicates that more elements should be produced and written to the source. + case produceMore + + /// Indicates that a callback should be enqueued. + /// + /// The associated token should be passed to the ``enqueueCallback(_:)`` method. + case enqueueCallback(CallbackToken) + } + + /// Backing class for the source used to hook a deinit. + final class _Backing: Sendable { + let storage: _BackPressuredStorage + + init(storage: _BackPressuredStorage) { + self.storage = storage + } + + deinit { + self.storage.sourceDeinitialized() + } + } + + /// A callback to invoke when the stream finished. + /// + /// The stream finishes and calls this closure in the following cases: + /// - No iterator was created and the sequence was deinited + /// - An iterator was created and deinited + /// - After ``finish(throwing:)`` was called and all elements have been consumed + /// - The consuming task got cancelled + internal var onTermination: (@Sendable () -> Void)? { + set { + self._backing.storage.onTermination = newValue + } + get { + self._backing.storage.onTermination + } + } + + private var _backing: _Backing + + internal init(storage: _BackPressuredStorage) { + self._backing = .init(storage: storage) + } + + /// Writes new elements to the asynchronous stream. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error + /// indicating the failure. + /// + /// - Parameter sequence: The elements to write to the asynchronous stream. + /// - Returns: The result that indicates if more elements should be produced at this time. + internal func write(contentsOf sequence: S) throws -> WriteResult + where Element == S.Element, S: Sequence, Element: Sendable { + try self._backing.storage.write(contentsOf: sequence) + } + + /// Write the element to the asynchronous stream. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// provided element. If the asynchronous stream already terminated then this method will throw an error + /// indicating the failure. + /// + /// - Parameter element: The element to write to the asynchronous stream. + /// - Returns: The result that indicates if more elements should be produced at this time. + internal func write(_ element: Element) throws -> WriteResult { + try self._backing.storage.write(contentsOf: CollectionOfOne(element)) + } + + /// Enqueues a callback that will be invoked once more elements should be produced. + /// + /// Call this method after ``write(contentsOf:)`` or ``write(:)`` returned ``WriteResult/enqueueCallback(_:)``. + /// + /// - Important: Enqueueing the same token multiple times is not allowed. + /// + /// - Parameters: + /// - callbackToken: The callback token. + /// - onProduceMore: The callback which gets invoked once more elements should be produced. + internal func enqueueCallback( + callbackToken: WriteResult.CallbackToken, + onProduceMore: @escaping @Sendable (Result) -> Void + ) { + self._backing.storage.enqueueProducer( + callbackToken: callbackToken, + onProduceMore: onProduceMore + ) + } + + /// Cancel an enqueued callback. + /// + /// Call this method to cancel a callback enqueued by the ``enqueueCallback(callbackToken:onProduceMore:)`` method. + /// + /// - Note: This methods supports being called before ``enqueueCallback(callbackToken:onProduceMore:)`` is called and + /// will mark the passed `callbackToken` as cancelled. + /// + /// - Parameter callbackToken: The callback token. + internal func cancelCallback(callbackToken: WriteResult.CallbackToken) { + self._backing.storage.cancelProducer(callbackToken: callbackToken) + } + + /// Write new elements to the asynchronous stream and provide a callback which will be invoked once more elements should be produced. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// first element of the provided sequence. If the asynchronous stream already terminated then `onProduceMore` will be invoked with + /// a `Result.failure`. + /// + /// - Parameters: + /// - sequence: The elements to write to the asynchronous stream. + /// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be + /// invoked during the call to ``write(contentsOf:onProduceMore:)``. + internal func write( + contentsOf sequence: S, + onProduceMore: @escaping @Sendable (Result) -> Void + ) where Element == S.Element, S: Sequence, Element: Sendable { + do { + let writeResult = try self.write(contentsOf: sequence) + + switch writeResult { + case .produceMore: + onProduceMore(Result.success(())) + + case .enqueueCallback(let callbackToken): + self.enqueueCallback(callbackToken: callbackToken, onProduceMore: onProduceMore) + } + } catch { + onProduceMore(.failure(error)) + } + } + + /// Writes the element to the asynchronous stream. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// provided element. If the asynchronous stream already terminated then `onProduceMore` will be invoked with + /// a `Result.failure`. + /// + /// - Parameters: + /// - sequence: The element to write to the asynchronous stream. + /// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be + /// invoked during the call to ``write(_:onProduceMore:)``. + internal func write( + _ element: Element, + onProduceMore: @escaping @Sendable (Result) -> Void + ) { + self.write(contentsOf: CollectionOfOne(element), onProduceMore: onProduceMore) + } + + /// Write new elements to the asynchronous stream. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error + /// indicating the failure. + /// + /// This method returns once more elements should be produced. + /// + /// - Parameters: + /// - sequence: The elements to write to the asynchronous stream. + internal func write(contentsOf sequence: S) async throws + where Element == S.Element, S: Sequence, Element: Sendable { + let writeResult = try { try self.write(contentsOf: sequence) }() + + switch writeResult { + case .produceMore: + return + + case .enqueueCallback(let callbackToken): + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + self.enqueueCallback( + callbackToken: callbackToken, + onProduceMore: { result in + switch result { + case .success(): + continuation.resume(returning: ()) + case .failure(let error): + continuation.resume(throwing: error) + } + } + ) + } + } onCancel: { + self.cancelCallback(callbackToken: callbackToken) + } + } + } + + /// Write new element to the asynchronous stream. + /// + /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the + /// provided element. If the asynchronous stream already terminated then this method will throw an error + /// indicating the failure. + /// + /// This method returns once more elements should be produced. + /// + /// - Parameters: + /// - sequence: The element to write to the asynchronous stream. + internal func write(_ element: Element) async throws { + try await self.write(contentsOf: CollectionOfOne(element)) + } + + /// Write the elements of the asynchronous sequence to the asynchronous stream. + /// + /// This method returns once the provided asynchronous sequence or the the asynchronous stream finished. + /// + /// - Important: This method does not finish the source if consuming the upstream sequence terminated. + /// + /// - Parameters: + /// - sequence: The elements to write to the asynchronous stream. + internal func write(contentsOf sequence: S) async throws + where Element == S.Element, S: AsyncSequence, Element: Sendable { + for try await element in sequence { + try await self.write(contentsOf: CollectionOfOne(element)) + } + } + + /// Indicates that the production terminated. + /// + /// After all buffered elements are consumed the next iteration point will return `nil` or throw an error. + /// + /// Calling this function more than once has no effect. After calling finish, the stream enters a terminal state and doesn't accept + /// new elements. + /// + /// - Parameters: + /// - error: The error to throw, or `nil`, to finish normally. + internal func finish(throwing error: Error?) { + self._backing.storage.finish(error) + } + } + + /// Initializes a new ``BufferedStream`` and an ``BufferedStream/Source``. + /// + /// - Parameters: + /// - elementType: The element type of the stream. + /// - failureType: The failure type of the stream. + /// - backPressureStrategy: The backpressure strategy that the stream should use. + /// - Returns: A tuple containing the stream and its source. The source should be passed to the + /// producer while the stream should be passed to the consumer. + internal static func makeStream( + of elementType: Element.Type = Element.self, + throwing failureType: Error.Type = Error.self, + backPressureStrategy: Source.BackPressureStrategy + ) -> (`Self`, Source) where Error == Error { + let storage = _BackPressuredStorage( + backPressureStrategy: backPressureStrategy._internalBackPressureStrategy + ) + let source = Source(storage: storage) + + return (.init(storage: storage), source) + } + + init(storage: _BackPressuredStorage) { + self.implementation = .backpressured(.init(storage: storage)) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream { + struct _WatermarkBackPressureStrategy { + /// The low watermark where demand should start. + private let _low: Int + /// The high watermark where demand should be stopped. + private let _high: Int + + /// Initializes a new ``_WatermarkBackPressureStrategy``. + /// + /// - Parameters: + /// - low: The low watermark where demand should start. + /// - high: The high watermark where demand should be stopped. + init(low: Int, high: Int) { + precondition(low <= high) + self._low = low + self._high = high + } + + func didYield(bufferDepth: Int) -> Bool { + // We are demanding more until we reach the high watermark + bufferDepth < self._high + } + + func didConsume(bufferDepth: Int) -> Bool { + // We start demanding again once we are below the low watermark + bufferDepth < self._low + } + } + + enum _InternalBackPressureStrategy { + case watermark(_WatermarkBackPressureStrategy) + + mutating func didYield(bufferDepth: Int) -> Bool { + switch self { + case .watermark(let strategy): + return strategy.didYield(bufferDepth: bufferDepth) + } + } + + mutating func didConsume(bufferDepth: Int) -> Bool { + switch self { + case .watermark(let strategy): + return strategy.didConsume(bufferDepth: bufferDepth) + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream { + // We are unchecked Sendable since we are protecting our state with a lock. + final class _BackPressuredStorage: Sendable { + /// The state machine + let _stateMachine: _ManagedCriticalState<_StateMachine> + + var onTermination: (@Sendable () -> Void)? { + set { + self._stateMachine.withCriticalRegion { + $0._onTermination = newValue + } + } + get { + self._stateMachine.withCriticalRegion { + $0._onTermination + } + } + } + + init( + backPressureStrategy: _InternalBackPressureStrategy + ) { + self._stateMachine = .init(.init(backPressureStrategy: backPressureStrategy)) + } + + func sequenceDeinitialized() { + let action = self._stateMachine.withCriticalRegion { + $0.sequenceDeinitialized() + } + + switch action { + case .callOnTermination(let onTermination): + onTermination?() + + case .failProducersAndCallOnTermination(let producerContinuations, let onTermination): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + onTermination?() + + case .none: + break + } + } + + func iteratorInitialized() { + self._stateMachine.withCriticalRegion { + $0.iteratorInitialized() + } + } + + func iteratorDeinitialized() { + let action = self._stateMachine.withCriticalRegion { + $0.iteratorDeinitialized() + } + + switch action { + case .callOnTermination(let onTermination): + onTermination?() + + case .failProducersAndCallOnTermination(let producerContinuations, let onTermination): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + onTermination?() + + case .none: + break + } + } + + func sourceDeinitialized() { + let action = self._stateMachine.withCriticalRegion { + $0.sourceDeinitialized() + } + + switch action { + case .callOnTermination(let onTermination): + onTermination?() + + case .failProducersAndCallOnTermination(let producerContinuations, let onTermination): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + onTermination?() + + case .failProducers(let producerContinuations): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + + case .none: + break + } + } + + func write( + contentsOf sequence: some Sequence + ) throws -> Source.WriteResult { + let action = self._stateMachine.withCriticalRegion { + $0.write(sequence) + } + + switch action { + case .returnProduceMore: + return .produceMore + + case .returnEnqueue(let callbackToken): + return .enqueueCallback(callbackToken) + + case .resumeConsumerAndReturnProduceMore(let continuation, let element): + continuation.resume(returning: element) + return .produceMore + + case .resumeConsumerAndReturnEnqueue(let continuation, let element, let callbackToken): + continuation.resume(returning: element) + return .enqueueCallback(callbackToken) + + case .throwFinishedError: + throw AlreadyFinishedError() + } + } + + func enqueueProducer( + callbackToken: Source.WriteResult.CallbackToken, + onProduceMore: @escaping @Sendable (Result) -> Void + ) { + let action = self._stateMachine.withCriticalRegion { + $0.enqueueProducer(callbackToken: callbackToken, onProduceMore: onProduceMore) + } + + switch action { + case .resumeProducer(let onProduceMore): + onProduceMore(Result.success(())) + + case .resumeProducerWithError(let onProduceMore, let error): + onProduceMore(Result.failure(error)) + + case .none: + break + } + } + + func cancelProducer(callbackToken: Source.WriteResult.CallbackToken) { + let action = self._stateMachine.withCriticalRegion { + $0.cancelProducer(callbackToken: callbackToken) + } + + switch action { + case .resumeProducerWithCancellationError(let onProduceMore): + onProduceMore(Result.failure(CancellationError())) + + case .none: + break + } + } + + func finish(_ failure: Error?) { + let action = self._stateMachine.withCriticalRegion { + $0.finish(failure) + } + + switch action { + case .callOnTermination(let onTermination): + onTermination?() + + case .resumeConsumerAndCallOnTermination( + let consumerContinuation, + let failure, + let onTermination + ): + switch failure { + case .some(let error): + consumerContinuation.resume(throwing: error) + case .none: + consumerContinuation.resume(returning: nil) + } + + onTermination?() + + case .resumeProducers(let producerContinuations): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + + case .none: + break + } + } + + func next() async throws -> Element? { + let action = self._stateMachine.withCriticalRegion { + $0.next() + } + + switch action { + case .returnElement(let element): + return element + + case .returnElementAndResumeProducers(let element, let producerContinuations): + for producerContinuation in producerContinuations { + producerContinuation(Result.success(())) + } + + return element + + case .returnErrorAndCallOnTermination(let failure, let onTermination): + onTermination?() + switch failure { + case .some(let error): + throw error + + case .none: + return nil + } + + case .returnNil: + return nil + + case .suspendTask: + return try await self.suspendNext() + } + } + + func suspendNext() async throws -> Element? { + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + let action = self._stateMachine.withCriticalRegion { + $0.suspendNext(continuation: continuation) + } + + switch action { + case .resumeConsumerWithElement(let continuation, let element): + continuation.resume(returning: element) + + case .resumeConsumerWithElementAndProducers( + let continuation, + let element, + let producerContinuations + ): + continuation.resume(returning: element) + for producerContinuation in producerContinuations { + producerContinuation(Result.success(())) + } + + case .resumeConsumerWithErrorAndCallOnTermination( + let continuation, + let failure, + let onTermination + ): + switch failure { + case .some(let error): + continuation.resume(throwing: error) + + case .none: + continuation.resume(returning: nil) + } + onTermination?() + + case .resumeConsumerWithNil(let continuation): + continuation.resume(returning: nil) + + case .none: + break + } + } + } onCancel: { + let action = self._stateMachine.withCriticalRegion { + $0.cancelNext() + } + + switch action { + case .resumeConsumerWithCancellationErrorAndCallOnTermination( + let continuation, + let onTermination + ): + continuation.resume(throwing: CancellationError()) + onTermination?() + + case .failProducersAndCallOnTermination( + let producerContinuations, + let onTermination + ): + for producerContinuation in producerContinuations { + producerContinuation(.failure(AlreadyFinishedError())) + } + onTermination?() + + case .none: + break + } + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension BufferedStream { + /// The state machine of the backpressured async stream. + struct _StateMachine { + enum _State { + struct Initial { + /// The backpressure strategy. + var backPressureStrategy: _InternalBackPressureStrategy + /// Indicates if the iterator was initialized. + var iteratorInitialized: Bool + /// The onTermination callback. + var onTermination: (@Sendable () -> Void)? + } + + struct Streaming { + /// The backpressure strategy. + var backPressureStrategy: _InternalBackPressureStrategy + /// Indicates if the iterator was initialized. + var iteratorInitialized: Bool + /// The onTermination callback. + var onTermination: (@Sendable () -> Void)? + /// The buffer of elements. + var buffer: Deque + /// The optional consumer continuation. + var consumerContinuation: CheckedContinuation? + /// The producer continuations. + var producerContinuations: Deque<(UInt, (Result) -> Void)> + /// The producers that have been cancelled. + var cancelledAsyncProducers: Deque + /// Indicates if we currently have outstanding demand. + var hasOutstandingDemand: Bool + } + + struct SourceFinished { + /// Indicates if the iterator was initialized. + var iteratorInitialized: Bool + /// The buffer of elements. + var buffer: Deque + /// The failure that should be thrown after the last element has been consumed. + var failure: Error? + /// The onTermination callback. + var onTermination: (@Sendable () -> Void)? + } + + case initial(Initial) + /// The state once either any element was yielded or `next()` was called. + case streaming(Streaming) + /// The state once the source signalled that it is finished. + case sourceFinished(SourceFinished) + + /// The state once there can be no outstanding demand. This can happen if: + /// 1. The iterator was deinited + /// 2. The source finished and all buffered elements have been consumed + case finished(iteratorInitialized: Bool) + + /// An intermediate state to avoid CoWs. + case modify + } + + /// The state machine's current state. + var _state: _State + + // The ID used for the next CallbackToken. + var nextCallbackTokenID: UInt = 0 + + var _onTermination: (@Sendable () -> Void)? { + set { + switch self._state { + case .initial(var initial): + initial.onTermination = newValue + self._state = .initial(initial) + + case .streaming(var streaming): + streaming.onTermination = newValue + self._state = .streaming(streaming) + + case .sourceFinished(var sourceFinished): + sourceFinished.onTermination = newValue + self._state = .sourceFinished(sourceFinished) + + case .finished: + break + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + get { + switch self._state { + case .initial(let initial): + return initial.onTermination + + case .streaming(let streaming): + return streaming.onTermination + + case .sourceFinished(let sourceFinished): + return sourceFinished.onTermination + + case .finished: + return nil + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + } + + /// Initializes a new `StateMachine`. + /// + /// We are passing and holding the back-pressure strategy here because + /// it is a customizable extension of the state machine. + /// + /// - Parameter backPressureStrategy: The back-pressure strategy. + init( + backPressureStrategy: _InternalBackPressureStrategy + ) { + self._state = .initial( + .init( + backPressureStrategy: backPressureStrategy, + iteratorInitialized: false, + onTermination: nil + ) + ) + } + + /// Generates the next callback token. + mutating func nextCallbackToken() -> Source.WriteResult.CallbackToken { + let id = self.nextCallbackTokenID + self.nextCallbackTokenID += 1 + return .init(id: id) + } + + /// Actions returned by `sequenceDeinitialized()`. + enum SequenceDeinitializedAction { + /// Indicates that `onTermination` should be called. + case callOnTermination((@Sendable () -> Void)?) + /// Indicates that all producers should be failed and `onTermination` should be called. + case failProducersAndCallOnTermination( + [(Result) -> Void], + (@Sendable () -> Void)? + ) + } + + mutating func sequenceDeinitialized() -> SequenceDeinitializedAction? { + switch self._state { + case .initial(let initial): + if initial.iteratorInitialized { + // An iterator was created and we deinited the sequence. + // This is an expected pattern and we just continue on normal. + return .none + } else { + // No iterator was created so we can transition to finished right away. + self._state = .finished(iteratorInitialized: false) + + return .callOnTermination(initial.onTermination) + } + + case .streaming(let streaming): + if streaming.iteratorInitialized { + // An iterator was created and we deinited the sequence. + // This is an expected pattern and we just continue on normal. + return .none + } else { + // No iterator was created so we can transition to finished right away. + self._state = .finished(iteratorInitialized: false) + + return .failProducersAndCallOnTermination( + Array(streaming.producerContinuations.map { $0.1 }), + streaming.onTermination + ) + } + + case .sourceFinished(let sourceFinished): + if sourceFinished.iteratorInitialized { + // An iterator was created and we deinited the sequence. + // This is an expected pattern and we just continue on normal. + return .none + } else { + // No iterator was created so we can transition to finished right away. + self._state = .finished(iteratorInitialized: false) + + return .callOnTermination(sourceFinished.onTermination) + } + + case .finished: + // We are already finished so there is nothing left to clean up. + // This is just the references dropping afterwards. + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + mutating func iteratorInitialized() { + switch self._state { + case .initial(var initial): + if initial.iteratorInitialized { + // Our sequence is a unicast sequence and does not support multiple AsyncIterator's + fatalError("Only a single AsyncIterator can be created") + } else { + // The first and only iterator was initialized. + initial.iteratorInitialized = true + self._state = .initial(initial) + } + + case .streaming(var streaming): + if streaming.iteratorInitialized { + // Our sequence is a unicast sequence and does not support multiple AsyncIterator's + fatalError("Only a single AsyncIterator can be created") + } else { + // The first and only iterator was initialized. + streaming.iteratorInitialized = true + self._state = .streaming(streaming) + } + + case .sourceFinished(var sourceFinished): + if sourceFinished.iteratorInitialized { + // Our sequence is a unicast sequence and does not support multiple AsyncIterator's + fatalError("Only a single AsyncIterator can be created") + } else { + // The first and only iterator was initialized. + sourceFinished.iteratorInitialized = true + self._state = .sourceFinished(sourceFinished) + } + + case .finished(iteratorInitialized: true): + // Our sequence is a unicast sequence and does not support multiple AsyncIterator's + fatalError("Only a single AsyncIterator can be created") + + case .finished(iteratorInitialized: false): + // It is strange that an iterator is created after we are finished + // but it can definitely happen, e.g. + // Sequence.init -> source.finish -> sequence.makeAsyncIterator + self._state = .finished(iteratorInitialized: true) + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `iteratorDeinitialized()`. + enum IteratorDeinitializedAction { + /// Indicates that `onTermination` should be called. + case callOnTermination((@Sendable () -> Void)?) + /// Indicates that all producers should be failed and `onTermination` should be called. + case failProducersAndCallOnTermination( + [(Result) -> Void], + (@Sendable () -> Void)? + ) + } + + mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? { + switch self._state { + case .initial(let initial): + if initial.iteratorInitialized { + // An iterator was created and deinited. Since we only support + // a single iterator we can now transition to finish. + self._state = .finished(iteratorInitialized: true) + return .callOnTermination(initial.onTermination) + } else { + // An iterator needs to be initialized before it can be deinitialized. + fatalError("AsyncStream internal inconsistency") + } + + case .streaming(let streaming): + if streaming.iteratorInitialized { + // An iterator was created and deinited. Since we only support + // a single iterator we can now transition to finish. + self._state = .finished(iteratorInitialized: true) + + return .failProducersAndCallOnTermination( + Array(streaming.producerContinuations.map { $0.1 }), + streaming.onTermination + ) + } else { + // An iterator needs to be initialized before it can be deinitialized. + fatalError("AsyncStream internal inconsistency") + } + + case .sourceFinished(let sourceFinished): + if sourceFinished.iteratorInitialized { + // An iterator was created and deinited. Since we only support + // a single iterator we can now transition to finish. + self._state = .finished(iteratorInitialized: true) + return .callOnTermination(sourceFinished.onTermination) + } else { + // An iterator needs to be initialized before it can be deinitialized. + fatalError("AsyncStream internal inconsistency") + } + + case .finished: + // We are already finished so there is nothing left to clean up. + // This is just the references dropping afterwards. + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `sourceDeinitialized()`. + enum SourceDeinitializedAction { + /// Indicates that `onTermination` should be called. + case callOnTermination((() -> Void)?) + /// Indicates that all producers should be failed and `onTermination` should be called. + case failProducersAndCallOnTermination( + [(Result) -> Void], + (@Sendable () -> Void)? + ) + /// Indicates that all producers should be failed. + case failProducers([(Result) -> Void]) + } + + mutating func sourceDeinitialized() -> SourceDeinitializedAction? { + switch self._state { + case .initial(let initial): + // The source got deinited before anything was written + self._state = .finished(iteratorInitialized: initial.iteratorInitialized) + return .callOnTermination(initial.onTermination) + + case .streaming(let streaming): + if streaming.buffer.isEmpty { + // We can transition to finished right away since the buffer is empty now + self._state = .finished(iteratorInitialized: streaming.iteratorInitialized) + + return .failProducersAndCallOnTermination( + Array(streaming.producerContinuations.map { $0.1 }), + streaming.onTermination + ) + } else { + // The continuation must be `nil` if the buffer has elements + precondition(streaming.consumerContinuation == nil) + + self._state = .sourceFinished( + .init( + iteratorInitialized: streaming.iteratorInitialized, + buffer: streaming.buffer, + failure: nil, + onTermination: streaming.onTermination + ) + ) + + return .failProducers( + Array(streaming.producerContinuations.map { $0.1 }) + ) + } + + case .sourceFinished, .finished: + // This is normal and we just have to tolerate it + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `write()`. + enum WriteAction { + /// Indicates that the producer should be notified to produce more. + case returnProduceMore + /// Indicates that the producer should be suspended to stop producing. + case returnEnqueue( + callbackToken: Source.WriteResult.CallbackToken + ) + /// Indicates that the consumer should be resumed and the producer should be notified to produce more. + case resumeConsumerAndReturnProduceMore( + continuation: CheckedContinuation, + element: Element + ) + /// Indicates that the consumer should be resumed and the producer should be suspended. + case resumeConsumerAndReturnEnqueue( + continuation: CheckedContinuation, + element: Element, + callbackToken: Source.WriteResult.CallbackToken + ) + /// Indicates that the producer has been finished. + case throwFinishedError + + init( + callbackToken: Source.WriteResult.CallbackToken?, + continuationAndElement: (CheckedContinuation, Element)? = nil + ) { + switch (callbackToken, continuationAndElement) { + case (.none, .none): + self = .returnProduceMore + + case (.some(let callbackToken), .none): + self = .returnEnqueue(callbackToken: callbackToken) + + case (.none, .some((let continuation, let element))): + self = .resumeConsumerAndReturnProduceMore( + continuation: continuation, + element: element + ) + + case (.some(let callbackToken), .some((let continuation, let element))): + self = .resumeConsumerAndReturnEnqueue( + continuation: continuation, + element: element, + callbackToken: callbackToken + ) + } + } + } + + mutating func write(_ sequence: some Sequence) -> WriteAction { + switch self._state { + case .initial(var initial): + var buffer = Deque() + buffer.append(contentsOf: sequence) + + let shouldProduceMore = initial.backPressureStrategy.didYield( + bufferDepth: buffer.count + ) + let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken() + + self._state = .streaming( + .init( + backPressureStrategy: initial.backPressureStrategy, + iteratorInitialized: initial.iteratorInitialized, + onTermination: initial.onTermination, + buffer: buffer, + consumerContinuation: nil, + producerContinuations: .init(), + cancelledAsyncProducers: .init(), + hasOutstandingDemand: shouldProduceMore + ) + ) + + return .init(callbackToken: callbackToken) + + case .streaming(var streaming): + self._state = .modify + + streaming.buffer.append(contentsOf: sequence) + + // We have an element and can resume the continuation + let shouldProduceMore = streaming.backPressureStrategy.didYield( + bufferDepth: streaming.buffer.count + ) + streaming.hasOutstandingDemand = shouldProduceMore + let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken() + + if let consumerContinuation = streaming.consumerContinuation { + guard let element = streaming.buffer.popFirst() else { + // We got a yield of an empty sequence. We just tolerate this. + self._state = .streaming(streaming) + + return .init(callbackToken: callbackToken) + } + + // We got a consumer continuation and an element. We can resume the consumer now + streaming.consumerContinuation = nil + self._state = .streaming(streaming) + return .init( + callbackToken: callbackToken, + continuationAndElement: (consumerContinuation, element) + ) + } else { + // We don't have a suspended consumer so we just buffer the elements + self._state = .streaming(streaming) + return .init( + callbackToken: callbackToken + ) + } + + case .sourceFinished, .finished: + // If the source has finished we are dropping the elements. + return .throwFinishedError + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `enqueueProducer()`. + enum EnqueueProducerAction { + /// Indicates that the producer should be notified to produce more. + case resumeProducer((Result) -> Void) + /// Indicates that the producer should be notified about an error. + case resumeProducerWithError((Result) -> Void, Error) + } + + mutating func enqueueProducer( + callbackToken: Source.WriteResult.CallbackToken, + onProduceMore: @Sendable @escaping (Result) -> Void + ) -> EnqueueProducerAction? { + switch self._state { + case .initial: + // We need to transition to streaming before we can suspend + // This is enforced because the CallbackToken has no internal init so + // one must create it by calling `write` first. + fatalError("AsyncStream internal inconsistency") + + case .streaming(var streaming): + if let index = streaming.cancelledAsyncProducers.firstIndex(of: callbackToken.id) { + // Our producer got marked as cancelled. + self._state = .modify + streaming.cancelledAsyncProducers.remove(at: index) + self._state = .streaming(streaming) + + return .resumeProducerWithError(onProduceMore, CancellationError()) + } else if streaming.hasOutstandingDemand { + // We hit an edge case here where we wrote but the consuming thread got interleaved + return .resumeProducer(onProduceMore) + } else { + self._state = .modify + streaming.producerContinuations.append((callbackToken.id, onProduceMore)) + + self._state = .streaming(streaming) + return .none + } + + case .sourceFinished, .finished: + // Since we are unlocking between yielding and suspending the yield + // It can happen that the source got finished or the consumption fully finishes. + return .resumeProducerWithError(onProduceMore, AlreadyFinishedError()) + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `cancelProducer()`. + enum CancelProducerAction { + /// Indicates that the producer should be notified about cancellation. + case resumeProducerWithCancellationError((Result) -> Void) + } + + mutating func cancelProducer( + callbackToken: Source.WriteResult.CallbackToken + ) -> CancelProducerAction? { + switch self._state { + case .initial: + // We need to transition to streaming before we can suspend + fatalError("AsyncStream internal inconsistency") + + case .streaming(var streaming): + if let index = streaming.producerContinuations.firstIndex(where: { + $0.0 == callbackToken.id + }) { + // We have an enqueued producer that we need to resume now + self._state = .modify + let continuation = streaming.producerContinuations.remove(at: index).1 + self._state = .streaming(streaming) + + return .resumeProducerWithCancellationError(continuation) + } else { + // The task that yields was cancelled before yielding so the cancellation handler + // got invoked right away + self._state = .modify + streaming.cancelledAsyncProducers.append(callbackToken.id) + self._state = .streaming(streaming) + + return .none + } + + case .sourceFinished, .finished: + // Since we are unlocking between yielding and suspending the yield + // It can happen that the source got finished or the consumption fully finishes. + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `finish()`. + enum FinishAction { + /// Indicates that `onTermination` should be called. + case callOnTermination((() -> Void)?) + /// Indicates that the consumer should be resumed with the failure, the producers + /// should be resumed with an error and `onTermination` should be called. + case resumeConsumerAndCallOnTermination( + consumerContinuation: CheckedContinuation, + failure: Error?, + onTermination: (() -> Void)? + ) + /// Indicates that the producers should be resumed with an error. + case resumeProducers( + producerContinuations: [(Result) -> Void] + ) + } + + @inlinable + mutating func finish(_ failure: Error?) -> FinishAction? { + switch self._state { + case .initial(let initial): + // Nothing was yielded nor did anybody call next + // This means we can transition to sourceFinished and store the failure + self._state = .sourceFinished( + .init( + iteratorInitialized: initial.iteratorInitialized, + buffer: .init(), + failure: failure, + onTermination: initial.onTermination + ) + ) + + return .callOnTermination(initial.onTermination) + + case .streaming(let streaming): + if let consumerContinuation = streaming.consumerContinuation { + // We have a continuation, this means our buffer must be empty + // Furthermore, we can now transition to finished + // and resume the continuation with the failure + precondition(streaming.buffer.isEmpty, "Expected an empty buffer") + precondition( + streaming.producerContinuations.isEmpty, + "Expected no suspended producers" + ) + + self._state = .finished(iteratorInitialized: streaming.iteratorInitialized) + + return .resumeConsumerAndCallOnTermination( + consumerContinuation: consumerContinuation, + failure: failure, + onTermination: streaming.onTermination + ) + } else { + self._state = .sourceFinished( + .init( + iteratorInitialized: streaming.iteratorInitialized, + buffer: streaming.buffer, + failure: failure, + onTermination: streaming.onTermination + ) + ) + + return .resumeProducers( + producerContinuations: Array(streaming.producerContinuations.map { $0.1 }) + ) + } + + case .sourceFinished, .finished: + // If the source has finished, finishing again has no effect. + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `next()`. + enum NextAction { + /// Indicates that the element should be returned to the caller. + case returnElement(Element) + /// Indicates that the element should be returned to the caller and that all producers should be called. + case returnElementAndResumeProducers(Element, [(Result) -> Void]) + /// Indicates that the `Error` should be returned to the caller and that `onTermination` should be called. + case returnErrorAndCallOnTermination(Error?, (() -> Void)?) + /// Indicates that the `nil` should be returned to the caller. + case returnNil + /// Indicates that the `Task` of the caller should be suspended. + case suspendTask + } + + mutating func next() -> NextAction { + switch self._state { + case .initial(let initial): + // We are not interacting with the back-pressure strategy here because + // we are doing this inside `next(:)` + self._state = .streaming( + .init( + backPressureStrategy: initial.backPressureStrategy, + iteratorInitialized: initial.iteratorInitialized, + onTermination: initial.onTermination, + buffer: Deque(), + consumerContinuation: nil, + producerContinuations: .init(), + cancelledAsyncProducers: .init(), + hasOutstandingDemand: false + ) + ) + + return .suspendTask + case .streaming(var streaming): + guard streaming.consumerContinuation == nil else { + // We have multiple AsyncIterators iterating the sequence + fatalError("AsyncStream internal inconsistency") + } + + self._state = .modify + + if let element = streaming.buffer.popFirst() { + // We have an element to fulfil the demand right away. + let shouldProduceMore = streaming.backPressureStrategy.didConsume( + bufferDepth: streaming.buffer.count + ) + streaming.hasOutstandingDemand = shouldProduceMore + + if shouldProduceMore { + // There is demand and we have to resume our producers + let producers = Array(streaming.producerContinuations.map { $0.1 }) + streaming.producerContinuations.removeAll() + self._state = .streaming(streaming) + return .returnElementAndResumeProducers(element, producers) + } else { + // We don't have any new demand, so we can just return the element. + self._state = .streaming(streaming) + return .returnElement(element) + } + } else { + // There is nothing in the buffer to fulfil the demand so we need to suspend. + // We are not interacting with the back-pressure strategy here because + // we are doing this inside `suspendNext` + self._state = .streaming(streaming) + + return .suspendTask + } + + case .sourceFinished(var sourceFinished): + // Check if we have an element left in the buffer and return it + self._state = .modify + + if let element = sourceFinished.buffer.popFirst() { + self._state = .sourceFinished(sourceFinished) + + return .returnElement(element) + } else { + // We are returning the queued failure now and can transition to finished + self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized) + + return .returnErrorAndCallOnTermination( + sourceFinished.failure, + sourceFinished.onTermination + ) + } + + case .finished: + return .returnNil + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `suspendNext()`. + enum SuspendNextAction { + /// Indicates that the consumer should be resumed. + case resumeConsumerWithElement(CheckedContinuation, Element) + /// Indicates that the consumer and all producers should be resumed. + case resumeConsumerWithElementAndProducers( + CheckedContinuation, + Element, + [(Result) -> Void] + ) + /// Indicates that the consumer should be resumed with the failure and that `onTermination` should be called. + case resumeConsumerWithErrorAndCallOnTermination( + CheckedContinuation, + Error?, + (() -> Void)? + ) + /// Indicates that the consumer should be resumed with `nil`. + case resumeConsumerWithNil(CheckedContinuation) + } + + mutating func suspendNext( + continuation: CheckedContinuation + ) -> SuspendNextAction? { + switch self._state { + case .initial: + // We need to transition to streaming before we can suspend + preconditionFailure("AsyncStream internal inconsistency") + + case .streaming(var streaming): + guard streaming.consumerContinuation == nil else { + // We have multiple AsyncIterators iterating the sequence + fatalError( + "This should never happen since we only allow a single Iterator to be created" + ) + } + + self._state = .modify + + // We have to check here again since we might have a producer interleave next and suspendNext + if let element = streaming.buffer.popFirst() { + // We have an element to fulfil the demand right away. + + let shouldProduceMore = streaming.backPressureStrategy.didConsume( + bufferDepth: streaming.buffer.count + ) + streaming.hasOutstandingDemand = shouldProduceMore + + if shouldProduceMore { + // There is demand and we have to resume our producers + let producers = Array(streaming.producerContinuations.map { $0.1 }) + streaming.producerContinuations.removeAll() + self._state = .streaming(streaming) + return .resumeConsumerWithElementAndProducers( + continuation, + element, + producers + ) + } else { + // We don't have any new demand, so we can just return the element. + self._state = .streaming(streaming) + return .resumeConsumerWithElement(continuation, element) + } + } else { + // There is nothing in the buffer to fulfil the demand so we to store the continuation. + streaming.consumerContinuation = continuation + self._state = .streaming(streaming) + + return .none + } + + case .sourceFinished(var sourceFinished): + // Check if we have an element left in the buffer and return it + self._state = .modify + + if let element = sourceFinished.buffer.popFirst() { + self._state = .sourceFinished(sourceFinished) + + return .resumeConsumerWithElement(continuation, element) + } else { + // We are returning the queued failure now and can transition to finished + self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized) + + return .resumeConsumerWithErrorAndCallOnTermination( + continuation, + sourceFinished.failure, + sourceFinished.onTermination + ) + } + + case .finished: + return .resumeConsumerWithNil(continuation) + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + + /// Actions returned by `cancelNext()`. + enum CancelNextAction { + /// Indicates that the continuation should be resumed with a cancellation error, the producers should be finished and call onTermination. + case resumeConsumerWithCancellationErrorAndCallOnTermination( + CheckedContinuation, + (() -> Void)? + ) + /// Indicates that the producers should be finished and call onTermination. + case failProducersAndCallOnTermination([(Result) -> Void], (() -> Void)?) + } + + mutating func cancelNext() -> CancelNextAction? { + switch self._state { + case .initial: + // We need to transition to streaming before we can suspend + fatalError("AsyncStream internal inconsistency") + + case .streaming(let streaming): + self._state = .finished(iteratorInitialized: streaming.iteratorInitialized) + + if let consumerContinuation = streaming.consumerContinuation { + precondition( + streaming.producerContinuations.isEmpty, + "Internal inconsistency. Unexpected producer continuations." + ) + return .resumeConsumerWithCancellationErrorAndCallOnTermination( + consumerContinuation, + streaming.onTermination + ) + } else { + return .failProducersAndCallOnTermination( + Array(streaming.producerContinuations.map { $0.1 }), + streaming.onTermination + ) + } + + case .sourceFinished, .finished: + return .none + + case .modify: + fatalError("AsyncStream internal inconsistency") + } + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/Cancellation.swift b/Sources/_NIOFileSystem/Internal/Cancellation.swift new file mode 100644 index 000000000..467ea3c5b --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/Cancellation.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +/// Executes the closure and masks cancellation. +@_spi(Testing) +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public func withoutCancellation( + _ execute: @escaping () async throws -> R +) async throws -> R { + // Okay as we immediately wait for the result of the task. + let unsafeExecute = UnsafeTransfer(execute) + let t = Task { + try await unsafeExecute.wrappedValue() + } + return try await t.value +} + +/// Executes `fn` and then `tearDown`, which cannot be cancelled. +@_spi(Testing) +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public func withUncancellableTearDown( + _ fn: () async throws -> R, + tearDown: @escaping (Result) async throws -> Void +) async throws -> R { + let result: Result + do { + result = .success(try await fn()) + } catch { + result = .failure(error) + } + + let errorOnlyResult: Result = result.map { _ in () } + let tearDownResult: Result = try await withoutCancellation { + do { + return .success(try await tearDown(errorOnlyResult)) + } catch { + return .failure(error) + } + } + + try tearDownResult.get() + return try result.get() +} diff --git a/Sources/_NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift b/Sources/_NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift new file mode 100644 index 000000000..3a998f5b2 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import DequeModule +import NIOConcurrencyHelpers + +/// Type modeled after a "token bucket" pattern, which is similar to a semaphore, but is built with +/// Swift Concurrency primitives. +/// +/// This is an adaptation of the TokenBucket found in Swift Package Manager. +/// Instead of using an ``actor``, we define a class and limit access through +/// ``NIOLock``. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +final class TokenBucket: @unchecked Sendable { + private var tokens: Int + private var waiters: Deque> + private let lock: NIOLock + + init(tokens: Int) { + precondition(tokens >= 1, "Need at least one token!") + self.tokens = tokens + self.waiters = Deque() + self.lock = NIOLock() + } + + /// Executes an `async` closure immediately when a token is available. + /// Only the same number of closures will be executed concurrently as the number + /// of `tokens` passed to ``TokenBucket/init(tokens:)``, all subsequent + /// invocations of `withToken` will suspend until a "free" token is available. + /// - Parameter body: The closure to invoke when a token is available. + /// - Returns: Resulting value returned by `body`. + func withToken( + _ body: @Sendable () async throws -> ReturnType + ) async rethrows -> ReturnType { + await self.getToken() + defer { self.returnToken() } + return try await body() + } + + private func getToken() async { + self.lock.lock() + if self.tokens > 0 { + self.tokens -= 1 + self.lock.unlock() + return + } + + await withCheckedContinuation { + self.waiters.append($0) + self.lock.unlock() + } + } + + private func returnToken() { + if let waiter = self.lock.withLock({ () -> CheckedContinuation? in + if let nextWaiter = self.waiters.popFirst() { + return nextWaiter + } + + self.tokens += 1 + return nil + }) { + waiter.resume() + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/Concurrency Primitives/UnsafeTransfer.swift b/Sources/_NIOFileSystem/Internal/Concurrency Primitives/UnsafeTransfer.swift new file mode 100644 index 000000000..c39dd0b5e --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/Concurrency Primitives/UnsafeTransfer.swift @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +@usableFromInline +struct UnsafeTransfer: @unchecked Sendable { + @usableFromInline + var wrappedValue: Value + + @inlinable + init(_ wrappedValue: Value) { + self.wrappedValue = wrappedValue + } +} diff --git a/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift b/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift new file mode 100644 index 000000000..ce793264a --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift @@ -0,0 +1,165 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystem { + /// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to + /// `destinationPath`. + /// + /// The parallelism is solely at the level of individual items (files, symbolic links and + /// directories). A larger file is not 'split' into concurrent reads or writes. + /// + /// If a symbolic link is encountered, then only the link is copied. If supported by the file + /// system, the copied items will preserve permissions and any extended attributes. + /// + /// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open + /// file descriptors at any point. Operations are assumed to consume 2 descriptors, so the + /// maximum open descriptors are `maxConcurrentOperations * 2` + @usableFromInline + func copyDirectoryParallel( + from sourcePath: FilePath, + to destinationPath: FilePath, + maxConcurrentOperations: Int, + shouldProceedAfterError: @escaping @Sendable ( + _ entry: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + // Implemented with NIOAsyncSequenceProducer rather than AsyncStream. It is approximately + // the same speed in the best case, but has significantly less variance. + // NIOAsyncSequenceProducer also enforces a multi-producer, single-consumer access pattern. + let copyRequiredQueue = NIOAsyncSequenceProducer.makeSequence( + elementType: DirCopyItem.self, + backPressureStrategy: NoBackPressureStrategy(), + finishOnDeinit: false, + delegate: DirCopyDelegate() + ) + + // We ignore the result of yield in all cases, because we are not implementing back + // pressure, and cancellation is dealt with separately. + @Sendable func yield(_ contentsOf: [DirCopyItem]) { + _ = copyRequiredQueue.source.yield(contentsOf: contentsOf) + } + + // Kick-start the procees by enqueuing the root entry. The calling function already + // validated the root needed copying, so it is safe to force unwrap the value. + _ = copyRequiredQueue.source.yield( + .toCopy(from: .init(path: sourcePath, type: .directory)!, to: destinationPath) + ) + + // The processing of the very first item (the root) will increment this counter. Processing + // will finish when the counter hits zero again. + // + // This does not need to be a ManagedAtomic or similar because: + // - All state maintenance is done within the withThrowingTaskGroup closure + // - All actual file system work is done by tasks created on the `taskGroup` + var activeDirCount = 0 + + // Despite there being no 'result' for each operation, we cannot use a discarding task group, + // because we use the 'drain results' queue as a concurrency limiting side effect. + try await withThrowingTaskGroup(of: Void.self) { taskGroup in + // Process each item in the current task. + // + // Side Effects: + // - Updates activeDirCount and finishes the stream if required. + // - Might add a task to `taskGroup`. + // + // Returns true if it added a task, false otherwise. + func onNextItem(_ item: DirCopyItem) -> Bool { + switch item { + case .endOfDir: + activeDirCount -= 1 + if activeDirCount == 0 { + copyRequiredQueue.source.finish() + } + return false + case let .toCopy(from: from, to: to): + if from.type == .directory { + activeDirCount += 1 + } + taskGroup.addTask { + try await copySelfAndEnqueueChildren( + from: from, + to: to, + yield: yield, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + } + return true + } + } + + let iter = copyRequiredQueue.sequence.makeAsyncIterator() + + // inProgress counts the number of tasks we have added to the task group. + // Get up to the maximum concurrency first. + // We haven't started monitoring for task completion, so inProgress is 'worst case'. + var inProgress = 0 + while inProgress <= maxConcurrentOperations { + let item = await iter.next() + if let item = item { + if onNextItem(item) { + inProgress += 1 + } + } else { + // Either we completed things before we hit the limit or we were cancelled. In + // the latter case we choose to propagate the cancellation clearly. This makes + // testing for it more reliable. + try Task.checkCancellation() + return + } + } + + // One in (finish) -> one out (start another), but only for items that trigger a task. + while let _ = try await taskGroup.next() { + var keepConsuming = true + while keepConsuming { + let item = await iter.next() + if let item = item { + keepConsuming = !onNextItem(item) + } else { + // We must check here, to accurately propagate the cancellation. + try Task.checkCancellation() + keepConsuming = false + } + } + } + } + } +} + +/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +private struct NoBackPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategy { + mutating func didYield(bufferDepth: Int) -> Bool { true } + + mutating func didConsume(bufferDepth: Int) -> Bool { true } +} + +/// We ignore back pressure, the inherent handle limiting in copyDirectoryParallel means it is unnecessary. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +private struct DirCopyDelegate: NIOAsyncSequenceProducerDelegate, Sendable { + @inlinable + func produceMore() {} + + @inlinable + func didTerminate() {} +} diff --git a/Sources/_NIOFileSystem/Internal/ParallelRemoval.swift b/Sources/_NIOFileSystem/Internal/ParallelRemoval.swift new file mode 100644 index 000000000..cd8b6702d --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/ParallelRemoval.swift @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystem { + /// Recursively walk all objects found in `path`. Call ourselves recursively + /// on each directory that we find, as soon as the file descriptor for + /// `path` has been closed; also delete all files that we come across. + func discoverAndRemoveItemsInTree( + at path: FilePath, + _ bucket: TokenBucket + ) async throws -> Int { + // Discover current directory and find all files/directories. Free up + // the handle as fast as possible. + let (directoriesToRecurseInto, itemsToDelete) = try await bucket.withToken { + try await self.withDirectoryHandle(atPath: path) { directory in + var subdirectories: [FilePath] = [] + var itemsInDirectory: [FilePath] = [] + + for try await batch in directory.listContents().batched() { + for entry in batch { + switch entry.type { + case .directory: + subdirectories.append(entry.path) + default: + itemsInDirectory.append(entry.path) + } + } + } + + return (subdirectories, itemsInDirectory) + } + } + + return try await withThrowingTaskGroup(of: Int.self) { group in + // Delete all items we found in the current directory. + for item in itemsToDelete { + group.addTask { + try await self.removeOneItem(at: item) + } + } + + // Recurse into all newly found subdirectories. + for directory in directoriesToRecurseInto { + group.addTask { + try await self.discoverAndRemoveItemsInTree(at: directory, bucket) + } + } + + // Await task groups to finish and sum all items deleted so far. + var numberOfDeletedItems = try await group.reduce(0, +) + + // Remove top level directory. + numberOfDeletedItems += try await self.removeOneItem(at: path) + + return numberOfDeletedItems + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/String+UnsafeUnititializedCapacity.swift b/Sources/_NIOFileSystem/Internal/String+UnsafeUnititializedCapacity.swift new file mode 100644 index 000000000..54c20a92a --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/String+UnsafeUnititializedCapacity.swift @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +extension String { + @inlinable + init( + backportUnsafeUninitializedCapacity capacity: Int, + initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer) throws -> Int + ) rethrows { + // The buffer will store zero terminated C string + let buffer = UnsafeMutableBufferPointer.allocate(capacity: capacity + 1) + defer { + buffer.deallocate() + } + + let initializedCount = try initializer(buffer) + precondition(initializedCount <= capacity, "Overran buffer in initializer!") + + // add zero termination + buffer[initializedCount] = 0 + + self = String(cString: buffer.baseAddress!) + } +} + +// Frustratingly, Swift 5.3 shipped before the macOS 11 SDK did, so we cannot gate the availability of +// this declaration on having the 5.3 compiler. This has caused a number of build issues. While updating +// to newer Xcodes does work, we can save ourselves some hassle and just wait until 5.4 to get this +// enhancement on Apple platforms. +extension String { + @inlinable + init( + customUnsafeUninitializedCapacity capacity: Int, + initializingUTF8With initializer: ( + _ buffer: UnsafeMutableBufferPointer + ) throws -> Int + ) rethrows { + if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { + try self.init( + unsafeUninitializedCapacity: capacity, + initializingUTF8With: initializer + ) + } else { + try self.init( + backportUnsafeUninitializedCapacity: capacity, + initializingUTF8With: initializer + ) + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/System Calls/CInterop.swift b/Sources/_NIOFileSystem/Internal/System Calls/CInterop.swift new file mode 100644 index 000000000..2235af8a6 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/CInterop.swift @@ -0,0 +1,83 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +import CNIODarwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Android) +@preconcurrency import Android +import CNIOLinux +#endif + +/// Aliases for platform-dependent types used for system calls. +extension CInterop { + #if canImport(Darwin) + public typealias Stat = Darwin.stat + #elseif canImport(Glibc) + public typealias Stat = Glibc.stat + #elseif canImport(Musl) + public typealias Stat = Musl.stat + #elseif canImport(Android) + public typealias Stat = Android.stat + #endif + + #if canImport(Darwin) + @_spi(Testing) + public static let maxPathLength = Darwin.PATH_MAX + #elseif canImport(Glibc) + @_spi(Testing) + public static let maxPathLength = Glibc.PATH_MAX + #elseif canImport(Musl) + @_spi(Testing) + public static let maxPathLength = Musl.PATH_MAX + #elseif canImport(Android) + @_spi(Testing) + public static let maxPathLength = Android.PATH_MAX + #endif + + #if canImport(Darwin) + typealias DirPointer = UnsafeMutablePointer + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + typealias DirPointer = OpaquePointer + #endif + + #if canImport(Darwin) + typealias DirEnt = Darwin.dirent + #elseif canImport(Glibc) + typealias DirEnt = Glibc.dirent + #elseif canImport(Musl) + typealias DirEnt = Musl.dirent + #elseif canImport(Android) + typealias DirEnt = Android.dirent + #endif + + #if canImport(Darwin) + typealias FTS = CNIODarwin.FTS + typealias FTSEnt = CNIODarwin.FTSENT + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + typealias FTS = CNIOLinux.FTS + typealias FTSEnt = CNIOLinux.FTSENT + #endif + + typealias FTSPointer = UnsafeMutablePointer + typealias FTSEntPointer = UnsafeMutablePointer +} diff --git a/Sources/_NIOFileSystem/Internal/System Calls/Errno.swift b/Sources/_NIOFileSystem/Internal/System Calls/Errno.swift new file mode 100644 index 000000000..7ae805987 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/Errno.swift @@ -0,0 +1,148 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +#elseif canImport(Musl) +@preconcurrency import Musl +#elseif canImport(Android) +@preconcurrency import Android +#endif + +extension Errno { + @_spi(Testing) + public static var _current: Errno { + get { + #if canImport(Darwin) + return Errno(rawValue: Darwin.errno) + #elseif canImport(Glibc) + return Errno(rawValue: Glibc.errno) + #elseif canImport(Musl) + return Errno(rawValue: Musl.errno) + #elseif canImport(Android) + return Errno(rawValue: Android.errno) + #endif + } + set { + #if canImport(Darwin) + Darwin.errno = newValue.rawValue + #elseif canImport(Glibc) + Glibc.errno = newValue.rawValue + #elseif canImport(Musl) + Musl.errno = newValue.rawValue + #elseif canImport(Android) + Android.errno = newValue.rawValue + #endif + } + } + + fileprivate static func clear() { + #if canImport(Darwin) + Darwin.errno = 0 + #elseif canImport(Glibc) + Glibc.errno = 0 + #elseif canImport(Musl) + Musl.errno = 0 + #elseif canImport(Android) + Android.errno = 0 + #endif + } +} + +/// Returns a `Result` representing the value returned from the given closure +/// or an `Errno` if that value was -1. +/// +/// If desired this function can call the closure in a loop until it does not +/// result in `Errno` being `.interrupted`. +@_spi(Testing) +public func valueOrErrno( + retryOnInterrupt: Bool = true, + _ fn: () -> I +) -> Result { + while true { + Errno.clear() + let result = fn() + if result == -1 { + let errno = Errno._current + if errno == .interrupted, retryOnInterrupt { + continue + } else { + return .failure(errno) + } + } else { + return .success(result) + } + } +} + +/// As `valueOrErrno` but discards the success value. +@_spi(Testing) +public func nothingOrErrno( + retryOnInterrupt: Bool = true, + _ fn: () -> I +) -> Result { + valueOrErrno(retryOnInterrupt: retryOnInterrupt, fn).map { _ in } +} + +/// Returns a `Result` representing the value returned from the given closure +/// or an `Errno` if that value was `nil`. +/// +/// If desired this function can call the closure in a loop until it does not +/// result in `Errno` being `.interrupted`. `Errno` is only checked if the +/// closure returns `nil`. +@_spi(Testing) +public func optionalValueOrErrno( + retryOnInterrupt: Bool = true, + _ fn: () -> R? +) -> Result { + while true { + Errno.clear() + if let result = fn() { + return .success(result) + } else { + let errno = Errno._current + if errno == .interrupted, retryOnInterrupt { + continue + } else if errno.rawValue == 0 { + return .success(nil) + } else { + return .failure(errno) + } + } + } +} + +/// As `valueOrErrno` but unconditionally checks the current `Errno`. +@_spi(Testing) +public func valueOrErrno( + retryOnInterrupt: Bool = true, + _ fn: () -> R +) -> Result { + while true { + Errno.clear() + let value = fn() + let errno = Errno._current + if errno.rawValue == 0 { + return .success(value) + } else if errno == .interrupted, retryOnInterrupt { + continue + } else { + return .failure(errno) + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/System Calls/FileDescriptor+Syscalls.swift b/Sources/_NIOFileSystem/Internal/System Calls/FileDescriptor+Syscalls.swift new file mode 100644 index 000000000..294124399 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/FileDescriptor+Syscalls.swift @@ -0,0 +1,326 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Bionic) +@preconcurrency import Bionic +import CNIOLinux +#endif + +extension FileDescriptor { + /// Opens or creates a file for reading or writing. + /// + /// The corresponding C function is `fdopenat`. + /// + /// - Parameters: + /// - path: The location of the file to open. If the path is relative then the file is opened + /// relative to the descriptor. + /// - mode: The read and write access to use. + /// - options: The behavior for opening the file. + /// - permissions: The file permissions to use for created files. + /// - retryOnInterrupt: Whether to retry the operation if it throws `Errno.interrupted`. The + /// default is true. Pass false to try only once and throw an error upon interruption. + /// - Returns: A file descriptor for the open file. + @_spi(Testing) + public func `open`( + atPath path: FilePath, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions, + permissions: FilePermissions?, + retryOnInterrupt: Bool = true + ) -> Result { + let oFlag = mode.rawValue | options.rawValue + let rawValue = valueOrErrno(retryOnInterrupt: retryOnInterrupt) { + path.withPlatformString { + if let permissions = permissions { + return system_fdopenat(self.rawValue, $0, oFlag, permissions.rawValue) + } else { + precondition(!options.contains(.create), "Create must be given permissions") + return system_fdopenat(self.rawValue, $0, oFlag) + } + } + } + + return rawValue.map { FileDescriptor(rawValue: $0) } + } + + /// Returns information about the status of the open file. + /// + /// The corresponding C function is `fstat`. + /// + /// - Returns: Information about the open file. + @_spi(Testing) + public func status() -> Result { + var status = CInterop.Stat() + return nothingOrErrno(retryOnInterrupt: false) { + system_fstat(self.rawValue, &status) + }.map { status } + } + + /// Sets the permission bits of the open file. + /// + /// The corresponding C function is `fchmod`. + /// + /// - Parameters: + /// - mode: The permissions to set on the file. + /// - retryOnInterrupt: Whether to retry the operation if it throws `Errno.interrupted`. The + /// default is true. Pass false to try only once and throw an error upon interruption. + @_spi(Testing) + public func changeMode( + _ mode: FilePermissions, + retryOnInterrupt: Bool = true + ) -> Result { + nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { + system_fchmod(self.rawValue, mode.rawValue) + } + } + + /// List the names of extended attributes. + /// + /// The corresponding C function is `flistxattr`. + /// + /// - Parameter buffer: The buffer into which names are written. Names are written are NULL + /// terminated UTF-8 strings and are returned in an arbitrary order. There is no padding + /// between strings. If `buffer` is `nil` then the return value is the size of the buffer + /// required to list all extended attributes. If there is not enough space in the `buffer` + /// then `Errno.outOfRange` is returned. + /// - Returns: The size of the extended attribute list. + @_spi(Testing) + public func listExtendedAttributes( + _ buffer: UnsafeMutableBufferPointer? + ) -> Result { + valueOrErrno(retryOnInterrupt: false) { + system_flistxattr(self.rawValue, buffer?.baseAddress, buffer?.count ?? 0) + } + } + + /// Get the value of the named extended attribute. + /// + /// The corresponding C function is `fgetxattr`. + /// + /// - Parameters: + /// - name: The name of the extended attribute. + /// - buffer: The buffer into which the value is written. If `buffer` is `nil` then the return + /// value is the size of the buffer required to read the value. If there is not enough + /// space in the `buffer` then `Errno.outOfRange` is returned. + /// - Returns: The size of the extended attribute value. + @_spi(Testing) + public func getExtendedAttribute( + named name: String, + buffer: UnsafeMutableRawBufferPointer? + ) -> Result { + valueOrErrno(retryOnInterrupt: false) { + name.withPlatformString { + system_fgetxattr(self.rawValue, $0, buffer?.baseAddress, buffer?.count ?? 0) + } + } + } + + /// Set the value of the named extended attribute. + /// + /// The corresponding C function is `fsetxattr`. + /// + /// - Parameters: + /// - name: The name of the extended attribute. + /// - value: The data to set for the attribute. + @_spi(Testing) + public func setExtendedAttribute( + named name: String, + to value: UnsafeRawBufferPointer? + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + name.withPlatformString { namePointer in + system_fsetxattr(self.rawValue, namePointer, value?.baseAddress, value?.count ?? 0) + } + } + } + + /// Remove the value for the named extended attribute. + /// + /// The corresponding C function is `fremovexattr`. + /// + /// - Parameters: + /// - name: The name of the extended attribute. + @_spi(Testing) + public func removeExtendedAttribute(_ name: String) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + name.withPlatformString { + system_fremovexattr(self.rawValue, $0) + } + } + } + + /// Synchronize modified data and metadata to a permanent storage device. + /// + /// The corresponding C functions is `fsync`. + /// + /// - Parameter retryOnInterrupt: Whether the call should be retried on `Errno.interrupted`. + @_spi(Testing) + public func synchronize(retryOnInterrupt: Bool = true) -> Result { + nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { + system_fsync(self.rawValue) + } + } + + /// Returns a pointer to a directory structure. + /// + /// The corresponding C function is `fdopendir` + /// + /// - Important: Calling this function cedes ownership of the file descriptor to the system. The + /// caller should not modify the descriptor or close the descriptor via `close()`. Once + /// directory iteration has been completed then `Libc.closdir(_:)` must be called. + internal func opendir() -> Result { + valueOrErrno(retryOnInterrupt: false) { + libc_fdopendir(self.rawValue) + } + } +} + +extension FileDescriptor { + func listExtendedAttributes() -> Result<[String], Errno> { + // Required capacity is returned if a no buffer is passed to flistxattr. + self.listExtendedAttributes(nil).flatMap { capacity in + guard capacity > 0 else { + // Required capacity is zero: no attributes to read. + return .success([]) + } + + // Read and decode. + var buffer = [CChar](repeating: 0, count: capacity) + return buffer.withUnsafeMutableBufferPointer { pointer in + self.listExtendedAttributes(pointer) + }.map { size in + // The buffer contains null terminated C-strings. + var attributes = [String]() + var slice = buffer.prefix(size) + while let index = slice.firstIndex(of: 0) { + // TODO: can we do this more cheaply? + let prefix = slice[...index] + attributes.append(String(cString: Array(prefix))) + slice = slice.dropFirst(prefix.count) + } + + return attributes + } + } + } + + func readExtendedAttribute(named name: String) -> Result<[UInt8], Errno> { + // Required capacity is returned if a no buffer is passed to fgetxattr. + self.getExtendedAttribute(named: name, buffer: nil).flatMap { capacity in + guard capacity > 0 else { + // Required capacity is zero: no values to read. + return .success([]) + } + + // Read and decode. + var buffer = [UInt8](repeating: 0, count: capacity) + return buffer.withUnsafeMutableBytes { bytes in + self.getExtendedAttribute(named: name, buffer: bytes) + }.map { size in + // Remove any trailing zeros. + buffer.removeLast(buffer.count - size) + return buffer + } + } + } +} + +extension FileDescriptor { + func readChunk(fromAbsoluteOffset offset: Int64, length: Int64) -> Result { + self._readChunk(fromAbsoluteOffset: offset, length: length) + } + + func readChunk(length: Int64) -> Result { + self._readChunk(fromAbsoluteOffset: nil, length: length) + } + + private func _readChunk( + fromAbsoluteOffset offset: Int64?, + length: Int64 + ) -> Result { + // This is used by the `FileChunks` and means we allocate for every chunk that we read for + // the file. That's fine for now because the syscall cost is likely to be the dominant + // factor here. However we should investigate whether it's possible to have a pool of + // buffers which we can reuse. This would need to be at least as large as the high watermark + // of the chunked file for it to be useful. + Result { + var buffer = ByteBuffer() + try buffer.writeWithUnsafeMutableBytes(minimumWritableBytes: Int(length)) { buffer in + let bufferPointer: UnsafeMutableRawBufferPointer + + // Don't vend a buffer which is larger than `length`; we can read less but we must + // not read more. + if length < buffer.count { + bufferPointer = UnsafeMutableRawBufferPointer( + start: buffer.baseAddress, + count: Int(length) + ) + } else { + bufferPointer = buffer + } + + if let offset { + return try self.read(fromAbsoluteOffset: offset, into: bufferPointer) + } else { + return try self.read(into: bufferPointer) + } + } + return buffer + } + } +} + +extension FileDescriptor { + func write( + contentsOf bytes: some Sequence, + toAbsoluteOffset offset: Int64 + ) -> Result { + Result { + Int64(try self.writeAll(toAbsoluteOffset: offset, bytes)) + } + } + + func write( + contentsOf bytes: some Sequence + ) -> Result { + Result { + Int64(try self.writeAll(bytes)) + } + } +} + +#if canImport(Glibc) || canImport(Musl) || canImport(Bionic) +extension FileDescriptor.OpenOptions { + static var temporaryFile: Self { + Self(rawValue: CNIOLinux_O_TMPFILE) + } +} + +extension FileDescriptor { + static var currentWorkingDirectory: Self { + Self(rawValue: AT_FDCWD) + } +} +#endif diff --git a/Sources/_NIOFileSystem/Internal/System Calls/Mocking.swift b/Sources/_NIOFileSystem/Internal/System Calls/Mocking.swift new file mode 100644 index 000000000..50a48514b --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/Mocking.swift @@ -0,0 +1,380 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +// This source file is part of the Swift System open source project// +// Copyright (c) 2020 Apple Inc. and the Swift System project authors +// Licensed under Apache License v2.0 with Runtime Library Exception// +// See https://swift.org/LICENSE.txt for license information + +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Android) +@preconcurrency import Android +import CNIOLinux +#endif + +// Syscall mocking support. +// +// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do +// eventually want to expose some solution to users. +// +// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking +// state, including whether it is enabled, is stored in thread-local storage. Mocking is only +// enabled in testing builds of System currently, to minimize runtime overhead of release builds. +// + +#if ENABLE_MOCKING +@_spi(Testing) +public struct Trace { + @_spi(Testing) + public struct Entry { + @_spi(Testing) + public var name: String + @_spi(Testing) + public var arguments: [AnyHashable] + + @_spi(Testing) + public init(name: String, _ arguments: [AnyHashable]) { + self.name = name + self.arguments = arguments + } + } + + private var entries: [Entry] = [] + private var firstEntry: Int = 0 + + @_spi(Testing) + public var isEmpty: Bool { firstEntry >= entries.count } + + @_spi(Testing) + public mutating func dequeue() -> Entry? { + guard !self.isEmpty else { return nil } + defer { firstEntry += 1 } + return entries[firstEntry] + } + + fileprivate mutating func add(_ e: Entry) { + entries.append(e) + } +} + +@available(*, unavailable) +extension Trace: Sendable {} + +@available(*, unavailable) +extension Trace.Entry: Sendable {} + +@_spi(Testing) +public enum ForceErrno: Equatable, Sendable { + case none + case always(errno: CInt) + + case counted(errno: CInt, count: Int) +} + +// Provide access to the driver, context, and trace stack of mocking +@_spi(Testing) +public final class MockingDriver { + // Record syscalls and their arguments + @_spi(Testing) + public var trace = Trace() + + // Mock errors inside syscalls + @_spi(Testing) + public var forceErrno = ForceErrno.none + + // Whether we should pretend to be Windows for syntactic operations + // inside FilePath + fileprivate var forceWindowsSyntaxForPaths = false +} + +@available(*, unavailable) +extension MockingDriver: Sendable {} + +private let driverKey: _PlatformTLSKey = { makeTLSKey() }() + +internal var currentMockingDriver: MockingDriver? { + #if !ENABLE_MOCKING + fatalError("Contextual mocking in non-mocking build") + #endif + guard let rawPtr = getTLS(driverKey) else { return nil } + + return Unmanaged.fromOpaque(rawPtr).takeUnretainedValue() +} + +extension MockingDriver { + /// Enables mocking for the duration of `f` with a clean trace queue + /// Restores prior mocking status and trace queue after execution + @_spi(Testing) + public static func withMockingEnabled( + _ f: (MockingDriver) throws -> Void + ) rethrows { + let priorMocking = currentMockingDriver + let driver = MockingDriver() + + defer { + if let object = priorMocking { + setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque()) + } else { + setTLS(driverKey, nil) + } + _fixLifetime(driver) + } + + setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque()) + return try f(driver) + } +} + +// Check TLS for mocking +@inline(never) +private var contextualMockingEnabled: Bool { + currentMockingDriver != nil +} + +extension MockingDriver { + @_spi(Testing) + public static var enabled: Bool { mockingEnabled } + + @_spi(Testing) + public static var forceWindowsPaths: Bool { + currentMockingDriver?.forceWindowsSyntaxForPaths ?? false + } +} + +#endif // ENABLE_MOCKING + +@inline(__always) +internal var mockingEnabled: Bool { + // Fast constant-foldable check for release builds + #if ENABLE_MOCKING + return contextualMockingEnabled + #else + return false + #endif +} + +@inline(__always) +internal var forceWindowsPaths: Bool { + #if !ENABLE_MOCKING + return false + #else + return MockingDriver.forceWindowsPaths + #endif +} + +#if ENABLE_MOCKING +// Strip the mock_system prefix and the arg list suffix +private func originalSyscallName(_ function: String) -> String { + // `function` must be of format `system_()` + for `prefix` in ["system_", "libc_"] { + if function.starts(with: `prefix`) { + return String(function.dropFirst(`prefix`.count).prefix { $0 != "(" }) + } + } + preconditionFailure("\(function) must start with 'system_' or 'libc_'") +} + +private func mockImpl(syscall name: String, args: [AnyHashable]) -> CInt { + precondition(mockingEnabled) + let origName = originalSyscallName(name) + guard let driver = currentMockingDriver else { + fatalError("Mocking requested from non-mocking context") + } + + driver.trace.add(Trace.Entry(name: origName, args)) + + switch driver.forceErrno { + case .none: break + case .always(let e): + system_errno = e + return -1 + case .counted(let e, let count): + assert(count >= 1) + system_errno = e + driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none + return -1 + } + + return 0 +} + +private func reinterpret(_ args: [AnyHashable?]) -> [AnyHashable] { + args.map { arg in + switch arg { + case let charPointer as UnsafePointer: + return String(_errorCorrectingPlatformString: charPointer) + case is UnsafeMutablePointer: + return "" + case is UnsafeMutableRawPointer: + return "" + case is UnsafeRawPointer: + return "" + case .none: + return "nil" + case let .some(arg): + return arg + } + } +} + +func mock( + syscall name: String = #function, + _ args: AnyHashable?... +) -> CInt { + mockImpl(syscall: name, args: reinterpret(args)) +} + +func mockInt( + syscall name: String = #function, + _ args: AnyHashable?... +) -> Int { + Int(mockImpl(syscall: name, args: reinterpret(args))) +} + +#endif // ENABLE_MOCKING + +// Force paths to be treated as Windows syntactically if `enabled` is +// true. +@_spi(Testing) +public func _withWindowsPaths(enabled: Bool, _ body: () -> Void) { + #if ENABLE_MOCKING + guard enabled else { + body() + return + } + MockingDriver.withMockingEnabled { driver in + driver.forceWindowsSyntaxForPaths = true + body() + } + #else + body() + #endif +} + +// Internal wrappers and typedefs which help reduce #if littering in System's +// code base. + +// TODO: Should CSystem just include all the header files we need? + +internal typealias _COffT = off_t + +// MARK: syscalls and variables + +#if canImport(Darwin) +internal var system_errno: CInt { + get { Darwin.errno } + set { Darwin.errno = newValue } +} +#elseif canImport(Glibc) +internal var system_errno: CInt { + get { Glibc.errno } + set { Glibc.errno = newValue } +} +#elseif canImport(Musl) +internal var system_errno: CInt { + get { Musl.errno } + set { Musl.errno = newValue } +} +#elseif canImport(Android) +internal var system_errno: CInt { + get { Android.errno } + set { Android.errno = newValue } +} +#endif + +// MARK: C stdlib decls + +// Convention: `system_foo` is system's wrapper for `foo`. + +internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer! { + strerror(__errnum) +} + +internal func system_strlen(_ s: UnsafePointer) -> Int { + strlen(s) +} +internal func system_strlen(_ s: UnsafeMutablePointer) -> Int { + strlen(s) +} + +// Convention: `system_platform_foo` is a +// platform-representation-abstracted wrapper around `foo`-like functionality. +// Type and layout differences such as the `char` vs `wchar` are abstracted. +// + +// strlen for the platform string +internal func system_platform_strlen(_ s: UnsafePointer) -> Int { + strlen(s) +} + +// memset for raw buffers +// FIXME: Do we really not have something like this in the stdlib already? +internal func system_memset( + _ buffer: UnsafeMutableRawBufferPointer, + to byte: UInt8 +) { + guard buffer.count > 0 else { return } + memset(buffer.baseAddress!, CInt(byte), buffer.count) +} + +// Interop between String and platfrom string +extension String { + internal func _withPlatformString( + _ body: (UnsafePointer) throws -> Result + ) rethrows -> Result { + // Need to #if because CChar may be signed + try withCString(body) + } + + internal init?(_platformString platformString: UnsafePointer) { + // Need to #if because CChar may be signed + self.init(validatingUTF8: platformString) + } + + internal init( + _errorCorrectingPlatformString platformString: UnsafePointer + ) { + // Need to #if because CChar may be signed + self.init(cString: platformString) + } +} + +internal typealias _PlatformTLSKey = pthread_key_t + +internal func makeTLSKey() -> _PlatformTLSKey { + var raw = pthread_key_t() + guard 0 == pthread_key_create(&raw, nil) else { + fatalError("Unable to create key") + } + return raw +} + +internal func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) { + guard 0 == pthread_setspecific(key, p) else { + fatalError("Unable to set TLS") + } +} + +internal func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? { + pthread_getspecific(key) +} diff --git a/Sources/_NIOFileSystem/Internal/System Calls/Syscall.swift b/Sources/_NIOFileSystem/Internal/System Calls/Syscall.swift new file mode 100644 index 000000000..c3965c0f5 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/Syscall.swift @@ -0,0 +1,437 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +import CNIODarwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Bionic) +@preconcurrency import Bionic +import CNIOLinux +#endif + +@_spi(Testing) +public enum Syscall: Sendable { + @_spi(Testing) + public static func stat(path: FilePath) -> Result { + path.withPlatformString { platformPath in + var status = CInterop.Stat() + return valueOrErrno(retryOnInterrupt: false) { + system_stat(platformPath, &status) + }.map { _ in + status + } + } + } + + @_spi(Testing) + public static func lstat(path: FilePath) -> Result { + path.withPlatformString { platformPath in + var status = CInterop.Stat() + return valueOrErrno(retryOnInterrupt: false) { + system_lstat(platformPath, &status) + }.map { _ in + status + } + } + } + + @_spi(Testing) + public static func mkdir(at path: FilePath, permissions: FilePermissions) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + path.withPlatformString { p in + system_mkdir(p, permissions.rawValue) + } + } + } + + @_spi(Testing) + public static func rename(from old: FilePath, to new: FilePath) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + old.withPlatformString { oldPath in + new.withPlatformString { newPath in + system_rename(oldPath, newPath) + } + } + } + } + + #if canImport(Darwin) + @_spi(Testing) + public static func rename( + from old: FilePath, + to new: FilePath, + options: RenameOptions + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + old.withPlatformString { oldPath in + new.withPlatformString { newPath in + system_renamex_np(oldPath, newPath, options.rawValue) + } + } + } + } + + @_spi(Testing) + public struct RenameOptions: OptionSet, Sendable { + public var rawValue: CUnsignedInt + + public init(rawValue: CUnsignedInt) { + self.rawValue = rawValue + } + + public static var exclusive: Self { + Self(rawValue: UInt32(bitPattern: RENAME_EXCL)) + } + + public static var swap: Self { + Self(rawValue: UInt32(bitPattern: RENAME_SWAP)) + } + } + #endif + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + @_spi(Testing) + public static func rename( + from old: FilePath, + relativeTo oldFD: FileDescriptor, + to new: FilePath, + relativeTo newFD: FileDescriptor, + flags: RenameAtFlags + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + old.withPlatformString { oldPath in + new.withPlatformString { newPath in + system_renameat2( + oldFD.rawValue, + oldPath, + newFD.rawValue, + newPath, + flags.rawValue + ) + } + } + } + } + + @_spi(Testing) + public struct RenameAtFlags: OptionSet { + public var rawValue: CUnsignedInt + + public init(rawValue: CUnsignedInt) { + self.rawValue = rawValue + } + + public static var exclusive: Self { + Self(rawValue: CNIOLinux_RENAME_NOREPLACE) + } + + public static var swap: Self { + Self(rawValue: CNIOLinux_RENAME_EXCHANGE) + } + } + #endif + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + @_spi(Testing) + public struct LinkAtFlags: OptionSet { + @_spi(Testing) + public var rawValue: CInt + + @_spi(Testing) + public init(rawValue: CInt) { + self.rawValue = rawValue + } + + @_spi(Testing) + public static var emptyPath: Self { + Self(rawValue: CNIOLinux_AT_EMPTY_PATH) + } + + @_spi(Testing) + public static var followSymbolicLinks: Self { + Self(rawValue: AT_SYMLINK_FOLLOW) + } + } + + @_spi(Testing) + public static func linkAt( + from source: FilePath, + relativeTo sourceFD: FileDescriptor, + to destination: FilePath, + relativeTo destinationFD: FileDescriptor, + flags: LinkAtFlags + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + source.withPlatformString { src in + destination.withPlatformString { dst in + system_linkat( + sourceFD.rawValue, + src, + destinationFD.rawValue, + dst, + flags.rawValue + ) + } + } + } + } + #endif + + @_spi(Testing) + public static func link( + from source: FilePath, + to destination: FilePath + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + source.withPlatformString { src in + destination.withPlatformString { dst in + system_link(src, dst) + } + } + } + } + + @_spi(Testing) + public static func unlink(path: FilePath) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + path.withPlatformString { ptr in + system_unlink(ptr) + } + } + } + + @_spi(Testing) + public static func symlink( + to destination: FilePath, + from source: FilePath + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + source.withPlatformString { src in + destination.withPlatformString { dst in + system_symlink(dst, src) + } + } + } + } + + @_spi(Testing) + public static func readlink(at path: FilePath) -> Result { + do { + let resolved = try path.withPlatformString { p in + try String(customUnsafeUninitializedCapacity: Int(CInterop.maxPathLength)) { pointer in + let result = pointer.withMemoryRebound(to: CInterop.PlatformChar.self) { ptr in + valueOrErrno(retryOnInterrupt: false) { + system_readlink(p, ptr.baseAddress!, ptr.count) + } + } + return try result.get() + } + } + return .success(FilePath(resolved)) + } catch let error as Errno { + return .failure(error) + } catch { + // Shouldn't happen: we deal in Result types and only ever with Errno. + fatalError("Unexpected error '\(error)' caught") + } + } + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + @_spi(Testing) + public static func sendfile( + to output: FileDescriptor, + from input: FileDescriptor, + offset: Int, + size: Int + ) -> Result { + valueOrErrno(retryOnInterrupt: false) { + system_sendfile(output.rawValue, input.rawValue, off_t(offset), size) + } + } + #endif + + @_spi(Testing) + public static func futimens( + fileDescriptor fd: FileDescriptor, + times: UnsafePointer? + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + system_futimens(fd.rawValue, times) + } + } +} + +@_spi(Testing) +public enum Libc: Sendable { + static func readdir( + _ dir: CInterop.DirPointer + ) -> Result?, Errno> { + optionalValueOrErrno(retryOnInterrupt: false) { + libc_readdir(dir) + } + } + + static func closedir( + _ dir: CInterop.DirPointer + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + libc_closedir(dir) + } + } + + #if canImport(Darwin) + @_spi(Testing) + public static func fcopyfile( + from source: FileDescriptor, + to destination: FileDescriptor, + state: copyfile_state_t?, + flags: copyfile_flags_t + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + libc_fcopyfile(source.rawValue, destination.rawValue, state, flags) + } + } + #endif + + #if canImport(Darwin) + @_spi(Testing) + public static func copyfile( + from source: FilePath, + to destination: FilePath, + state: copyfile_state_t?, + flags: copyfile_flags_t + ) -> Result { + source.withPlatformString { sourcePath in + destination.withPlatformString { destinationPath in + nothingOrErrno(retryOnInterrupt: false) { + libc_copyfile(sourcePath, destinationPath, state, flags) + } + } + } + } + #endif + + @_spi(Testing) + public static func remove( + _ path: FilePath + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + path.withPlatformString { + libc_remove($0) + } + } + } + + static func getcwd() -> Result { + var buffer = [CInterop.PlatformChar]( + repeating: 0, + count: Int(CInterop.maxPathLength) + ) + + return optionalValueOrErrno(retryOnInterrupt: false) { + buffer.withUnsafeMutableBufferPointer { pointer in + libc_getcwd(pointer.baseAddress!, pointer.count) + } + }.map { ptr in + // 'ptr' is just the input pointer, we should ignore it and just rely on the bytes + // in buffer. + // + // At this point 'ptr' must be non-nil, because if it were 'nil' we should be on the + // error path. + precondition(ptr != nil) + return FilePath(platformString: buffer) + } + } + + #if !os(Android) + static func constr(_ name: CInt) -> Result { + var buffer = [CInterop.PlatformChar](repeating: 0, count: 128) + + repeat { + let result = valueOrErrno(retryOnInterrupt: false) { + buffer.withUnsafeMutableBufferPointer { pointer in + libc_confstr(name, pointer.baseAddress!, pointer.count) + } + } + + switch result { + case let .success(length): + if length <= buffer.count { + return .success(String(cString: buffer)) + } else { + // The buffer wasn't long enough. Double and try again. + buffer.append(contentsOf: repeatElement(0, count: buffer.capacity)) + } + case let .failure(errno): + return .failure(errno) + } + } while true + } + #endif + + static func ftsOpen(_ path: FilePath, options: FTSOpenOptions) -> Result { + // 'fts_open' needs an unsafe mutable pointer to the C-string, `FilePath` doesn't offer this + // so copy out its bytes. + var pathBytes = path.withPlatformString { pointer in + // Length excludes the null terminator, so add it back. + let bufferPointer = UnsafeBufferPointer(start: pointer, count: path.length + 1) + return Array(bufferPointer) + } + + return valueOrErrno { + pathBytes.withUnsafeMutableBufferPointer { pointer in + // The array must be terminated with a nil. + libc_fts_open([pointer.baseAddress, nil], options.rawValue) + } + } + } + + /// Options passed to 'fts_open'. + struct FTSOpenOptions: OptionSet { + var rawValue: CInt + + /// Don't change directory while walking the filesystem hierarchy. + static var noChangeDir: Self { Self(rawValue: FTS_NOCHDIR) } + + /// Return FTS entries for symbolic links rather than their targets. + static var physical: Self { Self(rawValue: FTS_PHYSICAL) } + + /// Return FTS entries for the targets of symbolic links. + static var logical: Self { Self(rawValue: FTS_LOGICAL) } + } + + static func ftsRead( + _ pointer: CInterop.FTSPointer + ) -> Result?, Errno> { + optionalValueOrErrno { + libc_fts_read(pointer) + } + } + + static func ftsClose( + _ pointer: CInterop.FTSPointer + ) -> Result { + nothingOrErrno { + libc_fts_close(pointer) + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/System Calls/Syscalls.swift b/Sources/_NIOFileSystem/Internal/System Calls/Syscalls.swift new file mode 100644 index 000000000..a87187602 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/System Calls/Syscalls.swift @@ -0,0 +1,481 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +#if canImport(Darwin) +import Darwin +import CNIODarwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Android) +@preconcurrency import Android +import CNIOLinux +#endif + +// MARK: - system + +/// openat(2): Open or create a file for reading or writing +func system_fdopenat( + _ fd: FileDescriptor.RawValue, + _ path: UnsafePointer, + _ oflag: Int32 +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, path, oflag) + } + #endif + return openat(fd, path, oflag) +} + +/// openat(2): Open or create a file for reading or writing +func system_fdopenat( + _ fd: FileDescriptor.RawValue, + _ path: UnsafePointer, + _ oflag: Int32, + _ mode: CInterop.Mode +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, path, oflag, mode) + } + #endif + return openat(fd, path, oflag, mode) +} + +/// stat(2): Get file status +func system_stat( + _ path: UnsafePointer, + _ info: inout CInterop.Stat +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(path) + } + #endif + return stat(path, &info) +} + +/// lstat(2): Get file status +internal func system_lstat( + _ path: UnsafePointer, + _ info: inout CInterop.Stat +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(path) + } + #endif + return lstat(path, &info) +} + +/// fstat(2): Get file status +internal func system_fstat( + _ fd: FileDescriptor.RawValue, + _ info: inout CInterop.Stat +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd) + } + #endif + return fstat(fd, &info) +} + +/// fchmod(2): Change mode of file +internal func system_fchmod( + _ fd: FileDescriptor.RawValue, + _ mode: CInterop.Mode +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, mode) + } + #endif + return fchmod(fd, mode) +} + +/// fsync(2): Synchronize modifications to a file to permanent storage +internal func system_fsync( + _ fd: FileDescriptor.RawValue +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd) + } + #endif + return fsync(fd) +} + +/// mkdir(2): Make a directory file +internal func system_mkdir( + _ path: UnsafePointer, + _ mode: CInterop.Mode +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(path, mode) + } + #endif + return mkdir(path, mode) +} + +/// symlink(2): Make symolic link to a file +internal func system_symlink( + _ destination: UnsafePointer, + _ source: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(destination, source) + } + #endif + return symlink(destination, source) +} + +/// readlink(2): Read value of a symolic link +internal func system_readlink( + _ path: UnsafePointer, + _ buffer: UnsafeMutablePointer, + _ bufferSize: Int +) -> Int { + #if ENABLE_MOCKING + if mockingEnabled { + return mockInt(path, buffer, bufferSize) + } + #endif + return readlink(path, buffer, bufferSize) +} + +/// flistxattr(2): List extended attribute names +internal func system_flistxattr( + _ fd: FileDescriptor.RawValue, + _ namebuf: UnsafeMutablePointer?, + _ size: Int +) -> Int { + #if ENABLE_MOCKING + if mockingEnabled { + return mockInt(fd, namebuf, size) + } + #endif + #if canImport(Darwin) + // The final parameter is 'options'; there is no equivalent on Linux. + return flistxattr(fd, namebuf, size, 0) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + return flistxattr(fd, namebuf, size) + #endif +} + +/// fgetxattr(2): Get an extended attribute value +internal func system_fgetxattr( + _ fd: FileDescriptor.RawValue, + _ name: UnsafePointer, + _ value: UnsafeMutableRawPointer?, + _ size: Int +) -> Int { + #if ENABLE_MOCKING + if mockingEnabled { + return mockInt(fd, name, value, size) + } + #endif + + #if canImport(Darwin) + // Penultimate parameter is position which is reserved and should be zero. + // The final parameter is 'options'; there is no equivalent on Linux. + return fgetxattr(fd, name, value, size, 0, 0) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + return fgetxattr(fd, name, value, size) + #endif +} + +/// fsetxattr(2): Set an extended attribute value +internal func system_fsetxattr( + _ fd: FileDescriptor.RawValue, + _ name: UnsafePointer, + _ value: UnsafeRawPointer?, + _ size: Int +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, name, value, size) + } + #endif + + // The final parameter is 'options'/'flags' on Darwin/Linux respectively. + #if canImport(Darwin) + // Penultimate parameter is position which is reserved and should be zero. + return fsetxattr(fd, name, value, size, 0, 0) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + return fsetxattr(fd, name, value, size, 0) + #endif +} + +/// fremovexattr(2): Remove an extended attribute value +internal func system_fremovexattr( + _ fd: FileDescriptor.RawValue, + _ name: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, name) + } + #endif + + #if canImport(Darwin) + // The final parameter is 'options'; there is no equivalent on Linux. + return fremovexattr(fd, name, 0) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + return fremovexattr(fd, name) + #endif +} + +/// rename(2): Change the name of a file +internal func system_rename( + _ old: UnsafePointer, + _ new: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(old, new) + } + #endif + return rename(old, new) +} + +#if canImport(Darwin) +internal func system_renamex_np( + _ old: UnsafePointer, + _ new: UnsafePointer, + _ flags: CUnsignedInt +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(old, new, flags) + } + #endif + return renamex_np(old, new, flags) +} +#endif + +#if canImport(Glibc) || canImport(Musl) || canImport(Android) +internal func system_renameat2( + _ oldFD: FileDescriptor.RawValue, + _ old: UnsafePointer, + _ newFD: FileDescriptor.RawValue, + _ new: UnsafePointer, + _ flags: CUnsignedInt +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(oldFD, old, newFD, new, flags) + } + #endif + return CNIOLinux_renameat2(oldFD, old, newFD, new, flags) +} +#endif + +/// link(2): Creates a new link for a file. +#if canImport(Glibc) || canImport(Musl) || canImport(Android) +internal func system_linkat( + _ oldFD: FileDescriptor.RawValue, + _ old: UnsafePointer, + _ newFD: FileDescriptor.RawValue, + _ new: UnsafePointer, + _ flags: CInt +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(oldFD, old, newFD, new, flags) + } + #endif + return linkat(oldFD, old, newFD, new, flags) +} +#endif + +/// link(2): Creates a new link for a file. +internal func system_link( + _ old: UnsafePointer, + _ new: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(old, new) + } + #endif + return link(old, new) +} + +/// unlink(2): Remove a directory entry. +internal func system_unlink( + _ path: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(path) + } + #endif + return unlink(path) +} + +#if canImport(Glibc) || canImport(Musl) || canImport(Android) +/// sendfile(2): Transfer data between descriptors +internal func system_sendfile( + _ outFD: CInt, + _ inFD: CInt, + _ offset: off_t, + _ count: Int +) -> Int { + #if ENABLE_MOCKING + if mockingEnabled { + return mockInt(outFD, inFD, offset, count) + } + #endif + var offset = offset + return sendfile(outFD, inFD, &offset, count) +} +#endif + +internal func system_futimens( + _ fd: CInt, + _ times: UnsafePointer? +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, times) + } + #endif + return futimens(fd, times) +} + +// MARK: - libc + +/// fdopendir(3): Opens a directory stream for the file descriptor +internal func libc_fdopendir( + _ fd: FileDescriptor.RawValue +) -> CInterop.DirPointer { + fdopendir(fd)! +} + +/// readdir(3): Returns a pointer to the next directory entry +internal func libc_readdir( + _ dir: CInterop.DirPointer +) -> UnsafeMutablePointer? { + readdir(dir) +} + +/// readdir(3): Closes the directory stream and frees associated structures +internal func libc_closedir( + _ dir: CInterop.DirPointer +) -> CInt { + closedir(dir) +} + +/// remove(3): Remove directory entry +internal func libc_remove( + _ path: UnsafePointer +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(path) + } + #endif + return remove(path) +} + +#if canImport(Darwin) +/// fcopyfile(3): Copy a file from one file to another. +internal func libc_fcopyfile( + _ from: CInt, + _ to: CInt, + _ state: copyfile_state_t?, + _ flags: copyfile_flags_t +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(from, to, state, flags) + } + #endif + return fcopyfile(from, to, state, flags) +} +#endif + +#if canImport(Darwin) +/// copyfile(3): Copy a file from one file to another. +internal func libc_copyfile( + _ from: UnsafePointer, + _ to: UnsafePointer, + _ state: copyfile_state_t?, + _ flags: copyfile_flags_t +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(from, to, state, flags) + } + #endif + return copyfile(from, to, state, flags) +} +#endif + +/// getcwd(3): Get working directory pathname +internal func libc_getcwd( + _ buffer: UnsafeMutablePointer, + _ size: Int +) -> UnsafeMutablePointer? { + getcwd(buffer, size) +} + +/// confstr(3) +#if !os(Android) +internal func libc_confstr( + _ name: CInt, + _ buffer: UnsafeMutablePointer, + _ size: Int +) -> Int { + confstr(name, buffer, size) +} +#endif + +/// fts(3) +internal func libc_fts_open( + _ path: [UnsafeMutablePointer?], + _ options: CInt +) -> UnsafeMutablePointer { + #if os(Android) + // This branch is a workaround for incorrect nullability annotations in the Android SDK. + // They were added in https://android.googlesource.com/platform/bionic/+/dec8efd72a6ad8b807a15a614ae1519487cfa456, + // and lasted for more than a year: https://android.googlesource.com/platform/bionic/+/da81ec4d1cbd0279014feb60535bf38defcd9346. + CNIOLinux_fts_open(path, options, nil)! + #else + fts_open(path, options, nil)! + #endif +} + +/// fts(3) +internal func libc_fts_read( + _ fts: UnsafeMutablePointer +) -> UnsafeMutablePointer? { + fts_read(fts) +} + +/// fts(3) +internal func libc_fts_close( + _ fts: UnsafeMutablePointer +) -> CInt { + fts_close(fts) +} diff --git a/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift b/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift new file mode 100644 index 000000000..1e765a338 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/SystemFileHandle.swift @@ -0,0 +1,1537 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOConcurrencyHelpers +import NIOCore +import NIOPosix +import SystemPackage + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +@preconcurrency import Glibc +import CNIOLinux +#elseif canImport(Musl) +@preconcurrency import Musl +import CNIOLinux +#elseif canImport(Bionic) +@preconcurrency import Bionic +#endif + +/// An implementation of ``FileHandleProtocol`` which is backed by system calls and a file +/// descriptor. +@_spi(Testing) +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public final class SystemFileHandle: Sendable { + /// The executor on which to execute system calls. + internal var threadPool: NIOThreadPool { self.sendableView.threadPool } + + /// The path used to open this handle. + internal var path: FilePath { self.sendableView.path } + + @_spi(Testing) + public struct Materialization: Sendable { + /// The path of the file which was created. + var created: FilePath + /// The desired path of the file. + var desired: FilePath + /// Whether the ``desired`` file must be created exclusively. If `true` then if a file + /// already exists at the ``desired`` path then an error is thrown, otherwise any existing + /// file will be replaced.` + var exclusive: Bool + /// The mode used to materialize the file. + var mode: Mode + + enum Mode { + /// Rename the created file to become the desired file. + case rename + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + /// Link the unnamed file to the desired file using 'linkat(2)'. + case link + #endif + } + } + + fileprivate enum Lifecycle { + case open(FileDescriptor) + case detached + case closed + } + + @_spi(Testing) + public let sendableView: SendableView + + /// The file handle may be for a non-seekable file, so it shouldn't be 'Sendable', however, most + /// of the work performed on behalf of the handle is executed in a thread pool which means that + /// its state must be 'Sendable'. + @_spi(Testing) + public struct SendableView: Sendable { + /// The lifecycle of the file handle. + fileprivate let lifecycle: NIOLockedValueBox + + /// The executor on which to execute system calls. + internal let threadPool: NIOThreadPool + + /// The path used to open this handle. + internal let path: FilePath + + /// An action to take when closing the file handle. + fileprivate let materialization: Materialization? + + fileprivate init( + lifecycle: Lifecycle, + threadPool: NIOThreadPool, + path: FilePath, + materialization: Materialization? + ) { + self.lifecycle = NIOLockedValueBox(lifecycle) + self.threadPool = threadPool + self.path = path + self.materialization = materialization + } + } + + /// Creates a handle which takes ownership of the provided descriptor. + /// + /// - Precondition: The descriptor must be open. + /// - Parameters: + /// - descriptor: The open file descriptor. + /// - path: The path to the file used to open the descriptor. + /// - executor: The executor which system calls will be performed on. + @_spi(Testing) + public init( + takingOwnershipOf descriptor: FileDescriptor, + path: FilePath, + materialization: Materialization? = nil, + threadPool: NIOThreadPool + ) { + self.sendableView = SendableView( + lifecycle: .open(descriptor), + threadPool: threadPool, + path: path, + materialization: materialization + ) + } + + deinit { + self.sendableView.lifecycle.withLockedValue { lifecycle -> Void in + switch lifecycle { + case .open: + fatalError( + """ + Leaking file descriptor: the handle for '\(self.sendableView.path)' MUST be closed or \ + detached with 'close()' or 'detachUnsafeFileDescriptor()' before the final \ + reference to the handle is dropped. + """ + ) + case .detached, .closed: + () + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle.SendableView { + /// Returns the file descriptor if it's available; `nil` otherwise. + internal func descriptorIfAvailable() -> FileDescriptor? { + self.lifecycle.withLockedValue { + switch $0 { + case let .open(descriptor): + return descriptor + case .detached, .closed: + return nil + } + } + } + + /// Executes a closure with the file descriptor if it's available otherwise throws the result + /// of `onUnavailable`. + internal func _withUnsafeDescriptor( + _ execute: (FileDescriptor) throws -> R, + onUnavailable: () -> FileSystemError + ) throws -> R { + if let descriptor = self.descriptorIfAvailable() { + return try execute(descriptor) + } else { + throw onUnavailable() + } + } + + /// Executes a closure with the file descriptor if it's available otherwise returns the result + /// of `onUnavailable` as a `Result` Error. + internal func _withUnsafeDescriptorResult( + _ execute: (FileDescriptor) -> Result, + onUnavailable: () -> FileSystemError + ) -> Result { + if let descriptor = self.descriptorIfAvailable() { + return execute(descriptor) + } else { + return .failure(onUnavailable()) + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle: FileHandleProtocol { + // Notes which apply to the following block of functions: + // + // 1. Documentation is inherited from ``FileHandleProtocol`` and is not repeated here. + // 2. The functions should be annotated with @_spi(Testing); this is not possible with the + // conformance to FileHandleProtocol which requires them to be only marked public. However + // this is not an issue: the implementing type is annotated with @_spi(Testing) so the + // functions are not actually public. + // 3. Most of these functions call through to a synchronous version prefixed with an underscore, + // this is to make testing possible with the system call mocking infrastructure we are + // currently using. + + public func info() async throws -> FileInfo { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._info().get() + } + } + + public func replacePermissions(_ permissions: FilePermissions) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._replacePermissions(permissions) + } + } + + public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._addPermissions(permissions) + } + } + + public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._removePermissions(permissions) + } + } + + public func attributeNames() async throws -> [String] { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._attributeNames() + } + } + + public func valueForAttribute(_ name: String) async throws -> [UInt8] { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._valueForAttribute(name) + } + } + + public func updateValueForAttribute( + _ bytes: some (Sendable & RandomAccessCollection), + attribute name: String + ) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._updateValueForAttribute(bytes, attribute: name) + } + } + + public func removeValueForAttribute(_ name: String) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._removeValueForAttribute(name) + } + } + + public func synchronize() async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._synchronize() + } + } + + public func withUnsafeDescriptor( + _ execute: @Sendable @escaping (FileDescriptor) throws -> R + ) async throws -> R { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._withUnsafeDescriptor { + try execute($0) + } onUnavailable: { + FileSystemError( + code: .closed, + message: "File is closed ('\(sendableView.path)').", + cause: nil, + location: .here() + ) + } + } + } + + public func detachUnsafeFileDescriptor() throws -> FileDescriptor { + try self.sendableView.lifecycle.withLockedValue { lifecycle in + switch lifecycle { + case let .open(descriptor): + lifecycle = .detached + + // We need to be careful handling files which have delayed materialization to avoid + // leftover temporary files. + // + // Where we use the 'link' mode we simply call materialize and return the + // descriptor as it will be materialized when closed. + // + // For the 'rename' mode we create a hard link to the desired file and unlink the + // created file. + guard let materialization = self.sendableView.materialization else { + // File opened 'normally', just detach and return. + return descriptor + } + + switch materialization.mode { + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + case .link: + let result = self.sendableView._materializeLink( + descriptor: descriptor, + from: materialization.created, + to: materialization.desired, + exclusive: materialization.exclusive + ) + return try result.map { descriptor }.get() + #endif + + case .rename: + let result = Syscall.link( + from: materialization.created, + to: materialization.desired + ).mapError { errno in + FileSystemError.link( + errno: errno, + from: materialization.created, + to: materialization.desired, + location: .here() + ) + }.flatMap { + Syscall.unlink(path: materialization.created).mapError { errno in + .unlink(errno: errno, path: materialization.created, location: .here()) + } + } + + return try result.map { descriptor }.get() + } + + case .detached: + throw FileSystemError( + code: .closed, + message: """ + File descriptor has already been detached ('\(self.path)'). Handles may \ + only be detached once. + """, + cause: nil, + location: .here() + ) + + case .closed: + throw FileSystemError( + code: .closed, + message: """ + Cannot detach descriptor for closed file ('\(self.path)'). Handles may \ + only be detached while they are open. + """, + cause: nil, + location: .here() + ) + } + } + } + + public func close() async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._close(materialize: true).get() + } + } + + public func close(makeChangesVisible: Bool) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._close(materialize: makeChangesVisible).get() + } + } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } + } + + @_spi(Testing) + public enum UpdatePermissionsOperation: Sendable { case set, add, remove } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle.SendableView { + /// Returns a string in the format: "{message}, the file '{path}' is closed." + private func fileIsClosed(_ message: String) -> String { + "\(message), the file '\(self.path)' is closed." + } + + /// Returns a string in the format: "{message} for '{path}'." + private func unknown(_ message: String) -> String { + "\(message) for '\(self.path)'." + } + + @_spi(Testing) + public func _info() -> Result { + self._withUnsafeDescriptorResult { descriptor in + descriptor.status().map { stat in + FileInfo(platformSpecificStatus: stat) + }.mapError { errno in + .stat("fstat", errno: errno, path: self.path, location: .here()) + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Unable to get information"), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _replacePermissions(_ permissions: FilePermissions) throws { + try self._withUnsafeDescriptor { descriptor in + try self.updatePermissions( + permissions, + operation: .set, + operand: permissions, + descriptor: descriptor + ) + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Unable to replace permissions"), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _addPermissions(_ permissions: FilePermissions) throws -> FilePermissions { + try self._withUnsafeDescriptor { descriptor in + switch descriptor.status() { + case let .success(status): + let info = FileInfo(platformSpecificStatus: status) + let merged = info.permissions.union(permissions) + + // Check if we need to make any changes. + if merged == info.permissions { + return merged + } + + // Apply the new permissions. + try self.updatePermissions( + merged, + operation: .add, + operand: permissions, + descriptor: descriptor + ) + + return merged + + case let .failure(errno): + throw FileSystemError( + message: "Unable to add permissions.", + wrapping: .stat("fstat", errno: errno, path: self.path, location: .here()) + ) + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Unable to add permissions"), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _removePermissions(_ permissions: FilePermissions) throws -> FilePermissions { + try self._withUnsafeDescriptor { descriptor in + switch descriptor.status() { + case let .success(status): + let info = FileInfo(platformSpecificStatus: status) + let merged = info.permissions.subtracting(permissions) + + // Check if we need to make any changes. + if merged == info.permissions { + return merged + } + + // Apply the new permissions. + try self.updatePermissions( + merged, + operation: .remove, + operand: permissions, + descriptor: descriptor + ) + + return merged + + case let .failure(errno): + throw FileSystemError( + message: "Unable to remove permissions.", + wrapping: .stat("fstat", errno: errno, path: self.path, location: .here()) + ) + + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Unable to remove permissions"), + cause: nil, + location: .here() + ) + } + } + + private func updatePermissions( + _ permissions: FilePermissions, + operation: SystemFileHandle.UpdatePermissionsOperation, + operand: FilePermissions, + descriptor: FileDescriptor + ) throws { + try descriptor.changeMode(permissions).mapError { errno in + FileSystemError.fchmod( + operation: operation, + operand: operand, + permissions: permissions, + errno: errno, + path: self.path, + location: .here() + ) + }.get() + } + + @_spi(Testing) + public func _attributeNames() throws -> [String] { + try self._withUnsafeDescriptor { descriptor in + try descriptor.listExtendedAttributes().mapError { errno in + FileSystemError.flistxattr(errno: errno, path: self.path, location: .here()) + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Could not list extended attributes"), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _valueForAttribute(_ name: String) throws -> [UInt8] { + try self._withUnsafeDescriptor { descriptor in + try descriptor.readExtendedAttribute( + named: name + ).flatMapError { errno -> Result<[UInt8], FileSystemError> in + switch errno { + #if canImport(Darwin) + case .attributeNotFound: + // Okay, return empty value. + return .success([]) + #endif + case .noData: + // Okay, return empty value. + return .success([]) + default: + let error = FileSystemError.fgetxattr( + attribute: name, + errno: errno, + path: self.path, + location: .here() + ) + return .failure(error) + } + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed( + "Could not get value for extended attribute ('\(name)')" + ), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _updateValueForAttribute( + _ bytes: some RandomAccessCollection, + attribute name: String + ) throws { + try self._withUnsafeDescriptor { descriptor in + func withUnsafeBufferPointer(_ body: (UnsafeBufferPointer) throws -> Void) throws { + try bytes.withContiguousStorageIfAvailable(body) + ?? Array(bytes).withUnsafeBufferPointer(body) + } + + try withUnsafeBufferPointer { pointer in + let rawBufferPointer = UnsafeRawBufferPointer(pointer) + return try descriptor.setExtendedAttribute( + named: name, + to: rawBufferPointer + ).mapError { errno in + FileSystemError.fsetxattr( + attribute: name, + errno: errno, + path: self.path, + location: .here() + ) + }.get() + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed( + "Could not set value for extended attribute ('\(name)')" + ), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _removeValueForAttribute(_ name: String) throws { + try self._withUnsafeDescriptor { descriptor in + try descriptor.removeExtendedAttribute(name).mapError { errno in + FileSystemError.fremovexattr( + attribute: name, + errno: errno, + path: self.path, + location: .here() + ) + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Could not remove extended attribute ('\(name)')"), + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _synchronize() throws { + try self._withUnsafeDescriptor { descriptor in + try descriptor.synchronize().mapError { errno in + FileSystemError.fsync(errno: errno, path: self.path, location: .here()) + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: self.fileIsClosed("Could not synchronize"), + cause: nil, + location: .here() + ) + } + } + + internal func _duplicate() -> Result { + self._withUnsafeDescriptorResult { descriptor in + Result { + try descriptor.duplicate() + }.mapError { error in + FileSystemError.dup(error: error, path: self.path, location: .here()) + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Unable to duplicate descriptor of closed handle for '\(self.path)'.", + cause: nil, + location: .here() + ) + } + } + + @_spi(Testing) + public func _close(materialize: Bool, failRenameat2WithEINVAL: Bool = false) -> Result { + let descriptor: FileDescriptor? = self.lifecycle.withLockedValue { lifecycle in + switch lifecycle { + case let .open(descriptor): + lifecycle = .closed + return descriptor + case .detached, .closed: + return nil + } + } + + guard let descriptor = descriptor else { + return .success(()) + } + + // Materialize then close. + let materializeResult = self._materialize( + materialize, + descriptor: descriptor, + failRenameat2WithEINVAL: failRenameat2WithEINVAL + ) + + return Result { + try descriptor.close() + }.mapError { error in + .close(error: error, path: self.path, location: .here()) + }.flatMap { + materializeResult + } + } + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + fileprivate func _materializeLink( + descriptor: FileDescriptor, + from createdPath: FilePath, + to desiredPath: FilePath, + exclusive: Bool + ) -> Result { + func linkAtEmptyPath() -> Result { + Syscall.linkAt( + from: "", + relativeTo: descriptor, + to: desiredPath, + relativeTo: .currentWorkingDirectory, + flags: [.emptyPath] + ) + } + + func linkAtProcFS() -> Result { + Syscall.linkAt( + from: FilePath("/proc/self/fd/\(descriptor.rawValue)"), + relativeTo: .currentWorkingDirectory, + to: desiredPath, + relativeTo: .currentWorkingDirectory, + flags: [.followSymbolicLinks] + ) + } + + let result: Result + + switch linkAtEmptyPath() { + case .success: + result = .success(()) + + case .failure(.fileExists) where !exclusive: + // File exists and materialization _isn't_ exclusive. Remove the existing + // file and try again. + let removeResult = Libc.remove(desiredPath).mapError { errno in + FileSystemError.remove(errno: errno, path: desiredPath, location: .here()) + } + + let linkAtResult = linkAtEmptyPath().flatMapError { errno in + // ENOENT means we likely didn't have the 'CAP_DAC_READ_SEARCH' capability + // so try again by linking to the descriptor via procfs. + if errno == .noSuchFileOrDirectory { + return linkAtProcFS() + } else { + return .failure(errno) + } + }.mapError { errno in + FileSystemError.link( + errno: errno, + from: createdPath, + to: desiredPath, + location: .here() + ) + } + + result = removeResult.flatMap { linkAtResult } + + case .failure(.noSuchFileOrDirectory): + result = linkAtProcFS().flatMapError { errno in + if errno == .fileExists, !exclusive { + return Libc.remove(desiredPath).mapError { errno in + FileSystemError.remove( + errno: errno, + path: desiredPath, + location: .here() + ) + }.flatMap { + linkAtProcFS().mapError { errno in + FileSystemError.link( + errno: errno, + from: createdPath, + to: desiredPath, + location: .here() + ) + } + } + } else { + let error = FileSystemError.link( + errno: errno, + from: createdPath, + to: desiredPath, + location: .here() + ) + return .failure(error) + } + } + + case .failure(let errno): + result = .failure( + .link(errno: errno, from: createdPath, to: desiredPath, location: .here()) + ) + } + + return result + } + #endif + + func _materialize( + _ materialize: Bool, + descriptor: FileDescriptor, + failRenameat2WithEINVAL: Bool + ) -> Result { + guard let materialization = self.materialization else { return .success(()) } + + let createdPath = materialization.created + let desiredPath = materialization.desired + + let result: Result + switch materialization.mode { + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + case .link: + if materialize { + result = self._materializeLink( + descriptor: descriptor, + from: createdPath, + to: desiredPath, + exclusive: materialization.exclusive + ) + } else { + result = .success(()) + } + #endif + + case .rename: + if materialize { + var renameResult: Result + let renameFunction: String + #if canImport(Darwin) + renameFunction = "renamex_np" + renameResult = Syscall.rename( + from: createdPath, + to: desiredPath, + options: materialization.exclusive ? [.exclusive] : [] + ) + #elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) + // The created and desired paths are absolute, so the relative descriptors are + // ignored. However, they must still be provided to 'rename' in order to pass + // flags. + renameFunction = "renameat2" + if materialization.exclusive, failRenameat2WithEINVAL { + renameResult = .failure(.invalidArgument) + } else { + renameResult = Syscall.rename( + from: createdPath, + relativeTo: .currentWorkingDirectory, + to: desiredPath, + relativeTo: .currentWorkingDirectory, + flags: materialization.exclusive ? [.exclusive] : [] + ) + } + #endif + + if materialization.exclusive { + switch renameResult { + case .failure(.fileExists): + // A file exists at the desired path and the user specified exclusive + // creation, clear up by removing the file that we did create. + _ = Libc.remove(createdPath) + + case .failure(.invalidArgument): + // If 'renameat2' failed on Linux with EINVAL then in all likelihood the + // 'RENAME_NOREPLACE' option isn't supported. As we're doing an exclusive + // create, check the desired path doesn't exist then do a regular rename. + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + switch Syscall.stat(path: desiredPath) { + case .failure(.noSuchFileOrDirectory): + // File doesn't exist, do a 'regular' rename. + renameResult = Syscall.rename(from: createdPath, to: desiredPath) + + case .success: + // File exists so exclusive create isn't possible. Remove the file + // we did create then throw. + _ = Libc.remove(createdPath) + let error = FileSystemError( + code: .fileAlreadyExists, + message: """ + Couldn't open '\(desiredPath)', it already exists and the \ + file was opened with the 'existingFile' option set to 'none'. + """, + cause: nil, + location: .here() + ) + return .failure(error) + + case .failure: + // Failed to stat the desired file for reasons unknown. Remove the file + // we did create then throw. + _ = Libc.remove(createdPath) + let error = FileSystemError( + code: .unknown, + message: "Couldn't open '\(desiredPath)'.", + cause: FileSystemError.rename( + "renameat2", + errno: .invalidArgument, + oldName: createdPath, + newName: desiredPath, + location: .here() + ), + location: .here() + ) + return .failure(error) + } + #else + () // Not Linux, use the normal error flow. + #endif + + case .success, .failure: + () + } + } + + result = renameResult.mapError { errno in + .rename( + renameFunction, + errno: errno, + oldName: createdPath, + newName: desiredPath, + location: .here() + ) + } + } else { + // Don't materialize the source, remove it + result = Libc.remove(createdPath).mapError { + .remove(errno: $0, path: createdPath, location: .here()) + } + } + } + + return result + } + + func _setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) throws { + try self._withUnsafeDescriptor { descriptor in + let syscallResult: Result + switch (lastAccess, lastDataModification) { + case (.none, .none): + // If the timespec array is nil, as per the `futimens` docs, + // both the last accessed and last modification times + // will be set to now. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: nil + ) + + case (.some(let lastAccess), .none): + // Don't modify the last modification time. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(lastAccess), timespec(.omit)] + ) + + case (.none, .some(let lastDataModification)): + // Don't modify the last access time. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(.omit), timespec(lastDataModification)] + ) + + case (.some(let lastAccess), .some(let lastDataModification)): + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(lastAccess), timespec(lastDataModification)] + ) + } + + try syscallResult.mapError { errno in + FileSystemError.futimens( + errno: errno, + path: self.path, + lastAccessTime: lastAccess, + lastDataModificationTime: lastDataModification, + location: .here() + ) + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Couldn't modify file dates, the file '\(self.path)' is closed.", + cause: nil, + location: .here() + ) + } + } +} + +extension timespec { + fileprivate init(_ fileinfoTimespec: FileInfo.Timespec) { + // Clamp seconds to be positive + let seconds = max(0, fileinfoTimespec.seconds) + + // If nanoseconds are not UTIME_NOW or UTIME_OMIT, clamp to be between + // 0 and 1,000 million. + let nanoseconds: Int + switch fileinfoTimespec { + case .now, .omit: + nanoseconds = fileinfoTimespec.nanoseconds + default: + nanoseconds = min(1_000_000_000, max(0, fileinfoTimespec.nanoseconds)) + } + + self.init( + tv_sec: seconds, + tv_nsec: nanoseconds + ) + } +} + +// MARK: - Readable File Handle + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle: ReadableFileHandleProtocol { + // Notes which apply to the following block of functions: + // + // 1. Documentation is inherited from ``FileHandleProtocol`` and is not repeated here. + // 2. The functions should be annotated with @_spi(Testing); this is not possible with the + // conformance to FileHandleProtocol which requires them to be only marked public. However + // this is not an issue: the implementing type is annotated with @_spi(Testing) so the + // functions are not actually public. + + public func readChunk( + fromAbsoluteOffset offset: Int64, + length: ByteCount + ) async throws -> ByteBuffer { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._withUnsafeDescriptor { descriptor in + try descriptor.readChunk( + fromAbsoluteOffset: offset, + length: length.bytes + ).flatMapError { error in + if let errno = error as? Errno, errno == .illegalSeek { + guard offset == 0 else { + return .failure( + FileSystemError( + code: .unsupported, + message: "File is unseekable.", + cause: nil, + location: .here() + ) + ) + } + + return descriptor.readChunk(length: length.bytes).mapError { error in + FileSystemError.read( + usingSyscall: .read, + error: error, + path: sendableView.path, + location: .here() + ) + } + } else { + return .failure( + FileSystemError.read( + usingSyscall: .pread, + error: error, + path: sendableView.path, + location: .here() + ) + ) + } + } + .get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Couldn't read chunk, the file '\(sendableView.path)' is closed.", + cause: nil, + location: .here() + ) + } + } + } + + public func readChunks( + in range: Range, + chunkLength size: ByteCount + ) -> FileChunks { + FileChunks(handle: self, chunkLength: size, range: range) + } +} + +// MARK: - Writable File Handle + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle: WritableFileHandleProtocol { + @discardableResult + public func write( + contentsOf bytes: some (Sequence & Sendable), + toAbsoluteOffset offset: Int64 + ) async throws -> Int64 { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._withUnsafeDescriptor { descriptor in + try descriptor.write(contentsOf: bytes, toAbsoluteOffset: offset) + .flatMapError { error in + if let errno = error as? Errno, errno == .illegalSeek { + guard offset == 0 else { + return .failure( + FileSystemError( + code: .unsupported, + message: "File is unseekable.", + cause: nil, + location: .here() + ) + ) + } + + return descriptor.write(contentsOf: bytes) + .mapError { error in + FileSystemError.write( + usingSyscall: .write, + error: error, + path: sendableView.path, + location: .here() + ) + } + } else { + return .failure( + FileSystemError.write( + usingSyscall: .pwrite, + error: error, + path: sendableView.path, + location: .here() + ) + ) + } + } + .get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Couldn't write bytes, the file '\(sendableView.path)' is closed.", + cause: nil, + location: .here() + ) + } + } + } + + public func resize(to size: ByteCount) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._resize(to: size).get() + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle.SendableView { + func _resize(to size: ByteCount) -> Result<(), FileSystemError> { + self._withUnsafeDescriptorResult { descriptor in + Result { + try descriptor.resize(to: size.bytes, retryOnInterrupt: true) + }.mapError { error in + FileSystemError.ftruncate(error: error, path: self.path, location: .here()) + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Unable to resize file '\(self.path)'.", + cause: nil, + location: .here() + ) + } + } +} + +// MARK: - Directory File Handle + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle: DirectoryFileHandleProtocol { + public typealias ReadFileHandle = SystemFileHandle + public typealias WriteFileHandle = SystemFileHandle + public typealias ReadWriteFileHandle = SystemFileHandle + + public func listContents(recursive: Bool) -> DirectoryEntries { + DirectoryEntries(handle: self, recursive: recursive) + } + + public func openFile( + forReadingAt path: FilePath, + options: OpenOptions.Read + ) async throws -> SystemFileHandle { + let opts = options.descriptorOptions.union(.nonBlocking) + let handle = try await self.threadPool.runIfActive { [sendableView] in + let handle = try sendableView._open( + atPath: path, + mode: .readOnly, + options: opts, + transactionalIfPossible: false + ).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + public func openFile( + forReadingAndWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> SystemFileHandle { + let perms = options.permissionsForRegularFile + let opts = options.descriptorOptions.union(.nonBlocking) + let handle = try await self.threadPool.runIfActive { [sendableView] in + let handle = try sendableView._open( + atPath: path, + mode: .readWrite, + options: opts, + permissions: perms, + transactionalIfPossible: options.newFile?.transactionalCreation ?? false + ).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + public func openFile( + forWritingAt path: FilePath, + options: OpenOptions.Write + ) async throws -> SystemFileHandle { + let perms = options.permissionsForRegularFile + let opts = options.descriptorOptions.union(.nonBlocking) + let handle = try await self.threadPool.runIfActive { [sendableView] in + let handle = try sendableView._open( + atPath: path, + mode: .writeOnly, + options: opts, + permissions: perms, + transactionalIfPossible: options.newFile?.transactionalCreation ?? false + ).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } + + public func openDirectory( + atPath path: FilePath, + options: OpenOptions.Directory + ) async throws -> SystemFileHandle { + let opts = options.descriptorOptions.union(.nonBlocking) + let handle = try await self.threadPool.runIfActive { [sendableView] in + let handle = try sendableView._open( + atPath: path, + mode: .readOnly, + options: opts, + transactionalIfPossible: false + ).get() + // Okay to transfer: we just created it and are now moving back to the callers task. + return UnsafeTransfer(handle) + } + return handle.wrappedValue + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle.SendableView { + func _open( + atPath path: FilePath, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions, + permissions: FilePermissions? = nil, + transactionalIfPossible transactional: Bool + ) -> Result { + if transactional { + if path.isAbsolute { + // The provided path is absolute: just open the handle normally. + return SystemFileHandle.syncOpen( + atPath: path, + mode: mode, + options: options, + permissions: permissions, + transactionalIfPossible: transactional, + threadPool: self.threadPool + ) + } else if self.path.isAbsolute { + // The parent path is absolute and the provided path is relative; combine them. + return SystemFileHandle.syncOpen( + atPath: self.path.appending(path.components), + mode: mode, + options: options, + permissions: permissions, + transactionalIfPossible: transactional, + threadPool: self.threadPool + ) + } + + // At this point transactional file creation isn't possible. Fallback to + // non-transactional. + } + + // Provided and parent paths are relative. There's no way we can safely delay + // materialization as we don't know if the parent descriptor will be available when + // closing the opened file. + return self._withUnsafeDescriptorResult { descriptor in + descriptor.open( + atPath: path, + mode: mode, + options: options, + permissions: permissions + ).map { newDescriptor in + SystemFileHandle( + takingOwnershipOf: newDescriptor, + path: self.path.appending(path.components).lexicallyNormalized(), + threadPool: self.threadPool + ) + }.mapError { errno in + .open("openat", error: errno, path: self.path, location: .here()) + } + } onUnavailable: { + FileSystemError( + code: .closed, + message: """ + Unable to open file at path '\(path)' relative to '\(self.path)', the file \ + is closed. + """, + cause: nil, + location: .here() + ) + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension SystemFileHandle { + static func syncOpen( + atPath path: FilePath, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions, + permissions: FilePermissions?, + transactionalIfPossible transactional: Bool, + threadPool: NIOThreadPool + ) -> Result { + let isWritable = (mode == .writeOnly || mode == .readWrite) + let exclusiveCreate = options.contains(.exclusiveCreate) + let truncate = options.contains(.truncate) + let delayMaterialization = transactional && isWritable && (exclusiveCreate || truncate) + + if delayMaterialization { + // When opening in this mode we can more "atomically" create the file, that is, by not + // leaving the user with a half written file should e.g. the system crash or throw an + // error while writing. On non-Android Linux we do this by opening the directory for + // the path with `O_TMPFILE` and creating a hard link when closing the file. On other + // platforms we generate a dot file with a randomised suffix name and rename it to the + // destination. + #if os(Android) + let temporaryHardLink = false + #else + let temporaryHardLink = true + #endif + return Self.syncOpenWithMaterialization( + atPath: path, + mode: mode, + options: options, + permissions: permissions, + threadPool: threadPool, + useTemporaryFileIfPossible: temporaryHardLink + ) + } else { + return Self.syncOpen( + atPath: path, + mode: mode, + options: options, + permissions: permissions, + threadPool: threadPool + ) + } + } + + static func syncOpen( + atPath path: FilePath, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions, + permissions: FilePermissions?, + threadPool: NIOThreadPool + ) -> Result { + Result { + try FileDescriptor.open( + path, + mode, + options: options, + permissions: permissions + ) + }.map { descriptor in + SystemFileHandle( + takingOwnershipOf: descriptor, + path: path, + threadPool: threadPool + ) + }.mapError { errno in + FileSystemError.open("open", error: errno, path: path, location: .here()) + } + } + + @_spi(Testing) + public static func syncOpenWithMaterialization( + atPath path: FilePath, + mode: FileDescriptor.AccessMode, + options originalOptions: FileDescriptor.OpenOptions, + permissions: FilePermissions?, + threadPool: NIOThreadPool, + useTemporaryFileIfPossible: Bool = true + ) -> Result { + let openedPath: FilePath + let desiredPath: FilePath + + // There are two different approaches to materializing the file. On Linux, and where + // supported, we can open the file with the 'O_TMPFILE' flag which creates a temporary + // unnamed file. If we later decide the make the file visible we use 'linkat(2)' with + // the appropriate flags to link the unnamed temporary file to the desired file path. + // + // On other platforms, and when not supported on Linux, we create a regular file as we + // normally would and when we decide to materialize it we simply rename it to the desired + // name (or remove it if we aren't materializing it). + // + // There are, however, some wrinkles. + // + // Normally when a file is opened the system will open files specified with relative paths + // relative to the current working directory. However, when we delay making a file visible + // the current working directory could change which introduces an awkward race. Consider + // the following sequence of events: + // + // 1. User opens a file with delay materialization using a relative path + // 2. A temporary file is opened relative to the current working directory + // 3. The current working directory is changed + // 4. The file is closed. + // + // Where is the file created? It *should* be relative to the working directory at the time + // the user opened the file. However, if materializing the file relative to the new + // working directory would be very surprising behaviour for the user. + // + // To work around this we will get the current working directory only if the provided path + // is relative. That way all operations can be done on a path relative to a fixed point + // (i.e. the current working directory at this point in time). + if path.isRelative { + let currentWorkingDirectory: FilePath + + switch Libc.getcwd() { + case .success(let path): + currentWorkingDirectory = path + case .failure(let errno): + let error = FileSystemError( + message: """ + Can't open relative '\(path)' as the current working directory couldn't \ + be determined. + """, + wrapping: .getcwd(errno: errno, location: .here()) + ) + return .failure(error) + } + + func makePath() -> FilePath { + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + if useTemporaryFileIfPossible { + return currentWorkingDirectory.appending(path.components.dropLast()) + } + #endif + return currentWorkingDirectory.appending(path.components.dropLast()) + .appending(".tmp-" + String(randomAlphaNumericOfLength: 6)) + } + + openedPath = makePath() + desiredPath = currentWorkingDirectory.appending(path.components) + } else { + func makePath() -> FilePath { + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + if useTemporaryFileIfPossible { + return path.removingLastComponent() + } + #endif + return path.removingLastComponent() + .appending(".tmp-" + String(randomAlphaNumericOfLength: 6)) + } + + openedPath = makePath() + desiredPath = path + } + + let materializationMode: Materialization.Mode + let options: FileDescriptor.OpenOptions + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + if useTemporaryFileIfPossible { + options = [.temporaryFile] + materializationMode = .link + } else { + options = originalOptions + materializationMode = .rename + } + #else + options = originalOptions + materializationMode = .rename + #endif + + let materialization = Materialization( + created: openedPath, + desired: desiredPath, + exclusive: originalOptions.contains(.exclusiveCreate), + mode: materializationMode + ) + + do { + let descriptor = try FileDescriptor.open( + openedPath, + mode, + options: options, + permissions: permissions + ) + + let handle = SystemFileHandle( + takingOwnershipOf: descriptor, + path: openedPath, + materialization: materialization, + threadPool: threadPool + ) + + return .success(handle) + } catch { + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + // 'O_TMPFILE' isn't supported for the current file system, try again but using + // rename instead. + if useTemporaryFileIfPossible, let errno = error as? Errno, errno == .notSupported { + return Self.syncOpenWithMaterialization( + atPath: path, + mode: mode, + options: originalOptions, + permissions: permissions, + threadPool: threadPool, + useTemporaryFileIfPossible: false + ) + } + #endif + return .failure(.open("open", error: error, path: path, location: .here())) + } + } +} diff --git a/Sources/_NIOFileSystem/Internal/Utilities.swift b/Sources/_NIOFileSystem/Internal/Utilities.swift new file mode 100644 index 000000000..84440f106 --- /dev/null +++ b/Sources/_NIOFileSystem/Internal/Utilities.swift @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +@usableFromInline +internal final class Ref { + @usableFromInline + var value: Value + @inlinable + init(_ value: Value) { + self.value = value + } +} + +@available(*, unavailable) +extension Ref: Sendable {} + +extension String { + init(randomAlphaNumericOfLength length: Int) { + precondition(length > 0) + + let characters = (0..=6.2) +public typealias _NIOFileSystemSendableMetatype = SendableMetatype +#else +public typealias _NIOFileSystemSendableMetatype = Any +#endif diff --git a/Sources/_NIOFileSystem/OpenOptions.swift b/Sources/_NIOFileSystem/OpenOptions.swift new file mode 100644 index 000000000..a20898852 --- /dev/null +++ b/Sources/_NIOFileSystem/OpenOptions.swift @@ -0,0 +1,297 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import SystemPackage + +/// Options for opening file handles. +public enum OpenOptions: Sendable { + /// Options for opening a file for reading. + public struct Read: Hashable, Sendable { + /// If the last path component is a symbolic link then this flag determines whether the + /// link is followed. If `false` and the last path component is a symbolic link then an + /// error is thrown. + public var followSymbolicLinks: Bool + + /// Marks the descriptor of the opened file as 'close-on-exec'. + public var closeOnExec: Bool + + /// Creates a new set of options for opening a file for reading. + /// + /// - Parameters: + /// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`. + /// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults + /// to `false`. + public init( + followSymbolicLinks: Bool = true, + closeOnExec: Bool = false + ) { + self.followSymbolicLinks = followSymbolicLinks + self.closeOnExec = closeOnExec + } + } + + /// Options for opening a directory. + public struct Directory: Hashable, Sendable { + /// If the last path component is a symbolic link then this flag determines whether the + /// link is followed. If `false` and the last path component is a symbolic link then an + /// error is thrown. + public var followSymbolicLinks: Bool + + /// Marks the descriptor of the opened file as 'close-on-exec'. + public var closeOnExec: Bool + + /// Creates a new set of options for opening a directory. + /// + /// - Parameters: + /// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`. + /// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults + /// to `false`. + public init( + followSymbolicLinks: Bool = true, + closeOnExec: Bool = false + ) { + self.followSymbolicLinks = followSymbolicLinks + self.closeOnExec = closeOnExec + } + } + + /// Options for opening a file for writing (or reading and writing). + /// + /// You can use the following methods to create commonly used sets of options: + /// - ``newFile(replaceExisting:permissions:)`` to create a new file, optionally replacing + /// one which already exists. + /// - ``modifyFile(createIfNecessary:permissions:)`` to modify an existing file, optionally + /// creating it if it doesn't exist. + public struct Write: Hashable, Sendable { + /// The behavior for opening an existing file. + public var existingFile: OpenOptions.ExistingFile + + /// The creation options for a new file, if one should be created. `nil` means that no + /// file should be created. + public var newFile: OpenOptions.NewFile? + + /// If the last path component is a symbolic link then this flag determines whether the + /// link is followed. If `false` and the last path component is a symbolic link then an + /// error is thrown. + public var followSymbolicLinks: Bool + + /// Marks the descriptor of the opened file as 'close-on-exec'. + public var closeOnExec: Bool + + /// Creates a new set of options for opening a directory. + /// + /// - Parameters: + /// - existingFile: Options for handling an existing file. + /// - newFile: Options for creating a new file. + /// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`. + /// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults + /// to `false`. + public init( + existingFile: OpenOptions.ExistingFile, + newFile: OpenOptions.NewFile?, + followSymbolicLinks: Bool = true, + closeOnExec: Bool = false + ) { + self.existingFile = existingFile + self.newFile = newFile + self.followSymbolicLinks = followSymbolicLinks + self.closeOnExec = closeOnExec + } + + /// Create a new file for writing to. + /// + /// - Parameters: + /// - replaceExisting: Whether any existing file of the same name is replaced. If + /// this is `true` then any existing file of the same name will be replaced with the + /// new file. If this is `false` and a file already exists an error is thrown. + /// - permissions: The permissions to apply to the newly created file. Default permissions + /// (read-write owner permissions and read permissions for everyone else) are applied + /// if `nil`. + /// - Returns: Options for creating a new file for writing. + public static func newFile( + replaceExisting: Bool, + permissions: FilePermissions? = nil + ) -> Self { + Write( + existingFile: replaceExisting ? .truncate : .none, + newFile: NewFile(permissions: permissions) + ) + } + + /// Opens a file for modifying. + /// + /// - Parameters: + /// - createIfNecessary: Whether a file should be created if one doesn't exist. If + /// `false` and a file doesn't exist then an error is thrown. + /// - permissions: The permissions to apply to the newly created file. Default permissions + /// (read-write owner permissions and read permissions for everyone else) are applied + /// if `nil`. Ignored if `createIfNonExistent` is `false`. + /// - Returns: Options for modifying an existing file for writing. + public static func modifyFile( + createIfNecessary: Bool, + permissions: FilePermissions? = nil + ) -> Self { + Write( + existingFile: .open, + newFile: createIfNecessary ? NewFile(permissions: permissions) : nil + ) + } + } +} + +extension OpenOptions { + /// Options for opening an existing file. + public enum ExistingFile: Sendable, Hashable { + /// Indicates that no file exists. If a file does exist then an error is thrown when + /// opening the file. + case none + + /// Any existing file should be opened without modification. + case open + + /// Truncate the existing file. + /// + /// Setting this is equivalent to opening a file with `O_TRUNC`. + case truncate + } + + /// Options for creating a new file. + public struct NewFile: Sendable, Hashable { + /// The permissions to apply to the new file. `nil` implies default permissions + /// should be applied. + public var permissions: FilePermissions? + + /// Whether the file should be created and updated as a single transaction, if + /// applicable. + /// + /// When this option is set and applied the newly created file will only materialize + /// on the file system when the file is closed. When used in conjunction with + /// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka`` and + /// ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` the + /// file will only materialize when the file is closed and no errors have been thrown. + /// + /// - Important: This flag is only applied if ``OpenOptions/Write/existingFile`` is + /// ``OpenOptions/ExistingFile/none``. + public var transactionalCreation: Bool + + public init( + permissions: FilePermissions? = nil, + transactionalCreation: Bool = true + ) { + self.permissions = permissions + self.transactionalCreation = transactionalCreation + } + } +} + +extension OpenOptions.Write { + @_spi(Testing) + public var permissionsForRegularFile: FilePermissions? { + if let newFile = self.newFile { + return newFile.permissions ?? .defaultsForRegularFile + } else { + return nil + } + } + + var descriptorOptions: FileDescriptor.OpenOptions { + var options = FileDescriptor.OpenOptions() + + if !self.followSymbolicLinks { + options.insert(.noFollow) + } + + if self.closeOnExec { + options.insert(.closeOnExec) + } + + if self.newFile != nil { + options.insert(.create) + } + + switch self.existingFile { + case .none: + options.insert(.exclusiveCreate) + case .open: + () + case .truncate: + options.insert(.truncate) + } + + return options + } +} + +extension OpenOptions.Read { + var descriptorOptions: FileDescriptor.OpenOptions { + var options = FileDescriptor.OpenOptions() + + if !self.followSymbolicLinks { + options.insert(.noFollow) + } + + if self.closeOnExec { + options.insert(.closeOnExec) + } + + return options + } +} + +extension OpenOptions.Directory { + var descriptorOptions: FileDescriptor.OpenOptions { + var options = FileDescriptor.OpenOptions([.directory]) + + if !self.followSymbolicLinks { + options.insert(.noFollow) + } + + if self.closeOnExec { + options.insert(.closeOnExec) + } + + return options + } +} + +extension FileDescriptor.OpenOptions { + public init(_ options: OpenOptions.Read) { + self = options.descriptorOptions + } + + public init(_ options: OpenOptions.Write) { + self = options.descriptorOptions + } + + public init(_ options: OpenOptions.Directory) { + self = options.descriptorOptions + } +} + +extension FilePermissions { + /// Default permissions for regular files; owner read-write, group read, other read. + internal static let defaultsForRegularFile: FilePermissions = [ + .ownerReadWrite, + .groupRead, + .otherRead, + ] + + /// Default permissions for directories; owner read-write-execute, group read-execute, other + /// read-execute. + internal static let defaultsForDirectory: FilePermissions = [ + .ownerReadWriteExecute, + .groupReadExecute, + .otherReadExecute, + ] +} diff --git a/Sources/_NIOFileSystem/PrivacyInfo.xcprivacy b/Sources/_NIOFileSystem/PrivacyInfo.xcprivacy new file mode 100644 index 000000000..77e64b8e6 --- /dev/null +++ b/Sources/_NIOFileSystem/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPITypeReasons + + 0A2A.1 + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + + + NSPrivacyCollectedDataTypes + + NSPrivacyTrackingDomains + + + diff --git a/Sources/_NIOFileSystem/String+FileSystem.swift b/Sources/_NIOFileSystem/String+FileSystem.swift new file mode 100644 index 000000000..57e2d51c0 --- /dev/null +++ b/Sources/_NIOFileSystem/String+FileSystem.swift @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension String { + /// Reads the contents of the file at the path into a String. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + /// + /// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed) + } + + self = Self(buffer: byteBuffer) + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown. + /// + /// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } +} diff --git a/Sources/_NIOFileSystemFoundationCompat/Data+FileSystem.swift b/Sources/_NIOFileSystemFoundationCompat/Data+FileSystem.swift new file mode 100644 index 000000000..069a450a6 --- /dev/null +++ b/Sources/_NIOFileSystemFoundationCompat/Data+FileSystem.swift @@ -0,0 +1,57 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(Darwin) || os(Linux) || os(Android) +import _NIOFileSystem +import NIOCore +import NIOFoundationCompat +import struct Foundation.Data + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension Data { + /// Reads the contents of the file at the path. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed) + } + + self = Data(buffer: byteBuffer) + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } +} +#endif diff --git a/Sources/_NIOFileSystemFoundationCompat/Date+FileInfo.swift b/Sources/_NIOFileSystemFoundationCompat/Date+FileInfo.swift new file mode 100644 index 000000000..9acb95a35 --- /dev/null +++ b/Sources/_NIOFileSystemFoundationCompat/Date+FileInfo.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 +// +//===----------------------------------------------------------------------===// + +import _NIOFileSystem + +import struct Foundation.Date + +extension Date { + public init(timespec: FileInfo.Timespec) { + let timeInterval = Double(timespec.seconds) + Double(timespec.nanoseconds) / 1_000_000_000 + self = Date(timeIntervalSince1970: timeInterval) + } +} + +extension FileInfo.Timespec { + /// The UTC time of the timestamp. + public var date: Date { + Date(timespec: self) + } +}