Split FoundationEssentials extensions from NIOFoundationCompat
### Motivation:
Resolves#3038
### Modifications:
Split NIOFoundationCompat into two and only import FoundationEssentials
and NIOFoundationEssentialsCompat where appropriate.
### Result:
ByteBuffer/Codable extensions can be used without vendoring the code or
linking to Foundation.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Add multi-version matrix support to Wasm Swift SDK workflow
### Motivation:
The WASM CI only ran against nightly-main, making it impossible to
distinguish toolchain regressions from code issues. Other repos in the
ecosystem using `swiftlang/github-workflows` already test against
`nightly-main`, `nightly-6.3`, and `6.3` by default.
### Modifications:
- Add `nightly_main_enabled`, `nightly_6_3_enabled`, and
`release_6_3_enabled` boolean inputs to `wasm_swift_sdk.yml` (all
defaulting to `true`, matching the coverage of
`swiftlang/github-workflows/swift_package_test.yml`) and update the
matrix generation to emit the appropriate entry per enabled version.
- Update `install_swift_sdk.sh` to support non-main branch snapshots by
deriving the API and download paths from `INSTALL_SWIFT_BRANCH` rather
than hardcoding `main`/`development`.
- Fail early with a clear message if the branch snapshot API returns no
results, rather than hitting an unbound variable error.
### Result:
WASM builds are now tested against multiple Swift versions, providing a
stable baseline to identify nightly-only regressions. Callers using the
workflow without arguments get the new default coverage automatically;
those who want to narrow the matrix can set specific version inputs to
`false`.
---------
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Translate `HTTPHeaderValidationTests` to Swift testing
### Motivation:
We want to add tests that use parameterized testing to
`HTTPHeaderValidationTests`. In order to allow this we first need to
translate this file to use Swift Testing instead of XCTest.
### Modifications:
- Mechanical translation of `HTTPHeaderValidationTests` from XCTest to
Swift testing.
### Result:
We can add parameterized tests to HTTPHeaderValidationTests.
### Motivation:
A recent PR (#3574) added support for customising the container
environment used for the matrix job for users of the reusable workflow.
It supported a custom Dockerfile and controlling `--cap-add` options to
the `docker run` command. Users who require this fine-grained control
with `--cap-add` also will benefit from being able to control the
`--security-opt` of the `docker run` command.
### Modifications:
- Add support for `--security-opt` docker flags in custom CI jobs
### Result:
Users of the reusable matrix CI workflow can control the
`--security-opt` for the container.
As observed by @weissi https://github.com/apple/swift-nio/issues/3382
### Motivation:
When `getaddrinfo` fails, SwiftNIO throws `SocketAddressError.unknown`
which discards the error code. This makes it impossible for callers to
distinguish between different failure reasons (e.g., `EAI_NONAME` vs
`EAI_AGAIN`), which is needed for retry logic and diagnostics.
### Modifications:
- Add `SocketAddressError.UnknownHost` struct that carries `host`,
`port`, `errorCode` (from `getaddrinfo`), and `errorDescription` (from
`gai_strerror`).
- Update `SocketAddress.makeAddressResolvingHost` and
`GetaddrinfoResolver` to throw/fail with the new error type on both
POSIX and Windows paths.
- Update existing test catch blocks to use the new error type.
- Add `testGetaddrinfoErrorCodeIsPreserved` to verify the error code is
captured.
### Result:
Callers can now inspect the `getaddrinfo` error code when host
resolution fails, enabling more specific error handling. Resolves
https://github.com/apple/swift-nio/issues/3382
### Questions for reviewer
1. **Should `case unknown(host:port:)` be deprecated?** — This enum case
is no longer thrown after this PR. Callers catching `.unknown` will
silently stop matching. Should I add
`@available(*, deprecated, renamed: "UnknownHost")` to provide a
migration path?
2. **Should the doc comment on `makeAddressResolvingHost` be updated?**
— The `- Throws:` line still references `SocketAddressError.unknown`
instead of the new
`SocketAddressError.UnknownHost`.
---------
Co-authored-by: Si Beaumont <beaumont@apple.com>
### Motivation
* Some consumers need to run CI inside custom Docker images with
additional Linux capabilities. The shared matrix workflows had no way to
express this — consumers had to maintain entirely bespoke CI workflows
instead.
### Modifications
* Added `MATRIX_LINUX_DOCKERFILE` and
`MATRIX_LINUX_DOCKER_CAPABILITIES_JSON` environment variables to
`generate_matrix.sh`. These propagate as `dockerfile` (string) and
`docker_capabilities` (JSON array) fields in the matrix JSON. Defaults
are empty/`[]` so existing callers are unaffected.
* Extended `add_matrix_entry()` with two optional trailing parameters
for the new fields.
* In `swift_test_matrix.yml`:
- Made the "Pull Docker image" step conditional — skipped when a
`dockerfile` is provided.
- Added a "Build Docker image from Dockerfile" step that builds the
image with `--build-arg SWIFT_IMAGE=<matrix image>` so consumers can
parameterise the Swift base image.
- Added `--cap-add` flags to `docker run` when `docker_capabilities` is
non-empty.
### Result
* Consumers can set `MATRIX_LINUX_DOCKERFILE` to a repo-relative path
and `MATRIX_LINUX_DOCKER_CAPABILITIES_JSON` to a JSON array of
capabilities. The matrix will build their Dockerfile per Swift version
and run containers with the requested capabilities.
* Existing consumers that don't set these variables see no change.
### Motivation
* The nightly Swift container images were still using `jammy` (Ubuntu
22.04) while the release images for 6.2+ have moved to `noble` (Ubuntu
24.04). We should align them.
### Modifications
* Changed `linux_nightly_next_container_image` and
`linux_nightly_main_container_image` in `generate_matrix.sh` from
`-jammy` to `-noble`.
### Result
* Nightly CI jobs now use noble-based images, consistent with the 6.2+
release images.
Motivation:
Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.
Modifications:
* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml
* Set language mode 5 in Benchmarks package manifest
Result:
Code reflects our support window.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Fix Windows Docker daemon not starting before polling
### Motivation:
When a Windows runner is restored from a saved VM image, the Docker
service sometimes fails to start during the "second boot" due to a
failure creating the required virtual switches.
Manually restarting the Docker service resolves the issue every time.
### Modifications:
Before polling `docker info`, check whether the Docker service is
running and start it if it is not.
### Result:
The Docker daemon becomes available reliably on Windows runners.
### Motivation:
An upcoming change in the library template adds a code snippet. Since
our cxx interop compatibility test script does not account for that
tests fail on nightly.
### Modifications:
Insert a newline character before other modifications.
### Result:
The cxx interop compatibility tests pass again on nightly.
### Motivation
* Swift 6.3 has been released, we should add it to our CI coverage.
### Modifications
* Update `apple/swift-nio/scripts/generate_matrix.sh`
* Update `apple/swift-nio/scripts/check-matrix-job.sh`
* Update reusable adopters of `swift_test_matrix.yml`
* Update end-user adopter workflows of `swift_test_matrix.yml`
* Remove stale `NIGHTLY_6_1` fallback shims from `generate_matrix.sh`
* Migrate `linux_nightly_6_1_arguments_override` to
`linux_nightly_next_arguments_override` in `main.yml` and
`pull_request.yml`
* Copy benchmark thresholds from 6.2
### Result
* NIO tests against Swift 6.3 in CI and downstream repositories can
opt-in.
* A successful run using the new Swift 6.3 jobs:
https://github.com/apple/swift-nio/actions/runs/23841350537/job/69497505715?pr=3565
Motivation:
I have no clear picture of why the package-benchmark packages have shown
sudden performance regressions without any associated code or infra
change, but they have.
Modifications:
Increased the thresholds
Result:
CI passes again
### Motivation:
`testCanPinThreadsToCores` crashes with a precondition failure
(`pthread_setaffinity_np failed: 22`) on CI environments where the
container's available CPUs don't start from 0.
```console
% docker run --rm -v $PWD:/pwd -w /pwd swift:6.2 nproc
8
```
Running the test in an environment where the CPUs didn't start from 0
crashed:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 nproc
2
```
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
NIOPosix/LinuxCPUSet.swift:78: Precondition failed: pthread_setaffinity_np failed: 22
*** Signal 5: Backtracing from 0xf358a1ceb140... done ***
*** Program crashed: System trap at 0x0000f358a1ceb140 ***
Platform: arm64 Linux (Ubuntu 24.04.4 LTS)
Thread 0 "TP-#0" crashed:
0 0x0000f358a1ceb140 _assertionFailure(_:_:file:line:flags:) + 164 in libswiftCore.so
1 [ra] 0x0000ba727f86c0a0 static NIOThread.currentAffinity.setter + 939 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/LinuxCPUSet.swift:78:13
2 [ra] 0x0000ba727f878b48 closure #2 in NIOThreadPool._start(threadNamePrefix:) + 295 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/NIOThreadPool.swift:365:47
3 [ra] [thunk] 0x0000ba727f8fc5a0 thunk for @escaping @callee_guaranteed (@guaranteed NIOThread) -> () + 23 in swift-nioPackageTests.xctest at //<compiler-generated>
4 [ra] 0x0000ba727f8ff5c8 closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 767 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/ThreadPosix.swift:186:21
5 [ra] [thunk] 0x0000ba727f8ff678 @objc closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 11 in swift-nioPackageTests.xctest at //<compiler-generated>
6 [ra] 0x0000f358a03d595c <unknown> in libc.so.6
...
```
Also, when there was just one CPU, this test would pass but wasn't
actually testing the pinning because it was using
`min(1, System.coreCount / 2)` instead of `max`, which clamped down to 0
for the loop.
### Modifications:
- Select from available CPU IDs using `NIOThread.currentAffinity.cpuIds`
- Use `max` instead of `min` to still run the test on single core
environments.
### Result:
The test no longer crashes on CPU-restricted environments:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
✔ Test testCanPinThreadsToCores() passed after 0.001 seconds.
✔ Suite "NIOThreadPoolTest" passed after 0.001 seconds.
✔ Test run with 1 test in 1 suite passed after 0.001 seconds.
```
## Summary
- NIOFileSystem's `open` syscall error mapping only handled `EACCES`
(`.permissionDenied`) but not `EPERM` (`.notPermitted`), causing EPERM
errors (e.g., on network volumes) to be classified as "unknown" instead
of `permissionDenied`
- Added `.notPermitted` alongside `.permissionDenied` in the `open()`
switch case in `FileSystemError+Syscall.swift` (both `NIOFS` and
`_NIOFileSystem` modules)
- Added corresponding test expectation for the new errno mapping
## Motivation
Other syscall handlers in the same file (`remove`, `symlink`, `unlink`,
`futimens`) already correctly handle both `.permissionDenied` and
`.notPermitted` as `permissionDenied`. The `open` handler was missing
this treatment.
Fixes#3559
## Test plan
- [x] Updated `testErrnoMapping_open` to verify `.notPermitted` maps to
`.permissionDenied`
- [ ] CI will validate on all supported Swift versions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Motivation:
Similar to MultiThreadedEventLoopGroup, it is useful in some NUMA
circumstances to be able to pin thread pools to specific CPUs. This can
minimise the overheads of moving memory around across NUMA nodes.
Modifications:
Added a pinned CPUs initializer to NIOThreadPool
Result:
Users have more flexibility.
### Motivation
*
`MTELGScheduledCallbackTests.testCancelAfterShutdownDoesNotCallCancellationCallbackAgain`
is failing on iOS simulator CI. It schedules a callback with a
`.milliseconds(1)` deadline, then shuts down, expecting shutdown to
cancel the callback. On the simulator the 1ms timer fires before
shutdown processes, so the callback executes instead of being cancelled.
* This is the same class of bug previously fixed for
`testScheduledCallbackNotExecutedBeforeDeadline` in dcecf0cb.
### Modifications
* Change the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in
`testCancelAfterShutdownDoesNotCallCancellationCallbackAgain` (the
observed failure).
* Speculatively apply the same fix to
`testCancelExecutesCancellationCallback`,
`testCancelAfterCancelDoesNotCallCancellationCallbackAgain`, and
`testShutdownDoesNotCancelCancelledCallbacksAgain` which have the same
pattern.
* The `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this does not extend test duration.
### Result
* Scheduled callback cancellation tests no longer depend on real-time
precision and should not flake on slow CI runners or simulators.
### Motivation
* `testFlatBlockingMapOnto` sets up a `flatMapBlocking` chain that
dispatches work to `DispatchQueue.global()`, but never waits for the
chain to complete before returning. The `defer` block calls
`syncShutdownGracefully()`, which shuts down the event loop while the
GCD dispatch is still in-flight. When the GCD work completes and tries
to deliver its result back to the event loop, it finds the loop already
shut down, causing a crash. On fast machines the GCD work completes
before shutdown, but on slow iOS simulators shutdown wins the race
consistently. This crash also kills whichever other test happens to be
running concurrently (typically
`testRepeatedTaskThatIsCancelledAfterRunningAtLeastTwiceNotifies`).
### Modifications
* Capture the `EventLoopFuture` from the `flatMapBlocking` chain and
call `.wait()` on it before the function returns, ensuring the GCD
dispatch delivers its result back to the event loop before shutdown
begins. Move the assertions from the `.whenSuccess` closure to after the
`.wait()`.
### Result
* The event loop is no longer shut down while GCD work is in-flight,
fixing the crash on iOS simulator CI.
### Motivation
`testCopyFileReplacingExistingFileSucceeds` (and
`testCopySymlinkReplacingExistingSymlinkSucceeds`) verify that no .tmp-
prefixed files are left behind after a `copyItem(replaceExisting: true)`
call on Linux. However, both tests create their files in the shared
system temp directory (e.g. /tmp) and then scan that entire directory
for .tmp- files. When other tests run in parallel, their in-flight
`copyItem(replaceExisting: true)` operations leave transient .tmp- files
in the same directory, causing spurious failures.
### Changes
- Both tests now create a dedicated subdirectory for their files, so the
temp file scan only sees files belonging to that specific test.
- Cleanup is handled via `addTeardownBlock` to ensure the subdirectory
is removed even if the test fails early.
### Results
The temp file assertions are no longer affected by concurrent test
activity or other processes writing to the shared temp directory,
eliminating the flakiness.
Increase job timeout for macOS tests from 30 to 60 minutes.
### Motivation:
We see test jobs getting cancelled, for example:
https://github.com/apple/swift-nio/actions/runs/23240305356
### Modifications:
Increase test time.
### Result:
Test jobs will complete.
This PR adds support for FreeBSD to the `CNIOSHA1` target and the
`NIOConcurrencyHelpers` target.
### Motivation:
This PR is partial because the `NIOCore` target still can't be built,
and the existing PR #3398 includes almost the same changes too.
However, #3398 is a little bit old. Besides, the source code in
`NIOConcurrencyHelpers` is used in other repositories now, for example:
- https://github.com/apple/swift-log/pull/398
- https://github.com/apple/swift-log/pull/387 was merged before
swift-nio is fixed.
So I think it's important to fix `NIOConcurrencyHelpers` first, even if
the entire swift-nio is yet to be fixed.
### Modifications:
- Make `swift build --target NIOConcurrencyHelpers` work on FreeBSD
- Make `swift build --target CNIOSHA1` work on FreeBSD
### Result:
The following commands finished successfully.
```shell
swift build --target NIOConcurrencyHelpers
swift build --target CNIOSHA1
```
Environment:
- FreeBSD 15.0-RELEASE-p1 x86_64
- [Swift on FreeBSD Preview
toolchain](https://forums.swift.org/t/swift-on-freebsd-preview/83064)
```
Swift version 6.3-dev (LLVM b58b2a34d509492, Swift cf535d8b998d09b)
Target: x86_64-unknown-freebsd14.3
Build config: +assertions
```
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
* `testHalfCloseOwnOutputWithPopulatedBuffer` asserts that writing to a
half-closed channel produces `ChannelError.outputClosed`. However, after
flushing the buffered write and the FIN, the remote peer can process
both and fully close the connection before the subsequent write is
processed. When this happens the channel is fully closed and the write
fails with `.ioOnClosedChannel` instead.
* This race seems to be more likely on iOS simulators in CI.
### Modifications
* Accept either `.outputClosed` or `.ioOnClosedChannel` as valid errors
from the post-half-close write.
### Result
* The test no longer flakes on iOS simulator CI runs.
### Motivation
*
`MTELGScheduledCallbackTests.testScheduledCallbackNotExecutedBeforeDeadline`
is flakey on macOS CI. It schedules a callback with a 1ms deadline,
sleeps for 1µs via `Task.sleep`, then asserts the callback hasn't fired.
On a loaded CI runner, `Task.sleep` can overshoot well past 1ms, causing
the callback to fire before the assertion.
### Modifications
* Increase the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in `_BaseScheduledCallbackTests`. This makes it impossible
for the short sleep to overshoot past the deadline. The
`EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this change is harmless to them.
### Result
* The test reliably asserts that a callback is not executed before its
deadline without depending on real-time sleep precision.
…oopTest`
### Motivation
* `Task.sleep(for:)` and the `Duration` literals (`.milliseconds`,
`.seconds`) require iOS 16.0+, tvOS 16.0+, and watchOS 9.0+, so these
calls cause build failures on simulator test destinations in CI.
### Modifications
* Replaced all five `Task.sleep(for:)` calls in `EventLoopTest.swift`
with the universally available `Task.sleep(nanoseconds:)`.
### Result
* `EventLoopTest` compiles for iOS, tvOS, and watchOS simulator
destinations. Verified locally with `xcodebuild build-for-testing`.
Add Swift-version-based inputs to macOS CI workflows
### Motivation
- The macOS CI runners now provide symbolic links mapping Swift versions
to Xcode apps ( `Xcode_swift_6.1.app`, `Xcode_swift_6.2.app`,
`Xcode_swift_6.3.app`), decoupling CI from specific Xcode versions.
- Several Xcode versions (`16.3`, `26.0`, `26.1`, `26.2`) are being
deprecated and removed from runners.
- The `-require-explicit-sendable` build argument overrides on Xcode
16.2/16.3 are no longer needed.
### Modifications
- Added `swift_6_1_enabled`, `swift_6_2_enabled`, `swift_6_3_enabled`
inputs (with corresponding `build_arguments_override`,
`test_arguments_override`, setup_command) to `macos_tests.yml`, all
defaulting to false.
- Added macos_ `swift_6_1_enabled`, macos_ `swift_6_2_enabled`, macos_
`swift_6_3_enabled` inputs to `macos_benchmarks.yml`.
- Added matrix entries using the `Xcode_swift_6.X.app` symlink paths.
- All existing `xcode_*` inputs remain unchanged for backwards
compatibility with downstream consumers.
- Enabled the new Swift-version inputs in main.yml and pull_request.yml,
removing the old `xcode_16_2/16_3` build argument overrides.
### Result
- SwiftNIO CI now runs macOS jobs for Swift `6.1`, `6.2`, and `6.3`
using the stable `Xcode_swift_6.X.app` symlinks.
- Downstream consumers are unaffected.
An example of this working here
https://github.com/apple/swift-nio/actions/runs/22960228328/job/66648462048?pr=3546
### Motivation
* `.timeLimit` from Swift Testing requires iOS 16.0+, watchOS 9.0+, and
tvOS 16.0+, but the package's deployment targets are lower, causing
build failures on all iOS/watchOS/tvOS simulator test steps in CI.
### Modifications
* Removed `.timeLimit(.minutes(1))` from the `@Suite` attribute on
`MultiThreadedEventLoopGroupTests`.
* Removed `.timeLimit(.minutes(1))` from the `@Test` attribute on
`testRepeatedTaskThatCancelsItselfNotifiesOnlyWhenFinished`.
### Result
* Tests should compile on iOS, watchOS, and tvOS simulator destinations.
* The CI job timeout still guards against hung tests.
Port `EventLoopTest` to Swift Testing.
### Motivation:
Tests should use the latest Swift Testing framework when possible.
### Modifications:
- Ported `EventLoopTest ` from XCTest to Swift Testing
### Result:
All tests continue to pass, EventLoopTest now has more modern Swift
Testing syntax.
Motivation:
NIO has had support for CPU pinning for 8 years, but nobody has ever
used it. Ask me how I know?
Modifications:
- Make the CPU pinning constructor public.
Result:
Users can pin MTELG threads to specific CPU cores, _finally_.
### Motivation
* xcodebuild output is suppressed with `-quiet` in the macOS tests
workflow, making it hard to diagnose CI failures on the main branch.
### Modifications
* Add a `debug_output_enabled` boolean input to `macos_tests.yml`
(defaults to `false`), which controls a `QUIET_ARG` env var used by all
xcodebuild invocations.
* When `debug_output_enabled` is `true`, `-quiet` is elided and full
xcodebuild output is emitted.
* Enable `debug_output_enabled` in `main.yml` so nightly and main-branch
push builds produce verbose output.
### Result
* PR builds remain concise (default behaviour unchanged).
* Main-branch builds now include full xcodebuild output for easier
failure triage.
Motivation:
System.udpMaxSegments purports to expose the value of UDP_MAX_SEGMENTS.
However this doesn't appear to be part of the UAPI so it always returns
nil.
Modifications:
- Deprecate `System.udpMaxSegments`
- Remove the C shim
- Update tests
Result:
After your change, what will change.
Adds the changes from https://github.com/apple/swift-nio/pull/3508 to
the `_NIOFileSystem`.
### Motivation:
We have added capability to overwrite regular files and symbolic links
to `NIOFS` `FileSystem.copyItem` in
https://github.com/apple/swift-nio/pull/3508. Now we want to port the
same logic to `_NIOFileSystem`.
### Modifications:
- Adds a new `FileSystemProtocol.copyItem` requirement with
`replaceExisting: bool` parameter along with a default implementation.
- Adds an implementation of the new `FileSystemProtocol.copyItem`
requirement to `_NIOFileSystem`'s `FileSystem` struct for regular files
and symbolic links.
### Notes
It seems that the tests for `FileSystem` are only in `NIOFS` - so no
tests are added in this PR.
Extend timeout in testShutdownCancelsOutstandingScheduledCallbacks
### Motivation:
* `testShutdownCancelsOutstandingScheduledCallbacks` can be flaky,
particularly on slower systems like simulated devices in CI.
* In some circumstances the task can be executed before it has chance to
be cancelled.
### Modifications:
* Schedule the task for the far future so that it is available to be
cancelled even on slower systems.
### Result:
Less flaky tests.
### Motivation
`SocketAddress.init(ipAddress:port:)` uses `inet_pton` to parse IP
address strings. `inet_pton` does not support the `%scope` suffix used
in IPv6 link-local addresses (e.g., `fe80::1%eth0`), causing these
addresses to fail with `failedToParseIPString`. This forces downstream
consumers like grpc-swift-nio-transport to reimplement scoped IPv6
parsing using `getaddrinfo` themselves.
Related: https://github.com/grpc/grpc-swift-nio-transport/issues/147
### Modifications
When the IP address string contains a `%` character, fall back to
`getaddrinfo` with `AI_NUMERICHOST` instead of `inet_pton`. This
properly parses the `%scope` suffix and sets `sin6_scope_id` in the
resulting `sockaddr_in6`. The scoped path is extracted into a private
`_parseScopedIPv6` helper, guarded with `#if !os(Windows) && !os(WASI)`.
The non-scoped `inet_pton` path is completely unchanged.
Added 5 tests:
- Named scope (`fe80::1%lo`) — verifies `sin6_scope_id` matches
`if_nametoindex`
- Numeric scope (`fe80::1%1`) — verifies numeric index parsing
- Scoped vs non-scoped inequality — different `sin6_scope_id` means
different addresses
- Invalid scopes rejected — empty scope and nonexistent interface both
throw
- Non-scoped regression — `::1` still works with `scope_id == 0`
### Result
`SocketAddress(ipAddress: "fe80::1%eth0", port: 80)` now succeeds and
preserves the scope ID in `sin6_scope_id`. Non-scoped addresses continue
to work exactly as before.
### Context
This came up while working on IPv6 link-local support in
[grpc-swift-nio-transport#146](https://github.com/grpc/grpc-swift-nio-transport/pull/146),
where the workaround was to use `getaddrinfo` directly in the gRPC
layer. The reviewer suggested upstreaming this to swift-nio so the
workaround can be removed.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Shut down simulators between test runs
### Motivation:
I suspect the CI machines are underpowered and we see simulator load
failures during testing because we are running out of resources.
### Modifications:
Add a command to shutdown the simulators before running each simulator
test.
### Result:
Hopefully, tests will pass more reliably.
Let's improve NIOAsyncChannels performance, by using UnsafeContinuations
instead of CheckedContinuations.
### Motivation:
We want to improve the performance for our async APIs.
### Modifications:
- Introduce a new typealias `NIOUnsafeContinuation` that behaves like a
UnsafeContinuation in release mode and like a CheckedContinuation in
debug mode.
- Use the `NIOUnsafeContinuation` inside the `NIOAsyncWriter`
- Use the `NIOUnsafeContinuation` inside the
`NIOThrowingAsyncSequenceProducer`
### Result:
Fewer allocations
Fix static Linux SDK version hardcoding
### Motivation
* Nightly CI was failing with a checksum mismatch because the static
Linux SDK filename was hardcoded to `_static-linux-0.0.1`, but the
SDK has since been released as `0.1.0` with a different checksum.
* The swift.org releases API returns a `version` field alongside
the checksum for the `static-sdk` platform, so the version can be
resolved dynamically.
### Modifications
* Added `extract_static_sdk_version()` to read the `version` field from
the releases API response.
* In the `version` install path, override `sdk_suffix` with the
API-provided version rather than the hardcoded `0.0.1`.
### Result
* The correct SDK filename (`_static-linux-0.1.0`) is now resolved
and hopefully will continue to work for future version bumps.
### Motivation
* Other libraries often have byte buffer storage with similar concepts
as NIO's `ByteBuffer`, linear storage with reader and writer indices -
it would be nice to have efficient conversion to and from these objects.
* Efficienct conversion would likely mean taking ownership of the byte
storage allocated by the other object and exposing `ByteBuffer`s
internals so that they may be owned by another object, there is no API
for this currently.
### Modifications
* Added new methods behind `CustomByteBufferAllocator` SPI.
* Added public `ByteBuffer` initializer for adopting
externally-allocated memory
* Made `ByteBufferAllocator` initializer public with custom
`malloc`/`realloc`/`free`/`memcpy` hooks
* Updated `realloc` signature to pass old capacity alongside new
capacity to allow implementations to copy over bytes
* Added `withVeryUnsafeMutableBytesWithStorageManagement` for mutable
storage access
* Updated all existing tests using internal allocator API to use the new
API
* Added tests for custom allocator functionality
### Result
* Custom allocators can manage `ByteBuffer` memory with full size
information
* External systems can transfer memory ownership to `ByteBuffer`
* System allocator maintains zero overhead due to inlining of the
wrapper
* API (SPI) is extensible for future allocation system integrations
Ports the added system calls from `NIOFS` (from
https://github.com/apple/swift-nio/pull/3505) to `_NIOFileSystem`:
> Adds three new system call wrappers for the `symlinkat`,
`renameatx_np`, and `unlinkat` system calls.
### Motivation:
`_NIOFileSystem` module is around for backward compatibility - hence, we
are porting the new feature to it.
### Modifications:
Exactly same as in https://github.com/apple/swift-nio/pull/3505 but
applied to the `_NIOFileSystem`:
> Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.
Motivation:
Right now we store our selectable event loop reference in a NIO
ThreadSpecificVariable. That's nice enough, but this has become a hot
code path in cases where users are using the complete concurrency
override. In those cases, the ThreadSpecificVariable forces us to both
call `pthread_getspecific` and to end up needing to perform a dynamic
cast to our expected type.
These dynamic casts are costly: in one sample project where we spent
fully 7.84% of the runtime in dispatching tasks onto the EL, the cost of
that dynamic cast _alone_ was 0.5% of the runtime, with
pthread_getspecific being another 0.2%. This is 10% of the cost of
dispatching a job, entirely unnecessarily.
Modifications:
- Use some fancy C thread-locals, which have much better performance:
see #3302 for more on that.
- Use Unamanged to pass the self reference into and out of the
thread-local, avoiding dynamic casts.
Result:
Further improved performance for concurrency takeover.
Before this change:
```
any() from event loop thread (fast path): 30.654833 ns/iteration
any() from outside (fallback path): 17.881084 ns/iteration
```
After this change:
```
any() from event loop thread (fast path): 11.571958 ns/iteration
any() from outside (fallback path): 17.52175 ns/iteration
```
Nearly a 3x speedup on that particular operation. Not so bad.
Note the irony that before this change it was actually more expensive to
call `any` from _on_ an EL thread than off it. Both calls had to call
pthread_getspecific, which means all of this cost was the runtime type
conversion.
### Motivation
* `check_benchmark_thresholds.sh` runs `git add --intent-to-add .` and
`git diff HEAD` to show updated threshold files when benchmarks regress.
* The unscoped `.` caused the diff to include everything in the working
tree, including the `.build` directory, producing noisy output.
### Modifications
* Pass `${benchmark_package_path}/Thresholds/` to both `git add
--intent-to-add` and `git diff HEAD --` so only threshold files appear
in the diff.
### Result
* The diff printed on benchmark failure shows only threshold file
changes.
### Motivation
* Swift 5.10 is no longer actively supported and CI does not require it
### Modifications
* Default Swift 5.10 CI jobs to disabled
### Result
* Swift 5.10 CI jobs will not run unless opted-in
Motivation:
When using concurrency takeover, we currently spend nearly half the
runtime checking if our SelectableEventLoop has an enqueue function. We
know it does, but we just haven't given the compiler enough evidence.
This patch rewrites the code to prove it to the compiler.
Modifications:
- Expose internal functions without erased types on MTELG
- Use these internal functions, and call directly to SEL, eliminiating
the as!.
Result:
Massive perf improvement in task enqueueing.
Add parallel execution mode for integration tests
### Motivation:
Integration tests regularly take 21m in CI; they're the long pole.
### Modifications:
* Allocation count tests are now run in parallel if
`NIO_ALLOC_COUNTER_TESTS_PARALLEL` is `true`, tests in a given file
are still in serial.
* Test output is catted to different files and recovered and printed in
the order in which the tests were started.
### Result:
Integration test execution (and therefore a PR's CI checks) goes from
21m to 10m
Apple platform simulator CI failures
### Motivation
* Several tests failed when testing against simulators for Apple
platforms (iOS, tvOS, watchOS, visionOS)
### Modifications
* Added `@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)` to each
`@Test` method in `NIOThreadPoolTest`, `EventLoopFutureTest`, and
`NIOTransportAccessibleChannelCoreTests` to match the availability of
the APIs they use (`timeLimit` and `withUnsafeTransportIfAvailable`).
* Removed `.timeLimit(.minutes(1))` from the `@Suite` declarations on
`NIOThreadPoolTest` and `EventLoopFutureTest` - the `@Suite` macro
cannot be used with `@available`, so `timeLimit` cannot be used.
* Skip `testHomeDirectoryFromPasswd` on simulator targets via
`#if targetEnvironment(simulator)` / `XCTSkip`, since simulators retu>
success but nil information when invoking `getpwuid_r`.
### Result
* Apple simulator platform builds and test runs no longer fail due to
these issues. Some infrastructure issues remain to be resolved
separately.
### Motivation
* When threshold files don't exist yet, `thresholds update` creates new
untracked files. `git diff HEAD` only shows changes to tracked files, so
newly created threshold files were silently omitted from the diff.
### Modifications
* Run `git add --intent-to-add .` before `git diff HEAD` so that
untracked files are registered in the index and appear in the diff
output without staging their contents.
### Result
* The diff output now includes newly created threshold files.