### Motivation:
`testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only` would fail
sometimes leaking the IPv4 promise in `GetaddrinfoResolver`
`HappyEyeballsConnector` returns the connection when it resolves either
IPv4 of IPv6. It uses the `GetaddrinfoResolver` which holds a promise
for each of the IPv4 and IPv6 resolution; when one is completed the
connection will be returned and it is possible to start tearing down the
test and shutting down the event loop before the other is completed and
we leak the promise.
### Modifications:
Complete both futures on the event loop rather than the dispatch queue.
### Result:
The futures are completed in the same event loop tick meaning that we
cannot continue execution and leak one.
Motivation:
The compiler now self-presents as 6.2 on the nightlies, and the executor
takeover still works. Lift the guard.
Modifications:
Lift the guard on compiler version.
Result:
Integration tests pass again.
After the changes introduced in
https://github.com/apple/swift-nio-http2/pull/487, we need to make a
small change in the implementation of `NIOAsyncChannel` to wait on the
`closeFuture` instead of on `close`'s promise in the `executeThenClose`
implementation.
### Motivation:
`executeThenClose` shouldn't fail from errors arising from closing the
channel - at this point, the user of the channel cannot really do
anything, and since the channel has been closed, we should not fail
since resources have been cleaned up anyways.
### Modifications:
This PR changes the implementation of `NIOAsyncChannel` to wait on the
`closeFuture` instead of on `close`'s promise in the `executeThenClose`
implementation.
It also updates the docs for `closeFuture` to better explain when it
will be succeeded and why it won't ever be failed.
### Result:
`executeThenClose` won't throw errors upon closing.
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
See https://github.com/apple/swift-nio/pull/3021
Motivation:
NIOEmbedded is used all over NIO-land for testing various pieces of the
infrastructure, and so requires a substantial audit for strict
concurrency.
Modifications:
- Mark a few things Sendable.
- Fix the tests, which actually did have some nasty bugs
Result:
Sendable-clean NIOEmbedded
Motivation:
Users writing NIO code in a strict concurrency world often need to
interact with futures, promises, and event loops. The main interface to
these has strict sendability requirements, as it is possible the user is
doing so from outside the EventLoop that provides the isolation domain
for these types.
However, in many cases the user knows that they are on the isolation
domain in question. In that case, they need more capabilities. While
they can achieve their goals with NIOLoopBound today, it'd be nice if
they had a better option.
Modifications:
- Make EventLoop.Isolated public.
- Make EventLoopFuture.Isolated public.
- Make EventLoopPromise.Isolated public.
- Make all their relevant methods public.
- Move the runtime isolation check from the point of use to the point of
construction.
- Make the types non-Sendable to ensure that isolation check is
sufficient.
- Add unsafeUnchecked options to create these types when performance
matters and correctness is clear.
- Add tests for their behaviour.
- Update the documentation.
Result:
Writing safe code with promises, futures, and event loops is easier.
### Motivation:
SwiftNIO contained a bogus error message:
```
BUG in SwiftNIO (please report), unleakable promise leaked.:486: Fatal error: leaking promise created at (file: "BUG in SwiftNIO (please report), unleakable promise leaked.", line: 486)
```
The actual meaning is that the ELG was shut down prematurely.
### Modifications:
- Replace the message with an accurate one
### Result:
- Users less confused
- fixes#2855
- fixes#2201
I added this changed function call for Android in #2660 earlier this
year, because of [an incorrect Bionic function signature as explained
recently](https://github.com/apple/swift-nio/pull/3009#discussion_r1864807270),
but now that it has been worked around through a new API note as
mentioned there, this change is no longer needed.
I simply did not notice this earlier because it still compiles and
merely gives a warning, which removing this call now silences.
Motivation:
6.0.3 added new warnings about Sendable issues, so let's fix those to
keep things warnings free.
Modifications:
A bunch of Sendable usage fixes.
Result:
Warnings free builds again!
Motivation:
The not-actually-public `_NIOBase64` module has public extensions on
`String`. These are visible when transitively depending on `_NIOBase64`
but shouldn't be.
Modifications:
- Add underscored variants
- Deprecate public variants
Result:
Stricter API
Removes an outdated recommendation about shutting down
`MultiThreadedEventLoopGroup`s before the program exits. It's now
considered best practice to just exit the application and allow the host
OS to do resource clean up.
Introduce parallel removal of items, instead of only doing a sequential
removal (and discovery) one-by-one
### Motivation:
#2933 mentioned this function call appears to be slow. If we attempt to
delete a directory with lots of subdirectories, we end up discovering
each subdirectory one by one on a single thread.
### Modifications:
This PR refactors the logic to remove items. Instead of sequentially
discovering and deleting items one by one, we traverse all directories
up to a maximum concurrency, and issue file deletions in parallel within
each directory.
### Result:
The new concurrent implementation was measured to be ~1.4x faster than
`FileManager`, ~1.5x faster than `rm -rf` and ~3x faster than the
current sequential implementation on `main`. This new concurrent
implementation does use the most CPU out of all the other approaches.
Results are broken down into two sections. We delete a copy of the
`swift-nio` repository, where the `.build/` folder has grown to a large
size, providing lots of additional files and subdirectories.
We produce a single CLI using `--configration=release` that can switch
between using the `.sequential` mode (what is currently available on the
`main` branch), `.parallel` (the new concurrent implementation in this
PR) and `filemanager` (uses `Foundation.FileManager` as a comparison).
Resolves https://github.com/apple/swift-nio/issues/2933
#### Normal size
**Description:** The `swift-nio` library as found when building the CLI
used for benchmarking.
**Benchmark run with:** 3579 directories, 11657 files
```
$ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio"
Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio
Time (mean ± σ): 2.712 s ± 0.053 s [User: 0.526 s, System: 8.632 s]
Range (min … max): 2.625 s … 2.781 s 10 runs
Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio
Time (mean ± σ): 896.7 ms ± 25.6 ms [User: 302.9 ms, System: 5313.5 ms]
Range (min … max): 853.2 ms … 942.1 ms 10 runs
Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio
Time (mean ± σ): 1.337 s ± 0.076 s [User: 0.022 s, System: 1.253 s]
Range (min … max): 1.252 s … 1.508 s 10 runs
Benchmark 4: rm -rf /tmp/swift-nio
Time (mean ± σ): 1.483 s ± 0.037 s [User: 0.015 s, System: 1.416 s]
Range (min … max): 1.413 s … 1.541 s 10 runs
Summary
.build/release/NIOTestCLI --parallel /tmp/swift-nio ran
1.49 ± 0.10 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio
1.65 ± 0.06 times faster than rm -rf /tmp/swift-nio
3.02 ± 0.10 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio
```
#### Large size
**Description:** The `swift-nio` library as found after re-running the
`.github` workflow many times locally. I'm unable to reproduce this
directory size, but have benchmarked against it.
**Benchmark run with:** 15260 directories, 46842 files
```
$ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio"
Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio
Time (mean ± σ): 12.082 s ± 0.354 s [User: 2.180 s, System: 41.547 s]
Range (min … max): 11.717 s … 12.923 s 10 runs
Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio
Time (mean ± σ): 4.770 s ± 0.102 s [User: 1.357 s, System: 25.785 s]
Range (min … max): 4.570 s … 4.883 s 10 runs
Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio
Time (mean ± σ): 6.503 s ± 0.115 s [User: 0.081 s, System: 5.427 s]
Range (min … max): 6.262 s … 6.687 s 10 runs
Benchmark 4: rm -rf /tmp/swift-nio
Time (mean ± σ): 7.056 s ± 0.246 s [User: 0.064 s, System: 6.119 s]
Range (min … max): 6.435 s … 7.233 s 10 runs
Summary
.build/release/NIOTestCLI --parallel /tmp/swift-nio ran
1.36 ± 0.04 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio
1.48 ± 0.06 times faster than rm -rf /tmp/swift-nio
2.53 ± 0.09 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio
```
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation
Code that tries to work with `NIODeadline` can be challenging to test
using `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` because they
have their own, fake clock.
These testing event loops do implement `scheduleTask(in:_)` to submit
work in the future, relative to the event loop clock, but there is no
way to get the event loop's current notion of "now", as a `NIODeadline`,
and users sometimes find that `NIODeadline.now`, which returns the time
of the real clock, to be surprising.
### Modifications
Add `EventLoop.now` to get the current time of the event loop clock.
### Result
New APIs to support writing code that's easier to test.
Motivation:
`UnsafeRawBufferPointer.init(fastRebase:)` and
`UnsafeMutableRawBufferPointer.init(fastRebase:)` were shimmed into NIO
in https://github.com/apple/swift-nio/pull/1696. The shim is no longer
necessary.
Modifications:
- Revert the use of the `fastRebase` inits to the native
`.init(rebasing:)`.
Result:
Use of native APIs instead.
### Motivation:
Get this repo building again for Android with NDK 27
### Modifications:
- Update some networking declarations for newly added nullability
annotations
- Import the new Android overlay instead in some tests
- Add two force-unwraps on all platforms, that are needed for Android
### Result:
This repo and its tests build for Android again
I've been [using these patches on my Android
CI](https://github.com/finagolfin/swift-android-sdk/blob/main/swift-nio-ndk27.patch)
and natively on Android for a couple months now. I didn't bother keeping
this patch building for Android with Swift 5 anymore, as my Android CI
no longer tests Swift 5.
I built this pull and ran the tests on linux x86_64 to make sure there
was no regression.
Motivation:
When converting an Array that holds existentials, it is necessary for
Swift to allocate a new Array and copy the elements into it, so that it
can fix up their existential boxes. We forced this to happen with taking
a `[ChannelHandler]` to `[ChannelHandler & Sendable]`, without rewriting
the other functions.
The result of that was that the other functions needed to convert the
channel handler types, causing extra allocations in this path.
Modifications:
Propagate the constraint down to the point where we iterate the Array.
Result:
Allocations reduced.
Motivation:
In #2598, `NIOFileHandle` was annotated with `noasync` in a few places.
This is, unfortunately, a breaking change.
Modifications:
- Remove the `noasync` annotations
Result:
Adopters aren't broken
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
In vanishingly rare situations it is possible for the AAAA results to
come in on the same tick as the resolution delay timer completes. In
those cases, depending on the ordering of the tasks, we can get
situations where the resolution delay timer completion causes a crash.
Modifications:
Tolerate receiving the resolution delay timer after resolution
completes.
Result:
Fewer crashes
### Motivation:
Warnings are annoying.
### Modifications:
- Remove unnecessary use of `Foundation.Thread` which isn't Sendable.
- Remove now unnecessary `@retroactive`s.
- Enable `-warnings-as-errors` in CI
### Result:
- Warnings can't sneak in as easily anymore
- No more warnings left in `swift-nio`
```
$ rm -rf .build/arm64-apple-macosx/ && swift build --build-tests -Xswiftc -warnings-as-errors > /dev/null
echo $?
$ echo $?
0
```
Co-authored-by: Cory Benfield <lukasa@apple.com>
Updates to documentation comments in `NIOFileSystem`.
### Motivation:
I've been reviewing some parts of `NIOFileSystem` and came across a
variety of formatting of documentation comments.
### Modifications:
I've adopted a stricter 100-character limit (arbitrary, really; it could
be longer or shorter and is totally not consistent with the rest of the
repository). Also updated a bunch of grammar in comments. Fixed a few
typos along the way.
### Result:
- Updated comments have a better flow while reading, and aren't as
abrupt as before.
- Fewer typos in comments
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
When getting a `Data` from a `ByteBuffer` we currently allocate twice
(`__DataStorage`) and the closure for `Data.Deallocator`.
Modifications:
We can optimise that by making the closure capture exactly one
`AnyObject` which is already a reference counted object. The compiler
realises that (on Linux) and saves us an alloc.
Thanks @lukasa for the suggestion here:
https://github.com/apple/swift-nio/pull/1836#issuecomment-830044155
Result:
Fewer allocs.
### Motivation:
`NIOEventLoopGroupProvider.createNew` was probably never a good idea
because it creates shutdown issues for any library that uses it. Given
that we now have singleton (#2471) `EventLoopGroup`s, we can solve this
issue by just not having event loop group providers.
Users can just use `group: any EventLoopGroup` and optionally `group:
any EventLoopGroup = MultiThreadedEventLoopGroup.singleton`.
### Modifications:
- deprecate `NIOEventLoopGroupProvider.createNew`
- soft-deprecate (document as deprecated but don't mark
`@available(deprecated)`) `NIOEventLoopGroupProvider`
### Result:
- Libraries becomes easier to write and maintain.
- Fixes#2142
### Motivation:
Opening the `swift-nio` repository made me warning blind because there
were always so many trivially fixable warnings about things that were
correct but cannot be understood by the compiler.
### Modifications:
Fix all the sendable warnings that popped up, except for one test where
`NIOLockedValueBox<Thread?>` isn't sendable because `Foundation.Thread`
seemingly isn't `Sendable` which is odd. Guessing that'll be fixed on
their end.
### Result:
- Fewer warnings
- Less warning-blindness
- More checks
Motivation:
`IOData` is a legacy but alas also core type that needs to be
`Sendable`. Before this PR however it can't be `Sendable` because it
holds a `FileRegion` which holds a `NIOFileDescriptor`. So let's make
all of these `Sendable` but let's also start the deprecation journey for
the following types:
- `IOData`, now soft-deprecated (no warnings) because on its reliance on
`FileRegion`
- `FileRegion`, now soft-deprecated (no warnings) because on its
reliance on `NIOFileHandle`
- `NIOFileHandle`, now soft-deprecated (warnings on the
`NIOFileHandle(descriptor:)` constructor but with a
`NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor:)` alternative
- `NonBlockingFileIO`, now soft-deprecated (warnings on the `openFile`
functions (but with `_deprecated` alternatives) because of their
reliance on `NIOFileHandle)
Modification:
- Make `NIOFileDescriptor`, `FileRegion` and `IOData` `Sendable` by
tracking the fd number and the usage state in an atomic
- Enforce singular access by making the `withFileDescriptor { fd ... }`
function atomically exchange the fd number for a "I'm busy" sentinel
value
- Start deprecating `IOData`, `NIOFileHandle`, `NonBlockingFileIO`,
`FileRegion`
Result:
- `NIOFileDescriptor`, `FileRegion` and `IOData` can be `Sendable`
Motivation:
The high/low watermark backpressure strategy assumes that a yield can
never happen when there's no outstanding demand. It's reasonably easy
for this to not be a true: a handler decoding messages in a loop, for
example, may not pay attention to `read() calls and produce when there's
no outstanding demand. The channel should of course not read from the
socket, so produced values will stop being produced.
Modifications:
- Alter the high/low watermarks such that demand is only enabled when
the buffer depth is below the low watermark, and only disabled when
above the high watermark.
Result:
Fewer crashes
### Motivation:
In many situations, for example continuous profiling with sampling
profilers, it's important to distinguish between on- and off-CPU work.
That's most easily done if there are clear function names/prefixes to
grep for that are common places to just wait (off-CPU) and do no real
work. In SwiftNIO those are chiefly three places:
1. The `EventLoops` waiting for work
2. `The NIOThreadPool` threads waiting for work
3. `EventLoopFuture.wait()`
This patch makes sure that each of those will have a function with
prefix `_blockingWaitFor` in the function name which is easily
greppable.
### Modifications:
- Create some non-inlinable functions with `_blockingWaitFor...` that
just wait for `...`.
### Result:
SwiftNIO makes operational excellence easier and your SRE team more
happy.
### Motivation:
In some (probably niche) scenarios, especially in pre-Concurrency UI
applications on Darwin, it can be useful to wait for an a value whilst
still running the current `RunLoop`. That allows the UI and other things
to work whilst we're waiting for a future to complete.
### Modifications:
- Add `NIOFoundationCompat.EventLoopFuture.waitSpinningRunLoop()`.
### Result:
Better compatibility with Cocoa.
Add methods to ByteBuffer to read validated UTF8 strings
### Motivation:
The current `readString` and `getString` methods of `ByteBuffer` do not
verify that the string being read is valid UTF8. The Swift 6 standard
library comes with a new initialiser `String(validating:as:)`. This PR
adds alternative methods to ByteBuffer which uses this instead of
`String(decoding:as:)`.
### Modifications:
Added `ByteBuffer.getUTF8ValidatedString(at:length:)`
Added `ByteBuffer.readUTF8ValidatedString(length:)`
### Result:
You can read strings from a ByteBuffer and be certain they are valid
UTF8
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
We have some tests for our Vsock support that only run when we detect
the system supports Vsock. These weren't running in CI but, now we've
migrated CI to GitHub Actions, they can. In prototyping this though, I
discovered that one of our tests was too strict, and will fail for VMs
running on Hyper-V, which is the hypervisor used by GitHub actions.
Specifically, we have support for getting the local context ID by a
channel option. This is implemented by an ioctl, but the semantics of
the return value differ between the various Vsock transport kernel
modules:
- `virtio_transport`: returns the guest CID, which is a number greater
than `VMADDR_CID_HOST`, but less than `VMADDR_CID_ANY`, and returns
`VMADDR_CID_ANY` as an error.
- `vsock_loopback`: returns `VMADDR_CID_LOCAL` always.
- `vmci_transport`: returns the guest CID if the guest and host
transport are active; `VMADDR_CID_HOST` if only the host transport is
active; and `VMCI_INVALID_ID` otherwise, which happens to be the same
value as `VMADDR_CID_ANY`.
- `hyperv_transport`: returns `VMADDR_CID_ANY` always.
For this reason, we should probably remove any attempts to interpret the
validity of the value that comes back from the driver and users will
need to know what to do with it.
### Modifications:
- tests: Only run Vsock echo tests on Linux, when `vsock_loopback` is
loaded.
- tests: Remove asserts on the value of local Vsock CID.
- ci: Add pipeline that runs Vsock tests.
### Result:
- Vsock tests will no longer run unless `vsock_loopback` kernel module
is loaded.
- Vsock tests will no longer fail in Hyper-V VMs.
- Vsock tests will now run in CI.
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:
The thread performance checker warns that a threads with QoS are waiting
on threads in the NIOThreadPool. We can avoid these warnings by using a
condition variable instead.
Modifications:
- Replace the usage of a semaphore and lock in NIOThreadPool with a
condition lock.
- The condition value indicates whether the threads have work to do
(where work is processing work items or exiting their run loop).
Result:
- Fewer warnings
- Resolves#2960
Add support for treating WebSocketFrame reserved bits as an option set
### Motivation:
I would like to do mask operations on the reserved bits of the
WebSocketFrame eg check none are set, check only bits in a mask are set.
With the current public interface it is only possible to check the state
of one bit at a time.
### Modifications:
Add `WebSocketFrame.ReservedBits` OptionSet
Add computed member `WebSocketFrame.reservedBits`
### Result:
I can now check the status of multiple bits in one operation eg
`frame.reservedBits.isEmpty`
`frame.reservedBits.itersection([.rsv1, .rsv2]).isEmpty`
### Motivation:
Teaching the compiler that NIO is safe is good.
### Modifications:
Use NIOLoopBound and friends to explain.
### Result:
Fewer warnings.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Check for half closure during server upgrade and close channel if client
closes the channel
### Motivation:
This is to fix#2742
### Modifications:
Add `userInboundEventTriggered` function to
`NIOTypedHTTPServerProtocolUpgrader` which checks for
`ChannelEvent.inputClosed`
### Result:
Negotiation future now errors when client closes the connection instead
of never completing
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
Motivation:
ManagedBuffer is marked as explicitly not sendable on Swift nightly
builds. NIOLock and NIOLockedValueBox used a type derived from
ManagedBuffer and must be Sendable. Currently the derived type is marked
as `@unchecked Sendable`. However on nightly toolchains this now
conflicts with being explicitly not Sendable.
Modifications:
- Remove Sendable checking on NIOLock and NIOLockedValueBox
Result:
Fewer warnings
### 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:
With our earlier big refactors, NIOCore is now currently strict
concurrency clean. Let's lock in the win by adopting the relevant Swift
settings and fixing up the tests.
Modifications:
- Adopt our strict concurrency settings in NIOCore and NIOCoreTests
- Clean up the tests
Result:
One step closer to a world without warnings.
Motivation:
The ChannelInvoker protocols are an awkward beast. They aren't really
something that people can do generic programming against. Instead, they
were designed to do API sharing. Of course, they didn't do that very
well, and the strict concurrency checking world has revealed this.
Much of the API surface on ChannelInvoker is confused. There are
NIOAnys, which aren't Sendable. We allow sending user events without
requiring Sendable. And our two main conforming types are
ChannelPipeline and ChannelHandlerContext, two types with wildly
differing thread-safety semantics.
This PR aims to clean that up.
Modifications:
- Deprecated all API surface on ChannelInvoker protocols that uses
NIOAny.
ChannelInvoker has to be assumed to be a cross-thread protocol,
and that requires that it only use Sendable types. NIOAny isn't,
so these methods are no longer sound.
- Re-add non-deprecated versions on ChannelHandlerContext.
While it's not safe to use the NIOAny methods on Channel or
ChannelPipeline, it's totally safe to use them on
ChannelHandlerContext. So we keep those available and
undeprecated.
- Provide typed generic replacements on ChannelPipeline and on Channel
To replace the NIOAny methods on ChannelPipeline and Channel
we can use some typed generic ones instead. These are not
defined on ChannelInvoker, as the methods are useless on
ChannelHandlerContext. This begins the acknowledgement that
ChannelHandlerContext should not have conformed to these
protocols at all.
- Add Sendable constraints to the user event witnesses on ChannelInvoker
Again, these were missing, but must be there for Channel and
ChannelPipeline.
- Provide non-Sendable overloads on ChannelHandlerContext
ChannelHandlerContext is thread-bound, and so may safely pass
non-Sendable user events.
Result:
One step closer to strict concurrency cleanliness for NIOCore.
Add new protocol to get buffered bytes from `ChannelHandler`s and
`ChannelPipeline` API to query the buffered bytes from `ChannelHandler`s
### Motivation:
In #2849, a new `ChannelOption` is introduced to retrieve the number of
buffered outbound bytes in a `Channel`. However, this solution does not
account for bytes that may be buffered within individual
`ChannelHandler`s. This PR builds on #2849 by adding functionality to
audit buffered bytes residing in `ChannelHandler`s and exposing this
information through new `ChannelPipeline` APIs.
### Modifications:
- Two new protocols for `ChannelHandler` to audit buffered bytes for
inbound and outbound.
- `NIOOutboundByteBufferingChannelHandler`
- `NIOInboundByteBufferingChannelHandler`
- New `ChannelPipeline` APIs
- outboundBufferedBytes()
- outboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)
- inboundBufferedBytes()
- inboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)
### Result:
Users can now easily query the amount of bytes buffered in
`ChannelHandler`s using the new `ChannelPipeline` APIs, enhancing the
visibility of `ChannelHandler` performance.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### 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:
RemovableChannelHandlers have a large API surface in NIOCore. That API
surface is a bit awkward with regard to strict concurrency, and needs
some cleanup.
Modifications:
This patch adds some new API that is necessary to safely work with
RemovableChannelHandlers, deprecates some API that cannot plausibly be
used, and cleans up some other parts of the API.
Result:
Easier to work with RemovableChannelHandlers
# Motivation
It was currently possible that the producer's delegate is getting called
twice with `produceMore` even if no `yield` returned a `stopProducing`.
This could happen when we expected the producer to yield elements but
the consumer went below the low watermark again. Resulting in two
subsequent calls.
# Modification
This PR stores the current demand state in the strategy which let's us
avoid flipping the `hasOustandingDemand` state of the sequence.
# Result
Correctly, ensured the call order of `produceMore` and `stopProducing`.
### Motivation:
`EmbeddedChannel` & `EmbeddedEventLoop` currently violate `Sendable`.
They should store the current thread in `init` and then implement
`inEventLoop` and other functions with a check that the current thread
is correct.
Since NIO 1.0 `Embedded*` were always documented to not be thread-safe
but we should finally police this.
### Modifications:
- Implement the thread check
- For now, just warn (soon hopefully crash)
- Delete EmbeddedScheduledCallbackTests (#2950)
### Result:
- Less Embedded* abuse
- fixes#2949
Add Vision support
### Motivation:
https://github.com/apple/swift-nio/issues/2900 - close this
### Modifications:
- Bump SystemPackage to 1.4.0 and remove @preconcurrency
- remove `#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) ||
os(Linux) || os(Android)` to allow for visionOS support
- Remove conditional import for swift system
### Result:
Vision OS support
### Motivation:
`swift build --arch x64_64 --arch arm64` on at least Xcode 15.4 fails
with
```
/Users/johannes/devel/my-proj/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift:93:18: error: '_scheduleCallback' has a package access level but no -package-name was specified: /Users/johannes/devel/tfai-swift/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift
package func _scheduleCallback(
^
```
That's clearly an Xcode bug but that needs a workaround.
### Modifications:
- Don't use the `package` modifier for now
### Result:
SwiftNIO builds again.
### Motivation:
On Darwin, QoS (quality of service) of threads plays an important role,
especially on Apple Silicon machines with P-cores and E-cores. If you
spawn raw threads (like NIOPosix) and use a mechanism that doesn't
support QoS propagation (like reading/writing to networks -- like
NIOPosix does), it's recommended to default to the main thread's QoS.
Otherwise you'll always be at the default QoS for "legacy" threads which
means bad latencies, especially on Apple Silicon machines.
In a follow-up PR #2943 we're adding better configurability for thread
configuration.
### Modifications:
Default to main thread QoS on Darwin.
### Result:
Better latencies for applications with higher QoS classes.
Motivation:
The async flavour of withConnectedSocket accidentally type-erased the
channel, which caused it to be unable to be used.
Modifications:
Un-erase the type of the channel.
Add a test.
Result:
withConnectedSocket works again
Resolves#2936