Motivation:
We had a public typealias for an internal type, that's an error now in
Swift 4.2.
Modifications:
make the typealias internal.
Result:
compiles in Swift 4.2
Motivation:
On Linux registration without bind/connect leads to `EPOLLHUP` and in
tests we often hit that race. This fixes one more instance of that.
Modifications:
Make sure the bind happens before we enter the selector.
Result:
more stable tests, fixes#378.
Motivation:
Warnings are bad.
Modifications:
Changed things that still work in 4.0/4.1 but are warnings in 4.2 to
improved versions.
Result:
less warnings on the upcoming 4.2
* Add http-parser license and authors
Motivation:
Quote:
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
Just linking is not enough.
Modifications:
Added the http-parser license.
Added the AUTHORS file. Not required by the license,
but the right thing to do.
Result:
Proper license inclusion for http-parser.
Motivation:
We can't nil out the connectPromise before we fail it. This totally
slipped through because we never fully waited for it because of the
reasons below.
It's quite easy to misuse `eventLoop.submit` as if you do some
asynchronous operation (will return `EventLoopFuture<T>`) the result of
the submit will be `EventLoopFuture<EventLoopFuture<T>>`. So if you just
do
try eventLoop.submit {
return somethingAsynchronous
}.wait()
then you will have only waited for the asynchronous operation to have
started (it might still be running). Fortunately, the compiler usually
warns you about that unless it returns `Void`. So it naturally tells you
to write
try eventLoop.submit {
return somethingAsynchronous
}.wait().wait()
which will wait for both. Unfortunately, `XCTAssertNoThrow` will just
eat away any type so there it's advisable to write
XCTAssertNoThrow(try eventLoop.submit { ... }.wait.wait() as Void)
to be sure it's actually a void. The Swift compiler however has an
annoying bug where it won't always realise that that's a problem
(https://bugs.swift.org/browse/SR-7478). Fortunately the 4.1 release
behaves okay so CI will catch it.
Modifications:
- replace the bad pattern
_ = try el.submit { ... }
- added `as Void`s inside `XCTAssertNoThrow`s that do submit
- added missing `.wait()`s
Result:
tests should be more correct.
Motivation:
We don't want to regress the number of heap allocations we perform.
Modifications:
Added appropriate environment variables to Docker files.
Result:
Things go bang if we regress Future allocation counts.
Motivation:
be able to run the sanity check via docker compose
Modifications:
add sanity task to docker compose file
Result:
you can now run sanity check via docker
Motivation:
Many uses of atomics restrict themselves to using atomic variables within
objects that already have reference semantics (i.e. classes) and have
appropriate lifetime management. In this case, the current NIO Atomic
performs an unnecessary heap allocation in order to get itself a reference
count that it can use to free the underlying heap memory.
This is an unnecessary allocation that can often be elided, especially in
situations where many such atomics may be needed. Thus, we should provide
the ability to manually manage the lifetime of the heap-allocated memory for
the atomic, and change some uses of it in our codebase to reduce overhead.
Modifications:
1. Moved most of the code of Atomic to a new struct, UnsafeEmbeddedAtomic.
2. Reimplemented Atomic in terms of UnsafeEmbeddedAtomic.
3. Updated EventLoopFuture to use an UnsafeEmbeddedAtomic for isFulfilled.
Result:
1/3 as many allocations per EventLoopFuture.
Motivation: easier testing across different permutations of os and language versions
Modifications:
* update dockerfile to take both swift_version adn ubuntu_version
* update default linux version to 16.04
* create multiple docker-compose files that use arguments to define os and swift versions
* make docker-compose file DRYer with yaml anchors
Result: users/ci can easily run tests across various versions of ubuntu and swift
Motivation:
When debugging, I often use ByteBuffer.debugDescription which dumps
the bytes. Unfortunately, the format wasn't compatible with what
`xxd -r -p` expects. Now you can just copy some output, for example
echo '04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12' | xxd -r -p
and xxd -r -p will correctly parse the byte values.
Modifications:
made BB.debugDescription prefix byte values under 0x10 with a 0 instead
of a space.
Result:
easier debugging with the standard tools
Motivation:
Unfortunately as a result of #108 the WebSocketFrameDecoder can emit a
WebSocketFrame more than once if the user closes the connection in
channelRead, or any other callback while decode() is on the call stack.
This is obviously less than ideal, as it can allow multiple delivery of
frames.
Modifications:
Given WebSocketFrameDecoder a no-op implementation of decodeLast.
Result:
No multi-delivery of frames.
Motivation:
The dtrace scripts dev/malloc-aggregation.d was missing a bunch of more
rarely used memory allocation functions.
Modifications:
Added the more rarely used functions.
Result:
Better output when using dev/malloc-aggregation.d
Motivation:
We should not need to trigger any copy when the ByteBuffer was fully consumed and discardReadBytes() is called.
Modifications:
- If fully consumed just reset reader and writer Index.
- Add unit test
Result:
Less memory copies
Motivation:
There was some if let usage that is not needed . We can remove it and just pass down the promise (no matter if its nil or not).
Modifications:
Remove if let
Result:
Code cleanup
Motivation:
We should not need to do any precondition range changes when we change the reader / writer index within our ByteBuffer methods as we know the index is valid. Beside this we already have asserts in place.
Modifications:
Add missing _ methods to adjust the reader / writer index and make use of these.
Result:
Less range checks within our ByteBuffer methods.
Motivation:
We got a very valid question on Twitter
(https://twitter.com/karim_elna/status/989516133421199361) regarding
ByteBuffers 'sharing storage'. Our docs almost sound like a ByteBuffer
and its slices share storage even after a write. Especially given that
this is a difference to Netty, we should document this better.
Modifications:
Added clarifying documentation.
Result:
Hopefully the docs are more clear now.
Motivation:
@_inlineable is important for at least all performance sensitive
functions that use generics and/or closures.
Modifications:
added two missing @_inlineable
Result:
fewer allocations (not measurable because https://bugs.swift.org/browse/SR-7542)
Motivation:
We had a few issues with ByteBuffer methods allocating without us
knowing, the only way to make sure we don't regress is obviously a test.
Modifications:
add a ByteBuffer allocation counter test
Result:
less room for regressions.
Motivation:
There's a presumed optimiser bug which will trigger an allocation when
using `self` within `staticString.withUTF8Buffer { ... }` which makes it
cause an extra allocation.
Modifications:
use StaticString.utf8Start instead of withUTF8Buffer
Result:
less allocations
Motivation:
When compiling the tests the following warning is printed:
swift-nio/Tests/NIOTests/SelectorTest.swift:361:43: warning: result of call to 'wait()' is unused
}.wait().forEach { return try! $0.wait() } as Void)
Modifications:
Use XCTAssertNoThrow to silence the warnings.
Result:
No more warnings.
Motivation:
dtrace is extrmely useful when debugging allocation related issues. This
adds two scripts that have helped me many times.
Modifications:
- `dev/malloc-aggregation.d` which prints an aggregation of all
stacks that have allocated
- `dev/boxed-existentials.d` which live prints all allocations of boxed
existentials
Result:
sharing debugging tools is great
Motivation:
In the new CI, ChannelTests.testGeneralConnectTimeout often fails with
```
error: ChannelTests.testGeneralConnectTimeout : threw error "connection reset (error set): Network is unreachable (errno: 101) "
```
It's not a great test but this just works around it by saying that if
the network's down that's fine too.
Modifications:
also accept ENETDOWN and ENETUNREACH
Result:
tests should pass in new CI.
Motivation:
HTTP{Request,Response}Head were too large even with a less than 3 word
ByteBuffer, this shrinks them box CoW boxing them. Should also reduce
ARC traffic when passing around a bunch.
Modifications:
CoW box HTTP{Request,Response}Head
Result:
fewer existential containers created, more performance
Motivation:
NIO's dynamic pipeline comes with one performance caveat: If your type
isn't specialised in NIOAny (only types in the NIO module can be) and
it's over 3 words (24 bytes on 64-bit platforms), you'll suffer an
allocation for every time you box it in NIOAny. Very unfortunately, both
ByteBuffer and FileRegion were exactly 3 words wide which means that any
enum containing those would be wider than 3 words. Worse, both
HTTP{Request,Response}Head contained types that were wider than 3 words.
The best solution to this problem is to shrink ByteBuffer and FileRegion
to just under 3 words and that's exactly what this PR is doing. That is
slightly tricky as ByteBuffer was already bit packed fairly well
(reader/writer indices & slice begin/end were stored as a UInt32). The
trick we employ now is to store the slice beginning in a UInt24 and the
file region reader index in a UInt56. That saves one byte for both
ByteBuffer and FileRegion with very moderate tradeoffs: The reader index
in a file now needs to be within 64 PiB (peta bytes) and a byte buffer
slice beginning must start within 16 MiB (mega bytes). Note: The
reader/writer indices as well as slice ends are _not_ affected and can
still be within 4 GiB. Clearly no one would care about the restrictions
for FileRegions in the real world but we might hit the ByteBuffer slice
beginning limit in which case the slice would be copied out. But
given that slices are mostly used to slice off headers in network
protocols, 16 MiB should be _plenty_.
Norman was kind enough to measure the perf differences:
master (before this PR):
```
$ wrk -c 256 -d 10s -t 4 -s ~/Downloads/pipeline-many.lua -H "X-Host: SomeValue" -H "Host: swiftnio.io" -H "ThereAreEvenMoreHeaders: AndMoreValues" http://localhost:8888
Running 10s test @ http://localhost:8888
4 threads and 256 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 93.02ms 158.13ms 1.97s 93.07%
Req/Sec 112.79k 26.05k 258.75k 84.50%
4501098 requests in 10.04s, 214.63MB read
Socket errors: connect 0, read 111, write 0, timeout 89
Requests/sec: 448485.61
Transfer/sec: 21.39MB
```
after this PR:
```
$ wrk -c 256 -d 10s -t 4 -s ~/Downloads/pipeline-many.lua -H "X-Host: SomeValue" -H "Host: swiftnio.io" -H "ThereAreEvenMoreHeaders: AndMoreValues" http://localhost:8888
Running 10s test @ http://localhost:8888
4 threads and 256 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 107.53ms 206.56ms 1.99s 90.55%
Req/Sec 124.15k 26.56k 290.41k 89.25%
4952904 requests in 10.03s, 236.17MB read
Socket errors: connect 0, read 161, write 0, timeout 22
Requests/sec: 493852.65
Transfer/sec: 23.55MB
```
so we see a nice 10% improvement
Modifications:
- shrank ByteBuffer by 1 byte, making it 23 bytes in total
- shrank FileRegion by 1 byte, making it 23 bytes in total
- added @_inlineable to NIOAny where appropriate to not suffer boxed existentials in different places
- added tests for the new edge cases
Result:
- more speed
- fewer allocations
Refactored extension HTTPResponseStatus: Equatable, no change to the efficacy of the code.
Motivation:
Code readability is essential to a long-lasting maintainable project, the code this PR changes was "readable" however this PR will enhance the readability by removing excess lines of code.
Modifications:
Changed a long case statement, to a much shorter one.
Result:
There will be fewer lines of code, no change to the efficacy of product should occur. I am not familiar enough with the compiler to know if this will have a deleterious effect on performance I don't think it should be based on the way public var code: UInt { get } is implemented.
Motivation:
Its often useful to be able to add / retrieve elements on both sides of a CircularBuffer.
Modifications:
- Add last / prepend to be able to act on both ends.
- Add tests
Result:
Fixes https://github.com/apple/swift-nio/issues/279
Motivation:
The pipelining handler made the assumption that `channelRead` is never
called recursively. That's mostly true but there is at least one
situation where that's not true:
- pipelining handler seen a response .end and delivers a .head (which is
done in `channelRead`)
- a handler further down stream writes and flushes some response data
- the flushes fail which leads to us draining the receive buffer
- if the receive buffer contained more requests, the pipelining
handler's `channelRead` is called again (recursively)
The net result of that was that the new request parts from the receive
buffer would now jump the queue and go through the channel pipeline
next, before other already buffered messages.
Modifications:
made the pipelining handler buffer if a `channelRead` comes in from the
pipeline and there is already at least one message buffered.
Result:
the ordering of the incoming messages should now be respected which is
very important...
Motivation:
Often its useful to be still be able to access the local / remote address during channelInactive / handlerRemoved callbacks to for example log it. We should ensure its still accessible during it.
Modifications:
- Fallback to slow-path in ChannelHandlerContext.localAddress0 / remoteAddress0 if fast-path fails to try accessing the address via the cache.
- Clear cached addresses after all callbacks are run.
- Add unit test.
Result:
Be able to access addresses while handlers are notified.
Motivation:
There were two errors in testShuttingDownFailsRegistration that
could cause spurious test failures.
The first was that the test did not wait for connection establishment
before it began shutting the selector down, due to a change made in
The second was that the server side of the connection was not wedged open,
and so it would be closed by the call to loop.closeGently. That closure
could, if the main thread took long enough, lead to the client side
reading EOF and being forcibly closed.
Modifications:
Added a promise to wait for connection establishment.
Added support for wedging both the server and client side open.
Result:
Fewer test failures.
Motivation:
We should use power of two for the underlying storage to allow us to make use of bitmasking which is faster then modulo operations.
Modifications:
Use power of two and replace module with bitmasking.
Result:
Faster implementation of CircularBuffer.
Motivation:
It's quite common that someone asks for the canonical form of a header
and we don't have any header values. There's no need to do string
comparisons then, we can just return an empty array.
Modifications:
Check if we're asking for a header that isn't present and if so, just
return the empty array.
Result:
Should be ever so slightly faster.
Motivation:
Since forever we had a major bug in the Selector: In this condition:
- kqueue/epoll had many events
- in one of the earlier events we unregister a Channel whose fd is on of
the later events
- we subsequently (still in the same event loop tick) register a new
channel which gets the same fd as the previously closed one
then we would deliver an event that was meant for a previous channel to
a newly opened one.
Thanks to @mcdappdev for hitting this bug, helping us debug it and also
providing a repeatedly working repro.
Modifications:
if during event delivery any fd gets unregistered, we stop delivering
the remaining events and rely on the selector to redeliver them
again next time.
Result:
we don't deliver events for previously closed channels to new ones.
Motivation:
The NIOWebSocketServer demo works much better, when it actually
configures the WebSocketUpgrader.
You should have a test for that!
Modifications:
This adds the `upgrader` to the `HTTPUpgradeConfiguration`.
Result:
The demo will actually perform something web-sockety.
Motivation:
We recently changed the backing for the HTTP request and response
objects so that the URI string was no longer visible in
`request.description`. This patch fixes that and prints a format like
this:
HTTPRequestHead { method: GET, uri: "/", version: HTTP/1.1, headers: [("Host", "localhost:8888"), ("User-Agent", "curl/7.54.0"), ("Accept", "*/*")] }
and
HTTPResponseHead { version: HTTP/1.1, status: ok, headers: [("content-length", "12")] }
Modifications:
improved the HTTP request/response descriptions
Result:
debugging is easier
Motivation:
When a pending connect is still in process and the Channel is closed we need to ensure we use the correct ordering when notify the promises and ChannelHandlers in the pipeline.
The ordering should be:
- Notify pending connect promise
- Notify close promise
- Call channelInactive(...)
Modifications:
- Correct ordering of notification
- Add unit test
Result:
Ensure correct ordering when connect is still pending
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:
If a server binds "localhost", and then we try to connect with an
AF_INET socket, then on macOS at least some of the time we will have
a protocol mismatch, as at least some of the time localhost will have
resolved to ::1 before 127.0.0.1.
That's bad.
Modifications:
Create a socket whose address family matches the server's.
Result:
This test will pass more often
Motivation:
Immutable members of structs (properties defined with let) can never be changed
even if the struct itself is mutable (defined withh var). This makes it difficult
to build rich convenience APIs on top of these structs.
Modifications:
Changed all 'let' stored properties on HTTP{Request|Response}Head to 'var'.
Result:
HTTP{Request|Response}Head are easier to use now.
Motivation:
Since #286, we do eagerly detect connection resets which is good. To
resolve the situation we first try to read everything off the socket. If
something fails there, everything is good and the client gets the
correct error. If that however doesn't lead to any errors, we would
close the connection with `error: ChannelError.eof` which the client
would then see for example on a connect that happened to get
`ECONNRESET` or `ECONNREFUSED`. That's not right so these situations are
fixed here.
Modifications:
- on reset, try to get the socket error if any
- if no socket error was detected, we send a `ECONNRESET` because we
know we have been reset but not why and didn't encounter any errors
- write tests for these situations
Result:
connection resets that don't hit any other errors will now see the
correct error
Motivation:
The integration tests' info mode lets us see the number of allocations
the did, that's great.
Modifications:
run integration tests in info mode
Result:
mode information
Motivation:
Opening a file, seeking it or querying its size (or other information)
is blocking on UNIX so `NonBlockingFileIO` should support that too.
Modifications:
Added a method to `NonBlockingFileIO` which lets the user open a file
without blocking the calling thread.
Result:
Less blocking is good :)
Motivation:
When a connect() call returns an error other than EINPROGRESS, we
currently leave the FD registered and don't close the channel. This is
wrong, we should take this as a signal to close the socket immediately,
rathern than letting the selector tell us this FD is dead: after all,
we know it's dead.
Modifications:
Call `close0()` in synchronous connect failures.
Result:
Faster failures!
Motivation:
PR #286 started processing EPOLLHUPs. Sadly epoll also immediately
throws EPOLLHUP at you if you register a socket that isn't either
connected or listening. This fixes two more instances of this problem.
Modifications:
made sure sockets that are registered are either listening or
connected (and before we let the Selector wait for events)
Result:
tests should be more reliable
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.
Motivation:
Sometimes it's useful if the integration tests can output something that
isn't always useful. `-v` for verbose is way too verbose so this adds a
`-i` flag to the integration tests that lets 'info' messages through.
Modifications:
- add `-i` flags to integration tests
- make use of it in the integration counter tests
Result:
if we enable `-i` in CI, then we can constantly monitor the number of
allocations we do even if we don't fail the tests.