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:
I have several use-cases in my tests where it's necessary to have an EmbeddedChannel with multiple ChannelHandlers.
Modifications:
Add an initialiser that takes an array of ChannelHandlers, and adds them to the ChannelPipeline.
Result:
Previously:
let embeddedChannel = EmbeddedChannel(handler: ...)
try! embeddedChannel.pipeline.addHandlers([...]).wait()
Now:
let embeddedChannel = EmbeddedChannel(handlers: ...)
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
* Add synchronous channel options
Motivation:
The functions for getting and setting channel options are currently
asynchronous. This ensures that options are set and retrieved safely.
However, in some cases the caller knows they are on the correct event
loop but still has to pay the cost of allocating a future to either get
or set an option.
Modifications:
- Add a 'NIOSynchronousChannelOptions' protocol for getting and setting
options
- Add a customisation point to 'Channel' to return 'NIOSynchronousChannelOptions'.
- Default implementation returns nil so as to not break API.
- Add implementations for 'EmbeddedChannel' and 'BaseSocketChannel'
- Allocation tests for getting and setting autoRead
Results:
Options can be get and set synchronously.
Motivation:
When running load through EmbeddedChannel we spend an enormous amount of
time screwing around with removing things from Arrays. Arrays are not a
natural data type for `removeFirst()`, and in fact that method is
linear-time on Array due to the need for Array to be zero-indexed. Let's
stop using (and indeed misusing) Array on EmbeddedChannel.
While we're here, if we add some judicious @inlinable annotations we can
also save additional work generating results that users don't need.
Modifications:
- Replace arrays with circular buffers (including marked versions).
- Avoid CoWs and extra allocations on flush.
- Make some API methods inlinable to make them cheaper.
Result:
- Much cheaper EmbeddedChannel for benchmark purposes.
Motivation:
As outlined in https://bugs.swift.org/browse/SR-13923,
removeAll(keepingCapacity:) on Array has particularly negative
performance when that Array is not uniquely referenced. In this case, in
EmbeddedChannel, we _arrange_ to multiply reference it. This makes it
swamp our HTTP/2 microbenchmarks, spending more cycles copying this
buffer around than doing anything else.
Modifications:
- Just allocate a new buffer instead.
Result:
Much less copying.
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:
`EmbeddedEventLoop` executes scheduled tasks in their run-time order.
If multiple tasks are scheduled for the same time then the order in
which they are eventually executed is undefined.
Since `execute` defers to scheduling a task for "now" it is possible for
tasks to be executed out of order if `run()` is not called between each
execute.
In "real" event loops this isn't an issue because the system time must
advance between each call to `execute`.
Modifications:
- Add a 'insertionOrder' to `EmbeddedScheduledTask`; use it to break
ties when comparing two tasks with the same run time
- Add a task counter to `EmbeddedEventLoop` which is used to provide an
insertion order when scheduling tasks.
Result:
- EmbeddedEventLoop will `execute` tasks in order
Motivation:
You can schedule tasks for a deadline on `EmbeddedEventLoop` but have no
way of knowing the current time on the `EventLoop` and how much to
advance the time by in order to meet that deadline. In most cases this
is okay because you know that time starts at zero and you can keep track
of time, however, it's generally useful to not have to keep track of
this yourself.
Modifications:
- Add `advanceTime(to:)` on `EmbeddedEventLoop`
- Document that time may be controlled on `EmbeddedEventLoop` and how to
advance it
- Tests
Result:
- `EmbeddedEventLoop` is more usable with deadlines
- Better documentation
Motivation:
EmbeddedChannel advanced time to the distant future so that all
scheduled tasks would be run. However, if tasks were recursively
scheduled by executing the already scheduled tasks then the channel
would never finish.
Modifications:
When calling finish() on EmbeddedChannel, only run the tasks which have
been scheduled at that point in time.
Result:
Recursively scheduled tasks terminate when finish-ing the
EmbeddedChannel.
This allows other EventLoopGroup implementations to swap in other
bootstrap implementations. By default, it is unimplemented and will
throw an error once `connect` is called on the returned Bootstrap.
Support is implemented for `MultiThreadedEventLoopGroup`,
`SelectableEventLoop` and `EmbeddedEventLoop`.
Motivation:
In Swift, writing
var something: T?
init() {
self.something = someValue
}
means that the compiler will first set `self.something` to `nil` and
then in the init override it with `self.someValue`
(https://bugs.swift.org/browse/SR-11777). Unfortunately, because of
https://bugs.swift.org/browse/SR-11768 , stored property initialisation
cannot be made `@inlinable` (short of using `@frozen` which isn't
available in Swift 5.0).
The combination of SR-11768 and SR-11777 leads to `var something: T?`
having much worse code than `var something: Optional<T>` iff the `init`
is `public` and `@inlinable`.
Modifications:
Change all `var something: T?` to `var something: Optional<T>`
Result:
Faster code, sad NIO developers.
Motivation:
ChannelOptions types like WriteBufferWaterMarkOption are global, public types. These types should be namespaced.
Modifications:
Moved global, public ChannelOptions types into ChannelOptions.Types enum. Created global, public typealiases with deprecation attributes which point to the namespaced types. Switched usage of these types in the codebase to use the namespaced versions.
Result:
Usage of the global, public versions of these types will cause deprecation warnings.
Motivation:
To improve the performance of a given component it is very helpful to
know how it performs! This patch adds benchmarks and allocation counter
tests to NIO for websocket frame encoding.
Modifications:
- Wrote some benchmarks for WebSocket frame encoding.
- Wrote some allocation counter tests for WebSocket frame encoding.
- Extend the allocation counter tests to properly account for sub-tests
Result:
Better insight
Motivation:
EmbeddedChannel used to only support IOData on its outbound path, that
has been fixed in #763.
Modifications:
Remove the incorrectly documented brokenness.
Result:
More correct docs.
Motivation:
When testing programs that check flow control state, it's useful to be
able to control the results of that check. However, right now it's not
possible to set the flow control state of an EmbeddedChannel: it's just
always true. That's not super helpful.
Modifications:
Make EmbeddedChannel.isWritable a stored property that can be changed.
Result:
Better testing.
Motivation:
Spotted a couple of issues with the documentation and fixed them.
Modifications:
- explicitly marked all `public class`es as `public final class` to get
consistency in the Jazzy documentation.
- removed `public` extension methods of the `internal struct
PriorityQueue` which Jazzy showed in the docs.
- improved the largely missing `EmbeddedChannel` and `EmbeddedEventLoop`
documentation.
- clear up lies in the B2MD docs
- add some other missing docs
Result:
better docs makes happier users
Motivation:
EmbeddedChannel.finish/writeInbound/writeOutbound returned some mystery
bools. I always had to check the code to remember what they actually
meaned.
Whilst this is technically a breaking change, I couldn't find any users
of the return values on Github that are using the convergence releases.
Modifications:
Replace them by enums giving you all the information.
Result:
- fixes#916
- clearer APIs
Motivation:
Jazzy adds everything that has a `public` modifier to the documentation,
even if a type is `internal` or `private`. So conforming and internal
type to some protocol and making all those functions `public` has the
effect of essentially documenting stuff that you can't call (as it's not
actually public).
Modifications:
- remove `public` from functions in extensions on types that aren't
public
- change one `final public` to `public final` because Jazzy doesn't
normalise that
Result:
better docs
Motivation:
If you pick the wrong type for readIn/Outbound in tests, it's better to have an error thrown than a crash.
Modification:
- use `tryAs` rather than `forceAs` when trying to extract the buffer element
Result:
better usability in tests.
Motivation:
Unhandled outbound user events should be failed but previously they were
succeeded.
Modifications:
Succeeding them is odd because nothing happened to them, so they should
be failed.
Result:
fixes#487
Motivation:
readInbound/Outbound will soon throw errors if the type isn't right.
Modifications:
prepare tests for throwing readIn/Outbound
Result:
@ianpartridge's PR should pretty much merge after this.
Motivation:
There's just too much test code that has
(channel.eventLoop as! EmbeddedEventLoop).run()
Modifications:
have EmbeddedChannel expose its EmbeddedEventLoop
Result:
easier test code
Motivation:
Testing channel handlers that rely on `Channel.localAddress` or `Channel.remoteAddress` is currently quite inconvenient as one cannot set test values for `localeAddress` or `remoteAddress` on `EmbeddedChannel`.
Modifications:
Change `localAddress` and `remoteAddress` to variables instead of constants and set the address values in `bind()` and `connect()` as proposed in #829.
Result:
Arbitrary values for `localAddress` or `remoteAddress` can be set on `EmbeddedChannel`.
Motivation:
`ctx` was always an abbreviation was 'context` and in Swift we don't
really use abbreviations, so let's fix it.
Modifications:
- rename all instances of `ctx` to `context`
Result:
- fixes#483
Motivation:
- `ChannelPipeline.add(name:handler:...)` had a strange order of arguments
- `remove(handler:)` and `remove(ctx:)` both remove `ChannelHandler`s
but they read like they remove different things
So let's just fix the argument order and name them `addHandler` and
`removeHandler` making clear what they do.
Modifications:
- rename all `ChannelPipeline.add(name:handler:...)`s to `ChannelPipeline.addHandler(_:name:...)`
- rename all `ChannelPipeline.remove(...)`s to `ChannelPipeline.removeHandler(...)`
Result:
more readable and consistent code
Motivation:
ChannelOptions used a too complicated mechanism for what they are.
Modifications:
- change the ChannelOptions to a much simpler mechanism
- rename the generic parameters from T to Option
Result:
code easier to read and understand
Remove EmbeddedChannel restriction to IOData
Motivation:
You should be able to read any type from the outbound buffer.
Modifications:
Change Embedded channel outboundBuffer and pendingOutboundBuffer to store NIOAny instead of IOData and refactor test code accordingly.
Result:
- Users can test what went through the pipeline without serializing everything and using "if case let" syntax everywhere.
- fixes#551
Add deadlines as an alternative to timeouts
Motivation:
Address #603
Modifications:
- Add NIODeadline type
- Add func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T>
- Reduce the use of DispatchTime in favor of Time
- Replace timeout calls with deadline calls where it makes sense
Result:
Tasks can be scheduled after an amount of time has passed, or at a certain time.
Motivation:
EventLoopPromise.succeed/fail has extraneous labels that don't add
anything but noise.
Modifications:
remove extraneous labels
Result:
less noise in the code
Motivation:
Swift naming guidelines mandate that factory methods start with `make`,
like `makeSomething`. We had a few that were `newSomething`.
Modifications:
make all factories start with make
Result:
more compliant to Swift naming rules
Motivation:
_ = expression() is ugly and in many cases unimportant. In fact we train
ourselves to overread it which makes special cases where you'd actually
expect a result to be used just look normal.
Modifications:
remove _ = from a lot of places. In many cases we already had a better
(and sometimes cheaper way) to not return a value but in some cases
(mostly `remove` functions) I added `@discardableResult`
Result:
NIO source code looks nicer
Motivation:
Naked `try`s in tests are a problem because if they're hit you'll get a
bad error message and likely no file/line information. That has made
many flaky tests harder to debug than necessary.
Modifications:
- fix a lot of naked `try`s
- symlink `TestUtils` from `NIOTests` into `NIOHTTP1Tests`
- make a bunch of `wait()`s synchronous that were asynchronous by
accident
Result:
- better code
- easier to debug test failures
- setting better example
Motivation:
EmbeddedChannel just treated all `write`s as flushed. That's not a good
idea as all real channels obviously only actually write the bytes when
flushed. This changes that behaviour for `EmbeddedChannel`.
Modifications:
- make `write` only write to a buffer
- make `flush` then actually pretend to write the bytes
Result:
- EmbeddedChannel behaves more realisticly
Motivation:
In some contexts it is important to be able to pass file descriptors
around instead of specifying the particular host and port. This allows removing
certain windows for race conditions, and has positive security implications.
Modifications:
Added `withConnectedSocket(_:)` call to the `ClientBootstrap` that can
be used to create a new `Channel` out of existing file descriptor
representing the connected socket.
Result:
Allows initializing `Channel`s off the existing file descriptors.
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 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:
Testing specific ordering behaviours (e.g. cancelling tasks) requires
that EmbeddedEventLoop behave as similarly as possible to the full
event loop.
Modifications:
Adopt the batched scheduled task dispatch logic from the regular
event loop.
Result:
Easier to test subtle behaviours around task dispatch.
Motivation:
Sometimes we deviated from the style the Swift stdlib sets out for no
reason.
Modifications:
Fixed some stylistic deviations.
Result:
Looks more Swift-like.
Motivation:
At the moment EmbeddedChannel calls fireChannelRegistered() when connect(...) is called. This is not correct, as it should be done when register(...) is called.
Modifications:
- Correctly call `fireChannelRegistered(...)` when register(...) is called
- Simplify init of EmbeddedChannel
- Fix EmbeddedChannelTest
Result:
Correct invocation of methods.
Motivation:
guard !self.open else { ... } is a double negation and can be confusing,
guard self.isOpen else { ... } is much better
Modifications:
replaced all `var closed: Bool` with `var isOpen: Bool`
Result:
we're more positive
Motivation:
Channel.getOption(...) should return an EventLoopFuture to ensure we not end up with a deadlock.
Modifications:
Change getOption(...) to return EventLoopFuture.
Result:
No deadlocks and more consistent API.