From 022ee1328b0acf1050643b5bbac526dbdb5f52cd Mon Sep 17 00:00:00 2001 From: Matt Hope <74561306+UncleMattHope@users.noreply.github.com> Date: Mon, 29 Jul 2024 11:14:10 +0100 Subject: [PATCH] FileSystem.copyItem can parallelise directory copy (#2806) Motivation: Using some limited parallelism can improved the speed of the copy for very limited increase in cpu use. In circumstances where the source and/or destination are on a high latency device, such as a network file system, the resulting speed up can be even more significant. Providing conservative defaults, while allowing users the ability to control it directly if desired, provides for a faster default and access to user targeted gains in performance. The use of parallel by default is considered in keeping with the swift-nio model of concurrent capabilities. The parallelism used is restricted because the underlying limited resource for this is highly likely to be limited system file descriptors, rather than the limits of the underlying executor itself, especially on embedded devices with significantly more limited concurrent descriptors. Modifications: All copyItem overloads except ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)``` can, and likely will, use concurrent copies when copying directories. A Newly type ```CopyStrategy``` controls the behaviour, allowing: * ```parallel(maxDescriptors: Int)``` * Parallel limited to a maximum number of concurrently open file descriptors. * ```sequential``` * The previous behaviour, still asynchronous but only one operation at a time * ```platformDefault``` * Whatever the API determines the default should be from the prior options The cancellation semantics of copyItem were previously unclear/undocumented. These are now stated and cancellation is tested. There were some aspects of naming/types on this API which were inconsistent/unclear. Those have been altered to aid clarity. * Less duplication with the protocol docs * Consistent use of `item` not `file` * Use DirectoryEntry for the source in both ```shouldXxx``` callbacks NIOFileSystem package status remains unchanged, it is still _NIOFileSystem with the semantics that entails. Result: For any use of the following functions on FileSystemProtocol, when backed by FileSystem: - ```copyItem(*)```: The shouldCopyItem check happens before the internal FileSystem "do I know how to copy this sort of FileType" check. This makes the code a little simpler, but the desire is to allow consuming code to filter out anything unexpected if they like without needing to trap errors. - ```copyItem(sourcePath:destinationPath)```: Depending on the platform this will become parallel, users on MacOS, Linux and Windows will have up to 4 concurrent file system operations at once. Empirical testing on a MacBook pro with a significant dense directory hierarchy of 12 GiB had performance improvements of ~50% reduction in elapsed time for CPU usage increases below the noise floor of the testing - ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)```: When migrating from this to ```copyItem(sourcePath:destinationPath:copyStrategy:shouldProceedAfterError:shouldCopyItem)```care should be taken to ensure the should callbacks are safe to use in different concurrency domains, or that CopyStrategy.sequential is explicitly stated. The backward compatibility shim provided does this by default. --- Sources/NIOFileSystem/CopyStrategy.swift | 120 ++++++ Sources/NIOFileSystem/FileSystem.swift | 366 +++++++++++++----- .../NIOFileSystem/FileSystemProtocol.swift | 125 +++++- .../Internal/ParallelDirCopy.swift | 162 ++++++++ .../FileSystemTests.swift | 218 ++++++++++- 5 files changed, 863 insertions(+), 128 deletions(-) create mode 100644 Sources/NIOFileSystem/CopyStrategy.swift create mode 100644 Sources/NIOFileSystem/Internal/ParallelDirCopy.swift diff --git a/Sources/NIOFileSystem/CopyStrategy.swift b/Sources/NIOFileSystem/CopyStrategy.swift new file mode 100644 index 000000000..790206dae --- /dev/null +++ b/Sources/NIOFileSystem/CopyStrategy.swift @@ -0,0 +1,120 @@ +//===----------------------------------------------------------------------===// +// +// 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 alterations being 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 making `CopyStrategy`, + // the early error check there 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 the dominant aspect here. + // Empirical testing on an SSD copying to the same volume with a dense directory of small + // files and sub directories of similar shape totalling 12GB showed improvements in elapsed + // time for (expected) increases in CPU time up to parallel(8), beyond this the increases + // in CPU came with 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 to safety, not empirical testing. + return .parallel(4) + #else + // Safety first, if we have no view on it 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/inefficeint 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 7b2ab70eb..b18524a9f 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -293,21 +293,18 @@ public struct FileSystem: Sendable, FileSystemProtocol { // MARK: - File copying, removal, and moving - /// Copies the item at the specified path to a new location. + /// See ``FileSystemProtocol/copyItem(at:to:shouldProceedAfterError:shouldCopyFile:)`` /// /// 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). + /// But `shouldCopyItem` can be used to ignore things outside this supported set. /// /// #### Errors /// - /// Error codes thrown include: - /// - ``FileSystemError/Code-swift.struct/notFound`` if `sourcePath` doesn't exist. - /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if `destinationPath` exists. + /// 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. /// @@ -315,24 +312,16 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// 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. - /// - /// - 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. public func copyItem( at sourcePath: FilePath, to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy, shouldProceedAfterError: @escaping @Sendable ( - _ entry: DirectoryEntry, + _ source: DirectoryEntry, _ error: Error ) async throws -> Void, - shouldCopyFile: @escaping @Sendable ( - _ source: FilePath, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, _ destination: FilePath ) async -> Bool ) async throws { @@ -346,37 +335,36 @@ public struct FileSystem: Sendable, FileSystemProtocol { ) } - switch info.type { - case .regular: - if await shouldCopyFile(sourcePath, destinationPath) { + // 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: - if await shouldCopyFile(sourcePath, destinationPath) { + case .symlink: try await self.copySymbolicLink(from: sourcePath, to: destinationPath) - } - case .directory: - if await shouldCopyFile(sourcePath, destinationPath) { + case .directory: try await self.copyDirectory( from: sourcePath, to: destinationPath, + strategy: copyStrategy, shouldProceedAfterError: shouldProceedAfterError, - shouldCopyFile: shouldCopyFile + shouldCopyItem: shouldCopyItem + ) + + 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() ) } - - 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() - ) } } @@ -686,9 +674,8 @@ private let globalFileSystem: FileSystem = { extension NIOSingletons { /// 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_FILESYSTEM_THREAD_COUNT` environment variable. + /// 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 } } @@ -870,23 +857,41 @@ extension FileSystem { } } - /// Copies the directory from `sourcePath` to `destinationPath`. - private func copyDirectory( + /// 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 does indicate the items directly 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 file descriptor for the directory itself for as little time as possible + /// (certainly not across async invocations). + /// The down stream 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, - shouldCopyFile: @escaping @Sendable ( - _ source: FilePath, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, _ destination: FilePath ) async -> Bool - ) async throws { - // Strategy: copy regular files and symbolic links while the directory is open; defer - // copying directories until after the source directory has been closed to avoid consuming - // too many file descriptors. - let directoriesToCopy = try await self.withDirectoryHandle(atPath: sourcePath) { dir in + ) 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( @@ -917,75 +922,231 @@ extension FileSystem { () } #endif - - // Build a list of directories to copy over. Do this after closing the current - // directory to avoid using too many descriptors. - var directoriesToCopy = [(from: FilePath, to: FilePath)]() + // Build a list of items the caller needs to deal with, + // they 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 { - let entrySource = entry.path + // Any further work is pointless, we are under no obligation to cleanup + // so exit as fast and cleanly as possible. + try Task.checkCancellation() let entryDestination = destinationPath.appending(entry.name) - switch entry.type { - case .regular: - if await shouldCopyFile(entrySource, entryDestination) { - do { - try await self.copyRegularFile( - from: entry.path, - to: destinationPath.appending(entry.name) - ) - } catch { - try await shouldProceedAfterError(entry, error) - } + 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)) - case .symlink: - if await shouldCopyFile(entrySource, entryDestination) { - do { - try await self.copySymbolicLink( - from: entry.path, - to: destinationPath.appending(entry.name) - ) - } catch { - try await shouldProceedAfterError(entry, error) - } + 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) } - - case .directory: - directoriesToCopy.append((entrySource, entryDestination)) - - default: - let error = FileSystemError( - code: .unsupported, - message: """ - Can't copy '\(entrySource)' of type '\(entry.type)'; only regular \ - files, symbolic links and directories can be copied. - """, - cause: nil, - location: .here() - ) - - try await shouldProceedAfterError(entry, error) } } } - return directoriesToCopy + contentsToCopy.append(.endOfDir) + return contentsToCopy } + } - for entry in directoriesToCopy { - if await shouldCopyFile(entry.from, entry.to) { - try await self.copyDirectory( - from: entry.from, - to: entry.to, - shouldProceedAfterError: shouldProceedAfterError, - shouldCopyFile: shouldCopyFile - ) + /// This could be achieved through quite complicated special casing of the parallel copy. + /// The resulting code is far harder to read and debug though 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 async 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 2 descriptors, + // this keeps the downstream limiting code simple + // We do not preclude the use of more granular limiting in future (e.g. a directory + // scan only requires 1), 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 invovation 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 @@ -1376,5 +1537,4 @@ extension FileSystem { } } } - #endif diff --git a/Sources/NIOFileSystem/FileSystemProtocol.swift b/Sources/NIOFileSystem/FileSystemProtocol.swift index 9bd024d70..d60cdd085 100644 --- a/Sources/NIOFileSystem/FileSystemProtocol.swift +++ b/Sources/NIOFileSystem/FileSystemProtocol.swift @@ -176,24 +176,69 @@ public protocol FileSystemProtocol: Sendable { /// /// Note that other errors may also be thrown. /// - /// If the file at `sourcePath` is a symbolic link then only the link is copied to the new path. + /// 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. + /// - strategy: 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. - /// - shouldCopyFile: A closure which is executed before each copy to determine whether each - /// file should be copied. + /// 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 ( - _ path: DirectoryEntry, + _ source: DirectoryEntry, _ error: Error ) async throws -> Void, - shouldCopyFile: @escaping @Sendable ( - _ source: FilePath, + shouldCopyItem: @escaping @Sendable ( + _ source: DirectoryEntry, _ destination: FilePath ) async -> Bool ) async throws @@ -418,21 +463,79 @@ extension FileSystemProtocol { /// /// 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 ``copyItem(at:to:shouldProceedAfterError:shouldCopyFile:)``. + /// 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. - public func copyItem(at sourcePath: FilePath, to destinationPath: FilePath) async throws { - try await self.copyItem(at: sourcePath, to: destinationPath) { entry, error in + /// - 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 - } shouldCopyFile: { source, destination in + } 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) + } + ) + } + /// 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 diff --git a/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift new file mode 100644 index 000000000..cebfb635b --- /dev/null +++ b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift @@ -0,0 +1,162 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android) +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 (so files, symbolic links and directories), a larger file + /// is not considered for being 'split' into concurrent reads or wites. + /// If any symbolic link is encountered then only the link is copied. + /// The copied items will preserve permissions and any extended attributes (if supported by the file system). + /// + /// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open file descriptors at any point. + /// Operations are assume to consume 2 descriptors so maximum open descriptors is `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. + _ = copyRequiredQueue.source.yield( + .toCopy(from: .init(path: sourcePath, type: .directory)!, to: destinationPath) + ) + + // The processing of the very first item (the root) will increment this, + // after then when it hits zero we've finished. + // This does not need to be a ManagedAtomic or similar because: + // - All maintenance of state is done in the withThrowingTaskGroup callback + // - All actual file system work is done by tasks created on the `taskGroup` + var activeDirCount = 0 + + // Despite there being no 'result' of 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 + + // Code handling each item to process on the current task + // Side Effects: + // - Updates activeDirCount and finishes the stream if required. + // - Either adds a single task on `taskGroup` or none. + // 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 cancel clearly. + // This makes testing for the cancellation more reliable. + try Task.checkCancellation() + return + } + } + + // Then operate 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 { + 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() {} +} +#endif diff --git a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index 673f119f7..ac4bb8309 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -17,6 +17,7 @@ import NIOCore @_spi(Testing) import _NIOFileSystem @preconcurrency import SystemPackage import XCTest +import NIOConcurrencyHelpers extension FilePath { static let testData = FilePath(#filePath) @@ -655,17 +656,51 @@ final class FileSystemTests: XCTestCase { XCTAssertEqual(destination, "README.md") } - func testCopyEmptyDirectory() async throws { + /// This is is not quite the same as sequential, different code paths are used. + /// Tests using this ensure use of the parallel paths (which are more complex) while keeping actual + /// parallelism to minimal levels to make debugging simpler. + private let minimalParallel: CopyStrategy = try! .parallel(maxDescriptors: 2) + + func testCopyEmptyDirectorySequential() async throws { + try await testCopyEmptyDirectory(.sequential) + } + + func testCopyEmptyDirectoryParallelMinimal() async throws { + try await testCopyEmptyDirectory(minimalParallel) + } + + func testCopyEmptyDirectoryParallelDefault() async throws { + try await testCopyEmptyDirectory(.platformDefault) + } + + private func testCopyEmptyDirectory( + _ copyStrategy: CopyStrategy + ) async throws { let path = try await self.fs.temporaryFilePath() try await self.fs.createDirectory(at: path, withIntermediateDirectories: false) let copy = try await self.fs.temporaryFilePath() - try await self.fs.copyItem(at: path, to: copy) + try await self.fs.copyItem(at: path, to: copy, strategy: copyStrategy) try await self.checkDirectoriesMatch(path, copy) } - func testCopyGeneratedTreeStructure() async throws { + func testCopyOnGeneratedTreeStructureSequential() async throws { + try await testAnyCopyStrategyOnGeneratedTreeStructure(.sequential) + } + + func testCopyOnGeneratedTreeStructureParallelMinimal() async throws { + try await testAnyCopyStrategyOnGeneratedTreeStructure(minimalParallel) + } + + func testCopyOnGeneratedTreeStructureParallelDefault() async throws { + try await testAnyCopyStrategyOnGeneratedTreeStructure(.platformDefault) + } + + private func testAnyCopyStrategyOnGeneratedTreeStructure( + _ copyStrategy: CopyStrategy, + line: UInt = #line + ) async throws { let path = try await self.fs.temporaryFilePath() let items = try await self.generateDirectoryStructure( root: path, @@ -675,10 +710,13 @@ final class FileSystemTests: XCTestCase { let copy = try await self.fs.temporaryFilePath() do { - try await self.fs.copyItem(at: path, to: copy) + try await self.fs.copyItem(at: path, to: copy, strategy: copyStrategy) } catch { // Leave breadcrumbs to make debugging easier. - XCTFail("Failed to copy \(items) from '\(path)' to '\(copy)'") + XCTFail( + "Using \(copyStrategy) failed to copy \(items) from '\(path)' to '\(copy)'", + line: line + ) throw error } @@ -686,12 +724,30 @@ final class FileSystemTests: XCTestCase { try await self.checkDirectoriesMatch(path, copy) } catch { // Leave breadcrumbs to make debugging easier. - XCTFail("Failed to validate \(items) copied from '\(path)' to '\(copy)'") + XCTFail( + "Using \(copyStrategy) failed to validate \(items) copied from '\(path)' to '\(copy)'", + line: line + ) throw error } } - func testCopySelectively() async throws { + func testCopySelectivelySequential() async throws { + try await testCopySelectively(.sequential) + } + + func testCopySelectivelyParallelMinimal() async throws { + try await testCopySelectively(minimalParallel) + } + + func testCopySelectivelyParallelDefault() async throws { + try await testCopySelectively(.platformDefault) + } + + private func testCopySelectively( + _ copyStrategy: CopyStrategy, + line: UInt = #line + ) async throws { let path = try await self.fs.temporaryFilePath() // Only generate regular files. They'll be in the format 'file-N-regular'. @@ -704,11 +760,11 @@ final class FileSystemTests: XCTestCase { ) let copyPath = try await self.fs.temporaryFilePath() - try await self.fs.copyItem(at: path, to: copyPath) { _, error in + try await self.fs.copyItem(at: path, to: copyPath, strategy: copyStrategy) { _, error in throw error - } shouldCopyFile: { source, destination in + } shouldCopyItem: { source, destination in // Copy the directory and 'file-1-regular' - (source == path) || (source.lastComponent!.string == "file-0-regular") + (source.path == path) || (source.path.lastComponent!.string == "file-0-regular") } let paths = try await self.fs.withDirectoryHandle(atPath: copyPath) { dir in @@ -719,18 +775,140 @@ final class FileSystemTests: XCTestCase { XCTAssertEqual(paths.first?.name, "file-0-regular") } - func testCopyNonExistentFile() async throws { + func testCopyCancelledPartWayThroughSequential() async throws { + try await testCopyCancelledPartWayThrough(.sequential) + } + + func testCopyCancelledPartWayThroughParallelMinimal() async throws { + try await testCopyCancelledPartWayThrough(minimalParallel) + } + + func testCopyCancelledPartWayThroughParallelDefault() async throws { + try await testCopyCancelledPartWayThrough(.platformDefault) + } + + private func testCopyCancelledPartWayThrough( + _ copyStrategy: CopyStrategy, + line: UInt = #line + ) async throws { + let path = try await self.fs.temporaryFilePath() + + let _ = try await self.generateDirectoryStructure( + root: path, + // Ensure: + // - Parallelism is possible in directory scans. + // - There are sub directories underneath the point we trigger cancel + maxDepth: 4, + maxFilesPerDirectory: 10, + directoryProbability: 1.0, + symbolicLinkProbability: 0.0 + ) + + let copyPath = try await self.fs.temporaryFilePath() + + let requestedCancel = NIOLockedValueBox(false) + let cancelRequested = expectation(description: "cancel requested") + + let task = Task { + try await self.fs.copyItem(at: path, to: copyPath, strategy: copyStrategy) { _, error in + throw error + } shouldCopyItem: { source, destination in + // Abuse shouldCopy to trigger the cancellation after getting some way in. + if source.path != path && source.path.removingLastComponent() != path { + let shouldSleep = requestedCancel.withLockedValue { requested in + if !requested { + requested = true + cancelRequested.fulfill() + return true + } + + return requested + } + // Give the cancellation time to kick in, this should be more than plenty. + if shouldSleep { + do { + try await Task.sleep(for: .seconds(3)) + XCTFail("Should have been cancelled by now!") + } catch is CancellationError { + // This is fine - we got cancelled as desired, let the rest of the in flight + // logic wind down cleanly (we hope/assert) + } catch let error { + XCTFail("just expected a cancellation error not \(error)") + } + } + } + return true + } + + return "completed the copy" + } + + // Timeout notes: locally this should be fine as a second but on a loaded + // CI instance this test can be flaky at that level. + // Since testing cancellation is deemed highly desirable this is retained at + // quite relaxed thresholds. + // If this threshold remains insufficient for stable use then this test is likely + // not tenable to run in CI + await fulfillment(of: [cancelRequested], timeout: 5) + task.cancel() + let result = await task.result + switch result { + case let .success(msg): + XCTFail("expected the cancellation to have happened : \(msg)") + + case let .failure(err): + if err is CancellationError { + // success + } else { + XCTFail("expected CancellationError not \(err)") + } + } + // We can't assert anything about the state of the copy, + // it might happen to all finish in time depending on scheduling. + } + + func testCopyNonExistentFileSequential() async throws { + try await testCopyNonExistentFile(.sequential) + } + + func testCopyNonExistentFileParallelMinimal() async throws { + try await testCopyNonExistentFile(minimalParallel) + } + + func testCopyNonExistentFileParallelDefault() async throws { + try await testCopyNonExistentFile(.platformDefault) + } + + private func testCopyNonExistentFile( + _ copyStrategy: CopyStrategy, + line: UInt = #line + ) async throws { let source = try await self.fs.temporaryFilePath() let destination = try await self.fs.temporaryFilePath() await XCTAssertThrowsFileSystemErrorAsync { - try await self.fs.copyItem(at: source, to: destination) + try await self.fs.copyItem(at: source, to: destination, strategy: copyStrategy) } onError: { error in XCTAssertEqual(error.code, .notFound) } } - func testCopyToExistingDestination() async throws { + func testCopyToExistingDestinationSequential() async throws { + try await testCopyToExistingDestination(.sequential) + } + + func testCopyToExistingDestinationParallelMinimal() async throws { + try await testCopyToExistingDestination(minimalParallel) + } + + func testCopyToExistingDestinationParallelDefault() async throws { + try await testCopyToExistingDestination(.platformDefault) + } + + private func testCopyToExistingDestination( + _ copyStrategy: CopyStrategy, + line: UInt = #line + ) async throws { let source = try await self.fs.temporaryFilePath() let destination = try await self.fs.temporaryFilePath() @@ -743,7 +921,7 @@ final class FileSystemTests: XCTestCase { } await XCTAssertThrowsFileSystemErrorAsync { - try await self.fs.copyItem(at: source, to: destination) + try await self.fs.copyItem(at: source, to: destination, strategy: copyStrategy) } onError: { error in XCTAssertEqual(error.code, .fileAlreadyExists) } @@ -1507,4 +1685,16 @@ extension FileSystemTests { } } } + +#if !canImport(Darwin) && swift(<5.9.2) +extension XCTestCase { + func fulfillment( + of expectations: [XCTestExpectation], + timeout seconds: TimeInterval, + enforceOrder enforceOrderOfFulfillment: Bool = false + ) async { + wait(for: expectations, timeout: seconds) + } +} +#endif #endif