Commit Graph
1096 Commits
Author SHA1 Message Date
Cory Benfield 9326f749aa Allow ChannelCore implementors to unwrap NIOAny. (#321)
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
2018-04-18 10:04:12 +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
Pushkar N Kulkarni acfb5f7136 Make IdleStateHandler.IdleStateEvent public (#319)
IdleStateHandler.IdleStateEvent is currently internal. Make it public.

Motivation:

The IdleStateEvent is delivered to the user viapublic func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any). In this method, it must be possible to have a check on the type of event. IdleStateEvent must be public.

Modifications:

Change access level of IdleStateHandler.IdleStateEvent to public.

Result:

IdleStateEvent will become a part of the NIO API.
2018-04-16 20:57:03 +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
Norman Maurer 7758140634 Reduce allocations when notify promises related to pending writes. (#308)
Motivation:

We returned an callback which needed to be executed by the caller. This will cause extra allocations and is not needed. We can just return a EventLoopPromise which will cascade the notification.

Modification:

Not return a closure but promise.

Result:

Less allocations.
2018-04-13 15:20:47 +02:00
Norman Maurer 098239bb27 Remove PendingWriteStateManager.chunks (#312)
Motivation:

chunks variable is not needed anymore.

Modifications:

Remove not needed variable

Result:

Less code FTW.
2018-04-13 07:49:27 +02:00
Cory Benfield 3275ff7c9c Don't call to user code before reconciling Channel state. (#310)
Motivation:

Callouts to user code allows the user to make calls that re-enter
channel code. In the case of channel closure, we could call out to the
user before the channel knew it was completely closed, which would
trigger a safety assertion (in debug mode) or hit a fatalError
(in release mode).

Modifications:

Reconciled channel state before we call out to user code.
Added a test for this case.

Result:

Fewer crashes, better channel state management.
2018-04-12 13:49:09 +01:00
Johannes Weiß aee4aad3f9 fix a crash when async connect failed (#302) (#309)
Motivation:

When an asynchronous connect failed we would crash because we didn't
correctly close the connection to start tearing everything down.
That correctly made the `SocketChannelLifecycleManager` trip.

This was filed as #302.

Modifications:

Correctly deregister and close the connection if an async connect fails.

Result:

Fewer crashes, fixes #302.
2018-04-12 14:21:12 +02:00
Norman Maurer b6681c0daf TailChannelHandler does not need to implement _ChannelOutboundHandler (#297)
Motivation:

TailChannelHandler does not implement any _ChannelOutboundHandler methods and so has no need to conform to it.

Modifications:

Not implement _ChannelOutboundHandler for TailChannelHandler

Result:

More correct code.
2018-04-10 16:07:53 +02:00
Norman Maurer 33facfe0dc Stop calling read(...) if we were not able to fill the whole buffer. (#296)
Motivation:

If we not filled the whole buffer with read(...) we should stop reading and wait until we get notified again. Otherwise chances are good that the next read(...) call will either read nothing or only a very small amount of data.
Also this will allow us to call fireChannelReadComplete() which may give the user the chance to flush out all pending writes.

Modifications:

Stop reading and wait for next wakup when we not fill the whole buffer.

Result:

Less wasted read calls and early chance of flushing out pending data.
2018-04-10 15:44:46 +02:00
Karim ElNaggar 39b9a3d60b Add EventLoopFuture reduction primitives (#240)
* Add EventLoopFuture reduce(initialResult:) function (#240)

Motivation:

Add a new function to allow us to work with multiple EventLoopFutures, that return values, by combining their results and wrapping it in a new
EventLoopFuture, using a specified reducer function.

Modifications:

- Add a new function
EventLoopFuture<T>.reduce<U>(initialResult:futures:eventLoop:nextPartialResult)
- Changed the implementation of andAll<Void> to use
EventLoopFuture<Void>.reduce(initialResult)
- Add a new function EventLoopFuture<T>.reduce<U>(into:)

Result:

Can reduce multiple EventLoopFutures without having to deal with
creating EventLoopFutures.

Simplified EventLoopFuture andAll<Void>

- An API which can be used to construct collections from future values in a linear time.
2018-04-09 17:42:35 +01:00
Johannes Weiß 1506a1901c make generic/closure ByteBuffer methods inlineable (#266)
Motivation:

Generics and closures across modules can be problematic as the cause
allocations. ByteBuffer is one of NIO's core data types and therefore
should be well optimised. Generic/closure taking methods so far were a
bit of a problem. And with
[SE-0193](https://github.com/apple/swift-evolution/blob/master/proposals/0193-cross-module-inlining-and-specialization.md)
accepted, there's not much reason to use those features even though they
are (at the moment) @_.

For the 1000 requests over 1 connection allocation benchmark we go from

    "total_allocations": 325378

to

    "total_allocations": 321366

so we lose 4 allocations per HTTP request/response pair, not super
impressive but not nothing either.

Modifications:

Make generic/closure taking methods on ByteBuffer `@_inlineable`

Result:

Fewer allocations
2018-04-09 15:11:01 +02:00
Johannes Weiß 748e08e62a fix issues found by TSan (#294)
Motivation:

NIO 1.3.1 was TSan clean but `master` regressed. In total I could see
two breakages both proudly presented by `SocketChannelLifecycleManager`.
Sorry :| :

1. accessing the `isActiveAtomic` from arbitrary threads:
   this was clearly a bug because `SocketChannelLifecycleManager` is
   usually held mutabe. So `isActiveAtomic` needs to be injected into
   `SocketChannelLifecycleManager` rather than contstructed there
2. accessing the `ChannelPipeline` through `SocketChannelLifecycleManager`:
   same problem as above really.

Modifications:

inject both the ChannelPipeline and the isActiveAtomic in the
appropriate places.

Result:

NIO much more correct, TSan happy
2018-04-09 12:05:54 +01:00
Cory Benfield e6b8da38b5 Make Scheduled's constructor public. (#290)
Motivation:

You need to be able to implement EventLoop.scheduleTask to implement
your own event loop. EventLoop.scheduleTask requires creating a
Scheduled. Currently, Scheduled has no public initializer.

Modifications:

Make Scheduled's initializer public.

Result:

It will be possible to actually implement EventLoop.
2018-04-06 17:38:21 +02:00
Karim ElNaggar d58fa23e56 Add EventLoopFuture fold function (#269)
Motivation:

Add primitive for folding futuristic values.

Modifications:

Add a new EventLoopFuture extension containing the implementation of
`fold<U>(futures:combiningFunction)`.

Result:

An API for foding futures.
2018-04-05 09:47:35 +01:00
Matt Eaton 164b007e0e Fixed minor typos and updated force unwraps. (#273)
Motivation:

I wanted to make sure that I fixed the minor typos and that I addressed
the feedback that was provided to me in regards to force unwrapping.
I also wanted to make sure my error messages were accurate.

Modifications:

Fixed a few minor typos and updated the force unwrap error messages.

Result:

Fixed typos and guard statements with accurate error messages.
2018-04-04 12:57:31 +01:00
Johannes Weiß 2af28a75b8 use @convention(c) for malloc/realloc/free in ByteBuffer (#267)
Motivation:

Adding @convention(c) is beneficial for performance of variables bound
to C functions so we should do that in ByteBuffer.

Modifications:

Adds @convention(c) to the malloc/realloc/free constants in ByteBuffer

Result:

Slightly better performance.
2018-04-03 21:00:01 +02:00
Matt Eaton 66e4fdfbba Fixed a few minor typos and some force unwraps (#259)
fix some typos, force unwraps and inconsistencies

Motivation:
Reviewing the code I found a few typos that hindered readability, some unnecessary force unwraps and inconsistencies in the codebase.

Modifications:

- The main file in NIOWebSocketServer now accepts command line arguments
and binds to a passed in host and port like the other server examples do.
- Minor typo fixes
- removed one force unwrap

Result:

- The result of my change will bring the NIOWebSocketServer more inline
with how the NIOHTTP1 and NIOChat servers examples are setup.
- less force unwrapping
- fewer typos

[message edited by @weissi]
2018-04-03 11:44:14 +01:00
Norman Maurer 2a684fc1dc Don't re-arm timerfd each epoll_wait (#264)
Motivation:

When calling Selector.whenReady(...) and using a SelectorStrategy.blockUntil(...) we may end up re-arm the timerfd each time even if the wakeup time did not change.
This is expensive and can be avoided in most situations.

Modifications:

Keep track of the earliest scheduled timer and only schedule a new one if it would fire sooner.

Result:

Less overhead when using epoll and timers.
2018-04-03 09:53:19 +01:00
Johannes Weiß 23744213e6 make Channel lifecycle statemachine explicit (#220)
Motivation:

We had a lot of problems with the Channel lifecycle statemachine as it
wasn't explicit, this fixes this. Additionally, it asserts a lot more.

Modifications:

- made Channel lifecycle statemachine explicit
- lots of asserts

Result:

- hopefully the state machine works better
- the asserts should guide our way to work on in corner cases as well
2018-03-29 19:50:07 +02:00
Johannes Weiß 224120c175 bring back the deprecated NIOPriorityQueue module (#250)
Motivation:

We moved the priority queue implementation into the main `NIO` module
for performance reasons. I initially thought we didn't expose it to
external packages but we did (thanks @lukasa).

Modifications:

Bring back the `NIOPriorityQueue` module but deprecate it.

Result:

Speed & backwards compatibility :)
2018-03-28 17:06:05 +01:00
Norman Maurer 34e64a0820 Simplify ChannelHandlerContext (#247)
Motivation:

We can simplify the init method of ChannelHandlerContext and replace one let by a computed property.

Modifications:

Remove some if let statements that we not need and use computed property.

Result:

Simpler code and need one less variable per ChannelHandlerContext.
2018-03-28 14:15:01 +02:00
Norman Maurer b1f948a115 Set hints for getaddrinfo to restrict results (#221)
Motivation:

We only use our GetaddrinfoResolver for SocketChannels (TCP stream channels), so we should set some hints for getaddrinfo.

Modifications:

Set proto and socktype hints.

Result:

More correct usage of getaddrinfo. Fixes https://github.com/apple/swift-nio/issues/201.
2018-03-28 10:49:05 +02:00
Johannes Weiß c9c3974276 bring PriorityQueue/Heap implementations inline (#245)
Motivation:

We triggered extra allocations for the generics on PriorityQueue/Heap.
They unfortunately can't be solved using `@_specialize` as the element
type is `ScheduledTask`.
Fortunately we never exposed those types externally so we can just
inline without breaking the public API.

Modifications:

Moved everything from the `NIOPriorityQueue` module into the `NIO`
module.

Result:

Less allocations, more happiness.
2018-03-27 19:04:33 +02:00
Norman Maurer f4036e2b0d Make use of lock.withLockVoid to simplify code (#242)
Motivation:

We should make use of lock.withLockVoid to simplify our code and make it more robust.

Modifications:

- Replace manual lock() / unlock() calls by withLockVoid(...)
- Mark lock.withLock* as @_inlineable to ensure we not get an allocation for the closure.

Result:

Code is cleaner and easier to understand.
2018-03-27 15:22:57 +01:00
Norman Maurer 5eb21324fc Update EmbeddedChannel state before notify connect and close promise. (#241)
Motivation:

We need to update isActive before notify the promises of connect and close to correctly refect Channel.isActive in callbacks.

Modifications:

- Correctly update isActive before notify promises.
- Add unit test.

Result:

Correct Channel state in callbacks.
2018-03-27 15:18:23 +02:00
Norman Maurer 94edbad2be Directly use the IOEvent to init a SelectorEvent when using KQueue (#238)
Motivation:

When using KQueue we directly can tell what IOEvent we want to use in SelectorEvent without and branching.

Modifications:

Add new init method to SelectorEvent that takes the IOEvent directly and use it when using KQueue

Result:

Less branching per event when using KQueue
2018-03-27 13:45:10 +02:00
Norman Maurer 774f298dca Remove unnecessary promise allocation in Selector.closeGently(...) (#237)
Motivation:

We can remove a promise allocation in Selector.closeGently if there are still Channels registered and also simplify the code a bit.

Modifications:

Remove creation of promise and just use eventLoop.new*Future(...) when needed.

Result:

Less allocations and cleaner code.
2018-03-26 19:50:20 +02:00
Cory Benfield 0a23199d7d Remove busywork left over from flush promises. (#234)
Motivation:

The Socket channels and PendingDatagramWritesManager had a bunch of
overhead left over from when they were handling flush promises. This was
only adding to code complexity and perf cost.

Modifications:

Removed the promise label in markPendingWritePoint.

Reworked the code to stop expecting write promises in
PendingDatagramWritesManager.

Result:

Smaller, faster code.
2018-03-26 17:07:56 +01:00
Norman Maurer cce02c9e40 Remove one pair of lock() / unlock() during EventLoop run. (#235)
Motivation:

We can remove one lock() / unlock() pair by saving the next ready task during loop execution.

Modifications:

Remvoe one lock() / unlock() pair.

Result:

Less locking during EventLoop run executions.
2018-03-26 16:42:39 +02:00
Norman Maurer 6cf8ca4398 Remove #available(OSX 10.12, *) check which is not needed anymore (#233)
Motivation:

At some point we needed to check for #available(OSX 10.12, *) which is not true anymore as we use our own Thread impl.

Modifications:

Remove #available(OSX 10.12, *) check

Result:

Remove incorrect and not needed check.
2018-03-26 14:23:14 +01:00
Norman Maurer c3fc78fe00 Take closeFuture into account when closing EventLoopGroup (#231)
Motiviation:

When the Selector is closed we also close the registered Channels and notify the future once all the close operations complete. The problem here is that while the close operation may be complete already there may still be events flowing through the ChannelPipeline. The only way to ensure this not happens anymore is to take the closeFuture into account of each Channel (as the closeFuture will only be notified once all is done for a Channel).

Modification:

- Also take the closeFuture into account per Channel
- Add test

Result:

Safer shutdown of EventLoopGroup.
2018-03-26 12:07:28 +01:00
Helge Heß be00f2ebb9 Typo: writte => written (#230)
Fixed typo
2018-03-24 12:58:36 +00:00
Tim a0b7f646fb Fixes build issue on 4.1 (#229)
Motivation:

Resolves #228

Modifications:

Remove type information in empty closure fixed build warning with compiler suggestion

Result:

No API changes, no issues building on 4.1!
2018-03-23 16:28:43 +00:00
Norman Maurer 1bcf85dd24 Correctly fail EventLoopFuture for unsupported operations on ServerSocketChannel (#226)
Motivation:

ServerSocketChannel should just fail the EventLoopFuture for unsupported operations and not crash.

Modifications:

- Correctly fail the EventLoopFuture for unsupported operations
- Add unit test.

Result:

No more crashes when users invoke unsupported operations.
2018-03-23 15:02:31 +00:00
Norman Maurer eb60e8978f Dissallow access and removal of Head and Tail ChannelHandlers (#225)
Motivation:

The Head and Tail ChannelHandlers should not be accessible as these are implementation details of the ChannelPipeline and removal of these will even make the whole ChannelPipeline not work anymore.

Modifications:

- Make it impossible to access / removal the Head and Tail ChannelHandlers
- Exclude the Head and Tail ChannelHandler from the debug String
- Add unit tests.

Result:

More robust ChannelPipeline.
2018-03-23 15:02:16 +01:00
Gopal Sharma 61f03a7a53 Annotate global constants that refer to C functions with @convention(c) (#223)
Motivation:

This fixes https://github.com/apple/swift-nio/issues/206.

Also see: https://bugs.swift.org/browse/SR-7242.

Modifications:

Annotated global constants that refer to C functions with @convention(c), and added explcit types.

Results:

https://bugs.swift.org/browse/SR-7242 is worked around.
2018-03-23 09:37:51 +00:00
Norman Maurer 91d7058a36 Not retry calling close(...) when EINTR is reported. (#217)
Motivation:

Usually we retry the syscall when EINTR is reported. This is not safe in the case of close(...) as the file descriptor may already be closed. The problem arise if this was the case and we retry it and the file descriptor is already reused again. In this case we would close a wrong file descriptor.

See:
  - https://bugs.chromium.org/p/chromium/issues/detail?id=269623
  - https://lwn.net/Articles/576478/

Modifications:

Ignore EINTR on close(...) and just assume the FD was closed.

Result:

Not possible to close the wrong file descriptor when close(...) reports EINTR.
2018-03-22 18:16:00 +01:00
Tibor Bödecs 1f83a1d5cb Changed EventLoop{Future,Promise}<()> occurances to EventLoop{Future,Promise}<Void> (#211) (#219)
Motivation:

Fix inconsistency of <Void> and <()> occurances in the codebase.

Modifications:

Changed EventLoop{Future,Promise}<()> occurances to EventLoop{Future,Promise}<Void>

Result:

Consistent code style for EventLoopPromise and EventLoopFuture.
2018-03-22 17:36:10 +01:00
Norman Maurer 536298389f Remove unsafe assert on Linux (#218)
Motivation:

b8055f7467 added some code to guard against the case when a fd is deregistered while processing ready events. On Linux it also added an assert which tried to verify that the fd in question is not registered anymore via epoll. The problem here is that it may also be closed which will have epoll_ctl fail with EBADF

Modifications:

Remove assert and add test-case which would have triggered the assert.

Result:

No more assertion error on linux.
2018-03-22 13:56:00 +00:00
Johannes Weiß f58e8318fb move BaseSocketChannel to its own file (#212)
Motivation:

{,Server,Datagram,Base}SocketChannel hold quite a bit of complexity and
also a many of lines of code. Yet they all shared the very same file
which isn't great.

Modifications:

- moved BaseSocketChannel into its own file
- made the methods that need overriding internal (from `fileprivate`)

Result:

SocketChannel.swift has a lot fewer lines of code.
2018-03-21 17:15:53 +00:00
Johannes Weiß 24fbb1ba1b channelActive needs to happen before channelRead (#204)
Motivation:

`readIfNeeded` was triggered straight after the channel was registered
but _before_ `channelActive` was called which is wrong.

Modifications:

Moved the calls to `readIfNeeded` into `becomeActive0` and removed them
everywhere else (except some error path).

Result:

handle ChannelHandler lifecycle more correctly.
2018-03-21 17:03:46 +00:00
Norman Maurer 3c8caab5b6 Add some docs to note on which message types a bootstrapped Channel will operate. (#207)
Motivation:

It's not clear to a user which inbound / outbound messages is expected for the different Channel implementations. This can result into wrong code and confused users.

Modifications:

Add some docs to explain which messages are supported / expected by the different Channels that can be bootstrapped.

Result:

More clear docs.
2018-03-21 15:44:32 +01:00
Norman Maurer b8055f7467 Guard against the case when a Selectable is deregistered during Selector.whenReady(...) processing. (#210)
Motivation:

It's possible someone deregistered a Selectable while Selector.whenReady(...) is processed and an even for the now deregistered Selectable is ready. In this case we crashed (due a force-unwrap) on linux.

Modifications:

- Skip the processing of the Selectable if deregistered (by replacing force-unwrap with an if let).
- Add unit test.

Result:

No more crashes caused by this on Linux
2018-03-21 15:32:15 +01:00
Tibor Bödecs 9a6f34fcc9 ChannelInvoker.newPromise should pass file and line to eventLoop.newPromise (#202) (#208)
Motivation:

Introduced some new parameters to fix #202

Modifications:

Created new parameters for the file and line newPromise method inside ChannelOutboundInvoker.

Result:

File and line numbers are now passed to the eventLoop object, all unit tests have been passed.
2018-03-21 11:15:12 +01:00
Norman Maurer 8bf013d7bd If connectSocket() completes directly we need to mark channel as active (#205)
Motivation:

If connectSocket() completes directly we failed to mark the Channel active by calling becomeActive0(...).

Modifications:

Correctly call becomeActive0(...)

Result:

Mark Channel active if connect succeed directly.
2018-03-21 10:12:24 +00:00
Johannes Weiß 88b91259f6 fix message for non-blocking connect errors (#203)
Motivation:

If a non-blocking connect failed, the error indicated that `getsockaddr`
failed which isn't true.

Modifications:

Adjusted the message.

Result:

Fewer lies.
2018-03-20 19:11:42 +01:00
Norman Maurer 17d5da5a2c Return failed EventLoopFuture when getOption(...) / setOption(...) is called on a closed Channel (#198)
Motivation:

We should return a failed EventLoopFuture when getOption(...) / setOption(...) is called on a closed Channel as otherwise it may not be safe to modify the Channel ioptions after its closed.

Modifications:

- Add guards that check if the Channel is still open and if not fail the operation.
- Add testcase

Result:

Calling getOption(...) / setOption(...) on a closed Channel fails.
2018-03-20 17:38:24 +01:00
Cory Benfield fef728cab0 HappyEyeballs should tolerate uncancellable tasks. (#191)
Motivation:

The HappyEyeballs state machine incorrectly assumed that it would always
be able to cancel any scheduled task that would execute on the event loop
that the state machine itself was running on. This is not accurate: if
the scheduled task is scheduled to execute at roughly the same time as
another callback into the state machine then it may be uncancellable.

Modifications:

Allowed the three scheduled tasks (connect timeout, connect delay, and
resolver delay) to fire in completed.

Result:

No fatalErrors in window conditions under high load
2018-03-21 01:14:47 +09:00
Cory Benfield 28014b0358 Better docs for threading guarantees of futures (#197) 2018-03-20 15:30:48 +01:00