Commit Graph
800 Commits
Author SHA1 Message Date
Cory Benfield 25da619b78 Extract EventLoop protocols and EventLoopFuture to Core (#1898)
Motivation:

The next step on extracting the base abstractions is to pull out
EventLoop, EventLoopGroup and related types, and also EventLoopPromise
and EventLoopFuture. These types are fundamental to the API.

Modifications:

- Extract EventLoop, EventLoopGroup, and related types.
- Extract EventLoopPromise and EventLoopFuture.
- Add new @testable imports.
- Split MultiThreadedEventLoopGroup into new file, appropriately named.

Result:

Better separation.
2021-07-21 07:56:11 +01:00
Cory Benfield 5b56f012e8 Better default for safe loop shutdown. (#1905)
Motivation:

In #1904 we included a change to add a debugging hook to confirm a group
could safely be shut down. Sadly, the default behaviour was too
aggressive, and would cause failures in downstream projects.

Modifications:

- Change the default behaviour of _preconditionSafeToSyncShutdown to be
  a no-op, as it currently is in NIO programs today.

Result:

Downstream projects won't break.
2021-07-20 16:24:59 +01:00
Cory Benfield c9fb1c23a1 Avoid syncShutdownGracefully knowing about MTELG. (#1904)
Motivation:

As part of the ongoing split of NIO into two components, we need to
decouple EventLoopGroup from MultiThreadedEventLoopGroup. This is
largely straightforward, but EventLoopGroup.syncShutdownGracefully uses
a hook on MTELG to try to provide debugging help.

That hook cannot stand, so we must break it. Unfortunately this slightly
reduces our ability to detect possible blocks of a SelectableEventLoop,
but in return we get to increase our ability to detect blocks of other
event loop groups.

Modifications:

- Added a debugging hook to detect possible blocking of event loops.

Result:

Less coupling.
2021-07-20 13:22:41 +01:00
Cory Benfield f607e5a47c Extract basic data structures to NIOCore. (#1895)
Motivation:

Currently the "core" NIO module (currently called NIO) contains two
fairly distinct kinds of things. The first is the core abstractions and
data structures: the things that all NIO programs must necessarily deal
with. This includes our base abstraction protocols (e.g. `EventLoop`,
`Channel`, and `ChannelHandler`), as well as our base data types (e.g.
`ByteBuffer`, `SocketAddress`, `EventLoopFuture`).

The second thing the core NIO module contains is the default POSIX
sockets event-loop and channels. These are the mainline production loops
for NIO programs, and are supported in the various BSD-like OSes to
varying extents. These can be thought of as a baseline implementation of
the core abstraction protocols that form the first part of NIO.

These two fairly distinct use-cases have no particular reason to be
glued together, and in fact in gluing them together we have done a bit
of a disservice to our adopters. The biggest issue is that it has become
impossible to write a NIO program or library that does not bring along
the POSIX layer of NIO. This has made porting NIO to other platforms
difficult (Windows has been painful, and Webassembly is coming down the
road as well), and has also bloated the size of iOS/macOS applications
that use NIO via NIOTransportServices, as all of these applications must
bring along an event loop and several Channels they will not use.

To that end, we plan to begin a scope of work to split the core NIO
module in two. Specifically, we intend to extract the baseline protocols
and data types into a new module, called `NIOCore`, which will be able
to be the baseline NIO module.

The end goal is that libraries that implement protocols on top of
SwiftNIO should be able to depend solely on `NIOCore`, not `NIO`. This
will allow NIO applications to bring along only the event loops they
want or need, without needing to pay for the POSIX sockets
implementation. This should also make porting easier, as there will be
no pressure to bring the existing `NIO` module to new platforms if it
does not fit well.

Modifications:

This is the first in a series of patches, which extracts some of the
low-hanging fruit. In particular, it extracts:

- `ByteBuffer` (and associated types)
- `RecvByteBufferAllocator`
- `CircularBuffer`

This also adds in the backwards compatibility shim: the `NIO` package
performs an exported import of `NIOCore`. This will allow this change to
avoid breaking API.

However, to make a clean break we intend not to release a new NIO minor
version until we have completed our extraction. If we fail to do this it
won't be the end of the world, we can release subsequent minor versions
that continue to extract new types. However, as much as possible should
go at once.

This patch also duplicates a few methods and files. At the end of the
patch series we need to reconcile this duplication. In many cases the
duplication will no longer be necessary, but in some cases we may have
necessary duplicates.

Result:

The first step along the road to better platform citizenship is taken.
2021-07-14 09:58:25 +01:00
Matt EatonandCory Benfield 3873886ebd issue-1036: Fix for dates on Linux test generation script. (#1894)
* issue-1036: Fix for dates on Linux test generation script.

Motivation:

Fix for issue-1036 to add a date or date range for the header.
These dates are derived from the git log on the file.

Modifications:

Parsing method to extract the date or date range from the git log
of the file.  This was added to generate_linux_tests.

Result:

Dynamic date or date range added to the file header.

* issue-1036: Added revised headers from generation script

* Regenerating dates on XCTests.

Motivation:

Addressing feedback from PR.

Modifications:

All of the XCTests now have -2021 as a header date attached to them.

Result:

Dates modified on the XCTests.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-07-13 14:31:01 +01:00
Austin ffa6a871f7 Feature: Datagram Packet Info (#1888)
* Break out control message parsing by IP version

* Add shims for Darwin packet info

* Add shims for Linux packet info

* Add channel option for receiving datagram packet info

* Add NIOPacketInfo to AddressedEnvelope.Metadata

* Pipe up packet info channel option to receive path

* Add NIOPacketInfo info and fix backwards compatability

* Document packet info socket options

* Cleanup packet info control message parsing

* Add packet info and ECN combined tests

* Find real interface index during NIOPacketInfo tests

* Add PacketInfo tests to Linux tests
2021-07-08 11:04:53 +01:00
d1b7c07883 Adds Equatable and ExpressibleByArrayLiteral conformance to ByteBufferView (#1886)
* Adds Equatable and ExpressibleByArrayLiteral conformance to ByteBufferView

* Adds linux test

* Equatable conformance compares slices of buffers

* Adds Hashable conformance to ByteBufferView

* Runs script for linux tests

* Force unwrap slicing the buffer in ByteBufferView equatable conformance implementation

* Adds Hashable conformance tests

* Addresses comments on test-related changes

* Minor grammar change

* Generates linux tests

Co-authored-by: Matteo Comisso <matteocomisso@skyscanner.net>
Co-authored-by: Matteo Comisso <matteo.comisso@me.copm>
2021-06-30 10:26:40 +01:00
buttaface a1f405285a Fix tests for 32-bit platforms, tested for Android armv7 (#1877)
Motivation:

Get the tests passing on 32-bit platforms again.

Modifications:

- Change the way _UInt56.max is initialized.
- Set the proper max capacity for AdaptiveRecvByteBufferAllocator
  and change the test to match it.
- Add a cmsghdrExample for Android armv7.

Result:

All the same tests pass on Android armv7 as Android AArch64.
2021-06-11 12:20:19 +01:00
David Nadoba 465f87dd7c Random WebSocket Request Key (#1855)
* add randomRequestKey method

* fix some typos

* fix compilation on 5.0

* run generate_linux_tests.rb

* add test with default random number generator

* @inlineable

* base64Encoding @inlineable
2021-05-24 16:02:16 +01:00
David Nadoba 4ded06871a Add method to generate a random mask (#1824)
* add static method to generate a random mask

* use SystemRandomNumberGenerator by default and add documentation

* use WebSocketMaskingKey instead of Self to support Swift 5.0

* add tests for random masking key

* add return keyword to support Swift 5.0

* run scripts/generate_linux_tests.rb

* rename T to Generator

* test SystemRandomNumberGenerator

* Revert "test SystemRandomNumberGenerator"

This reverts commit d9bdbe57ac.

* work around thread sanitizer bug on Swift 5.3
2021-05-24 10:12:36 +01:00
Cory Benfield d161bf6587 Tests should tolerate cpusets. (#1853)
Motivation:

Our current CPU pinning tests do not expect to be pinned to cores that
do not include core 0. That's unnecessary.

Modifications:

- Expect to pin to the first core in our cpuset.

Result:

Tests run inside cpusets.
2021-05-07 11:28:18 +01:00
Cory Benfield e0e289ac0e Rewrite RecvByteBufferAllocator. (#1850)
Motivation:

Platforms with 32-bit integers continue to exist. On those platforms,
the way we calculate the size table for AdaptiveRecvByteBufferAllocator
will trap, as we attempt to compare an Int to UInt32.max as a loop
termination condition.

While I was amending this code, I noticed that
AdaptiveRecvByteBufferAllocator had a number of very strange behaviours,
and was arguably excessively complex. To that end, this patch
constitutes a substantial rewrite of the allocator. To understand what
it does, we need to describe the previous allocator algorithm.

The goal of AdaptiveRecvByteBufferAllocator is to attempt to dynamically
track the throughput of a TCP connection and to minimise the memory
usage required to get it to achieve maximum throughput, within
user-defined constraints. To that end, it implements a fairly simple
resizing algorithm.

At a high level, the algorithm is as follows. The allocator keeps track
of the size of the buffer it is offering the user. When the user reports
how much of that buffer they actually used, the allocator determines
whether better throughput could be achieved with larger allocation
sizes, or whether throughput would not be harmed with smaller allocation
sizes. It then adjusts accordingly.

When does the allocator believe beetter throughput could be achieved
with larger allocation sizes? When the allocation was entirely filled.
If a network recv() entirely fills the buffer, that means there was
likely more data to read that could not be added to the buffer. Improved
throughput would be gained by using larger buffers, as fewer system
calls would be necessary.

Similarly, the allocator believes it could shrink the buffer size
without harming throughput when the recv() uses less memory than the
next buffer size down. However, the algorithm attempts to detect the
possibility that we have "read until the end". The reason this is
relevant is that after a read completes we will often serve other work
on the loop for a while, causing data to pile up. As a result, we don't
want to shrink the buffer if the average read size would be higher, just
because one read happened to be short.

The original implementation's algorithm was based on a bucketed
scheme. For allocation sizes below 512 bytes, the allocation buckets
moved 16 bytes at a time. In principle this gave the allocator 16 byte
granularity. For allocation sizes above 512 bytes, the allocation
buckets would double: 512, 1024, 2048, 4096, and so on, up to
UInt32.max. This, incidentally, was the source of the crash on 32-bit
systems.

Unfortunately, this scheme had a few failings.

Firstly, the implementation complexity was fairly high. The bounds
provided by the user needed to be turned into bucket indices,
necessitating an awkward and complex binary search of the bucket array.
The bucket array itself needed to be generated, forcing a dispatch_once
to guard it and dirtying memory.

Secondly, the scheme was weighted very heavily toward growing memory and
not giving it back. Whenever the buffer was filled and a new size up
wanted to be chosen, the allocator would jump _4_ size buckets. As the
default initial size was 2048 bytes, and the default maximum was 65kB,
the first read of 2048 bytes would cause the allocator to immediately
jump up to allocating 32kB of memory for the next read: a huge leap! It
would then only release memory after two short reads, at which point it
would drop back only 1 bucket, meaning that there was a very aggressive
sawtooth pattern favouring higher memory usage. This pattern favours
benchmarks, where high-throughput localhost connections will naturally
want larger buffer sizes, but it is unnecessarily aggressive for
real-world networks.

Thirdly, the scheme had a bug that would mean it did not require two
_consecutive_ short reads to shrink the buffer, just two short reads
between an increase. This means that it had a tendency not to stabilise:
two "read to the end"s in two different event loop ticks would cause
the buffer to shrink, even if there had been 10 almost-full-reads
in between.

Fourthly, the system would occasionally report that the Channel should
reallocate the buffer because it was larger, when in fact it wasn't:
we'd hit the max, and were never going to get larger. This forced
high-throughput Channels to excessively allocate, albeit only in systems
that customized this allocator (and basically no-one does).

Fifthly, the bucketing system was defeated by ByteBuffer. While having
16-byte granularity was nice in principle, ByteBuffer only allows
power-of-two allocation sizes. This meant that, at the low end, there
were several wasted buckets that were effectively identical. Between 256
bytes and 512 bytes there were 15 redundant buckets!

This last point is the main reason to justify a rewrite. The complexity
of the scheme was in principle justified by having fine, granular
control of allocation sizes. Given that those don't exist, there is no
reason not to simply resort to power-of-two sizing. Once we do that, we
can replace the complex bucketing system by simple shift-and-multiply
math. The effect of this is to produce smaller code (we save about 30%
of the instructions, even as we add some extra safety preconditions)
with no additional branching, and no need to load from a random table in
memory. This avoids the need to keep that table in cache, reducing cache
pressure in the hot read loop. Additionally, we can drop the index into
the table, which lets us save some per-Channel memory, further reducing
cache pressure.

Additionally, constructing one of these is now vastly cheaper. That
matters less (it's not really hot-code), but it does improve Channel
creation time somewhat.

Modifications:

- Remove the size table.
- Round all values to powers of two.
- Implement new "previous power of two" function.
- Cap the allocation size at the largest power of 2 representable in a
  32-bit Int.
- Add more tests.

Result:

The result is less code, simpler code, and faster code. No trapping on
32-bit integer platforms.
2021-05-06 16:44:06 +01:00
David Nadoba 6befe13e23 WebSocket Frame Aggregator (#1823)
* implement and test WebSocketFrameAggregator

* add documentation

* fix review comments

* run scripts/generate_linux_tests.rb

* fix Swift 5.0

* move redundant channel creation into init

* create channel in setUp

* wrap all trys in XCTAssertNoThrow

* cache accumulatedFrameSize

* accumulate buffered frames into the first frames data buffer

* Revert "accumulate buffered frames into the first frames data buffer"

This reverts commit 0f83823f95.

* use channel allocator
2021-04-30 15:39:24 +01:00
Johannes WeissandCory Benfield 903048293b ByteBuffer: more random tests (#1837)
Motivation:

Noticed that in #1835 I still had no tests where genuinely every offset
stored in a ByteBuffer is non-zero.

Modification:

Add a test for that too now.

Result:

More test coverage.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-04-30 13:21:48 +01:00
Johannes Weiss 9edca4aa21 ByteBufferTests: some extra tests around withUnsafeMutableReadableBytes (#1835)
Motivation:

Tests are always good, withUnsafeMutableReadableBytes was undertested
(probably).

Modification:

Add tests.

Result:

Better sleep.
2021-04-30 10:31:46 +01:00
Joakim HassilaandJohannes Weiss 8ea0afb4c4 Added second implementation of liburing as discussed in #1761. (#1804)
Motivation:

As outlined in #1761, io_uring is a new async I/O facility on Linux.

This commit includes a second stab at adding this to SwiftNIO.

Modifications:

Added Uring Selector implementation.

Added liburing support shims.

Disabled one assert that trips during normal usage likely due to async nature of poll updates, for discussion

Added shared kernel sqpoll ring support (can be run with normal user privs in 5.13)

Support for both single shot polls (should work all the way back to 5.1 kernels, needs testing) and multishot streaming polls and modifications for polls (scheduled due in 5.13) for slightly better performance (and better impedance match to SwiftNIO usage)

Added extensive debug logs which can be enabled with -D compiler flags (should likely be removed when bringup and testing is complete)

Adjusted tests.

Added documentation.

Result:

Basic liburing support is in place.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2021-04-29 10:40:27 +01:00
Cory Benfield c6fc49a84a Reduce selector wakeups. (#1820)
Motivation:

Right now all tasks scheduled onto an event loop from a different loop
wake up the underlying selector by writing to an eventfd. This is a
fairly inefficient way to handle things: it incurs a lot of syscall
traffic unnecessarily.

Given that we currently protect the pending tasks queue with a big dumb
lock, we can safely keep track of whether we're going to dequeue this
task. If we are, we don't need to wake the selector.

Modifications:

- Keep track of whether we're de-queueing tasks or not.
- Arrange to wake the selector only once.

Result:

Cheaper task enqueueing on hot loops.
2021-04-28 15:09:07 +01:00
Cory Benfield 21782f3bdc Implement reserveCapacity for CircularBuffer. (#1819)
Motivation:

While spelunking through the code I noticed we called
CircularBuffer.reserveCapacity, but never actually implemented it. This
means it never did anything. It should do something.

Modifications:

- Implemented reserveCapacity.

Result:

reserveCapacity does something now.
2021-04-26 14:10:43 +01:00
Johannes Weiss e2990d9672 refactor registration IDs (#1801)
Motivation:

Instead of manual shifting / masking we can write the whole registration
ID code normally in Swift.

Modifications:

Refactored RegistrationID to use Swift instead of shifting / masking.

Result:

Nicer code.
2021-04-23 12:43:30 +01:00
Johannes Weiss 06ce11fb82 generic integer bit packing (#1807)
Motivation:

With the registration ID refactoring (#1801) we'll now have the third
reimplementation of integer bit packing. Three is one too many, let's
make it generic.

Modifications:

Introduce generic integer bit packing and use it for _UInt56/24.

Result:

- Less bit packing code.
- Will simplify #1801
2021-04-22 15:02:47 +01:00
Johannes Weiss a305518d88 implement CircularBuffer.first: to prevent allocs (#1814)
Motivation:

Due to https://bugs.swift.org/browse/SR-14516 , we sometimes get
allocating (!?) `subscript.read` accessors in the CircularBuffer.first
depending on the `Element` type...

Modifications:

Implement `CircularBuffer.first` instead of inheriting it from
Collection.

Result:

Fewer allocs in some cases.
2021-04-22 13:34:14 +01:00
Fabian Fett e02d1fec02 Fix crash: Create ByteBuffer Slice from ByteBuffer Slice after 16MB (#1813)
Fixes an issue that could lead to an assert in Debug mode and to undefined behavior in Release mode.

Motivation:

When reading a new ByteBuffer slice from an originating ByteBuffer slice where the new ByteBuffer slice starts more than 16MiB into the underlying ByteBuffer storage, the new ByteBuffer slice will get a new 0 based storage.
When creating the storage for the new slice we have an issue in where storage based indices were used which should have been slice based indices.

Modifications:

Using the correct indices, when creating a ByteBuffer slice which is more than 16MiB into its originating storage.

Result:

We can create ByteBuffer slices from slices after the 16MiB threshold.
Fixes an issue that was raised in PostgresNIO
2021-04-22 11:08:36 +01:00
Johannes Weiss f7918a80f1 support qemu: qemu returns ENOPROTOOPT for unknown socket opts (#1806)
Motivation:

When running SwiftNIO under Qemu, then one test case fails because it
expects `ENOTSOCK` but Qemu returns `ENOPROTOOPT`. This is a Qemu bug.

Modification:

Accept `ENOTSOCK` or `ENOPROTOOPT`.

Result:

Test suite works under Qemu.
2021-04-15 11:30:26 +01:00
Joakim Hassila f0b825f9b7 Add sequenceIdentifier to Registrations to handle outdated events robustly. (#1799)
Motivation:

Currently the selector implementation just discards all pending events from the kernel when a deregistration
has occurred during the event loop tick. This has been needed to not fail the test testWeDoNotDeliverEventsForPreviouslyClosedChannels.

A cleanup case has been around for a while at: https://github.com/apple/swift-nio/issues/381

And when discussing this in https://github.com/apple/swift-nio/pull/1788 (to solve https://github.com/apple/swift-nio/issues/1761)

we came to an agreement that the solution with tagging registrations on the backend would not suit only io_uring,
but also solve the issue robustly for kqueue and epoll.

Modification:

Added sequenceIdentifier to the Registration and add support for it throughout.
Mask in sequence identifier into user data in both kqueue and epoll.
In kqueue, we just store the sequence identifier in the udata field (to support 32-bit properly).
In epoll, where we know we have 64-bits, we mask it in together with fd.
Removed all references to the old workaround from #381.

Result:

- New solution that doesn't need to discard all events when deregistrations are done during the event loop tick.
- fixes #381
2021-04-13 10:35:41 +01:00
ed0b013c57 Split Selector into separate files per backend. (#1795)
Motivation:
Currently all backends are platform-conditional in the `Selector` code, making it
harder to read and difficult to extend for future new backend implementations.
By splitting the `Selector` into a generic part and per-backend platform implementation
it is easier to add additional backends in the future.

Modifications:
Split Selector into `SelectorGeneric`, `SelectorEpoll` and `SelectorKqueue`.
Add a _SelectorBackendProtocol that should be implemented by actual backends.
Fixed tests.

Result:
- Easier to read code
- Makes it easier to add new backends

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2021-04-09 16:49:02 +01:00
5c469aba3d Add an initialiser to EmbeddedChannel that adds multiple ChannelHandlers
Motivation:

I have several use-cases in my tests where it's necessary to have an EmbeddedChannel with multiple ChannelHandlers.

Modifications:

Add an initialiser that takes an array of ChannelHandlers, and adds them to the ChannelPipeline.

Result:

Previously:

let embeddedChannel = EmbeddedChannel(handler: ...)
try! embeddedChannel.pipeline.addHandlers([...]).wait()

Now:

let embeddedChannel = EmbeddedChannel(handlers: ...)

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2021-04-09 15:22:35 +01:00
George Barnett f63571296d Add 'promise' versions of EventLoopFuture.{and,when}All{succeed,complete} (#1794)
Motivation:

Most NIO APIs have two versions: one accepting a promise (often
optional) and another which returns a future. Many applications and
frameworks built on top of NIO also use this pattern. To maximise
composability we should try to provide both versions where possible.

Modifications:

Add versions of `andAllSucceed`, `andAllComplete`, `whenAllSucceed`
and `whenAllComplete` which accept an `EventLoopPromise` in place of
an `EventLoop` and defer the implementation of the future versions to
the promise versions.

Result:

- Better composability.
- Fewer allocations if the caller already has a promise.
2021-04-08 09:38:50 +01:00
David Evans 97919c94f9 Better error type for inactive thread pools (#1787)
* Better error type for inactive thread pools

* Soundness

* Typos

* PR comments

* Defer ELG shutdown

* Remove redundant try
2021-03-22 10:01:39 +00:00
George Barnett d22d89804c Add assertion helpers for NIOHTTP1TestServer (#1760)
Motivation:

Verifying the contents of inbound request parts for `NIOHTTP1TestServer`
can be quite tedious and whenever I use `NIOHTTP1TestServer` in
different projects I find myself writing similar extensions to help
verify the inbound request parts are as expected.

Modifications:

- Add verification methods to `NIOHTTP1TestServer` which checks for the
  expected part and optionally verifies it further in a callback

Result:

It's easier to test with NIOHTTP1TestServer
2021-03-03 10:20:55 +00:00
David Evans 740e3a875a Fix tests in release mode (#1769) 2021-02-26 16:33:19 +00:00
George Barnett 178636d999 Use the pre-succeeded void future when possible for async pipeline operations (#1766)
Motivation:

We added synchronous pipeline operations to allow the caller to save
allocations when they know they are already on the correct event loop.
However, we missed a trick! In some cases the caller cannot guarantee
they are on the correct event loop and must use an asynchronous method
instead. If that method returns a void future and is called on the event
loop, then we can perform the operation synchronously and return a
cached void future.

Modifications:

- Add API to `EventLoop` for creating a 'completed' future with a
  `Result` (similar to `EventLoopPromise.completeWith`)
- Add an equivalent for making completed void futures
- Use these when asynchronously adding handlers and the caller is
  already on the right event loop.

Result:

- Fewer allocations on the happiest of happy paths when adding handlers
  asynchronously to a pipeline.
2021-02-25 13:08:00 +00:00
Johannes Weiss de3c2dba50 HTTP server upgrade tests: cosmetic improvements (#1763)
Motivation:

The HTTP server upgrade tests had unncessarily wide and also verbose
test assertions.

Modifications:

Rewrote them much simpler and narrowed what states are allowed.

Result:

- Neater code
- Works around https://bugs.swift.org/browse/SR-14253
2021-02-23 15:34:37 +00:00
George Barnett 9451f4ac6f Add synchronous channel options (#1755)
* Add synchronous channel options

Motivation:

The functions for getting and setting channel options are currently
asynchronous. This ensures that options are set and retrieved safely.
However, in some cases the caller knows they are on the correct event
loop but still has to pay the cost of allocating a future to either get
or set an option.

Modifications:

- Add a 'NIOSynchronousChannelOptions' protocol for getting and setting
  options
- Add a customisation point to 'Channel' to return 'NIOSynchronousChannelOptions'.
- Default implementation returns nil so as to not break API.
- Add implementations for 'EmbeddedChannel' and 'BaseSocketChannel'
- Allocation tests for getting and setting autoRead

Results:

Options can be get and set synchronously.
2021-02-22 11:07:30 +00:00
Johannes Weiss 8b062c0317 SAL: more sync between test and EL threads (#1749)
Motivation:

The SAL (Syscall Abstraction Layer) virtualises pretty much all system
resources that NIO uses, except time and threads. That means that unless
explicitly made sure, the EL thread and the test thread run at their own
pace.

The synchronisation point is whenever the EL thread makes a
(virtualised) syscall which the test thread then sees (and asserts).

The problem in #1748 was that we were assuming that the EL thread would
park itself very fast. So when the test driver thread came along to
execute something on the EL, it just assumed that the EL has already
parked (ie. waited for a wakeup). Seemingly that works most of the time
but not always.

Modifications:

- Always actually wait for the EL to park itself.
- Delete duplicated code in `salWait` to use `runSAL`
- fixes #1748

Result:

Fewer races.
2021-02-17 08:33:22 +00:00
George Barnett 63d356819c Add synchronous pipeline operations (#1741)
Motivation:

`ChannelPipeline` is explicitly thread-safe, any of the operations may
be called from outside of the channel's event loop. However, there are
often cases where it is known that the caller be on the right event
loop, and an asynchronous API is unnecessary.

In some cases -- such as when a pipeline is configured dynamically and
handlers are added from the 'channelRead' implementation of one handler
-- it forces the caller to write code that they might not actually need:
such as buffering events which may happen before the future completes.
This is unnecessary complexity when the caller knows that they must
already be on an event loop.

Modifications:

- Add a 'SynchronousOperations' view to the 'ChannelPipeline' which is
  available to callers via 'syncOperations'.
- Supported operations include: adding a handler, adding multiple
  handlers, retrieving a context via various predicates and retrieving a
  handler of a given type.
- Some of the operations in 'ChannelPipeline' were refactored to have an
  explicitly synchronous version, asynchronous versions complete their
  promise based on the result of these calls.
- Various minor documentation fixes and addition of 'self' where it was
  not used explicitly.

Result:

Users can perform synchronous operations on the 'ChannelPipeline' if
they know they are on the right event loop.
2021-02-09 09:59:41 +00:00
Johannes Weiss c5a214f075 B2MD: Don't try to reclaim if continuing to parse (#1733)
Motivation:

B2MD called out to the decoder's `shouldReclaimBytes` after every
parsing attempt, even if the parser said `.continue`.

That's quite pointless because we won't add any bytes into the buffer
before we're trying the parser again.

Modifications:

Only ask the decoder if we should reclaim bytes if the decoder actually
says `.needMoreData`.

Result:

Faster, better, more sensible.
2021-01-29 17:03:04 +00:00
Fabian Fett 6b41c18bf6 Fix Codec memory reclaim bug (#1729) 2021-01-21 20:32:20 +00:00
Fabian Fett 76b4637122 Make language more welcoming (#1728) 2021-01-21 12:45:46 +00:00
Cory Benfield 8ea768b0b8 Add static vars for common HTTP versions (#1723)
Motivation:

I'm sick of typing `.init(major: 1, minor: 1)`.

Modifications:

- Added static vars for common HTTP versions.

Result:

Maybe I'll never type `.init(major: 1, minor: 1)` ever again.
2021-01-19 17:27:02 +00:00
Johannes Weiss 2b821b2ef6 Specialise succeeded Void futures so we allocate less (#1703)
Motivation:

Succeeded `EventLoopFuture<Void>`s are quite important in SwiftNIO, they
happen all over the place. Unfortunately, we usually allocate each time,
unnecessarily.

Modifications:

Offer `EventLoop`s the option to cache succeeded void futures.

Result:

Fewer allocations.
2021-01-15 17:07:15 +00:00
Cory Benfield 1a2996bfc5 Revert "Retry on EPROTOTYPE on socket writes. (#1706)" (#1707)
This reverts commit 4853e910e8.

While we have been able to observe the effect that this change was
trying to workaround, the change seems to interact poorly with a
different issue in Big Sur that can cause EPROTOTYPE to be consistently
emitted during socket writes on otherwise connected sockets. This would
change a connection-terminating error into a 100% CPU spin that rendered
the event loop entirely useless: a substantial regression.

For this reason, we should back this out until the issue is better
characterised.
2020-12-18 15:32:53 +00:00
Cory Benfield 4853e910e8 Retry on EPROTOTYPE on socket writes. (#1706)
Motivation:

When writing to a network socket on Apple platforms it is possible to
see EPROTOTYPE returned as an error. This is an undocumented and
special-case error code that appears to be associated with socket
shutdown, and so can fire when writing to a socket that is being shut
down by the other side. This should not be fired into the pipeline but
instead should be retried.

Modifications:

- Retry EPROTOTYPE errors on socket write methods.
- Add an (unfortunately) probabilistic test bed.

Result:

Should avoid weird error cases.
2020-12-17 17:45:23 +00:00
George Barnett 8b47ef29a8 Fix casing of 'SocketAddress.init(packedIpAddress:port:)' (#1698)
Motivation:

A new init was added to `SocketAddress` in #1692, but the casing of
`packedIpAddress` is incorrect, it should be `packedIPAddress`. This
hasn't been released yet so let's fix it while we still can!

Modifications:

- s/packedIpAddress/packedIPAddress

Result:

More consistent API
2020-11-30 17:51:12 +00:00
buttafaceandCory Benfield 44d67ba4e0 Update and finish Android port. (#1695)
Motivation:

Be able to run and test swift-nio on Android.

Modifications:

- Remove the custom ifaddrs and use the one from the Android NDK instead.
- Enable a bunch of conditionally-compiled code for Android.
- Add a handful of constants and other Android declarations.
- Cast some types because of mismatches specific to Android.

Result:

Most tests pass on Android AArch64 and ARMv7.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-11-27 11:16:11 +00:00
Rémi DoreauandCory Benfield da6cc5141c Create SocketAddress from packed byte representation (#1692)
Motivation:

A user should be able to create SocketAddress from packed bytes representation.

Modifications:

I added a new SocketAddress initializer which takes the IP address in ByteBuffer form. I have also added tests that ensure the initializer works properly.

Result:

We have a new way to initialize a SocketAddress from a byteBuffer.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-11-27 10:18:47 +00:00
2f9ea47738 Conform TimeAmount to AdditiveArithmetic (#1691)
Conforms TimeAmount to AdditiveArithmetic.

Motivation:
TimeAmount does not support -=, +=. Sometimes it is useful to manipulate time amounts when building up a delay and if that iteration fails, we would want to delay += .milliseconds(5) to add 5 milliseconds to our delay and try again.

Modifications:
Conformed TimeAmount to AdditiveArithmetic: added a static zero property and required operators.

Result:
TimeAmount conforms to AdditiveArithmetic.

Co-authored-by: Josh <jrtkski@icloud.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-11-17 15:30:17 +00:00
Saleem Abdulrasool 20e63d07dc NIO: extract control message handling into a separate protocol (#1678)
These are part of the BSD sockets APIs, but not directly related to the
socket interfaces.  Create an extension point to permit the different
platforms to shuffle their implementation into place.  This provides a
nicer spelling for the functions and enables the codepaths on Windows as
well.
2020-10-19 16:18:57 +01:00
AndriusandCory Benfield e6b7d718a8 HTTPObjectAggregator implementation (#1664)
* HTTPServerObjectAggregator for requests

* Apply suggestions from code review

Co-authored-by: Cory Benfield <lukasa@apple.com>

* most of code review comments addressed

* tidy up state machine close

* bad line breaks

* more verbose error reporting

* removes expect:continue functionality due to #1422

* public type naming and error handling tweaks

* wrong expectation in test

* do not quietly swallow unexpected errors in channelRead

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-10-08 11:37:32 +01:00
Graeme Jenkinson b5c1696033 Provide a convenience API for dispatching blocking work (#1563) (#1662)
Motivation:

SwiftNIO lacks a convenience API for performing blocking IO / tasks. As
this is a fairly common task it then requires the clients to make ad hoc
implementations that address this requirement.

Modifications:

Extension to DispatchQueue with the following method to schedule a work
item to the `DispatchQueue` and return and `EventLoopFuture` for the
result returned:

- `asyncWithFuture<NewValue>(eventLoop: EventLoop, _ callbackMayBlock: @escaping () throws -> NewValue) -> EventLoopFuture<NewValue>`

Added new unit tests for this function both when the promise succeeds
and fails.

Extention to EventLoopFuture with the following public functions:

- `flatMapBlocking<NewValue)(onto queue DispatchQueue, _ callbackMayBlock: @escpaing (Value) throws -> NewValue) -> EventLoopFuture<NewValue>`
- `whenSuccessBlocking(onto queue DispatchQueue, _ callbackMayBlock: @escaping (Value) -> Void) -> EventLoopFuture<NewValue>`
- `whenFailureBlocking()onto queue DispatchQueue, _ callbackMayBlock: @escaping (Error) -> Void) -> EventLoopFuture<NewValue>`
- `whenCompleteBlocking(onto queue DispatchQueue, _ callbackMayBlock: @escaping (Result<Value, Error>) -> Void) -> EventLoopFuture<NewValue>`

These functions may all be called safely with callbacks that perform blocking IO / Tasks.

Added new unit tests to EventLoopFutureTest.swift for each new function.

Result:

New public API for `EventLoopFuture` that allows scheduling of blocking IO / Tasks.
2020-09-30 17:04:21 +01:00
Graeme Jenkinson 7c42e5a45d A helper for easily unwrapping Optional values in an EventLoopFuture (#1656)
Motivation:

Unwrapping an `Optional` value from an `EventLoopFuture` is a fairly
common requirement that currently involves the client writing
boilerplate code, for example:

```
extension EventLoopFuture {
    func unwrapOptional<T>(orError error: Swift.Error) -> EventLoopFuture<T> where Value == T? {
        self.flatMapThrowing { value in
            guard let value = value else {
                throw error
            }
            return value
        }
    }
}
```

As this is a fairly common requirement adding an extension of
`EventLoopFuture` to unwrap `Optional` values would remove this
burden from clients.

Modifications:

Added Extension to `EventLoopFuture` containing the following functions:

- `unwrap<NewValue>(orError: Error)`: Unwraps a future returning a new
  `EventLoopFuture` with the same value as the resolved future when
  its value is Optional.some(...)`, otherwise the `Error` passed in
  the `orError` parameter is thrown

- func unwrap<NewValue>(orReplace: NewValue)`: Unwraps a future returning a new
  `EventLoopFuture` with either: the value passed in the `orReplace`
  parameter when the future resolved with value `Optional.none`, or
  the same value otherwise.

- func unwrap<NewValue>(orElse: @escaping ()- > NewValue): Unwraps a future
  returning a new `EventLoopFuture` with either: the value returned
  by the closure passed in the `orElse` parameter when the future
  resolved with value `Optional.none`, or the same value otherwise.

Added new unit tests for each new `unwrap(orXXX:)` function.

Result:

Client's no longer have to write their own boilerplate code.
2020-09-30 13:47:14 +01:00