Motivation:
When implementing a custom ChannelCore, you will probably need access
to the data inside a NIOAny. It should be possible to unwrap that.
Modifications:
Added an extension to ChannelCore to allow unwrapping a NIOAny.
Added @_versioned to almost all of NIOAny.
Result:
ChannelCore is implementable outside NIO
Motivation:
The ping/pong test should only do 4 allocations:
- readFromSocket does unconditionally allocate one ByteBuffer
(allocating one ByteBuffer does 2 allocations)
- we have a ping and a pong side, each call readFromSocket
so 2 * 2 = 4 allocations per message. Before adding the `@_inlineable`
to the read/write/get/set integer methods in ByteBuffer however I was
seeing way more allocations. So looked at them and fixed them.
Turns out that massively reduces the number of allocations for HTTP too.
On Linux I was seeing this change:
1000_reqs_1_conn: 282000 -> 70000
1_reqs_1000_conn: 1287000 -> 907000
Modifications:
- made the ByteBuffer integer methods inlineable
- added a test that makes sure we don't regress on the simplest possible
use of NIO: a ping/pong server
Result:
After your change, what will change.
IdleStateHandler.IdleStateEvent is currently internal. Make it public.
Motivation:
The IdleStateEvent is delivered to the user viapublic func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any). In this method, it must be possible to have a check on the type of event. IdleStateEvent must be public.
Modifications:
Change access level of IdleStateHandler.IdleStateEvent to public.
Result:
IdleStateEvent will become a part of the NIO API.
Motivation:
We had a number of problems:
1. We wanted to lazily process input EOFs and connection resets only
when the user actually calls `read()`. On Linux however you cannot
unsubscribe from `EPOLLHUP` so that's not possible.
2. Lazily processing input EOFs/connection resets wastes kernel
resources and that could potentially lead to a DOS
3. The very low-level `Selector` interpreted the eventing mechanism's
events quite a lot so the `EventLoop`/`Channel` only ever saw
`readable` or `writable` without further information what exactly
happened.
4. We completely ignored `EPOLLHUP` until now which on Unix Domain
Socket close leads to a 100% CPU spin (issue #277)
Modifications:
- made the `Selector` interface richer, it now sends the following
events: `readable`, `writable`, `readEOF` (input EOF), `reset`
(connection reset or some error)
- process input EOFs and connection resets/errors eagerly
- change all tests which relied on using unconnected and unbound sockets
to user connected/bound ones as `epoll_wait` otherwise would keep
sending us a stream of `EPOLLHUP`s which would now lead to an eager
close
Result:
- most importantly: fix issue #277
- waste less kernel resources (by dealing with input EOFs/connection
resets eagerly)
- bring kqueue/epoll more in line
Motivation:
We returned an callback which needed to be executed by the caller. This will cause extra allocations and is not needed. We can just return a EventLoopPromise which will cascade the notification.
Modification:
Not return a closure but promise.
Result:
Less allocations.
Motivation:
Callouts to user code allows the user to make calls that re-enter
channel code. In the case of channel closure, we could call out to the
user before the channel knew it was completely closed, which would
trigger a safety assertion (in debug mode) or hit a fatalError
(in release mode).
Modifications:
Reconciled channel state before we call out to user code.
Added a test for this case.
Result:
Fewer crashes, better channel state management.
Motivation:
When an asynchronous connect failed we would crash because we didn't
correctly close the connection to start tearing everything down.
That correctly made the `SocketChannelLifecycleManager` trip.
This was filed as #302.
Modifications:
Correctly deregister and close the connection if an async connect fails.
Result:
Fewer crashes, fixes#302.
Motivation:
TailChannelHandler does not implement any _ChannelOutboundHandler methods and so has no need to conform to it.
Modifications:
Not implement _ChannelOutboundHandler for TailChannelHandler
Result:
More correct code.
Motivation:
If we not filled the whole buffer with read(...) we should stop reading and wait until we get notified again. Otherwise chances are good that the next read(...) call will either read nothing or only a very small amount of data.
Also this will allow us to call fireChannelReadComplete() which may give the user the chance to flush out all pending writes.
Modifications:
Stop reading and wait for next wakup when we not fill the whole buffer.
Result:
Less wasted read calls and early chance of flushing out pending data.
* Add EventLoopFuture reduce(initialResult:) function (#240)
Motivation:
Add a new function to allow us to work with multiple EventLoopFutures, that return values, by combining their results and wrapping it in a new
EventLoopFuture, using a specified reducer function.
Modifications:
- Add a new function
EventLoopFuture<T>.reduce<U>(initialResult:futures:eventLoop:nextPartialResult)
- Changed the implementation of andAll<Void> to use
EventLoopFuture<Void>.reduce(initialResult)
- Add a new function EventLoopFuture<T>.reduce<U>(into:)
Result:
Can reduce multiple EventLoopFutures without having to deal with
creating EventLoopFutures.
Simplified EventLoopFuture andAll<Void>
- An API which can be used to construct collections from future values in a linear time.
Motivation:
Generics and closures across modules can be problematic as the cause
allocations. ByteBuffer is one of NIO's core data types and therefore
should be well optimised. Generic/closure taking methods so far were a
bit of a problem. And with
[SE-0193](https://github.com/apple/swift-evolution/blob/master/proposals/0193-cross-module-inlining-and-specialization.md)
accepted, there's not much reason to use those features even though they
are (at the moment) @_.
For the 1000 requests over 1 connection allocation benchmark we go from
"total_allocations": 325378
to
"total_allocations": 321366
so we lose 4 allocations per HTTP request/response pair, not super
impressive but not nothing either.
Modifications:
Make generic/closure taking methods on ByteBuffer `@_inlineable`
Result:
Fewer allocations
Motivation:
NIO 1.3.1 was TSan clean but `master` regressed. In total I could see
two breakages both proudly presented by `SocketChannelLifecycleManager`.
Sorry :| :
1. accessing the `isActiveAtomic` from arbitrary threads:
this was clearly a bug because `SocketChannelLifecycleManager` is
usually held mutabe. So `isActiveAtomic` needs to be injected into
`SocketChannelLifecycleManager` rather than contstructed there
2. accessing the `ChannelPipeline` through `SocketChannelLifecycleManager`:
same problem as above really.
Modifications:
inject both the ChannelPipeline and the isActiveAtomic in the
appropriate places.
Result:
NIO much more correct, TSan happy
Motivation:
You need to be able to implement EventLoop.scheduleTask to implement
your own event loop. EventLoop.scheduleTask requires creating a
Scheduled. Currently, Scheduled has no public initializer.
Modifications:
Make Scheduled's initializer public.
Result:
It will be possible to actually implement EventLoop.
Motivation:
Add primitive for folding futuristic values.
Modifications:
Add a new EventLoopFuture extension containing the implementation of
`fold<U>(futures:combiningFunction)`.
Result:
An API for foding futures.
Motivation:
I wanted to make sure that I fixed the minor typos and that I addressed
the feedback that was provided to me in regards to force unwrapping.
I also wanted to make sure my error messages were accurate.
Modifications:
Fixed a few minor typos and updated the force unwrap error messages.
Result:
Fixed typos and guard statements with accurate error messages.
Motivation:
Adding @convention(c) is beneficial for performance of variables bound
to C functions so we should do that in ByteBuffer.
Modifications:
Adds @convention(c) to the malloc/realloc/free constants in ByteBuffer
Result:
Slightly better performance.
fix some typos, force unwraps and inconsistencies
Motivation:
Reviewing the code I found a few typos that hindered readability, some unnecessary force unwraps and inconsistencies in the codebase.
Modifications:
- The main file in NIOWebSocketServer now accepts command line arguments
and binds to a passed in host and port like the other server examples do.
- Minor typo fixes
- removed one force unwrap
Result:
- The result of my change will bring the NIOWebSocketServer more inline
with how the NIOHTTP1 and NIOChat servers examples are setup.
- less force unwrapping
- fewer typos
[message edited by @weissi]
Motivation:
When calling Selector.whenReady(...) and using a SelectorStrategy.blockUntil(...) we may end up re-arm the timerfd each time even if the wakeup time did not change.
This is expensive and can be avoided in most situations.
Modifications:
Keep track of the earliest scheduled timer and only schedule a new one if it would fire sooner.
Result:
Less overhead when using epoll and timers.
Motivation:
We had a lot of problems with the Channel lifecycle statemachine as it
wasn't explicit, this fixes this. Additionally, it asserts a lot more.
Modifications:
- made Channel lifecycle statemachine explicit
- lots of asserts
Result:
- hopefully the state machine works better
- the asserts should guide our way to work on in corner cases as well
Motivation:
We moved the priority queue implementation into the main `NIO` module
for performance reasons. I initially thought we didn't expose it to
external packages but we did (thanks @lukasa).
Modifications:
Bring back the `NIOPriorityQueue` module but deprecate it.
Result:
Speed & backwards compatibility :)
Motivation:
We can simplify the init method of ChannelHandlerContext and replace one let by a computed property.
Modifications:
Remove some if let statements that we not need and use computed property.
Result:
Simpler code and need one less variable per ChannelHandlerContext.
Motivation:
We only use our GetaddrinfoResolver for SocketChannels (TCP stream channels), so we should set some hints for getaddrinfo.
Modifications:
Set proto and socktype hints.
Result:
More correct usage of getaddrinfo. Fixes https://github.com/apple/swift-nio/issues/201.
Motivation:
We triggered extra allocations for the generics on PriorityQueue/Heap.
They unfortunately can't be solved using `@_specialize` as the element
type is `ScheduledTask`.
Fortunately we never exposed those types externally so we can just
inline without breaking the public API.
Modifications:
Moved everything from the `NIOPriorityQueue` module into the `NIO`
module.
Result:
Less allocations, more happiness.
Motivation:
We should make use of lock.withLockVoid to simplify our code and make it more robust.
Modifications:
- Replace manual lock() / unlock() calls by withLockVoid(...)
- Mark lock.withLock* as @_inlineable to ensure we not get an allocation for the closure.
Result:
Code is cleaner and easier to understand.
Motivation:
We need to update isActive before notify the promises of connect and close to correctly refect Channel.isActive in callbacks.
Modifications:
- Correctly update isActive before notify promises.
- Add unit test.
Result:
Correct Channel state in callbacks.
Motivation:
When using KQueue we directly can tell what IOEvent we want to use in SelectorEvent without and branching.
Modifications:
Add new init method to SelectorEvent that takes the IOEvent directly and use it when using KQueue
Result:
Less branching per event when using KQueue
Motivation:
We can remove a promise allocation in Selector.closeGently if there are still Channels registered and also simplify the code a bit.
Modifications:
Remove creation of promise and just use eventLoop.new*Future(...) when needed.
Result:
Less allocations and cleaner code.
Motivation:
The Socket channels and PendingDatagramWritesManager had a bunch of
overhead left over from when they were handling flush promises. This was
only adding to code complexity and perf cost.
Modifications:
Removed the promise label in markPendingWritePoint.
Reworked the code to stop expecting write promises in
PendingDatagramWritesManager.
Result:
Smaller, faster code.
Motivation:
We can remove one lock() / unlock() pair by saving the next ready task during loop execution.
Modifications:
Remvoe one lock() / unlock() pair.
Result:
Less locking during EventLoop run executions.
Motivation:
At some point we needed to check for #available(OSX 10.12, *) which is not true anymore as we use our own Thread impl.
Modifications:
Remove #available(OSX 10.12, *) check
Result:
Remove incorrect and not needed check.
Motiviation:
When the Selector is closed we also close the registered Channels and notify the future once all the close operations complete. The problem here is that while the close operation may be complete already there may still be events flowing through the ChannelPipeline. The only way to ensure this not happens anymore is to take the closeFuture into account of each Channel (as the closeFuture will only be notified once all is done for a Channel).
Modification:
- Also take the closeFuture into account per Channel
- Add test
Result:
Safer shutdown of EventLoopGroup.
Motivation:
Resolves#228
Modifications:
Remove type information in empty closure fixed build warning with compiler suggestion
Result:
No API changes, no issues building on 4.1!
Motivation:
ServerSocketChannel should just fail the EventLoopFuture for unsupported operations and not crash.
Modifications:
- Correctly fail the EventLoopFuture for unsupported operations
- Add unit test.
Result:
No more crashes when users invoke unsupported operations.
Motivation:
The Head and Tail ChannelHandlers should not be accessible as these are implementation details of the ChannelPipeline and removal of these will even make the whole ChannelPipeline not work anymore.
Modifications:
- Make it impossible to access / removal the Head and Tail ChannelHandlers
- Exclude the Head and Tail ChannelHandler from the debug String
- Add unit tests.
Result:
More robust ChannelPipeline.
Motivation:
Usually we retry the syscall when EINTR is reported. This is not safe in the case of close(...) as the file descriptor may already be closed. The problem arise if this was the case and we retry it and the file descriptor is already reused again. In this case we would close a wrong file descriptor.
See:
- https://bugs.chromium.org/p/chromium/issues/detail?id=269623
- https://lwn.net/Articles/576478/
Modifications:
Ignore EINTR on close(...) and just assume the FD was closed.
Result:
Not possible to close the wrong file descriptor when close(...) reports EINTR.
Motivation:
Fix inconsistency of <Void> and <()> occurances in the codebase.
Modifications:
Changed EventLoop{Future,Promise}<()> occurances to EventLoop{Future,Promise}<Void>
Result:
Consistent code style for EventLoopPromise and EventLoopFuture.
Motivation:
b8055f7467 added some code to guard against the case when a fd is deregistered while processing ready events. On Linux it also added an assert which tried to verify that the fd in question is not registered anymore via epoll. The problem here is that it may also be closed which will have epoll_ctl fail with EBADF
Modifications:
Remove assert and add test-case which would have triggered the assert.
Result:
No more assertion error on linux.
Motivation:
{,Server,Datagram,Base}SocketChannel hold quite a bit of complexity and
also a many of lines of code. Yet they all shared the very same file
which isn't great.
Modifications:
- moved BaseSocketChannel into its own file
- made the methods that need overriding internal (from `fileprivate`)
Result:
SocketChannel.swift has a lot fewer lines of code.
Motivation:
`readIfNeeded` was triggered straight after the channel was registered
but _before_ `channelActive` was called which is wrong.
Modifications:
Moved the calls to `readIfNeeded` into `becomeActive0` and removed them
everywhere else (except some error path).
Result:
handle ChannelHandler lifecycle more correctly.
Motivation:
It's not clear to a user which inbound / outbound messages is expected for the different Channel implementations. This can result into wrong code and confused users.
Modifications:
Add some docs to explain which messages are supported / expected by the different Channels that can be bootstrapped.
Result:
More clear docs.
Motivation:
It's possible someone deregistered a Selectable while Selector.whenReady(...) is processed and an even for the now deregistered Selectable is ready. In this case we crashed (due a force-unwrap) on linux.
Modifications:
- Skip the processing of the Selectable if deregistered (by replacing force-unwrap with an if let).
- Add unit test.
Result:
No more crashes caused by this on Linux
Motivation:
Introduced some new parameters to fix#202
Modifications:
Created new parameters for the file and line newPromise method inside ChannelOutboundInvoker.
Result:
File and line numbers are now passed to the eventLoop object, all unit tests have been passed.
Motivation:
If connectSocket() completes directly we failed to mark the Channel active by calling becomeActive0(...).
Modifications:
Correctly call becomeActive0(...)
Result:
Mark Channel active if connect succeed directly.
Motivation:
If a non-blocking connect failed, the error indicated that `getsockaddr`
failed which isn't true.
Modifications:
Adjusted the message.
Result:
Fewer lies.
Motivation:
We should return a failed EventLoopFuture when getOption(...) / setOption(...) is called on a closed Channel as otherwise it may not be safe to modify the Channel ioptions after its closed.
Modifications:
- Add guards that check if the Channel is still open and if not fail the operation.
- Add testcase
Result:
Calling getOption(...) / setOption(...) on a closed Channel fails.
Motivation:
The HappyEyeballs state machine incorrectly assumed that it would always
be able to cancel any scheduled task that would execute on the event loop
that the state machine itself was running on. This is not accurate: if
the scheduled task is scheduled to execute at roughly the same time as
another callback into the state machine then it may be uncancellable.
Modifications:
Allowed the three scheduled tasks (connect timeout, connect delay, and
resolver delay) to fire in completed.
Result:
No fatalErrors in window conditions under high load