Commit Graph
235 Commits
Author SHA1 Message Date
Si BeaumontandAgam Dua b0e024792a Add opt-in API for channels to expose their underlying transport (#3509)
## 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>
2026-02-17 16:12:58 +00:00
Fabian Fett 2fdda6c78e Fix benchmark succeeding – even though Benchmark build failed (#3502)
### 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
2026-02-17 10:30:44 +00:00
Raphael d948192838 Don't send (in)active when channel closes directly (#3497)
### 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.
2026-02-11 15:46:19 +00:00
Kushal Pisavadia 9b92dcd5c2 Replace ConditionLock with wake-one signalling NIOThreadPoolWorkAvailable (#3507)
**TL;DR** This change leads to a ~90% reduction in observed system CPU
time for some use cases by waking a single thread, instead of all idle
threads.

# Changes

Inlining the commit messages here.

## Add NIOThreadPool submit throughput benchmarks

### Motivation

`NIOThreadPool` had no benchmarks measuring submit overhead. This makes
it difficult to evaluate the cost of signalling changes or to catch
latency regressions.

### Modifications

Add thread pool submit benchmarks, covering use cases with 4-thread and
16-thread pools.

### Result

`NIOThreadPool` submit throughput and context-switch overhead are now
tracked by benchmarks.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        77 │        78 │        79 │        80 │        80 │        92 │        92 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │       106 │       107 │       108 │       109 │       110 │       116 │       116 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │      1649 │      1752 │      1768 │      1795 │      1826 │      1929 │      1929 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │      1701 │      1805 │      1821 │      1849 │      1879 │      1987 │      1987 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        51 │        52 │        52 │        53 │        53 │        57 │        57 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │       167 │       177 │       178 │       181 │       183 │       200 │       200 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        44 │        44 │        44 │        45 │        45 │        45 │        45 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        65 │        65 │        65 │        66 │        66 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │       159 │       162 │       163 │       165 │       166 │       169 │       169 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │       178 │       182 │       183 │       185 │       186 │       190 │       190 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        19 │        19 │        20 │        20 │        20 │        21 │        21 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        76 │        79 │        79 │        80 │        80 │        82 │        82 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>

## Replace `ConditionLock` with wake-one signalling
`NIOThreadPoolWorkAvailable`

### Motivation

`NIOThreadPool` used `ConditionLock` which calls
`pthread_cond_broadcast` on every state change, waking all threads when
only one work item is enqueued. This causes a thundering-herd problem.

### Modifications

Add `NIOThreadPoolWorkAvailable` in NIOConcurrencyHelpers that uses
`pthread_cond_signal` (wake-one) for work submission and
`pthread_cond_broadcast` only for shutdown. Replace
`ConditionLock<_WorkState>` and the `_WorkState` enum in `NIOThreadPool`
with this new primitive.

### Result

Submitting a work item wakes exactly **one** thread instead of all
threads.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        47 │        49 │        49 │        50 │        50 │        55 │        55 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        57 │        58 │        59 │        60 │        61 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        10 │        10 │        10 │        10 │        10 │        12 │        12 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        54 │        55 │        56 │        56 │        57 │        65 │        65 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        45 │        46 │        46 │        47 │        57 │        75 │        75 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        54 │        55 │        56 │        57 │        68 │        87 │        87 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (μs) *   │      9055 │      9372 │      9478 │      9765 │     10887 │     12585 │     12585 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        52 │        53 │        53 │        54 │        64 │       124 │       124 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>
2026-02-10 20:01:35 +00:00
Fabian Fett 6a6f7d7c33 Centralize UnsafeTransfer in NIOCore (#3492)
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.
2026-02-03 10:27:30 +00:00
scottmarchant 5bf0267df4 build: Elide NIOPosix for WASI platforms only (#3485)
### 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).
2026-01-23 16:39:32 +00:00
Johannes Weiss 1268babbc1 Allowlist 6.3 to be allowable for Swift Concurrency takeover (#3467)
Make 6.3 fast
2025-12-19 13:19:04 +00:00
aryan-25 a1605a3303 Use explicit class name in all Self.[un]wrap{In}{Out}bound{In}{Out} calls (#3463)
### Motivation:

Swift does not currently generic specialize static methods on final
classes that have no parent classes when the method is implemented in a
protocol. This means that calling such methods through `Self` will not
involve a generic specialization, whereas using the explicit type name
will.

This pattern manifests in the `[un]wrap{In}{Out}bound{In}{Out}` static
methods defined in the
[`ChannelInboundHandler`](https://github.com/apple/swift-nio/blob/27146d484478b1bb0f150e848758f3a34ed9cbd0/Sources/NIOCore/TypeAssistedChannelHandler.swift#L60)
and
[`ChannelOutboundHandler`](https://github.com/apple/swift-nio/blob/27146d484478b1bb0f150e848758f3a34ed9cbd0/Sources/NIOCore/TypeAssistedChannelHandler.swift#L95)
protocols and their use from all channel handler classes. As such, we
should replace the `Self` part in all
`Self.[un]wrap{In}{Out}bound{In}{Out}` calls with the explicit class
name.

### Modifications:

Replaced all `Self.[un]wrap{In}{Out}bound{In}{Out}` calls to use the
explicit class name.

### Result:

Eliminates unnecessary overhead.
2025-12-15 17:36:11 +00:00
3405691582andRick Newton-Rogers 2bc71a6aff Partial OpenBSD support. (#3394)
### 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>
2025-11-26 09:07:02 +00:00
Johannes WeissandGeorge Barnett 3eea09220e do not waste time when metrics delegate is not set (#3441)
### 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>
2025-11-20 16:13:15 +00: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 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
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 f2ebedb36a The formatter changed its mind (#3379) 2025-09-23 14:58:24 +01:00
Fabian Fett e95d742160 [Windows] Reimplement pwrite (#3364)
Very much like #3361. Just for writing.

Result: NIOPosix compiles on Windows.
2025-09-01 16:12:41 +02:00
Fabian Fett db4d4c2566 [Windows] Sleep instead of WSAPoll, if no outstanding IO (#3365) 2025-09-01 10:55:18 +00:00
Fabian Fett 5bf5054a83 [Windows] Reimplement pread (#3361)
- 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
2025-08-29 13:39:04 +01:00
Fabian Fett c26397c5b4 [Windows] Make SelectorGeneric compile on Windows (#3359)
This is very half implemented, but it makes SelectorGeneric compile on
Windows. So that's a step forward, isn't it?
2025-08-28 16:44:55 +00:00
Fabian Fett 663b627102 [Windows] Return false from concurrency takeover (#3362)
Follow up to #3347. comment:
https://github.com/apple/swift-nio/pull/3347/files#r2307432411
2025-08-28 14:09:36 +00:00
Johannes Weiss f656af6b79 SelectableEventLoop.debugDescription: fix debugDescription deadlock (#3360)
### 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
2025-08-28 13:08:45 +01:00
Fabian Fett e8c1d6e09b [Windows] Disable Pipelines for now (fatalError) (#3358)
### 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.
2025-08-26 12:08:14 +00:00
Fabian Fett aff71b37f5 [Windows] Use recv instead of read (#3357) 2025-08-26 10:30:46 +00:00
Fabian Fett 0878179234 [Windows] Allow _SelectorBackendProtocol to work with Windows Handles (#3356)
`_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`.
2025-08-26 12:06:59 +02:00
Fabian Fett 148589720a [Windows] Add shims to make string from GetLastError using FormatMessage (#3353)
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.
2025-08-19 14:31:06 +00:00
Fabian Fett 9cde8e3a00 [Windows] dup is deprecated on Windows, use _dup instead (#3352) 2025-08-19 13:21:59 +00:00
Fabian Fett 456921a854 [Windows] Fix getenv warnings in NIOPosix and NIOEmbedded (#3351)
Less yellow code.
2025-08-19 12:48:46 +00:00
Fabian FettandGeorge Barnett 806a7276b1 [Windows] Use WSASend as writev equivalent (#3350)
See title. `writev` does not exist in Windows land.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-08-19 12:20:43 +00:00
Fabian Fett 54b0dc09ca [Windows] Make SocketChannel.swift compile (#3348)
- vsock isn't supported on windows.
- creating `in_addr` needs conditional compiling
2025-08-19 10:37:12 +00:00
Fabian Fett 3bf9c1bd2c [Windows] fatalError concurrency takeover (#3347)
To make further progress, let's disable the concurrency takeover feature
for now.
2025-08-18 10:50:40 +00:00
Fabian Fett 5dca91e191 [Windows] Make SelectableEventLoop compile (#3344)
- Add overwrite for `write` method that calls undeprecated `_write`
- Add errno global readonly variable
2025-08-13 09:18:50 +00:00
Fabian Fett 357ff9f16e [Windows] Map naming conventions Windows -> Posix (ssize_t) (#3343)
`ssize_t` doesn't exist in Windows land. Windows loves uppercase naming.
Therefore we need a typealias.
2025-08-12 17:37:00 +00:00
Fabian FettandCory Benfield d21f56b4bd [Windows] Make ControlMessage.swift compile (#3342)
See title.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-08-12 15:36:19 +00:00
Fabian Fett a8b744cb61 [Windows] Make Thread.swift compile (#3341)
See title.
2025-08-12 16:11:18 +01:00
Fabian Fett b881f6ec60 [Windows] Add msghdr extension for Windows (#3336)
To be able to compile on Windows eventually, we need to bridge msghdr
and WSAMSG. This PR tries to accomplish this by using extensions on
those types.
2025-08-11 15:49:00 +01:00
Fabian Fett 1944fd3721 [Windows] Ensure ssize_t and socklen_t are available (#3337)
See title.
2025-08-11 15:11:27 +01:00
Cory Benfield 41b126283c Don't double-initialize Pipe Bootstraps (#3330)
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.
2025-08-01 10:11:41 +00:00
Rafael Cepeda 02be63c7f4 Fixes all warnings when -require-explicit-sendable flag is enabled (#3320)
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.
2025-07-30 11:50:28 +01:00
Fabian Fett 4205ccaf1c [Windows] IOVector is WSABUF on Windows (#3324)
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.
2025-07-28 18:52:00 +02:00
Rafael Cepeda d6609623dd Fix docc (#3315)
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.
2025-07-23 13:37:57 +01:00
Cory Benfield ee67a96bcb Call channel initializer when using async methods on pipe bootstrap (#3309)
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.
2025-07-18 09:13:00 +01:00
Johannes Weiss 344db24aaa NIOThread: remove the detached threads functionality (#3304)
### 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
2025-07-15 15:20:20 +01:00
Johannes Weiss 933b9d738d Structured Concurrency compliant MTELG create/shutdown (#3296)
### 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
2025-07-15 12:14:04 +01:00
Johannes Weiss acca4e525c NIOThread refactor: pthread_t lifetimes (#3297)
### 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.
2025-07-15 10:03:12 +01:00
Johannes Weiss 0b65385fad improve inEventLoop checks (#3302)
### 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
2025-07-14 17:15:10 +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
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
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