### Motivation:
`NIOFileSystem` currently exposes the same API as `_NIOFileSystem`,
which is not API stable. `NIOFileSystem`
was created in error, and its lack of underscore incorrectly implies API
stability. Users who are currently importing `NIOFileSystem` should
ideally move to `_NIOFileSystem`. However this isn't made clear in the
docs:
1. The README talks about the non-underscored `NIOFileSystem`.
2. There are no hosted API docs `NIOFileSystem`.
3. The hosted API docs for `NIO` point to the docs for `NIOFileSystem`
-- results in 404.
### Modifications:
- Update the README to refer to `_NIOFileSystem`.
- Update the hosted API docs for `NIO` to point to docs for
`_NIOFileSystem`.
- Add hosted API docs for `NIOFileSystem` with a statement explaining
the situation and pointing people to the docs
for `_NIOFileSystem`.
### Result:
Clearer documentation on the state and relationship of the
`NIOFileSystem` and `_NIOFileSystem` modules.
Motivation:
We changed the file path type in `_NIOFileSystem` to use `NIOFilePath`
instead of `FilePath`. Originally we planned to use API shims to avoid
breaking API, however in some cases this was inevitable (i.e. where a
file path is returned to the caller).
To roll over to the new API we will instead introduce the
`NIOFileSystem` module using `NIOFilePath` and have `_NIOFileSystem` use
`FilePath`. Users can then opt-in to the new stable API rather than
having it forced upon them.
The first wave of these changes turns `_NIOFileSystem` into
`NIOFileSystem` and uses `NIOFilePath` for its APIs.
Modifications:
- Remove disfavoured overloads (i.e. `FilePath` APIs)
- Update the `DirectoryEntry` API to use `NIOFilePath`.
- Update tests to use `NIOFilePath` since many were relying on the newly
removed shims
- Remove the underscore from the module names and products
- Remove deprecated methods
A follow up change will re-instate the `_NIOFileSystem` (and compat)
module and products using `FilePath`.
Result:
`NIOFileSystem` has a stable API.
Motivation:
Our docs for running alloc counting benchmarks are scattered between a
few places, and our info about debugging allocations is also a bit
outdated.
Modifiactions:
- Add a doc on running the two different flavours of allocation counting
test. Remove the entry about bencharks from the README.
- Add a doc on debugging allocations
Most of the content comes from the original
`docs/debugging-allocations.md` doc but has been updated a little and
includes info about the new stackdiff tool.
Result:
Better docs
* [GHA] Unacceptable language check
# Motivation
Next up replacing part of our soundness script that checked for unacceptable language.
# Modification
This PR adds a new GH action that checks for unacceptable language.
# Result
One more script replaced
* PR review
* Change homepage link to repo
Motivation:
The existing link to NIOFileSystem docs 404's
Modifications:
Speculative fixes because getting any links to work locally is
challenging.
* rename `NIOFileSystem.md` -> `index.md` in line with other modules
* modify the link on the NIO index page to reference `_NIOFileSystem`
local experiments suggest it might change the form of the generated
URL to where the docs can be found
(https://swiftpackageindex.com/apple/swift-nio/2.67.0/documentation/_NIOFileSystem).
Result:
Hopefully the NIOFileSystem docs link will work
Motivation:
I/O is typically blocking, but options for interacting with the
filesystem using `async` APIs are limited. This change adds a new module
to NIO, `NIOFileSystem`. At the moment this is exposed as the
`_NIOFileSystem` product while users get a chance to try it out and
provide feedback.
During this time the API of `NIOFileSystem` is subject to change.
Breaking changes will come in _minor_ NIO releases and additive changes
may come in _patch_ releases of NIO.
Modifications:
- Add `NIOFileSystem`, `NIOFileSystemFoundationCompat`,
`NIOFileSystemTests`, `NIOFileSystemIntegrationTests`, and
`NIOFileSystemFoundationCompatTests`.
- Update docs
- Update CNIOLinux and CNIODarwin shims
Result:
File system can be accessed via `async` APIs
Motivation:
Up until recently, it has not been possible to regression check our
documentation. However, in recent releases of the DocC plugin it has
become possible to make warnings into errors, making it possible for us
to CI our docs.
This patch adds support for doing that, and also cleans up our
documentation so that it successfully passes the check.
Along the way I accidentally wrote an `index.md` for `NIOCore` so I
figure we may as well keep it.
Modifications:
- Structure the documentation for NIOCore
- Fix up DocC issues
- Add `check-docs.sh` script to check the docs cleanly build
- Wire things up to our docker-compose scripts.
Result:
We can CI our docs.
Co-authored-by: George Barnett <gbarnett@apple.com>
* initial adoption of DocC based documentaiton
motivation: use DocC for docs
change:
* add DocC catalog to NIO target, as the "landing page"
* remove jazzy doc generation script
* add Package.swift with tools-version 5.6 so that DocC can be used, and add a dependency on the DocC plugin
* udpate soundness script
* * add packge.swift files for older vrsions
* adjust waning-as-error and enable-test-discovery to the different permutations
* fixup
* remove jazzy
Co-authored-by: Cory Benfield <lukasa@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.
Motivation:
EmbeddedChannel is an important testing tool, and we want to use it
without needing to bring along the POSIX layer. They are not tightly
coupled. However, it also doesn't belong naturally in NIOCore, so we
should probably put it in its own place.
Modifications:
- Moved EmbeddedChannel and EmbeddedEventLoop to NIOEmbedded.
- Moved the tests to NIOEmbeddedTests
- Duplicated some test helpers
Result:
Easy to use EmbeddedChannel without the POSIX layer.
Motivation:
I'd like to move EmbeddedChannel and friends out of the main NIO
repository and into their own module. Unfortunately, EmbeddedChannel
shares the PriorityQueue implementation we wrote with the various POSIX
channels. To avoid duplicating the code, we should pull it out to its
own module.
However, we've never wanted to commit to the API of this data structure,
and the same is true now. To that end, I'm pulling it into an
underscored module that is not a product of the package.
We could have used the `@_spi` annotation here but honestly I'm a bit
nervous about doing that at the low-level of NIO itself, as if the Swift
team does change the spelling of it at any point in the future we'll be
in real trouble. This way works almost as well, and makes our intent a
lot clearer.
Modifications:
- Extracted Heap and PriorityQueue to a new module.
- Made everything @inlinable to do our best to make performance
acceptable.
Result:
We can re-use PriorityQueue.
Motivation:
MultcastChannel is a general abstraction for expressing multicast
capabilities on a given Channel. This abstraction doesn't have any
particularly tight tie to the POSIX layer, so it belongs in NIOCore.
This is also expressed in terms of NIONetworkDevice, so we need to move
that over. That also encourages us to bring over
System.enumerateDevices, and given that System.coreCount is also fairly
general-purpose we may as well bring it along too.
Modifications:
- Move MulticastChannel to NIOCore
- Move NIONetworkDevice to NIOCore
- Move System to NIOCore
Result:
More general-purpose abstractions in NIOCore.
Motivation:
SocketOptionProvider is a general interface for setting socket options
that are "wider" than a single platform Int. There is nothing inherent
in NIO to require the definition of this protocol to be there, so we
can move it to NIOCore.
Modifications:
- Move the definition of SocketOptionProvider to NIOCore.
Result:
SocketOptionProvider is generally available.
Motivation:
NIO supplies a number of first-party ChannelHandlers that cover specific
use-cases. These aren't tied to the POSIX IO layer and so they should
come out.
Modifications:
- Move ChannelHandlers.swift to NIOCore
- Move NIOCloseOnErrorHandler.swift to NIOCore
Result:
Helper handlers in NIOCore
Motivation:
Our basic Channel Handlers don't need to be in NIO anymore: they aren't
realistically tied to that code. So we can move them to NIOCore.
Modifications:
- Move Codecs to NIOCore
- Move SingleStepByteToMessageDecoder to NIOCore.
Result:
Even more stuff in NIOCore
Motivation:
MCB is a companion part of circular buffer, and should also be a core
component of NIO.
Modifications:
Move MarkedCircularBuffer to NIOCore
Result:
MCB is in the common code.
Motivation:
The UniversalBootstrap abstraction allows you to write code that is
agnostic to the specific event loop and channel implementation. This is
likely to be used in places that don't want to have to express a
concrete requirement for a specific channel or loop, and so properly
belongs in NIOCore.
Modifications:
- Move Universal Bootstrap
- Move TCP convenience options, which are required by the universal
bootstrap.
Result:
Universal Bootstrap will be in NIOCore.
Motivation:
The most important API surface area in NIO are the Channel abstractions.
These are shared in all NIO programs, and are also used by several
projects to implement their I/O abstraction. There are several moving
parts to this abstraction, all of which are moving:
- Channel itself
- ChannelPipeline
- ChannelHandler
As these all move, they force several other pieces of API to move with
them. Most notably they force us to move NIOAny, which also forces us to
move FileHandle and FileRegion. That also forces us to bring over part
of our syscall abstraction. This duplication is acceptable due to its
minimal surface area, but it is definitely a flaw in our abstraction
design that we had to do that at all.
We also need to move the channel option abstraction, AddressedEnvelope,
and the DeadChannel.
Modifications:
- Moved a bunch of the Channel abstraction over.
- Moved Channel-associated types.
Result:
Channel will be part of NIOCore.
Motivation:
For Channel implementations, we implemented ChannelCore.unwrapData to
allow them to unwrap a NIOAny into their expected data type. This
remains our recommended flow, as Channels are supposed to know what data
type they can send. However, in a few cases the Channel has a runtime
type: in particular, EmbeddedChannel is capable of tolerating nearly
anything.
As we're coming to split the code apart, we'll likely want
EmbeddedChannel to live in a different module than NIOCore. To that end,
we need to add new API to ChannelCore to allow the specific
EmbeddedChannel use-case.
Modifications:
- Implement ChannelCore.tryUnwrapData.
- Use this within EmbeddedChannel.
Result:
EmbeddedChannel can attempt to unwrap things.
Motivation:
When pulling out the NIOBSDSocket later in #1907 we dropped some of the
socket option fixes for 32 bit platforms, which broke them.
Modifications:
Restore the socket options.
Result:
32-bit build should be working again.
Motivation:
A while back we added a ChannelCore extension method that would allow
removing handlers from a channel pipeline, in order to implement
Channels outside of NIO. This extension worked well, but it did assume
that you had a Channel to give it. There's no reason it needed a Channel
instead of just a ChannelPipeline, but it was based on the assumption
that Self would conform to Channel. Of course, this is usually true, but
it turns out not to always be true, and EmbeddedChannel is one example
where the Channel and ChannelCore are separate.
To that end, we shouldn't require using the Channel here, just the
ChannelPipeline. This will also let us force our NIO channels onto the
public API, which will make migrating to NIOCore easier.
Modifications:
- Deprecate ChannelCore.removeHandlers(channel:)
- Implement ChannelCore.removeHandlers(pipeline:)
- Swap existing Channel implementations to use the new method.
Result:
More consistent usage of our APIs.
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
This is the next stage of our move of common interchange objects to
NIOCore and out of the NIO module. This time around we need
SocketAddress, which is part of the Channel API. Sadly, SocketAddress is
not as clean as some of the other ports, because it leaks a number of
POSIX-y concepts. This also forces us to bring along NIOBSDSocket, which
ideally we would not move, but we foolishly exposed as API on
SocketAddress.
Modifications:
- Move NIOBSDSocket API components into NIOCore.
- Split out the internal abstractions for NIOBSDSocket and leave those
in NIO.
- Move SocketAddress into NIOCore.
Result:
SocketAddress will be sitting in NIOCore.
Motivation:
NIO provides some scope for performing "synchronous" ChannelPipeline
operations. These are only safe to perform from the event loop to which
the pipeline is bound, and they avoid the need to check what thread
context you're running on in release mode.
Several of the built-in channels currently skip the public, thread-safe
API to ChannelPipeline in favour of directly calling into the
synchronous pipeline interface. This is going to cause us some trouble
when we pull ChannelPipeline out into NIOCore.
To that end, we should add the rest of the ChannelPipeline API surface
area to the SyncOperations structure and convert ourselves over to using
them.
Modifications:
- Implemented the pipeline operations on SyncOperations
- Added a test
- Swapped our channels to use the new APIs.
Result:
Better abstraction between ChannelPipeline and the Channels
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
GetaddrinfoResolver is blocking the calling thread for anything that
uses a `ClientBootstrap`. Often, `ClientBootstrap`s are used on
EventLoops which obviously creates a problem because you mustn't block
EventLoops.
Modifications:
- Offload the `getaddrinfo` call to a `DispatchQueue`.
- Keep the semantics:
* only do one concurrent `getaddrinfo` call per SelectableEventLoop
* prevent thread explosion on `SelectableEventLoop`
Result:
Less EL blocking.
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
The next step on extracting the base abstractions is to pull out
EventLoop, EventLoopGroup and related types, and also EventLoopPromise
and EventLoopFuture. These types are fundamental to the API.
Modifications:
- Extract EventLoop, EventLoopGroup, and related types.
- Extract EventLoopPromise and EventLoopFuture.
- Add new @testable imports.
- Split MultiThreadedEventLoopGroup into new file, appropriately named.
Result:
Better separation.
Motivation:
In #1904 we included a change to add a debugging hook to confirm a group
could safely be shut down. Sadly, the default behaviour was too
aggressive, and would cause failures in downstream projects.
Modifications:
- Change the default behaviour of _preconditionSafeToSyncShutdown to be
a no-op, as it currently is in NIO programs today.
Result:
Downstream projects won't break.
Motivation:
As part of the ongoing split of NIO into two components, we need to
decouple EventLoopGroup from MultiThreadedEventLoopGroup. This is
largely straightforward, but EventLoopGroup.syncShutdownGracefully uses
a hook on MTELG to try to provide debugging help.
That hook cannot stand, so we must break it. Unfortunately this slightly
reduces our ability to detect possible blocks of a SelectableEventLoop,
but in return we get to increase our ability to detect blocks of other
event loop groups.
Modifications:
- Added a debugging hook to detect possible blocking of event loops.
Result:
Less coupling.
Motivation:
EventLoopFuture is capable of tracking where it was allocated from in
debug mode, to enable high-fidelity tracking of leaked promises.
Currently this behaviour is limited to SelectableEventLoop, but there is
no good reason to tie it so specifically to that loop.
Modifications:
- Extend `EventLoop` to allow all event loops to track promise
allocation and destruction.
- Add helpers to `EmbeddedEventLoop` to let it participate.
- Add new type to express a future ID.
Result:
Wider support for diagnostics.
Motivation:
As we break apart NIO, it's a bit awkward that EventLoopFuture.wait
knows about two specific EventLoop implementations. It does this in
order to detect deadlocks, so we should try to preserve the capability
as best as possible.
Modifications:
- Add EventLoop._preconditionSafeToWait, which can reproduce much of the
logic currently in EventLoopFuture.wait().
- Provide implementations for SelectableEventLoop and EmbeddedEventLoop.
Result:
Partial reproduction of the current behaviour of EventLoopFuture.wait().
Unfortunately this cannot completely reimplement this behaviour, as we
cannot safely call MultiThreadedEventLoopGroup.currentEventLoop for all
event loops. This is as close as we can safely get without breaking the
abstraction boundary, sadly.
Motivation:
Currently the "core" NIO module (currently called NIO) contains two
fairly distinct kinds of things. The first is the core abstractions and
data structures: the things that all NIO programs must necessarily deal
with. This includes our base abstraction protocols (e.g. `EventLoop`,
`Channel`, and `ChannelHandler`), as well as our base data types (e.g.
`ByteBuffer`, `SocketAddress`, `EventLoopFuture`).
The second thing the core NIO module contains is the default POSIX
sockets event-loop and channels. These are the mainline production loops
for NIO programs, and are supported in the various BSD-like OSes to
varying extents. These can be thought of as a baseline implementation of
the core abstraction protocols that form the first part of NIO.
These two fairly distinct use-cases have no particular reason to be
glued together, and in fact in gluing them together we have done a bit
of a disservice to our adopters. The biggest issue is that it has become
impossible to write a NIO program or library that does not bring along
the POSIX layer of NIO. This has made porting NIO to other platforms
difficult (Windows has been painful, and Webassembly is coming down the
road as well), and has also bloated the size of iOS/macOS applications
that use NIO via NIOTransportServices, as all of these applications must
bring along an event loop and several Channels they will not use.
To that end, we plan to begin a scope of work to split the core NIO
module in two. Specifically, we intend to extract the baseline protocols
and data types into a new module, called `NIOCore`, which will be able
to be the baseline NIO module.
The end goal is that libraries that implement protocols on top of
SwiftNIO should be able to depend solely on `NIOCore`, not `NIO`. This
will allow NIO applications to bring along only the event loops they
want or need, without needing to pay for the POSIX sockets
implementation. This should also make porting easier, as there will be
no pressure to bring the existing `NIO` module to new platforms if it
does not fit well.
Modifications:
This is the first in a series of patches, which extracts some of the
low-hanging fruit. In particular, it extracts:
- `ByteBuffer` (and associated types)
- `RecvByteBufferAllocator`
- `CircularBuffer`
This also adds in the backwards compatibility shim: the `NIO` package
performs an exported import of `NIOCore`. This will allow this change to
avoid breaking API.
However, to make a clean break we intend not to release a new NIO minor
version until we have completed our extraction. If we fail to do this it
won't be the end of the world, we can release subsequent minor versions
that continue to extract new types. However, as much as possible should
go at once.
This patch also duplicates a few methods and files. At the end of the
patch series we need to reconcile this duplication. In many cases the
duplication will no longer be necessary, but in some cases we may have
necessary duplicates.
Result:
The first step along the road to better platform citizenship is taken.
* Break out control message parsing by IP version
* Add shims for Darwin packet info
* Add shims for Linux packet info
* Add channel option for receiving datagram packet info
* Add NIOPacketInfo to AddressedEnvelope.Metadata
* Pipe up packet info channel option to receive path
* Add NIOPacketInfo info and fix backwards compatability
* Document packet info socket options
* Cleanup packet info control message parsing
* Add packet info and ECN combined tests
* Find real interface index during NIOPacketInfo tests
* Add PacketInfo tests to Linux tests
* Adds Equatable and ExpressibleByArrayLiteral conformance to ByteBufferView
* Adds linux test
* Equatable conformance compares slices of buffers
* Adds Hashable conformance to ByteBufferView
* Runs script for linux tests
* Force unwrap slicing the buffer in ByteBufferView equatable conformance implementation
* Adds Hashable conformance tests
* Addresses comments on test-related changes
* Minor grammar change
* Generates linux tests
Co-authored-by: Matteo Comisso <matteocomisso@skyscanner.net>
Co-authored-by: Matteo Comisso <matteo.comisso@me.copm>
Motivation:
Triple slashes should be for exportable documentation (like functions declarations).
Modification:
Replaced `///` with `//`.
Result:
Better looking code comments.
Co-authored-by: Antoine Cœur <acoeur@apple.com>
Motivation:
Get the tests passing on 32-bit platforms again.
Modifications:
- Change the way _UInt56.max is initialized.
- Set the proper max capacity for AdaptiveRecvByteBufferAllocator
and change the test to match it.
- Add a cmsghdrExample for Android armv7.
Result:
All the same tests pass on Android armv7 as Android AArch64.
Motivation:
On some Linux platforms the definition of SO_TIMESTAMP is too complex
for the clang importer to handle. Delegate to C to find out what it
should be. The same problem applies to SO_RCVTIMEO.
Modifications:
- Define SO_TIMESTAMP in CNIOLinux instead.
- Define SO_RCVTIMEO in CNIOLinux instead.
Result:
Should build on the awkward Linux platforms.
Motivation:
Platforms with 32-bit integers continue to exist. On those platforms,
the way we calculate the size table for AdaptiveRecvByteBufferAllocator
will trap, as we attempt to compare an Int to UInt32.max as a loop
termination condition.
While I was amending this code, I noticed that
AdaptiveRecvByteBufferAllocator had a number of very strange behaviours,
and was arguably excessively complex. To that end, this patch
constitutes a substantial rewrite of the allocator. To understand what
it does, we need to describe the previous allocator algorithm.
The goal of AdaptiveRecvByteBufferAllocator is to attempt to dynamically
track the throughput of a TCP connection and to minimise the memory
usage required to get it to achieve maximum throughput, within
user-defined constraints. To that end, it implements a fairly simple
resizing algorithm.
At a high level, the algorithm is as follows. The allocator keeps track
of the size of the buffer it is offering the user. When the user reports
how much of that buffer they actually used, the allocator determines
whether better throughput could be achieved with larger allocation
sizes, or whether throughput would not be harmed with smaller allocation
sizes. It then adjusts accordingly.
When does the allocator believe beetter throughput could be achieved
with larger allocation sizes? When the allocation was entirely filled.
If a network recv() entirely fills the buffer, that means there was
likely more data to read that could not be added to the buffer. Improved
throughput would be gained by using larger buffers, as fewer system
calls would be necessary.
Similarly, the allocator believes it could shrink the buffer size
without harming throughput when the recv() uses less memory than the
next buffer size down. However, the algorithm attempts to detect the
possibility that we have "read until the end". The reason this is
relevant is that after a read completes we will often serve other work
on the loop for a while, causing data to pile up. As a result, we don't
want to shrink the buffer if the average read size would be higher, just
because one read happened to be short.
The original implementation's algorithm was based on a bucketed
scheme. For allocation sizes below 512 bytes, the allocation buckets
moved 16 bytes at a time. In principle this gave the allocator 16 byte
granularity. For allocation sizes above 512 bytes, the allocation
buckets would double: 512, 1024, 2048, 4096, and so on, up to
UInt32.max. This, incidentally, was the source of the crash on 32-bit
systems.
Unfortunately, this scheme had a few failings.
Firstly, the implementation complexity was fairly high. The bounds
provided by the user needed to be turned into bucket indices,
necessitating an awkward and complex binary search of the bucket array.
The bucket array itself needed to be generated, forcing a dispatch_once
to guard it and dirtying memory.
Secondly, the scheme was weighted very heavily toward growing memory and
not giving it back. Whenever the buffer was filled and a new size up
wanted to be chosen, the allocator would jump _4_ size buckets. As the
default initial size was 2048 bytes, and the default maximum was 65kB,
the first read of 2048 bytes would cause the allocator to immediately
jump up to allocating 32kB of memory for the next read: a huge leap! It
would then only release memory after two short reads, at which point it
would drop back only 1 bucket, meaning that there was a very aggressive
sawtooth pattern favouring higher memory usage. This pattern favours
benchmarks, where high-throughput localhost connections will naturally
want larger buffer sizes, but it is unnecessarily aggressive for
real-world networks.
Thirdly, the scheme had a bug that would mean it did not require two
_consecutive_ short reads to shrink the buffer, just two short reads
between an increase. This means that it had a tendency not to stabilise:
two "read to the end"s in two different event loop ticks would cause
the buffer to shrink, even if there had been 10 almost-full-reads
in between.
Fourthly, the system would occasionally report that the Channel should
reallocate the buffer because it was larger, when in fact it wasn't:
we'd hit the max, and were never going to get larger. This forced
high-throughput Channels to excessively allocate, albeit only in systems
that customized this allocator (and basically no-one does).
Fifthly, the bucketing system was defeated by ByteBuffer. While having
16-byte granularity was nice in principle, ByteBuffer only allows
power-of-two allocation sizes. This meant that, at the low end, there
were several wasted buckets that were effectively identical. Between 256
bytes and 512 bytes there were 15 redundant buckets!
This last point is the main reason to justify a rewrite. The complexity
of the scheme was in principle justified by having fine, granular
control of allocation sizes. Given that those don't exist, there is no
reason not to simply resort to power-of-two sizing. Once we do that, we
can replace the complex bucketing system by simple shift-and-multiply
math. The effect of this is to produce smaller code (we save about 30%
of the instructions, even as we add some extra safety preconditions)
with no additional branching, and no need to load from a random table in
memory. This avoids the need to keep that table in cache, reducing cache
pressure in the hot read loop. Additionally, we can drop the index into
the table, which lets us save some per-Channel memory, further reducing
cache pressure.
Additionally, constructing one of these is now vastly cheaper. That
matters less (it's not really hot-code), but it does improve Channel
creation time somewhat.
Modifications:
- Remove the size table.
- Round all values to powers of two.
- Implement new "previous power of two" function.
- Cap the allocation size at the largest power of 2 representable in a
32-bit Int.
- Add more tests.
Result:
The result is less code, simpler code, and faster code. No trapping on
32-bit integer platforms.
Motivation:
As outlined in #1761, io_uring is a new async I/O facility on Linux.
This commit includes a second stab at adding this to SwiftNIO.
Modifications:
Added Uring Selector implementation.
Added liburing support shims.
Disabled one assert that trips during normal usage likely due to async nature of poll updates, for discussion
Added shared kernel sqpoll ring support (can be run with normal user privs in 5.13)
Support for both single shot polls (should work all the way back to 5.1 kernels, needs testing) and multishot streaming polls and modifications for polls (scheduled due in 5.13) for slightly better performance (and better impedance match to SwiftNIO usage)
Added extensive debug logs which can be enabled with -D compiler flags (should likely be removed when bringup and testing is complete)
Adjusted tests.
Added documentation.
Result:
Basic liburing support is in place.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
Right now all tasks scheduled onto an event loop from a different loop
wake up the underlying selector by writing to an eventfd. This is a
fairly inefficient way to handle things: it incurs a lot of syscall
traffic unnecessarily.
Given that we currently protect the pending tasks queue with a big dumb
lock, we can safely keep track of whether we're going to dequeue this
task. If we are, we don't need to wake the selector.
Modifications:
- Keep track of whether we're de-queueing tasks or not.
- Arrange to wake the selector only once.
Result:
Cheaper task enqueueing on hot loops.
Motivation:
While spelunking through the code I noticed we called
CircularBuffer.reserveCapacity, but never actually implemented it. This
means it never did anything. It should do something.
Modifications:
- Implemented reserveCapacity.
Result:
reserveCapacity does something now.
Motivation:
We alloc quite a lot with our implementations of flatMapThrowing and flatMapErrorThrowing.
While we don't use Futures a lot in NIO itself a lot of our users, depend quite a bit on them. Let's make their code faster.
Modifications:
Create a Promise and use _whenComplete directly instead of going through another flatMap method
Result:
In my testing I see a reduction of 3 allocs per invocation 🎉
Motivation:
We and the OSes only support `CInt` as file descriptors. For some reason
we had interfaces that took `Int`s as fds which requires frequent
casting around. This is unnecessary.
Modifications:
- make fds `CInt` (internally)
- clean up some `Int32` as `CInt` use
Result:
cleaner code, less casting
Motivation:
Instead of manual shifting / masking we can write the whole registration
ID code normally in Swift.
Modifications:
Refactored RegistrationID to use Swift instead of shifting / masking.
Result:
Nicer code.
Motivation:
With the registration ID refactoring (#1801) we'll now have the third
reimplementation of integer bit packing. Three is one too many, let's
make it generic.
Modifications:
Introduce generic integer bit packing and use it for _UInt56/24.
Result:
- Less bit packing code.
- Will simplify #1801
Motivation:
Due to https://bugs.swift.org/browse/SR-14516 , we sometimes get
allocating (!?) `subscript.read` accessors in the CircularBuffer.first
depending on the `Element` type...
Modifications:
Implement `CircularBuffer.first` instead of inheriting it from
Collection.
Result:
Fewer allocs in some cases.
Fixes an issue that could lead to an assert in Debug mode and to undefined behavior in Release mode.
Motivation:
When reading a new ByteBuffer slice from an originating ByteBuffer slice where the new ByteBuffer slice starts more than 16MiB into the underlying ByteBuffer storage, the new ByteBuffer slice will get a new 0 based storage.
When creating the storage for the new slice we have an issue in where storage based indices were used which should have been slice based indices.
Modifications:
Using the correct indices, when creating a ByteBuffer slice which is more than 16MiB into its originating storage.
Result:
We can create ByteBuffer slices from slices after the 16MiB threshold.
Fixes an issue that was raised in PostgresNIO