Commit Graph
2945 Commits
Author SHA1 Message Date
Johannes Weiss 8c6c83c05d NIOThreadPool: backed by NIOThreads (pthreads) instead of DispatchQueues (#1100)
Motivation:

NIOThreadPool was grossly abusing Dispatch to block a large number of
threads for (usually) blocking IO work.

Modifications:

Back the NIOThreadPool by NIOThreads (pthreads) instead of
DispatchQueues.

Result:

Less abuse.
2019-08-09 15:20:53 +01:00
Will Lisac 26586835fd Fail promise in MessageToByteHandler write error cases (#1096)
* Fail promise in MessageToByteHandler write error cases

* Add test case for MessageToByteHandler failing write promises
2.6.1
2019-08-08 10:33:00 +01:00
Johannes Weiss b564a726a9 really no double handlerRemoved calls (#1094)
Motivation:

In #1091 we fixed the most common case of handlerRemoved being called
multiple times. There was still another (less likely) problem left which
is if a manual removal is triggered from _within_ the handlerRemoved
call from a pipeline teardown, then we would still call handlerRemoved
another time.

Modifications:

Properly guard against handlerRemoved being called twice.

Result:

Fewer bugs.
2019-08-06 18:10:53 +01:00
Johannes Weiss f98ed180e5 HTTPDecoder: don't deliver unsolicited responses (#1093)
Motivation:

Despite the fact that we already stopped delivering unsolicited
responses for the HTTP response decoder, there was a window where we
would deliver a second .head for a response that come without a request.

Modifications:

Don't deliver a second .head even if send together with a first, legit
response.

Result:

Being a HTTP client using NIO is now easier.
2019-08-06 17:39:38 +01:00
Cory Benfield 5d54458488 Deliver HTTPServerUpgradeHandler data on removal. (#1092)
Motivation:

There is currently a pair of windows in which it is possible for the
HTTPServerUpgradeHandler to buffer some data without replaying it. This
can happen if it is reentrantly called just after it finishes
unbuffering data, which is not great.

To avoid this, we move to execute this data delivery while we're
removing ourselves. This ensures that we are confident that we cannot be
reentrantly called after our last outcall, meaning we can be confident
of 100% data delivery.

Modifications:

- Moved delayed data delivery to removeHandler.

Result:

Less chance of quiet data loss
2019-08-05 16:07:19 +01:00
Johannes WeissandCory Benfield b07efecaea fix double remove of handlers (#1091)
* fix double remove of handlers

Motivation:

Previously, it was possible that a handler was removed twice: Once by
Channel teardown and another time by a user-trigger removal that wasn't
instantaneous. This racy situation can happen in the real world. NIO
behaved wrongly in two ways:

1. we would call `handlerRemoved` twiced
2. ByteToMessageHandler would fail an assertion about the current
   removal state

Modifications:

- Only call `handlerRemoved` when the handler actually gets removed.
- Fix the assertion.

Result:

fewer bugs

* Update Sources/NIO/ChannelPipeline.swift

Co-Authored-By: Cory Benfield <lukasa@apple.com>
2.6.0
2019-07-31 16:18:15 +01:00
Konrad `ktoso` Malawski 0225a2bf22 nil out writeRecorder, same as all other fields in teardown (#1090)
Motivation:

Without niling out it may linger around once the last test has
completed, and keep some messages in memory which will not be inspected
anymore

Modifications:

nil out the writeRecorder same as all other fields are currently nilled
out

Result:

In case XCTest keeps the class around, not keeping around the messages
stored by the writeRecorder
2019-07-31 09:34:06 +01:00
Dario Rexin 5cd9a7faa8 Add comments to the handling in MultiThreadedEventLoopGroup.shutdownGracefully (#1089) 2019-07-30 17:52:42 +01:00
Dario Rexin 0dc794498f Fix hanging thread when shutting down an already closed EventLoopGroup (#1085)
* Fix hanging thread when shutting down an already closed EventLoopGroup

* Generate Linux tests

* Remove accidental shutdownLock.unlock

* Move dispatching of callbacks out of lock

* Use Lock.withLock instead of manual lock/unlock

* Remove superfluous lock.unlock
2019-07-30 17:18:10 +01:00
Liam Flynn 4fa0921e61 Update the README file to include some recently added examples. (#1087)
Motivation:

To give visibility to recently added examples.
To satisfy issue #465

Modifications:

Added links to examples in readme.
Slightly re-arranged the order so that echo examples are next to each other in the list.

Result:

You can now see the UDP, HTTP and WebSocket client examples from the README file.
2019-07-30 11:31:13 +01:00
Cory Benfield 2b1d7be0bc Tolerate unsolicited HTTP responses. (#1084)
Motivation:

Right now NIO clients will crash in the (admittedly unlikely) event that
a HTTP server sends an unsolicited extra response on a connection. This
seems pretty unnecessary, and fairly graceless.

Modifications:

- Replace a forcible pop with an optional one.
- Added NIOHTTPDecoderError type.

Result:

Removed a crash that we definitely don't want.
2019-07-30 10:53:14 +01:00
Johannes Weiss 4cef48e760 DEVELOPMENT-SNAPSHOT-2019-07-25-a (#1086)
* DEVELOPMENT-SNAPSHOT-2019-07-28-a

* Update docker-compose.1604.51.yaml
2019-07-30 09:22:46 +01:00
Liam Flynn fa2a1fd168 Add a WebSocket Client example. As Per issue #465 (#1064)
Motivation:

To provide an example of the usage of the WebSocket client upgrade functionality.
To satisfy issue #465

Modifications:

Added a ‘WebSocketClient’ example with a readme and a target in the package file.

Result:

There is now a WebSocket client example to assist with the creation of a WebSocket client.
2019-07-26 15:42:05 +01:00
Johannes Weiss 96d9e44b26 ByteBuffer: viewBytes should handle negative values (#1082)
Motivation:

All ByteBuffer API that is used to parse potentially untrusted data
should be resilient against negative indices, offsets, and lenghts.
Unfortunately, ByteBuffer.viewBytes(at:length:) was not.

Modifications:

Make ByteBuffer.viewBytes(at:length:) resilient against negative values.

Result:

Fewer crashes.
2019-07-25 15:24:33 +01:00
Cory Benfield 6a79d4687e Make pipeline handler behave better when removed (#1080)
Motivation:

The HTTPServerPipelineHandler is removed from pipelines in many cases,
but the most common case is over upgrade. While the handler is
removable, it doesn't make any effort to ensure that it leaves the
pipeline in a sensible state, which is pretty awkward.

In particular, there are 3 things the pipeline handler may be holding
on to that can lead to damage. The first is pipelined requests: if there
are any, they should be delivered, as the user may be deliberately
allowing pipelining.

The second thing is read() calls. The HTTPServerPipelineHandler exerts
backpressure on clients that aggressively pipeline by refusing to read
from the socket. If that happens, and then the handler is removed from
the channel, it will "forget" to restart reading from the socket on the
way out. That leaves the channel quietly in a state where no reads will
occur ever again, which is pretty uncool.

The third thing is quiescing. The HTTPServerPipelineHandler catches
quiescing events and allows them to deliver a response before closing a
connection. If that has happened when the pipeline handler is removed,
it should fall back to the behaviour as though it were not there.

Modifications:

- Added a handlerRemoved implementation to play event state that should
    be replayed.
- Added a channelInactive implementation to drop data.

Result:

More graceful handler removal.
2.5.1
2019-07-23 20:10:26 +01:00
Johannes Weiss d9dc73592b 5.1-DEVELOPMENT-SNAPSHOT-2019-07-19-a (#1079) 2.5.0 2019-07-20 19:50:51 +01:00
Cory Benfield da23f751ee Deprecate and replace ByteBuffer.set(buffer:at:) (#1078)
Motivation:

In NIO2 we tried to adopt the Swift convention of avoiding functions
that differ only by the word of their first label where that label is
describing their type. Sadly, we missed one.

Modifications:

- Wrote setBuffer(_:at:)
- Deprecated set(buffer:at:) in favour of the new function.

Result:

Users will get some deprecation warnings I guess.
2019-07-19 17:31:41 +01:00
Johannes Weiss 22822a949c fix subtracting NIODeadlines (#1074)
Motivation:

Subtracting deadlines should just work, no matter if the result is
positive or negative.

Modifications:

Don't crash on earlierDeadline - laterDeadline.

Result:

- fewer crashes
- fixes https://github.com/swift-server/async-http-client/issues/71
2019-07-19 16:50:10 +01:00
Johannes Weiss 774807763e NonBlockingFileIO: add multi write test (#1077)
Motivation:

The behaviour of multiple writes followed by each other is important so
we should have a unit test for that.

Modifications:

Add a unit test that shows that we just write to where ever the seek
pointer is.

Result:

More test coverage.
2019-07-17 19:33:47 +01:00
Johannes Weiss ca69149d5f api breakage tester: fetch all refs (#1076)
Motivation:

To be able to use SHA sums as git versions, we need to pull all the refs
to we get even the commit SHAs from PRs. That's important so CI can use
this script.

Modifications:

Fetch `+refs/pull/*:refs/remotes/origin/pr/*` refs.

Result:

Should be able to be usable in CI across forks.
2019-07-17 18:23:45 +01:00
Johannes Weiss fb03f947a5 ELF: On reduce, hop to target EventLoop before doing operation (#1070)
Motivation:

Folds often involves chaining multiple futures together. It's
beneficial if you're already on the target EventLoop as it might
vastly reduce the amount of EventLoop hops.

Modifications:

Execute onto the target EventLoop before doing the folds.

Result:

Fixes #1054
2019-07-17 13:54:25 +01:00
Johannes Weiss 6b20fa5ce8 add two ELF.reduce benchmarks (#1069)
Motivation:

As #1054 shows, we have some low-hanging performance fruit regarding
off-EventLoop future reduces. We should quantify those.

Modifications:

Add benchmarks to quantify the potential wins.

Result:

More benchmarks.
2019-07-17 12:13:40 +01:00
tomer doron eeac3d51d9 add swift-api-digester docker setup (#1067)
motivation: prepare to run swift-api-digester in ci

changes:
* add jq to docker setup
* remove redundant ruby setting from docker file
2019-07-16 17:48:40 -07:00
Johannes Weiss 5f8d3f0b40 workaround SR-11143 for api-digester: pass -sdk / on Linux (#1068)
Motivation:

swift-api-digester requires to be passed `-sdk /` on Linux.

Modifications:

Pass `-sdk /` on Linux and the SDK directory on Darwin.

Result:

check_no_api_breakages works on Linux.
2019-07-16 12:40:51 +01:00
Johannes Weiss 5f0a703818 make illegal SelectableEventLoop.shutdown impossible (#1055)
Motivation:

It's illegal to shut down a SelectableEventLoop because the only valid
owner is a MultiThreadedEventLoopGroup which never uses
shutdownGracefully on its EventLoops.

Modifications:

Fail shutdown attempts instead of running some random, untested code.

Result:

Fail illegal calls rather than running some dangerous code which will
lead to deadlocks further down the line.
2019-07-12 08:42:46 +01:00
Johannes Weiss c71df779ba 5.1 DEVELOPMENT-SNAPSHOT-2019-07-09-a (#1062) 2019-07-11 21:25:37 +01:00
Johannes Weiss 334815f658 HTTPDecoder: no error on unclean EOF on upgrade (#1063)
Motivation:

Previously we thought that if we have some bytes left that belong to an
upgraded protocol, we should deliver those as an error. This is
implemented on `master` but not in any released NIO version.
However, no other handler sends errors on unclean shutdown, so it feels
wrong to do it in this one very specific case (EOF on inflight upgrade
with data for the upgraded protocol)

Modifications:

Remove the error again.

Result:

Less behaviour change to the last released NIO version.
2.4.0
2019-07-11 17:29:03 +01:00
Johannes Weiss 7a250a225e HTTPDecoder: Don't invoke left overs strategy on EOF (#1061)
Motivation:

Do as we documented and invoke the leftovers strategy only when the
handler is removed.

Modifications:

Don't invoke leftovers on EOF (which isn't something the user can
control).

Result:

- Fewer crashes
- should fix https://github.com/IBM-Swift/Kitura-WebSocket-NIO/issues/35
2019-07-10 12:58:28 -04:00
Konrad `ktoso` Malawski ed3bca3131 check breakages: fail loudly when unable to checkout tag (#1060)
One line description of your change

Motivation:

When using the script ad hoc to verify something you may have forgotten to pull all tags,
the script then fails mysteriously in silence and no output. Detective work can then lead the script mysteriously stopping after a checkout:

```
+ cd /tmp/.check-api_1Q1rvO/repo
+ git checkout 1.1.0
$ ...
```

which reminds you to perform a fetch; it would be nicer if it told us about the issue explicitly though.

Modifications:

Don't silence `git checkout` all error output, though use quiet mode so no progress is printed.

Result:

Script fails nicer and reminds you to perform a git fetch if you forgot to do so.

e.g.

```
[5/5] Merging module Metrics
error: pathspec '1.1.0' did not match any file(s) known to git
```
2019-07-09 15:51:40 +01:00
Liam Flynn 64c673b6e8 Add a WebSocket client upgrader. (#1038)
Motivation:

There is a client protocol upgrader but, unlike the server protocol upgrader, it does not have a WebSocket protocol as part of the project.

Modifications:

Made the magic WebSocket GUID public to the WebSockets project.
Added a NIOWebSocketClientUpgrader.
Added tests for the upgrader.
Updated the Linux test script files.

Result:

The project now has a WebSocket client upgrader to match the WebSocket server upgrader.
2019-07-08 03:55:02 -04:00
George Barnett 07e7e01c76 Check jq is available before checking API breakages (#1058)
* Check jq is available before checking API breakages

Motivation:

If jq wasn't installed the API breakage script would erronesouly say
that there were no breaking API changes. That's pretty bad.

Modifications:

Check jq is available before running the check. Updated the usage
message to specify that a Swift 5.1+ toolchain is required.

Result:

More correctness.
2019-07-04 18:47:21 +01:00
Konrad `ktoso` Malawski c49d5e7a5e EventLoopPromise.completeWith(Future), mirroring ELF.cascade(to:) #1052 (#1053)
Motivation:

EventLoopFuture and EventLoopPromise are symmetric APIs and for easier
discoverability of being able to complete a promise with a future it
is helpful to have a mirror of future.cascade put onto promise.

Modifications:

- Adds ELP.completeWith(ELF)

Result:

It is now possible to complete a promise with a future,
and not only cascade a future to a promise.
2019-06-28 12:23:12 +01:00
Julian Lettner 803d36b7f3 Tiny test code cleanup (#1051) 2019-06-27 07:49:46 +01:00
Johannes Weiss 069fcde4c5 docs: add forgotten modules (#1050)
Motivation:

Embarrassingly, we forgot a bunch of modules in the documentation.

Modifications:

Add the forgotten modules.

Result:

Better docs.
2019-06-23 16:33:47 +01:00
Johannes Weiss 7f20464df3 enable TCP_NODELAY by default (#1020)
Motivation:

Networking software like SwiftNIO that always has explicit flushes
usually does not benefit from having TCP_NODELAY switched off. The
benefits of having it turned on are usually quite substantial and yet we
forced our users for the longest time to enable it manually.

Quite a bit of engineering time has been lost finding performance
problems and it turns out switching TCP_NODELAY on solves them
magically.

Netty has made the switch to TCP_NODELAY on by default, SwiftNIO should
follow.

Modifications:

Enable TCP_NODELAY by default.

Result:

If the user forgot to enable TCP_NODELAY, their software should now be
faster.
2.3.0
2019-06-19 18:04:01 +01:00
Johannes Weiss 1549cd7e87 ByteBuffer.get/readData: Heuristic when to copy/not copy (#1046)
Motivation:

Previously, ByteBuffer tried to never copy the bytes when transferring
to a `Data`. For small copies that's definitely not a good choice
because it means an extra allocation.

Modifications:

- introduce `ByteTransferStrategy` so the user can choose
- make a heuristic: copy is less than 256kB, try not to copy above

Result:

More sensible defaults.
2019-06-19 17:46:25 +01:00
Cory Benfield 22a368730c Return accidentally removed API. (#1045)
Motivation:

We accidentally removed NIOFileHandle(path:) when we added some
arguments with default values to it. This doesn't normally break source,
but in some weird edge cases it can, and it's bad form to remove it.

Modifications:

- Replace the missing function

Result:

Fewer highly unlikely source breakages.
2019-06-19 17:15:21 +01:00
Johannes Weiss 448a0ba8c8 analyze_performance_results: switch to "min" instead of "mean" (#1044)
Motivation:

Mean is not a great aggregation function because it's not resilient
against outliers at all, so let's switch to min.

Modifications:

Switch 'mean' to 'min' for aggregation.

Result:

Aggregation function that's more resilient against outliers.
2019-06-19 16:10:43 +01:00
Johannes Weiss bc816050cc don't close server socket if fcntl(O_NONBLOCK) throws EINVAL (#1041)
Motivation:

Darwin does sometimes hand us back an (as of the docs) illegal error
code of EINVAL. So far, NIO has done the non-sensical thing of closing
the server socket as a result.

Modifications:

Just close the accepted socket, leave the server socket open, and fire
the error through the pipeline.

Result:

- fixes #1030
- better behaviour
2019-06-19 15:42:18 +01:00
Liam Flynn 856fe3be1a Updated the embedded channel tests to write to the input and output multiple times. (#1033)
Motivation:

The current test check that the buffer can be written to and then that it is cleared.
They do not check that once the buffer is cleared, it can be written to again.

Modifications:

Added a test for both the inbound and outbound buffer to check multiple writes to each buffer.

Result:

We can not be sure that multiple writes to either the inbound or outbound buffers on the embedded channel works.Updated the embedded channel tests to write to the input and output buffers multiple times.
2019-06-19 15:20:28 +01:00
Johannes Weiss 39e60dd694 5.1-DEVELOPMENT-SNAPSHOT-2019-06-17-a (#1043) 2019-06-19 08:43:05 +01:00
Johannes Weiss 7829542cc5 remove platform availability again (#1042)
Motivation:

The platform availability that we recently introduced caused problems
because it would require all downstream projects to define the same or
narrower platform availability to still compile with NIO which would
make this very disrupting and also SemVer major.

Modifications:

Remove the platform availability declarations.

Result:

No SemVer breakages.
2019-06-18 20:21:12 +01:00
Johannes Weiss 3e7198f52c when making a socket non-blocking, get & OR flags (#1040)
Motivation:

Previously, we would just `F_SETFL, O_NONBLOCK` which would erase all
possibly pre-existing flags which isn't great.

Modifications:

First get the existing flags and then do `F_SETFL, existingFlags |
O_NONBLOCK`.

Result:

Possibly helps with #1030, definitely better style.
2019-06-18 15:37:38 +01:00
Liam Flynn 5f1432db38 Add self where required WebSocket server tests. (#1034)
Motivation:

To ensure the swift-NIO style for self is followed within the WebSocket tests.
Modifications:

Altered the style within the WebSocketServerEndToEnd tests.
Result:

Slightly more readable code.
2019-06-18 11:25:51 +01:00
Johannes Weiss bf2598d193 iOS & simulator compatibility (#1037)
Motivation:

We should have better iOS compatibility.

Modifications:

- make all OS-conditional imports the same
- don't check TSI_S_ESTABLISHED (which is unavailable on iOS)
- update availability to reflect the OS versions we actually support
- make sure temporary UDS paths aren't too long

Result:

better iOS compatibility
2019-06-18 10:38:39 +01:00
Liam Flynn 57785e6d9c An HTTP upgrader class for a client pipeline. (#1001)
* Reorder ‘channel active’ calls to the same order as `_ChannelInboundHandler` and their likely chronological order.

Motivation:
When first viewing the example classes, coming to the ‘read’ method first, leaves the subject unclear as to what the method is ‘reading’.
It is preferable to view something being sent first, and then to view the reading of the response.
It also matches the call order against the protocol making it a little easier for those unfamiliar with the protocol to see which methods have been implemented.

Modifications:
Moved channel active calls to be top of the class.
Despite the diff there are no actual code modifications.
UDP Client changed to indent using spaces to match rest of project. Incidental change.

Result:
The examples are slighter clearer to read, particularly for newcomers to swift-no as the calls are in a logical chronological order.

* Fix an error in the upgrader and its tests which checked the connection header incorrectly.

Motivation:
To correct the logic in the upgrader. Previously it checked if the upgraders required headers include the connection header. Now it checks that the connection header value was present as a separate header in the incoming request.
To prepare the class naming for the presence of a client upgrader.

Modifications:
Slight change in server upgrader handler logic with accompanying tests.
Renamed upgrader and test files to include the word ‘server’.
Ran the linux test script.

Result:
The server upgrader now checks for the presence of the connection header value as a header of its own.

* Rename WebSocketServer upgrader to make the naming clearer and make way for a client version.

Motivation:

To make the web socket upgrader naming clearer, particularly once we add a client version.

Modifications:

Rename WebSocketUpgrader too WebSocketServerUpgrader.

Result:

Improved clarity of naming on the web socket upgrader.

* Adds  correct naming conventions to NIOWebSocketServerUpgrader. Sets back an incorrect fix (non-fix).

* Move deprecation for NIOWebSocketServerUpgrader typealias out of API shims file.

* Makes HTTPEncoder removable.
Adds a client upgrade handler with tests.
Adds the ability to use a client upgrader to the client setup.
Initial linux file update.

* Allow assertContains to be accessed publicly, so that it can be used in the client side tests.

* Update tests to remove server upgrader from client tests.
Change client tests to use Embedded channel.
Update HTTPUpgradeConfiguration class name to be NIOHTTPServerUpgradeConfiguration
Few other small stylistic changes.

* Removed awaiting upgrader state.
Removed future from handle upgrade call as is synchronous.
Removed protocol iterator from handle upgrade call as is not required by the client.

* Ensure that the client handler calls for the HTTPPipeline are backwards compatible.
Ensure that incoming promises to the handler write call are completed.
Neaten the upgrade header formation to remove looping.
Improve the correctness of the upgrade error throwing.

* Update scripts to match new unit tests.

* Change the documentation for HTTPServerPipeline to remove nil options which have now been removed.

* Restore an incorrectly added server pipeline comment change and make it to the client pipeline instead.

* Raise the allocation limits in the docker images to allow the tests to pass.
2019-06-16 11:10:12 +01:00
Liam Flynn f5084352c6 Rename the EndToEndTests in the WebSocket project to WebSocketServerEndToEndTests. (#1032)
Motivation:

To make the web socket server end to end tests class more descriptive.
This will allow ‘WebSocketClientEndToEndTests’ or other end to end tests to be added at a later date.

Modifications:

Renames the class and filename for ‘EndToEndTests’ to ‘WebSocketServerEndToEndTests’

Result:

The nomenclature now allow for other end to end tests to be added.
2019-06-11 19:22:02 -07:00
Simon Evans dfe4318c50 When testing for an IPv6 Loopack interface try resolving ::1 (#1028)
Motivation:

On an Ubuntu18 system with a loopback interface configured with both
an IPv4 and IPv6 address, SocketAddress(ipAddress: "::1", port: 0) will
succeed, indicating that an IPv6 interface is configured. However if the
ethernet address has only an IPv4 address, getaddrinfo("::1", ...) will
fail even though the host resolution should work. This appears to be a
bug in the getaddrinfo() config.

This means that the tests will proceed assuming IPv6 is available, but
later tests that attempt to resolve "::1" will fail unexpectedly.

Modifications:

Change the ipv6Loopback test to attempt a resolution initially and if
this fails then assume that an IPv6 loopback is not available.

Result:

The Multicast.testCanJoinBasicMulticastGroupIPv6 test is skipped instead
of failing.
2019-06-07 16:33:35 -07:00
George Barnett 8aaaaab4fa Add an optimization tips document. (#1024)
Motivation:

NIO doesn't offer any tips of on how to write performant code. After
discussing with @weissi we decided it would be useful to gather and
document some useful tips and tricks.

Modifications:

Started an optimization tips document.

Result:

Easier for NIO users to write performant code.
2019-06-05 07:48:57 -07:00
Johannes Weiss a04da61854 alloc test: don't delete tmpdir (#1026)
Motivation:

The allocation tests shouldn't delete their working directory because
that's where you would navigate to debug them. Usually, they're run
through the integration tests which automatically clean up anyway.

Modifications:

Don't delete work dir

Result:

Easier to debug
2019-06-05 06:12:14 -07:00