Commit Graph
2945 Commits
Author SHA1 Message Date
Johannes Weiss 7445783b96 connect timeout tests: work around ECONNREFUSED (#653)
Motivation:

Some network configurations might disallow connecting to unknown IP
addresses. The effect of that is that we might see `ECONNREFUSED` when
trying to connect to 198.51.100.254 which nominally is reserved for
documentation only (ie. we shouldn't get any RSTs).

Modifications:

ignore `ECONNREFUSED` in the timeout tests too

Result:

tests stable in less permissive network environments
2018-11-13 16:34:44 +00:00
Johannes Weiss 08ab8b51cd remove ugly and unnecessary ignore result (_ = ...) (#652)
Motivation:

_ = expression() is ugly and in many cases unimportant. In fact we train
ourselves to overread it which makes special cases where you'd actually
expect a result to be used just look normal.

Modifications:

remove _ = from a lot of places. In many cases we already had a better
(and sometimes cheaper way) to not return a value but in some cases
(mostly `remove` functions) I added `@discardableResult`

Result:

NIO source code looks nicer
2018-11-13 14:49:08 +00:00
Cory Benfield a0b3b19cf4 Provide ChannelPipeline.remove methods with promises. (#651)
Motivation:

ChannelPipeline.remove0 contains a comment that indicates that users
were expected to be able to use the ChannelHandlerContext when both
handlerRemoved and the promise for channel removal call out.

This works when invoking remove() from outside the event loop, but if
a handler invokes remove on itself then it will only be able to attach
a callback to the future *after* the callout occurs. This means that a
ChannelHandler removing itself from the pipeline cannot rely on there
being a moment when it can still invoke the ChannelHandlerContext, but
when it is no longer a formal part of the pipeline.

This kind of behaviour is useful in some unusual cases, and it would
be nice to support it.

Modifications:

- Added remove() methods that accept promises as input.
- Rewrote the current remove() methods in terms of the new ones.
- Added tests.

Result:

ChannelHandlers can perform cleanup with a valid ChannelHandlerContext
but outside the Channel.
2018-11-07 11:50:51 +00:00
Johannes Weiss 035962e6b6 EventLoop.assertInEventLoop and preconditionInEventLoop (#644)
Motivation:

Dispatch can only precondition that code is run from a certain queue, it
can't return if code is running on a certain queue.
To support that this introduces new EventLoop.assertInEventLoop and
EventLoop.preconditionInEventLoop methods instead of
assert(eventLoop.inEventLoop).

Modifications:

add EventLoop.assertInEventLoop and EventLoop.preconditionInEventLoop

Result:

better support for Network.framework in NIOTS
1.11.0
2018-11-05 09:50:33 +00:00
Johannes Weiss 26bee21674 fix Swift 5 warnings (mostly redundant modifiers (#642)
Motivation:

Swift 5 complains on redundant modifiers. For example declaring a
`public func` inside of a `public extension` is now a warning. I don't
agree with this but I dislike warnings even more, so...

Modifications:

remove all redundant modifiers that the compiler now warns about such as

    swift-nio/Sources/NIOPriorityQueue/PriorityQueue.swift:90:5: warning: 'public' modifier is redundant for property declared in a public extension

Result:

no warnings in Swift 5
2018-11-01 09:50:55 +00:00
Johannes Weiss 054f65e473 add String blitting benchmarks (#641)
Motivation:

Writing Strings to ByteBuffers is important, let's have some more
benchmarks.

Modifications:

add String to ByteBuffer benchmarks

Result:

more benchmarks
2018-10-30 23:41:20 -07:00
Johannes Weiss ab69133269 ByteBuffer: small & medium sized string copies over 10% faster (#640)
Motivation:

urbp[start ..< end] is quite a bit faster than when done in two
operations urbp.dropFirst(start).prefix(length). This improves small (4
bytes) & medium sized (24 bytes) String copies by over 10%. Good for
HTTP headers etc.

Modifications:

replace urbp.dropFirst(start).prefix(length) by urbp[start ..< start +
length]

Result:

small & medium sized String copies faster
2018-10-30 21:01:19 +00:00
Johannes Weiss ee9a229a33 String decoding: go through URBP directly instead of Slice (#639)
Motivation:

String decoding can work faster when going through URBP directly instead
of a Slice of a URBP. The reason is that if the String has the utf8
represenation stored directly it'll just be a memcpy (+ validation).

Modifications:

go through URBP when decoding a String using String(decoding:as:)

Result:

faster if the String utf8 representation happens to be available
2018-10-30 08:20:21 +00:00
Norio Nomura 287d50c373 CONNECT method should not have request body (#637)
* CONNECT method has no request body

### Motivation:

[rfc7231](https://tools.ietf.org/html/rfc7231#section-4.3.6) said:
> A payload within a `CONNECT` request message has no defined semantics;
   sending a payload body on a `CONNECT` request might cause some existing
   implementations to reject the request.

### Modifications:

Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.no`.

### Result:

`HTTPRequestEncoder` does not generate chunked body for `CONNECT` method.

* Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.unlikely`
2018-10-29 22:54:52 -07:00
Johannes Weiss 6e6c68c1b2 verify that IOThreadPools get shut down (#635)
Motivation:

Not shutting down IOThreadPools leads to thread leaks so we should
verify they're actually shut down.

Modifications:

add a check that we're shutting down

Result:

fewer thread leaks
2018-10-29 09:51:31 -07:00
Johannes Weiss 176dd6e856 fix potential deadlock in BlockingIOThreadPool (#634)
Motivation:

BlockingIOThreadPool used to call out with a lock held and on top of
that on the wrong thread...

Modifications:

Make BlockingIOThreadPool call out on the supplied `queue`

Result:

fewer deadlock and surprises
1.10.0
2018-10-19 16:52:51 +01:00
Johannes Weiss 9bae007a15 use umbrella headers for C modules (#636)
Motivation:

SwiftPM only generates fully usable clang modules for C modules if they
have umbrella headers. Therefore, adding a generated NIO.xcodeproj to
another Xcode project as a sub-project never worked.
To make a header an umbrella header you need to name them _exactly_ like
the module.

Modifications:

give each C module an umbrella header

Result:

generated NIO Xcode projects can be used as sub-projects.
2018-10-19 14:49:43 +01:00
Johannes Weiss ed28803a78 update http_parser.c (#627)
Motivation:

There was an outstanding change in http_parser.c that we did not yet
have in our copy.

Modifications:

run the update http parser script and add changes as well as a test case
designed to hit the change.

Result:

ship the latest and greatest
2018-10-16 10:27:44 +01:00
Gopal Sharma 8d7d4cb9ca Fix minor typo (#626) 2018-09-30 08:19:08 +01:00
Cory Benfield 19b07156e5 Rest between runs of tests that join multicast groups. (#625)
Motivation:

On some machines we've seen tests that rapidly join and leave multicast groups
hitting spurious test failures. These test failures manifest as hitting ENOMEM on
setsockopt(IP_ADD_MEMBERSHIP). The reason appears to be that the IGMP join/leave
messages that the kernel needs to emit for these joins can be queued up waiting for
a timer to fire, and if we move sufficiently quickly we can push too many
messages into that queue.

This can be avoided by avoiding the need to emit the IGMP join/leave messages
at all. We can do that by forcing the multicast joins onto the loopback interface,
as there's no value in the kernel emitting join/leaves on the loopback. Given that
for these tests the join is necessary only to get the kernel to have IGMP state,
there's no reason not to do this.

Modifications:

Forced all multicast joins onto the loopback address.

Result:

No weird ENOMEM crashes in test runs.
2018-09-28 15:28:27 +02:00
Albert Aleksieiev a59293cbcd add Android support (#609)
### Motivation:

make swift-nio compatible with Android, and pass all test in Android.

### Modifications:

* add missed `ifaddrs` implementation
* add missed thread related functions - `CNIOLinux_pthread_getname_np`, `CNIOLinux_pthread_setaffinity_np` and `CNIOLinux_pthread_getaffinity_np`
* fix types incositency between Linux and Android, e.g. `Epoll.swift` class
* make bytes counter explicitely 64bits to avoid overflow on 32bit, in `PendingWritesManager.swift` and `PendingDatagramWritesState.swift`
* fix issue with Unix domain socket, first byte need to be zero in Android
* several incosistency fixes between Linux and Android api.

### Result:

now swift-nio works on Android. All tests passed!
2018-09-27 11:32:43 +01:00
Cory Benfield 81e97329f3 Work around SE-0213 (#623)
Motivation:

In Swift 5, types that conform to ExpressibleByIntegerLiteral will now
have their init(integerLiteral:) initializer invoked whenever the
compiler sees code of the form `Type(integerLiteral)`, rather than
before where the integer literal would be created as `Int` and then
an alternative initializer would be called. This broke our tests, so
we should fix it now that we're aware of it.

Modifications:

Force the type of the argument for the one broken test line, add new
test lines that execute this code path.

Result:

Better testing, fewer compile errors.
2018-09-25 12:21:56 +01:00
Cory Benfield c73eb57694 Support UDP multicast. (#618)
Motivation:

A large number of very useful protocols are implemented using multicast
with UDP. As a result, it would be helpful to add support for joining and
leaving IP multicast groups using SwiftNIO.

Modifications:

- Defines a MulticastChannel protocol for channels that support joining and
  leaving multicast groups.
- Adds an implementation of MulticastChannel to DatagramChannel.
- Adds a interfaceIndex property to NIONetworkInterface.
- Adds if_nametoindex to the Posix enum.
- Adds a isMulticast computed property to SocketAddress
- Adds a demo multicast chat application.
- Add a number of multicast-related socket options to SocketOptionProvider.

Result:

NIO users will be able to write channels that handle multicast UDP.
2018-09-24 10:24:09 +01:00
Johannes Weiss 79267e893b make the allocation limits for Swift 4.2 the main ones (#621)
Motivation:

We always care most about the latest released Swift version. Therefore I
added allocation limits for Swift 4.2 and indicated that the old ones
can be removed as soon as they change.

Modifications:

- added allocation limits for Swift 4.2
- added a comment to the old ones that they don't need to be changed
  anymore now

Result:

- best support for best version
- document that Swift 4.2 is awesome, lots fewer allocations!
2018-09-20 21:21:11 +01:00
Johannes Weiss 2e96e47016 explain some force tries/unwraps (#619)
Motivation:

It's generally good style to explain why something needs to be force
unwrapped/tried if not obvious.

Modifications:

Add explanations to a bunch of places.

Result:

Code easier to understand.
2018-09-19 15:51:03 +01:00
Johannes Weiss cb2367f391 CI: use Swift 4.2-RELEASE instead of CONVERGENCE (#616)
Motivation:

Now that 4.2 has been released, there's no reason to use the CONVERGENCE
version anymore.

Modifications:

use the RELEASE instead of the CONVERGENCE version of Swift 4.2

Result:

use the latest and greatest
2018-09-18 17:10:37 +01:00
Cory Benfield be4ea8ac74 Add SocketOptionChannel for wider socket options. (#589)
Motivation:

A small number of socket options have values that do not fit into a C
int type. Our current ChannelOption based approach for setting these
simply does not work, and cannot be extended to support the truly arbitrary
types that the setsockopt/getsockopt functions allow here.

This makes it impossible to use some socket options, which is hardly a
good place to be.

There were a number of ways we could have addressed this: we could have
special-cased all socket options with non-integer types in ChannelOption,
but I believe that would be too manual, and risk limiting users that need
to set other socket options. We could also have added a ChannelOption
that simply allows users to pass a buffer to write into or read from,
but that is a very un-Swift-like API that feels pretty gross to hold.

Ultimately, the nicest seemed to be a new protocol users could check
for, and that would provide APIs that let users hold the correct concrete
type. As with setsockopt/getsockopt, while this API is typed it is
not type-safe: ultimately, the struct we have here is treated just as a
buffer by setsockopt/getsockopt. We do not attempt to prevent users from
shooting themselves in the foot here.

This PR does not include an example use case in any server, as I will
provide such an example in a subsequent multicast PR.

Modifications:

- Added a SocketOptionChannel protocol.
- Conformed BaseSocketChannel to SocketOptionChannel.
- Wrote some tests for this.

Result:

Users can set and get sockopts with data that is larger than a C int.
2018-09-18 13:40:38 +02:00
Markus Jais c9e3c4d48c Added some unit tests to MarkedCircularBuffer (#607)
Motivation:

MarkedCircularBuffer was missing unit tests for some methods and
public attributes

Modifications:

Added several unit tests

Result:

Now MarkedCircularBuffer has better test coverage
2018-09-14 15:38:41 +02:00
Norman Maurer a0c6cffc88 Correct propagate channelActive events to the next handler when using… (#615)
* Correct propagate channelActive events to the next handler when using IdleStateHandler.

Motivation:

We missed to propagate the channelActive event to the next handler in IdleStateHandler, which means handlers placed after it in the pipeline will never receive such an event.

Modifications:

- Correctly call ctx.fireChannelActive()
- Add unit test to assert we forward all inbound events.

Result:

Fixes https://github.com/apple/swift-nio/issues/614.
2018-09-13 09:09:15 +02:00
Johannes Weiss 59ad713348 document the prerequisites (#613)
Motivation:

We should document the system requirements.

Modifications:

Add list of prerequisites to readme.

Result:

Easier to get started for users.
2018-09-12 11:47:21 +01:00
Johannes Weiss 463f8d95d2 EventLoopPromise didn't point out it has reference semantics (#612)
Motivation:

Sometimes people assume that all `struct`s have value semantics but
that's not true. We should still point that out.

Modifications:

point out that EventLoopPromise has reference semantics

Result:

clearer docs
2018-09-11 15:16:06 +01: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
Cory Benfield 19444825fa Actually report errors when hitting blacklisted errnos. (#610)
Motivation:

It's not all that useful to print the value of the pointer from sterror.
Instead we should aim to print the string. While we're here, let's avoid
repeating too much code.

Modifications:

- Centralised the handling of blacklisted errnos.
- Correctly printed the error string when a blacklisted errno is hit.
- Updated the output of the assertion to include the function failing.

Result:

Better diagnostics when blacklisted errnos are hit.
2018-09-10 10:58:50 +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 713b7e36e3 fix warning in a test (#605)
Motivation:

nobody likes warnings, even in tests

Modifications:

fixed a test warning

Result:

no more warnings (apart from the deprecation ones)
2018-09-03 18:12:54 +02:00
Norman Maurer 6fa273a6f3 Cleanup of bf8c642896 2018-08-30 20:48:15 +02:00
Norman Maurer bf8c642896 Include ipaddress in SocketAddress.description. (#601)
Motivation:

WE should include the ipaddress in the description of SocketAddress if any way used as there may be no host at all.

Modifications:

- Always include ipaddress if possible.
- Add unit tests.

Result:

More useful description of the SocketAddress
2018-08-30 20:46:08 +02:00
Johannes Weiss 501af860f5 allow two distinct ChannelOptions of one type (#597)
Motivation:

Quite embarrasingly, we previously would only store one `ChannelOption`
per `ChannelOption` type. Most channel option types are distinct and
that's probably why it took so long to find this issue. Thanks
@pushkarnk for reporting. Unfortunately though, the most important
`ChannelOption` is `.socket` which crucially also holds a level and a
name. That means if you set two `ChannelOptions.socket` options with
distinct name/level, one would still override the other.

Example:

    .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEPORT), value: 1)
    .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)

would only actually set the latter.

Modifications:

- made all common `ChannelOption` types equatable (for 2.0 this will
  be a protocol requirement)
- deprecated non-Equatable `ChannelOption` types
- zero out buffer before calling getsockopt as Linux doesn't do that

Result:

you can now set two distinct `ChannelOptions` for one type
2018-08-29 15:24:58 +01:00
Johannes Weiss df764fedf0 don't crash when Channel goes inactive in read triggered by write error (#594)
Motivation:

Previously we asserted that a Channel cannot go inactive after calling
out for a read that was triggered by (draining the receive buffer after)
a write error.

This assertion was put in place to guard against `readComplete` events
sent on inactive channels. It did that job just fine but crashes aren't
great so we now conditionally fire the `readComplete` event if the
Channel stays active.

Modifications:

make the readComplete event firing conditional

Result:

fewer crashes, more happy faces
2018-08-27 11:49:58 +01:00
Johannes Weiss ce0c6d92e9 pipeline handler: fix error state tracking (#595)
Motivation:

@pushkarnk hit an interesting edge case that we previously mishandled
and crashed. All these conditions need to be true

1. Whilst have an ongoing request (ie. outstanding response), ...
2. ... a `HTTPParserError` arrives (which we correctly queue)
3. Later the outstanding response is completed and then ...
4. ... the `HTTPServerProtocolErrorHandler` sends a .badRequest response

We previously crashed. The reason we crashed is that the
`HTTPServerPipelineHandler` obviously tracks state and then asserts that
no response is sent for a wrong request. It does have an affordance to
allow a .badRequest response for a request it couldn't parse. However
this state tracking wasn't done if the error itself was enqueued for
later delivery.

Thanks very much @pushkarnk for the report!

Modifications:

instead of delivering the error directly use the `deliverOneError`
function which transitions the state correctly.

Result:

fewer crashes & hopefully happy Pushkar
2018-08-27 11:09:51 +01:00
Johannes Weiss 8ecced9e24 warn that ChannelHandlers should be instantiated within initializer closures (#590)
Motivation:

For (stateful) ChannelHandlers it's very important that the
ChannelHandlers get instantiated _within_ the bootstrap's initializer
closures (and not before that).

Modifications:

Add warnings about the fact that they should be instantiated within the
closures.

Result:

- better docs
- more correct user code
2018-08-24 09:04:44 +02:00
Johannes Weiss 927034f7de mark more Collections as ContiguousCollections (#586)
Motivation:

All the mutable variants and also some slices of clearly contiguous
collections weren't marked as ContiguousCollections but they should be.

Modifications:

- made UnsafeMutable[Raw]BufferPointer a ContiguousCollection
- made Slice<UnsafeRawBufferPointer> a ContiguousCollection

Result:

faster code
2018-08-23 17:18:51 +01:00
Rukshani Athapathu 5011c409bb Fix readme erroneous statement regarding channel pipeline (#592) 2018-08-23 16:07:32 +01:00
Johannes Weiss aaf434022f fix limits on 32-bit systems to values that work (#580)
Motivation:

We should have different constants for 32-bit systems where necessary
for example all the maximums should be Int32.max and not UInt32.max
because UInt32.max doesn't fit into an Int on 32-bit platforms. But
where unnecessary 32-bit and 64-bit should share maximum values.

Modifications:

- removed some constraints that should be unnecessary
- skip tests that can't work on 32-bit systems

Result:

better and more consistent 32-bit runs
2018-08-23 10:38:47 +01:00
Johannes Weiss 7de224eaf3 better documentation for MultiThreadedEventLoopGroup (#582)
Motivation:

MultiThreadedEventLoopGroup's docs didn't make it clear that you leak
threads if not shut down.

Modifications:

Add clarification that you should shut down
MultiThreadedEventLoopGroups.

Result:

hopefully clearer documentation.
2018-08-21 11:43:42 +01:00
Matt Eaton 7895bc88fd Enhanced the output of the NIOEchoClient Example (#585)
Motivation:

I was testing the NIOEchoClient example on Linux and noticed that I received no character output.
I thought this would be handy and added this code to do so.

Modifications:

Small modification to the channelRead method in NIOEchoClient to read the bytes and transform to a string.

Result:

The display of the characters on your echo client before the channel closes.
2018-08-20 11:45:16 +01:00
Cotton Hou ee52d7694a Typo in EchoServer example (#583) 2018-08-18 18:44:32 +01: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
Helge Heß e8c04e0eca Make tests work on 32-bit (#486)
* 32-bit fix for tests: Replace 0xDEADBEEF w/ 0x1337BEEF

Motivation:

Make tests compile on Raspberry Pi.

Modifications:

- Change tests so that they compile on 32-bit machines,
like Raspi. Replaced 0xDEADBEEF which doesn't fit into
an Int32, w/ 0x1337BEEF.
- make ByteBuffer work better on 32-bit
- fix other wrong assertions and limits that are too big on 32bit

Also use TimeAmount.Value in one test.

Result:

Tests will compile on Raspi ...
2018-08-16 18:05:11 +01:00
Johannes Weiss 0ce3cf5b79 if an EventLoopFuture.wait() blows up, tell users where (#578)
Motivation:

If the deadlock detection in EventLoopFuture.wait() blows up we should
tell users the file/line where they called it from not where our
preconditon is.

Modifications:

- add a file/line parameter with default value obvs

Result:

better diagnostics
2018-08-16 16:42:26 +01:00
Johannes Weiss a9072729bb output a hint if we get a reset connection w/o error set (#573)
Motivation:

We have one case in the code where we expect a socket error to be set
when we hit a connection that got the `.reset` event. On Linux that's
expected and therefore we just map this to `ECONNRESET`.
On other platforms however that is unexpected. Now I just found an
[Envoy commit](https://github.com/envoyproxy/envoy/commit/62f8e51bdd2d72cbac739087dabd3f51bdfc5cbd#diff-3315c7b2    91f78a482ebd4cbfc0545362R345)
which suggests this might not work on FreeBSD. This should prompt our
users to let us know if we ever see this error on non-Linux systems.

Modifications:

Add a message that makes it clear this is unexpected and link our
ticket.

Result:

we should learn if this actually happens on macOS.
2018-08-16 15:13:02 +01:00
Johannes Weiss 4117f4efae better wait on EventLoop detection (#553)
Motivation:

It's important that in NIO programs you don't call
EventLoopFuture.wait() on an EventLoop. We previously had some detection
built in but we can do better.

Modifications:

Detect wait() called on any of MultiThreadedEventLoopGroup's EventLoops.

Result:

Quicker and more deterministic detection if wait() abuse.
2018-08-16 10:44:32 +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 d7b5bf6e15 make ByteBuffer._Storage.fullSlice a computed property (#560)
Motivation:

ByteBuffer._Storage.fullSlice can always be trivially computed, so it
should be.

Modifications:

make ByteBuffer._Storage.fullSlice computed

Result:

saved almost 56 bits per ByteBuffer
2018-08-16 09:50:48 +01:00
Johannes Weiss d32d5c6a50 add forgotten selfs (#574)
Motivation:

Swift code that doesn't use explicit `self.` is hard to read, even
harder to search for and quite bug prone. During my analysis I found
quite a number of them, this fixes the ones I came across.

Modifications:

Add a bunch of missing explicit `self.`s

Result:

code easier to read and less bug prone
2018-08-16 09:28:24 +01:00