From d963335ba01956badefd32d28d42f7c65d1bc1ad Mon Sep 17 00:00:00 2001 From: George Barnett Date: Wed, 5 Nov 2025 08:47:05 +0000 Subject: [PATCH] Fail on early errors in parallel copy (#3435) Motivation: 'copyItem' can be used to copy files/directories from a source to a destination address and fails if the destination already exists. The parallel version of it can wedge if a directory is being copied and the directory can't be created at the destination path (for example, if a file already exists at the destination). The parallel copy works by feeding tasks (e.g. "copy this item from here to there") into an async sequence and processing each task in a separate child task within a task group. When copying directories a new directory is created at the destination path and then each file within the source directory is emitted as a separate item to process. Another item is sent on the async sequence to indicate when the source directory is finished with which may result in finishing the async sequence. However, if creating the destination directory fails then that event isn't sent. This results in the calling code never terminating the async sequence and causes 'copyItem' to wedge. Modifications: - Use non-idempotent directory creation (copy item should fail if the destination already exists, this was a regression introduced in 7124f096). - Check whether to continue when a dir can't be created but always emit the end of dir event - If terminating when the task group hasn't reached its width limit then check child tasks for errors Result: Parallel copy doesn't wedge --- Sources/NIOFS/FileSystem.swift | 63 +++++++++++++------ Sources/NIOFS/Internal/ParallelDirCopy.swift | 4 ++ Sources/_NIOFileSystem/FileSystem.swift | 63 +++++++++++++------ .../Internal/ParallelDirCopy.swift | 4 ++ .../FileSystemTests.swift | 25 ++++++++ 5 files changed, 123 insertions(+), 36 deletions(-) diff --git a/Sources/NIOFS/FileSystem.swift b/Sources/NIOFS/FileSystem.swift index 650c516d3..a0663a1d8 100644 --- a/Sources/NIOFS/FileSystem.swift +++ b/Sources/NIOFS/FileSystem.swift @@ -232,12 +232,27 @@ public struct FileSystem: Sendable, FileSystemProtocol { at path: NIOFilePath, withIntermediateDirectories createIntermediateDirectories: Bool, permissions: FilePermissions? + ) async throws { + try await self.createDirectory( + at: path, + withIntermediateDirectories: createIntermediateDirectories, + permissions: permissions, + idempotent: true + ) + } + + private func createDirectory( + at path: NIOFilePath, + withIntermediateDirectories createIntermediateDirectories: Bool, + permissions: FilePermissions?, + idempotent: Bool ) async throws { try await self.threadPool.runIfActive { try self._createDirectory( at: path.underlying, withIntermediateDirectories: createIntermediateDirectories, - permissions: permissions ?? .defaultsForDirectory + permissions: permissions ?? .defaultsForDirectory, + idempotent: idempotent ).get() } } @@ -795,7 +810,8 @@ extension FileSystem { private func _createDirectory( at fullPath: FilePath, withIntermediateDirectories createIntermediateDirectories: Bool, - permissions: FilePermissions + permissions: FilePermissions, + idempotent: Bool = true ) -> Result { // We assume that we will be creating intermediate directories: // - Try creating the directory. If it fails with ENOENT (no such file or directory), then @@ -826,16 +842,20 @@ extension FileSystem { case let .failure(errno): if errno == .fileExists { - switch self._info(forFileAt: path, infoAboutSymbolicLink: false) { - case let .success(maybeInfo): - if let info = maybeInfo, info.type == .directory { - break loop - } else { - // A file exists at this path. + if idempotent { + switch self._info(forFileAt: path, infoAboutSymbolicLink: false) { + case let .success(maybeInfo): + if let info = maybeInfo, info.type == .directory { + break loop + } else { + // A file exists at this path. + return .failure(.mkdir(errno: errno, path: path, location: .here())) + } + case .failure: + // Unable to determine what exists at this path. return .failure(.mkdir(errno: errno, path: path, location: .here())) } - case .failure: - // Unable to determine what exists at this path. + } else { return .failure(.mkdir(errno: errno, path: path, location: .here())) } } @@ -930,7 +950,8 @@ extension FileSystem { try await self.createDirectory( at: NIOFilePath(destinationPath), withIntermediateDirectories: false, - permissions: info.permissions + permissions: info.permissions, + idempotent: false // Fail if the destination dir already exists. ) #if !os(Android) @@ -1165,13 +1186,19 @@ extension FileSystem { } case .directory: - let addToQueue = try await self.prepareDirectoryForRecusiveCopy( - from: from.path.underlying, - to: to, - shouldProceedAfterError: shouldProceedAfterError, - shouldCopyItem: shouldCopyItem - ) - yield(addToQueue) + do { + let addToQueue = try await self.prepareDirectoryForRecusiveCopy( + from: from.path.underlying, + to: to, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + yield(addToQueue) + } catch { + // The caller expects an end-of-dir regardless of whether there was an error or not. + yield([.endOfDir]) + try await shouldProceedAfterError(from, error) + } default: let error = FileSystemError( diff --git a/Sources/NIOFS/Internal/ParallelDirCopy.swift b/Sources/NIOFS/Internal/ParallelDirCopy.swift index 029dd77ac..a548f4515 100644 --- a/Sources/NIOFS/Internal/ParallelDirCopy.swift +++ b/Sources/NIOFS/Internal/ParallelDirCopy.swift @@ -126,6 +126,10 @@ extension FileSystem { // the latter case we choose to propagate the cancellation clearly. This makes // testing for it more reliable. try Task.checkCancellation() + + // If any child tasks failed throw up an error. + try await taskGroup.waitForAll() + return } } diff --git a/Sources/_NIOFileSystem/FileSystem.swift b/Sources/_NIOFileSystem/FileSystem.swift index 53174c19a..3fd16ecc3 100644 --- a/Sources/_NIOFileSystem/FileSystem.swift +++ b/Sources/_NIOFileSystem/FileSystem.swift @@ -232,12 +232,27 @@ public struct FileSystem: Sendable, FileSystemProtocol { at path: FilePath, withIntermediateDirectories createIntermediateDirectories: Bool, permissions: FilePermissions? + ) async throws { + try await self.createDirectory( + at: path, + withIntermediateDirectories: createIntermediateDirectories, + permissions: permissions, + idempotent: true + ) + } + + private func createDirectory( + at path: FilePath, + withIntermediateDirectories createIntermediateDirectories: Bool, + permissions: FilePermissions?, + idempotent: Bool ) async throws { try await self.threadPool.runIfActive { try self._createDirectory( at: path, withIntermediateDirectories: createIntermediateDirectories, - permissions: permissions ?? .defaultsForDirectory + permissions: permissions ?? .defaultsForDirectory, + idempotent: idempotent ).get() } } @@ -809,7 +824,8 @@ extension FileSystem { private func _createDirectory( at fullPath: FilePath, withIntermediateDirectories createIntermediateDirectories: Bool, - permissions: FilePermissions + permissions: FilePermissions, + idempotent: Bool = true ) -> Result { // We assume that we will be creating intermediate directories: // - Try creating the directory. If it fails with ENOENT (no such file or directory), then @@ -840,16 +856,20 @@ extension FileSystem { case let .failure(errno): if errno == .fileExists { - switch self._info(forFileAt: path, infoAboutSymbolicLink: false) { - case let .success(maybeInfo): - if let info = maybeInfo, info.type == .directory { - break loop - } else { - // A file exists at this path. + if idempotent { + switch self._info(forFileAt: path, infoAboutSymbolicLink: false) { + case let .success(maybeInfo): + if let info = maybeInfo, info.type == .directory { + break loop + } else { + // A file exists at this path. + return .failure(.mkdir(errno: errno, path: path, location: .here())) + } + case .failure: + // Unable to determine what exists at this path. return .failure(.mkdir(errno: errno, path: path, location: .here())) } - case .failure: - // Unable to determine what exists at this path. + } else { return .failure(.mkdir(errno: errno, path: path, location: .here())) } } @@ -944,7 +964,8 @@ extension FileSystem { try await self.createDirectory( at: destinationPath, withIntermediateDirectories: false, - permissions: info.permissions + permissions: info.permissions, + idempotent: false // Fail if the destination dir already exists. ) #if !os(Android) @@ -1179,13 +1200,19 @@ extension FileSystem { } case .directory: - let addToQueue = try await self.prepareDirectoryForRecusiveCopy( - from: from.path, - to: to, - shouldProceedAfterError: shouldProceedAfterError, - shouldCopyItem: shouldCopyItem - ) - yield(addToQueue) + do { + let addToQueue = try await self.prepareDirectoryForRecusiveCopy( + from: from.path, + to: to, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + yield(addToQueue) + } catch { + // The caller expects an end-of-dir regardless of whether there was an error or not. + yield([.endOfDir]) + try await shouldProceedAfterError(from, error) + } default: let error = FileSystemError( diff --git a/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift b/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift index ae9d30f6f..203453242 100644 --- a/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift +++ b/Sources/_NIOFileSystem/Internal/ParallelDirCopy.swift @@ -126,6 +126,10 @@ extension FileSystem { // the latter case we choose to propagate the cancellation clearly. This makes // testing for it more reliable. try Task.checkCancellation() + + // If any child tasks failed throw up an error. + try await taskGroup.waitForAll() + return } } diff --git a/Tests/NIOFSIntegrationTests/FileSystemTests.swift b/Tests/NIOFSIntegrationTests/FileSystemTests.swift index 9235fd939..b813c91bc 100644 --- a/Tests/NIOFSIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFSIntegrationTests/FileSystemTests.swift @@ -717,6 +717,31 @@ final class FileSystemTests: XCTestCase { try await self.checkDirectoriesMatch(path, copy) } + func testCopyDirectoryToExistingDestinationSequential() async throws { + try await self.testCopyDirectoryToExistingDestination(.sequential) + } + + func testCopyDirectoryToExistingDestinationParallelMinimal() async throws { + try await self.testCopyDirectoryToExistingDestination(Self.minimalParallel) + } + + func testCopyDirectoryToExistingDestinationParallelDefault() async throws { + try await self.testCopyDirectoryToExistingDestination(.platformDefault) + } + + private func testCopyDirectoryToExistingDestination( + _ strategy: CopyStrategy + ) async throws { + let path1 = try await self.fs.temporaryFilePath() + let path2 = try await self.fs.temporaryFilePath() + try await self.fs.createDirectory(at: path1, withIntermediateDirectories: false) + try await self.fs.createDirectory(at: path2, withIntermediateDirectories: false) + + await XCTAssertThrowsErrorAsync { + try await self.fs.copyItem(at: path1, to: path2, strategy: strategy) + } + } + func testCopyOnGeneratedTreeStructureSequential() async throws { try await testAnyCopyStrategyOnGeneratedTreeStructure(.sequential) }