### Motivation:
Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.
Without this change:
```swift
dependencies: [
// Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
.product(
name: "NIOPosix",
package: "swift-nio",
condition: .when(platforms: [
.macOS,
.macCatalyst,
.iOS,
.tvOS,
.watchOS,
.visionOS,
.driverKit,
.linux,
.windows,
.android,
.openbsd,
// .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
])
),
]
```
With this change:
```swift
dependencies: [
// Without this PR, downstream packages can consume NIOPosix simply:
.product(name: "NIOPosix", package: "swift-nio"),
]
```
### Modifications:
- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix
### Result:
Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.
### Testing performed
- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
### Motivation:
Detached threads are a bad idea, their lifetime becomes random and NIO
doesn't need this functionality (except for in some tests that are
easily refactored)
### Modifications:
- Refactor tests to not use detached threads
- Remove detached threads functionality
### Result:
- Cleaner, less complex and more correct code
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.
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 <lukasa@apple.com>
### Motivation:
In many situations, for example continuous profiling with sampling
profilers, it's important to distinguish between on- and off-CPU work.
That's most easily done if there are clear function names/prefixes to
grep for that are common places to just wait (off-CPU) and do no real
work. In SwiftNIO those are chiefly three places:
1. The `EventLoops` waiting for work
2. `The NIOThreadPool` threads waiting for work
3. `EventLoopFuture.wait()`
This patch makes sure that each of those will have a function with
prefix `_blockingWaitFor` in the function name which is easily
greppable.
### Modifications:
- Create some non-inlinable functions with `_blockingWaitFor...` that
just wait for `...`.
### Result:
SwiftNIO makes operational excellence easier and your SRE team more
happy.
Motivation:
The thread performance checker warns that a threads with QoS are waiting
on threads in the NIOThreadPool. We can avoid these warnings by using a
condition variable instead.
Modifications:
- Replace the usage of a semaphore and lock in NIOThreadPool with a
condition lock.
- The condition value indicates whether the threads have work to do
(where work is processing work items or exiting their run loop).
Result:
- Fewer warnings
- Resolves#2960
### Motivation:
Documentation checking catches more issues in Swift 6.0.
### Modifications:
Adopt the Swift 6.0 image and fix the errors.
### Result:
More accurate docs.
Dispatch is not supported on WASI, and only Unix domain sockets are
supported, which means we have to exclude those APIs on this platform.
There's work in progress to enable tests for this on CI, but nothing I
can provide for this PR at the current moment.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
* Apply formatting
* Apply no block comments rule
* Apply OmitExplicitReturns
* Apple OnlyOneTrailingClosureArgument
* Apply NoAssignmentInExpressions
* Fix up DontRepeatTypeInStaticProperties lint errors
* Apply `OrderedImports`
* Apply `ReplaceForEachWithForLoop`
* format file
* Enable the formatting pipeline
* Adopt `AmbiguousTrailingClosureOverload`
* Fix license header
* Fix format check
* Fix `EndOfLineComment`
* Fix CI
* Adapt CI script to check if changes when running formatting
* Separate lint and format into to steps
* Fix format
* Adopt `UseEarlyExits`
* Revert "Adopt `UseEarlyExits`"
This reverts commit d1ac5bbe12.
Motivation:
To dedupe the thread pool from NIOFileSystem and NIOPosix, the one from
NIOPosix needs to gain support for cancellation for its async
`runIfActive` function.
Modification:
- Generate a work ID when submitting async work to the pool, add that ID
to a set in the cancellation handler
- Check the existence of the ID in the cancel set when dequeuing the
work
Result:
Queued NIOThreadPool tasks can be cancelled before they are run.
Motivation:
DispatchGroup can cause thread performance checker warnings in
places we don't want them. We can avoid those warnings in some
cases by using a condition variable instead.
Modifications:
- Replaced a use of DispatchGroup with a condition variable
in NIOThreadPool setup.
- Removed an unnecessary DispatchGroup in the shutdown code
Result:
Fewer thread performance checker warnings.
Motivation:
`numberOfThreads` is a required parameter to the public constructor, it's therefore known to the caller. Any use case that wants to optimise its logic for the parallelism offered by the particular `NIOThreadPool` needs to carry the number of threads separately from the `NIOThreadPool` itself. We should exposes `numberOfThreads` publicly from `NIOThreadPool` to avoid this complexity and possible bugs.
This is especially true for `NIOThreadPool.singleton` where the decision on the number of threads used is achieved through some complex and dynamic logic. It's therefore best not to second guess the result of those calculations.
Modifications:
Flip the visibility of `numberOfThreads` in `NIOThreadPool` to `public`.
Result:
Some complexity gets removed from client packages.
Co-authored-by: Cory Benfield <lukasa@apple.com>
* Benchmark for measuring NIOThreadPool dispatch
* Avoid CoW cost for NIOThreadPool work queue
* Flip stray `var` to a `let`.
* Use .modifying state to prevent CoW, not a class
* Removing some obselete comment noise.
* Use Deque instead of CirclarBuffer in NIOThreadPool
* Ratchet down the # of allocs for read_10000_chunks_from_file. NIOTheadPool changes reduced the allocations required.
* Async versions of NonBlockingFileIO functions
I have not produced async versions of the readChunked functions. These
would likely be replaced with an AsyncSequence though.
* Add tests for async versions of NonBlockingFileIO
* Add wrapper for FileRegion to avoid Sendable issues
* Allocate ByteBuffer in readSync
* Update read_10000_chunks_from_file alloc count
* Add UnsafeTransfer to NIOPosix.
Use in NonBlockingFileIO.openFile functions
* Update Sources/NIOPosix/NonBlockingFileIO.swift
Co-authored-by: George Barnett <gbarnett@apple.com>
* formatting, docc
* update comment
* replace openFile with withOpenFile
* More indentation
* Update comments
* Remove docc links to NIOCore types
* Fix read docc links
* Catch errors when closing file handle in withOpenFile
* rename to withFileHandle
* Fix double close on error
Also
- move @available above each function
- Remove wording about separate from Task pool
* Update Sources/NIOPosix/NonBlockingFileIO.swift
Co-authored-by: George Barnett <gbarnett@apple.com>
* withOpenFile is now withFileRegion
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
* Add async version of NIOThreadPool.runIfActive
* Changes from comments in PR
Remove no longer supported code
Add tests for errors being thrown, and the thread pool not being active
* Collapse async runIfActive into one function
* remove whitespace
* Make T Sendable
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
* Bump minimum Swift version to 5.7
Motivation:
Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6
Modifications:
* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update integration test script
* Update docs
Result:
Remove support for Swift 5.6, add 5.10
* fix indentation issues
* 5.9 docker image use release image
### Motivation:
SwiftNIO allows and encourages to precisely manage all operating system resources like file descriptors & threads. That is a very important property of the system but in many places -- especially since Swift Concurrency arrived -- many simpler SwiftNIO programs only require a single, globally shared EventLoopGroup. Often even with just one thread.
Long story short: Many, probably most users would happily trade precise control over the threads for not having to pass around `EventLoopGroup`s. Today, many of those users resort to creating (and often leaking) threads because it's simpler. Adding a `.globalSingle` static var which _lazily_ provides singleton `EventLoopGroup`s and `NIOThreadPool`s is IMHO a much better answer.
Finally, this aligns SwiftNIO a little more with Apple's SDKs which have a lot of global singletons that hold onto system resources (`Dispatch`'s thread pool, `URLSession.shared`, ...). At least in `Dispatch`'s case the Apple SDKs actually make it impossible to manage the resources, there can only ever be one global pool of threads. That's fine for app development but wouldn't be good enough for certain server use cases, therefore I propose to add `NIOSingleton`s as an _option_ to the user. Confident programmers (especially in libraries) are still free and encouraged to manage all the resources deterministically and explicitly.
Companion PRs:
- https://github.com/apple/swift-nio-transport-services/pull/180
- https://github.com/swift-server/async-http-client/pull/697
### Modifications:
- Add the `NIOSingletons` type
- Add `MultiThreadedEventLoopGroup.singleton`
- Add `NIOThreadPool.singleton`
### Result:
- Easier use of NIO that requires fewer parameters for users who don't require full control.
- Helps with #2142
- Fixes#2472
- Partially addresses #2473
mark syncShutdownGracefully noasync
Motivation:
The code as-is blocks the calling thread.
Modifications:
* mark `EventLoopGroup.syncShutdownGracefully()` and `NIOThreadPool.syncShutdownGracefully()` noasync on Swift > 5.7
* offer NIOThreadPool.shutdownGracefully()
* add renamed to syncShutdownGracefully()
Motivation:
The remaining NIO code really conceptually belongs in a module called
NIOPosix, and NIOCore should really be called NIO. We can't really do
that last step, but we can prepare by pushing the bulk of the remaining
code into a module called NIOPosix.
Modifications:
- Move NIO to NIOPosix
- Make NIO an umbrella module.
Result:
NIOPosix exists.