Commit Graph
2140 Commits
Author SHA1 Message Date
Bas Broek 4c89a4e675 Give symbols some breathing room
Motivation:

Adds spacing around a `+` and `{`.
2018-03-19 14:44:08 +01:00
Bas Broek 1db0be8ed9 Infer return types
Motivation:

Removes unncessary explicit types that are inferred.

Modifications:

Infer types that are being returned from a function or computed variable.

Result:

Cleans up the code.
2018-03-19 14:43:55 +01:00
Bas Broek b180113d81 Improve switch readability
Motivation:
This changes two things:
- it removes the negation of non-used associated types (the removal of `(_)`).
- it prefers exhausting `switch`es over `default`ing.

This change does not impact bahavior; it is pure refactoring.

Modifications:

Omitting needless `(_)`'s and explicitly exhausting switches.

Result:

This change is pure refactoring.
2018-03-19 14:43:38 +01:00
Norman Maurer edfbe50fc8 Ensure we always update the promise before calling fire* methods and also udate channel state before. (#181)
Motivation:

We not always ensure correct ordering which made it quite hard to reason about things. We should always first notify the promise before we call the fire* method that belongs to the event. Beside this we sometimes fired events or notified promised before correctly update the active state / addresses of a Channel which could result in unexpected results when query the Channel during execution of callbacks and handlers.

Modifications:

- Ensure we always notify promise first
- Always correctly update channel state before notify promise
- Add test to verify notification order.

Result:

Correct ordering of events which makes things easier to reason about and which follows what netty is doing.
2018-03-19 20:52:31 +09:00
Cory Benfield 54c68db6fb Make EmbeddedEventLoop behave more like the regular one. (#189)
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.
2018-03-19 20:41:35 +09:00
Norman Maurer b91090f563 Fix possible endless loop when shutdown SelectableEventLoop (#188)
Motivation:

When the SelectableEventLoop is shutdown it will process a defer block in which we tried to fail all scheduled tasks that were not processed yet. The problem here was that we incorrectly not dropped the processed task and so ended in an endless loop which prevent the defer block to complete.

Beside this how we processed the scheduled tasks that were ready for execution was quite in-efficient as we always called removeFirst() which will most likely case a memory copy to move the elements around.

Modifications:

- Correctly fail all scheduled tasks without end up in an endless loop
- Use a for each loop to reduce overhead of processing ready tasks.

Result:

It's always possible to shutdown a SelectableEventLoop and less overhead when processing ready tasks.
2018-03-19 19:53:41 +09:00
Helge Heß b06b712085 No need to wrap fatalError within code
Motivation:

No need for the "self-invoking function" here.

Modifications:

Call fatalError directly.

Result:

18 bytes are saved in the source code. No functional
difference.
2018-03-19 09:52:44 +01:00
Helge Heß 94718bcaa8 Wrap sendfile() in #if's that match the import
Motivation:

NIO doesn't compile on iOS. Which I'd like to do.

Modifications:

The #if's used to protect the syscall do not match
the #if's used to import.
Specifically the Darwin branch only applied to
macOS, not watchOS or homePodOS.

Result:

Hopefully will compile on iOS.
2018-03-19 09:52:44 +01:00
adamnemecek 81d9da57d8 Refactor PriorityQueue ==. (#183)
Motivation:

The new implementation doesn't convert lhs and rhs to arrays, thereby saving 2 allocations.

Modifications:

Changed the body of priority queue ==.

Result:

The comparison will be faster and use less memory.
2018-03-17 01:56:15 +09:00
Cory Benfield ab4032c4eb Suppress compiler warnings in release mode. (#179)
Motivation:

There's no reason for us to emit compiler warnings.

Modifications:

Remove use of _isDebugAssertConfiguration to guard code, instead
use a hand-rolled hacky solution on top of assert.

Result:

Fewer warnings, more sadness.
2018-03-16 23:53:16 +09:00
Siemen Sikkema 37ee542874 Replace internal HTTPResponseStatus factory method with public init (#158)
Motivation:

In order to create a `HTTPResponseStatus` value from an status code code
currently one would have to make a custom HTTPResponseStatus. The
problem with that is that:
`HTTPResponseStatus.custom(code: 200, reasonPhrase: "") != HTTPResponseStatus.ok`
The logic of detecting whether a status code matches one of the known
cases already exists but only in an internal factory method.

Modifications:

- removed internal static `from` method from `HTTPResponseStatus`
- added public init with the functionality previously in `from`
- replace the single use of the `from` method with the new `init`

Result:

When initializing a `HTTPResponseStatus` value with a value of e.g.
`200` the init method will result in a `HTTPResponseStatus.ok`.
2018-03-16 23:34:49 +09:00
Cory Benfield 28fe6e4abd Support hopping event loops with EventLoopFuture (#177)
Motivation:

A somewhat common requirement when working with chains of futures
is needing to hop from one event loop to another. This is particularly
common when relying on the fact that EventLoopFuture will synchronize
with the event loop that created it: you often want to rely on that
implicit locking, rather than use Dispatch or Lock to achieve the
same effect.

While doing this hop requires relatively little code, it's not
necessarily totally apparent to new users how they would do it.
Additionally, the most naive implementation incurs the overhead of
allocations and reference counting in cases where it's not necessary
(e.g. when you have only one event loop, or when both work items are
being scheduled on the same event loop).

For this reason, we should have a nice concise way for a user to
request this behaviour and get a relatively performant implementation
of the behaviour.

Modifications:

Added EventLoopFuture<T>.on(eventLoop:).

Changed AcceptHandler to use the new method rather than its (slower)
alternative.

Result:

Users will have an easier time working with EventLoopFutures.
2018-03-16 14:42:24 +01:00
Johannes Weiß 320561f437 fix EventLoopFuture.and's serious threading issues (#176)
Motivation:

EventLoopFuture.and had serious threading issues if the EventLoops
weren't the same.

Modifications:

Fixed the threading issues and tested them properly.

Result:

Hopefully `and` and `andAll` now don't crash if you use them across
EventLoops.
2018-03-16 12:44:49 +01:00
Norman Maurer 2c4d81dd79 Don't close DatagramChannel when recvfrom fails with ECONNREFUSED / ENOMEM (#171)
Motivation:

We should not close the DatagramChannel when recvfrom fails with ECONNREFUSED / ENOMEM. The former may be caused by a previous sendto and the other may be recoverable by just stop reading for some time.

Modifications:

- Special handle ECONNREFUSED and ENOMEN to not close the channel.
- Add unit tests

Result:

More robust datagram support.
2018-03-16 10:10:50 +01:00
Johannes Weiß f10d71b379 fix closed accepting Channels in closed ServerSocketChannels (#170)
Motivation:

For servers NIO had a race where when you start tearing down the
`ServerSocketChannel` and at roughly the same time a client connects, we
would not fully bring that channel up, nor tear it down. That lead to
open channels being deallocated which leads to a crash as that's an
illegal state.

Modifications:

Made sure newly accepted channels get closed if the
`ServerSocketChannel` is already clsing.

Result:

No crashes anymore when a client connects to a closing server.
2018-03-16 17:49:19 +09:00
Johannes Weiß 7e090d622d port numbers sin[6]_port are in network byte order (#167)
Motivation:

We returned port numbers directly from the sockaddr structures but
they're in network byte order. Our code only read them correctly when
presenting, oops.

Modifications:

Corrected the port number reading and tested that.

Result:

Port numbers should now be correct.
2018-03-16 17:36:17 +09:00
Norman Maurer 22d3439c4b Add handler that provides some backoff for accepts if these failed because of an IOError. (#126)
Motivation:

Often accept errors are recoverable over time as for example you may just run out of file descriptors. Because of this it may be useful to just "delay" accepts a bit to recover.

Modifications:

Add ChannelHandler which will backoff accepts.

Result:

Be able to recover from accept errors gracefully.
2018-03-15 21:23:19 +01:00
Norman Maurer 0c37c649fa Add missing docs to EventLoopPromise and EventLoopFuture (#169)
Motivation:

EventLoopPromise and EventLoopFuture had some missing docs.

Modifications:

Add docs

Result:

More complete documentation.
2018-03-16 03:08:05 +09:00
Norman Maurer b98c4eb48d channelRead should never be triggered if autoRead is false. (#164)
Motivation:

At the moment its possible that channelRead is triggered even if autoRead is never changed to true and no read() is triggered.

Modifications:

- Always register with .none on the Selector and then just call readIfNeeded0()
- Only register for EPOLLRDHUP if .read, .write or .all is used.
- Add test case.

Result:

Fixes https://github.com/apple/swift-nio/issues/160.
2018-03-15 18:53:45 +01:00
Cory Benfield 4c0ed16cde Add new, better helper method for configuring HTTP servers. (#159)
Motivation:

The current HTTP server helpers are not modular, meaning that each
time we add a new first-party HTTP handler we need to add a brand new
method. Additionally, they do not currently compose, so if you want
assistance with HTTP pipelining *and* to support HTTP upgrade you are
out of luck.

Modifications:

Deprecate the two existing server helpers.

Add a new server helper that can be extended to support all of the
possible features that users may want in their HTTP pipelines.

Result:

Users will have a single place to go that can be used to configure
their HTTP server pipeline, and that understands how the different
handlers fit together in a complete pipeline.
2018-03-16 02:13:13 +09:00
Norman Maurer c40c6e1222 Add support to obtain the current EventLoop (#120)
Motivation:

In certain cases it would be useful to be able to access the current EventLoop (which is tied to a thread).

Modifications:

- Add MultiThreadEventLoopGroup.currentEventLoop
- Add tests

Result:

Fixes [#59]
2018-03-15 16:05:35 +01:00
Semen Zhydenko 73e89833fc Fixed typos in comments 2018-03-15 22:11:46 +09:00
Cory Benfield 79a87ab76a Let Upgrade handler remove other HTTP handlers. (#144)
Motivation:

The HTTP pipeline may contain other HTTP protocol specific handlers,
beyond just the ones that the upgrade handler knows explicitly. It should
be possible to get the upgrade handler to remove those at the right time.

Modifications:

Add extra support for removing handlers.

Result:

It'll be possible for the HTTP upgrade logic to remove things like the
pipelining handler at upgrade time.
2018-03-15 01:34:03 +09:00
Cory Benfield 25dd80aa9f Add support for getting a handler of a given type. (#155)
Motivation:

It is often useful to find a handler of a given type even when you
aren't holding a reference to that handler. This patch allows us to
do that.

Modifications:

Add context(handlerType:) function to the channel pipeline.

Result:

Users can find handlers of a given type in a pipeline.
2018-03-14 23:20:29 +09:00
Johannes Weiß 4098832e4e don't use _Nonnull for clang 3.6 (#147) (#154)
Motivation:

Clang 3.6 doesn't know about `_Nonnull` which breaks compilation for our
C atomics.

Modifications:

Defined `_Nonnull` as `__attribute__((nonnull))` which seems to already
be available before clang 3.7.

Result:

NIO compiles with clang 3.6 as the default C compiler.
2018-03-14 22:11:17 +09:00
Johannes Weiß 2cac305e3e work bug in latest Swift 4.1 with closures taking () (SR-7191) (#149)
Motivation:

In a few instances, we have code that ignores a `()` argument in a
closure with this syntax:

    { (_: Void) in

whilst that's a bit odd, it shouldn't be wrong and Swift 4.0.x is also
totally happy with it. The latest Swift 4.1 candidates however are not
and also there's a better way of spelling this:

    { () in

and in some cases even just

    {

Modifications:

Removed instances of `{ (_: Void) in`

Result:

Compiles with `swift-4.1-DEVELOPMENT-SNAPSHOT-2018-03-12-a`
2018-03-14 08:41:03 +01:00
Cory Benfield b542775605 Add initial websocket codec. (#109)
Motivation:

Websockets is a major protocol in use on the web today, and is
particularly valuable in applications that use asynchronous I/O
as it allows servers to keep connections open for long periods of
time for fully-duplex communication.

Users of NIO should be able to build websocket clients and servers
without too much difficulty.

Modifications:

Provided a WebsocketFrameEncoder and Decoder that can serialize and
deserialize Websocket frames.

Result:

Easier use of websockets.
2018-03-13 17:24:54 +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
Norman Maurer 005a3b702b Don't close ServerSocketChannel when accept fails with ECONNABORTED / EMFILE / ENFILE, ENOBUFS. ENOMEM. (#125)
Motivation:

We should not close the server socket when accept fails with ECONNABORTED / EMFILE / ENFILE, ENOBUFS. ENOMEM as generally speaking these may be "recoverable" once some existing connections were closed for example. It's possible to implement a backoff strategy for these with a ChannelHandler.

Modifications:

- Special handle of ECONNABORTED / EMFILE / ENFILE, ENOBUFS. ENOMEM for ServerSocketChannel.

Result:

Not close servet socket for errors from which it is possible to recover.
2018-03-13 15:09:13 +00:00
Jason Toffaletti 5a4f630c5b make isOpen a computed property (#136)
Motivation:

Reduce memory footprint of BaseSocket

Modifications:

- made isOpen a computed var from 'descriptor >= 0'
- BaseSocket init check precondition 'descriptor >= 0'

Result:

- isOpen no longer requires storage space
- close() sets descriptor to -1
- descriptor property changed from let to var
2018-03-12 22:04:47 +01:00
Cory Benfield e6456f9024 Add support for adding handlers at arbitrary pipeline locations (#128)
Motivation:

Currently we only supporting adding channel handlers at the front
or the end of the pipeline. This is potentially a bit frustrating:
it becomes impossible to insert handlers relative to a specific
point in the pipeline, which limits users ability to code generic
pipeline modification operations.

Modifications:

Added two new methods to ChannelPipeline, specifically
add(handler:before:) and add(handler:after:). Also performed a
substantial internal refactoring of the ChannelPipeline handler
adding code to ensure that all operations go through the same
logical path, redefining add(handler:first:) in terms of adding
either before tail or after head.

Result:

Users will be able to insert channel handlers at any point in a
ChannelPipeline, so long as they are able to point at a handler
already in that pipeline.
2018-03-12 20:16:13 +01:00
Jason Toffaletti 49e159c51d use accept4 and SOCK_NONBLOCK on Linux (#124)
Motivation:

Reduce system calls on Linux required for configuring sockets as
nonblocking.

Modifications:

- expose accept4 as CNIOLinux_accept4
- add Linux internal enum for exposing Linux specific API
- wrap CNIOLinux_accept4 with Linux.accept4
- expose SOCK_NONBLOCK and SOCK_CLOEXEC on Linux
- add setNonBlocking parameter to BaseSocket.newSocket
- add setNonBlocking parameter to ServerSocket.accept

Result:

Servers and clients on Linux will use fewer system calls creating new sockets.
2018-03-12 20:12:20 +01:00
Ben Cohen 41b8941402 Nest HTTPHeaderIterator inside HTTPHeader, un-erase makeIterator() return type. (#94)
Motivation:

Simplifies the code by putting the iterator in HTTPHeader's namespace.

Additionally, removing the type erasure should result in more performant code as `AnyIterator` is an optimization barrier. The type erasure did not appear to be adding an abstraction benefit.

Modifications:

Nested (internal) type `HTTPHeaderIterator` as `HTTPHeader.Iterator`
Explicit rather than inferred types for `Element` and `Iterator`.
Eliminated `AnyIterator` wrapper from `makeIterator()`
Added lower-priority version that still returns `AnyIterator` for source compatibility.

Result:

Unless caller was explicitly typing the iterator, should have no noticeable impact other than performance.
2018-03-12 18:44:43 +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
Jason Toffaletti ee60aa62c0 properly destroy pthread mutex and cond (#133)
properly destroy pthread mutex and cond

Motivation:

properly destroy pthread mutex and cond

Modifications:

call pthread_mutex_destroy in Lock deinit
call pthread_cond_destroy in ConditionLock deinit

Result:

Lock and ConditionLock deinit may crash if locks are still in use.
2018-03-12 17:54:03 +01: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
Cory Benfield fee84ed63a Revert "make isOpen a computed property (#123)" (#129)
This reverts commit 4deeaf6365.
2018-03-12 13:27:42 +01:00
Jason Toffaletti 4deeaf6365 make isOpen a computed property (#123)
Motivation:

Reduce memory footprint of BaseSocket and FileHandle

Modifications:

- made isOpen a computed var from 'descriptor >= 0'
- add withSocketpair to TestUtils
- use real pipe and socketpair file descriptors for tests
- BaseSocket and FileHandle init check precondition 'descriptor >= 0'

Result:

- isOpen no longer requires storage space
- close() sets descriptor to -1
- descriptor property changed from let to var
- tests will need to use valid file descriptors
2018-03-12 19:07:30 +09:00
Norman Maurer 95a6e44e93 Remove return when possible. (#122)
Motivation:

We can cleanup the code by removing return keywords in closures sometimes.

Modifications:

Remove return when possible.

Result:

Cleaner code.
2018-03-11 22:47:29 +09:00
Cory Benfield 43dd9c0b33 Ensure that handlers added with first:true are in proper order. (#118)
Motivation:

Right now addHandlers(first:) does not actually add handlers at the
front of the pipeline: it just adds them *backwards* at the end of
the pipeline. That's definitely not right.

Modifications:

Pass the first: flag into the call to add each specific handler to
ensure they're actually put at the front of the pipeline.

Result:

Handlers added to the front of the pipeline actually are.
2018-03-09 15:26:53 -08:00
Cory Benfield 684ae3d933 Add READMEs for the various sample applications (#117) 2018-03-09 09:06:06 -08:00
Shaun Hubbard 9015319d82 fixed doc comment (#119) 2018-03-09 23:25:17 +09:00
Helge Heß ad8afee8aa Fix issue #110, IPv6 address desc contains 0 bytes (#111)
Motivation:

Fix for issue #110, .description on IPv6 addresses
return a String with 0 codepoints in it, like so:

  [IPv6]::1<NUL><NUL><NUL>....lots..

Modifications:

Use String(cString:) instead of decode, which doesn't
care about \0-cstr terminators.

Result:

Issue fixed, everything is awesome, everyone is happy.
2018-03-08 20:22:42 +09:00
Cory Benfield 1fdee500e5 Ensure channels don't get stuck completely unregistered. (#104)
Motivation:

It should be possible to have channels that are not registered
for any form of I/O without them getting stuck in that model
forever.

Modifications:

Remove the code that prevents channels registered for `.none` from
registering for anything else.

Result:

Channels can actually be registered for nothing without becoming
wedged open forever.
2018-03-06 02:08:19 +09:00
Norman Maurer 784c5a7355 Declare ThreadSpecificVariable public (#102)
Motivation:

It's often useful for users to be able to store a thread-specific value (and so also EventLoop specific). We have ThreadSpecificVariable for this which was internal.

Modifications:

Change ThreadSpecificVariable to be public.

Result:

Fixes [#61].
2018-03-06 00:32:05 +09:00
Norman Maurer 01f74a4b4e Prefer to use ctx.remoteAddress over ctx.channel.remoteAddress (#103)
Motivation:

We should use ctx.remoteAddress whenever possible as its "cheaper".

Modifications:

Replace ctx.channel.remoteAddress with ctx.remoteAddress

Result:

More correct and better example code.
2018-03-06 00:25:55 +09:00
John Connolly fa60fa8c40 Change class func to static on Thread. (#101)
Motivation:
Thread is declared final, so I believe spawnAndRun should be static.

Modifications:
Change class func to static
Result:
More consistent code, and spawnAndRun is statically dispatched.
2018-03-06 00:12:23 +09:00
Norman Maurer 3e70c798c8 Use one Box to store both, the local and remote address. (#99)
Motivation:

We should just use one Box to store both, the local and the remote address. This will remove some heap allocations. And reduce memory overhead.

Modifications:

Use a tuple which holds the local and remote address and so only use one Box for the cached addresses.

Result:

Less heap allocations and less memory usage.
2018-03-06 00:02:57 +09:00
Johannes Weiß a597c7320c make ChannelPipeline.init public (#84)
Motivation:

There are a few network protocols that are best implemented with child
`Channel`s. And given that those child `Channels` need a
`ChannelPipeline` the init for `ChannelPipeline` should be public.
Otherwise these protocols can only be sensibly implemented in the core
`NIO` module which is unfair.

Modifications:

make `ChannelPipeline.init` public

Result:

modules other than `NIO` can implement child `Channel`s.
2018-03-05 06:26:06 -08:00
Ian Partridge 8b8951eadd doc: ByteBuffer improvements (#85)
* doc: ByteBuffer improvements

* doc: don't imply that creating a new ByteBufferAllocator for every buffer is OK
2018-03-05 19:29:47 +09:00