Commit Graph
209 Commits
Author SHA1 Message Date
Si Beaumont e932d3c4d8 Workaround test crashing when compiled in release mode on Swift 6.2 (#3511)
### Motivation:

Our post-merge, pre-release pipelines run tests for our supported Swift
versions in both debug and release mode. The recent PR to add
`withUnsafeTransportIfAvailable` added some tests for various valid and
invalid usages of the API. One of the invalid usages was causing the
tests to crash, when compiled in release mode, in the Swift runtime:

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for debugging...
[1/1] Write swift-version-24593BA9C3E375BF.txt
Build complete! (2.38s)
Test Suite 'Selected tests' started at 2026-02-18 13:28:18.905
Test Suite 'Selected tests' passed at 2026-02-18 13:28:18.905
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.
✔ Test testUnderlyingSocketAccessForSocketBasedChannel() passed after 0.005 seconds.
✔ Suite NIOTransportAccessibleChannelCoreTests passed after 0.005 seconds.
✔ Test run with 1 test in 1 suite passed after 0.005 seconds.
```

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test -c release --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for production...
[1/1] Write swift-version-24593BA9C3E375BF.txt
Build complete! (2.12s)
Test Suite 'Selected tests' started at 2026-02-18 13:27:12.102
Test Suite 'Selected tests' passed at 2026-02-18 13:27:12.103
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.

*** Signal 11: Backtracing from 0xffff8854b1ec... done ***

*** Program crashed: Bad pointer dereference at 0x0000000000000000 ***

Platform: arm64 Linux (Ubuntu 24.04.4 LTS)

Thread 0 "NIO-ELT-1-#1" crashed:

  0                0x0000ffff8854b1ec tryCast(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InProcess> const*&, swift::TargetMetadata<swift::InProcess> const*&, bool, bool, bool) + 52 in libswiftCore.so
  1 [ra]           0x0000ffff8854b148 swift_dynamicCast + 79 in libswiftCore.so
  2 [ra] [system]  0x0000aaaab8668588 specialized ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable<A, B>(of:_:) + 135 in swift-nioPackageTests.xctest at //<compiler-generated>
  3 [ra]           0x0000aaaab8668148 closure #1 in NIOTransportAccessibleChannelCoreTests.testUnderlyingSocketAccessForSocketBasedChannel() + 3103 in swift-nioPackageTests.xctest at /tmp/swift-generated-sources/@__swiftmacro_13NIOPosixTests0049NIOTransportAccessibleChannelCoreTestsswift_IhHJqfMX55_16_33_309B77F97E02F918EDFF07092681CD49Ll6expectfMf8_.swift:1:40
  4 [ra] [thunk]   0x0000aaaab866be1c partial apply for closure #1 in NIOTransportAccessibleChannelCoreTests.testUnderlyingSocketAccessForSocketBasedChannel() + 15 in swift-nioPackageTests.xctest at //<compiler-generated>
  5 [ra]           0x0000aaaab7f410ec closure #1 in EventLoop.submit<A>(_:) + 95 in swift-nioPackageTests.xctest at /pwd/Sources/NIOCore/EventLoop.swift:1030:69
  6 [ra] [inlined] 0x0000aaaab841d468 closure #1 in SelectableEventLoop.run(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:618:17
  7 [ra] [inlined] 0x0000aaaab841d468 specialized withAutoReleasePool<A>(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:49:16
  8 [ra] [inlined] 0x0000aaaab841d468 SelectableEventLoop.run(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:615:9
  9 [ra]           0x0000aaaab841d468 SelectableEventLoop.runOneLoopTick(selfIdentifier:) + 535 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:809:22
 10 [ra]           0x0000aaaab8423e5c SelectableEventLoop.run() + 331 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:923:38
 11 [ra] [inlined] 0x0000aaaab83de614 static MultiThreadedEventLoopGroup.runTheLoop(thread:uniqueID:parentGroup:canEventLoopBeShutdownIndividually:selectorFactory:initializer:metricsDelegate:_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift:117:22
 12 [ra]           0x0000aaaab83de614 closure #1 in static MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name:uniqueID:parentGroup:selectorFactory:initializer:metricsDelegate:) + 1255 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift:139:41
 13 [ra] [thunk]   0x0000aaaab83e1eec partial apply for closure #1 in static MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name:uniqueID:parentGroup:selectorFactory:initializer:metricsDelegate:) + 39 in swift-nioPackageTests.xctest at //<compiler-generated>
 14 [ra] [thunk]   0x0000aaaab843f534 thunk for @escaping @callee_guaranteed (@guaranteed NIOThread) -> () + 23 in swift-nioPackageTests.xctest at //<compiler-generated>
 15 [ra]           0x0000aaaab84409dc closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 319 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/ThreadPosix.swift:186:21
 16 [ra]           0x0000ffff86af595c <unknown> in libc.so.6
...


Registers:

 x0 0x0000ffff62fddfe0  48 60 00 58 ff ff 00 00 e0 e0 fd 62 ff ff 00 00  H`·Xÿÿ··ààýbÿÿ··
 x1 0x0000000000000000  0
 x2 0x0000ffff62fddff0  40 b4 01 5c ff ff 00 00 20 83 d1 b8 aa aa 00 00  @´·\ÿÿ·· ·Ñ¸ªª··
 x3 0x0000ffff58002038  03 03 00 00 00 00 00 00 01 00 00 00 01 00 00 00  ················
 x4 0x0000ffff62fddfa8  00 00 00 00 00 00 00 00 00 e0 fd 62 ff ff 00 00  ·········àýbÿÿ··
 x5 0x0000ffff62fddfa0  38 20 00 58 ff ff 00 00 00 00 00 00 00 00 00 00  8 ·Xÿÿ··········
 x6 0x0000000000000001  1
 x7 0x0000000000000000  0
 x8 0x0000000000000000  0
 x9 0x0000ffff886cf4e8  98 73 54 88 ff ff 00 00 08 be 5b 88 ff ff 00 00  ·sT·ÿÿ···¾[·ÿÿ··
x10 0x000000000000ffff  65535
x11 0x0000000000000000  0
x12 0x0000000000000000  0
x13 0x0000000000000001  1
x14 0x0000aaaab8e3ff2c  05 00 00 00 d4 2e a7 ff 00 00 03 00 51 00 00 00  ····Ô.§ÿ····Q···
x15 0x0000000000000009  9
x16 0x0000aaaab8d70520  f8 b0 54 88 ff ff 00 00 b4 45 55 88 ff ff 00 00  ø°T·ÿÿ··´EU·ÿÿ··
x17 0x0000ffff8854b0f8  ff 43 01 d1 fd 7b 02 a9 f6 57 03 a9 f4 4f 04 a9  ÿC·Ñý{·©öW·©ôO·©
x18 0x0000000000000000  0
x19 0x0000ffff58002038  03 03 00 00 00 00 00 00 01 00 00 00 01 00 00 00  ················
x20 0x0000ffff62fddff0  40 b4 01 5c ff ff 00 00 20 83 d1 b8 aa aa 00 00  @´·\ÿÿ·· ·Ñ¸ªª··
x21 0x0000000000000006  6
x22 0x0000000000000000  0
x23 0x0000aaaab86688b0  09 00 40 f9 09 01 00 f9 c0 03 5f d6 ff c3 00 d1  ··@ù···ùÀ·_Öÿ÷Ñ
x24 0x0000ffff5c01b440  f0 9d d9 b8 aa aa 00 00 03 00 00 00 08 00 00 00  ð·Ù¸ªª··········
x25 0x0000aaaab8d18320  0c 9c e2 b8 aa aa 00 00 ec 3c 3a b8 aa aa 00 00  ··â¸ªª··ì<:¸ªª··
x26 0x0000ffff62fde170  6e 69 6c 00 00 00 00 00 00 00 00 00 00 00 00 e3  nil············ã
x27 0x0000ffff62fde0e0  2d 00 00 00 00 00 00 d0 a0 3b de b8 aa aa 00 80  -······Ð ;Þ¸ªª··
x28 0x0000ffff886c6c28  02 02 00 00 00 00 00 00 30 b0 6f 88 ff ff 00 00  ········0°o·ÿÿ··
 fp 0x0000ffff62fddf30  b0 df fd 62 ff ff 00 00 48 b1 54 88 ff ff 00 00  °ßýbÿÿ··H±T·ÿÿ··
 lr 0x0000ffff8854b148  1f 08 00 71 c0 00 00 54 1f 04 00 71 c1 00 00 54  ···qÀ··T···qÁ··T
 sp 0x0000ffff62fddf00  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ················
 pc 0x0000ffff8854b1ec  68 01 40 f9 69 00 40 f9 1f fd 1f f1 f3 83 88 1a  h·@ùi·@ù·ý·ñó···


Images (20 omitted):

0x0000aaaab7d20000–0x0000aaaab8cd6d00 a17d4d145f2d2621f7b9d43c2b2d2a754b69002b swift-nioPackageTests.xctest /pwd/.build/aarch64-unknown-linux-gnu/release/swift-nioPackageTests.xctest
0x0000ffff86a70000–0x0000ffff86c09ec1 d5ef86dde36cbd3289566cf5098226035d76f2e1 libc.so.6                    /usr/lib/aarch64-linux-gnu/libc.so.6
0x0000ffff88160000–0x0000ffff8869e0c8 f62b9374639c58d0b60814a6fbec69d2b596cfc7 libswiftCore.so              /usr/lib/swift/linux/libswiftCore.so

Backtrace took 0.62s

error: Exited with unexpected signal code 11
```

The test is fine for both debug and release mode on Swift 6.0, 6.1, and
6.3-nightly.

### Modifications:

Since this is a valid construction and the crash is a Swift bug, and
since it only manifests on a specific Swift version, and since it's only
triggered when mis-using the API, we can just not perform this part of
the test on Swift 6.2. The API is fully functional when used correctly.

### Result:

Running NIO tests, compiled in release mode, no longer crashes on Swift
6.2.3.

### Local testings:

With this branch:

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test -c release --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for production...
[8/8] Linking swift-nioPackageTests.xctest
Build complete! (38.46s)
Test Suite 'Selected tests' started at 2026-02-18 14:23:12.902
Test Suite 'Selected tests' passed at 2026-02-18 14:23:12.902
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.
✔ Test testUnderlyingSocketAccessForSocketBasedChannel() passed after 0.002 seconds.
✔ Suite NIOTransportAccessibleChannelCoreTests passed after 0.003 seconds.
✔ Test run with 1 test in 1 suite passed after 0.003 seconds.
```
2026-02-18 15:11:55 +00:00
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
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
scottmarchant 90ed88baab test: Port NIOThreadPoolTest to Swift Testing. (#3490)
Ports NIOThreadPoolTest in NIOPosix from XCTest to Swift Testing.

### Motivation:

Tests should use the latest Swift Testing framework when possible.

### Modifications:

- Ported `NIOThreadPoolTest` from XCTest to Swift Testing
- Updated test implementation from Dispatch to Swift Concurrency as
needed to support test functionality

### Result:

All tests continue to pass, NIOThreadPoolTest now has more modern Swift
Testing syntax.
2026-02-06 15:19:18 +00:00
scottmarchant e0476c6072 test: Port EventLoopFutureTest to Swift Testing. (#3491)
Port `EventLoopFutureTest` to Swift Testing. Includes some adjustments
to ensure tests are ran from the event loop, among other minor changes

### Motivation:

Tests should use the latest Swift Testing framework when possible.

### Modifications:

- Ported `EventLoopFutureTest ` from XCTest to Swift Testing
- Consolidated instantiations of `EmbeddedEventLoop()` into a private
function called `makeEventLoop` to allow for easier injection of a
different loop from a single location.
- Migrated some `.wait` usages to `.get` to allow tests to run async.

### Result:

All tests continue to pass, EventLoopFutureTest now has more modern
Swift Testing syntax.
2026-02-05 08:24:43 +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 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
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 f2ebedb36a The formatter changed its mind (#3379) 2025-09-23 14:58:24 +01: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 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
George Barnett 6b484ecafc Make testMetricsDelegateTickInfo less flaky (#3335)
Motivation:

testMetricsDelegateTickInfo fails occasionally because there are more
event loop ticks than it expects. This is because the expectation in the
test was incorrect.

Modifications:

- Update the test expectation and an explanation of how we got to that
number.
- Shutdown the ELG while we're at it.

Result:

Tests are less flaky
2025-08-07 14:40:57 +00: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
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
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
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
Roman A f3645a02b7 a couple grammar fixes (#3259) 2025-05-30 10:34:44 +00: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
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 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
George Barnett c420f0d4e6 Enable strict concurrency for NIOPosixTests (#3211) 2025-04-16 13:00:13 +00:00
George BarnettandCory Benfield ae60dc3e07 Strict concurrency for SAL tests (#3205)
Motivation:

The syscall abstraction layer tests aren't sendable clean.

Modifications:

- Factor out the setup/teardown of SAL tests into a SALContext
- SALContext a method to run a SAL test with two closues: one on the
hooked event loop and another on the calling thread.
- The EL bound closure is provided with the EL and locked boxes for the
user ot kernel and kernel to user boxes.
- The closure on the calling thread is provided with an 'assertions'
object which provides a view over the hooked selector.
- Note that there are still sendable holes in this code.
- Refactored the tests to use these APIs.

Results:

Safer tests.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-16 10:41:32 +00:00
George Barnett b7d4e5b050 Strict concurrency for a handful more NIOPosixTests (#3199) 2025-04-14 11:42:56 +00:00
George BarnettandCory Benfield d0fb818d9c Strict concurrency for NIOPosixTests EchoServerClient (#3195)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-10 19:22:48 +00:00
George BarnettandCory Benfield 25394096e5 Strict concurrency for NIOPosixTests, EL and ELF (#3193)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-10 14:18:10 +00:00
George Barnett f9fd017096 Remove unchecked from SelectorTest (#3192)
Motivation:

One of the SelectorTests used an `@unchecked Sendable` box which did
runtime checking of the `EventLoop`. We have a type for this already,
it's called `NIOLoopBoundBox`, we should use it.

Modifications:

- Replace `Box` with `NIOLoopBoundBox`

Result:

Fewer `@unchecked Sendable`s
2025-04-10 10:45:20 +01:00
George Barnett a0df65d474 Strict concurrency for NIOPosix ChannelTests (#3191) 2025-04-09 13:22:42 +00:00
George Barnett 3fd5e7484f Strict concurrency for NIOPosix StreamChannelsTest (#3189) 2025-04-09 12:08:27 +00:00
George Barnett 431b5097ae Strict concurrency for NIOPosix NonBlockingFileIOTest (#3188) 2025-04-09 11:12:22 +00:00
George BarnettandGus Cairo cee62a0354 Strict concurrency for NIOPosix SelectorTest (#3190)
Co-authored-by: Gus Cairo <me@gustavocairo.com>
2025-04-09 09:42:16 +00:00
George Barnett 18408abca3 Strict concurrency for NIOPosix ChannelPipelineTests (#3184) 2025-04-08 15:25:25 +00:00
George Barnett 06b7d4c9cc Strict concurrency for NIOPosix AcceptBackoffHandlerTests (#3182) 2025-04-08 15:00:42 +00:00
George Barnett 83441a3bb3 Strict concurrency NIOPosix EventLoopTest (#3185) 2025-04-08 13:49:14 +00:00
George Barnett f35421bd63 Strict concurrency for NIOPosix BootstrapTest (#3183) 2025-04-08 13:20:43 +00:00
George BarnettandRick Newton-Rogers 202f987738 Strict concurrency for NIOHTTP1Tests (#3169)
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2025-04-07 11:27:05 +01:00
George Barnett 825d963ea1 Use overflow addition in tests to avoid compilation failures (#3155)
Motivation:

A few tests are failing to compiler on 32-bit platforms with recently
nightly toolchains. These tests are skipped if `Int` is 32 bits wide but
the compiler doesn't know that.

Modifications:

- Use overflow addition to stop the compiler from complaining; the
addition won't ever actually overflow because of the runtime check done
ahead of time.

Result:

- Tests compile again
- Resolves #3154
2025-03-27 11:31:36 +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
Honza Dvorsky 450880a7b1 Add a missing import to CNIOLinux (#3140)
### Motivation:

Same as https://github.com/apple/swift-nio-extras/pull/251, just for
swift-nio.

### Modifications:

Added the missing import.

### Result:

Fixes a CI diagnostic.
2025-03-11 15:33:37 +00:00
George Barnett 4f2d42f83f Remove side effect from assertion in IPHeaderRemoverHandler (#3129)
Motivation:

The 'testRawSocketBootstrap_withProtocolNegotiation' test times out when
run in release mode. This is because 'IPHeaderRemoverHandler' removes
the IPv4 headers as a side effect of an assertion. This means that the
headers are only removed when compiled in debug mode.

Modifications:

Always remove the headers.

Result:

The test passes in release mode.
2025-03-05 18:03:22 +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
Tim CondonandCory Benfield ac79370dee Add ChannelPipeline.SynchronousOperations.Position (#3065)
Adds a new `ChannelPipeline.SynchronousOperations.Position` type to fill
a hole in the API that prevented non-sendable Channel handlers being
added at a position to the pipeline via the synchronous operations.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-02-04 10:31:29 +00:00
Cory Benfield 0c547a717c Fix the HappyEyeballsResolver and core Bootstraps under strict concurrency (#3062)
### Motivation:

The HappyEyeballsResolver, being an old part of our stack, has a lot of
code in it that fails to pass strict concurrency checking. That's deeply
suboptimal.

### Modifications:

- Clean up the happy eyeballs resolver under strict concurrency
- Further cleanups to the bootstraps

### Result:

Another step taken on the road to strict concurrency.
2025-01-23 13:22:18 +00:00