770 Commits
Author SHA1 Message Date
Johannes Weiss 2601092b54 security: ByteBuffer: fix heap buffer overflow on slice realloc
Motivation:

ByteBuffer had a very bad (exploitable!) security vulnerability if the
following conditions are all true:

- user writes to a ByteBuffer which is a slice (slice.lowerBound != 0)
- the slice is uniquely referenced (ie. the buffer that it was sliced
  from is gone)
- the write triggers a re-allocation

Then the slice is actually _larger_ than the overall available capacity
so another write to said ByteBuffer could end up out of bounds.

Modifications:

- fixed slice reallocation

Result:

- fixed security vulnerability
2018-06-27 17:26:04 +01:00
Cory Benfield 77dc77b9b5 Don't provide promises when we don't care about results. (#437)
Motivation:

When we don't care about the result of an operation, we shouldn't provide
a promise.

While I'm here I also removed an unnecessary close() call in the
AcceptHandler: the close() would be called again almost immediately.

Modifications:

Removed a close() call.
Set `promise: nil` on a pair of close() calls.

Result:

Fewer promise allocations.
2018-05-24 12:53:51 +01:00
Norman Maurer d53ee6dafc Only forward bytes on removal when we know we can handle it (#430)
Motivation:

398b950eee introduced a change which forwarded bytes that were buffered in HTTPDecoder after it was removed when an upgrade was detected. This may be risky if we dont know that the pipeline can handle it.

Modifications:

- Add new initializer that allow us to configure if we should forward bytes or not.
- Automatically use this if we know that we added an upgrader
- Add unit tests.

Result:

Less risky implementation.
2018-05-23 20:26:24 +02:00
Cory Benfield 9e0eb8347a Correctly account for writes of all datagrams. (#431)
Motivation:

The Darwin gathering datagram writes shim incorrectly placed the
"bytes written" amount into the first slot in the array for every write.
This had the effect of incorrectly accounting for the amount of bytes
written for literally every element of a vector write. Not good.

Modifications:

Correctly account for each vector write element.

Result:

Lower risk of preconditions in incorrect situations, better accounting
of written bytes.
2018-05-23 17:48:10 +01:00
Norman Maurer 398b950eee Ensure HTTPDecoder will not run into re-entrance issues and correctly forward bytes left after removal. (#427)
Motivation:

We need to ensure we correctly guard against re-entrancy for all cases. Also we did not correctly ensure we forward pending data after removal which could lead to missing data after upgrades.

Modifications:

- pause the parser when we need to callout to the pipeline and so ensure we never fire events throught the pipeline while in callbacks of http_parser
- correctly forward any pending bytes if an upgrade happened when the decoder is removed
- Ensure HTTPUpgradeHandler only remove decoder after the full request is received
- Add testcase provided by @weissi

Result:

Correctly handle upgrades and pending data. Fixes https://github.com/apple/swift-nio/issues/422.
2018-05-23 12:38:53 +01:00
Johannes Weiß 80363d9d8c fix EventLoops that Bootstrap channel initialiser's call out on (#424)
Motivation:

Previously we were not running the (child/server)channelInitializers on the
event loop associated to the `Channel` we're initialising. Almost all
operations in there are pipeline modifications which are thread safe so
it presumably wasn't a massive correctness issue. However it's very
expensive to hop threads that often and it is also very unexpected. This
addresses this issue.

Modifications:

made all (child/server)channelInitializers run on the event loop that is
associated to their `Channel`

Result:

- more correctness
- less unexpected behaviour
2018-05-22 15:58:43 +01:00
Johannes Weiss ec880b0853 don't just drop Channels on the floor if registration fails
Motivation:

If registration of a Channel fails we need to close that Channel.
Previously we'd just drop it on the floor which triggers an assertion
that an open channel got leaked.

Modifications:

In cases where the Channel registration fails, we need to close that
channel.

Result:

- No crashes if registration fails.
- fixes #417
2018-05-22 11:29:20 +01:00
Johannes Weiß f2343bfd95 retain Channel from ChannelPipeline until destroyed (#415)
Motivation:

A long time ago, `ChannelPipeline.channel` was public and needed to be
thread-safe. That meant we could never mutate `ChannelPipeline.channel`.
Instead we stored it as an unowned reference that we only read when the
`Channel` was still alive.

It was the right call making `ChannelPipeline.channel` internal but we
forgot to then remove the `unowned` reference from `ChannelPipeline` to
`Channel`. This patch makes this reference strong but nils it out
whenever the `ChannelPipeline` is destroyed. That makes everything
easier because there is no danger anymore that the `Channel` gets
deallocated when the `ChannelPipeline` is still alive.

After destroying the `ChannelPipeline` we will still hand out a
`DeadChannel` if you call `ctx.channel` (as it's a non-optional
requirement).

This comes with an unfortunate drawback: Now if you just leak an open
Channel (which you shouldn't be able to when using the Bootstraps) we
can no longer detect that as the Channel and the ChannelPipeline will
have a retain cycle. Unfortunately I don't think there's a good way to
safely assert that.

Modifications:

- made `ChannelPipeline` hold a strong reference to `Channel` until the
  `ChannelPipeline` is destroyed

Result:

- don't crash if the user only retains the ChannelPipeline but not the
  Channel
2018-05-22 11:01:00 +02:00
Johannes Weiß 6e73790951 explain why typealias is complicated (#423)
Motivation:

We should explain why this typealias

    public typealias RangeType<Bound> = CountableRange<Bound> where Bound: Strideable, Bound.Stride: SignedInteger

isn't just

    public typealias RangeType = CountableRange

and that's because SR-6963.

Modifications:

added a comment explaining why

Result:

code easier to read
2018-05-21 19:44:01 +01:00
Johannes Weiss 5aa140ca96 websockets: connection closed frame must be flushed
Motivation:

Because EmbeddedChannel used to treat all writes as flushed the test
that tested that we do send out the WebSockets connection close frame
didn't actually test the right thing. Now that EmbeddedChannel behaves
more realisticly, this test actually fails.

This fixes the bug and the test that tests that a WebSockets connection
is successfully torn down after an error occured.

Modifications:

- use `writeAndFlush` to send out the connection close frame.

Result:

WebSockets connection actually gets closed on error.
2018-05-21 16:05:17 +01:00
Johannes Weiss c3d02b8d47 EmbeddedChannel: make write not auto-flush
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
2018-05-21 16:05:17 +01:00
Johannes Weiß 78e28e7d9c workaround SR-6963 (#420)
Motivation:

SR-6963 is currently blocking builds with Swift 4.2 pre-releases, we
should work around it.

Modifications:

work around SR-6963.

Result:

builds with 4.2 pre-release
2018-05-21 09:22:47 +01:00
Cory Benfield bad7c29742 Add ChannelCore.removeHandlers. (#408)
Motivation:

If ChannelPipeline.removeHandlers is internal it is extremely difficult
to implement a correct ChannelCore. For that reason, we should make it
available as an extension on ChannelCore.

This is a minor layering violation, but that's ok: ChannelCore and
Channel are not actually intended to be separate objects in most cases,
they are just separate for code clarity reasons.

Modifications:

Add ChannelCore.removeHandlers as a public method.

Result:

Easier to implement ChannelCore.
2018-05-18 10:48:39 +02:00
Johannes Weiß cea84765de Channel quiescing support (#399)
Motivation:

In certain cases it's useful to quiesce a channel instead of just
closing them immediately for example when receiving a signal.
This lays the groundwork by introducing the
`ChannelShouldQuiesceUserEvent` user event that when received can be
interpreted by a ChannelHandler in a protocol & application specific
way. Some protocols support tear down and that would be a good place to
initiate the tear down.

Modifications:

- introduce `ChannelShouldQuiesceUserEvent`
- handle `ChannelShouldQuiesceUserEvent` in the `AcceptHandler` with
  closing the server socket
- handle `ChannelShouldQuiesceUserEvent` in the
  `HTTPServerPipelineHandler` by only handling a already in-flight
  request and then no longer accepting input
- added `CircularBuffer.removeAll` (& tests)
- added tests for `nextPowerOf2()`

Result:

- handlers can now support quiescing
2018-05-18 10:48:18 +02:00
Johannes Weiß 6020265f13 fewer warnings for 4.2 in 4.2 mode (#407)
Motivation:

Minus [SR-7578](https://bugs.swift.org/browse/SR-7578) which will be
fixed soon, we should then compile warning-free in `-swift-version 4`
mode which is good.
However, we should also be as warning-free as possible in
`-swift-version 4.2`. This is not entirely possible because of
`@_inlineable` vs `@inlinable` but we can address the other warnings.

Modifications:

- make `CountableRange` vs `Range` (which used to be separate types but
  are now the same) work warning-free Swift 4.[01] and Swift 4.2

Result:

Fewer warnings.
2018-05-17 13:53:56 +01:00
Norman Maurer e029edef2a Do not allocate String to check if HTTP message is keep alive (#402)
Motivation:

We can check if a HTTP message is using keep alive without any allocation.

Modifications:

Directly act on the internal storage of HTTPHeaders to find out if keep alive is used or not.

Result:

Less allocations
2018-05-16 11:42:22 +01:00
Norman Maurer a7614d9180 Reuse detected keepalive of http_parser as long as possible (#299)
Motivation:

To detect if keepalive is used we need to search the headers (if HTTP/1.1 is used). This may be expensive depending how many headers are present. http_parser itself detects already if keep alive should be used and so we can re-use this as long as the user did not modify the headers.

Modifications:

Reuse keepalive parsed by http_parser as long as the headers were not modified.

Result:

Less overhead as long as the headers are not modified.
2018-05-14 18:04:52 +02:00
Johannes Weiß ec79bf2b0b add performance tester (#396)
Motivation:

NIO wants to be a highly performant library and therefore we need
performance tests.

Modifications:

Add a couple of performance tests.

Result:

Easier to talk about perf improvements/regressions if we use similar
benchmarks.
2018-05-11 07:22:24 +02:00
Alex Blewitt 1fa9f15aca Explicitly define constants through Posix and import errno.h (#400)
Explicitly define constants through Posix and import errno.h

Motivation:

We implicitly depend on errno's ENOENT in Linux.swift, but don't explicitly import errno.h.

Similarly, in some cases the compiler can be confused as to where SHUT_* come from, so make them an exported value from Posix instead.

Result:

Compiles successfully on Linux and Darwin.
2018-05-10 20:12:33 +02:00
Norman Maurer 4cbafde292 Add better guards again re-entrance in ByteToMessageDecoder (#370)
Motivation:

When the ByteToMessageDecoder re-entranced in its decode(...) / decodeLast(...) methods it could be possible that the ordering of processing and so the seen bytes are mixed.

Modifications:

- Refresh the buffer (and take a slice)  on each loop iteration and update the cumulationBuffers indicies.

Result:

More robust code.
2018-05-08 18:29:55 +02:00
Cory Benfield e9285c6bc8 Make hopTo(eventLoop:) public. (#395)
Motivation:

When this method was originally introduced it was also intended as a
helper for external users, but we never made it public.

Modifications:

Make hopTo(eventLoop:) public.

Result:

Users will have an easier time managing their threads.
2018-05-08 16:36:30 +01:00
Ludovic Dewailly 6fcbfc9b75 Minor typo: becuase -> because - issue#393 (#394) 2018-05-08 08:42:59 +02:00
Johannes Weiß 12cae95c64 remove assertion that String.UTF8View doesn't underestimate count (#392)
Motivation:

I left an assertion that String.UTF8View's underestimatedCount is equal
to the actual count of UTF-8 code units. It's good to see that it never
failed so far so we can expect it to be really good which is important
for performance.
However, there's no problem if it does actually underestimate maybe for
some special kind of Strings. So the assertion really isn't meaningful.

Modifications:

Remove the assertion.

Result:

Most likely nothing but we will not crash on something that we
shouldn't crash on.
2018-05-06 20:34:28 +02:00
Johannes Weiß a7ed5fd4e9 let the stdlib enumerate the Sequence elements (#391)
Motivation:

Very unfortunately [SR-7602](https://bugs.swift.org/browse/SR-7602)
Swift's String doesn't work very well on UTF-8 encoded data. Fortunately
(but unfairly see point (3) in
[SR-7602](https://bugs.swift.org/browse/SR-7602)) however there is now a
contiguous String storage for ASCII-only Strings that _only the stdlib_
can access. To benefit from the stdlib's capabilities of enumerating the
bytes faster than we can, we should use UnsafeMutableBufferPointer#initialize(from: Bytes).
Thanks @airspeedswift for pointing this out.

The performance gains on a recent Swift version are noticeable:

after this patch:

```
no-net_http1_10k_reqs_1_conn: 0.225782990455627, 0.228317022323608, 0.225206971168518, 0.22549307346344, 0.223728060722351, 0.225827932357788, 0.222437977790833, 0.221745014190674, 0.220004916191101, 0.222965002059937
http1_10k_reqs_1_conn: 0.688782095909119, 0.682757973670959, 0.689703941345215, 0.708670020103455, 0.691922068595886, 0.687381982803345, 0.681567072868347, 0.684866905212402, 0.683283090591431, 0.699701905250549
http1_10k_reqs_100_conns: 0.782313942909241, 0.779283046722412, 0.773630023002625, 0.776782989501953, 0.774596929550171, 0.775121927261353, 0.773631930351257, 0.784304022789001, 0.795854926109314, 0.786051988601685
```

before this patch:

```
no-net_http1_10k_reqs_1_conn: 0.232797980308533, 0.236240983009338, 0.237086057662964, 0.236070990562439, 0.236560940742493, 0.236254930496216, 0.234392046928406, 0.235393047332764, 0.234088897705078, 0.245710015296936
http1_10k_reqs_1_conn: 0.76228404045105, 0.788464903831482, 0.747326016426086, 0.753327012062073, 0.735787987709045, 0.727090001106262, 0.720335006713867, 0.721843004226685, 0.719871044158936, 0.728644967079163
http1_10k_reqs_100_conns: 0.841314911842346, 0.884468078613281, 0.854345917701721, 0.847344040870667, 0.847607016563416, 0.841101050376892, 0.814589977264404, 0.818693995475769, 0.832610964775085, 0.828818082809448
```

Modifications:

use UnsafeMutableBufferPointer#initialize(from: Bytes) to enumerate
String's bytes.

Result:

faster but still not fast enough, we need SR-7602 to be addressed
2018-05-06 09:30:54 +01:00
Norman Maurer 62a9ff1955 Fix possible header / URI corruption when discardReadBytes() is called in HTTPDecoder (#385)
Motivation:

When discardReadBytes() was called and we still did not pass the Head to the user it was quite possible that the headers / URI could be corrupted as the stored readerIndex did not matchup anymore.

Modifications:

- Override most of the functionality of ByteToMessageDecoder in HTTPDecoder to better work with the provided state machine of http_parser
- Remove allocations by removing the pendingInOut Array as its not needed anymore.
- Add guards against re-entrance calls
- Add unit test that shows that everything works as expected now.

Result:

Fixed bug and reduced allocations (8% - 10% perf win).
2018-05-04 19:22:54 +02:00
Johannes Weiß 2f55baf537 implement lazy selector registration (#388)
Motivation:

Previously we would eagerly register any fd with the selector
(epoll/kqueue) which works well with kqueue. With epoll however, you'll
get `EPOLLHUP` immediately if you supplied a socket that hasn't had
connect/bind called on it.
We got away with this because we took quite a bit of care to always make
sure we call connect/bind pretty much immediately after we registered
it.  And crucially before we ever asked the selector to tell us about
new events.

Modifications:

made selector registration lazy (when we try activating the channel by
calling connect/bind)

Result:

the user can now register and connect whenever they feel like it.
2018-05-04 19:09:59 +02:00
Helge Heß 7fcbff9fce Add support for compiling and running NIO on Raspberry Pi 32-bit (#383)
* Make NIOHTTP1 compile on 32-bit platforms

Motivation:

When building a datacenter out of Apple Watches w/ shattered
glasses, you'll need the ability to build on 32 bit platforms.
This fixes building NIOHTTP1 on such platforms.

Modifications:

This was resetting the parser context pointer using a very
long deadly beef. Had to shorted this for 32bit cows.

Result:

NIOHTTP1 compiles on 32 bit ARM platforms.
2018-05-04 17:13:13 +01:00
Johannes Weiß a5db2a6751 fix event loop hop between registration and activation of accepted channels (#389)
Motivation:

Once again, we had an extra event loop hop between a channel
registration and its activation. Usually this shows up as `EPOLLHUP` but
not so for accepted channels. What happened instead is that we had a
small race window after we accepted a channel. It was in a state where
it was not marked active _yet_ and therefore we'd not read out its data
in case we received a `.readEOF`. That usually leads to a stale
connection. Fortunately it doesn't happen very often that the client
connects, immediately sends some data and then shuts the write end of
the socket.

Modifications:

prevent the event loop hop between registration and activation

Result:

will always read out the read buffer on .readEOF
2018-05-04 15:48:08 +01:00
Johannes Weiß 5bebbf5565 don't crash if close is called when close fails (#387)
Motivation:

@vlm hit an interesting situation which is very likely the sign of
another bug that we have yet to find:

During a close, @vlm hit an error in close which lead to a user callout
which then closed again.

The immediate fix is simple (this PR) is as always not to call out to
the user before reconciling our own state. But hitting this bug also
means that either a `socket.close` or a `selectableEventLoop.deregister`
failed as we only called out in those situations. That definitely hides
a condition that is hard to imagine without another bug that we still
need to find.

Modifications:

in `BaseSocketChannel.close0` follow rule 0 and don't call out before
reconciling state.

Result:

fewer crashes, less potential to hide other bugs.
2018-05-03 17:35:49 +02:00
Johannes Weiß 359f35930a fix Swift 4.2 compile error (#384)
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
2018-05-02 18:42:48 +01:00
Johannes Weiß 8bf1be0672 fix some Swift 4.2 warnings (#374)
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
2018-05-01 16:04:44 +01:00
Helge Heß 772917f3a1 Add http-parser license and authors (#251)
* 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.
2018-05-01 15:49:14 +01:00
Johannes Weiß 86fce7fce8 don't nil out connectPromise prematurely and wait fully (#337)
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.
2018-05-01 15:24:20 +01:00
adamnemecek a022954256 Refactored UInt32 and UInt64 methods nextPowerOf2 (#371)
* * refactored UInt32 and UInt64 methods nextPowerOf2

* Added nextPowerOf2 to FixedWidthInteger
2018-05-01 10:36:37 +01:00
Cory Benfield a1980922f3 Add UnsafeEmbeddedAtomic and use it. (#373)
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.
2018-05-01 11:02:27 +02:00
Johannes Weiß a4318d5e75 make BB.debugDescription print xxd -r -p compatible format (#367)
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
2018-04-27 11:59:08 +01:00
Cory Benfield 708a62d257 Avoid delivering websocket frames twice on EOF. (#368)
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.
2018-04-27 11:02:51 +01:00
Norman Maurer e5dedbec14 Not cause a CoW when calling ByteBuffer.discardReadBytes() while it was fully consumed. (#363)
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
2018-04-27 10:04:18 +01:00
Norman Maurer cf064a0575 Remove unnecessary if let usage in writeAndFlush (#365)
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
2018-04-27 09:48:34 +01:00
adamnemecek 776c3f42cb trimmed whitespace (#361)
Trimmed trailing whitespace.

Motivation:

Trimmed trailing whitespace.

Modifications:

Trimmed trailing whitespace.

Result:

Less trailing whitespace.
2018-04-27 08:33:32 +02:00
Norman Maurer 6565ec5a39 Not do any precondition range checks when moving the reader / writer index from within our methods of ByteBuffer. (#362)
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.
2018-04-26 21:43:41 +02:00
Johannes Weiß 5d3aa226d1 improve ByteBuffer documentation regarding CoW on slices (#359)
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.
2018-04-26 21:24:48 +02:00
Johannes Weiß 69c3d28a0b two missing @_inlineables (#360)
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)
2018-04-26 18:32:21 +01:00
Johannes Weiß 89e5574bb4 fix optimiser problem triggered in BB.set(staticString:) (#354)
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
2018-04-26 15:41:49 +02:00
Johannes Weiß bc61e6a815 shrink HTTP{Request,Response}Head by CoW boxing them (#351)
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
2018-04-24 20:03:27 +02:00
Johannes Weiß db61cfe38e make enums containing ByteBuffer fit in three words (#349)
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
2018-04-24 18:51:24 +01:00
Shaun Hubbard 163827b68e Refactor http response status equatable (#335)
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.
2018-04-24 15:36:36 +02:00
Norman Maurer 976074d536 Add last / prepend to CircularBuffer (#347)
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
2018-04-24 10:26:38 +02:00
Johannes Weiß ec30e5cc5a fix recursive channelReads in pipelining handler (#348)
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...
2018-04-24 08:18:21 +01:00
Norman Maurer 9f01374169 Ensure localAddress / remoteAddress are still accessible in channelInactive / handlerRemoved (#346)
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.
2018-04-23 12:51:01 +02:00