mirror of
https://github.com/apple/swift-nio
synced 2026-11-27 05:04:22 +00:00
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:
1 parent
b6a6e430df
commit
022ee1328b
5 files changed
+863
-128
No files matched your search
@@ -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<Bool>(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
|
||||
Reference in new issue
Block a user