51 Commits
Author SHA1 Message Date
Johannes Weiss c07fea1aa5 HTTP1 example server: don't crash on empty file served (#962)
Motivation:

The file-io implementation in the example HTTP1 server just crashed on
empty file ;).

Modifications:

- fix the crash
- add integration test

Result:

fewer crashes

(cherry picked from commit c90b159b4f)
2019-04-12 16:37:14 +01:00
Cory Benfield 0bcc08d85f Simplify Heap implementation. (#960)
Motivation:

Our original Heap implementation used a bunch of static functions
in order to make it clear how it related to textbook heap
implementations. This was primarily done to ensure that it was easier
to see the correctness of the code.

However, we've long been satisfied with the correctness of the code,
and the Heap is one of the best tested parts of NIO. For this reason,
we should be free to refactor it.

Given https://bugs.swift.org/browse/SR-10346, we've been given an
incentive to do that refactor right now. This is because the Heap
is causing repeated CoW operations each time we enqueue new work
onto the event loop. That's a substantial performance cost: well
worth fixing with a small rewrite.

Modifications:

- Removed all static funcs from Heap
- Rewrote some into instance funcs
- Merged the implementation of insert into append.
- Added an allocation test to avoid regressing this change.

Result:

Faster Heap, happier users, sadder textbook authors.

(cherry picked from commit 0179535b99)
2019-04-12 16:37:02 +01:00
Johannes Weiss 22e6cd3c67 HTTP/1 headers simplification & cleanup (#857)
Motivation:

The HTTP/1 headers were quite complicated, CoW-boxed and exposed their
guts (being a ByteBuffer). In Swift 5 this is no longer necessary
because of native UTF-8 Strings.

Modifications:

- make headers simply `[(String, String)]`
- remove `HTTPHeaderIndex`, `HTTPListHeaderIterator`, etc

Result:

- simpler and more performant code
2019-03-06 18:11:40 +00:00
Johannes Weiss ac26c7298d slight improvements to the allocation tests (#859)
Motivation:

The allocation tests were needlessly running the resolver within the
allocation counted loop.

Modifications:

- bump to Swift version 5.0
- take the resolving out of the allocation counting loop

Result:

more accurate results
2019-03-01 18:53:25 +00:00
Johannes Weiss 66b00ec637 B2MD: fast-path to reduce allocations (#854)
Motivation:

B2MD has an important fast path:
- everything was consumed
- no buffers collected during re-entrancy

In this case we should short-circuit and move on as quickly as possible.

Modifications:

If everything was consumed in `decode` and no buffers were collected in
re-entrancy, returning a buffer isn't actually useful, we should just
drop it and not risk taking an allocation for a useless `clear`.

Result:

faster & fewer allocs
2019-02-28 15:04:43 +00:00
Johannes Weiss 840ccfb7fa integration tests: debug mode which doesn't delete tmp (#852)
Motivation:

Sometimes the contents of the temporary directories are important, so
let's have a flag to keep them.

Modifications:

introduce a -d flag which keeps the tmpdir

Result:

easier debugging
2019-02-28 10:26:02 +00:00
Johannes Weiss a41280919e rename ctx to context (#842)
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
2019-02-25 18:20:22 +00:00
Johannes Weiss 46ffd630de ChannelPipeline: addHandler and removeHandler instead of add/remove (#817)
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
2019-02-21 11:46:54 +00:00
Johannes Weiss 1198931823 ByteBuffer: rename set(<type>:, ...) to set<Type>(...) (#812)
Motivation:

ByteBuffer methods like `set(string:)` never felt very Swift-like and
also didn't look the same as their counterparts like `getString(...)`.

Modifications:

- rename all `ByteBuffer.set/write(<type>:,...)` methods to
  `ByteBuffer.set/write<Type>(...)`
- polyfill the old spellings in `_NIO1APIShims`

Result:

code more Swift-like
2019-02-12 11:11:45 +00:00
Nathan Harris caf9a3d8da standardize ELF.cascade* collection of methods (#802)
Motivation:

The `ELF.cascade` methods have a parameter label `promise` that does not match Swift API Guidelines, and a way to cascade just successes is not available - while for failures there is.

Modifications:

`ELF.cascade*` methods that already exist have had their `promise` label renamed to `to`, and a new `ELF.cascadeSuccess` method has been added.

Result:

EventLoopFuture now has the cascade methods `ELF.cascade(to:)`, `ELF.cascadeFailure(to:)`, and `ELF.cascadeSuccess(to:)`
2019-02-05 09:01:48 +00:00
Johannes Weiss 2392a0775d enable HTTP1 error handling by default (#801)
Motivation:

For compatibility reasons, we used to disable HTTP1 error handling by
default to not break SemVer.

Modifications:

enable HTTP1 error handling by default

Result:

HTTP1 protocol errors now handled automatically by default
2019-02-01 18:02:47 +00:00
Johannes Weiss de8d3e260e alloc tests: hook posix_memalign & reallocf (#782)
Motivation:

Swift started using posix_memalign very recently (Jan 2019) so we need
to hook that too to get correct results.

Modifications:

Hook posix_memalign, reallocf & valloc

Result:

alloc tests should pass again
2019-01-25 16:11:23 +00:00
Johannes Weiss f3294dd803 rename ELF.mapIfError to ELF.recover (#777)
Motivation:

The name `mapIfError` implied that you can transform the error value but
really that's never what it did. Instead, it allowed you to recover
from a failure.

Modifications:

- rename `mapIfError` to `recover`

Result:

cleaner method names
2019-01-24 17:09:13 +00:00
Johannes Weiss c4ff795dda remove ELP.succeed/fail's labels (#776)
Motivation:

EventLoopPromise.succeed/fail has extraneous labels that don't add
anything but noise.

Modifications:

remove extraneous labels

Result:

less noise in the code
2019-01-24 16:42:53 +00:00
Johannes Weiss 3e7d6a7bfd rename ELF.then to ELF.flatMap (#760)
Motivation:

ELF's API should be as close as possible to the new Result's API.
Therefore, we should rename `then` to `flatMap`

Modifications:

- renamed `then` to `flatMap`
- renamed `thenIfError` to `flatMapError`
- renamed ELF's generic parameter from `T` to `Value`

Result:

- more like Result
- fixes #688
2019-01-21 16:41:04 +00:00
Johannes Weiss 08eb3259ce better DispatchData support (#732)
Motivation:

DispatchData's APIs are less than optimal and the current one we used
did allocate at least on Linux to copy bytes out.

Modifications:

introduce ByteBuffer.write/read/set/getDispatchData

Result:

when Dispatch gets fixed, lower allocations
2019-01-03 17:45:45 +00:00
Johannes Weiss 90b72abd21 re-enable allocation test for Swift 5 (fixes #685) (#710)
Motivation:

We had to disable the allocation test because of a SwiftPM bug which is
now fixed.

Modifications:

re-enable the allocation tests

Result:

more tests == better
2019-01-03 11:32:13 +00:00
Ilya Puchka 0db96bf744 [NIOHTTP1Server] Use fixed default string to write in response and do not hardcode content length (#718)
* Use fixed default string to write in response and do not hardcode content length

Motivation:

Improve example code, resolve #714

Modifications:

Move hardcoded "Hello world" string to a constant property and removed hardcoding of content length header value

Result:

In example code content length will be written correctly when default response changes
2019-01-03 10:09:13 +00:00
Johannes Weiss 9b78557aff kick off NIO2 (#678)
Motivation:

NIO2 development starts now.

Modifications:

Made NIO Swift 5-only for everything else see docs/public-api-changes-NIO1-to-NIO2.md

Result:

NIO2 development can start.
2018-12-07 21:15:34 +00:00
Johannes Weiss a20e129c22 change newPromise(for: T.Type) to newPromise(of: T.Type) (#672)
Motivation:

making a promise of a type is more grammatical than making a promise for
a type.

Modifications:

s/newPromise(for/newPromise(of/g

Result:

more grammar
2018-11-28 17:32:07 +00:00
Johannes Weiss c1a84a0085 optional type parameter for newPromise() (#671)
Motivation:

When creating new promises I always find it very frustrating to type the
`: EventLoopPromise<Type>` type annotation but it's necessary for the
compiler to know type the promise will be fulfilled with.

Modifications:

allow an optional `for: SomeType.self` parameter for `newPromise` as

    let p = eventLoop.newPromise(for: Int.self)

is much easier to type than

    let p: EventLoopPromise<Int> = eventLoop.newPromise()

Result:

easier to write code
2018-11-28 12:18:03 +00:00
Johannes Weiss 1ac60906f2 allow more time to close fds in integration tests (#611)
Motivation:

As #563 shows, sometimes in CI we don't reach the number of open
expected file descriptors. The current assumption is that this is just a
race when CI is slow. This allows up to 10s to reach the correct number
of open file descriptors.

Modifications:

- allow up to 10s to reach the correct number of fds

Result:

hopefully fixing #563 finally
2018-09-11 12:49:13 +01:00
Johannes Weiss 89603d6244 add Ubuntu 18.04 and Swift 4.2 support (#604)
Motivation:

We should support the latest and greatest.

Modifications:

- add Ubuntu 18.04 support (packages exist for Swift 4.2 only)
- add Swift 4.2 support (for Ubuntu 14.04, 16.04 and 18.04)

Result:

- supporting the latest stuff
2018-09-07 14:54:23 -07:00
Johannes Weiss 0a7d346a4a unify dead pointer dummy values (#579)
Motivation:

Previously we used 0xdeadbeef for all dead pointers but that doesn't fit
into an `Int` on 32-bit platforms.

Modifications:

change the dead pointer value to 0xdeadbee which is good because even
after offsetting the pointer by a couple of bytes, we'll still have
'dead' in the registers which should give us a hint.

Result:

- unified dead pointer values on 32 and 64 bit
2018-08-16 19:00:56 +01:00
Johannes Weiss adf8db6133 run a netstat if there's a socket leak in integration tests (#576)
Motivation:

We have a flaky integration test (#563) and I can't reproduce locally in
docker unfortunately. We have an `lsof` output but it just reads

    NIOHTTP1S 5157 root   12u  sock       0,7      0t0 113688082 can't identify protocol

which isn't very helpful. That's a known `lsof` on Linux but and the
recommendation is to run `netstat` which we now do.

Modifications:

add netstat output to the integration tests debugging info.

Result:

hopefully more information so we can soon fix #563
2018-08-16 10:13:20 +01:00
Johannes Weiss f8600df5dc safer UnsafeRawBufferPointer use (#559)
Motivation:

Unsafe(Mutable)RawBufferPointers have a few APIs that make our code
easier to reason about. In this PR I'm trying to introduce some of it.

Modifications:

Improved UnsafeRawBufferPointer usage

Result:

code easier to reason about which hopefully leads to fewer bugs. Also:
In many cases we now get free bounds checking in debug mode, yay :).
2018-08-09 11:53:45 +01:00
Norman Maurer 82a6e4d821 Rename numThreads to numberOfThreads parameter. (#443)
Motivation:

We should be consistent with naming and also choose descriptive names.

Modifications:

- Deprecate old init method that uses numThreads
- Add new init with numberOfThreads param name
- Everywhere use the new init

Result:

More consistent and descriptive naming. Fixes https://github.com/apple/swift-nio/issues/432.
2018-05-25 17:37:55 +02: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
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ß 8d2c93a599 add a ByteBuffer allocation test (#358)
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.
2018-04-26 16:41:01 +01:00
Johannes Weiß c3706cdf2a reduce allocations & test we don't regress (#316)
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.
2018-04-17 13:07:15 +01:00
Johannes Weiß 4e4890d990 add 'info' mode for integration tests (#318)
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.
2018-04-17 10:13:05 +02:00
Johannes Weiß b109389c54 eagerly process input EOF/connection resets (fixes #277) (#286)
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
2018-04-16 19:36:47 +02:00
Johannes Weiß c9c43b53c1 propagate exit code in integration tests in verbose mode (#311)
Motivation:

Previously the integration tests ran in verbose mode wouldn't actually
fail as we didn't correctly propagate the exit code.

Modifications:

correctly propagate the exit code

Result:

integration tests correctly fail in verbose mode too
2018-04-13 14:35:37 +02:00
Johannes Weiß d94ab56d58 workaround ab (ApacheBench) in keep-alive mode (#260)
Motivation:

`ab -k` behaves weirdly: it'll send an HTTP/1.0 request with keep-alive set
but stops doing anything at all if the server doesn't also set Connection: keep-alive
which our example HTTP1Server didn't do.

Modifications:

In the HTTP1Server example if we receive an HTTP/1.0 request with
Connection: keep-alive, we'll now set keep-alive too.

Result:

ab -k doesn't get stuck anymore.
2018-04-10 18:28:10 +02:00
Norman Maurer 48cef4a59b Implement lazy headers parsing (#291)
Motivation:

We are currently parsing each header eagly which means we need to convert from bytes to String frequently. The reality is that most of the times the user is not really interested in all the headers and so it is kind of wasteful to do so.

Modification:

Rewrite our internal storage of HTTPHeaders to use a ByteBuffer as internal storage and so only parse headers on demand.

Result:

Less overhead for parsing headers.
2018-04-10 14:57:58 +02:00
Cory Benfield 1bff3ab7e8 Enable our one disabled integration test. (#295)
Motivation:

We have one integration test left disabled, but actually it basically
already passes: it just expects the wrong format of error. We should
have all our integration tests enabled.

Modifications:

Enabled the test.
Changed the wording of the error it expected.

Result:

No disabled integration tests.
2018-04-10 10:07:39 +01:00
Cory Benfield 5b2ad2d921 Add support for automatic HTTP error reporting. (#268)
Motivation:

Currently the HTTP decoders can throw errors, but they will be ignored
and lead to a simple EOF. That's not ideal: in most cases we should make
a best-effort attempt to send a 4XX error code before we shut the client
down.

Modifications:

Provided a new ChannelHandler that generates 400 errors when the HTTP
decoder fails.
Added a flag to automatically add that handler to the channel pipeline.
Added the handler to the HTTP sample server.
Enabled integration test 12.

Result:

Easier error handling for HTTP servers.
2018-04-07 10:13:31 +02:00
Johannes Weiß d7fb0ef4e3 improve integration tests verbose mode (#261)
Motivation:

Previously, the integration test's verbose mode would only shows the
output after the test has run, but a live view is better.

Modifications:

Made the integration test's verbose output live.

Result:

Easier to debug the integration tests.
2018-04-03 16:16:42 +01:00
Johannes Weiß 2839ef0a3c alloc counter test: better recursive malloc (#263)
Motivation:

The allocation counter integration tests previously used a pretty crude
malloc implementation for the case that malloc is needed whilst we
resolve malloc from libc using dlsym. This implements a much better
version and also allows us to actually use free. Previously we just
leaked all the memory (which is okay as its just a test but in
constrained environments this wouldn't scale as we might actually run
out of memory). The reason we used to leak the memory is that given a
pointer we couldn't figure out if that pointer was alloated using libc's
malloc or our crude malloc implementation so we didn't know how to free.
The new version fixes that as all the pointers vended from
recursive_malloc live in one global block. That makes it trivial to
check if a given pointer is allocated by recursive_malloc (lives in that
block) or libc's malloc (doesn't live in the recursive_malloc block).

Modifications:

- implemented a better recursive_malloc function
- make the allocation counter test actually free memory that can be
  freed

Result:

Less memory use in the allocation counter test.
2018-04-03 13:29:23 +01:00
Johannes Weiß ba470b7888 just set 127.0.0.1 as localhost's IPv4 address (#258)
Motivation:

Previously we tried to use `host` to determine localhost's IPv4 address.
That didn't work reliably in Docker and sometimes on macOS. Let's just
fix this to 127.0.0.1.

Modifications:

Hardcode localhost's IPv4 address as 127.0.0.1.

Result:

More stable test_16_tcp_client_ip
2018-03-30 17:47:54 +01:00
Johannes Weiß fee0b6199e make allocation counter test fail on error in subshell (#262)
Motivation:

In shell, subshells don't inherit the shell flags (such as `set -eu`)
and therefore need to set them again. The allocation counter test uses a
subshell but forgot to `set -eu` in the subshell.

Modifications:

`set -eu` in the subshell for the allocation counter tests.

Result:

if there's an error building the test program the test now fails.
2018-03-30 16:01:33 +01:00
Johannes Weiß 17c511464d allow some cool down time after allocation measurements (#257)
Motivation:

We have code running on multiple threads and certain allocations/frees
happen for example after a promise has been fulfilled. We can't
deterministically wait for that so the only thing we can do is sleep a
little and wait...

Modifications:

Added a 100ms delay after an allocation counted test run.

Result:

Hopefully we don't see this again:

    ["total_allocations": 322051, "remaining_allocations": 24], ["total_allocations": 322051, "remaining_allocations": -24]

where the first test run had 24 allocations that weren't freed and the
second one on the other hand had 24 frees for allocations that "didn't
happen"...
2018-03-30 16:35:37 +02:00
Johannes Weiß 68db2325df add a simple leak detector (#255)
Motivation:

Memory leaks are rare in Swift but they can happen. If we run a
realistic workload and the number of `malloc`s and `free`s is very close
to 0, we can be fairly sure we didn't have any (too bad) leaks.
Therefore this adds a simple leaks detector.

Modifications:

Add a leak detector.

Result:

We should now detect leaks even if the total number of allocations
doesn't increase.
2018-03-29 18:43:49 +01:00
Johannes Weiß c84b19a399 add an allocation counting integration test (#252)
Motivation:

In Swift, it's really easy to accidentally add allocations yet the
number of allocations is really important for performance.
Therefore it's useful to have an integration test that counts the number
of allocations and compares them to a reference (and fails if the number
of allocations increases).

Modifications:

- add an allocation counter
- add a HTTP1 client/server example that is run with the allocation
  counter intrumentation

Result:

We should now be able to track the number of allocations.
2018-03-29 18:31:08 +01:00
Cory Benfield 860a7d40a3 Add channel handler for server side pipelining. (#62)
Motivation:

HTTP pipelining can be tricky to handle properly on the server side.
In particular, it's very easy to write out of order or inconsistently
mutate state. Users often need help to handle this appropriately.

Modifications:

Added a HTTPServerPipelineHandler that only lets one request through
at a time.

Result:

Better servers that are more able to handle HTTP pipelining
2018-03-13 15:21:12 +00:00
Johannes Weiß 1065c9d38e add license headers for shell scripts (#135)
Motivation:

Our shell scripts didn't have license headers but they should.

Modifications:

Add licensing headers to all shell scripts

Result:

Licensing clear for shell scripts too.
2018-03-12 17:12:47 +00:00
Cory Benfield 9ed09c0a5c Our sample HTTP server should respect HTTP keep-alive. (#115)
Motivation:

Currently our HTTP server almost always just assumes that keep-alive
is enabled. It really shouldn't, it should validate more carefully.
Additionally, it mishandles TCP half-close in a way that breaks with
netcat.

Modifications:

Added keep-alive tracking to all handlers and ensured that connections
will be closed after a response to a keep-alive request has been sent.
Also add support for handling TCP half-close.

Result:

Non-keep-alive connections will be closed by the server in all cases.
Half-closed connections will be appropriately managed.
2018-03-12 13:54:58 +01:00
Johannes Weiß de0bc1ed83 fix integration tests on Darwin (#4)
Motivation:

The integration tests didn't work on Darwin anymore as the `CNIODarwin`
module wasn't included in their build.

Modifications:

Included the `CNIODarwin` module, just like `CNIOLinux`.

Result:

integration tests run on Darwin
2018-02-21 20:14:24 +01:00
Johannes Weiß 85513e7268 rename linker tests 2018-02-19 20:08:13 +00:00