## 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
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.
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.
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.
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.
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.
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.
### 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:
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
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.
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
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>
### 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:
`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
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>
### 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
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>
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
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
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>
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.
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>
### 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.
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>
### 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.