mirror of
https://github.com/apple/swift-nio
synced 2026-11-23 04:34:23 +00:00
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.
### Motivation:
The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.
The current loop looks like this:
```swift
// Successfully made a directory, construct its children.
while let subdirectory = droppedComponents.popLast() {
path.append(subdirectory)
switch Syscall.mkdir(at: path, permissions: permissions) {
case .success:
continue
case let .failure(errno):
return .failure(.mkdir(errno: errno, path: path, location: .here()))
}
}
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
### Modifications:
The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:
If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.
### Result:
Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.
Co-authored-by: David Stern <d_stern@apple.com>