Motivation:
Peter thinks that result-erasing maps should not allocate, and we have
special code paths in the code to try to make Void -> Void maps not
allocate. Sadly, both code paths currently do allocate.
Per our rules for not trying to make optimizations without data, we
should start measuing these closures so we can make optimizations.
Modifications:
- Added an alloc couter test for result-erasing maps.
Result:
Alloc counter test suitable for any fix of #1697.
Motivation:
Allocation counter tests are good, and we aren't measuring this today.
Modifications:
- Wrote some add/remove tests that use different remove functions.
Result:
Better insight into performance.
Motivation:
The allocation counter test framework only supports a single shared
file which is quite limiting, especially if you rely on generated code.
Modifications:
- The '-s' option can now be passed multiple times
- The symlink name for any of the passed files will be the basename of
the provided file rather than 'shared.swift'
Result:
Allocation counter test framework can use more than one shared file.
* 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.
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.
Motivation:
The alloc counters need to store the pointer to the original libc
implmentations of the hooked functions somewhere. Previously, we would
store them in thread locals. That works fine but creates quite some
overhead (and allocations) per thread (to do dlsym on every thread).
Modifications:
Instead, we now store the libc function pointers in (atomic) globals so
we need to only resolve each function once, no matter how many threads
we use.
Result:
Faster, and more accurate.
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.
* Add allocation test for adding multiple handlers
Motivation:
I believe there is at least 1 avoidable allocation in this area.
Even if there isn't, making sure we don't increase allocations is good.
Modifications:
Add a test of allocations when adding multiple handlers.
Set limits for docker images.
Result:
Allocations when adding multiple handlers are now checked.
* Remove an allocation from addHandlers
Motivation:
Fewer allocations should improve performance.
Modifications:
Split out a sub function from addHandlers.
I originally thought I'd have to change the part of this
function which reads `var handlers = handlers` as there was
a surprising allocation at the beginning of this function.
It seems that breaking out some of the logic is sufficient
to remove an allocation.
Result:
1 fewer allocation.
* Fix up alloc tests.
Motivation:
It's possible relaying ECN information will cause allocations.
Having a test which uses them will ensure this doesn't happen.
Modifications:
Added metadata data to always send ECN state and set a channel
option requesting to recieve it.
Result:
Allocation test will attempt to send and receive ECN data.
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:
There is at least a theoretical race to flush before close in prior version.
Having terrible code in the NIO repo is asking for someone to copy it.
Modifications:
flatMap the various parts of the client together which also ensures the
flush is complete before close is called.
Result:
Slightly nicer code, slightly fewer allocations.
Motivation:
so_reuseaddr on linux allows multiple binding to the same port simultaneously - this has not been seen to happen in practice but it is best to be cautious.
Modifications:
Remove address reuse from the UDP allocation tests.
Result:
Reduced danger of binding the same port twice.
Motivation:
Hanging tests make doing work and asserting correctness very difficult.
Modifications:
Remove address reuse from the server side of the udp channel.
Result:
The tests no longer hang.
(The reason things we hanging was that the client side was occasionally getting assigned the same port number as the server side (extremely agressive port reuse)
Motivation:
The Swift runtime is now using malloc_zone_*, we need to implement
replacements for these too. This is just a first pass, eventually, we
should implement _all_ replacements as `malloc_zone_memalign` which is
powerful enough to implement all others.
Modifications:
Provide new replacements.
Result:
Alloc tests work again on macOS.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
We now have sufficiently many integration tests that the number of TCP
sockets in TIME_WAIT begins to cause resource pressure on the system.
This can lead to the integration tests failing due to being unable to
assign a socket.
We can force this to not happen by disabling linger. As we're running on
a lossless fabric (localhost), this is entirely safe.
Modifications:
- Disable TIME_WAIT for integration tests.
Result:
Integration tests will pass.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Peter Adams <pp_adams@apple.com>
Motivation:
The 1000 TCP connections allocation counter test did way too many thread
crosses and other things that allocated for unrelated reasons.
Modifications:
Remove those.
Result:
Much more stable
Motivation:
Allocation tests are very hard to use productively if they don't produce stable results.
Modifications:
Change TCP and UDP connection tests to monitor on the server side as well as the client side to make sure all data is completely send and received before stopping counting allocations.
Result:
Allocation tests are more stable than before.
Motivation:
It's 2020, we shouldn't use unnecessary offensive, insulting, or
outdated language.
Modifications:
Fix a few examples.
Result:
More inclusive.
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:
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.
Fine grained UDP allocation tests
Motivation:
The existing UDP allocation tests count allocations everywhere.
Split out 3 tests to cover:
Making connections.
Making bootstraps.
Transferring data.
Modifications:
Three new tests.
Result:
Easier to debug changes to allocation profiles in UDP.
Motivation:
The existing tcp allocation tests cover everything from bootstrap creation through to sending data in one massive test. The parameters of how many iterations control the focus of the test. It would be better to be more explicit about what we're trying to test.
Modifications:
2 new tests:
* client bootstrap creation.
* connection establishment.
(Data transfer is already covered by the ping_pong test)
Result:
Easier to assess the impact of changes to memory allocation patterns.
Motivation:
The linker test script that checks what libraries we link was totally
broken.
Modifications:
Fix the linker test script.
Result:
We can correctly determine what we link and what not.
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
UDP based allocation tests (#1496)
Motivation:
With future work being considered in the UDP space it will be useful to have a baseline measure of allocations.
Modifications:
New allocation tests for UDP -
Ideas inspired by the TCP allocation tests.
Code a modified version of UDPEchoServer and UDPEchoClient examples.
Result:
There are UDP based allocation tests.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
The core problem is that we hook the system's allocator (malloc, free,
and friends) to get the most accurate allocation counts. This however
also means that all threads count into our limits which inherently means
we can't be 100% stable always.
Previously, we just waited a fixed 100ms and expected everything to be
as quiesced as it'll get. But we can do better.
Modifications:
- discard runs with negative remaining allocations (clearly bogus,
quiescing not long enough in a previous run)
- instead of waiting a fixed amount of time, wait until the results
appear quiesced (stable (for first run) or zero (for subsequent runs)
remaining allocation counts.
Result:
Allocation counter tests should be much more stable on busier machines.
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:
Clang modules seem to mess with stuff like _GNU_SOURCE as soon as
they're included. We do need _GNU_SOURCE (but don't like the
`#define __USE_GNU` hack).
Modifications:
Include the modularised headers last.
Result:
Alloc counter tests work without `#define __USE_GNU`.
motivation: tsan is broken on ubuntu 18.04.use 16.04 so 5.2 build can pass
changes:
* change 5.2 docker setup to use 16.04 instead of 18.04
* add the ability to pipe arguments to the integration tests via the docker setup
* skip tests_02 integration tests suite since it broken on 5.2 (swift-pm issue?)
fake the new limits from #1362
Co-authored-by: tomer doron <tomer@apple.com>
* add an allocation counter test for scheduling tasks
Motivation:
Scheduling tasks is important so we should have an allocation counter
test.
Modifications:
add one
Result:
more alloc counter tests
* Update test_schedule_10000_tasks.swift
* Update docker-compose.1804.50.yaml
* Update docker-compose.1604.51.yaml
Motivation:
It is useful/interesting to have an overview about total bytes
allocated, not only the number of malloc calls.
This is not used to fail tests though, more as an informational thing.
Modifications:
Introduce and hit new counter with allocated size whenever allocations
happen.
Result:
It is possible to inspect the total allocated bytes.
Motivation:
ByteBufferView isn't a mutable collection, but it probably should be.
Modifications:
- Add `copyBytes(at:to:length)` to `ByteBuffer` to copy bytes from a
readable region of a buffer to another part of the buffer
- Conform `ByteBufferView` to `MutableCollection`, `RangeReplaceableCollection`
and `MutableDataProtocol`
- Add an allocation counting test
Result:
`ByteBufferView` is now mutable.
Motivation:
Using the single test argument with the run-nio-alloc-counter-tests.sh
does not work as expected as the given test would just replace the first
test in the list.
Modifications:
Replace the tests to run with a single-element array containing the test
provided as an argument.
Result:
- A single test can be run when specified as a command line arg.
* Allow single test to be specified as an argument to run-nio-alloc-counter-tests.sh.
Motivation:
run-nio-alloc-counter-tests.sh currently runs all tests. When writing or
debugging a test, you commonly want to run a single test. At the moment the
common practice is to edit the script to hardcode a test to run, which is
annoying and error-prone.
Modifications:
Add an optional argument to the script to specify the test to run.
Result:
$ ./run-nio-alloc-counter-tests.sh
runs all tests.
$ ./run-nio-alloc-counter-tests.sh test_decode_1000_ws_frames.swift
runs only test_decode_1000_ws_frames.swift.
Motivation:
Certain POSIX error numbers mean the NIO program is broken beyond repair and should crash. One such value is EBADF, which indicates that the file descriptor that NIO passed to the kernel is invalid for some reason. SR-11557 was discovered in part because debug builds of NIO crash for this.
I have promoted these checks from an assertion to a precondition adding a function preconditionIsNotBlacklistedErrno. Issue was raised in issue #1156
Modifications:
- Add function preconditionIsNotBlacklistedErrno to enable option to stop program execution in both debug mode and release mode if the errno is blacklisted.
- Update assertIsNotBlacklistedErrno to all preconditionIsNotBlacklistedErrno when the program is in debug mode
- Update wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close to call preconditionIsNotBlacklistedErrno in stead of assertIsNotBlacklistedErrno
Result:
Functions wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close will stop the execution in both debug mode and release mode if the errno is blacklisted.
Motivation:
There are use-cases for SwiftNIO where there are no actual sockets but
rather two pipe file descriptors - one for input, one for output.
There's no real reason why SwiftNIO shouldn't work for those.
Modifications:
Add a PipeChannel.
Result:
More use-cases for SwiftNIO.
Motivation:
To improve the performance of a given component it is very helpful to
know how it performs! This patch adds benchmarks and allocation counter
tests to NIO for websocket frame encoding.
Modifications:
- Wrote some benchmarks for WebSocket frame encoding.
- Wrote some allocation counter tests for WebSocket frame encoding.
- Extend the allocation counter tests to properly account for sub-tests
Result:
Better insight
Motivation:
The integration tests depended on python in order to print 80,000 x
characters.
Modifications:
Remove the python dependency and express the same with `dd` & `tr`.
Result:
Fewer dependencies.
Motivation:
NIO's Lock currently just deadlocks if a thread which already holds a
lock tries to reacquire it. This however isn't even really defined
behaviour.
Modifications:
Switch us to a guaranteed crash from a unguarnateed hang.
Result:
Easier to debug deadlocks with NIO's lock.
Motivation:
Networking software like SwiftNIO that always has explicit flushes
usually does not benefit from having TCP_NODELAY switched off. The
benefits of having it turned on are usually quite substantial and yet we
forced our users for the longest time to enable it manually.
Quite a bit of engineering time has been lost finding performance
problems and it turns out switching TCP_NODELAY on solves them
magically.
Netty has made the switch to TCP_NODELAY on by default, SwiftNIO should
follow.
Modifications:
Enable TCP_NODELAY by default.
Result:
If the user forgot to enable TCP_NODELAY, their software should now be
faster.
Motivation:
We should have better iOS compatibility.
Modifications:
- make all OS-conditional imports the same
- don't check TSI_S_ESTABLISHED (which is unavailable on iOS)
- update availability to reflect the OS versions we actually support
- make sure temporary UDS paths aren't too long
Result:
better iOS compatibility
Motivation:
The allocation tests shouldn't delete their working directory because
that's where you would navigate to debug them. Usually, they're run
through the integration tests which automatically clean up anyway.
Modifications:
Don't delete work dir
Result:
Easier to debug
Motivation:
For the allocation counter tests to be as useful as possible, we should
disallow limits that are too high, we should capture the allocation
count very close to where it actually is.
Modifications:
Don't allow any allocation counter test to allocate fewer than
'limit - 1000' allocations.
Result:
Better limits.