Commit Graph
2140 Commits
Author SHA1 Message Date
PeterAdams76andJohannes Weiss 0db1cd5318 Add custom index methods to ByteBufferView (#1394)
Motivation:

The performance of firstIndex and lastIndex is
dramatically improved by addding custom
indexing methods as detailed in issue 1385.

Modifications:

Added methods to ByteBufferView:
_customIndexOfEquatableElement
for firstIndex
_customLastIndexOfEquatableElement
for lastIndex

Added a unit test for firstIndex and lastIndex
to ensure functional behaviour is unchanged.

Result:

firstIndex and lastIndex behave as before.

Performance is improved by approximately 20% for
the shortest searches.
When tested searching over 1024 byte buffer
with either no match or a match at the end
I observed approximately 15 times performance

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-02-19 18:12:38 +00:00
Saleem AbdulrasoolandCory Benfield 1832cff669 CNIOAtomics: declare atomic operations using a macro (#1400)
Use a macro to define the interface for the typed atomics.  This reduces
the boiler plate that is expanded by hand.  More importantly, it makes
it easier to add new types in the future.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-02-18 10:24:20 +00:00
Saleem AbdulrasoolandCory Benfield ca9f613bbc NIO: excise UDS support for Windows (#1404)
This removes support for Unix Domain Sockets from NIO on Windows.
Although Windows 10.17063 introduced basic support for UDS, the support
is incomplete and has differences from the tradtional UDS sockets in
terms of behaviour.  Excise the support initially to get NIO to build on
Windows.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-02-18 09:36:18 +00:00
Johannes Weiss 16ab4d657e add AcceptHandler after serverChannelInitializer runs (#1393)
Motivation:

For compatibility with 2.13.1 and earlier, we're adding the
AcceptHandler after the serverChannelInitializer runs. If that's the
best solution is discussed in #1392.

Modifications:

- add AcceptHandler after the serverChannelInitializer
- give the AcceptHandler the name AcceptHandler

Result:

- better compatibility
2020-02-13 12:55:52 +00:00
Cory Benfield bfde40cac8 Update http-parser for CVE. (#1387)
Motivation:

http-parser shipped a patche for node.js CVE-2019-15605, which allowed
HTTP request smuggling. This affected SwiftNIO as well, and so we need
to immediately ship an update to help protect affected users.

A CVE for SwiftNIO will follow, but as this patch is in the wild and
SwiftNIO is known to be affected we should not delay shipping this fix.

Modifications:

- Update http-parser.
- Add regression tests to validate this behaviour.

Result:

Close request smugging vector.
2020-02-10 16:44:44 +00:00
Johannes Weiss c6e5fe88e1 ByteBuffer: make getInteger for UInt8 faster (#1380)
Motivation:

getInteger used the normal, generic implementation for UInt8s, however
they can be made considerably faster by using a specialised method.
ByteBufferIterator was also affected by this.

Modifications:

Use a specialised version for UInt8s for getInteger.

Result:

- ByteBufferView can be iterated about 20% faster.
2020-02-06 11:59:10 +00:00
Johannes Weiss d1ef9be53c update vendored code & attribute it correctly (#1382)
Motivation:

This updates all vendored code and also lets github know what's vendored
code through `.gitattributes`.

Modifications:

- http_parser update
- attribution

Result:

- better github stats
- up to date software
2020-02-05 15:04:35 +00:00
George Barnett a678727747 Provide descriptions for EventLoopError (#1381)
Motivation:

EventLoopError does not conform to CustomStringConvertible. When these
errors appear in programs depending on NIO the source of the error is
non-obvious to the user.

EventLoopError.shutdown, for example, would appear in logs as
"shutdown" with no indication that it was the event loop being referred
to.

Modifications:

- Conform EventLoopError to CustomStringConvertible

Result:

- More helpful error descriptions for EventLoopError
2020-02-05 11:26:41 +00:00
George Barnett c92a9c638c Reserve capacity in terms of writable bytes (#1378)
Motivation:

Often we know ahead of time that we will need to write a certain number
of bytes into a buffer. It is useful to ensure the buffer has enough
capacity to store these bytes without causing unnecessary allocations.
However, `reserveCapacity()` is defined in terms of the capacity of the
buffer and it's can be easy to forget that this does not take into
account the writer index.

Modifications:

- Add a method which reserves enough capacity to write at least the
  specified number of bytes.
- Update `writeWithUnsafeMutableBytes(minimumWritableBytes:body:)` to use the
  new method.

Result:

It's easier for users to reserve enough writable capacity ahead of time.
2020-02-04 14:38:11 +00:00
Doug Friedman a4fe7d4840 get IOError down to git in an existential container (#1355) (#1376)
resolves #1355 shaving off some bytes from IOError struct

Motivation:

It's important for frequently used errors to fit in existential containers because otherwise throwing them leads to allocations.

Modifications:

- Don't store `StaticString`s anymore which are 2 words + 1 bytes wide

Result:

Fewer allocations when IOErrors are thrown.
2020-02-03 12:30:37 +00:00
ba37512da9 apply ChannelOptions before channel initializer runs (#1372)
Motivation:

The channel initializers should see the the Channel after the options
have been applied so they can potentially override the options.

Modifications:

Set the options before the channel initialiser rather than after.

Result:

- More sense, more compatibility with Netty
- fixes #1114

Co-authored-by: George Barnett <gbrntt@gmail.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-02-01 10:21:54 +00:00
George Barnett b4483e5c49 Avoid curried thunks (workaround SR-12115) (#1374)
Motivation:

Calling `function(otherFunction)` allocates, but
`function({ otherFunction($0) }` does not.

See: SR-12115 and SR-12116.

Modifications:

Avoid passing functions directly; pass them in new closures instead.

Result:

Fewer allocations.
2020-01-31 17:57:30 +00:00
Johannes Weiss 52a4cae14d add SAL (Syscall Abstraction Layer) and new SALChannelTests
## Motivation:

In SwiftNIO's codebase, most things were always testable just as well as user code is. With one big missing piece: We could never make the `Selector` do arbitrary things to the `Channel` implementations which lead to super expensive to (create, read, understand) integration tests like [`testWriteAndFlushFromReentrantFlushNowTriggeredOutOfWritabilityWhereOuterSaysAllWrittenAndInnerDoesNot `](https://github.com/apple/swift-nio/blob/5dc9083c6a78b10432b4b55b95704e61ca08f09d/Tests/NIOTests/StreamChannelsTest.swift#L468-L760).

## Modification

Add SAL, a 'syscall abstraction layer' which makes it possible to assert all syscalls that come through a `Socket` or the `Selector` by mocking them. It lets the NIO programmer play the kernel in these "SAL tests" which makes it possible to assert the exact syscalls (with their parameters) and decide the syscalls' returns.

## Result

Finally, we're able to write proper unit tests for scenarios where the `Channel` drove the `Selector` incorrectly.
2020-01-28 12:36:36 +00:00
Fabian Fett 5dc9083c6a Recursive file reading not building up EventLoopFuture chain (#1353)
* Recursive file reading not building up EventLoopFuture chain

# Motivation:

After a long discussion with @adam-fowler today in aws-sdk-swift about how to recursively build a streaming interface (see https://github.com/swift-aws/aws-sdk-swift-core/pull/181), we came to the conclusion that it’s probably for the best not to build up an EventLoopFuture chain, since all EventLoopFutures are kept in memory while iterating. It would be better to create a promise that is captured by the recursive function, because in this case the internal EventLoopFutures can be released.

The memory footprint should be O(1) instead O(n) with a EventLoopFuture chain.

Later today, @adam-fowler made me aware of this code in NIO and that it uses a chain.

# Modifications:

```swift
_read(remainingReads: Int, bytesReadSoFar: Int64)
```

The internal read function no longer returns an EventLoopFuture. All Futures end with an `whenSuccess` or `whenFailure` case.

# Result:

From my understanding the memory footprint should be reduced when reading large files. The interface stays completely the same.
2020-01-27 13:33:50 +00:00
Christian PriebeandJohannes Weiss 4409b57d4c Rename misnamed closure parameter argument in ServerBootstrap.bind0 (#1347)
Motivation:

Non-functional change: `bind0(_ makeSocketAddress: () throws -> SocketAddress)
-> EventLoopFuture<Channel>` calls `bind0` with a `register` closure that is
passed an event loop as first argument. However, the name of the first parameter
of the closure declaration is named "eventGroup" which is confusing. It should
therefore be renamed to "eventLoop" which is consistent with other closures
passed as `register` arguments at other callsites.

Modifications:

Rename (unused) closure parameter "eventGroup" to "eventLoop".

Result:

Improved code readability.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-01-22 15:13:34 +00:00
Christian PriebeandJohannes Weiss 03d90a6f2d Add setSubstring/writeSubstring to ByteBuffer. (#1346)
Motivation:

The `ByteBuffer` API currently has `setString`/`writeString` support for the `String`
type but no support for the `Substring` type (see #1332).

Modifications:

Add `setSubstring`/`writeSubstring` functions to `ByteBuffer`. We do not change
the exisiting set-/writeString API to take a generic `StringProtocol` argument
as it would change the ABI and adds performance overhead. We also do not let
`setString` call into `setSubstring` for now, as Substring currently (as of
Swift 5.1.3) has no fast access to the backing storage and this therefore would
introduce a performance regression.

Result:

ByteBuffer API for writing Substrings.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-01-22 14:45:40 +00:00
Johannes Weiss 45bca5672c improve flushNow re-entrancy protection (#1348)
improve flushNow re-entrancy protection

Motivation:

The fix in #1344 wasn't complete, there is another, quite complicated scenario where we would still forget to send flushed bytes until we see another `flush` call. The scenario is

         1: writable()
         2: --> flushNow (result: .writtenCompletely)
         3:     --> writabilityChanged callout
         4:         --> flushNow because user calls writeAndFlush (result: .couldNotWriteEverything)
         5:         --> registerForWritable (because line 4 could not write everything and flushNow returned .register)
         6: --> unregisterForWritable (because line 2 wrote everything and flushNow returned .unregister)

Line 6 undoes the registeration in line 5.

Modification:

This fix makes sure that flushNow never re-enters and therefore the problem described above cannot happen anymore.

Result:

Hopefully actually fixes rdar://58571521
2020-01-22 12:08:15 +00:00
Christian Priebe 84a33c5cdd Add bindTimeout function to ServerBootstrap (#1349)
Motivation:

We add an empty `bindTimeout` function to `ServerBootstrap`. While
ServerBootstrap itself is based on a blocking socket bind operation, this
enables the possibility of having bind be asynchronous in other use cases and
it unifies the API with other Bootstrap classes, e.g. `NIOTSListenerBootstrap`.
See also #1135.

Modifications:

Add `bindTimeout` function to `ServerBootstrap`.
Add `Bootstrap.testServerBootstrapBindTimeout` test.

Result:

`ServerBootstrap` has a `bindTimeout` function/API compatibility with other
Bootstrap classes.
2020-01-22 11:26:51 +00:00
Johannes Weiss 99ca704088 improve flushNow behaviour tests & description (#1345) 2020-01-20 15:55:47 +00:00
Johannes Weiss 6633f54708 support pread (#1324) 2020-01-20 09:56:54 +00:00
Johannes Weiss ca0ed86766 flushes from channelWritabilityChanged callbacks get lost (#1344) 2020-01-18 09:05:37 +00:00
Volodymyr Sapsai eb2dfd8d1b Fix documentation for HTTPRequestDecoder. (#1342)
There is no `ChannelPipeline.addHTTPServerHandlers` but there is `ChannelPipeline.configureHTTPServerPipeline`.

Comment for `HTTPResponseDecoder` mentioning `ChannelPipeline.addHTTPClientHandlers` is correct.
2020-01-16 09:51:53 +00:00
Bouke Haarsma 976e65aba7 Read exactly UInt64's size from timerfd (#1340)
On 32-bit systems we would try to read 4 byte, which is incorrect. From `man timerfd_read`:
> (...) then the buffer given to read(2) returns an unsigned 8-byte integer (uint64_t) containing the number of expirations that  have  occurred (...)
> A  read(2) will fail with the error EINVAL if the size of the supplied buffer is less than 8 bytes.
2020-01-15 10:22:16 +00:00
Liam Flynn 8ccae09377 Correct NIOHTTPWebClientSocketUpgrader to NIOHTTPWebSocketClientUpgrader (#1336)
Motivation:

The class name was a typo.
It is a client upgrader that upgrades WebSocket connections, so the updated name suits better.

Modifications:

Change class name of ‘NIOHTTPWebClientSocketUpgrader’ to ‘NIOHTTPWebSocketClientUpgrader’.
Update the WebSocket client example that uses this class.
Add a typealias to allow the old class name to be used.

Result:

Improved naming.
2020-01-15 09:24:50 +00:00
Liam Flynn 9fad4f5216 Change the byte to message decoder verifier example to be correct. (#1338)
Motivation:

The byte to message decoder example on the ‘verifyDecoder’ method was not compiling.

Modifications:

Added the example output objects to an array so that they match the method signature.

Result:

The example is now compiling and can serve as the basis for creating an implementation from the example.
2020-01-15 07:39:49 +00:00
George Barnett f44fe0b204 Fix documenation in HTTPHeaders. (#1335)
Motivation:

`subscript(name:)` and `first(name:)` incorrectly referred users to
`getCanonicalForm` for a maximally decomposed list of header fields.
This no longer exists.

Modifications:

Point users to `subscript(canonicalForm:)`.

Result:

More accurate documenation.
2020-01-11 16:51:50 +00:00
Fabian Fett ea5a64978d Initializing HTTPMethod with String picks explicit value over catch all RAW(value) (#1329)
Motivation:

When initializing an `HTTPMethod` with a `String` we currently switch over all expected values to pick an explicit value, only to overwrite our found explicit value with a catchall `RAW(value: String)`. This doesn’t make a ton of sense. This went unnoticed because we use the conditional conformance on `RawRepresentable` to be `Equatable`. But `switch`es  don’t use the `Equatable` protocol to match enums. The issue is visible there.

Modifications:

Added a testcase with a switch that fails, if the `.RAW(value: String)` value is used for `”GET”`. Removed the final overwrite in HTTPMethod(rawValue: String). Therefore the test passes.

Result:

We can initialize the HTTPMethod with a String and get an explicit value.
2020-01-02 11:39:54 -05:00
Fabian Fett 653492753c Faster Base64 Encoding for NIOWebsocket connections (#1328)
Motivation:

In performance tests was shown that the current base 64 encoding function doesn’t perform very well.

https://github.com/apple/swift-nio/issues/1322

Modifications:

This commit replaces the current Base64 implementation with a more performant one (by using UInt8 bytes instead of Unicode.Scalars).

Result:

The API will stay the same. Base64 encoding is just faster.
2019-12-24 12:41:43 +00:00
Fabian Fett f1a7accb76 ByteBuffer is now Hashable (#1326)
Motivation:

`ByteBuffer` should implement the `Hashable` protocol as stated by: https://github.com/apple/swift-nio/issues/1320

Modifications:

Implemented the `Hashable` protocol for `ByteBuffer` and added a test `testHasherUsesReadBuffersOnly`.

Result:

`ByteBuffer` implements the `Hashable` protocol. The test `testHasherUsesReadBuffersOnly` is failing for the moment though.
2019-12-23 12:30:40 +00:00
George Barnett f6487a11d8 Drain scheduled tasks on EmbeddedChannel finish() (#1319)
Motivation:

EmbeddedChannel advanced time to the distant future so that all
scheduled tasks would be run. However, if tasks were recursively
scheduled by executing the already scheduled tasks then the channel
would never finish.

Modifications:

When calling finish() on EmbeddedChannel, only run the tasks which have
been scheduled at that point in time.

Result:

Recursively scheduled tasks terminate when finish-ing the
EmbeddedChannel.
2019-12-20 15:26:18 +00:00
Johannes Weiss 7bf170f63a make SelectableEventLoop.description not take a lock (#1318)
Motivation:

SelectableEventLoop's description was taking a lock and would also lock
every single scheduled task. That's overkill.

Modifications:

Make it only log the thread and selector (which don't require locks).

Result:

better description
2019-12-19 15:19:14 +00:00
Johannes Weiss 6174c9802c add descriptions to EventLoop and NIOThread (#1317)
Motivation:

Certain issues are easier debugged if we can print the thread names.

Modifications:

- add the thread name to SelectableEventLoop's description
- make EventLoop and NIOThread CustomStringConvertible

Result:

easier debugging.
2019-12-19 14:52:03 +00:00
Cory Benfield 4dd5586c4b HEAD and DELETE may have bodies. (#1314)
Motivation:

We incorrectly asserted that HEAD and DELETE may not have request
bodies, but they can, it's just unlikely.

Modifications:

Change the categorisation of HEAD and DELETE.

Result:

Better behaviour in unusual cases.
2019-12-18 18:41:43 +00:00
Trevör 9e80488089 Use actual element count of PriorityQueue for its description (#1296) 2019-12-18 11:32:58 +00:00
Johannes Weiss 9fb70afddf close kqueue/epoll fds in Selector.close (#1308)
Motivation:

There was always this one big embarrassment in the NIO codebase: We
violated the iron rule of 'no fd or scarce resource management in deinit'
in just one place: The most long-lived thing there is in NIO: The
Selector for the SelectableEventLoopGroup. Sure enough, even that tiny
violation lead to issues.

Modifications:

Close the fds in `close` rather than `deinit`.

Result:

- I'm feeling better
- makes @ktoso happy
- fixes #1302
2019-12-17 18:30:17 +00:00
Johannes Weiss 9f94448bc6 accept: don't do unnecessary dodgy pointer things (#1306)
Motivation:

We never look at the socket address that accept(4) returns so we
shouldn't ask for it. Additionally, it wasn't always the right size (in
IPv6 case) and also the pointer operations were dodgy.

Modifications:

Remove the whole socket address pointer stuff for accept.

Result:

Cleaner code.
2019-12-17 11:57:38 +00:00
Johannes Weiss c1f0544980 fix EVFILT_EXCEPT loop if autoRead is off on Darwin (#1305)
Motivation:

Due to rdar://53656794, we sometimes (especially on UNIX Domain Sockets)
see EVFILT_EXCEPT firing when data is available to read depite the fact
that we're setting the low watermark to CInt.max. This means that
EVFILT_EXCEPT becomes essentially unusable.

Modifications:

- Don't use EVFILT_EXCEPT on Darwin
- We lose early EOF delivery on Darwin

Result:

Fewer possibilities of a spin loop on Darwin.
2019-12-16 14:42:50 +00:00
Johannes Weiss 6c36c4a6d5 SelectableEventLoop: Call wakeup less frequently (#1301)
Motivation:

Previously, we unconditionally woke up the selector for every task that
was added. But this is only necessary if we're not already on the
EventLoop. Because if we are, we'll have another look at the outstanding
tasks anyway.

Modifications:

Remove selector wakeups.

Result:

Faster executes.
2019-12-12 17:35:23 +00:00
Johannes Weiss 5a567709b2 remove phantom publics from EventLoop and Heap (#1298)
Motivation:

In SelectableEventloop, Heap, PriorityQueue, etc there were quite a few
phantom publics left which cause issues with #1257 and are confusing.

Modifications:

- remove the phantom publics
- move SelectableEventLoop to its own file

Result:

- clearer what's going on (public means public)
2019-12-11 18:41:51 +00:00
Joe Smith 06dab4e04b Create a ClientBootstrap protocol (#1253)
This allows other EventLoopGroup implementations to swap in other
bootstrap implementations. By default, it is unimplemented and will
throw an error once `connect` is called on the returned Bootstrap.

Support is implemented for `MultiThreadedEventLoopGroup`,
`SelectableEventLoop` and `EmbeddedEventLoop`.
2019-12-11 12:06:11 +00:00
Johannes Weiss 3f04a5c056 workaround failed associated type inference (#1299)
Motivation:

Some Swift nightly snapshots fail to compile NIO in release mode
(rdar://57793267), this change is to work around this issue by telling
them compiler the associatedtypes explicitly.

Modifications:

- add `Element` and `Indices` typealises to `CircularBuffer` explicitly.

Result:

Complies on all nightlies also in release mode.
2019-12-10 16:26:38 +00:00
Johannes Weiss e208ab9555 fix AtomicBox by deprecating it and implementing it with a CAS loop (#1287)
Motivation:

Atomic references cannot easily be maintained correctly because the
`load` operation gets a pointer value that might (before the loader gets
a change to retain the returned reference) be destroyed by another
thread.

Modifications:

- Deprecate `AtomicBox`
- Implement `NIOCASLoopBox` with functionality similar to AtomicBox (but
  implemented using a CAS loop :( ).

Result:

- fixes #1286
2019-12-06 17:41:14 +00:00
Johannes Weiss eee18dc81f save allocations on connect (#1290)
Motivation:

ClientBootstrap.connect was needlessly overallocaing (for a needless
promise and a needless cascade).

Modifications:

Remove the needless allocations.

Result:

Fewer allocations.
2019-12-06 16:55:51 +00:00
George Barnett 6761c87d1e Add first(name:) to HTTPHeaders (#1282)
Motivation:

In some cases you only expect (or care about) a single value for a
header. However, getting this value without allocating an array or
traversing the whole array requres using first(where:) provided by
Sequence. This is not very ergonomic as it requires users to do the
case-insensitive comparison and then exctact the value from the
HTTPHeaders. Additionally, users cannot use NIO's case insensitive
ASCII comparison.

Modifications:

- Provide a first(name:) method on HTTPHeaders which returns the value
  from the first header whose name is a case insentive match of the
  subscript parameter.

Result:

It's easier to get the first value from HTTPHeaders matching a given
name.
2019-12-06 16:31:38 +00:00
Johannes Weiss d5ac36e60f optimise future callback collection (#1293)
Motivation:

The futures implementation used a particularly inefficient way to
accumulate all callbacks.

Modifications:

Improved this by allocating fewer arrays.

Result:

Fewer allocations.
2019-12-06 14:37:11 +00:00
Petro Rovenskyy 31afb078c9 Replaced CircularBuffer's uses of checked arithmetic (+, -) (#1284)
* Replaced CircularBuffer's uses of checked arithmetic (+, -) with `&+` and `&-`.

* fixed PR feedback.
2019-12-05 19:34:26 +00:00
Johannes Weiss 88c7994869 stop using AtomicBox (#1289)
Motivation:

AtomicBox doesn't properly work (#1286) and despite fixing it in #1287,
it's really not worth using AtomicBox (which as of #1287 instroduces a
CAS loop) anymore.

Modifications:

Remove the two uses of AtomicBox.

Result:

No usage of broken/slow data types.
2019-12-05 19:04:06 +00:00
Johannes Weiss e3290d891a make sure ByteToMessageHandler is happy never being in a pipeline (#1288)
Motivation:

ByteToMessageHandler was expecting to always be added to a
ChannelPipeline. That's mostly true but not always.

Modifications:

Make sure we don't crash if a ByteToMessageHandler was never added.

Result:

Fewer crashes.
2019-12-05 10:53:31 +00:00
Petro Rovenskyy ab8dc8c55f implemented Equatable for _UInt24 and _UInt56 and marked as @inlinable (#1285) 2019-12-04 15:43:15 +00:00
Jari (LotU) 198b84b01c Webhooks upgrade complete fix (#1280)
Motivation:

Fixes the bug described in #1279

Modifications:

Moved state change in NIOHTTPClientUpgradeHandler.performUpgrade to after firing buffered messages.

Result:

- The upgradeState will now only change to upgradeComplete after buffered reads are handeld.
- Fixes #1279
2019-12-04 12:04:05 +00:00