Commit Graph
2140 Commits
Author SHA1 Message Date
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
Johannes Weiß 7e70bf5a87 rename HTTPHeaders.getCanonicalForm to subject and improve efficiency (#293)
Motivation:

HTTPHeaders had an unusual API for Swift: `getCanonicalForm(String)` which is
better suited as a subscript `[canonicalForm: String]`.
Also the implementation was needlessly inefficient.

Modifications:

- renamed HTTPHeaders.getCanonicalForm to HTTPHeaders[canonicalForm]
- improved efficiency by replacing anti-pattern
  Array.map { ...  }.reduce(+, []) by flatMap

Result:

more Swift in both meanings
2018-04-09 08:18:48 +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
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
Cory Benfield d6ade1424e Forbid HTTP protocols other than 1. (#283)
Motivation:

Our HTTP code handles only HTTP/1.X. There is no reason to support
HTTP/0.9, and we cannot safely handle a major protocol higher than 1 in
this code, so we should simply treat requests/responses claiming to be
of those protocols as errors.

Modifications:

HTTPDecoder now checks the major version is equal to 1 before it
continues with parsing. If it hits an error, that error will be propagated
out to the user.

Result:

Better resilience against bad HTTP messages.
2018-04-06 11:26:32 +01: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
Norman Maurer 82578be02f Just store NIOAny in the pending array. (#275)
Motivation:

We stored a closure in the pending array which is not really needed. We can just store the NIOAny directly without creating a closure first.

Modifications:

Replace closure with NIOAny

Result:

Less creation of closures.
2018-04-04 15:03:00 +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
Norman Maurer c2a31f7a02 Ensure fireChannelActive(...) is always called before fireChannelRead(...) (#195)
Motivation:

fireChannelActive(...) must always be called before fireChannelRead(...) which was not the cause all of the times as once ChannelOptions were applied to the accepted SocketChannel it was possible that read0() was called during this. This would then lead to an assert error as it tried to reregister on the Selector before we ever registered.

Modifications:

- Ensure we only try to reregister once we have registered to the Selector
- Only trigger read0() or pauseRead0() if the autoRead value actually changed
- Add unit test

Result:

Correct order of events and no crashes.
2018-03-20 21:44:45 +09:00
Cory Benfield a3fad287c3 Add docs to explain inbound/outbound (#142) 2018-03-19 19:38:24 +01:00
Norman Maurer 58a9651d90 Re-use same ContiguousArray for tasks copy operations. (#192)
Motivation:

We allocated a new ContiguousArray per each EventLoop run when tasks needed to be executed. We can just re-use the same instance all the time and so safe malloc operations (we will need to do memset tho).
Beside this we also did not reserve the needed capacity up fron which could lead to realloc operations.

Modifications:

- Reuse same ContiguousArray instance
- Correctly set the initial capacity

Result:

Less overhead when processing tasks via the EventLoop
2018-03-19 19:35:43 +01:00
Cory Benfield 28d4ddb33b Correctly expose backward-compat shim for header iterator. (#194)
Motivation:

header iterator that could be used to keep access to the iterator with
type erasure. However, it was accidentally made internal, and therefore
useless.

Modifications:

Made the shim public.

Result:

Users can actually upgrade their systems.
2018-03-19 23:53:20 +09:00
Bas Broek 1e7410aab8 Conform to the Swift bool naming guidelines
Motivation:

Changes the Boolean `fulfilled` to `isFulfilled` to make it more clear it is in fact a Boolean.

Also changes a `func isRecoverable()` to `var isRecoverable`.

Both of these were non-public, so this is no breaking change.

Modifications:

Renamed one Boolean and changed one function to a variable.

Result:

No use of unncessary (and potentially misinforming) functions, as well as adhering to the Swift boolean naming guidelines.
2018-03-19 14:55:53 +01:00
Bas Broek afa1037410 Prefer passing functions to flatMap
Motivation:

Passing in a function directly makes the code a bit more concise.

Modifications:

Changing `flatMap { Int($0) }` to `flatMap(Int.init)`.

Result:

More concise code.
2018-03-19 14:55:53 +01:00
Bas Broek ce4ccc519c Fix indentation 2018-03-19 14:55:53 +01:00
Bas Broek a095decbc2 Prefer if case over switch
Motivation:

There are quite a few `switch`es that cover just two cases. Explicitly state this via an `if case` + `else` structure.

Modifications:

Changes something like:

switch a {
case .b:
  return c
default:
  return d
}

to

if case .b = a {
  return c
} else {
  return d
}

Result:

This should prevent misinterpretation and thus potential bugs in the future.
2018-03-19 14:45:32 +01:00