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.
This commit is contained in:
Matt Hope authored and GitHub committed 2024-07-29 11:14:10 +01:00
1 parent b6a6e430df
commit 022ee1328b
5 files changed
+863 -128

No files matched your search

+114 -11
View File
@@ -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