From e69354f1237d34e3453248dfca57aade20a288d8 Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Thu, 16 Nov 2023 16:21:21 +0000 Subject: [PATCH] Async apis for NonBlockingFileIO (#2576) * Async versions of NonBlockingFileIO functions I have not produced async versions of the readChunked functions. These would likely be replaced with an AsyncSequence though. * Add tests for async versions of NonBlockingFileIO * Add wrapper for FileRegion to avoid Sendable issues * Allocate ByteBuffer in readSync * Update read_10000_chunks_from_file alloc count * Add UnsafeTransfer to NIOPosix. Use in NonBlockingFileIO.openFile functions * Update Sources/NIOPosix/NonBlockingFileIO.swift Co-authored-by: George Barnett * formatting, docc * update comment * replace openFile with withOpenFile * More indentation * Update comments * Remove docc links to NIOCore types * Fix read docc links * Catch errors when closing file handle in withOpenFile * rename to withFileHandle * Fix double close on error Also - move @available above each function - Remove wording about separate from Task pool * Update Sources/NIOPosix/NonBlockingFileIO.swift Co-authored-by: George Barnett * withOpenFile is now withFileRegion --------- Co-authored-by: George Barnett --- Sources/NIOPosix/NIOThreadPool.swift | 2 +- Sources/NIOPosix/NonBlockingFileIO.swift | 534 ++++++++++++++-- Sources/NIOPosix/UnsafeTransfer.swift | 33 + .../NIOPosixTests/NonBlockingFileIOTest.swift | 605 ++++++++++++++++++ Tests/NIOPosixTests/TestUtils.swift | 58 ++ docker/docker-compose.2204.510.yaml | 2 +- docker/docker-compose.2204.57.yaml | 2 +- docker/docker-compose.2204.58.yaml | 2 +- docker/docker-compose.2204.59.yaml | 2 +- docker/docker-compose.2204.main.yaml | 2 +- 10 files changed, 1165 insertions(+), 77 deletions(-) create mode 100644 Sources/NIOPosix/UnsafeTransfer.swift diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index 6d2980189..39db18919 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -360,4 +360,4 @@ extension NIOThreadPool { } } } -} +} \ No newline at end of file diff --git a/Sources/NIOPosix/NonBlockingFileIO.swift b/Sources/NIOPosix/NonBlockingFileIO.swift index 2e07175bc..63830a8e0 100644 --- a/Sources/NIOPosix/NonBlockingFileIO.swift +++ b/Sources/NIOPosix/NonBlockingFileIO.swift @@ -15,7 +15,7 @@ import NIOCore import NIOConcurrencyHelpers -/// `NonBlockingFileIO` is a helper that allows you to read files without blocking the calling thread. +/// ``NonBlockingFileIO`` is a helper that allows you to read files without blocking the calling thread. /// /// It is worth noting that `kqueue`, `epoll` or `poll` returning claiming a file is readable does not mean that the /// data is already available in the kernel's memory. In other words, a `read` from a file can still block even if @@ -25,19 +25,19 @@ import NIOConcurrencyHelpers /// - [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html): "epoll is simply a faster poll(2), and can be used wherever the latter is used since it shares the same semantics." /// - [`kqueue`](https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2): "Returns when the file pointer is not at the end of file." /// -/// `NonBlockingFileIO` helps to work around this issue by maintaining its own thread pool that is used to read the data +/// ``NonBlockingFileIO`` helps to work around this issue by maintaining its own thread pool that is used to read the data /// from the files into memory. It will then hand the (in-memory) data back which makes it available without the possibility /// of blocking. public struct NonBlockingFileIO: Sendable { - /// The default and recommended size for `NonBlockingFileIO`'s thread pool. + /// The default and recommended size for ``NonBlockingFileIO``'s thread pool. public static let defaultThreadPoolSize = 2 /// The default and recommended chunk size. public static let defaultChunkSize = 128*1024 - /// `NonBlockingFileIO` errors. + /// ``NonBlockingFileIO`` errors. public enum Error: Swift.Error { - /// `NonBlockingFileIO` is meant to be used with file descriptors that are set to the default (blocking) mode. + /// ``NonBlockingFileIO`` is meant to be used with file descriptors that are set to the default (blocking) mode. /// It doesn't make sense to use it with a file descriptor where `O_NONBLOCK` is set therefore this error is /// raised when that was requested. case descriptorSetToNonBlocking @@ -45,7 +45,7 @@ public struct NonBlockingFileIO: Sendable { private let threadPool: NIOThreadPool - /// Initialize a `NonBlockingFileIO` which uses the `NIOThreadPool`. + /// Initialize a ``NonBlockingFileIO`` which uses the `NIOThreadPool`. /// /// - parameters: /// - threadPool: The `NIOThreadPool` that will be used for all the IO. @@ -53,7 +53,7 @@ public struct NonBlockingFileIO: Sendable { self.threadPool = threadPool } - /// Read a `FileRegion` in chunks of `chunkSize` bytes on `NonBlockingFileIO`'s private thread + /// Read a `FileRegion` in chunks of `chunkSize` bytes on ``NonBlockingFileIO``'s private thread /// pool which is separate from any `EventLoop` thread. /// /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `fileRegion.readableBytes` is greater than @@ -89,7 +89,7 @@ public struct NonBlockingFileIO: Sendable { chunkHandler: chunkHandler) } - /// Read `byteCount` bytes in chunks of `chunkSize` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread + /// Read `byteCount` bytes in chunks of `chunkSize` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread /// pool which is separate from any `EventLoop` thread. /// /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than @@ -128,7 +128,7 @@ public struct NonBlockingFileIO: Sendable { chunkHandler: chunkHandler) } - /// Read `byteCount` bytes from offset `fileOffset` in chunks of `chunkSize` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread + /// Read `byteCount` bytes from offset `fileOffset` in chunks of `chunkSize` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread /// pool which is separate from any `EventLoop` thread. /// /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than @@ -225,7 +225,7 @@ public struct NonBlockingFileIO: Sendable { return promise.futureResult } - /// Read a `FileRegion` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. + /// Read a `FileRegion` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread. /// /// The returned `ByteBuffer` will not have less than `fileRegion.readableBytes` unless we hit end-of-file in which /// case the `ByteBuffer` will contain the bytes available to read. @@ -250,15 +250,15 @@ public struct NonBlockingFileIO: Sendable { eventLoop: eventLoop) } - /// Read `byteCount` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. + /// Read `byteCount` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread. /// /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which /// case the `ByteBuffer` will contain the bytes available to read. /// /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes. - /// - note: `read(fileRegion:allocator:eventLoop:)` should be preferred as it uses `FileRegion` object instead of + /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of /// raw `NIOFileHandle`s. In case you do want to use raw `NIOFileHandle`s, - /// please consider using `read(fileHandle:fromOffset:byteCount:allocator:eventLoop:)` + /// please consider using ``read(fileHandle:fromOffset:byteCount:allocator:eventLoop:)`` /// because it doesn't use the file descriptor's seek pointer (which may be shared with other file /// descriptors and even across processes.) /// @@ -279,7 +279,7 @@ public struct NonBlockingFileIO: Sendable { eventLoop: eventLoop) } - /// Read `byteCount` bytes starting at `fileOffset` from `fileHandle` in `NonBlockingFileIO`'s private thread pool + /// Read `byteCount` bytes starting at `fileOffset` from `fileHandle` in ``NonBlockingFileIO``'s private thread pool /// which is separate from any `EventLoop` thread. /// /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which @@ -289,7 +289,7 @@ public struct NonBlockingFileIO: Sendable { /// same `fileHandle` in multiple threads. /// /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes. - /// - note: `read(fileRegion:allocator:eventLoop:)` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s. + /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to read. @@ -320,40 +320,49 @@ public struct NonBlockingFileIO: Sendable { } let byteCount = rawByteCount < Int32.max ? rawByteCount : size_t(Int32.max) - var buf = allocator.buffer(capacity: byteCount) return self.threadPool.runIfActive(eventLoop: eventLoop) { () -> ByteBuffer in - var bytesRead = 0 - while bytesRead < byteCount { - let n = try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: byteCount - bytesRead) { ptr in - let res = try fileHandle.withUnsafeFileDescriptor { descriptor -> IOResult in - if let offset = fromOffset { - return try Posix.pread(descriptor: descriptor, - pointer: ptr.baseAddress!, - size: byteCount - bytesRead, - offset: off_t(offset) + off_t(bytesRead)) - } else { - return try Posix.read(descriptor: descriptor, - pointer: ptr.baseAddress!, - size: byteCount - bytesRead) - } - } - switch res { - case .processed(let n): - assert(n >= 0, "read claims to have read a negative number of bytes \(n)") - return n - case .wouldBlock: - throw Error.descriptorSetToNonBlocking + try self.readSync(fileHandle: fileHandle, fromOffset: fromOffset, byteCount: byteCount, allocator: allocator) + } + } + + private func readSync( + fileHandle: NIOFileHandle, + fromOffset: Int64?, // > 2 GB offset is reasonable on 32-bit systems + byteCount: Int, + allocator: ByteBufferAllocator + ) throws -> ByteBuffer { + var bytesRead = 0 + var buf = allocator.buffer(capacity: byteCount) + while bytesRead < byteCount { + let n = try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: byteCount - bytesRead) { ptr in + let res = try fileHandle.withUnsafeFileDescriptor { descriptor -> IOResult in + if let offset = fromOffset { + return try Posix.pread(descriptor: descriptor, + pointer: ptr.baseAddress!, + size: byteCount - bytesRead, + offset: off_t(offset) + off_t(bytesRead)) + } else { + return try Posix.read(descriptor: descriptor, + pointer: ptr.baseAddress!, + size: byteCount - bytesRead) } } - if n == 0 { - // EOF - break - } else { - bytesRead += n + switch res { + case .processed(let n): + assert(n >= 0, "read claims to have read a negative number of bytes \(n)") + return n + case .wouldBlock: + throw Error.descriptorSetToNonBlocking } } - return buf + if n == 0 { + // EOF + break + } else { + bytesRead += n + } } + return buf } /// Changes the file size of `fileHandle` to `size`. @@ -394,7 +403,7 @@ public struct NonBlockingFileIO: Sendable { } } - /// Write `buffer` to `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. + /// Write `buffer` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to write to. @@ -407,7 +416,7 @@ public struct NonBlockingFileIO: Sendable { return self.write0(fileHandle: fileHandle, toOffset: nil, buffer: buffer, eventLoop: eventLoop) } - /// Write `buffer` starting from `toOffset` to `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. + /// Write `buffer` starting from `toOffset` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to write to. @@ -433,35 +442,44 @@ public struct NonBlockingFileIO: Sendable { } return self.threadPool.runIfActive(eventLoop: eventLoop) { - var buf = buffer + try self.writeSync(fileHandle: fileHandle, byteCount: byteCount, toOffset: toOffset, buffer: buffer) + } + } - var offsetAccumulator: Int = 0 - repeat { - let n = try buf.readWithUnsafeReadableBytes { ptr in - precondition(ptr.count == byteCount - offsetAccumulator) - let res: IOResult = try fileHandle.withUnsafeFileDescriptor { descriptor in - if let toOffset = toOffset { - return try Posix.pwrite(descriptor: descriptor, - pointer: ptr.baseAddress!, - size: byteCount - offsetAccumulator, - offset: off_t(toOffset + Int64(offsetAccumulator))) - } else { - return try Posix.write(descriptor: descriptor, - pointer: ptr.baseAddress!, - size: byteCount - offsetAccumulator) - } - } - switch res { - case .processed(let n): - assert(n >= 0, "write claims to have written a negative number of bytes \(n)") - return n - case .wouldBlock: - throw Error.descriptorSetToNonBlocking + private func writeSync( + fileHandle: NIOFileHandle, + byteCount: Int, + toOffset: Int64?, + buffer: ByteBuffer + ) throws { + var buf = buffer + + var offsetAccumulator: Int = 0 + repeat { + let n = try buf.readWithUnsafeReadableBytes { ptr in + precondition(ptr.count == byteCount - offsetAccumulator) + let res: IOResult = try fileHandle.withUnsafeFileDescriptor { descriptor in + if let toOffset = toOffset { + return try Posix.pwrite(descriptor: descriptor, + pointer: ptr.baseAddress!, + size: byteCount - offsetAccumulator, + offset: off_t(toOffset + Int64(offsetAccumulator))) + } else { + return try Posix.write(descriptor: descriptor, + pointer: ptr.baseAddress!, + size: byteCount - offsetAccumulator) } } - offsetAccumulator += n - } while offsetAccumulator < byteCount - } + switch res { + case .processed(let n): + assert(n >= 0, "write claims to have written a negative number of bytes \(n)") + return n + case .wouldBlock: + throw Error.descriptorSetToNonBlocking + } + } + offsetAccumulator += n + } while offsetAccumulator < byteCount } /// Open the file at `path` for reading on a private thread pool which is separate from any `EventLoop` thread. @@ -712,3 +730,377 @@ public struct NIODirectoryEntry: Hashable { } } #endif + +extension NonBlockingFileIO { + /// Read a `FileRegion` in ``NonBlockingFileIO``'s private thread pool. + /// + /// The returned `ByteBuffer` will not have less than the minimum of `fileRegion.readableBytes` and `UInt32.max` unless we hit + /// end-of-file in which case the `ByteBuffer` will contain the bytes available to read. + /// + /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the + /// same `FileRegion` in multiple threads. + /// + /// - note: Only use this function for small enough `FileRegion`s as it will need to allocate enough memory to hold `fileRegion.readableBytes` bytes. + /// - note: In most cases you should prefer one of the `readChunked` functions. + /// + /// - parameters: + /// - fileRegion: The file region to read. + /// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`. + /// - returns: ByteBuffer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func read(fileRegion: FileRegion, allocator: ByteBufferAllocator) async throws -> ByteBuffer { + let readableBytes = fileRegion.readableBytes + return try await self.read( + fileHandle: fileRegion.fileHandle, + fromOffset: Int64(fileRegion.readerIndex), + byteCount: readableBytes, + allocator: allocator + ) + } + + /// Read `byteCount` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread pool. + /// + /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which + /// case the `ByteBuffer` will contain the bytes available to read. + /// + /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes. + /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of + /// raw `NIOFileHandle`s. In case you do want to use raw `NIOFileHandle`s, + /// please consider using ``read(fileHandle:fromOffset:byteCount:allocator:eventLoop:)`` + /// because it doesn't use the file descriptor's seek pointer (which may be shared with other file + /// descriptors and even across processes.) + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to read. + /// - byteCount: The number of bytes to read from `fileHandle`. + /// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`. + /// - returns: ByteBuffer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func read( + fileHandle: NIOFileHandle, + byteCount: Int, + allocator: ByteBufferAllocator + ) async throws-> ByteBuffer { + return try await self.read0( + fileHandle: fileHandle, + fromOffset: nil, + byteCount: byteCount, + allocator: allocator + ) + } + + /// Read `byteCount` bytes starting at `fileOffset` from `fileHandle` in ``NonBlockingFileIO``'s private thread pool + ///. + /// + /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which + /// case the `ByteBuffer` will contain the bytes available to read. + /// + /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the + /// same `fileHandle` in multiple threads. + /// + /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes. + /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s. + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to read. + /// - fileOffset: The offset to read from. + /// - byteCount: The number of bytes to read from `fileHandle`. + /// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`. + /// - returns: ByteBuffer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func read(fileHandle: NIOFileHandle, + fromOffset fileOffset: Int64, + byteCount: Int, + allocator: ByteBufferAllocator) async throws -> ByteBuffer { + return try await self.read0(fileHandle: fileHandle, + fromOffset: fileOffset, + byteCount: byteCount, + allocator: allocator) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private func read0(fileHandle: NIOFileHandle, + fromOffset: Int64?, // > 2 GB offset is reasonable on 32-bit systems + byteCount rawByteCount: Int, + allocator: ByteBufferAllocator) async throws -> ByteBuffer { + guard rawByteCount > 0 else { + return allocator.buffer(capacity: 0) + } + let byteCount = rawByteCount < Int32.max ? rawByteCount : size_t(Int32.max) + + return try await self.threadPool.runIfActive { () -> ByteBuffer in + try self.readSync(fileHandle: fileHandle, fromOffset: fromOffset, byteCount: byteCount, allocator: allocator) + } + } + + /// Changes the file size of `fileHandle` to `size`. + /// + /// If `size` is smaller than the current file size, the remaining bytes will be truncated and are lost. If `size` + /// is larger than the current file size, the gap will be filled with zero bytes. + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to write to. + /// - size: The new file size in bytes to write. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func changeFileSize(fileHandle: NIOFileHandle, + size: Int64) async throws { + return try await self.threadPool.runIfActive { + try fileHandle.withUnsafeFileDescriptor { descriptor -> Void in + try Posix.ftruncate(descriptor: descriptor, size: off_t(size)) + } + } + } + + /// Returns the length of the file associated with `fileHandle`. + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to read from. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func readFileSize(fileHandle: NIOFileHandle) async throws -> Int64 { + return try await self.threadPool.runIfActive { + return try fileHandle.withUnsafeFileDescriptor { descriptor in + let curr = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_CUR) + let eof = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_END) + try Posix.lseek(descriptor: descriptor, offset: curr, whence: SEEK_SET) + return Int64(eof) + } + } + } + + /// Write `buffer` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool. + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to write to. + /// - buffer: The `ByteBuffer` to write. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func write(fileHandle: NIOFileHandle, + buffer: ByteBuffer) async throws { + return try await self.write0(fileHandle: fileHandle, toOffset: nil, buffer: buffer) + } + + /// Write `buffer` starting from `toOffset` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool. + /// + /// - parameters: + /// - fileHandle: The `NIOFileHandle` to write to. + /// - toOffset: The file offset to write to. + /// - buffer: The `ByteBuffer` to write. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func write(fileHandle: NIOFileHandle, + toOffset: Int64, + buffer: ByteBuffer) async throws { + return try await self.write0(fileHandle: fileHandle, toOffset: toOffset, buffer: buffer) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private func write0(fileHandle: NIOFileHandle, + toOffset: Int64?, + buffer: ByteBuffer) async throws { + let byteCount = buffer.readableBytes + + guard byteCount > 0 else { + return + } + + return try await self.threadPool.runIfActive { + try self.writeSync(fileHandle: fileHandle, byteCount: byteCount, toOffset: toOffset, buffer: buffer) + } + } + + /// Open file at `path` and query its size on a private thread pool, run an operation given + /// the resulting file region and then close the file handle. + /// + /// The will return the result of the operation. + /// + /// - note: This function opens a file and queries it size which are both blocking operations + /// + /// - parameters: + /// - path: The path of the file to be opened for reading. + /// - body: operation to run with file handle and region + /// - returns: return value of operation + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func withFileRegion( + path: String, + _ body: (_ fileRegion: FileRegion) async throws -> Result + ) async throws -> Result { + let fileRegion = try await self.threadPool.runIfActive { + let fh = try NIOFileHandle(path: path) + do { + let fr = try FileRegion(fileHandle: fh) + return UnsafeTransfer(fr) + } catch { + _ = try? fh.close() + throw error + } + } + let result: Result + do { + result = try await body(fileRegion.wrappedValue) + } catch { + try fileRegion.wrappedValue.fileHandle.close() + throw error + } + try fileRegion.wrappedValue.fileHandle.close() + return result + } + + /// Open file at `path` on a private thread pool, run an operation given the file handle and then close the file handle. + /// + /// This function will return the result of the operation. + /// + /// - parameters: + /// - path: The path of the file to be opened for writing. + /// - mode: File access mode. + /// - flags: Additional POSIX flags. + /// - returns: return value of operation + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func withFileHandle( + path: String, + mode: NIOFileHandle.Mode, + flags: NIOFileHandle.Flags = .default, + _ body: (NIOFileHandle) async throws -> Result + ) async throws -> Result { + let fileHandle = try await self.threadPool.runIfActive { + return try UnsafeTransfer(NIOFileHandle(path: path, mode: mode, flags: flags)) + } + let result: Result + do { + result = try await body(fileHandle.wrappedValue) + } catch { + try fileHandle.wrappedValue.close() + throw error + } + try fileHandle.wrappedValue.close() + return result + } + +#if !os(Windows) + + /// Returns information about a file at `path` on a private thread pool. + /// + /// - note: If `path` is a symlink, information about the link, not the file it points to. + /// + /// - parameters: + /// - path: The path of the file to get information about. + /// - returns: file information. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func lstat(path: String) async throws -> stat { + return try await self.threadPool.runIfActive { + var s = stat() + try Posix.lstat(pathname: path, outStat: &s) + return s + } + } + + /// Creates a symbolic link to a `destination` file at `path` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the link. + /// - destination: Target path where this link will point to. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func symlink(path: String, to destination: String) async throws { + return try await self.threadPool.runIfActive { + try Posix.symlink(pathname: path, destination: destination) + } + } + + /// Returns target of the symbolic link at `path` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the link to read. + /// - returns: link target. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func readlink(path: String) async throws -> String { + return try await self.threadPool.runIfActive { + let maxLength = Int(PATH_MAX) + let pointer = UnsafeMutableBufferPointer.allocate(capacity: maxLength) + defer { + pointer.deallocate() + } + let length = try Posix.readlink(pathname: path, outPath: pointer.baseAddress!, outPathSize: maxLength) + return String(decoding: UnsafeRawBufferPointer(pointer).prefix(length), as: UTF8.self) + } + } + + /// Removes symbolic link at `path` on a private thread pool which is separate from any `EventLoop` thread. + /// + /// - parameters: + /// - path: The path of the link to remove. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func unlink(path: String) async throws { + return try await self.threadPool.runIfActive { + try Posix.unlink(pathname: path) + } + } + + + /// Creates directory at `path` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the directory to be created. + /// - withIntermediateDirectories: Whether intermediate directories should be created. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func createDirectory(path: String, withIntermediateDirectories createIntermediates: Bool = false, mode: NIOPOSIXFileMode) async throws { + return try await self.threadPool.runIfActive { + if createIntermediates { + #if canImport(Darwin) + try Posix.mkpath_np(pathname: path, mode: mode) + #else + try self.createDirectory0(path, mode: mode) + #endif + } else { + try Posix.mkdir(pathname: path, mode: mode) + } + } + } + + /// List contents of the directory at `path` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the directory to list the content of. + /// - returns: The directory entries. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func listDirectory(path: String) async throws -> [NIODirectoryEntry] { + return try await self.threadPool.runIfActive { + let dir = try Posix.opendir(pathname: path) + var entries: [NIODirectoryEntry] = [] + do { + while let entry = try Posix.readdir(dir: dir) { + let name = withUnsafeBytes(of: entry.pointee.d_name) { pointer -> String in + let ptr = pointer.baseAddress!.assumingMemoryBound(to: CChar.self) + return String(cString: ptr) + } + entries.append(NIODirectoryEntry(ino: UInt64(entry.pointee.d_ino), type: entry.pointee.d_type, name: name)) + } + try? Posix.closedir(dir: dir) + } catch { + try? Posix.closedir(dir: dir) + throw error + } + return entries + } + } + + /// Renames the file at `path` to `newName` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the file to be renamed. + /// - newName: New file name. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func rename(path: String, newName: String) async throws { + return try await self.threadPool.runIfActive() { + try Posix.rename(pathname: path, newName: newName) + } + } + + /// Removes the file at `path` on a private thread pool. + /// + /// - parameters: + /// - path: The path of the file to be removed. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func remove(path: String) async throws { + return try await self.threadPool.runIfActive() { + try Posix.remove(pathname: path) + } + } +#endif +} \ No newline at end of file diff --git a/Sources/NIOPosix/UnsafeTransfer.swift b/Sources/NIOPosix/UnsafeTransfer.swift new file mode 100644 index 000000000..daef8dacc --- /dev/null +++ b/Sources/NIOPosix/UnsafeTransfer.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +/// ``UnsafeTransfer`` can be used to make non-`Sendable` values `Sendable`. +/// As the name implies, the usage of this is unsafe because it disables the sendable checking of the compiler. +/// It can be used similar to `@unsafe Sendable` but for values instead of types. +@usableFromInline +struct UnsafeTransfer { + @usableFromInline + var wrappedValue: Wrapped + + @inlinable + init(_ wrappedValue: Wrapped) { + self.wrappedValue = wrappedValue + } +} + +extension UnsafeTransfer: @unchecked Sendable {} + +extension UnsafeTransfer: Equatable where Wrapped: Equatable {} +extension UnsafeTransfer: Hashable where Wrapped: Hashable {} + diff --git a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift index 1e742b1e9..cd5d4d5f3 100644 --- a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift +++ b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift @@ -1041,4 +1041,609 @@ class NonBlockingFileIOTest: XCTestCase { } XCTAssertEqual(content.utf8.count, numCalls) } + +} + + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension NonBlockingFileIOTest { + func testAsyncBasicFileIOWorks() async throws { + let content = "hello" + try await withTemporaryFile(content: content) { (fileHandle, _) -> Void in + let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5) + var buf = try await self.fileIO.read(fileRegion: fr, + allocator: self.allocator) + XCTAssertEqual(content.utf8.count, buf.readableBytes) + XCTAssertEqual(content, buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncOffsetWorks() async throws { + let content = "hello" + try await withTemporaryFile(content: content) { (fileHandle, _) -> Void in + let fr = FileRegion(fileHandle: fileHandle, readerIndex: 3, endIndex: 5) + var buf = try await self.fileIO.read(fileRegion: fr, + allocator: self.allocator) + XCTAssertEqual(2, buf.readableBytes) + XCTAssertEqual("lo", buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncOffsetBeyondEOF() async throws { + let content = "hello" + try await withTemporaryFile(content: content) { (fileHandle, _) -> Void in + let fr = FileRegion(fileHandle: fileHandle, readerIndex: 3000, endIndex: 3001) + var buf = try await self.fileIO.read(fileRegion: fr, + allocator: self.allocator) + XCTAssertEqual(0, buf.readableBytes) + XCTAssertEqual("", buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncEmptyReadWorks() async throws { + try await withTemporaryFile { (fileHandle, _) -> Void in + let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 0) + let buf = try await self.fileIO.read(fileRegion: fr, + allocator: self.allocator) + XCTAssertEqual(0, buf.readableBytes) + } + } + + func testAsyncReadingShortWorks() async throws { + let content = "hello" + try await withTemporaryFile(content: "hello") { (fileHandle, _) -> Void in + let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 10) + var buf = try await self.fileIO.read(fileRegion: fr, + allocator: self.allocator) + XCTAssertEqual(content.utf8.count, buf.readableBytes) + XCTAssertEqual(content, buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncDoesNotBlockTheThreadOrEventLoop() async throws { + try await withPipe { readFH, writeFH in + async let byteBufferTask = try await self.fileIO.read( + fileHandle: readFH, + byteCount: 10, + allocator: self.allocator) + do { + try await self.threadPool.runIfActive { + try writeFH.withUnsafeFileDescriptor { writeFD in + _ = try Posix.write(descriptor: writeFD, pointer: "X", size: 1) + } + try writeFH.close() + } + var buf = try await byteBufferTask + XCTAssertEqual(1, buf.readableBytes) + XCTAssertEqual("X", buf.readString(length: buf.readableBytes)) + } + return [readFH] + } + } + + func testAsyncGettingErrorWhenEventLoopGroupIsShutdown() async throws { + try await self.threadPool.shutdownGracefully() + + try await withPipe { readFH, writeFH in + do { + _ = try await self.fileIO.read( + fileHandle: readFH, + byteCount: 1, + allocator: self.allocator) + XCTFail("testAsyncGettingErrorWhenEventLoopGroupIsShutdown: fileIO.read should throw an error") + } catch { + XCTAssertTrue(error is NIOThreadPoolError.ThreadPoolInactive) + } + return [readFH, writeFH] + } + } + + func testAsyncReadDoesNotReadShort() async throws { + try await withPipe { readFH, writeFH in + async let bufferTask = try await self.fileIO.read(fileHandle: readFH, + byteCount: 10, + allocator: self.allocator) + for i in 0..<10 { + try await Task.sleep(nanoseconds: 5_000_000) + try await self.threadPool.runIfActive { + try writeFH.withUnsafeFileDescriptor { writeFD in + _ = try Posix.write(descriptor: writeFD, pointer: "\(i)", size: 1) + } + } + } + try writeFH.close() + + var buf = try await bufferTask + XCTAssertEqual(10, buf.readableBytes) + XCTAssertEqual("0123456789", buf.readString(length: buf.readableBytes)) + return [readFH] + } + } + + func testAsyncReadMoreThanIntMaxBytesDoesntThrow() async throws { + try XCTSkipIf(MemoryLayout.size == MemoryLayout.size) + // here we try to read way more data back from the file than it contains but it serves the purpose + // even on a small file the OS will return EINVAL if you try to read > INT_MAX bytes + try await withTemporaryFile(content: "some-dummy-content", { (filehandle, path) -> Void in + let content = try await self.fileIO.read(fileHandle: filehandle, byteCount:Int(Int32.max)+10, allocator: .init()) + XCTAssertEqual(String(buffer: content), "some-dummy-content") + }) + } + + func testAsyncReadingFileSize() async throws { + try await withTemporaryFile(content: "0123456789") { (fileHandle, _) -> Void in + let size = try await self.fileIO.readFileSize(fileHandle: fileHandle) + XCTAssertEqual(size, 10) + } + } + + func testAsyncChangeFileSizeShrink() async throws { + try await withTemporaryFile(content: "0123456789") { (fileHandle, _) -> Void in + try await self.fileIO.changeFileSize(fileHandle: fileHandle, + size: 1) + let fileRegion = try FileRegion(fileHandle: fileHandle) + var buf = try await self.fileIO.read(fileRegion: fileRegion, + allocator: self.allocator) + XCTAssertEqual("0", buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncChangeFileSizeGrow() async throws { + try await withTemporaryFile(content: "0123456789") { (fileHandle, _) -> Void in + try await self.fileIO.changeFileSize(fileHandle: fileHandle, + size: 100) + let fileRegion = try FileRegion(fileHandle: fileHandle) + var buf = try await self.fileIO.read(fileRegion: fileRegion, + allocator: self.allocator) + let zeros = (1...90).map { _ in UInt8(0) } + guard let bytes = buf.readBytes(length: buf.readableBytes)?.suffix(from: 10) else { + XCTFail("readBytes(length:) should not be nil") + return + } + XCTAssertEqual(zeros, Array(bytes)) + } + } + + func testAsyncWriting() async throws { + try await withTemporaryFile(content: "") { (fileHandle, path) in + var buffer = self.allocator.buffer(capacity: 3) + buffer.writeStaticString("123") + + try await self.fileIO.write(fileHandle: fileHandle, + buffer: buffer) + let offset = try fileHandle.withUnsafeFileDescriptor { + try Posix.lseek(descriptor: $0, offset: 0, whence: SEEK_SET) + } + XCTAssertEqual(offset, 0) + + let readBuffer = try await self.fileIO.read(fileHandle: fileHandle, + byteCount: 3, + allocator: self.allocator) + XCTAssertEqual(readBuffer.getString(at: 0, length: 3), "123") + } + } + + func testAsyncWriteMultipleTimes() async throws { + try await withTemporaryFile(content: "AAA") { (fileHandle, path) in + var buffer = self.allocator.buffer(capacity: 3) + buffer.writeStaticString("xxx") + + for i in 0 ..< 3 { + buffer.writeString("\(i)") + try await self.fileIO.write(fileHandle: fileHandle, + buffer: buffer) + } + let offset = try fileHandle.withUnsafeFileDescriptor { + try Posix.lseek(descriptor: $0, offset: 0, whence: SEEK_SET) + } + XCTAssertEqual(offset, 0) + + let expectedOutput = "xxx0xxx01xxx012" + let readBuffer = try await self.fileIO.read(fileHandle: fileHandle, + byteCount: expectedOutput.utf8.count, + allocator: self.allocator) + XCTAssertEqual(expectedOutput, String(decoding: readBuffer.readableBytesView, as: Unicode.UTF8.self)) + } + } + + func testAsyncWritingWithOffset() async throws { + try await withTemporaryFile(content: "hello") { (fileHandle, _) -> Void in + var buffer = self.allocator.buffer(capacity: 3) + buffer.writeStaticString("123") + + try await self.fileIO.write(fileHandle: fileHandle, + toOffset: 1, + buffer: buffer) + let offset = try fileHandle.withUnsafeFileDescriptor { + try Posix.lseek(descriptor: $0, offset: 0, whence: SEEK_SET) + } + XCTAssertEqual(offset, 0) + + var readBuffer = try await self.fileIO.read(fileHandle: fileHandle, + byteCount: 5, + allocator: self.allocator) + XCTAssertEqual(5, readBuffer.readableBytes) + XCTAssertEqual("h123o", readBuffer.readString(length: readBuffer.readableBytes)) + } + } + + // This is undefined behavior and may cause different + // results on other platforms. Please add #if:s according + // to platform requirements. + func testAsyncWritingBeyondEOF() async throws { + try await withTemporaryFile(content: "hello") { (fileHandle, _) -> Void in + var buffer = self.allocator.buffer(capacity: 3) + buffer.writeStaticString("123") + + try await self.fileIO.write(fileHandle: fileHandle, + toOffset: 6, + buffer: buffer) + + let fileRegion = try FileRegion(fileHandle: fileHandle) + var buf = try await self.fileIO.read(fileRegion: fileRegion, + allocator: self.allocator) + XCTAssertEqual(9, buf.readableBytes) + XCTAssertEqual("hello", buf.readString(length: 5)) + XCTAssertEqual([ UInt8(0) ], buf.readBytes(length: 1)) + XCTAssertEqual("123", buf.readString(length: buf.readableBytes)) + } + } + + func testAsyncFileOpenWorks() async throws { + let content = "123" + try await withTemporaryFile(content: content) { (fileHandle, path) -> Void in + try await self.fileIO.withFileRegion(path: path) { fr in + try fr.fileHandle.withUnsafeFileDescriptor { fd in + XCTAssertGreaterThanOrEqual(fd, 0) + } + XCTAssertTrue(fr.fileHandle.isOpen) + XCTAssertEqual(0, fr.readerIndex) + XCTAssertEqual(3, fr.endIndex) + } + } + } + + func testAsyncFileOpenWorksWithEmptyFile() async throws { + let content = "" + try await withTemporaryFile(content: content) { (fileHandle, path) -> Void in + try await self.fileIO.withFileRegion(path: path) { fr in + try fr.fileHandle.withUnsafeFileDescriptor { fd in + XCTAssertGreaterThanOrEqual(fd, 0) + } + XCTAssertTrue(fr.fileHandle.isOpen) + XCTAssertEqual(0, fr.readerIndex) + XCTAssertEqual(0, fr.endIndex) + } + } + } + + func testAsyncFileOpenFails() async throws { + do { + _ = try await self.fileIO.withFileRegion(path: "/dev/null/this/does/not/exist") { _ in} + XCTFail("should've thrown") + } catch let e as IOError where e.errnoCode == ENOTDIR { + // OK + } catch { + XCTFail("wrong error: \(error)") + } + } + + func testAsyncOpeningFilesForWriting() async throws { + try await withTemporaryDirectory { dir in + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: .write, + flags: .allowFileCreation() + ) { _ in } + } + } + + func testAsyncOpeningFilesForWritingFailsIfWeDontAllowItExplicitly() async throws { + do { + try await withTemporaryDirectory { dir in + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: .write, + flags: .default + ) { _ in } + } + XCTFail("testAsyncOpeningFilesForWritingFailsIfWeDontAllowItExplicitly: openFile should fail") + } catch { + XCTAssertEqual(ENOENT, (error as? IOError)?.errnoCode) + } + } + + func testAsyncOpeningFilesForWritingDoesNotAllowReading() async throws { + try await withTemporaryDirectory { dir in + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: .write, + flags: .allowFileCreation() + ) { fileHandle in + XCTAssertEqual(-1 /* read must fail */, + try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in + var data: UInt8 = 0 + return withUnsafeMutableBytes(of: &data) { ptr in + read(fd, ptr.baseAddress, ptr.count) + } + }) + } + } + } + + func testAsyncOpeningFilesForWritingAndReading() async throws { + try await withTemporaryDirectory { dir in + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: [.write, .read], + flags: .allowFileCreation() + ) { fileHandle in + XCTAssertEqual(0 /* read should read EOF */, + try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in + var data: UInt8 = 0 + return withUnsafeMutableBytes(of: &data) { ptr in + read(fd, ptr.baseAddress, ptr.count) + } + }) + } + } + } + + func testAsyncOpeningFilesForWritingDoesNotImplyTruncation() async throws { + try await withTemporaryDirectory { dir in + // open 1 + write + do { + try await self.fileIO.withFileHandle( + path: "\(dir)/file", + mode: [.write, .read], + flags: .allowFileCreation() + ) { fileHandle in + try fileHandle.withUnsafeFileDescriptor { fd in + var data = UInt8(ascii: "X") + XCTAssertEqual(IOResult.processed(1), + try withUnsafeBytes(of: &data) { ptr in + try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count) + }) + } + } + } + + // open 2 + write again + read + do { + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: [.write, .read], + flags: .default + ) { fileHandle in + try fileHandle.withUnsafeFileDescriptor { fd in + try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_END) + var data = UInt8(ascii: "Y") + XCTAssertEqual(IOResult.processed(1), + try withUnsafeBytes(of: &data) { ptr in + try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count) + }) + } + XCTAssertEqual(2 /* both bytes */, + try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in + var data: UInt16 = 0 + try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_SET) + let readReturn = withUnsafeMutableBytes(of: &data) { ptr in + read(fd, ptr.baseAddress, ptr.count) + } + XCTAssertEqual(UInt16(bigEndian: (UInt16(UInt8(ascii: "X")) << 8) | UInt16(UInt8(ascii: "Y"))), + data) + return readReturn + }) + } + } + } + } + + func testAsyncOpeningFilesForWritingCanUseTruncation() async throws { + try await withTemporaryDirectory { dir in + // open 1 + write + do { + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: [.write, .read], + flags: .allowFileCreation() + ) { fileHandle in + try fileHandle.withUnsafeFileDescriptor { fd in + var data = UInt8(ascii: "X") + XCTAssertEqual(IOResult.processed(1), + try withUnsafeBytes(of: &data) { ptr in + try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count) + }) + } + } + } + // open 2 (with truncation) + write again + read + do { + try await self.fileIO!.withFileHandle( + path: "\(dir)/file", + mode: [.write, .read], + flags: .posix(flags: O_TRUNC, mode: 0) + ) { fileHandle in + try fileHandle.withUnsafeFileDescriptor { fd in + try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_END) + var data = UInt8(ascii: "Y") + XCTAssertEqual(IOResult.processed(1), + try withUnsafeBytes(of: &data) { ptr in + try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count) + }) + } + XCTAssertEqual(1 /* read should read just one byte because we truncated the file */, + try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in + var data: UInt16 = 0 + try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_SET) + let readReturn = withUnsafeMutableBytes(of: &data) { ptr in + read(fd, ptr.baseAddress, ptr.count) + } + XCTAssertEqual(UInt16(bigEndian: UInt16(UInt8(ascii: "Y")) << 8), data) + return readReturn + }) + } + } + } + } + + func testAsyncReadFromOffset() async throws { + try await withTemporaryFile(content: "hello world") { (fileHandle, path) in + let buffer = try await self.fileIO.read(fileHandle: fileHandle, + fromOffset: 6, + byteCount: 5, + allocator: ByteBufferAllocator()) + let string = String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self) + XCTAssertEqual("world", string) + } + } + + func testAsyncReadFromOffsetAfterEOFDeliversExactlyOneChunk() async throws { + try await withTemporaryFile(content: "hello world") { (fileHandle, path) in + let readableBytes = try await self.fileIO.read( + fileHandle: fileHandle, + fromOffset: 100, + byteCount: 5, + allocator: .init() + ).readableBytes + XCTAssertEqual(0,readableBytes) + } + } + + func testAsyncReadFromEOFDeliversExactlyOneChunk() async throws { + try await withTemporaryFile(content: "") { (fileHandle, path) in + let readableBytes = try await self.fileIO.read( + fileHandle: fileHandle, + byteCount: 5, + allocator: .init() + ).readableBytes + XCTAssertEqual(0, readableBytes) + } + } + + func testAsyncThrowsErrorOnUnstartedPool() async throws { + await withTemporaryFile(content: "hello, world") { fileHandle, path in + let threadPool = NIOThreadPool(numberOfThreads: 1) + let fileIO = NonBlockingFileIO(threadPool: threadPool) + do { + try await fileIO.withFileRegion(path: path) { _ in } + XCTFail("testAsyncThrowsErrorOnUnstartedPool: openFile should throw an error") + } catch { + } + } + } + + func testAsyncLStat() async throws { + try await withTemporaryFile(content: "hello, world") { _, path in + let stat = try await self.fileIO.lstat(path: path) + XCTAssertEqual(12, stat.st_size) + XCTAssertEqual(S_IFREG, S_IFMT & stat.st_mode) + } + + try await withTemporaryDirectory { path in + let stat = try await self.fileIO.lstat(path: path) + XCTAssertEqual(S_IFDIR, S_IFMT & stat.st_mode) + } + } + + func testAsyncSymlink() async throws { + try await withTemporaryFile(content: "hello, world") { _, path in + let symlink = "\(path).symlink" + try await self.fileIO.symlink(path: symlink, to: path) + + let link = try await self.fileIO.readlink(path: symlink) + XCTAssertEqual(path, link) + let stat = try await self.fileIO.lstat(path: symlink) + XCTAssertEqual(S_IFLNK, S_IFMT & stat.st_mode) + + try await self.fileIO.unlink(path: symlink) + do { + _ = try await self.fileIO.lstat(path: symlink) + XCTFail("testAsyncSymlink: lstat should throw an error after unlink") + } catch { + XCTAssertEqual(ENOENT, (error as? IOError)?.errnoCode) + } + } + } + + func testAsyncCreateDirectory() async throws { + try await withTemporaryDirectory { path in + let dir = "\(path)/f1/f2///f3" + try await self.fileIO.createDirectory(path: dir, withIntermediateDirectories: true, mode: S_IRWXU) + + let stat = try await self.fileIO.lstat(path: dir) + XCTAssertEqual(S_IFDIR, S_IFMT & stat.st_mode) + + try await self.fileIO.createDirectory(path: "\(dir)/f4", withIntermediateDirectories: false, mode: S_IRWXU) + + let stat2 = try await self.fileIO.lstat(path: dir) + XCTAssertEqual(S_IFDIR, S_IFMT & stat2.st_mode) + + let dir3 = "\(path)/f4/." + try await self.fileIO.createDirectory(path: dir3, withIntermediateDirectories: true, mode: S_IRWXU) + } + } + + func testAsyncListDirectory() async throws { + try await withTemporaryDirectory { path in + let file = "\(path)/file" + try await self.fileIO.withFileHandle( + path: file, + mode: .write, + flags: .allowFileCreation() + ) { handle in + let list = try await self.fileIO.listDirectory(path: path) + XCTAssertEqual([".", "..", "file"], list.sorted(by: { $0.name < $1.name }).map(\.name)) + } + } + } + + func testAsyncRename() async throws { + try await withTemporaryDirectory { path in + let file = "\(path)/file" + try await self.fileIO.withFileHandle( + path: file, + mode: .write, + flags: .allowFileCreation() + ) { handle in + let stat = try await self.fileIO.lstat(path: file) + XCTAssertEqual(S_IFREG, S_IFMT & stat.st_mode) + + let new = "\(path).new" + try await self.fileIO.rename(path: file, newName: new) + + let stat2 = try await self.fileIO.lstat(path: new) + XCTAssertEqual(S_IFREG, S_IFMT & stat2.st_mode) + + do { + _ = try await self.fileIO.lstat(path: file) + XCTFail("testAsyncRename: lstat should throw an error after file renamed") + } catch { + XCTAssertEqual(ENOENT, (error as? IOError)?.errnoCode) + } + } + } + } + + func testAsyncRemove() async throws { + try await withTemporaryDirectory { path in + let file = "\(path)/file" + try await self.fileIO.withFileHandle( + path: file, + mode: .write, + flags: .allowFileCreation() + ) { handle in + let stat = try await self.fileIO.lstat(path: file) + XCTAssertEqual(S_IFREG, S_IFMT & stat.st_mode) + + try await self.fileIO.remove(path: file) + do { + _ = try await self.fileIO.lstat(path: file) + XCTFail("testAsyncRemove: lstat should throw an error after file removed") + } catch { + XCTAssertEqual(ENOENT, (error as? IOError)?.errnoCode) + } + } + } + } } diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index 273b6b145..910744bc6 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -60,6 +60,28 @@ func withPipe(_ body: (NIOCore.NIOFileHandle, NIOCore.NIOFileHandle) throws -> [ } } +func withPipe(_ body: (NIOCore.NIOFileHandle, NIOCore.NIOFileHandle) async throws -> [NIOCore.NIOFileHandle]) async throws { + var fds: [Int32] = [-1, -1] + fds.withUnsafeMutableBufferPointer { ptr in + XCTAssertEqual(0, pipe(ptr.baseAddress!)) + } + let readFH = NIOFileHandle(descriptor: fds[0]) + let writeFH = NIOFileHandle(descriptor: fds[1]) + var toClose: [NIOFileHandle] = [readFH, writeFH] + var error: Error? = nil + do { + toClose = try await body(readFH, writeFH) + } catch let err { + error = err + } + try toClose.forEach { fh in + XCTAssertNoThrow(try fh.close()) + } + if let error = error { + throw error + } +} + func withTemporaryDirectory(_ body: (String) throws -> T) rethrows -> T { let dir = createTemporaryDirectory() defer { @@ -68,6 +90,14 @@ func withTemporaryDirectory(_ body: (String) throws -> T) rethrows -> T { return try body(dir) } +func withTemporaryDirectory(_ body: (String) async throws -> T) async rethrows -> T { + let dir = createTemporaryDirectory() + defer { + try? FileManager.default.removeItem(atPath: dir) + } + return try await body(dir) +} + /// This function creates a filename that can be used for a temporary UNIX domain socket path. /// /// If the temporary directory is too long to store a UNIX domain socket path, it will `chdir` into the temporary @@ -131,6 +161,34 @@ func withTemporaryFile(content: String? = nil, _ body: (NIOCore.NIOFileHandle } return try body(fileHandle, path) } + +func withTemporaryFile(content: String? = nil, _ body: @escaping @Sendable (NIOCore.NIOFileHandle, String) async throws -> T) async rethrows -> T { + let (fd, path) = openTemporaryFile() + let fileHandle = NIOFileHandle(descriptor: fd) + defer { + XCTAssertNoThrow(try fileHandle.close()) + XCTAssertEqual(0, unlink(path)) + } + if let content = content { + try Array(content.utf8).withUnsafeBufferPointer { ptr in + var toWrite = ptr.count + var start = ptr.baseAddress! + while toWrite > 0 { + let res = try Posix.write(descriptor: fd, pointer: start, size: toWrite) + switch res { + case .processed(let written): + toWrite -= written + start = start + written + case .wouldBlock: + XCTFail("unexpectedly got .wouldBlock from a file") + continue + } + } + XCTAssertEqual(0, lseek(fd, 0, SEEK_SET)) + } + } + return try await body(fileHandle, path) +} var temporaryDirectory: String { get { #if targetEnvironment(simulator) diff --git a/docker/docker-compose.2204.510.yaml b/docker/docker-compose.2204.510.yaml index 6c4362987..a9089f498 100644 --- a/docker/docker-compose.2204.510.yaml +++ b/docker/docker-compose.2204.510.yaml @@ -62,7 +62,7 @@ services: - MAX_ALLOCS_ALLOWED_modifying_1000_circular_buffer_elements=0 - MAX_ALLOCS_ALLOWED_modifying_byte_buffer_view=6050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=343 - - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=140050 + - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=130050 - MAX_ALLOCS_ALLOWED_schedule_10000_tasks=50100 - MAX_ALLOCS_ALLOWED_schedule_and_run_10000_tasks=50050 - MAX_ALLOCS_ALLOWED_scheduling_10000_executions=85 diff --git a/docker/docker-compose.2204.57.yaml b/docker/docker-compose.2204.57.yaml index eccb233c9..d6d16f9c3 100644 --- a/docker/docker-compose.2204.57.yaml +++ b/docker/docker-compose.2204.57.yaml @@ -63,7 +63,7 @@ services: - MAX_ALLOCS_ALLOWED_modifying_1000_circular_buffer_elements=0 - MAX_ALLOCS_ALLOWED_modifying_byte_buffer_view=6050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=341 - - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=140050 + - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=130050 - MAX_ALLOCS_ALLOWED_schedule_10000_tasks=50100 - MAX_ALLOCS_ALLOWED_schedule_and_run_10000_tasks=50050 - MAX_ALLOCS_ALLOWED_scheduling_10000_executions=85 diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml index c7f4059b0..827f76771 100644 --- a/docker/docker-compose.2204.58.yaml +++ b/docker/docker-compose.2204.58.yaml @@ -63,7 +63,7 @@ services: - MAX_ALLOCS_ALLOWED_modifying_1000_circular_buffer_elements=0 - MAX_ALLOCS_ALLOWED_modifying_byte_buffer_view=6050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=341 - - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=140050 + - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=130050 - MAX_ALLOCS_ALLOWED_schedule_10000_tasks=50100 - MAX_ALLOCS_ALLOWED_schedule_and_run_10000_tasks=50050 - MAX_ALLOCS_ALLOWED_scheduling_10000_executions=85 diff --git a/docker/docker-compose.2204.59.yaml b/docker/docker-compose.2204.59.yaml index c1d94f76b..c348433d9 100644 --- a/docker/docker-compose.2204.59.yaml +++ b/docker/docker-compose.2204.59.yaml @@ -63,7 +63,7 @@ services: - MAX_ALLOCS_ALLOWED_modifying_1000_circular_buffer_elements=0 - MAX_ALLOCS_ALLOWED_modifying_byte_buffer_view=6050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=350 - - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=140050 + - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=130050 - MAX_ALLOCS_ALLOWED_schedule_10000_tasks=50100 - MAX_ALLOCS_ALLOWED_schedule_and_run_10000_tasks=50050 - MAX_ALLOCS_ALLOWED_scheduling_10000_executions=85 diff --git a/docker/docker-compose.2204.main.yaml b/docker/docker-compose.2204.main.yaml index ad3a7fb6a..5d08b84b1 100644 --- a/docker/docker-compose.2204.main.yaml +++ b/docker/docker-compose.2204.main.yaml @@ -62,7 +62,7 @@ services: - MAX_ALLOCS_ALLOWED_modifying_1000_circular_buffer_elements=0 - MAX_ALLOCS_ALLOWED_modifying_byte_buffer_view=6050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=343 - - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=140050 + - MAX_ALLOCS_ALLOWED_read_10000_chunks_from_file=130050 - MAX_ALLOCS_ALLOWED_schedule_10000_tasks=50100 - MAX_ALLOCS_ALLOWED_schedule_and_run_10000_tasks=50050 - MAX_ALLOCS_ALLOWED_scheduling_10000_executions=85