Motivation:
A number of users have asked for the ability to install SwiftNIO
via Cocoapods. This is an entirely reasonable request, so let's
do it.
Modifications:
- Added a script that can generate, and optionally upload,
podspecs.
- Made a slight modification to the dependency script to provide
target-specific dependencies.
Result:
Users can use cocoapods if they prefer.
Motivation:
Previously the code said that fcntl doesn't return anything but that's
just not true, it returns `CInt`.
Modifications:
Made `fcntl` return `CInt` and tested that.
Result:
more correct code and more tests
Motivation:
The tests that test that we don't leak RepeatedTasks/EventLoops were a
bit racy so this needed fixing.
Modifications:
fixed the races in the tests
Result:
fixes#565
Motivation:
We were inadvertently doing an implicit integer conversion from
ssize_t to unsigned int in our sendmmsg shim. This can sometimes
generate warnings. The conversion itself is safe.
Modifications:
Make the conversion explicit.
Result:
No warnings.
Motivation:
For a long while I had a script which runs NIO's performance tests
against different Swift toolchains. It should be in the repository.
Modifications:
add scripts/compare_perf_of_swift_versions.sh
Result:
everybody can run the performance tests against different Swift versions
Motivation:
Sometimes it's useful to know the top-sorted dependency order. For
example if you need to do something in an order where all dependencies
of a target have already previously processed.
Modifications:
added scripts/list_topsorted_dependencies.sh
Result:
can write other scripts that need top-sorted dependencies
Motivation:
HTTP/2 adds an additional item to a header key/value pair:
its indexability. By default, headers can be inserted into
the HPACK header table index; sometimes this will be denied
(common case is 'content-length' header, which is rarely going
to be the same, and will just cause the table to purge more
often than is really necessary). Additionally, a header may be
marked as not only non-indexable but also non-rewritable by
proxies. HTTPHeaders provides nowhere to store this, so the
HPACKHeaders implementation referenced in
apple/swift-nio-http2#10 was created to add in that capability.
Now, given that we really want the HTTP version to be an
implementation detail, we want to keep the HPACK details hidden,
and would thus be using HTTPHeaders in client APIs. NIOHTTP2
already has a HTTP1-to-HTTP2 channel handler that translates
between the two. Thus it behooves us to have the means to copy
the actual key/value pairs between the two types without making
a round-trip from UTF-8 bytes to UTF-16 Strings. These changes
allow NIOHPACK or NIOHTTP2 to implement that round-trip internally.
Modifications:
- HTTPHeader and HTTPHeaderIndex types are now public.
- HTTPHeaders.buffer and HTTPHeaders.headers properties are now
public.
- A new static method, HTTPHeaders.createHeaderBlock(buffer:headers:)
was created to serve as a public means to create a HTTPHeaders from
a ByteBuffer from outside NIOHTTP1. @Lukasa suggested this should
be a static method rather than an initializer.
Result:
Nothing in NIOHTTP1 changes in operation. All public types have
documentation comments noting that they are only public for very
specific reasons, and are not intended for general use. Once this
is committed, NIOHPACK & NIOHTTP2 will be able to implement fast
round-trips between HTTPHeaders and HPACKHeaders.
Motivation:
Unsafe(Mutable)RawBufferPointers have a few APIs that make our code
easier to reason about. In this PR I'm trying to introduce some of it.
Modifications:
Improved UnsafeRawBufferPointer usage
Result:
code easier to reason about which hopefully leads to fewer bugs. Also:
In many cases we now get free bounds checking in debug mode, yay :).
Motivation:
NIOTS wasn't mentioned in the out-of-tree repos. Also their descripton
could've been a bit better.
Modifications:
added NIOTS and swift-nio-extras to the list of out-of-tree projects
Result:
better discoverability
match all values in HTTPHeaders.isKeepAlive(...)
HTTPHeaders.isKeepAlive(...) does only match the first value.
### Motivation:
Keep-alive and Close may be something on comma separated arrays
### Modifications:
- Made an extension function to `ByteBuffer` that could separate the strings at low level, without Swift string API, so that it could split the values
- Another extension functions that compares the comma separated array with a given array to tell the caller which exists and which no
- Added unit tests for them
- Used them in the HTTPHeader
### Result:
- Now, if a request is sent using Keep-alive or Close where it was in an array, it will be handled
- fixes#410
Motivation:
I spotted this while flamegraphing: apparently we missed the
declaration for inlineability here.
Modifications:
Made these two functions inlineable.
Result:
Better optimizations.
Motivation:
For newcomers that start to explore SwiftNIO on
GitHub, the first thing they stumble upon is `README.md`.
This file contains a high level description of the framework
and mentions a few types that are important when getting
started. Adding links from these types to the generated
HTML documentation reduces possible friction and makes
it easier for newcomers to grasp fundamental building
blocks of SwiftNIO.
Modifications:
- Added Markdown links from first use of types in
README.md to generated documentation at
https://apple.github.io/swift-nio/
- Added Wikipedia links for few important concepts:
`pthreads`, `kqueue`, `epoll`
Result:
Easier navigation from `README.md` to
related documentation.
Motivation:
There were a number of race conditions in both the RepeatedTasks
implementation and its tests:
- #554: the RepeatedTask could fire more than once before the
cancellation was actually processed leading to a crash in tests
- #548: a test was testing that the RepeatedTask ran a certain
number of times but the counting was racing with the checking
- TOCTOU issue: When a RepeatedTask was cancelled it was possible that
it fires one extra time because a TOCTOU issue
Modifications:
- fixed the test races
- fixed the TOCTOU issue by checking if it was cancelled when it's
executed rather than only when it's scheduled to be executed
Result:
- tests should be more stable (fixes#548 & fixes#554)
- RepeatedTask cancellation improved
Motivation:
Naked `try`s in tests are a problem because if they're hit you'll get a
bad error message and likely no file/line information. That has made
many flaky tests harder to debug than necessary.
Modifications:
- fix a lot of naked `try`s
- symlink `TestUtils` from `NIOTests` into `NIOHTTP1Tests`
- make a bunch of `wait()`s synchronous that were asynchronous by
accident
Result:
- better code
- easier to debug test failures
- setting better example
Motivation:
ByteBuffer has a number of readWith* methods, some of them return the
`T` which was returned from the closure. This shouldn't be discardable.
Others however just return thr number of bytes read which should be
discardable.
Modifications:
made the readWith* functions that return the number of bytes read
@discardableResults
Result:
nicer user code
Motivation:
It's poor style to assume a certain piece of memory is bound to a
certain type across a whole program. That's because any piece of code
run in between might have rebound the memory and also it's hard to prove
that the binding assumption is actually correct. Therefore we should
restrain from using them.
Modifications:
remove more assumptions that memory is bound to a certain type.
Result:
better code
Motivation:
Apparently when I wrote the WebSocket parser I forgot that enums are
great, and so I added a bunch of optional properties. That was silly.
This patch changes the WSParser structure to use an enum with
associated data to ensure that we only store state when we are supposed
to, and to guarantee that the state is good.
Modifications:
Move all state to enum case associated data.
Result:
Easier to validate the correctness of the WSParser code.
Motivation:
The (`internal`) `Socket` API should've always been based on
`Unsafe(Mutable)RawBufferPointer`s but for some reason (probably just
age) it was `Unsafe(Mutable)Pointer<UInt8>` alongside a `size: Int`.
Modifications:
switched the `Socket` APIs from `Unsafe(Mutable)Pointer<UInt8>` and a
size to `Unsafe(Mutable)RawBufferPointer`.
Result:
better Swift code.
Motivation:
We suspect a DNS resolver issue in one of our test harnesses to cause
most of the flaky tests. This patch adds more debug information about
the resolver to flaky tests.
Modifications:
print the resolver output when flaky tests fail
Result:
one step closer to no flaky tests
* Simplify C string to String conversion in IOError.reasonForError
Motivation:
The standard library already has a String initializer that takes a
null-terminated UTF-8 C string. There's no need to construct an
UnsafeBufferPointer to use the Collection-based init(decoding:as:).
Modifications:
Replaced a manual pointer conversion with the appropriate stdlib API.
Result:
No change. Both version return the same String. The new version is
is arguably more correct because it saves the memory-rebinding step.
I haven't added new tests because the modified code is covered by
SystemTest.testErrorsWorkCorrectly.
Motivation:
I came across a few typos and then went through the entire code base
fixing similar errors when I noticed a pattern.
Modifications:
No changes to the code, just to comments.
Result:
No changes.
Motivation:
As discussed with Andrew Trick on the Swift Forums, the additional call
to assumingMemoryBound(to:) is redundant here. Unmanaged.fromOpaque
takes a raw pointer, and p is just that.
See https://forums.swift.org/t/withunsafetypepunnedpointer/14540/9
for the discussion.
Modifications:
Deleted an unnecessary call to assumingMemoryBound(to:). With this
change, we follow the intended usage of Unmanaged more closely.
Result:
No material change. We save one redundant UnsafeRawPointer ->
UnsafePointer<ThreadBox> -> UnsafeRawPointer conversion.
Motivation:
As described in #537, ByteBuffer.changeCapacity is not a very good
function. We want to replace it with a better one, more similar to
reserveCapacity on the standard library data structures, and ideally
substantially faster.
Modifications:
- Deprecated ByteBuffer.changeCapacity.
- Added ByteBuffer.reserveCapacity.
- Changed the implementation of changeCapacity to call reserveCapacity
when we're increasing the capacity.
Result:
Better APIs, better performance in the legacy ones, everything is
better.
* EventLoopIterator
Provide a way to iterate over the EventLoops that compose an EventLoopGroup
Motivation:
For some use cases, it might be necessary to access the underlying event loops. See #497.
Modifications:
Added an EventLoopIterator as well as a new protocol requirement to EventLoopGroup called makeIterator() -> EventLoopIterator? . This is optional to avoid a SemVer Major, but will be made non-optional with 2.0.0. A current implementation is provided for every EventLoop through a protocol extension as well as for the MultiThreadedEventLoopGroup.
Result:
It is now possible to iterate over the EventLoops that compose a EventLoopGroup
Motivation:
`NonBlockingFileIO` currently provides multiple read functions, but no functions to write to a `FileHandle` in an asynchronous non-blocking way.
Modifications:
`NonBlockingFileIO` struct now has simple basic `write` function that supports writing from a `ByteBuffer` to a `FileHandle`. Added `testWriting()` to `NonBlockingFileIOTest`.
Result:
`NonBlockingFileIO` now has a basic building block for asynchronous non-blocking writes.
Resolves#406.
Motivation:
`ByteBuffer`'s `get*` methods can be used in an unsafe way and we didn't
warn the user enough.
Modifications:
Warn the user in the documentation of all the `get*` methods.
Result:
Less confusion.
Motivation:
Currently if you hit a parse error in the WebSocketFrameDecoder, that
handler takes it upon itself to return the error code and shut the connection
down. That's not really its job: it's not a pattern that we use anywhere
else, and it prevents users from overriding this handling with their own
choices.
We should stop doing that. Unfortunately, we can't totally stop it because
it's a supported feature in the current release of NIO, but we can give
users the option to opt-out, and also build our future solution at the same
time.
Modifications:
1. Added support for disabling the automatic error handling in
WebSocketFrameDecoder.
2. Created a new WebSocketProtocolErrorHandler class that will be used for
default error handling in 2.0.
3. Added support to the WebSocketUpgrader to disable automatic error handling
altogether.
4. Changed the WebSocketUpgrader to use the WebSocketProtocolErrorHandler
for default error handling when necessary.
Result:
Better separation of concerns, and users can override NIO's default
error handling behaviour.
Motivation:
This ensures that the client's context information will be propagated into
the promise which is implicitly created by thenIfError(). Without this, if
that promise leaked the client would only see information about where it was
allocated inside of NIO, which is not helpful.
Modifications:
Propagate #file/#line.
Result:
Client's will see a #file/#line in their code, rather than something like:
```
Fatal error: leaking promise created at (file: ".../.build/checkouts/swift-nio.git-bla/Sources/NIO/EventLoopFuture.swift", line: 583)
```
Motivation:
On macOS it is possible to hot-loop on kevent when a channel has autoRead
disabled but pending data in the receive buffer. This is because
EVFILT_EXCEPT will fire when there is pending data in the receive buffer.
For now we work around this by setting NOTE_LOWAT to Int.max, which will
ensure that we don't actually get EVFILT_EXCEPT fired for pending data.
Modifications:
- When registering EVFILT_EXCEPT, set NOTE_LOWAT to Int.max.
- Fix a test that definitely didn't test what it wanted to.
Result:
No hot-loops with pending data.
Motivation:
The bytes that a Unsafe(Mutable)RawBufferPointers points to can be
accessed directly as `UInt8`s. We didn't know that so we bind
`ByteBuffer`s memory to `UInt8` so that we can access it as
`UnsafePointer<UInt8>` using `assumingMemoryBound(to: UInt8.self)` in
many places. Most of the time that is unnecessarily awkward and
unnecessary.
Modifications:
- remove some easy instances where we access an
`UnsafeMutableBufferPointer` as `UnsafeBufferPointer<UInt8>` just to
read some `UInt8`s.
Result:
less awkward looking code
Motivation:
Fix comparison that causes incorrect processing of nonexistent events via optional promotion.
Modifications:
Changed comparison to use _none
Result:
No processing nonexistent events.
Pass the reference to RepeatedTask to its closure to allow a thread-safe cancelling.
Motivation:
With the current implementation, one has to create a reference and use a lock to thread-safely cancel the RepeatedTask. This makes the use more difficult and error-prone.
Modifications:
Added a RepeatedTask parameter to the scheduleRepeatedTask closure.
Result:
It is now possible to cancel the RepeatedTask from within the task closure.
Motivation:
We should not treat the HTTP protocol upgrade string as a case-sensitive
string, as clients may incorrectly deviate from the string as specified,
and we should still tolerate that.
Modifications:
Treat the upgrade string as case insensitive.
Result:
Wider compatibility for HTTP upgrade.
Motivation:
testScheduleRepeatedTask and
testScheduleRepeatedTaskCancelFromDifferentThread has threading issues
that I unfortunately missed in review.
Modifications:
fix the threading issues by using a `DispatchGroup`
Result:
fewer theading issues in the tests
Motivation:
We have a few flaky tests, namely:
- testWriteOnAccept (#510)
- testBootstrapsCallInitializersOnCorrectEventLoop (#449)
- testCloseFutureNotifiedBeforeUnblock (#440)
- testFailedRegistrationOfAcceptedSocket (#439)
- testPortNumbers (#429)
- testPendingReadProcessedAfterWriteError (#246)
and we should make them non-flaky. First step to achieve this is better
diagnostics and this is what this patch is trying to deliver.
Modifications:
improve flaky tests' diagnostics
Result:
hopefully we can soon make them non-flaky.
Motivation:
Given that wrapErrorIsNullReturnCall exists purely to wrap syscalls that
return NULL pointers on errors, there is no point allowing the return
value to be nil. Additionally, it's currently weirdly specific about the
return pointer type, so we can make the function generic.
Modifications:
- Make the return value of wrapErrorIsNullReturnCall generic.
- Make the return value of wrapErrorIsNullReturnCall non-optional.
Result:
Easier to use wrapErrorIsNullReturnCall and any matching function
Motivation:
ContiguousCollections shouldn't give access to more than `count` bytes
via `withUnsafeBytes` but if they do we should still handle this
correctly and only copy `count` bytes.
Modifications:
- copy an upper limit of `count` bytes
- fail hard if `withUnsafeBytes` offers fewer bytes as we can't do
anything sensible then.
Result:
even illegal `ContiguousCollection` implementations don't cause issues.
Motivation:
During the `PR` apple/swift-nio#347 there was a discussion around which
protocols this autoexpanding buffer should conform; the following 3
being the winners:
1. BidirectionalCollection
2. RandomAccessCollection
3. RangeReplaceableCollection
Modifications:
Added conformance to the 3 protocolos and provided implementaiton for 4
methods:
1. replaceSubrange(:with:)
2. index(before:)
3. removeSubrange(:)
4. remove(at:)
5. removeLast(:)
Result:
With the conformance of this 3 protocols and the implementation of this
5 functions we get dropLast(), dropLast(:), removeFirst(), removeLast()
& popLast() for free.
Provide a mechanism to repeatedly schedule a task in the EventLoop
Motivation:
In some cases a certain task should run repeatedly, like polling an API or querying a database. For these scenarios a repeated scheduling mechanism is beneficial.
Modifications:
Added a method to EventLoop to schedule repeated tasks.
Result:
It is possible to schedule task with an initial delay and a fixed delay now. Furthermore, these task can be cancelled.
Motivation:
testBootstrapsCallInitializersOnCorrectEventLoop had a massive race
condition, we'd never wait for childChannelDone and serverChannelDone to
actually be fulfilled which could lead to leaked promises. No idea why
this didn't fail more often.
Modifications:
Wait for futures to be fulfilled to make sure we don't leak the
promises.
Result:
tests more stable.
Motivation:
In a few situations we used `Int` in places where malloc/realloc
actually use `size_t`. On 64-bit platforms this doesn't actually matter
but on 32-bit it does!
Modifications:
- replace `Int` with `size_t` where appropriate
Result:
- should be able to use more than 2GB on 32-bit platforms
Motivation:
In Swift 4.2 you'll get a warning if you use an internal typealias from an
`@inlinable`/`@_inlineable` function. To fix it, you usually make it
`@usableFromInline`/`@_versioned`. Swift
4.0 however doesn't support those attributes for typealiases. The workaround is
to just make the typealias public (and underscored).
Modifications:
make `ByteBuffer.Capacity` and `ByteBuffer.Index` underscored and public
Result:
compiles warning-free on Swift 4.0, 4.1 and 4.2
Motivation:
swift-nio example projects (http, echo) don't print anything to the console when running inside docker container because of buffering issue.
Modifications:
Added tty: true to the docker-compose.yaml for http & echo.
Result:
Buffering issue is resolved. http & echo prints logs to the console.
Motivation:
The server attaches a dynamic handler to requests and will keep passing
data until the handlers are removed; which never happens.
Modifications:
`nil` out the `handler` when `completeResponse` is called.
Result:
When connections are reused we now get the correct dynamic handler for
it instead of the previous one.
Motivation:
We used an incorrect precondition and so it would be hit if someone tried to create a ByteBufferView add all bytes in a ByteBuffer.
Modifications:
Allow upperBound up to capacity
Result:
Fixes https://github.com/apple/swift-nio/issues/482.
Motivation:
Our copy of http_parser has become almost a year old now, and there are
both some bugfixes that improve correctness and some performance
improvements in http_parser that we should pick up.
Modifications:
- Updated http_parser
- Added tests to confirm we don't suffer from
https://github.com/nodejs/http-parser/pull/432
- Added tests that we didn't get broken by SOURCE verb addition.
Result:
Shiny new http_parser!