Commit Graph
2140 Commits
Author SHA1 Message Date
Cory Benfield ed9e5760c6 Functions that return values should return those values (#3283)
Motivation:

The title really says it all.

Modifications:

Have the Android shim actually do what it should

Result:

Fewer horrifying memory safety bugs
2025-07-03 15:25:30 -07:00
Cory Benfield ad6b5f1727 Work around Android nullability errors (#3279)
Motivation:

Android messed up their nullability annotations in fts_open. The
original change in
https://android.googlesource.com/platform/bionic/+/dec8efd72a6ad8b807a15a614ae1519487cfa456
asserted that fts_open's path argument took a non-null pointer to an
array of non-null pointers to strings. That's challenging, because the
_end_ of that array is indicated by a null pointer.

Regardless, this was eventually fixed in

https://android.googlesource.com/platform/bionic/+/da81ec4d1cbd0279014feb60535bf38defcd9346.
Unfortunately, that was more than a year after the offending change, so
we need to work around it.

Modifications:

Add a shim for Android that omits the nullability annotations. Use that
shim on Android.

Result:

Android works again.
Resolves #3273.
2025-07-01 08:11:16 +01:00
Luke HowardandCory Benfield 8d265e31fc Support for 64-bit timespec seconds on 32-bit platforms (#3277)
Modern 32-bit platforms (such as embedded Linux builds) support 64-bit
timestamps in `time_t` and `timespec`. Accommodate this.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-06-30 17:08:50 +00:00
scottmarchant 15dfe081a1 fix: Fix compiler error found on latest main that breaks wasip1 (wasm) compilation (#3271)
This is a quick simple fix for compiling NIOCore to wasm using the
command `swift build --swift-sdk wasm32-unknown-wasip1-threads --target
NIOCore`.

This fixes all errors for `wasip1`, however there are other errors
remaining in `main` when compiling for `wasi` using the command `swift
build --swift-sdk wasm32-unknown-wasi --target NIOCore`. Those issues
are out of scope for this PR.

### Motivation:

I am working to enable wasm compilation for a wide range of repositories
which depend on NIOCore. See
[here](https://github.com/PassiveLogic/swift-web-examples/issues/1) for
a sneak peak. This change is required to enable compiling several
respositories.

### Modifications:

`.multicastNotSupported` is elided for `os(WASI)` builds in
Channel.swift, however some new code referenced that case without proper
`WASI` guards.

This modification simply adds the appropriate elision guard to fix
wasip1 builds for NIOCore.

### Result:

After making this change, `swift build --swift-sdk
wasm32-unknown-wasip1-threads --target NIOCore` builds again (assuming
you have the appropriate wasm sdk installed).
2025-06-24 09:52:12 +00:00
Paul ToffoloniandFabian Fett 8d2347a56b Add scheduleCallback APIs to NIOIsolatedEventLoop (#3263)
Fixes #3262 by adding the missing APIs.

### Motivation:

As explained by the issue linked above, having a
non-`Sendable`-requiring variant of the new `scheduleCallback` APIs on
`NIOIsolatedEventLoop` can be useful since we're not always dealing with
`Sendable` types.

### Modifications:

This adds the required `scheduleCallback` APIs to `NIOIsolatedEventLoop`
by wrapping the non-`Sendable` `NIOScheduleCallbackHandler` in a
`NIOLoopBound`-based handler.
### Result:

The two `scheduleCallback`s can be used on `NIOIsolatedEventLoop` too.

---------

Co-authored-by: Fabian Fett <fabianfett@apple.com>
2025-06-18 14:54:33 +01:00
Orhan Yigit Yazicilar cddbde511a Adding RawSpan support to writeBytes in ByteBuffer (#3269)
Motivation:

With the new Swift version (6.2) we get access to spans for safely
interacting with the contiguous memory owned by other types. Allow users
write bytes to the ByteBuffer with RawSpans.

Modifications:

* ByteBuffer-core: Overload the setBytes, _setBytes, and
_setBytesAssumingUniqueBufferAccess to use RawSpan instead of
UnsafeRawBufferPointer
* ByteBuffer-aux: Overload the writeBytes to use RawSpan instead of
UnsafeRawBufferPointer

Result:

Users can now write the contiguous memory of other types into ByteBuffer
using the new RawSpan overloads, removing the need for unsafe pointer
handling.
2025-06-16 17:11:03 +00:00
RaphaelandGeorge Barnett 357955a8e6 Extend NIOEventLoopTickInfo with end-time and loop sleep time (#3268)
### Motivation

NIO’s event loop can emit metrics. Currently, this includes the start
time (i.e. when the loop started working) and the number of tasks which
were executed in that tick.

It would be useful to collect the time the loop tick ended and the
length of time the loop was asleep before starting the tick.

### Modifications

The event loop has a new property to track the time between runs. The
tick info collects two new values:

* The time the loop finished: the end-time.
* The time since the last run: the sleep time.

For the first run, the sleep time is the time since the event loop was
created.

### Result

The new metrics are available for collection.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-06-16 15:34:56 +01:00
Cory Benfield c9e2ac115f Adjust for SendableMetatype (#3266)
Motivation

With the introduction of isolated conformances, it has become necessary
to start managing the use of metatypes for some of our protocols. In
general, we don't want to force the relevant protocols to only be
conformed in non-isolated forms. Instead, we just want to make the
specific APIs non-usable.

Modifications

- Add shims for SendableMetatype that only use it when it is available.
- Require SendableMetatype where needed, gated by @preconcurrency.

Result

We continue to be safe.
2025-06-13 09:12:25 +01:00
hamzahrmalik 37094b1b42 Embedded channels should set local and remote address always (#3254)
Embedded channels should set local and remote address always

### Motivation:

Currently, if connect or bind are called without a promise, the
remote/local address does not get set because those were getting set in
the whenSuccess of the promise.

### Modifications:

If the user didn't provide a promise, create one ourselves, so we have
something to listen for.

### Result:

Calling connect/bind will always result in remote/local address getting
set, regardless of whether you pass a promise
2025-05-30 17:21:18 +01:00
Roman A f3645a02b7 a couple grammar fixes (#3259) 2025-05-30 10:34:44 +00:00
Egor ZhdanandCory Benfield adfa636b4b Make CNIOAtomics and CNIODarwin compatible with C++ interop (#3251)
### Motivation:

This fixes linker errors such as
```
@nonobjc __C.catmc_nio_atomic_uint_least32_t_create_with_existing_storage(Swift.UnsafeMutablePointer<__C.catmc_nio_atomic_uint_least32_t>, Swift.UInt32) -> () in NIOAtomic.swift.o
   NOTE: found '_catmc_nio_atomic_uint_least32_t_create_with_existing_storage' in c-nioatomics.c.o, declaration possibly missing 'extern "C"'
```
when building with Swift/C++ interoperability enabled.

### Modifications:

Wrapped the C declarations a couple of headers in `extern "C" { ... }`
blocks.

### Result:

The project builds successfully with Swift/C++ interop enabled.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-05-23 17:30:27 +00:00
Marc Prud'hommeaux b23163df5f Handle different ThreadDestructor signatures between Android NDK 27 and NDK 28 (#3249)
This change enables swift-nio to be compiled for Android against both
NDK 27 and NDK 28

### Motivation:

Android's NDK had been adopting [nullability
annotations](https://android.googlesource.com/platform/developers/docs/+/refs/heads/master/api-guidelines/ndk.md#nullability)
in its C headers, and they have been changing them from release to
release. The churn has mostly died down since the release of the NDK 27
(LTS), but one new change in NDK 28 affects the destructor argument for
`pthread_create`, making the existing `ThreadDestructor` typealias
invalid and leading to the following compile error when the [Android SDK
bundle](https://github.com/skiptools/swift-android-toolchain/releases)
is installed and linked to NDK 28:

```
$ swiftly run swift build --swift-sdk aarch64-unknown-linux-android28 +6.2-snapshot-2025-05-15-a

Building for debugging...
/opt/src/github/swift-everywhere/swift-nio/Sources/NIOPosix/ThreadPosix.swift:82:9: error: cannot convert value of type '@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?' to expected argument type '@convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer'
 80 |         &handleLinux,
 81 |         nil,
 82 |         destructor,
    |         `- error: cannot convert value of type '@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?' to expected argument type '@convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer'
 83 |         args
 84 |     )
[4/21] Compiling NIOPosix ThreadPosix.swift
```

This change adapts the parameter we pass to that function to accommodate
both NDK 27 and NDK 28.

### Modifications:

There's currently no way to determine which version of the NDK is in use
at compile time (see https://github.com/swiftlang/swift/issues/81402),
so this accommodation is implementing by having two functions named
`coerceThreadDestructor` that return values that are suitable either NDK
27 or NDK 28 (using `unsafeBitCast`, but the layout of C functions
doesn't know anything about nullability, so this is safe), and then let
the type inference for `pthread_create` handle the rest.

### Result:

swift-nio can be compiled against both NDK 27 and NDK 28 without errors.
2025-05-23 16:51:42 +00:00
Fabian FettandGeorge Barnett fec9719099 NIOThrowingAsyncSequenceProducer make more funcs @inlinable (#3243)
When working on performance in PostgresNIO I noticed a few
`_swift_getGenericMetadata`s. We don't like those. I could trace them
down to `NIOThrowingAsyncSequenceProducer`. All methods on this object
are generic, since the object itself is generic.

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-05-23 13:43:07 +00:00
a0c542bff1 Fix NIOAsyncWriter test on concurrency thread pool with single thread (#3135)
### Motivation:

The testSuspendingBufferedYield_whenWriterFinished test fails on the
Android emulator. See also the discussion in #3044.

### Modifications:

The test requires at least two threads in the concurrency thread pool
because it blocks one task, which waits for another task to set a
condition. This PR adds support for running a task executor based on a
NIOThreadPool and uses it for the test. Using a custom task executor
guarantees that at least two threads are available for the test.

Additionally, the test has been renamed to
testWriterFinish_AndSuspendBufferedYield, which is more in line with the
other test names.

### Result:

The test will pass regardless of the width of the global concurrency
thread pool.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-05-12 15:12:53 +01:00
Rick Newton-Rogers 8b74598216 Remove assertions on PWM failAll and closeOutbound (#3231)
### Motivation:

`failAll` and `closeOutbound` are likely to be called multiple times,
either because of the user calling close or because the channel reads
EOF.

Depending on the ordering it is possible with the recent code changes
for us to reach code which currently asserts we are open when a prior
close operation has set `isOpen` to false.

Before the recent change which queues outbound closes behind pending
writes was made an outbound mode close after reading EOF would result in
an error (file descriptor already closed!: Bad file descriptor), after
the change was made it would cause an assertion failure.

### Modifications:

* Remove the assertions for `isOpen` in `failAll` and `closeOutbound`,
we can tolerate being called more than once.
* Issue socket shutdown even if we believe we are closed to match
previous behavior and the behavior of the other SocketChannels
* Update the `isOpen` state in `closeOutbound`, this was missing.
* Add a test which panics before this change.

### Result:

The code is more tolerant of multiple close operations and the previous
behavior is restored
2025-05-07 19:40:13 +01:00
Rick Newton-Rogers 14dcafc6ec Update Array+FileSystem.swift to add visionOS (#3220)
Fix visionOS builds and tests

### Motivation:

visionOS builds and tests were failing because of missing cases in
availability guards.

### Modifications:

Spell guards in terms of Darwin where appropriate, add visionOS

### Result:

Example run of this working in CI
https://github.com/apple/swift-nio/actions/runs/14876166161/job/41773757638?pr=3220
2025-05-07 13:22:23 +00:00
Rafael CepedaandGeorge Barnett afa7d4f57d Moving PooledRecvBufferAllocator from NIOPosix to NIOCore (#3110)
Moving `PooledRecvBufferAllocator` from NIOPosix to NIOCore, making it
part of its public interface.

### Motivation:

We want to introduce the capability of reusing receiving buffers from a
pool into swift-nio-transport-services project. To prevent duplicating
this functionality there, this change is making the existing
functionality from NIO part of its public API.

### Modifications:

Moved the type `PooledRecvBufferAllocator` from NIOPosix module to
NIOCore and turned it into a public type.

### Result:

`PooledRecvBufferAllocator` is part of NIOCore public API.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-05-07 12:50:15 +00:00
Rick Newton-Rogers 57658e12ff Drop Swift 5.9 (#3228)
Motivation:

Swift 5.9 is no longer supported, we should bump the tools version and
remove it from our CI.

Modifications:

* Bump the Swift tools version to Swift 5.10
* Remove Swift 5.9 jobs where appropriate in main.yml, pull_request.yml

Result:

Code reflects our support window.
2025-05-07 12:24:44 +00:00
Axel AnderssonandGeorge Barnett 960dcfb29b Make ChannelError and NIOConnectionError conform to CustomStringConvertible (#3230)
### Motivation:

`ChannelError` and `NIOConnectionError` should conform
`CustomStringConvertible` so that these errors can be easily logged.

As discussed in https://github.com/apple/swift-nio/issues/3222.

### Modifications:

Added conformance to `ChannelError` and wrote error messages for all
cases.

Added conformance to `NIOConnectionError`.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-05-07 10:40:46 +00:00
Cory Benfield abe4f1bcb6 Replace almost all public static lets with computed vars (#3229)
Motivation:

Public static lets can serve a bunch of roles, but one of them is to
store simple constants: integers, and other trivial types, for example.
This is a nice pattern and for internal and private static lets it works
well, but for public ones it produces some inefficient code.

In particular, it has two downsides. First, it allocates storage for
that value. We don't actually need to allocate a few hundred extra
megabytes for the various integers we want to store.

Secondly, it forces calling code to access the address and call the
dispatch_once code in order to get hold of the value. For trivial types
we don't need that cost: they can just know what the value is directly.

Inlinable computed vars avoid all of these costs: they have no size
overhead for storage, and they are visible to all clients so their
values can be directly assembled.

While I'm here, I added a bunch of other inlinable annotations for a few
trivial data types I stumbled onto.

Modifications:

- Added loads of inlinables. Like, loads.
- Swapped many static lets to static vars.

Result:

Better codegen, smaller memory footprints, more attributes.
2025-05-02 16:08:10 +01:00
Rick Newton-Rogers ea8703616e BaseStreamSocketChannel half-close allows outstanding writes to complete (#3148)
### Motivation:

At the moment half-closes are actioned immediately and fails all
outstanding writes. We should refuse new writes but allow these writes
to complete before completing the close.

### Modifications:

Modify the PendingWritesManager internal buffer to hold an enum of
either writes or close events. We use this to store the close and only
action it when the preceding writes have been handled.

### Result:

Outbound close should no longer fail outstanding writes

Should resolve https://github.com/apple/swift-nio/issues/3139
2025-04-30 14:56:03 +01:00
Cory Benfield 0f54d58bb5 Fix compiler issues on 5.10 x86 Ubuntu Noble. (#3224)
Motivation:

There's a known compiler issue on the 5.10 toolchain for x86 on Ubuntu
Noble. This issue causes the compile to fail, even though the code is
fine. We shouldn't allow that.

Modifications:

Shuffle the whitespace around to fix the issue.
Suppress the linter issues.

Result:

Compiler is back. Resolves #3223.
2025-04-28 10:07:35 +00:00
Cory BenfieldandGeorge Barnett 6e17bc9468 Update LLHTTP and apply patch to support C++ interop (#3216)
### Motivation

C++ interop support in Xcode has started to dislike the header files
from llhttp. While a bug has been filed upstream at
https://github.com/nodejs/llparse/issues/71 it doesn't seem as though
there is any movement on that fix upstream. As a result, we need to
apply a patch.

To keep the code maintainable, we'd like to apply that patch in an
automated fashion, so we should do so by amending the "update and patch"
script. Along the way, we should update LLHTTP to the latest code.

### Modifications

The modifications are split into separate commits.

1. Modify the script to fix some bugs that have crept in.
2. Run the script to update LLHTTP to latest, without the patch.
3. Fix up the tests to account for the fact that we get some different
errors from LLHTTP now.
4. Apply the patch suggested by @postmechanical in #3093
5. Re-run the script, which only applies the patch

### Result

C++ interop should be working again. Resolves #3093.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-04-22 13:11:47 +01:00
Cory Benfield 6789c58fdb Clarify test server error code (#3212)
Motivation

The NIOHTTP1TestServer had a weird codepath where we could hit errors
configuring the channel pipeline, but we weren't sure why. I've
investigated, and this happens because a Channel that had been accepted
earlier was closed while we were waiting to start handling it. This is
totally benign: the code works just fine in that situation.

To be clear, though, let's document the behaviour and add a test.

Modifications

- Code comment to explain the behaviour
- Added a regression test

Result

More confidence.
2025-04-16 16:02:32 +00:00
Adam FowlerandCory Benfield d7a8ff6e36 Add errorCaught to NIOTypedHTTPClientUpgradeHandler (#3210)
To handle errors fired by previous ChannelHandlers. eg
NIOSSLClientHandler

### Motivation:

Otherwise if a ChannelHandler previous to the upgrade ChannelHandler
fails the error returned is `inappropriateOperationForState` and the
error fired by the original ChannelHandler is lost.

Added `testReturnsErrorsFromPriorChannelHandlers`. Also had to
reorganise `setUpClientChannel` slightly so I could get the result of
the upgrade.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-16 14:24:42 +00:00
George Barnett b34052b28b Swift concurrency for NIOWebSocketTests (#3208) 2025-04-15 16:38:21 +01:00
Raghav Roy 8440498328 Add More Peek API Variants for ByteBuffer (#3174)
### Motivation:

Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address issue #2034 and issue #2736, and is a continuation
of PR #3157

### Modifications:

Introduced peekSlice(), peekLengthPrefixedSlice(), peekData(),
peekUUIDBytes() and peekWebSocketErrorCode().
Added tests for each peek API covering normal, empty and repeated peek
scenarios.

### Result:

Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
2025-04-10 14:44:53 +00:00
Raghav RoyandCory Benfield 12d8a4c6d7 Add Peek API for Multiple Integers (#3175)
### Motivation:

The current readMultipleIntegers methods are used to consume multiple
integer values at once, but lack an equivalent nonmutating API. This can
lead to unnecessary complexity when users want to inspect values without
advancing readerIndex. THis patch introduces peekMultipleIntegers which
uses the current readerIndex, improving safety. This extends previous
work on peek methods (issue #2034, issue #2736).

### Modifications:

Updated the generation script (.sh file) to produce peekMultipleIntegers
variants for each arity of readMultipleIntegers.
    Added new tests mirroring the existing multi-read/write tests

### Result:

Users can now inspect multiple integer values in a ByteBuffer without
consuming them, enabling safer workflows.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-10 10:23:27 +00:00
George BarnettandCory Benfield 69e8d39aa4 Expose the event loop from the loop bound boxes (#3179)
Motivation:

NIOLoopBound and NIOLoopBoundBox both have a public-but-underscored
event loop property, i.e. the loop to which the value is bound. It's
often very helpful to be able to access the event loop the value is
isolated to. Having access allows you to execute onto the event loop and
safely access the value.

Modifications:

- Make the property public and add a deprecated shim for the
public-but-underscored variant.

Result:

Can access the event loop of a loop bound value

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-09 13:47:34 +00:00
Marc Prud'hommeaux c626de9f4d Ignore return value of signal() on Android (#3181)
Fixes https://github.com/apple/swift-nio/issues/3180 by ignoring return
value of signal() on Android
2025-04-08 12:52:04 +00:00
George Barnett 4b7854daaa Strict concurrency for NIOPerformanceTester and NIOCrashTester (#3167) 2025-04-07 14:10:48 +00:00
George Barnett 195bca151e Strict concurrency for websocket client/server demo and async demo (#3161) 2025-04-01 16:39:33 +00:00
Raghav Roy 1d7a94655f Add Peek API variants for ByteBuffer (#3160)
### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736, and is a continuation of
PR https://github.com/apple/swift-nio/pull/3157

### Modifications:
- Introduced peekBytes(), peekString(), peekNullTerminatedString(),
peekUTF8ValidatedString() and peekDispatchData().
- Added tests for each peek API covering normal, empty, repeated, and
partial read scenarios.

### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.

***PS**: I have focussed on the ByteBuffer-aux get\* implementations, so
I'm not sure if I am missing any other important/error-prone get\*
elsewhere, if so, please point me to them and I'll be happy to add
respective peek\*'s!*
2025-03-31 10:30:37 +01:00
Raghav RoyandGeorge Barnett e8260eb721 Add peekInteger API to ByteBuffer (#3157)
### Motivation:

The existing getInteger API is often used incorrectly, leading to
verbose or error-prone code as mentioned in
https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736. Users may
unintentionally access data without correctly managing the reader index.
To address this, I added a peekInteger API that reads integers using the
current readerIndex without modifying it.

### Modifications:

* Added a peekInteger method to ByteBuffer, which provides a nonmutating
way to read integers using the current readerIndex.
* Implemented peekInteger using the existing getInteger function.
* Added comprehensive unit tests to validate correct behavior, including
scenarios for different integer types, insufficient bytes, and
multi-write scenarios.

### Result:

* Users now have access to a safer API for inspecting integers in a
buffer without modifying state.
* Added tests for integer reading scenarios.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-03-27 09:54:07 +00:00
scottmarchantandScott Marchant 320fe4c406 fix: Fix NIOCore build for wasm targets (#3156)
Fixes NIOCore compiler errors for the `wasm32` architecture.

### Motivation:

When compiling NIOCore for a SwiftWasm target, several compilation
errors such as the following occur:

```
> swift build --swift-sdk wasm32-unknown-wasi --target NIOCore

.../swift-nio/Sources/NIOCore/FileHandle.swift:151:42: error: cannot find type 'TwoUInt32s' in scope
149 | public final class NIOFileHandle: FileDescriptor & Sendable {
150 |     private static let descriptorClosed: CInt = CInt.min
151 |     private let descriptor: UnsafeAtomic<TwoUInt32s>
    |                                          `- error: cannot find type 'TwoUInt32s' in scope
152 | 
153 |     public var isOpen: Bool {
.../swift-nio/Sources/NIOCore/FileHandle.swift:77:8: error: Unknown architecture
 75 | typealias TwoUInt32s = DoubleWord
 76 | #else
 77 | #error("Unknown architecture")
    |        `- error: Unknown architecture
 78 | #endif
 79 | 
 
…
```
The compilation errors were introduced with the following change: 


https://github.com/apple/swift-nio/pull/2598/files#diff-a041d0c0d50a8f4fcda2020eeb4450ea994920ef61653cc06014457ccdb3ba0cR70

### Modifications:

The fix is straight-forward and unlikely to affect any existing
compilation targets other than the `wasm32` target.

We simply need to add `arch(wasm32)` to compiler architecture condtions
for a new typedef on line, then NIOCore compiles to wasm32 again.

### Result:

Before: NIOCore wasm build fails ❌ 

After: NIOCore wasm build succeeds ✅

Co-authored-by: Scott Marchant <scottm@passivelogic.com>
2025-03-27 09:28:30 +00:00
Rafael CepedaandFranz Busch 050158c75a Changed NIOAsyncChannel.executeThenClose to accept actor-isolated parameter (#3121)
Improve usability of NIOAsyncChannel.executeThenClose function from an
Actor

### Motivation:

When calling executeThenClose from inside an actor, the closure which we
pass is not isolated to the same actor
This makes it hard to use

e.g. the following code won’t compile on Swift 6 because the closure is
`self-isolated` so can’t be passed

```
await withDiscardingTaskGroup { group in
            do {
                try await serverChannel.executeThenClose { inboundStream, _ in
                    try await self.handleInboundStream(inboundStream: inboundStream, group: &group)
                }
             } catch {}
}
```

Making the closure as @Sendable allows it to be passed, but then we
can’t access `group` anymore

### Modifications:

Added actor isolation parameter to the `executeThenClose` function. 

### Result:

`executeThenClose` will be able to be asynchronously called from inside
an Actor, as it will now be part of the Actor's isolation domain.

---------

Co-authored-by: Franz Busch <privat@franz-busch.de>
2025-03-25 13:31:39 +00:00
Johannes Weiss 40ee44c6b9 always @preconcurrency import Glibc/Musl/Android/Bionic/WASILibc (#3153)
### Motivation:

The non-`Darwin` libcs don't have the correct concurrency annotations.
But due to these Swift bugs, it's important that the _first_ importer
uses `@preconcurrency`:

- https://github.com/swiftlang/swift/issues/79414
- https://github.com/swiftlang/swift/issues/77866

### Modifications:

Much like the Foundation (& corelibs) PRs such as
https://github.com/swiftlang/swift-foundation/pull/1175 , use
`@preconcurrency import` for the non-`Darwin` libcs.

### Result:

Fewer bad warnings/errors in user code.
2025-03-21 15:35:05 +00:00
George Barnett 6b00972ad9 Add make*Future methods to isolated event loop (#3152)
Motivation:

Creating a completed future of a non-sendable value when on the current
event loop is currently a little tedious. It requires you to create a
promise, succeed it using the isolated view, or fail it using the
non-isolated view. This is more tedious than it needs to be.

Modifications:

- Add `make{Succeeded,Failed,Completed}Future` methods to the isolated
event loop. These don't require the `Success` value to be `Sendable`.

Result:

It's easier to create completed futures of non sendable values from an
isolated event loop.
2025-03-20 16:00:04 +00:00
hamzahrmalikandCory Benfield 69b63df3d9 Allow NIOLoopBoundBox to be initialized by sending in a value (#3138)
Allow NIOLoopBoundBox to be initialized by sending in a value
### Motivation:

It should be possible to initialize a loopbound box off-loop if the
initial value of the box is being moved onto the loop.

### Modifications:

Add another static function, to create a loopboundbox by `sending` a
value. This is safe because the compiler will not let the caller use the
value after putting it into the box. Only the box (or rather, the el
which the box is bound to) will be able to access the value thereafter.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-03-11 17:08:49 +00:00
Rick Newton-Rogers be266a94ed Downgrade NIOHTTP1TestServer handleChannel failure (#3137)
### Motivation:

We added a fatalError to report NIOHTTP1TestServer handleChannel
failures when doing the strict concurrency work which are now being hit.

We don't know if these failures are actually new or not because the
previous code just swallowed such errors.

### Modifications:

Print the errors but limp-on to see if the test goes on to pass, if so
this might not be a new error.

### Result:

Less severe response to NIOHTTP1TestServer handleChannel failure.
2025-03-10 11:46:44 +00:00
Rick Newton-Rogers 6adf682d16 Enable strict concurrency checking for NIOTestUtils (#3130)
### Motivation:

To ensure `NIOTestUtils` concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* `NIOHTTP1TestServer` does pipeline configuration as synchronous
operations.

### Result:

`NIOTestUtils` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
2025-03-07 10:52:08 +00:00
Rick Newton-Rogers 5fe3d44328 Enable strict concurrency checking for NIOWebSocket (#3127)
Enable strict concurrency checking for NIOWebSocket

### Motivation:

To ensure NIOWebSocket concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* `NIOWebSocketClientUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `NIOWebSocketServerUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `WebSocketOpcode.allCases` public computed variable is replaced with a
`let` which manually enumerates the cases instead

### Result:

`NIOWebSocket` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
2025-03-07 09:34:06 +00:00
Rick Newton-Rogers de47bf8ba5 Enable strict concurrency checking for NIOHTTP1Server (#3132)
### Motivation:

To ensure `NIOHTTP1Server` concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* User synchronous operations in pipeline configurations

### Result:

Builds will warn and CI will fail if regressions are introduced.
2025-03-06 14:58:02 +00:00
Johannes Weiss 3de7a286c0 NIOSingletons docs: Clarify the set once-ness (#3128)
### Motivation:

The docs don't make it clear that the thread count suggestions for the
singletons are:

- set once
- privileged
- need to happen very early on to be effective

### Modifications:

Clarify that.

### Result:

Fewer surprises.
2025-03-05 17:39:05 +00:00
Tim Condon 6c44e2d605 Hashable SocketAddressError (#3119)
Make `SocketAddressError` `Equatable` and `Hashable`. This is useful when running tests
that you expect to throw this error as it allows you to write for
example
```swift
await #expect(throws: SocketAddressError.unknown(host: "127.0.0.1", port: Int.max)) {
    try await app.startup()
}
```
2025-02-23 21:23:06 +00:00
Rick Newton-Rogers 5f60ceeca0 Enable strict concurrency checking for NIOHTTP1 (#3115)
### Motivation:

To ensure NIOHTTP1 concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* Mark several objects `Sendable` with `@preconcurrency` annotations
where they are returned in futures which may execute in arbitrary
concurrency domains.
  * `NIOTypedHTTPClientProtocolUpgrader`
  * `NIOTypedHTTPClientUpgradeConfiguration`
  * `NIOUpgradableHTTPServerPipelineConfiguration`
  * `NIOUpgradableHTTPClientPipelineConfiguration`
  * `NIOTypedHTTPServerProtocolUpgrader`
  * `NIOTypedHTTPServerUpgradeConfiguration`
* Mark handlers as explicitly not sendable
  * `NIOTypedHTTPClientUpgradeHandler`
  * `NIOTypedHTTPServerUpgradeHandler`
* Added new Sendable type aliases:
  * `NIOHTTPClientUpgradeSendableConfiguration`
  * `NIOHTTPServerUpgradeSendableConfiguration`

### Result:

No more concurrency warnings. Builds will warn and CI will fail if
regressions are introduced.
2025-02-19 15:04:51 +00:00
Cory BenfieldandGeorge Barnett f46998ce2d Make isolated execute on async testing eventloop actually run (#3116)
Motivation:

The isolated execute on async testing event loop wouldn't execute tasks
in the case of promise being nil

Modifications:

Rewrite the execute logic slightly.

Result:

Correct execution

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-02-18 19:03:24 +00:00
Rick Newton-Rogers 7789652b83 Add more methods to work with Isolated futures (#3117)
### Motivation:

Whilst working on the NIOHTTP1 strict concurrency work I encountered a
few gaps in the API where I needed isolated analogues of methods on
futures.

### Modifications:

* Add `makeSucceededIsolatedFuture`
* Add a new internal initializer for `EventLoopFuture` which does not
require the value to be Sendable for use in isolated contexts.
* Add a variant of `flatMapError` which can handle closures which return
isolated futures
* Add a `futureResult` computed property which allows us to avoid the
otherwise clumsy `future.nonIsolated().futureResult.assumeIsolated()`

### Result:

More ability to work with isolated futures.
2025-02-14 14:56:06 +00:00
Rick Newton-Rogers c51907a839 Enable strict concurrency checking for NIOTLS (#3112)
### Motivation:

To ensure NIOTLS concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* Require `NegotiationResult` to be `Sendable`
* In `NIOTypedApplicationProtocolNegotiationHandler<NegotiationResult>`
the
result is used to fulfil promises and perform hops so we need it to be
sendable when accessed from these other concurrency domains.

### Result:

Builds will warn and CI will fail if regressions are introduced.
2025-02-07 16:52:40 +00:00
Johannes Weiss 73e83ab73f document known Structured Concurrency violations (#3108)
### Motivation:

Not all NIO APIs, particularly the async-bridge interfaces that use
`.get()` under the hood respect Structured Concurrency. That might be
okay, but it definitely ought to be documented.

Note: `NIOAsyncChannel` does follow Structured Concurrency.

### Modifications:

Annotate known Structured Concurrency violations.

### Result:

Better docs.
2025-02-05 11:12:57 +00:00