Commit Graph
1096 Commits
Author SHA1 Message Date
Johannes Weiss c6479eb1fc ByteBuffer.viewBytes now returns an Optional (#878)
Motivation:

ByteBuffer.viewBytes would unconditionally return a ByteBufferView even
if the requested bytes were not readable.

Modifications:

- make it return an `Optional<ByteBufferView>`

Result:

safer, better APIs
2019-03-07 09:12:53 +00:00
Daniel Alm 8335074108 Make NIOAny log the contents of its storage when encountering fatal unwrapping errors. (#876)
Motivation:
This should make debugging crashes easier, as knowing the contents of the badly-unwrapped `NIOAny` should make it more clear where exactly it could have been written. Personally I'd prefer this to never cause a fatal error, but I assume that would need more discussion.
2019-03-06 16:43:13 +00:00
Johannes Weiss f1efb4a104 new http parser (#814)
Motivation:

The old HTTP parser tried to convert `http_parser` to a one-shot parser
by pausing it constantly. That was done to be resilient against
re-entrancy. But now, we have the new `ByteToMessageDecoder` which
protects against that so HTTP decoder can just become a real
`ByteToMessageDecoder`. It also serves as a great testbed for
`ByteToMessageDecoder`.

Modifications:

- make the HTTP decoder a `ByteToMessageDecoder`
- refactor the implementation

Result:

cleaner code, more use of `ByteToMessageDecoder`
2019-03-06 11:51:42 +00:00
Johannes Weiss 5fba8b7def B2MD: Stop parsing loop correctly on EOF (#875)
Motivation:

Introduced in #767 we would never interrupt a parsing loop unless the
decoder was removed, that's wrong and we need to interrupt also if we
seen `channelInactive` or inbound half closure.

Modifications:

interrupt the parsing loop on EOF.

Result:

more correct B2MD
2019-03-06 09:48:53 +00:00
Johannes Weiss 796a7d6d7e ByteBuffer get* now respects reader/writer indexes (#869)
Motivation:

Previously, ByteBuffers get* methods would get bytes from anywhere, even
if the bytes were not readable. That can lead to security issues in code
that doesn't expect this. NIO shouldn't contain such unsafe methods
without the word 'unsafe'.

Modifications:

Made all `get*` methods respect reader/writerIndex.

Result:

safer user code
2019-03-05 13:52:17 +00:00
Johannes Weiss e654e18644 fix NIOAny.tryAsOther (#870)
Motivation:

tryAsOther previously only returned the value if it was stored as the
.other case in NIOAny but we should do better.

Modifications:

also return the fastpath cases in tryOther (just slower than in the
actual fast path)

Result:

EmbeddedChannel.readIn/Outbound work properly
2019-03-05 12:30:29 +00:00
Ian Partridge aa03d7a385 EmbeddedChannel: use tryAs() not forceAs() (#602)
Motivation:

If you pick the wrong type for readIn/Outbound in tests, it's better to have an error thrown than a crash.

Modification:

- use `tryAs` rather than `forceAs` when trying to extract the buffer element

Result:
better usability in tests.
2019-03-05 11:48:25 +00:00
Cory Benfield b13bc66062 Support using recvmmsg to perform gathering reads. (#743)
Motivation:

Some DatagramChannels are extremely high-throughput. This can occur
when UDP is being used as an encapsulation for a transport protocol
(e.g. QUIC), or when a highly utilized service is being offered on a
single port (e.g. DNS).

In these cases, the syscall overhead of datagram reads is quite high
(one recvfrom call per datagram). It would be helpful to be able to
trade off some memory usage in order to reduce the cost of the syscalls
in this situation.

This patch adds support for transparently using the recvmmsg syscall
to achieve this kind of tradeoff.

Modifications:

- Added support to the DatagramChannel for issuing vector reads.
- Added new ChannelOption: DatagramVectorReadMessageCountOption
- Added UDP echo server example to exercise functionality.
- Tests

Result:

Able to achieve higher read throughput on supported systems.
2019-03-05 11:25:21 +00:00
JovanMilenkovic 56a72a2a89 Conform NIOAny to CustomStringConvertible (#751)
Motivation:

NIOAny is used extensively across SwiftNIO but can't be reasonably debugged. Users may want to simply call String(describing: CustomStringConvertible) to inspect what is the data they are working with at the moment instead of seeing an output that has no debug value.

Modifications:

Conform NIOAny to CustomStringConvertible, along with other types it currently uses that lacked string representation.

Result:

Users can perform simple debugging by printing their NIOAny object.
2019-03-05 09:23:25 +00:00
Cory Benfield fe4327d359 Hard-fail on invalid write types in core channels. (#323)
Motivation:

There is relatively little benefit in allowing the user to send invalid
data types on a given channel. Currently we tolerate this by simply
failing the promise, but this is not really ideal: if the user never sets
a promise here they never even find out that we bailed on sending their
data. Given that we attempt to be type safe everywhere else, we should
just blow up immediately if the user attempts to write an invalid data
type.

Modifications:

Removed the nice gentle type casts, replaced them with explody ones.

Result:

Faster failure in error cases.
2019-03-05 09:02:14 +00:00
Johannes Weiss eb524c72ad improve and simplify MessageToByteEncoder (#868)
Motivation:

MessageToByteEncoder was a protocol that similar to ByteToMessageDecoder
was pretty hard to hold correctly (override some methods but not
others). This PR brings MessageToByteEncoder more in line with the new
ByteToMessageDecoder.

Modifications:

- refactor `MessageToByteEncoder`
- introduce `MessageToByteHandler`, similar to `ByteToMessageHandler`

Result:

- better API, more similar to ByteToMessageDecoder
- fixes #864
2019-03-04 19:19:53 +00:00
Johannes Weiss cde067e603 fail unhandled outbound user events (#867)
Motivation:

Unhandled outbound user events should be failed but previously they were
succeeded.

Modifications:

Succeeding them is odd because nothing happened to them, so they should
be failed.

Result:

fixes #487
2019-03-04 15:43:33 +00:00
Johannes Weiss 47a3e7a7a0 conform ByteBufferView to Foundation's ContiguousBytes protocol (#800)
Motivation:

- Foundation has (on master) introduces a ContiguousBytes protocol and we
  should conform to that.
- Sequence has withContiguousStorageIfAvailable and ByteBufferView
  should conform to that too

Modifications:

add conformance

Result:

more compatibility.
2019-03-04 15:07:29 +00:00
Johannes Weiss a1981eb0fd prepare tests for throwing readIn/Outbound (#861)
Motivation:

readInbound/Outbound will soon throw errors if the type isn't right.

Modifications:

prepare tests for throwing readIn/Outbound

Result:

@ianpartridge's PR should pretty much merge after this.
2019-03-04 09:40:59 +00:00
Tanner 56669eabd2 improve ChannelPipeline debug print (#851)
Motivation:

ChannelPipeline layout helps understanding NIO and debugging

Modifications:

improved the ChannelPipeline `debugDescription`

Result:

NIO better
2019-02-28 18:01:55 +00:00
Johannes Weiss b1f62f71a6 EmbeddedChannel: expose EmbeddedEventLoop (#855)
Motivation:

There's just too much test code that has

(channel.eventLoop as! EmbeddedEventLoop).run()

Modifications:

have EmbeddedChannel expose its EmbeddedEventLoop

Result:

easier test code
2019-02-28 16:30:36 +00:00
Johannes Weiss 66b00ec637 B2MD: fast-path to reduce allocations (#854)
Motivation:

B2MD has an important fast path:
- everything was consumed
- no buffers collected during re-entrancy

In this case we should short-circuit and move on as quickly as possible.

Modifications:

If everything was consumed in `decode` and no buffers were collected in
re-entrancy, returning a buffer isn't actually useful, we should just
drop it and not risk taking an allocation for a useless `clear`.

Result:

faster & fewer allocs
2019-02-28 15:04:43 +00:00
Johannes Weiss d3862c0ecc B2MD: actually call decoderRemoved (#853)
Motivation:

decoderRemoved was never actually called...

Modifications:

call decoderRemoved on removal

Result:

more correct B2MD
2019-02-28 13:21:32 +00:00
Johannes Weiss 14327af193 don't leak pthread_keys (#157)
Motivation:

Previously we leaked `pthread_key`s as we only ever called
`pthread_key_create` but never `pthread_key_delete`. This patch fixes
that.

Modifications:

- made `ThreadSpecificVariable` a class (so we get lifecycle management
  through ARC)
- instead of just storing the value, store `Box<(ThreadSpecificVariable<T>, T)>`
  so we can control the lifecycle of the `ThreadSpecificVariable` as
  needed

Result:

We don't leak `pthread_key`s anymore.
2019-02-26 14:57:47 +00:00
Johannes Weiss 7255124e2e ELF: fix andAll* (#843)
Motivation:

andAllComplete/Succeed would never fulfill their promise if 0 futures
were andAll'd.

Modifications:

Fulfill immediately if there's 0 futures to wait on.

Result:

don't get stuck anymore on 0 futures.
2019-02-26 12:58:41 +00:00
Markus Kieselmann cdc0c29604 make localAddress and remoteAddress testable in EmbeddedChannel (#833)
Motivation:
Testing channel handlers that rely on `Channel.localAddress` or `Channel.remoteAddress` is currently quite inconvenient as one cannot set test values for `localeAddress` or `remoteAddress` on `EmbeddedChannel`.

Modifications:
Change `localAddress` and `remoteAddress` to variables instead of constants and set the address values in `bind()` and `connect()` as proposed in #829.

Result:
Arbitrary values for `localAddress` or `remoteAddress` can be set on `EmbeddedChannel`.
2019-02-26 10:35:38 +00:00
Johannes Weiss a41280919e rename ctx to context (#842)
Motivation:

`ctx` was always an abbreviation was 'context` and in Swift we don't
really use abbreviations, so let's fix it.

Modifications:

- rename all instances of `ctx` to `context`

Result:

- fixes #483
2019-02-25 18:20:22 +00:00
Johannes Weiss 862533d089 B2MD: Don't deliver data after error (#837)
Motivation:

B2MD should never call any of the decode functions after the user has
thrown an error.

Modifications:

introduce an error state and make sure we don't call out if in error
state

Result:

B2MD more correct
2019-02-25 17:18:11 +00:00
Johannes Weiss afbab95f27 address #186: rename BlockingIOThreadPool to NIOThreadPool (#838)
Motivation:

The thread pool implementation can be used for many things not just
blocking IO.

Modifications:

rename BlockingIOThreadPool to NIOThreadPool

Result:

fixes #186
2019-02-25 16:51:47 +00:00
Johannes Weiss b7f4e494f3 introduce WriteObservingByteToMessageDecoder (#834)
Motivation:

Some B2MDs need to observe writes.

Modifications:

Make those B2MD's B2MHs ChannelOutboundHandlers and let the B2MDs
observe the writes.

Result:

HTTPDecoder can be expressed as B2MD.
2019-02-25 14:25:31 +00:00
Johannes Weiss f720de3ae0 make ChannelOptions.Storage public (#827)
Motivation:

To implement your own `Channel`s, you very likely need
`ChannelOptions.Storage`, so let's make it public.

Modifications:

- make ChannelOptions.Storage public

Result:

easier custom Channels
2019-02-21 19:43:23 +00:00
Johannes Weiss ff31b3135d improve B2MD EOF handling (#831)
Motivation:

Previously B2MDs didn't really have defined semantics regarding EOFs and
we didn't tell them if there was an EOF. Also `decodeLast` was optional
and all that was bad.

Modifications:

- require `decodeLast`
- add a `seenEOF: Bool` parameter to `decodeLast` which tells the
  decoder if an EOF has been seen

Result:

- clearer semantics
- more information
2019-02-21 14:14:50 +00:00
Johannes Weiss 46ffd630de ChannelPipeline: addHandler and removeHandler instead of add/remove (#817)
Motivation:

- `ChannelPipeline.add(name:handler:...)` had a strange order of arguments
- `remove(handler:)` and `remove(ctx:)` both remove `ChannelHandler`s
  but they read like they remove different things

So let's just fix the argument order and name them `addHandler` and
`removeHandler` making clear what they do.

Modifications:

- rename all `ChannelPipeline.add(name:handler:...)`s to `ChannelPipeline.addHandler(_:name:...)`
- rename all `ChannelPipeline.remove(...)`s to `ChannelPipeline.removeHandler(...)`

Result:

more readable and consistent code
2019-02-21 11:46:54 +00:00
Johannes Weiss 5143f0bc17 opaque indices for (Marked)CircularBuffer (#826)
Motivation:

Opaque indices are a good idea for collections, (Marked)CircularBuffer
should use those too.

Modifications:

Cheapest possible implementation for opaque indices, could be much
improved. This is the cheapest possible implementation for opaque
indices and this could be much improved later, see #682 but the
improvements won't be SemVer major :).

Result:

first stab at #682
2019-02-19 18:46:01 +00:00
Johannes Weiss bf3b87cb4e simplify ChannelOptions (#828)
Motivation:

ChannelOptions used a too complicated mechanism for what they are.

Modifications:

- change the ChannelOptions to a much simpler mechanism
- rename the generic parameters from T to Option

Result:

code easier to read and understand
2019-02-19 18:31:26 +00:00
Johannes Weiss 3d3cc6d685 rename FileHandle to NIOFileHandle (#818)
Motivation:

Collisions with Foundation and other standard libraries is painful.

Modifications:

- rename `FileHandle` to `NIOFileHandle`
- rename `Thread` to `NIOThread` (only exposed in docs)

Result:

fewer collisions
2019-02-19 16:52:00 +00:00
Johannes Weiss 877f0ebc12 require ChannelOptions to be Equatable (#823)
Motivation:

ChannelOptions should've always been Equatable and so far we've hacked
around them not being Equatable when we wanted to compare them.

Modifications:

make all ChannelOptions Equtable

Result:

- ChannelOption comparison actually works
- fixes #598
- make more ChannelOptions stuff inlinable to not regress allocations
2019-02-19 12:30:26 +00:00
Johannes Weiss 03aa0bd43e rename Channel._unsafe to Channel._channelCore (#820)
Motivation:

_unsafe is non-descriptive

Modifications:

- rename Channel._unsafe to Channel._channelCore

Result:

clearer API
2019-02-14 14:14:11 +00:00
Johannes Weiss 7ded801710 Thread's == was public by accident (#819)
Motivation:

Thread's equality function was public by accident.

Modifications:

make Thread's equality function internal

Result:

Thread remains internal
2019-02-14 13:25:49 +00:00
Johannes Weiss 0ac7e2266b remove extension public/internal modifiers (#822)
Motivation:

public/internal modifiers for `extension`s are confusing as a
`func foo` is public if within a `public extension`.

Modifications:

remove all `internal` (redundant) and `public` (dangerous) modifiers for
`extensions`.

Result:

- code easier to read
- code much easier to review in a small diff
2019-02-14 13:25:30 +00:00
Nathan Harris 9e73705fd4 Update ELF parameter labels to be more Swifty (#809)
Motivation:

As part of NIO2 - much work has been done to round out the API of EventLoopFuture. This finishes existing public API parameters to be more in line with Swift API guidelines.

Modifications:

Methods in EventLoopFuture that had `eventLoop` as a parameter label have been changed to `on`

Results:

EventLoopFuture public API is more "Swifty" with calls such as `future.hop(to: eventLoop)` rather than `future.hopTo(eventLoop: eventLoop)`
2019-02-12 21:40:23 +01:00
Johannes Weiss 6e7a3de8e8 make all removals go through the RemovableChannelHandler API (#815)
Motivation:

Some of the ChannelPipeline removal methods did not go through the
RemovableChannelHandler API.

Modifications:

make all removal APIs go through the RemovableChannelHandler API

Result:

fewer bugs
2019-02-12 19:06:39 +01:00
Johannes Weiss c6c1f84459 CircularBuffer: speedup removeAll (#816)
Motivation:

Previously CircularBuffer.removeAll would always allocate (a new backing
store), even when `keepingCapacity: true`.

Modifications:

Don't make CircularBuffer allocate unnecessarily

Result:

faster CircularBuffer.removeAll
2019-02-12 18:52:29 +01:00
Johannes Weiss 1198931823 ByteBuffer: rename set(<type>:, ...) to set<Type>(...) (#812)
Motivation:

ByteBuffer methods like `set(string:)` never felt very Swift-like and
also didn't look the same as their counterparts like `getString(...)`.

Modifications:

- rename all `ByteBuffer.set/write(<type>:,...)` methods to
  `ByteBuffer.set/write<Type>(...)`
- polyfill the old spellings in `_NIO1APIShims`

Result:

code more Swift-like
2019-02-12 11:11:45 +00:00
Johannes Weiss d938264fcb better ChannelHandler removal API (#767)
Motivation:

If ChannelHandler removal worked correctly, it was often either by
accident or by intricate knowledge about the implementation of the
ChannelHandler that is to be removed. Especially when it comes to
re-entrancy it mostly didn't work correctly.

Modifications:

- introduce a `RemovableChannelHandler` API
- raise allocation limit per HTTP connection by 1
  (https://bugs.swift.org/browse/SR-9905)

Result:

Make things work by contruction rather than accident
2019-02-12 11:27:48 +01:00
Cory Benfield 2738b6d54f Add TCP_INFO/TCP_CONNECTION_INFO queries. (#811)
Motivation:

Many users may wish to see the underlying TCP connection state for
important calculations, such as for BDP or RTT numbers. We can make this
available easily enough.

Modifications:

- Added a function to get TCP_INFO on Linux/FreeBSD.
- Added a function to get TCP_CONNECTION_INFO on Darwin.

Result:

Better connection stats
2019-02-11 12:42:37 +01:00
Gwynne Raskind 642076e9f8 Fix a race condition when remote closes connection after accept() but before fcntl() on macOS. (#807)
Motivation:

A race condition occurs when a socket is closed from the remote end after `accept()` returns it, but before `fcntl(F_SETFL, F_SETNOSIGPIPE)` is invoked. This causes the `fcntl()` call to fail with `EINVAL` ("The socket has been shut down."). This currently triggers an assertion failure. As the race depends on the remote and can be easily demonstrated (using `nmap` is a good way to set it off), the assertion is semantically invalid (`EINVAL` is not programmer error). Additionally, errors reported by `fcntl()` in general are being ignored when not asserted.

Modifications:

The race is avoided by treating `EINVAL` as a normal error while retaining the existing behavior for all other error cases. Both uses of `fcntl()` to disable `SIGPIPE` now properly report errors.

Result:

`Posix.accept()` and `Posix.socket()` may now potentially throw additional errors. It is no longer possible to crash a debug server by running `nmap` against it.
2019-02-06 17:08:00 +00:00
George Barnett 7f68ff36d3 Remove outdated documentation (#808) 2019-02-06 14:02:12 +00:00
Nathan Harris 06fb45d07e Rename ELF.andAll(_:eventLoop:) to andAllSucceed(_🔛) and add ELF.andAllComplete (#803)
Motiviation:

After adding `ELF.whenAllComplete` the concept of "fail fast" and "fail slow" for reducing an array of future results together was introduced.

This commit adds that concepts with the `andAll* methods that act as simple completion notifications.

Modifications:

Rename `EventLoopFuture.andAll(_:eventLoop:)` to `andAllSucceed(_🔛)` to denote its "fail fast" nature, and to match Swift API guidelines.

Add new `EventLoopFuture.andAllComplete(_🔛)` for a "fail slow" companion.

Shift implementation of `whenAllComplete(_🔛)` to be usable without unnecessary allocations in `andAllComplete`

Result:

EventLoopFuture now has two methods for "flattening" arrays of EventLoopFuture into a single notification ELF
2019-02-06 09:16:48 +00:00
Nathan Harris caf9a3d8da standardize ELF.cascade* collection of methods (#802)
Motivation:

The `ELF.cascade` methods have a parameter label `promise` that does not match Swift API Guidelines, and a way to cascade just successes is not available - while for failures there is.

Modifications:

`ELF.cascade*` methods that already exist have had their `promise` label renamed to `to`, and a new `ELF.cascadeSuccess` method has been added.

Result:

EventLoopFuture now has the cascade methods `ELF.cascade(to:)`, `ELF.cascadeFailure(to:)`, and `ELF.cascadeSuccess(to:)`
2019-02-05 09:01:48 +00:00
Nathan Harris 9b9dcebecf add ELF.whenAllSucceed method to act as "fail fast" counter-part to ELF.whenAllComplete (#804)
Motivation:

`ELF.whenAllComplete` is a "fail slow" method that returns an `EventLoopFuture` that always succeeds after all provided futures complete - fulfilling with all the results of the futures.

`ELF.whenAllSucceed` is a "fail fast" method that returns an `EventLoopFuture` that succeeds if all of the futures succeed - and returning the fulfilled values.

This new method acts as a counterpart to both `ELF.whenAllComplete` and `andAll`

Modifications:

Add `ELF.whenAllSucceed` that returns an EventLoopFuture with all of the values provided from the futures being awaited.

Rename `ELF.whenAllComplete(_:eventLoop:)` to `ELF.whenAllComplete(_🔛)` to match new `whenAllSucceed` and Swift API guidelines

Result:

New method for flattening multiple futures into a single EventLoopFuture that fulfills with an array of their success values if they all succeed.
2019-02-04 17:43:01 +00:00
Alex Reilly 6ca8c0e189 Documentation grammar fixes (#805) 2019-02-03 09:15:32 +00:00
George Barnett 6050c9c864 Fix documenation markup (#799)
Motivation:

Quick Documentation was not rendering some parameter documentation
correctly as it was over-indented.

Modifications:

Reduced indentation for over-indented parameters.

Result:

Quick Documentation renders correctly.
2019-02-01 15:34:59 +00:00
Johannes Weiss 89a4eaa807 fix #657 (#795)
Motivation:

testCloseInReadTriggeredByDrainingTheReceiveBufferBecauseOfWriteError
expected (without knowing it) that networking on localhost is
synchronous enough that a succeeded write means that it has
simultaneously arrived in the reader's read buffer.

On macOS that's not necessarily true, so this test failed very seldom
seemingly more often if you had more physical cores.

Modifications:

Introduce a nasty blocking `poll` call in the test that waits until we
have bytes in the read buffer.

Result:

- fixes #657
2019-01-31 16:41:55 +00:00
JovanMilenkovic cf56bfd119 Remove EmbeddedChannel restriction to IOData (#763)
Remove EmbeddedChannel restriction to IOData

Motivation:

You should be able to read any type from the outbound buffer.

Modifications:

Change Embedded channel outboundBuffer and pendingOutboundBuffer to store NIOAny instead of IOData and refactor test code accordingly.

Result:

- Users can test what went through the pipeline without serializing everything and using "if case let" syntax everywhere.
- fixes #551
2019-01-30 19:24:59 +00:00