Motivation:
Network congestion can be controlled without packet loss if explicit congestion notification messages are understood.
Modifications:
Receive single and vector paths to get notification and surface.
Send paths for both single and vector sends.
Round trip tests.
Storage for control messages added in a reusable way.
I have tested allocations and they seem to be fine but the allocation tests for vector read and write were not stable enough to sensibly add to CI.
Result:
Explicit Congestion Notifications can be both sent and received.
Motivation:
ECN information is held in metadata.
As part of the path to writing ECN to the network the
required state needs to pass through PendingDatagramWritesManager.
Modifications:
Add an extra metadata field to PendingDatagramWrite and ensure
this data is passed to the correct write method.
Result:
Nothing visible - just preparation for actual ECN send.
Motivation:
This needs to be possible so users can specify what
ECN status they wish to send. The auto-generated
initialiser is internal.
Modifications:
Add public initialiser to AddressedEnvelope.Metadata
Add public initialiser to AddressedEnvelope taking Metadata
Result:
Users will be able to construct AddressedEnvelopes with Metadata set.
Motivation:
cmsghdrs can be used to send an receive extra data on UDP packets.
For example ECN data.
Modifications:
Map in Linux and Darwin versions of cmsghdr macros as functions.
Create strctures for holding a received collection; parsing ecn
data from a received collection and building a collection suitable
for sending.
Result:
Functions to manipulate cmsghdr and data exist.
Motivation:
sendmsg is more powerful - this is paving the way for
Explicit Congestion Notifications to be sent.
Modifications:
Replace the sendto system call with sendmsg up to DatagramChannel.
Result:
Sendmsg will be used to send UDP data.
Motivation:
The socket address types are some of the worst types for handling in
Swift. They pervasively type-pun in a way that Swift strongly wants to
resist, and they expose a bunch of data through awkward fixed-length
arrays.
We've done a number of passes over this code to improve its pointer
hygeine. This is another one. Here, we remove some uses of the memory
binding APIs that were unnecessary, and that can instead take advantage
of the way Swift handles binding memory of homogeneous tuple types.
In Swift, whenever we have a homogeneous tuple (i.e. a tuple whose
elements are all the same type), that memory is actually bound to _two_
types: to the tuple type, and to the type of the elements. This allows
us to use `assumingMemoryBound(to:)` to convert between the pointer to
the tuple and the pointer to the first element of the tuple.
This knowledge lets us remove calls to `bindMemory` and
`withMemoryRebound`. Neither call is correct to use in this situation,
and while we were unlikely to encounter any damage, this is the best
possible use of the Swift pointer APIs for this work.
Modifications:
- Rewrite accesses to the UNIX domain socket path to use appropriately
typed pointers without binding or rebinding memory.
- Added some assertions about the static types of the stored elements.
Result:
Better management of pointer type bindings.
Motivation:
When attempting to obtain metadata about a read, we need to use recvmsg
in order to obtain that data. While we're using recvmmsg for vector
reads right now, our scalar reads use recvfrom, which does not provide
us with that metadata.
While we're not extracting metadata right now, we may well do so in
future, so we can apply it now.
Modifications:
- Move recvfrom usage to recvmsg.
Result:
We'll be able to extend recvmsg to extract metadata.
Motivation:
Split out the internal implied BSD socket API code to allow alternative implementations of these interfaces on other platforms.
Modifications:
- Split the code apart.
- Provide POSIX and Windows implementations of the BSD socket API.
Result:
Should be easier to run NIO unmodified on Windows.
Motivation:
Fixes: #1334
Modifications:
ELF hops on the correct EL before executing.
Result:
Fixes precondition failure, caused by being on the wrong ELG.
Motivation:
Our API documentation claims that NIOThreadPool.start() will tolerate
being called multiple times. However, this wasn't actually true: in
debug mode it'd hit an assertion, and in release mode it would quietly
orphan all its threads and replace them with new ones, leaving there
with twice as many threads and some that wouldn't be closed down.
We should support the functionality we claim we do.
Modifications:
- Fixed the incorrect check for running thread pool state.
- Added a test to validate we actually allow multiple starts.
Result:
Thread pools really can be started multiple times.
Motivation:
TimeAmount wasn't `Hashable` and there's no clear reason it shouldn't
be.
Modifications:
Add synthesized `Hashable` conformance to `TimeAmount`
Result:
`TimeAmount` is hashable.
Motivation:
`EmbeddedEventLoop` executes scheduled tasks in their run-time order.
If multiple tasks are scheduled for the same time then the order in
which they are eventually executed is undefined.
Since `execute` defers to scheduling a task for "now" it is possible for
tasks to be executed out of order if `run()` is not called between each
execute.
In "real" event loops this isn't an issue because the system time must
advance between each call to `execute`.
Modifications:
- Add a 'insertionOrder' to `EmbeddedScheduledTask`; use it to break
ties when comparing two tasks with the same run time
- Add a task counter to `EmbeddedEventLoop` which is used to provide an
insertion order when scheduling tasks.
Result:
- EmbeddedEventLoop will `execute` tasks in order
Motivation:
You can schedule tasks for a deadline on `EmbeddedEventLoop` but have no
way of knowing the current time on the `EventLoop` and how much to
advance the time by in order to meet that deadline. In most cases this
is okay because you know that time starts at zero and you can keep track
of time, however, it's generally useful to not have to keep track of
this yourself.
Modifications:
- Add `advanceTime(to:)` on `EmbeddedEventLoop`
- Document that time may be controlled on `EmbeddedEventLoop` and how to
advance it
- Tests
Result:
- `EmbeddedEventLoop` is more usable with deadlines
- Better documentation
Motivation:
Guide novice users towards the options they are most likely to want to use.
Modifications:
New type to represent shorthand TCP client options containing only the options
which are sensible for novice users.
New type to represent a collection of these options.
A method to allow underlying bootstraps to override universal behaviour - default
implementation is to do nothing.
A test case to demonstrate that shorthand options match old style options.
A test case to demonstrate that overriding option behaviour is possible.
Result:
For universal botostrap there will be an new way of setting options involving
less typing which guides the user towards the common options.
Motivation:
NIO users need to understand the semantic of the underlying protocol.
Therefore NIO does not (and in many case cannot) check all the
invariants. Generally however, we try to be helpful and assert a bunch
of things that a user has (hopefully) checked. That doesn't affect
performance and simplifies development for users.
Modifications:
- assert that request/response heads don't set content-length +
transfer-encoding: chunked
Result:
Developers of libraries like AHC will have an easier time.
Motivation:
It's 2020, we shouldn't use unnecessary offensive, insulting, or
outdated language.
Modifications:
Fix a few examples.
Result:
More inclusive.
Motivation:
Previously, if we scheduled EventLoop executions from the promises we
failed during EventLoop shutdown, we'd blow up. Thanks to @fabianfett
for the bug report.
Modifications:
Set the EL state to 'exiting thread' only after we failed all
outstanding tasks.
Result:
Fewer crashes.
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
There are multiple sub-optimal ByteBuffer creation patterns that occur
in the wild. Most often they happen when people don't actually have
access to a `Channel` just want to "convert" a `String` into a
`ByteBuffer`. To do this, they are forced to type
var buffer = ByteBufferAllocator().buffer(capacity: string.utf8.count)
buffer.writeString(string)
Sometimes, they don't get the capacity calculation right or just put a
`0`.
Similar problems happen if NIO users want to cache a ByteBuffer in their
`ChannelHandler`. You will then find this code:
```swift
if self.buffer == nil {
self.buffer = receivedBuffer
} else {
var receivedBuffer = receivedBuffer
self.buffer!.writeBuffer(&receivedBuffer)
}
```
And lastly, sometimes people want to append one `ByteBuffer` to another
without mutating the appendee. That's also cumbersome because we only
support a mutable version of `writeBuffer`.
Modifications:
- add `ByteBuffer` convenience initialisers
- add convenience `writeBuffer` methods to `Optional<ByteBuffer>`
- add `writeBufferImmutable` which doesn't mutate the appendee.
Result:
More convenience.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Sometimes it can be useful to use NIOPipeBootstrap with a single file
descriptor, like a serial line. Previously however we would only accept
two distinct fds (without checking they're distinct...).
Also, we didn't correctly check file types.
Modifications:
- also support NIOPipeChannel for streams that have just 1 fd
- fix file type check
- check that the 2 fds are distinct in withPipe(fds...)
Result:
- more functionality
- fewer bugs
Motivation:
It's often very important to test that in certain cases we actually
crash with a certain error message whilst having access to all of NIO.
Modifications:
Add a crash tester test suite.
Result:
We can test crashers.
Motivation:
In general there's no good justification for `SocketAddress` not to be
`Hashable`: it's a well-formed value type that can easily have a
clearly-defined version of hashability defined. In particular, we have
a clear definition of equatability for this type already present in the
code.
This makes SocketAddress more broadly useful in a range of
circumstances.
Modifications:
- Defined `Hashable` for `SocketAddress`.
- Fixed broken `Equatable` implementation for `SocketAddress`.
Result:
Users can obtain the hash value of `SocketAddress`.
Motivation:
Previously, if the user sent us a 0 length chunk, we would encode it as
`0\r\n\r\n` which means the _end_ of the body in chunked encoding. But
the end in NIO is send by sending `.end(...)`.
Modifications:
Don't write anything for 0 length writes.
Result:
More correct behaviour with 0 length body chunks.
Motivation:
The current System.coreCount implementation relies on _SC_NPROCESSORS_ONLN so isn't cgroups aware which might have a bad impact for apps runnings in containers (e.g. Docker, Kubernetes, Amazon ECS...).
Modifications:
- Changed System.coreCount on Linux only to make it read from CFS quotas and cpusets when present.
- Removed incorrect precondition in Sources/NIO/LinuxCPUSet.swift
Result:
System.coreCount returns correct values when apps run in containers.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
It's not obvious what happens when `childChannelInitializer` returns a
failed future.
Modifications:
Add a note to the `childChannelInitializer` documentation.
Result:
Better docs.
Motivation:
We know that on Darwin (eg. when the other end of a TCP connection reset
_really_ early on) F_SETNOSIGPIPE sometimes fails. We thought we could
handle it but we weren't able to handle everywhere.
Modifications:
- make us survive it everywhere
- tests
Result:
- Fewer crashes with ClientBootstrap.withConnectedSocket
Motivation:
Currently the best, or at least simplest, way to schedule a delayed asynchronous task and wait on its complete result is something like `eventLoop.scheduleTask(in: ...) { return somethingAsync(...) }.futureResult.flatMap { $0 }`. This is not only unobvious but also a bit ugly.
Modifications:
I have added methods which correspond to scheduleTask() in the same way flatSubmit() does to submit(). The returned Scheduled<T> object allows cancellation of the asynchronous task's execution in the same way that is possible for synchronous scheduled tasks, and the futureResult does not complete until the entire asynchronous task does. Callers wishing to wait only for submission of the delayed task, rather than its overall completion, may continue to use the existing scheduleTask() APIs to do so. Tests have been added to verify that the behavior of the new methods is as expected.
These changes are purely additive.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
Usually, you spawn a new MultiThreadedEventLoopGroup to run NIO
programs. But if you're a very simple command line utility, that may not
be necessary, so why not just re-use the main thread?
Modifications:
Allow taking over threads and making them EventLoops.
Result:
Fewer threads if you want.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
The names of most of the BSD socket option values were brought over into
their NIO helper properties, with their namespace removed. This vastly
increases the risk of collision, particularly for things like TCP_INFO,
which just became .info.
Modifications:
- Added the prefixes back, e.g. `.info` is now `.tcp_info`.
- Renamed socket type `.dgram` to `.datagram`, as this is the nice clean
API and we should use nice clean names.
Result:
Better APIs
Motivation:
It is valuable to be able to provide additional context for any kind of assertion failure, such as obvious points of API misuse or when the purpose of the assertion itself is unclear.
Modifications:
Added an overload of preconditionInEventLoop() that accepts a message autoclosure parameter in the same fashion as `Swift.precondition(_:file:line:)`. Default the implementation of the original version to calling the new one with an empty message. Add defaulted implementation of the new version which forwards the message closure to precondition(). Add the new message parameter directly to assertInEventLoop() without a forwarder since it is not a customization point.
Result:
It is now possible to optionally provide explanatory messages to be included when the "in event loop" precondition fails, as with any other precondition.
Add Optional ECN MetaData to Addressed Envelope
Motivation:
This is a very small step along the path to #1472
Modifications:
Add an optional metadata field to addressed envelope. Currently the only possible data is ECN information. This is not currently populated anywhere.
Result:
Metadata in place for future work.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Newer Swift 5.3 snapshots have spotted more vars that could be lets.
Modifications:
Made two vars lets.
Result:
The word `let` appears more frequently; the word `var`, less so.
This finishes up the encapsulation that is required to ensure that we
are not leaking libc interfaces to clients but instead vend an
enumeration that they can use. The enumeration is open so although we
may not have the full interface enumerated, users will not be prevented
from using alternate values.
Motivation:
In one of the previous patches, we accidentally merged the deprecation
of `ChannelOptions.Types.SocketOption.init` which will break a lot of
NIO programs.
Modifications:
Undo the deprecation.
Result:
NIOTS builds without warnings.
This adds a new enumeration which encapsulates the socket type values.
This enables ports to provide the same surface with a different name as
necessary.
* NIO: Add new `BSDSocket` namespace
This starts the split of the POSIX/Linux/Darwin/BSD interfaces and the
BSD Socket interfaces in order to support Windows. The constants on
Windows are not part of the C standard library and need to be explicitly
prefixed. Use the import by name to avoid the `#if` conditions on the
wrapped versions. This will allow us to cleanly cleave the dependency
on the underlying C library.
This change adds a `BSDSocket.OptionLevel` and `BSDSocket.Option` types
which allow us to get proper enumerations for these values and pipe them
throughout the NIO codebase.
* Apply suggestions from code review
Co-Authored-By: Cory Benfield <lukasa@apple.com>
Motivation:
Today, we just expect the ELGs passed to the bootstraps to be the
correct ones, if not, we crash.
Modifications:
Offer an alternative `validatingGroup:` `init` that just returns `nil`
if the ELGs are of the wrong types.
Result:
Easier to work with multi-stack systems for example when the user might
pass an ELG for either NIO on Sockets or NIO on Network.framework.
Motivation:
Previously, NIOThreadPool would use super long thread names. Linux
doesn't allow more than 15 bytes (+ \0 char) so in the end they would
never get set at all.
Modifications:
- Shorten NIOThreadPool's thread names
- Only take the first 15 characters of thread names in general on Linux
Result:
We don't lose thread names on Linux.