## Motivation
NIO channels abstract over an underlying transport mechanisms (sockets,
pipes, etc.), which users typically need not interact with. However,
there are scenarios where users need direct access to the underlying
transport for low-level operations that work outside NIOs abstraction.
One example is performing out out-of-band operations on the underlying
file descriptor for a socket-based channel.
This PR adds a structured way to access the underlying transport of a
channel, for channels that choose to implement it.
## Modifications
- Add a new `public protocol
NIOTransportAccessibleChannelCore<Transport>` which provides a scoped
`withUnsafeTransport(_:)`, used for channel implementations to opt-in.
- Add conformance to
`NIOTransportAccessibleChannel<NIOBSDSocket.Handle>` for
`BaseSocketChannel`, to make this API available for all socket-based
channels, including channels returned from the socket-based bootstrap
public APIs.
- Add public API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
Note that not all channels need to or should their transport, which is
why this was added as an additional protocol that refines `ChannelCore`,
vs. extending `Channel` or `ChannelCore` with a default implementation.
The protocol uses a primary associated type allowing channels to provide
typed access to the transport. E.g. this could be used in NIO Transport
Services to expose the underlying `NWConnection`, if desired.
The method itself is spelled with "unsafe", uses scoped access, and has
clear documentation that users must not violated any of NIOs assumptions
about the state of the underlying transport. It's very much not intended
for every day use. It being on `ChannelCore` should defer users of the
low-level API, since `Channel._channelCore` is marked as for NIO
internal use, and the public `withUnsafeTransportIfAvailable(_:)` will
take care of the runtime checks for channels that have opted into this
API.
## Result
- New opt-in API for channel implementations to expose their underlying
transport
- All socket-based channels from NIOPosix now expose the underlying
socket file descriptor
- New API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
for users
---------
Co-authored-by: Agam Dua <agam_dua@apple.com>
### Motivation:
Currently if there is an error in the Benchmark targets, that prevents
the Benchmark to build correctly, we still get a CI success.
### Modifications:
- Check for the threshold changed error
### Result:
- More reliable CI
### Motivation
Issue #2773 reports a problem where channels can receive
`channelInactive` before `channelActive`. This breaks expectations and
should not happen. Instead of sending them in the wrong order, this PR
suppresses both of them in those cases.
### Modifications
* Add a test to reproduce the problematic behavior.
* Update the state machine to split the active state into two. This
decouples succeeding the promise from sending the signal. Transiting to
closing only sends `channelInactive` when originating from the state
that sent `channelActive`.
### Result
Address #2773.
Edit: Updated modifications to reflect latests commit.
We have a number of copies of `UnsafeTransfer` and two copies of
`UnsafeMutableTransferBox` in our code base. Before introducing more of
those, lets centralize to just one using a `package` access modifier.
### Motivation:
Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.
Without this change:
```swift
dependencies: [
// Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
.product(
name: "NIOPosix",
package: "swift-nio",
condition: .when(platforms: [
.macOS,
.macCatalyst,
.iOS,
.tvOS,
.watchOS,
.visionOS,
.driverKit,
.linux,
.windows,
.android,
.openbsd,
// .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
])
),
]
```
With this change:
```swift
dependencies: [
// Without this PR, downstream packages can consume NIOPosix simply:
.product(name: "NIOPosix", package: "swift-nio"),
]
```
### Modifications:
- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix
### Result:
Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.
### Testing performed
- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
### Motivation:
Additional partial platform support.
### Modifications:
* Create a new CNIOBSD module for OpenBSD, for general cleanliness, and
make use of it throughout. Some of the changes are borrowed directly
from CNIOLinux; some may technically be unnecessary; I am erring
somewhat on expediency to functionality.
* Since `malloc_size` is unavailable on OpenBSD, and some of the helpers
make use of ManagedBufferPointer which makes use of it, mark some of
this as unavailable as well.
* Usual pthread optional typing changes, since pthread types are
pointers on this platform.
* Add conditionals to exclude other functionality not available here,
like IP_RECVPKTINFO or IP_PKTINFO.
* d_ino is a backwards-compatibility macro valued token for dirent, so
instead, just expand with a conditional.
* Use kqueue on OpenBSD. This necessitates adding some conditionals for
type and feature compatibility.
* The vsock API is unavailable on OpenBSD.
### Result:
Tested the NIOTCPEchoClient and NIOTCPEchoServer appears to work and
that swift-nio-ssh (hopefully wlog) builds with a local repository with
these changes.
Because NIOFS/_NIOFileSystem depend on some non-portable components,
such as extended attributes, sendfile, non-portable linkat flags, and
renameat2, this is only just partial OpenBSD support, which means that
`swift build` on the full swift-nio project won't build cleanly, but at
least the portable parts can be used to build servers and clients. This
commit will mark the linked bug as fixed; I will open a new bug for file
system support.
Fixes#3383.
---------
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
### Motivation:
Unfortunately, even if no metics delegate has been configured,
significant work is being done _each EL tick_. Concretely:
- 2 `NIODealine.now()` calls which are expensive particularly on some
hypervisors (may cause a VMEXIT!)
- Some unnecessary calculations
### Modifications:
- Only perform the metrics delegate work if a delegate has actually been
set
### Result:
If no delegate is set, each EL tick will now be faster.
Co-authored-by: George Barnett <gbarnett@apple.com>
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.
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.
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.
- pread does not exist in ucrt. We need to reimplement it using read and
lseek.
- `FileDescriptor.setNonBlocking` is currently not needed in Windows to
compile. Let's not compile it.
- Set up correct sys calls for lseek and ftruncate
### Motivation:
In #3297, I introduced a deadlock involving `SelectableEventLoop`'s
`debugDescription`. I was under the impression that it's not possible to
call this from outside the `NIO` module so I deemed it safe. That was a
mistake :).
### Modifications:
- Make it impossible to deadlock around
`SelectableEventLoop.debugDescription`.
### Result:
- Fewer deadlocks
### Motivation
In Linux we can use `epoll` to observe sockets and pipes. WSAPoll sadly
only works for sockets. To observe pipes in Windows we can use
`WaitForMultipleObjects`. However we should try to get to a place where
we can start to fix tests first.
### Changes
- fatalError all pipe functions that do not compile right now.
`_SelectorBackendProtocol` currently requires the file descriptors to be
of `CInt` (aka Int32). However Windows HANDLES are pointers therefore
`UInt64`s. Let's use the typealias that we already have
`NIOBSDSocket.Handle`.
If we receive a functions error via `GetLastError`, we can stringify it
via `FormatMessage`. Sadly `FormatMessage` isn't auto imported into
Swift, which is why we need to use the shim layer.
Motivation:
In #3309 I fixed an issue where the channel initializer would not be
called in some PipeBootstrap paths. Unfortunately, that introduced a new
bug where the initializer was now called twice on some other paths.
Modifications:
Get the number of calls back to 1 on the non-async paths. Add some tests
Result:
Better pipe bootstrap behaviour.
Fixes all warnings when `-require-explicit-sendable` flag is enabled and
enables the flag on macOS CI.
### Motivation:
We want to ensure our public API is either explicitly marked as
`Sendable` or not.
### Modifications:
Marked appropriate public types as `Sendable`, or explicitly defined
their conformance to the `Sendable` protocol as unavailable.
### Result:
We can now enable `-require-explicit-sendable` compiler flag in our
codebase.
On Windows there is no iovec, because of this we need to make sure,
that:
1. We use the typealias `IOVector` as much as possible
2. We add platform specific code to `IOVector` extensions
Also adds some more Windows imports to fix some compiler errors.
This change fixes an example shown in the ServerBootstrap documentation.
### Motivation:
The current example given to users of ServerBootstrap will show a
Sendable conformance warning in Swift 6.0 or later.
### Modifications:
Changed the example to use `syncOperations`
### Result:
The new example doesn't contain any warnings.
Motivation:
For our async initializers on bootstraps, it's imortant that _both_
channel initializers are called, not only the one that comes as an
argument on the bind function.
Modifications:
Fix the takeOwnershipOfDescriptor async functions to call the
initializer from the bootstrap, and add regression tests.
Result:
Better behaved code.
### Motivation:
Detached threads are a bad idea, their lifetime becomes random and NIO
doesn't need this functionality (except for in some tests that are
easily refactored)
### Modifications:
- Refactor tests to not use detached threads
- Remove detached threads functionality
### Result:
- Cleaner, less complex and more correct code
### Motivation:
Structured Concurrency is helpful but so far, MTELG was very difficult
to use with it mostly because Swift is still missing `async` in
`defer`s.
This builds on
- #3297
- #3302
- #3304
### Modifications:
- Add MTELG.withELG { ... }
### Result:
MTELG + SC = <3
### Motivation:
NIOThread assumed it can hold onto `pthread_t` forever. Unfortunately,
on Linux, `pthread_t` is dead when the thread got joined (if not
detached) or if it exits (if detached) _which is at a random point in
time_.
### Modifications:
- Only assume ownership owner the `pthread_t` if not detached
- `nil` out the `pthread_t` on `join()`
### Result:
- Fewer `pthread_t` lifecycle bugs.
### Motivation:
`inEventLoop` is very much in the performance path of SwiftNIO,
especially these days with Concurrency, `NIOLoopBound` and friends.
Previously, we relied on `pthread_equal(pthread_self(), myPthread)`,
however, this could cause a number of issues.
1. Holding onto a `pthread_t` after `.join` is actually illegal (fixed
in #3297)
2. Potential ABA issues when `pthread_t` pointer are re-used for new
pthreads
3. Fix would require a lock around `myPthread` which makes things (2x
slower, even without contention)
### Modifications:
- New type `SelectableEventLoopUniqueID` which can be packed into a
`UInt`
- Attach them into a C thread local
### Result:
- Even faster than the old, incorrect version
- old: `measuring: el_in_eventloop_100M: 0.257395375, 0.241049208,
0.243188792, 0.259125916, 0.24843225, 0.229690125, 0.244281541,
0.225078834, 0.236395, 0.233305167`
- new: `measuring: el_in_eventloop_100M: 0.175561125, 0.187225625,
0.199269375, 0.19740975, 0.1922695, 0.179850958, 0.177612458,
0.17665125, 0.17897475, 0.18038775`
- More correct
- Groundwork to make #3297 not make things slower
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>
### Motivation
NIO’s event loop can emit metrics. Currently, this includes the start
time (i.e. when the loop started working) and the number of tasks which
were executed in that tick.
It would be useful to collect the time the loop tick ended and the
length of time the loop was asleep before starting the tick.
### Modifications
The event loop has a new property to track the time between runs. The
tick info collects two new values:
* The time the loop finished: the end-time.
* The time since the last run: the sleep time.
For the first run, the sleep time is the time since the event loop was
created.
### Result
The new metrics are available for collection.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation
With the introduction of isolated conformances, it has become necessary
to start managing the use of metatypes for some of our protocols. In
general, we don't want to force the relevant protocols to only be
conformed in non-isolated forms. Instead, we just want to make the
specific APIs non-usable.
Modifications
- Add shims for SendableMetatype that only use it when it is available.
- Require SendableMetatype where needed, gated by @preconcurrency.
Result
We continue to be safe.
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.