Commit Graph
2945 Commits
Author SHA1 Message Date
Vladimir Kukushkin 206dacff8e Do not run the matrix if there is no macOS versions picked for benchmarks (#3450)
After the recent addition of macOS-based benchmarks, the `main` workflow
has been failing with:

```
Error when evaluating 'strategy' for job 'benchmarks-macos'. apple/swift-nio/.github/workflows/benchmarks.yml@main (Line: 239, Col: 15): Matrix vector 'config' does not contain any values
```

This happens because `swift-nio` does not set any `_enabled` flag for
any version of Xcode to run the benchmarks.

An example of a failed run:
https://github.com/apple/swift-nio/actions/runs/19479529118

### Motivation:

Scheduled jobs should not fail.

### Modifications:

Added a condition for running macOS benchmarks matrix generation job.

### Result:

Jobs should not fail without any Xcode versions picked for running
benchmarks.

An example of a run with macos-matrix job skipped:
https://github.com/apple/swift-nio/actions/runs/19482328681/job/55758816398
An example of a run with a opt-in macOS Benchmarks:
https://github.com/apple/swift-nio/actions/runs/19484086327/job/55762298924
2025-11-19 11:48:44 +00:00
Vladimir Kukushkin 6dae9889c4 Run benchmarks in CI on macOS in addition to linux (#3444)
Run benchmarks on macOS in addition to Linux.

### Motivation:

1. macOS and Linux benchmark yield different results and we would like
to rack both of them.
2. default Linux GitHub workers do not provide access to PMU, which is
necessary for instructions metric benchmarking

### Modifications:

- `benchmarks.yml` workflow support running benchmarks on self-hosted
macOS runners

### Result:

Benchmarks are running on both linux and macOS runners. An example of an
opt-in PR running just one Xcode version:
https://github.com/apple/swift-nio/actions/runs/19468002318/job/55707591945.

An example of an opt-in PR and thresholds expectations check failed:
https://github.com/apple/swift-nio/actions/runs/19468236909/job/55708359111

I've been running `swift-nio` benchmarks on macOS runners and it is much
less stable than Linux for allocations and context switches. I suggest
we make this an opt-in feature and take in only for instructions count
benchmarks, for example upcoming to the `swift-log`. This also makes it
less stressful for macOS runners pool.
2025-11-18 14:56:53 +00:00
Max Desiatov 6e02c7a246 Make ByteBuffer.writeBytes(_: RawSpan) broadly available (#3447)
`RawSpan` can be back-deployed, so availability can become consistent
with similar methods like this one
https://github.com/apple/swift-nio/blob/56724a2b6d8e2aed1b2c5f23865b9ea5c43f9977/Sources/NIOCore/ByteBuffer-aux.swift#L1020C3-L1024C38
2.90.0
2025-11-17 09:22:35 +00:00
Rick Newton-Rogers 56724a2b6d NIOAsyncTestingChannel local/remote addrs on EmbeddedChannelCore (#3442)
### Motivation:

`NIOAsyncTestingChannel` stored its `localAddress` and `remoteAddress`
in a locked storage on itself for thread safety, however in doing so
left us open to bugs because a handler grabbing the addresses of the
context had no visibility of the values.

### Modifications:

Reach into `EmbeddedChannelCore` for the addresses instead of storing
them on the `NIOAsyncTestinghannel`. I also considered a delegate
approach where the `EmbeddedChannelCore` could offload the
responsibility for storing the values back to the
`NIOAsyncTestingChannel` but it was complicated and of questionable
value.

### Result:

* The correct address values are seen no matter how they are obtained.
* We probably take a performance hit locking the values in this way but
this is testing code so probably not the end of the world.
2.89.0
2025-11-11 15:08:15 +00:00
Rick Newton-RogersandCory Benfield 2dbd1bf60b A script for updating Integration Tests thresholds from CI (#3443)
### Motivation:

We have a way to update Benchmarks thresholds from CI logs but not for
the older Integration Tests.

### Modifications:

A new script which pulls integration test logs and uses our existing
parsing script to pull out updated values.

### Result:

Easier threshold updates.


```
❯ ./dev/update-integration-test-thresholds.sh
Usage: ./dev/update-integration-test-thresholds.sh <url>
   or: URL=<url> ./dev/update-integration-test-thresholds.sh

Example:
  ./dev/update-integration-test-thresholds.sh https://github.com/apple/swift-nio/pull/3442
  ./dev/update-integration-test-thresholds.sh https://github.com/apple/swift-nio/actions/runs/19234929677
  URL=https://github.com/apple/swift-nio/pull/3442 ./dev/update-integration-test-thresholds.sh
```

```
❯ ./dev/update-integration-test-thresholds.sh 'https://github.com/apple/swift-nio/actions/runs/19234929677/job/54982236271?pr=3442'
** Processing run in apple/swift-nio
** Fetching integration test checks from workflow run 19234929677
** Pulling logs for Swift nightly-main (job 54982236243)
** Updated IntegrationTests/tests_04_performance/Thresholds/nightly-main.json
** Pulling logs for Swift 6.2 (job 54982236259)
** Updated IntegrationTests/tests_04_performance/Thresholds/6.2.json
** Pulling logs for Swift nightly-next (job 54982236267)
** Updated IntegrationTests/tests_04_performance/Thresholds/nightly-next.json
** Pulling logs for Swift 6.0 (job 54982236271)
** Updated IntegrationTests/tests_04_performance/Thresholds/6.0.json
** Pulling logs for Swift 6.1 (job 54982236345)
** Updated IntegrationTests/tests_04_performance/Thresholds/6.1.json
** Done! Updated 5 threshold file(s)
```

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-11-10 22:36:54 +00:00
Fabian Fett 45b463c5eb Quality of Life: Add NIOLoopBoundBox.withValue (#3385)
When having a state machine inside the `NIOLoopBoundBox` we currently
check the EL when reading and writing. This is unnecessary. Because of
this, this PR introduces a new `withValue` method, that allows users to read and
write the value inside the NIOLoopBoundBox while only paying the cost
for the EL check once.
2025-11-10 10:08:50 -05:00
Cory Benfield 83d438650a Document the GSO/GRO APIs (#3440) 2025-11-10 08:11:51 +00:00
Cory Benfield 5741df9cc4 Enable per-message GRO on Linux (#3439)
Motivation:

NIO has existing GRO support. This GRO support is applied at Channel
scope, which makes it somewhat less than ideal, as it forces the
datagram sizes to be accessed using socket options. In real applications
this is less desirable than being able to do this on a per-superbuffer
context.

Linux supports this already by using recvmsg/recvmmsg control data. We
just need to wire this up in NIO. We can re-use the existing metadata
fields on AddressedEnvelope.

Modifications:

- Add a new ChannelOption to extra metadata
- Reject setting this option on non-Linux devices.
- On Linux, use this to load the control data.
- Added new tests that validate the behaviour is correct.

Result:

Enable per-message GRO.
2025-11-07 13:24:30 -05:00
Cory Benfield a7da98c3ac Enable per-message GSO on Linux (#3436)
Motivation:

NIO has existing GSO support. This GSO support is applied at Channel
scope, which makes it somewhat less than ideal, as it forces the
datagram sizes to be known statically ahead of time. In real
applications this is less common than being able to do this on a
per-superbuffer
context.

Linux supports this already by using sendmsg/sendmmsg control data. We
just need to wire this up in NIO.

An extension to this is that we can also do per-message GRO in Linux.
I'll tackle this in a later patch to keep the diffs small.

Modifications:

- Adding a new field on AddressedEnvelope Metadata.
- Reject setting this field on non-Linux devices.
- On Linux, use this to set the control data.
- Added new tests that validate the behaviour is correct.

Result:

Enable per-message GSO.
2025-11-07 08:34:33 +00:00
Cory Benfield 88dc99031f Add some spans to ByteBuffer (#3371)
Motivation:

Users would like to be able to access the underlying memory of a
ByteBuffer, as evidenced by the plethora of `withUnsafe*` methods that
ByteBuffer has. As Swift 6.2 has introduced some initial APIs for safe
memory access to underlying storage, we should offer similar APIs on
ByteBuffer to enable users to get safer access to that storage.

For now, the obvious APIs to be able to supplement are:

- withUnsafeReadableBytes
- withUnsafeMutableReadableBytes
- writeWithUnsafeMutableWritableBytes

We can also offer some new APIs to allow initializing a buffer directly
from an OutputSpan.

Note that we can only do this because the Language Steering Group has
pinky promised that they will not break the "Lifetimes" experimental
feature: see

https://forums.swift.org/t/experimental-support-for-lifetime-dependencies-in-swift-6-2-and-beyond/78638
for more details. We are taking them at their word, and so we are
enabling that feature.

Modifications:

Many new methods and tests.

Result:

Safer access.
2025-11-06 11:54:06 -05:00
Rick Newton-Rogers 74e77dad61 Switch test targets in macos_tests.yml (#3437)
### Motivation:

The Watch Series 10 and iPhone 16 Pro simulators haven't been working
for some time

### Modifications:

Swap the iOS and macOS test targets

### Result:

Testing against simulators should work

Here is an example of the change in action. The new targets can be
discovered but one of the Xcodes then hits an unrelated issue
https://github.com/apple/swift-nio/actions/runs/19130486127/job/54672071880?pr=3437
2025-11-06 13:33:17 +00:00
Rick Newton-Rogers aa3bf227dd Add Xcode 26.1 to macOS CI (#3438)
### Motivation:

Xcode 26.1 has been released so our support window slides forwards.

### Modifications:

* Add Xcode 26.1 job
* Log Xcode and swift versions for debugging purposes

### Result:

Current Xcode support window, easier debugging.

**NOTE:** we will soon disable Xcode 16.3 by default but will give
adopters time to update their PR status checks first

An example of this in action
https://github.com/apple/swift-nio/actions/runs/19129667587/job/54667112541?pr=3438
2025-11-06 11:38:40 +00:00
Cory Benfield fd7c6af4f0 Replace rethrows with typed throws in ByteBuffer (#3372)
Motivation:

Users who want to use typed throws would benefit from us propagating the
thrown error type through our APIs. Most of our surface doesn't allow
for that because it relies on standard library APIs that haven't been
updated, but we can do it for ByteBuffer which is entirely ours.

Modifications:

- Adopt typed rethrows in ByteBuffer

Result:

Users have an easier time working with ByteBuffer
2025-11-05 16:14:30 -05:00
scottmarchant cc38f7abcf feat: Enable NIOFoundationCompat to compile using Swift for WebAssembly. Fix NIOCore WASI compilation issue. (#3422)
Fix Swift for WebAssembly compilation in NIOFoundationCompat.

### Motivation:

NIO is a common dependency, and it is important to enable compiling NIO
using Swift for WebAssembly. This PR fixes compilation for
NIOFoundationCompat.

### Modifications:

- Fix NIOFoundationCompat compilation

### Result:

With these changes, the following build commands succeed: ✅ 

```
swift build --swift-sdk wasm32-unknown-wasip1-threads --target NIOCore
swift build --swift-sdk wasm32-unknown-wasip1-threads --target NIOFoundationCompat
```

### Context:

This PR is [part of a larger effort by
PassiveLogic](https://github.com/PassiveLogic/swift-web-examples/issues/1)
to improve Swift for WebAssembly support
2025-11-05 19:55:48 +00:00
George Barnett d963335ba0 Fail on early errors in parallel copy (#3435)
Motivation:

'copyItem' can be used to copy files/directories from a source to a
destination address and fails if the destination already exists. The
parallel version of it can wedge if a directory is being copied and the
directory can't be created at the destination path (for example, if a
file already exists at the destination).

The parallel copy works by feeding tasks (e.g. "copy this item from here
to there") into an async sequence and processing each task in a separate
child task within a task group. When copying directories a new directory
is created at the destination path and then each file within the source
directory is emitted as a separate item to process. Another item is sent
on the async sequence to indicate when the source directory is finished
with which may result in finishing the async sequence.

However, if creating the destination directory fails then that event
isn't sent. This results in the calling code never terminating the async
sequence and causes 'copyItem' to wedge.

Modifications:

- Use non-idempotent directory creation (copy item should fail if the
destination already exists, this was a regression introduced in
7124f096).
- Check whether to continue when a dir can't be created but always emit
the end of dir event
- If terminating when the task group hasn't reached its width limit then
check child tasks for errors

Result:

Parallel copy doesn't wedge
2025-11-05 08:47:05 +00:00
scottmarchant e304a1a363 chore: For WASI builds only, use fatalError in all .wait() calls. Recommend using .get() instead. (#3421)
Use fatalError in all .wait() calls for WASI builds only, and point
developers towards .get() instead.

### Motivation:

While working to adopt NIO in some wasm code, I've commonly ran into
issues any time code calls `.wait()` during wasm runtime. Typically the
executable either traps or crashes any time `.wait()` is called with an
ambiguous error: `Uncaught (in promise) RuntimeError: Atomics.wait
cannot be called in this context`. The error occurs because it is
forbidden to block the main thread for a wasm executable, and the
current implementation of `.wait()` blocks the calling thread.

The fix is straight forward, all calls to `.wait()` need refactor to
`.get()`, which sometimes involves some Swift Concurrency adoption (eg.
`async`) in the process. That change avoids blocking the main thread.

### Modifications:

Added `fatalError` with a descriptive error message to help developers
identify the issue easier.

### Result:

For WASI builds only, changes the trap error message `Uncaught (in
promise) RuntimeError: Atomics.wait cannot be called in this context`
into the following error message instead:

```
NIO's wait() function should not be called on WASI platforms. It will freeze or crash. Use get() instead.
```

### Alternatives considered

- We could instead conditionalize `.wait()` completely out of nio for
WASI builds, to turn runtime errors into compiler errors. That makes
detection of this issue easier, but forces a refactor and breaking
change, and somewhat precludes the possibility that WASI might support
this down the road with a future change.
- We could add a deprecation for WASI only. But long term WASI may be
able to support this blocking call, so deprecation and removal is
communicating the wrong message if the future ends up being reality.

### Context

This PR is [part of a larger effort by
PassiveLogic](https://github.com/PassiveLogic/swift-web-examples/issues/1)
to move Swift for WebAssembly support forward in a large number of
dependencies.
2025-11-03 12:50:23 -05:00
Rick Newton-Rogers fa91d790ad Generate matrix nested manifests (#3431)
Generate matrix script finds manifests in subdirs

### Motivation:

The genereate matrix script attempts to derive the minimum Swift version
supported by the package so that it doesn't run CI on versions which are
older than that supported. At the moment it can't cope with repositories
with packages in subdirectories like swift-nio-examples.

### Modifications:

The script looks for manifests in subdirectories if
`FIND_SUBDIRECTORY_MANIFESTS_ENABLED=true`. This is opt-in because by
default CI only uses the top-level manifests.

### Result:

CI should generate more appropriate jobs.

An example of this in action
https://github.com/apple/swift-nio/actions/runs/18968739126/job/54171197381?pr=3431
2025-10-31 10:36:21 +00:00
Rick Newton-Rogers 3ed0975c29 Android use static swift stdlib (#3430)
android build use swift static stdlib

### Motivation:

Android build fails and the guide says to use this flag
https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html

Recent failure - although weirdly it doesn't seem to happen every time:
```
error: link command failed with exit code 1 (use -v to see invocation)
ld.lld: error: cannot open crtbegin_dynamic.o: No such file or directory
ld.lld: error: cannot open crtend_android.o: No such file or directory
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[558/601] Linking NIOUDPEchoClient

```

### Modifications:

android build use swift static stdlib

### Result:

hopefully success - making this change locally seemed to work.

This change can be seen in action here
https://github.com/apple/swift-nio/actions/runs/18949279888/job/54110590743?pr=3430
2025-10-31 09:54:51 +00:00
Rick Newton-Rogers d373d41637 Swift SDK installation script improvements (#3429)
Swift SDK installation script improvements
  
  ### Motivation:
  
The SDK installation scripts had a few rough edges and didn't verify the
  artefacts they downloaded.
  
  ### Modifications:
  
  * Change naming to the more accurate "Swift SDK" where we can without
    breaking downstream adopters.
  * Separate Android NDK installation into its own script.
  * Avoid using `cd` when setting up Android NDK.
  * Verify checksums for SDKs and signatures for toolchains.
  * Specify/control the SDK directory.
  
  ### Result:
  
  * More accurate naming.
  * More maintainable scripts.
  * More secure downloads.

An example of this working
https://github.com/apple/swift-nio/actions/runs/18944235613/job/54090944716?pr=3429
2025-10-30 17:50:17 +01:00
Marc Prud'hommeaux a24771a4c2 Fix the Android CI workflow by adding a post-install step the configure the SDK (#3424)
Fixes the Android CI workflow

### Motivation:

The recently-added Android SDK workflow
[fails](https://github.com/apple/swift-nio/actions/runs/18718487605/job/53384086329?pr=3418)
(as mentioned at
https://github.com/apple/swift-nio/pull/3418#issue-3540969388). The
confusing error message is due to a post-install step that is needed to
download and link the Android NDK into the Swift SDK's artifactbundle.

This PR also adds a one-line fix to
[Sources/NIOPerformanceTester/main.swift](https://github.com/apple/swift-nio/compare/main...swift-android-sdk:swift-nio:main#diff-de179adbbfacb89c9533f4efd21f7f641eedc0c8642d7d650cdfc9d9278a7a55)
that gets it building for Android so the entire swift-nio package can be
built.

### Modifications:

Adds a post-install step to the SDK installation that is needed for the
Swift SDK for Android. This is the same technique used by
https://github.com/swiftlang/github-workflows/pull/172, and is described
as a necessary step in the [Android getting started
guide](https://github.com/swiftlang/swift-org-website/blob/0dc655ce267e7b6bada2a2032cc7855c3b5e19d9/documentation/articles/swift-android-getting-started.md)

### Result:

The "Android Swift SDK" CI check should now pass successfully. See an
example at
https://github.com/swift-android-sdk/swift-nio/actions/runs/18761057590/job/53525442382

### Note:

This PR will _not_ pass the Android check until it has been merged,
because it relies on being able to down the the script
https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_swift_sdk.sh
from `apple/swift-nio/main`, which will not include the Android fix
until the PR is merged. But once it is merged, the Android SDK CI should
start passing.
2.88.0
2025-10-30 10:04:17 +00:00
Zamderax ec26755611 Tests: inline TestUtils.swift in NIOHTTP1Tests to avoid broken symlink on non-symlink filesystems (#3426)
On filesystems without symlink support for Windows, the symlinked test
helper at is materialized as a plain text file containing the relative
path, which breaks compilation with errors like:
```
expressions are not allowed at the top level
cannot find 'assertNoThrowWithValue' in scope
```
This change inlines the contents, restoring the intended shared test
utilities for the NIOHTTP1 test target. This helps Windows compile the
Test target
2025-10-29 13:27:40 +00:00
Rick Newton-Rogers 52296f555a Update main.yml to refer to wasm_swift_sdk.yml (#3425)
Update main.yml to refer to wasm_swift_sdk.yml after it was recently
renamed
2025-10-27 10:30:17 +00:00
Max Desiatov 603edbaa34 Fix naming in Wasm Swift SDK workflow (#3423)
"SDK" and "Swift SDK" are different concepts, compare `swift build
--help | grep sdk` output, where we have separate CLI options for these
with different meaning:
* SDK is used by Clang and Xcode, with Swift Driver also implementing
the `-sdk` flag. There's no specification for how Clang SDKs are
distributed, thus we don't distribute any Wasm SDK as such.
* Swift SDK is purely a SwiftPM feature, which uses artifact bundles for
distribution. We do distribute Swift SDKs for Wasm.

Same for static Linux BTW, so a separate PR is needed to clean up that
confusion for Musl-related CI workflows.

Additionally, Wasm is not an acronym. Per the Wasm spec
https://webassembly.github.io/spec/core/intro/introduction.html#wasm:
> A contraction of “WebAssembly”, not an acronym, hence not using
all-caps.
2025-10-24 17:06:41 +01:00
Rick Newton-Rogers 102fa28e6b Env var no keys (#3420)
Fix env var support

### Motivation:

The new WASM and Android SDK workflows report an error in CI
```
jq: error (at <stdin>:1): string ("\"$env_var...) has no keys
```

### Modifications:

Construct the matrix separately and include the env var variable.

### Result:

No more issue in logs, env vars are applied

See this in action here:
https://github.com/apple/swift-nio/actions/runs/18719810714/job/53388814243?pr=3420
2025-10-23 09:42:42 +01:00
Rick Newton-Rogers 412a870a93 Android SDK Workflow (#3418)
### Motivation:

Android SDKs now exist and testing is good.

### Modifications:

Add an Android GitHub Actions workflow using the latest nightly image
and enable it in NIO targetting NIOCore (matching WASM testing).

### Result:

More reusable workflows and more test coverage for NIO

See this in action here (the CI job works but NIOCore fails to build):
https://github.com/apple/swift-nio/actions/runs/18718487605/job/53384086329?pr=3418
2025-10-22 15:00:34 +01:00
e46b29f349 WASM SDK GitHub Actions workflows use NIO matrix (#3417)
WASM SDK GitHub Actions workflows use NIO matrix rather than the
swiftlang one

### Motivation:

Using the NIO one is more in line with the surrounding workflows and
surfaces a simpler UI (possible jobs which aren't run don't appear in
the UI)

### Modifications:

Pull in changes from https://github.com/apple/swift-nio/pull/3159 and
add in the ability to specify environment variables and other build
arguments in line with the static Linux SDK workflow.

### Result:

More regularity, simpler checks UI.

See this in action here:
https://github.com/apple/swift-nio/actions/runs/18717131164/job/53379323803?pr=3417

---------

Co-authored-by: Yuta Saito <kateinoigakukun@gmail.com>
Co-authored-by: Max Desiatov <m_desiatov@apple.com>
2025-10-22 14:22:24 +01:00
Rick Newton-Rogers 843c8cf264 Don't generate matrix jobs for Swift versions which aren't supported by the package. (#3415)
Don't generate matrix jobs for Swift versions which aren't supported by
the package.

### Motivation:

Matrix workflows should not generate jobs for Swift versions < tools
version, doing so wastes compute and adds noise.

This means that:
- New repos don’t need to manually opt-out of old Swift versions
- Repos which have dropped an old Swift version (during a migration
window) won’t have failing tests until it’s turned off centrally.

### Modifications:

- The generate script now looks for `Package.swift` and
`Package@swift-*.swift` files and uses the lowest tools version in any
found file to determine the minimum supported Swift version
- Any Swift version lower than the minimum is disregarded and no jobs
are generated for it
- A new parameter is added to the workflows which allows the minimum
Swift version to be set manually (`minimum_swift_version`)

### Result:

By default in this and downstream packages we don't generate matrix jobs
for Swift versions which aren't supported by the package.


An example of this working:
https://github.com/apple/swift-nio/actions/runs/18711362977/job/53360387720?pr=3415
2025-10-22 11:40:01 +01:00
Mahdi Bahrami 0469372396 Implement AsyncSequence/splitLines() (#3411)
~~Implement `AsyncSequence/split()` functions similar to
`String/split()` functions in std-lib.~~
Implement `AsyncSequence/splitLines()` functions similar to
`String/split(whereSeparator: \.isNewline)` in std-lib.

### Motivation:

~~Provide an easy way for users to split the data incoming from an async
sequence, using their preferred separator.~~
Provide an easy way for users to split the data incoming from an async
sequence, on new lines.

### Modifications:

Add `internal SplitMessageDecoder: NIOSingleStepByteToMessageDecoder`.
Add `public NIOSplitLinesMessageDecoder:
NIOSingleStepByteToMessageDecoder`.
Add `public
AsyncSequence/splitLines(omittingEmptySubsequences:maximumBufferSize) ->
AsyncSeq<ByteBuffer>`.
Add `public
AsyncSequence/splitUTF8Lines(omittingEmptySubsequences:maximumBufferSize)
-> AsyncSeq<String>`.

### Result:

Users can easily split the data.
2025-10-21 16:13:43 +01:00
Mahdi Bahrami f2ad915d57 [perf] Manually implement lastIndex(where:) in ByteBufferView (#3413)
### Motivation:

`ByteBuffer.lastIndex(where:)` is of suboptimal performance.
The default Collection implementations don't go through any "magic
underscored" functions like `_customIndexOfEquatableElement`.

### Modifications:

Manually implement `lastIndex(where:)`.

### Result:

Basically free performance boost. 2x+ boost even for not big buffers of
a few hundred bytes.

This function is currently used in
`ByteBufferView.trim(limitingElements:)`.

I have no immediate use case for this function, but it's still an issue
worth addressing.
2025-10-21 14:02:55 +01:00
Hamza Hassanain 7124f0963a feat(NIOFileSystem): Add idempotent directory creation behavior (#3404) (#3410)
The createDirectory function will succeed without error if the target
directory already exists.

###  Motivation

This change addresses issue #3404. Currently,
`fileSystem.createDirectory` fails if the target directory already
exists, forcing users to write boilerplate try/catch blocks to handle
this common and expected case.

The goal is to make this function's behavior idempotent.

### Modifications

To achieve this, I've made the following changes:

**(Implementation)** A new private helper function,
`_handleCreateDirectoryFileExists`, was introduced. This function is
responsible for:

1. Performing a `stat` call on the path that failed.
2. Checking if the existing item is a directory (`S_IFDIR`).
3. Returning a success result if it's a directory, or re-throwing the
original `.fileExists` error if it's a file or another type of entity.

**(Logic)** The core `_createDirectory` function was updated to call
this new helper function whenever `Syscall.mkdir` fails with an `EEXIST`
(`.fileExists`) error. This check is applied in both internal loops to
correctly handle cases where either an intermediate directory or the
final target directory already exists.

### Result
With this change, users can now call the function
`fileSystem.createDirectory` and the operation will succeed even if the
directory is already present, leading to cleaner and more predictable
code.
2025-10-20 15:49:26 +01:00
Mahdi Bahrami 767ea9ee09 [perf] Manually implement firstIndex(where:) in ByteBufferView (#3412)
### Motivation:

`ByteBuffer.firsIndex` is of suboptimal performance.
The default Collection implementations don't go through any "magic
underscored" functions like `_customIndexOfEquatableElement`.

### Modifications:

Manually implement `firstIndex(where:)`.

### Result:

Basically free performance boost. 2x+ boost even for not big buffers of
a few hundred bytes.

There are some usage of this function in `BufferedReader`. Those will
become much faster.
Also this function is used in `ByteBufferView.trim(limitingElements:)`.

Also makes #3411 stuff faster. See:
https://github.com/apple/swift-nio/pull/3411#discussion_r2436260691
2025-10-17 07:15:44 +00:00
Mahdi Bahrami 86c5ead5dd Introduce NIODecodedAsyncSequence for easy decoding of async sequences (#3407)
Previous PR: #3405 

Add an API on top of `AsyncSequence<ByteBuffer>` which can dynamically
decode values.
~~Add an API on top of the new `AsyncSequence<ByteBuffer>` APIs which
splits the file based on its content.~~

### Motivation:

Provides a nice API to decode files, instead of users having to go
though manually handling `BufferedReader.read(while:)`.
I struggled with this, as documented in
https://swift-open-source.slack.com/archives/C9MMT6VGB/p1760115481607159

### Modifications:

Add `NIODecodedAsyncSequence` + functions on `AsyncSequence<ByteBuffer>`
to create such a sequence.
~~Add `NIOSplitMessageDecoder` + stdlib-like functions on
`AsyncSequence<ByteBuffer>` to create such a sequence.~~

### Result:

Users can decode an async sequence of `ByteBuffer`s easier.
~~Users can easily split files based on their content.~~

### Checklist

See this comment for a checklist of the remaining things to do:
https://github.com/apple/swift-nio/pull/3407#issuecomment-3403382404
2025-10-16 09:49:55 +00:00
Cory Benfield cdf721f4d6 Avoid zombie pipe channels when receiving writeEOF (#3408)
Motivation

In rare cases where the inbound side of a pipe channel is already closed
(either because it was never open or because it was closed during use),
we can get into trouble if the reader drops the read side of our write
pipe. In that context, the Linux kernel will deliver an EPOLLHUP, but
while we'll close the FD we'll let the channel hang out as a zombie.
This is, obviously, suboptimal.

Modifications

In writeEOF, we check whether the read side is already closed. If it is,
we trigger a close internally to shut the channel down. Added a test for
this as needed, and modified an existing test that would now trip over
this behaviour. Also added a new test for the reverse case to ensure we
don't end up with zombies there (we don't).

Results

No zombie channels.
2025-10-15 10:16:39 +01:00
Rick Newton-Rogers 4e8f4b1c9a Enable Xcode beta by default in macos_tests.yml (#3401)
26.1 Beta 2 has been released so we have an Xcode beta to be testing, we
should enable it by default again. It was previously disabled under the
impression that there was no current beta.
2.87.0
2025-10-09 16:31:10 +01:00
Melissa Kilby dee7095f8d set explicit permissions for GitHub workflows - all remaining workflows (#3396)
See https://github.com/apple/swift-nio/issues/3386

Note: I consistently placed the permissions key at the top (slightly
corrected recent PRs).

CC @rnro

Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-07 11:31:35 +01:00
Cory Benfield 97c3f28ad0 Fix flakiness in testWithConfiguredStreamSocket (#3399)
Motivation:

This test occasionally fails in our ongoing continuous CI solution.
Flaky tests are bad, and we should aim not to have them, so let's fix
it.

My diagnosis of the most likely race here (which leads to
`alreadyClosed`) being thrown _somewhere_ from this code is that the
client channel got closed unexpectedly. This would happen if an unusual
series of events occurs:

1. The client connection succeeds and the channel starts up
2. The server close then goes through and the server channel is closed
_before_ it actually accepts the connection.
3. This causes the client connection to be reset.
4. The client channel observes this and handles that close.
5. We then close the client from the outside.

Modifications:

Add a ConditionLock we can use to wait for a connection to be
established.
Make the use of this ConditionLock resilient to weird test behaviour by
always using timeouts for blocking operations.

Result:

Less flaky tests.
2025-10-06 14:53:44 +01:00
Fabian FettandCory Benfield a3ed8e10ab Drop Swift 5.10 (#3393)
This PR drops Swift 5.10 and enables Swift 6 language mode.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-10-06 10:58:33 +01:00
Cory Benfield 2143eb91f1 Tweak test availability to avoid segfaults (#3397)
Motivation

Availability guards on test functions don't work the way we'd want them
to: in particular, xctest still ends up calling these functions even on
platforms that are less available than the functions in question. We
need to move these to checks in in the function themselves.

Modifications

Replace @available with guard available

Result

No more segfaults in tests.
2025-10-04 09:30:21 +01:00
Melissa KilbyandRick Newton-Rogers 2b3140a59c update: set explicit permissions for GitHub workflows - unit-tests (#3388)
See https://github.com/apple/swift-nio/issues/3386
CC @FranzBusch @ktoso @Lukasa

Signed-off-by: Melissa Kilby <mkilby@apple.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2025-10-02 14:27:33 +00:00
Melissa Kilby 0c2869d9a2 update: set explicit permissions for GitHub workflows - execute-matri… (#3391)
See https://github.com/apple/swift-nio/issues/3386
CC @FranzBusch @ktoso @Lukasa

Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-02 13:50:44 +00:00
Melissa Kilby 8c359a17d8 update: set explicit permissions for GitHub workflows - release-builds (#3390)
See https://github.com/apple/swift-nio/issues/3386
CC @FranzBusch @ktoso @Lukasa

Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-02 11:51:15 +00:00
Melissa KilbyandRick Newton-Rogers f5a2e752e1 update: set explicit permissions for GitHub workflows - benchmarks (#3389)
See https://github.com/apple/swift-nio/issues/3386
CC @FranzBusch @ktoso @Lukasa

Signed-off-by: Melissa Kilby <mkilby@apple.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2025-10-02 11:27:33 +00:00
Melissa Kilby 662d3ddd84 update: set explicit permissions for GitHub workflows - cxx-interop (#3387)
See https://github.com/apple/swift-nio/issues/3386
CC @FranzBusch @ktoso @Lukasa

Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-02 12:00:17 +01:00
Mahdi BahramiandCory Benfield 2e22c89844 Add InlineArray helpers to ByteBuffer (#3252)
### Motivation:

Useful for parsing packets, for example `ipv4: InlineArray<4, UInt8>`
and `ipv6: InlineArray<16, UInt8>`.

### Modifications:

For now I've only added a `readInlineArray` function. I know some other
functions are missing, such as `writeInlineArray`.
I wanted to first open up a discussion and see if these changes are
acceptable. I can add those functions too if required, in this PR or
other PRs.

### Result:

Users can read `ByteBuffer` into stack-allocated memory, which can be
more performant than the other alternatives like `Array`, or more
convenient than reading as a tuple like `(UInt8, UInt8, UInt8, UInt8)`.

### Caveats:

Swift 6.2 is required so I've used `#if compiler(>=6.2)`.
Furthermore, `InlineArray` is marked as available on `macOS(9999)` since
the Swift team have yet to update that mark, although `InlineArray` is
planned for Swift 6.2 per the
[proposal](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0453-vector.md).

Edit: to be clear things work fine on Linux and that's where I've been
using this same `readInlineArray` function that I've proposed.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-09-24 09:18:00 +00:00
George Barnett a18bddb0ac Add back NIOFileSystem (#3380)
Motivation:

We accidentally removed the 'NIOFileSystem' module from the
'_NIOFileSystem' product in the last release.

Modifications:

- Rename 'NIOFileSystem' and 'NIOFileSystemFoundationCompat' to 'NIOFS'
  and 'NIOFSFoundationCompat'
- Add back 'NIOFileSystem' which re-exports '_NIOFileSystem' (there was
  no publicly available 'NIOFileSystemFoundationCompat' module to
  remove, only '_NIOFileSystemFoundationCompat').

Result:

Fewer breaks
2.86.2
2025-09-23 17:29:01 +01:00
Rick Newton-Rogers db496205af Static sdk allow custom args (#3377)
Allow custom argument specification in the Static SDK workflow

### Motivation:

Sometimes users may want to specify more/different parameters such as
specifying building only some targets

### Modifications:

Add a parameter for the build arguments

### Result:

More flexible SDK CI.

You can see this in action here
https://github.com/apple/swift-nio/actions/runs/17858707940/job/50783709148?pr=3377
2025-09-23 14:23:32 +00:00
Cory Benfield f2ebedb36a The formatter changed its mind (#3379) 2025-09-23 14:58:24 +01:00
Rick Newton-Rogers 154706efd3 Matrix custom env vars (#3376)
Allow the specification of custom environment variables in our matrix
workflow and those which use it.

### Motivation:

It can be useful to supply custom environment variables to control build
and runtime options.

### Modifications:

Allow users to supply a string of custom environment variable key-value
pairs which are supplied to the docker container running the matrix
commands.

To attempt to avoid issues with this string concatenation the change
also allows the user to specify custom list entry and key-value-pair
separators.

To avoid parameter bloat the env vars are set for all Swift versions,
hopefully that's sufficient for now.

### Result:

Adopters can 

Examples of this working on Linux and Windows, note the presence of the
test environment variables I injected:
-
https://github.com/apple/swift-nio/actions/runs/17917619451/job/50943847555?pr=3376
- https://github.com/apple/swift-crypto/pull/413/checks

e.g. 
```
Executing Docker command: docker run -v /home/runner/work/swift-nio/swift-nio:/swift-nio -w /swift-nio -e CI=true -e GITHUB_ACTIONS=true -e SWIFT_VERSION=6.0 -e workspace=/swift-nio -e TEST_DEBUG=1 -e TEST_LOG_LEVEL=info swift:6.0-jammy bash -c swift --version && swift test -Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error
```
2.86.1
2025-09-22 16:06:47 +01:00
Fabian Fett 6c114e3c62 Update CI scripts for 6.2 (#3374)
Replaces: #3373
2025-09-19 13:55:48 +01:00
Rick Newton-Rogers 325c3231cf Add Xcode 26.0, 16.4 CI, remove 16.2 (#3375)
### Motivation:

New Xcodes are out so we should test with them.

### Modifications:

Update the macOS matrix generation script

### Result:

Add Xcode 26.0, 16.4 CI, remove 16.2 jobs by default.

CI with the new Xcodes working (except 26.0 which will come online as
nodes recycle
https://github.com/apple/swift-nio/actions/runs/17834807139/job/50709176060?pr=3375)
2025-09-19 09:30:08 +01:00