Motivation:
Users can write arbitrary code in their deinits, and that arbitrary code
_may_ end up hitting Objective-C autoreleases. We don't want to leak
those objects into the per-thread autoreleasepool, as that may not be
popped for a very long time, if ever, so we need to to ensure that
deiniting the task objects has an autoreleasepool.
Modifications:
Add an autoreleasepool around the task drop, and tests to validate that
we do things correctly.
Result:
Better memory management around deinit
### Motivation
`HTTPResponseEncoder` writes hand-optimised status lines for the
well-known `HTTPResponseStatus` values instead of going through the
general `default` path that formats `HTTP/<version> <code>
<reasonPhrase>`. Several of those fast paths had drifted out of sync
with `HTTPResponseStatus.reasonPhrase`, so the exact bytes on the wire
depended on whether a status happened to have a fast path:
* **HTTP/1.0 + 511** emitted the wrong HTTP version (`HTTP/1.1 511 ...`)
— a wire-format correctness bug, not just cosmetic.
* **HTTP/1.1 + 431** emitted the reason phrase `Range Not Satisfiable`
instead of `Request Header Fields Too Large`.
* **HTTP/1.1 + 416** emitted `Request Range Not Satisified` (also
misspelled) instead of `Range Not Satisfiable`.
* **HTTP/1.0 and HTTP/1.1 + 307** emitted `Tempory Redirect`
(misspelled) instead of `Temporary Redirect`.
Resolves#3630.
### Modifications
* Correct the five diverging status lines in `HTTPResponseEncoder` so
they match `HTTPResponseStatus.reasonPhrase` and carry the correct HTTP
version.
* Add a regression test that, for every well-known status at both
HTTP/1.0 and HTTP/1.1, asserts the encoded status line equals the
canonical `HTTP/<version> <code> <reasonPhrase>` form, keeping the fast
paths in lockstep with `reasonPhrase`.
### Result
The encoder now produces correct, consistent status lines for all
well-known statuses regardless of whether they use a fast path. The new
test fails on the pre-fix code (the 511 case fails on the version, the
431/416/307 cases on the reason phrase) and passes after the fix.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
## Motivation
`scripts/check_benchmark_thresholds.sh` started printing path-qualified
diff markers in #3602 so multi-package benchmark runs can identify which
package produced each diff.
`dev/thresholds-from-benchmark-output.sh` still scrapes the old exact
marker line, which means local threshold updates from CI logs can miss
the diff entirely once the new marker format appears.
## Changes
Relax the scraper to match the stable `=== BEGIN DIFF` prefix instead of
the old exact line, preserving compatibility with both the original
marker and the newer path-qualified form.
## Validation
- `bash -n dev/thresholds-from-benchmark-output.sh`
- Verified the scrape pipeline against both `=== BEGIN DIFF ===` and
`=== BEGIN DIFF (Benchmarks) ===` sample log lines
Co-authored-by: Cory Benfield <lukasa@apple.com>
Off-by-one in the QUIC variable-length integer length boundaries.
### Motivation:
`bytesNeededForInteger` classifies an integer into the 1/2/4/8 byte QUIC
encoding using half-open ranges (`0..<63`, `0..<16383`,
`0..<1_073_741_823`, `0..<4_611_686_018_427_387_903`). Those upper
bounds are the *largest* value each size can hold (2^6-1, 2^14-1, 2^30-1
and 2^62-1 per RFC 9000 § 16), so each maximum is wrongly excluded:
- 63, 16383 and 2^30-1 report one byte too many, so the encoder writes
them with a larger encoding than needed.
- 2^62-1, the largest value the encoding can represent, falls through to
the `fatalError` and crashes the encoder.
The existing one-byte write test only iterates `0..<63`, so the 63 case
was never exercised.
### Modifications:
- Switch the four ranges in `bytesNeededForInteger` to inclusive bounds.
- Extend the one-byte write test to include 63, and add boundary checks
plus a 2^62-1 round-trip test.
### Result:
Boundary values encode in the minimal number of bytes and 2^62-1
round-trips instead of crashing.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This PR is just a cleanup of the source code.
### Motivation:
The `CNIOFreeBSD` source code contains inconsistent trailing
whitespaces, which hinders future modifications.
### Modifications:
Removed all trailing whitespaces from `CNIOFreeBSD`.
### Result:
The source code remains exactly the same; only the trailing whitespace
has been removed.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Enable Xcode betas by default now that they are available on runners
again
### Motivation:
Xcode betas are available on runners again
### Modifications:
Enable Xcode betas by default now that they are available on runners
again
### Result
Downstream packages will run Xcode beta builds
An example of this running
https://github.com/apple/swift-nio/actions/runs/27679540593/job/81863193279?pr=3627
Motivation:
swift-nio-quic and swift-nio-http3 were recently open sourced, they
should be listed in the README.
Modifications:
- Update README
Result:
- More NIO
Drop unused SystemPackage import from FileSystemTests
### Motivation:
swift-system 1.7.0 exposes a new type named `FileType`, which is
ambiguous with `NIOFS.FileType` when both modules are imported in the
same file. This causes a compile-time error when building
`FileSystemTests.swift` in the `NIOFSIntegrationTests` target.
Fixes#3622.
### Modifications:
Drop the unused `SystemPackage` import in `FileSystemTests.swift`.
### Result:
`NIOFSIntegrationTests` builds against swift-system 1.7.0 and later.
### Motivation:
The CI pipelines offer the latest released Swift versions (which have
included Swift 6.3 for some time now) and
a nightly-main and nightly-next. Right now nightly-next pipelines are
all still 6.3, which is a problem and folks are
likely operating under the misguided assumption that they have 6.4
coverage in their pipelines.
### Modifications:
- Update the nightly-next pipelines to use 6.4 nightly images
### Result:
Nightly next pipelines moved to 6.4
We are running into some issues when doing:
```swift
let writeOptions: OpenOptions.Write =
byteOffset > 0 ? .modifyFile(createIfNecessary: true) : .newFile(replaceExisting: true)
try await FileSystem.shared.withFileHandle(
forWritingAt: FilePath(outputFilePath),
options: writeOptions
) { fileHandle in
```
which results in crashes on some Android devices where `renameat2` is
not available:
```
('renameat2' system call failed with '(38) Function not implemented'.)
```
This PR adds functionality similar to what is already done for `EINVAL`
on Linux, such that both lead to the same recovery: stat the
destination, then plain rename() if absent.
And for non-exclusive renames where it also fails to function not
implemented, it falls back to plain `rename`.
Error instead of silently truncating oversized `NonBlockingFileIO`
reads.
### Motivation:
A `ByteBuffer` can hold at most `UInt32.max` bytes, so a read for more
than that can never be satisfied. Today the read functions clamp the
requested `byteCount` to `Int32.max` and then read at most that many
bytes, returning a short buffer with no error and no end-of-file. That
silently breaks the documented contract that the returned `ByteBuffer`
is only shorter than `byteCount` when end-of-file is reached. It also
means a request between 2 GiB and 4 GiB returns fewer bytes than the
caller asked for.
Resolves#2591.
### Modifications:
- `read0` (both the `EventLoopFuture` and the `async` overload) now
fails with an `IOError` (`EINVAL`) when `byteCount` is larger than
`UInt32.max` instead of clamping. The guard runs before any allocation.
On 32-bit platforms `Int.max` is smaller than `UInt32.max` so the guard
is never hit there, and behaviour is unchanged.
- `readSync` now caps the size of each individual `read`/`pread` syscall
at `Int32.max` rather than capping the total `byteCount`. The OS returns
`EINVAL` for a single read larger than `Int32.max`, and the surrounding
loop already reads repeatedly until the whole request is satisfied or
end-of-file is reached, so a request up to `UInt32.max` is now read in
full.
- Added tests covering the future and async read variants for a
`byteCount` larger than a `ByteBuffer` can hold.
I went with `IOError(errnoCode: EINVAL, ...)` rather than a new
`NonBlockingFileIO.Error` case to keep this non API-breaking, matching
the existing `IOError(errnoCode: ENOTDIR, ...)` use in the same file.
Happy to switch to a typed error case if you would prefer that.
### Result:
A read that cannot fit in a `ByteBuffer` fails clearly, and reads
between 2 GiB and 4 GiB are no longer truncated. No public API changes.
`ByteBuffer` exposes `read`, `write`, and (since the peek work landed)
`peek`
variants of `MultipleIntegers`, but not the absolute-index `get`/`set`
pair that
every other integer accessor on `ByteBuffer` has. This fills that gap,
which is
what #2736 originally asked for.
The thread on #2736 settled on adding `peek*` first so that the common
"look without consuming" use case has a non-mutating, index-free
spelling, and
that is now in place. `get`/`set` remain useful for the niche cases that
genuinely need to address an arbitrary index, so this completes the set
of four
for `MultipleIntegers` to match `getInteger`/`setInteger`.
Both methods are generated from `dev/generate-bytebuffer-multi-int.sh`,
the same
script that produces the read/write/peek variants, so they stay in
lockstep with
the rest of the file across all arities (2 through 15):
- `getMultipleIntegers(at:endianness:as:)` reads at an explicit index
without
moving the reader index and returns `nil` when the requested bytes are
not
readable, exactly like `getInteger(at:)`.
- `setMultipleIntegers(_:at:endianness:as:)` writes at an explicit index
without
moving the writer index and returns the number of bytes written, exactly
like
`setInteger(_:at:)`.
The new tests mirror the existing read/write and peek tests: a
round-trip across
both endiannesses, a check that the bytes written by `set` are
byte-for-byte
identical to `writeMultipleIntegers`, coverage of every arity, a check
that
neither method moves the reader or writer index, and the out-of-bounds /
before-reader-index cases that must return `nil`.
Resolves#2736
RFC 6455 §5.2 specifies that when the payload length indicator byte is
127, the following 8 bytes hold a 64-bit unsigned integer and the most
significant bit of that integer must be 0. The maximum legal value is
therefore 0x7FFFFFFFFFFFFFFF, which equals Int.max on all 64-bit
platforms Swift supports.
WSParser.parseStep read the raw UInt64 and passed it directly to Int()
without a bounds check. Swift's Int initializer performs a checked
conversion and traps on overflow, so any remote peer that sends a single
WebSocket frame with the MSB of the 8-byte length set will cause a fatal
error in the receiving process. No authentication is required; the frame
is processed before any application handler runs.
The fix adds a guard that rejects the frame with
NIOWebSocketError.invalidFrameLength before the conversion, which is the
same error path used for frames that exceed maxFrameSize. The call site
in decode() is updated to propagate the throw.
A regression test covers the exact byte sequence that previously caused
the fatal trap.
Co-authored-by: g0w6y <g0w6y@users.noreply.github.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
ByteBuffer.readInlineArray reads each element through getInteger(at:).
The index parameter of getInteger(at:) is an absolute index into the
buffer, the same one readInteger passes self.readerIndex into. The loop
in readInlineArray instead passed stride * index, which starts at zero
and never accounts for the reader index.
As long as the buffer has a reader index of zero this absolute index
lines up with the bytes the caller expects, which is why the current
tests pass: they all read from a freshly written buffer. On any buffer
whose reader index has already moved (the normal case once some bytes
have been consumed, for example reading a length prefix before the
array), getInteger(at:) is given an index below the reader index.
rangeWithinReadableBytes rejects it, getInteger returns nil, and the
force-unwrap on the result traps. So a public read API crashes the
process on entirely valid input.
The fix snapshots the reader index before building the array and offsets
each element index by it, so getInteger(at:) gets the correct absolute
index. The multiplication stays bounded by bytesRequired as before, and
adding the reader index cannot overflow because the result stays within
the writer index.
I added a regression test that writes a short prefix, reads it off so
the reader index is non-zero, then reads an InlineArray and checks both
the element values and the resulting reader index. It traps before this
change and passes after it. The three existing InlineArray tests, the
full ByteBufferTest suite (275 tests), and ByteBufferSpanTests all still
pass.
Reopening the change from #3604, which I closed inadvertently. The
original branch and fork were deleted, so this is a fresh PR with the
identical commit.
Don't fatalError in
NIOTypedHTTPServerUpgraderStateMachine.findingUpgraderCompleted` when
the state is `.finished`.
### Motivation:
There is a race where the connection can be closed and the
NIOTypedHTTPServerUpgraderHandler can be removed setting the state to
`.finished` while we are still finding upgraders. And then when
`findingUpgraderCompleted` gets called it would fatalError.
### Modifications:
- Return `nil` as an action if the state is `.finished` when
`findingUpgraderCompleted` is called.
- Added a new set of tests which test the
`NIOTypedHTTPServerUpgraderStateMachine` directly instead of relying on
`HTTPServerUpgraderTests`. I used Swift Testing for these, not sure what
NIO policy on new tests are?
### Result:
No more crashes and better testing for
NIOTypedHTTPServerUpgraderStateMachine
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
* External callers of `macos_benchmarks.yml` (e.g. swift-log) currently
invoke the reusable workflow once per benchmark package, paying
self-hosted macOS runner-recycling cost for each invocation.
### Modifications
* Add a new `benchmark_package_paths` input to
`.github/workflows/macos_benchmarks.yml` and mark the singular
`benchmark_package_path` as deprecated. The run step forwards both
inputs straight to the script via `BENCHMARK_PACKAGE_PATH` and
`BENCHMARK_PACKAGE_PATHS` environment variables; the workflow itself
does no path parsing.
* Teach `scripts/check_benchmark_thresholds.sh` to accept
`BENCHMARK_PACKAGE_PATHS` as either a JSON array of strings
(auto-detected by a leading `[`, requires `jq`) or a newline-separated
list, falling back to the legacy `BENCHMARK_PACKAGE_PATH` when unset or
when the JSON form is an empty array.
* The script now loops over the resolved package list, wraps each
iteration in a GitHub Actions `::group::`, and emits an `::error::`
summary listing failed packages at the end, exiting non-zero if any
failed.
### Result
* A single workflow invocation runs all listed packages serially on each
Swift/Xcode runner, paying runner-recycling cost once per Swift version
instead of once per (version x package).
* Existing single-package callers keep working unchanged.
* Adopters of the script in other contexts (e.g. the Linux
`benchmarks.yml`) can pick up multi-package support by passing
`BENCHMARK_PACKAGE_PATHS` without reimplementing parsing or
failure-collection logic.
An example of this working https://github.com/apple/swift-log/pull/466
### Motivation
We want our tests to pass in reasonable time.
### Changes
- Disable test
`ByteBufferCrashTests.setBytesWithoutContigiousStorageMoreThanUInt32maxBytes`
- Do not initialize data in `ByteBufferCrashTests.
takingOwnershipOfPointerThatsToLarge`
### Result
Tests are faster again.
Add configurable HTTP/1 decoder parsing limits
### Motivation:
The HTTP/1 decoder previously enforced a single hardcoded limit (80 KB per header field) and placed no cap on the total header-block size or the number of header fields per message. That made resource use unpredictable on requests with very many or very large headers, and there was no way for users to tune the limits for their workload.
### Modifications:
- Introduce a new public `NIOHTTPDecoderLimitConfiguration` exposing three parsing limits:
- maxHeaderFieldSize — maximum size of a single header field (name + value). Default: 80 KB.
- maxHeaderListSize — maximum total bytes of all header field names and values combined per message. Default: 2 MB.
- maxHeaderFieldCount — maximum number of header fields per message, including trailers. Default: 256.
- Plumb the configuration through `HTTPDecoder` / `HTTPRequestDecoder` / `HTTPResponseDecoder` initializers. The existing initializers continue to work unchanged via convenience overloads that fall back to
default limits.
- Expose the configuration on `NIOUpgradableHTTPServerPipelineConfiguration` and `NIOUpgradableHTTPClientPipelineConfiguration` so users of the typed pipeline setup can override the defaults.
- Track per-message totals in `BetterHTTPParser` and reject with `HTTPParserError.headerOverflow` when a limit is exceeded; counters reset at each new message so HTTP/1 pipelined connections behave
correctly.
- Add tests covering the success and error paths for each limit, the default behaviors, and that trailer fields count toward the field-count cap.
### Result:
Users can configure the HTTP/1 decoder's per-field-size, total-list-size, and field-count limits. Existing call sites continue to compile and run unchanged, now with bounded defaults across all three dimensions instead of just one.
## Summary
Trivial typo fix in the Swift Concurrency user-facing documentation.
In
[`Sources/NIOCore/Docs.docc/swift-concurrency.md`](https://github.com/apple/swift-nio/blob/main/Sources/NIOCore/Docs.docc/swift-concurrency.md),
the NIOAsyncChannel websocket-upgrade walkthrough reads:
> switch over the the `upgradeResult`. Importantly, we have to `await`
the
Drops the duplicate "the".
## Test plan
- [x] `grep -rEn '\b(the the|of of|in in|and and|that that|is is|to
to)\b' --include='*.swift' --include='*.md' Sources` — exit 1 after the
fix (was the only hit before).
## Scope
One-character change in one Markdown file. No code, no behavior, no API.
Co-authored-by: Cory Benfield <lukasa@apple.com>
The `getifaddrs` is only available on Android API 24+. So, to make
`swift-nio` compile on API 23, we need to add `@available` annotations
to the functions that use it. Which are just the two interface enumerate
functions.
### Result:
`swift-nio` can be compiled for Android 23.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
When connecting to services with multiple DNS records (e.g. Kubernetes
headless services), getaddrinfo returns addresses in a deterministic
order, causing all connections to go to the same backend. SwiftNIO now
provides a RandomizedDNSResolver that shuffles results.
### Modifications:
Add a dnsResolver property to HTTPClient.Configuration with two options:
.system (default, current behavior) and randomized (uses NIO's
RandomizedDNSResolver to shuffle DNS results). Apply the resolver to
ClientBootstrap during connection creation.
### Result:
Users can opt into randomized DNS resolution by setting
config.dnsResolver = .randomized, enabling load distribution across
multiple backend IPs while preserving the default behavior.
---------
Co-authored-by: Pavan sai kumar alladi <p_alladi@apple.com>
### Motivation
* The versioned `linux_nightly_6_1_enabled` input was deprecated a while
back in favour of `linux_nightly_next_enabled`, but the workflows still
combined the two with `||`/`&&` to keep the old name working.
* Now that callers have migrated, the shim is unnecessary complexity.
### Modifications
* In `unit_tests.yml`, `cxx_interop.yml`, and `benchmarks.yml`, replace
`inputs.linux_nightly_6_1_enabled || inputs.linux_nightly_next_enabled`
(and the `&&` variants) with just `inputs.linux_nightly_next_enabled`.
### Result
* `MATRIX_LINUX_NIGHTLY_NEXT_ENABLED` is driven solely by
`linux_nightly_next_enabled`.
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.
### Motivation:
The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.
The current loop looks like this:
```swift
// Successfully made a directory, construct its children.
while let subdirectory = droppedComponents.popLast() {
path.append(subdirectory)
switch Syscall.mkdir(at: path, permissions: permissions) {
case .success:
continue
case let .failure(errno):
return .failure(.mkdir(errno: errno, path: path, location: .here()))
}
}
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
### Modifications:
The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:
If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.
### Result:
Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.
Co-authored-by: David Stern <d_stern@apple.com>
Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length.
### Motivation:
There are already some APIs for writing length-prefixed strings and
bytes with a custom strategy for encoding the length, but there weren't
helpers to read them.
### Modifications:
- Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length
- Add tests for the new APIs
- Fix DocC comments and improve the related article
### Result:
New APIs are added for reading length-prefixed strings and bytes with a
custom strategy for encoding the length.
### Motivation
* Xcode 15.4, 16.0, 16.1, 16.2, and 26 beta were already deprecated
and defaulted to `false` with no callers enabling them — redundant code.
* Xcode 16.3, 16.4, 26.0, and 26.1 will soon be uninstalled from the
runners. Their inputs are kept so downstream callers don't break, but
they should no longer produce any matrix entries.
### Modifications
* Remove input declarations, shell variables, matrix construction
blocks, and environment variable mappings for 15.4/16.0/16.1/16.2/26
beta entirely.
* Remove the matrix logic for 16.3/16.4/26.0/26.1 but retain the input
declarations as no-ops, with descriptions communicating they have no
effect.
### Result
* Less dead code in the shared workflow.
* Callers still passing `xcode_16_3` through `xcode_26_1` inputs get no
error but also no job — a graceful no-op while they migrate to
`swift_*` inputs.
### Motivation
* The `swift_*` inputs request Xcodes by Swift version with symlinks on
the runners owning the mapping. This more directly expresses the
library support window.
* All callers should migrate to `swift_6_1/6_2/6_3_enabled` instead of
specifying Xcode versions directly.
### Modifications
* Default `xcode_16_3/16_4/26_0/26_1/26_2_enabled` to `false` and mark
their descriptions as deprecated.
* Default `swift_6_1/6_2/6_3_enabled` to `true`.
### Result
* Repos still passing `xcode_*_enabled: true` explicitly continue to
work until they migrate.
This PR is a step towards having full support for FreeBSD in SwiftNIO.
It builds on #3494 to enable full compilation of the NIOCore target.
### Motivation:
Currently, SwiftNIO doesn't not compile on FreeBSD. This PR ensures that
at least the **NIOCore** module compiles correctly on FreeBSD.
### Modifications:
* Make `swift build --target NIOCore` work on FreeBSD.
### Result:
Using the available Swift FreeBSD x86_64 toolchain, it is now possible
to run `swift build --target NIOCore` successfully.
Strip Transfer-Encoding when Content-Length is present in HTTPEncoder
### Motivation
When `correctlyFrameTransportHeaders()` detected a `Content-Length`
header, it returned `.contentLength` without removing any existing
`Transfer-Encoding` header.
### Changes
- Remove `Transfer-Encoding` header, if a `Content-Length` header is
present
### Result
NIO sends either a `Content-Length` header or a `Transfer-Encoding`
header, but not both.
### Motivation:
Internally, `FTSInfo` always casted up to `CInt` from `UInt16` but for
some reason it only accepted `UInt16`. Let's add a `CInt` constructor
too.
### Modifications:
- Make internal `FTSInfo` constructible from `CInt` and `UInt16`.
### Result:
- Slightly better platform compatibility
- Possibly fewer casts
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.
```