This change fixes an example shown in the ServerBootstrap documentation.
### Motivation:
The current example given to users of ServerBootstrap will show a
Sendable conformance warning in Swift 6.0 or later.
### Modifications:
Changed the example to use `syncOperations`
### Result:
The new example doesn't contain any warnings.
Instead of checking for a setup command in bash, we use GitHub Actions
to determine if there is anything to run
### Motivation:
Slightly cleaner output when looking at logs.
### Modifications:
Moved an if statement from bash to yaml.
### Result:
The setup commands step will generally be skipped instead of executing a
no-op
Co-authored-by: Cory Benfield <lukasa@apple.com>
Teach the script to indicate what is different on failure rather than
keeping quiet. This helps when the script is failing in CI but not
locally.
### Motivation:
The script is reporting that there are missing changes in CI on
swift-crypto, but I am unable to reproduce them locally. This is to get
immediate insight on why the check fails rather than keeping quiet.
### Modifications:
Include the diff in the update-cmake-lists script.
### Result:
update-cmake-lists script outputs the difference between what is in a PR
vs what it expects to see instead of shrugging and leaving it as an
exercise to the user.
Motivation:
For our async initializers on bootstraps, it's imortant that _both_
channel initializers are called, not only the one that comes as an
argument on the bind function.
Modifications:
Fix the takeOwnershipOfDescriptor async functions to call the
initializer from the bootstrap, and add regression tests.
Result:
Better behaved code.
Motivation:
The nightly visionOS tests are failing because there
are too many simulators matching the given destination
selector.
Modifications:
- On Xcode 16.2 use visionOS 2.3
Result:
Nightly CI passes
### 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:
Structured Concurrency is helpful but so far, MTELG was very difficult
to use with it mostly because Swift is still missing `async` in
`defer`s.
This builds on
- #3297
- #3302
- #3304
### Modifications:
- Add MTELG.withELG { ... }
### Result:
MTELG + SC = <3
### Motivation:
NIOThread assumed it can hold onto `pthread_t` forever. Unfortunately,
on Linux, `pthread_t` is dead when the thread got joined (if not
detached) or if it exits (if detached) _which is at a random point in
time_.
### Modifications:
- Only assume ownership owner the `pthread_t` if not detached
- `nil` out the `pthread_t` on `join()`
### Result:
- Fewer `pthread_t` lifecycle bugs.
Motivation:
The compiler is better at optimising closures wrapped in nominal types
than raw closures when used as generic parameters. CallbackList is used
a lot and stores an optional closure as well as on optional array of
closures. Wrapping these internally should save some allocations.
Modifications:
- Wrap the element stored in the `CallbackList`.
Result:
Fewer allocs
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
`inEventLoop` is very much in the performance path of SwiftNIO,
especially these days with Concurrency, `NIOLoopBound` and friends.
Previously, we relied on `pthread_equal(pthread_self(), myPthread)`,
however, this could cause a number of issues.
1. Holding onto a `pthread_t` after `.join` is actually illegal (fixed
in #3297)
2. Potential ABA issues when `pthread_t` pointer are re-used for new
pthreads
3. Fix would require a lock around `myPthread` which makes things (2x
slower, even without contention)
### Modifications:
- New type `SelectableEventLoopUniqueID` which can be packed into a
`UInt`
- Attach them into a C thread local
### Result:
- Even faster than the old, incorrect version
- old: `measuring: el_in_eventloop_100M: 0.257395375, 0.241049208,
0.243188792, 0.259125916, 0.24843225, 0.229690125, 0.244281541,
0.225078834, 0.236395, 0.233305167`
- new: `measuring: el_in_eventloop_100M: 0.175561125, 0.187225625,
0.199269375, 0.19740975, 0.1922695, 0.179850958, 0.177612458,
0.17665125, 0.17897475, 0.18038775`
- More correct
- Groundwork to make #3297 not make things slower
### Motivation:
PR #3297 is changing `inEventLoop` and `inEventLoop` is very much on the
perf path. So let's add a benchmark
### Modifications:
- Add `(!)inEventLoop` benchmark
- Fix a guaranteed deadlock in `TCPThroughputBenchmark` to make the
benchmarks runnable
### Result:
- More benchmarks
- Fewer hangs
Add patch for `<stddef.h>` being included inside of extern "C" section
which is invalid in C++.
### Motivation:
When building with C++ interop enabled on Linux, `<stddef.h>` fails to
import because the C++ module `_Builtin_stddef.max_align_t` (which it
includes) is re-imported with C language linkage.
```
<module-includes>:1:10: note: in file included from <module-includes>:1:
1 | #include "/home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/CNIOLLHTTP.h"
| `- note: in file included from <module-includes>:1:
2 |
/home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/CNIOLLHTTP.h:20:10: note: in file included from /home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/CNIOLLHTTP.h:20:
18 | #define C_NIO_LLHTTP_SWIFT
19 |
20 | #include "c_nio_llhttp.h"
| `- note: in file included from /home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/CNIOLLHTTP.h:20:
21 |
22 | static inline llhttp_errno_t c_nio_llhttp_execute_swift(llhttp_t *parser,
/home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/c_nio_llhttp.h:559:10: note: in file included from /home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/c_nio_llhttp.h:559:
557 | extern "C" {
558 | #endif
559 | #include <stddef.h>
| `- note: in file included from /home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/c_nio_llhttp.h:559:
560 |
561 | #if defined(__wasm__)
<unknown>:0: error: could not build C module 'CNIOLLHTTP'
/home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/recipe-sysroot-native/usr/lib/clang/17/include/stddef.h:128:1: error: import of C++ module '_Builtin_stddef.max_align_t' appears within extern "C" language linkage specification
126 |
127 | #if defined(__need_max_align_t)
128 | #include <__stddef_max_align_t.h>
| `- error: import of C++ module '_Builtin_stddef.max_align_t' appears within extern "C" language linkage specification
129 | #undef __need_max_align_t
130 | #endif /* defined(__need_max_align_t) */
/home/xtremek/Programming/xavgru12/meta-swift-project/poky/build-qemuarm64/tmp-glibc/work/cortexa57-oe-linux/swift-hello-world/1.0/build/checkouts/swift-nio/Sources/CNIOLLHTTP/include/c_nio_llhttp.h:557:1: note: extern "C" language linkage specification begins here
555 | #define INCLUDE_LLHTTP_API_H_
556 | #ifdef __cplusplus
557 | extern "C" {
| `- note: extern "C" language linkage specification begins here
558 | #endif
```
### Modifications:
Added a patch to the `update_and_patch_llhttp.sh` file to move this
include to the correct location, and ran the script to actually apply it
to the included `c_nio_llhttp.h` file in the `CNIOLLHTTP` target.
### Result:
swift-nio compiles properly on a package with C++ interop
(`.interoperabilityMode(.Cxx)`) enabled in Linux.
@lhoward @Lukasa
Update llhttp dependency in `CNIOLLHTTP` target ahead of adding a new
patch to the `update_and_patch_llhttp.sh` script.
### Motivation:
We need to update the `update_and_patch_llhttp.sh` script to add an
additional patch to fix compiling swift-nio with C++ interop enabled in
Swift targets. It was recommended to update llhttp separately from the
patch update and ahead of time to keep the changes separate from each
other.
### Modifications:
Ran the `update_and_patch_llhttp.sh` script in the CNIOLLHTTP target to
update the llhttp dependency to the latest version (9.3.0). It appears
that the only changes from 9.2.1 (previous version) is a few new
includes, and the definition of the `UNREACHABLE` macro that is used
instead of the `abort()` call.
### Result:
Everything compiles locally and test suite passes with these changes.
@Lukasa
Motivation:
When debugging allocations it is frequently helpful to be able to use
bpftrace instead of the more limited heaptrack.
Modifications:
Offer an equivalent of malloc-aggregation.d for bpftrace.
Result:
Allocation recording on Linux is available.
Motivation:
Our docs for running alloc counting benchmarks are scattered between a
few places, and our info about debugging allocations is also a bit
outdated.
Modifiactions:
- Add a doc on running the two different flavours of allocation counting
test. Remove the entry about bencharks from the README.
- Add a doc on debugging allocations
Most of the content comes from the original
`docs/debugging-allocations.md` doc but has been updated a little and
includes info about the new stackdiff tool.
Result:
Better docs
Specify default macOS variant in non-catalyst builds.
https://developer.apple.com/forums/thread/737851
### Motivation:
macOS build has an extra warning:
```
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, name:Any Mac }
{ platform:macOS, variant:Mac Catalyst, name:Any Mac }
```
### Modifications:
Explicitly select the macOS variant.
### Result:
No warnings
Motivation:
When you diff two sets of alloc stacks there are often natural pairings
which aren't exact matches (e.g. the compiler inlined something in one
but not the other). These are tedious to pair up manually, we can make
that easier.
Modifications:
- Add a 'merge' which allows you to interactively pair up stacks across
the two different sets by using the levenshtein distance between them.
- After interactive merging is complete any remaining alloc stacks.
Result:
Easier to diff stacks
Motivation:
Sometimes it's helpful to view the alloc stacks from a program.
Modifications:
- Add a 'dump' subcommand to stackdiff allowing you to dump the stack
diff from heaptrack/dtrace/bpftrace
- You can also filter the stacks so that only certain stacks are
included
Result:
Can dump filtered alloc stacks to stdout
Motivation:
We often debug allocations on macOS, so being able to parse the output
from malloc-aggregation.d is valuable.
Modifications:
- Add a dtrace parser to stackdiff
Result:
Can diff outputs from dtrace
Motivation:
When debugging allocs its helpful to get a diff between two programs.
Modification:
- Adds a 'diff' subcommand which is roughly equivalent to the existing
'stackdiff-dtrace.py' script.
Result:
Alloc stacks can be diffed
Motivation:
Our alloc regression workflows are somewhat disparate: on macOS we have
dtrace and a script to diff two ouputs. On Linux we have heaptrack and
bpftrace but no way to analyze their outputs.
Diffing output from these tools can be quite tedious if the stacks vary
even a little (because the compiler decided to not inline a function,
for example).
Most of the tedium in this workflow is from pairing up equivalent stacks
across the two inputs. We can make this easier to do by ranking
suggestions based on how similar they are and letting the user decide
whether to accept the match or not.
Modifications:
- Add a subpackage with some internals for parsing heaptrack,
aggregating stacks, and measuring the similarity between them
- The CLI took is currently a no-op, it'll be added in subsequent PRs
Result:
Easier to diagnose alloc regressions
### Motivation:
The macOS runners have a symlink to the latest released Xcode beta at
Xcode-latest.app, by making use of it we will always test against the
most recent version.
### Modifications:
Introduce new parameters for the latest Xcode beta and deprecate those
which mention Xcode 21 betas.
### Result:
Tests will move on to using Xcode 26 beta 2 via the symlink
Example of this working
https://github.com/apple/swift-nio/actions/runs/16075841548/job/45370760690?pr=3285
Motivation:
Android messed up their nullability annotations in fts_open. The
original change in
https://android.googlesource.com/platform/bionic/+/dec8efd72a6ad8b807a15a614ae1519487cfa456
asserted that fts_open's path argument took a non-null pointer to an
array of non-null pointers to strings. That's challenging, because the
_end_ of that array is indicated by a null pointer.
Regardless, this was eventually fixed in
https://android.googlesource.com/platform/bionic/+/da81ec4d1cbd0279014feb60535bf38defcd9346.
Unfortunately, that was more than a year after the offending change, so
we need to work around it.
Modifications:
Add a shim for Android that omits the nullability annotations. Use that
shim on Android.
Result:
Android works again.
Resolves#3273.
Modern 32-bit platforms (such as embedded Linux builds) support 64-bit
timestamps in `time_t` and `timespec`. Accommodate this.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Point API docs URLs to the latest stable version instead of the unstable
main branch.
### Motivation:
For most of developers this README.md is the main entry point when
searching online or installing the library, so pointing them to API docs
for the latest stable release makes more sense then the main branch,
which may contain not-yet-released API or breaking changes.
### Modifications:
This PR removes `main` branch name from API docs URLs, making them
always point to the latest stable release instead of the main branch.
### Result:
API docs URLs in README.md point to the latest stable release.
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Add assembly files for Windows
### Motivation:
These assembly files are now required to build on Windows Arm64.
### Modifications:
* The Windows assembly files are now handled in `update-cmake-lists.sh`.
### Result:
The assembly source files will be properly updated in `swift-crypto`.
This is a quick simple fix for compiling NIOCore to wasm using the
command `swift build --swift-sdk wasm32-unknown-wasip1-threads --target
NIOCore`.
This fixes all errors for `wasip1`, however there are other errors
remaining in `main` when compiling for `wasi` using the command `swift
build --swift-sdk wasm32-unknown-wasi --target NIOCore`. Those issues
are out of scope for this PR.
### Motivation:
I am working to enable wasm compilation for a wide range of repositories
which depend on NIOCore. See
[here](https://github.com/PassiveLogic/swift-web-examples/issues/1) for
a sneak peak. This change is required to enable compiling several
respositories.
### Modifications:
`.multicastNotSupported` is elided for `os(WASI)` builds in
Channel.swift, however some new code referenced that case without proper
`WASI` guards.
This modification simply adds the appropriate elision guard to fix
wasip1 builds for NIOCore.
### Result:
After making this change, `swift build --swift-sdk
wasm32-unknown-wasip1-threads --target NIOCore` builds again (assuming
you have the appropriate wasm sdk installed).
Fixed issue with macOS CI when overrides are being used.
### Motivation:
When we use Xcode_XX_X_build_arguments_override, the CI fails because of
an extra double quotes ("") making its way to the final command.
### Modifications:
Remove the extra double quote from the Yaml file defining macOS tests.
### Result:
We are able to run `swift build` with extra arguments.
Fixes#3262 by adding the missing APIs.
### Motivation:
As explained by the issue linked above, having a
non-`Sendable`-requiring variant of the new `scheduleCallback` APIs on
`NIOIsolatedEventLoop` can be useful since we're not always dealing with
`Sendable` types.
### Modifications:
This adds the required `scheduleCallback` APIs to `NIOIsolatedEventLoop`
by wrapping the non-`Sendable` `NIOScheduleCallbackHandler` in a
`NIOLoopBound`-based handler.
### Result:
The two `scheduleCallback`s can be used on `NIOIsolatedEventLoop` too.
---------
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Motivation:
With the new Swift version (6.2) we get access to spans for safely
interacting with the contiguous memory owned by other types. Allow users
write bytes to the ByteBuffer with RawSpans.
Modifications:
* ByteBuffer-core: Overload the setBytes, _setBytes, and
_setBytesAssumingUniqueBufferAccess to use RawSpan instead of
UnsafeRawBufferPointer
* ByteBuffer-aux: Overload the writeBytes to use RawSpan instead of
UnsafeRawBufferPointer
Result:
Users can now write the contiguous memory of other types into ByteBuffer
using the new RawSpan overloads, removing the need for unsafe pointer
handling.
### Motivation
NIO’s event loop can emit metrics. Currently, this includes the start
time (i.e. when the loop started working) and the number of tasks which
were executed in that tick.
It would be useful to collect the time the loop tick ended and the
length of time the loop was asleep before starting the tick.
### Modifications
The event loop has a new property to track the time between runs. The
tick info collects two new values:
* The time the loop finished: the end-time.
* The time since the last run: the sleep time.
For the first run, the sleep time is the time since the event loop was
created.
### Result
The new metrics are available for collection.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation
With the introduction of isolated conformances, it has become necessary
to start managing the use of metatypes for some of our protocols. In
general, we don't want to force the relevant protocols to only be
conformed in non-isolated forms. Instead, we just want to make the
specific APIs non-usable.
Modifications
- Add shims for SendableMetatype that only use it when it is available.
- Require SendableMetatype where needed, gated by @preconcurrency.
Result
We continue to be safe.
Add Xcode 26 beta 1 to macOS CI and disable Xcode 16.1 jobs by default
### Motivation:
* Xcode 26 beta 1 is now released, we should test our code on it.
* We should drop 16.1 to conserve the number of jobs. 16.1 isn't
offering much coverage anyway since it has the same Swift minor version
(6.0) as Xcode 16.2.
### Modifications:
* Enable use of Xcode 26 beta 1 by default.
* Disable Xcode 16.1 jobs by default
### Result:
* This and downstream repos will run Xcode builds on Xcode 26 beta 1.
* Xcode 16.1 jobs won't run by default on this or downstream repos but
will run if explicitly requested.
An example of this working
https://github.com/apple/swift-nio/actions/runs/15614383580/job/43983277904?pr=3267
Embedded channels should set local and remote address always
### Motivation:
Currently, if connect or bind are called without a promise, the
remote/local address does not get set because those were getting set in
the whenSuccess of the promise.
### Modifications:
If the user didn't provide a promise, create one ourselves, so we have
something to listen for.
### Result:
Calling connect/bind will always result in remote/local address getting
set, regardless of whether you pass a promise
### Motivation:
The current method of parsing the ASCII table output is brittle and
because the text output and the stored thresholds in JSON have different
precisions doesn't always work.
### Modifications:
* In the event that a deviation is found re-run the benchmarks in update
mode and print the git diff to the logs.
* The threshold update script scrapes this from the logs and applies it
locally so that it can then be committed.
* Add the functionality in the update script to update thresholds based
on diff in logs
### Result:
More reliable threshold updates.
An example of this working:
https://github.com/apple/swift-nio/actions/runs/15302748893?pr=3257
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Some 429: Too many requests responses have been seen when attempting to
curl remote CI scripts.
### Modifications:
Adding `--retry 3` which means that curl will retry 3 times on transient
error codes.
### Result:
Transient errors will be retried 3 times, first for 1 second and then
doubled each retry.
From `man curl`
```
--retry <num>
If a transient error is returned when curl tries to perform a transfer, it
retries this number of times before giving up. Setting the number to 0
makes curl do no retries (which is the default). Transient error means
either: a timeout, an FTP 4xx response code or an HTTP 408, 429, 500, 502,
503 or 504 response code.
When curl is about to retry a transfer, it first waits one second and then
for all forthcoming retries it doubles the waiting time until it reaches 10
minutes which then remains delay between the rest of the retries. By using
--retry-delay you disable this exponential backoff algorithm. See also
--retry-max-time to limit the total time allowed for retries.
curl complies with the Retry-After: response header if one was present to
know when to issue the next retry (added in 7.66.0).
If --retry is provided several times, the last set value is used.
```
### Motivation:
This fixes linker errors such as
```
@nonobjc __C.catmc_nio_atomic_uint_least32_t_create_with_existing_storage(Swift.UnsafeMutablePointer<__C.catmc_nio_atomic_uint_least32_t>, Swift.UInt32) -> () in NIOAtomic.swift.o
NOTE: found '_catmc_nio_atomic_uint_least32_t_create_with_existing_storage' in c-nioatomics.c.o, declaration possibly missing 'extern "C"'
```
when building with Swift/C++ interoperability enabled.
### Modifications:
Wrapped the C declarations a couple of headers in `extern "C" { ... }`
blocks.
### Result:
The project builds successfully with Swift/C++ interop enabled.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This change enables swift-nio to be compiled for Android against both
NDK 27 and NDK 28
### Motivation:
Android's NDK had been adopting [nullability
annotations](https://android.googlesource.com/platform/developers/docs/+/refs/heads/master/api-guidelines/ndk.md#nullability)
in its C headers, and they have been changing them from release to
release. The churn has mostly died down since the release of the NDK 27
(LTS), but one new change in NDK 28 affects the destructor argument for
`pthread_create`, making the existing `ThreadDestructor` typealias
invalid and leading to the following compile error when the [Android SDK
bundle](https://github.com/skiptools/swift-android-toolchain/releases)
is installed and linked to NDK 28:
```
$ swiftly run swift build --swift-sdk aarch64-unknown-linux-android28 +6.2-snapshot-2025-05-15-a
Building for debugging...
/opt/src/github/swift-everywhere/swift-nio/Sources/NIOPosix/ThreadPosix.swift:82:9: error: cannot convert value of type '@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?' to expected argument type '@convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer'
80 | &handleLinux,
81 | nil,
82 | destructor,
| `- error: cannot convert value of type '@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?' to expected argument type '@convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer'
83 | args
84 | )
[4/21] Compiling NIOPosix ThreadPosix.swift
```
This change adapts the parameter we pass to that function to accommodate
both NDK 27 and NDK 28.
### Modifications:
There's currently no way to determine which version of the NDK is in use
at compile time (see https://github.com/swiftlang/swift/issues/81402),
so this accommodation is implementing by having two functions named
`coerceThreadDestructor` that return values that are suitable either NDK
27 or NDK 28 (using `unsafeBitCast`, but the layout of C functions
doesn't know anything about nullability, so this is safe), and then let
the type inference for `pthread_create` handle the rest.
### Result:
swift-nio can be compiled against both NDK 27 and NDK 28 without errors.
When working on performance in PostgresNIO I noticed a few
`_swift_getGenericMetadata`s. We don't like those. I could trace them
down to `NIOThrowingAsyncSequenceProducer`. All methods on this object
are generic, since the object itself is generic.
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Nightly builds for 6.2 exist, we should test against them.
### Modifications:
Update the matrix nightly-next to point to 6.2. This will affect
downstream adopters but shouldn't break them because they don't gatet
PRs on this passing.
### Result:
nightly tests will run against Swift 6.2
An example of this working
https://github.com/apple/swift-nio/actions/runs/15185876449/job/42706027686?pr=3250
### Motivation:
To have more version about which swift is running to aid in debugging.
### Modifications:
Run swift --version on common workflows, this should be safe because
they all assume Swift is already nistalled unlike the Static SDK
workflow.
### Result:
Swift tools information will be printed before job execution
An example of this working:
https://github.com/apple/swift-nio/actions/runs/15049159516/job/42299334292