From 29c65edb970945a8eea0ef1f654a97ba4e907495 Mon Sep 17 00:00:00 2001 From: Michael Gecht Date: Tue, 10 Dec 2024 17:43:29 +0000 Subject: [PATCH] Add parallel removal of items (#3008) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce parallel removal of items, instead of only doing a sequential removal (and discovery) one-by-one ### Motivation: #2933 mentioned this function call appears to be slow. If we attempt to delete a directory with lots of subdirectories, we end up discovering each subdirectory one by one on a single thread. ### Modifications: This PR refactors the logic to remove items. Instead of sequentially discovering and deleting items one by one, we traverse all directories up to a maximum concurrency, and issue file deletions in parallel within each directory. ### Result: The new concurrent implementation was measured to be ~1.4x faster than `FileManager`, ~1.5x faster than `rm -rf` and ~3x faster than the current sequential implementation on `main`. This new concurrent implementation does use the most CPU out of all the other approaches. Results are broken down into two sections. We delete a copy of the `swift-nio` repository, where the `.build/` folder has grown to a large size, providing lots of additional files and subdirectories. We produce a single CLI using `--configration=release` that can switch between using the `.sequential` mode (what is currently available on the `main` branch), `.parallel` (the new concurrent implementation in this PR) and `filemanager` (uses `Foundation.FileManager` as a comparison). Resolves https://github.com/apple/swift-nio/issues/2933 #### Normal size **Description:** The `swift-nio` library as found when building the CLI used for benchmarking. **Benchmark run with:** 3579 directories, 11657 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 2.712 s ± 0.053 s [User: 0.526 s, System: 8.632 s] Range (min … max): 2.625 s … 2.781 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 896.7 ms ± 25.6 ms [User: 302.9 ms, System: 5313.5 ms] Range (min … max): 853.2 ms … 942.1 ms 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 1.337 s ± 0.076 s [User: 0.022 s, System: 1.253 s] Range (min … max): 1.252 s … 1.508 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 1.483 s ± 0.037 s [User: 0.015 s, System: 1.416 s] Range (min … max): 1.413 s … 1.541 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.49 ± 0.10 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.65 ± 0.06 times faster than rm -rf /tmp/swift-nio 3.02 ± 0.10 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` #### Large size **Description:** The `swift-nio` library as found after re-running the `.github` workflow many times locally. I'm unable to reproduce this directory size, but have benchmarked against it. **Benchmark run with:** 15260 directories, 46842 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 12.082 s ± 0.354 s [User: 2.180 s, System: 41.547 s] Range (min … max): 11.717 s … 12.923 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 4.770 s ± 0.102 s [User: 1.357 s, System: 25.785 s] Range (min … max): 4.570 s … 4.883 s 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 6.503 s ± 0.115 s [User: 0.081 s, System: 5.427 s] Range (min … max): 6.262 s … 6.687 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 7.056 s ± 0.246 s [User: 0.064 s, System: 6.119 s] Range (min … max): 6.435 s … 7.233 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.36 ± 0.04 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.48 ± 0.06 times faster than rm -rf /tmp/swift-nio 2.53 ± 0.09 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` --------- Co-authored-by: George Barnett --- NOTICE.txt | 9 + Sources/NIOFileSystem/CopyStrategy.swift | 121 ------------ Sources/NIOFileSystem/FileSystem.swift | 88 ++++++--- .../NIOFileSystem/FileSystemProtocol.swift | 76 +++++++- Sources/NIOFileSystem/IOStrategy.swift | 184 ++++++++++++++++++ .../Concurrency Primitives/TokenBucket.swift | 88 +++++++++ .../Internal/ParallelRemoval.swift | 72 +++++++ .../FileSystemTests.swift | 49 +++-- 8 files changed, 513 insertions(+), 174 deletions(-) delete mode 100644 Sources/NIOFileSystem/CopyStrategy.swift create mode 100644 Sources/NIOFileSystem/IOStrategy.swift create mode 100644 Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift create mode 100644 Sources/NIOFileSystem/Internal/ParallelRemoval.swift diff --git a/NOTICE.txt b/NOTICE.txt index cbcc2e69b..d79250ea5 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -95,3 +95,12 @@ This product contains a derivation of the mocking infrastructure from Swift Syst * https://www.apache.org/licenses/LICENSE-2.0 * HOMEPAGE: * https://github.com/apple/swift-system + +--- + +This product contains a derivation of "TokenBucket.swift" from Swift Package Manager. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/swiftlang/swift-package-manager diff --git a/Sources/NIOFileSystem/CopyStrategy.swift b/Sources/NIOFileSystem/CopyStrategy.swift deleted file mode 100644 index ae8b4770e..000000000 --- a/Sources/NIOFileSystem/CopyStrategy.swift +++ /dev/null @@ -1,121 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 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 { - // Avoid exposing to prevent breaking changes - internal enum Wrapped: Hashable, Sendable { - // platformDefault is reified into one of the concrete options below: - - case sequential - // Constraints on this value are enforced only on creation of `CopyStrategy`. The early - // error check is desirable over validating on downstream use. - case parallel(_ maxDescriptors: Int) - } - - internal let wrapped: Wrapped - private init(_ wrapped: Wrapped) { - self.wrapped = wrapped - } - - // 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 underlying storage device. Further we - // assume an SSD or similar underlying 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: for now we model the directory scan as needing two handles because, during the creation - // of the destination directory we hold the handle for a 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() -> Wrapped { - #if os(macOS) || os(Linux) || os(Windows) - // 4 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 os(iOS) || os(tvOS) || os(watchOS) || 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 - } -} - -extension CopyStrategy { - // 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(Self.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 IO 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" - } - } -} diff --git a/Sources/NIOFileSystem/FileSystem.swift b/Sources/NIOFileSystem/FileSystem.swift index 33bf8c605..834994925 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -366,6 +366,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { } } + /// 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 @@ -387,11 +389,14 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// - 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. @@ -421,41 +426,62 @@ public struct FileSystem: Sendable, FileSystemProtocol { ) } - 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) + switch removalStrategy.wrapped { + case .sequential: + return try await self.removeItemSequentially(at: path) + case let .parallel(maxDescriptors): + return try await self.removeConcurrently(at: path, maxDescriptors) } - for subdirectory in subdirectories { - filesRemoved += try await self.removeItem(at: subdirectory) - } - - // The directory should be empty now. Remove ourself. - filesRemoved += try await self.removeOneItem(at: path) - - return filesRemoved - 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 @@ -490,7 +516,7 @@ public struct FileSystem: Sendable, FileSystemProtocol { case .differentLogicalDevices: // Fall back to copy and remove. try await self.copyItem(at: sourcePath, to: destinationPath) - try await self.removeItem(at: sourcePath) + try await self.removeItem(at: sourcePath, strategy: .platformDefault) } } @@ -518,9 +544,9 @@ public struct FileSystem: Sendable, FileSystemProtocol { withItemAt existingPath: FilePath ) async throws { do { - try await self.removeItem(at: destinationPath) + try await self.removeItem(at: destinationPath, strategy: .platformDefault) try await self.moveItem(at: existingPath, to: destinationPath) - try await self.removeItem(at: existingPath) + try await self.removeItem(at: existingPath, strategy: .platformDefault) } catch let error as FileSystemError { throw FileSystemError( message: "Can't replace '\(destinationPath)' with '\(existingPath)'.", diff --git a/Sources/NIOFileSystem/FileSystemProtocol.swift b/Sources/NIOFileSystem/FileSystemProtocol.swift index b5bf70143..934220762 100644 --- a/Sources/NIOFileSystem/FileSystemProtocol.swift +++ b/Sources/NIOFileSystem/FileSystemProtocol.swift @@ -249,19 +249,23 @@ public protocol FileSystemProtocol: Sendable { /// 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). + /// 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. - /// - 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 + /// - 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 @@ -588,9 +592,12 @@ extension FileSystemProtocol { /// 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). + /// 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. @@ -599,7 +606,56 @@ extension FileSystemProtocol { public func removeItem( at path: FilePath ) async throws -> Int { - try await self.removeItem(at: path, recursively: true) + 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. @@ -659,7 +715,7 @@ extension FileSystemProtocol { try await execute(handle, directory) } } tearDown: { _ in - try await self.removeItem(at: directory, recursively: true) + try await self.removeItem(at: directory, strategy: .platformDefault, recursively: true) } } } diff --git a/Sources/NIOFileSystem/IOStrategy.swift b/Sources/NIOFileSystem/IOStrategy.swift new file mode 100644 index 000000000..fcb7fb432 --- /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 underlying storage device. Further we + // assume an SSD or similar underlying 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 os(iOS) || os(tvOS) || os(watchOS) || 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/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/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/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index 5de584660..e262147fa 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -222,7 +222,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if path.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: path) + try await fileSystem.removeItem(at: path, strategy: .platformDefault) } } @@ -351,7 +351,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault) } } @@ -399,7 +399,7 @@ final class FileSystemTests: XCTestCase { if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath, recursively: true) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault, recursively: true) } } @@ -586,8 +586,8 @@ final class FileSystemTests: XCTestCase { let sourcePath = try await self.fs.temporaryFilePath() let destPath = try await self.fs.temporaryFilePath() self.addTeardownBlock { - _ = try? await self.fs.removeItem(at: sourcePath) - _ = try? await self.fs.removeItem(at: destPath) + _ = try? await self.fs.removeItem(at: sourcePath, strategy: .platformDefault) + _ = try? await self.fs.removeItem(at: destPath, strategy: .platformDefault) } let sourceInfo = try await self.fs.withFileHandle( @@ -991,7 +991,7 @@ final class FileSystemTests: XCTestCase { let infoAfterCreation = try await self.fs.info(forFileAt: path) XCTAssertNotNil(infoAfterCreation) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 1) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1002,11 +1002,11 @@ final class FileSystemTests: XCTestCase { let path = try await self.fs.temporaryFilePath() let info = try await self.fs.info(forFileAt: path) XCTAssertNil(info) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 0) } - func testRemoveDirectory() async throws { + func testRemoveDirectorySequentially() async throws { let path = try await self.fs.temporaryFilePath() let created = try await self.generateDirectoryStructure( root: path, @@ -1019,12 +1019,37 @@ final class FileSystemTests: XCTestCase { // Removing a non-empty directory recursively should throw 'notEmpty' await XCTAssertThrowsFileSystemErrorAsync { - try await self.fs.removeItem(at: path, recursively: false) + try await self.fs.removeItem(at: path, strategy: .sequential, recursively: false) } onError: { error in XCTAssertEqual(error.code, .notEmpty) } - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .sequential) + XCTAssertEqual(created, removed) + + let infoAfterRemoval = try await self.fs.info(forFileAt: path) + XCTAssertNil(infoAfterRemoval) + } + + func testRemoveDirectoryConcurrently() async throws { + let path = try await self.fs.temporaryFilePath() + let created = try await self.generateDirectoryStructure( + root: path, + maxDepth: 3, + maxFilesPerDirectory: 10 + ) + + let infoAfterCreation = try await self.fs.info(forFileAt: path) + XCTAssertNotNil(infoAfterCreation) + + // Removing a non-empty directory recursively should throw 'notEmpty' + await XCTAssertThrowsFileSystemErrorAsync { + try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2), recursively: false) + } onError: { error in + XCTAssertEqual(error.code, .notEmpty) + } + + let removed = try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2)) XCTAssertEqual(created, removed) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1602,7 +1627,7 @@ extension FileSystemTests { // Clean up after ourselves. self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: temporaryDirectoryPath) + try await fileSystem.removeItem(at: temporaryDirectoryPath, strategy: .platformDefault) } guard let info = try await self.fs.info(forFileAt: temporaryDirectoryPath) else { @@ -1640,7 +1665,7 @@ extension FileSystemTests { let temporaryDirectoryPath = try await self.fs.createTemporaryDirectory(template: template) self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: templateRoot, recursively: true) + try await fileSystem.removeItem(at: templateRoot, strategy: .platformDefault, recursively: true) } guard