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:
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:
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:
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:
Currently the selector implementation just discards all pending events from the kernel when a deregistration
has occurred during the event loop tick. This has been needed to not fail the test testWeDoNotDeliverEventsForPreviouslyClosedChannels.
A cleanup case has been around for a while at: https://github.com/apple/swift-nio/issues/381
And when discussing this in https://github.com/apple/swift-nio/pull/1788 (to solve https://github.com/apple/swift-nio/issues/1761)
we came to an agreement that the solution with tagging registrations on the backend would not suit only io_uring,
but also solve the issue robustly for kqueue and epoll.
Modification:
Added sequenceIdentifier to the Registration and add support for it throughout.
Mask in sequence identifier into user data in both kqueue and epoll.
In kqueue, we just store the sequence identifier in the udata field (to support 32-bit properly).
In epoll, where we know we have 64-bits, we mask it in together with fd.
Removed all references to the old workaround from #381.
Result:
- New solution that doesn't need to discard all events when deregistrations are done during the event loop tick.
- fixes#381
Motivation:
Succeeded `EventLoopFuture<Void>`s are quite important in SwiftNIO, they
happen all over the place. Unfortunately, we usually allocate each time,
unnecessarily.
Modifications:
Offer `EventLoop`s the option to cache succeeded void futures.
Result:
Fewer allocations.
Motivation:
Right now Heap.heapify incurs quite a lot of ARC traffic when it is used
in SelectableEventLoop. Specifically, each of the invocations of
self.comparator in heapify incurs three refcount operations. These three
are all the result of the fact that the comparator is an arbitrary
function, but all three are guaranteed to be unnecessary.
The first refcount is for the closure context for self.comparator. Of
course, self.comparator has only two possible values, neither of which
needs a closure context, but the compiler doesn't know that and the type
system doesn't encode it.
The other two refcounts are for the ScheduledTask objects themselves.
Again, the compiler doesn't know what the comparator function will do,
so it must defensively ensure that a retain/release is inserted for the
arguments of that function.
If we happen to hit both branches of the code, we'll execute 6 retains
and 6 releases, and even in fairly average cases we'll execute 3 of
each.
All of this is unnecessary: the only runtime function ever used here is
a trivial comparison operation. We know what it is at compile time, we
just have to ask. While it was admirable to have the configurability of
the priority queue in place, after 3 years I think we have a pretty good
feeling that we're not going to need the ability to have a max-heap
instead of a min-heap.
We can always get this back if we need it.
Modifications:
- Removed the configurability of Heap.
- Removed HeapType.
- Removed arguments from PriorityQueue
- Removed all tests testing now-removed max-heap functionality.
Result:
Less ARC traffic in the core task scheduling loop.
Motivation:
Network congestion can be controlled without packet loss if explicit congestion notification messages are understood.
Modifications:
Receive single and vector paths to get notification and surface.
Send paths for both single and vector sends.
Round trip tests.
Storage for control messages added in a reusable way.
I have tested allocations and they seem to be fine but the allocation tests for vector read and write were not stable enough to sensibly add to CI.
Result:
Explicit Congestion Notifications can be both sent and received.
Motivation:
Previously, if we scheduled EventLoop executions from the promises we
failed during EventLoop shutdown, we'd blow up. Thanks to @fabianfett
for the bug report.
Modifications:
Set the EL state to 'exiting thread' only after we failed all
outstanding tasks.
Result:
Fewer crashes.
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Usually, you spawn a new MultiThreadedEventLoopGroup to run NIO
programs. But if you're a very simple command line utility, that may not
be necessary, so why not just re-use the main thread?
Modifications:
Allow taking over threads and making them EventLoops.
Result:
Fewer threads if you want.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
testSafeToExecuteTrue/False accessed an internal property of the event
loop without synchronisation.
Modifications:
Fix the threading issue.
Result:
Tests with TSan happy.
Motivation:
Since #1395, we crash when something is scheduled to an already shutdown
EventLoop. That's a good intent (#1383) but we feel it's a little too
risky right now.
Modifications:
Print an ERROR instead of just crashing.
Result:
Fewer crashes.
Treat the `autoreleasepool` case for Darwin as the special case rather
than Linux as the special case. This is following the case throughout
the rest of the code base. This is also needed for the Windows port.
* prevent execution of tasks on an already shutdown EL
* fixup! prevent execution of tasks on an already shutdown EL
* fixup! prevent execution of tasks on an already shutdown EL
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
## Motivation:
In SwiftNIO's codebase, most things were always testable just as well as user code is. With one big missing piece: We could never make the `Selector` do arbitrary things to the `Channel` implementations which lead to super expensive to (create, read, understand) integration tests like [`testWriteAndFlushFromReentrantFlushNowTriggeredOutOfWritabilityWhereOuterSaysAllWrittenAndInnerDoesNot `](https://github.com/apple/swift-nio/blob/5dc9083c6a78b10432b4b55b95704e61ca08f09d/Tests/NIOTests/StreamChannelsTest.swift#L468-L760).
## Modification
Add SAL, a 'syscall abstraction layer' which makes it possible to assert all syscalls that come through a `Socket` or the `Selector` by mocking them. It lets the NIO programmer play the kernel in these "SAL tests" which makes it possible to assert the exact syscalls (with their parameters) and decide the syscalls' returns.
## Result
Finally, we're able to write proper unit tests for scenarios where the `Channel` drove the `Selector` incorrectly.
Motivation:
SelectableEventLoop's description was taking a lock and would also lock
every single scheduled task. That's overkill.
Modifications:
Make it only log the thread and selector (which don't require locks).
Result:
better description
Motivation:
Certain issues are easier debugged if we can print the thread names.
Modifications:
- add the thread name to SelectableEventLoop's description
- make EventLoop and NIOThread CustomStringConvertible
Result:
easier debugging.
Motivation:
There was always this one big embarrassment in the NIO codebase: We
violated the iron rule of 'no fd or scarce resource management in deinit'
in just one place: The most long-lived thing there is in NIO: The
Selector for the SelectableEventLoopGroup. Sure enough, even that tiny
violation lead to issues.
Modifications:
Close the fds in `close` rather than `deinit`.
Result:
- I'm feeling better
- makes @ktoso happy
- fixes#1302
Motivation:
Due to rdar://53656794, we sometimes (especially on UNIX Domain Sockets)
see EVFILT_EXCEPT firing when data is available to read depite the fact
that we're setting the low watermark to CInt.max. This means that
EVFILT_EXCEPT becomes essentially unusable.
Modifications:
- Don't use EVFILT_EXCEPT on Darwin
- We lose early EOF delivery on Darwin
Result:
Fewer possibilities of a spin loop on Darwin.
Motivation:
Previously, we unconditionally woke up the selector for every task that
was added. But this is only necessary if we're not already on the
EventLoop. Because if we are, we'll have another look at the outstanding
tasks anyway.
Modifications:
Remove selector wakeups.
Result:
Faster executes.
Motivation:
In SelectableEventloop, Heap, PriorityQueue, etc there were quite a few
phantom publics left which cause issues with #1257 and are confusing.
Modifications:
- remove the phantom publics
- move SelectableEventLoop to its own file
Result:
- clearer what's going on (public means public)