From 848e42899027d1b47219bf513cf771fcfd14e4eb Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Mon, 25 Nov 2024 18:15:18 +0000 Subject: [PATCH 01/93] deprecate NIOEventLoopGroupProvider.createNew (#2480) ### Motivation: `NIOEventLoopGroupProvider.createNew` was probably never a good idea because it creates shutdown issues for any library that uses it. Given that we now have singleton (#2471) `EventLoopGroup`s, we can solve this issue by just not having event loop group providers. Users can just use `group: any EventLoopGroup` and optionally `group: any EventLoopGroup = MultiThreadedEventLoopGroup.singleton`. ### Modifications: - deprecate `NIOEventLoopGroupProvider.createNew` - soft-deprecate (document as deprecated but don't mark `@available(deprecated)`) `NIOEventLoopGroupProvider` ### Result: - Libraries becomes easier to write and maintain. - Fixes #2142 --- Sources/NIOCore/Docs.docc/index.md | 1 - Sources/NIOCore/EventLoop.swift | 21 +++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Sources/NIOCore/Docs.docc/index.md b/Sources/NIOCore/Docs.docc/index.md index 13d76894e..5b437b073 100644 --- a/Sources/NIOCore/Docs.docc/index.md +++ b/Sources/NIOCore/Docs.docc/index.md @@ -21,7 +21,6 @@ More specialized modules provide concrete implementations of many of the abstrac - ``EventLoopGroup`` - ``EventLoop`` -- ``NIOEventLoopGroupProvider`` - ``EventLoopIterator`` - ``Scheduled`` - ``RepeatedTask`` diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 047c06e67..376f06d8f 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -1246,16 +1246,33 @@ extension EventLoopGroup { } #endif -/// This type is intended to be used by libraries which use NIO, and offer their users either the option +/// Deprecated. +/// +/// This type was intended to be used by libraries which use NIO, and offer their users either the option /// to `.share` an existing event loop group or create (and manage) a new one (`.createNew`) and let it be /// managed by given library and its lifecycle. +/// +/// Please use a `group: any EventLoopGroup` parameter instead. If you want to default to a global +/// singleton group instead, consider group: any EventLoopGroup = MultiThreadedEventLoopGroup.singleton` or +/// similar. +/// +/// - See also: https://github.com/apple/swift-nio/issues/2142 public enum NIOEventLoopGroupProvider { /// Use an `EventLoopGroup` provided by the user. /// The owner of this group is responsible for its lifecycle. case shared(EventLoopGroup) - /// Create a new `EventLoopGroup` when necessary. + + /// Deprecated. Create a new `EventLoopGroup` when necessary. /// The library which accepts this provider takes ownership of the created event loop group, /// and must ensure its proper shutdown when the library is being shut down. + @available( + *, + deprecated, + message: """ + Please use `.shared(existingGroup)` or use the singleton via \ + `.shared(MultiThreadedEventLoopGroup.singleton)` or similar + """ + ) case createNew } From d6be946626e395deb740ca83f99f5d2ec752f0e3 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 26 Nov 2024 11:36:30 +0000 Subject: [PATCH 02/93] ByteBuffer: one fewer allocs to go to Data (#1839) Motivation: When getting a `Data` from a `ByteBuffer` we currently allocate twice (`__DataStorage`) and the closure for `Data.Deallocator`. Modifications: We can optimise that by making the closure capture exactly one `AnyObject` which is already a reference counted object. The compiler realises that (on Linux) and saves us an alloc. Thanks @lukasa for the suggestion here: https://github.com/apple/swift-nio/pull/1836#issuecomment-830044155 Result: Fewer allocs. --- Sources/NIOFoundationCompat/ByteBuffer-foundation.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift index 8b221d75c..cf1a25830 100644 --- a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift +++ b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -126,11 +126,11 @@ extension ByteBuffer { count: Int(length) ) } else { - _ = storageRef.retain() + let storage = storageRef.takeUnretainedValue() return Data( bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr.baseAddress!.advanced(by: index)), count: Int(length), - deallocator: .custom { _, _ in storageRef.release() } + deallocator: .custom { _, _ in withExtendedLifetime(storage) {} } ) } } From 4d2fb577b9c0430d1c56478a1bf6f9f4c73942e4 Mon Sep 17 00:00:00 2001 From: Michael Gecht Date: Tue, 26 Nov 2024 14:48:29 +0000 Subject: [PATCH 03/93] Update documentation comments (#2998) Updates to documentation comments in `NIOFileSystem`. ### Motivation: I've been reviewing some parts of `NIOFileSystem` and came across a variety of formatting of documentation comments. ### Modifications: I've adopted a stricter 100-character limit (arbitrary, really; it could be longer or shorter and is totally not consistent with the rest of the repository). Also updated a bunch of grammar in comments. Fixed a few typos along the way. ### Result: - Updated comments have a better flow while reading, and aren't as abrupt as before. - Fewer typos in comments --------- Co-authored-by: Cory Benfield --- CONTRIBUTING.md | 7 +- Package.swift | 2 +- README.md | 6 +- Sources/NIOFileSystem/CopyStrategy.swift | 51 +++--- Sources/NIOFileSystem/FileSystem.swift | 166 +++++++++--------- .../Internal/ParallelDirCopy.swift | 63 +++---- Sources/NIOPosix/NIOThreadPool.swift | 4 +- 7 files changed, 149 insertions(+), 150 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d1311924..05b102e75 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,6 @@ your contribution to Apple and the community, and agree by submitting the patch that your contributions are licensed under the Apache 2.0 license (see `LICENSE.txt`). - ## How to submit a bug report Please ensure to specify the following: @@ -20,7 +19,6 @@ Please ensure to specify the following: * OS version and the output of `uname -a` * Network configuration - ### Example ``` @@ -89,7 +87,7 @@ SwiftNIO has been created to be high performance. The integration tests cover s ### Formatting -Try to keep your lines less than 120 characters long so github can correctly display your changes. +Try to keep your lines less than 120 characters long so GitHub can correctly display your changes. SwiftNIO uses the [swift-format](https://github.com/swiftlang/swift-format) tool to bring consistency to code formatting. There is a specific [.swift-format](./.swift-format) configuration file. This will be checked and enforced on PRs. Note that the check will run on the current most recent stable version target which may not match that in your own local development environment. @@ -106,7 +104,6 @@ act --container-architecture linux/amd64 --action-offline-mode --bind workflow_c This will run the format checks, binding to your local checkout so the edits made are to your own source. - ### Extensibility Try to make sure your code is robust to future extensions. The public interface is very hard to change after release - please refer to the [API guidelines](./docs/public-api.md) @@ -115,4 +112,4 @@ Try to make sure your code is robust to future extensions. The public interface Please open a pull request at https://github.com/apple/swift-nio. Make sure the CI passes, and then wait for code review. -After review you may be asked to make changes. When you are ready, use the request re-review feature of github or mention the reviewers by name in a comment. +After review you may be asked to make changes. When you are ready, use the request re-review feature of GitHub or mention the reviewers by name in a comment. diff --git a/Package.swift b/Package.swift index 4bbbe48e7..021ebf8e5 100644 --- a/Package.swift +++ b/Package.swift @@ -23,7 +23,7 @@ let swiftAtomics: PackageDescription.Target.Dependency = .product(name: "Atomics let swiftCollections: PackageDescription.Target.Dependency = .product(name: "DequeModule", package: "swift-collections") let swiftSystem: PackageDescription.Target.Dependency = .product(name: "SystemPackage", package: "swift-system") -// These platforms require a depdency on `NIOPosix` from `NIOHTTP1` to maintain backward +// These platforms require a dependency on `NIOPosix` from `NIOHTTP1` to maintain backward // compatibility with previous NIO versions. let historicalNIOPosixDependencyRequired: [Platform] = [.macOS, .iOS, .tvOS, .watchOS, .linux, .android] diff --git a/README.md b/README.md index 055c5359c..48d8b2497 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ SwiftNIO | Minimum Swift Version `2.43.0 ..< 2.51.0` | 5.5.2 `2.51.0 ..< 2.60.0` | 5.6 `2.60.0 ..< 2.65.0` | 5.7 -`2.65.0 ..< 2.76.0 | 5.8 +`2.65.0 ..< 2.76.0` | 5.8 `2.76.0 ...` | 5.9 ### SwiftNIO 1 @@ -116,7 +116,7 @@ SemVer and SwiftNIO's Public API guarantees should result in a working program w SwiftNIO is fundamentally a low-level tool for building high-performance networking applications in Swift. It particularly targets those use-cases where using a "thread-per-connection" model of concurrency is inefficient or untenable. This is a common limitation when building servers that use a large number of relatively low-utilization connections, such as HTTP servers. -To achieve its goals SwiftNIO extensively uses "non-blocking I/O": hence the name! Non-blocking I/O differs from the more common blocking I/O model because the application does not wait for data to be sent to or received from the network: instead, SwiftNIO asks for the kernel to notify it when I/O operations can be performed without waiting. +To achieve its goals, SwiftNIO extensively uses "non-blocking I/O": hence the name! Non-blocking I/O differs from the more common blocking I/O model because the application does not wait for data to be sent to or received from the network: instead, SwiftNIO asks for the kernel to notify it when I/O operations can be performed without waiting. SwiftNIO does not aim to provide high-level solutions like, for example, web frameworks do. Instead, SwiftNIO is focused on providing the low-level building blocks for these higher-level applications. When it comes to building a web application, most users will not want to use SwiftNIO directly: instead, they'll want to use one of the many great web frameworks available in the Swift ecosystem. Those web frameworks, however, may choose to use SwiftNIO under the covers to provide their networking support. @@ -139,7 +139,7 @@ All SwiftNIO applications are ultimately constructed of these various components #### EventLoops and EventLoopGroups -The basic I/O primitive of SwiftNIO is the event loop. The event loop is an object that waits for events (usually I/O related events, such as "data received") to happen and then fires some kind of callback when they do. In almost all SwiftNIO applications there will be relatively few event loops: usually only one or two per CPU core the application wants to use. Generally speaking event loops run for the entire lifetime of your application, spinning in an endless loop dispatching events. +The basic I/O primitive of SwiftNIO is the event loop. The event loop is an object that waits for events (usually I/O related events, such as "data received") to happen and then fires some kind of callback when they do. In almost all SwiftNIO applications there will be relatively few event loops: usually only one or two per CPU core the application wants to use. Generally speaking, event loops run for the entire lifetime of your application, spinning in an endless loop dispatching events. Event loops are gathered together into event loop *groups*. These groups provide a mechanism to distribute work around the event loops. For example, when listening for inbound connections the listening socket will be registered on one event loop. However, we don't want all connections that are accepted on that listening socket to be registered with the same event loop, as that would potentially overload one event loop while leaving the others empty. For that reason, the event loop group provides the ability to spread load across multiple event loops. diff --git a/Sources/NIOFileSystem/CopyStrategy.swift b/Sources/NIOFileSystem/CopyStrategy.swift index 790206dae..ae8b4770e 100644 --- a/Sources/NIOFileSystem/CopyStrategy.swift +++ b/Sources/NIOFileSystem/CopyStrategy.swift @@ -13,16 +13,16 @@ //===----------------------------------------------------------------------===// /// How to perform copies. Currently only relevant to directory level copies when using -/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` -/// or other overloads that use the default behaviour +/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other +/// overloads that use the default behaviour. public struct CopyStrategy: Hashable, Sendable { - // Avoid exposing to prevent alterations being breaking changes + // Avoid exposing to prevent breaking changes internal enum Wrapped: Hashable, Sendable { // platformDefault is reified into one of the concrete options below: case sequential - // Constraints on this value are enforced only on making `CopyStrategy`, - // the early error check there is desirable over validating on downstream use. + // Constraints on this value are enforced only on creation of `CopyStrategy`. The early + // error check is desirable over validating on downstream use. case parallel(_ maxDescriptors: Int) } @@ -33,14 +33,13 @@ public struct CopyStrategy: Hashable, Sendable { // These selections are relatively arbitrary but the rationale is as follows: // - // - Never exceed the default OS limits even if 4 such operations - // were happening at once + // - Never exceed the default OS limits even if 4 such operations were happening at once. // - Sufficient to enable significant speed up from parallelism - // - Not wasting effort by pushing contention to the underlying storage device - // Further we assume an SSD or similar underlying storage tech. - // Users on spinning rust need to account for that themselves anyway + // - Not wasting effort by pushing contention to the underlying storage device. Further we + // assume an SSD or similar underlying storage tech. Users on spinning rust need to account + // for that themselves anyway. // - // That said, empirical testing for this has not been performed, suggestions welcome + // That said, empirical testing for this has not been performed, suggestions welcome. // // Note: for now we model the directory scan as needing two handles because, during the creation // of the destination directory we hold the handle for a while copying attributes @@ -48,20 +47,22 @@ public struct CopyStrategy: Hashable, Sendable { // This may not result in a faster copy though so things are left simple internal static func determinePlatformDefault() -> Wrapped { #if os(macOS) || os(Linux) || os(Windows) - // 4 concurrent file copies/directory scans. - // Avoiding storage system contention is the dominant aspect here. - // Empirical testing on an SSD copying to the same volume with a dense directory of small - // files and sub directories of similar shape totalling 12GB showed improvements in elapsed - // time for (expected) increases in CPU time up to parallel(8), beyond this the increases - // in CPU came with only moderate gains. + // 4 concurrent file copies/directory scans. Avoiding storage system contention is of utmost + // importance. + // + // Testing was performed on an SSD, while copying objects (a dense directory of small files + // and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed + // improvements in elapsed time for (expected) increases in CPU time up to parallel(8). + // Beyond this, the increases in CPU led to only moderate gains. + // // Anyone tuning this is encouraged to cover worst case scenarios. return .parallel(8) #elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android) - // Reduced maximum descriptors in embedded world - // This is chosen based on biasing to safety, not empirical testing. + // Reduced maximum descriptors in embedded world. This is chosen based on biasing towards + // safety, not empirical testing. return .parallel(4) #else - // Safety first, if we have no view on it keep it simple. + // Safety first. If we do not know what system we run on, we keep it simple. return .sequential #endif } @@ -69,19 +70,19 @@ public struct CopyStrategy: Hashable, Sendable { extension CopyStrategy { // A copy fundamentally can't work without two descriptors unless you copy - // everything into memory which is infeasible/inefficeint for large copies. + // everything into memory which is infeasible/inefficient for large copies. private static let minDescriptorsAllowed = 2 - /// Operate in whatever manner is deemed a reasonable default for the platform. - /// This will limit the maximum file descriptors usage based on 'reasonable' defaults. + /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit + /// the maximum file descriptors usage based on reasonable defaults. /// /// Current assumptions (which are subject to change): /// - Only one copy operation would be performed at once /// - The copy operation is not intended to be the primary activity on the device public static let platformDefault: Self = Self(Self.determinePlatformDefault()) - /// The copy is done asynchronously, but only one operation will occur at a time. - /// This is the only way to guarantee only one callback to the `shouldCopyItem` will happen at a time + /// The copy is done asynchronously, but only one operation will occur at a time. This is the + /// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time. public static let sequential: Self = Self(.sequential) /// Allow multiple IO operations to run concurrently, including file copies/directory creation and scanning diff --git a/Sources/NIOFileSystem/FileSystem.swift b/Sources/NIOFileSystem/FileSystem.swift index 76a1bcb8a..33bf8c605 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -32,12 +32,11 @@ import Bionic /// /// ### Creating a `FileSystem` /// -/// You should prefer using the `shared` instance of the file system. The -/// `shared` instance uses two threads unless the `SWIFT_FILE_SYSTEM_THREAD_COUNT` -/// environment variable is set. +/// You should prefer using the `shared` instance of the file system. The `shared` instance uses two +/// threads unless the `SWIFT_FILE_SYSTEM_THREAD_COUNT` environment variable is set. /// -/// If you require more granular control you can create a ``FileSystem`` with the required number -/// of threads by calling ``withFileSystem(numberOfThreads:_:)`` or by using ``init(threadPool:)``. +/// If you require more granular control you can create a ``FileSystem`` with the required number of +/// threads by calling ``withFileSystem(numberOfThreads:_:)`` or by using ``init(threadPool:)``. /// /// ### Errors /// @@ -54,8 +53,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// Returns a shared global instance of the ``FileSystem``. /// /// The file system executes blocking work in a thread pool which defaults to having two - /// threads. This can be modified by `blockingPoolThreadCountSuggestion` or by - /// setting the `NIO_SINGLETON_BLOCKING_POOL_THREAD_COUNT` environment variable. + /// threads. This can be modified by `blockingPoolThreadCountSuggestion` or by setting the + /// `NIO_SINGLETON_BLOCKING_POOL_THREAD_COUNT` environment variable. public static var shared: FileSystem { globalFileSystem } private let threadPool: NIOThreadPool @@ -70,8 +69,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// Creates a new ``FileSystem`` using the provided thread pool. /// /// - Parameter threadPool: A started thread pool to execute blocking system calls on. The - /// ``FileSystem`` doesn't take ownership of the thread pool and you remain responsible - /// for shutting it down when necessary. + /// ``FileSystem`` doesn't take ownership of the thread pool and you remain responsible for + /// shutting it down when necessary. public init(threadPool: NIOThreadPool) { self.init(threadPool: threadPool, ownsThreadPool: false) } @@ -217,8 +216,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// Error codes thrown include: /// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if a file or directory already /// exists . - /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if a component in the `path` - /// prefix does not exist and `createIntermediateDirectories` is `false`. + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if a component in the `path` prefix + /// does not exist and `createIntermediateDirectories` is `false`. /// /// #### Implementation details /// @@ -248,10 +247,10 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// #### Errors /// /// Error codes thrown include: - /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the template doesn't end - /// in at least 3 'X's. - /// - ``FileSystemError/Code-swift.struct/permissionDenied`` if the user doesn't have - /// permission to create a directory at the path specified in the template. + /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if the template doesn't end in at + /// least 3 'X's. + /// - ``FileSystemError/Code-swift.struct/permissionDenied`` if the user doesn't have permission + /// to create a directory at the path specified in the template. /// /// #### Implementation details /// @@ -277,9 +276,9 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// - Parameters: /// - path: The path of the file. - /// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true` then information - /// about the link will be returned, otherwise information about the destination of the - /// symbolic link is returned. + /// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true`, + /// then information about the link will be returned. Otherwise, information about the + /// destination of the symbolic link is returned. /// - Returns: Information about the file at the given path or `nil` if no file exists. public func info( forFileAt path: FilePath, @@ -299,18 +298,18 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// - symbolic link, or /// - directory. /// - /// But `shouldCopyItem` can be used to ignore things outside this supported set. + /// `shouldCopyItem` can be used to ignore objects not part of this set. /// /// #### Errors /// /// In addition to the already documented errors these may be thrown - /// - ``FileSystemError/Code-swift.struct/unsupported`` if an item to be copied is not a - /// regular file, symbolic link or directory. + /// - ``FileSystemError/Code-swift.struct/unsupported`` if an item to be copied is not a regular + /// file, symbolic link or directory. /// /// #### Implementation details /// - /// This function is platform dependent. On Darwin the `copyfile(2)` system call is - /// used and items are cloned where possible. On Linux the `sendfile(2)` system call is used. + /// This function is platform dependent. On Darwin the `copyfile(2)` system call is used and + /// items are cloned where possible. On Linux the `sendfile(2)` system call is used. public func copyItem( at sourcePath: FilePath, to destinationPath: FilePath, @@ -334,8 +333,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { ) } - // By doing this before looking at the type we allow callers to decide whether - // unanticipated kinds of entries can be safely ignored without needing changes upstream + // By doing this before looking at the type, we allow callers to decide whether + // unanticipated kinds of entries can be safely ignored without needing changes upstream. if await shouldCopyItem(.init(path: sourcePath, type: info.type)!, destinationPath) { switch info.type { case .regular: @@ -400,7 +399,7 @@ public struct FileSystem: Sendable, FileSystemProtocol { switch result { case .success: - // Great; we removed 1 whole item. + // Great; we removed an entire item. return 1 case .failure(.noSuchFileOrDirectory): @@ -413,8 +412,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { code: .notEmpty, message: """ Can't remove directory at path '\(path)', it isn't empty and \ - 'removeItemRecursively' is false. Remove items from the directory first \ - or set 'removeItemRecursively' to true when calling \ + 'removeItemRecursively' is false. Remove items from the directory first or \ + set 'removeItemRecursively' to true when calling \ 'removeItem(at:recursively:)'. """, cause: nil, @@ -674,8 +673,8 @@ private let globalFileSystem: FileSystem = { extension NIOSingletons { /// Returns a shared global instance of the ``FileSystem``. /// - /// The file system executes blocking work in a thread pool see `blockingPoolThreadCountSuggestion` - /// for the default behaviour and ways to control it. + /// The file system executes blocking work in a thread pool. See + /// `blockingPoolThreadCountSuggestion` for the default behaviour and ways to control it. public static var fileSystem: FileSystem { globalFileSystem } } @@ -737,7 +736,8 @@ extension FileSystem { } } - /// Opens `path` for reading and writing and returns ``ReadWriteFileHandle`` or ``FileSystemError``. + /// Opens `path` for reading and writing and returns ``ReadWriteFileHandle`` or + /// ``FileSystemError``. private func _openFile( forReadingAndWritingAt path: FilePath, options: OpenOptions.Write @@ -777,15 +777,16 @@ extension FileSystem { withIntermediateDirectories createIntermediateDirectories: Bool, permissions: FilePermissions ) -> Result { - // Logic, assuming we are creating intermediate directories: try creating the directory, - // if it fails with ENOENT (no such file or directory) then drop the last component and - // append it to a buffer. Repeat until the path is empty meaning we cannot create the - // directory, or we succeed in which case we can append build up our original path - // creating directories one at a time. + // We assume that we will be creating intermediate directories: + // - Try creating the directory. If it fails with ENOENT (no such file or directory), then + // drop the last component and append it to a buffer. + // - Repeat until the path is empty. This means we cannot create the directory or we + // succeed, in which case we can build up our original path and create directories one at + // a time. var droppedComponents: [FilePath.Component] = [] var path = fullPath - // Normalize the path to remove any '..' which may not be necessary. + // Normalize the path to remove any superflous '..'. path.lexicallyNormalize() if path.isEmpty { @@ -857,28 +858,24 @@ extension FileSystem { } } - /// Represents an item in a directory that needs copying, or - /// an explicit indication of the end of items. - /// The provision of the ``endOfDir`` case significantly simplifies the parallel code + /// Represents an item in a directory that needs copying, or an explicit indication of the end + /// of items. The provision of the ``endOfDir`` case significantly simplifies the parallel code enum DirCopyItem: Hashable, Sendable { case endOfDir case toCopy(from: DirectoryEntry, to: FilePath) } - /// Creates the directory ``destinationPath`` based on the directory at ``sourcePath`` - /// including any permissions/attributes. - /// It does not copy the contents but does indicate the items directly within ``sourcePath`` which - /// should be copied + /// Creates the directory ``destinationPath`` based on the directory at ``sourcePath`` including + /// any permissions/attributes. It does not copy the contents but indicates the items within + /// ``sourcePath`` which should be copied. /// - /// This is a little cumbersome because it is used by ``copyDirectorySequential`` and - /// ``copyDirectoryParallel``. - /// It is desirable to use the file descriptor for the directory itself for as little time as possible - /// (certainly not across async invocations). - /// The down stream paths in the parallel and sequential paths are very different - /// - Returns: - /// An array of `DirCopyItem` which have passed the ``shouldCopyItem```filter - /// The target file paths will all be in ``destinationPath`` - /// The array will always finish with an ``DirCopyItem.endOfDir`` + /// This is a little cumbersome, because it is used by ``copyDirectorySequential`` and + /// ``copyDirectoryParallel``. It is desirable to use the directories' file descriptor for as + /// little time as possible, and certainly not across asynchronous invocations. The downstream + /// paths in the parallel and sequential paths are very different + /// - Returns: An array of `DirCopyItem` which have passed the ``shouldCopyItem``` filter. The + /// target file paths will all be in ``destinationPath``. The array will always finish with + /// an ``DirCopyItem.endOfDir``. private func prepareDirectoryForRecusiveCopy( from sourcePath: FilePath, to destinationPath: FilePath, @@ -917,26 +914,24 @@ extension FileSystem { } } } catch let error as FileSystemError where error.code == .unsupported { - // Not all file systems support extended attributes. Swallow errors which indicate - // that is the case. + // Not all file systems support extended attributes. Swallow errors indicating this. () } #endif - // Build a list of items the caller needs to deal with, - // they then do any further work after closing the current directory + // Build a list of items the caller needs to deal with, then do any further work after + // closing the current directory. var contentsToCopy = [DirCopyItem]() for try await batch in dir.listContents().batched() { for entry in batch { - // Any further work is pointless, we are under no obligation to cleanup - // so exit as fast and cleanly as possible. + // Any further work is pointless. We are under no obligation to cleanup. Exit as + // fast and cleanly as possible. try Task.checkCancellation() let entryDestination = destinationPath.appending(entry.name) if await shouldCopyItem(entry, entryDestination) { - // Assume there's a good chance of everything in the batch - // being included in the common case. - // Let geometric growth go from this point though. + // Assume there's a good chance of everything in the batch being included in + // the common case. Let geometric growth go from this point though. if contentsToCopy.isEmpty { // Reserve space for the endOfDir entry too. contentsToCopy.reserveCapacity(batch.count + 1) @@ -967,8 +962,8 @@ extension FileSystem { } } - /// This could be achieved through quite complicated special casing of the parallel copy. - /// The resulting code is far harder to read and debug though so this is kept as a special case + /// This could be achieved through quite complicated special casing of the parallel copy. The + /// resulting code is far harder to read and debug, so this is kept as a special case. private func copyDirectorySequential( from sourcePath: FilePath, to destinationPath: FilePath, @@ -981,9 +976,9 @@ extension FileSystem { _ destination: FilePath ) async -> Bool ) async throws { - // Strategy: find all needed items to copy/recurse into while the directory is open; - // defer actual copying and recursion until after the source directory has been closed - // to avoid consuming too many file descriptors. + // Strategy: find all needed items to copy/recurse into while the directory is open; defer + // actual copying and recursion until after the source directory has been closed to avoid + // consuming too many file descriptors. let toCopy = try await self.prepareDirectoryForRecusiveCopy( from: sourcePath, to: destinationPath, @@ -997,9 +992,9 @@ extension FileSystem { // Sequential cases doesn't need to worry about this, it uses simple recursion. continue case let .toCopy(source, destination): - // Note: The entry type could have changed between finding it and acting on it. - // This is inherent in file systems, just more likely in an async environment - // we just accept those coming through as regular errors. + // Note: The entry type could have changed between finding it and acting on it. This + // is inherent in file systems, just more likely in an asynchronous environment. We + // just accept those coming through as regular errors. switch source.type { case .regular: do { @@ -1069,12 +1064,14 @@ extension FileSystem { shouldCopyItem: shouldCopyItem ) case let .parallel(maxDescriptors): - // Note that maxDescriptors was validated on construction of CopyStrategy. - // See notes on CopyStrategy about assumptions on descriptor use. - // For now we take the worst case peak for every operation, which is 2 descriptors, - // this keeps the downstream limiting code simple - // We do not preclude the use of more granular limiting in future (e.g. a directory - // scan only requires 1), for now we just drop any excess remainder entirely. + // Note that maxDescriptors was validated on construction of CopyStrategy. See notes on + // CopyStrategy about assumptions on descriptor use. For now, we take the worst case + // peak for every operation, which is two file descriptors. This keeps the downstream + // limiting code simple. + // + // We do not preclude the use of more granular limiting in the future (e.g. a directory + // scan requires only a single file descriptor). For now we just drop any excess + // remainder entirely. let limitValue = maxDescriptors / 2 return try await self.copyDirectoryParallel( from: sourcePath, @@ -1086,9 +1083,9 @@ extension FileSystem { } } - /// Building block of the parallel directory copy implementation - /// Each invovation of this is allowed to consume two file descriptors, - /// any further work (if any) should be sent to `yield` for future processing + /// Building block of the parallel directory copy implementation. Each invocation of this is + /// allowed to consume two file descriptors. Any further work (if any) should be sent to `yield` + /// for future processing. func copySelfAndEnqueueChildren( from: DirectoryEntry, to: FilePath, @@ -1344,7 +1341,7 @@ extension FileSystem { // Check that the destination doesn't exist. 'rename' will remove it otherwise! switch self._info(forFileAt: destinationPath, infoAboutSymbolicLink: true) { case .success(.none): - // Doens't exist: continue + // Doesn't exist: continue () case .success(.some): @@ -1375,8 +1372,7 @@ extension FileSystem { return .success(.moved) case .failure(.improperLink): - // The two paths are on different logical devices; copy and then remove the - // original. + // The two paths are on different logical devices; copy and then remove the original. return .success(.differentLogicalDevices) case let .failure(errno): @@ -1410,7 +1406,8 @@ extension FileSystem { let lastComponent = lastComponentPath.string - // Finding the index of the last non-'X' character in `lastComponent.string` and advancing it by one. + // Finding the index of the last non-'X' character in `lastComponent.string` and advancing + // it by one. let prefix: String var index = lastComponent.lastIndex(where: { $0 != "X" }) if index != nil { @@ -1484,7 +1481,8 @@ extension FileSystem { case let .failure(error): if let systemCallError = error.cause as? FileSystemError.SystemCallError { switch systemCallError.errno { - // If the file at the generated path already exists, we generate a new file path. + // If the file at the generated path already exists, we generate a new file + // path. case .fileExists, .isDirectory: break default: diff --git a/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift index 8f1d6b381..ce793264a 100644 --- a/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift +++ b/Sources/NIOFileSystem/Internal/ParallelDirCopy.swift @@ -16,16 +16,18 @@ import NIOCore @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension FileSystem { - - /// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to `destinationPath`. + /// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to + /// `destinationPath`. /// - /// The parallelism is solely at the level of individual items (so files, symbolic links and directories), a larger file - /// is not considered for being 'split' into concurrent reads or wites. - /// If any symbolic link is encountered then only the link is copied. - /// The copied items will preserve permissions and any extended attributes (if supported by the file system). + /// The parallelism is solely at the level of individual items (files, symbolic links and + /// directories). A larger file is not 'split' into concurrent reads or writes. /// - /// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open file descriptors at any point. - /// Operations are assume to consume 2 descriptors so maximum open descriptors is `maxConcurrentOperations * 2` + /// If a symbolic link is encountered, then only the link is copied. If supported by the file + /// system, the copied items will preserve permissions and any extended attributes. + /// + /// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open + /// file descriptors at any point. Operations are assumed to consume 2 descriptors, so the + /// maximum open descriptors are `maxConcurrentOperations * 2` @usableFromInline func copyDirectoryParallel( from sourcePath: FilePath, @@ -40,9 +42,9 @@ extension FileSystem { _ destination: FilePath ) async -> Bool ) async throws { - // Implemented with NIOAsyncSequenceProducer rather than AsyncStream. - // It is approximately the same speed in the best case but has significantly less variance. - // NIOAsyncSequenceProducer also enforces a multi producer single consumer access pattern. + // Implemented with NIOAsyncSequenceProducer rather than AsyncStream. It is approximately + // the same speed in the best case, but has significantly less variance. + // NIOAsyncSequenceProducer also enforces a multi-producer, single-consumer access pattern. let copyRequiredQueue = NIOAsyncSequenceProducer.makeSequence( elementType: DirCopyItem.self, backPressureStrategy: NoBackPressureStrategy(), @@ -50,33 +52,35 @@ extension FileSystem { delegate: DirCopyDelegate() ) - // We ignore the result of yield in all cases because we are not implementing back pressure - // and cancellation is dealt with separately. + // We ignore the result of yield in all cases, because we are not implementing back + // pressure, and cancellation is dealt with separately. @Sendable func yield(_ contentsOf: [DirCopyItem]) { _ = copyRequiredQueue.source.yield(contentsOf: contentsOf) } - // Kick start the procees by enqueuing the root entry, - // the calling function already validated the root needed copying. + // Kick-start the procees by enqueuing the root entry. The calling function already + // validated the root needed copying, so it is safe to force unwrap the value. _ = copyRequiredQueue.source.yield( .toCopy(from: .init(path: sourcePath, type: .directory)!, to: destinationPath) ) - // The processing of the very first item (the root) will increment this, - // after then when it hits zero we've finished. + // The processing of the very first item (the root) will increment this counter. Processing + // will finish when the counter hits zero again. + // // This does not need to be a ManagedAtomic or similar because: - // - All maintenance of state is done in the withThrowingTaskGroup callback + // - All state maintenance is done within the withThrowingTaskGroup closure // - All actual file system work is done by tasks created on the `taskGroup` var activeDirCount = 0 - // Despite there being no 'result' of each operation we cannot use a discarding task group + // Despite there being no 'result' for each operation, we cannot use a discarding task group, // because we use the 'drain results' queue as a concurrency limiting side effect. try await withThrowingTaskGroup(of: Void.self) { taskGroup in - - // Code handling each item to process on the current task + // Process each item in the current task. + // // Side Effects: // - Updates activeDirCount and finishes the stream if required. - // - Either adds a single task on `taskGroup` or none. + // - Might add a task to `taskGroup`. + // // Returns true if it added a task, false otherwise. func onNextItem(_ item: DirCopyItem) -> Bool { switch item { @@ -105,7 +109,7 @@ extension FileSystem { let iter = copyRequiredQueue.sequence.makeAsyncIterator() - // inProgress counts the number of tasks we have added to the task group + // inProgress counts the number of tasks we have added to the task group. // Get up to the maximum concurrency first. // We haven't started monitoring for task completion, so inProgress is 'worst case'. var inProgress = 0 @@ -116,16 +120,15 @@ extension FileSystem { inProgress += 1 } } else { - // Either we completed things before we hit the limit or we were cancelled. - // In the latter case we choose to propagate the cancel clearly. - // This makes testing for the cancellation more reliable. + // Either we completed things before we hit the limit or we were cancelled. In + // the latter case we choose to propagate the cancellation clearly. This makes + // testing for it more reliable. try Task.checkCancellation() return } } - // Then operate one in (finish) -> one out (start another), - // but only for items that trigger a task. + // One in (finish) -> one out (start another), but only for items that trigger a task. while let _ = try await taskGroup.next() { var keepConsuming = true while keepConsuming { @@ -133,7 +136,7 @@ extension FileSystem { if let item = item { keepConsuming = !onNextItem(item) } else { - // To accurately propagate the cancellation we must check here too + // We must check here, to accurately propagate the cancellation. try Task.checkCancellation() keepConsuming = false } @@ -143,7 +146,7 @@ extension FileSystem { } } -/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``. +/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) private struct NoBackPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategy { mutating func didYield(bufferDepth: Int) -> Bool { true } diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index 6d3bc08f7..75dfd0874 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -441,11 +441,11 @@ extension NIOThreadPool { } /// Runs the submitted closure if the thread pool is still active, otherwise throw an error. - /// The closure will be run on the thread pool so can do blocking work. + /// The closure will be run on the thread pool, such that we can do blocking work. /// /// - Parameters: /// - body: The closure which performs some blocking work to be done on the thread pool. - /// - Returns: result of the passed closure. + /// - Returns: Result of the passed closure. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func runIfActive(_ body: @escaping @Sendable () throws -> T) async throws -> T { let workID = self.nextWorkID.loadThenWrappingIncrement(ordering: .relaxed) From d2cc4d7f94bbc705c6a4a6fbb37ad56caa814b2c Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Tue, 26 Nov 2024 15:42:10 +0000 Subject: [PATCH 04/93] Cxx interop CI appends swiftSettings (#3002) Cxx interop CI appends `swiftSettings` to any existing settings rather than overriding them. ### Motivation: This better accommodates workflows for example which use Swift 5 language mode on a per-target basis. ### Modifications: Cxx interop CI appends `swiftSettings` to any existing settings rather than overriding them. ### Result: Cxx interop CI jobs don't cause unexpected build configurations. --- scripts/check-cxx-interop-compatibility.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check-cxx-interop-compatibility.sh b/scripts/check-cxx-interop-compatibility.sh index 5ad33a609..9e868e94b 100755 --- a/scripts/check-cxx-interop-compatibility.sh +++ b/scripts/check-cxx-interop-compatibility.sh @@ -33,7 +33,7 @@ swift package init { echo "let swiftSettings: [SwiftSetting] = [.interoperabilityMode(.Cxx)]" - echo "for target in package.targets { target.swiftSettings = swiftSettings }" + echo "for target in package.targets { target.swiftSettings = (target.swiftSettings ?? []) + swiftSettings }" } >> Package.swift echo "package.dependencies.append(.package(path: \"$source_dir\"))" >> Package.swift From 49b9d9725ef1dc20d01970fa9e9334e1d16c19ca Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 26 Nov 2024 16:02:36 +0000 Subject: [PATCH 05/93] fix remaining warnings & enable -warnings-as-errors in CI (#3000) ### Motivation: Warnings are annoying. ### Modifications: - Remove unnecessary use of `Foundation.Thread` which isn't Sendable. - Remove now unnecessary `@retroactive`s. - Enable `-warnings-as-errors` in CI ### Result: - Warnings can't sneak in as easily anymore - No more warnings left in `swift-nio` ``` $ rm -rf .build/arm64-apple-macosx/ && swift build --build-tests -Xswiftc -warnings-as-errors > /dev/null echo $? $ echo $? 0 ``` Co-authored-by: Cory Benfield --- .github/workflows/main.yml | 4 +-- .../ByteBuffer-foundation.swift | 6 ---- .../NIOPosixTests/EchoServerClientTest.swift | 2 +- Tests/NIOPosixTests/NIOThreadPoolTest.swift | 29 +++++++------------ Tests/NIOPosixTests/SALEventLoopTests.swift | 6 +--- Tests/NIOPosixTests/TestUtils.swift | 4 +-- 6 files changed, 17 insertions(+), 34 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 13420a4d8..f6fd16711 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,8 +14,8 @@ jobs: with: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" - linux_6_0_arguments_override: "--explicit-target-dependency-import-check error" - linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error" + linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + linux_nightly_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" cxx-interop: diff --git a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift index cf1a25830..c4240d4ed 100644 --- a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift +++ b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift @@ -377,15 +377,9 @@ extension ByteBufferAllocator { } // MARK: - Conformances -#if compiler(>=6.0) -extension ByteBufferView: @retroactive ContiguousBytes {} -extension ByteBufferView: @retroactive DataProtocol {} -extension ByteBufferView: @retroactive MutableDataProtocol {} -#else extension ByteBufferView: ContiguousBytes {} extension ByteBufferView: DataProtocol {} extension ByteBufferView: MutableDataProtocol {} -#endif extension ByteBufferView { public typealias Regions = CollectionOfOne diff --git a/Tests/NIOPosixTests/EchoServerClientTest.swift b/Tests/NIOPosixTests/EchoServerClientTest.swift index 678f6da80..9675e1946 100644 --- a/Tests/NIOPosixTests/EchoServerClientTest.swift +++ b/Tests/NIOPosixTests/EchoServerClientTest.swift @@ -224,7 +224,7 @@ class EchoServerClientTest: XCTestCase { try withTemporaryUnixDomainSocketPathName { udsPath in // Bootstrap should not overwrite an existing file unless it is a socket - FileManager.default.createFile(atPath: udsPath, contents: nil, attributes: nil) + _ = FileManager.default.createFile(atPath: udsPath, contents: nil, attributes: nil) let bootstrap = ServerBootstrap(group: group) XCTAssertThrowsError( diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index ed39352df..21eda2b44 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -78,18 +78,15 @@ class NIOThreadPoolTest: XCTestCase { // The lock here is arguably redundant with the dispatchgroup, but let's make // this test thread-safe even if I screw up. - let lock = NIOLock() - let threadOne: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) - let threadTwo: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) + let threadOne: NIOLockedValueBox = NIOLockedValueBox(NIOThread?.none) + let threadTwo: NIOLockedValueBox = NIOLockedValueBox(NIOThread?.none) completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLock { () -> Void in - threadOne.withLockedValue { threadOne in - XCTAssertEqual(threadOne, nil) - threadOne = Thread.current - } + threadOne.withLockedValue { threadOne in + XCTAssertEqual(threadOne, nil) + threadOne = NIOThread.current } completionGroup.leave() } @@ -99,22 +96,18 @@ class NIOThreadPoolTest: XCTestCase { completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLock { () -> Void in - threadTwo.withLockedValue { threadTwo in - XCTAssertEqual(threadTwo, nil) - threadTwo = Thread.current - } + threadTwo.withLockedValue { threadTwo in + XCTAssertEqual(threadTwo, nil) + threadTwo = NIOThread.current } completionGroup.leave() } completionGroup.wait() - lock.withLock { () -> Void in - XCTAssertNotNil(threadOne) - XCTAssertNotNil(threadTwo) - XCTAssertEqual(threadOne.withLockedValue { $0 }, threadTwo.withLockedValue { $0 }) - } + XCTAssertNotNil(threadOne.withLockedValue { $0 }) + XCTAssertNotNil(threadTwo.withLockedValue { $0 }) + XCTAssertEqual(threadOne.withLockedValue { $0 }, threadTwo.withLockedValue { $0 }) } func testAsyncThreadPool() async throws { diff --git a/Tests/NIOPosixTests/SALEventLoopTests.swift b/Tests/NIOPosixTests/SALEventLoopTests.swift index 6cc81f5c8..ad3656475 100644 --- a/Tests/NIOPosixTests/SALEventLoopTests.swift +++ b/Tests/NIOPosixTests/SALEventLoopTests.swift @@ -59,16 +59,12 @@ final class SALEventLoopTests: XCTestCase, SALTest { } // Now execute 10 tasks. - var i = 0 for _ in 0..<10 { - thisLoop.execute { - i &+= 1 - } + thisLoop.execute {} } // Now enqueue a "last" task. thisLoop.execute { - i &+= 1 promise.succeed(()) } diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index c239a09c8..ab5a11891 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -127,7 +127,7 @@ func withTemporaryUnixDomainSocketPathName( shortEnoughPath = path restoreSavedCWD = false } catch SocketAddressError.unixDomainSocketPathTooLong { - FileManager.default.changeCurrentDirectoryPath( + _ = FileManager.default.changeCurrentDirectoryPath( URL(fileURLWithPath: path).deletingLastPathComponent().absoluteString ) shortEnoughPath = URL(fileURLWithPath: path).lastPathComponent @@ -141,7 +141,7 @@ func withTemporaryUnixDomainSocketPathName( try? FileManager.default.removeItem(atPath: path) } if restoreSavedCWD { - FileManager.default.changeCurrentDirectoryPath(saveCurrentDirectory) + _ = FileManager.default.changeCurrentDirectoryPath(saveCurrentDirectory) } } return try body(shortEnoughPath) From 16f19c0c645014a41456097f1848018efca41d7e Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 26 Nov 2024 16:19:33 +0000 Subject: [PATCH 06/93] Prevent crash in Happy Eyeballs Resolver (#3003) Motivation: In vanishingly rare situations it is possible for the AAAA results to come in on the same tick as the resolution delay timer completes. In those cases, depending on the ordering of the tasks, we can get situations where the resolution delay timer completion causes a crash. Modifications: Tolerate receiving the resolution delay timer after resolution completes. Result: Fewer crashes --- Sources/NIOPosix/HappyEyeballs.swift | 7 ++- Tests/NIOPosixTests/HappyEyeballsTest.swift | 47 +++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/Sources/NIOPosix/HappyEyeballs.swift b/Sources/NIOPosix/HappyEyeballs.swift index 015a8b4af..25071ec32 100644 --- a/Sources/NIOPosix/HappyEyeballs.swift +++ b/Sources/NIOPosix/HappyEyeballs.swift @@ -464,7 +464,12 @@ internal final class HappyEyeballsConnector { // notifications, and can also get late scheduled task callbacks. We want to just quietly // ignore these, as our transition into the complete state should have already sent // cleanup messages to all of these things. - case (.complete, .resolverACompleted), + // + // We can also get the resolutionDelayElapsed after allResolved, as it's possible that + // callback was already dequeued in the same tick as the cancellation. That's also fine: + // the resolution delay isn't interesting. + case (.allResolved, .resolutionDelayElapsed), + (.complete, .resolverACompleted), (.complete, .resolverAAAACompleted), (.complete, .connectSuccess), (.complete, .connectFailed), diff --git a/Tests/NIOPosixTests/HappyEyeballsTest.swift b/Tests/NIOPosixTests/HappyEyeballsTest.swift index 66f0dec09..29f35820f 100644 --- a/Tests/NIOPosixTests/HappyEyeballsTest.swift +++ b/Tests/NIOPosixTests/HappyEyeballsTest.swift @@ -1308,4 +1308,51 @@ public final class HappyEyeballsTest: XCTestCase { XCTAssertNoThrow(try client.close().wait()) } + + func testResolutionTimeoutAndResolutionInSameTick() throws { + var channels: [Channel] = [] + let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { + let channelFuture = defaultChannelBuilder(loop: $0, family: $1) + channelFuture.whenSuccess { channel in + try! channel.pipeline.addHandler(ConnectionDelayer(), name: CONNECT_DELAYER, position: .first).wait() + channels.append(channel) + } + return channelFuture + } + let targetFuture = eyeballer.resolveAndConnect().flatMapThrowing { (channel) -> String? in + let target = channel.connectTarget() + _ = try (channel as! EmbeddedChannel).finish() + return target + } + loop.run() + + // Then, queue a task to resolve the v6 promise after 50ms. + // Why 50ms? This is the same time as the resolution delay. + let promise = resolver.v6Promise + loop.scheduleTask(in: .milliseconds(50)) { + promise.fail(DummyError()) + } + + // Kick off the IPv4 resolution. This triggers the timer for the resolution delay. + resolver.v4Promise.succeed(SINGLE_IPv4_RESULT) + loop.run() + + // Advance time 50ms. + loop.advanceTime(by: .milliseconds(50)) + + // Then complete the connection future. + XCTAssertEqual(channels.count, 1) + channels.first!.succeedConnection() + + // Should be done. + let target = try targetFuture.wait() + XCTAssertEqual(target!, "10.0.0.1") + + // We should have had queries for AAAA and A. + let expectedQueries: [DummyResolver.Event] = [ + .aaaa(host: "example.com", port: 80), + .a(host: "example.com", port: 80), + ] + XCTAssertEqual(resolver.events, expectedQueries) + } } From ca55b0e50febfc597537a820048ccc5cdbd4f5bf Mon Sep 17 00:00:00 2001 From: George Barnett Date: Wed, 27 Nov 2024 11:21:34 +0000 Subject: [PATCH 07/93] Remove noasync from NIOFileHandle (#3001) Motivation: In #2598, `NIOFileHandle` was annotated with `noasync` in a few places. This is, unfortunately, a breaking change. Modifications: - Remove the `noasync` annotations Result: Adopters aren't broken --------- Co-authored-by: Cory Benfield --- Sources/NIOCore/FileHandle.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/Sources/NIOCore/FileHandle.swift b/Sources/NIOCore/FileHandle.swift index 62fd100e2..6c7dc0812 100644 --- a/Sources/NIOCore/FileHandle.swift +++ b/Sources/NIOCore/FileHandle.swift @@ -373,7 +373,6 @@ extension NIOFileHandle { use NIOFileSystem as a replacement API. """ ) - @available(*, noasync, message: "This method may block the calling thread") public convenience init( path: String, mode: Mode = .read, @@ -415,7 +414,6 @@ extension NIOFileHandle { use NIOFileSystem as a replacement API. """ ) - @available(*, noasync, message: "This method may block the calling thread") public convenience init(path: String) throws { try self.init(_deprecatedPath: path) } From 8126cba71251682a15a7878f67ab0ad5659f2a98 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 28 Nov 2024 11:30:54 +0000 Subject: [PATCH 08/93] Avoid converting array holding existentials (#3006) Motivation: When converting an Array that holds existentials, it is necessary for Swift to allocate a new Array and copy the elements into it, so that it can fix up their existential boxes. We forced this to happen with taking a `[ChannelHandler]` to `[ChannelHandler & Sendable]`, without rewriting the other functions. The result of that was that the other functions needed to convert the channel handler types, causing extra allocations in this path. Modifications: Propagate the constraint down to the point where we iterate the Array. Result: Allocations reduced. --- .../tests_04_performance/Thresholds/5.10.json | 76 +++++++++--------- .../tests_04_performance/Thresholds/5.9.json | 77 ++++++++++--------- .../tests_04_performance/Thresholds/6.0.json | 76 +++++++++--------- .../Thresholds/nightly-6.0.json | 76 +++++++++--------- .../Thresholds/nightly-main.json | 76 +++++++++--------- Sources/NIOCore/ChannelPipeline.swift | 58 +++++++++++++- 6 files changed, 246 insertions(+), 193 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index 1fb41c219..9f75ed151 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -1,50 +1,50 @@ { "10000000_asyncsequenceproducer": 19, - "1000000_asyncwriter": 1000013, - "1000_addHandlers": 44000, - "1000_addHandlers_sync": 36000, - "1000_addRemoveHandlers_handlercontext": 8032, - "1000_addRemoveHandlers_handlername": 8032, - "1000_addRemoveHandlers_handlertype": 8032, - "1000_autoReadGetAndSet": 18000, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 43050, + "1000_addHandlers_sync": 36050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1000, - "1000_copying_circularbuffer_to_array": 1000, - "1000_getHandlers": 8034, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, "1000_getHandlers_sync": 34, - "1000_reqs_1_conn": 26363, - "1000_rst_connections": 145004, - "1000_tcpbootstraps": 3001, - "1000_tcpconnections": 152002, - "1000_udp_reqs": 6014, - "1000_udpbootstraps": 2000, - "1000_udpconnections": 75008, - "1_reqs_1000_conn": 389000, - "bytebuffer_lots_of_rw": 2005, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, - "decode_1000_ws_frames": 2000, + "decode_1000_ws_frames": 2050, "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2003, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003, - "encode_1000_ws_frames_new_buffer": 3000, - "encode_1000_ws_frames_new_buffer_with_mask": 5000, - "encode_1000_ws_frames_new_buffer_with_space": 3000, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_erase_result": 4001, - "future_lots_of_callbacks": 53001, - "get_100000_headers_canonical_form": 700000, - "get_100000_headers_canonical_form_trimming_whitespace": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6000, + "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 319, - "read_10000_chunks_from_file": 110009, - "schedule_10000_tasks": 40084, - "schedule_and_run_10000_tasks": 50010, + "read_10000_chunks_from_file": 110050, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6156, - "udp_1_reqs_1000_conn": 162000 + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index b77ad41e4..2edeea7c8 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -1,50 +1,51 @@ { "10000000_asyncsequenceproducer": 19, - "1000000_asyncwriter": 1000013, - "1000_addHandlers": 44000, - "1000_addHandlers_sync": 36000, - "1000_addRemoveHandlers_handlercontext": 8032, - "1000_addRemoveHandlers_handlername": 8032, - "1000_addRemoveHandlers_handlertype": 8032, - "1000_autoReadGetAndSet": 18000, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 43050, + "1000_addHandlers_sync": 36050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1000, - "1000_copying_circularbuffer_to_array": 1000, - "1000_getHandlers": 8034, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, "1000_getHandlers_sync": 34, - "1000_reqs_1_conn": 26372, - "1000_rst_connections": 147004, - "1000_tcpbootstraps": 4001, - "1000_tcpconnections": 154002, - "1000_udp_reqs": 6014, - "1000_udpbootstraps": 2000, - "1000_udpconnections": 75008, - "1_reqs_1000_conn": 398000, - "bytebuffer_lots_of_rw": 2005, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 147050, + "1000_tcpbootstraps": 4050, + "1000_tcpconnections": 154050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 398050, + "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, - "decode_1000_ws_frames": 2000, + "decode_1000_ws_frames": 2050, "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2003, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003, - "encode_1000_ws_frames_new_buffer": 3000, - "encode_1000_ws_frames_new_buffer_with_mask": 5000, - "encode_1000_ws_frames_new_buffer_with_space": 3000, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_erase_result": 4001, - "future_lots_of_callbacks": 53001, - "get_100000_headers_canonical_form": 700000, - "get_100000_headers_canonical_form_trimming_whitespace": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6000, + "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 334, - "read_10000_chunks_from_file": 110009, - "schedule_10000_tasks": 40084, - "schedule_and_run_10000_tasks": 50010, + "read_10000_chunks_from_file": 110050, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6156, - "udp_1_reqs_1000_conn": 162000 + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } + diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index 1fb41c219..9f75ed151 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -1,50 +1,50 @@ { "10000000_asyncsequenceproducer": 19, - "1000000_asyncwriter": 1000013, - "1000_addHandlers": 44000, - "1000_addHandlers_sync": 36000, - "1000_addRemoveHandlers_handlercontext": 8032, - "1000_addRemoveHandlers_handlername": 8032, - "1000_addRemoveHandlers_handlertype": 8032, - "1000_autoReadGetAndSet": 18000, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 43050, + "1000_addHandlers_sync": 36050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1000, - "1000_copying_circularbuffer_to_array": 1000, - "1000_getHandlers": 8034, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, "1000_getHandlers_sync": 34, - "1000_reqs_1_conn": 26363, - "1000_rst_connections": 145004, - "1000_tcpbootstraps": 3001, - "1000_tcpconnections": 152002, - "1000_udp_reqs": 6014, - "1000_udpbootstraps": 2000, - "1000_udpconnections": 75008, - "1_reqs_1000_conn": 389000, - "bytebuffer_lots_of_rw": 2005, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, - "decode_1000_ws_frames": 2000, + "decode_1000_ws_frames": 2050, "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2003, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003, - "encode_1000_ws_frames_new_buffer": 3000, - "encode_1000_ws_frames_new_buffer_with_mask": 5000, - "encode_1000_ws_frames_new_buffer_with_space": 3000, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_erase_result": 4001, - "future_lots_of_callbacks": 53001, - "get_100000_headers_canonical_form": 700000, - "get_100000_headers_canonical_form_trimming_whitespace": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6000, + "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 319, - "read_10000_chunks_from_file": 110009, - "schedule_10000_tasks": 40084, - "schedule_and_run_10000_tasks": 50010, + "read_10000_chunks_from_file": 110050, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6156, - "udp_1_reqs_1000_conn": 162000 + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index 1fb41c219..9f75ed151 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -1,50 +1,50 @@ { "10000000_asyncsequenceproducer": 19, - "1000000_asyncwriter": 1000013, - "1000_addHandlers": 44000, - "1000_addHandlers_sync": 36000, - "1000_addRemoveHandlers_handlercontext": 8032, - "1000_addRemoveHandlers_handlername": 8032, - "1000_addRemoveHandlers_handlertype": 8032, - "1000_autoReadGetAndSet": 18000, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 43050, + "1000_addHandlers_sync": 36050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1000, - "1000_copying_circularbuffer_to_array": 1000, - "1000_getHandlers": 8034, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, "1000_getHandlers_sync": 34, - "1000_reqs_1_conn": 26363, - "1000_rst_connections": 145004, - "1000_tcpbootstraps": 3001, - "1000_tcpconnections": 152002, - "1000_udp_reqs": 6014, - "1000_udpbootstraps": 2000, - "1000_udpconnections": 75008, - "1_reqs_1000_conn": 389000, - "bytebuffer_lots_of_rw": 2005, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, - "decode_1000_ws_frames": 2000, + "decode_1000_ws_frames": 2050, "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2003, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003, - "encode_1000_ws_frames_new_buffer": 3000, - "encode_1000_ws_frames_new_buffer_with_mask": 5000, - "encode_1000_ws_frames_new_buffer_with_space": 3000, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_erase_result": 4001, - "future_lots_of_callbacks": 53001, - "get_100000_headers_canonical_form": 700000, - "get_100000_headers_canonical_form_trimming_whitespace": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6000, + "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 319, - "read_10000_chunks_from_file": 110009, - "schedule_10000_tasks": 40084, - "schedule_and_run_10000_tasks": 50010, + "read_10000_chunks_from_file": 110050, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6156, - "udp_1_reqs_1000_conn": 162000 + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 1fb41c219..9f75ed151 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -1,50 +1,50 @@ { "10000000_asyncsequenceproducer": 19, - "1000000_asyncwriter": 1000013, - "1000_addHandlers": 44000, - "1000_addHandlers_sync": 36000, - "1000_addRemoveHandlers_handlercontext": 8032, - "1000_addRemoveHandlers_handlername": 8032, - "1000_addRemoveHandlers_handlertype": 8032, - "1000_autoReadGetAndSet": 18000, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 43050, + "1000_addHandlers_sync": 36050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1000, - "1000_copying_circularbuffer_to_array": 1000, - "1000_getHandlers": 8034, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, "1000_getHandlers_sync": 34, - "1000_reqs_1_conn": 26363, - "1000_rst_connections": 145004, - "1000_tcpbootstraps": 3001, - "1000_tcpconnections": 152002, - "1000_udp_reqs": 6014, - "1000_udpbootstraps": 2000, - "1000_udpconnections": 75008, - "1_reqs_1000_conn": 389000, - "bytebuffer_lots_of_rw": 2005, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, - "decode_1000_ws_frames": 2000, + "decode_1000_ws_frames": 2050, "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2003, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2003, - "encode_1000_ws_frames_new_buffer": 3000, - "encode_1000_ws_frames_new_buffer_with_mask": 5000, - "encode_1000_ws_frames_new_buffer_with_space": 3000, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5000, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_erase_result": 4001, - "future_lots_of_callbacks": 53001, - "get_100000_headers_canonical_form": 700000, - "get_100000_headers_canonical_form_trimming_whitespace": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700000, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700000, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6000, + "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 319, - "read_10000_chunks_from_file": 110009, - "schedule_10000_tasks": 40084, - "schedule_and_run_10000_tasks": 50010, + "read_10000_chunks_from_file": 110050, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6156, - "udp_1_reqs_1000_conn": 162000 + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 } diff --git a/Sources/NIOCore/ChannelPipeline.swift b/Sources/NIOCore/ChannelPipeline.swift index 2aa8d6c62..6920a2b0f 100644 --- a/Sources/NIOCore/ChannelPipeline.swift +++ b/Sources/NIOCore/ChannelPipeline.swift @@ -1119,7 +1119,7 @@ extension ChannelPipeline { /// - position: The position in the `ChannelPipeline` to add the handlers. /// - Returns: A result representing whether the handlers were added or not. fileprivate func addHandlersSync( - _ handlers: [ChannelHandler], + _ handlers: [ChannelHandler & Sendable], position: ChannelPipeline.Position ) -> Result { switch position { @@ -1130,6 +1130,29 @@ extension ChannelPipeline { } } + /// Synchronously adds the provided `ChannelHandler`s to the pipeline in the order given, taking + /// account of the behaviour of `ChannelHandler.add(first:)`. + /// + /// This duplicate of the above method exists to avoid needing to rebox the array of existentials + /// from any (ChannelHandler & Sendable) to any ChannelHandler. + /// + /// - Important: Must be called on the `EventLoop`. + /// - Parameters: + /// - handlers: The array of `ChannelHandler`s to add. + /// - position: The position in the `ChannelPipeline` to add the handlers. + /// - Returns: A result representing whether the handlers were added or not. + fileprivate func addHandlersSyncNotSendable( + _ handlers: [ChannelHandler], + position: ChannelPipeline.Position + ) -> Result { + switch position { + case .first, .after: + return self._addHandlersSyncNotSendable(handlers.reversed(), position: position) + case .last, .before: + return self._addHandlersSyncNotSendable(handlers, position: position) + } + } + /// Synchronously adds a sequence of `ChannelHandlers` to the pipeline at the given position. /// /// - Important: Must be called on the `EventLoop`. @@ -1140,6 +1163,35 @@ extension ChannelPipeline { private func _addHandlersSync( _ handlers: Handlers, position: ChannelPipeline.Position + ) -> Result where Handlers.Element == ChannelHandler & Sendable { + self.eventLoop.assertInEventLoop() + + for handler in handlers { + let result = self.addHandlerSync(handler, position: position) + switch result { + case .success: + () + case .failure: + return result + } + } + + return .success(()) + } + + /// Synchronously adds a sequence of `ChannelHandlers` to the pipeline at the given position. + /// + /// This duplicate of the above method exists to avoid needing to rebox the array of existentials + /// from any (ChannelHandler & Sendable) to any ChannelHandler. + /// + /// - Important: Must be called on the `EventLoop`. + /// - Parameters: + /// - handlers: A sequence of handlers to add. + /// - position: The position in the `ChannelPipeline` to add the handlers. + /// - Returns: A result representing whether the handlers were added or not. + private func _addHandlersSyncNotSendable( + _ handlers: Handlers, + position: ChannelPipeline.Position ) -> Result where Handlers.Element == ChannelHandler { self.eventLoop.assertInEventLoop() @@ -1201,7 +1253,7 @@ extension ChannelPipeline { _ handlers: [ChannelHandler], position: ChannelPipeline.Position = .last ) throws { - try self._pipeline.addHandlersSync(handlers, position: position).get() + try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get() } /// Add one or more handlers to the pipeline. @@ -1214,7 +1266,7 @@ extension ChannelPipeline { _ handlers: ChannelHandler..., position: ChannelPipeline.Position = .last ) throws { - try self._pipeline.addHandlersSync(handlers, position: position).get() + try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get() } /// Remove a `ChannelHandler` from the `ChannelPipeline`. From 8a1523fb1a7e04c41346e375905d510eb45df55d Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Thu, 28 Nov 2024 15:20:37 +0100 Subject: [PATCH 09/93] Aligning semantic version label check name (#3007) --- .github/workflows/pull_request_label.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull_request_label.yml b/.github/workflows/pull_request_label.yml index fbc861863..c78fe14fa 100644 --- a/.github/workflows/pull_request_label.yml +++ b/.github/workflows/pull_request_label.yml @@ -6,7 +6,7 @@ on: jobs: semver-label-check: - name: Semantic Version label check + name: Semantic version label check runs-on: ubuntu-latest timeout-minutes: 1 steps: From 33b8a4801fbef544301c82a62564c0071322dda5 Mon Sep 17 00:00:00 2001 From: finagolfin Date: Sun, 1 Dec 2024 23:27:08 +0530 Subject: [PATCH 10/93] Use the new Android overlay in the tests and update some Bionic declarations (#3009) ### Motivation: Get this repo building again for Android with NDK 27 ### Modifications: - Update some networking declarations for newly added nullability annotations - Import the new Android overlay instead in some tests - Add two force-unwraps on all platforms, that are needed for Android ### Result: This repo and its tests build for Android again I've been [using these patches on my Android CI](https://github.com/finagolfin/swift-android-sdk/blob/main/swift-nio-ndk27.patch) and natively on Android for a couple months now. I didn't bother keeping this patch building for Android with Swift 5 anymore, as my Android CI no longer tests Swift 5. I built this pull and ran the tests on linux x86_64 to make sure there was no regression. --- .../Internal/System Calls/Syscalls.swift | 11 +---------- Sources/NIOPosix/System.swift | 18 ++++++++++++++---- .../NIOConcurrencyHelpersTests.swift | 4 ++-- Tests/NIOCoreTests/XCTest+Extensions.swift | 4 ++++ Tests/NIOEmbeddedTests/TestUtils.swift | 4 ++++ Tests/NIOFileSystemTests/FileInfoTests.swift | 10 +++++----- Tests/NIOFileSystemTests/FileTypeTests.swift | 2 ++ 7 files changed, 32 insertions(+), 21 deletions(-) diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift index dcff57801..e2f5efd32 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift @@ -452,21 +452,12 @@ internal func libc_confstr( #endif /// fts(3) -#if os(Android) -internal func libc_fts_open( - _ path: [UnsafeMutablePointer], - _ options: CInt -) -> UnsafeMutablePointer { - fts_open(path, options, nil)! -} -#else internal func libc_fts_open( _ path: [UnsafeMutablePointer?], _ options: CInt ) -> UnsafeMutablePointer { - fts_open(path, options, nil) + fts_open(path, options, nil)! } -#endif /// fts(3) internal func libc_fts_read( diff --git a/Sources/NIOPosix/System.swift b/Sources/NIOPosix/System.swift index adb7cb2ff..c221bd40d 100644 --- a/Sources/NIOPosix/System.swift +++ b/Sources/NIOPosix/System.swift @@ -124,12 +124,20 @@ private let sysWritev = sysWritev_wrapper #elseif !os(Windows) private let sysWritev: @convention(c) (Int32, UnsafePointer?, CInt) -> CLong = writev #endif -#if !os(Windows) +#if canImport(Android) +private let sysRecvMsg: @convention(c) (CInt, UnsafeMutablePointer, CInt) -> ssize_t = recvmsg +private let sysSendMsg: @convention(c) (CInt, UnsafePointer, CInt) -> ssize_t = sendmsg +#elseif !os(Windows) private let sysRecvMsg: @convention(c) (CInt, UnsafeMutablePointer?, CInt) -> ssize_t = recvmsg private let sysSendMsg: @convention(c) (CInt, UnsafePointer?, CInt) -> ssize_t = sendmsg #endif private let sysDup: @convention(c) (CInt) -> CInt = dup -#if !os(Windows) +#if canImport(Android) +private let sysGetpeername: + @convention(c) (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt = getpeername +private let sysGetsockname: + @convention(c) (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt = getsockname +#elseif !os(Windows) private let sysGetpeername: @convention(c) (CInt, UnsafeMutablePointer?, UnsafeMutablePointer?) -> CInt = getpeername private let sysGetsockname: @@ -141,7 +149,9 @@ private let sysIfNameToIndex: @convention(c) (UnsafePointer) -> CUnsigned #else private let sysIfNameToIndex: @convention(c) (UnsafePointer?) -> CUnsignedInt = if_nametoindex #endif -#if !os(Windows) +#if canImport(Android) +private let sysSocketpair: @convention(c) (CInt, CInt, CInt, UnsafeMutablePointer) -> CInt = socketpair +#elseif !os(Windows) private let sysSocketpair: @convention(c) (CInt, CInt, CInt, UnsafeMutablePointer?) -> CInt = socketpair #endif @@ -1000,7 +1010,7 @@ internal enum Posix { socketVector: UnsafeMutablePointer? ) throws { _ = try syscall(blocking: false) { - sysSocketpair(domain.rawValue, type.rawValue, protocolSubtype.rawValue, socketVector) + sysSocketpair(domain.rawValue, type.rawValue, protocolSubtype.rawValue, socketVector!) } } #endif diff --git a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift index 53864db0f..bb0622262 100644 --- a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift +++ b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift @@ -22,8 +22,8 @@ import XCTest import Darwin #elseif canImport(Glibc) import Glibc -#elseif canImport(Bionic) -import Bionic +#elseif canImport(Android) +import Android #else #error("The Concurrency helpers test module was unable to identify your C library.") #endif diff --git a/Tests/NIOCoreTests/XCTest+Extensions.swift b/Tests/NIOCoreTests/XCTest+Extensions.swift index 0fc5c8b7d..2970c6551 100644 --- a/Tests/NIOCoreTests/XCTest+Extensions.swift +++ b/Tests/NIOCoreTests/XCTest+Extensions.swift @@ -15,6 +15,10 @@ import NIOCore import XCTest +#if canImport(Android) +import Android +#endif + func assert( _ condition: @autoclosure () -> Bool, within time: TimeAmount, diff --git a/Tests/NIOEmbeddedTests/TestUtils.swift b/Tests/NIOEmbeddedTests/TestUtils.swift index 02fe152e7..c25bc44a1 100644 --- a/Tests/NIOEmbeddedTests/TestUtils.swift +++ b/Tests/NIOEmbeddedTests/TestUtils.swift @@ -17,6 +17,10 @@ import NIOConcurrencyHelpers import NIOCore import XCTest +#if canImport(Android) +import Android +#endif + // FIXME: Duplicated with NIO func assert( _ condition: @autoclosure () -> Bool, diff --git a/Tests/NIOFileSystemTests/FileInfoTests.swift b/Tests/NIOFileSystemTests/FileInfoTests.swift index 2e679d9a9..ae06ab5e2 100644 --- a/Tests/NIOFileSystemTests/FileInfoTests.swift +++ b/Tests/NIOFileSystemTests/FileInfoTests.swift @@ -19,8 +19,8 @@ import _NIOFileSystem import Darwin #elseif canImport(Glibc) import Glibc -#elseif canImport(Bionic) -import Bionic +#elseif canImport(Android) +import Android #endif final class FileInfoTests: XCTestCase { @@ -44,7 +44,7 @@ final class FileInfoTests: XCTestCase { status.st_birthtimespec = timespec(tv_sec: 3, tv_nsec: 0) status.st_flags = 11 status.st_gen = 12 - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) status.st_atim = timespec(tv_sec: 0, tv_nsec: 0) status.st_mtim = timespec(tv_sec: 1, tv_nsec: 0) status.st_ctim = timespec(tv_sec: 2, tv_nsec: 0) @@ -98,7 +98,7 @@ final class FileInfoTests: XCTestCase { assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_birthtimespec.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_flags += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_gen += 1 } - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_atim.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_mtim.tv_sec += 1 } assertNotEqualAfterMutation { $0.platformSpecificStatus!.st_ctim.tv_sec += 1 } @@ -151,7 +151,7 @@ final class FileInfoTests: XCTestCase { } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_flags += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_gen += 1 } - #elseif canImport(Glibc) || canImport(Bionic) + #elseif canImport(Glibc) || canImport(Android) assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_atim.tv_sec += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_mtim.tv_sec += 1 } assertDifferentHashValueAfterMutation { $0.platformSpecificStatus!.st_ctim.tv_sec += 1 } diff --git a/Tests/NIOFileSystemTests/FileTypeTests.swift b/Tests/NIOFileSystemTests/FileTypeTests.swift index 0655d32a5..b25e2170f 100644 --- a/Tests/NIOFileSystemTests/FileTypeTests.swift +++ b/Tests/NIOFileSystemTests/FileTypeTests.swift @@ -19,6 +19,8 @@ import XCTest import Darwin #elseif canImport(Glibc) import Glibc +#elseif canImport(Android) +import Android #endif final class FileTypeTests: XCTestCase { From 876fbf694b2f27a9783a8e944dddd37bb1710d3e Mon Sep 17 00:00:00 2001 From: Clinton Nkwocha <32041805+clintonpi@users.noreply.github.com> Date: Tue, 3 Dec 2024 15:29:47 +0000 Subject: [PATCH 11/93] Revert `fastRebase` implementation (#3014) Motivation: `UnsafeRawBufferPointer.init(fastRebase:)` and `UnsafeMutableRawBufferPointer.init(fastRebase:)` were shimmed into NIO in https://github.com/apple/swift-nio/pull/1696. The shim is no longer necessary. Modifications: - Revert the use of the `fastRebase` inits to the native `.init(rebasing:)`. Result: Use of native APIs instead. --- Sources/NIOCore/ByteBuffer-aux.swift | 13 ++++---- Sources/NIOCore/ByteBuffer-core.swift | 16 +++++----- Sources/NIOCore/ByteBuffer-int.swift | 2 +- Sources/NIOCore/PointerHelpers.swift | 43 --------------------------- Sources/NIOPosix/ControlMessage.swift | 10 +++++-- Sources/NIOPosix/PointerHelpers.swift | 41 ------------------------- 6 files changed, 25 insertions(+), 100 deletions(-) delete mode 100644 Sources/NIOCore/PointerHelpers.swift delete mode 100644 Sources/NIOPosix/PointerHelpers.swift diff --git a/Sources/NIOCore/ByteBuffer-aux.swift b/Sources/NIOCore/ByteBuffer-aux.swift index 5e07f4af2..232dffd87 100644 --- a/Sources/NIOCore/ByteBuffer-aux.swift +++ b/Sources/NIOCore/ByteBuffer-aux.swift @@ -39,7 +39,7 @@ extension ByteBuffer { // this is not technically correct because we shouldn't just bind // the memory to `UInt8` but it's not a real issue either and we // need to work around https://bugs.swift.org/browse/SR-9604 - [UInt8](UnsafeRawBufferPointer(fastRebase: ptr[range]).bindMemory(to: UInt8.self)) + [UInt8](UnsafeRawBufferPointer(rebasing: ptr[range]).bindMemory(to: UInt8.self)) } } @@ -205,7 +205,10 @@ extension ByteBuffer { } return self.withUnsafeReadableBytes { pointer in assert(range.lowerBound >= 0 && (range.upperBound - range.lowerBound) <= pointer.count) - return String(decoding: UnsafeRawBufferPointer(fastRebase: pointer[range]), as: Unicode.UTF8.self) + return String( + decoding: UnsafeRawBufferPointer(rebasing: pointer[range]), + as: Unicode.UTF8.self + ) } } @@ -329,7 +332,7 @@ extension ByteBuffer { self.withVeryUnsafeMutableBytes { destCompleteStorage in assert(destCompleteStorage.count >= index + allBytesCount) let dest = destCompleteStorage[index..= 0, "Can't write fewer than 0 bytes") self.reserveCapacity(index + count) self.withVeryUnsafeMutableBytes { pointer in - let dest = UnsafeMutableRawBufferPointer(fastRebase: pointer[index.. UnsafeMutablePointer { self._ensureAvailableCapacity(_Capacity(capacity), at: index) let newBytesPtr = UnsafeMutableRawBufferPointer( - fastRebase: self._slicedStorageBuffer[Int(index)..= writerIndex let range = Range(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex)) - return try body(.init(fastRebase: self._slicedStorageBuffer[range])) + return try body(.init(rebasing: self._slicedStorageBuffer[range])) } /// Yields the bytes currently writable (`bytesWritable` = `capacity` - `writerIndex`). Before reading those bytes you must first @@ -677,7 +679,7 @@ public struct ByteBuffer { _ body: (UnsafeMutableRawBufferPointer) throws -> T ) rethrows -> T { self._copyStorageAndRebaseIfNeeded() - return try body(.init(fastRebase: self._slicedStorageBuffer.dropFirst(self.writerIndex))) + return try body(.init(rebasing: self._slicedStorageBuffer.dropFirst(self.writerIndex))) } /// This vends a pointer of the `ByteBuffer` at the `writerIndex` after ensuring that the buffer has at least `minimumWritableBytes` of writable bytes available. @@ -748,7 +750,7 @@ public struct ByteBuffer { public func withUnsafeReadableBytes(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T { // This is safe, writerIndex >= readerIndex let range = Range(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex)) - return try body(.init(fastRebase: self._slicedStorageBuffer[range])) + return try body(.init(rebasing: self._slicedStorageBuffer[range])) } /// Yields a buffer pointer containing this `ByteBuffer`'s readable bytes. You may hold a pointer to those bytes @@ -769,7 +771,7 @@ public struct ByteBuffer { let storageReference: Unmanaged = Unmanaged.passUnretained(self._storage) // This is safe, writerIndex >= readerIndex let range = Range(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex)) - return try body(.init(fastRebase: self._slicedStorageBuffer[range]), storageReference) + return try body(.init(rebasing: self._slicedStorageBuffer[range]), storageReference) } /// See `withUnsafeReadableBytesWithStorageManagement` and `withVeryUnsafeBytes`. @@ -1120,7 +1122,7 @@ extension ByteBuffer { self._ensureAvailableCapacity(_Capacity(length), at: _toIndex(toIndex)) self.withVeryUnsafeMutableBytes { ptr in let srcPtr = UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: fromIndex), count: length) - let targetPtr = UnsafeMutableRawBufferPointer(fastRebase: ptr.dropFirst(toIndex)) + let targetPtr = UnsafeMutableRawBufferPointer(rebasing: ptr.dropFirst(toIndex)) targetPtr.copyMemory(from: srcPtr) } diff --git a/Sources/NIOCore/ByteBuffer-int.swift b/Sources/NIOCore/ByteBuffer-int.swift index d0fb02690..87e0c9abb 100644 --- a/Sources/NIOCore/ByteBuffer-int.swift +++ b/Sources/NIOCore/ByteBuffer-int.swift @@ -67,7 +67,7 @@ extension ByteBuffer { return self.withUnsafeReadableBytes { ptr in var value: T = 0 withUnsafeMutableBytes(of: &value) { valuePtr in - valuePtr.copyMemory(from: UnsafeRawBufferPointer(fastRebase: ptr[range])) + valuePtr.copyMemory(from: UnsafeRawBufferPointer(rebasing: ptr[range])) } return _toEndianness(value: value, endianness: endianness) } diff --git a/Sources/NIOCore/PointerHelpers.swift b/Sources/NIOCore/PointerHelpers.swift deleted file mode 100644 index 0acc2f2c2..000000000 --- a/Sources/NIOCore/PointerHelpers.swift +++ /dev/null @@ -1,43 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2017-2018 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 -// -//===----------------------------------------------------------------------===// - -// MARK: Rebasing shims - -// FIXME: Duplicated in NIO. - -// These methods are shimmed in to NIO until https://github.com/apple/swift/pull/34879 is resolved. -// They address the fact that the current rebasing initializers are surprisingly expensive and do excessive -// checked arithmetic. This expense forces them to often be outlined, reducing the ability to optimise out -// further preconditions and branches. -extension UnsafeRawBufferPointer { - @inlinable - init(fastRebase slice: Slice) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } - - @inlinable - init(fastRebase slice: Slice) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} - -extension UnsafeMutableRawBufferPointer { - @inlinable - init(fastRebase slice: Slice) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} diff --git a/Sources/NIOPosix/ControlMessage.swift b/Sources/NIOPosix/ControlMessage.swift index 79cf861e5..6e6338e6b 100644 --- a/Sources/NIOPosix/ControlMessage.swift +++ b/Sources/NIOPosix/ControlMessage.swift @@ -79,7 +79,9 @@ struct UnsafeControlMessageStorage: Collection { /// Get the part of the buffer for use with a message. public subscript(position: Int) -> UnsafeMutableRawBufferPointer { UnsafeMutableRawBufferPointer( - fastRebase: self.buffer[(position * self.bytesPerMessage)..<((position + 1) * self.bytesPerMessage)] + rebasing: self.buffer[ + (position * self.bytesPerMessage)..<((position + 1) * self.bytesPerMessage) + ] ) } @@ -316,7 +318,9 @@ struct UnsafeOutboundControlBytes { type: CInt, payload: PayloadType ) { - let writableBuffer = UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[writePosition...]) + let writableBuffer = UnsafeMutableRawBufferPointer( + rebasing: self.controlBytes[writePosition...] + ) let requiredSize = NIOBSDSocketControlMessage.space(payloadSize: MemoryLayout.stride(ofValue: payload)) precondition(writableBuffer.count >= requiredSize, "Insufficient size for cmsghdr and data") @@ -342,7 +346,7 @@ struct UnsafeOutboundControlBytes { if writePosition == 0 { return UnsafeMutableRawBufferPointer(start: nil, count: 0) } - return UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[0..) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } - - @inlinable - init(fastRebase slice: Slice) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} - -extension UnsafeMutableRawBufferPointer { - @inlinable - init(fastRebase slice: Slice) { - let base = slice.base.baseAddress?.advanced(by: slice.startIndex) - self.init(start: base, count: slice.endIndex &- slice.startIndex) - } -} From d3e8c8c67d11db89607bb8dbff098f8b12d946de Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Thu, 5 Dec 2024 08:23:51 +0000 Subject: [PATCH 12/93] Introduce JSON matrix workflow (#3013) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce and adopt a new method for defining test matrices, `swift_test_matrix.yml`. ⚠️ Any external adopters of the unit tests, Cxx interop and benchmarks workflows are automatically opted in to use the new infrastructure. ### Motivation: * The current matrix workflow has the limitation that it only supports pre-defined sets of variables which are explored in the test matrix. At the moment this is a pre-defined set of Swift versions on Linux and Windows. * Adding more means hard-coding them at multiple levels of the workflow hierarchy. * Currently skipped Windows matrix jobs show up as successes in the GitHub UI leading to a misleading impression of good coverage. ### Modifications: Introduce and adopt a new method for defining test matrices, `swift_test_matrix.yml`. The new method is based around the approach of defining the test matrix via a JSON object which may be supplied via an input string from another workflow or from a file on-disk in a repository. Taking this approach means that we have the ability to add new targets to the matrix simply by adding new elements to the JSON array, increasing flexibility and the scope for future growth. The unit tests, Cxx interop and benchmarks workflows are all modified to use the new approach, this opts-in all downstream adopters. This should be transparent to all downstream adopters. In order to unify the Linux and Windows jobs I removed the use of the `container:` GitHub Actions affordance in the Linux jobs which transparently means all steps are executed within the nested container. Instead we must manually call in to the docker container which complicates scripting a little. I tested to see if doing this slowed down the jobs (perhaps GitHub was caching the docker images more intelligently) but it does not. This approach follows the pattern of @FranzBusch 's open PR https://github.com/apple/swift-nio/pull/2942 ### Result: * More flexible test matrix definitions * No more false-passes for disabled Windows targets --- .github/workflows/benchmarks.yml | 34 ++++-- .github/workflows/cxx_interop.yml | 40 +++++-- .github/workflows/main.yml | 29 ++++- .github/workflows/pull_request.yml | 33 +++-- .github/workflows/swift_test_matrix.yml | 93 ++++++++++++++ .github/workflows/unit_tests.yml | 54 ++++++--- scripts/generate_matrix.sh | 153 ++++++++++++++++++++++++ 7 files changed, 380 insertions(+), 56 deletions(-) create mode 100644 .github/workflows/swift_test_matrix.yml create mode 100755 scripts/generate_matrix.sh diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index 2b2e4eb38..f039ba7c5 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -45,18 +45,32 @@ on: default: false jobs: + construct-matrix: + name: Construct Benchmarks matrix + runs-on: ubuntu-latest + outputs: + benchmarks-matrix: '${{ steps.generate-matrix.outputs.benchmarks-matrix }}' + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - id: generate-matrix + run: echo "benchmarks-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + env: + MATRIX_LINUX_COMMAND: "swift package --package-path ${{ inputs.benchmark_package_path }} ${{ inputs.swift_package_arguments }} benchmark baseline check --check-absolute-path ${{ inputs.benchmark_package_path }}/Thresholds/${SWIFT_VERSION}/" + MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q libjemalloc-dev" + MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} + MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }} + MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} + benchmarks: name: Benchmarks + needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main with: name: "Benchmarks" - matrix_linux_command: "apt-get update -y -q && apt-get install -y -q libjemalloc-dev && swift package --package-path ${{ inputs.benchmark_package_path }} ${{ inputs.swift_package_arguments }} benchmark baseline check --check-absolute-path ${{ inputs.benchmark_package_path }}/Thresholds/${SWIFT_VERSION}/" - matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }} - matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }} - matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }} - matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }} - matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }} - matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }} - matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }} - matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }} + matrix_string: '${{ needs.construct-matrix.outputs.benchmarks-matrix }}' diff --git a/.github/workflows/cxx_interop.yml b/.github/workflows/cxx_interop.yml index 3e6642607..545d59638 100644 --- a/.github/workflows/cxx_interop.yml +++ b/.github/workflows/cxx_interop.yml @@ -26,30 +26,44 @@ on: windows_6_0_enabled: type: boolean - description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking default: false windows_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking default: false windows_nightly_main_enabled: type: boolean - description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking default: false jobs: + construct-matrix: + name: Construct Cxx interop matrix + runs-on: ubuntu-latest + outputs: + cxx-interop-matrix: '${{ steps.generate-matrix.outputs.cxx-interop-matrix }}' + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - id: generate-matrix + run: echo "cxx-interop-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + env: + MATRIX_LINUX_COMMAND: "curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/check-cxx-interop-compatibility.sh | bash" + MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q curl jq" + MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} + MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }} + MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} + cxx-interop: name: Cxx interop + needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main with: name: "Cxx interop" - matrix_linux_command: "apt-get update -y -q && apt-get install -y -q jq && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/check-cxx-interop-compatibility.sh | bash" - matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }} - matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }} - matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }} - matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }} - matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }} - matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }} - matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }} - matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }} + matrix_string: '${{ needs.construct-matrix.outputs.cxx-interop-matrix }}' diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f6fd16711..b7ff32779 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,7 @@ jobs: unit-tests: name: Unit tests # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/unit_tests.yml@main + uses: apple/swift-nio/.github/workflows/unit_tests.yml@matrix_file # TODO: replace with @main with: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" @@ -21,19 +21,36 @@ jobs: cxx-interop: name: Cxx interop # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main + uses: apple/swift-nio/.github/workflows/cxx_interop.yml@matrix_file # TODO: replace with @main benchmarks: name: Benchmarks # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/benchmarks.yml@main + uses: apple/swift-nio/.github/workflows/benchmarks.yml@matrix_file # TODO: replace with @main with: benchmark_package_path: "Benchmarks" + construct-integration-test-matrix: + name: Construct integration test matrix + runs-on: ubuntu-latest + outputs: + integration-test-matrix: '${{ steps.generate-matrix.outputs.integration-test-matrix }}' + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - id: generate-matrix + run: echo "integration-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + env: + MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq" + MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh" + integration-tests: - name: Integration Tests + name: Integration tests + needs: construct-integration-test-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main with: name: "Integration tests" - matrix_linux_command: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq && ./scripts/integration_tests.sh" + matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}' diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1e5a3b734..b20fa6ff5 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -14,33 +14,50 @@ jobs: unit-tests: name: Unit tests # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/unit_tests.yml@main + uses: apple/swift-nio/.github/workflows/unit_tests.yml@matrix_file # TODO: replace with @main with: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" - linux_6_0_arguments_override: "--explicit-target-dependency-import-check error" - linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error" + linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + linux_nightly_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" benchmarks: name: Benchmarks # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/benchmarks.yml@main + uses: apple/swift-nio/.github/workflows/benchmarks.yml@matrix_file # TODO: replace with @main with: benchmark_package_path: "Benchmarks" cxx-interop: name: Cxx interop # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main + uses: apple/swift-nio/.github/workflows/cxx_interop.yml@matrix_file # TODO: replace with @main + + construct-integration-test-matrix: + name: Construct integration test matrix + runs-on: ubuntu-latest + outputs: + integration-test-matrix: '${{ steps.generate-matrix.outputs.integration-test-matrix }}' + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - id: generate-matrix + run: echo "integration-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + env: + MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq" + MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh" integration-tests: - name: Integration Tests + name: Integration tests + needs: construct-integration-test-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main with: name: "Integration tests" - matrix_linux_command: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq && ./scripts/integration_tests.sh" + matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}' vsock-tests: name: Vsock tests diff --git a/.github/workflows/swift_test_matrix.yml b/.github/workflows/swift_test_matrix.yml new file mode 100644 index 000000000..675bf0915 --- /dev/null +++ b/.github/workflows/swift_test_matrix.yml @@ -0,0 +1,93 @@ +name: Matrix + +on: + workflow_call: + inputs: + name: + type: string + description: "The name of the workflow used for the concurrency group." + required: true + matrix_path: + type: string + description: "The path of the test matrix definition." + default: "" + matrix_string: + type: string + description: "The test matrix definition." + default: "" + +# We will cancel previously triggered workflow runs +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.name }} + cancel-in-progress: true + +jobs: + generate-matrix: + name: Prepare matrices + runs-on: ubuntu-latest + outputs: + swift-matrix: ${{ steps.load-matrix.outputs.swift-matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Mark the workspace as safe + # https://github.com/actions/checkout/issues/766 + run: git config --global --add safe.directory ${GITHUB_WORKSPACE} + - id: load-matrix + run: | + if [ -n '${{ inputs.matrix_string }}' ]; then + printf "swift-matrix=%s" "$(echo '${{ inputs.matrix_string }}' | jq -c '.')" >> "$GITHUB_OUTPUT" + else + printf "swift-matrix=%s" "$(jq -c '.' ${{ inputs.matrix_path }})" >> "$GITHUB_OUTPUT" + fi + + execute-matrix: + name: ${{ matrix.swift.platform }} (${{ matrix.swift.name }}) + needs: generate-matrix + runs-on: ${{ matrix.swift.runner }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.generate-matrix.outputs.swift-matrix) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + submodules: true + - name: Pull Docker image + run: docker pull ${{ matrix.swift.image }} + - name: Run matrix job + if: ${{ matrix.swift.platform != 'Windows' }} + run: | + if [[ -n "${{ matrix.swift.setup_command }}" ]]; then + setup_command_expression="${{ matrix.swift.setup_command }} &&" + else + setup_command_expression="" + fi + workspace="/$(basename ${{ github.workspace }})" + docker run -v ${{ github.workspace }}:"$workspace" \ + -w "$workspace" \ + -e SWIFT_VERSION="${{ matrix.swift.swift_version }}" \ + -e setup_command_expression="$setup_command_expression" \ + -e workspace="$workspace" \ + ${{ matrix.swift.image }} \ + bash -c "swift --version && git config --global --add safe.directory \"$workspace\" && $setup_command_expression ${{ matrix.swift.command }} ${{ matrix.swift.command_arguments }}" + - name: Run matrix job (Windows) + if: ${{ matrix.swift.platform == 'Windows' }} + run: | + if (-not [string]::IsNullOrEmpty("${{ matrix.swift.setup_command }}")) { + $setup_command_expression = "${{ matrix.swift.setup_command }} &" + } else { + $setup_command_expression = "" + } + $workspace = "C:\" + (Split-Path ${{ github.workspace }} -Leaf) + docker run -v ${{ github.workspace }}:$($workspace) ` + -w $($workspace) ` + -e SWIFT_VERSION="${{ matrix.swift.swift_version }}" ` + -e setup_command_expression=%setup_command_expression% ` + ${{ matrix.swift.image }} ` + cmd /s /c "swift --version & powershell Invoke-Expression ""$($setup_command_expression) ${{ matrix.swift.command }} ${{ matrix.swift.command_arguments }}""" + env: + SWIFT_VERSION: ${{ matrix.swift.swift_version }} diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 8a70518bb..a0be8a107 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -70,27 +70,43 @@ on: default: "" jobs: + construct-matrix: + name: Construct unit test matrix + runs-on: ubuntu-latest + outputs: + unit-test-matrix: '${{ steps.generate-matrix.outputs.unit-test-matrix }}' + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - id: generate-matrix + run: echo "unit-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + env: + MATRIX_LINUX_COMMAND: "swift test" + MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} + MATRIX_LINUX_5_9_COMMAND_ARGUMENTS: ${{ inputs.linux_5_9_arguments_override }} + MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }} + MATRIX_LINUX_5_10_COMMAND_ARGUMENTS: ${{ inputs.linux_5_10_arguments_override }} + MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} + MATRIX_LINUX_6_0_COMMAND_ARGUMENTS: ${{ inputs.linux_6_0_arguments_override }} + MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_6_0_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_6_0_arguments_override }} + MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} + MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_main_arguments_override }} + MATRIX_WINDOWS_COMMAND: "swift test" + MATRIX_WINDOWS_6_0_ENABLED: ${{ inputs.windows_6_0_enabled }} + MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS: ${{ inputs.windows_6_0_arguments_override }} + MATRIX_WINDOWS_NIGHTLY_6_0_ENABLED: ${{ inputs.windows_nightly_6_0_enabled }} + MATRIX_WINDOWS_NIGHTLY_6_0_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_6_0_arguments_override }} + MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED: ${{ inputs.windows_nightly_main_enabled }} + MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_main_arguments_override }} + unit-tests: name: Unit tests + needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main with: name: "Unit tests" - matrix_linux_command: "swift test" - matrix_linux_5_9_enabled: ${{ inputs.linux_5_9_enabled }} - matrix_linux_5_9_command_override: "swift test ${{ inputs.linux_5_9_arguments_override }}" - matrix_linux_5_10_enabled: ${{ inputs.linux_5_10_enabled }} - matrix_linux_5_10_command_override: "swift test ${{ inputs.linux_5_10_arguments_override }}" - matrix_linux_6_0_enabled: ${{ inputs.linux_6_0_enabled }} - matrix_linux_6_0_command_override: "swift test ${{ inputs.linux_6_0_arguments_override }}" - matrix_linux_nightly_6_0_enabled: ${{ inputs.linux_nightly_6_0_enabled }} - matrix_linux_nightly_6_0_command_override: "swift test ${{ inputs.linux_nightly_6_0_arguments_override }}" - matrix_linux_nightly_main_enabled: ${{ inputs.linux_nightly_main_enabled }} - matrix_linux_nightly_main_command_override: "swift test ${{ inputs.linux_nightly_main_arguments_override }}" - matrix_windows_command: "swift test" - matrix_windows_6_0_enabled: ${{ inputs.windows_6_0_enabled }} - matrix_windows_6_0_command_override: "swift test ${{ inputs.windows_6_0_arguments_override }}" - matrix_windows_nightly_6_0_enabled: ${{ inputs.windows_nightly_6_0_enabled }} - matrix_windows_nightly_6_0_command_override: "swift test ${{ inputs.windows_nightly_6_0_arguments_override }}" - matrix_windows_nightly_main_enabled: ${{ inputs.windows_nightly_main_enabled }} - matrix_windows_nightly_main_command_override: "swift test ${{ inputs.windows_nightly_main_arguments_override }}" + matrix_string: '${{ needs.construct-matrix.outputs.unit-test-matrix }}' diff --git a/scripts/generate_matrix.sh b/scripts/generate_matrix.sh new file mode 100755 index 000000000..dbab4f69a --- /dev/null +++ b/scripts/generate_matrix.sh @@ -0,0 +1,153 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftNIO open source project +## +## Copyright (c) 2024 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 +## +##===----------------------------------------------------------------------===## + +# Parameters +linux_command="$MATRIX_LINUX_COMMAND" # required if any Linux pipeline is enabled +linux_setup_command="$MATRIX_LINUX_SETUP_COMMAND" +linux_5_9_enabled="${MATRIX_LINUX_5_9_ENABLED:=true}" +linux_5_9_command_arguments="$MATRIX_LINUX_5_9_COMMAND_ARGUMENTS" +linux_5_10_enabled="${MATRIX_LINUX_5_10_ENABLED:=true}" +linux_5_10_command_arguments="$MATRIX_LINUX_5_10_COMMAND_ARGUMENTS" +linux_6_0_enabled="${MATRIX_LINUX_6_0_ENABLED:=true}" +linux_6_0_command_arguments="$MATRIX_LINUX_6_0_COMMAND_ARGUMENTS" +linux_nightly_6_0_enabled="${MATRIX_LINUX_NIGHTLY_6_0_ENABLED:=true}" +linux_nightly_6_0_command_arguments="$MATRIX_LINUX_NIGHTLY_6_0_COMMAND_ARGUMENTS" +linux_nightly_main_enabled="${MATRIX_LINUX_NIGHTLY_MAIN_ENABLED:=true}" +linux_nightly_main_command_arguments="$MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS" + +windows_command="$MATRIX_WINDOWS_COMMAND" # required if any Windows pipeline is enabled +windows_setup_command="$MATRIX_WINDOWS_SETUP_COMMAND" +windows_6_0_enabled="${MATRIX_WINDOWS_6_0_ENABLED:=false}" +windows_6_0_command_arguments="$MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS" +windows_nightly_6_0_enabled="${MATRIX_WINDOWS_NIGHTLY_6_0_ENABLED:=false}" +windows_nightly_6_0_command_arguments="$MATRIX_WINDOWS_NIGHTLY_6_0_COMMAND_ARGUMENTS" +windows_nightly_main_enabled="${MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED:=false}" +windows_nightly_main_command_arguments="$MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS" + +# Defaults +linux_runner="ubuntu-latest" +linux_5_9_container_image="swift:5.9-jammy" +linux_5_10_container_image="swift:5.10-jammy" +linux_6_0_container_image="swift:6.0-jammy" +linux_nightly_6_0_container_image="swiftlang/swift:nightly-6.0-jammy" +linux_nightly_main_container_image="swiftlang/swift:nightly-main-jammy" + +windows_6_0_runner="windows-2022" +windows_6_0_container_image="swift:6.0-windowsservercore-ltsc2022" +windows_nightly_6_0_runner="windows-2019" +windows_nightly_6_0_container_image="swiftlang/swift:nightly-6.0-windowsservercore-1809" +windows_nightly_main_runner="windows-2019" +windows_nightly_main_container_image="swiftlang/swift:nightly-main-windowsservercore-1809" + +# Create matrix from inputs +matrix='{"swift": []}' + +## Linux +if [[ "$linux_5_9_enabled" == "true" || "$linux_5_10_enabled" == "true" || "$linux_6_0_enabled" == "true" || \ + "$linux_nightly_6_0_enabled" == "true" || "$linux_nightly_main_enabled" == "true" ]]; then + if [[ -z "$linux_command" ]]; then + echo "No linux command defined"; exit 1 + fi +fi + + +if [[ "$linux_5_9_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_5_9_command_arguments" \ + --arg container_image "$linux_5_9_container_image" \ + --arg runner "$linux_runner" \ + '.swift[.swift| length] |= . + { "name": "5.9", "image": $container_image, "swift_version": "5.9", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_5_10_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_5_10_command_arguments" \ + --arg container_image "$linux_5_10_container_image" \ + --arg runner "$linux_runner" \ + '.swift[.swift| length] |= . + { "name": "5.10", "image": $container_image, "swift_version": "5.10", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_6_0_command_arguments" \ + --arg container_image "$linux_6_0_container_image" \ + --arg runner "$linux_runner" \ + '.swift[.swift| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_nightly_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_nightly_6_0_command_arguments" \ + --arg container_image "$linux_nightly_6_0_container_image" \ + --arg runner "$linux_runner" \ + '.swift[.swift| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +if [[ "$linux_nightly_main_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$linux_setup_command" \ + --arg command "$linux_command" \ + --arg command_arguments "$linux_nightly_main_command_arguments" \ + --arg container_image "$linux_nightly_main_container_image" \ + --arg runner "$linux_runner" \ + '.swift[.swift| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') +fi + +## Windows +if [[ "$windows_6_0_enabled" == "true" || "$windows_nightly_6_0_enabled" == "true" || "$windows_nightly_main_enabled" == "true" ]]; then + if [[ -z "$windows_command" ]]; then + echo "No windows command defined"; exit 1 + fi +fi + +if [[ "$windows_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_6_0_command_arguments" \ + --arg container_image "$windows_6_0_container_image" \ + --arg runner "$windows_6_0_runner" \ + '.swift[.swift| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +if [[ "$windows_nightly_6_0_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_nightly_6_0_command_arguments" \ + --arg container_image "$windows_nightly_6_0_container_image" \ + --arg runner "$windows_nightly_6_0_runner" \ + '.swift[.swift| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +if [[ "$windows_nightly_main_enabled" == "true" ]]; then + matrix=$(echo "$matrix" | jq -c \ + --arg setup_command "$windows_setup_command" \ + --arg command "$windows_command" \ + --arg command_arguments "$windows_nightly_main_command_arguments" \ + --arg container_image "$windows_nightly_main_container_image" \ + --arg runner "$windows_nightly_main_runner" \ + '.swift[.swift| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') +fi + +echo "$matrix" | jq -c \ No newline at end of file From 692cf0a7b82ae1d669cf6ca1b8c7a1f83650a688 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Thu, 5 Dec 2024 08:47:27 +0000 Subject: [PATCH 13/93] Matrix workflows refer to main branch (#3016) Matrix workflows refer to main branch ### Motivation: Now that the workflow files are committed we can refer to them on the main branch ### Modifications: Replace @matrix_file with @main ### Result: More stable references in workflows. --- .github/workflows/benchmarks.yml | 2 +- .github/workflows/cxx_interop.yml | 2 +- .github/workflows/main.yml | 8 ++++---- .github/workflows/pull_request.yml | 8 ++++---- .github/workflows/unit_tests.yml | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index f039ba7c5..87c22373e 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -70,7 +70,7 @@ jobs: name: Benchmarks needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main with: name: "Benchmarks" matrix_string: '${{ needs.construct-matrix.outputs.benchmarks-matrix }}' diff --git a/.github/workflows/cxx_interop.yml b/.github/workflows/cxx_interop.yml index 545d59638..95e3b872e 100644 --- a/.github/workflows/cxx_interop.yml +++ b/.github/workflows/cxx_interop.yml @@ -63,7 +63,7 @@ jobs: name: Cxx interop needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main with: name: "Cxx interop" matrix_string: '${{ needs.construct-matrix.outputs.cxx-interop-matrix }}' diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b7ff32779..d57889114 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,7 @@ jobs: unit-tests: name: Unit tests # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/unit_tests.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/unit_tests.yml@main with: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" @@ -21,12 +21,12 @@ jobs: cxx-interop: name: Cxx interop # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/cxx_interop.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main benchmarks: name: Benchmarks # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/benchmarks.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/benchmarks.yml@main with: benchmark_package_path: "Benchmarks" @@ -50,7 +50,7 @@ jobs: name: Integration tests needs: construct-integration-test-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main with: name: "Integration tests" matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}' diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index b20fa6ff5..2ad5d6c36 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -14,7 +14,7 @@ jobs: unit-tests: name: Unit tests # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/unit_tests.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/unit_tests.yml@main with: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" @@ -25,14 +25,14 @@ jobs: benchmarks: name: Benchmarks # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/benchmarks.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/benchmarks.yml@main with: benchmark_package_path: "Benchmarks" cxx-interop: name: Cxx interop # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/cxx_interop.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main construct-integration-test-matrix: name: Construct integration test matrix @@ -54,7 +54,7 @@ jobs: name: Integration tests needs: construct-integration-test-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main with: name: "Integration tests" matrix_string: '${{ needs.construct-integration-test-matrix.outputs.integration-test-matrix }}' diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index a0be8a107..2b7a82cc6 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -106,7 +106,7 @@ jobs: name: Unit tests needs: construct-matrix # Workaround https://github.com/nektos/act/issues/1875 - uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@matrix_file # TODO: replace with @main + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main with: name: "Unit tests" matrix_string: '${{ needs.construct-matrix.outputs.unit-test-matrix }}' From 234ea1051fec6a2c8ac312e77d4313ee1e134033 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Thu, 5 Dec 2024 09:22:20 +0000 Subject: [PATCH 14/93] Re-usable workflows curl scripts (#3017) Re-usable workflows curl scripts ### Motivation: Other workflows re-use the NIO workflows they don't do a full git checkout so they don't have access to the scripts, we need to curl them. ### Modifications: curl the scripts ### Result: Downstream repositories should be able to re-use these workflows --- .github/workflows/benchmarks.yml | 2 +- .github/workflows/cxx_interop.yml | 2 +- .github/workflows/main.yml | 2 +- .github/workflows/pull_request.yml | 2 +- .github/workflows/unit_tests.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index 87c22373e..4fd97e040 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -56,7 +56,7 @@ jobs: with: persist-credentials: false - id: generate-matrix - run: echo "benchmarks-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + run: echo "benchmarks-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT" env: MATRIX_LINUX_COMMAND: "swift package --package-path ${{ inputs.benchmark_package_path }} ${{ inputs.swift_package_arguments }} benchmark baseline check --check-absolute-path ${{ inputs.benchmark_package_path }}/Thresholds/${SWIFT_VERSION}/" MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q libjemalloc-dev" diff --git a/.github/workflows/cxx_interop.yml b/.github/workflows/cxx_interop.yml index 95e3b872e..3e0dda32e 100644 --- a/.github/workflows/cxx_interop.yml +++ b/.github/workflows/cxx_interop.yml @@ -49,7 +49,7 @@ jobs: with: persist-credentials: false - id: generate-matrix - run: echo "cxx-interop-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + run: echo "cxx-interop-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT" env: MATRIX_LINUX_COMMAND: "curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/check-cxx-interop-compatibility.sh | bash" MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q curl jq" diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d57889114..71ced6aa1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -41,7 +41,7 @@ jobs: with: persist-credentials: false - id: generate-matrix - run: echo "integration-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + run: echo "integration-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT" env: MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq" MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh" diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 2ad5d6c36..0336d05c6 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -45,7 +45,7 @@ jobs: with: persist-credentials: false - id: generate-matrix - run: echo "integration-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + run: echo "integration-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT" env: MATRIX_LINUX_SETUP_COMMAND: "apt-get update -y -q && apt-get install -y -q lsof dnsutils netcat-openbsd net-tools curl jq" MATRIX_LINUX_COMMAND: "./scripts/integration_tests.sh" diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 2b7a82cc6..8d064fec5 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -81,7 +81,7 @@ jobs: with: persist-credentials: false - id: generate-matrix - run: echo "unit-test-matrix=$(./scripts/generate_matrix.sh)" >> "$GITHUB_OUTPUT" + run: echo "unit-test-matrix=$(curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/generate_matrix.sh | bash)" >> "$GITHUB_OUTPUT" env: MATRIX_LINUX_COMMAND: "swift test" MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} From 74f767454f648a43176f0161784557898dcb2d7a Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Thu, 5 Dec 2024 15:03:53 +0000 Subject: [PATCH 15/93] GHA: Separate matrix input handling (#3018) ### Motivation: The new test matrix workflow is quite verbose in the most common case, unit tests, outputting two workflow entries for handling and preparing the matrix inputs. In addition to this, it appeared that when running in `act` the matrix preparation step would run multiple times. ### Modifications: * Prioritize the current most common case, string inputs, and skip the matrix preparation step in this case reducing the number of workflows run. * Separate the path for loading the JSON matrix from a file into its own workflow. ### Result: * Less noise in the output * More reliable and efficient local matrix runs --- .github/workflows/swift_load_test_matrix.yml | 40 ++++++++++++++++++++ .github/workflows/swift_test_matrix.yml | 30 +-------------- 2 files changed, 42 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/swift_load_test_matrix.yml diff --git a/.github/workflows/swift_load_test_matrix.yml b/.github/workflows/swift_load_test_matrix.yml new file mode 100644 index 000000000..f0c34c2da --- /dev/null +++ b/.github/workflows/swift_load_test_matrix.yml @@ -0,0 +1,40 @@ +name: Matrix Load + +on: + workflow_call: + inputs: + name: + type: string + description: "The name of the workflow used for the concurrency group." + required: true + matrix_path: + type: string + description: "The path of the test matrix definition." + default: "" + +jobs: + load-matrix: + name: Prepare matrices + runs-on: ubuntu-latest + outputs: + swift-matrix: ${{ steps.load-matrix.outputs.swift-matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Mark the workspace as safe + # https://github.com/actions/checkout/issues/766 + run: git config --global --add safe.directory ${GITHUB_WORKSPACE} + - id: load-matrix + run: | + printf "swift-matrix=%s" "$(jq -c '.' ${{ inputs.matrix_path }})" >> "$GITHUB_OUTPUT" + + execute-matrix: + name: Execute matrix + needs: load-matrix + # Workaround https://github.com/nektos/act/issues/1875 + uses: apple/swift-nio/.github/workflows/swift_test_matrix.yml@main + with: + name: ${{ inputs.name }} + matrix_string: '${{ needs.load-matrix.outputs.swift-matrix }}' diff --git a/.github/workflows/swift_test_matrix.yml b/.github/workflows/swift_test_matrix.yml index 675bf0915..cec7fd70f 100644 --- a/.github/workflows/swift_test_matrix.yml +++ b/.github/workflows/swift_test_matrix.yml @@ -7,14 +7,10 @@ on: type: string description: "The name of the workflow used for the concurrency group." required: true - matrix_path: - type: string - description: "The path of the test matrix definition." - default: "" matrix_string: type: string description: "The test matrix definition." - default: "" + required: true # We will cancel previously triggered workflow runs concurrency: @@ -22,34 +18,12 @@ concurrency: cancel-in-progress: true jobs: - generate-matrix: - name: Prepare matrices - runs-on: ubuntu-latest - outputs: - swift-matrix: ${{ steps.load-matrix.outputs.swift-matrix }} - steps: - - name: Checkout repository - uses: actions/checkout@v4 - with: - persist-credentials: false - - name: Mark the workspace as safe - # https://github.com/actions/checkout/issues/766 - run: git config --global --add safe.directory ${GITHUB_WORKSPACE} - - id: load-matrix - run: | - if [ -n '${{ inputs.matrix_string }}' ]; then - printf "swift-matrix=%s" "$(echo '${{ inputs.matrix_string }}' | jq -c '.')" >> "$GITHUB_OUTPUT" - else - printf "swift-matrix=%s" "$(jq -c '.' ${{ inputs.matrix_path }})" >> "$GITHUB_OUTPUT" - fi - execute-matrix: name: ${{ matrix.swift.platform }} (${{ matrix.swift.name }}) - needs: generate-matrix runs-on: ${{ matrix.swift.runner }} strategy: fail-fast: false - matrix: ${{ fromJson(needs.generate-matrix.outputs.swift-matrix) }} + matrix: ${{ fromJson(inputs.matrix_string) }} steps: - name: Checkout repository uses: actions/checkout@v4 From c3a8d18219e32c1eb218c96243eefa130c05cf9f Mon Sep 17 00:00:00 2001 From: Si Beaumont Date: Fri, 6 Dec 2024 17:08:56 +0000 Subject: [PATCH 16/93] Add EventLoop.now API for getting the current time (#3015) ### Motivation Code that tries to work with `NIODeadline` can be challenging to test using `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` because they have their own, fake clock. These testing event loops do implement `scheduleTask(in:_)` to submit work in the future, relative to the event loop clock, but there is no way to get the event loop's current notion of "now", as a `NIODeadline`, and users sometimes find that `NIODeadline.now`, which returns the time of the real clock, to be surprising. ### Modifications Add `EventLoop.now` to get the current time of the event loop clock. ### Result New APIs to support writing code that's easier to test. --- Sources/NIOCore/EventLoop.swift | 8 +++++ .../NIOEmbedded/AsyncTestingEventLoop.swift | 4 ++- Sources/NIOEmbedded/Embedded.swift | 3 +- Sources/NIOPosix/SelectableEventLoop.swift | 6 ++++ .../AsyncTestingEventLoopTests.swift | 10 ++++++ .../EmbeddedEventLoopTest.swift | 33 ++++++++++++++++++- Tests/NIOPosixTests/EventLoopTest.swift | 8 +++++ 7 files changed, 69 insertions(+), 3 deletions(-) diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 376f06d8f..021725af9 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -269,6 +269,9 @@ public protocol EventLoop: EventLoopGroup { @preconcurrency func submit(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture + /// The current time of the event loop. + var now: NIODeadline { get } + /// Schedule a `task` that is executed by this `EventLoop` at the given time. /// /// - Parameters: @@ -394,6 +397,11 @@ public protocol EventLoop: EventLoopGroup { func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) } +extension EventLoop { + /// Default implementation of `now`: Returns `NIODeadline.now()`. + public var now: NIODeadline { .now() } +} + extension EventLoop { /// Default implementation of `makeSucceededVoidFuture`: Return a fresh future (which will allocate). public func makeSucceededVoidFuture() -> EventLoopFuture { diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 14e5242df..7997d38e3 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -63,7 +63,9 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// The current "time" for this event loop. This is an amount in nanoseconds. /// As we need to access this from any thread, we store this as an atomic. private let _now = ManagedAtomic(0) - internal var now: NIODeadline { + + /// The current "time" for this event loop. This is an amount in nanoseconds. + public var now: NIODeadline { NIODeadline.uptimeNanoseconds(self._now.load(ordering: .relaxed)) } diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index c509a8ffa..70148c416 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -94,8 +94,9 @@ extension EmbeddedScheduledTask: Comparable { /// responsible for ensuring they never call into the `EmbeddedEventLoop` in an /// unsynchronized fashion. public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { + private var _now: NIODeadline = .uptimeNanoseconds(0) /// The current "time" for this event loop. This is an amount in nanoseconds. - internal var _now: NIODeadline = .uptimeNanoseconds(0) + public var now: NIODeadline { _now } private enum State { case open, closing, closed } private var state: State = .open diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 89fc4737f..9449d6297 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -298,6 +298,12 @@ internal final class SelectableEventLoop: EventLoop { thread.isCurrent } + /// - see: `EventLoop.now` + @usableFromInline + internal var now: NIODeadline { + .now() + } + /// - see: `EventLoop.scheduleTask(deadline:_:)` @inlinable internal func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index 08cee06cb..66c40c741 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -619,4 +619,14 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { await eventLoop.advanceTime(by: .seconds(1)) XCTAssertEqual(counter.load(ordering: .relaxed), 3) } + + func testCurrentTime() async { + let eventLoop = NIOAsyncTestingEventLoop() + + await eventLoop.advanceTime(to: .uptimeNanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(42)) + + await eventLoop.advanceTime(by: .nanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(84)) + } } diff --git a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift index a23665ec2..b1690f7f8 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift @@ -396,7 +396,7 @@ public final class EmbeddedEventLoopTest: XCTestCase { try eventLoop.syncShutdownGracefully() childTasks.append( scheduleRecursiveTask( - at: eventLoop._now + childTaskStartDelay, + at: eventLoop.now + childTaskStartDelay, andChildTaskAfter: childTaskStartDelay ) ) @@ -497,4 +497,35 @@ public final class EmbeddedEventLoopTest: XCTestCase { eventLoop.advanceTime(by: .seconds(1)) XCTAssertEqual(counter, 3) } + + func testCurrentTime() { + let eventLoop = EmbeddedEventLoop() + + eventLoop.advanceTime(to: .uptimeNanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(42)) + + eventLoop.advanceTime(by: .nanoseconds(42)) + XCTAssertEqual(eventLoop.now, .uptimeNanoseconds(84)) + } + + func testScheduleRepeatedTask() { + let eventLoop = EmbeddedEventLoop() + + var counter = 0 + eventLoop.scheduleRepeatedTask(initialDelay: .seconds(1), delay: .seconds(1)) { repeatedTask in + guard counter < 10 else { + repeatedTask.cancel() + return + } + counter += 1 + } + + XCTAssertEqual(counter, 0) + + eventLoop.advanceTime(by: .seconds(1)) + XCTAssertEqual(counter, 1) + + eventLoop.advanceTime(by: .seconds(9)) + XCTAssertEqual(counter, 10) + } } diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index f14ba2dc4..947d916be 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1962,6 +1962,10 @@ private class EventLoopWithPreSucceededFuture: EventLoop { preconditionFailure("not implemented") } + var now: NIODeadline { + preconditionFailure("not implemented") + } + @discardableResult func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { preconditionFailure("not implemented") @@ -2013,6 +2017,10 @@ private class EventLoopWithoutPreSucceededFuture: EventLoop { preconditionFailure("not implemented") } + var now: NIODeadline { + preconditionFailure("not implemented") + } + @discardableResult func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { preconditionFailure("not implemented") From 29c65edb970945a8eea0ef1f654a97ba4e907495 Mon Sep 17 00:00:00 2001 From: Michael Gecht Date: Tue, 10 Dec 2024 17:43:29 +0000 Subject: [PATCH 17/93] Add parallel removal of items (#3008) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce parallel removal of items, instead of only doing a sequential removal (and discovery) one-by-one ### Motivation: #2933 mentioned this function call appears to be slow. If we attempt to delete a directory with lots of subdirectories, we end up discovering each subdirectory one by one on a single thread. ### Modifications: This PR refactors the logic to remove items. Instead of sequentially discovering and deleting items one by one, we traverse all directories up to a maximum concurrency, and issue file deletions in parallel within each directory. ### Result: The new concurrent implementation was measured to be ~1.4x faster than `FileManager`, ~1.5x faster than `rm -rf` and ~3x faster than the current sequential implementation on `main`. This new concurrent implementation does use the most CPU out of all the other approaches. Results are broken down into two sections. We delete a copy of the `swift-nio` repository, where the `.build/` folder has grown to a large size, providing lots of additional files and subdirectories. We produce a single CLI using `--configration=release` that can switch between using the `.sequential` mode (what is currently available on the `main` branch), `.parallel` (the new concurrent implementation in this PR) and `filemanager` (uses `Foundation.FileManager` as a comparison). Resolves https://github.com/apple/swift-nio/issues/2933 #### Normal size **Description:** The `swift-nio` library as found when building the CLI used for benchmarking. **Benchmark run with:** 3579 directories, 11657 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 2.712 s ± 0.053 s [User: 0.526 s, System: 8.632 s] Range (min … max): 2.625 s … 2.781 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 896.7 ms ± 25.6 ms [User: 302.9 ms, System: 5313.5 ms] Range (min … max): 853.2 ms … 942.1 ms 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 1.337 s ± 0.076 s [User: 0.022 s, System: 1.253 s] Range (min … max): 1.252 s … 1.508 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 1.483 s ± 0.037 s [User: 0.015 s, System: 1.416 s] Range (min … max): 1.413 s … 1.541 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.49 ± 0.10 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.65 ± 0.06 times faster than rm -rf /tmp/swift-nio 3.02 ± 0.10 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` #### Large size **Description:** The `swift-nio` library as found after re-running the `.github` workflow many times locally. I'm unable to reproduce this directory size, but have benchmarked against it. **Benchmark run with:** 15260 directories, 46842 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 12.082 s ± 0.354 s [User: 2.180 s, System: 41.547 s] Range (min … max): 11.717 s … 12.923 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 4.770 s ± 0.102 s [User: 1.357 s, System: 25.785 s] Range (min … max): 4.570 s … 4.883 s 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 6.503 s ± 0.115 s [User: 0.081 s, System: 5.427 s] Range (min … max): 6.262 s … 6.687 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 7.056 s ± 0.246 s [User: 0.064 s, System: 6.119 s] Range (min … max): 6.435 s … 7.233 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.36 ± 0.04 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.48 ± 0.06 times faster than rm -rf /tmp/swift-nio 2.53 ± 0.09 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` --------- Co-authored-by: George Barnett --- NOTICE.txt | 9 + Sources/NIOFileSystem/CopyStrategy.swift | 121 ------------ Sources/NIOFileSystem/FileSystem.swift | 88 ++++++--- .../NIOFileSystem/FileSystemProtocol.swift | 76 +++++++- Sources/NIOFileSystem/IOStrategy.swift | 184 ++++++++++++++++++ .../Concurrency Primitives/TokenBucket.swift | 88 +++++++++ .../Internal/ParallelRemoval.swift | 72 +++++++ .../FileSystemTests.swift | 49 +++-- 8 files changed, 513 insertions(+), 174 deletions(-) delete mode 100644 Sources/NIOFileSystem/CopyStrategy.swift create mode 100644 Sources/NIOFileSystem/IOStrategy.swift create mode 100644 Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift create mode 100644 Sources/NIOFileSystem/Internal/ParallelRemoval.swift diff --git a/NOTICE.txt b/NOTICE.txt index cbcc2e69b..d79250ea5 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -95,3 +95,12 @@ This product contains a derivation of the mocking infrastructure from Swift Syst * https://www.apache.org/licenses/LICENSE-2.0 * HOMEPAGE: * https://github.com/apple/swift-system + +--- + +This product contains a derivation of "TokenBucket.swift" from Swift Package Manager. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/swiftlang/swift-package-manager diff --git a/Sources/NIOFileSystem/CopyStrategy.swift b/Sources/NIOFileSystem/CopyStrategy.swift deleted file mode 100644 index ae8b4770e..000000000 --- a/Sources/NIOFileSystem/CopyStrategy.swift +++ /dev/null @@ -1,121 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2024 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 -// -//===----------------------------------------------------------------------===// - -/// How to perform copies. Currently only relevant to directory level copies when using -/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other -/// overloads that use the default behaviour. -public struct CopyStrategy: Hashable, Sendable { - // Avoid exposing to prevent breaking changes - internal enum Wrapped: Hashable, Sendable { - // platformDefault is reified into one of the concrete options below: - - case sequential - // Constraints on this value are enforced only on creation of `CopyStrategy`. The early - // error check is desirable over validating on downstream use. - case parallel(_ maxDescriptors: Int) - } - - internal let wrapped: Wrapped - private init(_ wrapped: Wrapped) { - self.wrapped = wrapped - } - - // These selections are relatively arbitrary but the rationale is as follows: - // - // - Never exceed the default OS limits even if 4 such operations were happening at once. - // - Sufficient to enable significant speed up from parallelism - // - Not wasting effort by pushing contention to the underlying storage device. Further we - // assume an SSD or similar underlying storage tech. Users on spinning rust need to account - // for that themselves anyway. - // - // That said, empirical testing for this has not been performed, suggestions welcome. - // - // Note: for now we model the directory scan as needing two handles because, during the creation - // of the destination directory we hold the handle for a while copying attributes - // a much more complex internal state machine could allow doing two of these if desired - // This may not result in a faster copy though so things are left simple - internal static func determinePlatformDefault() -> Wrapped { - #if os(macOS) || os(Linux) || os(Windows) - // 4 concurrent file copies/directory scans. Avoiding storage system contention is of utmost - // importance. - // - // Testing was performed on an SSD, while copying objects (a dense directory of small files - // and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed - // improvements in elapsed time for (expected) increases in CPU time up to parallel(8). - // Beyond this, the increases in CPU led to only moderate gains. - // - // Anyone tuning this is encouraged to cover worst case scenarios. - return .parallel(8) - #elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android) - // Reduced maximum descriptors in embedded world. This is chosen based on biasing towards - // safety, not empirical testing. - return .parallel(4) - #else - // Safety first. If we do not know what system we run on, we keep it simple. - return .sequential - #endif - } -} - -extension CopyStrategy { - // A copy fundamentally can't work without two descriptors unless you copy - // everything into memory which is infeasible/inefficient for large copies. - private static let minDescriptorsAllowed = 2 - - /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit - /// the maximum file descriptors usage based on reasonable defaults. - /// - /// Current assumptions (which are subject to change): - /// - Only one copy operation would be performed at once - /// - The copy operation is not intended to be the primary activity on the device - public static let platformDefault: Self = Self(Self.determinePlatformDefault()) - - /// The copy is done asynchronously, but only one operation will occur at a time. This is the - /// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time. - public static let sequential: Self = Self(.sequential) - - /// Allow multiple IO operations to run concurrently, including file copies/directory creation and scanning - /// - /// - Parameter maxDescriptors: a conservative limit on the number of concurrently open - /// file descriptors involved in the copy. This number must be >= 2 though, if you are using a value that low - /// you should use ``sequential`` - /// - /// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` - /// is less than 2. - /// - public static func parallel(maxDescriptors: Int) throws -> Self { - guard maxDescriptors >= Self.minDescriptorsAllowed else { - // 2 is not quite the same as sequential, you could have two concurrent directory listings for example - // less than 2 and you can't actually do a _copy_ though so it's non-sensical. - throw FileSystemError( - code: .invalidArgument, - message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal", - cause: nil, - location: .here() - ) - } - return .init(.parallel(maxDescriptors)) - } -} - -extension CopyStrategy: CustomStringConvertible { - public var description: String { - switch self.wrapped { - case .sequential: - return "sequential" - case let .parallel(maxDescriptors): - return "parallel with max \(maxDescriptors) descriptors" - } - } -} diff --git a/Sources/NIOFileSystem/FileSystem.swift b/Sources/NIOFileSystem/FileSystem.swift index 33bf8c605..834994925 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -366,6 +366,8 @@ public struct FileSystem: Sendable, FileSystemProtocol { } } + /// See ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` + /// /// Deletes the file or directory (and its contents) at `path`. /// /// Only regular files, symbolic links and directories may be removed. If the file at `path` is @@ -387,11 +389,14 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// - Parameters: /// - path: The path to delete. + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. /// - removeItemRecursively: Whether or not to remove items recursively. /// - Returns: The number of deleted items which may be zero if `path` did not exist. @discardableResult public func removeItem( at path: FilePath, + strategy removalStrategy: RemovalStrategy, recursively removeItemRecursively: Bool ) async throws -> Int { // Try to remove the item: we might just get lucky. @@ -421,41 +426,62 @@ public struct FileSystem: Sendable, FileSystemProtocol { ) } - var (subdirectories, filesRemoved) = try await self.withDirectoryHandle( - atPath: path - ) { directory in - var subdirectories = [FilePath]() - var filesRemoved = 0 - - for try await batch in directory.listContents().batched() { - for entry in batch { - switch entry.type { - case .directory: - subdirectories.append(entry.path) - - default: - filesRemoved += try await self.removeOneItem(at: entry.path) - } - } - } - - return (subdirectories, filesRemoved) + switch removalStrategy.wrapped { + case .sequential: + return try await self.removeItemSequentially(at: path) + case let .parallel(maxDescriptors): + return try await self.removeConcurrently(at: path, maxDescriptors) } - for subdirectory in subdirectories { - filesRemoved += try await self.removeItem(at: subdirectory) - } - - // The directory should be empty now. Remove ourself. - filesRemoved += try await self.removeOneItem(at: path) - - return filesRemoved - case let .failure(errno): throw FileSystemError.remove(errno: errno, path: path, location: .here()) } } + @discardableResult + private func removeItemSequentially( + at path: FilePath + ) async throws -> Int { + var (subdirectories, filesRemoved) = try await self.withDirectoryHandle( + atPath: path + ) { directory in + var subdirectories = [FilePath]() + var filesRemoved = 0 + + for try await batch in directory.listContents().batched() { + for entry in batch { + switch entry.type { + case .directory: + subdirectories.append(entry.path) + + default: + filesRemoved += try await self.removeOneItem(at: entry.path) + } + } + } + + return (subdirectories, filesRemoved) + } + + for subdirectory in subdirectories { + filesRemoved += try await self.removeItemSequentially(at: subdirectory) + } + + // The directory should be empty now. Remove ourself. + filesRemoved += try await self.removeOneItem(at: path) + + return filesRemoved + + } + + private func removeConcurrently( + at path: FilePath, + _ maxDescriptors: Int + ) async throws -> Int { + let bucket: TokenBucket = .init(tokens: maxDescriptors) + return try await self.discoverAndRemoveItemsInTree(at: path, bucket) + } + /// Moves the named file or directory to a new location. /// /// Only regular files, symbolic links and directories may be moved. If the item to be is a @@ -490,7 +516,7 @@ public struct FileSystem: Sendable, FileSystemProtocol { case .differentLogicalDevices: // Fall back to copy and remove. try await self.copyItem(at: sourcePath, to: destinationPath) - try await self.removeItem(at: sourcePath) + try await self.removeItem(at: sourcePath, strategy: .platformDefault) } } @@ -518,9 +544,9 @@ public struct FileSystem: Sendable, FileSystemProtocol { withItemAt existingPath: FilePath ) async throws { do { - try await self.removeItem(at: destinationPath) + try await self.removeItem(at: destinationPath, strategy: .platformDefault) try await self.moveItem(at: existingPath, to: destinationPath) - try await self.removeItem(at: existingPath) + try await self.removeItem(at: existingPath, strategy: .platformDefault) } catch let error as FileSystemError { throw FileSystemError( message: "Can't replace '\(destinationPath)' with '\(existingPath)'.", diff --git a/Sources/NIOFileSystem/FileSystemProtocol.swift b/Sources/NIOFileSystem/FileSystemProtocol.swift index b5bf70143..934220762 100644 --- a/Sources/NIOFileSystem/FileSystemProtocol.swift +++ b/Sources/NIOFileSystem/FileSystemProtocol.swift @@ -249,19 +249,23 @@ public protocol FileSystemProtocol: Sendable { /// at the given path then this function returns zero. /// /// If the item at the `path` is a directory and `removeItemRecursively` is `true` then the - /// contents of all of its subdirectories will be removed recursively before the directory - /// at `path`. Symbolic links are removed (but their targets are not deleted). + /// contents of all of its subdirectories will be removed recursively before the directory at + /// `path`. Symbolic links are removed (but their targets are not deleted). /// /// - Parameters: /// - path: The path to delete. - /// - removeItemRecursively: If the item being removed is a directory, remove it by - /// recursively removing its children. Setting this to `true` is synonymous with - /// calling `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. Ignored if /// the item being removed isn't a directory. + /// - removeItemRecursively: If the item being removed is a directory, remove it by + /// recursively removing its children. Setting this to `true` is synonymous with calling + /// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item + /// being removed isn't a directory. /// - Returns: The number of deleted items which may be zero if `path` did not exist. @discardableResult func removeItem( at path: FilePath, + strategy removalStrategy: RemovalStrategy, recursively removeItemRecursively: Bool ) async throws -> Int @@ -588,9 +592,12 @@ extension FileSystemProtocol { /// The item to be removed must be a regular file, symbolic link or directory. If no file exists /// at the given path then this function returns zero. /// - /// If the item at the `path` is a directory then the contents of all of its subdirectories - /// will be removed recursively before the directory at `path`. Symbolic links are removed (but - /// their targets are not deleted). + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// The strategy for deletion will be determined automatically depending on the discovered + /// platform. /// /// - Parameters: /// - path: The path to delete. @@ -599,7 +606,56 @@ extension FileSystemProtocol { public func removeItem( at path: FilePath ) async throws -> Int { - try await self.removeItem(at: path, recursively: true) + try await self.removeItem(at: path, strategy: .platformDefault, recursively: true) + } + + /// 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 + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// The strategy for deletion will be determined automatically depending on the discovered + /// platform. + /// + /// - Parameters: + /// - path: The path to delete. + /// - removeItemRecursively: If the item being removed is a directory, remove it by + /// recursively removing its children. Setting this to `true` is synonymous with calling + /// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item + /// being removed isn't a directory. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath, + recursively removeItemRecursively: Bool + ) async throws -> Int { + try await self.removeItem(at: path, strategy: .platformDefault, recursively: removeItemRecursively) + } + + /// 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 + /// at the given path then this function returns zero. + /// + /// If the item at the `path` is a directory then the contents of all of its subdirectories will + /// be removed recursively before the directory at `path`. Symbolic links are removed (but their + /// targets are not deleted). + /// + /// - Parameters: + /// - path: The path to delete. + /// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a + /// concurrent scan of the tree at `path` and delete files when they are found. + /// - Returns: The number of deleted items which may be zero if `path` did not exist. + @discardableResult + public func removeItem( + at path: FilePath, + strategy removalStrategy: RemovalStrategy + ) async throws -> Int { + try await self.removeItem(at: path, strategy: removalStrategy, recursively: true) } /// Create a directory at the given path. @@ -659,7 +715,7 @@ extension FileSystemProtocol { try await execute(handle, directory) } } tearDown: { _ in - try await self.removeItem(at: directory, recursively: true) + try await self.removeItem(at: directory, strategy: .platformDefault, recursively: true) } } } diff --git a/Sources/NIOFileSystem/IOStrategy.swift b/Sources/NIOFileSystem/IOStrategy.swift new file mode 100644 index 000000000..fcb7fb432 --- /dev/null +++ b/Sources/NIOFileSystem/IOStrategy.swift @@ -0,0 +1,184 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +/// How many file descriptors to open when performing I/O operations. +enum IOStrategy: Hashable, Sendable { + // platformDefault is reified into one of the concrete options below: + case sequential + case parallel(_ maxDescriptors: Int) + + // These selections are relatively arbitrary but the rationale is as follows: + // + // - Never exceed the default OS limits even if 4 such operations were happening at once. + // - Sufficient to enable significant speed up from parallelism + // - Not wasting effort by pushing contention to the underlying storage device. Further we + // assume an SSD or similar underlying storage tech. Users on spinning rust need to account + // for that themselves anyway. + // + // That said, empirical testing for this has not been performed, suggestions welcome. + // + // Note: The directory scan is modelled after a copy strategy needing two handles: during the + // creation of the destination directory we hold the handle while copying attributes. A much + // more complex internal state machine could allow doing two of these if desired. This may not + // result in a faster copy though so things are left simple. + internal static func determinePlatformDefault() -> Self { + #if os(macOS) || os(Linux) || os(Windows) + // Eight file descriptors allow for four concurrent file copies/directory scans. Avoiding + // storage system contention is of utmost importance. + // + // Testing was performed on an SSD, while copying objects (a dense directory of small files + // and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed + // improvements in elapsed time for (expected) increases in CPU time up to parallel(8). + // Beyond this, the increases in CPU led to only moderate gains. + // + // Anyone tuning this is encouraged to cover worst case scenarios. + return .parallel(8) + #elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android) + // Reduced maximum descriptors in embedded world. This is chosen based on biasing towards + // safety, not empirical testing. + return .parallel(4) + #else + // Safety first. If we do not know what system we run on, we keep it simple. + return .sequential + #endif + } +} + +/// How to perform copies. Currently only relevant to directory level copies when using +/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other +/// overloads that use the default behaviour. +public struct CopyStrategy: Hashable, Sendable { + internal let wrapped: IOStrategy + private init(_ strategy: IOStrategy) { + switch strategy { + case .sequential: + self.wrapped = .sequential + case let .parallel(maxDescriptors): + self.wrapped = .parallel(maxDescriptors) + } + } + + // A copy fundamentally can't work without two descriptors unless you copy everything into + // memory which is infeasible/inefficient for large copies. + private static let minDescriptorsAllowed = 2 + + /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit + /// the maximum file descriptors usage based on reasonable defaults. + /// + /// Current assumptions (which are subject to change): + /// - Only one copy operation would be performed at once + /// - The copy operation is not intended to be the primary activity on the device + public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault()) + + /// The copy is done asynchronously, but only one operation will occur at a time. This is the + /// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time. + public static let sequential: Self = Self(.sequential) + + /// Allow multiple I/O operations to run concurrently, including file copies/directory creation + /// and scanning. + /// + /// - Parameter maxDescriptors: a conservative limit on the number of concurrently open file + /// descriptors involved in the copy. This number must be >= 2 though, if you are using a + /// value that low you should use ``sequential`` + /// + /// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` is less + /// than 2. + /// + public static func parallel(maxDescriptors: Int) throws -> Self { + guard maxDescriptors >= Self.minDescriptorsAllowed else { + // 2 is not quite the same as sequential, you could have two concurrent directory + // listings for example less than 2 and you can't actually do a _copy_ though so it's + // non-sensical. + throw FileSystemError( + code: .invalidArgument, + message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal", + cause: nil, + location: .here() + ) + } + return .init(.parallel(maxDescriptors)) + } +} + +extension CopyStrategy: CustomStringConvertible { + public var description: String { + switch self.wrapped { + case .sequential: + return "sequential" + case let .parallel(maxDescriptors): + return "parallel with max \(maxDescriptors) descriptors" + } + } +} + +/// How to perform file deletions. Currently only relevant to directory level deletions when using +/// ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` or other overloads that use the +/// default behaviour. +public struct RemovalStrategy: Hashable, Sendable { + internal let wrapped: IOStrategy + private init(_ strategy: IOStrategy) { + switch strategy { + case .sequential: + self.wrapped = .sequential + case let .parallel(maxDescriptors): + self.wrapped = .parallel(maxDescriptors) + } + } + + // A deletion requires no file descriptors. We only consume a file descriptor while scanning the + // contents of a directory, so the minimum is 1. + private static let minRequiredDescriptors = 1 + + /// Operate in whatever manner is deemed a reasonable default for the platform. This will limit + /// the maximum file descriptors usage based on reasonable defaults. + /// + /// Current assumptions (which are subject to change): + /// - Only one delete operation would be performed at once + /// - The delete operation is not intended to be the primary activity on the device + public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault()) + + /// Traversal of directories and removal of files will be done sequentially without any + /// parallelization. + public static let sequential: Self = Self(.sequential) + + /// Allow for one or more directory scans to run at the same time. Removal of files will happen + /// on asynchronous tasks in parallel. + /// + /// Setting `maxDescriptors` to 1, will limit the speed of directory discovery. Deletion of + /// files within that directory will run in parallel, but discovery of subdirectories will be + /// limited to one at a time. + public static func parallel(maxDescriptors: Int) throws -> Self { + guard maxDescriptors >= Self.minRequiredDescriptors else { + throw FileSystemError( + code: .invalidArgument, + message: + "Can't do a remove operation without at least one file descriptor '\(maxDescriptors)' is illegal", + cause: nil, + location: .here() + ) + } + return .init(.parallel(maxDescriptors)) + } +} + +extension RemovalStrategy: CustomStringConvertible { + public var description: String { + switch self.wrapped { + case .sequential: + return "sequential" + case let .parallel(maxDescriptors): + return "parallel with max \(maxDescriptors) descriptors" + } + } +} diff --git a/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift b/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift new file mode 100644 index 000000000..3a998f5b2 --- /dev/null +++ b/Sources/NIOFileSystem/Internal/Concurrency Primitives/TokenBucket.swift @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import DequeModule +import NIOConcurrencyHelpers + +/// Type modeled after a "token bucket" pattern, which is similar to a semaphore, but is built with +/// Swift Concurrency primitives. +/// +/// This is an adaptation of the TokenBucket found in Swift Package Manager. +/// Instead of using an ``actor``, we define a class and limit access through +/// ``NIOLock``. +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +final class TokenBucket: @unchecked Sendable { + private var tokens: Int + private var waiters: Deque> + private let lock: NIOLock + + init(tokens: Int) { + precondition(tokens >= 1, "Need at least one token!") + self.tokens = tokens + self.waiters = Deque() + self.lock = NIOLock() + } + + /// Executes an `async` closure immediately when a token is available. + /// Only the same number of closures will be executed concurrently as the number + /// of `tokens` passed to ``TokenBucket/init(tokens:)``, all subsequent + /// invocations of `withToken` will suspend until a "free" token is available. + /// - Parameter body: The closure to invoke when a token is available. + /// - Returns: Resulting value returned by `body`. + func withToken( + _ body: @Sendable () async throws -> ReturnType + ) async rethrows -> ReturnType { + await self.getToken() + defer { self.returnToken() } + return try await body() + } + + private func getToken() async { + self.lock.lock() + if self.tokens > 0 { + self.tokens -= 1 + self.lock.unlock() + return + } + + await withCheckedContinuation { + self.waiters.append($0) + self.lock.unlock() + } + } + + private func returnToken() { + if let waiter = self.lock.withLock({ () -> CheckedContinuation? in + if let nextWaiter = self.waiters.popFirst() { + return nextWaiter + } + + self.tokens += 1 + return nil + }) { + waiter.resume() + } + } +} diff --git a/Sources/NIOFileSystem/Internal/ParallelRemoval.swift b/Sources/NIOFileSystem/Internal/ParallelRemoval.swift new file mode 100644 index 000000000..cd8b6702d --- /dev/null +++ b/Sources/NIOFileSystem/Internal/ParallelRemoval.swift @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileSystem { + /// Recursively walk all objects found in `path`. Call ourselves recursively + /// on each directory that we find, as soon as the file descriptor for + /// `path` has been closed; also delete all files that we come across. + func discoverAndRemoveItemsInTree( + at path: FilePath, + _ bucket: TokenBucket + ) async throws -> Int { + // Discover current directory and find all files/directories. Free up + // the handle as fast as possible. + let (directoriesToRecurseInto, itemsToDelete) = try await bucket.withToken { + try await self.withDirectoryHandle(atPath: path) { directory in + var subdirectories: [FilePath] = [] + var itemsInDirectory: [FilePath] = [] + + for try await batch in directory.listContents().batched() { + for entry in batch { + switch entry.type { + case .directory: + subdirectories.append(entry.path) + default: + itemsInDirectory.append(entry.path) + } + } + } + + return (subdirectories, itemsInDirectory) + } + } + + return try await withThrowingTaskGroup(of: Int.self) { group in + // Delete all items we found in the current directory. + for item in itemsToDelete { + group.addTask { + try await self.removeOneItem(at: item) + } + } + + // Recurse into all newly found subdirectories. + for directory in directoriesToRecurseInto { + group.addTask { + try await self.discoverAndRemoveItemsInTree(at: directory, bucket) + } + } + + // Await task groups to finish and sum all items deleted so far. + var numberOfDeletedItems = try await group.reduce(0, +) + + // Remove top level directory. + numberOfDeletedItems += try await self.removeOneItem(at: path) + + return numberOfDeletedItems + } + } +} diff --git a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index 5de584660..e262147fa 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -222,7 +222,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if path.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: path) + try await fileSystem.removeItem(at: path, strategy: .platformDefault) } } @@ -351,7 +351,7 @@ final class FileSystemTests: XCTestCase { // Avoid dirtying the current working directory. if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault) } } @@ -399,7 +399,7 @@ final class FileSystemTests: XCTestCase { if directoryPath.isRelative { self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: directoryPath, recursively: true) + try await fileSystem.removeItem(at: directoryPath, strategy: .platformDefault, recursively: true) } } @@ -586,8 +586,8 @@ final class FileSystemTests: XCTestCase { let sourcePath = try await self.fs.temporaryFilePath() let destPath = try await self.fs.temporaryFilePath() self.addTeardownBlock { - _ = try? await self.fs.removeItem(at: sourcePath) - _ = try? await self.fs.removeItem(at: destPath) + _ = try? await self.fs.removeItem(at: sourcePath, strategy: .platformDefault) + _ = try? await self.fs.removeItem(at: destPath, strategy: .platformDefault) } let sourceInfo = try await self.fs.withFileHandle( @@ -991,7 +991,7 @@ final class FileSystemTests: XCTestCase { let infoAfterCreation = try await self.fs.info(forFileAt: path) XCTAssertNotNil(infoAfterCreation) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 1) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1002,11 +1002,11 @@ final class FileSystemTests: XCTestCase { let path = try await self.fs.temporaryFilePath() let info = try await self.fs.info(forFileAt: path) XCTAssertNil(info) - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .platformDefault) XCTAssertEqual(removed, 0) } - func testRemoveDirectory() async throws { + func testRemoveDirectorySequentially() async throws { let path = try await self.fs.temporaryFilePath() let created = try await self.generateDirectoryStructure( root: path, @@ -1019,12 +1019,37 @@ final class FileSystemTests: XCTestCase { // Removing a non-empty directory recursively should throw 'notEmpty' await XCTAssertThrowsFileSystemErrorAsync { - try await self.fs.removeItem(at: path, recursively: false) + try await self.fs.removeItem(at: path, strategy: .sequential, recursively: false) } onError: { error in XCTAssertEqual(error.code, .notEmpty) } - let removed = try await self.fs.removeItem(at: path) + let removed = try await self.fs.removeItem(at: path, strategy: .sequential) + XCTAssertEqual(created, removed) + + let infoAfterRemoval = try await self.fs.info(forFileAt: path) + XCTAssertNil(infoAfterRemoval) + } + + func testRemoveDirectoryConcurrently() async throws { + let path = try await self.fs.temporaryFilePath() + let created = try await self.generateDirectoryStructure( + root: path, + maxDepth: 3, + maxFilesPerDirectory: 10 + ) + + let infoAfterCreation = try await self.fs.info(forFileAt: path) + XCTAssertNotNil(infoAfterCreation) + + // Removing a non-empty directory recursively should throw 'notEmpty' + await XCTAssertThrowsFileSystemErrorAsync { + try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2), recursively: false) + } onError: { error in + XCTAssertEqual(error.code, .notEmpty) + } + + let removed = try await self.fs.removeItem(at: path, strategy: .parallel(maxDescriptors: 2)) XCTAssertEqual(created, removed) let infoAfterRemoval = try await self.fs.info(forFileAt: path) @@ -1602,7 +1627,7 @@ extension FileSystemTests { // Clean up after ourselves. self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: temporaryDirectoryPath) + try await fileSystem.removeItem(at: temporaryDirectoryPath, strategy: .platformDefault) } guard let info = try await self.fs.info(forFileAt: temporaryDirectoryPath) else { @@ -1640,7 +1665,7 @@ extension FileSystemTests { let temporaryDirectoryPath = try await self.fs.createTemporaryDirectory(template: template) self.addTeardownBlock { [fileSystem = self.fs] in - try await fileSystem.removeItem(at: templateRoot, recursively: true) + try await fileSystem.removeItem(at: templateRoot, strategy: .platformDefault, recursively: true) } guard From b2356d9e33af062d043d485a3c323bb907053f66 Mon Sep 17 00:00:00 2001 From: Rauhul Varma Date: Wed, 11 Dec 2024 08:31:10 -0800 Subject: [PATCH 18/93] Remove outdated documentation (#3023) Removes an outdated recommendation about shutting down `MultiThreadedEventLoopGroup`s before the program exits. It's now considered best practice to just exit the application and allow the host OS to do resource clean up. --- Sources/NIOPosix/MultiThreadedEventLoopGroup.swift | 3 --- 1 file changed, 3 deletions(-) diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index b92a4bb01..0361e1a19 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -51,9 +51,6 @@ typealias ThreadInitializer = (NIOThread) -> Void /// all run their own `EventLoop`. Those threads will not be shut down until `shutdownGracefully` or /// `syncShutdownGracefully` is called. /// -/// - Note: It's good style to call `MultiThreadedEventLoopGroup.shutdownGracefully` or -/// `MultiThreadedEventLoopGroup.syncShutdownGracefully` when you no longer need this `EventLoopGroup`. In -/// many cases that is just before your program exits. /// - warning: Unit tests often spawn one `MultiThreadedEventLoopGroup` per unit test to force isolation between the /// tests. In those cases it's important to shut the `MultiThreadedEventLoopGroup` down at the end of the /// test. A good place to start a `MultiThreadedEventLoopGroup` is the `setUp` method of your `XCTestCase` From 8bf40344623bad55bef36d8c4b50a44ea1dd062e Mon Sep 17 00:00:00 2001 From: George Barnett Date: Thu, 12 Dec 2024 10:29:03 +0000 Subject: [PATCH 19/93] Deprecate not-actually-public Base64 APIs (#3022) Motivation: The not-actually-public `_NIOBase64` module has public extensions on `String`. These are visible when transitively depending on `_NIOBase64` but shouldn't be. Modifications: - Add underscored variants - Deprecate public variants Result: Stricter API --- Sources/NIOCore/ByteBuffer-aux.swift | 4 ++-- .../NIOWebSocketClientUpgrader.swift | 4 ++-- .../NIOWebSocketServerUpgrader.swift | 3 ++- Sources/_NIOBase64/Base64.swift | 16 +++++++++++-- Tests/NIOBase64Tests/Base64Test.swift | 23 +++++++++---------- 5 files changed, 31 insertions(+), 19 deletions(-) diff --git a/Sources/NIOCore/ByteBuffer-aux.swift b/Sources/NIOCore/ByteBuffer-aux.swift index 232dffd87..1ec8e9cf3 100644 --- a/Sources/NIOCore/ByteBuffer-aux.swift +++ b/Sources/NIOCore/ByteBuffer-aux.swift @@ -733,13 +733,13 @@ extension ByteBuffer: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let base64String = try container.decode(String.self) - self = try ByteBuffer(bytes: base64String.base64Decoded()) + self = try ByteBuffer(bytes: base64String._base64Decoded()) } /// Encodes this buffer as a base64 string in a single value container. public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() - let base64String = String(base64Encoding: self.readableBytesView) + let base64String = String(_base64Encoding: self.readableBytesView) try container.encode(base64String) } } diff --git a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift index a25e69df9..cc5fa16e3 100644 --- a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift @@ -149,7 +149,7 @@ extension NIOWebSocketClientUpgrader { UInt64.random(in: UInt64.min...UInt64.max, using: &generator), UInt64.random(in: UInt64.min...UInt64.max, using: &generator) ) - return String(base64Encoding: buffer.readableBytesView) + return String(_base64Encoding: buffer.readableBytesView) } /// Generates a random WebSocket Request Key by generating 16 bytes randomly using the `SystemRandomNumberGenerator` and encoding them as a base64 string as defined in RFC6455 https://tools.ietf.org/html/rfc6455#section-4.1. /// - Returns: base64 encoded request key @@ -179,7 +179,7 @@ private func _shouldAllowUpgrade(upgradeResponse: HTTPResponseHead, requestKey: var hasher = SHA1() hasher.update(string: requestKey) hasher.update(string: magicWebSocketGUID) - let expectedAcceptValue = String(base64Encoding: hasher.finish()) + let expectedAcceptValue = String(_base64Encoding: hasher.finish()) return expectedAcceptValue == acceptValueHeader[0] } diff --git a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift index 8aa16eec7..4f888a3e3 100644 --- a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift @@ -15,6 +15,7 @@ import CNIOSHA1 import NIOCore import NIOHTTP1 +import _NIOBase64 let magicWebSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" @@ -303,7 +304,7 @@ private func _buildUpgradeResponse( var hasher = SHA1() hasher.update(string: key) hasher.update(string: magicWebSocketGUID) - acceptValue = String(base64Encoding: hasher.finish()) + acceptValue = String(_base64Encoding: hasher.finish()) } extraHeaders.replaceOrAdd(name: "Upgrade", value: "websocket") diff --git a/Sources/_NIOBase64/Base64.swift b/Sources/_NIOBase64/Base64.swift index dc001f85b..15bf79e3b 100644 --- a/Sources/_NIOBase64/Base64.swift +++ b/Sources/_NIOBase64/Base64.swift @@ -16,15 +16,27 @@ // https://github.com/fabianfett/swift-base64-kit extension String { + /// Base64 encode a collection of UInt8 to a string, without the use of Foundation. + @available(*, deprecated, message: "This API was unintentionally made public.") + @inlinable + public init(base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { + self.init(_base64Encoding: bytes) + } + + @available(*, deprecated, message: "This API was unintentionally made public.") + @inlinable + public func base64Decoded() throws -> [UInt8] { + try self._base64Decoded() + } /// Base64 encode a collection of UInt8 to a string, without the use of Foundation. @inlinable - public init(base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { + public init(_base64Encoding bytes: Buffer) where Buffer.Element == UInt8 { self = Base64.encode(bytes: bytes) } @inlinable - public func base64Decoded() throws -> [UInt8] { + public func _base64Decoded() throws -> [UInt8] { try Base64.decode(string: self) } } diff --git a/Tests/NIOBase64Tests/Base64Test.swift b/Tests/NIOBase64Tests/Base64Test.swift index dd6262a9d..5c320706b 100644 --- a/Tests/NIOBase64Tests/Base64Test.swift +++ b/Tests/NIOBase64Tests/Base64Test.swift @@ -13,59 +13,58 @@ //===----------------------------------------------------------------------===// import XCTest - -@testable import _NIOBase64 +import _NIOBase64 class Base64Test: XCTestCase { func testEncodeEmptyData() throws { let data = [UInt8]() - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual(encodedData.count, 0) } func testBase64EncodingOfEmptyString() throws { let string = "" - let encoded = String(base64Encoding: string.utf8) + let encoded = String(_base64Encoding: string.utf8) XCTAssertEqual(encoded, "") } func testBase64DecodingOfEmptyString() throws { let encoded = "" XCTAssertNoThrow { - let decoded = try encoded.base64Decoded() + let decoded = try encoded._base64Decoded() XCTAssertEqual(decoded, [UInt8]()) } } func testBase64EncodingArrayOfNulls() throws { let data = Array(repeating: UInt8(0), count: 10) - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual(encodedData, "AAAAAAAAAAAAAA==") } func testBase64DecodeArrayOfNulls() throws { let encoded = "AAAAAAAAAAAAAA==" - let decoded = try! encoded.base64Decoded() + let decoded = try! encoded._base64Decoded() let expected = Array(repeating: UInt8(0), count: 10) XCTAssertEqual(decoded, expected) } func testBase64EncodeingHelloWorld() throws { let string = "Hello, world!" - let encoded = String(base64Encoding: string.utf8) + let encoded = String(_base64Encoding: string.utf8) let expected = "SGVsbG8sIHdvcmxkIQ==" XCTAssertEqual(encoded, expected) } func testBase64DecodeHelloWorld() throws { let encoded = "SGVsbG8sIHdvcmxkIQ==" - let decoded = try! encoded.base64Decoded() + let decoded = try! encoded._base64Decoded() XCTAssertEqual(decoded, "Hello, world!".utf8.map { UInt8($0) }) } func testBase64EncodingAllTheBytesSequentially() throws { let data = Array(UInt8(0)...UInt8(255)) - let encodedData = String(base64Encoding: data) + let encodedData = String(_base64Encoding: data) XCTAssertEqual( encodedData, "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" @@ -74,14 +73,14 @@ class Base64Test: XCTestCase { func testBase64DecodingWithInvalidLength() { let encoded = "dGVzbA!==" - XCTAssertThrowsError(try encoded.base64Decoded()) { error in + XCTAssertThrowsError(try encoded._base64Decoded()) { error in XCTAssertEqual(error as? Base64Error, .invalidLength) } } func testBase64DecodeWithInvalidCharacter() throws { let encoded = "SGVsbG8sI_dvcmxkIQ==" - XCTAssertThrowsError(try encoded.base64Decoded()) { error in + XCTAssertThrowsError(try encoded._base64Decoded()) { error in XCTAssertEqual(error as? Base64Error, .invalidCharacter) } } From 969b06b844f092627c8b888be32d636a5a112166 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Fri, 13 Dec 2024 13:50:27 +0000 Subject: [PATCH 20/93] rename top matrix workflow object 'swift'->'config' (#3024) ### Motivation: The use of 'swift' here is very arbitrary and adds no value. The object is only there at all because GitHub Actions seems to require it. ### Modifications: Rename the top-level object from 'swift' to 'config' to maybe add value to the intent of the object and hopefully be less cryptic. ### Result: Everything should just keep working. --- .github/workflows/swift_test_matrix.yml | 32 ++++++++++++------------- scripts/generate_matrix.sh | 18 +++++++------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/.github/workflows/swift_test_matrix.yml b/.github/workflows/swift_test_matrix.yml index cec7fd70f..9b4a36e93 100644 --- a/.github/workflows/swift_test_matrix.yml +++ b/.github/workflows/swift_test_matrix.yml @@ -19,8 +19,8 @@ concurrency: jobs: execute-matrix: - name: ${{ matrix.swift.platform }} (${{ matrix.swift.name }}) - runs-on: ${{ matrix.swift.runner }} + name: ${{ matrix.config.platform }} (${{ matrix.config.name }}) + runs-on: ${{ matrix.config.runner }} strategy: fail-fast: false matrix: ${{ fromJson(inputs.matrix_string) }} @@ -31,37 +31,37 @@ jobs: persist-credentials: false submodules: true - name: Pull Docker image - run: docker pull ${{ matrix.swift.image }} + run: docker pull ${{ matrix.config.image }} - name: Run matrix job - if: ${{ matrix.swift.platform != 'Windows' }} + if: ${{ matrix.config.platform != 'Windows' }} run: | - if [[ -n "${{ matrix.swift.setup_command }}" ]]; then - setup_command_expression="${{ matrix.swift.setup_command }} &&" + if [[ -n "${{ matrix.config.setup_command }}" ]]; then + setup_command_expression="${{ matrix.config.setup_command }} &&" else setup_command_expression="" fi workspace="/$(basename ${{ github.workspace }})" docker run -v ${{ github.workspace }}:"$workspace" \ -w "$workspace" \ - -e SWIFT_VERSION="${{ matrix.swift.swift_version }}" \ + -e SWIFT_VERSION="${{ matrix.config.swift_version }}" \ -e setup_command_expression="$setup_command_expression" \ -e workspace="$workspace" \ - ${{ matrix.swift.image }} \ - bash -c "swift --version && git config --global --add safe.directory \"$workspace\" && $setup_command_expression ${{ matrix.swift.command }} ${{ matrix.swift.command_arguments }}" + ${{ matrix.config.image }} \ + bash -c "swift --version && git config --global --add safe.directory \"$workspace\" && $setup_command_expression ${{ matrix.config.command }} ${{ matrix.config.command_arguments }}" - name: Run matrix job (Windows) - if: ${{ matrix.swift.platform == 'Windows' }} + if: ${{ matrix.config.platform == 'Windows' }} run: | - if (-not [string]::IsNullOrEmpty("${{ matrix.swift.setup_command }}")) { - $setup_command_expression = "${{ matrix.swift.setup_command }} &" + if (-not [string]::IsNullOrEmpty("${{ matrix.config.setup_command }}")) { + $setup_command_expression = "${{ matrix.config.setup_command }} &" } else { $setup_command_expression = "" } $workspace = "C:\" + (Split-Path ${{ github.workspace }} -Leaf) docker run -v ${{ github.workspace }}:$($workspace) ` -w $($workspace) ` - -e SWIFT_VERSION="${{ matrix.swift.swift_version }}" ` + -e SWIFT_VERSION="${{ matrix.config.swift_version }}" ` -e setup_command_expression=%setup_command_expression% ` - ${{ matrix.swift.image }} ` - cmd /s /c "swift --version & powershell Invoke-Expression ""$($setup_command_expression) ${{ matrix.swift.command }} ${{ matrix.swift.command_arguments }}""" + ${{ matrix.config.image }} ` + cmd /s /c "swift --version & powershell Invoke-Expression ""$($setup_command_expression) ${{ matrix.config.command }} ${{ matrix.config.command_arguments }}""" env: - SWIFT_VERSION: ${{ matrix.swift.swift_version }} + SWIFT_VERSION: ${{ matrix.config.swift_version }} diff --git a/scripts/generate_matrix.sh b/scripts/generate_matrix.sh index dbab4f69a..c7915b478 100755 --- a/scripts/generate_matrix.sh +++ b/scripts/generate_matrix.sh @@ -52,7 +52,7 @@ windows_nightly_main_runner="windows-2019" windows_nightly_main_container_image="swiftlang/swift:nightly-main-windowsservercore-1809" # Create matrix from inputs -matrix='{"swift": []}' +matrix='{"config": []}' ## Linux if [[ "$linux_5_9_enabled" == "true" || "$linux_5_10_enabled" == "true" || "$linux_6_0_enabled" == "true" || \ @@ -70,7 +70,7 @@ if [[ "$linux_5_9_enabled" == "true" ]]; then --arg command_arguments "$linux_5_9_command_arguments" \ --arg container_image "$linux_5_9_container_image" \ --arg runner "$linux_runner" \ - '.swift[.swift| length] |= . + { "name": "5.9", "image": $container_image, "swift_version": "5.9", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "5.9", "image": $container_image, "swift_version": "5.9", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi if [[ "$linux_5_10_enabled" == "true" ]]; then @@ -80,7 +80,7 @@ if [[ "$linux_5_10_enabled" == "true" ]]; then --arg command_arguments "$linux_5_10_command_arguments" \ --arg container_image "$linux_5_10_container_image" \ --arg runner "$linux_runner" \ - '.swift[.swift| length] |= . + { "name": "5.10", "image": $container_image, "swift_version": "5.10", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "5.10", "image": $container_image, "swift_version": "5.10", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi if [[ "$linux_6_0_enabled" == "true" ]]; then @@ -90,7 +90,7 @@ if [[ "$linux_6_0_enabled" == "true" ]]; then --arg command_arguments "$linux_6_0_command_arguments" \ --arg container_image "$linux_6_0_container_image" \ --arg runner "$linux_runner" \ - '.swift[.swift| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi if [[ "$linux_nightly_6_0_enabled" == "true" ]]; then @@ -100,7 +100,7 @@ if [[ "$linux_nightly_6_0_enabled" == "true" ]]; then --arg command_arguments "$linux_nightly_6_0_command_arguments" \ --arg container_image "$linux_nightly_6_0_container_image" \ --arg runner "$linux_runner" \ - '.swift[.swift| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi if [[ "$linux_nightly_main_enabled" == "true" ]]; then @@ -110,7 +110,7 @@ if [[ "$linux_nightly_main_enabled" == "true" ]]; then --arg command_arguments "$linux_nightly_main_command_arguments" \ --arg container_image "$linux_nightly_main_container_image" \ --arg runner "$linux_runner" \ - '.swift[.swift| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi ## Windows @@ -127,7 +127,7 @@ if [[ "$windows_6_0_enabled" == "true" ]]; then --arg command_arguments "$windows_6_0_command_arguments" \ --arg container_image "$windows_6_0_container_image" \ --arg runner "$windows_6_0_runner" \ - '.swift[.swift| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') + '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') fi if [[ "$windows_nightly_6_0_enabled" == "true" ]]; then @@ -137,7 +137,7 @@ if [[ "$windows_nightly_6_0_enabled" == "true" ]]; then --arg command_arguments "$windows_nightly_6_0_command_arguments" \ --arg container_image "$windows_nightly_6_0_container_image" \ --arg runner "$windows_nightly_6_0_runner" \ - '.swift[.swift| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') + '.config[.config| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') fi if [[ "$windows_nightly_main_enabled" == "true" ]]; then @@ -147,7 +147,7 @@ if [[ "$windows_nightly_main_enabled" == "true" ]]; then --arg command_arguments "$windows_nightly_main_command_arguments" \ --arg container_image "$windows_nightly_main_container_image" \ --arg runner "$windows_nightly_main_runner" \ - '.swift[.swift| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') + '.config[.config| length] |= . + { "name": "nightly-main", "image": $container_image, "swift_version": "nightly-main", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') fi echo "$matrix" | jq -c \ No newline at end of file From 742ae54a2f60ce5a1acf2fd2d2b3c8e4c59cb82a Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 13 Dec 2024 16:52:38 +0000 Subject: [PATCH 21/93] Fix new warnings (#3026) Motivation: 6.0.3 added new warnings about Sendable issues, so let's fix those to keep things warnings free. Modifications: A bunch of Sendable usage fixes. Result: Warnings free builds again! --- .../NIOAsyncAwaitDemo/AsyncChannelIO.swift | 7 +- Sources/NIOPosix/Bootstrap.swift | 8 +- .../AsyncTestingChannelTests.swift | 16 ++-- .../HTTPClientUpgradeTests.swift | 4 +- .../HTTPServerUpgradeTests.swift | 4 +- .../AsyncChannelBootstrapTests.swift | 30 ++++---- .../NIOScheduledCallbackTests.swift | 76 +++++++++---------- .../RawSocketBootstrapTests.swift | 36 +++++++-- Tests/NIOPosixTests/SocketChannelTest.swift | 3 +- .../UniversalBootstrapSupportTest.swift | 8 +- .../WebSocketClientEndToEndTests.swift | 53 +++++++++---- 11 files changed, 150 insertions(+), 95 deletions(-) diff --git a/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift b/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift index e5612e1f6..5e6f04a38 100644 --- a/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift +++ b/Sources/NIOAsyncAwaitDemo/AsyncChannelIO.swift @@ -24,8 +24,11 @@ struct AsyncChannelIO { } func start() async throws -> AsyncChannelIO { - try await channel.pipeline.addHandler(RequestResponseHandler()) - .get() + try await channel.eventLoop.submit { + try channel.pipeline.syncOperations.addHandler( + RequestResponseHandler() + ) + }.get() return self } diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index fa117e857..e3b5710ff 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -2420,6 +2420,8 @@ extension NIOPipeBootstrap { let channel: PipeChannel let pipeChannelInput: SelectablePipeHandle? let pipeChannelOutput: SelectablePipeHandle? + let hasNoInputPipe: Bool + let hasNoOutputPipe: Bool do { if let input = input { try self.validateFileDescriptorIsNotAFile(input) @@ -2430,6 +2432,8 @@ extension NIOPipeBootstrap { pipeChannelInput = input.flatMap { SelectablePipeHandle(takingOwnershipOfDescriptor: $0) } pipeChannelOutput = output.flatMap { SelectablePipeHandle(takingOwnershipOfDescriptor: $0) } + hasNoInputPipe = pipeChannelInput == nil + hasNoOutputPipe = pipeChannelOutput == nil do { channel = try self.hooks.makePipeChannel( eventLoop: eventLoop as! SelectableEventLoop, @@ -2458,10 +2462,10 @@ extension NIOPipeBootstrap { channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult.map { result } }.flatMap { result -> EventLoopFuture in - if pipeChannelInput == nil { + if hasNoInputPipe { return channel.close(mode: .input).map { result } } - if pipeChannelOutput == nil { + if hasNoOutputPipe { return channel.close(mode: .output).map { result } } return channel.selectableEventLoop.makeSucceededFuture(result) diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index 1619f9563..5fa112f6d 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -21,7 +21,7 @@ import XCTest @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) class AsyncTestingChannelTests: XCTestCase { func testSingleHandlerInit() async throws { - class Handler: ChannelInboundHandler { + final class Handler: ChannelInboundHandler, Sendable { typealias InboundIn = Never } @@ -43,7 +43,7 @@ class AsyncTestingChannelTests: XCTestCase { } func testMultipleHandlerInit() async throws { - class Handler: ChannelInboundHandler, RemovableChannelHandler { + final class Handler: ChannelInboundHandler, RemovableChannelHandler, Sendable { typealias InboundIn = Never let identifier: String @@ -334,7 +334,7 @@ class AsyncTestingChannelTests: XCTestCase { try await XCTAsyncAssertTrue(await channel.finish().isClean) // channelInactive should fire only once. - XCTAssertEqual(inactiveHandler.inactiveNotifications, 1) + XCTAssertEqual(inactiveHandler.inactiveNotifications.load(ordering: .sequentiallyConsistent), 1) } func testEmbeddedLifecycle() async throws { @@ -355,7 +355,7 @@ class AsyncTestingChannelTests: XCTestCase { XCTAssertFalse(channel.isActive) } - private final class ExceptionThrowingInboundHandler: ChannelInboundHandler { + private final class ExceptionThrowingInboundHandler: ChannelInboundHandler, Sendable { typealias InboundIn = String public func channelRead(context: ChannelHandlerContext, data: NIOAny) { @@ -363,7 +363,7 @@ class AsyncTestingChannelTests: XCTestCase { } } - private final class ExceptionThrowingOutboundHandler: ChannelOutboundHandler { + private final class ExceptionThrowingOutboundHandler: ChannelOutboundHandler, Sendable { typealias OutboundIn = String typealias OutboundOut = Never @@ -372,12 +372,12 @@ class AsyncTestingChannelTests: XCTestCase { } } - private final class CloseInChannelInactiveHandler: ChannelInboundHandler { + private final class CloseInChannelInactiveHandler: ChannelInboundHandler, Sendable { typealias InboundIn = ByteBuffer - public var inactiveNotifications = 0 + public let inactiveNotifications = ManagedAtomic(0) public func channelInactive(context: ChannelHandlerContext) { - inactiveNotifications += 1 + inactiveNotifications.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) context.close(promise: nil) } } diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index 43cfbb4c6..97d9df956 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -318,7 +318,7 @@ private func assertPipelineContainsUpgradeHandler(channel: Channel) { @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) class HTTPClientUpgradeTestCase: XCTestCase { func setUpClientChannel( - clientHTTPHandler: RemovableChannelHandler, + clientHTTPHandler: RemovableChannelHandler & Sendable, clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) throws -> EmbeddedChannel { @@ -1063,7 +1063,7 @@ class HTTPClientUpgradeTestCase: XCTestCase { @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { override func setUpClientChannel( - clientHTTPHandler: RemovableChannelHandler, + clientHTTPHandler: RemovableChannelHandler & Sendable, clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) throws -> EmbeddedChannel { diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index 3a69f806e..9049c5122 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -1388,7 +1388,7 @@ class HTTPServerUpgradeTestCase: XCTestCase { XCTAssertNil(upgradeRequest.wrappedValue) upgradeHandlerCbFired.wrappedValue = true - _ = context.channel.pipeline.addHandler( + try! context.channel.pipeline.syncOperations.addHandler( CheckWeReadInlineAndExtraData( firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, @@ -2145,7 +2145,7 @@ final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase { XCTAssertNotNil(upgradeRequest.wrappedValue) upgradeHandlerCbFired.wrappedValue = true - _ = context.channel.pipeline.addHandler( + try! context.channel.pipeline.syncOperations.addHandler( CheckWeReadInlineAndExtraData( firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index 847a5ac78..68604ef0f 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -284,7 +284,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } @@ -366,7 +366,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureNestedProtocolNegotiationHandlers(channel: channel) + try Self.configureNestedProtocolNegotiationHandlers(channel: channel) } } @@ -508,7 +508,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { port: 0 ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } @@ -958,7 +958,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { output: pipe2WriteFD ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) + try Self.configureProtocolNegotiationHandlers(channel: channel) } } } catch { @@ -1251,7 +1251,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( AddressedEnvelopingHandler(remoteAddress: SocketAddress(ipAddress: "127.0.0.1", port: 0)) ) - return try self.configureProtocolNegotiationHandlers( + return try Self.configureProtocolNegotiationHandlers( channel: channel, proposedALPN: nil, inboundID: 1, @@ -1275,7 +1275,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( AddressedEnvelopingHandler(remoteAddress: SocketAddress(ipAddress: "127.0.0.1", port: 0)) ) - return try self.configureProtocolNegotiationHandlers( + return try Self.configureProtocolNegotiationHandlers( channel: channel, proposedALPN: proposedALPN, inboundID: 2, @@ -1329,7 +1329,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { to: .init(ipAddress: "127.0.0.1", port: port) ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @@ -1345,7 +1345,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { to: .init(ipAddress: "127.0.0.1", port: port) ) { channel in channel.eventLoop.makeCompletedFuture { - try self.configureNestedProtocolNegotiationHandlers( + try Self.configureNestedProtocolNegotiationHandlers( channel: channel, proposedOuterALPN: proposedOuterALPN, proposedInnerALPN: proposedInnerALPN @@ -1382,7 +1382,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { ) { channel in channel.eventLoop.makeCompletedFuture { try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) - return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + return try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @@ -1418,13 +1418,13 @@ final class AsyncChannelBootstrapTests: XCTestCase { ) { channel in channel.eventLoop.makeCompletedFuture { try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) - return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + return try Self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) } } } @discardableResult - private func configureProtocolNegotiationHandlers( + private static func configureProtocolNegotiationHandlers( channel: Channel, proposedALPN: TLSUserEventHandler.ALPN? = nil, inboundID: UInt8? = nil, @@ -1437,7 +1437,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } @discardableResult - private func configureNestedProtocolNegotiationHandlers( + private static func configureNestedProtocolNegotiationHandlers( channel: Channel, proposedOuterALPN: TLSUserEventHandler.ALPN? = nil, proposedInnerALPN: TLSUserEventHandler.ALPN? = nil @@ -1456,7 +1456,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( TLSUserEventHandler(proposedALPN: proposedInnerALPN) ) - let negotiationFuture = try self.addTypedApplicationProtocolNegotiationHandler(to: channel) + let negotiationFuture = try Self.addTypedApplicationProtocolNegotiationHandler(to: channel) return negotiationFuture } @@ -1465,7 +1465,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { try channel.pipeline.syncOperations.addHandler( TLSUserEventHandler(proposedALPN: proposedInnerALPN) ) - let negotiationHandler = try self.addTypedApplicationProtocolNegotiationHandler(to: channel) + let negotiationHandler = try Self.addTypedApplicationProtocolNegotiationHandler(to: channel) return negotiationHandler } @@ -1481,7 +1481,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } @discardableResult - private func addTypedApplicationProtocolNegotiationHandler( + private static func addTypedApplicationProtocolNegotiationHandler( to channel: Channel ) throws -> EventLoopFuture { let negotiationHandler = NIOTypedApplicationProtocolNegotiationHandler { diff --git a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift index b115ac2f8..9940b74e1 100644 --- a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift +++ b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import Atomics import NIOCore import NIOEmbedded import NIOPosix @@ -26,9 +27,6 @@ protocol ScheduledCallbackTestRequirements { // ELG-backed ELs need to be shutdown via the ELG. func shutdownEventLoop() async throws - - // This is here for NIOAsyncTestingEventLoop only. - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R } final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { @@ -43,10 +41,6 @@ final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { func shutdownEventLoop() async throws { try await self.group.shutdownGracefully() } - - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try body() - } } override func setUp() async throws { @@ -66,10 +60,6 @@ final class NIOAsyncTestingEventLoopScheduledCallbackTests: _BaseScheduledCallba func shutdownEventLoop() async throws { await self._loop.shutdownGracefully() } - - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try await self._loop.executeInContext(body) - } } override func setUp() async throws { @@ -98,10 +88,6 @@ extension _BaseScheduledCallbackTests { func shutdownEventLoop() async throws { try await self.requirements.shutdownEventLoop() } - - func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { - try await self.requirements.maybeInContext(body) - } } // The tests, abstracted over any of the event loops. @@ -111,10 +97,10 @@ extension _BaseScheduledCallbackTests { let handler = MockScheduledCallbackHandler() _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + handler.assert(callbackCount: 0, cancelCount: 0) try await self.advanceTime(by: .microseconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + handler.assert(callbackCount: 0, cancelCount: 0) } func testSheduledCallbackExecutedAtDeadline() async throws { @@ -123,7 +109,7 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) } func testMultipleSheduledCallbacksUsingSameHandler() async throws { @@ -135,7 +121,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 2, cancelCount: 0) } + handler.assert(callbackCount: 2, cancelCount: 0) _ = try self.loop.scheduleCallback(in: .milliseconds(2), handler: handler) _ = try self.loop.scheduleCallback(in: .milliseconds(3), handler: handler) @@ -143,7 +129,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(3)) try await handler.waitForCallback(timeout: .seconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 4, cancelCount: 0) } + handler.assert(callbackCount: 4, cancelCount: 0) } func testMultipleSheduledCallbacksUsingDifferentHandlers() async throws { @@ -156,8 +142,8 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handlerA.waitForCallback(timeout: .seconds(1)) try await handlerB.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handlerA.assert(callbackCount: 1, cancelCount: 0) } - try await self.maybeInContext { handlerB.assert(callbackCount: 1, cancelCount: 0) } + handlerA.assert(callbackCount: 1, cancelCount: 0) + handlerB.assert(callbackCount: 1, cancelCount: 0) } func testCancelExecutesCancellationCallback() async throws { @@ -165,7 +151,7 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testCancelAfterDeadlineDoesNotExecutesCancellationCallback() async throws { @@ -175,7 +161,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) } func testCancelAfterCancelDoesNotCallCancellationCallbackAgain() async throws { @@ -184,7 +170,7 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testCancelAfterShutdownDoesNotCallCancellationCallbackAgain() async throws { @@ -192,10 +178,10 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) scheduledCallback.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownCancelsOutstandingScheduledCallbacks() async throws { @@ -203,7 +189,7 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownDoesNotCancelCancelledCallbacksAgain() async throws { @@ -211,10 +197,10 @@ extension _BaseScheduledCallbackTests { let handle = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) handle.cancel() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + handler.assert(callbackCount: 0, cancelCount: 1) } func testShutdownDoesNotCancelPastCallbacks() async throws { @@ -223,16 +209,16 @@ extension _BaseScheduledCallbackTests { _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) try await self.shutdownEventLoop() - try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + handler.assert(callbackCount: 1, cancelCount: 0) } } -private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler { - var callbackCount = 0 - var cancelCount = 0 +private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler, Sendable { + let callbackCount = ManagedAtomic(0) + let cancelCount = ManagedAtomic(0) let callbackStream: AsyncStream private let callbackStreamContinuation: AsyncStream.Continuation @@ -246,17 +232,29 @@ private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler { } func handleScheduledCallback(eventLoop: some EventLoop) { - self.callbackCount += 1 + self.callbackCount.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) self.callbackStreamContinuation.yield() } func didCancelScheduledCallback(eventLoop: some EventLoop) { - self.cancelCount += 1 + self.cancelCount.wrappingIncrement(by: 1, ordering: .sequentiallyConsistent) } func assert(callbackCount: Int, cancelCount: Int, file: StaticString = #file, line: UInt = #line) { - XCTAssertEqual(self.callbackCount, callbackCount, "Unexpected callback count", file: file, line: line) - XCTAssertEqual(self.cancelCount, cancelCount, "Unexpected cancel count", file: file, line: line) + XCTAssertEqual( + self.callbackCount.load(ordering: .sequentiallyConsistent), + callbackCount, + "Unexpected callback count", + file: file, + line: line + ) + XCTAssertEqual( + self.cancelCount.load(ordering: .sequentiallyConsistent), + cancelCount, + "Unexpected cancel count", + file: file, + line: line + ) } func waitForCallback(timeout: TimeAmount, file: StaticString = #file, line: UInt = #line) async throws { diff --git a/Tests/NIOPosixTests/RawSocketBootstrapTests.swift b/Tests/NIOPosixTests/RawSocketBootstrapTests.swift index a65ad1ae9..a7c42c3c8 100644 --- a/Tests/NIOPosixTests/RawSocketBootstrapTests.swift +++ b/Tests/NIOPosixTests/RawSocketBootstrapTests.swift @@ -47,8 +47,13 @@ final class RawSocketBootstrapTests: XCTestCase { let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let channel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try channel.close().wait()) } @@ -93,15 +98,25 @@ final class RawSocketBootstrapTests: XCTestCase { let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let readChannel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try readChannel.close().wait()) } let writeChannel = try NIORawSocketBootstrap(group: elg) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try writeChannel.close().wait()) } @@ -147,8 +162,13 @@ final class RawSocketBootstrapTests: XCTestCase { defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let channel = try NIORawSocketBootstrap(group: elg) .channelOption(.ipOption(.ip_hdrincl), value: 1) - .channelInitializer { - $0.pipeline.addHandler(DatagramReadRecorder(), name: "ByteReadRecorder") + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler( + DatagramReadRecorder(), + name: "ByteReadRecorder" + ) + } } .bind(host: "127.0.0.1", ipProtocol: .reservedForTesting).wait() defer { XCTAssertNoThrow(try channel.close().wait()) } diff --git a/Tests/NIOPosixTests/SocketChannelTest.swift b/Tests/NIOPosixTests/SocketChannelTest.swift index cb8161a7e..a42eefb0f 100644 --- a/Tests/NIOPosixTests/SocketChannelTest.swift +++ b/Tests/NIOPosixTests/SocketChannelTest.swift @@ -1138,11 +1138,12 @@ class DropAllReadsOnTheFloorHandler: ChannelDuplexHandler { // What we're trying to do here is forcing a close without calling `close`. We know that the other side of // the connection is fully closed but because we support half-closure, we need to write to 'learn' that the // other side has actually fully closed the socket. + let promise = self.waitUntilWriteFailedPromise func writeUntilError() { context.writeAndFlush(Self.wrapOutboundOut(buffer)).map { writeUntilError() }.whenFailure { (_: Error) in - self.waitUntilWriteFailedPromise.succeed(()) + promise.succeed(()) } } writeUntilError() diff --git a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift index 8b671fce6..9d729c553 100644 --- a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift +++ b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift @@ -83,7 +83,13 @@ class UniversalBootstrapSupportTest: XCTestCase { let client = try NIOClientTCPBootstrap(ClientBootstrap(group: group), tls: DummyTLSProvider()) .channelInitializer { channel in - channel.pipeline.addHandlers(counter1, DropChannelReadsHandler(), counter2) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandlers( + counter1, + DropChannelReadsHandler(), + counter2 + ) + } } .channelOption(.autoRead, value: false) .connectTimeout(.hours(1)) diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index 23202c2c4..71a86bdc1 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -170,7 +170,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -244,7 +246,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -275,7 +279,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -307,7 +313,9 @@ class WebSocketClientEndToEndTests: XCTestCase { let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -332,13 +340,12 @@ class WebSocketClientEndToEndTests: XCTestCase { } fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { - - let handler = WebSocketRecorderHandler() - let basicUpgrader = NIOWebSocketClientUpgrader( requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(handler) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -361,6 +368,10 @@ class WebSocketClientEndToEndTests: XCTestCase { clientChannel.embeddedEventLoop.run() + // Ok, now grab the handler. We can do this with sync operations, because this is an + // EmbeddedChannel. + let handler = try clientChannel.pipeline.syncOperations.handler(type: WebSocketRecorderHandler.self) + return (clientChannel, handler) } @@ -501,7 +512,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -570,7 +583,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -603,7 +618,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -637,7 +654,9 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: requestKey, upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketRecorderHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -665,12 +684,12 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { } override fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { - let handler = WebSocketRecorderHandler() - let basicUpgrader = NIOTypedWebSocketClientUpgrader( requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(handler) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketRecorderHandler()) + } } ) @@ -695,6 +714,10 @@ final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { try upgradeResult.wait() + // Ok, now grab the handler. We can do this with sync operations, because this is an + // EmbeddedChannel. + let handler = try clientChannel.pipeline.syncOperations.handler(type: WebSocketRecorderHandler.self) + return (clientChannel, handler) } } From 47785adb51d724a2d19c7d042a89bcb1b65036b9 Mon Sep 17 00:00:00 2001 From: finagolfin Date: Sun, 15 Dec 2024 17:07:57 +0530 Subject: [PATCH 22/93] Remove now unneeded fts_open bitcast for Android (#3025) I added this changed function call for Android in #2660 earlier this year, because of [an incorrect Bionic function signature as explained recently](https://github.com/apple/swift-nio/pull/3009#discussion_r1864807270), but now that it has been worked around through a new API note as mentioned there, this change is no longer needed. I simply did not notice this earlier because it still compiles and merely gives a warning, which removing this call now silences. --- Sources/NIOFileSystem/Internal/System Calls/Syscall.swift | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift index de5325940..fe0318707 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift @@ -400,14 +400,7 @@ public enum Libc { return valueOrErrno { pathBytes.withUnsafeMutableBufferPointer { pointer in // The array must be terminated with a nil. - #if os(Android) - libc_fts_open( - [pointer.baseAddress!, unsafeBitCast(0, to: UnsafeMutablePointer.self)], - options.rawValue - ) - #else libc_fts_open([pointer.baseAddress, nil], options.rawValue) - #endif } } } From ecfaa2c6ff3234bdf7909eba0da01c245922e471 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Mon, 16 Dec 2024 08:32:23 +0000 Subject: [PATCH 23/93] fix bogus "unleakable promise leaked" error message (#2855) (#3027) ### Motivation: SwiftNIO contained a bogus error message: ``` BUG in SwiftNIO (please report), unleakable promise leaked.:486: Fatal error: leaking promise created at (file: "BUG in SwiftNIO (please report), unleakable promise leaked.", line: 486) ``` The actual meaning is that the ELG was shut down prematurely. ### Modifications: - Replace the message with an accurate one ### Result: - Users less confused - fixes #2855 - fixes #2201 --- Sources/NIOCore/EventLoopFuture.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Sources/NIOCore/EventLoopFuture.swift b/Sources/NIOCore/EventLoopFuture.swift index 793d3a7ed..4579576ed 100644 --- a/Sources/NIOCore/EventLoopFuture.swift +++ b/Sources/NIOCore/EventLoopFuture.swift @@ -163,7 +163,12 @@ public struct EventLoopPromise { internal static func makeUnleakablePromise(eventLoop: EventLoop, line: UInt = #line) -> EventLoopPromise { EventLoopPromise( eventLoop: eventLoop, - file: "BUG in SwiftNIO (please report), unleakable promise leaked.", + file: """ + EventLoopGroup shut down with unfulfilled promises remaining. \ + This suggests that the EventLoopGroup was shut down with unfinished work outstanding which is \ + illegal. Either switch to using the singleton EventLoopGroups or fix the issue by only shutting down \ + the EventLoopGroups when all the work associated with them has finished. + """, line: line ) } From 55d0f72b309a9217405c9c7fc0163af521ee0db3 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Mon, 16 Dec 2024 11:17:18 +0000 Subject: [PATCH 24/93] Enable MemberImportVisibility check on all targets (#3021) Enable MemberImportVisibility check on all targets. Use a standard string header and footer to bracket the new block for ease of updating in the future with scripts. Co-authored-by: George Barnett --- Package.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Package.swift b/Package.swift index 021ebf8e5..b1fcd3cc5 100644 --- a/Package.swift +++ b/Package.swift @@ -566,3 +566,14 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { .package(path: "../swift-system"), ] } + +// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // +for target in package.targets { + if target.type != .plugin { + var settings = target.swiftSettings ?? [] + // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md + settings.append(.enableUpcomingFeature("MemberImportVisibility")) + target.swiftSettings = settings + } +} +// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // From b99b6278e84df8c27d081d94a115da1856fbabd9 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Mon, 16 Dec 2024 13:53:22 +0000 Subject: [PATCH 25/93] Revert "Enable MemberImportVisibility check on all targets" (#3028) Reverts apple/swift-nio#3021 --- Package.swift | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Package.swift b/Package.swift index b1fcd3cc5..021ebf8e5 100644 --- a/Package.swift +++ b/Package.swift @@ -566,14 +566,3 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { .package(path: "../swift-system"), ] } - -// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // -for target in package.targets { - if target.type != .plugin { - var settings = target.swiftSettings ?? [] - // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md - settings.append(.enableUpcomingFeature("MemberImportVisibility")) - target.swiftSettings = settings - } -} -// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // From 1e4fde1093463c9cdde8b001f78fdcd8f2b61675 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 16 Dec 2024 14:20:01 +0000 Subject: [PATCH 26/93] Add isolated views to EventLoop, Promise, and Future (#2969) Motivation: Users writing NIO code in a strict concurrency world often need to interact with futures, promises, and event loops. The main interface to these has strict sendability requirements, as it is possible the user is doing so from outside the EventLoop that provides the isolation domain for these types. However, in many cases the user knows that they are on the isolation domain in question. In that case, they need more capabilities. While they can achieve their goals with NIOLoopBound today, it'd be nice if they had a better option. Modifications: - Make EventLoop.Isolated public. - Make EventLoopFuture.Isolated public. - Make EventLoopPromise.Isolated public. - Make all their relevant methods public. - Move the runtime isolation check from the point of use to the point of construction. - Make the types non-Sendable to ensure that isolation check is sufficient. - Add unsafeUnchecked options to create these types when performance matters and correctness is clear. - Add tests for their behaviour. - Update the documentation. Result: Writing safe code with promises, futures, and event loops is easier. --- .../AsyncChannel/AsyncChannelHandler.swift | 2 +- Sources/NIOCore/ChannelHandlers.swift | 24 +- Sources/NIOCore/ChannelPipeline.swift | 12 +- Sources/NIOCore/Codec.swift | 2 +- .../Docs.docc/loops-futures-concurrency.md | 74 +++- .../EventLoopFuture+AssumeIsolated.swift | 238 +++++++++---- Sources/NIOEmbedded/Embedded.swift | 10 + .../EventLoopFutureIsolatedTests.swift | 318 ++++++++++++++++++ 8 files changed, 580 insertions(+), 100 deletions(-) create mode 100644 Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift index 63d243b74..149c0ff5e 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift @@ -188,7 +188,7 @@ extension NIOAsyncChannelHandler: ChannelInboundHandler { // We are making sure to be on our event loop so we can safely use self in whenComplete channelReadTransformation(unwrapped) .hop(to: context.eventLoop) - .assumeIsolated() + .assumeIsolatedUnsafeUnchecked() .whenComplete { result in switch result { case .success: diff --git a/Sources/NIOCore/ChannelHandlers.swift b/Sources/NIOCore/ChannelHandlers.swift index 8e0da681e..358332945 100644 --- a/Sources/NIOCore/ChannelHandlers.swift +++ b/Sources/NIOCore/ChannelHandlers.swift @@ -114,7 +114,7 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler, RemovableChannelH } private func scheduleRead(at: NIODeadline, context: ChannelHandlerContext) { - self.scheduledRead = context.eventLoop.assumeIsolated().scheduleTask(deadline: at) { + self.scheduledRead = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(deadline: at) { self.doRead(context) } } @@ -252,7 +252,9 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl } let writePromise = promise ?? context.eventLoop.makePromise() - writePromise.futureResult.assumeIsolated().whenComplete { (_: Result) in + writePromise.futureResult.hop( + to: context.eventLoop + ).assumeIsolatedUnsafeUnchecked().whenComplete { (_: Result) in self.lastWriteCompleteTime = .now() } context.write(data, promise: writePromise) @@ -272,7 +274,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl } if self.reading { - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( in: timeout, self.makeReadTimeoutTask(context, timeout) ) @@ -282,7 +284,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl let diff = .now() - self.lastReadTime if diff >= timeout { // Reader is idle - set a new timeout and trigger an event through the pipeline - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( in: timeout, self.makeReadTimeoutTask(context, timeout) ) @@ -290,7 +292,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl context.fireUserInboundEventTriggered(IdleStateEvent.read) } else { // Read occurred before the timeout - set a new timeout with shorter delay. - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( deadline: self.lastReadTime + timeout, self.makeReadTimeoutTask(context, timeout) ) @@ -309,7 +311,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl if diff >= timeout { // Writer is idle - set a new timeout and notify the callback. - self.scheduledWriterTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledWriterTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( in: timeout, self.makeWriteTimeoutTask(context, timeout) ) @@ -317,7 +319,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl context.fireUserInboundEventTriggered(IdleStateEvent.write) } else { // Write occurred before the timeout - set a new timeout with shorter delay. - self.scheduledWriterTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledWriterTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( deadline: self.lastWriteCompleteTime + timeout, self.makeWriteTimeoutTask(context, timeout) ) @@ -332,7 +334,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl } if self.reading { - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( in: timeout, self.makeAllTimeoutTask(context, timeout) ) @@ -345,7 +347,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl let diff = .now() - latestLast if diff >= timeout { // Reader is idle - set a new timeout and trigger an event through the pipeline - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( in: timeout, self.makeAllTimeoutTask(context, timeout) ) @@ -353,7 +355,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl context.fireUserInboundEventTriggered(IdleStateEvent.all) } else { // Read occurred before the timeout - set a new timeout with shorter delay. - self.scheduledReaderTask = context.eventLoop.assumeIsolated().scheduleTask( + self.scheduledReaderTask = context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask( deadline: latestLast + timeout, self.makeAllTimeoutTask(context, timeout) ) @@ -367,7 +369,7 @@ public final class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandl _ body: @escaping (ChannelHandlerContext, TimeAmount) -> (() -> Void) ) -> Scheduled? { if let timeout = amount { - return context.eventLoop.assumeIsolated().scheduleTask(in: timeout, body(context, timeout)) + return context.eventLoop.assumeIsolatedUnsafeUnchecked().scheduleTask(in: timeout, body(context, timeout)) } return nil } diff --git a/Sources/NIOCore/ChannelPipeline.swift b/Sources/NIOCore/ChannelPipeline.swift index 6920a2b0f..7c4b0853a 100644 --- a/Sources/NIOCore/ChannelPipeline.swift +++ b/Sources/NIOCore/ChannelPipeline.swift @@ -472,10 +472,10 @@ public final class ChannelPipeline: ChannelInvoker { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { - promise.assumeIsolated().completeWith(self.contextSync(handler: handler)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(handler: handler)) } else { self.eventLoop.execute { - promise.assumeIsolated().completeWith(self.contextSync(handler: handler)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(handler: handler)) } } @@ -501,10 +501,10 @@ public final class ChannelPipeline: ChannelInvoker { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { - promise.assumeIsolated().completeWith(self.contextSync(name: name)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(name: name)) } else { self.eventLoop.execute { - promise.assumeIsolated().completeWith(self.contextSync(name: name)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self.contextSync(name: name)) } } @@ -534,10 +534,10 @@ public final class ChannelPipeline: ChannelInvoker { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { - promise.assumeIsolated().completeWith(self._contextSync(handlerType: handlerType)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self._contextSync(handlerType: handlerType)) } else { self.eventLoop.execute { - promise.assumeIsolated().completeWith(self._contextSync(handlerType: handlerType)) + promise.assumeIsolatedUnsafeUnchecked().completeWith(self._contextSync(handlerType: handlerType)) } } diff --git a/Sources/NIOCore/Codec.swift b/Sources/NIOCore/Codec.swift index acb4fc139..f38f2eb9e 100644 --- a/Sources/NIOCore/Codec.swift +++ b/Sources/NIOCore/Codec.swift @@ -749,7 +749,7 @@ extension ByteToMessageHandler: RemovableChannelHandler { public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { precondition(self.removalState == .notBeingRemoved) self.removalState = .removalStarted - context.eventLoop.assumeIsolated().execute { + context.eventLoop.assumeIsolatedUnsafeUnchecked().execute { self.processLeftovers(context: context) assert(!self.state.isLeftoversNeedProcessing, "illegal state: \(self.state)") switch self.removalState { diff --git a/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md b/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md index b5cbffa4f..a9af119ec 100644 --- a/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md +++ b/Sources/NIOCore/Docs.docc/loops-futures-concurrency.md @@ -138,10 +138,11 @@ guaranteed to fire on the same isolation domain as the ``ChannelHandlerContext`` of data race is present. However, Swift Concurrency cannot guarantee this at compile time, as the specific isolation domain is determined only at runtime. -In these contexts, today users can make their callbacks safe using ``NIOLoopBound`` and -``NIOLoopBoundBox``. These values can only be constructed on the event loop, and only allow -access to their values on the same event loop. These constraints are enforced at runtime, -so at compile time these are unconditionally `Sendable`. +In these contexts, users that cannot require NIO 2.77.0 can make their callbacks +safe using ``NIOLoopBound`` and ``NIOLoopBoundBox``. These values can only be +constructed on the event loop, and only allow access to their values on the same +event loop. These constraints are enforced at runtime, so at compile time these are +unconditionally `Sendable`. > Warning: ``NIOLoopBound`` and ``NIOLoopBoundBox`` replace compile-time isolation checks with runtime ones. This makes it possible to introduce crashes in your code. Please @@ -150,18 +151,43 @@ so at compile time these are unconditionally `Sendable`. ``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain before using these types. -> Note: In a future NIO release we intend to improve the ergonomics of this common problem - by offering a related type that can only be created from an ``EventLoopFuture`` on a - given ``EventLoop``. This minimises the number of runtime checks, and will make it - easier and more pleasant to write this kind of code. +From NIO 2.77.0, new types were introduced to make this common problem easier. These types are +``EventLoopFuture/Isolated`` and ``EventLoopPromise/Isolated``. These isolated view types +can only be constructed from an existing Future or Promise, and they can only be constructed +on the ``EventLoop`` to which those futures or promises are bound. Because they are not +`Sendable`, we can be confident that these values never escape the isolation domain in which +they are created, which must be the same isolation domain where the callbacks execute. + +As a result, these types can drop the `@Sendable` requirements on all the future closures, and +many of the `Sendable` requirements on the return types from future closures. They can also +drop the `Sendable` requirements from the promise completion functions. + +These isolated views can be obtained by calling ``EventLoopFuture/assumeIsolated()`` or +``EventLoopPromise/assumeIsolated()``. + +> Warning: ``EventLoopFuture/assumeIsolated()`` and ``EventLoopPromise/assumeIsolated()`` + supplement compile-time isolation checks with runtime ones. This makes it possible + to introduce crashes in your code. Please ensure that you are 100% confident that the + isolation domains align. If you are not sure that the ``EventLoopFuture`` or + ``EventLoopPromise`` you wish to attach a callback to is bound to your + ``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain + before using these types. + +> Warning: ``EventLoopFuture/assumeIsolated()`` and ``EventLoopPromise/assumeIsolated()`` + **must not** be called from a Swift concurrency context, either an async method or + from within an actor. This is because it uses runtime checking of the event loop + to confirm that the value is not being sent to a different concurrency domain. + + When using an ``EventLoop`` as a custom actor executor, this API can be used to retrieve + a value that region based isolation will then allow to be sent to another domain. ## Interacting with Event Loops on the Event Loop As with Futures, there are occasionally times where it is necessary to schedule ``EventLoop`` operations on the ``EventLoop`` where your code is currently executing. -Much like with ``EventLoopFuture``, you can use ``NIOLoopBound`` and ``NIOLoopBoundBox`` -to make these callbacks safe. +Much like with ``EventLoopFuture``, if you need to support NIO versions before 2.77.0 +you can use ``NIOLoopBound`` and ``NIOLoopBoundBox`` to make these callbacks safe. > Warning: ``NIOLoopBound`` and ``NIOLoopBoundBox`` replace compile-time isolation checks with runtime ones. This makes it possible to introduce crashes in your code. Please @@ -170,7 +196,27 @@ to make these callbacks safe. ``EventLoop``, use ``EventLoopFuture/hop(to:)`` to move it to your isolation domain before using these types. -> Note: In a future NIO release we intend to improve the ergonomics of this common problem - by offering a related type that can only be created from an ``EventLoopFuture`` on a - given ``EventLoop``. This minimises the number of runtime checks, and will make it - easier and more pleasant to write this kind of code. +From NIO 2.77.0, a new type was introduced to make this common problem easier. This type is +``NIOIsolatedEventLoop``. This isolated view type can only be constructed from an existing +``EventLoop``, and it can only be constructed on the ``EventLoop`` that is being wrapped. +Because this type is not `Sendable`, we can be confident that this value never escapes the +isolation domain in which it was created, which must be the same isolation domain where the +callbacks execute. + +As a result, this type can drop the `@Sendable` requirements on all the operation closures, and +many of the `Sendable` requirements on the return types from these closures. + +This isolated view can be obtained by calling ``EventLoop/assumeIsolated()``. + +> Warning: ``EventLoop/assumeIsolated()`` supplements compile-time isolation checks with + runtime ones. This makes it possible to introduce crashes in your code. Please ensure + that you are 100% confident that the isolation domains align. If you are not sure that + the your code is running on the relevant ``EventLoop``, prefer the non-isolated type. + +> Warning: ``EventLoop/assumeIsolated()`` **must not** be called from a Swift concurrency + context, either an async method or from within an actor. This is because it uses runtime + checking of the event loop to confirm that the value is not being sent to a different + concurrency domain. + + When using an ``EventLoop`` as a custom actor executor, this API can be used to retrieve + a value that region based isolation will then allow to be sent to another domain. diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index d2dded2cf..4748ef320 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -14,8 +14,14 @@ /// A struct wrapping an ``EventLoop`` that ensures all calls to any method on this struct /// are coming from the event loop. -@usableFromInline -struct IsolatedEventLoop { +/// +/// This type is explicitly not `Sendable`. It may only be constructed on an event loop, +/// using ``EventLoop/assumeIsolated()``, and may not subsequently be passed to other isolation +/// domains. +/// +/// Using this type relaxes the need to have the closures for ``EventLoop/execute(_:)``, +/// ``EventLoop/submit(_:)``, and ``EventLoop/scheduleTask(in:_:)`` to be `@Sendable`. +public struct NIOIsolatedEventLoop { @usableFromInline let _wrapped: EventLoop @@ -25,9 +31,9 @@ struct IsolatedEventLoop { } /// Submit a given task to be executed by the `EventLoop` + @available(*, noasync) @inlinable - func execute(_ task: @escaping () -> Void) { - self._wrapped.assertInEventLoop() + public func execute(_ task: @escaping () -> Void) { let unsafeTransfer = UnsafeTransfer(task) self._wrapped.execute { unsafeTransfer.wrappedValue() @@ -39,9 +45,9 @@ struct IsolatedEventLoop { /// - Parameters: /// - task: The closure that will be submitted to the `EventLoop` for execution. /// - Returns: `EventLoopFuture` that is notified once the task was executed. + @available(*, noasync) @inlinable - func submit(_ task: @escaping () throws -> T) -> EventLoopFuture { - self._wrapped.assertInEventLoop() + public func submit(_ task: @escaping () throws -> T) -> EventLoopFuture { let unsafeTransfer = UnsafeTransfer(task) return self._wrapped.submit { try unsafeTransfer.wrappedValue() @@ -51,18 +57,19 @@ struct IsolatedEventLoop { /// Schedule a `task` that is executed by this `EventLoop` at the given time. /// /// - Parameters: + /// - deadline: The time at which the task should run. /// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block. /// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait /// on the completion of the task. /// /// - Note: You can only cancel a task before it has started executing. @discardableResult + @available(*, noasync) @inlinable - func scheduleTask( + public func scheduleTask( deadline: NIODeadline, _ task: @escaping () throws -> T ) -> Scheduled { - self._wrapped.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(task) return self._wrapped.scheduleTask(deadline: deadline) { try unsafeTransfer.wrappedValue() @@ -72,6 +79,7 @@ struct IsolatedEventLoop { /// Schedule a `task` that is executed by this `EventLoop` after the given amount of time. /// /// - Parameters: + /// - delay: The time to wait before running the task. /// - task: The synchronous task to run. As with everything that runs on the `EventLoop`, it must not block. /// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait /// on the completion of the task. @@ -79,12 +87,12 @@ struct IsolatedEventLoop { /// - Note: You can only cancel a task before it has started executing. /// - Note: The `in` value is clamped to a maximum when running on a Darwin-kernel. @discardableResult + @available(*, noasync) @inlinable - func scheduleTask( + public func scheduleTask( in delay: TimeAmount, _ task: @escaping () throws -> T ) -> Scheduled { - self._wrapped.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(task) return self._wrapped.scheduleTask(in: delay) { try unsafeTransfer.wrappedValue() @@ -97,20 +105,23 @@ struct IsolatedEventLoop { /// this event loop might differ. /// /// - Parameters: + /// - deadline: The time at which we should run the asynchronous task. + /// - file: The file in which the task is scheduled. + /// - line: The line of the `file` in which the task is scheduled. /// - task: The asynchronous task to run. As with everything that runs on the `EventLoop`, it must not block. /// - Returns: A `Scheduled` object which may be used to cancel the task if it has not yet run, or to wait /// on the full execution of the task, including its returned `EventLoopFuture`. /// /// - Note: You can only cancel a task before it has started executing. @discardableResult + @available(*, noasync) @inlinable - func flatScheduleTask( + public func flatScheduleTask( deadline: NIODeadline, file: StaticString = #file, line: UInt = #line, _ task: @escaping () throws -> EventLoopFuture ) -> Scheduled { - self._wrapped.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(task) return self._wrapped.flatScheduleTask(deadline: deadline, file: file, line: line) { try unsafeTransfer.wrappedValue() @@ -119,26 +130,54 @@ struct IsolatedEventLoop { /// Returns the wrapped event loop. @inlinable - func nonisolated() -> any EventLoop { + public func nonisolated() -> any EventLoop { self._wrapped } } + extension EventLoop { /// Assumes the calling context is isolated to the event loop. - @usableFromInline - func assumeIsolated() -> IsolatedEventLoop { - IsolatedEventLoop(self) + @inlinable + @available(*, noasync) + public func assumeIsolated() -> NIOIsolatedEventLoop { + self.preconditionInEventLoop() + return NIOIsolatedEventLoop(self) + } + + /// Assumes the calling context is isolated to the event loop. + /// + /// This version of ``EventLoop/assumeIsolated()`` omits the runtime + /// isolation check in release builds and doesn't prevent you using it + /// from using it in async contexts. + @inlinable + public func assumeIsolatedUnsafeUnchecked() -> NIOIsolatedEventLoop { + self.assertInEventLoop() + return NIOIsolatedEventLoop(self) } } +@available(*, unavailable) +extension NIOIsolatedEventLoop: Sendable {} + extension EventLoopFuture { /// A struct wrapping an ``EventLoopFuture`` that ensures all calls to any method on this struct /// are coming from the event loop of the future. - @usableFromInline - struct Isolated { + /// + /// This type is explicitly not `Sendable`. It may only be constructed on an event loop, + /// using ``EventLoopFuture/assumeIsolated()``, and may not subsequently be passed to other isolation + /// domains. + /// + /// Using this type relaxes the need to have the closures for the various ``EventLoopFuture`` + /// callback-attaching functions be `Sendable`. + public struct Isolated { @usableFromInline let _wrapped: EventLoopFuture + @inlinable + init(_wrapped: EventLoopFuture) { + self._wrapped = _wrapped + } + /// When the current `EventLoopFuture` is fulfilled, run the provided callback, /// which will provide a new `EventLoopFuture`. /// @@ -160,6 +199,9 @@ extension EventLoopFuture { /// } /// ``` /// + /// Note that the returned ``EventLoopFuture`` still needs a `Sendable` wrapped value, + /// as it may have been created on a different event loop. + /// /// Note: In a sense, the `EventLoopFuture` is returned before it's created. /// /// - Parameters: @@ -167,14 +209,14 @@ extension EventLoopFuture { /// a new `EventLoopFuture`. /// - Returns: A future that will receive the eventual value. @inlinable - func flatMap( + @available(*, noasync) + public func flatMap( _ callback: @escaping (Value) -> EventLoopFuture ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.flatMap { unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -192,14 +234,14 @@ extension EventLoopFuture { /// a new value lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the eventual value. @inlinable - func flatMapThrowing( + @available(*, noasync) + public func flatMapThrowing( _ callback: @escaping (Value) throws -> NewValue ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.flatMapThrowing { try unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -217,14 +259,14 @@ extension EventLoopFuture { /// a new value lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the eventual value or a rethrown error. @inlinable - func flatMapErrorThrowing( + @available(*, noasync) + public func flatMapErrorThrowing( _ callback: @escaping (Error) throws -> Value ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.flatMapErrorThrowing { try unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -254,14 +296,14 @@ extension EventLoopFuture { /// a new value lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the eventual value. @inlinable - func map( + @available(*, noasync) + public func map( _ callback: @escaping (Value) -> (NewValue) ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.map { unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -279,14 +321,14 @@ extension EventLoopFuture { /// a new value lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the recovered value. @inlinable - func flatMapError( + @available(*, noasync) + public func flatMapError( _ callback: @escaping (Error) -> EventLoopFuture ) -> EventLoopFuture.Isolated where Value: Sendable { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.flatMapError { unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -303,14 +345,14 @@ extension EventLoopFuture { /// a new value or error lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the eventual value. @inlinable - func flatMapResult( + @available(*, noasync) + public func flatMapResult( _ body: @escaping (Value) -> Result ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(body) return self._wrapped.flatMapResult { unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -326,14 +368,14 @@ extension EventLoopFuture { /// a new value lifted into a new `EventLoopFuture`. /// - Returns: A future that will receive the recovered value. @inlinable - func recover( + @available(*, noasync) + public func recover( _ callback: @escaping (Error) -> Value ) -> EventLoopFuture.Isolated { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.recover { unsafeTransfer.wrappedValue($0) - }.assumeIsolated() + }.assumeIsolatedUnsafeUnchecked() } /// Adds an observer callback to this `EventLoopFuture` that is called when the @@ -347,8 +389,8 @@ extension EventLoopFuture { /// - Parameters: /// - callback: The callback that is called with the successful result of the `EventLoopFuture`. @inlinable - func whenSuccess(_ callback: @escaping (Value) -> Void) { - self._wrapped.eventLoop.assertInEventLoop() + @available(*, noasync) + public func whenSuccess(_ callback: @escaping (Value) -> Void) { let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.whenSuccess { unsafeTransfer.wrappedValue($0) @@ -366,8 +408,8 @@ extension EventLoopFuture { /// - Parameters: /// - callback: The callback that is called with the failed result of the `EventLoopFuture`. @inlinable - func whenFailure(_ callback: @escaping (Error) -> Void) { - self._wrapped.eventLoop.assertInEventLoop() + @available(*, noasync) + public func whenFailure(_ callback: @escaping (Error) -> Void) { let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.whenFailure { unsafeTransfer.wrappedValue($0) @@ -380,10 +422,10 @@ extension EventLoopFuture { /// - Parameters: /// - callback: The callback that is called when the `EventLoopFuture` is fulfilled. @inlinable - func whenComplete( + @available(*, noasync) + public func whenComplete( _ callback: @escaping (Result) -> Void ) { - self._wrapped.eventLoop.assertInEventLoop() let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.whenComplete { unsafeTransfer.wrappedValue($0) @@ -397,14 +439,14 @@ extension EventLoopFuture { /// - callback: the callback that is called when the `EventLoopFuture` is fulfilled. /// - Returns: the current `EventLoopFuture` @inlinable - func always( + @available(*, noasync) + public func always( _ callback: @escaping (Result) -> Void - ) -> EventLoopFuture { - self._wrapped.eventLoop.assertInEventLoop() + ) -> EventLoopFuture.Isolated { let unsafeTransfer = UnsafeTransfer(callback) return self._wrapped.always { unsafeTransfer.wrappedValue($0) - } + }.assumeIsolatedUnsafeUnchecked() } /// Unwrap an `EventLoopFuture` where its type parameter is an `Optional`. @@ -416,10 +458,11 @@ extension EventLoopFuture { /// ``` /// /// - Parameters: - /// - orReplace: the value of the returned `EventLoopFuture` when then resolved future's value is `Optional.some()`. + /// - replacement: the value of the returned `EventLoopFuture` when then resolved future's value is `Optional.some()`. /// - Returns: an new `EventLoopFuture` with new type parameter `NewValue` and the value passed in the `orReplace` parameter. @inlinable - func unwrap( + @available(*, noasync) + public func unwrap( orReplace replacement: NewValue ) -> EventLoopFuture.Isolated where Value == NewValue? { self.map { (value) -> NewValue in @@ -440,12 +483,13 @@ extension EventLoopFuture { /// ``` /// /// - Parameters: - /// - orElse: a closure that returns the value of the returned `EventLoopFuture` when then resolved future's value + /// - callback: a closure that returns the value of the returned `EventLoopFuture` when then resolved future's value /// is `Optional.some()`. /// - Returns: an new `EventLoopFuture` with new type parameter `NewValue` and with the value returned by the closure /// passed in the `orElse` parameter. @inlinable - func unwrap( + @available(*, noasync) + public func unwrap( orElse callback: @escaping () -> NewValue ) -> EventLoopFuture.Isolated where Value == NewValue? { self.map { (value) -> NewValue in @@ -458,34 +502,73 @@ extension EventLoopFuture { /// Returns the wrapped event loop future. @inlinable - func nonisolated() -> EventLoopFuture { + public func nonisolated() -> EventLoopFuture { self._wrapped } } - /// Assumes the calling context is isolated to the future's event loop. - @usableFromInline - func assumeIsolated() -> Isolated { + /// Returns a variant of this ``EventLoopFuture`` with less strict + /// `Sendable` requirements. Can only be called from on the + /// ``EventLoop`` to which this ``EventLoopFuture`` is bound, will crash + /// if that invariant fails to be met. + @inlinable + @available(*, noasync) + public func assumeIsolated() -> Isolated { + self.eventLoop.preconditionInEventLoop() + return Isolated(_wrapped: self) + } + + /// Returns a variant of this ``EventLoopFuture`` with less strict + /// `Sendable` requirements. Can only be called from on the + /// ``EventLoop`` to which this ``EventLoopFuture`` is bound, will crash + /// if that invariant fails to be met. + /// + /// This is an unsafe version of ``EventLoopFuture/assumeIsolated()`` which + /// omits the runtime check in release builds and doesn't prevent you using it + /// from using it in async contexts. + @inlinable + @available(*, noasync) + public func assumeIsolatedUnsafeUnchecked() -> Isolated { self.eventLoop.assertInEventLoop() return Isolated(_wrapped: self) } } +@available(*, unavailable) +extension EventLoopFuture.Isolated: Sendable {} + extension EventLoopPromise { /// A struct wrapping an ``EventLoopPromise`` that ensures all calls to any method on this struct /// are coming from the event loop of the promise. - @usableFromInline - struct Isolated { + /// + /// This type is explicitly not `Sendable`. It may only be constructed on an event loop, + /// using ``EventLoopPromise/assumeIsolated()``, and may not subsequently be passed to other isolation + /// domains. + /// + /// Using this type relaxes the need to have the promise completion functions accept `Sendable` + /// values, as this type can only be handled on the ``EventLoop``. + /// + /// This type does not offer the full suite of completion functions that ``EventLoopPromise`` + /// does, as many of those functions do not require `Sendable` values already. It only offers + /// versions for the functions that do require `Sendable` types. If you have an + /// ``EventLoopPromise/Isolated`` but need a regular ``EventLoopPromise``, use + /// ``EventLoopPromise/Isolated/nonisolated()`` to unwrap the value. + public struct Isolated { @usableFromInline let _wrapped: EventLoopPromise + @inlinable + init(_wrapped: EventLoopPromise) { + self._wrapped = _wrapped + } + /// Deliver a successful result to the associated `EventLoopFuture` object. /// /// - Parameters: /// - value: The successful result of the operation. @inlinable - func succeed(_ value: Value) { - self._wrapped.futureResult.eventLoop.assertInEventLoop() + @available(*, noasync) + public func succeed(_ value: Value) { self._wrapped._setValue(value: .success(value))._run() } @@ -504,22 +587,43 @@ extension EventLoopPromise { /// - Parameters: /// - result: The result which will be used to succeed or fail this promise. @inlinable - func completeWith(_ result: Result) { - self._wrapped.futureResult.eventLoop.assertInEventLoop() + @available(*, noasync) + public func completeWith(_ result: Result) { self._wrapped._setValue(value: result)._run() } /// Returns the wrapped event loop promise. @inlinable - func nonisolated() -> EventLoopPromise { + public func nonisolated() -> EventLoopPromise { self._wrapped } } - /// Assumes the calling context is isolated to the promise's event loop. - @usableFromInline - func assumeIsolated() -> Isolated { + /// Returns a variant of this ``EventLoopPromise`` with less strict + /// `Sendable` requirements. Can only be called from on the + /// ``EventLoop`` to which this ``EventLoopPromise`` is bound, will crash + /// if that invariant fails to be met. + @inlinable + @available(*, noasync) + public func assumeIsolated() -> Isolated { + self.futureResult.eventLoop.preconditionInEventLoop() + return Isolated(_wrapped: self) + } + + /// Returns a variant of this ``EventLoopPromise`` with less strict + /// `Sendable` requirements. Can only be called from on the + /// ``EventLoop`` to which this ``EventLoopPromise`` is bound, will crash + /// if that invariant fails to be met. + /// + /// This is an unsafe version of ``EventLoopPromise/assumeIsolated()`` which + /// omits the runtime check in release builds and doesn't prevent you using it + /// from using it in async contexts. + @inlinable + public func assumeIsolatedUnsafeUnchecked() -> Isolated { self.futureResult.eventLoop.assertInEventLoop() return Isolated(_wrapped: self) } } + +@available(*, unavailable) +extension EventLoopPromise.Isolated: Sendable {} diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index 70148c416..fed89fc1a 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -304,6 +304,16 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { } #endif + public func preconditionInEventLoop(file: StaticString, line: UInt) { + self.checkCorrectThread() + // Currently, inEventLoop is always true so this always passes. + } + + public func preconditionNotInEventLoop(file: StaticString, line: UInt) { + // As inEventLoop always returns true, this must always preconditon. + preconditionFailure("Always in EmbeddedEventLoop", file: file, line: line) + } + public func _preconditionSafeToWait(file: StaticString, line: UInt) { self.checkCorrectThread() // EmbeddedEventLoop always allows a wait, as waiting will essentially always block diff --git a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift new file mode 100644 index 000000000..2388c2823 --- /dev/null +++ b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift @@ -0,0 +1,318 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore +import NIOPosix +import XCTest + +final class SuperNotSendable { + var x: Int = 5 +} + +@available(*, unavailable) +extension SuperNotSendable: Sendable {} + +final class EventLoopFutureIsolatedTest: XCTestCase { + func testCompletingPromiseWithNonSendableValue() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolated().succeed(value) + return promise.futureResult.assumeIsolated().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + }.wait() + } + + func testCompletingPromiseWithNonSendableResult() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolated().completeWith(.success(value)) + return promise.futureResult.assumeIsolated().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + }.wait() + } + + func testCompletingPromiseWithNonSendableValueUnchecked() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolatedUnsafeUnchecked().succeed(value) + return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + }.wait() + } + + func testCompletingPromiseWithNonSendableResultUnchecked() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let value = SuperNotSendable() + promise.assumeIsolatedUnsafeUnchecked().completeWith(.success(value)) + return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in + XCTAssertIdentical(val, value) + }.nonisolated() + }.wait() + } + + func testBackAndForthUnwrapping() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.submit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult + + XCTAssertEqual(promise.assumeIsolated().nonisolated(), promise) + XCTAssertEqual(future.assumeIsolated().nonisolated(), future) + promise.assumeIsolated().succeed(SuperNotSendable()) + }.wait() + } + + func testBackAndForthUnwrappingUnchecked() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.submit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult + + XCTAssertEqual(promise.assumeIsolatedUnsafeUnchecked().nonisolated(), promise) + XCTAssertEqual(future.assumeIsolatedUnsafeUnchecked().nonisolated(), future) + promise.assumeIsolated().succeed(SuperNotSendable()) + }.wait() + } + + func testFutureChaining() throws { + enum TestError: Error { + case error + } + + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + try loop.flatSubmit { + let promise = loop.makePromise(of: SuperNotSendable.self) + let future = promise.futureResult.assumeIsolated() + let originalValue = SuperNotSendable() + + // Note that for this test it is _very important_ that all of these + // close over `originalValue`. This proves the non-Sendability of + // the closure. + + // This block is the main happy path. + let newFuture = future.flatMap { result in + XCTAssertIdentical(originalValue, result) + let promise = loop.makePromise(of: Int.self) + promise.succeed(4) + return promise.futureResult + }.map { (result: Int) in + XCTAssertEqual(result, 4) + return originalValue + }.flatMapThrowing { (result: SuperNotSendable) in + XCTAssertIdentical(originalValue, result) + return SuperNotSendable() + }.flatMapResult { (result: SuperNotSendable) -> Result in + XCTAssertNotIdentical(originalValue, result) + return .failure(TestError.error) + }.recover { err in + XCTAssertTrue(err is TestError) + return originalValue + }.always { val in + XCTAssertNotNil(try? val.get()) + } + + newFuture.whenComplete { result in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertIdentical(r, originalValue) + } + newFuture.whenSuccess { result in + XCTAssertIdentical(result, originalValue) + } + + // This block covers the flatMapError and whenFailure tests + let throwingFuture = newFuture.flatMapThrowing { (_: SuperNotSendable) throws -> SuperNotSendable in + XCTAssertEqual(originalValue.x, 5) + throw TestError.error + } + throwingFuture.whenFailure { error in + // Supurious but forces the closure. + XCTAssertEqual(originalValue.x, 5) + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + return + } + } + throwingFuture.flatMapErrorThrowing { error in + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + throw error + } + return originalValue + }.whenComplete { result in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertIdentical(r, originalValue) + } + throwingFuture.map { _ in 5 }.flatMapError { (error: any Error) -> EventLoopFuture in + guard let error = error as? TestError, error == .error else { + XCTFail("Invalid passed error: \(error)") + return loop.makeSucceededFuture(originalValue.x) + } + return loop.makeSucceededFuture(originalValue.x - 1) + }.whenComplete { (result: Result) in + guard case .success(let r) = result else { + XCTFail("Unexpected error") + return + } + XCTAssertEqual(r, originalValue.x - 1) + } + + // This block handles unwrap. + newFuture.map { x -> SuperNotSendable? in + XCTAssertEqual(originalValue.x, 5) + return nil + }.unwrap(orReplace: originalValue).unwrap( + orReplace: SuperNotSendable() + ).map { x -> SuperNotSendable? in + XCTAssertIdentical(x, originalValue) + return nil + }.unwrap(orElse: { + originalValue + }).unwrap(orElse: { + SuperNotSendable() + }).whenSuccess { x in + XCTAssertIdentical(x, originalValue) + } + + promise.assumeIsolated().succeed(originalValue) + return newFuture.map { _ in }.nonisolated() + }.wait() + } + + func testEventLoopIsolated() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + let result: Int = try loop.flatSubmit { + let value = SuperNotSendable() + + // Again, all of these need to close over value. In addition, + // many need to return it as well. + let isolated = loop.assumeIsolated() + XCTAssertIdentical(isolated.nonisolated(), loop) + isolated.execute { + XCTAssertEqual(value.x, 5) + } + let firstFuture = isolated.submit { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.map { $0.x } + + let secondFuture = isolated.scheduleTask(deadline: .now() + .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let thirdFuture = isolated.scheduleTask(in: .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let fourthFuture = isolated.flatScheduleTask(deadline: .now() + .milliseconds(50)) { + let promise = loop.makePromise(of: Int.self) + promise.succeed(value.x + 1) + return promise.futureResult + }.futureResult.map { $0 } + + return EventLoopFuture.reduce( + into: 0, + [firstFuture, secondFuture, thirdFuture, fourthFuture], + on: loop + ) { $0 += $1 } + }.wait() + + XCTAssertEqual(result, 6 * 4) + } + + func testEventLoopIsolatedUnchecked() throws { + let group = MultiThreadedEventLoopGroup.singleton + let loop = group.next() + + let result: Int = try loop.flatSubmit { + let value = SuperNotSendable() + + // Again, all of these need to close over value. In addition, + // many need to return it as well. + let isolated = loop.assumeIsolatedUnsafeUnchecked() + XCTAssertIdentical(isolated.nonisolated(), loop) + isolated.execute { + XCTAssertEqual(value.x, 5) + } + let firstFuture = isolated.submit { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.map { $0.x } + + let secondFuture = isolated.scheduleTask(deadline: .now() + .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let thirdFuture = isolated.scheduleTask(in: .milliseconds(50)) { + let val = SuperNotSendable() + val.x = value.x + 1 + return val + }.futureResult.map { $0.x } + + let fourthFuture = isolated.flatScheduleTask(deadline: .now() + .milliseconds(50)) { + let promise = loop.makePromise(of: Int.self) + promise.succeed(value.x + 1) + return promise.futureResult + }.futureResult.map { $0 } + + return EventLoopFuture.reduce( + into: 0, + [firstFuture, secondFuture, thirdFuture, fourthFuture], + on: loop + ) { $0 += $1 } + }.wait() + + XCTAssertEqual(result, 6 * 4) + } +} From 1a3229b9fc43fb5a5b6ffcfd100fadc06f0df9dd Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 16 Dec 2024 17:53:38 +0000 Subject: [PATCH 27/93] Fix now-racy scheduled callback tests (#3031) Motivation: In PR 3026 we I fixed some warnings, but as part of doing so I eliminated some complexity in the scheduled callback tests. Apparently I did that a bit hard, as I lost a few synchronization edges that made the tests lightly flaky. Modifications: - Re-add synchronization edges between the EL and the test when we advance time - Re-add synchronization edges after cancellation calls. Result: More reliable tests --- .../NIOScheduledCallbackTests.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift index 9940b74e1..16dc984ac 100644 --- a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift +++ b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift @@ -27,6 +27,8 @@ protocol ScheduledCallbackTestRequirements { // ELG-backed ELs need to be shutdown via the ELG. func shutdownEventLoop() async throws + + func waitForLoopTick() async throws } final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { @@ -41,6 +43,10 @@ final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { func shutdownEventLoop() async throws { try await self.group.shutdownGracefully() } + + func waitForLoopTick() async throws { + try await self.loop.submit {}.get() + } } override func setUp() async throws { @@ -60,6 +66,10 @@ final class NIOAsyncTestingEventLoopScheduledCallbackTests: _BaseScheduledCallba func shutdownEventLoop() async throws { await self._loop.shutdownGracefully() } + + func waitForLoopTick() async throws { + try await self._loop.executeInContext {} + } } override func setUp() async throws { @@ -83,6 +93,7 @@ extension _BaseScheduledCallbackTests { func advanceTime(by amount: TimeAmount) async throws { try await self.requirements.advanceTime(by: amount) + try await self.requirements.waitForLoopTick() } func shutdownEventLoop() async throws { @@ -151,6 +162,7 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() + try await self.requirements.waitForLoopTick() handler.assert(callbackCount: 0, cancelCount: 1) } @@ -161,6 +173,7 @@ extension _BaseScheduledCallbackTests { try await self.advanceTime(by: .milliseconds(1)) try await handler.waitForCallback(timeout: .seconds(1)) scheduledCallback.cancel() + try await self.requirements.waitForLoopTick() handler.assert(callbackCount: 1, cancelCount: 0) } @@ -169,7 +182,9 @@ extension _BaseScheduledCallbackTests { let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) scheduledCallback.cancel() + try await self.requirements.waitForLoopTick() scheduledCallback.cancel() + try await self.requirements.waitForLoopTick() handler.assert(callbackCount: 0, cancelCount: 1) } @@ -197,6 +212,7 @@ extension _BaseScheduledCallbackTests { let handle = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) handle.cancel() + try await self.requirements.waitForLoopTick() handler.assert(callbackCount: 0, cancelCount: 1) try await self.shutdownEventLoop() From 2d72ada99957e8aa19245ccd013f55790be781d9 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 17 Dec 2024 09:49:06 +0000 Subject: [PATCH 28/93] Get NIOEmbedded clean under strict concurrency (#3030) Motivation: NIOEmbedded is used all over NIO-land for testing various pieces of the infrastructure, and so requires a substantial audit for strict concurrency. Modifications: - Mark a few things Sendable. - Fix the tests, which actually did have some nasty bugs Result: Sendable-clean NIOEmbedded --- .../tests_04_performance/Thresholds/5.10.json | 6 +- .../tests_04_performance/Thresholds/5.9.json | 6 +- .../tests_04_performance/Thresholds/6.0.json | 6 +- .../Thresholds/nightly-6.0.json | 6 +- .../Thresholds/nightly-main.json | 14 ++--- Package.swift | 6 +- Sources/NIOEmbedded/AsyncTestingChannel.swift | 62 +++++++++++-------- .../NIOEmbedded/AsyncTestingEventLoop.swift | 23 +++++-- Sources/NIOEmbedded/Embedded.swift | 50 +++++++++++++-- .../AsyncTestingChannelTests.swift | 2 +- .../AsyncTestingEventLoopTests.swift | 57 +++++++++-------- .../EmbeddedChannelTest.swift | 56 +++++++++++------ .../EmbeddedEventLoopTest.swift | 43 +++++++------ Tests/NIOEmbeddedTests/TestUtils.swift | 15 +++-- 14 files changed, 224 insertions(+), 128 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index 9f75ed151..c3fc7078e 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -1,8 +1,8 @@ { "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 43050, - "1000_addHandlers_sync": 36050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,7 +11,7 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 34, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index 2edeea7c8..b9e6d8faa 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -1,8 +1,8 @@ { "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 43050, - "1000_addHandlers_sync": 36050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,7 +11,7 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 34, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, "1000_rst_connections": 147050, "1000_tcpbootstraps": 4050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index 9f75ed151..c3fc7078e 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -1,8 +1,8 @@ { "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 43050, - "1000_addHandlers_sync": 36050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,7 +11,7 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 34, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index 9f75ed151..c3fc7078e 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -1,8 +1,8 @@ { "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 43050, - "1000_addHandlers_sync": 36050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,7 +11,7 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 34, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 9f75ed151..f75dbda93 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -1,8 +1,8 @@ { "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 43050, - "1000_addHandlers_sync": 36050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,7 +11,7 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 34, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, @@ -34,10 +34,10 @@ "execute_hop_10000_tasks": 0, "future_erase_result": 4050, "future_lots_of_callbacks": 53050, - "get_100000_headers_canonical_form": 700050, - "get_100000_headers_canonical_form_trimming_whitespace": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, + "get_100000_headers_canonical_form": 500050, + "get_100000_headers_canonical_form_trimming_whitespace": 500050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 500050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 500050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 319, diff --git a/Package.swift b/Package.swift index 021ebf8e5..1b63eae19 100644 --- a/Package.swift +++ b/Package.swift @@ -105,7 +105,8 @@ let package = Package( "_NIODataStructures", swiftAtomics, swiftCollections, - ] + ], + swiftSettings: strictConcurrencySettings ), .target( name: "NIOPosix", @@ -429,7 +430,8 @@ let package = Package( "NIOConcurrencyHelpers", "NIOCore", "NIOEmbedded", - ] + ], + swiftSettings: strictConcurrencySettings ), .testTarget( name: "NIOPosixTests", diff --git a/Sources/NIOEmbedded/AsyncTestingChannel.swift b/Sources/NIOEmbedded/AsyncTestingChannel.swift index 75889e5c3..d3a4834f7 100644 --- a/Sources/NIOEmbedded/AsyncTestingChannel.swift +++ b/Sources/NIOEmbedded/AsyncTestingChannel.swift @@ -199,24 +199,28 @@ public final class NIOAsyncTestingChannel: Channel { /// `nil` because ``NIOAsyncTestingChannel``s don't have parents. public let parent: Channel? = nil - // This is only written once, from a single thread, and never written again, so it's _technically_ thread-safe. Most methods cannot safely + // These two variables are only written once, from a single thread, and never written again, so they're _technically_ thread-safe. Most methods cannot safely // be used from multiple threads, but `isActive`, `isOpen`, `eventLoop`, and `closeFuture` can all safely be used from any thread. Just. + #if compiler(>=5.10) + @usableFromInline + nonisolated(unsafe) var channelcore: EmbeddedChannelCore! + nonisolated(unsafe) private var _pipeline: ChannelPipeline! + #else @usableFromInline var channelcore: EmbeddedChannelCore! + private var _pipeline: ChannelPipeline! + #endif + + private struct State { + var isWritable: Bool + var localAddress: SocketAddress? + var remoteAddress: SocketAddress? + } /// Guards any of the getters/setters that can be accessed from any thread. - private let stateLock: NIOLock = NIOLock() - - // Guarded by `stateLock` - private var _isWritable: Bool = true - - // Guarded by `stateLock` - private var _localAddress: SocketAddress? = nil - - // Guarded by `stateLock` - private var _remoteAddress: SocketAddress? = nil - - private var _pipeline: ChannelPipeline! + private let stateLock = NIOLockedValueBox( + State(isWritable: true, localAddress: nil, remoteAddress: nil) + ) /// - see: `Channel._channelCore` public var _channelCore: ChannelCore { @@ -231,11 +235,11 @@ public final class NIOAsyncTestingChannel: Channel { /// - see: `Channel.isWritable` public var isWritable: Bool { get { - self.stateLock.withLock { self._isWritable } + self.stateLock.withLockedValue { $0.isWritable } } set { - self.stateLock.withLock { () -> Void in - self._isWritable = newValue + self.stateLock.withLockedValue { + $0.isWritable = newValue } } } @@ -243,11 +247,11 @@ public final class NIOAsyncTestingChannel: Channel { /// - see: `Channel.localAddress` public var localAddress: SocketAddress? { get { - self.stateLock.withLock { self._localAddress } + self.stateLock.withLockedValue { $0.localAddress } } set { - self.stateLock.withLock { () -> Void in - self._localAddress = newValue + self.stateLock.withLockedValue { + $0.localAddress = newValue } } } @@ -255,11 +259,11 @@ public final class NIOAsyncTestingChannel: Channel { /// - see: `Channel.remoteAddress` public var remoteAddress: SocketAddress? { get { - self.stateLock.withLock { self._remoteAddress } + self.stateLock.withLockedValue { $0.remoteAddress } } set { - self.stateLock.withLock { () -> Void in - self._remoteAddress = newValue + self.stateLock.withLockedValue { + $0.remoteAddress = newValue } } } @@ -283,8 +287,11 @@ public final class NIOAsyncTestingChannel: Channel { /// - Parameters: /// - handler: The `ChannelHandler` to add to the `ChannelPipeline` before register. /// - loop: The ``NIOAsyncTestingEventLoop`` to use. - public convenience init(handler: ChannelHandler, loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop()) async - { + @preconcurrency + public convenience init( + handler: ChannelHandler & Sendable, + loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop() + ) async { await self.init(handlers: [handler], loop: loop) } @@ -295,8 +302,9 @@ public final class NIOAsyncTestingChannel: Channel { /// - Parameters: /// - handlers: The `ChannelHandler`s to add to the `ChannelPipeline` before register. /// - loop: The ``NIOAsyncTestingEventLoop`` to use. + @preconcurrency public convenience init( - handlers: [ChannelHandler], + handlers: [ChannelHandler & Sendable], loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop() ) async { self.init(loop: loop) @@ -671,3 +679,7 @@ extension NIOAsyncTestingChannel.LeftOverState: @unchecked Sendable {} @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension NIOAsyncTestingChannel.BufferState: @unchecked Sendable {} #endif + +// Synchronous options are never Sendable. +@available(*, unavailable) +extension NIOAsyncTestingChannel.SynchronousOptions: Sendable {} diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 7997d38e3..3321a6a60 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -14,7 +14,13 @@ #if canImport(Dispatch) import Atomics + +#if canImport(Darwin) import Dispatch +#else +@preconcurrency import Dispatch +#endif + import NIOConcurrencyHelpers import NIOCore import _NIODataStructures @@ -125,7 +131,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { self.scheduledTasks.removeFirst { $0.id == taskID } } - private func insertTask( + private func insertTask( taskID: UInt64, deadline: NIODeadline, promise: EventLoopPromise, @@ -152,7 +158,11 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// - see: `EventLoop.scheduleTask(deadline:_:)` @discardableResult - public func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { + @preconcurrency + public func scheduleTask( + deadline: NIODeadline, + _ task: @escaping @Sendable () throws -> T + ) -> Scheduled { let promise: EventLoopPromise = self.makePromise() let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) @@ -190,7 +200,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// - see: `EventLoop.scheduleTask(in:_:)` @discardableResult - public func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { + @preconcurrency + public func scheduleTask(in: TimeAmount, _ task: @escaping @Sendable () throws -> T) -> Scheduled { self.scheduleTask(deadline: self.now + `in`, task) } @@ -230,7 +241,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// On an `NIOAsyncTestingEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. Unlike with the other operations, this will /// immediately execute, to eliminate a common class of bugs. - public func execute(_ task: @escaping () -> Void) { + @preconcurrency + public func execute(_ task: @escaping @Sendable () -> Void) { if self.inEventLoop { self.scheduleTask(deadline: self.now, task) } else { @@ -359,7 +371,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { } /// - see: `EventLoop.shutdownGracefully` - public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + @preconcurrency + public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) { self.queue.async { self._shutdownGracefully() queue.async { diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index fed89fc1a..865a97c88 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -36,6 +36,22 @@ import WASILibc #error("Unknown C library.") #endif +private func printError(_ string: StaticString) { + string.withUTF8Buffer { buf in + var buf = buf + while buf.count > 0 { + // 2 is stderr + let rc = write(2, buf.baseAddress, buf.count) + if rc < 0 { + let err = errno + if err == EINTR { continue } + fatalError("Unexpected error writing: \(err)") + } + buf = .init(rebasing: buf.dropFirst(Int(rc))) + } + } +} + internal struct EmbeddedScheduledTask { let id: UInt64 let task: () -> Void @@ -146,14 +162,13 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { "EmbeddedEventLoop is not thread-safe. You can only use it from the thread you created it on." ) } else { - fputs( + printError( """ ERROR: NIO API misuse: EmbeddedEventLoop is not thread-safe. \ You can only use it from the thread you created it on. This problem will be upgraded to a forced \ crash in future versions of SwiftNIO. - """, - stderr + """ ) } return @@ -185,7 +200,7 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { insertOrder: self.nextTaskNumber(), task: { do { - promise.succeed(try task()) + promise.assumeIsolated().succeed(try task()) } catch let err { promise.fail(err) } @@ -365,6 +380,11 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { }() } +// EmbeddedEventLoop is extremely _not_ Sendable. However, the EventLoop protocol +// requires it to be. We are doing some runtime enforcement of correct use, but +// ultimately we can't have the compiler validating this usage. +extension EmbeddedEventLoop: @unchecked Sendable {} + @usableFromInline class EmbeddedChannelCore: ChannelCore { var isOpen: Bool { @@ -484,8 +504,11 @@ class EmbeddedChannelCore: ChannelCore { self.pipeline.syncOperations.fireChannelInactive() self.pipeline.syncOperations.fireChannelUnregistered() + let loopBoundSelf = NIOLoopBound(self, eventLoop: self.eventLoop) + eventLoop.execute { // ensure this is executed in a delayed fashion as the users code may still traverse the pipeline + let `self` = loopBoundSelf.value self.removeHandlers(pipeline: self.pipeline) self.closePromise.succeed(()) } @@ -583,6 +606,10 @@ class EmbeddedChannelCore: ChannelCore { } } +// ChannelCores are basically never Sendable. +@available(*, unavailable) +extension EmbeddedChannelCore: Sendable {} + /// `EmbeddedChannel` is a `Channel` implementation that does neither any /// actual IO nor has a proper eventing mechanism. The prime use-case for /// `EmbeddedChannel` is in unit tests when you want to feed the inbound events @@ -867,8 +894,8 @@ public final class EmbeddedChannel: Channel { @inlinable @discardableResult public func writeInbound(_ data: T) throws -> BufferState { self.embeddedEventLoop.checkCorrectThread() - self.pipeline.fireChannelRead(data) - self.pipeline.fireChannelReadComplete() + self.pipeline.syncOperations.fireChannelRead(NIOAny(data)) + self.pipeline.syncOperations.fireChannelReadComplete() try self.throwIfErrorCaught() return self.channelcore.inboundBuffer.isEmpty ? .empty : .full(Array(self.channelcore.inboundBuffer)) } @@ -1086,5 +1113,16 @@ extension EmbeddedChannel { } } +// EmbeddedChannel is extremely _not_ Sendable. However, the Channel protocol +// requires it to be. We are doing some runtime enforcement of correct use, but +// ultimately we can't have the compiler validating this usage. +extension EmbeddedChannel: @unchecked Sendable {} + +@available(*, unavailable) +extension EmbeddedChannel.LeftOverState: @unchecked Sendable {} + +@available(*, unavailable) +extension EmbeddedChannel.BufferState: @unchecked Sendable {} + @available(*, unavailable) extension EmbeddedChannel.SynchronousOptions: Sendable {} diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index 5fa112f6d..5022dcd3c 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -36,7 +36,7 @@ class AsyncTestingChannelTests: XCTestCase { } let channel = NIOAsyncTestingChannel() - XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).wait()) { e in + XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) { e in XCTAssertEqual(e as? ChannelPipelineError, .notFound) } diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index 66c40c741..86920495f 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -19,7 +19,7 @@ import XCTest @testable import NIOEmbedded -private class EmbeddedTestError: Error {} +private final class EmbeddedTestError: Error {} @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) final class NIOAsyncTestingEventLoopTests: XCTestCase { @@ -336,10 +336,12 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // advanceTime(by:) is the same as on MultiThreadedEventLoopGroup: specifically, that tasks run via // schedule that expire "now" all run at the same time, and that any work they schedule is run // after all such tasks expire. + struct TestState { + var firstScheduled: Scheduled? + var secondScheduled: Scheduled? + } let loop = NIOAsyncTestingEventLoop() - let lock = NIOLock() - var firstScheduled: Scheduled? = nil - var secondScheduled: Scheduled? = nil + let lock = NIOLockedValueBox(TestState()) let orderingCounter = ManagedAtomic(0) // Here's the setup. First, we'll set up two scheduled tasks to fire in 5 nanoseconds. Each of these @@ -356,13 +358,13 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // // To validate the ordering, we'll use a counter. - lock.withLock { () -> Void in - firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - let second = lock.withLock { () -> Scheduled? in - XCTAssertNotNil(firstScheduled) - firstScheduled = nil - XCTAssertNotNil(secondScheduled) - return secondScheduled + lock.withLockedValue { + $0.firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + let second = lock.withLockedValue { + XCTAssertNotNil($0.firstScheduled) + $0.firstScheduled = nil + XCTAssertNotNil($0.secondScheduled) + return $0.secondScheduled } if let partner = second { @@ -379,11 +381,11 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } } - secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - lock.withLock { () -> Void in - secondScheduled = nil - XCTAssertNil(firstScheduled) - XCTAssertNil(secondScheduled) + $0.secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + lock.withLockedValue { + $0.secondScheduled = nil + XCTAssertNil($0.firstScheduled) + XCTAssertNil($0.secondScheduled) } XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 2, desired: 3) @@ -482,6 +484,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { let eventLoop = NIOAsyncTestingEventLoop() let tasksRun = ManagedAtomic(0) + @Sendable func scheduleRecursiveTask( at taskStartTime: NIODeadline, andChildTaskAfter childTaskStartDelay: TimeAmount @@ -514,29 +517,33 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { func testShutdownCancelsRemainingScheduledTasks() async { let eventLoop = NIOAsyncTestingEventLoop() - var tasksRun = 0 + let tasksRun = ManagedAtomic(0) - let a = eventLoop.scheduleTask(in: .seconds(1)) { tasksRun += 1 } - let b = eventLoop.scheduleTask(in: .seconds(2)) { tasksRun += 1 } + let a = eventLoop.scheduleTask(in: .seconds(1)) { + tasksRun.wrappingIncrement(ordering: .sequentiallyConsistent) + } + let b = eventLoop.scheduleTask(in: .seconds(2)) { + tasksRun.wrappingIncrement(ordering: .sequentiallyConsistent) + } - XCTAssertEqual(tasksRun, 0) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 0) await eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) XCTAssertNoThrow(try eventLoop.syncShutdownGracefully()) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) await eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) await eventLoop.advanceTime(to: .distantFuture) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) XCTAssertNoThrow(try a.futureResult.wait()) await XCTAssertThrowsError(try await b.futureResult.get()) { error in XCTAssertEqual(error as? EventLoopError, .cancelled) - XCTAssertEqual(tasksRun, 1) + XCTAssertEqual(tasksRun.load(ordering: .sequentiallyConsistent), 1) } } diff --git a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift index 3c77ca624..3b48ed3b3 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift @@ -12,12 +12,14 @@ // //===----------------------------------------------------------------------===// +import Atomics +import NIOConcurrencyHelpers import NIOCore import XCTest @testable import NIOEmbedded -class ChannelLifecycleHandler: ChannelInboundHandler { +final class ChannelLifecycleHandler: ChannelInboundHandler, Sendable { public typealias InboundIn = Any public enum ChannelState { @@ -27,17 +29,28 @@ class ChannelLifecycleHandler: ChannelInboundHandler { case active } - public var currentState: ChannelState - public var stateHistory: [ChannelState] + public var currentState: ChannelState { + get { + self._state.withLockedValue { $0.currentState } + } + } + public var stateHistory: [ChannelState] { + get { + self._state.withLockedValue { $0.stateHistory } + } + } + + private let _state: NIOLockedValueBox<(currentState: ChannelState, stateHistory: [ChannelState])> public init() { - currentState = .unregistered - stateHistory = [.unregistered] + self._state = NIOLockedValueBox((currentState: .unregistered, stateHistory: [.unregistered])) } private func updateState(_ state: ChannelState) { - currentState = state - stateHistory.append(state) + self._state.withLockedValue { + $0.currentState = state + $0.stateHistory.append(state) + } } public func channelRegistered(context: ChannelHandlerContext) { @@ -77,7 +90,7 @@ class EmbeddedChannelTest: XCTestCase { } let channel = EmbeddedChannel(handler: Handler()) - XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) + XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) } func testSingleHandlerInitNil() { @@ -86,7 +99,7 @@ class EmbeddedChannelTest: XCTestCase { } let channel = EmbeddedChannel(handler: nil) - XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).wait()) { e in + XCTAssertThrowsError(try channel.pipeline.handler(type: Handler.self).map { _ in }.wait()) { e in XCTAssertEqual(e as? ChannelPipelineError, .notFound) } } @@ -104,13 +117,19 @@ class EmbeddedChannelTest: XCTestCase { let channel = EmbeddedChannel( handlers: [Handler(identifier: "0"), Handler(identifier: "1"), Handler(identifier: "2")] ) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "0")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "0") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler0").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "1")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "1") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler1").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "2")) + XCTAssertNoThrow( + XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).map { $0.identifier }.wait(), "2") + ) XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) } @@ -180,7 +199,7 @@ class EmbeddedChannelTest: XCTestCase { func testWriteInboundByteBufferReThrow() { let channel = EmbeddedChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingInboundHandler()).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ExceptionThrowingInboundHandler())) XCTAssertThrowsError(try channel.writeInbound("msg")) { error in XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) } @@ -189,7 +208,7 @@ class EmbeddedChannelTest: XCTestCase { func testWriteOutboundByteBufferReThrow() { let channel = EmbeddedChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingOutboundHandler()).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ExceptionThrowingOutboundHandler())) XCTAssertThrowsError(try channel.writeOutbound("msg")) { error in XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) } @@ -323,7 +342,7 @@ class EmbeddedChannelTest: XCTestCase { func testCloseOnInactiveIsOk() throws { let channel = EmbeddedChannel() let inactiveHandler = CloseInChannelInactiveHandler() - XCTAssertNoThrow(try channel.pipeline.addHandler(inactiveHandler).wait()) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(inactiveHandler)) XCTAssertTrue(try channel.finish().isClean) // channelInactive should fire only once. @@ -479,11 +498,12 @@ class EmbeddedChannelTest: XCTestCase { func testFinishWithRecursivelyScheduledTasks() throws { let channel = EmbeddedChannel() let tasks: NIOLoopBoundBox<[Scheduled]> = NIOLoopBoundBox([], eventLoop: channel.eventLoop) - var invocations = 0 + let invocations = ManagedAtomic(0) + @Sendable func recursivelyScheduleAndIncrement() { let task = channel.pipeline.eventLoop.scheduleTask(deadline: .distantFuture) { - invocations += 1 + invocations.wrappingIncrement(ordering: .sequentiallyConsistent) recursivelyScheduleAndIncrement() } tasks.value.append(task) @@ -494,7 +514,7 @@ class EmbeddedChannelTest: XCTestCase { try XCTAssertNoThrow(channel.finish()) // None of the tasks should have been executed, they were scheduled for distant future. - XCTAssertEqual(invocations, 0) + XCTAssertEqual(invocations.load(ordering: .sequentiallyConsistent), 0) // Because the root task didn't run, it should be the onnly one scheduled. XCTAssertEqual(tasks.value.count, 1) diff --git a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift index b1690f7f8..989bef581 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedEventLoopTest.swift @@ -12,13 +12,14 @@ // //===----------------------------------------------------------------------===// +import Atomics import NIOConcurrencyHelpers import NIOCore import XCTest @testable import NIOEmbedded -private class EmbeddedTestError: Error {} +private final class EmbeddedTestError: Error {} public final class EmbeddedEventLoopTest: XCTestCase { func testExecuteDoesNotImmediatelyRunTasks() throws { @@ -195,37 +196,38 @@ public final class EmbeddedEventLoopTest: XCTestCase { } func testScheduledTasksFuturesFire() throws { - var fired = false + let fired = ManagedAtomic(false) let loop = EmbeddedEventLoop() let task = loop.scheduleTask(in: .nanoseconds(5)) { true } - task.futureResult.whenSuccess { fired = $0 } + task.futureResult.whenSuccess { fired.store($0, ordering: .sequentiallyConsistent) } loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired) + XCTAssertFalse(fired.load(ordering: .sequentiallyConsistent)) loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired) + XCTAssertTrue(fired.load(ordering: .sequentiallyConsistent)) } func testScheduledTasksFuturesError() throws { - var err: EmbeddedTestError? = nil - var fired = false + let err: NIOLockedValueBox = NIOLockedValueBox(nil) + let fired = ManagedAtomic(false) let loop = EmbeddedEventLoop() let task = loop.scheduleTask(in: .nanoseconds(5)) { - err = EmbeddedTestError() - throw err! + let localErr = EmbeddedTestError() + err.withLockedValue { $0 = localErr } + throw localErr } task.futureResult.map { XCTFail("Scheduled future completed") }.recover { caughtErr in - XCTAssertTrue(err === caughtErr as? EmbeddedTestError) + XCTAssertTrue(err.withLockedValue { $0 === caughtErr as? EmbeddedTestError }) }.whenComplete { (_: Result) in - fired = true + fired.store(true, ordering: .sequentiallyConsistent) } loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired) + XCTAssertFalse(fired.load(ordering: .sequentiallyConsistent)) loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired) + XCTAssertTrue(fired.load(ordering: .sequentiallyConsistent)) } func testTaskOrdering() { @@ -511,21 +513,24 @@ public final class EmbeddedEventLoopTest: XCTestCase { func testScheduleRepeatedTask() { let eventLoop = EmbeddedEventLoop() - var counter = 0 + let counter = ManagedAtomic(0) eventLoop.scheduleRepeatedTask(initialDelay: .seconds(1), delay: .seconds(1)) { repeatedTask in - guard counter < 10 else { + guard counter.load(ordering: .sequentiallyConsistent) < 10 else { repeatedTask.cancel() return } - counter += 1 + counter.wrappingIncrement(ordering: .sequentiallyConsistent) } - XCTAssertEqual(counter, 0) + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 0) eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(counter, 1) + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 1) eventLoop.advanceTime(by: .seconds(9)) - XCTAssertEqual(counter, 10) + XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 10) } } + +@available(*, unavailable) +extension EmbeddedEventLoopTest: Sendable {} diff --git a/Tests/NIOEmbeddedTests/TestUtils.swift b/Tests/NIOEmbeddedTests/TestUtils.swift index c25bc44a1..3cefa8106 100644 --- a/Tests/NIOEmbeddedTests/TestUtils.swift +++ b/Tests/NIOEmbeddedTests/TestUtils.swift @@ -48,26 +48,25 @@ extension EventLoopFuture { if self.eventLoop.inEventLoop { // Easy, we're on the EventLoop. Let's just use our knowledge that we run completed future callbacks // immediately. - var fulfilled = false + let fulfilled = NIOLoopBoundBox(false, eventLoop: self.eventLoop) self.whenComplete { _ in - fulfilled = true + fulfilled.value = true } - return fulfilled + return fulfilled.value } else { - let lock = NIOLock() + let fulfilled = NIOLockedValueBox(false) let group = DispatchGroup() - var fulfilled = false // protected by lock group.enter() self.eventLoop.execute { let isFulfilled = self.isFulfilled // This will now enter the above branch. - lock.withLock { - fulfilled = isFulfilled + fulfilled.withLockedValue { + $0 = isFulfilled } group.leave() } group.wait() // this is very nasty but this is for tests only, so... - return lock.withLock { fulfilled } + return fulfilled.withLockedValue { $0 } } } } From 60089114f8af82d8fb290579fbde46e11f07a552 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Tue, 17 Dec 2024 11:21:02 +0000 Subject: [PATCH 29/93] Enable MemberImportVisibility check - attempt 2 (#3029) Enable MemberImportVisibility check on all targets. Use a standard string header and footer to bracket the new block for ease of updating in the future with scripts. See https://github.com/apple/swift-nio/pull/3021 --- Package.swift | 11 +++++++++++ Sources/NIOCrashTester/CrashTests+Strict.swift | 1 + Sources/NIOCrashTester/CrashTests+System.swift | 1 + Sources/NIOMulticastChat/main.swift | 1 + Sources/NIOPosix/BaseSocket.swift | 1 + Sources/NIOPosix/Bootstrap.swift | 1 + Sources/NIOPosix/DatagramVectorReadManager.swift | 1 + Sources/NIOPosix/NonBlockingFileIO.swift | 1 + Sources/NIOPosix/PendingDatagramWritesManager.swift | 1 + Sources/NIOPosix/PendingWritesManager.swift | 1 + Sources/NIOPosix/SelectorEpoll.swift | 1 + Sources/NIOPosix/Socket.swift | 1 + Sources/NIOPosix/SocketChannel.swift | 1 + Tests/NIOFileSystemTests/FileInfoTests.swift | 9 +++++++++ Tests/NIOFileSystemTests/Internal/SyscallTests.swift | 1 + Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift | 1 + Tests/NIOPosixTests/ControlMessageTests.swift | 1 + Tests/NIOPosixTests/NIOThreadPoolTest.swift | 1 + Tests/NIOPosixTests/NonBlockingFileIOTest.swift | 1 + .../PendingDatagramWritesManagerTests.swift | 1 + Tests/NIOPosixTests/SocketAddressTest.swift | 1 + Tests/NIOPosixTests/SocketOptionProviderTest.swift | 1 + Tests/NIOPosixTests/StreamChannelsTest.swift | 1 + Tests/NIOPosixTests/SyscallAbstractionLayer.swift | 1 + Tests/NIOPosixTests/SystemTest.swift | 1 + Tests/NIOPosixTests/ThreadTest.swift | 1 + 26 files changed, 44 insertions(+) diff --git a/Package.swift b/Package.swift index 1b63eae19..610fbf6db 100644 --- a/Package.swift +++ b/Package.swift @@ -568,3 +568,14 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { .package(path: "../swift-system"), ] } + +// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // +for target in package.targets { + if target.type != .plugin { + var settings = target.swiftSettings ?? [] + // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md + settings.append(.enableUpcomingFeature("MemberImportVisibility")) + target.swiftSettings = settings + } +} +// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- // diff --git a/Sources/NIOCrashTester/CrashTests+Strict.swift b/Sources/NIOCrashTester/CrashTests+Strict.swift index d97a737a0..cbbe46a52 100644 --- a/Sources/NIOCrashTester/CrashTests+Strict.swift +++ b/Sources/NIOCrashTester/CrashTests+Strict.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #if !canImport(Darwin) || os(macOS) +import NIOCore import NIOPosix struct StrictCrashTests { diff --git a/Sources/NIOCrashTester/CrashTests+System.swift b/Sources/NIOCrashTester/CrashTests+System.swift index 3147ff081..b5863eb20 100644 --- a/Sources/NIOCrashTester/CrashTests+System.swift +++ b/Sources/NIOCrashTester/CrashTests+System.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #if !canImport(Darwin) || os(macOS) +import NIOCore import NIOPosix import Foundation diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index 94beddc8f..7d3298ee7 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore import NIOPosix diff --git a/Sources/NIOPosix/BaseSocket.swift b/Sources/NIOPosix/BaseSocket.swift index 58e20d3e8..5c5ab3ceb 100644 --- a/Sources/NIOPosix/BaseSocket.swift +++ b/Sources/NIOPosix/BaseSocket.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOConcurrencyHelpers import NIOCore diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index e3b5710ff..20a0a4844 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore #if os(Windows) diff --git a/Sources/NIOPosix/DatagramVectorReadManager.swift b/Sources/NIOPosix/DatagramVectorReadManager.swift index 2d4987a9d..7f6ced454 100644 --- a/Sources/NIOPosix/DatagramVectorReadManager.swift +++ b/Sources/NIOPosix/DatagramVectorReadManager.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore /// An object that manages issuing vector reads for datagram channels. diff --git a/Sources/NIOPosix/NonBlockingFileIO.swift b/Sources/NIOPosix/NonBlockingFileIO.swift index fe3448d11..7b8c9a823 100644 --- a/Sources/NIOPosix/NonBlockingFileIO.swift +++ b/Sources/NIOPosix/NonBlockingFileIO.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOConcurrencyHelpers import NIOCore diff --git a/Sources/NIOPosix/PendingDatagramWritesManager.swift b/Sources/NIOPosix/PendingDatagramWritesManager.swift index ace953fbc..8c058bd4e 100644 --- a/Sources/NIOPosix/PendingDatagramWritesManager.swift +++ b/Sources/NIOPosix/PendingDatagramWritesManager.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore private struct PendingDatagramWrite { diff --git a/Sources/NIOPosix/PendingWritesManager.swift b/Sources/NIOPosix/PendingWritesManager.swift index 001b05c21..6e6b3fff7 100644 --- a/Sources/NIOPosix/PendingWritesManager.swift +++ b/Sources/NIOPosix/PendingWritesManager.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore private struct PendingStreamWrite { diff --git a/Sources/NIOPosix/SelectorEpoll.swift b/Sources/NIOPosix/SelectorEpoll.swift index 832dc41df..d0dbf09ed 100644 --- a/Sources/NIOPosix/SelectorEpoll.swift +++ b/Sources/NIOPosix/SelectorEpoll.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import NIOConcurrencyHelpers import NIOCore #if !SWIFTNIO_USE_IO_URING diff --git a/Sources/NIOPosix/Socket.swift b/Sources/NIOPosix/Socket.swift index 1535e42d0..b8434d62e 100644 --- a/Sources/NIOPosix/Socket.swift +++ b/Sources/NIOPosix/Socket.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore /// The container used for writing multiple buffers via `writev`. diff --git a/Sources/NIOPosix/SocketChannel.swift b/Sources/NIOPosix/SocketChannel.swift index e1a9a473c..6dd227131 100644 --- a/Sources/NIOPosix/SocketChannel.swift +++ b/Sources/NIOPosix/SocketChannel.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore #if os(Windows) diff --git a/Tests/NIOFileSystemTests/FileInfoTests.swift b/Tests/NIOFileSystemTests/FileInfoTests.swift index ae06ab5e2..6760b5d3a 100644 --- a/Tests/NIOFileSystemTests/FileInfoTests.swift +++ b/Tests/NIOFileSystemTests/FileInfoTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest import _NIOFileSystem @@ -23,6 +24,14 @@ import Glibc import Android #endif +#if canImport(Darwin) +private let S_IFREG = Darwin.S_IFREG +#elseif canImport(Glibc) +private let S_IFREG = Glibc.S_IFREG +#elseif canImport(Musl) +private let S_IFREG = Musl.S_IFREG +#endif + final class FileInfoTests: XCTestCase { private var status: CInterop.Stat { var status = CInterop.Stat() diff --git a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift index 2ca520421..aa067798f 100644 --- a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift +++ b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import SystemPackage import XCTest @_spi(Testing) import _NIOFileSystem diff --git a/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift b/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift index 1545d88ad..38dabf7d0 100644 --- a/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/BlockingIOThreadPoolTest.swift @@ -14,6 +14,7 @@ import Dispatch import Foundation +import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/ControlMessageTests.swift b/Tests/NIOPosixTests/ControlMessageTests.swift index fc33f634a..26b6634bb 100644 --- a/Tests/NIOPosixTests/ControlMessageTests.swift +++ b/Tests/NIOPosixTests/ControlMessageTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest @testable import NIOPosix diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index 21eda2b44..d88f7c87e 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -15,6 +15,7 @@ import Atomics import Dispatch import NIOConcurrencyHelpers +import NIOCore import NIOEmbedded import XCTest diff --git a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift index 26ab80d61..4e452b1f1 100644 --- a/Tests/NIOPosixTests/NonBlockingFileIOTest.swift +++ b/Tests/NIOPosixTests/NonBlockingFileIOTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift index 3ef944b19..b94e37cf9 100644 --- a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift +++ b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOEmbedded import XCTest diff --git a/Tests/NIOPosixTests/SocketAddressTest.swift b/Tests/NIOPosixTests/SocketAddressTest.swift index d12d8e626..e08ebbe74 100644 --- a/Tests/NIOPosixTests/SocketAddressTest.swift +++ b/Tests/NIOPosixTests/SocketAddressTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import XCTest @testable import NIOCore diff --git a/Tests/NIOPosixTests/SocketOptionProviderTest.swift b/Tests/NIOPosixTests/SocketOptionProviderTest.swift index 962a620da..32d2c704e 100644 --- a/Tests/NIOPosixTests/SocketOptionProviderTest.swift +++ b/Tests/NIOPosixTests/SocketOptionProviderTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/StreamChannelsTest.swift b/Tests/NIOPosixTests/StreamChannelsTest.swift index 072f35d41..668dd1d33 100644 --- a/Tests/NIOPosixTests/StreamChannelsTest.swift +++ b/Tests/NIOPosixTests/StreamChannelsTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOLinux import NIOCore import NIOTestUtils import XCTest diff --git a/Tests/NIOPosixTests/SyscallAbstractionLayer.swift b/Tests/NIOPosixTests/SyscallAbstractionLayer.swift index 6137b4349..36e774e2d 100644 --- a/Tests/NIOPosixTests/SyscallAbstractionLayer.swift +++ b/Tests/NIOPosixTests/SyscallAbstractionLayer.swift @@ -15,6 +15,7 @@ // This file contains a syscall abstraction layer (SAL) which hooks the Selector and the Socket in a way that we can // play the kernel whilst NIO thinks it's running on a real OS. +import CNIOLinux import NIOConcurrencyHelpers import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/SystemTest.swift b/Tests/NIOPosixTests/SystemTest.swift index aabe80090..41840e3d0 100644 --- a/Tests/NIOPosixTests/SystemTest.swift +++ b/Tests/NIOPosixTests/SystemTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOCore import XCTest diff --git a/Tests/NIOPosixTests/ThreadTest.swift b/Tests/NIOPosixTests/ThreadTest.swift index 8320f068d..d0d5b1172 100644 --- a/Tests/NIOPosixTests/ThreadTest.swift +++ b/Tests/NIOPosixTests/ThreadTest.swift @@ -14,6 +14,7 @@ import Dispatch import NIOConcurrencyHelpers +import NIOCore import XCTest @testable import NIOPosix From d73d86261c85a56fa7b913de92435224df439ac8 Mon Sep 17 00:00:00 2001 From: Gus Cairo Date: Tue, 17 Dec 2024 16:39:44 +0000 Subject: [PATCH 30/93] Wait for `closeFuture` instead of close promise in `NIOAsyncChannel`'s `executeThenClose` (#3032) After the changes introduced in https://github.com/apple/swift-nio-http2/pull/487, we need to make a small change in the implementation of `NIOAsyncChannel` to wait on the `closeFuture` instead of on `close`'s promise in the `executeThenClose` implementation. ### Motivation: `executeThenClose` shouldn't fail from errors arising from closing the channel - at this point, the user of the channel cannot really do anything, and since the channel has been closed, we should not fail since resources have been cleaned up anyways. ### Modifications: This PR changes the implementation of `NIOAsyncChannel` to wait on the `closeFuture` instead of on `close`'s promise in the `executeThenClose` implementation. It also updates the docs for `closeFuture` to better explain when it will be succeeded and why it won't ever be failed. ### Result: `executeThenClose` won't throw errors upon closing. --- .../NIOCore/AsyncChannel/AsyncChannel.swift | 22 ++++++++++++++----- Sources/NIOCore/Channel.swift | 6 +++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannel.swift b/Sources/NIOCore/AsyncChannel/AsyncChannel.swift index 10354f076..105862576 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannel.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannel.swift @@ -301,15 +301,25 @@ public struct NIOAsyncChannel: Sendable { } } + self._outbound.finish() + // We ignore errors from close, since all we care about is that the channel has been closed + // at this point. + self.channel.close(promise: nil) + // `closeFuture` should never be failed, so we could ignore the error. However, do an + // assertionFailure to guide bad Channel implementations that are incorrectly failing this + // future to stop failing it. do { - self._outbound.finish() - try await self.channel.close().get() + try await self.channel.closeFuture.get() } catch { - if let error = error as? ChannelError, error == .alreadyClosed { - return result - } - throw error + assertionFailure( + """ + The channel's closeFuture should never be failed, but it was failed with error: \(error). + This is an error in the channel's implementation. + Refer to `Channel/closeFuture`'s documentation for more information. + """ + ) } + return result } } diff --git a/Sources/NIOCore/Channel.swift b/Sources/NIOCore/Channel.swift index 8d0af1fec..9793102d5 100644 --- a/Sources/NIOCore/Channel.swift +++ b/Sources/NIOCore/Channel.swift @@ -107,6 +107,12 @@ public protocol Channel: AnyObject, ChannelOutboundInvoker, _NIOPreconcurrencySe var allocator: ByteBufferAllocator { get } /// The `closeFuture` will fire when the `Channel` has been closed. + /// + /// - Important: This future should never be failed: it signals when the channel has been closed, and this action should not fail, + /// regardless of whether the close happenned cleanly or not. + /// If you are interested in any errors thrown during `close` to diagnose any unclean channel closures, you + /// should instead use the future returned from ``ChannelOutboundInvoker/close(mode:file:line:)-7hlgf`` + /// or pass a promise via ``ChannelOutboundInvoker/close(mode:promise:)``. var closeFuture: EventLoopFuture { get } /// The `ChannelPipeline` which handles all I/O events and requests associated with this `Channel`. From 2122fd866183ce31af4787e450398a28ac5caec1 Mon Sep 17 00:00:00 2001 From: finagolfin Date: Wed, 18 Dec 2024 16:11:17 +0530 Subject: [PATCH 31/93] Import Android instead for NIOEmbedded (#3033) Pull #3030 invokes C APIs that aren't in the extremely limited Bionic module, so import the much larger Android overlay instead. This [just broke my daily Android CI](https://github.com/finagolfin/swift-android-sdk/actions/runs/12389744616/job/34583381415#step:19:239). --- Sources/NIOEmbedded/Embedded.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index 865a97c88..fbbfb4d67 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -28,8 +28,8 @@ import Darwin import Glibc #elseif canImport(Musl) import Musl -#elseif canImport(Bionic) -import Bionic +#elseif canImport(Android) +import Android #elseif canImport(WASILibc) import WASILibc #else @@ -130,7 +130,7 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { public let description = "EmbeddedEventLoop" - #if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic) + #if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Android) private let myThread: pthread_t = pthread_self() func isCorrectThread() -> Bool { From 7dea8e7ad1d92aa3ee3f93d4e2537103e4078d28 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Wed, 18 Dec 2024 12:51:53 +0100 Subject: [PATCH 32/93] Update release.yml and label action (#3035) Update the release.yml file with the latest label changes --- .github/actions/pull_request_semver_label_checker/action.yml | 2 +- .github/release.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/actions/pull_request_semver_label_checker/action.yml b/.github/actions/pull_request_semver_label_checker/action.yml index 31dda8124..bbdeffd75 100644 --- a/.github/actions/pull_request_semver_label_checker/action.yml +++ b/.github/actions/pull_request_semver_label_checker/action.yml @@ -18,4 +18,4 @@ runs: GH_TOKEN: ${{ inputs.token }} run: | gh pr view ${{ github.event.number }} --repo ${{ github.repository }} --json labels \ - | jq -e '[.labels[].name] | any(. == "⚠️ semver/major" or . == "semver/minor" or . == "semver/patch" or . == "semver/none")' + | jq -e '[.labels[].name] | any(. == "⚠️ semver/major" or . == "🆕 semver/minor" or . == "🔨 semver/patch" or . == "semver/none")' diff --git a/.github/release.yml b/.github/release.yml index f96b51492..e29eb8464 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -5,10 +5,10 @@ changelog: - ⚠️ semver/major - title: SemVer Minor labels: - - semver/minor + - 🆕 semver/minor - title: SemVer Patch labels: - - semver/patch + - 🔨 semver/patch - title: Other Changes labels: - semver/none From 56f9b7c6fc9525ba36236dbb151344f8c35288df Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Thu, 19 Dec 2024 11:27:19 +0100 Subject: [PATCH 33/93] =?UTF-8?q?Fix=20flaky=20test=20testTasksScheduledDu?= =?UTF-8?q?ringShutdownAreAutomaticallyCancel=E2=80=A6=20(#3036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit …ledOrNotScheduledAnymore # Motivation This task was flaky and hit the assertion with the count being 1 # Modification This changes the expectation to greater than 0 since we can always guarantee that one scheduled task is run but due to timing windows it might be that we shutdown the EL before the second task is enqueued which meant it was immediately failed. # Result One less flaky test --- Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index 86920495f..c4d33f78e 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -480,7 +480,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } } - func testTasksScheduledDuringShutdownAreAutomaticallyCancelled() async throws { + func testTasksScheduledDuringShutdownAreAutomaticallyCancelledOrNotScheduled() async throws { let eventLoop = NIOAsyncTestingEventLoop() let tasksRun = ManagedAtomic(0) @@ -511,7 +511,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } try await eventLoop.executeInContext { - XCTAssertGreaterThan(tasksRun.load(ordering: .acquiring), 1) + XCTAssertGreaterThan(tasksRun.load(ordering: .acquiring), 0) } } From 100b1f4ff9c0d21c43bd9f5beafda8e7693a12f7 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Tue, 7 Jan 2025 10:36:03 +0000 Subject: [PATCH 34/93] Print alloc-limits-from-test-output usage when no args (#3041) Motivation: The alloc-limits-from-test-output doesn't print usage if you don't pass in a format arg, it just sits and waits for stdin. Modifications: Print usage if running interactively Result: Easier to get usage --- dev/alloc-limits-from-test-output | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dev/alloc-limits-from-test-output b/dev/alloc-limits-from-test-output index 2fa9322ce..d6718709d 100755 --- a/dev/alloc-limits-from-test-output +++ b/dev/alloc-limits-from-test-output @@ -49,6 +49,12 @@ case "$mode_flag" in ;; esac +# stdin is coming from a terminal, i.e. nothing is being piped in. +if [[ -t 0 ]]; then + usage + exit 1 +fi + function allow_slack() { raw="$1" if [[ ! "$raw" =~ ^[0-9]+$ ]]; then From 4292153274d3a35ab45453e29128322ee32d69f0 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 8 Jan 2025 15:51:08 +0000 Subject: [PATCH 35/93] Support concurrency take over in 6.2 (#3043) Motivation: The compiler now self-presents as 6.2 on the nightlies, and the executor takeover still works. Lift the guard. Modifications: Lift the guard on compiler version. Result: Integration tests pass again. --- Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift b/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift index 64b53d837..010a06297 100644 --- a/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift +++ b/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift @@ -40,7 +40,7 @@ extension NIOSingletons { @discardableResult public static func unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor() -> Bool { // Guard between the minimum and maximum supported version for the hook - #if compiler(>=5.9) && compiler(<6.2) + #if compiler(>=5.9) && compiler(<6.3) guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else { return false } From 27c839f4700069928196cd0e9fa03b22f297078a Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Wed, 8 Jan 2025 16:33:33 +0000 Subject: [PATCH 36/93] GetaddrinfoResolver succeeds futures on eventLoop (#3042) ### Motivation: `testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only` would fail sometimes leaking the IPv4 promise in `GetaddrinfoResolver` `HappyEyeballsConnector` returns the connection when it resolves either IPv4 of IPv6. It uses the `GetaddrinfoResolver` which holds a promise for each of the IPv4 and IPv6 resolution; when one is completed the connection will be returned and it is possible to start tearing down the test and shutting down the event loop before the other is completed and we leak the promise. ### Modifications: Complete both futures on the event loop rather than the dispatch queue. ### Result: The futures are completed in the same event loop tick meaning that we cannot continue execution and leak one. --- .../5.10/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../5.9/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../6.0/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- Sources/NIOPosix/Bootstrap.swift | 4 ++-- Sources/NIOPosix/GetaddrinfoResolver.swift | 19 ++++++++++++++----- Tests/NIOPosixTests/BootstrapTest.swift | 4 ++-- 8 files changed, 23 insertions(+), 14 deletions(-) diff --git a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json index d7233c85b..c9e4dbd4c 100644 --- a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 555 + "mallocCountTotal" : 107 } diff --git a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json index 8517c2fe4..82d63a322 100644 --- a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 556 + "mallocCountTotal" : 109 } diff --git a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json index 67abcf36a..c9e4dbd4c 100644 --- a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 548 + "mallocCountTotal" : 107 } diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json index 67abcf36a..c9e4dbd4c 100644 --- a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 548 + "mallocCountTotal" : 107 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json index 67abcf36a..c9e4dbd4c 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 548 + "mallocCountTotal" : 107 } diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 20a0a4844..6d1312b6a 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -956,8 +956,6 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { /// /// Using `bind` is not necessary unless you need the local address to be bound to a specific address. /// - /// - Note: Using `bind` will disable Happy Eyeballs on this `Channel`. - /// /// - Parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> ClientBootstrap { @@ -978,6 +976,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { /// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established. /// + /// - Note: Makes use of Happy Eyeballs. + /// /// - Parameters: /// - host: The host to connect to. /// - port: The port to connect to. diff --git a/Sources/NIOPosix/GetaddrinfoResolver.swift b/Sources/NIOPosix/GetaddrinfoResolver.swift index 7a17589fb..b24b0a9a2 100644 --- a/Sources/NIOPosix/GetaddrinfoResolver.swift +++ b/Sources/NIOPosix/GetaddrinfoResolver.swift @@ -51,6 +51,7 @@ import struct WinSDK.SOCKADDR_IN6 let offloadQueueTSV = ThreadSpecificVariable() internal class GetaddrinfoResolver: Resolver { + private let loop: EventLoop private let v4Future: EventLoopPromise<[SocketAddress]> private let v6Future: EventLoopPromise<[SocketAddress]> private let aiSocktype: NIOBSDSocket.SocketType @@ -67,6 +68,7 @@ internal class GetaddrinfoResolver: Resolver { aiSocktype: NIOBSDSocket.SocketType, aiProtocol: NIOBSDSocket.OptionLevel ) { + self.loop = loop self.v4Future = loop.makePromise() self.v6Future = loop.makePromise() self.aiSocktype = aiSocktype @@ -90,7 +92,6 @@ internal class GetaddrinfoResolver: Resolver { /// Initiate a DNS AAAA query for a given host. /// /// Due to the nature of `getaddrinfo`, we only actually call the function once, in this function. - /// That means this function call actually blocks: sorry! /// /// - Parameters: /// - host: The hostname to do an AAAA lookup on. @@ -214,8 +215,12 @@ internal class GetaddrinfoResolver: Resolver { info = nextInfo } - v6Future.succeed(v6Results) - v4Future.succeed(v4Results) + // Ensure that both futures are succeeded in the same tick + // to avoid racing and potentially leaking a promise + self.loop.execute { + self.v6Future.succeed(v6Results) + self.v4Future.succeed(v4Results) + } } /// Record an error and fail the lookup process. @@ -223,7 +228,11 @@ internal class GetaddrinfoResolver: Resolver { /// - Parameters: /// - error: The error encountered during lookup. private func fail(_ error: Error) { - self.v6Future.fail(error) - self.v4Future.fail(error) + // Ensure that both futures are succeeded in the same tick + // to avoid racing and potentially leaking a promise + self.loop.execute { + self.v6Future.fail(error) + self.v4Future.fail(error) + } } } diff --git a/Tests/NIOPosixTests/BootstrapTest.swift b/Tests/NIOPosixTests/BootstrapTest.swift index 8c64a578e..309f8b1c8 100644 --- a/Tests/NIOPosixTests/BootstrapTest.swift +++ b/Tests/NIOPosixTests/BootstrapTest.swift @@ -734,7 +734,7 @@ class BootstrapTest: XCTestCase { // Some platforms don't define "localhost" for IPv6, so check that // and use "ip6-localhost" instead. if !isIPv4 { - let hostResolver = GetaddrinfoResolver(loop: group.next(), aiSocktype: .stream, aiProtocol: .tcp) + let hostResolver = GetaddrinfoResolver(loop: self.group.next(), aiSocktype: .stream, aiProtocol: .tcp) let hostv6 = try! hostResolver.initiateAAAAQuery(host: "localhost", port: 8088).wait() if hostv6.isEmpty { localhost = "ip6-localhost" @@ -752,7 +752,7 @@ class BootstrapTest: XCTestCase { XCTFail("can't connect channel 1") return } - XCTAssertEqual(localIP, maybeChannel1?.localAddress?.ipAddress) + XCTAssertEqual(localIP, myChannel1Address.ipAddress) // Try 3: Bind the client to the same address/port as in try 2 but to server 2. XCTAssertNoThrow( try ClientBootstrap(group: self.group) From 7bc19dc61ead074f3671aaf370d376fa9e0bf7db Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 13 Jan 2025 09:58:30 +0000 Subject: [PATCH 37/93] Add Sendability annotations on SocketOptionProvider (#3034) ### Motivation: SocketOptionProvider is used to apply a number of socket options. As part of using it in NIOPosix, it became apparent that several necessary sendability annotations are missing. Let's add those. ### Modifications: - Add Sendable constraints with @preconcurrency to SocketOptionProvider. - Update the BaseSocketChannel conformance to match ### Result: Tighter Sendable constraints on SocketOptionProvider. --- Sources/NIOCore/SocketOptionProvider.swift | 227 ++++++++++++++++-- ...seSocketChannel+SocketOptionProvider.swift | 11 +- 2 files changed, 212 insertions(+), 26 deletions(-) diff --git a/Sources/NIOCore/SocketOptionProvider.swift b/Sources/NIOCore/SocketOptionProvider.swift index 97f177298..d0592d0f5 100644 --- a/Sources/NIOCore/SocketOptionProvider.swift +++ b/Sources/NIOCore/SocketOptionProvider.swift @@ -75,7 +75,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { /// - value: The value to set the socket option to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - func unsafeSetSocketOption( + @preconcurrency + func unsafeSetSocketOption( level: SocketOptionLevel, name: SocketOptionName, value: Value @@ -95,7 +96,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { /// - value: The value to set the socket option to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - func unsafeSetSocketOption( + @preconcurrency + func unsafeSetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option, value: Value @@ -114,7 +116,11 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { /// - name: The name of the socket option, e.g. `SO_REUSEADDR`. /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - func unsafeGetSocketOption(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture + @preconcurrency + func unsafeGetSocketOption( + level: SocketOptionLevel, + name: SocketOptionName + ) -> EventLoopFuture #endif /// Obtain the value of the socket option for the given level and name. @@ -129,7 +135,8 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { /// - name: The name of the socket option, e.g. `SO_REUSEADDR`. /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - func unsafeGetSocketOption( + @preconcurrency + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture @@ -137,7 +144,7 @@ public protocol SocketOptionProvider: _NIOPreconcurrencySendable { #if !os(Windows) extension SocketOptionProvider { - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option, value: Value @@ -149,7 +156,7 @@ extension SocketOptionProvider { ) } - func unsafeGetSocketOption( + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture { @@ -175,6 +182,12 @@ public typealias NIOLinger = linger // around. As a result, if you change one, you should probably change them all. // // You are welcome to add more helper methods here, but each helper method you add must be tested. +// +// Please note that to work around a Swift compiler issue regarding lookup of the Sendability of +// libc types across modules, the actual calls to `unsafeSetSocketOption` and `unsafeGetSocketOption` +// _must_ be made inside non-`public` non-`@inlinable` methods. Otherwise we'll produce crashes +// in release mode. NIO's integration tests are a good canary for this: if you call your method +// from an alloc counter test in the integration tests, it'll crash if you messed it up. extension SocketOptionProvider { /// Sets the socket option SO_LINGER to `value`. /// @@ -183,6 +196,176 @@ extension SocketOptionProvider { /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. public func setSoLinger(_ value: linger) -> EventLoopFuture { + self._setSoLinger(value) + } + + /// Gets the value of the socket option SO_LINGER. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getSoLinger() -> EventLoopFuture { + self._getSoLinger() + } + + /// Sets the socket option IP_MULTICAST_IF to `value`. + /// + /// - Parameters: + /// - value: The value to set IP_MULTICAST_IF to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPMulticastIF(_ value: in_addr) -> EventLoopFuture { + self._setIPMulticastIF(value) + } + + /// Gets the value of the socket option IP_MULTICAST_IF. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPMulticastIF() -> EventLoopFuture { + self._getIPMulticastIF() + } + + /// Sets the socket option IP_MULTICAST_TTL to `value`. + /// + /// - Parameters: + /// - value: The value to set IP_MULTICAST_TTL to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture { + self._setIPMulticastTTL(value) + } + + /// Gets the value of the socket option IP_MULTICAST_TTL. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPMulticastTTL() -> EventLoopFuture { + self._getIPMulticastTTL() + } + + /// Sets the socket option IP_MULTICAST_LOOP to `value`. + /// + /// - Parameters: + /// - value: The value to set IP_MULTICAST_LOOP to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture { + self._setIPMulticastLoop(value) + } + + /// Gets the value of the socket option IP_MULTICAST_LOOP. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPMulticastLoop() -> EventLoopFuture { + self._getIPMulticastLoop() + } + + /// Sets the socket option IPV6_MULTICAST_IF to `value`. + /// + /// - Parameters: + /// - value: The value to set IPV6_MULTICAST_IF to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture { + self._setIPv6MulticastIF(value) + } + + /// Gets the value of the socket option IPV6_MULTICAST_IF. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPv6MulticastIF() -> EventLoopFuture { + self._getIPv6MulticastIF() + } + + /// Sets the socket option IPV6_MULTICAST_HOPS to `value`. + /// + /// - Parameters: + /// - value: The value to set IPV6_MULTICAST_HOPS to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture { + self._setIPv6MulticastHops(value) + } + + /// Gets the value of the socket option IPV6_MULTICAST_HOPS. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPv6MulticastHops() -> EventLoopFuture { + self._getIPv6MulticastHops() + } + + /// Sets the socket option IPV6_MULTICAST_LOOP to `value`. + /// + /// - Parameters: + /// - value: The value to set IPV6_MULTICAST_LOOP to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + public func setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture { + self._setIPv6MulticastLoop(value) + } + + /// Gets the value of the socket option IPV6_MULTICAST_LOOP. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getIPv6MulticastLoop() -> EventLoopFuture { + self._getIPv6MulticastLoop() + } + + #if os(Linux) || os(FreeBSD) || os(Android) + /// Gets the value of the socket option TCP_INFO. + /// + /// This socket option cannot be set. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getTCPInfo() -> EventLoopFuture { + self._getTCPInfo() + } + #endif + + #if canImport(Darwin) + /// Gets the value of the socket option TCP_CONNECTION_INFO. + /// + /// This socket option cannot be set. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getTCPConnectionInfo() -> EventLoopFuture { + self._getTCPConnectionInfo() + } + #endif + + #if os(Linux) + /// Gets the value of the socket option MPTCP_INFO. + /// + /// This socket option cannot be set. + /// + /// - Returns: An `EventLoopFuture` containing the value of the socket option, or + /// any error that occurred while retrieving the socket option. + public func getMPTCPInfo() -> EventLoopFuture { + self._getMPTCPInfo() + } + #endif + + // MARK: Non-public non-inlinable actual implementations for the above. + // + // As discussed above, these are needed to work around a compiler issue + // that was present at least up to the 6.0 compiler series. This prevents + // the specialization being emitted in the caller code, which is unfortunate, + // but it also ensures that we avoid the crash. We should remove these when + // they're no longer needed. + + /// Sets the socket option SO_LINGER to `value`. + /// + /// - Parameters: + /// - value: The value to set SO_LINGER to. + /// - Returns: An `EventLoopFuture` that fires when the option has been set, + /// or if an error has occurred. + private func _setSoLinger(_ value: linger) -> EventLoopFuture { #if os(WASI) self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported) #else @@ -194,7 +377,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getSoLinger() -> EventLoopFuture { + private func _getSoLinger() -> EventLoopFuture { #if os(WASI) self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported) #else @@ -208,7 +391,7 @@ extension SocketOptionProvider { /// - value: The value to set IP_MULTICAST_IF to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPMulticastIF(_ value: in_addr) -> EventLoopFuture { + private func _setIPMulticastIF(_ value: in_addr) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_if, value: value) } @@ -216,7 +399,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPMulticastIF() -> EventLoopFuture { + private func _getIPMulticastIF() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_if) } @@ -226,7 +409,7 @@ extension SocketOptionProvider { /// - value: The value to set IP_MULTICAST_TTL to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture { + private func _setIPMulticastTTL(_ value: CUnsignedChar) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_ttl, value: value) } @@ -234,7 +417,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPMulticastTTL() -> EventLoopFuture { + private func _getIPMulticastTTL() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_ttl) } @@ -244,7 +427,7 @@ extension SocketOptionProvider { /// - value: The value to set IP_MULTICAST_LOOP to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture { + private func _setIPMulticastLoop(_ value: CUnsignedChar) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ip, name: .ip_multicast_loop, value: value) } @@ -252,7 +435,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPMulticastLoop() -> EventLoopFuture { + private func _getIPMulticastLoop() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ip, name: .ip_multicast_loop) } @@ -262,7 +445,7 @@ extension SocketOptionProvider { /// - value: The value to set IPV6_MULTICAST_IF to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture { + private func _setIPv6MulticastIF(_ value: CUnsignedInt) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_if, value: value) } @@ -270,7 +453,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPv6MulticastIF() -> EventLoopFuture { + private func _getIPv6MulticastIF() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_if) } @@ -280,7 +463,7 @@ extension SocketOptionProvider { /// - value: The value to set IPV6_MULTICAST_HOPS to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture { + private func _setIPv6MulticastHops(_ value: CInt) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_hops, value: value) } @@ -288,7 +471,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPv6MulticastHops() -> EventLoopFuture { + private func _getIPv6MulticastHops() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_hops) } @@ -298,7 +481,7 @@ extension SocketOptionProvider { /// - value: The value to set IPV6_MULTICAST_LOOP to. /// - Returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. - public func setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture { + private func _setIPv6MulticastLoop(_ value: CUnsignedInt) -> EventLoopFuture { self.unsafeSetSocketOption(level: .ipv6, name: .ipv6_multicast_loop, value: value) } @@ -306,7 +489,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getIPv6MulticastLoop() -> EventLoopFuture { + private func _getIPv6MulticastLoop() -> EventLoopFuture { self.unsafeGetSocketOption(level: .ipv6, name: .ipv6_multicast_loop) } @@ -317,7 +500,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getTCPInfo() -> EventLoopFuture { + private func _getTCPInfo() -> EventLoopFuture { self.unsafeGetSocketOption(level: .tcp, name: .tcp_info) } #endif @@ -329,7 +512,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getTCPConnectionInfo() -> EventLoopFuture { + private func _getTCPConnectionInfo() -> EventLoopFuture { self.unsafeGetSocketOption(level: .tcp, name: .tcp_connection_info) } #endif @@ -341,7 +524,7 @@ extension SocketOptionProvider { /// /// - Returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getMPTCPInfo() -> EventLoopFuture { + private func _getMPTCPInfo() -> EventLoopFuture { self.unsafeGetSocketOption(level: .mptcp, name: .mptcp_info) } #endif diff --git a/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift b/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift index c50429abd..47eb8dd11 100644 --- a/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift +++ b/Sources/NIOPosix/BaseSocketChannel+SocketOptionProvider.swift @@ -15,7 +15,7 @@ import NIOCore extension BaseSocketChannel: SocketOptionProvider { #if !os(Windows) - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: SocketOptionLevel, name: SocketOptionName, value: Value @@ -28,7 +28,7 @@ extension BaseSocketChannel: SocketOptionProvider { } #endif - func unsafeSetSocketOption( + func unsafeSetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option, value: Value @@ -47,7 +47,10 @@ extension BaseSocketChannel: SocketOptionProvider { } #if !os(Windows) - func unsafeGetSocketOption(level: SocketOptionLevel, name: SocketOptionName) -> EventLoopFuture { + func unsafeGetSocketOption( + level: SocketOptionLevel, + name: SocketOptionName + ) -> EventLoopFuture { unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel(rawValue: CInt(level)), name: NIOBSDSocket.Option(rawValue: CInt(name)) @@ -55,7 +58,7 @@ extension BaseSocketChannel: SocketOptionProvider { } #endif - func unsafeGetSocketOption( + func unsafeGetSocketOption( level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option ) -> EventLoopFuture { From 23d0b08ad23244e926ddb7f0aafe439db9f3b29e Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 13 Jan 2025 11:06:36 +0000 Subject: [PATCH 38/93] unchecked Sendable for the Channels (#3050) ### Motivation: All of NIO's channels are thread-safe, and that includes the NIOPosix ones. In an ideal world we'd have written these in such a way that they rely on very small, easily-verified types to enforce this constraint. We will migrate towards that in time, but for expediency we can mark these as they are, which is `@unchecked Sendable`. ### Modifications: Mark the core NIOPosix channel types `@unchecked Sendable`. ### Result: Fewer warnings. --- Sources/NIOPosix/BaseSocketChannel.swift | 4 ++-- Sources/NIOPosix/BaseStreamSocketChannel.swift | 2 +- Sources/NIOPosix/PipeChannel.swift | 2 +- Sources/NIOPosix/SocketChannel.swift | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Sources/NIOPosix/BaseSocketChannel.swift b/Sources/NIOPosix/BaseSocketChannel.swift index 50668f35a..2a1951531 100644 --- a/Sources/NIOPosix/BaseSocketChannel.swift +++ b/Sources/NIOPosix/BaseSocketChannel.swift @@ -223,7 +223,7 @@ private struct SocketChannelLifecycleManager { /// For this reason, `BaseSocketChannel` exists to provide a common core implementation of /// the `SelectableChannel` protocol. It uses a number of private functions to provide hooks /// for subclasses to implement the specific logic to handle their writes and reads. -class BaseSocketChannel: SelectableChannel, ChannelCore { +class BaseSocketChannel: SelectableChannel, ChannelCore, @unchecked Sendable { typealias SelectableType = SocketType.SelectableType struct AddressCache { @@ -1419,7 +1419,7 @@ extension BaseSocketChannel { } /// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`). -func executeAndComplete(_ promise: EventLoopPromise?, _ body: () throws -> Value) { +func executeAndComplete(_ promise: EventLoopPromise?, _ body: () throws -> Value) { do { let result = try body() promise?.succeed(result) diff --git a/Sources/NIOPosix/BaseStreamSocketChannel.swift b/Sources/NIOPosix/BaseStreamSocketChannel.swift index 6f04ecec6..7878415d3 100644 --- a/Sources/NIOPosix/BaseStreamSocketChannel.swift +++ b/Sources/NIOPosix/BaseStreamSocketChannel.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore -class BaseStreamSocketChannel: BaseSocketChannel { +class BaseStreamSocketChannel: BaseSocketChannel, @unchecked Sendable { internal var connectTimeoutScheduled: Optional> private var allowRemoteHalfClosure: Bool = false private var inputShutdown: Bool = false diff --git a/Sources/NIOPosix/PipeChannel.swift b/Sources/NIOPosix/PipeChannel.swift index e105a724f..27130a292 100644 --- a/Sources/NIOPosix/PipeChannel.swift +++ b/Sources/NIOPosix/PipeChannel.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore -final class PipeChannel: BaseStreamSocketChannel { +final class PipeChannel: BaseStreamSocketChannel, @unchecked Sendable { private let pipePair: PipePair internal enum Direction { diff --git a/Sources/NIOPosix/SocketChannel.swift b/Sources/NIOPosix/SocketChannel.swift index 6dd227131..fd51c008c 100644 --- a/Sources/NIOPosix/SocketChannel.swift +++ b/Sources/NIOPosix/SocketChannel.swift @@ -50,7 +50,7 @@ extension ByteBuffer { /// A `Channel` for a client socket. /// /// - Note: All operations on `SocketChannel` are thread-safe. -final class SocketChannel: BaseStreamSocketChannel { +final class SocketChannel: BaseStreamSocketChannel, @unchecked Sendable { private var connectTimeout: TimeAmount? = nil init(eventLoop: SelectableEventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, enableMPTCP: Bool = false) throws @@ -192,7 +192,7 @@ final class SocketChannel: BaseStreamSocketChannel { /// A `Channel` for a server socket. /// /// - Note: All operations on `ServerSocketChannel` are thread-safe. -final class ServerSocketChannel: BaseSocketChannel { +final class ServerSocketChannel: BaseSocketChannel, @unchecked Sendable { private var backlog: Int32 = 128 private let group: EventLoopGroup @@ -451,7 +451,7 @@ final class ServerSocketChannel: BaseSocketChannel { /// A channel used with datagram sockets. /// /// Currently, it does not support connected mode which is well worth adding. -final class DatagramChannel: BaseSocketChannel { +final class DatagramChannel: BaseSocketChannel, @unchecked Sendable { private var reportExplicitCongestionNotifications = false private var receivePacketInfo = false From 329ef54dd8204dcd2ea82860d808f4a75fd6f5a5 Mon Sep 17 00:00:00 2001 From: hamzahrmalik Date: Mon, 13 Jan 2025 15:21:42 +0000 Subject: [PATCH 39/93] Add channel initializer closure to NIOAsyncTestingChannel.init (#3053) Since nio 2.78, adding handlers to a pipeline requires the handlers to be sendable. That makes the [NIOAsyncTestingChannel.init(handlers:loop:)](https://swiftpackageindex.com/apple/swift-nio/2.78.0/documentation/nioembedded/nioasynctestingchannel/init(handlers:loop:)) function cumbersome, because you cannot create handlers and then call the function (unless your handlers are Sendable) even if you never use the handlers elsewhere. This PR adds a new initializer which takes a closure. The closure is run on-loop before the channel is registered. This means we can do: ```swift let channel = try await NIOAsyncTestingChannel { let handler = MyUnsendableHandler() try $0.pipeline.syncOperations.addHandler(handler) } ``` --- Sources/NIOEmbedded/AsyncTestingChannel.swift | 25 +++++++++++++++---- .../AsyncTestingChannelTests.swift | 11 ++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/Sources/NIOEmbedded/AsyncTestingChannel.swift b/Sources/NIOEmbedded/AsyncTestingChannel.swift index d3a4834f7..8e0ca9c33 100644 --- a/Sources/NIOEmbedded/AsyncTestingChannel.swift +++ b/Sources/NIOEmbedded/AsyncTestingChannel.swift @@ -307,12 +307,27 @@ public final class NIOAsyncTestingChannel: Channel { handlers: [ChannelHandler & Sendable], loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop() ) async { + try! await self.init(loop: loop) { channel in + try channel.pipeline.syncOperations.addHandlers(handlers) + } + } + + /// Create a new instance. + /// + /// During creation it will automatically also register itself on the ``NIOAsyncTestingEventLoop``. + /// + /// - Parameters: + /// - loop: The ``NIOAsyncTestingEventLoop`` to use. + /// - channelInitializer: The initialization closure which will be run on the `EventLoop` before registration. This could be used to add handlers using `syncOperations`. + public convenience init( + loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop(), + channelInitializer: @escaping @Sendable (NIOAsyncTestingChannel) throws -> Void + ) async throws { self.init(loop: loop) - - try! await self._pipeline.addHandlers(handlers) - - // This will never throw... - try! await self.register() + try await loop.submit { + try channelInitializer(self) + }.get() + try await self.register() } /// Asynchronously closes the ``NIOAsyncTestingChannel``. diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index 5022dcd3c..4e9cd0754 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -65,6 +65,17 @@ class AsyncTestingChannelTests: XCTestCase { XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) } + func testClosureInit() async throws { + final class Handler: ChannelInboundHandler, Sendable { + typealias InboundIn = Never + } + + let channel = try await NIOAsyncTestingChannel { + try $0.pipeline.syncOperations.addHandler(Handler()) + } + XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) + } + func testWaitForInboundWrite() async throws { let channel = NIOAsyncTestingChannel() let task = Task { From 588523e7d6f24bb4a5db037ca775f64a315dea06 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 13 Jan 2025 17:44:49 +0000 Subject: [PATCH 40/93] Test allocations of isolated ELF views (#3054) Motivation: We've added isolated views onto EventLoopFutures. These are great, but as initially implemented they add a bunch of overhead to the nonisolated versions. That's not optimal, but before we change the code we should make sure we have a benchmark baseline. Modifications: - Extend the test_future_lots_of_callbacks alloc test to add all the callbacks that the isolated views have. - Duplicate that test to one that adds isolated wrappers so we can compare. Result: Two regression tests whose allocation counts should be equal, but aren't. --- .../tests_04_performance/Thresholds/5.10.json | 3 +- .../tests_04_performance/Thresholds/5.9.json | 4 +- .../tests_04_performance/Thresholds/6.0.json | 3 +- .../Thresholds/nightly-6.0.json | 3 +- .../Thresholds/nightly-main.json | 3 +- ...re_assume_isolated_lots_of_callbacks.swift | 122 ++++++++++++++++++ .../test_future_lots_of_callbacks.swift | 41 +++++- 7 files changed, 169 insertions(+), 10 deletions(-) create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index c3fc7078e..a13f5e39d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -32,8 +32,9 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "future_assume_isolated_lots_of_callbacks": 92050, "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, + "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, "get_100000_headers_canonical_form_trimming_whitespace": 700050, "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index b9e6d8faa..82cfbff08 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -32,8 +32,9 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "future_assume_isolated_lots_of_callbacks": 91050, "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, + "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, "get_100000_headers_canonical_form_trimming_whitespace": 700050, "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, @@ -48,4 +49,3 @@ "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } - diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index c3fc7078e..a13f5e39d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -32,8 +32,9 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "future_assume_isolated_lots_of_callbacks": 92050, "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, + "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, "get_100000_headers_canonical_form_trimming_whitespace": 700050, "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index c3fc7078e..a13f5e39d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -32,8 +32,9 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "future_assume_isolated_lots_of_callbacks": 92050, "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, + "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, "get_100000_headers_canonical_form_trimming_whitespace": 700050, "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index f75dbda93..1009e21d2 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -32,8 +32,9 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "future_assume_isolated_lots_of_callbacks": 92050, "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, + "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 500050, "get_100000_headers_canonical_form_trimming_whitespace": 500050, "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 500050, diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift new file mode 100644 index 000000000..d9a04d14e --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_future_assume_isolated_lots_of_callbacks.swift @@ -0,0 +1,122 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore +import NIOEmbedded + +// This test is an equivalent of test_future_lots_of_callbacks.swift. It should +// have the same allocations as that test, and any difference is a bug. +func run(identifier: String) { + measure(identifier: identifier) { + struct MyError: Error {} + @inline(never) + func doThenAndFriends(loop: EventLoop) { + let p = loop.makePromise(of: Int.self) + let f = p.futureResult.assumeIsolated().flatMap { (r: Int) -> EventLoopFuture in + // This call allocates a new Future, and + // so does flatMap(), so this is two Futures. + loop.makeSucceededFuture(r + 1) + }.flatMapThrowing { (r: Int) -> Int in + // flatMapThrowing allocates a new Future, and calls `flatMap` + // which also allocates, so this is two. + r + 2 + }.map { (r: Int) -> Int in + // map allocates a new future, and calls `flatMap` which + // also allocates, so this is two. + r + 2 + }.flatMapThrowing { (r: Int) -> Int in + // flatMapThrowing allocates a future on the error path and + // calls `flatMap`, which also allocates, so this is two. + throw MyError() + }.flatMapError { (err: Error) -> EventLoopFuture in + // This call allocates a new Future, and so does flatMapError, + // so this is two Futures. + loop.makeFailedFuture(err) + }.flatMapErrorThrowing { (err: Error) -> Int? in + // flatMapError allocates a new Future, and calls flatMapError, + // so this is two Futures + throw err + }.recover { (err: Error) -> Int? in + // recover allocates a future, and calls flatMapError, so + // this is two Futures. + nil + }.unwrap { () -> Int in + // unwrap calls map, with an extra closure, so this is three. + 1 + }.always { (Int) -> Void in + // This is a do-nothing call, but it can't be optimised out. + // always calls whenComplete but adds a new closure, so it allocates + // two times. + _ = 1 + 1 + }.flatMapResult { (Int) -> Result in + // flatMapResult allocates a new future and creates a _whenComplete closure, + // so this is two. + .success(5) + } + .unwrap(orReplace: 5) // Same as unwrap above, this is three. + + // Add some when*. + f.whenSuccess { + // whenSuccess should be just one. + _ = $0 + 1 + } + f.whenFailure { _ in + // whenFailure should also be just one. + fatalError() + } + f.whenComplete { + // whenComplete should also be just one. + switch $0 { + case .success: + () + case .failure: + fatalError() + } + } + + p.assumeIsolated().succeed(0) + + // Wait also allocates a lock. + _ = try! f.nonisolated().wait() + } + @inline(never) + func doAnd(loop: EventLoop) { + // This isn't relevant to this test, but we keep it here to keep the numbers lining up. + let p1 = loop.makePromise(of: Int.self) + let p2 = loop.makePromise(of: Int.self) + let p3 = loop.makePromise(of: Int.self) + + // Each call to and() allocates a Future. The calls to + // and(result:) allocate two. + + let f = p1.futureResult + .and(p2.futureResult) + .and(p3.futureResult) + .and(value: 1) + .and(value: 1) + + p1.succeed(1) + p2.succeed(1) + p3.succeed(1) + _ = try! f.wait() + } + + let el = EmbeddedEventLoop() + for _ in 0..<1000 { + doThenAndFriends(loop: el) + doAnd(loop: el) + } + return 1000 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift index 2e0173ba0..42e8e5731 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_future_lots_of_callbacks.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2025 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -37,19 +37,52 @@ func run(identifier: String) { // flatMapThrowing allocates a future on the error path and // calls `flatMap`, which also allocates, so this is two. throw MyError() - }.flatMapError { (err: Error) -> EventLoopFuture in + }.flatMapError { (err: Error) -> EventLoopFuture in // This call allocates a new Future, and so does flatMapError, // so this is two Futures. loop.makeFailedFuture(err) - }.flatMapErrorThrowing { (err: Error) -> Int in + }.flatMapErrorThrowing { (err: Error) -> Int? in // flatMapError allocates a new Future, and calls flatMapError, // so this is two Futures throw err - }.recover { (err: Error) -> Int in + }.recover { (err: Error) -> Int? in // recover allocates a future, and calls flatMapError, so // this is two Futures. + nil + }.unwrap { () -> Int in + // unwrap calls map, with an extra closure, so this is three. 1 + }.always { (Int) -> Void in + // This is a do-nothing call, but it can't be optimised out. + // always calls whenComplete but adds a new closure, so it allocates + // two times. + _ = 1 + 1 + }.flatMapResult { (Int) -> Result in + // flatMapResult allocates a new future and creates a _whenComplete closure, + // so this is two. + .success(5) } + .unwrap(orReplace: 5) // Same as unwrap above, this is three. + + // Add some when*. + f.whenSuccess { + // whenSuccess should be just one. + _ = $0 + 1 + } + f.whenFailure { _ in + // whenFailure should also be just one. + fatalError() + } + f.whenComplete { + // whenComplete should also be just one. + switch $0 { + case .success: + () + case .failure: + fatalError() + } + } + p.succeed(0) // Wait also allocates a lock. From e19202cb015be4cda2ecbde38c8eafe028016628 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 13 Jan 2025 20:31:22 +0000 Subject: [PATCH 41/93] Avoid abstraction overheads on isolated ELF (#3055) Motivation: Unfortunately, closure composition is really expensive: closures that capture closures always heap allocate. To make ELF.Isolated perform well, then, we need to inline the method bodies directly. Modifications: - Add some isolated functions into ELF for enqueueing callbacks. - Inline the implementation of the ELF methods into the isolated view. Result: Allocation counts match between isolated/nonisolated. --- .../tests_04_performance/Thresholds/5.10.json | 2 +- .../tests_04_performance/Thresholds/5.9.json | 2 +- .../tests_04_performance/Thresholds/6.0.json | 2 +- .../Thresholds/nightly-6.0.json | 2 +- .../Thresholds/nightly-main.json | 2 +- .../EventLoopFuture+AssumeIsolated.swift | 167 +++++++++++++----- Sources/NIOCore/EventLoopFuture.swift | 20 ++- 7 files changed, 146 insertions(+), 51 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index a13f5e39d..ecf2101b4 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -32,7 +32,7 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_assume_isolated_lots_of_callbacks": 92050, + "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index 82cfbff08..edd71c82f 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -32,7 +32,7 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_assume_isolated_lots_of_callbacks": 91050, + "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index a13f5e39d..ecf2101b4 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -32,7 +32,7 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_assume_isolated_lots_of_callbacks": 92050, + "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index a13f5e39d..ecf2101b4 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -32,7 +32,7 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_assume_isolated_lots_of_callbacks": 92050, + "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 700050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 1009e21d2..36eadc747 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -32,7 +32,7 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "future_assume_isolated_lots_of_callbacks": 92050, + "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, "get_100000_headers_canonical_form": 500050, diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index 4748ef320..951c8656f 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -213,10 +213,25 @@ extension EventLoopFuture { public func flatMap( _ callback: @escaping (Value) -> EventLoopFuture ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMap { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let t): + let futureU = callback(t) + if futureU.eventLoop.inEventLoop { + return futureU._addCallback { + next._setValue(value: futureU._value!) + } + } else { + futureU.cascade(to: next) + return CallbackList() + } + case .failure(let error): + return next._setValue(value: .failure(error)) + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -238,10 +253,22 @@ extension EventLoopFuture { public func flatMapThrowing( _ callback: @escaping (Value) throws -> NewValue ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapThrowing { - try unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let t): + do { + let r = try callback(t) + return next._setValue(value: .success(r)) + } catch { + return next._setValue(value: .failure(error)) + } + case .failure(let e): + return next._setValue(value: .failure(e)) + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -263,10 +290,22 @@ extension EventLoopFuture { public func flatMapErrorThrowing( _ callback: @escaping (Error) throws -> Value ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapErrorThrowing { - try unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let t): + return next._setValue(value: .success(t)) + case .failure(let e): + do { + let r = try callback(e) + return next._setValue(value: .success(r)) + } catch { + return next._setValue(value: .failure(error)) + } + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -300,10 +339,17 @@ extension EventLoopFuture { public func map( _ callback: @escaping (Value) -> (NewValue) ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.map { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + if NewValue.self == Value.self && NewValue.self == Void.self { + self.whenSuccess(callback as! (Value) -> Void) + return self as! EventLoopFuture.Isolated + } else { + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + next._setValue(value: base._value!.map(callback)) + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() + } } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -325,10 +371,25 @@ extension EventLoopFuture { public func flatMapError( _ callback: @escaping (Error) -> EventLoopFuture ) -> EventLoopFuture.Isolated where Value: Sendable { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.flatMapError { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let t): + return next._setValue(value: .success(t)) + case .failure(let e): + let t = callback(e) + if t.eventLoop.inEventLoop { + return t._addCallback { + next._setValue(value: t._value!) + } + } else { + t.cascade(to: next) + return CallbackList() + } + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is fulfilled, run the provided callback, which @@ -349,10 +410,22 @@ extension EventLoopFuture { public func flatMapResult( _ body: @escaping (Value) -> Result ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(body) - return self._wrapped.flatMapResult { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let value): + switch body(value) { + case .success(let newValue): + return next._setValue(value: .success(newValue)) + case .failure(let error): + return next._setValue(value: .failure(error)) + } + case .failure(let e): + return next._setValue(value: .failure(e)) + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// When the current `EventLoopFuture` is in an error state, run the provided callback, which @@ -372,10 +445,17 @@ extension EventLoopFuture { public func recover( _ callback: @escaping (Error) -> Value ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.recover { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + let next = EventLoopPromise.makeUnleakablePromise(eventLoop: self._wrapped.eventLoop) + let base = self._wrapped + base._whenCompleteIsolated { + switch base._value! { + case .success(let t): + return next._setValue(value: .success(t)) + case .failure(let e): + return next._setValue(value: .success(callback(e))) + } + } + return next.futureResult.assumeIsolatedUnsafeUnchecked() } /// Adds an observer callback to this `EventLoopFuture` that is called when the @@ -391,9 +471,12 @@ extension EventLoopFuture { @inlinable @available(*, noasync) public func whenSuccess(_ callback: @escaping (Value) -> Void) { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.whenSuccess { - unsafeTransfer.wrappedValue($0) + let base = self._wrapped + base._whenCompleteIsolated { + if case .success(let t) = base._value! { + callback(t) + } + return CallbackList() } } @@ -410,9 +493,12 @@ extension EventLoopFuture { @inlinable @available(*, noasync) public func whenFailure(_ callback: @escaping (Error) -> Void) { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.whenFailure { - unsafeTransfer.wrappedValue($0) + let base = self._wrapped + base._whenCompleteIsolated { + if case .failure(let e) = base._value! { + callback(e) + } + return CallbackList() } } @@ -426,9 +512,10 @@ extension EventLoopFuture { public func whenComplete( _ callback: @escaping (Result) -> Void ) { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.whenComplete { - unsafeTransfer.wrappedValue($0) + let base = self._wrapped + base._whenCompleteIsolated { + callback(base._value!) + return CallbackList() } } @@ -443,10 +530,8 @@ extension EventLoopFuture { public func always( _ callback: @escaping (Result) -> Void ) -> EventLoopFuture.Isolated { - let unsafeTransfer = UnsafeTransfer(callback) - return self._wrapped.always { - unsafeTransfer.wrappedValue($0) - }.assumeIsolatedUnsafeUnchecked() + self.whenComplete { result in callback(result) } + return self } /// Unwrap an `EventLoopFuture` where its type parameter is an `Optional`. diff --git a/Sources/NIOCore/EventLoopFuture.swift b/Sources/NIOCore/EventLoopFuture.swift index 4579576ed..482bdb5af 100644 --- a/Sources/NIOCore/EventLoopFuture.swift +++ b/Sources/NIOCore/EventLoopFuture.swift @@ -26,9 +26,9 @@ import Dispatch /// In particular, note that _run() here continues to obtain and execute lists of callbacks until it completes. /// This eliminates recursion when processing `flatMap()` chains. @usableFromInline -internal struct CallbackList: Sendable { +internal struct CallbackList { @usableFromInline - internal typealias Element = @Sendable () -> CallbackList + internal typealias Element = () -> CallbackList @usableFromInline internal var firstCallback: Optional @usableFromInline @@ -115,6 +115,9 @@ internal struct CallbackList: Sendable { } } +@available(*, unavailable) +extension CallbackList: Sendable {} + /// Internal error for operations that return results that were not replaced @usableFromInline internal struct OperationPlaceholderError: Error { @@ -779,7 +782,7 @@ extension EventLoopFuture { /// Add a callback. If there's already a value, invoke it and return the resulting list of new callback functions. @inlinable - internal func _addCallback(_ callback: @escaping @Sendable () -> CallbackList) -> CallbackList { + internal func _addCallback(_ callback: @escaping () -> CallbackList) -> CallbackList { self.eventLoop.assertInEventLoop() if self._value == nil { self._callbacks.append(callback) @@ -800,14 +803,21 @@ extension EventLoopFuture { @inlinable internal func _internalWhenComplete(_ callback: @escaping @Sendable () -> CallbackList) { if self.eventLoop.inEventLoop { - self._addCallback(callback)._run() + self._whenCompleteIsolated(callback) } else { self.eventLoop.execute { - self._addCallback(callback)._run() + self._whenCompleteIsolated(callback) } } } + /// Add a callback. If there's already a value, run as much of the chain as we can. + @inlinable + internal func _whenCompleteIsolated(_ callback: @escaping () -> CallbackList) { + self.eventLoop.assertInEventLoop() + self._addCallback(callback)._run() + } + /// Adds an observer callback to this `EventLoopFuture` that is called when the /// `EventLoopFuture` has a success result. /// From 9d7cf6825e8c473d4c537cd81f229b477dec2ef6 Mon Sep 17 00:00:00 2001 From: hamzahrmalik Date: Tue, 14 Jan 2025 14:13:20 +0000 Subject: [PATCH 42/93] Clarify docs on EventLoopFuture/assumeIsolatedUnsafeUnchecked (#3058) - Clarify that it will only crash on release builds - Fix the claim that the function can be used from async contexts (it is marked noasync) --- Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index 951c8656f..f743550fd 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -606,11 +606,10 @@ extension EventLoopFuture { /// Returns a variant of this ``EventLoopFuture`` with less strict /// `Sendable` requirements. Can only be called from on the /// ``EventLoop`` to which this ``EventLoopFuture`` is bound, will crash - /// if that invariant fails to be met. + /// if that invariant fails to be met in debug builds. /// /// This is an unsafe version of ``EventLoopFuture/assumeIsolated()`` which - /// omits the runtime check in release builds and doesn't prevent you using it - /// from using it in async contexts. + /// omits the runtime check in release builds. @inlinable @available(*, noasync) public func assumeIsolatedUnsafeUnchecked() -> Isolated { From 6fb31ea6892dd171bcdb12e3f72dcfb50f73e72d Mon Sep 17 00:00:00 2001 From: Manolo van Ee Date: Tue, 14 Jan 2025 16:28:58 +0100 Subject: [PATCH 43/93] NIOAsyncWriter: Fix suspending yield when writer is finished (#3044) This fixes hitting the following preconditionFailure in NIOAsyncWriter: "This should have already been handled by `yield()`". It doesn't expect a yield to be suspended when the state is `.writerFinished`, but this can definitely happen. This seemed to be the correct solution to me, but please check it carefully, because I'm unfamiliar with this code. I'm not happy about the test for this. It's blocking the `didYield` call for a while, to make sure the correct state is reached. See also the 'FIXME' line. What would be a better way to do this? --------- Co-authored-by: Cory Benfield --- .../AsyncSequences/NIOAsyncWriter.swift | 35 ++++++++++++++- .../AsyncSequences/NIOAsyncWriterTests.swift | 45 +++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift index badc34f96..f232d518f 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift @@ -1173,7 +1173,38 @@ extension NIOAsyncWriter { delegate: delegate ) - case .initial, .finished, .writerFinished: + case .writerFinished( + let isWritable, + let inDelegateOutcall, + var suspendedYields, + let cancelledYields, + let bufferedYieldIDs, + let delegate, + let error + ): + // We have a suspended yield at this point that hasn't been cancelled yet. + // It was buffered before we became finished, so we still have to deliver it. + // We need to store the yield now. + + self._state = .modifying + + let suspendedYield = SuspendedYield( + yieldID: yieldID, + continuation: continuation + ) + suspendedYields.append(suspendedYield) + + self._state = .writerFinished( + isWritable: isWritable, + inDelegateOutcall: inDelegateOutcall, + suspendedYields: suspendedYields, + cancelledYields: cancelledYields, + bufferedYieldIDs: bufferedYieldIDs, + delegate: delegate, + error: error + ) + + case .initial, .finished: preconditionFailure("This should have already been handled by `yield()`") case .modifying: @@ -1501,7 +1532,7 @@ extension NIOAsyncWriter { self._state = .writerFinished( isWritable: isWritable, - inDelegateOutcall: inDelegateOutcall, + inDelegateOutcall: false, suspendedYields: .init(), cancelledYields: cancelledYields, bufferedYieldIDs: bufferedYieldIDs, diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift index 31c680b8b..4f15ac9af 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift @@ -606,6 +606,51 @@ final class NIOAsyncWriterTests: XCTestCase { self.assert(suspendCallCount: 1, yieldCallCount: 1, terminateCallCount: 1) } + func testSuspendingBufferedYield_whenWriterFinished() async throws { + self.sink.setWritability(to: false) + + let bothSuspended = expectation(description: "suspended on both yields") + let suspendedAgain = ConditionLock(value: false) + self.delegate.didSuspendHandler = { + if self.delegate.didSuspendCallCount == 2 { + bothSuspended.fulfill() + } else if self.delegate.didSuspendCallCount > 2 { + suspendedAgain.lock() + suspendedAgain.unlock(withValue: true) + } + } + + self.delegate.didYieldHandler = { _ in + if self.delegate.didYieldCallCount == 1 { + // Delay this yield until the other yield is suspended again. + // FIXME: This will never finish if no other thread is handling the other yield. + suspendedAgain.lock(whenValue: true) + suspendedAgain.unlock() + } + } + + let task1 = Task { [writer] in + try await writer!.yield("message1") + } + let task2 = Task { [writer] in + try await writer!.yield("message2") + } + + await fulfillment(of: [bothSuspended], timeout: 1) + self.writer.finish() + + self.assert(suspendCallCount: 2, yieldCallCount: 0, terminateCallCount: 0) + + // We have to become writable again to unbuffer the yields + // The first call to didYield will pause, so that the other yield will be suspended again. + self.sink.setWritability(to: true) + + await XCTAssertNoThrow(try await task1.value) + await XCTAssertNoThrow(try await task2.value) + + self.assert(suspendCallCount: 3, yieldCallCount: 2, terminateCallCount: 1) + } + func testWriterFinish_whenFinished() { // This tests just checks that finishing again is a no-op self.writer.finish() From 96877aff7f63db6b01b3ec7b5769c0e1b3c79a4e Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 14 Jan 2025 16:36:17 +0000 Subject: [PATCH 44/93] Fix compiling on 6.1 (#3057) Motivation: Swift 6.1 nightlies have added many new warnings and errors to NIO. This patch resolves all of them. Modifications: - Clean up missing imports - Move away from @_implementationOnly where necessary - Fix a few things where Sendable mismatches were present. Result: Clean compile again --------- Co-authored-by: Johannes Weiss --- Package.swift | 3 ++- Sources/NIOCore/EventLoop.swift | 5 +++-- Sources/NIOCore/FileRegion.swift | 3 --- Sources/NIOEmbedded/AsyncTestingEventLoop.swift | 9 +++++---- Sources/NIOHTTP1/HTTPDecoder.swift | 13 +++++++++---- Sources/NIOPosix/DatagramVectorReadManager.swift | 1 + Sources/NIOPosix/PendingDatagramWritesManager.swift | 1 + Sources/NIOPosix/SelectableEventLoop.swift | 2 +- Sources/NIOPosix/SelectorKqueue.swift | 1 + Tests/NIOPosixTests/HappyEyeballsTest.swift | 1 + Tests/NIOPosixTests/MulticastTest.swift | 2 +- .../PendingDatagramWritesManagerTests.swift | 1 + 12 files changed, 26 insertions(+), 16 deletions(-) diff --git a/Package.swift b/Package.swift index 610fbf6db..14f9183f9 100644 --- a/Package.swift +++ b/Package.swift @@ -443,6 +443,7 @@ let package = Package( "NIOConcurrencyHelpers", "NIOEmbedded", "CNIOLinux", + "CNIODarwin", "NIOTLS", ] ), @@ -558,7 +559,7 @@ let package = Package( if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { package.dependencies += [ .package(url: "https://github.com/apple/swift-atomics.git", from: "1.1.0"), - .package(url: "https://github.com/apple/swift-collections.git", from: "1.0.2"), + .package(url: "https://github.com/apple/swift-collections.git", from: "1.1.0"), .package(url: "https://github.com/apple/swift-system.git", from: "1.4.0"), ] } else { diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 021725af9..1b619a3b0 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -761,12 +761,13 @@ extension EventLoop { /// - Returns: An `EventLoopFuture` containing the result of `task`'s execution. @inlinable @preconcurrency - public func submit(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture { + public func submit(_ task: @escaping @Sendable () throws -> T) -> EventLoopFuture { let promise: EventLoopPromise = makePromise(file: #fileID, line: #line) self.execute { do { - promise.succeed(try task()) + // UnsafeUnchecked is allowed here because we know we are on the EL. + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) } catch let err { promise.fail(err) } diff --git a/Sources/NIOCore/FileRegion.swift b/Sources/NIOCore/FileRegion.swift index 1b1f1c5b0..7ceaacd5d 100644 --- a/Sources/NIOCore/FileRegion.swift +++ b/Sources/NIOCore/FileRegion.swift @@ -93,9 +93,6 @@ public struct FileRegion: Sendable { } } -@available(*, unavailable) -extension FileRegion: Sendable {} - extension FileRegion { /// Create a new `FileRegion` forming a complete file. /// diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 3321a6a60..b0ee04036 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -131,7 +131,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { self.scheduledTasks.removeFirst { $0.id == taskID } } - private func insertTask( + private func insertTask( taskID: UInt64, deadline: NIODeadline, promise: EventLoopPromise, @@ -145,7 +145,8 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { insertOrder: self.nextTaskNumber(), task: { do { - promise.succeed(try task()) + // UnsafeUnchecked is acceptable because we know we're in the loop here. + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) } catch let err { promise.fail(err) } @@ -159,7 +160,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// - see: `EventLoop.scheduleTask(deadline:_:)` @discardableResult @preconcurrency - public func scheduleTask( + public func scheduleTask( deadline: NIODeadline, _ task: @escaping @Sendable () throws -> T ) -> Scheduled { @@ -201,7 +202,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// - see: `EventLoop.scheduleTask(in:_:)` @discardableResult @preconcurrency - public func scheduleTask(in: TimeAmount, _ task: @escaping @Sendable () throws -> T) -> Scheduled { + public func scheduleTask(in: TimeAmount, _ task: @escaping @Sendable () throws -> T) -> Scheduled { self.scheduleTask(deadline: self.now + `in`, task) } diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index a38c775cf..763319891 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -12,9 +12,14 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly import CNIOLLHTTP import NIOCore +#if compiler(>=6.1) +private import CNIOLLHTTP +#else +@_implementationOnly import CNIOLLHTTP +#endif + extension UnsafeMutablePointer where Pointee == llhttp_t { /// Returns the `KeepAliveState` for the current message that is parsed. fileprivate var keepAliveState: KeepAliveState { @@ -631,7 +636,7 @@ public final class HTTPDecoder: ByteToMessageDecoder, HTTPDecoderDelega self.url = String(decoding: bytes, as: Unicode.UTF8.self) } - func didFinishHead( + fileprivate func didFinishHead( versionMajor: Int, versionMinor: Int, isUpgrade: Bool, @@ -815,7 +820,7 @@ extension HTTPParserError { /// - Parameter fromCHTTPParserErrno: The error from the underlying library. /// - Returns: The corresponding `HTTPParserError`, or `nil` if there is no /// corresponding error. - static func httpError(fromCHTTPParserErrno: llhttp_errno_t) -> HTTPParserError? { + fileprivate static func httpError(fromCHTTPParserErrno: llhttp_errno_t) -> HTTPParserError? { switch fromCHTTPParserErrno { case HPE_INTERNAL: return .invalidInternalState @@ -874,7 +879,7 @@ extension HTTPMethod { /// /// - Parameter httpParserMethod: The method returned by `http_parser`. /// - Returns: The corresponding `HTTPMethod`. - static func from(httpParserMethod: llhttp_method) -> HTTPMethod { + fileprivate static func from(httpParserMethod: llhttp_method) -> HTTPMethod { switch httpParserMethod { case HTTP_DELETE: return .DELETE diff --git a/Sources/NIOPosix/DatagramVectorReadManager.swift b/Sources/NIOPosix/DatagramVectorReadManager.swift index 7f6ced454..88224bf1d 100644 --- a/Sources/NIOPosix/DatagramVectorReadManager.swift +++ b/Sources/NIOPosix/DatagramVectorReadManager.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import CNIODarwin import CNIOLinux import NIOCore diff --git a/Sources/NIOPosix/PendingDatagramWritesManager.swift b/Sources/NIOPosix/PendingDatagramWritesManager.swift index 8c058bd4e..e9f201ce9 100644 --- a/Sources/NIOPosix/PendingDatagramWritesManager.swift +++ b/Sources/NIOPosix/PendingDatagramWritesManager.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIODarwin import CNIOLinux import NIOCore diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 9449d6297..04e0cc0bb 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -60,7 +60,7 @@ public protocol NIOEventLoopMetricsDelegate: Sendable { /// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread` /// is guaranteed to never change! @usableFromInline -internal final class SelectableEventLoop: EventLoop { +internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { static let strictModeEnabled: Bool = { switch getenv("SWIFTNIO_STRICT").map({ String.init(cString: $0).lowercased() }) { diff --git a/Sources/NIOPosix/SelectorKqueue.swift b/Sources/NIOPosix/SelectorKqueue.swift index 4c45dd159..34651bd49 100644 --- a/Sources/NIOPosix/SelectorKqueue.swift +++ b/Sources/NIOPosix/SelectorKqueue.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import NIOConcurrencyHelpers import NIOCore #if canImport(Darwin) diff --git a/Tests/NIOPosixTests/HappyEyeballsTest.swift b/Tests/NIOPosixTests/HappyEyeballsTest.swift index 29f35820f..7e91b60a6 100644 --- a/Tests/NIOPosixTests/HappyEyeballsTest.swift +++ b/Tests/NIOPosixTests/HappyEyeballsTest.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIOLinux import NIOEmbedded import XCTest diff --git a/Tests/NIOPosixTests/MulticastTest.swift b/Tests/NIOPosixTests/MulticastTest.swift index c9ae19d29..e2fe3a8b0 100644 --- a/Tests/NIOPosixTests/MulticastTest.swift +++ b/Tests/NIOPosixTests/MulticastTest.swift @@ -11,7 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// - +import CNIOLinux import NIOCore import NIOPosix import XCTest diff --git a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift index b94e37cf9..dee71c2a6 100644 --- a/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift +++ b/Tests/NIOPosixTests/PendingDatagramWritesManagerTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import CNIODarwin import CNIOLinux import NIOEmbedded import XCTest From ed8e3950a8aa244e186f8253eb4f37e0e2e8a58e Mon Sep 17 00:00:00 2001 From: Manolo van Ee Date: Tue, 14 Jan 2025 17:58:52 +0100 Subject: [PATCH 45/93] Remove unnecessary 'FIXME' comment (#3059) This was left in when pull request #3044 was merged, but as discussed on that pull request, this doesn't need to be fixed. --- Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift index 4f15ac9af..848c65f86 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift @@ -623,7 +623,6 @@ final class NIOAsyncWriterTests: XCTestCase { self.delegate.didYieldHandler = { _ in if self.delegate.didYieldCallCount == 1 { // Delay this yield until the other yield is suspended again. - // FIXME: This will never finish if no other thread is handling the other yield. suspendedAgain.lock(whenValue: true) suspendedAgain.unlock() } From 6ac01d173462705f8163dbaac52a6c2d565ea3e0 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 14 Jan 2025 20:49:33 +0000 Subject: [PATCH 46/93] Clean up sendability in the bootstraps (#3051) ### Motivation: The bootstraps are the next most obvious target for cleaning up Sendability issues. These issues are mostly just missing annotations, but there are a few places where we had actual latent threading bugs that were missed. A lot more of the control flow is made more explicit in this patch, and in general it should get a lot easier to be confident that the code is correct. ### Modifications: - Add necessary `@Sendable` annotations - Clean up some incorrect `self` captures of bootstraps, which are not `Sendable`, and which could lead to real threading bugs - Make a few methods `static` to avoid needing to capture `self` at all. - Make a few threading assumptions clear by using the isolated views or the sync operations - Add some missing `Sendable` constraints on interior generic functions. ### Result: Better safety, better correctness in the bootstraps. --- .../tests_04_performance/Thresholds/5.10.json | 4 +- .../tests_04_performance/Thresholds/5.9.json | 4 +- .../tests_04_performance/Thresholds/6.0.json | 4 +- .../Thresholds/nightly-6.0.json | 4 +- .../Thresholds/nightly-main.json | 4 +- Sources/NIOPosix/Bootstrap.swift | 141 +++++++++++------- dev/malloc-aggregation.d | 17 ++- dev/stackdiff-dtrace.py | 14 +- 8 files changed, 118 insertions(+), 74 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index ecf2101b4..844e97841 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 389050, + "1_reqs_1000_conn": 384050, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -41,7 +41,7 @@ "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 319, + "ping_pong_1000_reqs_1_conn": 314, "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index edd71c82f..6e9df5a2f 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 398050, + "1_reqs_1000_conn": 393050, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -41,7 +41,7 @@ "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 334, + "ping_pong_1000_reqs_1_conn": 329, "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index ecf2101b4..5235f29b3 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 389050, + "1_reqs_1000_conn": 384000, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -41,7 +41,7 @@ "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 319, + "ping_pong_1000_reqs_1_conn": 314, "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index ecf2101b4..5235f29b3 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 389050, + "1_reqs_1000_conn": 384000, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -41,7 +41,7 @@ "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 319, + "ping_pong_1000_reqs_1_conn": 314, "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 36eadc747..5500c5235 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 389050, + "1_reqs_1000_conn": 384050, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -41,7 +41,7 @@ "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 500050, "modifying_1000_circular_buffer_elements": 0, "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 319, + "ping_pong_1000_reqs_1_conn": 314, "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 6d1312b6a..1ea1d311f 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -386,7 +386,7 @@ public final class ServerBootstrap { private func bind0( makeServerChannel: (_ eventLoop: SelectableEventLoop, _ childGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel, - _ register: @escaping (EventLoop, ServerSocketChannel) -> EventLoopFuture + _ register: @escaping @Sendable (EventLoop, ServerSocketChannel) -> EventLoopFuture ) -> EventLoopFuture { let eventLoop = self.group.next() let childEventLoopGroup = self.childGroup @@ -410,15 +410,18 @@ public final class ServerBootstrap { serverChannelOptions.applyAllChannelOptions(to: serverChannel).flatMap { serverChannelInit(serverChannel) }.flatMap { - serverChannel.pipeline.addHandler( - AcceptHandler( - childChannelInitializer: childChannelInit, - childChannelOptions: childChannelOptions - ), - name: "AcceptHandler" - ) - }.flatMap { - register(eventLoop, serverChannel) + do { + try serverChannel.pipeline.syncOperations.addHandler( + AcceptHandler( + childChannelInitializer: childChannelInit, + childChannelOptions: childChannelOptions + ), + name: "AcceptHandler" + ) + return register(eventLoop, serverChannel) + } catch { + return eventLoop.makeFailedFuture(error) + } }.map { serverChannel as Channel }.flatMapError { error in @@ -434,11 +437,11 @@ public final class ServerBootstrap { public typealias InboundIn = SocketChannel public typealias InboundOut = SocketChannel - private let childChannelInit: ((Channel) -> EventLoopFuture)? + private let childChannelInit: (@Sendable (Channel) -> EventLoopFuture)? private let childChannelOptions: ChannelOptions.Storage init( - childChannelInitializer: ((Channel) -> EventLoopFuture)?, + childChannelInitializer: (@Sendable (Channel) -> EventLoopFuture)?, childChannelOptions: ChannelOptions.Storage ) { self.childChannelInit = childChannelInitializer @@ -461,10 +464,12 @@ public final class ServerBootstrap { let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } + let childChannelOptions = self.childChannelOptions @inline(__always) + @Sendable func setupChildChannel() -> EventLoopFuture { - self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture in + childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture in childEventLoop.assertInEventLoop() return childChannelInit(accepted) } @@ -472,20 +477,17 @@ public final class ServerBootstrap { @inline(__always) func fireThroughPipeline(_ future: EventLoopFuture, context: ChannelHandlerContext) { + // Strictly these asserts are redundant with future.assumeIsolated(), but as this code + // has guarantees that can be quite hard to follow we keep them here. ctxEventLoop.assertInEventLoop() assert(ctxEventLoop === context.eventLoop) - let loopBoundContext = context.loopBound - future.flatMap { (_) -> EventLoopFuture in - let context = loopBoundContext.value - ctxEventLoop.assertInEventLoop() + future.assumeIsolated().flatMap { (_) -> EventLoopFuture in guard context.channel.isActive else { return ctxEventLoop.makeFailedFuture(ChannelError._ioOnClosedChannel) } context.fireChannelRead(Self.wrapInboundOut(accepted)) return context.eventLoop.makeSucceededFuture(()) }.whenFailure { error in - let context = loopBoundContext.value - ctxEventLoop.assertInEventLoop() self.closeAndFire(context: context, accepted: accepted, err: error) } } @@ -770,10 +772,9 @@ extension Channel { // implementation, `epoll` will send us `EPOLLHUP`. To have it run synchronously, we need to invoke the // `flatMap` on the eventloop that the `register` will succeed on. self.eventLoop.assertInEventLoop() - return self.register().flatMap { - self.eventLoop.assertInEventLoop() - return body(self) - } + return self.register().assumeIsolated().flatMap { + body(self) + }.nonisolated() } } @@ -811,8 +812,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { if let protocolHandlers = self.protocolHandlers { let channelInitializer = _channelInitializer return { channel in - channelInitializer(channel).flatMap { - channel.pipeline.addHandlers(protocolHandlers(), position: .first) + channelInitializer(channel).hop(to: channel.eventLoop).flatMapThrowing { + try channel.pipeline.syncOperations.addHandlers(protocolHandlers(), position: .first) } } } else { @@ -1005,11 +1006,14 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { return connector.resolveAndConnect() } - private func connect(freshChannel channel: Channel, address: SocketAddress) -> EventLoopFuture { + private static func connect( + freshChannel channel: Channel, + address: SocketAddress, + connectTimeout: TimeAmount + ) -> EventLoopFuture { let connectPromise = channel.eventLoop.makePromise(of: Void.self) channel.connect(to: address, promise: connectPromise) - let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) { - [connectTimeout = self.connectTimeout] in + let cancelTask = channel.eventLoop.scheduleTask(in: connectTimeout) { connectPromise.fail(ChannelError.connectTimeout(connectTimeout)) channel.close(promise: nil) } @@ -1024,8 +1028,9 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { injectedChannel: SocketChannel, to address: SocketAddress ) -> EventLoopFuture { - self.initializeAndRegisterChannel(injectedChannel) { channel in - self.connect(freshChannel: channel, address: address) + let connectTimeout = self.connectTimeout + return self.initializeAndRegisterChannel(injectedChannel) { channel in + Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout) } } @@ -1035,11 +1040,13 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { /// - address: The address to connect to. /// - Returns: An `EventLoopFuture` to deliver the `Channel` when connected. public func connect(to address: SocketAddress) -> EventLoopFuture { - self.initializeAndRegisterNewChannel( + let connectTimeout = self.connectTimeout + + return self.initializeAndRegisterNewChannel( eventLoop: self.group.next(), protocolFamily: address.protocol ) { channel in - self.connect(freshChannel: channel, address: address) + Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout) } } @@ -1103,6 +1110,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture { let eventLoop = group.next() let channelInitializer = self.channelInitializer + let options = self._channelOptions + let channel: SocketChannel do { channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, socket: socket) @@ -1110,9 +1119,10 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() - return self._channelOptions.applyAllChannelOptions(to: channel).flatMap { + return options.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() @@ -1137,7 +1147,7 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { private func initializeAndRegisterNewChannel( eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, - _ body: @escaping (Channel) -> EventLoopFuture + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { let channel: SocketChannel do { @@ -1150,16 +1160,18 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { private func initializeAndRegisterChannel( _ channel: SocketChannel, - _ body: @escaping (Channel) -> EventLoopFuture + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { let channelInitializer = self.channelInitializer let channelOptions = self._channelOptions let eventLoop = channel.eventLoop + let bindTarget = self.bindTarget @inline(__always) + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() - return channelOptions.applyAllChannelOptions(to: channel).flatMap { [bindTarget = self.bindTarget] in + return channelOptions.applyAllChannelOptions(to: channel).flatMap { if let bindTarget = bindTarget { return channel.bind(to: bindTarget).flatMap { channelInitializer(channel) @@ -1230,6 +1242,7 @@ extension ClientBootstrap { channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture ) async throws -> Output { let eventLoop = self.group.next() + let connectTimeout = self.connectTimeout return try await self.initializeAndRegisterNewChannel( eventLoop: eventLoop, protocolFamily: address.protocol, @@ -1238,7 +1251,7 @@ extension ClientBootstrap { eventLoop.makeSucceededFuture(output) }, { channel in - self.connect(freshChannel: channel, address: address) + Self.connect(freshChannel: channel, address: address, connectTimeout: connectTimeout) } ).get().1 } @@ -1322,7 +1335,7 @@ extension ClientBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - func connect( + func connect( host: String, port: Int, eventLoop: EventLoop, @@ -1359,7 +1372,10 @@ extension ClientBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func withConnectedSocket( + private func withConnectedSocket< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( eventLoop: EventLoop, socket: NIOBSDSocket.Handle, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -1382,14 +1398,17 @@ extension ClientBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func initializeAndRegisterNewChannel( + private func initializeAndRegisterNewChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< PostRegistrationTransformationResult >, - _ body: @escaping (Channel) -> EventLoopFuture + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture<(Channel, PostRegistrationTransformationResult)> { let channel: SocketChannel do { @@ -1408,7 +1427,10 @@ extension ClientBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func initializeAndRegisterChannel( + private func initializeAndRegisterChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( channel: SocketChannel, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture, @@ -1416,9 +1438,12 @@ extension ClientBootstrap { PostRegistrationTransformationResult > ) -> EventLoopFuture { - let channelInitializer = { channel in - self.channelInitializer(channel) + let bootstrapChannelInitializer = self.channelInitializer + let channelInitializer = { @Sendable channel in + bootstrapChannelInitializer(channel).hop(to: channel.eventLoop) + .assumeIsolated() .flatMap { channelInitializer(channel) } + .nonisolated() } let channelOptions = self._channelOptions let eventLoop = channel.eventLoop @@ -1431,6 +1456,7 @@ extension ClientBootstrap { return channelOptions .applyAllChannelOptions(to: channel) + .assumeIsolated() .flatMap { if let bindTarget = bindTarget { return @@ -1455,6 +1481,7 @@ extension ClientBootstrap { channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } + .nonisolated() } if eventLoop.inEventLoop { @@ -1708,10 +1735,10 @@ public final class DatagramBootstrap { private func withNewChannel( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, - _ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture + _ bringup: @escaping @Sendable (EventLoop, DatagramChannel) -> EventLoopFuture ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } + let channelInitializer = self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) } let channelOptions = self._channelOptions let channel: DatagramChannel @@ -1721,6 +1748,7 @@ public final class DatagramBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { @@ -1927,7 +1955,7 @@ extension DatagramBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func connect0( + private func connect0( makeSocketAddress: () throws -> SocketAddress, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< @@ -1958,7 +1986,7 @@ extension DatagramBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func bind0( + private func bind0( makeSocketAddress: () throws -> SocketAddress, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< @@ -1989,7 +2017,10 @@ extension DatagramBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func makeConfiguredChannel( + private func makeConfiguredChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, registration: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -1998,9 +2029,14 @@ extension DatagramBootstrap { > ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = { (channel: Channel) -> EventLoopFuture in - let initializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } - return initializer(channel).flatMap { channelInitializer(channel) } + let bootstrapChannelInitializer = + self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) } + let channelInitializer = { @Sendable (channel: Channel) -> EventLoopFuture in + bootstrapChannelInitializer(channel) + .hop(to: channel.eventLoop) + .assumeIsolated() + .flatMap { channelInitializer(channel) } + .nonisolated() } let channelOptions = self._channelOptions @@ -2011,6 +2047,7 @@ extension DatagramBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { diff --git a/dev/malloc-aggregation.d b/dev/malloc-aggregation.d index a0c2f3aa4..af9803fc3 100755 --- a/dev/malloc-aggregation.d +++ b/dev/malloc-aggregation.d @@ -28,17 +28,24 @@ printf("=====\n"); } +pid$target::aligned_alloc:entry, +pid$target::calloc:entry, pid$target::malloc:entry, pid$target::posix_memalign:entry, pid$target::realloc:entry, pid$target::reallocf:entry, -pid$target::calloc:entry, pid$target::valloc:entry, -pid$target::malloc_zone_malloc:entry, -pid$target::malloc_zone_realloc:entry, +pid$target::malloc_type_aligned_alloc:entry, +pid$target::malloc_type_calloc:entry, +pid$target::malloc_type_malloc:entry, +pid$target::malloc_type_posix_memalign:entry, +pid$target::malloc_type_realloc:entry, +pid$target::malloc_type_valloc:entry, pid$target::malloc_zone_calloc:entry, -pid$target::malloc_zone_valloc:entry, -pid$target::malloc_zone_memalign:entry { +pid$target::malloc_zone_malloc:entry, +pid$target::malloc_zone_memalign:entry, +pid$target::malloc_zone_realloc:entry, +pid$target::malloc_zone_valloc:entry { @malloc_calls[ustack()] = count(); } diff --git a/dev/stackdiff-dtrace.py b/dev/stackdiff-dtrace.py index 6f95335f5..a277915d6 100755 --- a/dev/stackdiff-dtrace.py +++ b/dev/stackdiff-dtrace.py @@ -17,7 +17,7 @@ import collections import re import sys -num_regex = "^ +([0-9]+)$" +num_regex = b"^ +([0-9]+)$" def put_in_dict(path): @@ -54,10 +54,10 @@ def put_in_dict(path): # libswiftCore.dylib`swift_allocObject+0x27 # (truncated) dictionary = collections.defaultdict(list) - with open(path, "r") as f: + with open(path, "rb") as f: current_stack = [] for line in f: - if not line.startswith(" "): + if not line.startswith(b" "): # All lines we're intereted in are indented so ignore this one. pass elif re.match(num_regex, line): @@ -69,10 +69,10 @@ def put_in_dict(path): # everything before the '+'. We only take at most the first 8 # lines for the key so that we group 'similar' stacks in our # output. - key = "\n".join(line.split("+")[0] for line in current_stack[:8]) + key = b"\n".join(line.split(b"+")[0] for line in current_stack[:8]) # Record this stack and reset our state to build a new one. - dictionary[key].append((int(line), "\n".join(current_stack))) + dictionary[key].append((int(line), b"\n".join(current_stack))) current_stack = [] else: # This line doesn't contain just a number. This might be an @@ -106,7 +106,7 @@ def extract_useful_keys(d): def print_dictionary_member(d, key): print(total_count_for_key(d, key)) - print(key) + print(key.decode('utf8')) print() print_dictionary_member_detail(d, key) print() @@ -116,7 +116,7 @@ def print_dictionary_member_detail(d, key): value = d[key] for (count, stack) in value: print(" %d" % count) - print(" " + stack.replace("\n", "\n ")) + print((b" " + stack.replace(b"\n", b"\n ")).decode('utf8')) def usage(): From ba72f31e11275fc5bf060c966cf6c1f36842a291 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 15 Jan 2025 09:41:12 +0000 Subject: [PATCH 47/93] Add some trivial Sendable annotations (#3060) Motivation We have a few types lying around that can trivially be Sendable, and that `-require-explicit-sendable` needs to be `Sendable`. Let's add those annotations. Modifications Made a few types Sendable Result One step closer to our strict concurrency goal --- Sources/NIOCore/ChannelOption.swift | 2 +- Sources/NIOPosix/BSDSocketAPICommon.swift | 6 +++--- Sources/NIOPosix/IntegerTypes.swift | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/NIOCore/ChannelOption.swift b/Sources/NIOCore/ChannelOption.swift index 17109fa98..b97647f85 100644 --- a/Sources/NIOCore/ChannelOption.swift +++ b/Sources/NIOCore/ChannelOption.swift @@ -64,7 +64,7 @@ public typealias ConnectTimeoutOption = ChannelOptions.Types.ConnectTimeoutOptio public typealias AllowRemoteHalfClosureOption = ChannelOptions.Types.AllowRemoteHalfClosureOption extension ChannelOptions { - public enum Types { + public enum Types: Sendable { /// `SocketOption` allows users to specify configuration settings that are directly applied to the underlying socket file descriptor. /// diff --git a/Sources/NIOPosix/BSDSocketAPICommon.swift b/Sources/NIOPosix/BSDSocketAPICommon.swift index 37f91f403..4e7be4831 100644 --- a/Sources/NIOPosix/BSDSocketAPICommon.swift +++ b/Sources/NIOPosix/BSDSocketAPICommon.swift @@ -32,7 +32,7 @@ protocol _SocketShutdownProtocol { } @usableFromInline -internal enum Shutdown: _SocketShutdownProtocol { +internal enum Shutdown: _SocketShutdownProtocol, Sendable { case RD case WR case RDWR @@ -49,7 +49,7 @@ extension NIOBSDSocket { extension NIOBSDSocket { /// Specifies the type of socket. @usableFromInline - internal struct SocketType: RawRepresentable { + internal struct SocketType: RawRepresentable, Sendable { public typealias RawValue = CInt public var rawValue: RawValue public init(rawValue: RawValue) { @@ -144,7 +144,7 @@ extension NIOBSDSocket { /// They aren't necessarily protocols in their own right: for example, ``mptcp`` /// is not. They act to modify the socket type instead: thus, ``mptcp`` acts /// to modify `SOCK_STREAM` to ask for ``mptcp`` support. - public struct ProtocolSubtype: RawRepresentable, Hashable { + public struct ProtocolSubtype: RawRepresentable, Hashable, Sendable { public typealias RawValue = CInt /// The underlying value of the protocol subtype. diff --git a/Sources/NIOPosix/IntegerTypes.swift b/Sources/NIOPosix/IntegerTypes.swift index 3ac37dc0b..2a0a1fe3d 100644 --- a/Sources/NIOPosix/IntegerTypes.swift +++ b/Sources/NIOPosix/IntegerTypes.swift @@ -16,7 +16,7 @@ /// A 24-bit unsigned integer value type. @usableFromInline -struct _UInt24 { +struct _UInt24: Sendable { @usableFromInline var _backing: (UInt16, UInt8) @inlinable @@ -65,7 +65,7 @@ extension _UInt24: CustomStringConvertible { // MARK: _UInt56 /// A 56-bit unsigned integer value type. -struct _UInt56 { +struct _UInt56: Sendable { @usableFromInline var _backing: (UInt32, UInt16, UInt8) @inlinable init(_ value: UInt64) { From 2620f8e9a051246e2e11a3134979c9fbc08cc6a3 Mon Sep 17 00:00:00 2001 From: John Zhou <37914490+johnnzhou@users.noreply.github.com> Date: Thu, 16 Jan 2025 03:08:33 -0800 Subject: [PATCH 48/93] Fix WebSocketProtocolErrorHandler sending the close frame with appropriate masking key (#3040) Enhance `WebSocketProtocolErrorHandler` to correctly add masking key for client/server. ### Motivation: In `NIOWebSocket`, the automatic error handling provided by `WebSocketProtocolErrorHandler` offers a convenient way for both clients and servers to handle protocol-level errors. However, the `WebSocketFrame` used in `WebSocketProtocolErrorHandler` does not fully adhere to the RFC 6455 standard. Specifically, as per [RFC 6455 Section 5.1](https://datatracker.ietf.org/doc/html/rfc6455#section-5.1), a client *must* mask all frames it sends to the server, while a server *must not* mask any frames it sends to the client. This PR addressed this discrepancy to ensure compliance with the WebSocket protocol. ### Modifications: In the `WebSocketProtocolErrorHandler` initializer, the user can specify whether the handler is used for a WebSocket client or server. Within the `errorCaught` method, the `WebSocketFrame` will include a maskingKey if the handler is used by a client, or nil if it is used by a server. Additionally, the `@unchecked` annotation is removed from `NIOWebSocketServerUpgrader` since the project is now using swift 5.9 toolchain. ### Result: The `WebSocketProtocolErrorHandler` is more robust and can correctly close the connection is error occurs. --- .../NIOWebSocketClientUpgrader.swift | 2 +- .../NIOWebSocketServerUpgrader.swift | 5 +--- .../WebSocketProtocolErrorHandler.swift | 22 +++++++++++++- .../WebSocketClientEndToEndTests.swift | 29 +++++++++++++++++++ 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift index cc5fa16e3..e8f1b5ca4 100644 --- a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift @@ -199,7 +199,7 @@ private func _upgrade( ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: maxFrameSize)) ) if enableAutomaticErrorHandling { - try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler()) + try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler(isServer: false)) } } .flatMap { diff --git a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift index 4f888a3e3..14e3c7261 100644 --- a/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketServerUpgrader.swift @@ -62,11 +62,8 @@ extension HTTPHeaders { /// /// This upgrader assumes that the `HTTPServerUpgradeHandler` will appropriately mutate the pipeline to /// remove the HTTP `ChannelHandler`s. -public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, @unchecked Sendable { - // This type *is* Sendable but we can't express that properly until Swift 5.7. In the meantime - // the conformance is `@unchecked`. +public final class NIOWebSocketServerUpgrader: HTTPServerProtocolUpgrader, Sendable { - // FIXME: remove @unchecked when 5.7 is the minimum supported version. private typealias ShouldUpgrade = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture private typealias UpgradePipelineHandler = @Sendable (Channel, HTTPRequestHead) -> EventLoopFuture /// RFC 6455 specs this as the required entry in the Upgrade header. diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index e367184b6..6c63126e9 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -22,7 +22,20 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { public typealias InboundIn = Never public typealias OutboundOut = WebSocketFrame - public init() {} + /// Indicate that this `ChannelHandeler` is used by a WebSocket server or client. Default is true. + private let isServer: Bool + + public init() { + self.isServer = true + } + + /// Initialize this `ChannelHandler` to be used by a WebSocket server or client. + /// + /// - Parameters: + /// - isServer: indicate whether this `ChannelHandler` is used by a WebSocket server or client. + public init(isServer: Bool) { + self.isServer = isServer + } public func errorCaught(context: ChannelHandlerContext, error: Error) { let loopBoundContext = context.loopBound @@ -32,6 +45,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { let frame = WebSocketFrame( fin: true, opcode: .connectionClose, + maskKey: self.makeMaskingKey(), data: data ) context.writeAndFlush(Self.wrapOutboundOut(frame)).whenComplete { (_: Result) in @@ -44,6 +58,12 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { // forward the error on to let others see it. context.fireErrorCaught(error) } + + private func makeMaskingKey() -> WebSocketMaskingKey? { + // According to RFC 6455 Section 5, a client *must* mask all frames that it sends to the server. + // A server *must not* mask any frames that it sends to the client + self.isServer ? nil : .random() + } } @available(*, unavailable) diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index 71a86bdc1..11e8f848e 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -466,6 +466,35 @@ class WebSocketClientEndToEndTests: XCTestCase { // Close the pipeline. XCTAssertNoThrow(try clientChannel.close().wait()) } + + func testErrorHandlerMaskFrameForClient() throws { + + let (clientChannel, _) = try self.runSuccessfulUpgrade() + let maskBitMask: UInt8 = 0x80 + + var data = clientChannel.allocator.buffer(capacity: 4) + // A fake frame header that claims that the length of the frame is 16385 bytes, + // larger than the frame max. + data.writeBytes([0x81, 0xFE, 0x40, 0x01]) + + XCTAssertThrowsError(try clientChannel.writeInbound(data)) { error in + XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError) + } + + clientChannel.embeddedEventLoop.run() + var buffer = try clientChannel.readAllOutboundBuffers() + + guard let (_, secondByte) = buffer.readMultipleIntegers(as: (UInt8, UInt8).self) else { + XCTFail("Insufficient bytes from WebSocket frame") + return + } + + let maskedBit = (secondByte & maskBitMask) + XCTAssertEqual(0x80, maskedBit) + + XCTAssertNoThrow(!clientChannel.isActive) + XCTAssertTrue(try clientChannel.finish(acceptAlreadyClosed: true).isClean) + } } #if !canImport(Darwin) || swift(>=5.10) From 30e1f2e3f496211be4373115d40199e2b3fa2a15 Mon Sep 17 00:00:00 2001 From: Natik Gadzhi Date: Thu, 16 Jan 2025 04:25:15 -0800 Subject: [PATCH 49/93] feat: Add `String(contentsOf: FilePath ...)` (#3048) ### Motivation: Makes it possible to read contents of an NIOFileSystem.FilePath into a String directly. Closes #3010. ### Modifications: - Added a new `String+FileSystem.swift` into `NIOFileSystem` target. - Added basic tests to the existing `ConvenienceTests.swift`. - Added a test to cover `Array+FileSystem` initializer as well. ### Result: - String initializer for `FilePath` is now available - Array initializer for `FilePath` now has a test --------- Co-authored-by: George Barnett Co-authored-by: Cory Benfield --- Sources/NIOFileSystem/String+FileSystem.swift | 56 +++++++++++++++++++ .../ConvenienceTests.swift | 27 +++++++++ 2 files changed, 83 insertions(+) create mode 100644 Sources/NIOFileSystem/String+FileSystem.swift diff --git a/Sources/NIOFileSystem/String+FileSystem.swift b/Sources/NIOFileSystem/String+FileSystem.swift new file mode 100644 index 000000000..57e2d51c0 --- /dev/null +++ b/Sources/NIOFileSystem/String+FileSystem.swift @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension String { + /// Reads the contents of the file at the path into a String. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown. + /// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file. + /// + /// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount, + fileSystem: some FileSystemProtocol + ) async throws { + let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in + try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed) + } + + self = Self(buffer: byteBuffer) + } + + /// Reads the contents of the file at the path using ``FileSystem``. + /// + /// - Parameters: + /// - path: The path of the file to read. + /// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown. + /// + /// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown. + public init( + contentsOf path: FilePath, + maximumSizeAllowed: ByteCount + ) async throws { + self = try await Self( + contentsOf: path, + maximumSizeAllowed: maximumSizeAllowed, + fileSystem: .shared + ) + } +} diff --git a/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift b/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift index 85a09505d..de9a60948 100644 --- a/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/ConvenienceTests.swift @@ -70,4 +70,31 @@ final class ConvenienceTests: XCTestCase { let bytes = try await ByteBuffer(contentsOf: path, maximumSizeAllowed: .bytes(1024)) XCTAssertEqual(bytes, ByteBuffer(bytes: Array(0..<64))) } + + // MARK: - String + FileSystem + + func testStringFromFullFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await "some text".write(toFileAt: path) + + let string = try await String(contentsOf: path, maximumSizeAllowed: .bytes(1024)) + XCTAssertEqual(string, "some text") + } + + func testStringFromPartOfAFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await "some text".write(toFileAt: path) + + await XCTAssertThrowsFileSystemErrorAsync { + try await String(contentsOf: path, maximumSizeAllowed: .bytes(4)) + } + } + + // MARK: - Array + FileSystem + func testArrayFromFullFile() async throws { + let path = try await Self.fs.temporaryFilePath() + try await Array("some text".utf8).write(toFileAt: path) + let array = try await Array(contentsOf: path, maximumSizeAllowed: .bytes(1024)) + XCTAssertEqual(array, Array("some text".utf8)) + } } From f5773c171c8722c6f5c8258755e97d238c1a00ee Mon Sep 17 00:00:00 2001 From: Natik Gadzhi Date: Thu, 16 Jan 2025 08:05:51 -0800 Subject: [PATCH 50/93] feat: NIO.TimeAmount(string:) and TimeAmount.description (#3046) Adds `TimeAmount.init(string:)` and `TimeAmount.description` for parsing time amounts from strings and pretty printing them. Closes #2504. ### Motivation: Had a minute, wanted to work on Swift-NIO a bit more, and saw @weissi still wanted this. ### Modifications: It's largely based on the snippet @weissi made in #2504 with a few changes: - Added unit tests. - Added support for more unit aliases for convenience based on @glbrntt's suggestion. - Changed `.gitignore` to ignore `.build` everywhere, I've got a few of them when testing locally. ### Open questions: - I originally thought perhaps I should add support for multiple number and unit pairs, i.e. `1h 31m`, but decided against it. Feels like an edge case. Happy to add this if you think it's needed. --------- Co-authored-by: Cory Benfield --- .gitignore | 2 +- Sources/NIOCore/EventLoop.swift | 82 ++++++++++++++++++ Tests/NIOCoreTests/TimeAmountTests.swift | 103 ++++++++++++++++++++++- 3 files changed, 185 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index f22758cad..f6bd1f104 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .DS_Store -/.build +.build /.index-build /Packages /*.xcodeproj diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 1b619a3b0..3a3fa4a6c 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -551,6 +551,88 @@ public struct TimeAmount: Hashable, Sendable { } } +/// Contains the logic for parsing time amounts from strings, +/// and printing pretty strings to represent time amounts. +extension TimeAmount: CustomStringConvertible { + + /// Errors thrown when parsint a TimeAmount from a string + internal enum ValidationError: Error, Equatable { + /// Can't parse the provided unit + case unsupportedUnit(String) + + /// Can't parse the number into a Double + case invalidNumber(String) + } + + /// Creates a TimeAmount from a string representation with an optional default unit. + /// + /// Supports formats like: + /// - "5s" (5 seconds) + /// - "100ms" (100 milliseconds) + /// - "42" (42 of default unit) + /// - "1 hr" (1 hour) + /// + /// This function only supports one pair of the number and units, i.e. "5s" or "100ms" but not "5s 100ms". + /// + /// Supported units: + /// - h, hr, hrs (hours) + /// - m, min (minutes) + /// - s, sec, secs (seconds) + /// - ms, millis (milliseconds) + /// - us, µs, micros (microseconds) + /// - ns, nanos (nanoseconds) + /// + /// - Parameters: + /// - userProvidedString: The string to parse + /// + /// - Throws: ValidationError if the string cannot be parsed + public init(_ userProvidedString: String) throws { + let lowercased = String(userProvidedString.filter { !$0.isWhitespace }).lowercased() + let parsedNumbers = lowercased.prefix(while: { $0.isWholeNumber || $0 == "," || $0 == "." }) + let parsedUnit = String(lowercased.dropFirst(parsedNumbers.count)) + + guard let numbers = Int64(parsedNumbers) else { + throw ValidationError.invalidNumber("'\(userProvidedString)' cannot be parsed as number and unit") + } + + switch parsedUnit { + case "h", "hr", "hrs": + self = .hours(numbers) + case "m", "min": + self = .minutes(numbers) + case "s", "sec", "secs": + self = .seconds(numbers) + case "ms", "millis": + self = .milliseconds(numbers) + case "us", "µs", "micros": + self = .microseconds(numbers) + case "ns", "nanos": + self = .nanoseconds(numbers) + default: + throw ValidationError.unsupportedUnit("Unknown unit '\(parsedUnit)' in '\(userProvidedString)'") + } + } + + /// Returns a human-readable string representation of the time amount + /// using the most appropriate unit + public var description: String { + let fullNS = self.nanoseconds + let (fullUS, remUS) = fullNS.quotientAndRemainder(dividingBy: 1_000) + let (fullMS, remMS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000) + let (fullS, remS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000_000) + + if remS == 0 { + return "\(fullS) s" + } else if remMS == 0 { + return "\(fullMS) ms" + } else if remUS == 0 { + return "\(fullUS) us" + } else { + return "\(fullNS) ns" + } + } +} + extension TimeAmount: Comparable { @inlinable public static func < (lhs: TimeAmount, rhs: TimeAmount) -> Bool { diff --git a/Tests/NIOCoreTests/TimeAmountTests.swift b/Tests/NIOCoreTests/TimeAmountTests.swift index 0cf762a1d..1285b7584 100644 --- a/Tests/NIOCoreTests/TimeAmountTests.swift +++ b/Tests/NIOCoreTests/TimeAmountTests.swift @@ -11,9 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import NIOCore + import XCTest +@testable import NIOCore + class TimeAmountTests: XCTestCase { func testTimeAmountConversion() { XCTAssertEqual(TimeAmount.nanoseconds(3), .nanoseconds(3)) @@ -61,4 +63,103 @@ class TimeAmountTests: XCTestCase { XCTAssertEqual(TimeAmount.minutes(.min), underflowCap) XCTAssertEqual(TimeAmount.hours(.min), underflowCap) } + + func testTimeAmountParsing() throws { + // Test all supported hour formats + XCTAssertEqual(try TimeAmount("2h"), .hours(2)) + XCTAssertEqual(try TimeAmount("2hr"), .hours(2)) + XCTAssertEqual(try TimeAmount("2hrs"), .hours(2)) + + // Test all supported minute formats + XCTAssertEqual(try TimeAmount("3m"), .minutes(3)) + XCTAssertEqual(try TimeAmount("3min"), .minutes(3)) + + // Test all supported second formats + XCTAssertEqual(try TimeAmount("4s"), .seconds(4)) + XCTAssertEqual(try TimeAmount("4sec"), .seconds(4)) + XCTAssertEqual(try TimeAmount("4secs"), .seconds(4)) + + // Test all supported millisecond formats + XCTAssertEqual(try TimeAmount("5ms"), .milliseconds(5)) + XCTAssertEqual(try TimeAmount("5millis"), .milliseconds(5)) + + // Test all supported microsecond formats + XCTAssertEqual(try TimeAmount("6us"), .microseconds(6)) + XCTAssertEqual(try TimeAmount("6µs"), .microseconds(6)) + XCTAssertEqual(try TimeAmount("6micros"), .microseconds(6)) + + // Test all supported nanosecond formats + XCTAssertEqual(try TimeAmount("7ns"), .nanoseconds(7)) + XCTAssertEqual(try TimeAmount("7nanos"), .nanoseconds(7)) + } + + func testTimeAmountParsingWithWhitespace() throws { + XCTAssertEqual(try TimeAmount("5 s"), .seconds(5)) + XCTAssertEqual(try TimeAmount("100 ms"), .milliseconds(100)) + XCTAssertEqual(try TimeAmount("42 ns"), .nanoseconds(42)) + XCTAssertEqual(try TimeAmount(" 5s "), .seconds(5)) + } + + func testTimeAmountParsingCaseInsensitive() throws { + XCTAssertEqual(try TimeAmount("5S"), .seconds(5)) + XCTAssertEqual(try TimeAmount("100MS"), .milliseconds(100)) + XCTAssertEqual(try TimeAmount("1HR"), .hours(1)) + XCTAssertEqual(try TimeAmount("30MIN"), .minutes(30)) + } + + func testTimeAmountParsingInvalidInput() throws { + // Empty string + XCTAssertThrowsError(try TimeAmount("")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'' cannot be parsed as number and unit") + ) + } + + // Invalid number + XCTAssertThrowsError(try TimeAmount("abc")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'abc' cannot be parsed as number and unit") + ) + } + + // Unknown unit + XCTAssertThrowsError(try TimeAmount("5x")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.unsupportedUnit("Unknown unit 'x' in '5x'") + ) + } + + // Missing number + XCTAssertThrowsError(try TimeAmount("ms")) { error in + XCTAssertEqual( + error as? TimeAmount.ValidationError, + TimeAmount.ValidationError.invalidNumber("'ms' cannot be parsed as number and unit") + ) + } + } + + func testTimeAmountPrettyPrint() { + // Basic formatting + XCTAssertEqual(TimeAmount.seconds(5).description, "5 s") + XCTAssertEqual(TimeAmount.milliseconds(100).description, "100 ms") + XCTAssertEqual(TimeAmount.microseconds(250).description, "250 us") + XCTAssertEqual(TimeAmount.nanoseconds(42).description, "42 ns") + + // Unit selection based on value + XCTAssertEqual(TimeAmount.nanoseconds(1_000).description, "1 us") + XCTAssertEqual(TimeAmount.nanoseconds(1_000_000).description, "1 ms") + XCTAssertEqual(TimeAmount.nanoseconds(1_000_000_000).description, "1 s") + + // Values with remainders + XCTAssertEqual(TimeAmount.nanoseconds(1_500).description, "1500 ns") + XCTAssertEqual(TimeAmount.nanoseconds(1_500_000).description, "1500 us") + XCTAssertEqual(TimeAmount.nanoseconds(1_500_000_000).description, "1500 ms") + + // Negative values + XCTAssertEqual(TimeAmount.seconds(-5).description, "-5 s") + XCTAssertEqual(TimeAmount.milliseconds(-100).description, "-100 ms") + } } From 15a38aef063069a6f8b96a13148ae5e5edb0ed29 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 17 Jan 2025 10:31:53 +0000 Subject: [PATCH 51/93] Add allocation counter tests for isolated EL operations (#3068) Motivation: As with the ELF operations before them, the isolated EL operations currently incur overhead above-and-beyond the overhead of their non-isolated counterparts. That's not what we want to see. However, before we "fix" them, we need to add regression testing to confirm our fix actually worked. Modifications: - Add isolated variations of all current EL scheduling tests. - Where isolated methods didn't have alloc counter tests, add new ones for the non-isolated versions too. Result: More tests. --- .../tests_04_performance/Thresholds/5.10.json | 8 ++++ .../tests_04_performance/Thresholds/5.9.json | 8 ++++ .../tests_04_performance/Thresholds/6.0.json | 10 ++++- .../Thresholds/nightly-6.0.json | 10 ++++- .../Thresholds/nightly-main.json | 8 ++++ ...isolated_scheduling_10000_executions.swift | 34 +++++++++++++++ .../test_flat_schedule_10000_tasks.swift | 41 +++++++++++++++++++ ...schedule_assume_isolated_10000_tasks.swift | 41 +++++++++++++++++++ ...schedule_assume_isolated_10000_tasks.swift | 37 +++++++++++++++++ ...t_schedule_with_deadline_10000_tasks.swift | 40 ++++++++++++++++++ ...deadline_assume_isolated_10000_tasks.swift | 41 +++++++++++++++++++ .../test_submit_10000_tasks.swift | 38 +++++++++++++++++ ...t_submit_assume_isolated_10000_tasks.swift | 38 +++++++++++++++++ 13 files changed, 352 insertions(+), 2 deletions(-) create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift create mode 100644 IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index 844e97841..fd2d7003a 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -20,6 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, + "assume_isolated_scheduling_10000_executions": 20100, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -32,6 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "flat_schedule_10000_tasks": 130100, + "flat_schedule_assume_isolated_10000_tasks": 150100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -45,7 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, + "schedule_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_10000_tasks": 40100, + "schedule_with_deadline_assume_isolated_10000_tasks": 50100, "scheduling_10000_executions": 89, + "submit_10000_tasks": 20100, + "submit_assume_isolated_10000_tasks": 30100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index 6e9df5a2f..760bb3b20 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -20,6 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 393050, + "assume_isolated_scheduling_10000_executions": 20100, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -32,6 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "flat_schedule_10000_tasks": 130100, + "flat_schedule_assume_isolated_10000_tasks": 150100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -45,7 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, + "schedule_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_10000_tasks": 40100, + "schedule_with_deadline_assume_isolated_10000_tasks": 50100, "scheduling_10000_executions": 89, + "submit_10000_tasks": 20100, + "submit_assume_isolated_10000_tasks": 30100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index 5235f29b3..fd2d7003a 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -19,7 +19,8 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 384000, + "1_reqs_1000_conn": 384050, + "assume_isolated_scheduling_10000_executions": 20100, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -32,6 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "flat_schedule_10000_tasks": 130100, + "flat_schedule_assume_isolated_10000_tasks": 150100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -45,7 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, + "schedule_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_10000_tasks": 40100, + "schedule_with_deadline_assume_isolated_10000_tasks": 50100, "scheduling_10000_executions": 89, + "submit_10000_tasks": 20100, + "submit_assume_isolated_10000_tasks": 30100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index 5235f29b3..fd2d7003a 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -19,7 +19,8 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 384000, + "1_reqs_1000_conn": 384050, + "assume_isolated_scheduling_10000_executions": 20100, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -32,6 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "flat_schedule_10000_tasks": 130100, + "flat_schedule_assume_isolated_10000_tasks": 150100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -45,7 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, + "schedule_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_10000_tasks": 40100, + "schedule_with_deadline_assume_isolated_10000_tasks": 50100, "scheduling_10000_executions": 89, + "submit_10000_tasks": 20100, + "submit_assume_isolated_10000_tasks": 30100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 5500c5235..194000e8e 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -20,6 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, + "assume_isolated_scheduling_10000_executions": 20100, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -32,6 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, + "flat_schedule_10000_tasks": 130100, + "flat_schedule_assume_isolated_10000_tasks": 150100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -45,7 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, + "schedule_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_10000_tasks": 40100, + "schedule_with_deadline_assume_isolated_10000_tasks": 50100, "scheduling_10000_executions": 89, + "submit_10000_tasks": 20100, + "submit_assume_isolated_10000_tasks": 30100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift new file mode 100644 index 000000000..7087e17aa --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_assume_isolated_scheduling_10000_executions.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let dg = DispatchGroup() + + try! loop.submit { + for _ in 0..<10_000 { + dg.enter() + loop.assumeIsolated().execute { dg.leave() } + } + }.wait() + dg.wait() + try! group.syncShutdownGracefully() + return 10_000 + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift new file mode 100644 index 000000000..1d80f8d43 --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_10000_tasks.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOCore +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + let deadline = NIODeadline.now() + .hours(1) + + for _ in 0..<10000 { + loop.flatScheduleTask(deadline: deadline) { + counter &+= 1 + return loop.makeSucceededFuture(counter) + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..4f980a00b --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_flat_schedule_assume_isolated_10000_tasks.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOCore +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + let deadline = NIODeadline.now() + .hours(1) + + for _ in 0..<10000 { + loop.assumeIsolated().flatScheduleTask(deadline: deadline) { + counter &+= 1 + return loop.makeSucceededFuture(counter) + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..7d63b19fb --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_assume_isolated_10000_tasks.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + for _ in 0..<10000 { + loop.assumeIsolated().scheduleTask(in: .hours(1)) { + counter &+= 1 + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift new file mode 100644 index 000000000..8b10c78eb --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_10000_tasks.swift @@ -0,0 +1,40 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOCore +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + let deadline = NIODeadline.now() + .hours(1) + + for _ in 0..<10000 { + loop.scheduleTask(deadline: deadline) { + counter &+= 1 + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..b0e157b0c --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_schedule_with_deadline_assume_isolated_10000_tasks.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOCore +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + let deadline = NIODeadline.now() + .hours(1) + + for _ in 0..<10000 { + loop.assumeIsolated().scheduleTask(deadline: deadline) { + counter &+= 1 + return counter + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift new file mode 100644 index 000000000..88ae88542 --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_10000_tasks.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + for _ in 0..<10000 { + _ = loop.submit { + counter &+= 1 + return counter + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift new file mode 100644 index 000000000..47f16587a --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_submit_assume_isolated_10000_tasks.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019-2025 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 +// +//===----------------------------------------------------------------------===// + +import Dispatch +import NIOPosix + +func run(identifier: String) { + measure(identifier: identifier) { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + let loop = group.next() + let counter = try! loop.submit { () -> Int in + var counter: Int = 0 + + for _ in 0..<10000 { + _ = loop.assumeIsolated().submit { + counter &+= 1 + return counter + } + } + + return counter + }.wait() + + try! group.syncShutdownGracefully() + return counter + } +} From 853619335df56ae35d09e8d1660d83ccb5b9e0a1 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 17 Jan 2025 14:15:35 +0000 Subject: [PATCH 52/93] Improve coverage of isolated views (#3069) Motivation: We were only testing the isolated views on SelectableEventLoop. That was fine when all the implementation was common, but it isn't going to be anymore, so we should start having tests across all our EL kinds. Modifications: Refactor the tests to take their EL as an argument Add support for ELs that need to be explicitly run Add tests for NIOAsyncTestingEL and EmbeddedEL Result: Better test coverage. --- .../EventLoopFutureIsolatedTests.swift | 299 ++++++++++++++---- 1 file changed, 241 insertions(+), 58 deletions(-) diff --git a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift index 2388c2823..4ef333934 100644 --- a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift +++ b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore +import NIOEmbedded import NIOPosix import XCTest @@ -23,100 +24,138 @@ final class SuperNotSendable { @available(*, unavailable) extension SuperNotSendable: Sendable {} -final class EventLoopFutureIsolatedTest: XCTestCase { - func testCompletingPromiseWithNonSendableValue() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() +private protocol RunnableEventLoop: EventLoop { + func runForTests() + func advanceTimeForTests(by: TimeAmount) +} - try loop.flatSubmit { +extension EmbeddedEventLoop: RunnableEventLoop { + fileprivate func runForTests() { + self.run() + } + + fileprivate func advanceTimeForTests(by amount: TimeAmount) { + self.advanceTime(by: amount) + } +} + +extension NIOAsyncTestingEventLoop: RunnableEventLoop { + fileprivate func runForTests() { + // This is horrible, but it's the only general-purpose implementation. + let promise = self.makePromise(of: Void.self) + promise.completeWithTask { + await self.run() + } + try! promise.futureResult.wait() + } + + fileprivate func advanceTimeForTests(by amount: TimeAmount) { + // This is horrible, but it's the only general-purpose implementation. + let promise = self.makePromise(of: Void.self) + promise.completeWithTask { + await self.advanceTime(by: amount) + } + try! promise.futureResult.wait() + } +} + +final class EventLoopFutureIsolatedTest: XCTestCase { + func _completingPromiseWithNonSendableValue(loop: any EventLoop) throws { + let f = loop.flatSubmit { let promise = loop.makePromise(of: SuperNotSendable.self) let value = SuperNotSendable() promise.assumeIsolated().succeed(value) return promise.futureResult.assumeIsolated().map { val in XCTAssertIdentical(val, value) }.nonisolated() - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testCompletingPromiseWithNonSendableResult() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.flatSubmit { + func _completingPromiseWithNonSendableResult(loop: any EventLoop) throws { + let f = loop.flatSubmit { let promise = loop.makePromise(of: SuperNotSendable.self) let value = SuperNotSendable() promise.assumeIsolated().completeWith(.success(value)) return promise.futureResult.assumeIsolated().map { val in XCTAssertIdentical(val, value) }.nonisolated() - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testCompletingPromiseWithNonSendableValueUnchecked() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.flatSubmit { + func _completingPromiseWithNonSendableValueUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { let promise = loop.makePromise(of: SuperNotSendable.self) let value = SuperNotSendable() promise.assumeIsolatedUnsafeUnchecked().succeed(value) return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in XCTAssertIdentical(val, value) }.nonisolated() - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testCompletingPromiseWithNonSendableResultUnchecked() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.flatSubmit { + func _completingPromiseWithNonSendableResultUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { let promise = loop.makePromise(of: SuperNotSendable.self) let value = SuperNotSendable() promise.assumeIsolatedUnsafeUnchecked().completeWith(.success(value)) return promise.futureResult.assumeIsolatedUnsafeUnchecked().map { val in XCTAssertIdentical(val, value) }.nonisolated() - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testBackAndForthUnwrapping() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.submit { + func _backAndForthUnwrapping(loop: any EventLoop) throws { + let f = loop.submit { let promise = loop.makePromise(of: SuperNotSendable.self) let future = promise.futureResult XCTAssertEqual(promise.assumeIsolated().nonisolated(), promise) XCTAssertEqual(future.assumeIsolated().nonisolated(), future) promise.assumeIsolated().succeed(SuperNotSendable()) - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testBackAndForthUnwrappingUnchecked() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.submit { + func _backAndForthUnwrappingUnchecked(loop: any EventLoop) throws { + let f = loop.submit { let promise = loop.makePromise(of: SuperNotSendable.self) let future = promise.futureResult XCTAssertEqual(promise.assumeIsolatedUnsafeUnchecked().nonisolated(), promise) XCTAssertEqual(future.assumeIsolatedUnsafeUnchecked().nonisolated(), future) promise.assumeIsolated().succeed(SuperNotSendable()) - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testFutureChaining() throws { + func _futureChaining(loop: any EventLoop) throws { enum TestError: Error { case error } - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - try loop.flatSubmit { + let f = loop.flatSubmit { let promise = loop.makePromise(of: SuperNotSendable.self) let future = promise.futureResult.assumeIsolated() let originalValue = SuperNotSendable() @@ -217,14 +256,15 @@ final class EventLoopFutureIsolatedTest: XCTestCase { promise.assumeIsolated().succeed(originalValue) return newFuture.map { _ in }.nonisolated() - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.runForTests() + } + try f.wait() } - func testEventLoopIsolated() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - let result: Int = try loop.flatSubmit { + func _eventLoopIsolated(loop: any EventLoop) throws { + let f = loop.flatSubmit { let value = SuperNotSendable() // Again, all of these need to close over value. In addition, @@ -240,7 +280,7 @@ final class EventLoopFutureIsolatedTest: XCTestCase { return val }.map { $0.x } - let secondFuture = isolated.scheduleTask(deadline: .now() + .milliseconds(50)) { + let secondFuture = isolated.scheduleTask(deadline: loop.now + .milliseconds(50)) { let val = SuperNotSendable() val.x = value.x + 1 return val @@ -252,7 +292,7 @@ final class EventLoopFutureIsolatedTest: XCTestCase { return val }.futureResult.map { $0.x } - let fourthFuture = isolated.flatScheduleTask(deadline: .now() + .milliseconds(50)) { + let fourthFuture = isolated.flatScheduleTask(deadline: loop.now + .milliseconds(50)) { let promise = loop.makePromise(of: Int.self) promise.succeed(value.x + 1) return promise.futureResult @@ -263,16 +303,17 @@ final class EventLoopFutureIsolatedTest: XCTestCase { [firstFuture, secondFuture, thirdFuture, fourthFuture], on: loop ) { $0 += $1 } - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.advanceTimeForTests(by: .milliseconds(51)) + } + let result = try f.wait() XCTAssertEqual(result, 6 * 4) } - func testEventLoopIsolatedUnchecked() throws { - let group = MultiThreadedEventLoopGroup.singleton - let loop = group.next() - - let result: Int = try loop.flatSubmit { + func _eventLoopIsolatedUnchecked(loop: any EventLoop) throws { + let f = loop.flatSubmit { let value = SuperNotSendable() // Again, all of these need to close over value. In addition, @@ -288,7 +329,7 @@ final class EventLoopFutureIsolatedTest: XCTestCase { return val }.map { $0.x } - let secondFuture = isolated.scheduleTask(deadline: .now() + .milliseconds(50)) { + let secondFuture = isolated.scheduleTask(deadline: loop.now + .milliseconds(50)) { let val = SuperNotSendable() val.x = value.x + 1 return val @@ -300,7 +341,7 @@ final class EventLoopFutureIsolatedTest: XCTestCase { return val }.futureResult.map { $0.x } - let fourthFuture = isolated.flatScheduleTask(deadline: .now() + .milliseconds(50)) { + let fourthFuture = isolated.flatScheduleTask(deadline: loop.now + .milliseconds(50)) { let promise = loop.makePromise(of: Int.self) promise.succeed(value.x + 1) return promise.futureResult @@ -311,8 +352,150 @@ final class EventLoopFutureIsolatedTest: XCTestCase { [firstFuture, secondFuture, thirdFuture, fourthFuture], on: loop ) { $0 += $1 } - }.wait() + } + if let runnable = loop as? RunnableEventLoop { + runnable.advanceTimeForTests(by: .milliseconds(50)) + } + let result = try f.wait() XCTAssertEqual(result, 6 * 4) } + + // MARK: SelectableEL + func testCompletingPromiseWithNonSendableValue_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_SelectableEL() throws { + let loop = MultiThreadedEventLoopGroup.singleton.next() + try self._eventLoopIsolatedUnchecked(loop: loop) + } + + // MARK: EmbeddedEL + func testCompletingPromiseWithNonSendableValue_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_EmbeddedEL() throws { + let loop = EmbeddedEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } + + // MARK: AsyncTestingEL + func testCompletingPromiseWithNonSendableValue_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_AsyncTestingEL() throws { + let loop = NIOAsyncTestingEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } } From 456ca2569315a9b8037b141daaf0a21444e63c08 Mon Sep 17 00:00:00 2001 From: Natik Gadzhi Date: Fri, 17 Jan 2025 09:13:40 -0800 Subject: [PATCH 53/93] Adds `Int(buffer:)` initializer to `FixedWidthInteger` types (#3047) ### Motivation: Makes it possible to make integers out of ByteBuffers directly with an initializer. I.e. `UInt32(buffer: ByteBuffer(bytes: [0, 1, 2, 3]))`. Closes #3012. ### Modifications: - Adds the `Int(buffer:)` initializer in `ByteBuffer-int.swift` - Adds tests in `ByteBufferTest.swift`. _Holy hell this file is huge._ - Note that `Int(buffer:)` will crash if the buffer does not have enough bytes in it to represent the desired integer type. - It also does _not_ expose endianness and uses `Endianness.host`, to keep the public API clean and simple. It's a convenience initializer, so I thought keeping it minimal is a good idea. ### Result: Nicer direct initializer for integers from ByteBuffers. --------- Co-authored-by: Johannes Weiss Co-authored-by: Cory Benfield --- Sources/NIOCore/ByteBuffer-int.swift | 16 ++++++++++++++++ Tests/NIOCoreTests/ByteBufferTest.swift | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/Sources/NIOCore/ByteBuffer-int.swift b/Sources/NIOCore/ByteBuffer-int.swift index 87e0c9abb..5e39004e9 100644 --- a/Sources/NIOCore/ByteBuffer-int.swift +++ b/Sources/NIOCore/ByteBuffer-int.swift @@ -116,6 +116,7 @@ extension ByteBuffer { } extension FixedWidthInteger { + /// Returns the next power of two. @inlinable func nextPowerOf2() -> Self { @@ -134,6 +135,21 @@ extension FixedWidthInteger { return 1 << ((Self.bitWidth - 1) - self.leadingZeroBitCount) } + + /// Initialize an integer from a byte buffer of exactly the right size. + /// The bytes will be read using the host system's endianness. + /// + /// - Parameters: + /// - buffer: The ByteBuffer to read from + /// - endianness: The endianness to use when reading the integer, defaults to the host system's endianness. + @inlinable + public init?(buffer: ByteBuffer, endianness: Endianness = .host) { + var buffer = buffer + guard let value = buffer.readInteger(endianness: endianness, as: Self.self), buffer.readableBytes == 0 else { + return nil + } + self = value + } } extension UInt32 { diff --git a/Tests/NIOCoreTests/ByteBufferTest.swift b/Tests/NIOCoreTests/ByteBufferTest.swift index 6be0ce37a..91e0ac0df 100644 --- a/Tests/NIOCoreTests/ByteBufferTest.swift +++ b/Tests/NIOCoreTests/ByteBufferTest.swift @@ -3499,6 +3499,29 @@ extension ByteBufferTest { } +// MARK: - Int / FixedWidthInteger init +extension ByteBufferTest { + func testCreateIntegersFromByteBuffer() { + let uint32BufferLE = ByteBuffer(bytes: [0x04, 0x03, 0x02, 0x01]) + let uint32BufferBE = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04]) + let tooSmallInt32Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03]) + + XCTAssertEqual(Int32(buffer: uint32BufferLE, endianness: .little), 0x0102_0304) + XCTAssertEqual(Int32(buffer: uint32BufferBE, endianness: .big), 0x0102_0304) + XCTAssertNil(Int32(buffer: tooSmallInt32Buffer)) + + let uint64BufferLE = ByteBuffer(bytes: [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01]) + let uint64BufferBE = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + let tooSmallInt64Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]) + let tooBigInt64Buffer = ByteBuffer(bytes: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]) + + XCTAssertEqual(Int64(buffer: uint64BufferLE, endianness: .little), 0x0102_0304_0506_0708) + XCTAssertEqual(Int64(buffer: uint64BufferBE, endianness: .big), 0x0102_0304_0506_0708) + XCTAssertNil(Int64(buffer: tooSmallInt64Buffer)) + XCTAssertNil(Int64(buffer: tooBigInt64Buffer)) + } +} + // MARK: - DispatchData init extension ByteBufferTest { From 77c1b79c6cc91b6168b785fcd74a9378d4c7c8fb Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 20 Jan 2025 14:06:21 +0000 Subject: [PATCH 54/93] Move Isolated EL operations to EL protocol (#3070) Motivation Right now the isolated view on the EventLoop has to implement its interface in terms of UnsafeTransfer, because there are no non-Sendable operations it can use. That hurts us because we have to allocate an extra closure for all these operations, making them slower than they need to be. This is unavoidable in some contexts, but most EventLoops would be able to offer a fast-path that avoids this extra allocation. To achieve that, we need to move this logic into a customisation point on the EventLoop protocol. Our fallback default implementation can be the same as we do today. Modifications - Add customisation points for EventLoop for each of its operations that has a protocol witness already. - Add default implementations of these, using the implementation from EventLoop.Isolated. Results No behavioural changes, but the code has moved. --------- Co-authored-by: George Barnett --- .../tests_04_performance/Thresholds/5.10.json | 2 +- .../tests_04_performance/Thresholds/5.9.json | 2 +- .../tests_04_performance/Thresholds/6.0.json | 2 +- .../Thresholds/nightly-6.0.json | 2 +- .../Thresholds/nightly-main.json | 2 +- Sources/NIOCore/EventLoop.swift | 111 ++++++++++++++++++ .../EventLoopFuture+AssumeIsolated.swift | 29 ++--- 7 files changed, 125 insertions(+), 25 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index fd2d7003a..4d7ee39d6 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 150100, + "flat_schedule_assume_isolated_10000_tasks": 110100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index 760bb3b20..d130a3f00 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 150100, + "flat_schedule_assume_isolated_10000_tasks": 110100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index fd2d7003a..4d7ee39d6 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 150100, + "flat_schedule_assume_isolated_10000_tasks": 110100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index fd2d7003a..4d7ee39d6 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 150100, + "flat_schedule_assume_isolated_10000_tasks": 110100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 194000e8e..273fc30e8 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 150100, + "flat_schedule_assume_isolated_10000_tasks": 110100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 3a3fa4a6c..98653bc56 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -395,6 +395,69 @@ public protocol EventLoop: EventLoopGroup { /// /// - NOTE: Event loops only need to implemented this if they provide a custom scheduled callback implementation. func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) + + /// Submit a given task to be executed by the ``EventLoop``, from a context where the caller + /// statically knows that the context is isolated. + /// + /// This is an optional performance hook. ``EventLoop`` implementers are not required to implement + /// this witness, but may choose to do so to enable better performance of the isolated EL views. If + /// they do so, ``EventLoop/Isolated/execute`` will perform better. + func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) + + /// Submit a given task to be executed by the ``EventLoop```, from a context where the caller + /// statically knows that the context is isolated. + /// + /// Once the execution is complete the returned ``EventLoopFuture`` is notified. + /// + /// This is an optional performance hook. ``EventLoop`` implementers are not required to implement + /// this witness, but may choose to do so to enable better performance of the isolated EL views. If + /// they do so, ``EventLoop/Isolated/submit`` will perform better. + /// + /// - Parameters: + /// - task: The closure that will be submitted to the ``EventLoop`` for execution. + /// - Returns: ``EventLoopFuture`` that is notified once the task was executed. + func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture + + /// Schedule a `task` that is executed by this ``EventLoop`` at the given time, from a context where the caller + /// statically knows that the context is isolated. + /// + /// This is an optional performance hook. ``EventLoop`` implementers are not required to implement + /// this witness, but may choose to do so to enable better performance of the isolated EL views. If + /// they do so, ``EventLoop/Isolated/scheduleTask(deadline:_:)`` will perform better. + /// + /// - Parameters: + /// - deadline: The instant in time before which the task will not execute. + /// - task: The synchronous task to run. As with everything that runs on the ``EventLoop```, it must not block. + /// - Returns: A ``Scheduled``` object which may be used to cancel the task if it has not yet run, or to wait + /// on the completion of the task. + /// + /// - Note: You can only cancel a task before it has started executing. + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled + + /// Schedule a `task` that is executed by this ``EventLoop`` after the given amount of time, from a context where the caller + /// statically knows that the context is isolated. + /// + /// This is an optional performance hook. ``EventLoop`` implementers are not required to implement + /// this witness, but may choose to do so to enable better performance of the isolated EL views. If + /// they do so, ``EventLoop/Isolated/scheduleTask(in:_:)`` will perform better. + /// + /// - Parameters: + /// - in: The amount of time before which the task will not execute. + /// - task: The synchronous task to run. As with everything that runs on the ``EventLoop``, it must not block. + /// - Returns: A ``Scheduled`` object which may be used to cancel the task if it has not yet run, or to wait + /// on the completion of the task. + /// + /// - Note: You can only cancel a task before it has started executing. + /// - Note: The `in` value is clamped to a maximum when running on a Darwin-kernel. + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + in: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled } extension EventLoop { @@ -422,6 +485,54 @@ extension EventLoop { { nil } + + /// Default implementation: wraps the task in an UnsafeTransfer. + @inlinable + public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) { + self.assertInEventLoop() + let unsafeTransfer = UnsafeTransfer(task) + self.execute { + unsafeTransfer.wrappedValue() + } + } + + /// Default implementation: wraps the task in an UnsafeTransfer. + @inlinable + public func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture { + self.assertInEventLoop() + let unsafeTransfer = UnsafeTransfer(task) + return self.submit { + try unsafeTransfer.wrappedValue() + } + } + + /// Default implementation: wraps the task in an UnsafeTransfer. + @inlinable + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + self.assertInEventLoop() + let unsafeTransfer = UnsafeTransfer(task) + return self.scheduleTask(deadline: deadline) { + try unsafeTransfer.wrappedValue() + } + } + + /// Default implementation: wraps the task in an UnsafeTransfer. + @inlinable + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + self.assertInEventLoop() + let unsafeTransfer = UnsafeTransfer(task) + return self.scheduleTask(in: delay) { + try unsafeTransfer.wrappedValue() + } + } } extension EventLoop { diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index f743550fd..49593c1f5 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -34,10 +34,7 @@ public struct NIOIsolatedEventLoop { @available(*, noasync) @inlinable public func execute(_ task: @escaping () -> Void) { - let unsafeTransfer = UnsafeTransfer(task) - self._wrapped.execute { - unsafeTransfer.wrappedValue() - } + self._wrapped._executeIsolatedUnsafeUnchecked(task) } /// Submit a given task to be executed by the `EventLoop`. Once the execution is complete the returned `EventLoopFuture` is notified. @@ -48,10 +45,7 @@ public struct NIOIsolatedEventLoop { @available(*, noasync) @inlinable public func submit(_ task: @escaping () throws -> T) -> EventLoopFuture { - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.submit { - try unsafeTransfer.wrappedValue() - } + self._wrapped._submitIsolatedUnsafeUnchecked(task) } /// Schedule a `task` that is executed by this `EventLoop` at the given time. @@ -70,10 +64,7 @@ public struct NIOIsolatedEventLoop { deadline: NIODeadline, _ task: @escaping () throws -> T ) -> Scheduled { - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.scheduleTask(deadline: deadline) { - try unsafeTransfer.wrappedValue() - } + self._wrapped._scheduleTaskIsolatedUnsafeUnchecked(deadline: deadline, task) } /// Schedule a `task` that is executed by this `EventLoop` after the given amount of time. @@ -93,10 +84,7 @@ public struct NIOIsolatedEventLoop { in delay: TimeAmount, _ task: @escaping () throws -> T ) -> Scheduled { - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.scheduleTask(in: delay) { - try unsafeTransfer.wrappedValue() - } + self._wrapped._scheduleTaskIsolatedUnsafeUnchecked(in: delay, task) } /// Schedule a `task` that is executed by this `EventLoop` at the given time. @@ -122,10 +110,11 @@ public struct NIOIsolatedEventLoop { line: UInt = #line, _ task: @escaping () throws -> EventLoopFuture ) -> Scheduled { - let unsafeTransfer = UnsafeTransfer(task) - return self._wrapped.flatScheduleTask(deadline: deadline, file: file, line: line) { - try unsafeTransfer.wrappedValue() - } + let promise: EventLoopPromise = self._wrapped.makePromise(file: file, line: line) + let scheduled = self.scheduleTask(deadline: deadline, task) + + scheduled.futureResult.flatMap { $0 }.cascade(to: promise) + return .init(promise: promise, cancellationTask: { scheduled.cancel() }) } /// Returns the wrapped event loop. From fd6eb16ae5d0f2d285d7a64806bacbd520dc224e Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 20 Jan 2025 16:09:52 +0000 Subject: [PATCH 55/93] Ensure we test the isolated fallback methods (#3072) Motivation I'm about to change all our main event loops to use our new customisation points. That's great, but it'll have the effect of removing all the testing of our default implementations, which is not a good idea. So let's add some more tests. Modifications Define a "fallback" event loop for testing the isolated methods. Result Reduced likelihood of regressions in future. --- .../EventLoopFutureIsolatedTests.swift | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift index 4ef333934..705d63197 100644 --- a/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift +++ b/Tests/NIOPosixTests/EventLoopFutureIsolatedTests.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOPosix @@ -24,6 +25,57 @@ final class SuperNotSendable { @available(*, unavailable) extension SuperNotSendable: Sendable {} +// A very stupid event loop that implements as little of the protocol as possible. +// +// We use this to confirm that the fallback path for the isolated views works, by not implementing +// their fast-paths. Instead, we forward to the underlying implementation. We use `AsyncTestingEventLoop` +// to provide the backing implementation. +private final class FallbackEventLoop: RunnableEventLoop { + private let base: NIOAsyncTestingEventLoop + + init() { + self.base = .init() + } + + var now: NIODeadline { + self.base.now + } + + var inEventLoop: Bool { + self.base.inEventLoop + } + + func execute(_ task: @escaping @Sendable () -> Void) { + self.base.execute(task) + } + + func scheduleTask( + deadline: NIOCore.NIODeadline, + _ task: @escaping @Sendable () throws -> T + ) -> NIOCore.Scheduled { + self.base.scheduleTask(deadline: deadline, task) + } + + func scheduleTask( + in delay: NIOCore.TimeAmount, + _ task: @escaping @Sendable () throws -> T + ) -> NIOCore.Scheduled { + self.base.scheduleTask(in: delay, task) + } + + func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable ((any Error)?) -> Void) { + self.base.shutdownGracefully(queue: queue, callback) + } + + func runForTests() { + self.base.runForTests() + } + + func advanceTimeForTests(by amount: TimeAmount) { + self.base.advanceTimeForTests(by: amount) + } +} + private protocol RunnableEventLoop: EventLoop { func runForTests() func advanceTimeForTests(by: TimeAmount) @@ -498,4 +550,50 @@ final class EventLoopFutureIsolatedTest: XCTestCase { let loop = NIOAsyncTestingEventLoop() try self._eventLoopIsolatedUnchecked(loop: loop) } + + // MARK: Fallback + func testCompletingPromiseWithNonSendableValue_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableValue(loop: loop) + } + + func testCompletingPromiseWithNonSendableResult_() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableResult(loop: loop) + } + + func testCompletingPromiseWithNonSendableValueUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableValueUnchecked(loop: loop) + } + + func testCompletingPromiseWithNonSendableResultUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._completingPromiseWithNonSendableResultUnchecked(loop: loop) + } + + func testBackAndForthUnwrapping_Fallback() throws { + let loop = FallbackEventLoop() + try self._backAndForthUnwrapping(loop: loop) + } + + func testBackAndForthUnwrappingUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._backAndForthUnwrappingUnchecked(loop: loop) + } + + func testFutureChaining_Fallback() throws { + let loop = FallbackEventLoop() + try self._futureChaining(loop: loop) + } + + func testEventLoopIsolated_Fallback() throws { + let loop = FallbackEventLoop() + try self._eventLoopIsolated(loop: loop) + } + + func testEventLoopIsolatedUnchecked_Fallback() throws { + let loop = FallbackEventLoop() + try self._eventLoopIsolatedUnchecked(loop: loop) + } } From bf41ad1595fa273de1f70ee8e3f51948fd47266d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mirza=20U=C4=8Danbarli=C4=87?= <56406159+supersonicbyte@users.noreply.github.com> Date: Mon, 20 Jan 2025 17:39:21 +0100 Subject: [PATCH 56/93] Improve HTTPHeaders description performance (#3063) ### Motivation: As outlined in this [issue](https://github.com/apple/swift-nio/issues/2930) by @weissi, the current performance of calling `description` on `HTTPHeaders` is undermined by the dynamism of Array. ### Modifications: The proposed solution replaces the implementation of `description` to iterate over the items and print them out manually. This provides a faster solution since we bypass the cost of calling into `description` of an Array. ### Result: A more performant implementation of `HTTPHeaders` description. --------- Co-authored-by: Johannes Weiss Co-authored-by: Cory Benfield --- .../tests_01_http/test_07_headers_work.sh | 4 ++-- Sources/NIOHTTP1/HTTPTypes.swift | 5 ++++- Sources/NIOPerformanceTester/main.swift | 11 ++++++++++ Tests/NIOHTTP1Tests/HTTPHeadersTest.swift | 22 +++++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/IntegrationTests/tests_01_http/test_07_headers_work.sh b/IntegrationTests/tests_01_http/test_07_headers_work.sh index 6e3dc3365..6389929d9 100644 --- a/IntegrationTests/tests_01_http/test_07_headers_work.sh +++ b/IntegrationTests/tests_01_http/test_07_headers_work.sh @@ -19,8 +19,8 @@ source defines.sh token=$(create_token) start_server "$token" do_curl "$token" -H "foo: bar" --http1.0 \ - "http://foobar.com/dynamic/info" > "${tmp:?"tmp variable not set"}/out" -if ! grep -q '("foo", "bar")' "$tmp/out"; then + "http://foobar.com/dynamic/info" >"${tmp:?"tmp variable not set"}/out" +if ! grep -q 'foo: bar' "$tmp/out"; then fail "couldn't find header in response" fi stop_server "$token" diff --git a/Sources/NIOHTTP1/HTTPTypes.swift b/Sources/NIOHTTP1/HTTPTypes.swift index 321b494d6..92579c9ec 100644 --- a/Sources/NIOHTTP1/HTTPTypes.swift +++ b/Sources/NIOHTTP1/HTTPTypes.swift @@ -313,7 +313,10 @@ public struct HTTPHeaders: CustomStringConvertible, ExpressibleByDictionaryLiter internal var keepAliveState: KeepAliveState = .unknown public var description: String { - self.headers.description + self.headers.lazy.map { + "\($0.0): \($0.1)" + } + .joined(separator: "; ") } internal var names: [String] { diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index 13fc75222..48b84d352 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -276,6 +276,17 @@ measureAndPrint(desc: "http_headers_canonical_form_trimming_whitespace_from_long return count } +measureAndPrint(desc: "http_headers_description_100k") { + let headers = HTTPHeaders(Array(repeating: ("String", "String"), count: 100)) + + for _ in 0..<100_000 { + let str = headers.description + precondition(str.utf8.count > 100) + } + + return 0 +} + measureAndPrint(desc: "bytebuffer_write_12MB_short_string_literals") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) diff --git a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift index bd424f77d..4971af97a 100644 --- a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift @@ -400,4 +400,26 @@ class HTTPHeadersTest: XCTestCase { headers.reserveCapacity(4) XCTAssertEqual(headers.capacity, 4) } + + func testHTTPHeadersDescription() { + let originalHeaders = [ + ("User-Agent", "1"), + ("host", "2"), + ("X-SOMETHING", "3"), + ("SET-COOKIE", "foo=bar"), + ("Set-Cookie", "buz=cux"), + ] + + let headers = HTTPHeaders(originalHeaders) + + let expectedOutput = """ + User-Agent: 1; \ + host: 2; \ + X-SOMETHING: 3; \ + SET-COOKIE: foo=bar; \ + Set-Cookie: buz=cux + """ + + XCTAssertEqual(expectedOutput, headers.description) + } } From 0e9b8378bac9e2d22932c34c7dfcbca6ecbf1a82 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 20 Jan 2025 17:08:14 +0000 Subject: [PATCH 57/93] Fast-path isolated view for EmbeddedEventLoop (#3073) Motivation: This patch takes advantage of the fast-path for isolated views on EmbeddedEventLoop, reducing overhead when using EmbeddedEL. Modifications: - Implement the new witnesses in EmbeddedEL Result: EmbeddedEL is faster when using isolated views. --- Sources/NIOEmbedded/Embedded.swift | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index fbbfb4d67..e19caf40a 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -355,6 +355,36 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { return } + public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) { + // Because of the way EmbeddedEL works, we can just delegate this directly + // to execute. + self.execute(task) + } + + public func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture { + // Because of the way EmbeddedEL works, we can delegate this directly to schedule. Note that I didn't + // say submit: we don't have an override of submit here. + self.scheduleTask(deadline: self._now, task).futureResult + } + + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + // Because of the way EmbeddedEL works, we can delegate this directly to schedule. + self.scheduleTask(deadline: deadline, task) + } + + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + // Because of the way EmbeddedEL works, we can delegate this directly to schedule. + self.scheduleTask(in: delay, task) + } + deinit { self.checkCorrectThread() precondition(scheduledTasks.isEmpty, "Embedded event loop freed with unexecuted scheduled tasks!") From 5771d508657c74975342962a66fd689926f09243 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 21 Jan 2025 16:04:37 +0000 Subject: [PATCH 58/93] Enable optimized Isolated view path for AsyncTestingEL (#3074) Motivation: NIOAsyncTestingEL is another place where we can reduce the overhead of the isolated EL views. It's nice for the tests to run faster. Modifications: - Implement the new protocol witnesses for AsyncTestingEL - Refactor common code for scheduleTask out Result: AsyncTestingEL is faster. --- .../NIOEmbedded/AsyncTestingEventLoop.swift | 143 ++++++++++++++---- 1 file changed, 112 insertions(+), 31 deletions(-) diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index b0ee04036..ef0070b1c 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -134,7 +134,7 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { private func insertTask( taskID: UInt64, deadline: NIODeadline, - promise: EventLoopPromise, + promise: EventLoopPromise?, task: @escaping () throws -> ReturnType ) { dispatchPrecondition(condition: .onQueue(self.queue)) @@ -146,12 +146,12 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { task: { do { // UnsafeUnchecked is acceptable because we know we're in the loop here. - promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) + promise?.assumeIsolatedUnsafeUnchecked().succeed(try task()) } catch let err { - promise.fail(err) + promise?.fail(err) } }, - promise.fail + { promise?.fail($0) } ) self.scheduledTasks.push(task) @@ -164,38 +164,24 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { deadline: NIODeadline, _ task: @escaping @Sendable () throws -> T ) -> Scheduled { - let promise: EventLoopPromise = self.makePromise() - let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + let scheduled: Scheduled + switch self._prepareToSchedule(returnType: T.self) { + case .doSchedule(let taskID, let promise, let returned): + scheduled = returned - switch self.state.load(ordering: .acquiring) { - case .open: - break - case .closing, .closed: - // If the event loop is shut down, or shutting down, immediately cancel the task. - promise.fail(EventLoopError.cancelled) - return Scheduled(promise: promise, cancellationTask: {}) - } - - let scheduled = Scheduled( - promise: promise, - cancellationTask: { - if self.inEventLoop { - self.removeTask(taskID: taskID) - } else { - self.queue.async { - self.removeTask(taskID: taskID) - } + // Ok, actually do it. + if self.inEventLoop { + self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task) + } else { + self.queue.async { + self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task) } } - ) - if self.inEventLoop { - self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task) - } else { - self.queue.async { - self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task) - } + case .returnImmediately(let returned): + scheduled = returned } + return scheduled } @@ -411,6 +397,62 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { dispatchPrecondition(condition: .notOnQueue(self.queue)) } + public func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) { + // Call directly to insertTask. That function has a thread-safety check, and + // the rest of this method is using thread-safe operations so we don't + // need any extra debug-mode checking here. + let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + self.insertTask( + taskID: taskID, + deadline: self.now, + promise: nil, + task: task + ) + } + + public func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture { + // Call directly to insertTask. That function has a thread-safety check, and + // the rest of this method is using thread-safe operations so we don't + // need any extra debug-mode checking here. + let promise = self.makePromise(of: T.self) + let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + self.insertTask( + taskID: taskID, + deadline: self.now, + promise: promise, + task: task + ) + return promise.futureResult + } + + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + // Call directly to insertTask. That function has a thread-safety check, and + // the rest of this method is using thread-safe operations so we don't + // need any extra debug-mode checking here. + let scheduled: Scheduled + switch self._prepareToSchedule(returnType: T.self) { + case .doSchedule(let taskID, let promise, let returned): + scheduled = returned + self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task) + case .returnImmediately(let returned): + scheduled = returned + } + + return scheduled + } + + @discardableResult + public func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + self._scheduleTaskIsolatedUnsafeUnchecked(deadline: self.now + delay, task) + } + public func preconditionInEventLoop(file: StaticString, line: UInt) { dispatchPrecondition(condition: .onQueue(self.queue)) } @@ -419,6 +461,45 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { dispatchPrecondition(condition: .notOnQueue(self.queue)) } + enum ScheduleCreationResult { + case doSchedule(taskID: UInt64, promise: EventLoopPromise, scheduled: Scheduled) + case returnImmediately(Scheduled) + } + private func _prepareToSchedule( + returnType: ReturnType.Type = ReturnType.self + ) -> ScheduleCreationResult { + let promise = self.makePromise(of: ReturnType.self) + + switch self.state.load(ordering: .acquiring) { + case .open: + break + case .closing, .closed: + // If the event loop is shut down, or shutting down, immediately cancel the task. + promise.fail(EventLoopError.cancelled) + return .returnImmediately(Scheduled(promise: promise, cancellationTask: {})) + } + + let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + + let scheduled = Scheduled( + promise: promise, + cancellationTask: { + if self.inEventLoop { + self.removeTask(taskID: taskID) + } else { + self.queue.async { + self.removeTask(taskID: taskID) + } + } + } + ) + return .doSchedule( + taskID: taskID, + promise: promise, + scheduled: scheduled + ) + } + deinit { precondition(scheduledTasks.isEmpty, "NIOAsyncTestingEventLoop freed with unexecuted scheduled tasks!") } From e2bfe0875b9a14783a0347aa1f0b1744c4d08548 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 21 Jan 2025 16:36:41 +0000 Subject: [PATCH 59/93] Adopt optimized isolated path for SelectableEL (#3075) Motivation: Users of SelectableEventLoop deserve to have their code that uses the isolated event loop view perform at least as well as the code that doesn't. Modifications: - Adopt the extra protocol witnesses. - Refactor out common code. Result: Better performance --------- Co-authored-by: George Barnett --- .../tests_04_performance/Thresholds/5.10.json | 10 +- .../tests_04_performance/Thresholds/5.9.json | 10 +- .../tests_04_performance/Thresholds/6.0.json | 10 +- .../Thresholds/nightly-6.0.json | 10 +- .../Thresholds/nightly-main.json | 10 +- Sources/NIOPosix/SelectableEventLoop.swift | 100 +++++++++++++++--- 6 files changed, 108 insertions(+), 42 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index 4d7ee39d6..e824e4b81 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -20,7 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, - "assume_isolated_scheduling_10000_executions": 20100, + "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 110100, + "flat_schedule_assume_isolated_10000_tasks": 100100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -48,12 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, - "schedule_assume_isolated_10000_tasks": 50100, + "schedule_assume_isolated_10000_tasks": 40100, "schedule_with_deadline_10000_tasks": 40100, - "schedule_with_deadline_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_assume_isolated_10000_tasks": 40100, "scheduling_10000_executions": 89, "submit_10000_tasks": 20100, - "submit_assume_isolated_10000_tasks": 30100, + "submit_assume_isolated_10000_tasks": 20100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index d130a3f00..dccd62038 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -20,7 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 393050, - "assume_isolated_scheduling_10000_executions": 20100, + "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 110100, + "flat_schedule_assume_isolated_10000_tasks": 100100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -48,12 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, - "schedule_assume_isolated_10000_tasks": 50100, + "schedule_assume_isolated_10000_tasks": 40100, "schedule_with_deadline_10000_tasks": 40100, - "schedule_with_deadline_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_assume_isolated_10000_tasks": 40100, "scheduling_10000_executions": 89, "submit_10000_tasks": 20100, - "submit_assume_isolated_10000_tasks": 30100, + "submit_assume_isolated_10000_tasks": 20100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index 4d7ee39d6..e824e4b81 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -20,7 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, - "assume_isolated_scheduling_10000_executions": 20100, + "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 110100, + "flat_schedule_assume_isolated_10000_tasks": 100100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -48,12 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, - "schedule_assume_isolated_10000_tasks": 50100, + "schedule_assume_isolated_10000_tasks": 40100, "schedule_with_deadline_10000_tasks": 40100, - "schedule_with_deadline_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_assume_isolated_10000_tasks": 40100, "scheduling_10000_executions": 89, "submit_10000_tasks": 20100, - "submit_assume_isolated_10000_tasks": 30100, + "submit_assume_isolated_10000_tasks": 20100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index 4d7ee39d6..e824e4b81 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -20,7 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, - "assume_isolated_scheduling_10000_executions": 20100, + "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 110100, + "flat_schedule_assume_isolated_10000_tasks": 100100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -48,12 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, - "schedule_assume_isolated_10000_tasks": 50100, + "schedule_assume_isolated_10000_tasks": 40100, "schedule_with_deadline_10000_tasks": 40100, - "schedule_with_deadline_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_assume_isolated_10000_tasks": 40100, "scheduling_10000_executions": 89, "submit_10000_tasks": 20100, - "submit_assume_isolated_10000_tasks": 30100, + "submit_assume_isolated_10000_tasks": 20100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 273fc30e8..cbc4c829f 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -20,7 +20,7 @@ "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, "1_reqs_1000_conn": 384050, - "assume_isolated_scheduling_10000_executions": 20100, + "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -34,7 +34,7 @@ "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 110100, + "flat_schedule_assume_isolated_10000_tasks": 100100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, @@ -48,12 +48,12 @@ "read_10000_chunks_from_file": 110050, "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, - "schedule_assume_isolated_10000_tasks": 50100, + "schedule_assume_isolated_10000_tasks": 40100, "schedule_with_deadline_10000_tasks": 40100, - "schedule_with_deadline_assume_isolated_10000_tasks": 50100, + "schedule_with_deadline_assume_isolated_10000_tasks": 40100, "scheduling_10000_executions": 89, "submit_10000_tasks": 20100, - "submit_assume_isolated_10000_tasks": 30100, + "submit_assume_isolated_10000_tasks": 20100, "udp_1000_reqs_1_conn": 6200, "udp_1_reqs_1000_conn": 162050 } diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 04e0cc0bb..7bb3c9e0a 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -308,6 +308,29 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { @inlinable internal func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { let promise: EventLoopPromise = self.makePromise() + let (task, scheduled) = self._prepareToSchedule(deadline: deadline, promise: promise, task: task) + + do { + try self._schedule0(.scheduled(task)) + } catch { + promise.fail(error) + } + + return scheduled + } + + /// - see: `EventLoop.scheduleTask(in:_:)` + @inlinable + internal func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { + self.scheduleTask(deadline: .now() + `in`, task) + } + + @inlinable + func _prepareToSchedule( + deadline: NIODeadline, + promise: EventLoopPromise, + task: @escaping () throws -> T + ) -> (ScheduledTask, Scheduled) { let task = ScheduledTask( id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), { @@ -337,9 +360,42 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { // one wakeup. } ) + return (task, scheduled) + } + + @inlinable + func _executeIsolatedUnsafeUnchecked(_ task: @escaping () -> Void) { + // nothing we can do if we fail enqueuing here. + try? self._scheduleIsolated0(.immediate(.function(task))) + } + + @inlinable + func _submitIsolatedUnsafeUnchecked(_ task: @escaping () throws -> T) -> EventLoopFuture { + let promise = self.makePromise(of: T.self) + + self._executeIsolatedUnsafeUnchecked { + do { + // UnsafeUnchecked is allowed here because we know we are on the EL. + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) + } catch let err { + promise.fail(err) + } + } + + return promise.futureResult + } + + @inlinable + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + deadline: NIODeadline, + _ task: @escaping () throws -> T + ) -> Scheduled { + let promise: EventLoopPromise = self.makePromise() + let (task, scheduled) = self._prepareToSchedule(deadline: deadline, promise: promise, task: task) do { - try self._schedule0(.scheduled(task)) + try self._scheduleIsolated0(.scheduled(task)) } catch { promise.fail(error) } @@ -347,10 +403,13 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { return scheduled } - /// - see: `EventLoop.scheduleTask(in:_:)` @inlinable - internal func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { - scheduleTask(deadline: .now() + `in`, task) + @discardableResult + func _scheduleTaskIsolatedUnsafeUnchecked( + in delay: TimeAmount, + _ task: @escaping () throws -> T + ) -> Scheduled { + self._scheduleTaskIsolatedUnsafeUnchecked(deadline: .now() + delay, task) } // - see: `EventLoop.execute` @@ -372,19 +431,7 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { @usableFromInline internal func _schedule0(_ task: LoopTask) throws { if self.inEventLoop { - precondition( - self._validInternalStateToScheduleTasks, - "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop." - ) - - self._tasksLock.withLock { () -> Void in - switch task { - case .scheduled(let task): - self._scheduledTasks.push(task) - case .immediate(let task): - self._immediateTasks.append(task) - } - } + try self._scheduleIsolated0(task) } else { let shouldWakeSelector: Bool = self.externalStateLock.withLock { guard self.validExternalStateToScheduleTasks else { @@ -434,6 +481,25 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { } } + /// Add the `ScheduledTask` to be executed. + @usableFromInline + internal func _scheduleIsolated0(_ task: LoopTask) throws { + self.assertInEventLoop() + precondition( + self._validInternalStateToScheduleTasks, + "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop." + ) + + self._tasksLock.withLock { () -> Void in + switch task { + case .scheduled(let task): + self._scheduledTasks.push(task) + case .immediate(let task): + self._immediateTasks.append(task) + } + } + } + /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. @usableFromInline internal func _wakeupSelector() throws { From 55956988959a23147d597b1ff3256214a7066a6c Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Wed, 22 Jan 2025 08:26:58 +0000 Subject: [PATCH 60/93] Update nightly CI pipelines to 6.1 instead of 6.0 (#3076) ### Motivation: Active development has moved to 6.1 so the Swift 6.0 nightlies no longer deliver much value. ### Modifications: * Deprecate 6.0 nightly CI configuration parameters * Introduce new 6.1 nightly CI configuration parameters * Update the matrix generation script to handle 6.1 ### Result: * No more nightly 6.0 CI, 6.1 nightlies are introduced. * Configuration for 6.0 nightlies no longer has any effect. * All repos are automatically opted-in to 6.1 nightly linux pipelines **even if they opted out of 6.0**. --- .github/workflows/unit_tests.yml | 36 +++++++++++++++++++++++--------- scripts/generate_matrix.sh | 36 ++++++++++++++++---------------- 2 files changed, 44 insertions(+), 28 deletions(-) diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 8d064fec5..d09b45ed9 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -29,11 +29,19 @@ on: default: "" linux_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." default: true linux_nightly_6_0_arguments_override: type: string - description: "The arguments passed to swift test in the Linux nightly 6.0 Swift version matrix job." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + default: "" + linux_nightly_6_1_enabled: + type: boolean + description: "Boolean to enable the Linux nightly 6.1 Swift version matrix job. Defaults to true." + default: true + linux_nightly_6_1_arguments_override: + type: string + description: "The arguments passed to swift test in the Linux nightly 6.1 Swift version matrix job." default: "" linux_nightly_main_enabled: type: boolean @@ -46,7 +54,7 @@ on: windows_6_0_enabled: type: boolean - description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to false." default: false windows_6_0_arguments_override: type: string @@ -54,15 +62,23 @@ on: default: "" windows_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." default: false windows_nightly_6_0_arguments_override: type: string - description: "The arguments passed to swift test in the Windows nightly 6.0 Swift version matrix job." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + default: "" + windows_nightly_6_1_enabled: + type: boolean + description: "Boolean to enable the Windows nightly 6.1 Swift version matrix job. Defaults to false." + default: false + windows_nightly_6_1_arguments_override: + type: string + description: "The arguments passed to swift test in the Windows nightly 6.1 Swift version matrix job." default: "" windows_nightly_main_enabled: type: boolean - description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to false." default: false windows_nightly_main_arguments_override: type: string @@ -90,15 +106,15 @@ jobs: MATRIX_LINUX_5_10_COMMAND_ARGUMENTS: ${{ inputs.linux_5_10_arguments_override }} MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} MATRIX_LINUX_6_0_COMMAND_ARGUMENTS: ${{ inputs.linux_6_0_arguments_override }} - MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} - MATRIX_LINUX_NIGHTLY_6_0_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_6_0_arguments_override }} + MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }} + MATRIX_LINUX_NIGHTLY_6_1_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_6_1_arguments_override }} MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.linux_nightly_main_arguments_override }} MATRIX_WINDOWS_COMMAND: "swift test" MATRIX_WINDOWS_6_0_ENABLED: ${{ inputs.windows_6_0_enabled }} MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS: ${{ inputs.windows_6_0_arguments_override }} - MATRIX_WINDOWS_NIGHTLY_6_0_ENABLED: ${{ inputs.windows_nightly_6_0_enabled }} - MATRIX_WINDOWS_NIGHTLY_6_0_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_6_0_arguments_override }} + MATRIX_WINDOWS_NIGHTLY_6_1_ENABLED: ${{ inputs.windows_nightly_6_1_enabled }} + MATRIX_WINDOWS_NIGHTLY_6_1_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_6_1_arguments_override }} MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED: ${{ inputs.windows_nightly_main_enabled }} MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS: ${{ inputs.windows_nightly_main_arguments_override }} diff --git a/scripts/generate_matrix.sh b/scripts/generate_matrix.sh index c7915b478..56a8ca6b9 100755 --- a/scripts/generate_matrix.sh +++ b/scripts/generate_matrix.sh @@ -22,8 +22,8 @@ linux_5_10_enabled="${MATRIX_LINUX_5_10_ENABLED:=true}" linux_5_10_command_arguments="$MATRIX_LINUX_5_10_COMMAND_ARGUMENTS" linux_6_0_enabled="${MATRIX_LINUX_6_0_ENABLED:=true}" linux_6_0_command_arguments="$MATRIX_LINUX_6_0_COMMAND_ARGUMENTS" -linux_nightly_6_0_enabled="${MATRIX_LINUX_NIGHTLY_6_0_ENABLED:=true}" -linux_nightly_6_0_command_arguments="$MATRIX_LINUX_NIGHTLY_6_0_COMMAND_ARGUMENTS" +linux_nightly_6_1_enabled="${MATRIX_LINUX_NIGHTLY_6_1_ENABLED:=true}" +linux_nightly_6_1_command_arguments="$MATRIX_LINUX_NIGHTLY_6_1_COMMAND_ARGUMENTS" linux_nightly_main_enabled="${MATRIX_LINUX_NIGHTLY_MAIN_ENABLED:=true}" linux_nightly_main_command_arguments="$MATRIX_LINUX_NIGHTLY_MAIN_COMMAND_ARGUMENTS" @@ -31,8 +31,8 @@ windows_command="$MATRIX_WINDOWS_COMMAND" # required if any Windows pipeline is windows_setup_command="$MATRIX_WINDOWS_SETUP_COMMAND" windows_6_0_enabled="${MATRIX_WINDOWS_6_0_ENABLED:=false}" windows_6_0_command_arguments="$MATRIX_WINDOWS_6_0_COMMAND_ARGUMENTS" -windows_nightly_6_0_enabled="${MATRIX_WINDOWS_NIGHTLY_6_0_ENABLED:=false}" -windows_nightly_6_0_command_arguments="$MATRIX_WINDOWS_NIGHTLY_6_0_COMMAND_ARGUMENTS" +windows_nightly_6_1_enabled="${MATRIX_WINDOWS_NIGHTLY_6_1_ENABLED:=false}" +windows_nightly_6_1_command_arguments="$MATRIX_WINDOWS_NIGHTLY_6_1_COMMAND_ARGUMENTS" windows_nightly_main_enabled="${MATRIX_WINDOWS_NIGHTLY_MAIN_ENABLED:=false}" windows_nightly_main_command_arguments="$MATRIX_WINDOWS_NIGHTLY_MAIN_COMMAND_ARGUMENTS" @@ -41,13 +41,13 @@ linux_runner="ubuntu-latest" linux_5_9_container_image="swift:5.9-jammy" linux_5_10_container_image="swift:5.10-jammy" linux_6_0_container_image="swift:6.0-jammy" -linux_nightly_6_0_container_image="swiftlang/swift:nightly-6.0-jammy" +linux_nightly_6_1_container_image="swiftlang/swift:nightly-6.1-jammy" linux_nightly_main_container_image="swiftlang/swift:nightly-main-jammy" windows_6_0_runner="windows-2022" windows_6_0_container_image="swift:6.0-windowsservercore-ltsc2022" -windows_nightly_6_0_runner="windows-2019" -windows_nightly_6_0_container_image="swiftlang/swift:nightly-6.0-windowsservercore-1809" +windows_nightly_6_1_runner="windows-2019" +windows_nightly_6_1_container_image="swiftlang/swift:nightly-6.1-windowsservercore-1809" windows_nightly_main_runner="windows-2019" windows_nightly_main_container_image="swiftlang/swift:nightly-main-windowsservercore-1809" @@ -56,7 +56,7 @@ matrix='{"config": []}' ## Linux if [[ "$linux_5_9_enabled" == "true" || "$linux_5_10_enabled" == "true" || "$linux_6_0_enabled" == "true" || \ - "$linux_nightly_6_0_enabled" == "true" || "$linux_nightly_main_enabled" == "true" ]]; then + "$linux_nightly_6_1_enabled" == "true" || "$linux_nightly_main_enabled" == "true" ]]; then if [[ -z "$linux_command" ]]; then echo "No linux command defined"; exit 1 fi @@ -93,14 +93,14 @@ if [[ "$linux_6_0_enabled" == "true" ]]; then '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi -if [[ "$linux_nightly_6_0_enabled" == "true" ]]; then +if [[ "$linux_nightly_6_1_enabled" == "true" ]]; then matrix=$(echo "$matrix" | jq -c \ --arg setup_command "$linux_setup_command" \ --arg command "$linux_command" \ - --arg command_arguments "$linux_nightly_6_0_command_arguments" \ - --arg container_image "$linux_nightly_6_0_container_image" \ + --arg command_arguments "$linux_nightly_6_1_command_arguments" \ + --arg container_image "$linux_nightly_6_1_container_image" \ --arg runner "$linux_runner" \ - '.config[.config| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') + '.config[.config| length] |= . + { "name": "nightly-6.1", "image": $container_image, "swift_version": "nightly-6.1", "platform": "Linux", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner}') fi if [[ "$linux_nightly_main_enabled" == "true" ]]; then @@ -114,7 +114,7 @@ if [[ "$linux_nightly_main_enabled" == "true" ]]; then fi ## Windows -if [[ "$windows_6_0_enabled" == "true" || "$windows_nightly_6_0_enabled" == "true" || "$windows_nightly_main_enabled" == "true" ]]; then +if [[ "$windows_6_0_enabled" == "true" || "$windows_nightly_6_1_enabled" == "true" || "$windows_nightly_main_enabled" == "true" ]]; then if [[ -z "$windows_command" ]]; then echo "No windows command defined"; exit 1 fi @@ -130,14 +130,14 @@ if [[ "$windows_6_0_enabled" == "true" ]]; then '.config[.config| length] |= . + { "name": "6.0", "image": $container_image, "swift_version": "6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') fi -if [[ "$windows_nightly_6_0_enabled" == "true" ]]; then +if [[ "$windows_nightly_6_1_enabled" == "true" ]]; then matrix=$(echo "$matrix" | jq -c \ --arg setup_command "$windows_setup_command" \ --arg command "$windows_command" \ - --arg command_arguments "$windows_nightly_6_0_command_arguments" \ - --arg container_image "$windows_nightly_6_0_container_image" \ - --arg runner "$windows_nightly_6_0_runner" \ - '.config[.config| length] |= . + { "name": "nightly-6.0", "image": $container_image, "swift_version": "nightly-6.0", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') + --arg command_arguments "$windows_nightly_6_1_command_arguments" \ + --arg container_image "$windows_nightly_6_1_container_image" \ + --arg runner "$windows_nightly_6_1_runner" \ + '.config[.config| length] |= . + { "name": "nightly-6.1", "image": $container_image, "swift_version": "nightly-6.1", "platform": "Windows", "command": $command, "command_arguments": $command_arguments, "setup_command": $setup_command, "runner": $runner }') fi if [[ "$windows_nightly_main_enabled" == "true" ]]; then From 9336e1f2590242c52e4dc45081dedb7bb4544f2e Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Wed, 22 Jan 2025 13:38:02 +0000 Subject: [PATCH 61/93] more 6.0 nightly to 6.1 nightly CI changes (#3078) ### Motivation: Some changes were missed in #3076, passing through parameters for the new 6.1 version. ### Modifications: Pass through more parameters, clean up misleading comments. ### Result: 6.1 nightly runs will be more like 6.0 nightly runs were --- .github/workflows/benchmarks.yml | 14 +++++++++----- .github/workflows/cxx_interop.yml | 8 ++++++-- .github/workflows/main.yml | 2 +- .github/workflows/pull_request.yml | 2 +- ...NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json | 0 .../NIOPosixBenchmarks.TCPEcho.p90.json | 0 ...NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json | 0 .../{nightly-6.0.json => nightly-6.1.json} | 0 scripts/check-matrix-job.ps1 | 6 +++--- scripts/check-matrix-job.sh | 6 +++--- 10 files changed, 23 insertions(+), 15 deletions(-) rename Benchmarks/Thresholds/{nightly-6.0 => nightly-6.1}/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json (100%) rename Benchmarks/Thresholds/{nightly-6.0 => nightly-6.1}/NIOPosixBenchmarks.TCPEcho.p90.json (100%) rename Benchmarks/Thresholds/{nightly-6.0 => nightly-6.1}/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json (100%) rename IntegrationTests/tests_04_performance/Thresholds/{nightly-6.0.json => nightly-6.1.json} (100%) diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index 4fd97e040..a5114b2f2 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -24,7 +24,11 @@ on: default: true linux_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + default: false + linux_nightly_6_1_enabled: + type: boolean + description: "Boolean to enable the Linux nightly 6.1 Swift version matrix job. Defaults to true." default: true linux_nightly_main_enabled: type: boolean @@ -33,15 +37,15 @@ on: windows_6_0_enabled: type: boolean - description: "Boolean to enable the Windows 6.0 Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows 6.0 Swift version matrix job. Currently has no effect!" # TODO: implement Windows benchmarking default: false windows_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." # TODO: implement Windows benchmarking default: false windows_nightly_main_enabled: type: boolean - description: "Boolean to enable the Windows nightly main Swift version matrix job. Defaults to true." + description: "Boolean to enable the Windows nightly main Swift version matrix job. Currently has no effect!" # TODO: implement Windows benchmarking default: false jobs: @@ -63,7 +67,7 @@ jobs: MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }} MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} - MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }} MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} benchmarks: diff --git a/.github/workflows/cxx_interop.yml b/.github/workflows/cxx_interop.yml index 3e0dda32e..c36eb3c0d 100644 --- a/.github/workflows/cxx_interop.yml +++ b/.github/workflows/cxx_interop.yml @@ -16,6 +16,10 @@ on: description: "Boolean to enable the Linux 6.0 Swift version matrix job. Defaults to true." default: true linux_nightly_6_0_enabled: + type: boolean + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + default: false + linux_nightly_6_1_enabled: type: boolean description: "Boolean to enable the Linux nightly 6.0 Swift version matrix job. Defaults to true." default: true @@ -30,7 +34,7 @@ on: default: false windows_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the Windows nightly 6.0 Swift version matrix job. Defaults to false. Currently has no effect!" # TODO: implement Windows Cxx compat checking + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." # TODO: implement Windows Cxx compat checking default: false windows_nightly_main_enabled: type: boolean @@ -56,7 +60,7 @@ jobs: MATRIX_LINUX_5_9_ENABLED: ${{ inputs.linux_5_9_enabled }} MATRIX_LINUX_5_10_ENABLED: ${{ inputs.linux_5_10_enabled }} MATRIX_LINUX_6_0_ENABLED: ${{ inputs.linux_6_0_enabled }} - MATRIX_LINUX_NIGHTLY_6_0_ENABLED: ${{ inputs.linux_nightly_6_0_enabled }} + MATRIX_LINUX_NIGHTLY_6_1_ENABLED: ${{ inputs.linux_nightly_6_1_enabled }} MATRIX_LINUX_NIGHTLY_MAIN_ENABLED: ${{ inputs.linux_nightly_main_enabled }} cxx-interop: diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 71ced6aa1..7b7111804 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -15,7 +15,7 @@ jobs: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" - linux_nightly_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + linux_nightly_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" cxx-interop: diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 0336d05c6..1925c4a54 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -19,7 +19,7 @@ jobs: linux_5_9_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_5_10_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" - linux_nightly_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + linux_nightly_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" benchmarks: diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json similarity index 100% rename from Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json rename to Benchmarks/Thresholds/nightly-6.1/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json similarity index 100% rename from Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEcho.p90.json rename to Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json similarity index 100% rename from Benchmarks/Thresholds/nightly-6.0/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json rename to Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEchoAsyncChannel.p90.json diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json similarity index 100% rename from IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json rename to IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json diff --git a/scripts/check-matrix-job.ps1 b/scripts/check-matrix-job.ps1 index c48aeb550..46ad96339 100644 --- a/scripts/check-matrix-job.ps1 +++ b/scripts/check-matrix-job.ps1 @@ -52,7 +52,7 @@ $command = $env:COMMAND $command_5_9 = $env:COMMAND_OVERRIDE_5_9 $command_5_10 = $env:COMMAND_OVERRIDE_5_10 $command_6_0 = $env:COMMAND_OVERRIDE_6_0 -$command_nightly_6_0 = $env:COMMAND_OVERRIDE_NIGHTLY_6_0 +$command_nightly_6_1 = $env:COMMAND_OVERRIDE_NIGHTLY_6_1 $command_nightly_main = $env:COMMAND_OVERRIDE_NIGHTLY_MAIN if ($swift_version -eq "5.9" -and $command_5_9) { @@ -64,9 +64,9 @@ if ($swift_version -eq "5.9" -and $command_5_9) { } elseif ($swift_version -eq "6.0" -and $command_6_0) { Log "Running 6.0 command override" Invoke-Expression $command_6_0 -} elseif ($swift_version -eq "nightly-6.0" -and $command_nightly_6_0) { +} elseif ($swift_version -eq "nightly-6.0" -and $command_nightly_6_1) { Log "Running nightly 6.0 command override" - Invoke-Expression $command_nightly_6_0 + Invoke-Expression $command_nightly_6_1 } elseif ($swift_version -eq "nightly-main" -and $command_nightly_main) { Log "Running nightly main command override" Invoke-Expression $command_nightly_main diff --git a/scripts/check-matrix-job.sh b/scripts/check-matrix-job.sh index 3b264670c..511144c4b 100755 --- a/scripts/check-matrix-job.sh +++ b/scripts/check-matrix-job.sh @@ -25,7 +25,7 @@ command="$COMMAND" command_5_9="$COMMAND_OVERRIDE_5_9" command_5_10="$COMMAND_OVERRIDE_5_10" command_6_0="$COMMAND_OVERRIDE_6_0" -command_nightly_6_0="$COMMAND_OVERRIDE_NIGHTLY_6_0" +command_nightly_6_1="$COMMAND_OVERRIDE_NIGHTLY_6_1" command_nightly_main="$COMMAND_OVERRIDE_NIGHTLY_MAIN" if [[ "$swift_version" == "5.9" ]] && [[ -n "$command_5_9" ]]; then @@ -37,9 +37,9 @@ elif [[ "$swift_version" == "5.10" ]] && [[ -n "$command_5_10" ]]; then elif [[ "$swift_version" == "6.0" ]] && [[ -n "$command_6_0" ]]; then log "Running 6.0 command override" eval "$command_6_0" -elif [[ "$swift_version" == "nightly-6.0" ]] && [[ -n "$command_nightly_6_0" ]]; then +elif [[ "$swift_version" == "nightly-6.0" ]] && [[ -n "$command_nightly_6_1" ]]; then log "Running nightly 6.0 command override" - eval "$command_nightly_6_0" + eval "$command_nightly_6_1" elif [[ "$swift_version" == "nightly-main" ]] && [[ -n "$command_nightly_main" ]]; then log "Running nightly main command override" eval "$command_nightly_main" From 187bfa88630a671781b9d1c3939a2f425ac0aa3a Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Wed, 22 Jan 2025 15:24:37 +0000 Subject: [PATCH 62/93] check-matrix-job.sh should tolerate unset 6.1 vars (#3080) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Motivation: We recently added support for nightly 6.1 Swift and old scripts making use of `check-matrix-job.sh` do not set `COMMAND_OVERRIDE_NIGHTLY_6_1` which causes the script to fail. We should tolerate this. ### Modifications: Add a default case for `COMMAND_OVERRIDE_NIGHTLY_6_1`. ### Result: No failures if a caller doesn't specify `COMMAND_OVERRIDE_NIGHTLY_6_1`. ``` ❯ SWIFT_VERSION=nightly-6.1 COMMAND="echo foo" COMMAND_OVERRIDE_5_9="" COMMAND_OVERRIDE_5_10="" COMMAND_OVERRIDE_6_0="" COMMAND_OVERRIDE_NIGHTLY_MAIN="" ./scripts/check-matrix-job.sh ** Running default command foo ❯ SWIFT_VERSION=nightly-6.1 COMMAND="echo foo" COMMAND_OVERRIDE_5_9="" COMMAND_OVERRIDE_5_10="" COMMAND_OVERRIDE_6_0="" COMMAND_OVERRIDE_NIGHTLY_MAIN="" COMMAND_OVERRIDE_NIGHTLY_6_1="echo bar" ./scripts/check-matrix-job.sh ** Running nightly 6.1 command override bar ``` --- scripts/check-matrix-job.ps1 | 4 ++-- scripts/check-matrix-job.sh | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/check-matrix-job.ps1 b/scripts/check-matrix-job.ps1 index 46ad96339..3f60cc5e8 100644 --- a/scripts/check-matrix-job.ps1 +++ b/scripts/check-matrix-job.ps1 @@ -64,8 +64,8 @@ if ($swift_version -eq "5.9" -and $command_5_9) { } elseif ($swift_version -eq "6.0" -and $command_6_0) { Log "Running 6.0 command override" Invoke-Expression $command_6_0 -} elseif ($swift_version -eq "nightly-6.0" -and $command_nightly_6_1) { - Log "Running nightly 6.0 command override" +} elseif ($swift_version -eq "nightly-6.1" -and $command_nightly_6_1) { + Log "Running nightly 6.1 command override" Invoke-Expression $command_nightly_6_1 } elseif ($swift_version -eq "nightly-main" -and $command_nightly_main) { Log "Running nightly main command override" diff --git a/scripts/check-matrix-job.sh b/scripts/check-matrix-job.sh index 511144c4b..a6723b929 100755 --- a/scripts/check-matrix-job.sh +++ b/scripts/check-matrix-job.sh @@ -25,7 +25,7 @@ command="$COMMAND" command_5_9="$COMMAND_OVERRIDE_5_9" command_5_10="$COMMAND_OVERRIDE_5_10" command_6_0="$COMMAND_OVERRIDE_6_0" -command_nightly_6_1="$COMMAND_OVERRIDE_NIGHTLY_6_1" +command_nightly_6_1="${COMMAND_OVERRIDE_NIGHTLY_6_1:=""}" command_nightly_main="$COMMAND_OVERRIDE_NIGHTLY_MAIN" if [[ "$swift_version" == "5.9" ]] && [[ -n "$command_5_9" ]]; then @@ -37,8 +37,8 @@ elif [[ "$swift_version" == "5.10" ]] && [[ -n "$command_5_10" ]]; then elif [[ "$swift_version" == "6.0" ]] && [[ -n "$command_6_0" ]]; then log "Running 6.0 command override" eval "$command_6_0" -elif [[ "$swift_version" == "nightly-6.0" ]] && [[ -n "$command_nightly_6_1" ]]; then - log "Running nightly 6.0 command override" +elif [[ "$swift_version" == "nightly-6.1" ]] && [[ -n "$command_nightly_6_1" ]]; then + log "Running nightly 6.1 command override" eval "$command_nightly_6_1" elif [[ "$swift_version" == "nightly-main" ]] && [[ -n "$command_nightly_main" ]]; then log "Running nightly main command override" From b14012bb1ae9876e048f60fb6e3986eb061ba558 Mon Sep 17 00:00:00 2001 From: Clinton Nkwocha <32041805+clintonpi@users.noreply.github.com> Date: Wed, 22 Jan 2025 16:26:51 +0000 Subject: [PATCH 63/93] Improve `flatScheduleTask` (#3079) Motivation: As pointed out in #3071, the `flatScheduleTask` implementations can be improved. Modifications: - Refactor the `flatScheduleTask` implementations to skip `flatMap` calls, which avoids creating an extra promise. - As there is now a lower number of allocations, reduce the necessary thresholds for the allocation tests. Result: Reduction in the number of allocations in the package. --------- Co-authored-by: George Barnett --- .../tests_04_performance/Thresholds/5.10.json | 4 ++-- .../tests_04_performance/Thresholds/5.9.json | 4 ++-- .../tests_04_performance/Thresholds/6.0.json | 6 +++--- .../Thresholds/nightly-6.1.json | 4 ++-- .../Thresholds/nightly-main.json | 4 ++-- Sources/NIOCore/EventLoop.swift | 20 +++++++++++++++++-- .../EventLoopFuture+AssumeIsolated.swift | 10 +++++++++- 7 files changed, 38 insertions(+), 14 deletions(-) diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.10.json b/IntegrationTests/tests_04_performance/Thresholds/5.10.json index e824e4b81..29a7bf1e7 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.10.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.10.json @@ -33,8 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 100100, + "flat_schedule_10000_tasks": 100100, + "flat_schedule_assume_isolated_10000_tasks": 90100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/5.9.json b/IntegrationTests/tests_04_performance/Thresholds/5.9.json index dccd62038..2d8cb07bf 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/5.9.json +++ b/IntegrationTests/tests_04_performance/Thresholds/5.9.json @@ -33,8 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 100100, + "flat_schedule_10000_tasks": 100100, + "flat_schedule_assume_isolated_10000_tasks": 90100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/6.0.json b/IntegrationTests/tests_04_performance/Thresholds/6.0.json index e824e4b81..0870e3343 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/6.0.json @@ -19,7 +19,7 @@ "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, "1000_udpconnections": 75050, - "1_reqs_1000_conn": 384050, + "1_reqs_1000_conn": 384000, "assume_isolated_scheduling_10000_executions": 89, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, @@ -33,8 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 100100, + "flat_schedule_10000_tasks": 100100, + "flat_schedule_assume_isolated_10000_tasks": 90100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json index e824e4b81..29a7bf1e7 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.1.json @@ -33,8 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 100100, + "flat_schedule_10000_tasks": 100100, + "flat_schedule_assume_isolated_10000_tasks": 90100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index cbc4c829f..a5ce73574 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -33,8 +33,8 @@ "encode_1000_ws_frames_new_buffer_with_space": 3050, "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, "execute_hop_10000_tasks": 0, - "flat_schedule_10000_tasks": 130100, - "flat_schedule_assume_isolated_10000_tasks": 100100, + "flat_schedule_10000_tasks": 100100, + "flat_schedule_assume_isolated_10000_tasks": 80100, "future_assume_isolated_lots_of_callbacks": 74050, "future_erase_result": 4050, "future_lots_of_callbacks": 74050, diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 98653bc56..d31640b0a 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -1009,7 +1009,15 @@ extension EventLoop { let promise: EventLoopPromise = self.makePromise(file: file, line: line) let scheduled = self.scheduleTask(deadline: deadline, task) - scheduled.futureResult.flatMap { $0 }.cascade(to: promise) + scheduled.futureResult.whenComplete { result in + switch result { + case .success(let futureResult): + promise.completeWith(futureResult) + case .failure(let error): + promise.fail(error) + } + } + return .init(promise: promise, cancellationTask: { scheduled.cancel() }) } @@ -1051,7 +1059,15 @@ extension EventLoop { let promise: EventLoopPromise = self.makePromise(file: file, line: line) let scheduled = self.scheduleTask(in: delay, task) - scheduled.futureResult.flatMap { $0 }.cascade(to: promise) + scheduled.futureResult.whenComplete { result in + switch result { + case .success(let futureResult): + promise.completeWith(futureResult) + case .failure(let error): + promise.fail(error) + } + } + return .init(promise: promise, cancellationTask: { scheduled.cancel() }) } diff --git a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift index 49593c1f5..7e7dd9f74 100644 --- a/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift +++ b/Sources/NIOCore/EventLoopFuture+AssumeIsolated.swift @@ -113,7 +113,15 @@ public struct NIOIsolatedEventLoop { let promise: EventLoopPromise = self._wrapped.makePromise(file: file, line: line) let scheduled = self.scheduleTask(deadline: deadline, task) - scheduled.futureResult.flatMap { $0 }.cascade(to: promise) + scheduled.futureResult.whenComplete { result in + switch result { + case .success(let futureResult): + promise.completeWith(futureResult) + case .failure(let error): + promise.fail(error) + } + } + return .init(promise: promise, cancellationTask: { scheduled.cancel() }) } From 0c547a717cfb79aaf669d825125fe99db421fff3 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 23 Jan 2025 13:22:18 +0000 Subject: [PATCH 64/93] Fix the HappyEyeballsResolver and core Bootstraps under strict concurrency (#3062) ### Motivation: The HappyEyeballsResolver, being an old part of our stack, has a lot of code in it that fails to pass strict concurrency checking. That's deeply suboptimal. ### Modifications: - Clean up the happy eyeballs resolver under strict concurrency - Further cleanups to the bootstraps ### Result: Another step taken on the road to strict concurrency. --- .../5.10/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../5.9/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../6.0/NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- .../NIOPosixBenchmarks.TCPEcho.p90.json | 2 +- Sources/NIOPosix/Bootstrap.swift | 166 +++++++++- Sources/NIOPosix/GetaddrinfoResolver.swift | 2 +- Sources/NIOPosix/HappyEyeballs.swift | 296 ++++++++++-------- Tests/NIOPosixTests/HappyEyeballsTest.swift | 123 ++++++-- 9 files changed, 413 insertions(+), 184 deletions(-) diff --git a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json index c9e4dbd4c..c6a93680d 100644 --- a/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.10/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 107 + "mallocCountTotal" : 108 } diff --git a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json index 82d63a322..248bd9606 100644 --- a/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/5.9/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 109 + "mallocCountTotal" : 110 } diff --git a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json index c9e4dbd4c..c6a93680d 100644 --- a/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/6.0/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 107 + "mallocCountTotal" : 108 } diff --git a/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json index c9e4dbd4c..c6a93680d 100644 --- a/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/nightly-6.1/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 107 + "mallocCountTotal" : 108 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json index c9e4dbd4c..c6a93680d 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOPosixBenchmarks.TCPEcho.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 107 + "mallocCountTotal" : 108 } diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 1ea1d311f..b7705dc01 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -823,7 +823,7 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { @usableFromInline internal var _channelOptions: ChannelOptions.Storage private var connectTimeout: TimeAmount = TimeAmount.seconds(10) - private var resolver: Optional + private var resolver: Optional private var bindTarget: Optional private var enableMPTCP: Bool @@ -924,7 +924,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { /// /// - Parameters: /// - resolver: The resolver that will be used during the connection attempt. - public func resolver(_ resolver: Resolver?) -> Self { + @preconcurrency + public func resolver(_ resolver: (Resolver & Sendable)?) -> Self { self.resolver = resolver return self } @@ -967,11 +968,23 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { func makeSocketChannel( eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily + ) throws -> SocketChannel { + try Self.makeSocketChannel( + eventLoop: eventLoop, + protocolFamily: protocolFamily, + enableMPTCP: self.enableMPTCP + ) + } + + static func makeSocketChannel( + eventLoop: EventLoop, + protocolFamily: NIOBSDSocket.ProtocolFamily, + enableMPTCP: Bool ) throws -> SocketChannel { try SocketChannel( eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily, - enableMPTCP: self.enableMPTCP + enableMPTCP: enableMPTCP ) } @@ -992,6 +1005,11 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { aiSocktype: .stream, aiProtocol: .tcp ) + let enableMPTCP = self.enableMPTCP + let channelInitializer = self.channelInitializer + let channelOptions = self._channelOptions + let bindTarget = self.bindTarget + let connector = HappyEyeballsConnector( resolver: resolver, loop: loop, @@ -999,7 +1017,14 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { port: port, connectTimeout: self.connectTimeout ) { eventLoop, protocolFamily in - self.initializeAndRegisterNewChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) { + Self.initializeAndRegisterNewChannel( + eventLoop: eventLoop, + protocolFamily: protocolFamily, + enableMPTCP: enableMPTCP, + channelInitializer: channelInitializer, + channelOptions: channelOptions, + bindTarget: bindTarget + ) { $0.eventLoop.makeSucceededFuture(()) } } @@ -1148,24 +1173,67 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> EventLoopFuture { + Self.initializeAndRegisterNewChannel( + eventLoop: eventLoop, + protocolFamily: protocolFamily, + enableMPTCP: self.enableMPTCP, + channelInitializer: self.channelInitializer, + channelOptions: self._channelOptions, + bindTarget: self.bindTarget, + body + ) + } + + private static func initializeAndRegisterNewChannel( + eventLoop: EventLoop, + protocolFamily: NIOBSDSocket.ProtocolFamily, + enableMPTCP: Bool, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { let channel: SocketChannel do { - channel = try self.makeSocketChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) + channel = try Self.makeSocketChannel( + eventLoop: eventLoop, + protocolFamily: protocolFamily, + enableMPTCP: enableMPTCP + ) } catch { return eventLoop.makeFailedFuture(error) } - return self.initializeAndRegisterChannel(channel, body) + return Self.initializeAndRegisterChannel( + channel, + channelInitializer: channelInitializer, + channelOptions: channelOptions, + bindTarget: bindTarget, + body + ) } private func initializeAndRegisterChannel( _ channel: SocketChannel, _ body: @escaping @Sendable (Channel) -> EventLoopFuture ) -> EventLoopFuture { - let channelInitializer = self.channelInitializer - let channelOptions = self._channelOptions + Self.initializeAndRegisterChannel( + channel, + channelInitializer: self.channelInitializer, + channelOptions: self._channelOptions, + bindTarget: self.bindTarget, + body + ) + } + + private static func initializeAndRegisterChannel( + _ channel: SocketChannel, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> EventLoopFuture { let eventLoop = channel.eventLoop - let bindTarget = self.bindTarget @inline(__always) @Sendable @@ -1352,6 +1420,11 @@ extension ClientBootstrap { aiProtocol: .tcp ) + let enableMPTCP = self.enableMPTCP + let bootstrapChannelInitializer = self.channelInitializer + let channelOptions = self._channelOptions + let bindTarget = self.bindTarget + let connector = HappyEyeballsConnector( resolver: resolver, loop: eventLoop, @@ -1359,9 +1432,13 @@ extension ClientBootstrap { port: port, connectTimeout: self.connectTimeout ) { eventLoop, protocolFamily in - self.initializeAndRegisterNewChannel( + Self.initializeAndRegisterNewChannel( eventLoop: eventLoop, protocolFamily: protocolFamily, + enableMPTPCP: enableMPTCP, + bootstrapChannelInitializer: bootstrapChannelInitializer, + channelOptions: channelOptions, + bindTarget: bindTarget, channelInitializer: channelInitializer, postRegisterTransformation: postRegisterTransformation ) { @@ -1426,6 +1503,46 @@ extension ClientBootstrap { ).map { (channel, $0) } } + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private static func initializeAndRegisterNewChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( + eventLoop: EventLoop, + protocolFamily: NIOBSDSocket.ProtocolFamily, + enableMPTPCP: Bool, + bootstrapChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< + PostRegistrationTransformationResult + >, + _ body: @escaping @Sendable (Channel) -> EventLoopFuture + ) -> EventLoopFuture<(Channel, PostRegistrationTransformationResult)> { + let channel: SocketChannel + do { + channel = try Self.makeSocketChannel( + eventLoop: eventLoop, + protocolFamily: protocolFamily, + enableMPTCP: enableMPTPCP + ) + } catch { + return eventLoop.makeFailedFuture(error) + } + return Self.initializeAndRegisterChannel( + channel: channel, + bootstrapChannelInitializer: bootstrapChannelInitializer, + channelOptions: channelOptions, + bindTarget: bindTarget, + channelInitializer: channelInitializer, + registration: { channel in + channel.registerAndDoSynchronously(body) + }, + postRegisterTransformation: postRegisterTransformation + ).map { (channel, $0) } + } + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) private func initializeAndRegisterChannel< ChannelInitializerResult: Sendable, @@ -1438,16 +1555,39 @@ extension ClientBootstrap { PostRegistrationTransformationResult > ) -> EventLoopFuture { - let bootstrapChannelInitializer = self.channelInitializer + Self.initializeAndRegisterChannel( + channel: channel, + bootstrapChannelInitializer: self.channelInitializer, + channelOptions: self._channelOptions, + bindTarget: self.bindTarget, + channelInitializer: channelInitializer, + registration: registration, + postRegisterTransformation: postRegisterTransformation + ) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private static func initializeAndRegisterChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( + channel: SocketChannel, + bootstrapChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + channelOptions: ChannelOptions.Storage, + bindTarget: SocketAddress?, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + registration: @escaping @Sendable (SocketChannel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture< + PostRegistrationTransformationResult + > + ) -> EventLoopFuture { let channelInitializer = { @Sendable channel in bootstrapChannelInitializer(channel).hop(to: channel.eventLoop) .assumeIsolated() .flatMap { channelInitializer(channel) } .nonisolated() } - let channelOptions = self._channelOptions let eventLoop = channel.eventLoop - let bindTarget = self.bindTarget @inline(__always) @Sendable diff --git a/Sources/NIOPosix/GetaddrinfoResolver.swift b/Sources/NIOPosix/GetaddrinfoResolver.swift index b24b0a9a2..3ec44ec6f 100644 --- a/Sources/NIOPosix/GetaddrinfoResolver.swift +++ b/Sources/NIOPosix/GetaddrinfoResolver.swift @@ -50,7 +50,7 @@ import struct WinSDK.SOCKADDR_IN6 // A thread-specific variable where we store the offload queue if we're on an `SelectableEventLoop`. let offloadQueueTSV = ThreadSpecificVariable() -internal class GetaddrinfoResolver: Resolver { +internal final class GetaddrinfoResolver: Resolver, Sendable { private let loop: EventLoop private let v4Future: EventLoopPromise<[SocketAddress]> private let v6Future: EventLoopPromise<[SocketAddress]> diff --git a/Sources/NIOPosix/HappyEyeballs.swift b/Sources/NIOPosix/HappyEyeballs.swift index 25071ec32..f1d2e9e3e 100644 --- a/Sources/NIOPosix/HappyEyeballs.swift +++ b/Sources/NIOPosix/HappyEyeballs.swift @@ -126,25 +126,142 @@ private struct TargetIterator: IteratorProtocol { /// Given a DNS resolver and an event loop, attempts to establish a connection to /// the target host over both IPv4 and IPv6. /// -/// This class provides the code that implements RFC 8305: Happy Eyeballs 2. This +/// This type provides the code that implements RFC 8305: Happy Eyeballs 2. This /// is a connection establishment strategy that attempts to efficiently and quickly /// establish connections to a host that has multiple IP addresses available to it, /// potentially over two different IP protocol versions (4 and 6). /// -/// This class should be created when a connection attempt is made and will remain +/// This type should be created when a connection attempt is made and will remain /// active until a connection is established. It is responsible for actually creating /// connections and managing timeouts. /// -/// This class's public API is thread-safe: the constructor and `resolveAndConnect` can +/// This type's public API is thread-safe: the constructor and `resolveAndConnect` can /// be called from any thread. `resolveAndConnect` will dispatch itself to the event /// loop to force serialization. /// -/// This class's private API is *not* thread-safe, and expects to be called from the -/// event loop thread of the `loop` it is passed. -/// /// The `ChannelBuilderResult` generic type can used to tunnel an arbitrary type /// from the `channelBuilderCallback` to the `resolve` methods return value. -internal final class HappyEyeballsConnector { +internal struct HappyEyeballsConnector: Sendable { + /// The DNS resolver provided by the user. + fileprivate let resolver: Resolver & Sendable + + /// The event loop this connector will run on. + fileprivate let loop: EventLoop + + /// The host name we're connecting to. + fileprivate let host: String + + /// The port we're connecting to. + fileprivate let port: Int + + /// A callback, provided by the user, that is used to build a channel. + /// + /// This callback is expected to build *and register* a channel with the event loop that + /// was used with this resolver. It is free to set up the channel asynchronously, but note + /// that the time taken to set the channel up will be counted against the connection delay, + /// meaning that long channel setup times may cause more connections to be outstanding + /// than intended. + /// + /// The channel builder callback takes an event loop and a protocol family as arguments. + fileprivate let channelBuilderCallback: + @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<(Channel, ChannelBuilderResult)> + + /// The amount of time to wait for an AAAA response to come in after a A response is + /// received. By default this is 50ms. + fileprivate let resolutionDelay: TimeAmount + + /// The amount of time to wait for a connection to succeed before beginning a new connection + /// attempt. By default this is 250ms. + fileprivate let connectionDelay: TimeAmount + + /// The amount of time to allow for the overall connection process before timing it out. + fileprivate let connectTimeout: TimeAmount + + /// The promise that will hold the final connected channel. + fileprivate let resolutionPromise: EventLoopPromise<(Channel, ChannelBuilderResult)> + + @inlinable + init( + resolver: Resolver & Sendable, + loop: EventLoop, + host: String, + port: Int, + connectTimeout: TimeAmount, + resolutionDelay: TimeAmount = .milliseconds(50), + connectionDelay: TimeAmount = .milliseconds(250), + channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture< + (Channel, ChannelBuilderResult) + > + ) { + self.resolver = resolver + self.loop = loop + self.host = host + self.port = port + self.connectTimeout = connectTimeout + self.channelBuilderCallback = channelBuilderCallback + + self.resolutionPromise = self.loop.makePromise() + + precondition( + resolutionDelay.nanoseconds > 0, + "Resolution delay must be greater than zero, got \(resolutionDelay)." + ) + self.resolutionDelay = resolutionDelay + + precondition( + connectionDelay >= .milliseconds(100) && connectionDelay <= .milliseconds(2000), + "Connection delay must be between 100 and 2000 ms, got \(connectionDelay)" + ) + self.connectionDelay = connectionDelay + } + + @inlinable + init( + resolver: Resolver & Sendable, + loop: EventLoop, + host: String, + port: Int, + connectTimeout: TimeAmount, + resolutionDelay: TimeAmount = .milliseconds(50), + connectionDelay: TimeAmount = .milliseconds(250), + channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture + ) where ChannelBuilderResult == Void { + self.init( + resolver: resolver, + loop: loop, + host: host, + port: port, + connectTimeout: connectTimeout, + resolutionDelay: resolutionDelay, + connectionDelay: connectionDelay + ) { loop, protocolFamily in + channelBuilderCallback(loop, protocolFamily).map { ($0, ()) } + } + } + + /// Initiate a DNS resolution attempt using Happy Eyeballs 2. + /// + /// returns: An `EventLoopFuture` that fires with a connected `Channel`. + @inlinable + func resolveAndConnect() -> EventLoopFuture<(Channel, ChannelBuilderResult)> { + // We dispatch ourselves onto the event loop, rather than do all the rest of our processing from outside it. + self.loop.execute { + let runner = HappyEyeballsConnectorRunner(connector: self) + runner.resolveAndConnect() + } + return self.resolutionPromise.futureResult + } + + /// Initiate a DNS resolution attempt using Happy Eyeballs 2. + /// + /// returns: An `EventLoopFuture` that fires with a connected `Channel`. + @inlinable + func resolveAndConnect() -> EventLoopFuture where ChannelBuilderResult == Void { + self.resolveAndConnect().map { $0.0 } + } +} + +private final class HappyEyeballsConnectorRunner { /// An enum for keeping track of connection state. private enum ConnectionState { /// Initial state. No work outstanding. @@ -205,57 +322,22 @@ internal final class HappyEyeballsConnector { case noTargetsRemaining } - /// The DNS resolver provided by the user. - private let resolver: Resolver - - /// The event loop this connector will run on. - private let loop: EventLoop - - /// The host name we're connecting to. - private let host: String - - /// The port we're connecting to. - private let port: Int - - /// A callback, provided by the user, that is used to build a channel. - /// - /// This callback is expected to build *and register* a channel with the event loop that - /// was used with this resolver. It is free to set up the channel asynchronously, but note - /// that the time taken to set the channel up will be counted against the connection delay, - /// meaning that long channel setup times may cause more connections to be outstanding - /// than intended. - /// - /// The channel builder callback takes an event loop and a protocol family as arguments. - private let channelBuilderCallback: - (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture<(Channel, ChannelBuilderResult)> - - /// The amount of time to wait for an AAAA response to come in after a A response is - /// received. By default this is 50ms. - private let resolutionDelay: TimeAmount + /// The thread-safe state across resolutions. + private let connector: HappyEyeballsConnector /// A reference to the task that will execute after the resolution delay expires, if /// one is scheduled. This is held to ensure that we can cancel this task if the AAAA /// response comes in before the resolution delay expires. private var resolutionTask: Optional> - /// The amount of time to wait for a connection to succeed before beginning a new connection - /// attempt. By default this is 250ms. - private let connectionDelay: TimeAmount - /// A reference to the task that will execute after the connection delay expires, if one /// is scheduled. This is held to ensure that we can cancel this task if a connection /// succeeds before the connection delay expires. private var connectionTask: Optional> - /// The amount of time to allow for the overall connection process before timing it out. - private let connectTimeout: TimeAmount - /// A reference to the task that will time us out. private var timeoutTask: Optional> - /// The promise that will hold the final connected channel. - private let resolutionPromise: EventLoopPromise<(Channel, ChannelBuilderResult)> - /// Our state machine state. private var state: ConnectionState @@ -280,89 +362,24 @@ internal final class HappyEyeballsConnector { @inlinable init( - resolver: Resolver, - loop: EventLoop, - host: String, - port: Int, - connectTimeout: TimeAmount, - resolutionDelay: TimeAmount = .milliseconds(50), - connectionDelay: TimeAmount = .milliseconds(250), - channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture< - (Channel, ChannelBuilderResult) - > + connector: HappyEyeballsConnector ) { - self.resolver = resolver - self.loop = loop - self.host = host - self.port = port - self.connectTimeout = connectTimeout - self.channelBuilderCallback = channelBuilderCallback + self.connector = connector self.resolutionTask = nil self.connectionTask = nil self.timeoutTask = nil self.state = .idle - self.resolutionPromise = self.loop.makePromise() - self.error = NIOConnectionError(host: host, port: port) - - precondition( - resolutionDelay.nanoseconds > 0, - "Resolution delay must be greater than zero, got \(resolutionDelay)." - ) - self.resolutionDelay = resolutionDelay - - precondition( - connectionDelay >= .milliseconds(100) && connectionDelay <= .milliseconds(2000), - "Connection delay must be between 100 and 2000 ms, got \(connectionDelay)" - ) - self.connectionDelay = connectionDelay - } - - @inlinable - convenience init( - resolver: Resolver, - loop: EventLoop, - host: String, - port: Int, - connectTimeout: TimeAmount, - resolutionDelay: TimeAmount = .milliseconds(50), - connectionDelay: TimeAmount = .milliseconds(250), - channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture - ) where ChannelBuilderResult == Void { - self.init( - resolver: resolver, - loop: loop, - host: host, - port: port, - connectTimeout: connectTimeout, - resolutionDelay: resolutionDelay, - connectionDelay: connectionDelay - ) { loop, protocolFamily in - channelBuilderCallback(loop, protocolFamily).map { ($0, ()) } - } + self.error = NIOConnectionError(host: self.connector.host, port: self.connector.port) } /// Initiate a DNS resolution attempt using Happy Eyeballs 2. - /// - /// returns: An `EventLoopFuture` that fires with a connected `Channel`. @inlinable - func resolveAndConnect() -> EventLoopFuture<(Channel, ChannelBuilderResult)> { - // We dispatch ourselves onto the event loop, rather than do all the rest of our processing from outside it. - self.loop.execute { - self.timeoutTask = self.loop.scheduleTask(in: self.connectTimeout) { - self.processInput(.connectTimeoutElapsed) - } - self.processInput(.resolve) + func resolveAndConnect() { + self.timeoutTask = self.connector.loop.assumeIsolated().scheduleTask(in: self.connector.connectTimeout) { + self.processInput(.connectTimeoutElapsed) } - return resolutionPromise.futureResult - } - - /// Initiate a DNS resolution attempt using Happy Eyeballs 2. - /// - /// returns: An `EventLoopFuture` that fires with a connected `Channel`. - @inlinable - func resolveAndConnect() -> EventLoopFuture where ChannelBuilderResult == Void { - self.resolveAndConnect().map { $0.0 } + self.processInput(.resolve) } /// Spin the state machine. @@ -490,11 +507,18 @@ internal final class HappyEyeballsConnector { // query. // // We hop back to `self.loop` because there's no guarantee the resolver runs - // on our event loop. - let aaaaLookup = self.resolver.initiateAAAAQuery(host: self.host, port: self.port).hop(to: self.loop) + // on our event loop. That hop then makes it safe for us to assumeIsolatedUnsafeUnchecked. + self.connector.loop.assertInEventLoop() + let aaaaLookup = self.connector.resolver.initiateAAAAQuery( + host: self.connector.host, + port: self.connector.port + ).hop(to: self.connector.loop).assumeIsolatedUnsafeUnchecked() self.whenAAAALookupComplete(future: aaaaLookup) - let aLookup = self.resolver.initiateAQuery(host: self.host, port: self.port).hop(to: self.loop) + let aLookup = self.connector.resolver.initiateAQuery( + host: self.connector.host, + port: self.connector.port + ).hop(to: self.connector.loop).assumeIsolatedUnsafeUnchecked() self.whenALookupComplete(future: aLookup) } @@ -506,7 +530,10 @@ internal final class HappyEyeballsConnector { /// /// This method sets off a scheduled task for the resolution delay. private func beginResolutionDelay() { - resolutionTask = loop.scheduleTask(in: resolutionDelay, resolutionDelayComplete) + resolutionTask = self.connector.loop.assumeIsolated().scheduleTask( + in: self.connector.resolutionDelay, + resolutionDelayComplete + ) } /// Called when we're ready to start connecting to targets. @@ -521,7 +548,11 @@ internal final class HappyEyeballsConnector { return } - connectionTask = loop.scheduleTask(in: connectionDelay) { self.processInput(.connectDelayElapsed) } + connectionTask = self.connector.loop.assumeIsolated().scheduleTask( + in: self.connector.connectionDelay + ) { + self.processInput(.connectDelayElapsed) + } connectToTarget(target) } @@ -573,7 +604,9 @@ internal final class HappyEyeballsConnector { /// Cleans up internal state and fails the connection promise. private func timedOut() { cleanUp() - self.resolutionPromise.fail(ChannelError.connectTimeout(self.connectTimeout)) + self.connector.resolutionPromise.fail( + ChannelError.connectTimeout(self.connector.connectTimeout) + ) } /// Called when we've attempted to connect to all our resolved targets, @@ -584,7 +617,7 @@ internal final class HappyEyeballsConnector { private func failed() { precondition(pendingConnections.isEmpty, "failed with pending connections") cleanUp() - self.resolutionPromise.fail(self.error) + self.connector.resolutionPromise.fail(self.error) } /// Called to connect to a given target. @@ -592,17 +625,18 @@ internal final class HappyEyeballsConnector { /// - Parameters: /// - target: The address to connect to. private func connectToTarget(_ target: SocketAddress) { - let channelFuture = channelBuilderCallback(self.loop, target.protocol) + let channelFuture = self.connector.channelBuilderCallback(self.connector.loop, target.protocol) + let isolatedChannelFuture = channelFuture.hop(to: self.connector.loop).assumeIsolated() pendingConnections.append(channelFuture) - channelFuture.whenSuccess { (channel, result) in + isolatedChannelFuture.whenSuccess { (channel, result) in // If we are in the complete state then we want to abandon this channel. Otherwise, begin // connecting. if case .complete = self.state { self.pendingConnections.removeAll { $0 === channelFuture } channel.close(promise: nil) } else { - channel.connect(to: target).map { + channel.connect(to: target).assumeIsolated().map { // The channel has connected. If we are in the complete state we want to abandon this channel. // Otherwise, fire the channel connected event. Either way we don't want the channel future to // be in our list of pending connections, so we don't either double close or close the connection @@ -613,7 +647,7 @@ internal final class HappyEyeballsConnector { channel.close(promise: nil) } else { self.processInput(.connectSuccess) - self.resolutionPromise.succeed((channel, result)) + self.connector.resolutionPromise.succeed((channel, result)) } }.whenFailure { err in // The connection attempt failed. If we're in the complete state then there's nothing @@ -631,7 +665,7 @@ internal final class HappyEyeballsConnector { } } } - channelFuture.whenFailure { error in + isolatedChannelFuture.whenFailure { error in self.error.connectionErrors.append(SingleConnectionFailure(target: target, error: error)) self.pendingConnections.removeAll { $0 === channelFuture } self.processInput(.connectFailed) @@ -644,7 +678,7 @@ internal final class HappyEyeballsConnector { assert(self.state == .complete, "Clean up in invalid state \(self.state)") if dnsResolutions < 2 { - resolver.cancelQueries() + self.connector.resolver.cancelQueries() } if let resolutionTask = self.resolutionTask { @@ -670,7 +704,7 @@ internal final class HappyEyeballsConnector { } /// A future callback that fires when a DNS A lookup completes. - private func whenALookupComplete(future: EventLoopFuture<[SocketAddress]>) { + private func whenALookupComplete(future: EventLoopFuture<[SocketAddress]>.Isolated) { future.map { results in self.targets.aResultsAvailable(results) }.recover { err in @@ -682,7 +716,7 @@ internal final class HappyEyeballsConnector { } /// A future callback that fires when a DNS AAAA lookup completes. - private func whenAAAALookupComplete(future: EventLoopFuture<[SocketAddress]>) { + private func whenAAAALookupComplete(future: EventLoopFuture<[SocketAddress]>.Isolated) { future.map { results in self.targets.aaaaResultsAvailable(results) }.recover { err in diff --git a/Tests/NIOPosixTests/HappyEyeballsTest.swift b/Tests/NIOPosixTests/HappyEyeballsTest.swift index 7e91b60a6..bebf3d48f 100644 --- a/Tests/NIOPosixTests/HappyEyeballsTest.swift +++ b/Tests/NIOPosixTests/HappyEyeballsTest.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import CNIOLinux +import NIOConcurrencyHelpers import NIOEmbedded import XCTest @@ -240,9 +241,12 @@ private class DummyResolver: Resolver { extension DummyResolver.Event: Equatable { } +@Sendable private func defaultChannelBuilder(loop: EventLoop, family: NIOBSDSocket.ProtocolFamily) -> EventLoopFuture { let channel = EmbeddedChannel(loop: loop as! EmbeddedEventLoop) - XCTAssertNoThrow(try channel.pipeline.addHandler(ConnectRecorder(), name: CONNECT_RECORDER).wait()) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler(ConnectRecorder(), name: CONNECT_RECORDER) + ) return loop.makeSucceededFuture(channel) } @@ -250,7 +254,7 @@ private func buildEyeballer( host: String, port: Int, connectTimeout: TimeAmount = .seconds(10), - channelBuilderCallback: @escaping (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture = + channelBuilderCallback: @escaping @Sendable (EventLoop, NIOBSDSocket.ProtocolFamily) -> EventLoopFuture = defaultChannelBuilder ) -> (eyeballer: HappyEyeballsConnector, resolver: DummyResolver, loop: EmbeddedEventLoop) { let loop = EmbeddedEventLoop() @@ -586,7 +590,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testMaximalConnectionDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -655,7 +659,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAllConnectionsFail() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -725,7 +729,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedAAAAResult() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -812,7 +816,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testTimeoutAfterAQuery() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -861,7 +865,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAConnectFailsWaitingForAAAA() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -920,7 +924,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedAResult() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -966,7 +970,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testTimeoutBeforeAResponse() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1015,7 +1019,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testAllConnectionsFailImmediately() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1065,7 +1069,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testLaterConnections() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1110,10 +1114,15 @@ public final class HappyEyeballsTest: XCTestCase { } func testDelayedChannelCreation() throws { - var ourChannelFutures: [EventLoopPromise] = [] + // This lock isn't really needed as the test is single-threaded, but because + // the buildEyeballer function constructs the event loop we can't use a LoopBoundBox. + // This is fine anyway. + let ourChannelFutures: NIOLockedValueBox<[EventLoopPromise]> = NIOLockedValueBox([]) let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { loop, _ in - ourChannelFutures.append(loop.makePromise()) - return ourChannelFutures.last!.futureResult + ourChannelFutures.withLockedValue { + $0.append(loop.makePromise()) + return $0.last!.futureResult + } } let channelFuture = eyeballer.resolveAndConnect() let expectedQueries: [DummyResolver.Event] = [ @@ -1127,37 +1136,51 @@ public final class HappyEyeballsTest: XCTestCase { // Return the IPv6 results and observe the channel creation attempts. resolver.v6Promise.succeed(MANY_IPv6_RESULTS) for channelCount in 1...10 { - XCTAssertEqual(ourChannelFutures.count, channelCount) + XCTAssertEqual( + ourChannelFutures.withLockedValue { $0.count }, + channelCount + ) loop.advanceTime(by: .milliseconds(250)) } XCTAssertFalse(channelFuture.isFulfilled) // Succeed the first channel future, which will connect because the default // channel builder always does. - defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { - ourChannelFutures.first!.succeed($0) - XCTAssertEqual($0.state(), .connected) + defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { result in + ourChannelFutures.withLockedValue { + $0.first!.succeed(result) + } + XCTAssertEqual(result.state(), .connected) } XCTAssertTrue(channelFuture.isFulfilled) // Ok, now succeed the second channel future. This should cause the channel to immediately be closed. - defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { - ourChannelFutures[1].succeed($0) - XCTAssertEqual($0.state(), .closed) + defaultChannelBuilder(loop: loop, family: .inet6).whenSuccess { result in + ourChannelFutures.withLockedValue { + $0[1].succeed(result) + } + XCTAssertEqual(result.state(), .closed) } - // Ok, now fail the third channel future. Nothing bad should happen here. - ourChannelFutures[2].fail(DummyError()) + try ourChannelFutures.withLockedValue { + // Ok, now fail the third channel future. Nothing bad should happen here. + $0[2].fail(DummyError()) - // Verify that the first channel is the one listed as connected. - XCTAssertTrue((try ourChannelFutures.first!.futureResult.wait()) === (try channelFuture.wait())) + // Verify that the first channel is the one listed as connected. + XCTAssertTrue((try $0.first!.futureResult.wait()) === (try channelFuture.wait())) + } } func testChannelCreationFails() throws { - var errors: [DummyError] = [] + // This lock isn't really needed as the test is single-threaded, but because + // the buildEyeballer function constructs the event loop we can't use a LoopBoundBox. + // This is fine anyway. + let errors: NIOLockedValueBox<[DummyError]> = NIOLockedValueBox([]) let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { loop, _ in - errors.append(DummyError()) - return loop.makeFailedFuture(errors.last!) + errors.withLockedValue { + $0.append(DummyError()) + return loop.makeFailedFuture($0.last!) + } } let channelFuture = eyeballer.resolveAndConnect() let expectedQueries: [DummyResolver.Event] = [ @@ -1171,21 +1194,21 @@ public final class HappyEyeballsTest: XCTestCase { // Here the AAAA and A results return. We are going to fail the channel creation // instantly, which should cause all 20 to appear. resolver.v6Promise.succeed(MANY_IPv6_RESULTS) - XCTAssertEqual(errors.count, 10) + XCTAssertEqual(errors.withLockedValue { $0.count }, 10) XCTAssertFalse(channelFuture.isFulfilled) resolver.v4Promise.succeed(MANY_IPv4_RESULTS) - XCTAssertEqual(errors.count, 20) + XCTAssertEqual(errors.withLockedValue { $0.count }, 20) XCTAssertTrue(channelFuture.isFulfilled) if let error = channelFuture.getError() as? NIOConnectionError { - XCTAssertEqual(error.connectionErrors.map { $0.error as! DummyError }, errors) + XCTAssertEqual(error.connectionErrors.map { $0.error as! DummyError }, errors.withLockedValue { $0 }) } else { XCTFail("Got unexpected error: \(String(describing: channelFuture.getError()))") } } func testCancellationSyncWithConnectDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1233,7 +1256,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testCancellationSyncWithResolutionDelay() throws { - var channels: [Channel] = [] + let channels = ChannelSet() defer { channels.finishAll() } @@ -1311,7 +1334,7 @@ public final class HappyEyeballsTest: XCTestCase { } func testResolutionTimeoutAndResolutionInSameTick() throws { - var channels: [Channel] = [] + let channels = ChannelSet() let (eyeballer, resolver, loop) = buildEyeballer(host: "example.com", port: 80) { let channelFuture = defaultChannelBuilder(loop: $0, family: $1) channelFuture.whenSuccess { channel in @@ -1357,3 +1380,35 @@ public final class HappyEyeballsTest: XCTestCase { XCTAssertEqual(resolver.events, expectedQueries) } } + +struct ChannelSet: Sendable, Sequence { + private let channels: NIOLockedValueBox<[Channel]> = .init([]) + + func append(_ channel: Channel) { + self.channels.withLockedValue { $0.append(channel) } + } + + var first: Channel? { + self.channels.withLockedValue { $0.first } + } + + var last: Channel? { + self.channels.withLockedValue { $0.last } + } + + var count: Int { + self.channels.withLockedValue { $0.count } + } + + subscript(index: Int) -> Channel { + self.channels.withLockedValue { $0[index] } + } + + func makeIterator() -> some IteratorProtocol { + self.channels.withLockedValue { $0.makeIterator() } + } + + func finishAll() { + self.channels.withLockedValue { $0 }.finishAll() + } +} From e40cbce38a1ca87328bbc3f05b7d174768ab6658 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 23 Jan 2025 15:46:48 +0000 Subject: [PATCH 65/93] Clean up Sendability in Thread and ThreadPool (#3081) Motivation Next on my journey of discovery is NIOThread and NIOThreadPool. These are basically fine, but they need some Sendability annotations and a bit of a cleanup. Modifications Add some Sendability Clean up some shutdown logic to avoid semaphores. Result Another step forward to a strict-concurrency safe world. --- Sources/NIOPosix/LinuxCPUSet.swift | 4 +- Sources/NIOPosix/NIOThreadPool.swift | 37 ++++++----- Sources/NIOPosix/Thread.swift | 4 +- Sources/NIOPosix/ThreadPosix.swift | 98 +++++++++++++++++----------- 4 files changed, 85 insertions(+), 58 deletions(-) diff --git a/Sources/NIOPosix/LinuxCPUSet.swift b/Sources/NIOPosix/LinuxCPUSet.swift index 6e4af51c4..4ca63931d 100644 --- a/Sources/NIOPosix/LinuxCPUSet.swift +++ b/Sources/NIOPosix/LinuxCPUSet.swift @@ -52,7 +52,7 @@ extension NIOThread { CNIOLinux_CPU_ZERO(&cpuset) let res = self.withUnsafeThreadHandle { p in - CNIOLinux_pthread_getaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset) + CNIOLinux_pthread_getaffinity_np(p.handle, MemoryLayout.size(ofValue: cpuset), &cpuset) } precondition(res == 0, "pthread_getaffinity_np failed: \(res)") @@ -75,7 +75,7 @@ extension NIOThread { CNIOLinux_CPU_SET(CInt(cpuID), &cpuset) } let res = self.withUnsafeThreadHandle { p in - CNIOLinux_pthread_setaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset) + CNIOLinux_pthread_setaffinity_np(p.handle, MemoryLayout.size(ofValue: cpuset), &cpuset) } precondition(res == 0, "pthread_setaffinity_np failed: \(res)") } diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index 75dfd0874..c3196b677 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -22,7 +22,7 @@ import Dispatch #endif /// Errors that may be thrown when executing work on a `NIOThreadPool` -public enum NIOThreadPoolError { +public enum NIOThreadPoolError: Sendable { /// The `NIOThreadPool` was not active. public struct ThreadPoolInactive: Error { @@ -73,7 +73,7 @@ public final class NIOThreadPool { } @usableFromInline - internal enum State { + internal enum State: Sendable { /// The `NIOThreadPool` is already stopped. case stopped /// The `NIOThreadPool` is shutting down, the array has one boolean entry for each thread indicating if it has shut down already. @@ -87,7 +87,7 @@ public final class NIOThreadPool { /// Whether threads in the pool have work. @usableFromInline - internal enum _WorkState: Hashable { + internal enum _WorkState: Hashable, Sendable { case hasWork case hasNoWork } @@ -138,7 +138,7 @@ public final class NIOThreadPool { self._shutdownGracefully(queue: queue, callback) } - private func _shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + private func _shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) { guard self.canBeStopped else { queue.async { callback(NIOThreadPoolError.UnsupportedOperation()) @@ -420,11 +420,17 @@ extension NIOThreadPool { /// - body: The closure which performs some blocking work to be done on the thread pool. /// - Returns: The `EventLoopFuture` of `promise` fulfilled with the result (or error) of the passed closure. @preconcurrency - public func runIfActive(eventLoop: EventLoop, _ body: @escaping @Sendable () throws -> T) -> EventLoopFuture { + public func runIfActive( + eventLoop: EventLoop, + _ body: @escaping @Sendable () throws -> T + ) -> EventLoopFuture { self._runIfActive(eventLoop: eventLoop, body) } - private func _runIfActive(eventLoop: EventLoop, _ body: @escaping () throws -> T) -> EventLoopFuture { + private func _runIfActive( + eventLoop: EventLoop, + _ body: @escaping @Sendable () throws -> T + ) -> EventLoopFuture { let promise = eventLoop.makePromise(of: T.self) self.submit { shouldRun in guard case shouldRun = NIOThreadPool.WorkItemState.active else { @@ -498,20 +504,21 @@ extension NIOThreadPool { } private func _syncShutdownGracefully() throws { - let errorStorageLock = NIOLock() - var errorStorage: Swift.Error? = nil - let continuation = DispatchWorkItem {} + let errorStorageLock = NIOLockedValueBox(nil) + let continuation = ConditionLock(value: 0) self.shutdownGracefully { error in if let error = error { - errorStorageLock.withLock { - errorStorage = error + errorStorageLock.withLockedValue { + $0 = error } } - continuation.perform() + continuation.lock(whenValue: 0) + continuation.unlock(withValue: 1) } - continuation.wait() - try errorStorageLock.withLock { - if let error = errorStorage { + continuation.lock(whenValue: 1) + continuation.unlock() + try errorStorageLock.withLockedValue { + if let error = $0 { throw error } } diff --git a/Sources/NIOPosix/Thread.swift b/Sources/NIOPosix/Thread.swift index 565b775ef..ab5afb979 100644 --- a/Sources/NIOPosix/Thread.swift +++ b/Sources/NIOPosix/Thread.swift @@ -21,7 +21,7 @@ enum LowLevelThreadOperations { } protocol ThreadOps { - associatedtype ThreadHandle + associatedtype ThreadHandle: Sendable associatedtype ThreadSpecificKey associatedtype ThreadSpecificKeyDestructor @@ -41,7 +41,7 @@ protocol ThreadOps { /// /// All methods exposed are thread-safe. @usableFromInline -final class NIOThread { +final class NIOThread: Sendable { internal typealias ThreadBoxValue = (body: (NIOThread) -> Void, name: String?) internal typealias ThreadBox = Box diff --git a/Sources/NIOPosix/ThreadPosix.swift b/Sources/NIOPosix/ThreadPosix.swift index f876c42c8..9da877516 100644 --- a/Sources/NIOPosix/ThreadPosix.swift +++ b/Sources/NIOPosix/ThreadPosix.swift @@ -74,8 +74,27 @@ private func sysPthread_create( typealias ThreadOpsSystem = ThreadOpsPosix +struct PthreadWrapper: @unchecked Sendable { + var handle: pthread_t +} + +extension Optional where Wrapped == PthreadWrapper { + mutating func withHandlePointer< + ReturnValue + >( + _ body: (UnsafeMutablePointer) throws -> ReturnValue + ) rethrows -> ReturnValue { + var handle = self?.handle + defer { + self = handle.map { PthreadWrapper(handle: $0) } + } + + return try body(&handle) + } +} + enum ThreadOpsPosix: ThreadOps { - typealias ThreadHandle = pthread_t + typealias ThreadHandle = PthreadWrapper typealias ThreadSpecificKey = pthread_key_t #if canImport(Darwin) typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer) -> Void @@ -89,7 +108,7 @@ enum ThreadOpsPosix: ThreadOps { // anyway. var chars: [CChar] = Array(repeating: 0, count: 64) return chars.withUnsafeMutableBufferPointer { ptr in - guard sys_pthread_getname_np(thread, ptr.baseAddress!, ptr.count) == 0 else { + guard sys_pthread_getname_np(thread.handle, ptr.baseAddress!, ptr.count) == 0 else { return nil } @@ -105,60 +124,61 @@ enum ThreadOpsPosix: ThreadOps { detachThread: Bool ) { let argv0 = Unmanaged.passRetained(args).toOpaque() - let res = sysPthread_create( - handle: &handle, - destructor: { - // Cast to UnsafeMutableRawPointer? and force unwrap to make the - // same code work on macOS and Linux. - let boxed = Unmanaged - .fromOpaque(($0 as UnsafeMutableRawPointer?)!) - .takeRetainedValue() - let (body, name) = (boxed.value.body, boxed.value.name) - let hThread: ThreadOpsSystem.ThreadHandle = pthread_self() + let res = handle.withHandlePointer { handlePtr in + sysPthread_create( + handle: handlePtr, + destructor: { + // Cast to UnsafeMutableRawPointer? and force unwrap to make the + // same code work on macOS and Linux. + let boxed = Unmanaged + .fromOpaque(($0 as UnsafeMutableRawPointer?)!) + .takeRetainedValue() + let (body, name) = (boxed.value.body, boxed.value.name) + let hThread: ThreadOpsSystem.ThreadHandle = PthreadWrapper(handle: pthread_self()) - if let name = name { - let maximumThreadNameLength: Int - #if os(Linux) || os(Android) - maximumThreadNameLength = 15 - #else - maximumThreadNameLength = .max - #endif - name.prefix(maximumThreadNameLength).withCString { namePtr in - // this is non-critical so we ignore the result here, we've seen - // EPERM in containers. - _ = sys_pthread_setname_np(hThread, namePtr) + if let name = name { + let maximumThreadNameLength: Int + #if os(Linux) || os(Android) + maximumThreadNameLength = 15 + #else + maximumThreadNameLength = .max + #endif + name.prefix(maximumThreadNameLength).withCString { namePtr in + // this is non-critical so we ignore the result here, we've seen + // EPERM in containers. + _ = sys_pthread_setname_np(hThread.handle, namePtr) + } } - } - body(NIOThread(handle: hThread, desiredName: name)) + body(NIOThread(handle: hThread, desiredName: name)) - #if os(Android) - return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! - #else - return nil - #endif - }, - args: argv0 - ) + #if os(Android) + return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! + #else + return nil + #endif + }, + args: argv0 + ) + } precondition(res == 0, "Unable to create thread: \(res)") if detachThread { - let detachError = pthread_detach(handle!) + let detachError = pthread_detach(handle!.handle) precondition(detachError == 0, "pthread_detach failed with error \(detachError)") } - } static func isCurrentThread(_ thread: ThreadOpsSystem.ThreadHandle) -> Bool { - pthread_equal(thread, pthread_self()) != 0 + pthread_equal(thread.handle, pthread_self()) != 0 } static var currentThread: ThreadOpsSystem.ThreadHandle { - pthread_self() + PthreadWrapper(handle: pthread_self()) } static func joinThread(_ thread: ThreadOpsSystem.ThreadHandle) { - let err = pthread_join(thread, nil) + let err = pthread_join(thread.handle, nil) assert(err == 0, "pthread_join failed with \(err)") } @@ -184,7 +204,7 @@ enum ThreadOpsPosix: ThreadOps { } static func compareThreads(_ lhs: ThreadOpsSystem.ThreadHandle, _ rhs: ThreadOpsSystem.ThreadHandle) -> Bool { - pthread_equal(lhs, rhs) != 0 + pthread_equal(lhs.handle, rhs.handle) != 0 } } From 6d57d047688bcc182cc8221369f7cd24b13a927d Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 08:49:29 +0000 Subject: [PATCH 66/93] Make NonBlockingFileIO strict-concurrency clean (#3082) ### Motivation: NonBlockingFileIO is now mostly in a good state, but there are some missed Sendable annotations. Let's clean that up. ### Modifications: Mark an inner function as `@Sendable` Add `Sendable` to `NIODirectoryEntry`. ### Result: The road continues --- Sources/NIOPosix/NonBlockingFileIO.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/NIOPosix/NonBlockingFileIO.swift b/Sources/NIOPosix/NonBlockingFileIO.swift index 7b8c9a823..b8218e040 100644 --- a/Sources/NIOPosix/NonBlockingFileIO.swift +++ b/Sources/NIOPosix/NonBlockingFileIO.swift @@ -205,6 +205,7 @@ public struct NonBlockingFileIO: Sendable { let promise = eventLoop.makePromise(of: Void.self) + @Sendable func _read(remainingReads: Int, bytesReadSoFar: Int64) { if remainingReads > 1 || (remainingReads == 1 && lastReadSize > 0) { let readSize = remainingReads > 1 ? chunkSize : lastReadSize @@ -843,7 +844,7 @@ public struct NonBlockingFileIO: Sendable { #if !os(Windows) /// A `NIODirectoryEntry` represents a single directory entry. -public struct NIODirectoryEntry: Hashable { +public struct NIODirectoryEntry: Hashable, Sendable { // File number of entry public var ino: UInt64 // File type From 171a93af3c668d8d143651975c2136f7792d3351 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 10:16:10 +0000 Subject: [PATCH 67/93] Sendability clean up for RawSocketBootstrap (#3083) Motivation RawSocketBootstrap isn't strict concurrency clean yet, and it should be. Modifications Add a few necessary Sendable constraints. Result No warnings here boss. --- Sources/NIOPosix/RawSocketBootstrap.swift | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Sources/NIOPosix/RawSocketBootstrap.swift b/Sources/NIOPosix/RawSocketBootstrap.swift index 72aec18cc..3389bb080 100644 --- a/Sources/NIOPosix/RawSocketBootstrap.swift +++ b/Sources/NIOPosix/RawSocketBootstrap.swift @@ -169,10 +169,10 @@ public final class NIORawSocketBootstrap { private func withNewChannel( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, - _ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture + _ bringup: @escaping @Sendable (EventLoop, DatagramChannel) -> EventLoopFuture ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } + let channelInitializer = self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) } let channelOptions = self._channelOptions let channel: DatagramChannel @@ -182,6 +182,7 @@ public final class NIORawSocketBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { @@ -255,7 +256,7 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func connect0( + private func connect0( host: String, ipProtocol: NIOIPProtocol, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -287,7 +288,7 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func bind0( + private func bind0( host: String, ipProtocol: NIOIPProtocol, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -320,7 +321,10 @@ extension NIORawSocketBootstrap { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - private func makeConfiguredChannel( + private func makeConfiguredChannel< + ChannelInitializerResult: Sendable, + PostRegistrationTransformationResult: Sendable + >( makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, registration: @escaping @Sendable (Channel) -> EventLoopFuture, @@ -329,9 +333,9 @@ extension NIORawSocketBootstrap { > ) -> EventLoopFuture { let eventLoop = self.group.next() - let channelInitializer = { (channel: Channel) -> EventLoopFuture in - let initializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } - return initializer(channel).flatMap { channelInitializer(channel) } + let bootstrapInitializer = self.channelInitializer ?? { @Sendable _ in eventLoop.makeSucceededFuture(()) } + let channelInitializer = { @Sendable (channel: Channel) -> EventLoopFuture in + bootstrapInitializer(channel).flatMap { channelInitializer(channel) } } let channelOptions = self._channelOptions @@ -342,6 +346,7 @@ extension NIORawSocketBootstrap { return eventLoop.makeFailedFuture(error) } + @Sendable func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { From 5ce7fde1df5fdca1d9de08febe8260c6ac08b64a Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 11:42:40 +0000 Subject: [PATCH 68/93] Strict concurrency for SelectableEventLoop & MTELG (#3084) Motivation SelectableEventLoop and MTEL are our major entry points for execution. These need to be strict concurrency clean. Unfortunately, changes in one tend to ripple into the other, so we need to tackle both at once. Modifications - A few closures get annotated @Sendable - Add a NIOLockedValueBox to convince the compiler that this use is safe. - Make a few types explicitly not Sendable Result No concurrency warnings in MTELG and SelectableEventLoop. --- .../MultiThreadedEventLoopGroup.swift | 25 +++++++++++++------ Sources/NIOPosix/SelectableEventLoop.swift | 13 ++++++++-- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index 0361e1a19..e6418d891 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -40,6 +40,9 @@ struct NIORegistration: Registration { var registrationID: SelectorRegistrationID } +@available(*, unavailable) +extension NIORegistration: Sendable {} + private let nextEventLoopGroupID = ManagedAtomic(0) /// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it. @@ -391,7 +394,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { return } - var result: Result = .success(()) + let result: NIOLockedValueBox> = NIOLockedValueBox(.success(())) for loop in self.eventLoops { g.enter() @@ -400,7 +403,9 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { case .success: () case .failure(let error): - result = .failure(error) + result.withLockedValue { + $0 = .failure(error) + } } g.leave() } @@ -418,14 +423,14 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { "MultiThreadedEventLoopGroup in illegal state when closing: \(self.runState)" ) case .closing(let callbacks): - let overallError: Error? = { - switch result { + let overallError: Error? = result.withLockedValue { + switch $0 { case .success: return nil case .failure(let error): return error } - }() + } self.runState = .closed(overallError) return (overallError, callbacks) } @@ -490,9 +495,9 @@ extension MultiThreadedEventLoopGroup: CustomStringConvertible { } @usableFromInline -struct ErasedUnownedJob { +struct ErasedUnownedJob: Sendable { @usableFromInline - let erasedJob: Any + let erasedJob: any Sendable @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) init(job: UnownedJob) { @@ -567,6 +572,12 @@ extension ScheduledTask: Comparable { } } +@available(*, unavailable) +extension ScheduledTask: Sendable {} + +@available(*, unavailable) +extension ScheduledTask.Kind: Sendable {} + extension NIODeadline { @inlinable func readyIn(_ target: NIODeadline) -> TimeAmount { diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 7bb3c9e0a..a30a0a58d 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -869,7 +869,10 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { self._succeededVoidFuture = nil } - internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result) -> Void) { + internal func initiateClose( + queue: DispatchQueue, + completionHandler: @escaping @Sendable (Result) -> Void + ) { func doClose() { self.assertInEventLoop() self._parentGroup = nil // break the cycle @@ -948,7 +951,7 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { } @usableFromInline - func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping @Sendable (Error?) -> Void) { if self.canBeShutdownIndividually { self.initiateClose(queue: queue) { result in self.syncFinaliseClose(joinThread: false) // This thread was taken over by somebody else @@ -1012,12 +1015,18 @@ enum UnderlyingTask { case callback(any NIOScheduledCallbackHandler) } +@available(*, unavailable) +extension UnderlyingTask: Sendable {} + @usableFromInline internal enum LoopTask { case scheduled(ScheduledTask) case immediate(UnderlyingTask) } +@available(*, unavailable) +extension LoopTask: Sendable {} + @inlinable internal func assertExpression(_ body: () -> Bool) { assert( From 5a572f587c256d97e5b49ee55a3730ce3a83188d Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 13:45:24 +0000 Subject: [PATCH 69/93] Add Sendable annotations to SelectorGeneric (#3085) ### Motivation: Explicit Sendable requires a bunch of annotations in SelectorGeneric, as many of these types are `@usableFromInline`. This patch applies those. ### Modifications: - Make many types Sendable - Make some explicitly not Sendable ### Result: No missing Sendable warnings --- Sources/NIOPosix/SelectorGeneric.swift | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Sources/NIOPosix/SelectorGeneric.swift b/Sources/NIOPosix/SelectorGeneric.swift index cb2626c76..e2f7197fa 100644 --- a/Sources/NIOPosix/SelectorGeneric.swift +++ b/Sources/NIOPosix/SelectorGeneric.swift @@ -20,7 +20,7 @@ import CNIOLinux #endif @usableFromInline -internal enum SelectorLifecycleState { +internal enum SelectorLifecycleState: Sendable { case open case closing case closed @@ -60,7 +60,7 @@ extension timespec { /// If then suddenly the socket becomes both readable and writable, the eventing mechanism will tell you about that /// fact using `[.read, .write]`. @usableFromInline -struct SelectorEventSet: OptionSet, Equatable { +struct SelectorEventSet: OptionSet, Equatable, Sendable { @usableFromInline typealias RawValue = UInt8 @@ -404,6 +404,9 @@ extension Selector: CustomStringConvertible { } } +@available(*, unavailable) +extension Selector: Sendable {} + /// An event that is triggered once the `Selector` was able to select something. @usableFromInline struct SelectorEvent { @@ -422,6 +425,9 @@ struct SelectorEvent { } } +@available(*, unavailable) +extension SelectorEvent: Sendable {} + extension Selector where R == NIORegistration { /// Gently close the `Selector` after all registered `Channel`s are closed. func closeGently(eventLoop: EventLoop) -> EventLoopFuture { @@ -473,7 +479,7 @@ extension Selector where R == NIORegistration { /// The strategy used for the `Selector`. @usableFromInline -enum SelectorStrategy { +enum SelectorStrategy: Sendable { /// Block until there is some IO ready to be processed or the `Selector` is explicitly woken up. case block @@ -489,7 +495,7 @@ enum SelectorStrategy { /// to mark events to allow for filtering of received return values to not be delivered to a /// new `Registration` instance that receives the same file descriptor. Ok if it wraps. /// Needed for i.e. testWeDoNotDeliverEventsForPreviouslyClosedChannels to succeed. -@usableFromInline struct SelectorRegistrationID: Hashable { +@usableFromInline struct SelectorRegistrationID: Hashable, Sendable { @usableFromInline var _rawValue: UInt32 @inlinable var rawValue: UInt32 { From ce5d042a3326cfa109313457135b4e32053bfbf3 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 14:10:43 +0000 Subject: [PATCH 70/93] Remove accidental static var (#3086) This was never written to, so we don't need it, and it's a Sendable violation. --- Sources/NIOPosix/Socket.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/NIOPosix/Socket.swift b/Sources/NIOPosix/Socket.swift index b8434d62e..6ae3de3c5 100644 --- a/Sources/NIOPosix/Socket.swift +++ b/Sources/NIOPosix/Socket.swift @@ -23,7 +23,7 @@ class Socket: BaseSocket, SocketProtocol { typealias SocketType = Socket /// The maximum number of bytes to write per `writev` call. - static var writevLimitBytes = Int(Int32.max) + static let writevLimitBytes = Int(Int32.max) /// The maximum number of `IOVector`s to write per `writev` call. static let writevLimitIOVectors: Int = Posix.UIO_MAXIOV From 407e633005aa93e5bcc27e0c226e6177d1c56e71 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 14:45:12 +0000 Subject: [PATCH 71/93] Add simple Sendable conformance to AsyncSequenceFromIterator (#3088) usableFromInline types need explicit Sendable conformances, so let's add one here. This type is a trivial wrapper, so let's express that --- Sources/NIOCore/AsyncAwaitSupport.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index 5152728c0..f5bc2af6f 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -423,6 +423,9 @@ struct AsyncSequenceFromIterator: AsyncSeq } } +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension AsyncSequenceFromIterator: Sendable where AsyncIterator: Sendable {} + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension EventLoop { @preconcurrency From c2ccad63e2c8ca6b7daf520bf6465fd1a1f31264 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 15:10:20 +0000 Subject: [PATCH 72/93] Add Sendable annotations to the syscall wrappers (#3087) Motivation Unfortunately there are a few places where we have to help the compiler out to realise that our copies of the libc functions are also Sendable, and -require-explicit-sendable can cause us some trouble if we don't annotate our usableFromInline types. Modifications Annotate our usableFromInline types Add some @Sendable Results The march continues --- Sources/NIOPosix/System.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/NIOPosix/System.swift b/Sources/NIOPosix/System.swift index c221bd40d..b320f20ce 100644 --- a/Sources/NIOPosix/System.swift +++ b/Sources/NIOPosix/System.swift @@ -86,15 +86,17 @@ let S_IFBLK = UInt32(SwiftGlibc.S_IFBLK) private let sysClose = close private let sysShutdown = shutdown private let sysBind = bind -private let sysFcntl: (CInt, CInt, CInt) -> CInt = fcntl +private let sysFcntl: @Sendable @convention(c) (CInt, CInt, CInt) -> CInt = { fcntl($0, $1, $2) } private let sysSocket = socket private let sysSetsockopt = setsockopt private let sysGetsockopt = getsockopt private let sysListen = listen private let sysAccept = accept private let sysConnect = connect -private let sysOpen: (UnsafePointer, CInt) -> CInt = open -private let sysOpenWithMode: (UnsafePointer, CInt, mode_t) -> CInt = open +private let sysOpen: @Sendable @convention(c) (UnsafePointer, CInt) -> CInt = { open($0, $1) } +private let sysOpenWithMode: @Sendable @convention(c) (UnsafePointer, CInt, mode_t) -> CInt = { + open($0, $1, $2) +} private let sysFtruncate = ftruncate private let sysWrite = write private let sysPwrite = pwrite @@ -444,7 +446,7 @@ internal func syscallForbiddingEINVAL( } @usableFromInline -internal enum Posix { +internal enum Posix: Sendable { #if canImport(Darwin) @usableFromInline static let UIO_MAXIOV: Int = 1024 @@ -1059,7 +1061,7 @@ extension Posix { #if canImport(Darwin) @usableFromInline -internal enum KQueue { +internal enum KQueue: Sendable { // TODO: Figure out how to specify a typealias to the kevent struct without run into trouble with the swift compiler From 85742bc5592ec83289ad1803a8cd68c46d167abc Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 24 Jan 2025 16:33:17 +0000 Subject: [PATCH 73/93] Avoid using stderr explicitly (#3089) Motivation It's tempting for us to use the FILE * for stderr whenever we want to print to it. However, the Linux libc modules aren't appropriately annotated to call that field constant, and indeed it isn't. This causes Swift to throw a fit if we even touch it. Modifications Introduce an awkward function that issues direct writes to stderr instead of using the FILE *. Result Swift is happier. --- Sources/NIOPosix/SelectableEventLoop.swift | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index a30a0a58d..16d5c5c9e 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -19,6 +19,22 @@ import NIOConcurrencyHelpers import NIOCore import _NIODataStructures +private func printError(_ string: StaticString) { + string.withUTF8Buffer { buf in + var buf = buf + while buf.count > 0 { + // 2 is stderr + let rc = write(2, buf.baseAddress, buf.count) + if rc < 0 { + let err = errno + if err == EINTR { continue } + fatalError("Unexpected error writing: \(err)") + } + buf = .init(rebasing: buf.dropFirst(Int(rc))) + } + } +} + /// Execute the given closure and ensure we release all auto pools if needed. @inlinable internal func withAutoReleasePool(_ execute: () throws -> T) rethrows -> T { @@ -438,12 +454,11 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { if Self.strictModeEnabled { fatalError("Cannot schedule tasks on an EventLoop that has already shut down.") } - fputs( + printError( """ ERROR: Cannot schedule tasks on an EventLoop that has already shut down. \ This will be upgraded to a forced crash in future SwiftNIO versions.\n - """, - stderr + """ ) return false } From 26d3fb909799d91ed95413fbfe764a274c005939 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 27 Jan 2025 08:11:08 +0000 Subject: [PATCH 74/93] Make NIOPosix strict-concurrency clean (#3090) Motivation NIOPosix should be clean under strict concurrency Modifications - Fix newly-added issue in GetaddrinfoResolver - Fix newly-added issue in SEL - Lock in the win in Package.swift Result We did it! --- Package.swift | 3 ++- Sources/NIOPosix/GetaddrinfoResolver.swift | 2 +- Sources/NIOPosix/SelectableEventLoop.swift | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index 14f9183f9..34dec3fd5 100644 --- a/Package.swift +++ b/Package.swift @@ -120,7 +120,8 @@ let package = Package( swiftAtomics, ], exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"], - resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [] + resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [], + swiftSettings: strictConcurrencySettings ), .target( name: "NIO", diff --git a/Sources/NIOPosix/GetaddrinfoResolver.swift b/Sources/NIOPosix/GetaddrinfoResolver.swift index 3ec44ec6f..bab810949 100644 --- a/Sources/NIOPosix/GetaddrinfoResolver.swift +++ b/Sources/NIOPosix/GetaddrinfoResolver.swift @@ -217,7 +217,7 @@ internal final class GetaddrinfoResolver: Resolver, Sendable { // Ensure that both futures are succeeded in the same tick // to avoid racing and potentially leaking a promise - self.loop.execute { + self.loop.execute { [v4Results, v6Results] in self.v6Future.succeed(v6Results) self.v4Future.succeed(v4Results) } diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index 16d5c5c9e..bfad156e7 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -351,7 +351,7 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), { do { - promise.succeed(try task()) + promise.assumeIsolatedUnsafeUnchecked().succeed(try task()) } catch let err { promise.fail(err) } From 1e900b4736a5bf76c16eabf7808548c90c0f14e1 Mon Sep 17 00:00:00 2001 From: Natik Gadzhi Date: Mon, 27 Jan 2025 00:45:46 -0800 Subject: [PATCH 75/93] `NIOFileSystem`: Try ${TMPDIR} first for temporary directory (#3067) ### Motivation: This PR aligns what temp directory NIOFileSystem will return first: - First try `${TMPDIR}` as it's an expressed user preference - On Darwin, try `_CS_DARWIN_USER_TMP_DIR` next. If it's set, return that. - Finally, fall back on `/tmp` on Darwin and Linux, and `/data/local/tmp` on Android. Closes #2861. ### Modifications: - Reworks `NIOFileSystem.temporaryDirectory`. ### Result: - NIOFileSystem will now try `${TMPDIR}` first for the temporary directory. ### Caveats: - We might want to align how Swift-NIO and FoundationEssentials resolve temp directory, and [FoundationEssentials have a different approach](https://github.com/swiftlang/swift-foundation/blob/9d57f36de757b3d5e3a2f7ffcf27aaec3033509f/Sources/FoundationEssentials/String/String%2BPath.swift#L484-L533). But, I agree with [this comment](https://github.com/apple/swift-nio/issues/2861#issuecomment-2327010713), it feels like TMPDIR is an expected default. --------- Co-authored-by: Cory Benfield Co-authored-by: George Barnett --- Sources/NIOFileSystem/FileSystem.swift | 36 ++++++++++--------- .../FileSystemTests.swift | 8 +++++ 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/Sources/NIOFileSystem/FileSystem.swift b/Sources/NIOFileSystem/FileSystem.swift index 834994925..b6af73fd5 100644 --- a/Sources/NIOFileSystem/FileSystem.swift +++ b/Sources/NIOFileSystem/FileSystem.swift @@ -636,31 +636,35 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// #### Implementation details /// - /// On Darwin this function uses `confstr(3)` and gets the value of `_CS_DARWIN_USER_TEMP_DIR`; - /// the users temporary directory. Typically items are removed after three days if they are not - /// accessed. - /// - /// On Linux this returns "/tmp". + /// On all platforms, this function first attempts to read the `TMPDIR` environment variable and returns that path, omitting trailing slashes. + /// If that fails: + /// - On Darwin this function uses `confstr(3)` and gets the value of `_CS_DARWIN_USER_TEMP_DIR`; + /// the users temporary directory. Typically items are removed after three days if they are not + /// accessed. + /// - On Android this returns "/data/local/tmp". + /// - On other platforms this returns "/tmp". /// /// - Returns: The path to a temporary directory. public var temporaryDirectory: FilePath { get async throws { + if let tmpdir = getenv("TMPDIR") { + return FilePath(String(cString: tmpdir)) + } + #if canImport(Darwin) return try await self.threadPool.runIfActive { - try Libc.constr(_CS_DARWIN_USER_TEMP_DIR).map { path in - FilePath(path) - }.mapError { errno in - FileSystemError.confstr( - name: "_CS_DARWIN_USER_TEMP_DIR", - errno: errno, - location: .here() - ) - }.get() + let result = Libc.constr(_CS_DARWIN_USER_TEMP_DIR) + switch result { + case .success(let path): + return FilePath(path) + case .failure(_): + return FilePath("/tmp") + } } #elseif os(Android) - return "/data/local/tmp" + return FilePath("/data/local/tmp") #else - return "/tmp" + return FilePath("/tmp") #endif } } diff --git a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index e262147fa..d0f5194db 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -1681,6 +1681,14 @@ extension FileSystemTests { XCTAssertGreaterThan(info.size, 0) } + func testTemporaryDirectoryRespectsEnvironment() async throws { + if let envTmpDir = getenv("TMPDIR") { + let envTmpDirString = String(cString: envTmpDir) + let fsTempDirectory = try await fs.temporaryDirectory + XCTAssertEqual(fsTempDirectory, FilePath(envTmpDirString)) + } + } + func testReadChunksRange() async throws { try await self.fs.withFileHandle(forReadingAt: FilePath(#filePath)) { handle in let info = try await handle.info() From dff45738d84a53dbc8ee899c306b3a7227f54f89 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 28 Jan 2025 20:38:50 +0000 Subject: [PATCH 76/93] undo Xcode 13 GM workaround (#3092) ### Motivation: Xcode 13 is really quite old (3 major releases and it was the GM release anyway) and this workaround can cause other issues. ### Modifications: - Remove the Xcode 13 GM workaround. - ### Result: Better, possibly faster code. --- Sources/NIOCore/ByteBuffer-core.swift | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Sources/NIOCore/ByteBuffer-core.swift b/Sources/NIOCore/ByteBuffer-core.swift index 812a8cc38..cc53d97f7 100644 --- a/Sources/NIOCore/ByteBuffer-core.swift +++ b/Sources/NIOCore/ByteBuffer-core.swift @@ -31,11 +31,10 @@ import WASILibc @usableFromInline let sysMalloc: @convention(c) (size_t) -> UnsafeMutableRawPointer? = malloc @usableFromInline let sysRealloc: @convention(c) (UnsafeMutableRawPointer?, size_t) -> UnsafeMutableRawPointer? = realloc - -/// Xcode 13 GM shipped with a bug in the SDK that caused `free`'s first argument to be annotated as -/// non-nullable. To that end, we define a thunk through to `free` that matches that constraint, as we -/// never pass a `nil` pointer to it. -@usableFromInline let sysFree: @convention(c) (UnsafeMutableRawPointer) -> Void = { free($0) } +@inlinable +func sysFree(_ ptr: UnsafeMutableRawPointer) { + free(ptr) +} extension _ByteBufferSlice: Equatable {} From 577e893f7e45d854602cf873170f5895c0a92455 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Fri, 31 Jan 2025 13:17:51 +0000 Subject: [PATCH 77/93] Update the legacy CI matrix for 6.1 nightly (#3094) ### Motivation: Some repositories still use the older CI Swift matrix directly so we need to update it to handle 6.1 nightlies. ### Modifications: Replace 6.0 nightly with 6.1 nightly. ### Result: External CI should use 6.1 nightly. --- .github/workflows/swift_matrix.yml | 44 +++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/.github/workflows/swift_matrix.yml b/.github/workflows/swift_matrix.yml index 4c4734cbb..6d501bb6e 100644 --- a/.github/workflows/swift_matrix.yml +++ b/.github/workflows/swift_matrix.yml @@ -46,15 +46,26 @@ on: description: "The command of the 6.0 Swift version linux matrix job to execute." matrix_linux_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." default: true matrix_linux_nightly_6_0_container_image: type: string - description: "Container image for the nightly 6.0 Swift version matrix job. Defaults to matching Swift Ubuntu image." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." default: "swiftlang/swift:nightly-6.0-jammy" matrix_linux_nightly_6_0_command_override: type: string - description: "The command of the nightly 6.0 Swift version linux matrix job to execute." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + matrix_linux_nightly_6_1_enabled: + type: boolean + description: "Boolean to enable the nightly 6.1 Swift version matrix job. Defaults to true." + default: true + matrix_linux_nightly_6_1_container_image: + type: string + description: "Container image for the nightly 6.1 Swift version matrix job. Defaults to matching Swift Ubuntu image." + default: "swiftlang/swift:nightly-6.1-jammy" + matrix_linux_nightly_6_1_command_override: + type: string + description: "The command of the nightly 6.1 Swift version linux matrix job to execute." matrix_linux_nightly_main_enabled: type: boolean description: "Boolean to enable the nightly main Swift version matrix job. Defaults to true." @@ -80,11 +91,18 @@ on: description: "The command of the 6.0 Swift version windows matrix job to execute." matrix_windows_nightly_6_0_enabled: type: boolean - description: "Boolean to enable the nightly 6.0 Swift version matrix job. Defaults to true." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." default: false matrix_windows_nightly_6_0_command_override: type: string - description: "The command of the nightly 6.0 Swift version windows matrix job to execute." + description: "⚠️ Deprecated, we no longer run against 6.0 nightly." + matrix_windows_nightly_6_1_enabled: + type: boolean + description: "Boolean to enable the nightly 6.1 Swift version matrix job. Defaults to true." + default: false + matrix_windows_nightly_6_1_command_override: + type: string + description: "The command of the nightly 6.1 Swift version windows matrix job to execute." matrix_windows_nightly_main_enabled: type: boolean description: "Boolean to enable the nightly main Swift version matrix job. Defaults to true." @@ -116,9 +134,9 @@ jobs: - image: ${{ inputs.matrix_linux_6_0_container_image }} swift_version: "6.0" enabled: ${{ inputs.matrix_linux_6_0_enabled }} - - image: ${{ inputs.matrix_linux_nightly_6_0_container_image }} - swift_version: "nightly-6.0" - enabled: ${{ inputs.matrix_linux_nightly_6_0_enabled }} + - image: ${{ inputs.matrix_linux_nightly_6_1_container_image }} + swift_version: "nightly-6.1" + enabled: ${{ inputs.matrix_linux_nightly_6_1_enabled }} - image: ${{ inputs.matrix_linux_nightly_main_container_image }} swift_version: "nightly-main" enabled: ${{ inputs.matrix_linux_nightly_main_enabled }} @@ -143,7 +161,7 @@ jobs: COMMAND_OVERRIDE_5_9: ${{ inputs.matrix_linux_5_9_command_override }} COMMAND_OVERRIDE_5_10: ${{ inputs.matrix_linux_5_10_command_override }} COMMAND_OVERRIDE_6_0: ${{ inputs.matrix_linux_6_0_command_override }} - COMMAND_OVERRIDE_NIGHTLY_6_0: ${{ inputs.matrix_linux_nightly_6_0_command_override }} + COMMAND_OVERRIDE_NIGHTLY_6_1: ${{ inputs.matrix_linux_nightly_6_1_command_override }} COMMAND_OVERRIDE_NIGHTLY_MAIN: ${{ inputs.matrix_linux_nightly_main_command_override }} run: | apt-get -qq update && apt-get -qq -y install curl @@ -185,9 +203,9 @@ jobs: matrix: # We are specifying only the major and minor of the docker images to automatically pick up the latest patch release swift: - - image: swiftlang/swift:nightly-6.0-windowsservercore-1809 - swift_version: "nightly-6.0" - enabled: ${{ inputs.matrix_windows_nightly_6_0_enabled }} + - image: swiftlang/swift:nightly-6.1-windowsservercore-1809 + swift_version: "nightly-6.1" + enabled: ${{ inputs.matrix_windows_nightly_6_1_enabled }} - image: swiftlang/swift:nightly-main-windowsservercore-1809 swift_version: "nightly-main" enabled: ${{ inputs.matrix_windows_nightly_main_enabled }} @@ -207,4 +225,4 @@ jobs: - name: Run matrix job if: ${{ matrix.swift.enabled }} run: | - docker run --env SWIFT_VERSION="${{ matrix.swift.swift_version }}" --env COMMAND="${{ inputs.matrix_windows_command }}" --env COMMAND_OVERRIDE_NIGHTLY_6_0="${{ inputs.matrix_windows_nightly_6_0_command_override }}" --env COMMAND_OVERRIDE_NIGHTLY_MAIN="${{ inputs.matrix_windows_nightly_main_command_override }}" -v ${{ github.workspace }}:C:\source ${{ matrix.swift.image }} cmd /s /c "swift --version & cd C:\source\ & powershell -File __check-matrix-job.ps1" + docker run --env SWIFT_VERSION="${{ matrix.swift.swift_version }}" --env COMMAND="${{ inputs.matrix_windows_command }}" --env COMMAND_OVERRIDE_NIGHTLY_6_1="${{ inputs.matrix_windows_nightly_6_1_command_override }}" --env COMMAND_OVERRIDE_NIGHTLY_MAIN="${{ inputs.matrix_windows_nightly_main_command_override }}" -v ${{ github.workspace }}:C:\source ${{ matrix.swift.image }} cmd /s /c "swift --version & cd C:\source\ & powershell -File __check-matrix-job.ps1" From 4ea59742f0ce8cced3ffea86ec79c5f578fc6517 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 10:22:07 +0000 Subject: [PATCH 78/93] Opt _NIOConcurrency into Strict Concurrency (#3095) Motivation: We intend to have this package be completely strict-concurrency clean, so every target needs to be opted in, even those that currently have no code. Modifications: Opt in this empty target to strict concurrency. Result: One more database entry. --- Package.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 34dec3fd5..9c9008210 100644 --- a/Package.swift +++ b/Package.swift @@ -136,7 +136,8 @@ let package = Package( dependencies: [ .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", - ] + ], + swiftSettings: strictConcurrencySettings ), .target( name: "NIOFoundationCompat", From 29c920d3e642a61f5bc0d2bdfddf7597a9921749 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 10:51:09 +0000 Subject: [PATCH 79/93] Opt NIOFoundationCompat into strict concurrency (#3096) Motivation: I continue to grab the low-hanging fruit. This time I've opted a purely data-processing module into strict concurrency. Truly, I am the hero Gotham deserves. Modifications: Set some build flags. Result: Stricter concurrency. --- Package.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 9c9008210..74d00fc68 100644 --- a/Package.swift +++ b/Package.swift @@ -144,7 +144,8 @@ let package = Package( dependencies: [ .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", - ] + ], + swiftSettings: strictConcurrencySettings ), .target( name: "CNIOAtomics", From a849d50ce633e92a954c5d5c50ab727cb8faecb9 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 11:25:02 +0000 Subject: [PATCH 80/93] Opt NIO module into Strict Concurrency (#3097) Motivation: Honestly these little modules are pretty mechanical now. Modifications: Add the strict concurrency flags to a module with nothing in it. Result: Become even more automatic from way downtown. --- Package.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 74d00fc68..a68614687 100644 --- a/Package.swift +++ b/Package.swift @@ -129,7 +129,8 @@ let package = Package( "NIOCore", "NIOEmbedded", "NIOPosix", - ] + ], + swiftSettings: strictConcurrencySettings ), .target( name: "_NIOConcurrency", From 8bf3316c377612594d0d88dae2c4541f845c003a Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 11:49:56 +0000 Subject: [PATCH 81/93] Clean up concurrency in NIOEchoClient (#3099) Motivation: We're getting to the examples now! This patch updates NIOEchoClient to be clean under strict concurrency. Modifications: Use the sync operations to add echo handler. Result: Another strict concurrency module. Co-authored-by: George Barnett --- Package.swift | 3 ++- Sources/NIOEchoClient/main.swift | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index a68614687..931bc2816 100644 --- a/Package.swift +++ b/Package.swift @@ -301,7 +301,8 @@ let package = Package( "NIOCore", "NIOConcurrencyHelpers", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOHTTP1Server", diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index d7de8eb35..e92ebc02f 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -58,7 +58,9 @@ let bootstrap = ClientBootstrap(group: group) // Enable SO_REUSEADDR. .channelOption(.socketOption(.so_reuseaddr), value: 1) .channelInitializer { channel in - channel.pipeline.addHandler(EchoHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(EchoHandler()) + } } defer { try! group.syncShutdownGracefully() From d273f906fe4819e74e45dc086425fd48ae8c1097 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 12:56:02 +0000 Subject: [PATCH 82/93] Add strict concurrency to NIOUDPEchoServer (#3101) Motivation: Another strict concurrency change, another echo handler. Modifications: Move to sync operations. Result: Another step on strict concurrency. --- Package.swift | 3 ++- Sources/NIOUDPEchoServer/main.swift | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index 931bc2816..863c3f401 100644 --- a/Package.swift +++ b/Package.swift @@ -375,7 +375,8 @@ let package = Package( "NIOPosix", "NIOCore", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOUDPEchoClient", diff --git a/Sources/NIOUDPEchoServer/main.swift b/Sources/NIOUDPEchoServer/main.swift index a33de6780..f8dd50857 100644 --- a/Sources/NIOUDPEchoServer/main.swift +++ b/Sources/NIOUDPEchoServer/main.swift @@ -47,8 +47,9 @@ var bootstrap = DatagramBootstrap(group: group) // Set the handlers that are applied to the bound channel .channelInitializer { channel in - // Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline. - channel.pipeline.addHandler(EchoHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(EchoHandler()) + } } defer { From aa360ab8e895d1f16160a5e7feca9b8d59224fd1 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 13:55:41 +0000 Subject: [PATCH 83/93] Lock in strict concurrency in NIOEchoServer (#3100) Motivation: Prior patches actually removed all the issues in NIOEchoServer, so let's bank the win. Modifications: Added strict concurrency checking to NIOEchoServer Result: More stricter. --- Package.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 863c3f401..585fd3471 100644 --- a/Package.swift +++ b/Package.swift @@ -292,7 +292,8 @@ let package = Package( "NIOCore", "NIOConcurrencyHelpers", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOEchoClient", From 9a181b3aae48f7297cb3636b2fce6d0e1cbf2c54 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 14:22:56 +0000 Subject: [PATCH 84/93] Update NIOUDPEchoClient for strict concurrency (#3102) Motivation: NIOUDPEchoClient should be strict concurrency clean. Modifications: Annotate one closure @Sendable to convince Swift it's ok. Result: Strict concurrency clean in NIOUDPEchoClient. --- Package.swift | 3 ++- Sources/NIOUDPEchoClient/main.swift | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index 585fd3471..7c7378bf7 100644 --- a/Package.swift +++ b/Package.swift @@ -385,7 +385,8 @@ let package = Package( "NIOPosix", "NIOCore", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOAsyncAwaitDemo", diff --git a/Sources/NIOUDPEchoClient/main.swift b/Sources/NIOUDPEchoClient/main.swift index 3a74de9d0..9d131b889 100644 --- a/Sources/NIOUDPEchoClient/main.swift +++ b/Sources/NIOUDPEchoClient/main.swift @@ -115,7 +115,7 @@ default: connectTarget = .ip(host: defaultHost, sendPort: defaultServerPort, listeningPort: defaultListeningPort) } -let remoteAddress = { () -> SocketAddress in +let remoteAddress = { @Sendable () -> SocketAddress in switch connectTarget { case .ip(let host, let sendPort, _): return try SocketAddress.makeAddressResolvingHost(host, port: sendPort) @@ -129,7 +129,9 @@ let bootstrap = DatagramBootstrap(group: group) // Enable SO_REUSEADDR. .channelOption(.socketOption(.so_reuseaddr), value: 1) .channelInitializer { channel in - channel.pipeline.addHandler(EchoHandler(remoteAddressInitializer: remoteAddress)) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(EchoHandler(remoteAddressInitializer: remoteAddress)) + } } defer { try! group.syncShutdownGracefully() From 0bc48ebbc574eca23c02af17886dc0e57a879876 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 15:20:45 +0000 Subject: [PATCH 85/93] Strict concurrency for TCP examples (#3103) Motivation: Two more examples with no changes required. Modifications: Lock in strict concurrency for NIOTCPEchoClient and NIOTCPEchoServer. Result: Even more stricter concurrencier. --- Package.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 7c7378bf7..96f4a3a07 100644 --- a/Package.swift +++ b/Package.swift @@ -275,7 +275,8 @@ let package = Package( "NIOPosix", "NIOCore", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOTCPEchoClient", @@ -283,7 +284,8 @@ let package = Package( "NIOPosix", "NIOCore", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOEchoServer", From 8f19d80751978af1448ab2dde781a7b8c2d5e877 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 16:04:40 +0000 Subject: [PATCH 86/93] Strict concurrency for the chat examples (#3104) Motivation: Our next suite of examples for strict concurrency are the chat ones. These are very similar to the rest: either no violation at all, or just a need to use the sync operations on pipeline setup. Modifications: - Use sync operations - Lock in strict concurrency checking Result: We continue our march. Co-authored-by: Rick Newton-Rogers --- Package.swift | 9 ++++++--- Sources/NIOChatClient/main.swift | 18 +++++------------- Sources/NIOMulticastChat/main.swift | 4 ++-- 3 files changed, 13 insertions(+), 18 deletions(-) diff --git a/Package.swift b/Package.swift index 96f4a3a07..fdccf7596 100644 --- a/Package.swift +++ b/Package.swift @@ -334,7 +334,8 @@ let package = Package( "NIOCore", "NIOConcurrencyHelpers", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOChatClient", @@ -343,7 +344,8 @@ let package = Package( "NIOCore", "NIOConcurrencyHelpers", ], - exclude: ["README.md"] + exclude: ["README.md"], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOWebSocketServer", @@ -370,7 +372,8 @@ let package = Package( dependencies: [ "NIOPosix", "NIOCore", - ] + ], + swiftSettings: strictConcurrencySettings ), .executableTarget( name: "NIOUDPEchoServer", diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index c41250e39..a350bf14b 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -18,19 +18,9 @@ private final class ChatHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer - private func printByte(_ byte: UInt8) { - #if os(Android) - print(Character(UnicodeScalar(byte)), terminator: "") - #else - fputc(Int32(byte), stdout) - #endif - } - public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = Self.unwrapInboundIn(data) - while let byte: UInt8 = buffer.readInteger() { - printByte(byte) - } + let buffer = Self.unwrapInboundIn(data) + print(String(buffer: buffer)) } public func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -47,7 +37,9 @@ let bootstrap = ClientBootstrap(group: group) // Enable SO_REUSEADDR. .channelOption(.socketOption(.so_reuseaddr), value: 1) .channelInitializer { channel in - channel.pipeline.addHandler(ChatHandler()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(ChatHandler()) + } } defer { try! group.syncShutdownGracefully() diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index 7d3298ee7..94316e5ec 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -72,8 +72,8 @@ let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) var datagramBootstrap = DatagramBootstrap(group: group) .channelOption(.socketOption(.so_reuseaddr), value: 1) .channelInitializer { channel in - channel.pipeline.addHandler(ChatMessageEncoder()).flatMap { - channel.pipeline.addHandler(ChatMessageDecoder()) + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandlers(ChatMessageEncoder(), ChatMessageDecoder()) } } From e2bfa2fc75665f716f48cb321554d4d06a3e9692 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 16:32:55 +0000 Subject: [PATCH 87/93] Strict concurrency enablement for some test targets (#3105) Motivation: A few more low-hanging-fruit test targets. Modifications: Enable strict concurrency for: - NIOFoundationCompatTests - NIOSingletonsTests Result: We're knocking down those targets, one by one. --- Package.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index fdccf7596..ea463d8ba 100644 --- a/Package.swift +++ b/Package.swift @@ -521,7 +521,8 @@ let package = Package( dependencies: [ "NIOCore", "NIOFoundationCompat", - ] + ], + swiftSettings: strictConcurrencySettings ), .testTarget( name: "NIOTests", @@ -529,7 +530,8 @@ let package = Package( ), .testTarget( name: "NIOSingletonsTests", - dependencies: ["NIOCore", "NIOPosix"] + dependencies: ["NIOCore", "NIOPosix"], + swiftSettings: strictConcurrencySettings ), .testTarget( name: "NIOFileSystemTests", From 2f1c7800e41cd4866bb25aeec704a699540cf663 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 16:57:45 +0000 Subject: [PATCH 88/93] Strict concurrency for NIOTests (#3106) Motivation: NIOTests was already warning free, now we're just going to make sure of it. Modifications: Enable strict concurrency for NIOTests Result: Our relentless safety march continues. --- Package.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index ea463d8ba..a4c9ee742 100644 --- a/Package.swift +++ b/Package.swift @@ -526,7 +526,8 @@ let package = Package( ), .testTarget( name: "NIOTests", - dependencies: ["NIO"] + dependencies: ["NIO"], + swiftSettings: strictConcurrencySettings ), .testTarget( name: "NIOSingletonsTests", From 08b3b4f95e0602e4fa9f9898a9d6204bf31a309b Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 3 Feb 2025 17:56:57 +0000 Subject: [PATCH 89/93] Make _NIOFileSystem strict concurrency compatible (#3098) Motivation: We're continuing out Strict Concurrency journey, making sure users of NIO can write data-race-free code. Modifications: - Added some missing Sendable annotations in NIOAsyncSequenceProducer - Made BufferedStream unconditionally Sendable, and required its Element type to also be Sendable. The prior constraint wasn't actually correct. We always behaved as though the element types were Sendable, by passing them into continuations. This cleans things up. - Made AnyAsyncSequence Sendable, which it needs to be. - Made BufferedOrAnyStream Sendable, which it needs to be. - Made DirectoryEntries explicitly Sendable, which it was. - Made DirectoryEntries.Batched explicitly Sendable. Result: Better concurrency-safety --- Package.swift | 2 +- .../AsyncSequences/NIOAsyncSequenceProducer.swift | 4 ++-- Sources/NIOFileSystem/DirectoryEntries.swift | 10 ++++++---- .../NIOFileSystem/Internal/BufferedOrAnyStream.swift | 10 +++++----- Sources/NIOFileSystem/Internal/BufferedStream.swift | 12 ++++++------ 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/Package.swift b/Package.swift index a4c9ee742..f88ea9746 100644 --- a/Package.swift +++ b/Package.swift @@ -247,7 +247,7 @@ let package = Package( path: "Sources/NIOFileSystem", exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"], resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [], - swiftSettings: [ + swiftSettings: strictConcurrencySettings + [ .define("ENABLE_MOCKING", .when(configuration: .debug)) ] ), diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift index e6484d846..acc3aff5e 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncSequenceProducer.swift @@ -105,7 +105,7 @@ public struct NIOAsyncSequenceProducer< /// to yield new elements to the sequence. /// 2. The ``sequence`` which is the actual `AsyncSequence` and /// should be passed to the consumer. - public struct NewSequence { + public struct NewSequence: Sendable { /// The source of the ``NIOAsyncSequenceProducer`` used to yield and finish. public let source: Source /// The actual sequence which should be passed to the consumer. @@ -268,7 +268,7 @@ extension NIOAsyncSequenceProducer { } /// The result of a call to ``NIOAsyncSequenceProducer/Source/yield(_:)``. - public enum YieldResult: Hashable { + public enum YieldResult: Hashable, Sendable { /// Indicates that the caller should produce more elements for now. The delegate's ``NIOAsyncSequenceProducerDelegate/produceMore()`` /// will **NOT** get called, since the demand was already signalled through this ``NIOAsyncSequenceProducer/Source/YieldResult``. case produceMore diff --git a/Sources/NIOFileSystem/DirectoryEntries.swift b/Sources/NIOFileSystem/DirectoryEntries.swift index 3830d94ab..1c0fa9d0b 100644 --- a/Sources/NIOFileSystem/DirectoryEntries.swift +++ b/Sources/NIOFileSystem/DirectoryEntries.swift @@ -21,7 +21,7 @@ import SystemPackage /// An `AsyncSequence` of entries in a directory. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -public struct DirectoryEntries: AsyncSequence { +public struct DirectoryEntries: AsyncSequence, Sendable { public typealias AsyncIterator = DirectoryIterator public typealias Element = DirectoryEntry @@ -35,7 +35,8 @@ public struct DirectoryEntries: AsyncSequence { /// Creates a ``DirectoryEntries`` sequence by wrapping an `AsyncSequence` of _batches_ of /// directory entries. - public init(wrapping sequence: S) where S.Element == Batched.Element { + @preconcurrency + public init(wrapping sequence: S) where S.Element == Batched.Element { self.batchedSequence = Batched(wrapping: sequence) } @@ -85,7 +86,7 @@ extension DirectoryEntries { /// The ``Batched`` sequence uses `Array` as its element type rather /// than `DirectoryEntry`. This can enable better performance by reducing the number of /// executor hops at the cost of ease-of-use. - public struct Batched: AsyncSequence { + public struct Batched: AsyncSequence, Sendable { public typealias AsyncIterator = BatchedIterator public typealias Element = [DirectoryEntry] @@ -93,7 +94,8 @@ extension DirectoryEntries { /// Creates a ``DirectoryEntries/Batched`` sequence by wrapping an `AsyncSequence` /// of directory entry batches. - public init(wrapping sequence: S) where S.Element == Element { + @preconcurrency + public init(wrapping sequence: S) where S.Element == Element { self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence) } diff --git a/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift b/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift index d28b756b9..50e097b93 100644 --- a/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift +++ b/Sources/NIOFileSystem/Internal/BufferedOrAnyStream.swift @@ -16,7 +16,7 @@ import NIOCore /// Wraps a ``NIOThrowingAsyncSequenceProducer`` or ``AnyAsyncSequence``. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -internal enum BufferedOrAnyStream { +internal enum BufferedOrAnyStream: Sendable { typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer< Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate > @@ -28,7 +28,7 @@ internal enum BufferedOrAnyStream(wrapping stream: S) where S.Element == Element { + internal init(wrapping stream: S) where S.Element == Element { self = .anyAsyncSequence(AnyAsyncSequence(wrapping: stream)) } @@ -69,10 +69,10 @@ internal enum BufferedOrAnyStream: AsyncSequence { - private let _makeAsyncIterator: () -> AsyncIterator +internal struct AnyAsyncSequence: AsyncSequence, Sendable { + private let _makeAsyncIterator: @Sendable () -> AsyncIterator - internal init(wrapping sequence: S) where S.Element == Element { + internal init(wrapping sequence: S) where S.Element == Element { self._makeAsyncIterator = { AsyncIterator(wrapping: sequence.makeAsyncIterator()) } diff --git a/Sources/NIOFileSystem/Internal/BufferedStream.swift b/Sources/NIOFileSystem/Internal/BufferedStream.swift index d450b00b5..0195fd0ef 100644 --- a/Sources/NIOFileSystem/Internal/BufferedStream.swift +++ b/Sources/NIOFileSystem/Internal/BufferedStream.swift @@ -118,7 +118,7 @@ import NIOConcurrencyHelpers /// } /// @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -internal struct BufferedStream { +internal struct BufferedStream { final class _Backing: Sendable { let storage: _BackPressuredStorage @@ -199,7 +199,7 @@ extension BufferedStream: AsyncSequence { } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) -extension BufferedStream: Sendable where Element: Sendable {} +extension BufferedStream: Sendable {} internal struct _ManagedCriticalState: @unchecked Sendable { let lock: NIOLockedValueBox @@ -303,7 +303,7 @@ extension BufferedStream { /// - Parameter sequence: The elements to write to the asynchronous stream. /// - Returns: The result that indicates if more elements should be produced at this time. internal func write(contentsOf sequence: S) throws -> WriteResult - where Element == S.Element, S: Sequence { + where Element == S.Element, S: Sequence, Element: Sendable { try self._backing.storage.write(contentsOf: sequence) } @@ -363,7 +363,7 @@ extension BufferedStream { internal func write( contentsOf sequence: S, onProduceMore: @escaping @Sendable (Result) -> Void - ) where Element == S.Element, S: Sequence { + ) where Element == S.Element, S: Sequence, Element: Sendable { do { let writeResult = try self.write(contentsOf: sequence) @@ -407,7 +407,7 @@ extension BufferedStream { /// - Parameters: /// - sequence: The elements to write to the asynchronous stream. internal func write(contentsOf sequence: S) async throws - where Element == S.Element, S: Sequence { + where Element == S.Element, S: Sequence, Element: Sendable { let writeResult = try { try self.write(contentsOf: sequence) }() switch writeResult { @@ -458,7 +458,7 @@ extension BufferedStream { /// - Parameters: /// - sequence: The elements to write to the asynchronous stream. internal func write(contentsOf sequence: S) async throws - where Element == S.Element, S: AsyncSequence { + where Element == S.Element, S: AsyncSequence, Element: Sendable { for try await element in sequence { try await self.write(contentsOf: CollectionOfOne(element)) } From ac79370deef8798c327c5414d4181e46674739e0 Mon Sep 17 00:00:00 2001 From: Tim Condon <0xTim@users.noreply.github.com> Date: Tue, 4 Feb 2025 11:31:29 +0100 Subject: [PATCH 90/93] Add ChannelPipeline.SynchronousOperations.Position (#3065) Adds a new `ChannelPipeline.SynchronousOperations.Position` type to fill a hole in the API that prevented non-sendable Channel handlers being added at a position to the pipeline via the synchronous operations. --------- Co-authored-by: Cory Benfield --- Sources/NIOCore/ChannelPipeline.swift | 114 ++++++- Sources/NIOHTTP1/HTTPPipelineSetup.swift | 279 ++++++++++++++++-- Tests/NIOPosixTests/ChannelPipelineTest.swift | 126 ++++++++ 3 files changed, 489 insertions(+), 30 deletions(-) diff --git a/Sources/NIOCore/ChannelPipeline.swift b/Sources/NIOCore/ChannelPipeline.swift index 7c4b0853a..6b63c5e2b 100644 --- a/Sources/NIOCore/ChannelPipeline.swift +++ b/Sources/NIOCore/ChannelPipeline.swift @@ -176,10 +176,14 @@ public final class ChannelPipeline: ChannelInvoker { let future: EventLoopFuture if self.eventLoop.inEventLoop { - future = self.eventLoop.makeCompletedFuture(self.addHandlerSync(handler, name: name, position: position)) + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + future = self.eventLoop.makeCompletedFuture( + self.addHandlerSync(handler, name: name, position: syncPosition) + ) } else { future = self.eventLoop.submit { - try self.addHandlerSync(handler, name: name, position: position).get() + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self.addHandlerSync(handler, name: name, position: syncPosition).get() } } @@ -198,7 +202,7 @@ public final class ChannelPipeline: ChannelInvoker { fileprivate func addHandlerSync( _ handler: ChannelHandler, name: String? = nil, - position: ChannelPipeline.Position = .last + position: ChannelPipeline.SynchronousOperations.Position = .last ) -> Result { self.eventLoop.assertInEventLoop() @@ -1122,11 +1126,12 @@ extension ChannelPipeline { _ handlers: [ChannelHandler & Sendable], position: ChannelPipeline.Position ) -> Result { - switch position { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + switch syncPosition { case .first, .after: - return self._addHandlersSync(handlers.reversed(), position: position) + return self._addHandlersSync(handlers.reversed(), position: syncPosition) case .last, .before: - return self._addHandlersSync(handlers, position: position) + return self._addHandlersSync(handlers, position: syncPosition) } } @@ -1143,7 +1148,7 @@ extension ChannelPipeline { /// - Returns: A result representing whether the handlers were added or not. fileprivate func addHandlersSyncNotSendable( _ handlers: [ChannelHandler], - position: ChannelPipeline.Position + position: ChannelPipeline.SynchronousOperations.Position ) -> Result { switch position { case .first, .after: @@ -1162,7 +1167,7 @@ extension ChannelPipeline { /// - Returns: A result representing whether the handlers were added or not. private func _addHandlersSync( _ handlers: Handlers, - position: ChannelPipeline.Position + position: ChannelPipeline.SynchronousOperations.Position ) -> Result where Handlers.Element == ChannelHandler & Sendable { self.eventLoop.assertInEventLoop() @@ -1191,7 +1196,7 @@ extension ChannelPipeline { /// - Returns: A result representing whether the handlers were added or not. private func _addHandlersSyncNotSendable( _ handlers: Handlers, - position: ChannelPipeline.Position + position: ChannelPipeline.SynchronousOperations.Position ) -> Result where Handlers.Element == ChannelHandler { self.eventLoop.assertInEventLoop() @@ -1238,11 +1243,29 @@ extension ChannelPipeline { public func addHandler( _ handler: ChannelHandler, name: String? = nil, - position: ChannelPipeline.Position = .last + position: ChannelPipeline.SynchronousOperations.Position = .last ) throws { try self._pipeline.addHandlerSync(handler, name: name, position: position).get() } + /// Add a handler to the pipeline. + /// + /// - Important: This *must* be called on the event loop. + /// - Parameters: + /// - handler: The handler to add. + /// - name: The name to use for the `ChannelHandler` when it's added. If no name is specified the one will be generated. + /// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func addHandler( + _ handler: ChannelHandler, + name: String? = nil, + position: ChannelPipeline.Position = .last + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._pipeline.addHandlerSync(handler, name: name, position: syncPosition).get() + } + /// Add an array of handlers to the pipeline. /// /// - Important: This *must* be called on the event loop. @@ -1251,11 +1274,27 @@ extension ChannelPipeline { /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. public func addHandlers( _ handlers: [ChannelHandler], - position: ChannelPipeline.Position = .last + position: ChannelPipeline.SynchronousOperations.Position = .last ) throws { try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get() } + /// Add an array of handlers to the pipeline. + /// + /// - Important: This *must* be called on the event loop. + /// - Parameters: + /// - handlers: The handlers to add. + /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func addHandlers( + _ handlers: [ChannelHandler], + position: ChannelPipeline.Position = .last + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._pipeline.addHandlersSyncNotSendable(handlers, position: syncPosition).get() + } + /// Add one or more handlers to the pipeline. /// /// - Important: This *must* be called on the event loop. @@ -1264,11 +1303,27 @@ extension ChannelPipeline { /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. public func addHandlers( _ handlers: ChannelHandler..., - position: ChannelPipeline.Position = .last + position: ChannelPipeline.SynchronousOperations.Position = .last ) throws { try self._pipeline.addHandlersSyncNotSendable(handlers, position: position).get() } + /// Add one or more handlers to the pipeline. + /// + /// - Important: This *must* be called on the event loop. + /// - Parameters: + /// - handlers: The handlers to add. + /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func addHandlers( + _ handlers: ChannelHandler..., + position: ChannelPipeline.Position = .last + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._pipeline.addHandlersSyncNotSendable(handlers, position: syncPosition).get() + } + /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - Parameters: @@ -1574,6 +1629,41 @@ extension ChannelPipeline { } } +extension ChannelPipeline.SynchronousOperations { + /// A `Position` within the `ChannelPipeline`'s `SynchronousOperations` used to insert non-sendable handlers + /// into the `ChannelPipeline` at a certain position. + public enum Position { + /// The first `ChannelHandler` -- the front of the `ChannelPipeline`. + case first + + /// The last `ChannelHandler` -- the back of the `ChannelPipeline`. + case last + + /// Before the given `ChannelHandler`. + case before(ChannelHandler) + + /// After the given `ChannelHandler`. + case after(ChannelHandler) + + public init(_ position: ChannelPipeline.Position) { + switch position { + case .first: + self = .first + case .last: + self = .last + case .before(let handler): + self = .before(handler) + case .after(let handler): + self = .after(handler) + } + } + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(*, unavailable) +extension ChannelPipeline.SynchronousOperations.Position: Sendable {} + /// Special `ChannelHandler` that forwards all events to the `Channel.Unsafe` implementation. final class HeadChannelHandler: _ChannelOutboundHandler, Sendable { diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index a789b8f6a..5e935123c 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -84,9 +84,10 @@ extension ChannelPipeline { let future: EventLoopFuture if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, withClientUpgrade: upgrade ) @@ -94,8 +95,9 @@ extension ChannelPipeline { future = self.eventLoop.makeCompletedFuture(result) } else { future = self.eventLoop.submit { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, withClientUpgrade: upgrade ) @@ -127,9 +129,10 @@ extension ChannelPipeline { let future: EventLoopFuture if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, enableOutboundHeaderValidation: enableOutboundHeaderValidation, withClientUpgrade: upgrade @@ -138,8 +141,9 @@ extension ChannelPipeline { future = self.eventLoop.makeCompletedFuture(result) } else { future = self.eventLoop.submit { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, enableOutboundHeaderValidation: enableOutboundHeaderValidation, withClientUpgrade: upgrade @@ -174,9 +178,10 @@ extension ChannelPipeline { let future: EventLoopFuture if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, enableOutboundHeaderValidation: enableOutboundHeaderValidation, encoderConfiguration: encoderConfiguration, @@ -186,8 +191,9 @@ extension ChannelPipeline { future = self.eventLoop.makeCompletedFuture(result) } else { future = self.eventLoop.submit { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self.syncOperations.addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, enableOutboundHeaderValidation: enableOutboundHeaderValidation, encoderConfiguration: encoderConfiguration, @@ -343,9 +349,10 @@ extension ChannelPipeline { let future: EventLoopFuture if self.eventLoop.inEventLoop { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) let result = Result { try self.syncOperations.configureHTTPServerPipeline( - position: position, + position: syncPosition, withPipeliningAssistance: pipelining, withServerUpgrade: upgrade, withErrorHandling: errorHandling, @@ -356,8 +363,9 @@ extension ChannelPipeline { future = self.eventLoop.makeCompletedFuture(result) } else { future = self.eventLoop.submit { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self.syncOperations.configureHTTPServerPipeline( - position: position, + position: syncPosition, withPipeliningAssistance: pipelining, withServerUpgrade: upgrade, withErrorHandling: errorHandling, @@ -384,14 +392,41 @@ extension ChannelPipeline.SynchronousOperations { /// the upgrade completion handler. See the documentation on `HTTPClientUpgradeHandler` /// for more details. /// - Throws: If the pipeline could not be configured. + public func addHTTPClientHandlers( + position: ChannelPipeline.SynchronousOperations.Position = .last, + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil + ) throws { + try self._addHTTPClientHandlers( + position: position, + leftOverBytesStrategy: leftOverBytesStrategy, + withClientUpgrade: upgrade + ) + } + + /// Configure a `ChannelPipeline` for use as a HTTP client with a client upgrader configuration. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`. + /// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder` + /// from the pipeline. + /// - upgrade: Add a `HTTPClientUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Should be a tuple of an array of `HTTPClientProtocolUpgrader` and + /// the upgrade completion handler. See the documentation on `HTTPClientUpgradeHandler` + /// for more details. + /// - Throws: If the pipeline could not be configured. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload @preconcurrency public func addHTTPClientHandlers( position: ChannelPipeline.Position = .last, leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self._addHTTPClientHandlers( - position: position, + position: syncPosition, leftOverBytesStrategy: leftOverBytesStrategy, withClientUpgrade: upgrade ) @@ -411,7 +446,7 @@ extension ChannelPipeline.SynchronousOperations { /// for more details. /// - Throws: If the pipeline could not be configured. public func addHTTPClientHandlers( - position: ChannelPipeline.Position = .last, + position: ChannelPipeline.SynchronousOperations.Position = .last, leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, enableOutboundHeaderValidation: Bool = true, withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil @@ -424,6 +459,36 @@ extension ChannelPipeline.SynchronousOperations { ) } + /// Configure a `ChannelPipeline` for use as a HTTP client. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`. + /// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder` + /// from the pipeline. + /// - enableOutboundHeaderValidation: Whether or not request header validation is enforced. + /// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for + /// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientProtocolUpgrader`` and + /// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler`` + /// for more details. + /// - Throws: If the pipeline could not be configured. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func addHTTPClientHandlers( + position: ChannelPipeline.Position = .last, + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + enableOutboundHeaderValidation: Bool = true, + withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._addHTTPClientHandlers( + position: syncPosition, + leftOverBytesStrategy: leftOverBytesStrategy, + enableOutboundHeaderValidation: enableOutboundHeaderValidation, + withClientUpgrade: upgrade + ) + } + /// Configure a `ChannelPipeline` for use as a HTTP client. /// /// - important: This **must** be called on the Channel's event loop. @@ -439,7 +504,7 @@ extension ChannelPipeline.SynchronousOperations { /// for more details. /// - Throws: If the pipeline could not be configured. public func addHTTPClientHandlers( - position: ChannelPipeline.Position = .last, + position: ChannelPipeline.SynchronousOperations.Position = .last, leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, enableOutboundHeaderValidation: Bool = true, encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), @@ -454,12 +519,45 @@ extension ChannelPipeline.SynchronousOperations { ) } - private func _addHTTPClientHandlers( + /// Configure a `ChannelPipeline` for use as a HTTP client. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`. + /// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder` + /// from the pipeline. + /// - enableOutboundHeaderValidation: Whether or not request header validation is enforced. + /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. + /// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for + /// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientProtocolUpgrader`` and + /// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler`` + /// for more details. + /// - Throws: If the pipeline could not be configured. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func addHTTPClientHandlers( position: ChannelPipeline.Position = .last, leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, enableOutboundHeaderValidation: Bool = true, encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._addHTTPClientHandlers( + position: syncPosition, + leftOverBytesStrategy: leftOverBytesStrategy, + enableOutboundHeaderValidation: enableOutboundHeaderValidation, + encoderConfiguration: encoderConfiguration, + withClientUpgrade: upgrade + ) + } + + private func _addHTTPClientHandlers( + position: ChannelPipeline.SynchronousOperations.Position = .last, + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + enableOutboundHeaderValidation: Bool = true, + encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), + withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil ) throws { // Why two separate functions? With the fast-path (no upgrader, yes header validator) we can promote the Array of handlers // to the stack and skip an allocation. @@ -481,7 +579,7 @@ extension ChannelPipeline.SynchronousOperations { } private func _addHTTPClientHandlers( - position: ChannelPipeline.Position, + position: ChannelPipeline.SynchronousOperations.Position, leftOverBytesStrategy: RemoveAfterUpgradeStrategy, encoderConfiguration: HTTPRequestEncoder.Configuration ) throws { @@ -496,7 +594,7 @@ extension ChannelPipeline.SynchronousOperations { } private func _addHTTPClientHandlersFallback( - position: ChannelPipeline.Position, + position: ChannelPipeline.SynchronousOperations.Position, leftOverBytesStrategy: RemoveAfterUpgradeStrategy, enableOutboundHeaderValidation: Bool, encoderConfiguration: HTTPRequestEncoder.Configuration, @@ -522,6 +620,47 @@ extension ChannelPipeline.SynchronousOperations { try self.addHandlers(handlers, position: position) } + + /// Configure a `ChannelPipeline` for use as a HTTP server. + /// + /// This function knows how to set up all first-party HTTP channel handlers appropriately + /// for server use. It supports the following features: + /// + /// 1. Providing assistance handling clients that pipeline HTTP requests, using the + /// `HTTPServerPipelineHandler`. + /// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`. + /// + /// This method will likely be extended in future with more support for other first-party + /// features. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`. + /// - pipelining: Whether to provide assistance handling HTTP clients that pipeline + /// their requests. Defaults to `true`. If `false`, users will need to handle + /// clients that pipeline themselves. + /// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If + /// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade + /// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more + /// details. + /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. + /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. + /// - Throws: If the pipeline could not be configured. + public func configureHTTPServerPipeline( + position: ChannelPipeline.SynchronousOperations.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true + ) throws { + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling + ) + } + /// Configure a `ChannelPipeline` for use as a HTTP server. /// /// This function knows how to set up all first-party HTTP channel handlers appropriately @@ -549,14 +688,17 @@ extension ChannelPipeline.SynchronousOperations { /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. /// - Throws: If the pipeline could not be configured. @preconcurrency + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) try self._configureHTTPServerPipeline( - position: position, + position: syncPosition, withPipeliningAssistance: pipelining, withServerUpgrade: upgrade, withErrorHandling: errorHandling @@ -594,7 +736,7 @@ extension ChannelPipeline.SynchronousOperations { /// spec compliance. Defaults to `true`. /// - Throws: If the pipeline could not be configured. public func configureHTTPServerPipeline( - position: ChannelPipeline.Position = .last, + position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true, @@ -609,6 +751,55 @@ extension ChannelPipeline.SynchronousOperations { ) } + /// Configure a `ChannelPipeline` for use as a HTTP server. + /// + /// This function knows how to set up all first-party HTTP channel handlers appropriately + /// for server use. It supports the following features: + /// + /// 1. Providing assistance handling clients that pipeline HTTP requests, using the + /// `HTTPServerPipelineHandler`. + /// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`. + /// 3. Providing assistance handling protocol errors. + /// 4. Validating outbound header fields to protect against response splitting attacks. + /// + /// This method will likely be extended in future with more support for other first-party + /// features. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`. + /// - pipelining: Whether to provide assistance handling HTTP clients that pipeline + /// their requests. Defaults to `true`. If `false`, users will need to handle + /// clients that pipeline themselves. + /// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If + /// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade + /// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more + /// details. + /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. + /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. + /// - headerValidation: Whether to validate outbound request headers to confirm that they meet + /// spec compliance. Defaults to `true`. + /// - Throws: If the pipeline could not be configured. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func configureHTTPServerPipeline( + position: ChannelPipeline.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation + ) + } + /// Configure a `ChannelPipeline` for use as a HTTP server. /// /// This function knows how to set up all first-party HTTP channel handlers appropriately @@ -641,7 +832,7 @@ extension ChannelPipeline.SynchronousOperations { /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. /// - Throws: If the pipeline could not be configured. public func configureHTTPServerPipeline( - position: ChannelPipeline.Position = .last, + position: ChannelPipeline.SynchronousOperations.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true, @@ -658,12 +849,64 @@ extension ChannelPipeline.SynchronousOperations { ) } - private func _configureHTTPServerPipeline( + /// Configure a `ChannelPipeline` for use as a HTTP server. + /// + /// This function knows how to set up all first-party HTTP channel handlers appropriately + /// for server use. It supports the following features: + /// + /// 1. Providing assistance handling clients that pipeline HTTP requests, using the + /// `HTTPServerPipelineHandler`. + /// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`. + /// 3. Providing assistance handling protocol errors. + /// 4. Validating outbound header fields to protect against response splitting attacks. + /// + /// This method will likely be extended in future with more support for other first-party + /// features. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - Parameters: + /// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`. + /// - pipelining: Whether to provide assistance handling HTTP clients that pipeline + /// their requests. Defaults to `true`. If `false`, users will need to handle + /// clients that pipeline themselves. + /// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If + /// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade + /// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more + /// details. + /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. + /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. + /// - headerValidation: Whether to validate outbound request headers to confirm that they meet + /// spec compliance. Defaults to `true`. + /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. + /// - Throws: If the pipeline could not be configured. + @available(*, deprecated, message: "Use ChannelPipeline.SynchronousOperations.Position instead") + @_disfavoredOverload + public func configureHTTPServerPipeline( position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true, withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration + ) throws { + let syncPosition = ChannelPipeline.SynchronousOperations.Position(position) + try self._configureHTTPServerPipeline( + position: syncPosition, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) + } + + private func _configureHTTPServerPipeline( + position: ChannelPipeline.SynchronousOperations.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init() ) throws { self.eventLoop.assertInEventLoop() diff --git a/Tests/NIOPosixTests/ChannelPipelineTest.swift b/Tests/NIOPosixTests/ChannelPipelineTest.swift index 130e39fd2..d00f460d0 100644 --- a/Tests/NIOPosixTests/ChannelPipelineTest.swift +++ b/Tests/NIOPosixTests/ChannelPipelineTest.swift @@ -2693,6 +2693,132 @@ class ChannelPipelineTest: XCTestCase { XCTAssertTrue(try channel.finish().isClean) } + + func testAddAfterForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let firstHandler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2))) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .after(firstHandler) + ) + ) + + channel.assertReadIndexOrder([1, 3, 2]) + channel.assertWriteIndexOrder([2, 3, 1]) + } + + func testAddBeforeForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let secondHandler = IndexWritingHandler(2) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1))) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler)) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .before(secondHandler) + ) + ) + + channel.assertReadIndexOrder([1, 3, 2]) + channel.assertWriteIndexOrder([2, 3, 1]) + } + + func testAddAfterLastForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let secondHandler = IndexWritingHandler(2) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1))) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler)) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .after(secondHandler) + ) + ) + + channel.assertReadIndexOrder([1, 2, 3]) + channel.assertWriteIndexOrder([3, 2, 1]) + } + + func testAddBeforeFirstForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + let firstHandler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2))) + XCTAssertNoThrow( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(3), + position: .before(firstHandler) + ) + ) + + channel.assertReadIndexOrder([3, 1, 2]) + channel.assertWriteIndexOrder([2, 1, 3]) + } + + func testAddAfterWhileClosedForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertThrowsError(try channel.finish()) { error in + XCTAssertEqual(.alreadyClosed, error as? ChannelError) + } + } + + let handler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler)) + XCTAssertNoThrow(try channel.close().wait()) + channel.embeddedEventLoop.run() + + XCTAssertThrowsError( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(2), + position: .after(handler) + ) + ) { error in + XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError) + } + } + + func testAddBeforeWhileClosedForSynchronousPosition() { + let channel = EmbeddedChannel() + defer { + XCTAssertThrowsError(try channel.finish()) { error in + XCTAssertEqual(.alreadyClosed, error as? ChannelError) + } + } + + let handler = IndexWritingHandler(1) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler)) + XCTAssertNoThrow(try channel.close().wait()) + channel.embeddedEventLoop.run() + + XCTAssertThrowsError( + try channel.pipeline.syncOperations.addHandler( + IndexWritingHandler(2), + position: .before(handler) + ) + ) { error in + XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError) + } + } } // this should be within `testAddMultipleHandlers` but https://bugs.swift.org/browse/SR-9956 From f43b37eb31a3058ddfef8ebb3e419bd0ff52e622 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 4 Feb 2025 11:01:48 +0000 Subject: [PATCH 91/93] Make the FileSystem world strict concurrency clean (#3107) Motivation: We have a few other file system modules with a small amount of code, and a lot of tests. Most of these require no changes for strict concurrency, so let's tackle them all. Modifications: Strict concurrency for filesystem targets enabled. Fixed a few incorrect test case captures. Result: Strict concurrency clean filesystem bits. --- Package.swift | 14 +++++++++----- .../FileSystemTests.swift | 12 ++++++------ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/Package.swift b/Package.swift index f88ea9746..072cb99b9 100644 --- a/Package.swift +++ b/Package.swift @@ -256,7 +256,8 @@ let package = Package( dependencies: [ "_NIOFileSystem" ], - path: "Sources/_NIOFileSystemExported" + path: "Sources/_NIOFileSystemExported", + swiftSettings: strictConcurrencySettings ), .target( name: "_NIOFileSystemFoundationCompat", @@ -264,7 +265,8 @@ let package = Package( "_NIOFileSystem", "NIOFoundationCompat", ], - path: "Sources/NIOFileSystemFoundationCompat" + path: "Sources/NIOFileSystemFoundationCompat", + swiftSettings: strictConcurrencySettings ), // MARK: - Examples @@ -543,7 +545,7 @@ let package = Package( swiftCollections, swiftSystem, ], - swiftSettings: [ + swiftSettings: strictConcurrencySettings + [ .define("ENABLE_MOCKING", .when(configuration: .debug)) ] ), @@ -560,14 +562,16 @@ let package = Package( // for the integration tests. Exclude the whole tree from // the build. "Test Data" - ] + ], + swiftSettings: strictConcurrencySettings ), .testTarget( name: "NIOFileSystemFoundationCompatTests", dependencies: [ "_NIOFileSystem", "_NIOFileSystemFoundationCompat", - ] + ], + swiftSettings: strictConcurrencySettings ), ] ) diff --git a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift index d0f5194db..4e82f7405 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileSystemTests.swift @@ -585,9 +585,9 @@ final class FileSystemTests: XCTestCase { func testCopyLargeFile() async throws { let sourcePath = try await self.fs.temporaryFilePath() let destPath = try await self.fs.temporaryFilePath() - self.addTeardownBlock { - _ = try? await self.fs.removeItem(at: sourcePath, strategy: .platformDefault) - _ = try? await self.fs.removeItem(at: destPath, strategy: .platformDefault) + self.addTeardownBlock { [fs] in + _ = try? await fs.removeItem(at: sourcePath, strategy: .platformDefault) + _ = try? await fs.removeItem(at: destPath, strategy: .platformDefault) } let sourceInfo = try await self.fs.withFileHandle( @@ -854,7 +854,7 @@ final class FileSystemTests: XCTestCase { _ copyStrategy: CopyStrategy, _ description: String, _ path: FilePath, - triggerCancel: @escaping (DirectoryEntry) -> Bool, + triggerCancel: @escaping @Sendable (DirectoryEntry) -> Bool, line: UInt = #line ) async throws { @@ -863,8 +863,8 @@ final class FileSystemTests: XCTestCase { let requestedCancel = NIOLockedValueBox(false) let cancelRequested = expectation(description: "cancel requested") - let task = Task { - try await self.fs.copyItem(at: path, to: copyPath, strategy: copyStrategy) { _, error in + let task = Task { [fs] in + try await 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. From 73e83ab73f6f83a1ac2a1e4223c87b47d4c3ae7b Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Wed, 5 Feb 2025 11:12:57 +0000 Subject: [PATCH 92/93] document known Structured Concurrency violations (#3108) ### Motivation: Not all NIO APIs, particularly the async-bridge interfaces that use `.get()` under the hood respect Structured Concurrency. That might be okay, but it definitely ought to be documented. Note: `NIOAsyncChannel` does follow Structured Concurrency. ### Modifications: Annotate known Structured Concurrency violations. ### Result: Better docs. --- Sources/NIOCore/AsyncAwaitSupport.swift | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index f5bc2af6f..ba8dfa3cf 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -15,6 +15,8 @@ extension EventLoopFuture { /// Get the value/error from an `EventLoopFuture` in an `async` context. /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// This function can be used to bridge an `EventLoopFuture` into the `async` world. Ie. if you're in an `async` /// function and want to get the result of this future. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -37,6 +39,9 @@ extension EventLoopFuture { #if canImport(Dispatch) extension EventLoopGroup { /// Shuts down the event loop gracefully. + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @inlinable public func shutdownGracefully() async throws { @@ -82,6 +87,8 @@ extension EventLoopPromise { extension Channel { /// Shortcut for calling `write` and `flush`. /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - data: the data to write @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -113,6 +120,9 @@ extension Channel { extension ChannelOutboundInvoker { /// Register on an `EventLoop` and so have all its IO handled. + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - file: The file this function was called in, for debugging purposes. /// - line: The line this function was called on, for debugging purposes. @@ -122,6 +132,9 @@ extension ChannelOutboundInvoker { } /// Bind to a `SocketAddress`. + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - address: the `SocketAddress` to which we should bind the `Channel`. /// - file: The file this function was called in, for debugging purposes. @@ -132,6 +145,9 @@ extension ChannelOutboundInvoker { } /// Connect to a `SocketAddress`. + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - address: the `SocketAddress` to which we should connect the `Channel`. /// - file: The file this function was called in, for debugging purposes. @@ -143,6 +159,8 @@ extension ChannelOutboundInvoker { /// Shortcut for calling `write` and `flush`. /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - data: the data to write /// - file: The file this function was called in, for debugging purposes. @@ -159,6 +177,8 @@ extension ChannelOutboundInvoker { /// Close the `Channel` and so the connection if one exists. /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - mode: the `CloseMode` that is used /// - file: The file this function was called in, for debugging purposes. @@ -170,6 +190,8 @@ extension ChannelOutboundInvoker { /// Trigger a custom user outbound event which will flow through the `ChannelPipeline`. /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// /// - Parameters: /// - event: the event itself. /// - file: The file this function was called in, for debugging purposes. @@ -196,17 +218,26 @@ extension ChannelPipeline { try await self.addHandler(handler, name: name, position: position).get() } + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @preconcurrency public func removeHandler(_ handler: RemovableChannelHandler & Sendable) async throws { try await self.removeHandler(handler).get() } + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func removeHandler(name: String) async throws { try await self.removeHandler(name: name).get() } + /// + /// - warning: This method currently violates Structured Concurrency because cancellation isn't respected. + /// @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @available( *, @@ -224,6 +255,7 @@ extension ChannelPipeline { message: "ChannelHandlerContext is not Sendable and it is therefore not safe to be used outside of its EventLoop" ) + @preconcurrency public func context(handler: ChannelHandler & Sendable) async throws -> ChannelHandlerContext { try await self.context(handler: handler).map { UnsafeTransfer($0) }.get().wrappedValue From c51907a839e63ebf0ba2076bba73dd96436bd1b9 Mon Sep 17 00:00:00 2001 From: Rick Newton-Rogers Date: Fri, 7 Feb 2025 16:52:40 +0000 Subject: [PATCH 93/93] Enable strict concurrency checking for NIOTLS (#3112) ### Motivation: To ensure NIOTLS concurrency safety. ### Modifications: * Enable strict concurrency checking in the package manifest. * Require `NegotiationResult` to be `Sendable` * In `NIOTypedApplicationProtocolNegotiationHandler` the result is used to fulfil promises and perform hops so we need it to be sendable when accessed from these other concurrency domains. ### Result: Builds will warn and CI will fail if regressions are introduced. --- Package.swift | 3 ++- .../NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 072cb99b9..008de4f82 100644 --- a/Package.swift +++ b/Package.swift @@ -221,7 +221,8 @@ let package = Package( .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", swiftCollections, - ] + ], + swiftSettings: strictConcurrencySettings ), .target( name: "NIOTestUtils", diff --git a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift index 75d95c5a4..0911efa95 100644 --- a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift @@ -39,7 +39,8 @@ import NIOCore /// specify a type that must be returned from the supplied closure. The result will then be used to succeed the ``NIOTypedApplicationProtocolNegotiationHandler/protocolNegotiationResult`` /// promise. This allows us to construct pipelines that include protocol negotiation handlers and be able to bridge them into `NIOAsyncChannel` /// based bootstraps. -public final class NIOTypedApplicationProtocolNegotiationHandler: ChannelInboundHandler, +@preconcurrency +public final class NIOTypedApplicationProtocolNegotiationHandler: ChannelInboundHandler, RemovableChannelHandler { public typealias InboundIn = Any