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
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
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.
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
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
Motivation:
Writing Strings to ByteBuffers is important, let's have some more
benchmarks.
Modifications:
add String to ByteBuffer benchmarks
Result:
more benchmarks
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
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
* 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`
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
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
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.
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
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.
### 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!
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.
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.
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!
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.
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
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.
Motivation:
MarkedCircularBuffer was missing unit tests for some methods and
public attributes
Modifications:
Added several unit tests
Result:
Now MarkedCircularBuffer has better test coverage
* 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.
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
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
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.
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
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
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
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
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
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
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
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
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.
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.
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
* 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 ...
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
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.
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.
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
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
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