### 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.
### 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).
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:
All of NIO's channels are thread-safe, and that includes the NIOPosix
ones. In an ideal world we'd have written these in such a way that they
rely on very small, easily-verified types to enforce this constraint. We
will migrate towards that in time, but for expediency we can mark these
as they are, which is `@unchecked Sendable`.
### Modifications:
Mark the core NIOPosix channel types `@unchecked Sendable`.
### Result:
Fewer warnings.
Motivation:
When a connected datagram socket sends a datagram to a port or host that
is not listening, an ICMP Destination Unreachable message may be
returned. That message triggers an ECONNRESET to be produced at the
socket layer.
On Darwin we handled this well, but on Linux it turned out that this
would push us into connection teardown and, eventually, into a crash.
Not so good.
To better handle this, we need to distinguish EPOLLERR from EPOLLHUP on
datagram sockets. In these cases, we should check whether the socket
error was fatal and, if it was not, we should continue our execution
having fired the error down the pipeline.
Modifications:
Modify the selector code to distinguish reset and error. Add support for
our channels to handle errors.
Have most channels handle errors as resets.
Override the logic for datagram channels to duplicate the logic in
readable.
Add a unit test.
Result:
Better datagrams for all.
### Motivation:
Documentation checking catches more issues in Swift 6.0.
### Modifications:
Adopt the Swift 6.0 image and fix the errors.
### Result:
More accurate docs.
### Motivation:
We could previously hit an assert do to a re-entrancy issue where
channel and buffered write state could change during a call-out leading
to invalid state.
### Modifications:
The decision on whether or not we should be registered for future writes
is now taken after the call outs to `fireChannelWritabilityChanged` and
`fireChannelReadComplete`. The new registration state is set to
`.unregister` if the channel is not open or if there are now flushed
pending writes.
### Result:
Scope for re-entrancy crashes is reduced.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Since Swift 5.5 and [SE-0299](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0299-extend-generic-static-member-lookup.md) it is possible to add static members to protocols which are discoverable through the shorthand dot syntax.
This change reduces type repetition and improves call-site legibility.
Modifications:
Added extensions for ChannelOption with static members where Self is bound to a concrete type.
Result:
ChannelOption types can be used with the leading dot syntax. For eg:
```
//before
.channelOption(ChannelOptions.explicitCongestionNotification, value: true)
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
//after
.channelOption(.explicitCongestionNotification, value: true)
.channelOption(.socketOption(.so_reuseaddr), value: 1)
```
* Apply formatting
* Apply no block comments rule
* Apply OmitExplicitReturns
* Apple OnlyOneTrailingClosureArgument
* Apply NoAssignmentInExpressions
* Fix up DontRepeatTypeInStaticProperties lint errors
* Apply `OrderedImports`
* Apply `ReplaceForEachWithForLoop`
* format file
* Enable the formatting pipeline
* Adopt `AmbiguousTrailingClosureOverload`
* Fix license header
* Fix format check
* Fix `EndOfLineComment`
* Fix CI
* Adapt CI script to check if changes when running formatting
* Separate lint and format into to steps
* Fix format
* Adopt `UseEarlyExits`
* Revert "Adopt `UseEarlyExits`"
This reverts commit d1ac5bbe12.
Motivation:
Existential errors (`any Error`) are unconditionally boxed. In NIO we
often create errors to fail promises. One place we do this is in the
head channel handler when the pipeline is closed. This error is created
regardless of whether there are actually any promises to fail. The
result is an unnecessary allocation when every channel is closed. This
is particuarly egregious when multiplexed protocols such as HTTP/2 are
used.
As the majority of errors in NIO carry no information beyond their
type/name we can declare these statically and pay the cost of each error
just once rather than once per use.
Modifications:
- Add internal static constants for `ChannelError` and `EventLoopError`
and use them throughout NIOCore and NIOPosix where they would
otherwise be boxed.
Result:
Fewer allocations
* Don't lose or delay writes before channelActive
Motivation:
In rare circumstances, some users have reported hangs, delays, or
lost writes when writing network proxies. These proxies have
typically been derived from our TLSify example:
https://github.com/apple/swift-nio-examples/tree/main/TLSify
This proxy makes its outbound connections in handlerAdded.
Generally this works without issue, as the connection takes
long enough to set up that channelActive fires before the
outbound connection has been made.
However, in some rare circumstances it is possible to both make an
outbound connection, have it succeed, _and_ read from the network
on that connection before NIO activates the inbound channel. This
would cause users to lose writes.
This violates a cardinal NIO rule: writes should never be lost.
If it is practical for us to delay them and apply them later, we
should. This patch addresses several holes in this area to correctly
handle these outbound writes.
The first hole is that we would fail writes if the Channel wasn't
yet active. This constraint was unnecessary: it was added in a
refactor to use an internal state machine, and while we had a test
that this happened, it didn't protect us from anything. We can
safely buffer a write at this point: and indeed, we _do_ buffer
flushes at this point. So the check was unneeded.
The second hole was that, even if we buffered the writes, we
frequently wouldn't unbuffer them again until a flush happened
after channelActive. This didn't happen on _every_ path: in the
rare case that connect() succeeded immediately, we would flush
the writes. But in all other cases, including listening
connections, we needed _another_ flush to happen to get the
writes out.
This fix patches up both issues and reconciles the flows. Now
we _always_ try to push out flushed writes when we activate the
Channel, just as we always try to read.
Modifications:
- Remove a check that failed writes if we weren't active.
- Remove a test that validated that we did that.
- Attempt to emit flushed writes on channelActive.
- Make sure we mark ourselves writable if we couldn't write
it all.
- Make `BaseSocket.getOption` non-final so we can hook it
in the SAL.
- Make `AcceptHandler` non-private so we can use it in tests.
- Extend the SAL to support `getOption`
- Write several SAL tests to ensure we manage our writes.
Result:
No lost writes.
* Code review feedback
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
Motivation:
When an error is hit during a read loop, a channel is able to tolerate
that error without closing. This is done for a number of reasons, but
the most important one is accepting sockets for already-closed
connections, which can trigger all kinds of errors on the read path.
Unfortunately, there was an edge-case in the code for handling this
case. If one or more reads in the loop had succeeded before the error
was caught, the inner code would be expecting a call to readIfNeeded,
but the outer code wouldn't make it. This would lead to autoRead
channels being wedged open.
Modifications:
This patch extends the Syscall Abstraction Layer to add support for
server sockets. It adds two tests: one for the basic accept flow, and
then one for the case discussed above.
This patch also refactors the code in BaseSocketChannel.readable0 to
more clearly show the path through the error case. There were a number
of early returns and partial conditionals that led to us checking the
same condition in a number of places. This refactor makes it clearer
that it is possible to exit this code in the happy path, with a
tolerated error, which should be considered the same as reading
_something_.
Result:
Harder to wedge a channel open.
Motivation:
Channels can read `ChannelOptions.maxMessagesPerRead` times from a
socket in each read cycle. They typically re-use the same buffer for
each read and rely on it CoWing if necessary. If we read more than once
in a cycle then we may CoW the buffer. Instead of reusing one buffer we
can reuse a pool of buffers limited by `maxMessagesPerRead` and cycle
through each, reducing the chance of CoWing the buffers.
Modifications:
- Extend `RecvByteBufferAllocator` to provide the size of the next
buffer with a default implementation returning `nil`.
- Add an recv buffer pool which lazily grows up to a fixed size and
attempts to reuse buffers where possible if doing so avoids CoWing.
Results:
Fewer allocations
* socket: Make destinationPtr param optional in sendmsg(...)
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: Fixup documentation: scalar writes use sendmsg, not sendto
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: Make sockaddr pointer param optional in scalarWriteOperation
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: Add isConnected property to PendingDatagramWritesState
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: If socket is connected use NULL msg_name in sendmsg(2)
Signed-off-by: Si Beaumont <beaumont@apple.com>
* BaseSocketChannel: Support connect after bind
Signed-off-by: Si Beaumont <beaumont@apple.com>
* DatagramChannel: Implement connectSocket(to:)
Signed-off-by: Si Beaumont <beaumont@apple.com>
* bootstrap: Rename bind0(makeChannel:registerAndBind:) to withNewChannel(makeChannel:bringup:)
Signed-off-by: Si Beaumont <beaumont@apple.com>
* bootstrap: Add set of DatagramBootstrap.connect(...) APIs
Signed-off-by: Si Beaumont <beaumont@apple.com>
* test: Remove DatagramChannelTests.testConnectionFails
Signed-off-by: Si Beaumont <beaumont@apple.com>
* test: Add ConnectedDatagramChannelTests, inheriting from DatagramChannelTests
Signed-off-by: Si Beaumont <beaumont@apple.com>
* NIOUDPEchoClient: Use connected-mode UDP
Signed-off-by: Si Beaumont <beaumont@apple.com>
* soundness: Update copyright notice
Signed-off-by: Si Beaumont <beaumont@apple.com>
* fixup: cleanup bootstrap APIs
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: Check address of pending write if connected and add test
Signed-off-by: Si Beaumont <beaumont@apple.com>
* Revert "pdwm: Check address of pending write if connected and add test"
This reverts commit a4ee0756d5.
* channel: Fail buffered writes on connect and validate writes when connected
Signed-off-by: Si Beaumont <beaumont@apple.com>
* Run soundness.sh to get linux tests generated
Signed-off-by: Si Beaumont <beaumont@apple.com>
* NIOUDPEchoClient: Connect socket to remote only if --connect is used
Signed-off-by: Si Beaumont <beaumont@apple.com>
* socket: Support ByteBuffer (without AddressedEnvelope) for DatagramChannel
Signed-off-by: Si Beaumont <beaumont@apple.com>
* test: Simplify some test code
Signed-off-by: Si Beaumont <beaumont@apple.com>
* pdwm: Factor out common, private add(_ pendingWrite:)
Signed-off-by: Si Beaumont <beaumont@apple.com>
* channel: Support AddressedEnvelope on connected socket for control messages
Signed-off-by: Si Beaumont <beaumont@apple.com>
* channel: Defer to common unwrapData for error handling
Signed-off-by: Si Beaumont <beaumont@apple.com>
* channel: Throw more specific (new) errors, instead of IOError
Signed-off-by: Si Beaumont <beaumont@apple.com>
* SocketChannelLifecycleManager: Add supportsReconnect boolean property, used in DatagramChannel
Signed-off-by: Si Beaumont <beaumont@apple.com>
Motivation:
The remaining NIO code really conceptually belongs in a module called
NIOPosix, and NIOCore should really be called NIO. We can't really do
that last step, but we can prepare by pushing the bulk of the remaining
code into a module called NIOPosix.
Modifications:
- Move NIO to NIOPosix
- Make NIO an umbrella module.
Result:
NIOPosix exists.